Type Substitute For Integer Literal


In version 3.3, the "substitute type rule" feature was added. This feature allows to substitute *type nodes* with other nodes to represent type instead, and this helps for overriding default type nodes. Let's assume the goal is to use this feature to enable dealing with integer literals as different types under some condition, e.g. deal with integer constants as short literals when it is needed (a use case is attached in the end). Suppose the substitution code will look like this.

substitute type rule IntegerLiteralToShort { 
      applicable for concept = IntegerType as integerType

substitute {
    if ( <some condition> )  {  
return new node<ShortType>(); 
return null;   // indicates no substitution will happen.


Note that according to the documentation: "The Substitute Type Rule is applicable to nodes that represent types", so I cannot write the substitute rule on IntegerConstant.

My question here is: How to find a way to get access to the *original* node in the AST that we assign the type to? Suppose I want to write the condition such that a short type is assigned when the original node in the code is a child of some expression of certain properties. It seems to me that this is not accessible from the integerType node, but I wish I am wrong. As an example: a condition could be like: if the node we are assigning the type to is IntegerConstant and is a child of arrayInitializer expression, substitute/return the short type node.

When we write "inference rules", we don't have this problem, because we have access to the AST node and we can inspect it easily.


By the way, I am trying to make use of the above as an exercise to fix a current inconsistency in the base language. Currently if you do:

short[] array = new short[]{1,2,3};

It gives an error. The underlying implementation takes care only of cases like:

short x = 3; 

by using a conditional in the type inference rule of VariableDeclaration, but this is absent in the ArrayCreatorWithInitializer type inference, so I was thinking to fix that using the substitute, but I cannot get access to the original node.






1 comment
Comment actions Permalink

There is no way to access the typed node (the "original" node) from a type, and it is intentional.

We are aware of inconsistency with short/char/byte constants that are treated all as ints. One way to deal with it would be to introduce a special type "numeric with value", which would then be coerced to appropriate type based on the value. This is on the todo list.



Please sign in to leave a comment.