Request: (expression).stringof should return a textual AST
janderson
askme at me.com
Fri May 4 09:25:58 PDT 2007
Don Clugston wrote:
> Many uses of textual macros involve D expression syntax.
> For example,
>
> int x;
> mixin(println("The value of x is $x and the next value is ${x+1}"));
>
> If these embedded expressions are evaluated by manually parsing the
> string, we need to be able to be able to identify D literals, such as
> floating-point literals (-0x1.2_5p-38, 1e80, etc). Also, we need to
> enforce the precedence rules. This is quite a lot of code that is
> difficult to get right.
>
> Almost all the difficulty could be avoided by standardizing the
> behaviour of (expression).stringof.
>
> The behaviour of .stringof when presented with an expression has changed
> a couple of times already. According to the spec, (expression).stringof
> is not supposed to perform semantic analysis, but it currently does (bug
> #1142). It seems that it parses the expression, performs type checking,
> and returns a slightly modified string.
>
> For use in metaprogramming, it would extremely useful if instead, it
> parsed the string, without reference to types, removed unnecessary
> spaces and parentheses, and inserted parentheses to indicate precedence.
>
> Under this proposal, with an expression, .stringof would return a value
> which was a standardised equivalent to the original string:
>
> (1.2e+58+2*3).stringof --> (1.2e+58)+((2)*(3))
> (func(var, var1*3.6)--> ((func)((var),((var1)*(3.6))))
>
> This would allow code generators to accept D expressions embedded in
> strings, without needing to implement a lexer or precedence of
> operators; it only needs to count the number of ( and ).
>
> All terminal expressions would be wrapped in () (or alternatively, they
> could be terminated with a space -- doesn't matter as long as it is
> consistent).
>
> If there is a mixin in the expression, it should be evaluated before
> .stringof is invoked. (It's not possible to know the precedence until
> you have the complete string).
Crazy thought 2003
Why not have the ability to stringarise any syntax that is within scope:
module me;
void func()
{
int X;
...
}
void bar()
{
string funcStr = stringof(func());
//funcStr = "void func()/n{/n int X/n.../n}"
string funcStr2 = stringof((func()));
//funcStr2 = "func()"
int X = 10;
int Y = 200;
string funcStr3 = stringof((X)+Y);
//funcStr3 = "10 + Y"
int X = 10;
int Y = 200;
string funcStr4 = stringof((X + 1) + Y);
//funcStr4 = "(X + 1) + Y"
int X = 10;
int Y = 200;
string funcStr5 = stringof(((X) + 1) + Y);
//funcStr5 = "11 + Y"
int X = 10;
int Y = 200;
string funcStr6 = stringof(me);
//funcStr6 = "module me; void foo(); void bar();";
//Note I'm using brackets here to specify what is the
//variable and what is a value. It probably should be
//another syntax.
}
//I know you could turn everything into a strings an use mixins however
it just doesn't look so nice.
-Joel
More information about the Digitalmars-d
mailing list