Debian Codegraph @

c2hs/base/syntax/Lexers.hs

raw symbols SCIP
1 -- Compiler Toolkit: Self-optimizing lexers
2 --
3 -- Author : Manuel M. T. Chakravarty
4 -- Created: 2 March 99
5 --
6 -- Version $Revision: 1.2 $ from $Date: 2004/11/13 17:26:51 $
7 --
8 -- Copyright (c) 1999 Manuel M. T. Chakravarty
9 --
10 -- This library is free software; you can redistribute it and/or
11 -- modify it under the terms of the GNU Library General Public
12 -- License as published by the Free Software Foundation; either
13 -- version 2 of the License, or (at your option) any later version.
14 --
15 -- This library is distributed in the hope that it will be useful,
16 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
17 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 -- Library General Public License for more details.
19 --
20 --- DESCRIPTION ---------------------------------------------------------------
21 --
22 -- Self-optimizing lexer combinators.
23 --
24 -- For detailed information, see ``Lazy Lexing is Fast'', Manuel
25 -- M. T. Chakravarty, in A. Middeldorp and T. Sato, editors, Proceedings of
26 -- Fourth Fuji International Symposium on Functional and Logic Programming,
27 -- Springer-Verlag, LNCS 1722, 1999. (See my Web page for details.)
28 --
29 -- Thanks to Simon L. Peyton Jones <[email protected]> and Roman
30 -- Lechtchinsky <[email protected]> for their helpful suggestions that
31 -- improved the design of this library.
32 --
33 --- DOCU ----------------------------------------------------------------------
34 --
35 -- language: Haskell 98
36 --
37 -- The idea is to combine the benefits of off-line generators with
38 -- combinators like in `Parsers.hs' (which builds on Swierstra/Duponcheel's
39 -- technique for self-optimizing parser combinators). In essence, a state
40 -- transition graph representing a lexer table is computed on the fly, to
41 -- make lexing deterministic and based on cheap table lookups.
42 --
43 -- Regular expression map to Haskell expressions as follows. If `x' and `y'
44 -- are regular expressions,
45 --
46 -- -> epsilon
47 -- xy -> x +> y
48 -- x*y -> x `star` y
49 -- x+y -> x `plus` y
50 -- x?y -> x `quest` y
51 --
52 -- Given such a Haskelized regular expression `hre', we can use
53 --
54 -- (1) hre `lexaction` \lexeme -> Nothing
55 -- (2) hre `lexaction` \lexeme -> Just token
56 -- (3) hre `lexmeta` \lexeme pos s -> (res, pos', s', Nothing)
57 -- (4) hre `lexmeta` \lexeme pos s -> (res, pos', s', Just l)
58 --
59 -- where `epsilon' is required at the end of `hre' if it otherwise ends on
60 -- `star', `plus', or `quest', and then, we have
61 --
62 -- (1) discards `lexeme' accepted by `hre',
63 -- (2) turns the `lexeme' accepted by `hre' into a token,
64 -- (3) while discarding the lexeme accepted by `hre', transforms the
65 -- position and/or user state, and
66 -- (4) while discarding the lexeme accepted by `hre', transforms the
67 -- position and/or user state and returns a lexer to be used for the
68 -- next lexeme.
69 --
70 -- The component `res' in case of a meta action, can be `Nothing', `Just
71 -- (Left err)', or `Just (Right token)' to return nothing, an error, or a
72 -- token from a meta action, respectively.
73 --
74 -- * By adding `ctrlLexer', `Positions' are properly handled in the presence
75 -- of layout control characters.
76 --
77 -- * This module makes essential use of graphical data structures (for
78 -- representing the state transition graph) and laziness (for maintaining
79 -- the last action in `execLexer'.
80 --
81 -- NOTES:
82 --
83 -- * In this implementation, the combinators `quest`, `star`, and `plus` are
84 -- *right* associative - this was different in the ``Lazy Lexing is Fast''
85 -- paper. This change was made on a suggestion by Martin Norb�ck
86 -- <[email protected]>.
87 --
88 --- TODO ----------------------------------------------------------------------
89 --
90 -- * error correction is missing
91 --
92 -- * in (>||<) in the last case, `(addBoundsNum bn bn')' is too simple, as
93 -- the number of outgoing edges is not the sum of the numbers of the
94 -- individual states when there are conflicting edges, ie, ones labeled
95 -- with the same character; however, the number is only used to decide a
96 -- heuristic, so it is questionable whether it is worth spending the
97 -- additional effort of computing the accurate number
98 --
99 -- * Unicode posses a problem as the character domain becomes too big for
100 -- using arrays to represent transition tables and even sparse structures
101 -- will posse a significant overhead when character ranges are naively
102 -- represented. So, it might be time for finite maps again.
103 --
104 -- Regarding the character ranges, there seem to be at least two
105 -- possibilities. Doaitse explicitly uses ranges and avoids expanding
106 -- them. The problem with this approach is that we may only have
107 -- predicates such as `isAlphaNum' to determine whether a given character
108 -- belongs to some character class. From this representation it is
109 -- difficult to efficiently compute a range. The second approach, as
110 -- proposed by Tom Pledger <[email protected]> (on the Haskell list)
111 -- would be to actually use predicates directly and make the whole business
112 -- efficient by caching predicate queries. In other words, for any given
113 -- character after we have determined (in a given state) once what the
114 -- following state on accepting that character is, we need not consult the
115 -- predicates again if we memorise the successor state the first time
116 -- around.
117 --
118 -- * Ken Shan <[email protected]> writes ``Section 4.3 of your paper
119 -- computes the definition
120 --
121 -- re1 `star` re2 = \l' -> let self = re1 self >||< re2 l' in self
122 --
123 -- If we let re2 = epsilon, we get
124 --
125 -- many :: Regexp s t -> Regexp s t
126 -- many re = \l' -> let self = re1 self >||< l' in self
127 --
128 -- since epsilon = id.'' This should actually be as good as the current
129 -- definition and it might be worthwhile to offer it as a variant.
130 --
131
132 module Lexers (Regexp, Lexer, Action, epsilon, char, (+>), lexaction,
133 lexactionErr, lexmeta, (>|<), (>||<), ctrlChars, ctrlLexer,
134 star, plus, quest, alt, string, LexerState, execLexer)
135 where
136
137 import Data.Maybe (fromMaybe, isNothing)
138 import Data.Array (Ix(..), Array, array, (!), assocs, accumArray)
139
140 import Position (Position(..), Pos (posOf), nopos, incPos, tabPos, retPos)
141 import DLists (DList, openDL, zeroDL, unitDL, snocDL, joinDL, closeDL)
142 import Errors (interr, ErrorLvl(..), Error, makeError)
143
144
145 infixr 4 `quest`, `star`, `plus`
146 infixl 3 +>, `lexaction`, `lexmeta`
147 infixl 2 >|<, >||<
148
149
150 -- constants
151 -- ---------
152
153 -- we use the dense representation if a table has at least the given number of
154 -- (non-error) elements
155 --
156 denseMin :: Int
157 denseMin = 20
158
159
160 -- data structures
161 -- ---------------
162
163 -- represents the number of (non-error) elements and the bounds of a table
164 --
165 type BoundsNum = (Int, Char, Char)
166
167 -- empty bounds
168 --
169 nullBoundsNum :: BoundsNum
170 nullBoundsNum = (0, maxBound, minBound)
171
172 -- combine two bounds
173 --
174 addBoundsNum :: BoundsNum -> BoundsNum -> BoundsNum
175 addBoundsNum (n, lc, hc) (n', lc', hc') = (n + n', min lc lc', max hc hc')
176
177 -- check whether a character is in the bounds
178 --
179 inBounds :: Char -> BoundsNum -> Bool
180 inBounds c (_, lc, hc) = c >= lc && c <= hc
181
182 -- Lexical actions take a lexeme with its position and may return a token; in
183 -- a variant, an error can be returned (EXPORTED)
184 --
185 -- * if there is no token returned, the current lexeme is discarded lexing
186 -- continues looking for a token
187 --
188 type Action t = String -> Position -> Maybe t
189 type ActionErr t = String -> Position -> Either Error t
190
191 -- Meta actions transform the lexeme, position, and a user-defined state; they
192 -- may return a lexer, which is then used for accepting the next token (this
193 -- is important to implement non-regular behaviour like nested comments)
194 -- (EXPORTED)
195 --
196 type Meta s t = String -> Position -> s -> (Maybe (Either Error t), -- err/tok?
197 Position, -- new pos
198 s, -- state
199 Maybe (Lexer s t)) -- lexer?
200
201 -- tree structure used to represent the lexer table (EXPORTED ABSTRACTLY)
202 --
203 -- * each node in the tree corresponds to a state of the lexer; the associated
204 -- actions are those that apply when the corresponding state is reached
205 --
206 data Lexer s t = Lexer (LexAction s t) (Cont s t)
207
208 -- represent the continuation of a lexer
209 --
210 data Cont s t = -- on top of the tree, where entries are dense, we use arrays
211 --
212 Dense BoundsNum (Array Char (Lexer s t))
213 --
214 -- further down, where the valid entries are sparse, we
215 -- use association lists, to save memory (the first argument
216 -- is the length of the list)
217 --
218 | Sparse BoundsNum [(Char, Lexer s t)]
219 --
220 -- end of a automaton
221 --
222 | Done
223 -- deriving Show
224
225 -- lexical action (EXPORTED ABSTRACTLY)
226 --
227 data LexAction s t = Action (Meta s t)
228 | NoAction
229 -- deriving Show
230
231 -- a regular expression (EXPORTED)
232 --
233 type Regexp s t = Lexer s t -> Lexer s t
234
235
236 -- basic combinators
237 -- -----------------
238
239 -- Empty lexeme (EXPORTED)
240 --
241 epsilon :: Regexp s t
242 epsilon = id
243
244 -- One character regexp (EXPORTED)
245 --
246 char :: Char -> Regexp s t
247 char c = \l -> Lexer NoAction (Sparse (1, c, c) [(c, l)])
248
249 -- Concatenation of regexps (EXPORTED)
250 --
251 (+>) :: Regexp s t -> Regexp s t -> Regexp s t
252 (+>) = (.)
253
254 -- Close a regular expression with an action that converts the lexeme into a
255 -- token (EXPORTED)
256 --
257 -- * Note: After the application of the action, the position is advanced
258 -- according to the length of the lexeme. This implies that normal
259 -- actions should not be used in the case where a lexeme might contain
260 -- control characters that imply non-standard changes of the position,
261 -- such as newlines or tabs.
262 --
263 lexaction :: Regexp s t -> Action t -> Lexer s t
264 lexaction re a = re `lexmeta` a'
265 where
266 a' lexeme pos@(Position fname row col) s =
267 let col' = col + length lexeme
268 in
269 col' `seq` case a lexeme pos of
270 Nothing -> (Nothing, (Position fname row col'), s, Nothing)
271 Just t -> (Just (Right t), (Position fname row col'), s, Nothing)
272
273 -- Variant for actions that may returns an error (EXPORTED)
274 --
275 lexactionErr :: Regexp s t -> ActionErr t -> Lexer s t
276 lexactionErr re a = re `lexmeta` a'
277 where
278 a' lexeme pos@(Position fname row col) s =
279 let col' = col + length lexeme
280 in
281 col' `seq` (Just (a lexeme pos), (Position fname row col'), s, Nothing)
282
283 -- Close a regular expression with a meta action (EXPORTED)
284 --
285 -- * Note: Meta actions have to advance the position in dependence of the
286 -- lexeme by themselves.
287 --
288 lexmeta :: Regexp s t -> Meta s t -> Lexer s t
289 lexmeta re a = re (Lexer (Action a) Done)
290
291 -- disjunctive combination of two regexps (EXPORTED)
292 --
293 (>|<) :: Regexp s t -> Regexp s t -> Regexp s t
294 re >|< re' = \l -> re l >||< re' l
295
296 -- disjunctive combination of two lexers (EXPORTED)
297 --
298 (>||<) :: Lexer s t -> Lexer s t -> Lexer s t
299 (Lexer a c) >||< (Lexer a' c') = Lexer (joinActions a a') (joinConts c c')
300
301 -- combine two disjunctive continuations
302 --
303 joinConts :: Cont s t -> Cont s t -> Cont s t
304 joinConts Done c' = c'
305 joinConts c Done = c
306 joinConts c c' = let (bn , cls ) = listify c
307 (bn', cls') = listify c'
308 in
309 -- note: `addsBoundsNum' can, at this point, only
310 -- approx. the number of *non-overlapping* cases;
311 -- however, the bounds are correct
312 --
313 aggregate (addBoundsNum bn bn') (cls ++ cls')
314 where
315 listify (Dense n arr) = (n, assocs arr)
316 listify (Sparse n cls) = (n, cls)
317 listify _ = interr "Lexers.listify: Impossible argument!"
318
319 -- combine two actions
320 --
321 joinActions :: LexAction s t -> LexAction s t -> LexAction s t
322 joinActions NoAction a' = a'
323 joinActions a NoAction = a
324 joinActions _ _ = interr "Lexers.>||<: Overlapping actions!"
325
326 -- Note: `n' is only an upper bound of the number of non-overlapping cases
327 --
328 aggregate :: BoundsNum -> ([(Char, Lexer s t)]) -> Cont s t
329 aggregate bn@(n, lc, hc) cls
330 | n >= denseMin = Dense bn (accumArray (>||<) noLexer (lc, hc) cls)
331 | otherwise = Sparse bn (accum (>||<) cls)
332 where
333 noLexer = Lexer NoAction Done
334
335 -- combine the elements in the association list that have the same key
336 --
337 accum :: Eq a => (b -> b -> b) -> [(a, b)] -> [(a, b)]
338 accum f [] = []
339 accum f ((k, e):kes) =
340 let (ke, kes') = gather k e kes
341 in
342 ke : accum f kes'
343 where
344 gather k e [] = ((k, e), [])
345 gather k e (ke'@(k', e'):kes) | k == k' = gather k (f e e') kes
346 | otherwise = let
347 (ke'', kes') = gather k e kes
348 in
349 (ke'', ke':kes')
350
351
352 -- handling of control characters
353 -- ------------------------------
354
355 -- control characters recognized by `ctrlLexer' (EXPORTED)
356 --
357 ctrlChars :: [Char]
358 ctrlChars = ['\n', '\r', '\f', '\t']
359
360 -- control lexer (EXPORTED)
361 --
362 -- * implements proper `Position' management in the presence of the standard
363 -- layout control characters
364 --
365 ctrlLexer :: Lexer s t
366 ctrlLexer =
367 char '\n' `lexmeta` newline
368 >||< char '\r' `lexmeta` newline
369 >||< char '\v' `lexmeta` newline
370 >||< char '\f' `lexmeta` formfeed
371 >||< char '\t' `lexmeta` tab
372 where
373 newline _ pos s = (Nothing, retPos pos , s, Nothing)
374 formfeed _ pos s = (Nothing, incPos pos 1, s, Nothing)
375 tab _ pos s = (Nothing, tabPos pos , s, Nothing)
376
377
378 -- non-basic combinators
379 -- ---------------------
380
381 -- x `star` y corresponds to the regular expression x*y (EXPORTED)
382 --
383 star :: Regexp s t -> Regexp s t -> Regexp s t
384 --
385 -- The definition used below can be obtained by equational reasoning from this
386 -- one (which is much easier to understand):
387 --
388 -- star re1 re2 = let self = (re1 +> self >|< epsilon) in self +> re2
389 --
390 -- However, in the above, `self' is of type `Regexp s t' (ie, a functional),
391 -- whereas below it is of type `Lexer s t'. Thus, below we have a graphical
392 -- body (finite representation of an infinite structure), which doesn't grow
393 -- with the size of the accepted lexeme - in contrast to the definition using
394 -- the functional recursion.
395 --
396 star re1 re2 = \l -> let self = re1 self >||< re2 l
397 in
398 self
399
400 -- x `plus` y corresponds to the regular expression x+y (EXPORTED)
401 --
402 plus :: Regexp s t -> Regexp s t -> Regexp s t
403 plus re1 re2 = re1 +> (re1 `star` re2)
404
405 -- x `quest` y corresponds to the regular expression x?y (EXPORTED)
406 --
407 quest :: Regexp s t -> Regexp s t -> Regexp s t
408 quest re1 re2 = (re1 +> re2) >|< re2
409
410 -- accepts a non-empty set of alternative characters (EXPORTED)
411 --
412 alt :: [Char] -> Regexp s t
413 --
414 -- Equiv. to `(foldr1 (>|<) . map char) cs', but much faster
415 --
416 alt [] = interr "Lexers.alt: Empty character set!"
417 alt cs = \l -> let bnds = (length cs, minimum cs, maximum cs)
418 in
419 Lexer NoAction (aggregate bnds [(c, l) | c <- cs])
420
421 -- accept a character sequence (EXPORTED)
422 --
423 string :: String -> Regexp s t
424 string [] = interr "Lexers.string: Empty character set!"
425 string cs = (foldr1 (+>) . map char) cs
426
427
428 -- execution of a lexer
429 -- --------------------
430
431 -- threaded top-down during lexing (current input, current position, meta
432 -- state) (EXPORTED)
433 --
434 type LexerState s = (String, Position, s)
435
436 -- apply a lexer, yielding a token sequence and a list of errors (EXPORTED)
437 --
438 -- * Currently, all errors are fatal; thus, the result is undefined in case of
439 -- an error (this changes when error correction is added).
440 --
441 -- * The final lexer state is returned.
442 --
443 -- * The order of the error messages is undefined.
444 --
445 execLexer :: Lexer s t -> LexerState s -> ([t], LexerState s, [Error])
446 --
447 -- * the following is moderately tuned
448 --
449 execLexer l state@([], _, _) = ([], state, [])
450 execLexer l state =
451 case lexOne l state of
452 (Nothing , _ , state') -> execLexer l state'
453 (Just res, l', state') -> let (ts, final, allErrs) = execLexer l' state'
454 in case res of
455 (Left err) -> (ts , final, err:allErrs)
456 (Right t ) -> (t:ts, final, allErrs)
457 where
458 -- accept a single lexeme
459 --
460 -- lexOne :: Lexer s t -> LexerState s t
461 -- -> (Either Error (Maybe t), Lexer s t, LexerState s t)
462 lexOne l0 state = oneLexeme l0 state zeroDL lexErr
463 where
464 -- the result triple of `lexOne' that signals a lexical error;
465 -- the result state is advanced by one character for error correction
466 --
467 lexErr = let (cs, pos@(Position fname row col), s) = state
468 err = makeError ErrorErr pos
469 ["Lexical error!",
470 "The character " ++ show (head cs)
471 ++ " does not fit here; skipping it."]
472 in
473 (Just (Left err), l, (tail cs, (Position fname row (col + 1)), s))
474
475 -- we take an open list of characters down, where we accumulate the
476 -- lexeme; this function returns maybe a token, the next lexer to use
477 -- (can be altered by a meta action), the new lexer state, and a list
478 -- of errors
479 --
480 -- we implement the "principle of the longest match" by taking a
481 -- potential result quadruple down (in the last argument); the
482 -- potential result quadruple is updated whenever we pass by an action
483 -- (different from `NoAction'); initially it is an error result
484 --
485 -- oneLexeme :: Lexer s t
486 -- -> LexerState
487 -- -> DList Char
488 -- -> (Maybe (Either Error t), Maybe (Lexer s t),
489 -- LexerState s t)
490 -- -> (Maybe (Either Error t), Maybe (Lexer s t),
491 -- LexerState s t)
492 oneLexeme (Lexer a cont) state@(cs, pos, s) csDL last =
493 let last' = action a csDL state last
494 in case cs of
495 [] -> last'
496 (c:cs') -> oneChar cont c (cs', pos, s) csDL last'
497
498 oneChar Done c state csDL last = last
499 oneChar (Dense bn arr) c state csDL last
500 | c `inBounds` bn = cont (arr!c) c state csDL last
501 | otherwise = last
502 oneChar (Sparse bn cls) c state csDL last
503 | c `inBounds` bn = case lookup c cls of
504 Nothing -> last
505 Just l' -> cont l' c state csDL last
506 | otherwise = last
507
508 -- continue within the current lexeme
509 --
510 cont l' c state csDL last = oneLexeme l' state (csDL `snocDL` c) last
511
512 -- execute the action if present and finalise the current lexeme
513 --
514 action (Action f) csDL (cs, pos, s) last =
515 case f (closeDL csDL) pos s of
516 (Nothing, pos', s', l')
517 | not . null $ cs -> lexOne (fromMaybe l0 l') (cs, pos', s')
518 (res , pos', s', l') -> (res, (fromMaybe l0 l'), (cs, pos', s'))
519 action NoAction csDL state last =
520 last -- no change