Parsing Java code with ANTLR “need concept”

前端 未结 1 1644
南方客
南方客 2021-01-20 10:02

I\'m trying to make a compilation of programs using ANTLR and I use the Java programming language as the target and the core of the issue is developing the Intent Regornizer

相关标签:
1条回答
  • 2021-01-20 10:55

    Whether or not 'c' has been declared is not part of the grammar.
    The parser outputs an Abstract Syntax Tree, the compiler takes that AST and does semantic analysis on it. It's at that stage that compiler errors are generated, such as "variable c does not exist in that scope".

    ANTLR produces an AST for you, and then it's done. The next stage (semantic analysis and compilation and generating an executable) is done by another part of the compiler.


    The method I've used to produce the behaviour you're looking for is to traverse the AST doing "semantic analysis" on each node. What the AST looks like will depend entirely on the grammar used to produce it, but your first program could look like this:

    PROGRAM
    |- FUNCTION_DEC "main"
       |- ARGS <none>
       |- SCOPE 1
          |- LOCAL_DEC "a", "b"
          |- EXPRESSION_STMT
             |- ASSIGNMENT
                |- VARIABLE "c"
                |- LITERAL 20
    

    And the semantic analysis could do something like this:
    1) Add "main" to the symbol table as a globally accessible function
    2) Add Scope 1 inside the scope of the main function to the symbol table
    3) Add "a" and "b" to the symbol table as local variables inside scope 1
    4) Look in the symbol table for variable "c" inside scope 1, fail, look in the parent scope of "main", fail, look in the global scope, fail, produce an error message: Variable 'c' not found.

    That's a fairly typical process as far as I know.

    0 讨论(0)
提交回复
热议问题