generation and calculation of prefix expression after compiling principle
Grammar references the previous compilation principle of eliminating the left recursion of the arithmetic expression grammar.
Parsing an arithmetic expression into a suffix expression is a computational scheme for many scripting languages at run time.
According to the original grammar:
Expr--expr-term | term-term
* factor |
term/factor
| Factor
Fact Or-(expr)
| number
| ID
Let's first list the functions to be implemented:
Class Parser {public
:
void expr (lexerstream* lexers)
{
}
void term (lexerstream* lexers)
{
}
void Factor (lexerstream* lexers)
{
}
};
The Lexerstream is a morpheme sequence stream.
Then the recursive algorithm is implemented according to the grammar of eliminating left recursion:
Expr, term trest
trest, term
|-term |ε
, factor frest
frest * Factor
| /factor
|ε
factor, number
| (expr)
The production of expr that does not eliminate left recursion and the elimination of left recursive expr and trest are first seen. The original expr generation itself is left recursive, so the recursive descent algorithm corresponds to an internal loop.
So give the implementation of expr first:
void expr (lexerstream* lexers)
{term
(lexers);
while (lexers->current () = = "+" | | lexers->current () = = "-") {
string op = lexers->current ();
Lexers->next ();
term (lexers);
cout << op; PUSH
}
}
Other production-like:
void term (lexerstream* lexers)
{
factor (lexers);
while (lexers->current () = = "*" | | lexers->current () = = "/") {
string op = lexers->current ();
Lexers->next ();
Factor (lexers);
cout << op; PUSH
}
}
void Factor (lexerstream* lexers)
{
string current = Lexers->current ();
if (current = = "(") {
lexers->next ();
Expr (lexers);
Lexers->next ();
String e = Lexers->current ();
if (E! = ")") {
cout << ' lost ' ("<< Endl;
}
} else {
cout << current; PUSH
Lexers->next ();
}
}
Detailed code to learncompilers/hll/calculator001 download.