Navigation
Synopsis Static type checking.
Description Type Lattice

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:
  • in a generic fashion as Tree and,
  • in a specific fashion as a more precisely typed syntax tree. Finally, each alias is structurally equivalent to one or more specific other types.
Rascal does not provide an explicit casting mechanism, but pattern matching can play that role.
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: false
We 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.
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit ask.rascal-mpl.org.