main.tex 123 KB
Newer Older
1 2 3 4
\def\true{true}
\let\fpacm\true
\documentclass[onecolumn,11pt,nocopyrightspace]{sigplanconf}
\usepackage{amstext}
5
\usepackage[T1]{fontenc}
6
\usepackage[latin1]{inputenc}
7
\usepackage{moreverb}
8
\usepackage{tikz}
9 10
\usepackage{xspace}
\usepackage{mymacros}
11
\def\fppdf{true}
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
\usepackage{fppdf}
\input{macros}
\input{version}

% ---------------------------------------------------------------------------------------------------------------------
% Headings.

\title{\menhir Reference Manual\\\normalsize (version \menhirversion)}

\begin{document}

\authorinfo{François Pottier\and Yann Régis-Gianas}
	   {INRIA}
	   {\{Francois.Pottier, Yann.Regis-Gianas\}@inria.fr}

\maketitle

% ---------------------------------------------------------------------------------------------------------------------

\clearpage
\tableofcontents
\clearpage

% ---------------------------------------------------------------------------------------------------------------------

\section{Foreword}

\menhir is a parser generator. It turns high-level grammar specifications,
decorated with semantic actions expressed in the \ocaml programming
language~\cite{objective-caml}, into parsers, again expressed in \ocaml. It is
based on Knuth's LR(1) parser construction technique~\cite{knuth-lr-65}. It is
strongly inspired by its precursors: \yacc~\cite{johnson-yacc-79},
\texttt{ML-Yacc}~\cite{tarditi-appel-00}, and \ocamlyacc~\cite{objective-caml},
but offers a large number of minor and major improvements that make it a more
modern tool.

This brief reference manual explains how to use \menhir. It does not attempt to
explain context-free grammars, parsing, or the LR technique. Readers who have
never used a parser generator are encouraged to read about these ideas
first~\cite{aho-86,appel-tiger-98,hopcroft-motwani-ullman-00}. They are also
invited to have a look at the \distrib{demos} directory in \menhir's
distribution.

55 56 57 58 59 60 61 62 63 64 65
Potential users of Menhir should be warned that \menhir's feature set is not
completely stable. There is a tension between preserving a measure of
compatibility with \ocamlyacc, on the one hand, and introducing new ideas, on
the other hand. Some aspects of the tool, such as the error handling
mechanism, are still potentially subject to incompatible changes: for
instance, in the future, the current error handling mechanism (which is based
on the \error token, see \sref{sec:errors}) could be removed and replaced with
an entirely different mechanism.

There is room for improvement in the tool and in this reference manual. Bug
reports and suggestions are welcome!
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

% ---------------------------------------------------------------------------------------------------------------------

\section{Usage}

\menhir is invoked as follows:
\begin{quote}
\cmenhir \nt{option} \ldots \nt{option} \nt{filename} \ldots \nt{filename}
\end{quote}
Each of the file names must end with \texttt{.mly} and denotes a partial
grammar specification. These partial grammar specifications are joined
(\sref{sec:split}) to form a single, self-contained grammar specification,
which is then processed. A number of optional command line switches allow
controlling many aspects of the process.

\docswitch{\obase \nt{basename}} This switch controls the base name
of the \ml and \mli files that are produced. That is, the tool will produce
files named \nt{basename}\texttt{.ml} and \nt{basename}\texttt{.mli}. Note
that \nt{basename} can contain occurrences of the \texttt{/} character, so it
really specifies a path and a base name. When only one \nt{filename} is
provided on the command line, the default \nt{basename} is obtained by
depriving \nt{filename} of its final \texttt{.mly} suffix. When multiple file
names are provided on the command line, no default base name exists, so that
the \obase switch \emph{must} be used.

\docswitch{\ocomment} This switch causes a few comments to be inserted into the
\ocaml code that is written to the \ml file.

94 95
\docswitch{\ocoq} This switch causes \menhir to produce Coq code. See \sref{sec:coq}.

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
\docswitch{\ocoqnoactions} (Used in conjunction with \ocoq.) This switch
causes the semantic actions present in the \texttt{.vy} file to be ignored and
replaced with \verb+tt+, the unique inhabitant of Coq's \verb+unit+ type. This
feature can be used to test the Coq back-end with a standard grammar, i.e., a
grammar that contains \ocaml semantic actions. Just rename the file from
\texttt{.mly} to \texttt{.vy} and set this switch.

\docswitch{\ocoqnocomplete} (Used in conjunction with \ocoq.) This switch
disables the generation of the proof of completeness of the parser
(\sref{sec:coq}). This can be necessary because the proof of completeness is
possible only if the grammar has no conflict (not even a benign one, in the
sense of \sref{sec:conflicts:benign}). This can be desirable also because, for
a complex grammar, completeness may require a heavy certificate and its
validation by Coq may take time.

111 112 113
\docswitch{\odepend} This switch causes \menhir to generate dependency information
for use in conjunction with \make. When invoked in this mode, \menhir does not
generate a parser. Instead, it examines the grammar specification and prints a
114
list of prerequisites for the targets \nt{basename}\texttt{.cm[iox]},
115 116 117 118 119 120
\nt{basename}\texttt{.ml}, and \nt{basename}\texttt{.mli}. This list is intended
to be textually included within a \Makefile. It is important to note that
\nt{basename}\texttt{.ml} and \nt{basename}\texttt{.mli} can have
\texttt{.cm[iox]} prerequisites. This is because, when the \oinfer switch
is used, \menhir infers types by invoking \ocamlc, and \ocamlc itself requires
the \ocaml modules that the grammar specification depends upon to have been
121 122 123
compiled first.
% The file \distrib{demos/obsolete/Makefile.shared} exploits the \odepend switch.
An end user who uses \ocamlbuild does not need this switch.
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

When in \odepend mode, \menhir computes dependencies by invoking \ocamldep.
The command that is used to run \ocamldep is controlled by the \oocamldep
switch.

\docswitch{\odump} This switch causes a description of the automaton
to be written to the file \nt{basename}\automaton.

\docswitch{\oexplain} This switch causes conflict explanations to be
written  to the file \nt{basename}\conflicts. See also \sref{sec:conflicts}.

\docswitch{\oexternaltokens \nt{T}} This switch causes the definition of
the \token type to be omitted in \nt{basename}\texttt{.ml} and
\nt{basename}\texttt{.mli}. Instead, the generated parser relies on
the type $T$\texttt{.}\token, where $T$ is an \ocaml module name. It is up to
the user to define module $T$ and to make sure that it exports a suitable
\token type. Module $T$ can be hand-written. It can also be automatically generated
out of a grammar specification using the \oonlytokens switch.

143
\docswitch{\ofixedexc} This switch causes the exception \texttt{Error} to be
144 145 146 147
internally defined as a synonym for \texttt{Parsing.Parse\_error}. This means
that an exception handler that catches \texttt{Parsing.Parse\_error} will also
catch the generated parser's \texttt{Error}. This helps increase Menhir's
compatibility with \ocamlyacc. There is otherwise no reason to use this switch.
148

149 150 151 152 153 154
\docswitch{\ograph} This switch causes a description of the grammar's
dependency graph to be written to the file \nt{basename}\dott. The graph's
vertices are the grammar's nonterminal symbols. There is a directed edge from
vertex $A$ to vertex $B$ if the definition of $A$ refers to $B$. The file is
in a format that is suitable for processing by the \emph{graphviz} toolkit.

155 156 157 158 159 160 161
\docswitch{\oignoreone \nt{symbol}} This switch suppresses the warning that
is normally emitted when \menhir finds that the terminal symbol \nt{symbol} is
unused.

\docswitch{\oignoreall} This switch suppresses all of the warnings that are
normally emitted when \menhir finds that some terminal symbols are unused.

162 163 164 165 166 167 168 169
\docswitch{\oinfer} This switch causes the semantic actions to be checked for
type consistency \emph{before} the parser is generated. This is done by
invoking the \ocaml compiler. Use of \oinfer is \textbf{strongly recommended},
because it helps obtain consistent, well-located type error messages,
especially when advanced features such as \menhir's standard library or
\dinline keyword are exploited. One downside of \oinfer is that the \ocaml
compiler usually needs to consult a few \texttt{.cm[iox]} files. This means
that these files must have been created first, requiring \Makefile changes and
170
use of the \odepend switch. The file \distrib{demos/obsolete/Makefile.shared} suggests
171 172
how to deal with this difficulty. A better option is to avoid \make altogether
and use \ocamlbuild, which has built-in knowledge of \menhir. Using
173
\ocamlbuild is \textbf{strongly recommended}!
174 175 176 177 178

% There is a slight catch with \oinfer. The types inferred by \ocamlc are valid
% in the toplevel context, but can change meaning when inserted into a local
% context.

179 180 181 182 183 184
\docswitch{\oinspection} This switch requires \otable. It causes \menhir to generate
not only the monolithic and incremental APIs (\sref{sec:monolithic},
\sref{sec:incremental}), but also the inspection API (\sref{sec:inspection}).
Activating this switch causes a few more tables to be produced, resulting in
somewhat larger code size.

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
\docswitch{\ointerpret} This switch causes \menhir to act as an interpreter,
rather than as a compiler. No \ocaml code is generated. Instead, \menhir
reads sentences off the standard input channel, parses them, and displays
outcomes. For more information, see \sref{sec:interpret}.

\docswitch{\ointerpretshowcst} This switch, used in conjunction with \ointerpret,
causes \menhir to display a concrete syntax tree when a sentence is successfully
parsed. For more information, see \sref{sec:interpret}.

\docswitch{\ologautomaton \nt{level}} When \nt{level} is nonzero, this switch
causes some information about the automaton to be logged to the standard error
channel.

\docswitch{\ologcode \nt{level}} When \nt{level} is nonzero, this switch
causes some information about the generated \ocaml code to be logged to the
standard error channel.

\docswitch{\ologgrammar \nt{level}} When \nt{level} is nonzero, this switch
causes some information about the grammar to be logged to the standard error
channel. When \nt{level} is 2, the \emph{nullable}, \emph{FIRST}, and
\emph{FOLLOW} tables are displayed.

\docswitch{\onoinline} This switch causes all \dinline keywords in the
grammar specification to be ignored. This is especially useful in order
to understand whether these keywords help solve any conflicts.

\docswitch{\onostdlib} This switch causes the standard library \emph{not}
to be implicitly joined with the grammar specifications whose names are
explicitly provided on the command line.

\docswitch{\oocamlc \nt{command}} This switch controls how \ocamlc is
invoked (when \oinfer is used). It allows setting both the name of
the executable and the command line options that are passed to it.

\docswitch{\oocamldep \nt{command}} This switch controls how \ocamldep is
invoked (when \odepend is used). It allows setting both the name of the
executable and the command line options that are passed to it.

\docswitch{\oonlypreprocess} This switch causes the grammar specifications
to be transformed up to the point where the automaton's construction can
begin. The grammar specifications whose names are provided on the command line
are joined (\sref{sec:split}); all parameterized nonterminal symbols are
expanded away (\sref{sec:templates}); type inference is performed, if \oinfer
is enabled; all nonterminal symbols marked \dinline are expanded away
(\sref{sec:inline}). This yields a single, monolithic grammar specification,
which is printed on the standard output channel.

\docswitch{\oonlytokens} This switch causes the \dtoken declarations in
the grammar specification to be translated into a definition of the \token
type, which is written to the files \nt{basename}\texttt{.ml} and
\nt{basename}\texttt{.mli}. No code is generated. This is useful when
a single set of tokens is to be shared between several parsers. The directory
\distrib{demos/calc-two} contains a demo that illustrates the use of this switch.

\docswitch{\orawdepend} This switch is analogous to \odepend, except that
\ocamldep's output is not postprocessed by \menhir; it is echoed without
241 242 243 244 245
change. This switch is not suitable for direct use with \make; it is
intended for use with \omake or \ocamlbuild, which perform their own
postprocessing.
An end user who uses \ocamlbuild does not need to mention this switch:
\ocamlbuild uses it automatically.
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

\docswitch{\ostrict} This switch causes several warnings about the grammar
and about the automaton to be considered errors. This includes warnings about
useless precedence declarations, non-terminal symbols that produce the empty
language, unreachable non-terminal symbols, productions that are never
reduced, conflicts that are not resolved by precedence declarations, and
end-of-stream conflicts.

\docswitch{\osuggestcomp} This switch causes \menhir to print a set of
suggested compilation flags, and exit. These flags are intended to be passed
to the \ocaml compilers (\ocamlc or \ocamlopt) when compiling and linking the
parser generated by \menhir. What are these flags? In the absence of the
\otable switch, they are empty. When \otable is set, these flags ensure that
\menhirlib is visible to the \ocaml compiler. If the support library
\menhirlib was installed via \ocamlfind, a \texttt{-package} directive is
261 262 263
issued; otherwise, a \texttt{-I} directive is used.
% The file \distrib{demos/obsolete/Makefile.shared} shows how to exploit
% the \texttt{--suggest-*} switches.
264 265 266 267 268 269 270

\docswitch{\osuggestlinkb} This switch causes \menhir to print a set of
suggested link flags, and exit. These flags are intended to be passed to
\texttt{ocamlc} when producing a bytecode executable. What are these flags? In
the absence of the \otable switch, they are empty. When \otable is set, these
flags ensure that \menhirlib is linked in. If the support library \menhirlib
was installed via \ocamlfind, a \texttt{-linkpkg} directive is issued;
271 272 273
otherwise, the object file \texttt{menhirLib.cmo} is named.
% The file \distrib{demos/obsolete/Makefile.shared} shows how to exploit
% the \texttt{--suggest-*} switches.
274 275 276 277 278 279 280

\docswitch{\osuggestlinko} This switch causes \menhir to print a set of
suggested link flags, and exit. These flags are intended to be passed to
\texttt{ocamlopt} when producing a native code executable. What are these
flags? In the absence of the \otable switch, they are empty. When \otable is
set, these flags ensure that \menhirlib is linked in. If the support library
\menhirlib was installed via \ocamlfind, a \texttt{-linkpkg} directive is
281 282 283
issued; otherwise, the object file \texttt{menhirLib.cmx} is named.
% The file \distrib{demos/obsolete/Makefile.shared} shows how to exploit
% the \texttt{--suggest-*} switches.
284 285 286 287 288 289 290 291

\docswitch{\ostdlib \nt{directory}} This switch controls the directory
where the standard library is found. It allows overriding the default
directory that is set at installation time. The trailing \texttt{/} character
is optional.

\docswitch{\otable} This switch causes \menhir to use its table-based
back-end, as opposed to its (default) code-based back-end. When \otable is
POTTIER Francois's avatar
POTTIER Francois committed
292 293
used, \menhir produces significantly more compact and somewhat slower parsers.
See \sref{sec:qa} for a speed comparison.
294 295 296 297 298 299 300 301 302 303 304 305

The table-based back-end produces rather compact tables, which are analogous
to those produced by \yacc, \bison, or \ocamlyacc. These tables are not quite
stand-alone: they are exploited by an interpreter, which is shipped as part of
the support library \menhirlib. For this reason, when \otable is used,
\menhirlib must be made visible to the \ocaml compilers, and must be linked
into your executable program. The \texttt{--suggest-*} switches, described
above, help do this.

The code-based back-end compiles the LR automaton directly into a nest of
mutually recursive \ocaml functions. In that case, \menhirlib is not required.

306 307 308
The incremental API (\sref{sec:incremental}) and the inspection API
(\sref{sec:inspection}) are made available only by the table-based back-end.

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
\docswitch{\otimings} This switch causes internal timing information to
be sent to the standard error channel.

\docswitch{\otrace} This switch causes tracing code to be inserted into
the generated parser, so that, when the parser is run, its actions are
logged to the standard error channel. This is analogous to \texttt{ocamlrun}'s
\texttt{p=1} parameter, except this switch must be enabled at compile time:
one cannot selectively enable or disable tracing at runtime.

\docswitch{\oversion} This switch causes \menhir to print its own version
number and exit.

% ---------------------------------------------------------------------------------------------------------------------

\section{Lexical conventions}

The semicolon character (\kw{;}) is treated as insignificant, just like white
space. Thus, rules and producers (for instance) can be separated with
327
semicolons if it is thought that this improves readability. Semicolons can be
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
omitted otherwise.

Identifiers (\nt{id}) coincide with \ocaml identifiers, except they are not
allowed to contain the quote (\kw{'}) character. Following
\ocaml, identifiers that begin with a lowercase letter
(\nt{lid}) or with an uppercase letter (\nt{uid}) are distinguished.

Comments are C-style (surrounded with \kw{/*} and \kw{*/}, cannot be nested),
C++-style (announced by \kw{/$\!$/} and extending until the end of the line), or
\ocaml-style (surrounded with \kw{(*} and \kw{*)}, can be nested). Of course,
inside \ocaml code, only \ocaml-style comments are allowed.

\ocaml type expressions are surrounded with \kangle{and}. Within such expressions,
all references to type constructors (other than the built-in \textit{list}, \textit{option}, etc.)
must be fully qualified.

% ---------------------------------------------------------------------------------------------------------------------

\section{Syntax of grammar specifications}

\begin{figure}
\begin{center}
\begin{tabular}{r@{}c@{}l}

\nt{specification} \is
   \sepspacelist{\nt{declaration}}
   \percentpercent
   \sepspacelist{\nt{rule}}
356
   \optional{\percentpercent \textit{OCaml code}} \\
357 358

\nt{declaration} \is
359
   \dheader{\textit{OCaml code}} \\
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
&& \dparameter \ocamlparam \\
&& \dtoken \optional{\ocamltype} \sepspacelist{\nt{uid}} \\
&& \dnonassoc \sepspacelist{\nt{uid}} \\
&& \dleft \sepspacelist{\nt{uid}} \\
&& \dright \sepspacelist{\nt{uid}} \\
&& \dtype \ocamltype \sepspacelist{\nt{lid}} \\
&& \dstart \optional{\ocamltype} \sepspacelist{\nt{lid}} \\

\nt{rule} \is
   \optional{\dpublic} \optional{\dinline}
   \nt{lid}
   \optional{\dlpar\sepcommalist{\nt{id}}\drpar}
   \deuxpoints
   \optional{\barre} \seplist{\ \barre}{\nt{group}} \\

\nt{group} \is
   \seplist{\ \barre}{\nt{production}}
   \daction
   \optional {\dprec \nt{id}} \\

\nt{production} \is
   \sepspacelist{\nt{producer}} \optional {\dprec \nt{id}} \\

\nt{producer} \is
   \optional{\nt{lid} \dequal} \nt{actual} \\

\nt{actual} \is
387 388
   \nt{id} \optional{\dlpar\sepcommalist{\nt{actual}}\drpar} \\
&& \nt{actual} \optional{\dquestion \barre \dplus \barre \dstar} \\
389
&& \seplist{\ \barre}{\nt{group}} % not really allowed everywhere
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

\end{tabular}
\end{center}
\caption{Syntax of grammar specifications}
\label{fig:syntax}
\end{figure}

The syntax of grammar specifications appears in \fref{fig:syntax}. (For
compatibility with \ocamlyacc, some specifications that do not fully adhere to
this syntax are also accepted.)

\subsection{Declarations}

A specification file begins with a sequence of declarations, ended by a
mandatory \percentpercent keyword.

\subsubsection{Headers}

A header is a piece of \ocaml code, surrounded with \dheader{and}. It is
copied verbatim at the beginning of the \ml file. It typically contains \ocaml
\kw{open} directives and function definitions for use by the semantic
actions. If a single grammar specification file contains multiple headers,
their order is preserved. However, when two headers originate in distinct
grammar specification files, the order in which they are copied to the \ml
file is unspecified.

\subsubsection{Parameters}
POTTIER Francois's avatar
POTTIER Francois committed
417
\label{sec:parameter}
418 419 420 421 422 423

A declaration of the form:
\begin{quote}
\dparameter \ocamlparam
\end{quote}
causes the entire parser to become parameterized over the \ocaml module
424 425 426 427
\nt{uid}, that is, to become an \ocaml functor. The directory
\distrib{demos/calc-param} contains a demo that illustrates the use of this switch.

If a single specification file
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
contains multiple \dparameter declarations, their order is preserved, so that
the module name \nt{uid} introduced by one declaration is effectively in scope
in the declarations that follow. When two \dparameter declarations originate
in distinct grammar specification files, the order in which they are processed
is unspecified. Last, \dparameter declarations take effect before \dheader{$\ldots$},
\dtoken, \dtype, or \dstart declarations are considered, so that the module name
\nt{uid} introduced by a \dparameter declaration is effectively in scope in
\emph{all} \dheader{$\ldots$}, \dtoken, \dtype, or \dstart declarations,
regardless of whether they precede or follow the \dparameter declaration.
This means, in particular, that the side effects of an \ocaml header are
observed only when the functor is applied, not when it is defined.

\subsubsection{Tokens}

A declaration of the form:
\begin{quote}
\dtoken \optional{\ocamltype} $\nt{uid}_1, \ldots, \nt{uid}_n$
\end{quote}
defines the identifiers $\nt{uid}_1, \ldots, \nt{uid}_n$ as tokens, that is,
as terminal symbols in the grammar specification and as data constructors in
the \textit{token} type. If an \ocaml type $t$ is present, then these tokens
are considered to carry a semantic value of type $t$, otherwise they are
considered to carry no semantic value.

\subsubsection{Priority and associativity}
\label{sec:assoc}

A declaration of one of the following forms:
\begin{quote}
\dnonassoc $\nt{uid}_1 \ldots \nt{uid}_n$ \\
\dleft $\nt{uid}_1 \ldots \nt{uid}_n$ \\
\dright $\nt{uid}_1 \ldots \nt{uid}_n$
\end{quote}
attributes both a \emph{priority level} and an \emph{associativity status} to
the symbols $\nt{uid}_1, \ldots, \nt{uid}_n$. The priority level assigned to
$\nt{uid}_1, \ldots, \nt{uid}_n$ is not defined explicitly: instead, it is
defined to be higher than the priority level assigned by the previous
\dnonassoc, \dleft, or \dright declaration, and lower than that assigned by the next
\dnonassoc, \dleft, or \dright declaration. The symbols $\nt{uid}_1, \ldots, \nt{uid}_n$
can be tokens (defined elsewhere by a \dtoken declaration) or dummies (not
defined anywhere). Both can be referred to as part of \dprec annotations.
Associativity status and priority levels allow shift/reduce conflicts to be
silently resolved (\sref{sec:conflicts}).

\subsubsection{Types}
POTTIER Francois's avatar
POTTIER Francois committed
473
\label{sec:type}
474 475 476 477 478 479 480 481 482 483 484

A declaration of the form:
\begin{quote}
\dtype \ocamltype $\nt{lid}_1 \ldots \nt{lid}_n$
\end{quote}
assigns an \ocaml type to each of the nonterminal symbols $\nt{lid}_1, \ldots, \nt{lid}_n$.
For start symbols, providing an \ocaml type is mandatory, but is usually done as part of the
\dstart declaration. For other symbols, it is optional. Providing type information can improve
the quality of \ocaml's type error messages.

\subsubsection{Start symbols}
POTTIER Francois's avatar
POTTIER Francois committed
485
\label{sec:start}
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500

A declaration of the form:
\begin{quote}
\dstart \optional{\ocamltype} $\nt{lid}_1 \ldots \nt{lid}_n$
\end{quote}
declares the nonterminal symbols $\nt{lid}_1, \ldots, \nt{lid}_n$ to be
start symbols. Each such symbol must be assigned an \ocaml type either as
part of the \dstart declaration or via separate \dtype declarations. Each
of $\nt{lid}_1, \ldots, \nt{lid}_n$ becomes the name of a function whose
signature is published in the \mli file and that can be used to invoke
the parser.

\subsection{Rules}

Following the mandatory \percentpercent keyword, a sequence of rules is
501 502 503 504 505 506 507 508
expected. Each rule defines a nonterminal symbol~\nt{id}.
%
(It is recommended that the name of a nonterminal symbol begin with a lowercase
letter, so it falls in the category \nt{lid}. This is in fact mandatory for the
start symbols.)
In its simplest
form, a rule begins with the nonterminal symbol \nt{id},
followed by a colon character (\deuxpoints),
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
and continues with a sequence of production groups
(\sref{sec:productiongroups}). Each production group is preceded with a
vertical bar character (\barre); the very first bar is optional. The meaning
of the bar is choice: the nonterminal symbol \nt{id} develops to either of the
production groups. We defer explanations of the keyword \dpublic
(\sref{sec:split}), of the keyword \dinline (\sref{sec:inline}), and of the
optional formal parameters $\dlpar\sepcommalist{\nt{id}}\drpar$
(\sref{sec:templates}).

\subsubsection{Production groups}
\label{sec:productiongroups}

In its simplest form, a production group consists of a single production (\sref{sec:productions}),
followed by an \ocaml semantic action (\sref{sec:actions}) and an optional
\dprec annotation (\sref{sec:prec}). A production specifies a sequence of terminal and
nonterminal symbols that should be recognized, and optionally binds
identifiers to their semantic values.

\paragraph{Semantic actions}
\label{sec:actions}

A semantic action is a piece of \ocaml code that is executed in order to
assign a semantic value to the nonterminal symbol with which this production
group is associated. A semantic action can refer to the (already computed)
semantic values of the terminal or nonterminal symbols that appear in the
534 535 536 537
production via the semantic value identifiers bound by the production.

For compatibility with \ocamlyacc, semantic actions can also refer to
unnamed semantic values via positional keywords of the form
Yann Régis-Gianas's avatar
Yann Régis-Gianas committed
538 539
\kw{\$1}, \kw{\$2}, etc.\ This style is discouraged. Furthermore, as
a positional keyword of the form \kw{\$i} is internally rewritten as
540
\nt{\_i}, the user should not use identifiers of the form \nt{\_i}.
541 542 543 544

\paragraph{\dprec annotations}
\label{sec:prec}

545 546
An annotation of the form \dprec \nt{id} indicates that the precedence level
of the production group is the level assigned to the symbol \nt{id} via a
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
previous \dnonassoc, \dleft, or \dright declaration (\sref{sec:assoc}). In the
absence of a
\dprec annotation, the precedence level assigned to each production is the
level assigned to the rightmost terminal symbol that appears in it. It is
undefined if the rightmost terminal symbol has an undefined precedence level
or if the production mentions no terminal symbols at all. The precedence level
assigned to a production is used when resolving shift/reduce conflicts
(\sref{sec:conflicts}).

\paragraph{Multiple productions in a group}

If multiple productions are present in a single group, then the semantic
action and precedence annotation are shared between them. This short-hand
effectively allows several productions to share a semantic action and
precedence annotation without requiring textual duplication. It is legal only
when every production binds exactly the same set of semantic value identifiers
and when no positional semantic value keywords (\kw{\$1}, etc.) are used.

\subsubsection{Productions}
\label{sec:productions}

A production is a sequence of producers (\sref{sec:producers}), optionally
followed by a \dprec annotation (\sref{sec:prec}). If a precedence annotation
is present, it applies to this production alone, not to other productions in
the production group. It is illegal for a production and its production group
to both carry \dprec annotations.

\subsubsection{Producers}
\label{sec:producers}

A producer is an actual (\sref{sec:actual}), optionally preceded with a
binding of a semantic value identifier, of the form \nt{lid} \dequal. The
actual specifies which construction should be recognized and how a semantic
value should be computed for that construction. The identifier \nt{lid}, if
present, becomes bound to that semantic value in the semantic action that
follows. Otherwise, the semantic value can be referred to via a positional
keyword (\kw{\$1}, etc.).

\subsubsection{Actuals}
\label{sec:actual}

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
In its simplest form, an actual is just a terminal or nonterminal symbol
$\nt{id}$. If it is a parameterized non-terminal symbol (see
\sref{sec:templates}), then it should be applied:
$\nt{id}\dlpar\sepcommalist{\nt{actual}}\drpar$.

An actual may be followed with a modifier (\dquestion, \dplus, or
\dstar). This is explained further on (see \sref{sec:templates} and
\fref{fig:sugar}).

An actual may also be an ``anonymous rule''. In that case, one writes
just the rule's right-hand side, which takes the form $\seplist{\ \barre\
}{\nt{group}}$.
(This form is allowed only as an argument in an application.)
This form is expanded on the fly to a definition of a fresh non-terminal
symbol, which is declared \dinline.
For instance, providing an anonymous rule as an argument to \nt{list}:
\begin{quote}
\begin{tabular}{l}
\nt{list} \dlpar \basic{e} = \nt{expression}; \basic{SEMICOLON} \dpaction{\basic{e}} \drpar
\end{tabular}
\end{quote}
is equivalent to writing this:
\begin{quote}
\begin{tabular}{l}
\nt{list} \dlpar \nt{expression\_SEMICOLON} \drpar
\end{tabular}
\end{quote}
where the non-terminal symbol \nt{expression\_SEMICOLON} is chosen fresh and is defined as follows:
\begin{quote}
\begin{tabular}{l}
\dinline \nt{expression\_SEMICOLON}:
\newprod \basic{e} = \nt{expression}; \basic{SEMICOLON} \dpaction{\basic{e}}
\end{tabular}
\end{quote}
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944

\section{Advanced features}

\subsection{Splitting specifications over multiple files}
\label{sec:split}

\paragraph{Modules}

Grammar specifications can be split over multiple files. When \menhir is
invoked with multiple argument file names, it considers each of these files as
a \emph{partial} grammar specification, and \emph{joins} these partial
specifications in order to obtain a single, complete specification.

This feature is intended to promote a form a modularity. It is hoped that, by
splitting large grammar specifications into several ``modules'', they can be
made more manageable. It is also hoped that this mechanism, in conjunction
with parameterization (\sref{sec:templates}), will promote sharing and reuse.
It should be noted, however, that this is only a weak form of
modularity. Indeed, partial specifications cannot be independently processed
(say, checked for conflicts).  It is necessary to first join them, so as to
form a complete grammar specification, before any kind of grammar analysis can
be done.

This mechanism is, in fact, how \menhir's standard library (\sref{sec:library})
is made available: even though its name does not appear on the command line,
it is automatically joined with the user's explicitly-provided grammar
specifications, making the standard library's definitions globally visible.

A partial grammar specification, or module, contains declarations and rules,
just like a complete one: there is no visible difference. Of course, it can
consist of only declarations, or only rules, if the user so chooses. (Don't
forget the mandatory \percentpercent keyword that separates declarations and
rules. It must be present, even if one of the two sections is empty.)

\paragraph{Private and public nonterminal symbols}

It should be noted that joining is \emph{not} a purely textual process. If two
modules happen to define a nonterminal symbol by the same name, then it is
considered, by default, that this is an accidental name clash. In that case,
each of the two nonterminal symbols is silently renamed so as to avoid the
clash. In other words, by default, a nonterminal symbol defined in module $A$
is considered \emph{private}, and cannot be defined again, or referred to, in
module $B$.

Naturally, it is sometimes desirable to define a nonterminal symbol $N$ in
module $A$ and to refer to it in module $B$. This is permitted if $N$ is
public, that is, if either its definition carries the keyword \dpublic or
$N$ is declared to be a start symbol. A public nonterminal symbol is never
renamed, so it can be referred to by modules other than its defining module.

In fact, it is even permitted to split the definition of a public nonterminal
symbol over multiple modules. That is, a public nonterminal symbol $N$ can
have multiple definitions in distinct modules. When the modules are joined,
the definitions are joined as well, using the choice (\barre) operator. This
feature allows splitting a grammar specification in a manner that is
independent of the grammar's structure. For instance, in the grammar of a
programming language, the definition of the nonterminal symbol \nt{expression}
could be split into multiple modules, where one module groups the expression
forms that have to do with arithmetic, one module groups those that concern
function definitions and function calls, one module groups those that concern
object definitions and method calls, and so on.

\paragraph{Tokens aside}

Another use of modularity consists in placing all \dtoken declarations in one
module, and the actual grammar specification in another module. The module
that contains the token definitions can then be shared, making it easier to
define multiple parsers that accept the same type of tokens. (On this topic,
see \distrib{demos/calc-two}.)

\subsection{Parameterizing rules}
\label{sec:templates}

A rule (that is, the definition of a nonterminal symbol) can be parameterized
over an arbitrary number of symbols, which are referred to as formal
parameters.

\paragraph{Example}

For instance, here is the definition of the parameterized
nonterminal symbol \nt{option}, taken from the standard library (\sref{sec:library}):
%
\begin{quote}
\begin{tabular}{l}
\dpublic \basic{option}(\basic{X}):
\newprod \dpaction{\basic{None}}
\newprod \basic{x} = \basic{X} \dpaction{\basic{Some} \basic{x}}
\end{tabular}
\end{quote}
%
This definition states that \nt{option}(\basic{X}) expands to either the empty
string, producing the semantic value \basic{None}, or to the string \basic{X},
producing the semantic value {\basic{Some}~\basic{x}}, where \basic{x} is the
semantic value of \basic{X}. In this definition, the symbol \basic{X} is
abstract: it stands for an arbitrary terminal or nonterminal symbol. The
definition is made public, so \nt{option} can be referred to within client
modules.

A client that wishes to use \nt{option} simply refers to it, together with
an actual parameter -- a symbol that is intended to replace \basic{X}. For
instance, here is how one might define a sequence of declarations, preceded
with optional commas:
%
\begin{quote}
\begin{tabular}{l}
\nt{declarations}:
\newprod \dpaction{[]}
\newprod \basic{ds} = \nt{declarations}; \nt{option}(\basic{COMMA}); \basic{d} = \nt{declaration}
         \dpaction{ \basic{d} :: \basic{ds} }
\end{tabular}
\end{quote}
%
This definition states that \nt{declarations} expands either to the empty
string or to \nt{declarations} followed by an optional comma followed by
\nt{declaration}. (Here, \basic{COMMA} is presumably a terminal symbol.)
When this rule is encountered, the definition of \nt{option} is instantiated:
that is, a copy of the definition, where \basic{COMMA} replaces \basic{X},
is produced. Things behave exactly as if one had written:

\begin{quote}
\begin{tabular}{l}
\basic{optional\_comma}:
\newprod \dpaction{\basic{None}}
\newprod \basic{x} = \basic{COMMA} \dpaction{\basic{Some} \basic{x}} \\

\nt{declarations}:
\newprod \dpaction{[]}
\newprod \basic{ds} = \nt{declarations}; \nt{optional\_comma}; \basic{d} = \nt{declaration}
         \dpaction{ \basic{d} :: \basic{ds} }
\end{tabular}
\end{quote}
%
Note that, even though \basic{COMMA} presumably has been declared as a token
with no semantic value, writing \basic{x}~=~\basic{COMMA} is legal, and binds
\basic{x} to the unit value. This design choice ensures that the definition
of \nt{option} makes sense regardless of the nature of \basic{X}: that is, \basic{X}
can be instantiated with a terminal symbol, with or without a semantic value,
or with a nonterminal symbol.

\paragraph{Parameterization in general}

In general, the definition of a nonterminal symbol $N$ can be
parameterized with an arbitrary number of formal parameters. When
$N$ is referred to within a production, it must be applied
to the same number of actuals. In general, an actual is:
%
\begin{itemize}
\item either a single symbol, which can be a terminal symbol, a nonterminal symbol, or a formal parameter;
\item or an application of such a symbol to a number of actuals.
\end{itemize}

For instance, here is a rule whose single production consists of a single
producer, which contains several, nested actuals. (This example is discussed
again in \sref{sec:library}.)
%
\begin{quote}
\begin{tabular}{l}
\nt{plist}(\nt{X}):
\newprod
  \basic{xs} = \nt{loption}(%
                     \nt{delimited}(%
                       \basic{LPAREN},
                       \nt{separated\_nonempty\_list}(\basic{COMMA}, \basic{X}),
                       \basic{RPAREN}%
                     )%
                   )
    \dpaction{\basic{xs}}
\end{tabular}
\end{quote}

\begin{figure}
\begin{center}
\begin{tabular}{r@{\hskip 2mm}c@{\hskip 2mm}l}
\nt{actual}\dquestion & is syntactic sugar for & \nt{option}(\nt{actual}) \\
\nt{actual}\dplus & is syntactic sugar for & \nt{nonempty\_list}(\nt{actual}) \\
\nt{actual}\dstar & is syntactic sugar for & \nt{list}(\nt{actual})
\end{tabular}
\end{center}
\caption{Syntactic sugar for simulating regular expressions}
\label{fig:sugar}
\end{figure}
%
Applications of the parameterized nonterminal symbols \nt{option},
\nt{nonempty\_list}, and \nt{list}, which are defined in
the standard library (\sref{sec:library}), can be written using
a familiar, regular-expression like syntax (\fref{fig:sugar}).

\paragraph{Higher-order parameters}

A formal parameter can itself expect parameters. For instance, here is a rule
that defines the syntax of procedures in an imaginary programming language:
%
\begin{quote}
\begin{tabular}{l}
\nt{procedure}(\nt{list}):
\newprod
\basic{PROCEDURE} \basic{ID} \nt{list}(\nt{formal}) \nt{SEMICOLON} \nt{block} \nt{SEMICOLON} \dpaction{$\ldots$}
\end{tabular}
\end{quote}
%
This rule states that the token \basic{ID}, which represents the name of the
procedure, should be followed with a list of formal parameters. (The
definitions of the nonterminal symbols \nt{formal} and \nt{block} are not
shown.) However, because \nt{list} is a formal parameter, as opposed to a
concrete nonterminal symbol defined elsewhere, this definition does not
specify how the list is laid out: which token, if any, is used to separate, or
terminate, list elements? is the list allowed to be empty? and so on. A more
concrete notion of procedure is obtained by instantiating the formal parameter
\nt{list}: for instance, \nt{procedure}(\nt{plist}), where \nt{plist} is the
parameterized nonterminal symbol defined earlier, is a valid application.

\paragraph{Consistency} Definitions and uses of parameterized nonterminal
symbols are checked for consistency before they are expanded away. In short,
it is checked that, wherever a nonterminal symbol is used, it is supplied with
actual arguments in appropriate number and of appropriate nature. This
guarantees that expansion of parameterized definitions terminates and produces
a well-formed grammar as its outcome.

\subsection{Inlining}
\label{sec:inline}

It is well-known that the following grammar of arithmetic expressions does not
work as expected: that is, in spite of the priority declarations, it has
shift/reduce conflicts.
%
\begin{quote}
\begin{tabular}{l}
\dtoken \kangle{\basic{int}} \basic{INT} \\
\dtoken \basic{PLUS} \basic{TIMES} \\
\dleft \basic{PLUS} \\
\dleft \basic{TIMES} \\ \\
\percentpercent \\ \\
\nt{expression}:
\newprod \basic{i} = \basic{INT}
         \dpaction{\basic{i}}
\newprod \basic{e} = \nt{expression}; \basic{o} = \nt{op}; \basic{f} = \nt{expression}
         \dpaction{\basic{o} \basic{e} \basic{f}} \\
\nt{op}:
\newprod \basic{PLUS} \dpaction{( + )}
\newprod \basic{TIMES} \dpaction{( * )}
\end{tabular}
\end{quote}
%
The trouble is, the precedence level of the production \nt{expression}
$\rightarrow$ \nt{expression} \nt{op} \nt{expression} is undefined, and
there is no sensible way of defining it via a \dprec declaration, since
the desired level really depends upon the symbol that was recognized by
\nt{op}: was it \basic{PLUS} or \basic{TIMES}?

The standard workaround is to abandon the definition of \nt{op} as a
separate nonterminal symbol, and to inline its definition into the
definition of \nt{expression}, like this:
%
\begin{quote}
\begin{tabular}{l}
\nt{expression}:
\newprod \basic{i} = \basic{INT}
         \dpaction{\basic{i}}
\newprod \basic{e} = \nt{expression}; \basic{PLUS}; \basic{f} = \nt{expression}
         \dpaction{\basic{e} + \basic{f}}
\newprod \basic{e} = \nt{expression}; \basic{TIMES}; \basic{f} = \nt{expression}
         \dpaction{\basic{e} * \basic{f}}
\end{tabular}
\end{quote}
%

This avoids the shift/reduce conflict, but gives up some of the original
specification's structure, which, in realistic situations, can be damageable.
Fortunately, \menhir offers a way of avoiding the conflict without manually
transforming the grammar, by declaring that the nonterminal symbol \nt{op}
should be inlined:
%
\begin{quote}
\begin{tabular}{l}
\nt{expression}:
\newprod \basic{i} = \basic{INT}
         \dpaction{\basic{i}}
\newprod \basic{e} = \nt{expression}; \basic{o} = \nt{op}; \basic{f} = \nt{expression}
         \dpaction{\basic{o} \basic{e} \basic{f}} \\
\dinline \nt{op}:
\newprod \basic{PLUS} \dpaction{( + )}
\newprod \basic{TIMES} \dpaction{( * )}
\end{tabular}
\end{quote}
%
The \dinline keyword causes all references to \nt{op} to be replaced with its
definition. In this example, the definition of \nt{op} involves two
productions, one that develops to \basic{PLUS} and one that expands to
\basic{TIMES}, so every production that refers to \nt{op} is effectively
turned into two productions, one that refers to \basic{PLUS} and one that refers to
\basic{TIMES}. After inlining, \nt{op} disappears and \nt{expression} has three
productions: that is, the result of inlining is exactly the manual workaround
shown above.

In some situations, inlining can also help recover a slight efficiency margin.
For instance, the definition:
%
\begin{quote}
\begin{tabular}{l}
\dinline \nt{plist}(\nt{X}):
\newprod
  \basic{xs} = \nt{loption}(%
                     \nt{delimited}(%
                       \basic{LPAREN},
                       \nt{separated\_nonempty\_list}(\basic{COMMA}, \basic{X}),
                       \basic{RPAREN}%
                     )%
                   )
    \dpaction{\basic{xs}}
\end{tabular}
\end{quote}
%
effectively makes \nt{plist}(\nt{X}) an alias for the right-hand side
\nt{loption}($\ldots$). Without the \dinline keyword, the language
recognized by the grammar would be the same, but the LR automaton
would probably have one more state and would perform one more
reduction at run time.

\subsection{The standard library}
\label{sec:library}

\begin{figure}
\begin{center}
945
\begin{tabular}{lp{51mm}l@{}l}
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
Name & Recognizes & Produces & Comment \\
\hline\\
\nt{option}(\nt{X})  & $\epsilon$ \barre \nt{X} & $\alpha$ \basic{option}, if \nt{X} : $\alpha$ \\
\nt{ioption}(\nt{X}) & $\epsilon$ \barre \nt{X} & $\alpha$ \basic{option}, if \nt{X} : $\alpha$ & (inlined) \\
\nt{boption}(\nt{X}) & $\epsilon$ \barre \nt{X} & \basic{bool} \\
\nt{loption}(\nt{X}) & $\epsilon$ \barre \nt{X} & $\alpha$ \basic{list}, if \nt{X} : $\alpha$ \nt{list} \\
\\
\nt{pair}(\nt{X}, \nt{Y}) & \nt{X} \nt{Y} & $\alpha\times\beta$, if \nt{X} : $\alpha$ and \nt{Y} : $\beta$ \\
\nt{separated\_pair}(\nt{X}, \nt{sep}, \nt{Y}) & \nt{X} \nt{sep} \nt{Y} & $\alpha\times\beta$,
                                                                 if \nt{X} : $\alpha$ and \nt{Y} : $\beta$ \\
\nt{preceded}(\nt{opening}, \nt{X}) & \nt{opening} \nt{X} & $\alpha$, if \nt{X} : $\alpha$ \\
\nt{terminated}(\nt{X}, \nt{closing}) & \nt{X} \nt{closing} & $\alpha$, if \nt{X} : $\alpha$ \\
\nt{delimited}(\nt{opening}, \nt{X}, \nt{closing}) & \nt{opening} \nt{X} \nt{closing}
                                                   & $\alpha$, if \nt{X} : $\alpha$ \\
\\
\nt{list}(\nt{X})
  & a possibly empty sequence of \nt{X}'s
  & $\alpha$ \basic{list}, if \nt{X} : $\alpha$ \\
\nt{nonempty\_list}(\nt{X})
  & a nonempty sequence of \nt{X}'s
  & $\alpha$ \basic{list}, if \nt{X} : $\alpha$ \\
\nt{separated\_list}(\nt{sep}, \nt{X})
  & a possibly empty sequence of \nt{X}'s separated with \nt{sep}'s
  & $\alpha$ \basic{list}, if \nt{X} : $\alpha$ \\
\nt{separated\_nonempty\_list}(\nt{sep}, \nt{X})
  & a nonempty sequence of \nt{X}'s separated with \nt{sep}'s
  & $\alpha$ \basic{list}, if \nt{X} : $\alpha$ \\

\end{tabular}
\end{center}
\caption{Summary of the standard library}
\label{fig:standard}
\end{figure}

Once equipped with a rudimentary module system (\sref{sec:split}),
parameterization (\sref{sec:templates}), and inlining (\sref{sec:inline}), it
is straightforward to propose a collection of commonly used definitions, such
as options, sequences, lists, and so on. This \emph{standard library} is
joined, by default, with every grammar specification. A summary of the
nonterminal symbols offered by the standard library appears in
\fref{fig:standard}. See also the short-hands documented in
\fref{fig:sugar}.

By relying on the standard library, a client module can concisely define
more elaborate notions. For instance, the following rule:
%
\begin{quote}
\begin{tabular}{l}
\dinline \nt{plist}(\nt{X}):
\newprod
  \basic{xs} = \nt{loption}(%
                     \nt{delimited}(%
                       \basic{LPAREN},
                       \nt{separated\_nonempty\_list}(\basic{COMMA}, \basic{X}),
                       \basic{RPAREN}%
                     )%
                   )
    \dpaction{\basic{xs}}
\end{tabular}
\end{quote}
%
causes \nt{plist}(\nt{X}) to recognize a list of \nt{X}'s, where the empty
list is represented by the empty string, and a non-empty list is delimited
with parentheses and comma-separated.

% ---------------------------------------------------------------------------------------------------------------------

\section{Conflicts}
\label{sec:conflicts}

When a shift/reduce or reduce/reduce conflict is detected, it is classified as
either benign, if it can be resolved by consulting user-supplied precedence
declarations, or severe, if it cannot. Benign conflicts are not reported.
Severe conflicts are reported and, if the \oexplain switch is on, explained.

\subsection{When is a conflict benign?}
1022
\label{sec:conflicts:benign}
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152

A shift/reduce conflict involves a single token (the one that one might wish
to shift) and one or more productions (those that one might wish to
reduce). When such a conflict is detected, the precedence level
(\sref{sec:assoc}, \sref{sec:prec}) of these entities are looked up and
compared as follows:
\begin{enumerate}
\item if only one production is involved, and if it has higher priority
      than the token, then the conflict is resolved in favor of reduction.
\item if only one production is involved, and if it has the same priority
      as the token, then the associativity status of the token is looked up:
      \begin{enumerate}
      \item if the token was declared nonassociative, then the conflict is
            resolved in favor of neither action, that is, a syntax error
	    will be signaled if this token shows up when this production
	    is about to be reduced;
      \item if the token was declared left-associative, then the conflict
            is resolved in favor of reduction;
      \item if the token was declared right-associative, then the conflict
            is resolved in favor of shifting.
      \end{enumerate}
\item \label{multiway}
      if multiple productions are involved, and if, considered one by one,
      they all cause the conflict to be resolved in the same way (that is,
      either in favor in shifting, or in favor of neither), then the conflict
      is resolved in that way.
\end{enumerate}
In either of these cases, the conflict is considered benign. Otherwise, it is
considered severe. Note that a reduce/reduce conflict is always considered
severe, unless it happens to be subsumed by a benign multi-way shift/reduce
conflict (item~\ref{multiway} above).

\subsection{How are severe conflicts explained?}

When the \odump switch is on, a description of the automaton is written to the
\automaton file. Severe conflicts are shown as part of this description.
Fortunately, there is also a way of understanding conflicts in terms of the
grammar, rather than in terms of the automaton. When the \oexplain switch is
on, a textual explanation is written to the \conflicts file.

\emph{Not all conflicts are explained} in this file: instead, \emph{only one conflict per
automaton state is explained}. This is done partly in the interest of brevity,
but also because Pager's algorithm can create artificial conflicts in a state
that already contains a true LR(1) conflict; thus, one cannot hope in general
to explain all of the conflicts that appear in the automaton. As a result of
this policy, once all conflicts explained in the \conflicts file have been
fixed, one might need to run \menhir again to produce yet more conflict
explanations.

\begin{figure}
\begin{quote}
\begin{tabular}{l}
\dtoken \basic{IF THEN ELSE} \\
\dstart \kangle{\basic{expression}} \nt{expression} \\
\\
\percentpercent \\
\\
\nt{expression}:
\newprod $\ldots$
\newprod \basic{IF b} = \nt{expression} \basic{THEN e} = \nt{expression} \dpaction{$\ldots$}
\newprod \basic{IF b} = \nt{expression} \basic{THEN e} = \nt{expression} \basic{ELSE f} = \nt{expression} \dpaction{$\ldots$}
\newprod $\ldots$
\end{tabular}
\end{quote}
\caption{Basic example of a shift/reduce conflict}
\label{fig:basicshiftreduce}
\end{figure}

\paragraph{How the conflict state is reached}

\fref{fig:basicshiftreduce} shows a grammar specification
with a typical shift/reduce conflict.
%
When this specification is analyzed, the conflict is detected, and an
explanation is written to the \conflicts file. The explanation first indicates
in which state the conflict lies by showing how that state is reached. Here,
it is reached after recognizing the following string of terminal and
nonterminal symbols---the \emph{conflict string}:
%
\begin{quote}
\basic{IF expression THEN IF expression THEN expression}
\end{quote}

Allowing the conflict string to contain both nonterminal and terminal symbols
usually makes it shorter and more readable. If desired, a conflict string
composed purely of terminal symbols could be obtained by replacing each
occurrence of a nonterminal symbol $N$ with an arbitrary $N$-sentence.

The conflict string can be thought of as a path that leads from one of the
automaton's start states to the conflict state.  When multiple such paths
exist, the one that is displayed is chosen shortest.  Nevertheless, it may
sometimes be quite long. In that case, artificially (and temporarily)
declaring some existing nonterminal symbols to be start symbols has the effect
of adding new start states to the automaton and can help produce shorter
conflict strings. Here, \nt{expression} was declared to be a start symbol,
which is why the conflict string is quite short.

In addition to the conflict string, the \conflicts file also states that the
\emph{conflict token} is \basic{ELSE}. That is, when the automaton has recognized
the conflict string and when the lookahead token (the next token on the input
stream) is \basic{ELSE}, a conflict arises. A conflict corresponds to a
choice: the automaton is faced with several possible actions, and does not
know which one should be taken. This indicates that the grammar is not LR(1).
The grammar may or may not be inherently ambiguous.

In our example, the conflict string and the conflict token are enough to
understand why there is a conflict: when two \basic{IF} constructs are nested,
it is ambiguous which of the two constructs the
\basic{ELSE} branch should be associated with. Nevertheless, the \conflicts file
provides further information: it explicitly shows that there exists a
conflict, by proving that two distinct actions are possible. Here, one of
these actions consists in \emph{shifting}, while the other consists in
\emph{reducing}: this is a \emph{shift/reduce} conflict.

A \emph{proof} takes the form of a \emph{partial derivation tree} whose
\emph{fringe} begins with the conflict string, followed by the conflict
token. A derivation tree is a tree whose nodes are labeled with symbols. The
root node carries a start symbol. A node that carries a terminal symbol is
considered a leaf, and has no children. A node that carries a nonterminal
symbol $N$ either is considered a leaf, and has no children; or is not
considered a leaf, and has $n$ children, where $n\geq 0$, labeled
$\nt{x}_1,\ldots,\nt{x}_n$, where $N \rightarrow
\nt{x}_1,\ldots,\nt{x}_n$ is a production. The fringe of a partial
derivation tree is the string of terminal and nonterminal symbols carried by
the tree's leaves. A string of terminal and nonterminal symbols that is the
fringe of some partial derivation tree is a \emph{sentential form}.

\paragraph{Why shifting is legal}

\begin{figure}
1153
\mycommonbaseline
1154
\begin{center}
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
\begin{tikzpicture}[level distance=12mm]
\node { \nt{expression} }
  child { node {\basic{IF}} }
  child { node {\nt{expression}} }
  child { node {\basic{THEN}} }
  child { node {\nt{expression}}
    child { node {\basic{IF}} }
    child { node {\nt{expression}} }
    child { node {\basic{THEN}} }
    child { node {\nt{expression}} }
    child { node {\basic{ELSE}} }
    child { node {\nt{expression}} }
  }
;
\end{tikzpicture}
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
\end{center}
\caption{A partial derivation tree that justifies shifting}
\label{fig:shifting:tree}
\end{figure}

\begin{figure}
\begin{center}
\begin{tabbing}
\= \nt{expression} \\
\> \basic{IF} \nt{expression} \basic{THEN} \= \nt{expression} \\
\>                                         \> \basic{IF} \nt{expression} \basic{THEN} \basic{expression}
                                              . \basic{ELSE} \nt{expression}
\end{tabbing}
\end{center}
\caption{A textual version of the tree in \fref{fig:shifting:tree}}
\label{fig:shifting:text}
\end{figure}

In our example, the proof that shifting is possible is the derivation tree
shown in Figures~\ref{fig:shifting:tree} and~\ref{fig:shifting:text}. At the
root of the tree is the grammar's start symbol, \nt{expression}. This symbol
develops into the string \nt{IF expression THEN expression}, which forms the
tree's second level. The second occurrence of \nt{expression} in that string
develops into \nt{IF expression THEN expression ELSE expression}, which forms
the tree's last level. The tree's fringe, a sentential form, is the string
\nt{IF expression THEN IF expression THEN expression ELSE expression}. As
announced earlier, it begins with the conflict string \nt{IF expression THEN
IF expression THEN expression}, followed with the conflict token
\nt{ELSE}.

In \fref{fig:shifting:text}, the end of the conflict string is materialized
with a dot. Note that this dot does not occupy the rightmost position in the
tree's last level. In other words, the conflict token (\basic{ELSE}) itself
occurs on the tree's last level. In practical terms, this means that, after
the automaton has recognized the conflict string and peeked at the conflict
token, it makes sense for it to \emph{shift} that token.

\paragraph{Why reducing is legal}

\begin{figure}
1210
\mycommonbaseline
1211
\begin{center}
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
\begin{tikzpicture}[level distance=12mm]
\node { \nt{expression} }
  child { node {\basic{IF}} }
  child { node {\nt{expression}} }
  child { node {\basic{THEN}} }
  child { node {\nt{expression}}
    child { node {\basic{IF}} }
    child { node {\nt{expression}} }
    child { node {\basic{THEN}} }
    child { node {\nt{expression}} }
  }
  child { node {\basic{ELSE}} }
  child { node {\nt{expression}} }
;
\end{tikzpicture}
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
\end{center}
\caption{A partial derivation tree that justifies reducing}
\label{fig:reducing:tree}
\end{figure}

\begin{figure}
\begin{center}
\begin{tabbing}
\= \nt{expression} \\
\> \basic{IF} \nt{expression} \basic{THEN} \= \nt{expression} \basic{ELSE} \nt{expression}
                                                              \sidecomment{lookahead token appears} \\
\>                                         \> \basic{IF} \nt{expression} \basic{THEN} \basic{expression} .
\end{tabbing}
\end{center}
\caption{A textual version of the tree in \fref{fig:reducing:tree}}
\label{fig:reducing:text}
\end{figure}

In our example, the proof that shifting is possible is the derivation tree
shown in Figures~\ref{fig:reducing:tree} and~\ref{fig:reducing:text}. Again,
the sentential form found at the fringe of the tree begins with the conflict
string, followed with the conflict token.

Again, in \fref{fig:reducing:text}, the end of the conflict string is
materialized with a dot. Note that, this time, the dot occupies the rightmost
position in the tree's last level. In other words, the conflict token
(\basic{ELSE}) appeared on an earlier level (here, on the second level).  This
fact is emphasized by the comment \inlinesidecomment{lookahead token appears}
found at the second level. In practical terms, this means that, after the
automaton has recognized the conflict string and peeked at the conflict token,
it makes sense for it to \emph{reduce} the production that corresponds to the
tree's last level---here, the production is \nt{expression} $\rightarrow$
\basic{IF} \nt{expression} \basic{THEN} \basic{expression}.

\paragraph{An example of a more complex derivation tree}

Figures~\ref{fig:xreducing:tree} and~\ref{fig:xreducing:text} show a partial
derivation tree that justifies reduction in a more complex situation. (This
derivation tree is relative to a grammar that is not shown.) Here, the
conflict string is \basic{DATA UIDENT EQUALS UIDENT}; the conflict token is
\basic{LIDENT}.  It is quite clear that the fringe of the tree begins with the
conflict string.  However, in this case, the fringe does not explicitly
exhibit the conflict token. Let us examine the tree more closely and answer
the question: following \basic{UIDENT}, what's the next terminal symbol on the
fringe?

\begin{figure}
1274
\mycommonbaseline
1275
\begin{center}
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
\begin{tikzpicture}[level distance=12mm,level 1/.style={sibling distance=18mm},
                                        level 2/.style={sibling distance=18mm},
                                        level 4/.style={sibling distance=24mm}]]
\node { \nt{decls} }
  child { node {\nt{decl}}
    child { node {\basic{DATA}} }
    child { node {\basic{UIDENT}} }
    child { node {\basic{EQUALS}} }
    child { node {\nt{tycon\_expr}}
      child { node {\nt{tycon\_item}}
        child { node {\basic{UIDENT}} }
        child { node {\nt{opt\_type\_exprs}}
          child { node {} edge from parent [dashed] }
        }
      }
    }
  }
  child { node {\nt{opt\_semi}} }
  child { node {\nt{decls}} }
;    
\end{tikzpicture}
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
\end{center}
\caption{A partial derivation tree that justifies reducing}
\label{fig:xreducing:tree}
\end{figure}

\begin{figure}
\begin{center}
\begin{tabbing}
\= \nt{decls} \\
\> \nt{decl} \nt{opt\_semi} \nt{decls}
\sidecomment{lookahead token appears because \nt{opt\_semi} can vanish
   and \nt{decls} can begin with \basic{LIDENT}} \\
\> \basic{DATA UIDENT} \basic{EQUALS} \= \nt{tycon\_expr}
\sidecomment{lookahead token is inherited} \\
\> \> \nt{tycon\_item} \sidecomment{lookahead token is inherited} \\
\> \> \basic{UIDENT} \= \nt{opt\_type\_exprs} \sidecomment{lookahead token is inherited} \\
\> \> \> .
\end{tabbing}
\end{center}
\caption{A textual version of the tree in \fref{fig:xreducing:tree}}
\label{fig:xreducing:text}
\end{figure}

First, note that \nt{opt\_type\_exprs} is \emph{not} a leaf node, even though
it has no children. The grammar contains the production $\nt{opt\_type\_exprs}
\rightarrow \epsilon$: the nonterminal symbol \nt{opt\_type\_exprs} develops
to the empty string. (This is made clear in \fref{fig:xreducing:text}, where a
single dot appears immediately below \nt{opt\_type\_exprs}.) Thus,
\nt{opt\_type\_exprs} is not part of the fringe.

Next, note that \nt{opt\_type\_exprs} is the rightmost symbol within its
level. Thus, in order to find the next symbol on the fringe, we have to look
up one level. This is the meaning of the comment \inlinesidecomment{lookahead
token is inherited}. Similarly, \nt{tycon\_item} and \nt{tycon\_expr} appear
rightmost within their level, so we again have to look further up.

This brings us back to the tree's second level. There, \nt{decl} is \emph{not}
the rightmost symbol: next to it, we find \nt{opt\_semi} and \nt{decls}. Does
this mean that \nt{opt\_semi} is the next symbol on the fringe? Yes and no.
\nt{opt\_semi} is a \emph{nonterminal} symbol, but we are really interested in finding
out what the next \emph{terminal} symbol on the fringe could be. The partial
derivation tree shown in Figures~\ref{fig:xreducing:tree}
and~\ref{fig:xreducing:text} does not explicitly answer this question. In
order to answer it, we need to know more about \nt{opt\_semi} and \nt{decls}.

Here, \nt{opt\_semi} stands (as one might have guessed) for an optional
semicolon, so the grammar contains a production $\nt{opt\_semi} \rightarrow
\epsilon$. This is indicated by the comment
\inlinesidecomment{\nt{opt\_semi} can vanish}. (Nonterminal symbols
that generate $\epsilon$ are also said to be \emph{nullable}.) Thus, one could
choose to turn this partial derivation tree into a larger one by developing
\nt{opt\_semi} into $\epsilon$, making it a non-leaf node. That would yield
a new partial derivation tree where the next symbol on the fringe, following
\basic{UIDENT}, is \nt{decls}.

Now, what about \nt{decls}? Again, it is a \emph{nonterminal} symbol, and we
are really interested in finding out what the next \emph{terminal} symbol on
the fringe could be. Again, we need to imagine how this partial derivation
tree could be turned into a larger one by developing \nt{decls}. Here, the
grammar happens to contain a production of the form $\nt{decls} \rightarrow
\basic{LIDENT} \ldots$ This is indicated by the comment
\inlinesidecomment{\nt{decls} can begin with \basic{LIDENT}}.
Thus, by developing \nt{decls}, it is possible to construct a partial
derivation tree where the next symbol on the fringe, following
\basic{UIDENT}, is \basic{LIDENT}. This is precisely the conflict
token.

To sum up, there exists a partial derivation tree whose
fringe begins the conflict string, followed with the conflict token.
Furthermore, in that derivation tree, the dot occupies the rightmost position
in the last level. As in our previous example, this means that, after the
automaton has recognized the conflict string and peeked at the conflict token,
it makes sense for it to \emph{reduce} the production that corresponds to the
tree's last level---here, the production is $\nt{opt\_type\_exprs}
\rightarrow \epsilon$.

\paragraph{Greatest common factor among derivation trees}

Understanding conflicts requires comparing two (or more) derivation trees. It
is frequent for these trees to exhibit a common factor, that is, to exhibit
identical structure near the top of the tree, and to differ only below a
specific node. Manual identification of that node can be tedious, so \menhir
performs this work automatically. When explaining a $n$-way conflict, it first
displays the greatest common factor of the $n$ derivation trees. A question
mark symbol $\basic{(?)}$ is used to identify the node where the trees begin
to differ. Then, \menhir displays each of the $n$ derivation trees,
\emph{without their common factor} -- that is, it displays $n$ sub-trees that
actually begin to differ at the root. This should make visual comparisons
significantly easier.

\subsection{How are severe conflicts resolved in the end?}

It is unspecified how severe conflicts are resolved. \menhir attempts to mimic
\ocamlyacc's specification, that is, to resolve shift/reduce conflicts in favor
of shifting, and to resolve reduce/reduce conflicts in favor of the production
that textually appears earliest in the grammar specification. However, this
specification is inconsistent in case of three-way conflicts, that is,
conflicts that simultaneously involve a shift action and several reduction
actions. Furthermore, textual precedence can be undefined when the grammar
specification is split over multiple modules. In short, \menhir's philosophy is
that
\begin{center}
severe conflicts should not be tolerated,
\end{center}
so you should not care how they are resolved.

% If a shift/reduce conflict is resolved in favor of reduction, then there can
% exist words of terminal symbols that are accepted by the canonical LR(1)
% automaton without traversing any conflict state and which are rejected by our
% automaton (constructed by Pager's method followed by conflict
% resolution). Same problem when a shift/reduce conflict is resolved in favor of
% neither action (via \dnonassoc) or when a reduce/reduce conflict is resolved
% arbitrarily.

\subsection{End-of-stream conflicts}
\label{sec:eos}

\menhir's treatment of the end of the token stream is (believed to be) fully compatible
with \ocamlyacc's. Yet, \menhir attempts to be more user-friendly by warning
about a class of so-called ``end-of-stream conflicts''.

1418 1419 1420 1421 1422
% TEMPORARY il faut noter que Menhir n'est pas conforme à ocamlyacc en
% présence de conflits end-of-stream; apparemment il part dans le mur
% en exigeant toujours le token suivant, alors que ocamlyacc est capable
% de s'arrêter (comment?); cf. problème de S. Hinderer (avril 2015).

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
\paragraph{How the end of stream is handled}

In many textbooks on parsing, it is assumed that the lexical analyzer, which
produces the token stream, produces a special token, written \eos, to signal
that the end of the token stream has been reached. A parser generator can take
advantage of this by transforming the grammar: for each start symbol $\nt{S}$
in the original grammar, a new start symbol $\nt{S'}$ is defined, together
with the production $S'\rightarrow S\eos$. The symbol $S$ is no longer a start
symbol in the new grammar. This means that the parser will accept a sentence
derived from $S$ only if it is immediately followed by the end of the token
stream.

This approach has the advantage of simplicity. However, \ocamlyacc and \menhir
do not follow it, for several reasons. Perhaps the most convincing one is that
it is not flexible enough: sometimes, it is desirable to recognize a sentence
derived from $S$, \emph{without} requiring that it be followed by the end of
the token stream: this is the case, for instance, when reading commands, one
by one, on the standard input channel. In that case, there is no end of stream:
the token stream is conceptually infinite. Furthermore, after a command has
been recognized, we do \emph{not} wish to examine the next token, because
doing so might cause the program to block, waiting for more input.

In short, \ocamlyacc and \menhir's approach is to recognize a sentence derived
from $S$ and to \emph{not look}, if possible, at what follows. However, this
is possible only if the definition of $S$ is such that the end of an
$S$-sentence is identifiable without knowledge of the lookahead token. When
the definition of $S$ does not satisfy this criterion, and \emph{end-of-stream
conflict} arises: after a potential $S$-sentence has been read, there can be a
tension between consulting the next token, in order to determine whether the
sentence is continued, and \emph{not} consulting the next token, because the
sentence might be over and whatever follows should not be read. \menhir warns
about end-of-stream conflicts, whereas \ocamlyacc does not.

\paragraph{A definition of end-of-stream conflicts}

Technically, \menhir proceeds as follows. A \eos symbol is introduced. It is,
however, only a \emph{pseudo-}token: it is never produced by the lexical
analyzer. For each start symbol $\nt{S}$ in the original grammar, a new start
symbol $\nt{S'}$ is defined, together with the production $S'\rightarrow S$.
The corresponding start state of the LR(1) automaton is composed of the LR(1)
item $S' \rightarrow . \;S\; [\eos]$. That is, the pseudo-token \eos initially
appears in the lookahead set, indicating that we expect to be done after
recognizing an $S$-sentence. During the construction of the LR(1) automaton,
this lookahead set is inherited by other items, with the effect that, in the
end, the automaton has:
\begin{itemize}
\item \emph{shift} actions only on physical tokens; and
\item \emph{reduce} actions either on physical tokens or on the pseudo-token \eos.
\end{itemize}
A state of the automaton has a reduce action on \eos if, in that state, an
$S$-sentence has been read, so that the job is potentially finished. A state
has a shift or reduce action on a physical token if, in that state, more
tokens potentially need to be read before an $S$-sentence is recognized. If a
state has a reduce action on \eos, then that action should be taken
\emph{without} requesting the next token from the lexical analyzer. On the
other hand, if a state has a shift or reduce action on a physical token, then
the lookahead token \emph{must} be consulted in order to determine if that
action should be taken.

\begin{figure}[p]
\begin{quote}
\begin{tabular}{l}
\dtoken \kangle{\basic{int}} \basic{INT} \\
\dtoken \basic{PLUS TIMES} \\
\dleft PLUS \\
\dleft TIMES \\
\dstart \kangle{\basic{int}} \nt{expr} \\
\percentpercent \\
\nt{expr}:
\newprod \basic{i} = \basic{INT} \dpaction{\basic{i}}
\newprod \basic{e1} = \nt{expr} \basic{PLUS} \basic{e2} = \nt{expr} \dpaction{\basic{e1 + e2}}
\newprod \basic{e1} = \nt{expr} \basic{TIMES} \basic{e2} = \nt{expr} \dpaction{\basic{e1 * e2}}
\end{tabular}
\end{quote}
\caption{Basic example of an end-of-stream conflict}
\label{fig:basiceos}
\end{figure}

\begin{figure}[p]
\begin{verbatim}
State 6:
expr -> expr . PLUS expr [ # TIMES PLUS ]
expr -> expr PLUS expr . [ # TIMES PLUS ]
expr -> expr . TIMES expr [ # TIMES PLUS ]
-- On TIMES shift to state 3
-- On # PLUS reduce production expr -> expr PLUS expr 

State 4:
expr -> expr . PLUS expr [ # TIMES PLUS ]
expr -> expr . TIMES expr [ # TIMES PLUS ]
expr -> expr TIMES expr . [ # TIMES PLUS ]
-- On # TIMES PLUS reduce production expr -> expr TIMES expr 

State 2:
expr' -> expr . [ # ]
expr -> expr . PLUS expr [ # TIMES PLUS ]
expr -> expr . TIMES expr [ # TIMES PLUS ]
-- On TIMES shift to state 3
-- On PLUS shift to state 5
-- On # accept expr
\end{verbatim}
\caption{Part of an LR automaton for the grammar in \fref{fig:basiceos}}
\label{fig:basiceosdump}
\end{figure}

\begin{figure}[p]
\begin{quote}
\begin{tabular}{l}
\ldots \\
\dtoken \basic{END} \\
\dstart \kangle{\basic{int}} \nt{main} \hskip 1cm \textit{// instead of \nt{expr}} \\
\percentpercent \\
\nt{main}:
\newprod \basic{e} = \nt{expr} \basic{END} \dpaction{\basic{e}} \\
\nt{expr}:
\newprod \ldots
\end{tabular}
\end{quote}
\caption{Fixing the grammar specification in \fref{fig:basiceos}}
\label{fig:basiceos:sol}
\end{figure}

An end-of-stream conflict arises when a state has distinct actions on \eos and
on at least one physical token. In short, this means that the end of an
$S$-sentence cannot be unambiguously identified without examining one extra
token. \menhir's default behavior, in that case, is to suppress the action on
\eos, so that more input is \emph{always} requested.

\paragraph{Example}

\fref{fig:basiceos} shows a grammar that has end-of-stream conflicts.
When this grammar is processed, \menhir warns about these conflicts,
and further warns that \nt{expr} is never accepted. Let us explain.

1557 1558
Part of the corresponding automaton, as described in the \automaton file, is
shown in \fref{fig:basiceosdump}. Explanations at the end of the \automaton
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
file (not shown) point out that states 6 and 2 have an end-of-stream
conflict. Indeed, both states have distinct actions on \eos and on the
physical token \basic{TIMES}.
%
It is interesting to note that, even though state 4 has actions on \eos and on
physical tokens, it does not have an end-of-stream conflict. This is because
the action taken in state 4 is always to reduce the production $\nt{expr}
\rightarrow \nt{expr}$ \basic{TIMES} \nt{expr}, regardless of the lookahead
token.

By default, \menhir produces a parser where end-of-stream conflicts are
resolved in favor of looking ahead: that is, the problematic reduce actions on
\eos are suppressed. This means, in particular, that the \emph{accept} action
in state 2, which corresponds to reducing the production $\nt{expr}
\rightarrow \nt{expr'}$, is suppressed. This explains why the symbol \nt{expr}
is never accepted: because expressions do not have an unambiguous end marker,
the parser will always request one more token and will never stop.

In order to avoid this end-of-stream conflict, the standard solution is to
introduce a new token, say \basic{END}, and to use it as an end marker for
expressions. The \basic{END} token could be generated by the lexical analyzer
when it encounters the actual end of stream, or it could correspond to a piece
of concrete syntax, say, a line feed character, a semicolon, or an
\texttt{end} keyword. The solution is shown in \fref{fig:basiceos:sol}.

% ---------------------------------------------------------------------------------------------------------------------

\section{Positions}
\label{sec:positions}

When an \ocamllex-generated lexical analyzer produces a token, it updates
two fields, named \verb+lex_start_p+ and \verb+lex_curr_p+, in its environment
record, whose type is \verb+Lexing.lexbuf+. Each of these fields holds a value
of type \verb+Lexing.position+. Together, they represent the token's start and
end positions within the text that is being scanned. A position consists
mainly of an offset (the position's \verb+pos_cnum+ field), but also holds
information about the current file name, the current line number, and the
current offset within the current line. (Not all \ocamllex-generated analyzers
keep this extra information up to date. This must be explicitly programmed by
the author of the lexical analyzer.)

\begin{figure}
\begin{center}
\begin{tabular}{lp{9cm}}
\verb+$startpos+ & start position of the sentence derived out of the production that is being reduced \\
\verb+$endpos+   & end position of the sentence derived out of the production that is being reduced \\
\verb+$startpos(+ \verb+$+\nt{i} \barre \nt{id} \verb+)+
                 & start position of the sentence derived out of the symbol whose semantic value is referred to as
                   \verb+$+\nt{i} or \nt{id} \\
\verb+$endpos(+ \verb+$+\nt{i} \barre \nt{id} \verb+)+
                 & end position of the sentence derived out of the symbol whose semantic value is referred to as
                   \verb+$+\nt{i} or \nt{id} \\
\verb+$startofs+ & start offset of the sentence derived out of the production that is being reduced \\
\verb+$endofs+   & end offset of the sentence derived out of the production that is being reduced \\
\verb+$startofs(+ \verb+$+\nt{i} \barre \nt{id} \verb+)+
                 & start offset of the sentence derived out of the symbol whose semantic value is referred to as
                   \verb+$+\nt{i} or \nt{id} \\
\verb+$endofs(+ \verb+$+\nt{i} \barre \nt{id} \verb+)+
                 & end offset of the sentence derived out of the symbol whose semantic value is referred to as
                   \verb+$+\nt{i} or \nt{id} \\
\end{tabular}
\end{center}
\caption{Position-related keywords}
\label{fig:pos}
\end{figure}

This mechanism allows associating pairs of positions with terminal symbols. If
desired, \menhir automatically extends it to nonterminal symbols as well. That
is, it offers a mechanism for associating pairs of positions with terminal or
nonterminal symbols. This is done by making a set of keywords, documented in
\fref{fig:pos}, available to semantic actions. Note that these keywords are
\emph{not} available elsewhere---in particular, not within \ocaml headers.
Note also that \ocaml's standard library module \texttt{Parsing} is
deprecated. The functions that it offers \emph{can} be called, but will return
dummy positions.

% ---------------------------------------------------------------------------------------------------------------------

1637
\section{Error handling}
1638 1639 1640 1641
\label{sec:errors}

\paragraph{Error handling}

1642
\menhir's error handling mechanism is inspired by that of \yacc and
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
\ocamlyacc, but is not identical. A special \error token is made available
for use within productions. The LR automaton is constructed exactly as if
\error was a regular terminal symbol. However, \error is never produced
by the lexical analyzer. Instead, when an error is detected, the current
lookahead token is discarded and replaced with the \error token, which becomes
the current lookahead token. At this point, the parser enters \emph{error
handling} mode.

In error handling mode, automaton states are popped off the automaton's stack
until a state that can \emph{act} on \error is found. This includes
\emph{both} shift \emph{and} reduce actions. (\yacc and \ocamlyacc do not
trigger reduce actions on \error. It is somewhat unclear why this is so.)

When a state that can reduce on \error is found, reduction is performed.
Since the lookahead token is still \error, the automaton remains in error
handling mode.

When a state that can shift on \error is found, the \error token is shifted.
1661
At this point, the parser returns to normal mode.
1662 1663 1664 1665 1666 1667 1668 1669

When no state that can act on \error is found on the automaton's stack, the
parser stops and raises the exception \texttt{Error}. This exception carries
no information. The position of the error can be obtained by reading the
lexical analyzer's environment record.

\paragraph{Error recovery}

1670 1671
\ocamlyacc offers an error recovery mode, which is entered immediately after
an \error token was successfully shifted. In this mode, tokens are repeatedly
1672
taken off the input stream and discarded until an acceptable token is found.
1673
This feature is no longer offered by \menhir.
1674 1675 1676

\paragraph{Error-related keywords}

1677
The following keyword is made available to semantic actions.
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832

When the \verb+$syntaxerror+ keyword is evaluated, evaluation of the semantic
action is aborted, so that the current reduction is abandoned; the current
lookahead token is discarded and replaced with the \error token; and error
handling mode is entered.  Note that there is no mechanism for inserting an
\error token \emph{in front of} the current lookahead token, even though this
might also be desirable.  It is unclear whether this keyword is useful; it
might be suppressed in the future.

\paragraph{When are errors detected?}

An error is detected when the current state of the automaton has no action on
the current lookahead token. Thus, understanding exactly when errors are
detected requires understanding how the automaton is constructed. \menhir's
construction technique is \emph{not} Knuth's canonical LR(1)
technique~\cite{knuth-lr-65}, which is too expensive to be practical. Instead,
\menhir \emph{merges} states~\cite{pager-77} and introduces so-called \emph{default
reductions}. Both techniques can \emph{defer} error detection by allowing
extra reductions to take place before an error is detected. All LALR(1) parser
generators exhibit the same problem.

% ---------------------------------------------------------------------------------------------------------------------

\section{Using \menhir as an interpreter}
\label{sec:interpret}

When \ointerpret is set, \menhir no longer behaves as a compiler. Instead,
it acts as an interpreter. That is, it repeatedly:
\begin{itemize}
\item reads a sentence off the standard input channel;
\item parses this sentence, according to the grammar;
\item displays an outcome.
\end{itemize}
This process stops when the end of the input channel is reached.

\subsection{Sentences}
\label{sec:sentences}

The syntax of sentences is as follows:
\begin{center}
\begin{tabular}{r@{}c@{}l}
\nt{sentence} \is
  \optional{\nt{lid}\,\deuxpoints} \sepspacelist{\nt{uid}} \,\dnewline
\end{tabular}
\end{center}

Less formally, a sentence is a sequence of zero or more terminal symbols
(\nt{uid}'s), separated with whitespace, terminated with a newline character,
and optionally preceded with a non-terminal start symbol (\nt{lid}). This
non-terminal symbol can be omitted if, and only if, the grammar only has one
start symbol.

For instance, here are four valid sentences for the grammar of arithmetic
expressions found in the directory \distrib{demos/calc}:
%
\begin{verbatim}
main: INT PLUS INT EOL
INT PLUS INT
INT PLUS PLUS INT EOL
INT PLUS PLUS
\end{verbatim}
%
In the first sentence, the start symbol \texttt{main} was explicitly
specified. In the other sentences, it was omitted, which is permitted, because
this grammar has no start symbol other than \texttt{main}.  The first sentence
is a stream of four terminal symbols, namely \texttt{INT}, \texttt{PLUS},
\texttt{INT}, and \texttt{EOL}. These terminal symbols must be provided under
their symbolic names. Writing, say, ``\texttt{12+32\textbackslash n}'' instead
of \texttt{INT PLUS INT EOL} is not permitted. \menhir would not be able to
make sense of such a concrete notation, since it does not have a lexer for it.

% On pourrait documenter le fait qu'une phrase finie est transformée par Menhir
% en un flot de tokens potentiellement infinie, avec un suffixe infini EOF ...
% Mais c'est un hack, qui pourrait changer à l'avenir.

\subsection{Outcomes}
\label{sec:outcomes}

As soon as \menhir is able to read a complete sentence off the standard input
channel (that is, as soon as it finds the newline character that ends the
sentence), it parses the sentence according to whichever grammar was specified
on the command line, and displays an outcome.

An outcome is one of the following:
\begin{itemize}
\item \texttt{ACCEPT}: a prefix of the sentence was successfully parsed;
      a parser generated by \menhir would successfully stop and produce
      a semantic value;
\item \texttt{OVERSHOOT}: the end of the sentence was reached before it
      could be accepted; a parser generated by \menhir would request a
      non-existent ``next token'' from the lexer, causing it to fail or
      block;
\item \texttt{REJECT}: the sentence was not accepted; a parser generated
      by \menhir would raise the exception \texttt{Error}.
\end{itemize}

When \ointerpretshowcst is set, each \texttt{ACCEPT} outcome is followed with
a concrete syntax tree. A concrete syntax tree is either a leaf or a node.  A
leaf is either a terminal symbol or \error. A node is annotated with a
non-terminal symbol, and carries a sequence of immediate descendants that
correspond to a valid expansion of this non-terminal symbol. \menhir's
notation for concrete syntax trees is as follows:
\begin{center}
\begin{tabular}{r@{}c@{}l}
\nt{cst} \is
   \nt{uid} \\
&& \error \\
&& \texttt{[} \nt{lid}\,\deuxpoints \sepspacelist{\nt{cst}} \texttt{]}
\end{tabular}
\end{center}

% This notation is not quite unambiguous (it is ambiguous if several
% productions are identical).

For instance, if one wished to parse the example sentences of
\sref{sec:sentences} using the grammar of arithmetic expressions in
\distrib{demos/calc}, one could invoke \menhir as follows:
\begin{verbatim}
$ menhir --interpret --interpret-show-cst demos/calc/parser.mly
main: INT PLUS INT EOL
ACCEPT
[main: [expr: [expr: INT] PLUS [expr: INT]] EOL]
INT PLUS INT
OVERSHOOT
INT PLUS PLUS INT EOL
REJECT
INT PLUS PLUS
REJECT
\end{verbatim}
(Here, \menhir's input---the sentences provided by the user on the standard
input channel--- is shown intermixed with \menhir's output---the outcomes
printed by \menhir on the standard output channel.) The first sentence is
valid, and accepted; a concrete syntax tree is displayed. The second sentence
is incomplete, because the grammar specifies that a valid expansion of
\texttt{main} ends with the terminal symbol \texttt{EOL}; hence, the outcome
is \texttt{OVERSHOOT}. The third sentence is invalid, because of the repeated
occurrence of the terminal symbol \texttt{PLUS}; the outcome is
\texttt{REJECT}. The fourth sentence, a prefix of the third one, is rejected
for the same reason.

\subsection{Remarks}

Using \menhir as an interpreter offers an easy way of debugging your grammar.
For instance, if one wished to check that addition is considered
left-associative, as requested by the \dleft directive found in the file
\distrib{demos/calc/parser.mly}, one could submit the following sentence:
\begin{verbatim}
$ ./menhir --interpret --interpret-show-cst ../demos/calc/parser.mly
INT PLUS INT PLUS INT EOL
ACCEPT
[main:
  [expr: [expr: [expr: INT] PLUS [expr: INT]] PLUS [expr: INT]]
  EOL
]
\end{verbatim}
1833
%$
1834 1835 1836 1837 1838 1839 1840 1841 1842
The concrete syntax tree displayed by \menhir is skewed towards the left,
as desired.

The switches \ointerpret and \otrace can be used in conjunction. When
\otrace is set, the interpreter logs its actions to the standard error
channel.

% ---------------------------------------------------------------------------------------------------------------------

1843 1844 1845 1846 1847
\section{Generated API}

When \menhir processes a grammar specification, say \texttt{parser.mly}, it
produces one \ocaml module, \texttt{Parser}, whose code resides in the file
\texttt{parser.ml} and whose signature resides in the file
1848 1849
\texttt{parser.mli}. We now review this signature. For simplicity,
we assume that the grammar specification has just one start symbol
1850
\verb+main+, whose \ocaml type is \verb+thing+.
1851

1852 1853
% ------------------------------------------------------------------------------

1854 1855 1856
\subsection{Monolithic API}
\label{sec:monolithic}

1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
The monolithic API defines the type \verb+token+, the exception \verb+Error+,
and the parsing function \verb+main+, named after the start symbol of the
grammar.

%% type token

The type \verb+token+ is an algebraic data type. A value of type \verb+token+
represents a terminal symbol and its semantic value. For instance, if the
grammar contains the declarations \verb+%token A+ and \verb+%token<int> B+,
then the generated file \texttt{parser.mli} contains the following definition:
\begin{verbatim}
  type token =
  | A
  | B of int
\end{verbatim}
%
If \oonlytokens is specified on the command line, the type \verb+token+ is
generated, and the rest is omitted. On the contrary, if \oexternaltokens is
used, the type \verb+token+ is omitted, but the rest (described below) is
generated.

%% exception Error

The exception \verb+Error+ carries no argument. It is raised by the parsing
function \verb+main+ (described below) when a syntax error is detected.
%
\begin{verbatim}
  exception Error
\end{verbatim}

%% val main

Next comes one parsing function for each start symbol of the grammar. Here, we
have assumed that there is one start symbol, named \verb+main+, so the
generated file \texttt{parser.mli} contains the following declaration:
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
\begin{verbatim}
  val main: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> thing
\end{verbatim}
% On ne montre pas la définition de l'exception Error.
This function expects two arguments, namely: a lexer, which typically is produced by
\ocamllex and has type \verb+Lexing.lexbuf -> token+; and a lexing buffer,
which has type \verb+Lexing.lexbuf+. This API is compatible with
\ocamlyacc. (For information on using \menhir without \ocamllex, please
consult \sref{sec:qa}.)
%
This API is ``monolithic'' in the sense that there is just one function, which
does everything: it pulls tokens from the lexer, parses, and eventually
returns a semantic value (or fails by throwing the exception \texttt{Error}).

1906 1907
% ------------------------------------------------------------------------------

1908 1909 1910 1911 1912 1913 1914 1915 1916
\subsection{Incremental API}
\label{sec:incremental}

If \otable is set, \menhir offers an incremental API in addition to the
monolithic API. In this API, control is inverted. The parser does not have
access to the lexer. Instead, when the parser needs the next token, it stops
and returns its current state to the user. The user is then responsible for
obtaining this token (typically by invoking the lexer) and resuming the parser
from that state.
1917 1918 1919
%
The directory \distrib{demos/calc-incremental} contains a demo that
illustrates the use of the incremental API.
1920 1921 1922 1923 1924

This API is ``incremental'' in the sense that the user has access to a
sequence of the intermediate states of the parser. Assuming that semantic
values are immutable, a parser state is a persistent data structure: it can be
stored and used multiple times, if desired. This enables applications such as
1925
``live parsing'', where a buffer is continuously parsed while it is being
1926 1927 1928 1929 1930 1931 1932 1933 1934
edited. The parser can be re-started in the middle of the buffer whenever the
user edits a character. Because two successive parser states share most of
their data in memory, a list of $n$ successive parser states occupies only
$O(n)$ space in memory.

% One could point out that semantic actions should be side-effect free.
% But that is an absolute requirement. Semantic actions can have side
% effects, if the user knows what they are doing.

1935 1936 1937
% TEMPORARY actually, live parsing also requires a way of performing
% error recovery, up to a complete parse... as in Merlin.

1938
In this API, the parser is started by invoking
1939
\verb+Incremental.main+. (Recall that we assume \verb+main+ is
1940 1941
the name of the start symbol.) The generated file \texttt{parser.mli} contains
the following declaration:
1942
\begin{verbatim}
1943
  module Incremental : sig
1944
    val main: unit -> thing MenhirInterpreter.checkpoint
1945
  end
1946
\end{verbatim}
1947 1948 1949 1950
We emphasize that the function \verb+Incremental.main+ does not parse
anything. It constructs a parser state which serves as a \emph{starting}
point. The functions \verb+offer+ and \verb+resume+, described below, are used
to drive the parser.
1951 1952

The sub-module \menhirinterpreter is also part of the incremental API.
1953
Its declaration, which appears in the generated file \texttt{parser.mli}, is as
1954 1955 1956
follows:
\begin{verbatim}
  module MenhirInterpreter : MenhirLib.IncrementalEngine.INCREMENTAL_ENGINE
1957
    with type token = token
1958 1959 1960 1961
\end{verbatim}
The signature \verb+INCREMENTAL_ENGINE+, defined in the module
\menhirlibincrementalengine, contains the following elements.
Please keep in mind that, from the outside, these elements should be referred
1962 1963 1964
to with an appropriate prefix: e.g., the type \verb+checkpoint+ should be referred
to as \verb+MenhirInterpreter.checkpoint+, or
\verb+Parser.MenhirInterpreter.checkpoint+, depending on which modules the user
1965 1966
chooses to open.

1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
%% type token

% Passons-le sous silence.

%% type env

\begin{verbatim}
  type env
\end{verbatim}

The abstract type \verb+env+ represents the current state of the
parser. (That is, it contains the current state and stack of the LR
automaton.) Assuming that semantic values are immutable, it is a persistent
data structure: it can be stored and used multiple times, if desired.

%% type production

\begin{verbatim}
  type production
\end{verbatim}

The abstract type \verb+production+ represents a production of the grammar.

1990
%% type 'a checkpoint
1991

1992
\begin{verbatim}
1993
  type 'a checkpoint = private
1994
    | InputNeeded of env
1995
    | Shifting of env * env * bool
1996 1997
    | AboutToReduce of env * production
    | HandlingError of env
1998 1999 2000 2001
    | Accepted of 'a
    | Rejected
\end{verbatim}

2002 2003
The type \verb+'a checkpoint+ represents an intermediate or
final state of the parser. An intermediate checkpoint is a suspension: it records
2004 2005 2006 2007
the parser's current state, and allows parsing to be resumed. The parameter
\verb+'a+ is the type of the semantic value that will eventually be produced
if the parser succeeds.

2008
\verb+Accepted+ and \verb+Rejected+ are final checkpoints. \verb+Accepted+ carries
2009 2010
a semantic value.

2011
\verb+InputNeeded+ is an intermediate checkpoint. It means that the parser wishes
2012 2013
to read one token before continuing.

2014
\verb+Shifting+ is an intermediate checkpoint. It means that the parser is taking
2015 2016 2017 2018 2019
a shift transition. It exposes the state of the parser before and after the
transition. The Boolean parameter tells whether the parser intends to request
a new token after this transition. (It always does, except when it is about to
accept.)

2020
\verb+AboutToReduce+ is an intermediate checkpoint: it means that the parser is
2021
about to perform a reduction step. \verb+HandlingError+ is also an
2022
intermediate checkpoint: it means that the parser has detected an error and is
2023
about to handle it. (Error handling is typically performed in several steps,
2024
so the next checkpoint is likely to be \verb+HandlingError+ again.) In these two
2025 2026 2027
cases, the parser does not need more input. The parser suspends itself at this
point only in order to give the user an opportunity to observe the parser's
transitions and possibly handle errors in a different manner, if desired.
2028

2029
%% val offer
2030 2031 2032

\begin{verbatim}
  val offer:
2033
    'a checkpoint ->
2034
    token * Lexing.position * Lexing.position ->
2035
    'a checkpoint
2036 2037 2038
\end{verbatim}

The function \verb+offer+ allows the user to resume the parser after the
2039 2040
parser has suspended itself with a checkpoint of the form \verb+InputNeeded env+.
This function expects the previous checkpoint \verb+checkpoint+ as well as a new token
2041
(together with the start and end positions of this token). It produces a new
2042
checkpoint, which again can be an intermediate checkpoint or a final checkpoint. It does
2043 2044 2045
not raise any exception. (The exception \texttt{Error} is used only in the
monolithic API.)

2046 2047
%% val resume

2048
\begin{verbatim}
2049
  val resume:
2050 2051
    'a checkpoint ->
    'a checkpoint
2052 2053
\end{verbatim}

2054
The function \verb+resume+ allows the user to resume the parser after the
2055
parser has suspended itself with a checkpoint of the form
2056
\verb+AboutToReduce (env, prod)+ or \verb+HandlingError env+.
2057 2058
This function expects just the previous checkpoint \verb+checkpoint+. It produces a new
checkpoint. It does not raise any exception.
2059

2060
The incremental API subsumes the monolithic API. Indeed, \verb+main+ can be
2061
(and is in fact) implemented by first using
2062
\verb+Incremental.main+, then calling \verb+offer+ and
2063
\verb+resume+ in a loop, until a final checkpoint is obtained.
2064

2065 2066 2067 2068
Although the type \verb+env+ is opaque, a parser state can be inspected via a
few accessor functions, which we are about to describe. Before we do so, we
give a few more type definitions.

2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
%% type supplier

\begin{verbatim}
  type supplier =
    unit -> token * Lexing.position * Lexing.position
\end{verbatim}

A token supplier is a function of no arguments which delivers a new token
(together with its start and end positions) every time it is called. The
function \verb+loop+ and its variants, described below, expect a supplier
as an argument.

%% val lexer_lexbuf_to_supplier

\begin{verbatim}
  val lexer_lexbuf_to_supplier:
    (Lexing.lexbuf -> token) ->
    Lexing.lexbuf ->
    supplier
\end{verbatim}

The function \verb+lexer_lexbuf_to_supplier+, applied to a lexer and to a
lexing buffer, produces a fresh supplier.

2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
%% (remark about the loop* functions)

The functions \verb+offer+ and \verb+resume+, documented above, are sufficient
to write a parser loop. One can imagine many variations of such a loop, which
is why we expose \verb+offer+ and \verb+resume+ in the first place!.
Nevertheless, some variations are so common that it is worth providing them,
ready for use.

%% val loop

\begin{verbatim}
  val loop: supplier -> 'a checkpoint -> 'a
\end{verbatim}

\verb+loop supplier checkpoint+ begins parsing from \verb+checkpoint+, reading
tokens from \verb+supplier+. It continues parsing until it reaches a
checkpoint of the form \verb+Accepted v+ or \verb+Rejected+. In the former
case, it returns \verb+v+. In the latter case, it raises the
exception \verb+Error+. (By the way, this is how we implement the monolithic
API on top of the incremental API.)

\begin{verbatim}
  val loop_handle:
    ('a -> 'answer) ->
    ('a checkpoint -> 'answer) ->
    supplier -> 'a checkpoint -> 'answer
\end{verbatim}

\verb+loop_handle succeed fail supplier checkpoint+ begins parsing from
\verb+checkpoint+, reading tokens from \verb+supplier+. It continues parsing until
it reaches a checkpoint of the form \verb+Accepted v+ or \verb+HandlingError env+
(or \verb+Rejected+, but that should not happen, as \verb+HandlingError _+
will be observed first). In the former case, it calls \verb+succeed v+. In
the latter case, it calls \verb+fail+ with this checkpoint. It cannot
raise \verb+Error+.

This means that Menhir's traditional error-handling procedure (which pops the
stack until a state that can act on the \error token is found) does not get a
chance to run. Instead, the user can implement her own error handling code, in
the \verb+fail+ continuation.

2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
%% type 'a lr1state

\begin{verbatim}
  type 'a lr1state
\end{verbatim}

The abstract type \verb+'a lr1state+ describes a (non-initial) state of the
LR(1) automaton.
%
If \verb+s+ is such a state, then \verb+s+ should have at least one incoming
transition, and all of its incoming transitions carry the same (terminal or
non-terminal) symbol, say $A$. We say that $A$ is the \emph{incoming symbol}
of the state~\verb+s+.
%
The index \verb+'a+ is the type of the semantic values associated with $A$.
The role played by \verb+'a+ is clarified in the definition of the
type \verb+element+, which follows.

%% type element

\begin{verbatim}
  type element =
    | Element: 'a lr1state * 'a * Lexing.position * Lexing.position -> element
\end{verbatim}

The type \verb+element+ describes one entry in the stack of the LR(1)
automaton. In a stack element of the form \verb+Element (s, v, startp, endp)+,
\verb+s+ is a (non-initial) state and \verb+v+ is a semantic value. The
value~\verb+v+ is associated with the incoming symbol~$A$ of the
state~\verb+s+. In other words, the value \verb+v+ was pushed onto the stack
just before the state \verb+s+ was entered. Thus, for some type \verb+'a+, the
state~\verb+s+ has type \verb+'a lr1state+ and the value~\verb+v+ has
type~\verb+'a+. The positions \verb+startp+ and \verb+endp+ delimit the
fragment of the input text that was reduced to the symbol $A$.

In order to do anything useful with the value \verb+v+, one must gain
information about the type \verb+'a+, by inspection of the state~\verb+s+. So
far, the type \verb+'a lr1state+ is abstract, so there is no way of
inspecting~\verb+s+. The inspection API (\sref{sec:inspection}) offers further
tools for this purpose.

%% type stack

\begin{verbatim}
  type stack =
    element stream
\end{verbatim}

A parser stack can be viewed as a stream of elements, where the first element
of the stream is the topmost element of the stack. (The type \verb+'a stream+
2184
is defined in the module \menhirlibgeneral.)
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
This stream is empty if the parser is in an initial state, and non-empty otherwise.
% (Which initial state? -- no way to know...)
In the latter case, 
the current state of the LR(1) automaton is found in the topmost stack element.

%% val stack

\begin{verbatim}
  val stack: env -> stack
\end{verbatim}

The function \verb+stack+ offers a view of the parser's stack as a stream of
elements. This stream is computed on-demand. (The internal representation of
the stack may be different, so a conversion is necessary.) Invoking the
function \verb+stack+, and demanding the next element of the stream, takes
constant time.

%% val positions

\begin{verbatim}
  val positions: env -> Lexing.position * Lexing.position
\end{verbatim}

The function \verb+positions+ returns the start and end positions of the
current lookahead token. It is legal to invoke this function only after at
least one token has been offered to the parser via \verb+offer+. In other
words, it is illegal to invoke it in an initial state.

% ------------------------------------------------------------------------------

\subsection{Inspection API}
\label{sec:inspection}
2217

2218
If \oinspection is set, \menhir offers an inspection API in addition to the
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
monolithic and incremental APIs. Like the incremental API, the inspection API
is found in the sub-module \menhirinterpreter. It offers the following types
and functions.

%% type _ terminal

The type \verb+'a terminal+ is a generalized algebraic data type (GADT). A
value of type \verb+'a terminal+ represents a terminal symbol (without a
semantic value). The index \verb+'a+ is the type of the semantic values
associated with this symbol. For instance, if the grammar contains the
declarations \verb+%token A+ and \verb+%token<int> B+, then the generated
module \menhirinterpreter contains the following definition:
%
\begin{verbatim}
  type _ terminal =
  | T_A : unit terminal
  | T_B : int terminal
\end{verbatim}
%
The data constructors are named after the terminal symbols, prefixed with ``\verb+T_+''.

%% type _ nonterminal

The type \verb+'a nonterminal+ is also a GADT. A value of type
\verb+'a nonterminal+ represents a nonterminal symbol (without a semantic value). The
index \verb+'a+ is the type of the semantic values associated with this
symbol. For instance, if \verb+main+ is the only nonterminal symbol,
then the generated
module \menhirinterpreter contains the following definition:
%
\begin{verbatim}
  type _ nonterminal =
  | N_main : thing nonterminal
\end{verbatim}
%
The data constructors are named after the nonterminal symbols, prefixed with ``\verb+N_+''.

%% type 'a symbol

The type \verb+'a symbol+
% (an algebraic data type)
is the disjoint union of the types \verb+'a terminal+ and \verb+'a nonterminal+.
In other words, a value of type \verb+'a symbol+ represents a terminal or nonterminal symbol (without
a semantic value).
This type is (always) defined as follows:
%
\begin{verbatim}
  type 'a symbol =
    | T : 'a terminal -> 'a symbol
    | N : 'a nonterminal -> 'a symbol
\end{verbatim}

%% type xsymbol

The type \verb+xsymbol+ is an existentially quantified version of the
type \verb+'a symbol+. It is useful in situations where the index \verb+'a+ is
not statically known. It is (always) defined as follows:
%
\begin{verbatim}
  type xsymbol = 
    | X : 'a symbol -> xsymbol
\end{verbatim}

%% type item

The type \verb+item+ describes an LR(0) item, that is, a pair of a production
\verb+prod+ and an index \verb+i+ into the right-hand side of this production.
If the length of the right-hand side is \verb+n+, then \verb+i+ is
comprised between 0 and \verb+n+, inclusive.

\begin{verbatim}
  type item =
      production * int
\end{verbatim}

%% Comparison functions.

The following functions implement total orderings on the types
\verb+_ terminal+, \verb+_ nonterminal+, \verb+xsymbol+,
\verb+production+, and \verb+item+.

\begin{verbatim}
  val compare_terminals: _ terminal -> _ terminal -> int
  val compare_nonterminals: _ nonterminal -> _ nonterminal -> int
  val compare_symbols: xsymbol -> xsymbol -> int
  val compare_productions: production -> production -> int
  val compare_items: item -> item -> int
\end{verbatim}

%% val incoming_symbol

The function \verb+incoming_symbol+ maps a (non-initial) LR(1)
state~\verb+s+ to its incoming symbol, that is, the symbol that the parser
must recognize before it enters the state \verb+s+.
%
\begin{verbatim}
  val incoming_symbol: 'a lr1state -> 'a symbol
\end{verbatim}
%
This function can be used to gain access to the semantic value \verb+v+
in a stack element \verb+Element (s, v, _, _)+. Indeed, by case analysis on the
symbol \verb+incoming_symbol s+, one gains information about the type \verb+'a+,
hence one obtains the ability to do something useful with the value~\verb+v+.

%% val items

The function \verb+items+ maps a (non-initial) LR(1) state~\verb+s+ to its
LR(0) \emph{core}, that is, to the underlying set of LR(0) items. This set
is represented as a list, whose elements appear in an arbitrary order. This
set is \emph{not} closed under $\epsilon$-transitions.
%
\begin{verbatim}
  val items: _ lr1state -> item list
\end{verbatim}

%% val lhs
%% val rhs

The functions \verb+lhs+ and \verb+rhs+ map a production \verb+prod+ to
its left-hand side and right-hand side, respectively. The left-hand side
is always a nonterminal symbol, hence always of the form \verb+N _+. The
right-hand side is a (possibly empty) sequence of (terminal or nonterminal)
symbols.
%
\begin{verbatim}
  val lhs: production -> xsymbol
  val rhs: production -> xsymbol list
\end{verbatim}
%

%% val nullable

The function \verb+nullable+, applied to a non-terminal symbol,
tells whether this symbol is nullable. A nonterminal symbol is nullable if and
only if it produces the empty word $\epsilon$.
%
\begin{verbatim}
  val nullable: _ nonterminal -> bool
\end{verbatim}

%% val first
%% val xfirst

The function call \verb+first nt t+ tells whether the \emph{FIRST} set of the
nonterminal symbol \verb+nt+ contains the terminal symbol \verb+t+. That is,
it returns \verb+true+ if and only if \verb+nt+ produces a word that begins
with \verb+t+. The function \verb+xfirst+ is identical to \verb+first+, except
it expects a first argument of type \verb+xsymbol+ instead of \verb+_ terminal+.
%
\begin{verbatim}
  val first: _ nonterminal -> _ terminal -> bool
  val xfirst: xsymbol -> _ terminal -> bool
\end{verbatim}

%% val foreach_terminal
%% val foreach_terminal_but_error

The function \verb+foreach_terminal+ enumerates the terminal symbols, including the special symbol \error.
The function \verb+foreach_terminal_but_error+ enumerates the terminal symbols, excluding \error.
\begin{verbatim}
  val foreach_terminal:           (xsymbol -> 'a -> 'a) -> 'a -> 'a
  val foreach_terminal_but_error: (xsymbol -> 'a -> 'a) -> 'a -> 'a
\end{verbatim}
2382

2383
% TEMPORARY
2384
% document the modules that use the inspection API: Printers, ErrorReporting
2385
% document MenhirLib.General?
2386
% The directory \distrib{demos/calc-inspection} contains a demo that illustrates the use of the inspection API.
2387
% review it / clean it up!
2388

2389 2390
% ---------------------------------------------------------------------------------------------------------------------

2391 2392 2393
\section{Coq back-end}
\label{sec:coq}

POTTIER Francois's avatar
POTTIER Francois committed
2394 2395 2396
\menhir is able to generate a parser that whose correctness can be formally
verified using the Coq proof assistant~\cite{jourdan-leroy-pottier-12}. This
feature is used to construct the parser of the CompCert certified C
2397 2398
compiler~\cite{compcert}.

POTTIER Francois's avatar
POTTIER Francois committed
2399 2400
Setting the \ocoq switch on the command line enables the Coq back-end.  When
this switch is set, \menhir expects an input file whose name ends
2401
in \texttt{.vy} and generates a Coq file whose name ends
POTTIER Francois's avatar
POTTIER Francois committed
2402
in \texttt{.v}.
2403

POTTIER Francois's avatar
POTTIER Francois committed
2404
Like a \texttt{.mly} file, a \texttt{.vy} file is a grammar specification,
2405
with embedded semantic actions. The only difference is that the semantic
POTTIER Francois's avatar
POTTIER Francois committed
2406 2407
actions in a \texttt{.vy} file are expressed in Coq instead
of \ocaml. A \texttt{.vy} file otherwise uses the same syntax as
2408 2409 2410 2411 2412
a \texttt{.mly} file. CompCert's
\href{https://github.com/AbsInt/CompCert/tree/master/cparser/Parser.vy}{\texttt{Parser.vy}}
serves as an example.

Several restrictions are imposed when \menhir is used in \ocoq mode:
POTTIER Francois's avatar
POTTIER Francois committed
2413
%
2414
\begin{itemize}
POTTIER Francois's avatar
POTTIER Francois committed
2415 2416 2417 2418 2419 2420 2421
\item The error handling mechanism (\sref{sec:errors}) is absent.
      The \verb+$syntaxerror+ keyword and the \error token are not supported.
\item Location information is not propagated. The \verb+$start*+ and \verb+$end*+
      keywords (\fref{fig:pos}) are not supported.
\item \dparameter (\sref{sec:parameter}) is not supported.
\item \dinline (\sref{sec:inline}) is not supported.
\item The standard library (\sref{sec:library}) is not supported, of course,
2422
      because its semantic actions are expressed in \ocaml. If desired, the user can define
POTTIER Francois's avatar
POTTIER Francois committed
2423 2424 2425 2426
      an analogous library, whose semantic actions are expressed in Coq.
\item Because Coq's type inference algorithm is rather unpredictable,
      the Coq type of every nonterminal symbol must be provided via a
      \dtype or \dstart declaration (\sref{sec:type}, \sref{sec:start}).
2427 2428 2429
\item Unless the proof of completeness has been deactivated using
  \ocoqnocomplete, the grammar must not have a conflict
  (not even a benign one, in the sense of \sref{sec:conflicts:benign}).
POTTIER Francois's avatar
POTTIER Francois committed
2430 2431 2432 2433
  That is, the grammar must be LR(1). Conflict resolution via
  priority and associativity declarations (\sref{sec:assoc})
  is not supported.
  The reason is that there is no simple formal specification
2434 2435 2436 2437 2438 2439
  of how conflict resolution should work.
\end{itemize}

The generated file contains several modules:

\begin{itemize}
POTTIER Francois's avatar
POTTIER Francois committed
2440 2441 2442 2443 2444
\item The module \verb+Gram+ defines the terminal and
  non-terminal symbols, the grammar, and the semantic actions.
\item The module \verb+Aut+ contains the automaton
  generated by \menhir, together with a certificate that is checked by Coq
  while establishing the soundness and completeness of the parser.
2445 2446
\end{itemize}

2447 2448 2449 2450 2451
The type of the terminal symbols is an inductive type, with one constructor
for each terminal symbol. A~terminal symbol per se does not carry a the
semantic value. We also define the type \verb+token+ of tokens, i.e.,
dependent pairs of a terminal symbol and a semantic value of an appropriate
type for this symbol. We model the lexer as an object of type
2452
\verb+Streams.Stream token+, i.e., an infinite stream of tokens.
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464

The proof of termination of an LR(1) parser in the case of invalid input seems
far from obvious. We did not find such a proof in the literature. In an
application such as CompCert~\cite{compcert}, this question is not considered
crucial. For this reason, we did not formally establish the termination of the
parser. Instead, we use the ``fuel'' technique. The parser takes an additional
parameter of type \verb+nat+ that indicates the maximum number of steps the
parser is allowed to perform. In practice, after extracting the code to
\ocaml, one can use the standard trick of passing an infinite amount of fuel,
defined in \ocaml by \verb+let rec inf = S inf+.

Parsing can have three different outcomes, represented by the type
2465 2466 2467 2468
\verb+parse_result+.
%
(This definition is implicitly parameterized over the initial
state~\verb+init+. We omit the details here.)
2469
%
2470
\begin{verbatim}
2471 2472 2473 2474 2475 2476 2477
  Inductive parse_result :=
  | Fail_pr:    parse_result
  | Timeout_pr: parse_result
  | Parsed_pr:
      symbol_semantic_type (NT (start_nt init)) ->
      Stream token ->
      parse_result.
2478 2479
\end{verbatim}

2480 2481 2482 2483 2484 2485 2486 2487 2488
The outcome \verb+Fail_pr+ means that parsing has failed because of a syntax
error. (If the completeness of the parser with respect to the grammar has been
proved, this implies that the input is invalid). The outcome \verb+Timeout_pr+
means that the fuel has been exhausted. Of course, this cannot happen if the
parser was given an infinite amount of fuel, as suggested above. The outcome
\verb+Parsed_pr+ means that the parser has succeeded in parsing a prefix of
the input stream. It carries the semantic value that has been constructed for
this prefix, as well as the remainder of the input stream.

2489
For each entry point \verb+entry+ of the grammar, \menhir generates a
2490
parsing function \verb+entry+, whose type is
2491
\verb+nat -> Stream token -> parse_result+.
POTTIER Francois's avatar