What are the general strategies for reducing a parse tree (ie. concrete syntax tree) into an abstract syntax tree?
For example, I have the following grammar rule:
statement_list : statement
| statement_list statement
which, if left as a parse tree, will generate fanning output that looks like
program
statement_list
statement_list
statement
definition
p_type
assignment
statement
definition
statement
assign
assignment
If I concatenate the children of each node (since a statement list has no inherent meaning after parsing), I can achieve the following
program
definition
p_type
assignment
definition
assign
assignment
This worked well - however, I'm unaware of any "rules" for doing this. Are there specific grammar rules I should be looking to simplify? Is it a matter of feel, or is there a more mechanistic process?
Typically, you would split the work into a tokenizer which splits the input stream representing the expression into a list of tokens, and a parser which takes the list of tokens and constructs a parse tree\ast from it. The first column is the actual text value. The second represents the token type.
A parse tree is a record of the rules (and tokens) used to match some input text whereas a syntax tree records the structure of the input and is insensitive to the grammar that produced it. Combining the above two definitions, An Abstract Syntax Tree describes the parse tree logically.
Abstract syntax trees are important data structures in a compiler. It contains the least unnecessary information. Abstract syntax trees are more compact than a parse tree and can be easily used by a compiler.
An Abstract Syntax Tree, or AST, is a tree representation of the source code of a computer program that conveys the structure of the source code. Each node in the tree represents a construct occurring in the source code.
It's not a matter of "feel". An abstract syntax tree depends on the meaning (semantics) of what's been parsed, and I think these would be the rules:
There's no single recipe. It depends on what the phrases in the target language mean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With