The One With D News and Opinions of the Digital Mars D Programming Language

12Sep/070

Don Clugston’s Compile-Time SyntaxTree

Don Clugston, the D community's resident CTFE guru, has put his considerable talent to work in order to create a module which performs lexing, parsing, and semantic analysis on D expressions at compile-time. This is mind-boggling stuff. What's more, he did it in under 300 lines of code. From the NG announcement:

contains one publicly usable function:

char [] syntaxtreeof(char [] expression).

When mixed in, this lexes and parses the expression, determines precedence and associativity, creating an object of type AbstractSyntaxTree, which contains a standardized 'placeholder expression' (eg "A+=(B*C)")
and a symbol table for the variables, constants and functions A,B,C,...
The symbol table includes the type and value for each symbol.
All aliases and compile-time constants are resolved and converted to a standard form.
All symbols must be reachable from the scope where syntaxtreeof() is mixed into.

The created AbstractSyntaxTree is a compile-time constant, so it can be used for further compile-time operations and code generation.

Works for almost any expression (templates, functions, strings, slicing, struct literals,...); the biggest omission is relational operators.

And example usage:

import SyntaxTree;

const foo = "abc";
int bar(real x, char [] s) { return 0; }
struct Duck{};
Duck duck;

AbstractSyntaxTree a = mixin(syntaxtreeof(`foo* bar(2.18_3242e+45L, "xyz") in duck`));

I guess there's a reason that the first letter in Don is 'D'.

Technorati Tags: ,

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.