Debian Codegraph @

lib/mllpt-lib/ml-lpt/doc/usage-ml-antlr.tex

raw
1 %!TEX root = manual.tex
2 %
3 \chapter{ML-Antlr}
4
5 %\section{Overview}
6
7 Parsers analyze the syntactic structure of an input string, and are usually specified with some variant of context-free grammars. \antlr{} is a parser generator for Standard ML based on Terence Parr's variant of $LL(k)$ parsing. The details of the parsing algorithm are given in the companion implementation notes; the practical restrictions on grammars are discussed in Section~\ref{sec:antlr-llk}. A parser generated by \antlr{} is a functor; it requires a module with the \texttt{ANTLR\char`\_LEXER} signature:
8 \begin{lstlisting}
9 signature ANTLR_LEXER = sig
10 type strm
11 val getPos : strm -> AntlrStreamPos.pos
12 end
13 \end{lstlisting}
14 Applying the parser functor will yield a module containing a \texttt{parse} function:
15 \begin{lstlisting}
16 val parse :
17 (Lex.strm -> ParserToks.token * AntlrStreamPos.span * Lex.strm)
18 -> Lex.strm
19 -> result_ty option * strm * ParserToks.token AntlrRepair.repair list
20 \end{lstlisting}
21 where \texttt{result\char`\_ty} is determined by the semantic actions for the parser. The \texttt{ParserTokens} module is generated by \antlr{} (see Section~\ref{sec:antlr-gencode}) and the \texttt{AntlrRepair} module is available in the \texttt{ml-lpt} library (see Chapter~\ref{ch:ml-lpt-lib}).
22
23 Notable features of \antlr{} include:
24 \begin{itemize}
25 \item Extended BNF format, including Kleene-closure (*), positive closure (+), and optional (?) operators.
26 \item Robust, automatic error repair.
27 \item Selective backtracking.
28 \item ``Inherited attributes'': information can flow downward as well as upward during a parse.
29 \item Semantic predicates: a syntactic match can be qualified by a semantic condition.
30 \item Grammar inheritence.
31 \item Convenient default actions, especially for EBNF constructions.
32 \item Convenient abbreviations for token names (\emph{e{.}g{.}}, \texttt{"("} rather than \texttt{LP})
33 \end{itemize}
34 The tool is invoked from the command-line as follows:
35 \begin{verbatim}
36 ml-antlr [options] file
37 \end{verbatim}
38 where \texttt{file} is the name of the input \ulex{} specification, and where \texttt{options} may be any combination of:
39
40 \vskip 12pt
41 \begin{tabular}{lp{0.65\textwidth}}
42 \texttt{--dot} & generate DOT output (for graphviz; see \texttt{http://www.graphviz.org}).
43 The generated file will be named \texttt{file.dot}, where \texttt{file} is the input file. \\
44 \\
45 \texttt{--latex} & generate a simple \LaTeX version of the grammar, named \texttt{file.tex}. \\
46 \\
47 \texttt{--unit-actions} & ignore the action code in the grammar, and instead return \texttt{()}
48 for every production. \\
49 \\
50 \texttt{--debug} & add code to the actions to print the left-hand-side of the production.
51 \end{tabular}%
52
53 \vskip 10pt \noindent
54 The output file will be called \texttt{file.sml}.
55
56 \section{Background definitions}
57
58 Before describing \antlr{}, we need some terminology. A \emph{context-free grammar} (CFG) is a set of \emph{token} (or \emph{terminal}) symbols, a set of \emph{nonterminal} symbols, a set of \emph{productions}, and a start symbol $S$, which must be a nonterminal.
59 The general term \emph{symbol} refers to both tokens and nonterminals. A production relates a nonterminal $A$ to a string of symbols $\alpha$; we write this relation as $A \ra \alpha$. Suppose $\alpha A \beta$ is a symbol string, and $A$ is a nonterminal symbol. We write $\alpha A \beta \Ra \alpha \gamma \beta$ if $A \ra \gamma$ is a production; this is called a one-step derivation. In general, a CFG generates a language, which is a set of token strings. The strings included in this language are exactly those token string derived in one or more steps from the start symbol $S$.
60
61 A parser recognizes whether an input string is in the language generated by a given CFG, usually computing some value (such as a parse tree) while doing so. The computations performed during a parse are called \emph{semantic actions} (or just \emph{actions}).
62
63 \section{Specification format}\label{sec:antlr-spec}
64
65 A \antlr{} specification is a list of semicolon-terminated \emph{declarations}. Each declaration is either a \emph{directive} or a \emph{nonterminal definition}. Directives are used to alter global specification properties (such as the name of the functor that will be generated) or to define supporting infrastructure for the grammar. The nonterminal definitions specify the grammar itself. The grammar for \antlr{} is given in Figure~\ref{fig:antlr-syntax}.
66
67 \begin{figure}
68 \Grammar{
69 \GFirstB{spec}
70 {$($ declaration \T{;} $)^*$}
71
72 \GFirstB{declaration}
73 {directive}
74 \GNextB
75 {nonterminal}
76
77 \GFirstB{directive}
78 {\kw{defs} code}
79 \GNextB
80 {\kw{entry} ID $($ \T{,} ID $)^*$}
81 \GNextB
82 {\kw{import} STRING $($ \kw{dropping} symbol$^+$ $)^?$}
83 \GNextB
84 {\kw{keywords} symbol $($ \T{,} symbol $)^*$}
85 \GNextB
86 {\kw{value} ID code}
87 \GNextB
88 {\kw{name} ID}
89 \GNextB
90 {\kw{header} code}
91 \GNextB
92 {\kw{refcell} ID \T{:} monotype \T{=} code}
93 \GNextB
94 {\kw{start} ID}
95 \GNextB
96 {\kw{tokentype} qualid}
97 \GNextB
98 {\kw{tokens} \T{:} tokdef $($ \T{|} tokdef $)^*$}
99 \GNextB
100 {\kw{nonterms} \T{:} datacon $($ \T{|} datacon $)^*$}
101
102 \GFirstB{code}
103 { \T{(} $\dots$ \T{)} }
104
105 \GFirstB{tokdef}
106 {datacon $($ \T{(} STRING \T{)} $)^?$}
107
108 \GFirstB{datacon}
109 {ID}
110 \GNextB
111 {ID \T{of} monotype}
112
113 \GFirstB{nonterminal}
114 {ID formals$^?$ \T{:} prodlist}
115
116 \GFirstB{formals}
117 { \T{(} ID $($ \T{,} ID $)^*$ \T{)} }
118
119 \GFirstB{prodlist}
120 {production $($ \T{|} production $)^*$}
121
122 \GFirstB{production}
123 {\kw{try}$^?$ named-item$^*$ $($ \kw{where} code $)^?$ $($ \T{=>} code $)^?$ }
124 \GFirstB{named-item}
125 {$($ ID \T{:} $)^?$ item}
126 \GFirstB{item}
127 {prim-item \T{?}}
128 \GNextB
129 {prim-item \T{+}}
130 \GNextB
131 {prim-item \T{*}}
132
133 \GFirstB{prim-item}
134 {symbol $($ \T{@} code $)^?$}
135 \GNextB
136 { \T{(} prodlist \T{)} }
137
138 \GFirstB{symbol}
139 {ID}
140 \GNextB
141 {STRING}
142
143 \GFirstB{monotype}{\textrm{An SML monomorphic type expression}}
144
145 \GFirstB{qualid}{\textrm{An SML qualified identifier}}
146
147 \GFirstB{ID}{\textrm{An SML identifier}}
148 \GFirstB{STRING}{\textrm{An SML string literal}}
149 }
150 \caption{The \antlr{} grammar}\label{fig:antlr-syntax}
151 \end{figure}
152
153 SML-style comments (\texttt{(* ... *)}) are treated as ignored whitespace anywhere they occur in the specification, \emph{except} in segments of code. The \textit{code} symbol represents a segment of SML code, enclosed in parentheses. Extra parentheses occuring within strings or comments in code need not be balanced.
154 A complete example specification appears in Chapter~\ref{ch:example}.
155
156 Most \antlr{} declarations are \emph{cumulative}: they may appear multiple times in a grammar specification, with each new declaration adding to the effect of the previous ones. Thus, for instance, the specification fragment
157 \begin{lstlisting}[language=MLAntlr]
158 %tokens : foo ;
159 %tokens : bar of string ;
160 \end{lstlisting}%
161 is equivalent to the single directive
162 \begin{lstlisting}[language=MLAntlr]
163 %tokens : foo | bar of string ;
164 \end{lstlisting}%
165 and similarly for nonterminal definitions and so on. All declarations are cumulative except for the \kw{start} and \kw{name} directives.
166 The reason for treating specifications in this way is to give the \kw{import} directive very simple semantics, as described below.
167
168 \section{Directives}
169
170 \subsection{The \kw{defs} directive}
171
172 The \kw{defs} directive is used to include a segment of code in the generated parser:
173 \begin{lstlisting}[language=SML]
174 %defs (
175 fun helperFn x = (* ... *)
176 );
177 \end{lstlisting}%
178 All definitions given will be in scope for the semantic actions (see Section~\ref{sec:antlr-actions}).
179
180 \subsection{The \kw{entry} directive}
181
182 It is often useful to parse input based on some fragment of a grammar. When a nonterminal is declared to be an \emph{entry point} for the grammar via \kw{entry}, \antlr{} will generate a separate \texttt{parse} function that expects the input to be a string derived from that nonterminal. Given a grammar with a nonterminal \texttt{exp} and the declaration
183 \begin{lstlisting}[language=MLAntlr]
184 %entry exp;
185 \end{lstlisting}%
186 the generated parser will include a function
187 \begin{lstlisting}
188 val parseexp : (Lex.strm -> ParserToks.token * AntlrStreamPos.span * Lex.strm)
189 -> Lex.strm
190 -> exp_ty option * strm * ParserToks.token AntlrRepair.repair list
191 \end{lstlisting}
192 where \texttt{exp\char`\_ty} is the type of the actions for the \texttt{exp} nonterminal. Note that if \texttt{exp} has inherited attributes (Section~\ref{sec:inh-attr}) they will appear as a tuple argument, curried after the lexer argument:
193 \begin{lstlisting}
194 val parseexp : (Lex.strm -> ParserToks.token * AntlrStreamPos.span * Lex.strm)
195 -> attributes
196 -> Lex.strm
197 -> exp_ty option * strm * ParserToks.token AntlrRepair.repair list
198 \end{lstlisting}
199 Finally, the \emph{start} symbol (Section~\ref{sec:start}) is always an entry point to the grammar, but the generated function is simply called \texttt{parse}.
200
201 \subsection{The \kw{import} directive}
202
203 The \kw{import} directive is used to include one grammar inside another. The string given in the directive should hold the path to a grammar file, and $\backslash$ characters must be escaped. By default, all declarations appearing in the specified file are included in the resulting grammar, except for \kw{start}, \kw{entry}, and \kw{name} declarations. However, individual tokens or nonterminals can be dropped by listing them in the \kw{dropping} clause of an \kw{import} declaration. Since nonterminal definitions are cumulative (Section~\ref{sec:antlr-nt}), the imported nonterminals can be extended with new productions simply by listing them.
204 The final grammar must, of course, ensure that all used tokens and nonterminals are defined.
205
206 \subsection{The \kw{keywords} and \kw{value} directives}
207
208 \Antlr{} uses an error-repair mechanism that is based on inserting or deleting tokens until
209 a correct parse is found.
210 The \kw{keywords} and \kw{default} directives allow one to improve this process.
211 Since changes to the input involving keywords can drastically alter the meaning of the
212 input, it is usually desirable to favor non-keyword repairs.
213 The \kw{keywords} directive is used to tell \antlr{} which tokens should be considered keywords.
214 The \kw{value} directive is used to define a default argument for non-nullary tokens, which
215 is used to construct a token value that can be inserted into the token stream
216 when attempting to find a repair.
217 For example
218 \begin{lstlisting}[language=MLAntlr]
219 %value NUMBER(0);
220 \end{lstlisting}%
221 would allow the \texttt{NUMBER} token to be inserted as an error repair.
222
223 Section~\ref{sec:antlr-gencode} describes how to report error repairs to the user.
224 %When a syntax error is discovered, \antlr{} attempts to find a single-token repair to the input that will %allow the parse to continue.
225
226 \subsection{The \kw{name} directive}
227
228 The prefix to use for the name of the generated parser functor is specified using \kw{name}.
229 In addition to the functor, \antlr{} will generate a module to define the \texttt{token} datatype.
230 If the declaration
231 \begin{lstlisting}[language=MLAntlr]
232 %name Example;
233 \end{lstlisting}%
234 appears in the specification, then the parser functor will be named
235 \texttt{ExampleParseFn} and the tokens module will be called \texttt{ExampleTokens}.
236
237 \subsection{The \kw{header} directive}
238 The \kw{header} directive allows one to specify the parser's functor.
239 This directive is useful when you want to add additional parameters to the functor,
240 but the declaration must include the \texttt{Lex} structure with signature
241 \texttt{ANTLR\char`\_LEXER}.
242 For example,
243 \begin{lstlisting}
244 %header (
245 functor ExampleParseFn (
246 structure Lex : ANTLR_LEXER
247 structure Extras : EXTRA_SIG));
248 \end{lstlisting}%
249
250 \noindent{}\textbf{Note:} the \kw{header} directive was added in SML/NJ version 110.72.
251
252 \subsection{The \kw{refcell} directive}
253
254 Because semantic actions must be pure (for backtracking and error repair), they cannot make use of standard reference cells to communicate information.
255 Nonterminals may inherit attributes (Section~\ref{sec:inh-attr}), which allows information to flow downward, but in some cases flowing information this way can become extremely tedious.
256 For example, a data structure may only need to be updated at a single point in the grammar, but in order to properly thread this state through the grammar, an inherited attribute would have to be added and propagated through every nonterminal.
257
258 The \kw{refcell} directive is used to declare a backtracking-safe reference cell and make it available to all semantic actions. Reference cells are declared by giving the name, type, and initial value for the cell. Each cell is bound in the semantic actions as a standard SML \texttt{ref} value. Thus, for example, we might have the following specification fragment:
259 \begin{lstlisting}[language=MLAntlr]
260 %refcell symbols : StringSet.set = ( StringSet.empty );
261
262 exp
263 : INT
264 | (exp)
265 | ID => ( symbols := StringSet.add(!symbols, ID); ID )
266 ;
267 \end{lstlisting}%
268 The result of this fragment is that all symbol uses are tracked, in any use of
269 the \texttt{exp} nonterminal, but without having to manually thread the data
270 structure state through the grammar.
271
272 The final contents of a reference cell is returned as an extra result from the parse
273 following the repair list.
274
275 \subsection{The \kw{start} directive}\label{sec:start}
276
277 A particular nonterminal must be designated as the start symbol for the grammar. The start symbol can be specified using \kw{start}; otherwise, the first nonterminal defined is assumed to be the start symbol.
278
279 \subsection{The \kw{tokentype} directive}
280
281 As noted above, \mlantlr{} synthesizes a structure that contains a datatype representing the
282 tokens specified in the grammar.
283 In some situations, it may be useful to specify the token datatype elsewhere (\eg{}, if you
284 want to use the same lexer for two different parsers).
285 In such a case, one can use the \kw{tokentype} directive to give a qualified name for the token
286 dataype.
287 This identifier will be used in the tokens structure to specify the tokens type.
288 For example, if the grammar specification contains the directive
289 \begin{lstlisting}[language=MLAntlr]
290 %tokentype MyTokens.t;
291 \end{lstlisting}%
292 then the code
293 \begin{lstlisting}[language=SML]
294 datatype token = datatype MyTokens.t
295 \end{lstlisting}%
296 in the tokens structure.
297 Even when the \kw{tokentype} directive is used, one must also declare the grammar's tokens
298 using the \kw{tokens} directive.
299 Furthermore, the user-supplied token datatype must include a nullary \texttt{EOF} constructor
300 in addition to exactly the constructors specified by the \kw{tokens} directives.\footnote{
301 When the \kw{tokentype} directive is specified, \mlantlr{} will generate a signature for
302 the tokens structure.
303 }
304
305 \noindent{}\textbf{Note:} the \kw{tokentype} directive was added in SML/NJ version 110.81.
306
307 \subsection{The \kw{tokens} directive}
308
309 The alphabet of the parser is defined using \kw{tokens}. The syntax for this directive resembles a datatype declaration in SML, except that optional abbreviations for tokens may be defined. For example:
310 \begin{lstlisting}[language=MLAntlr]
311 %tokens
312 : KW_let ("let") | KW_in ("in")
313 | ID of string | NUM of Int.int
314 | EQ ("=") | PLUS ("+")
315 | LP ("(") | RP (")")
316 ;
317 \end{lstlisting}%
318 Within nonterminal definitions, tokens may be referenced either by their name or abbreviation; the latter must always be double-quoted.
319
320 \subsection{The \kw{nonterms} directive}
321 \mlantlr{} normally identifies non-terminal symbols by their appearance on the left-hand side
322 of a production and relies on SML type inference to determine the type returned by parsing
323 a string derived from the nonterminal.
324 It is also possible to declare the type of a non-terminal using the \kw{nonterms} directive, which has
325 similar syntax to the \kw{tokens} directive.
326 Specifying the types of non-terminals is useful for improving the locality of type error
327 messages in the generated parser code.
328
329 \section{Nonterminal definitions}\label{sec:antlr-nt}
330
331 The syntax of nontermal definitions is given in Figure~\ref{fig:antlr-syntax}. As an illustration of the grammar, consider the following example, which defines a nonterminal with three productions, taking a formal parameter \texttt{env}:
332 \begin{lstlisting}[language=MLAntlr]
333 atomicExp(env)
334 : ID => ( valOf(AtomMap.find (env, Atom.atom ID)) )
335 | NUM
336 | "(" exp@(env) ")"
337 ;
338 \end{lstlisting}%
339 Note that actions are only allowed at the end of a production, and that they are optional.
340
341 As with most directives, the non-terminal definitions are cumulative.
342 For example, the definition of \texttt{atomicExp} above could also be
343 written as three separate rules.
344 \begin{lstlisting}[language=MLAntlr]
345 atomicExp(env) : ID => ( valOf(AtomMap.find (env, Atom.atom ID)) );
346 atomicExp(env) : NUM;
347 atomicExp(env) : "(" exp@(env) ")";
348 \end{lstlisting}%
349
350 \subsection{Extended BNF constructions}
351
352 In standard BNF syntax, the right side of a production is a simple string of symbols. Extended BNF allows regular expression-like operators to be used: \texttt{*}, \texttt{+}, and \texttt{?} can follow a symbol, denoting 0 or more, 1 or more, or 0 or 1 occurrences respectively. In addition, parentheses can be used within a production to enclose a \emph{subrule}, which may list several \texttt{|}-separated alternatives, each of which may have its own action. In the following example, the nonterminal \texttt{item\char`\_list} matches a semicolon-terminated list of identifiers and integers:
353 \begin{lstlisting}[language=MLAntlr]
354 item_list : (( ID | INT ) ";")* ;
355 \end{lstlisting}%
356 All of the extended BNF constructions have implications for the actions of a production; see Section~\ref{sec:antlr-actions} for details.
357
358 \subsection{Inherited attributes}\label{sec:inh-attr}
359
360 In most parsers, information can flow upward during the parse through actions, but not downard. In attribute grammar terminology, the former refers to \emph{synthesized} attributes, while the latter refers to \emph{inherited attributes}. Since \antlr{} is a predictive parser, it allows both kinds of attributes. Inherited attributes are treated as parameters to nonterminals, which can be used in their actions or semantic predicates. Formal parameters are introduced by enclosing them in parentheses after the name of a nonterminal and before its production list; the list of parameters will become a tuple. In the following, the nonterminal \texttt{expr} takes a single parameter called \texttt{env}:
361 \begin{lstlisting}[language=MLAntlr]
362 expr(env) : (* ... *) ;
363 \end{lstlisting}%
364 If a nonterminal has a formal parameter, any use of that nonterminal is required to apply it to an actual parameter. Actual parameters are introduced in a production by giving the name of a nonterminal, followed by the \texttt{@} sign, followed by the code to compute the parameter. For example:
365 \begin{lstlisting}[language=MLAntlr]
366 assignment : ID ":=" expr@(Env.emptyEnv) ;
367 \end{lstlisting}%
368
369 \subsection{Selective backtracking}
370
371 Sometimes it is inconvenient or impossible to construct a nonterminal definition which can be unambiguously resolved with finite lookahead.
372 % (see Section~\ref{sec:antlr-llk} for examples).
373 The \kw{try} keyword can be used to mark ambiguous \emph{productions} for selective backtracking. For backtracking to take place, each involved production must be so marked. Consider the following:
374 \begin{lstlisting}[language=MLAntlr]
375 A : %try B* ";"
376 | %try B* "(" C+ ")"
377 ;
378 \end{lstlisting}%
379 As written, the two productions cannot be distinguished with finite lookahead, since they share an arbitrary long prefix of \texttt{B} nonterminal symbols. Adding the \kw{try} markers tells \antlr{} to attempt to parse the first alternative, and if that fails to try the second. Another way to resolve the ambiguity is the use of subrules, which do not incur a performance penalty:
380 \begin{lstlisting}[language=MLAntlr]
381 A : B* ( ";"
382 | "(" C+ ")"
383 )
384 ;
385 \end{lstlisting}%
386 This is essentially \emph{left-factoring}. See Section~\ref{sec:antlr-llk} for more guidance on working with the $LL(k)$ restriction.
387
388 \subsection{Semantic predicates}
389
390 A production can be qualified by a \emph{semantic predicate} by introducting a \kw{where} clause. Even if the production is syntactically matched by the input, it will not be used unless its semantic predicate evaluates to \texttt{true}. A \kw{where} clause can thus introduce context-sensitivity into a grammar. The following example uses an inherited \texttt{env} attribute, containing a variable-value environment:
391 \begin{lstlisting}[language=MLAntlr]
392 atomicExp(env)
393 : ID %where ( AtomMap.inDomain(env, Atom.atom ID) )
394 => ( valOf(AtomMap.find (env, Atom.atom ID)) )
395 | NUM
396 | "(" exp@(env) ")"
397 ;
398 \end{lstlisting}%
399 In this example, if a variable is mentioned that has not been defined, the error is detected and reported during the parse as a syntax error.
400
401 Semantic predicates are most powerful when combined with selective backtracking. The combination allows two syntactically identical phrases to be distinguished by contextual, semantic information.
402
403 \subsection{Actions}\label{sec:antlr-actions}
404
405 Actions for productions are just SML code enclosed in parentheses. Because of potential backtracking and error repair, action code should be pure (except that they may update \antlr{} \texttt{refcell}s; see the \kw{refcell} directive).
406
407 In scope for an action are all the user definitions from the \kw{defs} directive. In addition, the formal parameters of the production are in scope, as are the semantic yield of all symbols to the left of the action (the yield of a token is the data associated with that token's constructor). In the following example, the first action has \texttt{env} and \texttt{exp} in scope, while the second action has \texttt{env} and \texttt{NUM} in scope:
408 \begin{lstlisting}[language=MLAntlr]
409 atomicExp(env)
410 : "(" exp@(env) ")" => ( exp )
411 | NUM => ( NUM )
412 ;
413 \end{lstlisting}%
414 Notice also that the actual parameter to \texttt{exp} in the first production is \texttt{env}, which is in scope at the point the parameter is given; \texttt{exp} itself would not be in scope at that point.
415
416 An important aspect of actions is naming: in the above example, \texttt{exp} and \texttt{NUM} were the default names given to the symbols in the production. In general, the default name of a symbol is just the symbol's name. If the same name appears multiple times in a production, a number is appended to the name of each yield, start from 1, going from left to right. A subrule (any items enclosed in parentheses) is by default called \texttt{SR}. Any default name may be overriden using the syntax \texttt{name=symbol}. Overriding a default name does \emph{not} change the automatic number for other default names. Consider:
417 \begin{lstlisting}[language=MLAntlr]
418 foo : A bar=A A ("," A)* A*
419 ;
420 \end{lstlisting}%
421 In this production, the names in scope from left to right are: \texttt{A1}, \texttt{bar}, \texttt{A3}, \texttt{SR}, \texttt{A4}.
422
423 The EBNF operators \texttt{*}, \texttt{+} and \texttt{?} have a special effect on the semantic yield of the symbols to which they are applied. Both \texttt{*} and \texttt{+} yield a \emph{list} of the type of their symbol, while \texttt{?} yields an option. For example, if \texttt{ID*} appeared in a production, its default name would be \texttt{ID}, and if the type of value of \texttt{ID} was \texttt{string}, it would yield a \texttt{string list}; likewise \texttt{ID?} would yield a \texttt{string option}.
424
425 Subrules can have embedded actions that determine their yield:
426 \begin{lstlisting}[language=MLAntlr]
427 plusList : ((exp "+" exp => ( exp1 + exp2 )) ";" => ( SR ))* => ( SR )
428 \end{lstlisting}%
429 The \texttt{plusList} nonterminal matches a list of semicolon-terminated additions. The innermost subrule, containing the addition, yields the value of the addition; that subrule is contained in a larger subrule terminated by a semicolon, which yield the value of the inner subrule. Finally, the semicolon-terminated subrule is itself within a subrule, which is repeated zero or more times. Note that the numbering scheme for names is restarted within each subrule.
430
431 Actions are \emph{optional}: if an action is not specified, the default behavior is to return all nonterminals and non-nullary tokens in scope. Thus, the last example can be written as
432 \begin{lstlisting}[language=MLAntlr]
433 plusList : ((exp "+" exp => ( exp1 + exp2 )) ";")*
434 \end{lstlisting}%
435 since \texttt{"+"} and \texttt{";"} represent nullary token values.
436
437 \section{The $LL(k)$ restriction}\label{sec:antlr-llk}
438
439 When working with any parser, one must be aware of the restrictions its algorithm places on grammars.
440 When \antlr{} analyzes a grammar, it attempts to create a prediction-decision
441 tree for each nonterminal.
442 In the usual case, this decision is made using lookahead token sets. The tool will start with $k = 1$
443 lookahead and increment up to a set maximum until it can
444 uniquely predict each production. Subtrees of the decision tree
445 remember the tokens chosen by their parents, and take this into account
446 when computing lookahead. For example, suppose we have two productions
447 at the top level that generate the following sentences:
448 \begin{verbatim}
449 prod1 ==> AA
450 prod1 ==> AB
451 prod1 ==> BC
452 prod2 ==> AC
453 prod2 ==> C
454 \end{verbatim}
455 At $k = 1$, the productions can generate the following sets:
456 \begin{verbatim}
457 prod1 {A, B}
458 prod2 {A, C}
459 \end{verbatim}
460 and $k = 2$,
461 \begin{verbatim}
462 prod1 {A, B, C}
463 prod2 {C, <EOF>}
464 \end{verbatim}
465 Examining the lookahead sets alone, this grammar fragment looks ambiguous
466 even for $k = 2$. However, \antlr{} will generate the following decision
467 tree:
468 \begin{lstlisting}[language=SML]
469 if LA(0) = A then
470 if LA(1) = A or LA(1) = B then
471 predict prod1
472 else if LA(1) = C then
473 predict prod2
474 else if LA(0) = B then
475 predict prod1
476 else if LA(1) = C then
477 predict prod2
478 \end{lstlisting}%
479
480 In \antlr{}, only a small amount of lookahead is used by default ($k = 3$). Thus, the following grammar is ambiguous for \antlr{}:
481 \begin{lstlisting}[language=MLAntlr]
482 foo : A A A B
483 | A A A A
484 ;
485 \end{lstlisting}%
486 and will generate the following error message:
487 \begin{verbatim}
488 Error: lookahead computation failed for 'foo',
489 with a conflict for the following productions:
490 foo ::= A A A A EOF
491 foo ::= A A A B EOF
492 The conflicting token sets are:
493 k = 1: {A}
494 k = 2: {A}
495 k = 3: {A}
496 \end{verbatim}
497 Whenever a lookahead ambiguity is detected, an error message of this form is given. The listed productions are the point of conflict.
498 The \texttt{k = ...} sets together give examples that can cause the ambiguity, in this case an input of \texttt{AAA}.
499
500 The problem with this example is that the two \texttt{foo} productions can only be distinguished by a token at $k = 4$ depth. This situation can usually be resolved using \emph{left-factoring}, which lifts the common prefix of multiple productions into a single production, and then distinguishes the old productions through a subrule:
501 \begin{lstlisting}[language=MLAntlr]
502 foo : A A A (B | A)
503 ;
504 \end{lstlisting}%
505 Recall that subrule alternatives can have their own actions:
506 \begin{lstlisting}[language=MLAntlr]
507 foo : A A A ( B => ( "got a B" )
508 | A => ( "got an A" )
509 )
510 ;
511 \end{lstlisting}%
512 making left-factoring a fairly versatile technique.
513
514 Another limitation of predictive parsing is \emph{left-recursion}, where a nonterminal recurs without any intermediate symbols:
515 \begin{lstlisting}[language=MLAntlr]
516 foo : foo A A
517 | B
518 ;
519 \end{lstlisting}%
520 Left-recursion breaks predictive parsing, because it is impossible to make a prediction for a left-recursive production without already having a prediction in hand. Usually, this is quite easily resolved using EBNF operators, since left-recursion is most often used for specifying lists. Thus, the previous example can be rewritten as
521 \begin{lstlisting}[language=MLAntlr]
522 foo : B (A A)*
523 ;
524 \end{lstlisting}%
525 which is both more readable and more amenable to $LL(k)$ parsing.
526
527 \section{Position tracking}
528
529 \antlr{} includes built-in support for propagating position information. Because the lexer module is required to provide a \texttt{getPos} function, the tokens themselves do not need to carry explicit position information.
530 A position \emph{span} is a pair to two lexer positions (the type \texttt{AntlrStreamPos.span} is
531 an abbreviation for \texttt{AntlrStreamPos.pos * AntlrStreamPos.pos}).
532 Within action code, the position span of any symbol (token, nonterminal, subrule) is available as a value; if the yield of the symbol is named \texttt{Sym}, its span is called \texttt{Sym\char`\_SPAN}.
533 Note that the span of a symbol after applying the \texttt{*} or \texttt{+} operators is the
534 span of the entire matched list:
535 \begin{lstlisting}[language=MLAntlr]
536 foo : A* => (* A_SPAN starts at the first A and ends at the last *)
537 \end{lstlisting}%
538 In addition, the span of the entire current production is available as \texttt{FULL\char`\_SPAN}.
539
540 %\section{Handling precedence}
541
542 \section{Using the generated code}\label{sec:antlr-gencode}
543
544 When \antlr{} is run, it generates a tokens module and a parser functor.
545 If the parser is given the name \texttt{Xyz} via the \kw{name} directive, these structures will be called \texttt{XyzParseFn} and \texttt{XyzTokens} respectively.
546 The tokens module will contain a single datatype, called \texttt{token}. The data constructors for the \texttt{token} type have the same name and type as those given in the \kw{tokens} directive; in addition, a nullary constructor called \texttt{EOF} will be available.
547
548 The generated parser functor includes the following:
549 \begin{lstlisting}[language=SML]
550 val parse : (Lex.strm -> ParserToks.token * AntlrStreamPos.span * Lex.strm)
551 -> Lex.strm
552 -> result_ty option * strm * ParserToks.token AntlrRepair.repair list
553 \end{lstlisting}%
554 where \texttt{result\char`\_ty} is the type of the semantic action for the grammar's start symbol.
555 The \texttt{parse} function is given a lexer function and a stream.
556 The result of a parse is the semantic yield of the parse, the value of the stream at the end of the parse, and a list of error repairs.
557 If an unrepairable error occurred, \texttt{NONE} is returned for the yield of the parse.
558
559 Note that if the start symbol for the grammar includes an inherited attribute (or a tuple of attributes), it will appear as an additional, curried parameter to the parser following the lexer parameter. Suppose, for example, that a grammar has a start symbol with an inherited \texttt{Int.int AtomMap.map}, and that the grammar yields \texttt{Int.int} values. The type of its \texttt{parse} function is as follows:
560 \begin{lstlisting}
561 val parse :
562 (strm -> ParserToks.token * strm) ->
563 Int.int AtomMap.map ->
564 strm ->
565 Int.int option * strm * ParserToks.token AntlrRepair.repair list
566 \end{lstlisting}
567
568 The \texttt{AntlrRepair} module is part of the \texttt{ml-lpt-lib} library; it is fully described in Chapter~\ref{ch:ml-lpt-lib}.
569 It includes a function \texttt{repairToString}:
570 \begin{lstlisting}
571 val repairToString :
572 ('token -> string) -> AntlrStreamPos.sourcemap
573 -> 'token repair -> string
574
575 \end{lstlisting}
576 which can be used to produce error messages from the parser's repair actions.
577 There is a more refined version of this function that allows one to specialize
578 the string representation of tokens based on whether the repair adds or deletes
579 them.
580 \begin{lstlisting}
581 datatype add_or_delete = ADD | DEL
582
583 val repairToString :
584 (add_or_delete -> 'token -> string) -> AntlrStreamPos.sourcemap
585 ->'token repair -> string
586 \end{lstlisting}
587
588
589 Likewise, the tokens module (\texttt{ParserTokens} in this example) includes a function:
590 \begin{lstlisting}
591 val toString : token -> string
592 \end{lstlisting}
593 Thus, although error reporting is customizable, a reasonable default is provided, as illustrated below:
594 \begin{lstlisting}
595 let
596 val sm = AntlrStreamPos.mkSourcemap()
597 val (result, strm', errs) = Parser.parse (Lexer.lex sm) strm
598 val errStrings =
599 map (AntlrRepair.repairToString ParserTokens.toString sm)
600 errs
601 in
602 print (String.concatWith "\n" errStrings)
603 end
604 \end{lstlisting}
605 The \texttt{toString} function will convert each token to its symbol as given in a \kw{tokens} directive,
606 using abbreviations when they are available.
607 By substituting a different function for \texttt{toString}, this behavior can be altered.