Reputation:
Is there a way to do this almost out-of-the-box?
I could go and write a big method that would use the collected tokens to figure out which leaves should be put in which branches and in the end populate a TreeNode object, but since gppg already handled everything by using supplied regular expressions, I was wondering if there's an easier way? Even if not, any pointers as to how best to approach the problem of creating an AST would be appreciated.
Apologies if I said anything silly, I'm only just beginning to play the compiler game. :)
Upvotes: 2
Views: 1940
Reputation: 5167
In your syntax file declare a property which will keep the root of your AST:
{%
public BatchNode Batch;
public ErrorHandler yyhldr;
private TransformationContext _txContext = TransformationContext.Instance;
%}
Start writing your grammar with actions which build nodes of your AST:
Batch
: StatementList {Batch = new BatchNode($1.Statements);}
;
StatementList
: Statement {$$.Statements = new List<StatementNode>(); $$.Statements.Add($1.Statement); }
| StatementList Statement {$$.Statements = $1.Statements; $$.Statements.Add($2.Statement);}
;
Call parser:
var parser = new Parser.Parser();
var scanner = new Scanner();
parser.scanner = scanner;
scanner.SetSource(sourceString, 0);
bool result = parser.Parse();
if (result)
HandleMyAst(parser.Batch)
Upvotes: 1
Reputation: 22404
Take a look at ANTLR, I did a simple .NET compiler written in C# with it few years back.
Upvotes: 0
Reputation: 1716
See MGrammar and Oslo...
http://msdn.microsoft.com/oslo
http://channel9.msdn.com/pdc2008/TL31/
Upvotes: 1