Recursive descent parser: Difference between revisions

Content deleted Content added
Corrected Coco/R link
 
(288 intermediate revisions by more than 100 users not shown)
Line 1:
{{short description|Algorithm}}
A '''recursive descent parser''' is a top-down [[parser]] built from a set of [[Mutual recursion|mutually-recursive]] procedures (or a non-recursive equivalent) where each such [[procedure]] usually implements one of the production rules of the [[formal grammar|grammar]]. Thus the structure of the resulting program closely mirrors that of the grammar it recognises.
{{More footnotes|date=February 2009}}
 
In [[computer science]], a '''recursive descent parser''' is a kind of [[top-down parsing|top-down parser]] built from a set of [[mutual recursion|mutually recursive]] procedures (or a non-recursive equivalent) where each such [[procedure (computer science)|procedure]] implements one of the [[Terminal and nonterminal symbols|nonterminals]] of the [[formal grammar|grammar]]. Thus the structure of the resulting program closely mirrors that of the grammar it recognizes.<ref>{{FOLDOC|Recursive+descent+parser}}</ref><ref>{{cite book | title=Recursive Programming Techniques | author=Burge, W.H. | year=1975 | publisher=Addison-Wesley Publishing Company | isbn=0-201-14450-6 | url-access=registration | url=https://archive.org/details/recursiveprogram0000burg }}</ref>
Recursive descent parsers recognize the class of [[LL parser|LL(k)]] grammars for unbounded ''k''. In less formal terms, they recognize all context-free grammars except those that are [[left recursion|left recursive]]. The running time of a recursive descent parser in the general case is [[exponential time|exponential]], although there is a modification to the algorithm called a [[packrat parser]], which trades memory for [[linear time]]. For a large class of grammars, it is also possible to eliminate left recursion and backtracking.
 
A ''predictive parser'' is a recursive descent parser that does not require [[backtracking]].<ref name="Watson2017">{{cite book|last=Watson|first=Des|title=A Practical Approach to Compiler Construction|url=https://books.google.com/books?id=05B0DgAAQBAJ&q=%22predictive+parser%22|date=22 March 2017|publisher=Springer|isbn=978-3-319-52789-5}}</ref> Predictive parsing is possible only for the class of [[LL parser|LL(''k'')]] grammars, which are the [[context-free grammar]]s for which there exists some positive integer ''k'' that allows a recursive descent parser to decide which production to use by examining only the next ''k'' tokens of input. The LL(''k'') grammars therefore exclude all [[ambiguous grammar]]s, as well as all grammars that contain [[left recursion]]. Any context-free grammar can be transformed into an equivalent grammar that has no left recursion, but removal of left recursion does not always yield an LL(''k'') grammar. A predictive parser runs in [[linear time]].
Recursive descent parsers are used less often in practice than [[LR parser|LR]] or [[LALR parser|LALR]] parsers which are easier to write using parser generators. However, recursive descent parsers have the advantage that they can pass information down to subrules, allowing for parameterized [[nonterminal]]s. This allows these parsers to match a certain class of non-[[context-free grammar|context-free]] languages.
 
Recursive descent with backtracking is a technique that determines which [[Production rule (formal languages)|production]] to use by trying each production in turn. Recursive descent with backtracking is not limited to LL(''k'') grammars, but is not guaranteed to terminate unless the grammar is LL(''k''). Even when they terminate, parsers that use recursive descent with backtracking may require [[exponential time]].
== Example parser ==
Given the following [[EBNF]] [[grammar]] (for [[Niklaus Wirth]]'s [[PL/0]], from
[[Algorithms + Data Structures = Programs]]):
 
Although predictive parsers are widely used, and are frequently chosen if writing a parser by hand, programmers often prefer to use a table-based parser produced by a [[parser generator]],{{Citation needed|date=February 2018}} either for an LL(''k'') language or using an alternative parser, such as [[LALR parser|LALR]] or [[LR parser|LR]]. This is particularly the case if a grammar is not in [[LL parser|LL(''k'')]] form, as transforming the grammar to LL to make it suitable for predictive parsing is involved. Predictive parsers can also be automatically generated, using tools like [[ANTLR]].
<pre>
program = block "." .
 
Predictive parsers can be depicted using transition diagrams for each non-terminal symbol where the edges between the initial and the final states are labelled by the symbols (terminals and non-terminals) of the right side of the production rule.<ref>{{cite book|last1=Aho|first1=Alfred V.|last2=Sethi|first2=Ravi|last3=Ullman|first3=Jeffrey|authorlink1=Alfred V. Aho|authorlink3=Jeffrey Ullman|title=Compilers: Principles, Techniques and Tools|url=https://archive.org/details/compilers00ahoa|url-access=limited|date=1986|publisher=Addison Wesley|page=[https://archive.org/details/compilers00ahoa/page/n193 183]|edition=first}}</ref>
block =
[ "const" ident "=" number {"," ident "=" number} ";"]
[ "var" ident {"," ident} ";"]
{ "procedure" ident ";" block ";" } statement .
 
==Example parser==
statement =
The following [[Extended Backus–Naur Form|EBNF]]-like [[formal grammar|grammar]] (for [[Niklaus Wirth]]'s [[PL/0]] programming language, from ''[[Algorithms + Data Structures = Programs]]'') is in [[LL parser|LL(1)]] form:
[ ident ":=" expression
| "call" ident
| "begin" statement {";" statement } "end"
| "if" condition "then" statement
| "while" condition "do" statement
].
 
<syntaxhighlight lang="ebnf">
condition =
program = block "." .
"odd" expression
| expression ("="|"#"|"<"|"<="|">"|">=") expression
block =
.
["const" ident "=" number {"," ident "=" number} ";"]
["var" ident {"," ident} ";"]
{"procedure" ident ";" block ";"} statement .
statement =
ident ":=" expression
| "call" ident
| "begin" statement {";" statement } "end"
| "if" condition "then" statement
| "while" condition "do" statement .
condition =
"odd" expression
| expression ("="|"#"|"<"|"<="|">"|">=") expression .
expression = ["+"|"-"] term {("+"|"-") term} .
term = factor {("*"|"/") factor} .
factor =
ident
| number
| "(" expression ")" .
</syntaxhighlight>
 
[[terminal symbol|Terminals]] are expressed in quotes. Each [[nonterminal symbol|nonterminal]] is defined by a rule in the grammar, except for ''ident'' and ''number'', which are assumed to be implicitly defined.
expression = [ "+"|"-"] term { ("+"|"-") term} .
 
===C implementation===
term = factor {("*"|"/") factor} .
 
What follows is an implementation of a recursive descent parser for the above language in [[C (programming language)|C]]. The parser reads in source code, and exits with an error message if the code fails to parse, exiting silently if the code parses correctly.
factor = ident | number | "(" expression ")" .
</pre>
 
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 current symbol from the input, and the function ''nextsym'', which updates ''sym'' when called.
[[Terminals]] are expressed in quotes (except for the well defined 'ident'
and 'number'). Each [[nonterminal]] is defined by a rule in the grammar.
 
The implementations of the functions ''nextsym'' and ''error'' are omitted for simplicity.
Notice how closely the code 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.
 
<syntaxhighlight lang="c">
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 nextsym(void);
void error(const char msg[]);
 
<pre>
int accept(Symbol s) {
if (sym == s) {
getsym nextsym();
return 1;
}
return 0;
}
 
int expect(Symbol s) {
if (accept(s))
return 1;
error("expect: unexpected symbol");
return 0;
}
 
void factor(void) {
if (accept(ident)) {
;
} else if (accept(number)) {
;
} else if (accept(lparen)) {
expression();
expect(rparen);
} else {
error("factor: syntax error");
getsym nextsym();
}
}
 
void term(void) {
factor();
while (sym == times || sym == slash) {
getsym();
factor();
while (sym == times || sym == slash) {
}
nextsym();
factor();
}
}
 
void expression(void) {
if (sym == plus || sym == minus)
getsym nextsym();
term();
while (sym == plus || sym == minus) {
getsym();
term();
while (sym == plus || sym == minus) {
}
nextsym();
term();
}
}
 
void condition(void) {
if (accept(oddsym)) {
expression();
} else {
expression();
if (sym == eql || sym == neq || sym == lss ||
sym == leq || sym == gtr || sym == geq) {
getsym();
expression();
} else {
error("condition: invalid operator"expression();
if (sym == eql || sym == neq || sym == lss || sym == leq || sym == gtr || sym == geq) {
getsym();
nextsym();
expression();
} else {
error("condition: invalid operator");
nextsym();
}
}
}
}
 
void statement(void) {
if (accept(ident)) {
expect(becomes);
expression();
} else if (accept(callsym)) {
expect(ident);
} else if (accept(beginsym)) {
do {
statement();
} while (accept(semicolon));
expect(endsym);
} else if (accept(ifsym)) {
condition();
expect(thensym);
statement();
} else if (accept(whilesym)) {
condition();
expect(dosym);
statement();
} else {
error("statement: syntax error");
nextsym();
}
}
 
void block(void) {
if (accept(constsym)) {
do {
expect(ident);
expect(eql);
expect(number);
} while (accept(comma));
expect(semicolon);
}
if (accept(varsym)) {
do {
expect(ident);
} while (accept(comma));
expect(semicolon);
}
while (accept(procsym)) {
expect(ident);
expect(semicolon);
block();
expect(semicolon);
}
statement();
 
statement();
}
 
void program(void) {
getsym nextsym();
block();
expect(period);
}
</syntaxhighlight>
</pre>
 
== Examples ==
Some recursive descent parser generators:
*[[TMG (language)|TMG]] – an early compiler-compiler used in the 1960s and early 1970s
*[[JavaCC]]
*[[Coco/R]]
*[[ANTLR]]
*[[Spirit Parser Framework]] – a C++ recursive descent parser generator framework requiring no pre-compile step
*[[parboiled (Java)]] – a recursive descent [[Parsing expression grammar|PEG]] parsing library for [[Java (programming language)|Java]]
 
The C++ front-end of the [[Clang]] compiler contains a hand-written parser based on the recursive-descent parsing algorithm. <ref>How Clang handles the type / variable name ambiguity of C/C++
https://eli.thegreenplace.net/2012/07/05/how-clang-handles-the-type-variable-name-ambiguity-of-cc/</ref>
 
==See also==
== Formalizing recursive descent parsers ==
*[[Parser combinator]] – a higher-order function used in combinatory parsing, a method of factoring recursive descent parser designs
Although [[context-free grammar]]s are commonly used to [[formal|formalize]] the syntax of the language recognized by a recursive descent parser (as in the example above), an alternate and more direct way to formalize recursive descent parsing is via [[parsing expression grammar]]s, which model the structure and behavior of typical recursive descent parsers directly.
*[[Parsing expression grammar]] – another form representing recursive descent grammar
*[[Recursive ascent parser]]
*[[Tail recursive parser]] – a variant of the recursive descent parser
 
==References==
== Implementation in functional languages ==
{{Reflist}}
Recursive descent parsers are particularly easy to implement in functional languages such as [[Haskell programming language|Haskell]]. See [http://www.cs.nott.ac.uk/~gmh/pearl.pdf Functional Pearls: Monadic Parsing in Haskell] (pdf format).
 
===General See Also references===
* ''[[Compilers: Principles, Techniques, and Tools]]'', first edition, Alfred V Aho, Ravi Sethi, and Jeffrey D Ullman, in particular Section 4.4.
*[[PL/0]] - for more about the programming language PL/0
* ''Modern Compiler Implementation in Java, Second Edition'', Andrew Appel, 2002, {{ISBN|0-521-82060-X}}.
*[[Coco/R]] - a recursive descent parser generator
* ''Recursive Programming Techniques'', W.H. Burge, 1975, {{ISBN|0-201-14450-6}}
*[[ANTLR]] - a recursive descent parser generator
* ''Crafting a Compiler with C'', Charles N Fischer and Richard J LeBlanc, Jr, 1991, {{ISBN|0-8053-2166-7}}.
* ''Compiling with C# and Java'', Pat Terry, 2005, {{ISBN|0-321-26360-X}}, 624
* ''Algorithms + Data Structures = Programs'', Niklaus Wirth, 1975, {{ISBN|0-13-022418-9}}
* ''Compiler Construction'', Niklaus Wirth, 1996, {{ISBN|0-201-40353-6}}
 
==External References links==
*[https://compilers.iecc.com/crenshaw/ Jack W. Crenshaw: ''Let's Build A Compiler'' (1988-1995)], in [[Pascal (programming language)|Pascal]], with [[assembly language]] output, using a "keep it simple" approach
* ''Recursive Programming Techniques'', W.H. Burge, 1975, ISBN 0-201-14450-6
* The [[Dragon book]], in particular Section 4.4
* [http://search.cpan.org/~dconway/Parse-RecDescent-1.94/lib/Parse/RecDescent.pod Parse::RecDescent]: A versatile recursive descent [[Perl]] module.
* [http://pyparsing.sourceforge.net/ pyparsing]: A versatile recursive descent [[Python (programming language)|Python]] module.
{{FOLDOC}}
* ''Algorithms + Data Structures = Programs'', Niklaus Wirth, 1975, ISBN 0-13-022418-9
* ''Compiler Construction'', Niklaus Wirth, 1996, ISBN 0-201-40353-6
* ''Compiling with C# and Java'', Pat Terry, 2005, ISBN/ISSN: 0-321-26360-X 624
 
{{Parsers}}
[[Category:Parsing algorithms]]
 
[[Category:Parsing algorithms]]
[[de:Rekursiver Abstieg]]
[[Category:Articles with example C code]]
[[ko:되부름 하향 구문 분석]]