Debian Codegraph @

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

raw
1 \chapter[\ulex]{Implementation: \ulex}
2
3 \section{Organization}
4
5 %\ulex{} is a scanner generator written in Standard ML. It replaces the older
6 %ML-Lex tool. For information about features and usage, see the \ulex{}
7 %Release Notes. This document describes the algorithms and code that make up
8 %\ulex{}.
9
10 \ulex{} is organized much like a compiler: there is a replacable front end for
11 parsing the ML-Lex specification format, several back ends to support various
12 output formats, and a middle component responsible for DFA generation. The
13 \nm{Main} module drives the tool, while the \nm{RegExp} and \nm{LexGen} modules
14 together provide DFA generation (see figure~\ref{fig:ml-flex}). The DFA
15 generation algorithm used in \ulex{} is somewhat nonstandard; it is based on
16 Brzozowski's notion of regular expression derivatives~\cite{derivatives}.
17 Chapter~\ref{ch:ulex-theory} describes the algorithm, as well as modifications
18 necessary to support unicode. This chapter gives more concrete
19 details about the code, broken down by module.
20
21 \begin{figure}\label{fig:ml-flex}
22 \begin{center}
23 \ifpdf
24 \includegraphics[scale=0.8]{impl-pic.pdf}
25 \fi
26 \end{center}
27 \caption{\ulex{} organization}
28 \end{figure}
29
30 \section{\nm{RegExp}}\label{sec:reg-exp}
31
32 In \ulex{}, REs are captured by the abstract type \nm{RegExp.re}. Introduction
33 is provided by various ``smart constructors'' (\nm{mkSym}, \nm{mkClosure},
34 $\dots$), and elimination is provided by the derivatives algorithm. The
35 signature for the \rm{RegExp} module is shown below:
36
37 \begin{verbatim}
38 signature REG_EXP =
39 sig
40
41 structure Sym : INTERVAL_DOMAIN
42 structure SymSet : INTERVAL_SET
43
44 type symbol
45 type sym_set
46 type re
47
48 val any : re (* wildcard *)
49 val none : re (* EMPTY language *)
50 val epsilon : re (* the nil character (of length 0) *)
51
52 val mkSym : symbol -> re
53 val mkSymSet : sym_set -> re
54
55 val mkOr : re * re -> re
56 val mkAnd : re * re -> re
57 val mkXor : re * re -> re
58 val mkNot : re -> re
59 val mkConcat : re * re -> re
60 val mkClosure : re -> re
61 val mkOpt : re -> re
62 val mkRep : re * int * int -> re
63 val mkAtLeast : re * int -> re
64
65 val isNone : re -> bool
66 val nullable : re -> bool
67 val derivative : symbol -> re -> re
68 val derivatives : re Vector.vector ->
69 ((re Vector.vector) * sym_set) list
70
71 val symToString : symbol -> string
72 val toString : re -> string
73 val compare : re * re -> order
74
75 end
76 \end{verbatim}
77
78 The included structure \nm{SymSet} provides symbol interval sets, which are
79 ideal when working with dense sets such as unicode character classes. Interval
80 set operations (\nm{union}, \nm{complement}, $\dots$) are used extensively;
81 documentation for the interval set library is available with the SML/NJ
82 distribution.
83
84 Recall that, in using RE derivatives for DFA construction, it is
85 important to aggresively identify when two REs generate the same
86 language so that they may be merged to a single state in the automaton.
87 \nm{RegExp} canonicalizes REs, which is why its \nm{re} type is abstract.
88 Canonicalization is performed using a lexicographic ordering on REs given by the
89 \nm{compare} function. The comparison is lexicographic in the sense that it
90 first examines the top-level operation of the two REs, and only does more
91 comparisons if that operation is the same. We represent REs as follows:
92 \begin{verbatim}
93 datatype re
94 = Epsilon
95 | Any
96 | None
97 | SymSet of sym_set
98 | Concat of re list
99 | Closure of re
100 | Op of (rator * re list)
101 | Not of re
102 and rator = OR | AND | XOR
103 \end{verbatim}
104 For the \nm{Op} constructor, which is used for three different commutative
105 operations, the sub-REs are to be listed in canonical order. The \nm{compare}
106 function itself will expect that this is the case, and since only smart
107 constructors can be used to construct REs, the invariant will always hold.
108
109 Smart constructors do additional canonicalization beyond ordering. For
110 example, \nm{mkNot (mkNot (none))} will be canonicalized
111 to the same representation as \nm{none}. Several similar RE equalities
112 are detected and used. Also, the smart constructors attempt to push the RE
113 reprsentation as much toward symbol sets as possible, replacing boolean
114 operations at the RE level with a single resulting symbol set when possible.
115 For example, suppose that \nm{AM} held the symbol set for $[A-M]$, \nm{HZ} the
116 set for $[H-Z]$, and \nm{AZ} the set for $[A-Z]$. Then we would have
117 \[
118 \texttt{compare (mkSymSet AZ, mkOr (mkSymSet AM, mkSymSet HZ)) = EQUAL}
119 \]
120 The hope is that the cumulative effect of such canonicalization will keep the
121 generated DFA close to minimal size.
122
123 The \nm{derivatve} function constructs a canonicalized derivative for a given
124 RE with respect to a given symbol; it is a transcription of the algorithm
125 described in section~\ref{sec:derivatives}.
126
127 In general, we will be interested in the derivatives of a vector of REs
128 (representing the rules in a lexer specification) with respect to \emph{every}
129 symbol in the alphabet. As section~\ref{sec:factorings} explains, the unicode
130 alphabet is too large for us to literally test the derivative at each symbol.
131 The \nm{derivatives} function will take a vector of REs and return a list of
132 \nm{re~Vector.vector~*~sym\_set} \emph{pairs}. In fact, \nm{derivatives}
133 is just an implementation of the factor and compress algorithm given
134 in~\ref{sec:factorings}. Each pair in the result list represents an arrow
135 transitioning out of the current state (which corresponds to the input RE
136 vector) to a new state (the output RE vector) on a given set of symbols (the
137 output symbol set). Thus the labor of DFA construction is split between the
138 \nm{RegExp} module, which computes derivatives (and hence transitions) and
139 \nm{LexGen}, which actually constructs the DFA graph.
140
141 \section{\nm{LexSpec} and \nm{LexOutputSpec}}
142
143 Before describing DFA generation, we briefly discuss the relevant input and
144 output data structures. The \nm{LexSpec} module has data constructors and
145 functions relevant to \eg the ML-Lex input specification format, as shown in
146 Figure~\ref{fig:lex-spec}
147
148 \begin{figure}
149 \begin{verbatim}
150 type action = string
151 type rule_spec = AtomSet.set option * RegExp.re
152 type rule = rule_spec * action
153
154 datatype spec = Spec of {
155 decls : string,
156 conf : config,
157 rules : rule list
158 }
159 \end{verbatim}
160 \caption{A fragment of \nm{LexSpec}}\label{fig:lex-spec}
161 \end{figure}
162
163 Actions, at least in the present implementation, are just raw strings. A
164 \nm{rule} consists of a rule specification and an associated action. The
165 optional atom set included with a rule spec represents the start states
166 to which that rule applies (with \nm{NONE} meaning, strangely enough, all start
167 states). With these definitions, a lexer specification is just a list of
168 rules, some declarations (a raw string containing code) and some miscellaneous
169 configuration data.
170
171 \begin{figure}
172 \begin{verbatim}
173 datatype dfa_state
174 = State of {
175 id : int,
176 label : RegExp.re Vector.vector,
177 final : int list,
178 next : (RegExp.sym_set * dfa_state) list ref
179 }
180
181 datatype machine = Machine of {
182 label : string,
183 rules : (RegExp.re * int) vector,
184 states : dfa_state list
185 }
186
187 type action = string
188
189 datatype spec = Spec of {
190 actions : action vector,
191 machines : machine list,
192 ... (* configuration data *)
193 }
194 \end{verbatim}
195 \caption{A fragment of \nm{LexOutputSpec}}\label{fig:lex-output-spec}
196 \end{figure}
197
198 As Figure~\ref{fig:lex-output-spec} illustrates, the output of DFA generation is
199 \emph{not} a DFA, but a collection of DFAs along with a vector of actions.
200 Each \nm{machine} represents a start state for the lexer; that is, each start
201 state has its own automaton. However, since start states may use the same
202 actions, we separate out the actions into a vector so that they are only
203 emitted once.
204
205 A \nm{machine} includes a label, which is just the name of the start state, as
206 well as the rules relevant to that machine, which are paired with an index to
207 the associated action in the action vector. The DFA itself is a list of
208 states, with the head of the list being $q_0$. A state, in turn, is labeled by
209 a vector of REs (with the same length as the \nm{rules} vector in the machine).
210 Since a given DFA state may be an accepting state for more than one rule, we
211 store a \emph{list} of rule indices for the \nm{final} flag. On a match, the
212 action for the lowest-index rule is executed first, but that action may use
213 \nm{REJECT()}, in which case it may be necessary to jump to the action for the
214 next rule index given in the \nm{final} list.
215
216 \section{\nm{LexGen}}\label{sec:lex-gen}
217
218 \nm{LexGen} is a very simple module with a single accessible function:
219 \begin{center}
220 \nm{gen : LexSpec.spec -> LexOutputSpec.spec}
221 \end{center}
222
223 The first task of the \nm{gen} function is to collate the actions and start
224 states. The actions from the input spec are separated from their rules into a
225 vector. Afterwards, \nm{gen} iterates over the specified start states,
226 collecting the rules for each start state and using the \nm{mkDFA} function to
227 generate a machine for each.
228
229 \nm{mkDFA} performs a straightforward imperative DFA construction, using
230 the \nm{derivatives} function from \nm{RegExp} to compute the transitions out of
231 each node. A map of RE vectors to DFA nodes is maintained (using
232 \nm{Vector.collate RegExp.compare} for ordering); this map is used to recognize
233 when a new out-edge is going to an existing DFA node. Finally, any transition
234 to a vector of REs which all generate the empty language is an error transition
235 (that is, the derivatives for the given transition symbol set all indicate a
236 non-match).
237
238 \section{Front ends}
239
240 At the moment, only one front end is available: the ML-Lex specification
241 format. Eventually \ulex{} will have its own format.
242
243 The ML-Lex front end is fairly straightforward: it uses ML-Yacc to do the
244 parsing, and can use either ML-Lex or \ulex{} to do the lexing. The
245 distribution includes a lexer that was generated from \ulex{} to serve as a
246 bootstrap.
247
248 \section{Back ends}
249
250 One exciting aspect of \ulex{} is the ability to easily add back ends. The
251 following back ends are currently included in the distribution.
252
253 \paragraph{SML control-flow lexer generation}
254
255 The most important back end is code generation for SML. At present, there is a
256 single code generation strategy: build a lexer using control-flow (\ie
257 if statements and tail-calls) to match the input. If the control-flow strategy
258 turns out to be inadequate, it would be fairly easy to add a code
259 generator for table-based lexing.
260
261 Code generation is performed by expanding stubs in a template SML file. The
262 template contains code for dealing with streams and setting up the lexer in the
263 appropriate way. Input is read from functional strings, which allow for
264 the arbitrary lookahead needed for maximal-munch. These streams also track
265 the current file position and line number.
266
267 A helper module, \nm{ML}, contains a representation for a good portion of the
268 Standard ML expression langauge, and support for pretty-printing such
269 expressions.
270
271 The generated code includes user actions and the DFA for each start state.
272 Within each start state there is one \emph{state function} per DFA node. Each
273 state function will examine the next character of input and perform a series of
274 if-tests to determine the correct transition. The if-tests perform a
275 hard-coded binary search over the symbol set intervals for the transitions.
276
277 The lexer stores a reference cell for the current functional stream. Each time
278 the lexer accepts a token, the cell is updated. \nm{yytext} is generated (only
279 when needed) by ``subtracting'' the new stream from the one stored in the
280 reference cell before updating it. Subtraction simply rescans the appropriate
281 number of characters from the stored stream, which should still have the string
282 in its buffer.
283
284 One subtlety is handling calls to \nm{REJECT()}. Since such calls are fairly
285 rare, we want to avoid tracking the information \nm{REJECT} needs if it won't
286 be used. \nm{REJECT} information consists of (in essence) a list of all the
287 previous matches. A previous match could occur on the same DFA state if
288 multiple REs matched the input at that state; otherwise, the previous match is
289 a prefix of the \nm{REJECT}ed match. Whenever a transition is made, the
290 appropriate previous match information is passed up to the next state.
291 However, if the current state is an accepting state that does not use
292 \nm{REJECT}, then the history is \emph{truncated} at the \nm{REJECT}-free
293 point, since it could never be used. This determination is made statically and
294 is hard-coded into the generated SML lexer.
295
296 \paragraph{Graphviz}
297
298 The Graphviz toolkit provides easy graph visualization using a very simple
299 graph description format. We utilize the DOT format. The Graphviz backend
300 will write one DOT file for each start state, showing all nodes for that start
301 state's DFA, along with labeled transitions. See \texttt{www.graphviz.org} for
302 details on the DOT format.
303
304 \paragraph{Text dump}
305
306 If Graphviz is not available or a more detailed summary is desired, the
307 \nm{DumpOutput} module can be used to print to standard out every DFA state,
308 labeled by its RE vector, along with out-edges, for every start state in the
309 lexer.
310
311 \paragraph{Interactive matching}
312
313 Finally, a simple interactive back end is available. Interactive matching
314 allows a user to enter arbitrary strings and find out (1) if they matched and
315 (2) what RE matched them. The code for interactive matching is quite simple.
316
317 \section{\nm{Main}}
318
319 The \nm{Main} module is the driver for \ulex{}: it is responsible for processing
320 command-line arguments and hooking up the appropriate front and back ends.
321 Since it is very simple, it gives a nice overview of the system and is a good
322 place to look first in trying to undertand the code.