Content deleted Content added
→Example parser: fmt (C example) (braces and 4-space indent) |
(Example parser - fmt and ANSI C, put back <pre> tags (C example) (braces and 4-space indent)) |
||
Line 15:
[[Algorithms + Data Structures = Programs]]) is in [[LL parser|LL(1)]] form:
<pre>
program = block "." .
Line 40 ⟶ 41:
factor = ident | number | "(" expression ")" .
</pre>
[[Terminal symbol|Terminals]] are expressed in quotes (except for the well defined ''ident''
Line 46 ⟶ 48:
Notice how closely the predictive parser below mirrors the grammar above. There is a procedure for each nonterminal in the grammar. Parsing descends in a top-down manner, until the final nonterminal has been processed. The program fragment depends on a global variable, ''sym'', which contains the next symbol from the input, and the global function ''getsym'', which updates ''sym'' when called.
<pre>
typedef enum {ident, number, lparen, rparen, times, slash, plus,
minus, eql, neq, lss, leq, gtr, geq, callsym, beginsym, semicolon,
endsym, ifsym, whilesym, becomes, thensym, dosym, constsym, comma,
varsym, procsym, period, oddsym} Symbol;
Symbol sym;
void getsym(void);
void error(const char msg[]);
void expression(void);
int accept(Symbol s) {
getsym();
return }
int expect(Symbol s) {
if (accept(s))
return 1;
error("expect: unexpected symbol");
return 0;
}
void factor(void) {
} else if
} else if (accept(lparen)) {
} else {
error("factor: syntax error");
getsym();
}
}
void term(void) {
while (sym == times || sym == slash) {
getsym();
factor();
}
}
void expression(void) {
if (sym == plus || sym == minus)
while (sym == plus ||
term();
}
}
void condition(void) {
if (accept(oddsym)) {
} else {
expression(); if (accept(ident)) {
} else if (accept(callsym)) {
} else if
} while
} else if
} else if (accept(whilesym)) {
}
}
void block(void) {
if (accept(constsym)) {
do {
expect(ident);
} while
}
if (accept(varsym)) {
}
while (accept( expect(semicolon);
}
}
void program(void) {
getsym();
block();
expect(period);
}
</pre>
== Formalizing recursive descent parsers ==
|