ANTLR - Writing Tree Grammar for AST

I have an AST obtained for some Lua code from my grammar file, which is currently doing parsing and lexing for me. I want to add tree-like grammar to this, but since I'm using C #, I'm not sure how to do this. What is the main process for generating tree grammar code when you already wrote the parser and lexer?

UPDATE: I have the following grammar file:

tree grammar LuaGrammar;

options {
  backtrack=true;
  language=CSharp2;
  //output=AST;
  tokenVocab=Lua;
  filter=true;
  ASTLabelType=CommonTree;
}
@lexer::namespace{/*my namespace*/}
@parser::namespace{/*my namespace*/}

dummyRule
    :   ^('=' x=. y=.) {};

is placed in the same directory as my main grammar file, which generates a fine. However, when I try to compile this, I get the following errors:

[02:54:06] error(143): C:\Users\RCIX\Desktop\AguaLua\Project\trunk\AguaLua\AguaLua\ANTLR Data\LuaGrammar.g:12:18: unknown or invalid action scope for tree grammar: lexer
[02:54:06] error(143): C:\Users\RCIX\Desktop\AguaLua\Project\trunk\AguaLua\AguaLua\ANTLR Data\LuaGrammar.g:13:19: unknown or invalid action scope for tree grammar: parser

Am I on the right track or completely off?

+3
source share
2 answers

, , .

1) @lexer @parser.

2) , , {...} , .. .

+1

:)

Tree Walker

class CalcTreeShaker extends TreeParser;

expr returns [float r]
{
float a,b;
r=0;
}
:   #(PLUS a=expr b=expr)   {r = a+b;}
|   #(STAR a=expr b=expr)   {r = a*b;}
|   i:INT           {r = Convert.ToSingle(i.getText());}
;

, expr. .

, , , .

expr , , PLUS STAR INT.

, , Antlr Tree #(...).

PLUS STAR 2 expr. expr , . , # {...}.

, , TreeWalker, return [...].

-, , . Antlr:)

// Get the ast from your parser.
CommonAST t = (CommonAST)parser.getAST();

// Create the Tree Shaker
CalcTreeWalker walker = new CalcTreeWalker();
CalcParser.initializeASTFactory(walker.getASTFactory());

// pass the ast to the walker and call the top level rule.
float r = walker.expr(t);
+2
source

Source: https://habr.com/ru/post/1732291/


All Articles