The previous article describes the transformation of expressions into a list of Tokenrecord objects through lexical analysis. In the first article, the expression is represented by a tree structure, and then it is convenient to compute the value from the subordinate node. So how do you parse a list into the structure of a tree?
Or an example to illustrate, such as 3*7+56/8-2*5, analysis into a tokenrecord list is
Mark Object |
corresponding expression |
Tokenvalue |
3 |
Tokenmultiply |
* |
Tokenvalue |
7 |
Tokenplus |
+ |
Tokenvalue |
56 |
Tokendivide |
/ |
Tokenvalue |
8 |
Tokenminus |
- |
Tokenvalue |
2 |
Tokenmultiply |
* |
Tokenvalue |
5 |
Analysis into a tree is
According to the actual arithmetic rules, operator precedence is computed first, and then the result of the operation is called by the lower-priority operator. In the tree view, the High-priority node is the subordinate of the lower priority node, the higher the priority, the closer the position is to the leaf. Because the unified object is used here, all the elements are represented by Tokenrecord, so the tokenvalue is also a priority. Through the analysis of the tree view, all the tokenvalue are in the position of the leaf, the Tokenvalue is the highest priority.
The analysis here will be implemented in code. Here you need to use the priority priority attribute in Tokenrecord, and use the stack. As with lexical analysis, it is necessary to analyze each tokenrecord in sequence. Take the above Tokenrecord list for analysis, and the bold text represents the Tokenrecord of the current analysis. The process of analysis has a principle called "high out of the low entry principle", need to explain.
"High out of the low entry principle" means:
1. Stack top Tokenrecord priority higher than the current Tokenrecord priority, then the stack top Tokenrecord stack (high out) to the temporary variable.
1.1 If the stack is empty, add the Tokenrecord in the temporary variable to the childlist of the current Tokenrecord, and then push the current Tokenrecord stack (low).
1.2 If the stack is not empty, find the top tokenrecord of the stack and the highest priority in the current Tokenrecord (the same is the top of the stack), add the Tokenrecord in the temporary variable to the childlist of the high priority Tokenrecord. The stack top and current tokenrecord are processed with high out and low entry principle.