![]() |
|
Navigation |
Synopsis Static type checking.
Description
![]() Rascal is based on static typing, this means that as many errors and inconsistencies as possible are spotted before the program is executed. The types are ordered in a so-called type lattice shown in the figure. The arrows describe a subtype-of relation between types. The type void is the smallest type and
is included in all other types and the type value is the largest type that includes all other types.
We also see that rel is a subtype of set and that each ADT is a subtype of node .
A special role is played by the datatype Tree that is the generic type of syntax trees.
Syntax trees for specific languages are all subtypes of Tree . As a result, syntax trees can be addressed at two levels:
Examples Some example can illustrate the above.
rascal>int I = 3;
int: 3
Since I is declared as type int , we cannot assign a real value to it:
rascal>I = 3.5;
|stdin:///|(4,3,<1,4>,<1,7>): Expected int, but got real
rascal>num N = 3;
num: 3
Since N is declared as type num , we can assign both int and real values to it:
rascal>N = 3.5;
num: 3.5
Since all types are a subtype of type value , one can assign values of any type to a variable declared as value :
rascal>value V = 3; value: 3 rascal>V = "abc"; value: "abc" rascal>V = false; value: falseWe can use pattern matching to classify the actual type of a value: rascal>str classify(value V){ >>>>>>> switch(V){ >>>>>>> case str S: return "A string"; >>>>>>> case bool B: return "A Boolean"; >>>>>>> default: return "Another type"; >>>>>>> } >>>>>>>} str (value): str classify(value); rascal>classify(V); str: "A Boolean" rascal>V = 3.5; value: 3.5 rascal>classify(V); str: "Another type"In addition to these standard examples, it is interesting that all AlgebraicDataTypes are subtypes of type node .
Let's introduce a simple Color data type:
rascal>data Color = red(int level) | blue(int level);
ok
Unsurprisingly, we have:
rascal>Color C = red(3);
Color: red(3)
Due to subtyping, we can also have:
rascal>node ND = red(3);
node: red(3)
One example of the actual application of subtypes can be found in Recipes:CountConstructors.
![]() |