Rupert
Rupert

Reputation:

Using C# and gppg, how would I construct an abstract syntax tree?

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

Answers (3)

Vadym Chekan
Vadym Chekan

Reputation: 5167

  1. 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;
    %}
    
  2. 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);}
        ;
    
  3. 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

kenny
kenny

Reputation: 22404

Take a look at ANTLR, I did a simple .NET compiler written in C# with it few years back.

Upvotes: 0

JoshL
JoshL

Reputation: 1716

See MGrammar and Oslo...

http://msdn.microsoft.com/oslo

http://channel9.msdn.com/pdc2008/TL31/

Upvotes: 1

Related Questions