Debian Codegraph @

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

raw
1 %!TEX root = manual.tex
2 %
3 \chapter{ML-ULex}
4
5 %\section{Overview}
6
7 Lexers analyze the lexical structure of an input string, and are usually specified using regular expressions. \textsc{ml-ulex} is a lexer generator for Standard ML. The module it generates will contain a type \texttt{strm} and a function
8 \begin{verbatim}
9 val lex : AntlrStreamPos.sourcemap -> strm
10 -> lex_result * AntlrStreamPos.span * strm
11 \end{verbatim}%
12 where \texttt{lex\char`\_result} is a type that must be defined by the user of \ulex{}.
13 Note that the lexer always returns a token: we assume that end-of-file will be explicitly represented by a token.
14 Compared to ML-Lex, \ulex{} offers the following improvements:
15 \begin{itemize}
16 \item Unicode is supported under the UTF8 encoding.
17 \item Regular expressions can include intersection and negation operators.
18 \item The position span of a token is automatically computed and returned to the lexer's caller (as can be seen
19 by the specification of the \texttt{lex} function above).
20 \item The specification format is somewhat cleaner.
21 \item The code base is much cleaner, and supports multiple back-ends, including DFA graph visualization and interactive testing of rules.
22 \end{itemize}%
23 The tool is invoked from the command-line as follows:
24 \begin{verbatim}
25 ml-ulex [options] file
26 \end{verbatim}%
27 where \texttt{file} is the name of the input \ulex{} specification, and where \texttt{options} may be any combination of:
28
29 \vskip 12pt
30 \begin{tabular}{lp{0.65\textwidth}}
31 \texttt{--dot} & generate DOT output (for graphviz; see \texttt{http://www.graphviz.org}). The produced file will be named \texttt{file.dot}, where \texttt{file} is the input file. \\
32 \\
33 \texttt{--match} & enter interactive matching mode. This will allow interactive testing of the machine; presently, only the \texttt{INITIAL} start state is available for testing
34 (see Section~\ref{sec:start-states} for details on start states). \\
35 \\
36 \texttt{--ml-lex-mode} & operate in \texttt{ml-lex} compatibility mode. See Section~\ref{sec:lex-compat} for details. \\
37 \\
38 \texttt{--table-based} & generate a table-based lexer.\\
39 \\
40 \texttt{--fn-based} & generate a lexer that represents states as functions and transitions as tail calls.\\
41 \\
42 \texttt{--minimize} & generate a minimal machine. Note that this is slow, and is almost never necessary. \\
43 \\
44 \texttt{--strict-sml} & generate strict SML (\ie{}, do not use SML/NJ extensions). This flag
45 is useful if you want to use the output with a different SML system.
46 \end{tabular}
47
48 \vskip 10pt \noindent
49 The output file will be called \texttt{file.sml}.
50
51 \section{Specification format}
52
53 A \ulex{} specification is a list of semicolon-terminated \emph{declarations}. Each declaration is either a \emph{directive} or a \emph{rule}. Directives are used to alter global specification properties (such as the name of the module that will be generated) or to define named regular expressions. Rules specify the actual reguluar expressions to be matched. The grammar is given in Figure~\ref{fig:ulex-syntax}.
54
55 \begin{figure}
56 \Grammar{
57 \GFirstB{spec}
58 {$($ declaration \T{;} $)^*$}
59
60 \GFirstB{declaration}
61 {directive}
62 \GNextB
63 {rule}
64
65 % {\kw{charset} $($ \T{ASCII7} $|$ \T{ASCII8} $|$ \T{UTF8} $)$}
66
67 \GFirstB{directive}
68 {\kw{arg} code}
69 \GNextB
70 {\kw{defs} code}
71 \GNextB
72 {\kw{let} ID \T{=} re}
73 \GNextB
74 {\kw{name} ID}
75 \GNextB
76 {\kw{header} code}
77 \GNextB
78 {\kw{states} ID$^+$}
79
80 \GFirstB{code}
81 { \T{(} $\dots$ \T{)} }
82
83 \GFirstB{rule}
84 { $($\T{<} ID $($ \T{,} ID $)^*$ \T{>}$)^?$ re \T{=>} code}
85 \GNextB
86 { $($\T{<} ID $($ \T{,} ID $)^*$ \T{>}$)^?$ \T{<<EOF>>} \T{=>} code}
87
88 \GFirstB{re}
89 {CHAR}
90 \GNextB
91 {\T{"} SCHAR$^*$ \T{"}}
92 \GNextB
93 {\T{(} re \T{)}}
94 \GNextCC
95 {\T{[} $($ \T{-} $|$ \T{\^{ }} $)^?$ $($ CCHAR \T{-} CCHAR $|$ CCHAR $)^+$
96 \T{-}$^?$ \T{]} \quad\phantom{.}}
97 {a character class}
98 \GNextC
99 {\T{\{} ID \T{\}}} {\kw{let}-bound RE}
100 \GNextC
101 {\T{.}} {wildcard (any single character including \texttt{{$\backslash$}n})}
102 \GNextC
103 {re \T{*}} {Kleene-closure (0 or more)}
104 \GNextC
105 {re \T{?}} {optional (0 or 1)}
106 \GNextC
107 {re \T{+}} {positive-closure (1 or more)}
108 \GNextC
109 {re \T{\{} NUM \T{\}}} {exactly {\it NUM} repetitions}
110 \GNextC
111 {re \T{\{} NUM$_1$, \ NUM$_2$ \T{\}}} {between {\it NUM$_1$} and {\it NUM$_2$} repetitions}
112 \GNextC
113 {re re} {concatenation}
114 \GNextC
115 {\T{$\sim$} re} {negation} %(any string not matched by \textit{re})}
116 \GNextC
117 {re \T{\&} re} {intersection}
118 \GNextC
119 {re \T{|} re} {union}
120 %\GNextB
121 % {re \T{/} re}
122 %\GNextB
123 % {re \T{\$}}
124 %\GNextB
125 % {\T{\_}}
126 \GFirstB{CHAR}
127 {any printable character not one of \
128 $\begin{array}[t]{l}
129 \normalfont
130 \texttt{\^{ } < > $\backslash$ ( ) \{ \} [ \& | * ?}\\
131 \normalfont
132 \texttt{+ " . ; = $\sim$ }
133 \end{array}$}
134 \GNextB{an SML or Unicode escape code}
135 \GFirstB{CCHAR}
136 {any printable character not one of \ \T{\^{ } - ] $\backslash$}}
137 \GNextB{an SML or Unicode escape code}
138 \GFirstB{SCHAR}
139 {any printable character not one of \ \T{" $\backslash$}}
140 \GNextB{an SML or Unicode escape code}
141 \GFirstB{NUM}
142 {one or more digits}
143 }
144 \caption{The \ulex{} grammar}\label{fig:ulex-syntax}
145 \end{figure}
146
147 There are a few lexical details of the specification format worth mentioning. First, SML-style comments (\texttt{(* ... *)}) are treated as ignored whitespace anywhere they occur in the specification, \emph{except} in segments of code. The \textit{ID} symbol used in the grammar stands for alpha-numeric-underscore identifiers, starting with an alpha character. The \textit{code} symbol represents a segment of SML code, enclosed in parentheses. Extra parentheses occuring within strings or comments in code need not be balanced.
148
149 A complete example specification appears in Chapter~\ref{ch:example}.
150
151 \section{Directives}
152
153 \subsection{The \kw{arg} directive}
154
155 Specifies an additional curried parameter, appearing after the sourcemap parameter, that will be passed into the \texttt{lex} function and made available to all lexer actions.
156
157 \subsection{The \kw{defs} directive}
158
159 The \kw{defs} directive is used to include a segment of code in the generated lexer module, as in the following example:
160 \begin{lstlisting}
161 %defs (
162 type lex_result = CalcParseToks.token
163 fun eof() = CalcParseTokens.EOF
164 fun helperFn x = (* ... *)
165 )
166 \end{lstlisting}
167 The definitions must at least fulfill the following signature:
168 \begin{lstlisting}
169 type lex_result
170 val eof : unit -> lex_result
171 \end{lstlisting}
172 unless EOF rules are specified, in which case only the \texttt{lex\char`\_result} type is needed~(see Section~\ref{sec:eof-rules}).
173 All semantic actions must yield values of type \texttt{lex\char`\_result}. The \texttt{eof} function is called by \ulex{} when the end of file is reached -- it acts as the semantic action for the empty input string. All definitions given will be in scope for the rule actions (see Section~\ref{sec:ulex-rules}).
174
175 \subsection{The \kw{let} directive}
176
177 Use \kw{let} to define named abbreviations for regular expressions; once bound, an abbreviation can be used in further \kw{let}-bindings or in rules. For example,
178 \begin{verbatim}
179 %let digit = [0-9];
180 \end{verbatim}
181 introduces an abbreviation for a regular expression matching a single digit. To use abbreviations, enclose their name in curly braces. For example, an additional \kw{let} definition can be given in terms of \texttt{digit},
182 \begin{verbatim}
183 %let int = {digit}+;
184 \end{verbatim}
185 which matches arbitrary-length integers. Note that scoping of let-bindings follows standard SML rules, so that the definition of \texttt{int} must appear after the definition of \texttt{digit}.
186
187 \subsection{The \kw{name} directive}
188
189 The name to use for the generated lexer module is specified using \kw{name}.
190
191 \subsection{The \kw{header} directive}
192 The \kw{header} directive allows one to specify the lexer's header.
193 This directive is useful when you want to use a functor for the lexer.
194 For example,
195 \begin{lstlisting}
196 %header (functor ExampleLexFn (Extras : EXTRA_SIG));
197 \end{lstlisting}%
198 Note that it is an error to include both the \kw{header} and \kw{name} directive in the
199 same lexer specification.
200
201 \subsection{The \kw{states} directive}
202 \label{sec:start-states}
203
204 It is often helpful for a lexer to have multiple \emph{start states}, which influence
205 the regular expressions that the lexer will match.
206 For instance, after seeing a double-quote, the lexer might switch into a \texttt{STRING}
207 start state that contains only the rules necessary for matching strings, and which
208 returns to the standard start state after the closing quote.
209
210 Start states are introduced via \kw{states} and are named using standard identifiers.
211 There is always an implicit, default start state called \texttt{INITIAL}.
212 Within a rule action, the function \texttt{YYBEGIN} can be applied to the name
213 of a start state to switch the lexer into that state; see~\ref{sec:ulex-actions}
214 for details on rule actions.
215
216 Using start states allows the lexer to be defined as a collection of finite-state machines
217 (one per start state), with arbitrary SML code used to control switching between machines.
218 This mechanism thus allows non-regular features to be supported by the lexer, such as
219 nested comments.
220
221 \section{Rules}\label{sec:ulex-rules}
222
223 In general, when \texttt{lex} is applied to an input stream, it will attempt to match a prefix of the input with a regular expression given in one of the rules. When a rule is matched, its \emph{action} (associated code) is evaluated and the result is returned. Hence, all actions must belong to the same type. %, but no restrictions are placed on what that type is.
224 Rules are specified by an optional list of start states, a regular expression, and the action code. The rule is said to ``belong'' to the start states it lists. If no start states are specified, the rule belongs to \emph{all} defined start states.
225
226 Rule matching is determined by three factors: start state, match length, and rule order. A rule is only considered for matching if it belongs to the lexer's current start state. If multiple rules match an input prefix, the rule matching the longest prefix is selected. In the case of a tie, the rule appearing first in the specification is selected.
227
228 For example, suppose the start state \texttt{FOO} is defined, and the following rules appear, with no other rules belonging to \texttt{FOO}:
229 \begin{verbatim}
230 <FOO> a+ => ( Tokens.as );
231 <FOO> a+b+ => ( Tokens.asbs );
232 <FOO> a+bb* => ( Tokens.asbs );
233 \end{verbatim}
234 If the current start state is not \texttt{FOO}, none of the rules will be considered. Otherwise, on input ``aabbbc'' all three rules are possible matches. The first rule is discarded, since the others match a longer prefix. The second rule is then selected, because it matches the same prefix as the third rule, but appears earlier in the specification.
235
236 \subsection{Regular expression syntax}
237
238 \newcommand{\REX}{\textit{re}}
239 \begin{figure}
240 \begin{minipage}[t]{.5\textwidth}
241 \begin{eqnarray*}
242 \sem{\T{.}} &=& \Sigma \\
243 \sem{\REX_1 \ \REX_2} &=& \sem{\REX_1} \cdot \sem{\REX_2} \\
244 \sem{\T{$\sim$} \ \REX} &=& \left(\bigcup_{i=0}^\infty \Sigma^i\right)\setminus \sem{\REX} \\
245 \sem{\REX_1 \ \T{\&} \ \REX_2} &=& \sem{\REX_1} \cap \sem{\REX_2} \\
246 \sem{\REX_1 \ \T{|} \ \REX_2} &=& \sem{\REX_1} \cup \sem{\REX_2} \\
247 \sem{\REX \ \T{?}} &=& \sem{\REX} \cup \{ \epsilon \}
248 \end{eqnarray*}
249 \end{minipage}\begin{minipage}[t]{.5\textwidth}
250 \begin{eqnarray*}
251 \sem{\REX \ \T{*}} &=& \bigcup_{i=0}^\infty \sem{\REX}^i \\
252 \sem{\REX \ \T{+}} &=& \bigcup_{i=1}^\infty \sem{\REX}^i \\
253 \sem{\REX \ \T{\{} n \T{\}}} &=& \sem{\REX}^n \\
254 \sem{\REX \ \T{\{} n \T{, } m \T{\}}} &=& \bigcup_{i=n}^m \sem{\REX}^i
255 \end{eqnarray*}
256 \end{minipage}
257 \caption{Semantics for regular expressions}\label{ulex-re-semantics}
258 \end{figure}
259
260 The syntax of regular expressions is given in Figure~\ref{fig:ulex-syntax}; constructs are listed in precedence order, from most tightly-binding to least. Escape codes are the same as in SML, but also include \texttt{$\backslash$uxxxx} and \texttt{$\backslash$Uxxxxxxxx}, where \texttt{xxxx} represents a hexidecimal number which in turn represents a Unicode symbol. The specification format itself freely accepts Unicode characters, and they may be used within a quoted string, or by themselves.
261
262 The semantics for \ulex{} regular expressions are shown in Figure~\ref{ulex-re-semantics}; they are standard. Some examples:
263 \[
264 \begin{array}{rcl}
265 \texttt{0 | 1 | 2 | 3} & \textit{denotes} &
266 \{ \texttt{0}, \texttt{1}, \texttt{2}, \texttt{3} \} \\
267 \texttt{[0123]} & \textit{denotes} &
268 \{ \texttt{0}, \texttt{1}, \texttt{2}, \texttt{3} \} \\
269 \texttt{0123} & \textit{denotes} &
270 \{ \texttt{0123} \} \\
271 \texttt{0*} & \textit{denotes} &
272 \{ \epsilon, \texttt{0}, \texttt{00}, \dots \} \\
273 \texttt{00*} & \textit{denotes} &
274 \{ \texttt{0}, \texttt{00}, \dots \} \\
275 \texttt{0+} & \textit{denotes} &
276 \{ \texttt{0}, \texttt{00}, \dots \} \\
277 \texttt{[0-9]\{3\}} & \textit{denotes} &
278 \{ \texttt{000}, \texttt{001}, \texttt{002}, \dots, \texttt{999} \} \\
279 \texttt{0* \& (..)*} & \textit{denotes} &
280 \{ \epsilon, \texttt{00}, \texttt{0000}, \dots \} \\
281 \texttt{\^{ }(abc)} & \textit{denotes} &
282 \Sigma^* \setminus \{ \texttt{abc} \} \\
283 \texttt{[\^{ }abc]} & \textit{denotes} &
284 \Sigma \setminus \{ \texttt{a}, \texttt{b}, \texttt{c} \}
285 \end{array}
286 \]
287
288 \subsection{EOF rules}\label{sec:eof-rules}
289
290 It is sometimes useful for the behavior of a lexer when it reaches the end-of-file to change
291 depending on the current start state.
292 Normally, there is a single user-defined \texttt{eof} function that defines EOF behavior, but
293 EOF rules can be used to be more selective, as in the following example:
294 \begin{verbatim}
295 <INITIAL> <<EOF>> => ( Tok.EOF );
296 <COMMENT> <<EOF>> => ( print "Error: unclosed comment";
297 Tok.EOF );
298 \end{verbatim}
299 Other than the special \T{<<EOF>>} symbol, EOF rules work exactly like normal rules.
300
301 Note that if you define any EOF rules, then you must define EOF rules for all states;
302 otherwise, your scanner may generate a \texttt{Match} exception on EOF.
303 Furthermore, if you define EOF rules, you do not need a definition of the \texttt{eof}
304 function.
305
306 \subsection{Actions}\label{sec:ulex-actions}
307
308 \newcommand{\itemtt}[2]{\item[{\normalfont\textbf{\texttt{val}} \texttt{#1} \texttt{:} \texttt{#2}}]\mbox{}\\}
309
310 Actions are arbitrary SML code enclosed in parentheses. The following names are in scope:
311 \begin{description}
312 \itemtt{YYBEGIN}{yystart\char`\_state -> unit}
313 This function changes the start state to its argument.
314 \itemtt{yysetStrm}{ULexBuffer.stream -> unit}
315 This function changes the current input source to its argument.
316 The functions \texttt{yystreamify}, \texttt{yystreamifyInstream} and \texttt{yystreamifyReader}
317 can be used to construct the stream; they work identically to the corresponding functions
318 described in Section~\ref{sec:ulex-code}
319 \itemtt{yytext}{string}
320 The matched text as a string.
321 \itemtt{yysubstr}{substring}
322 The matched text as a substring (avoids copying).
323 \itemtt{yyunicode}{UTF8.wchar list}
324 The matched text as a list of Unicode wide characters (\ie{}, words).
325 \itemtt{continue}{unit -> lex\char`\_result}
326 This function recursively calls the lexer on the input following the matched prefix, and returns its result.
327 The span for the resulting token begins at the left border of the match that calls \texttt{continue}.
328 \itemtt{skip}{unit -> lex\char`\_result}
329 This function is identical to \texttt{continue}, except that it moves forward the left marker
330 for the span of the returned token.
331 For example, \texttt{skip} can be used to skip preceding whitespace.
332 \itemtt{yysm}{AntlrSourcePos.sourcemap}
333 the sourcemap for the lexer, to be used with the functions in the \texttt{AntlrSourcePos} module.
334 \itemtt{yypos}{int}
335 the input character position of the left border of the matched RE, starting from 0.
336 \itemtt{yylineno}{int}
337 The current line number, starting from 1.
338 Note that lines are counted using the Unix line-ending convention.
339 \itemtt{yycolno}{int}
340 The current column number, starting from 1.
341 \end{description}%
342 Futhermore, any name bound in the \kw{\%defs} section is in scope in the actions.
343
344 \section{Using the generated code}\label{sec:ulex-code}
345
346 The generated lexer module has a signature that includes the following specifications:
347 \begin{lstlisting}
348 type prestrm
349 type strm = prestrm * start_state
350
351 val streamify : (unit -> string) -> strm
352 val streamifyReader : (char, 'a) StringCvt.reader -> 'a -> strm
353 val streamifyInstream : TextIO.instream -> strm
354
355 val lex : AntlrStreamPos.sourcemap -> strm
356 -> lex_result * AntlrStreamPos.span * strm
357 \end{lstlisting}%
358 where \texttt{lex\char`\_result} is the result type of the lexer actions, and \texttt{start\char`\_state} is an algebraic datatype with nullary constructors for each defined start state.
359 Note that \texttt{lex\char`\_result} must be defined as a type using the \kw{defs} directive.
360 In this interface, lexer start states are conceptually part of the input stream; thus, from an external viewpoint,
361 start states can be ignored.
362 It is, however, sometimes helpful to control the lexer start state externally, allowing contextual
363 information to influence the lexer.
364 This is why the \texttt{strm} type includes a concrete \texttt{start\char`\_state} component.
365
366 Note that the \texttt{AntlrStreamPos} module is part of the \texttt{ml-lpt-lib} library described in Chapter~\ref{ch:ml-lpt-lib}.
367 An \texttt{AntlrStreamPos.sourcemap} value, combined with an \texttt{AntlrStreamPos.pos} value, compactly represents position information (line number, column number, and so on).
368 An \texttt{AntlrStreamPos.span} is a pair of \texttt{pos} values that specify the character position of the
369 leftmost (first) character of the scanned token and the position of the
370 rightmost (last) character in the token (respectively).
371 By default, the span will cover the entire sequence of characters consumed by a call to the lexer, but one may
372 use the \texttt{skip} function (see Section~\ref{sec:ulex-actions}) to ignore leading whitespace,
373 \textit{etc.}\ when computing the span.
374 Code to compute the span is generated automatically by \texttt{ml-ulex}.
375
376 \section{\texttt{ml-lex} compatibility}\label{sec:lex-compat}
377
378 Running \ulex{} with the \texttt{--ml-lex-mode} option will cause it to process its input file using the ML-Lex format, and interpret the actions in a ML-Lex-compatible way. The compatibility extends to the bugs in ML-Lex, so in particular \texttt{yylineno} starts at 2 in \texttt{--ml-lex-mode}.