Home My Page Projects Code Snippets Project Openings SML/NJ
Summary Activity Forums Tracker Lists Tasks Docs Surveys News SCM Files

SCM Repository

[smlnj] Annotation of /ml-lex/trunk/lexgen.sml
ViewVC logotype

Annotation of /ml-lex/trunk/lexgen.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 919 - (view) (download)
Original Path: sml/trunk/src/ml-lex/lexgen.sml

1 : monnier 249 (* Lexical analyzer generator for Standard ML.
2 :     Version 1.7.0, June 1998
3 :    
4 :     Copyright (c) 1989-1992 by Andrew W. Appel,
5 :     David R. Tarditi, James S. Mattson
6 :    
7 :     This software comes with ABSOLUTELY NO WARRANTY.
8 :     This software is subject only to the PRINCETON STANDARD ML SOFTWARE LIBRARY
9 :     COPYRIGHT NOTICE, LICENSE AND DISCLAIMER, (in the file "COPYRIGHT",
10 :     distributed with this software). You may copy and distribute this software;
11 :     see the COPYRIGHT NOTICE for details and restrictions.
12 :    
13 :     Changes:
14 :     07/25/89 (drt): added %header declaration, code to place
15 :     user declarations at same level as makeLexer, etc.
16 :     This is needed for the parser generator.
17 :     /10/89 (appel): added %arg declaration (see lexgen.doc).
18 :     /04/90 (drt): fixed following bug: couldn't use the lexer after an
19 :     error occurred -- NextTok and inquote weren't being reset
20 :     10/22/91 (drt): disabled use of lookahead
21 :     10/23/92 (drt): disabled use of $ operator (which involves lookahead),
22 :     added handlers for dictionary lookup routine
23 :     11/02/92 (drt): changed handler for exception Reject in generated lexer
24 :     to Internal.Reject
25 :     02/01/94 (appel): Moved the exception handler for Reject in such
26 :     a way as to allow tail-recursion (improves performance
27 :     wonderfully!).
28 :     02/01/94 (appel): Fixed a bug in parsing of state names.
29 :     05/19/94 (Mikael Pettersson, mpe@ida.liu.se):
30 :     Transition tables are usually represented as strings, but
31 :     when the range is too large, int vectors constructed by
32 :     code like "Vector.vector[1,2,3,...]" are used instead.
33 :     The problem with this isn't that the vector itself takes
34 :     a lot of space, but that the code generated by SML/NJ to
35 :     construct the intermediate list at run-time is *HUGE*. My
36 :     fix is to encode an int vector as a string literal (using
37 :     two bytes per int) and emit code to decode the string to
38 :     a vector at run-time. SML/NJ compiles string literals into
39 :     substrings in the code, so this uses much less space.
40 :     06/02/94 (jhr): Modified export-lex.sml to conform to new installation
41 :     scheme. Also removed tab characters from string literals.
42 :     10/05/94 (jhr): Changed generator to produce code that uses the new
43 :     basis style strings and characters.
44 :     10/06/94 (jhr) Modified code to compile under new basis style strings
45 :     and characters.
46 :     02/08/95 (jhr) Modified to use new List module interface.
47 :     05/18/95 (jhr) changed Vector.vector to Vector.fromList
48 : blume 656
49 : monnier 249 * Revision 1.9 1998/01/06 19:23:53 appel
50 :     * added %posarg feature to permit position-within-file to be passed
51 :     * as a parameter to makeLexer
52 :     *
53 :     # Revision 1.8 1998/01/06 19:01:48 appel
54 :     # repaired error messages like "cannot have both %structure and %header"
55 :     #
56 :     # Revision 1.7 1998/01/06 18:55:49 appel
57 :     # permit %% to be unescaped within regular expressions
58 :     #
59 :     # Revision 1.6 1998/01/06 18:46:13 appel
60 :     # removed undocumented feature that permitted extra %% at end of rules
61 :     #
62 :     # Revision 1.5 1998/01/06 18:29:23 appel
63 :     # put yylineno variable inside makeLexer function
64 :     #
65 :     # Revision 1.4 1998/01/06 18:19:59 appel
66 :     # check for newline inside quoted string
67 :     #
68 :     # Revision 1.3 1997/10/04 03:52:13 dbm
69 :     # Fix to remove output file if ml-lex fails.
70 :     #
71 :     *)
72 :    
73 :     (* Subject: lookahead in sml-lex
74 :     Reply-to: david.tarditi@CS.CMU.EDU
75 :     Date: Mon, 21 Oct 91 14:13:26 -0400
76 :    
77 :     There is a serious bug in the implementation of lookahead,
78 :     as done in sml-lex, and described in Aho, Sethi, and Ullman,
79 :     p. 134 "Implementing the Lookahead Operator"
80 :    
81 :     We have disallowed the use of lookahead for now because
82 :     of this bug.
83 :    
84 :     As a counter-example to the implementation described in
85 :     ASU, consider the following specification with the
86 :     input string "aba" (this example is taken from
87 :     a comp.compilers message from Dec. 1989, I think):
88 :    
89 :     type lexresult=unit
90 :     val linenum = ref 1
91 :     fun error x = TextIO.output(TextIO.stdErr, x ^ "\n")
92 :     val eof = fn () => ()
93 :     %%
94 :     %structure Lex
95 :     %%
96 :     (a|ab)/ba => (print yytext; print "\n"; ());
97 :    
98 :     The ASU proposal works as follows. Suppose that we are
99 :     using NFA's to represent our regular expressions. Then to
100 :     build an NFA for e1 / e2, we build an NFA n1 for e1
101 :     and an NFA n2 for e2, and add an epsilon transition
102 :     from e1 to e2.
103 :    
104 :     When lexing, when we encounter the end state of e1e2,
105 :     we take as the end of the string the position in
106 :     the string that was the last occurrence of the state of
107 :     the NFA having a transition on the epsilon introduced
108 :     for /.
109 :    
110 :     Using the example we have above, we'll have an NFA
111 :     with the following states:
112 :    
113 :    
114 :     1 -- a --> 2 -- b --> 3
115 :     | |
116 :     | epsilon | epsilon
117 :     | |
118 :     |------------> 4 -- b --> 5 -- a --> 6
119 :    
120 :     On our example, we get the following list of transitions:
121 :    
122 :     a : 2, 4 (make an epsilon transition from 2 to 4)
123 :     ab : 3, 4, 5 (make an epsilon transition from 3 to 4)
124 :     aba : 6
125 :    
126 :     If we chose the last state in which we made an epsilon transition,
127 :     we'll chose the transition from 3 to 4, and end up with "ab"
128 :     as our token, when we should have "a" as our token.
129 :    
130 :     *)
131 :    
132 :     functor RedBlack(B : sig type key
133 :     val > : key*key->bool
134 :     end):
135 :     sig type tree
136 :     type key
137 :     val empty : tree
138 :     val insert : key * tree -> tree
139 :     val lookup : key * tree -> key
140 :     exception notfound of key
141 :     end =
142 :     struct
143 :     open B
144 :     datatype color = RED | BLACK
145 :     datatype tree = empty | tree of key * color * tree * tree
146 :     exception notfound of key
147 :    
148 :     fun insert (key,t) =
149 :     let fun f empty = tree(key,RED,empty,empty)
150 :     | f (tree(k,BLACK,l,r)) =
151 :     if key>k
152 :     then case f r
153 :     of r as tree(rk,RED, rl as tree(rlk,RED,rll,rlr),rr) =>
154 :     (case l
155 :     of tree(lk,RED,ll,lr) =>
156 :     tree(k,RED,tree(lk,BLACK,ll,lr),
157 :     tree(rk,BLACK,rl,rr))
158 :     | _ => tree(rlk,BLACK,tree(k,RED,l,rll),
159 :     tree(rk,RED,rlr,rr)))
160 :     | r as tree(rk,RED,rl, rr as tree(rrk,RED,rrl,rrr)) =>
161 :     (case l
162 :     of tree(lk,RED,ll,lr) =>
163 :     tree(k,RED,tree(lk,BLACK,ll,lr),
164 :     tree(rk,BLACK,rl,rr))
165 :     | _ => tree(rk,BLACK,tree(k,RED,l,rl),rr))
166 :     | r => tree(k,BLACK,l,r)
167 :     else if k>key
168 :     then case f l
169 :     of l as tree(lk,RED,ll, lr as tree(lrk,RED,lrl,lrr)) =>
170 :     (case r
171 :     of tree(rk,RED,rl,rr) =>
172 :     tree(k,RED,tree(lk,BLACK,ll,lr),
173 :     tree(rk,BLACK,rl,rr))
174 :     | _ => tree(lrk,BLACK,tree(lk,RED,ll,lrl),
175 :     tree(k,RED,lrr,r)))
176 :     | l as tree(lk,RED, ll as tree(llk,RED,lll,llr), lr) =>
177 :     (case r
178 :     of tree(rk,RED,rl,rr) =>
179 :     tree(k,RED,tree(lk,BLACK,ll,lr),
180 :     tree(rk,BLACK,rl,rr))
181 :     | _ => tree(lk,BLACK,ll,tree(k,RED,lr,r)))
182 :     | l => tree(k,BLACK,l,r)
183 :     else tree(key,BLACK,l,r)
184 :     | f (tree(k,RED,l,r)) =
185 :     if key>k then tree(k,RED,l, f r)
186 :     else if k>key then tree(k,RED, f l, r)
187 :     else tree(key,RED,l,r)
188 :     in case f t
189 :     of tree(k,RED, l as tree(_,RED,_,_), r) => tree(k,BLACK,l,r)
190 :     | tree(k,RED, l, r as tree(_,RED,_,_)) => tree(k,BLACK,l,r)
191 :     | t => t
192 :     end
193 :    
194 :    
195 :     fun lookup (key,t) =
196 :     let fun look empty = raise (notfound key)
197 :     | look (tree(k,_,l,r)) =
198 :     if k>key then look l
199 :     else if key>k then look r
200 :     else k
201 :     in look t
202 :     end
203 :    
204 :     end
205 :    
206 :     signature LEXGEN =
207 :     sig
208 :     val lexGen: string -> unit
209 :     end
210 :    
211 :     structure LexGen: LEXGEN =
212 :     struct
213 :     open Array List
214 :     infix 9 sub
215 :    
216 :     datatype token = CHARS of bool array | QMARK | STAR | PLUS | BAR
217 :     | LP | RP | CARAT | DOLLAR | SLASH | STATE of string list
218 :     | REPS of int * int | ID of string | ACTION of string
219 :     | BOF | EOF | ASSIGN | SEMI | ARROW | LEXMARK | LEXSTATES
220 :     | COUNT | REJECT | FULLCHARSET | STRUCT | HEADER | ARG | POSARG
221 :    
222 :     datatype exp = EPS | CLASS of bool array * int | CLOSURE of exp
223 :     | ALT of exp * exp | CAT of exp * exp | TRAIL of int
224 :     | END of int
225 :    
226 :     (* flags describing input Lex spec. - unnecessary code is omitted *)
227 :     (* if possible *)
228 :    
229 :     val CharFormat = ref false;
230 :     val UsesTrailingContext = ref false;
231 :     val UsesPrevNewLine = ref false;
232 :    
233 :     (* flags for various bells & whistles that Lex has. These slow the
234 :     lexer down and should be omitted from production lexers (if you
235 :     really want speed) *)
236 :    
237 :     val CountNewLines = ref false;
238 :     val PosArg = ref false;
239 :     val HaveReject = ref false;
240 :    
241 :     (* Can increase size of character set *)
242 :    
243 :     val CharSetSize = ref 129;
244 :    
245 :     (* Can name structure or declare header code *)
246 :    
247 :     val StrName = ref "Mlex"
248 :     val HeaderCode = ref ""
249 :     val HeaderDecl = ref false
250 :     val ArgCode = ref (NONE: string option)
251 :     val StrDecl = ref false
252 :    
253 :     val ResetFlags = fn () => (CountNewLines := false; HaveReject := false;
254 :     PosArg := false;
255 :     UsesTrailingContext := false;
256 :     CharSetSize := 129; StrName := "Mlex";
257 :     HeaderCode := ""; HeaderDecl:= false;
258 :     ArgCode := NONE;
259 :     StrDecl := false)
260 :    
261 :     val LexOut = ref(TextIO.stdOut)
262 :     fun say x = TextIO.output(!LexOut, x)
263 :    
264 :     (* Union: merge two sorted lists of integers *)
265 :    
266 :     fun union(a,b) = let val rec merge = fn
267 :     (nil,nil,z) => z
268 :     | (nil,el::more,z) => merge(nil,more,el::z)
269 :     | (el::more,nil,z) => merge(more,nil,el::z)
270 :     | (x::morex,y::morey,z) => if (x:int)=(y:int)
271 :     then merge(morex,morey,x::z)
272 :     else if x>y then merge(morex,y::morey,x::z)
273 :     else merge(x::morex,morey,y::z)
274 :     in merge(rev a,rev b,nil)
275 :     end
276 :    
277 :     (* Nullable: compute if a important expression parse tree node is nullable *)
278 :    
279 :     val rec nullable = fn
280 :     EPS => true
281 :     | CLASS(_) => false
282 :     | CLOSURE(_) => true
283 :     | ALT(n1,n2) => nullable(n1) orelse nullable(n2)
284 :     | CAT(n1,n2) => nullable(n1) andalso nullable(n2)
285 :     | TRAIL(_) => true
286 :     | END(_) => false
287 :    
288 :     (* FIRSTPOS: firstpos function for parse tree expressions *)
289 :    
290 :     and firstpos = fn
291 :     EPS => nil
292 :     | CLASS(_,i) => [i]
293 :     | CLOSURE(n) => firstpos(n)
294 :     | ALT(n1,n2) => union(firstpos(n1),firstpos(n2))
295 :     | CAT(n1,n2) => if nullable(n1) then union(firstpos(n1),firstpos(n2))
296 :     else firstpos(n1)
297 :     | TRAIL(i) => [i]
298 :     | END(i) => [i]
299 :    
300 :     (* LASTPOS: Lastpos function for parse tree expressions *)
301 :    
302 :     and lastpos = fn
303 :     EPS => nil
304 :     | CLASS(_,i) => [i]
305 :     | CLOSURE(n) => lastpos(n)
306 :     | ALT(n1,n2) => union(lastpos(n1),lastpos(n2))
307 :     | CAT(n1,n2) => if nullable(n2) then union(lastpos(n1),lastpos(n2))
308 :     else lastpos(n2)
309 :     | TRAIL(i) => [i]
310 :     | END(i) => [i]
311 :     ;
312 :    
313 :     (* ++: Increment an integer reference *)
314 :    
315 :     fun ++(x) : int = (x := !x + 1; !x);
316 :    
317 :     structure dict =
318 :     struct
319 :     type 'a relation = 'a * 'a -> bool
320 :     abstype ('b,'a) dictionary = DATA of { Table : ('b * 'a) list,
321 :     Leq : 'b * 'b -> bool }
322 :     with
323 :     exception LOOKUP
324 :     fun create Leqfunc = DATA { Table = nil, Leq = Leqfunc }
325 :     fun lookup (DATA { Table = entrylist, Leq = leq }) key =
326 :     let fun search [] = raise LOOKUP
327 :     | search((k,item)::entries) =
328 :     if leq(key,k)
329 :     then if leq(k,key) then item else raise LOOKUP
330 :     else search entries
331 :     in search entrylist
332 :     end
333 :     fun enter (DATA { Table = entrylist, Leq = leq })
334 :     (newentry as (key : 'b,item :'a)) : ('b,'a) dictionary =
335 :     let val gt = fn a => fn b => not (leq(a,b))
336 :     val eq = fn k => fn k' => (leq(k,k')) andalso (leq(k',k))
337 :     fun update nil = [ newentry ]
338 :     | update ((entry as (k,_))::entries) =
339 :     if (eq key k) then newentry::entries
340 :     else if gt k key then newentry::(entry::entries)
341 :     else entry::(update entries)
342 :     in DATA { Table = update entrylist, Leq = leq }
343 :     end
344 :     fun listofdict (DATA { Table = entrylist,Leq = leq}) =
345 :     let fun f (nil,r) = rev r
346 :     | f (a::b,r) = f (b,a::r)
347 :     in f(entrylist,nil)
348 :     end
349 :     end
350 :     end
351 :    
352 :     open dict;
353 :    
354 :     (* INPUT.ML : Input w/ one character push back capability *)
355 :    
356 :     val LineNum = ref 1;
357 :    
358 :     abstype ibuf =
359 :     BUF of TextIO.instream * {b : string ref, p : int ref}
360 :     with
361 :     fun make_ibuf(s) = BUF (s, {b=ref"", p = ref 0})
362 :     fun close_ibuf (BUF (s,_)) = TextIO.closeIn(s)
363 :     exception eof
364 :     fun getch (a as (BUF(s,{b,p}))) =
365 :     if (!p = (size (!b)))
366 :     then (b := TextIO.inputN(s, 1024);
367 :     p := 0;
368 :     if (size (!b))=0
369 :     then raise eof
370 :     else getch a)
371 :     else (let val ch = String.sub(!b,!p)
372 :     in (if ch = #"\n"
373 :     then LineNum := !LineNum + 1
374 :     else ();
375 :     p := !p + 1;
376 :     ch)
377 :     end)
378 :     fun ungetch(BUF(s,{b,p})) = (
379 :     p := !p - 1;
380 :     if String.sub(!b,!p) = #"\n"
381 :     then LineNum := !LineNum - 1
382 :     else ())
383 :     end;
384 :    
385 :     exception Error
386 :    
387 :     fun prErr x = (
388 :     TextIO.output (TextIO.stdErr, String.concat [
389 :     "ml-lex: error, line ", (Int.toString (!LineNum)), ": ", x, "\n"
390 :     ]);
391 :     raise Error)
392 :     fun prSynErr x = (
393 :     TextIO.output (TextIO.stdErr, String.concat [
394 :     "ml-lex: syntax error, line ", (Int.toString (!LineNum)), ": ", x, "\n"
395 :     ]);
396 :     raise Error)
397 :    
398 :     exception SyntaxError; (* error in user's input file *)
399 :    
400 :     exception LexError; (* unexpected error in lexer *)
401 :    
402 :     val LexBuf = ref(make_ibuf(TextIO.stdIn));
403 :     val LexState = ref 0;
404 :     val NextTok = ref BOF;
405 :     val inquote = ref false;
406 :    
407 :     fun AdvanceTok () : unit = let
408 :     fun isLetter c =
409 :     ((c >= #"a") andalso (c <= #"z")) orelse
410 :     ((c >= #"A") andalso (c <= #"Z"))
411 :     fun isDigit c = (c >= #"0") andalso (c <= #"9")
412 :     (* check for valid (non-leading) identifier character (added by JHR) *)
413 :     fun isIdentChr c =
414 :     ((isLetter c) orelse (isDigit c) orelse (c = #"_") orelse (c = #"'"))
415 :     fun atoi s = let
416 :     fun num (c::r, n) = if isDigit c
417 :     then num (r, 10*n + (Char.ord c - Char.ord #"0"))
418 :     else n
419 :     | num ([], n) = n
420 :     in
421 :     num (explode s, 0)
422 :     end
423 :    
424 :     fun skipws () = (case nextch()
425 :     of #" " => skipws()
426 :     | #"\t" => skipws()
427 :     | #"\n" => skipws()
428 :     | x => x
429 :     (* end case *))
430 :    
431 :     and nextch () = getch(!LexBuf)
432 :    
433 :     and escaped () = (case nextch()
434 :     of #"b" => #"\008"
435 :     | #"n" => #"\n"
436 :     | #"t" => #"\t"
437 :     | #"h" => #"\128"
438 :     | x => let
439 :     fun err t = prErr("illegal ascii escape '"^(implode(rev t))^"'")
440 :     fun cvt c = (Char.ord c - Char.ord #"0")
441 :     fun f (n, c, t) = if c=3
442 :     then if n >= (!CharSetSize)
443 :     then err t
444 :     else Char.chr n
445 :     else let val ch=nextch()
446 :     in
447 :     if isDigit ch
448 :     then f(n*10+(cvt ch), c+1, ch::t)
449 :     else err t
450 :     end
451 :     in
452 :     if isDigit x then f(cvt x, 1, [x]) else x
453 :     end
454 :     (* end case *))
455 :    
456 :     and onechar x = let val c = array(!CharSetSize, false)
457 :     in
458 :     update(c, Char.ord(x), true); CHARS(c)
459 :     end
460 :    
461 :     in case !LexState of 0 => let val makeTok = fn () =>
462 :     case skipws()
463 :     (* Lex % operators *)
464 :     of #"%" => (case nextch() of
465 :     #"%" => LEXMARK
466 :     | a => let fun f s =
467 :     let val a = nextch()
468 :     in if isLetter a then f(a::s)
469 :     else (ungetch(!LexBuf);
470 :     implode(rev s))
471 :     end
472 :     in case f [a]
473 :     of "reject" => REJECT
474 :     | "count" => COUNT
475 :     | "full" => FULLCHARSET
476 :     | "s" => LEXSTATES
477 :     | "S" => LEXSTATES
478 :     | "structure" => STRUCT
479 :     | "header" => HEADER
480 :     | "arg" => ARG
481 :     | "posarg" => POSARG
482 :     | _ => prErr "unknown % operator "
483 :     end
484 :     )
485 :     (* semicolon (for end of LEXSTATES) *)
486 :     | #";" => SEMI
487 :     (* anything else *)
488 :     | ch => if isLetter(ch) then
489 :     let fun getID matched =
490 :     let val x = nextch()
491 :     (**** fix by JHR
492 :     in if isLetter(x) orelse isDigit(x) orelse
493 :     x = "_" orelse x = "'"
494 :     ****)
495 :     in if (isIdentChr x)
496 :     then getID (x::matched)
497 :     else (ungetch(!LexBuf); implode(rev matched))
498 :     end
499 :     in ID(getID [ch])
500 :     end
501 :     else (prSynErr ("bad character: " ^ String.str ch))
502 :     in NextTok := makeTok()
503 :     end
504 :     | 1 => let val rec makeTok = fn () =>
505 :     if !inquote then case nextch() of
506 :     (* inside quoted string *)
507 :     #"\\" => onechar(escaped())
508 :     | #"\"" => (inquote := false; makeTok())
509 :     | #"\n" => (prSynErr "end-of-line inside quoted string";
510 :     inquote := false; makeTok())
511 :     | x => onechar(x)
512 :     else case skipws() of
513 :     (* single character operators *)
514 :     #"?" => QMARK
515 :     | #"*" => STAR
516 :     | #"+" => PLUS
517 :     | #"|" => BAR
518 :     | #"(" => LP
519 :     | #")" => RP
520 :     | #"^" => CARAT
521 :     | #"$" => DOLLAR
522 :     | #"/" => SLASH
523 :     | #";" => SEMI
524 :     | #"." => let val c = array(!CharSetSize,true) in
525 :     update(c,10,false); CHARS(c)
526 :     end
527 :     (* assign and arrow *)
528 :     | #"=" => let val c = nextch() in
529 :     if c = #">" then ARROW else (ungetch(!LexBuf); ASSIGN)
530 :     end
531 :     (* character set *)
532 :     | #"[" => let val rec classch = fn () => let val x = skipws()
533 :     in if x = #"\\" then escaped() else x
534 :     end;
535 :     val first = classch();
536 :     val flag = (first <> #"^");
537 :     val c = array(!CharSetSize,not flag);
538 :     fun add NONE = ()
539 :     | add (SOME x) = update(c, Char.ord(x), flag)
540 :     and range (x, y) = if x>y
541 :     then (prErr "bad char. range")
542 :     else let
543 :     val i = ref(Char.ord(x)) and j = Char.ord(y)
544 :     in while !i<=j do (
545 :     add (SOME(Char.chr(!i)));
546 :     i := !i + 1)
547 :     end
548 :     and getClass last = (case classch()
549 :     of #"]" => (add(last); c)
550 :     | #"-" => (case last
551 :     of NONE => getClass(SOME #"-")
552 :     | (SOME last') => let val x = classch()
553 :     in
554 :     if x = #"]"
555 :     then (add(last); add(SOME #"-"); c)
556 :     else (range(last',x); getClass(NONE))
557 :     end
558 :     (* end case *))
559 :     | x => (add(last); getClass(SOME x))
560 :     (* end case *))
561 :     in CHARS(getClass(if first = #"^" then NONE else SOME first))
562 :     end
563 :     (* Start States specification *)
564 :     | #"<" => let val rec get_state = fn (prev,matched) =>
565 :     case nextch() of
566 :     #">" => matched::prev
567 :     | #"," => get_state(matched::prev,"")
568 :     | x => if isIdentChr(x)
569 :     then get_state(prev,matched ^ String.str x)
570 :     else (prSynErr "bad start state list")
571 :     in STATE(get_state(nil,""))
572 :     end
573 :     (* {id} or repititions *)
574 :     | #"{" => let val ch = nextch() in if isLetter(ch) then
575 :     let fun getID matched = (case nextch()
576 :     of #"}" => matched
577 :     | x => if (isIdentChr x) then
578 :     getID(matched ^ String.str x)
579 :     else (prErr "invalid char. class name")
580 :     (* end case *))
581 :     in ID(getID(String.str ch))
582 :     end
583 :     else if isDigit(ch) then
584 :     let fun get_r (matched, r1) = (case nextch()
585 :     of #"}" => let val n = atoi(matched) in
586 :     if r1 = ~1 then (n,n) else (r1,n)
587 :     end
588 :     | #"," => if r1 = ~1 then get_r("",atoi(matched))
589 :     else (prErr "invalid repetitions spec.")
590 :     | x => if isDigit(x)
591 :     then get_r(matched ^ String.str x,r1)
592 :     else (prErr "invalid char in repetitions spec")
593 :     (* end case *))
594 :     in REPS(get_r(String.str ch,~1))
595 :     end
596 :     else (prErr "bad repetitions spec")
597 :     end
598 :     (* Lex % operators *)
599 :     | #"\\" => onechar(escaped())
600 :     (* start quoted string *)
601 :     | #"\"" => (inquote := true; makeTok())
602 :     (* anything else *)
603 :     | ch => onechar(ch)
604 :     in NextTok := makeTok()
605 :     end
606 : blume 919 | 2 => NextTok :=
607 :     (case skipws() of
608 :     #"(" =>
609 :     let
610 :     fun loop_to_end (backslash, x) =
611 :     let
612 :     val c = getch (! LexBuf)
613 :     val notb = not backslash
614 :     val nstr = c :: x
615 :     in
616 :     case c of
617 :     #"\"" => if notb then nstr
618 :     else loop_to_end (false, nstr)
619 :     | _ => loop_to_end (c = #"\\" andalso notb, nstr)
620 :     end
621 :     fun GetAct (lpct, x) =
622 :     let
623 :     val c = getch (! LexBuf)
624 :     val nstr = c :: x
625 :     in
626 :     case c of
627 :     #"\"" => GetAct (lpct, loop_to_end (false, nstr))
628 :     | #"(" => GetAct (lpct + 1, nstr)
629 :     | #")" => if lpct = 0 then implode (rev x)
630 :     else GetAct(lpct - 1, nstr)
631 :     | _ => GetAct(lpct, nstr)
632 :     end
633 :     in
634 :     ACTION (GetAct (0,nil))
635 :     end
636 :     | #";" => SEMI
637 :     | c => (prSynErr ("invalid character " ^ String.str c)))
638 :     | _ => raise LexError
639 : monnier 249 end
640 :     handle eof => NextTok := EOF ;
641 :    
642 :     fun GetTok (_:unit) : token =
643 :     let val t = !NextTok in AdvanceTok(); t
644 :     end;
645 :     val SymTab = ref (create String.<=) : (string,exp) dictionary ref
646 :    
647 :     fun GetExp () : exp =
648 :    
649 :     let val rec optional = fn e => ALT(EPS,e)
650 :    
651 :     and lookup' = fn name =>
652 :     lookup(!SymTab) name
653 :     handle LOOKUP => prErr ("bad regular expression name: "^
654 :     name)
655 :    
656 :     and newline = fn () => let val c = array(!CharSetSize,false) in
657 :     update(c,10,true); c
658 :     end
659 :    
660 :     and endline = fn e => trail(e,CLASS(newline(),0))
661 :    
662 :     and trail = fn (e1,e2) => CAT(CAT(e1,TRAIL(0)),e2)
663 :    
664 :     and closure1 = fn e => CAT(e,CLOSURE(e))
665 :    
666 :     and repeat = fn (min,max,e) => let val rec rep = fn
667 :     (0,0) => EPS
668 :     | (0,1) => ALT(e,EPS)
669 :     | (0,i) => CAT(rep(0,1),rep(0,i-1))
670 :     | (i,j) => CAT(e,rep(i-1,j-1))
671 :     in rep(min,max)
672 :     end
673 :    
674 :     and exp0 = fn () => case GetTok() of
675 :     CHARS(c) => exp1(CLASS(c,0))
676 :     | LP => let val e = exp0() in
677 :     if !NextTok = RP then
678 :     (AdvanceTok(); exp1(e))
679 :     else (prSynErr "missing '('") end
680 :     | ID(name) => exp1(lookup' name)
681 :     | _ => raise SyntaxError
682 :    
683 :     and exp1 = fn (e) => case !NextTok of
684 :     SEMI => e
685 :     | ARROW => e
686 :     | EOF => e
687 :     | LP => exp2(e,exp0())
688 :     | RP => e
689 :     | t => (AdvanceTok(); case t of
690 :     QMARK => exp1(optional(e))
691 :     | STAR => exp1(CLOSURE(e))
692 :     | PLUS => exp1(closure1(e))
693 :     | CHARS(c) => exp2(e,CLASS(c,0))
694 :     | BAR => ALT(e,exp0())
695 :     | DOLLAR => (UsesTrailingContext := true; endline(e))
696 :     | SLASH => (UsesTrailingContext := true;
697 :     trail(e,exp0()))
698 :     | REPS(i,j) => exp1(repeat(i,j,e))
699 :     | ID(name) => exp2(e,lookup' name)
700 :     | _ => raise SyntaxError)
701 :    
702 :     and exp2 = fn (e1,e2) => case !NextTok of
703 :     SEMI => CAT(e1,e2)
704 :     | ARROW => CAT(e1,e2)
705 :     | EOF => CAT(e1,e2)
706 :     | LP => exp2(CAT(e1,e2),exp0())
707 :     | RP => CAT(e1,e2)
708 :     | t => (AdvanceTok(); case t of
709 :     QMARK => exp1(CAT(e1,optional(e2)))
710 :     | STAR => exp1(CAT(e1,CLOSURE(e2)))
711 :     | PLUS => exp1(CAT(e1,closure1(e2)))
712 :     | CHARS(c) => exp2(CAT(e1,e2),CLASS(c,0))
713 :     | BAR => ALT(CAT(e1,e2),exp0())
714 :     | DOLLAR => (UsesTrailingContext := true;
715 :     endline(CAT(e1,e2)))
716 :     | SLASH => (UsesTrailingContext := true;
717 :     trail(CAT(e1,e2),exp0()))
718 :     | REPS(i,j) => exp1(CAT(e1,repeat(i,j,e2)))
719 :     | ID(name) => exp2(CAT(e1,e2),lookup' name)
720 :     | _ => raise SyntaxError)
721 :     in exp0()
722 :     end;
723 :     val StateTab = ref(create(String.<=)) : (string,int) dictionary ref
724 :    
725 :     val StateNum = ref 0;
726 :    
727 :     fun GetStates () : int list =
728 :    
729 :     let fun add nil sl = sl
730 :     | add (x::y) sl = add y (union ([lookup (!StateTab)(x)
731 :     handle LOOKUP =>
732 :     prErr ("bad state name: "^x)
733 :     ],sl))
734 :    
735 :     fun addall i sl =
736 :     if i <= !StateNum then addall (i+2) (union ([i],sl))
737 :     else sl
738 :    
739 :     fun incall (x::y) = (x+1)::incall y
740 :     | incall nil = nil
741 :    
742 :     fun addincs nil = nil
743 :     | addincs (x::y) = x::(x+1)::addincs y
744 :    
745 :     val state_list =
746 :     case !NextTok of
747 :     STATE s => (AdvanceTok(); LexState := 1; add s nil)
748 :     | _ => addall 1 nil
749 :    
750 :     in case !NextTok
751 :     of CARAT => (LexState := 1; AdvanceTok(); UsesPrevNewLine := true;
752 :     incall state_list)
753 :     | _ => addincs state_list
754 :     end
755 :    
756 :     val LeafNum = ref ~1;
757 :    
758 :     fun renum(e : exp) : exp =
759 :     let val rec label = fn
760 :     EPS => EPS
761 :     | CLASS(x,_) => CLASS(x,++LeafNum)
762 :     | CLOSURE(e) => CLOSURE(label(e))
763 :     | ALT(e1,e2) => ALT(label(e1),label(e2))
764 :     | CAT(e1,e2) => CAT(label(e1),label(e2))
765 :     | TRAIL(i) => TRAIL(++LeafNum)
766 :     | END(i) => END(++LeafNum)
767 :     in label(e)
768 :     end;
769 :    
770 :     exception ParseError;
771 :    
772 :     fun parse() : (string * (int list * exp) list * ((string,string) dictionary)) =
773 :     let val Accept = ref (create String.<=) : (string,string) dictionary ref
774 :     val rec ParseRtns = fn l => case getch(!LexBuf) of
775 :     #"%" => let val c = getch(!LexBuf) in
776 :     if c = #"%" then (implode (rev l))
777 :     else ParseRtns(c :: #"%" :: l)
778 :     end
779 :     | c => ParseRtns(c::l)
780 :     and ParseDefs = fn () =>
781 :     (LexState:=0; AdvanceTok(); case !NextTok of
782 :     LEXMARK => ()
783 :     | LEXSTATES =>
784 :     let fun f () = (case !NextTok of (ID i) =>
785 :     (StateTab := enter(!StateTab)(i,++StateNum);
786 :     ++StateNum; AdvanceTok(); f())
787 :     | _ => ())
788 :     in AdvanceTok(); f ();
789 :     if !NextTok=SEMI then ParseDefs() else
790 :     (prSynErr "expected ';'")
791 :     end
792 :     | ID x => (LexState:=1; AdvanceTok(); if GetTok() = ASSIGN
793 :     then (SymTab := enter(!SymTab)(x,GetExp());
794 :     if !NextTok = SEMI then ParseDefs()
795 :     else (prSynErr "expected ';'"))
796 :     else raise SyntaxError)
797 :     | REJECT => (HaveReject := true; ParseDefs())
798 :     | COUNT => (CountNewLines := true; ParseDefs())
799 :     | FULLCHARSET => (CharSetSize := 256; ParseDefs())
800 :     | HEADER => (LexState := 2; AdvanceTok();
801 :     case GetTok()
802 :     of ACTION s =>
803 :     if (!StrDecl) then
804 :     (prErr "cannot have both %structure and %header \
805 :     \declarations")
806 :     else if (!HeaderDecl) then
807 :     (prErr "duplicate %header declarations")
808 :     else
809 :     (HeaderCode := s; LexState := 0;
810 :     HeaderDecl := true; ParseDefs())
811 :     | _ => raise SyntaxError)
812 :     | POSARG => (PosArg := true; ParseDefs())
813 :     | ARG => (LexState := 2; AdvanceTok();
814 :     case GetTok()
815 :     of ACTION s =>
816 :     (case !ArgCode
817 :     of SOME _ => prErr "duplicate %arg declarations"
818 :     | NONE => ArgCode := SOME s;
819 :     LexState := 0;
820 :     ParseDefs())
821 :     | _ => raise SyntaxError)
822 :     | STRUCT => (AdvanceTok();
823 :     case !NextTok of
824 :     (ID i) =>
825 :     if (!HeaderDecl) then
826 :     (prErr "cannot have both %structure and %header \
827 :     \declarations")
828 :     else if (!StrDecl) then
829 :     (prErr "duplicate %structure declarations")
830 :     else (StrName := i; StrDecl := true)
831 :     | _ => (prErr "expected ID");
832 :     ParseDefs())
833 :     | _ => raise SyntaxError)
834 :     and ParseRules =
835 :     fn rules => (LexState:=1; AdvanceTok(); case !NextTok of
836 :     EOF => rules
837 :     | _ =>
838 :     let val s = GetStates()
839 :     val e = renum(CAT(GetExp(),END(0)))
840 :     in
841 :     if !NextTok = ARROW then
842 :     (LexState:=2; AdvanceTok();
843 :     case GetTok() of ACTION(act) =>
844 :     if !NextTok=SEMI then
845 :     (Accept:=enter(!Accept) (Int.toString (!LeafNum),act);
846 :     ParseRules((s,e)::rules))
847 :     else (prSynErr "expected ';'")
848 :     | _ => raise SyntaxError)
849 :     else (prSynErr "expected '=>'")
850 :     end)
851 :     in let val usercode = ParseRtns nil
852 :     in (ParseDefs(); (usercode,ParseRules(nil),!Accept))
853 :     end
854 :     end handle SyntaxError => (prSynErr "")
855 :    
856 :     fun makebegin () : unit =
857 :     let fun make nil = ()
858 :     | make ((x,n:int)::y)=(say "val "; say x; say " = " ;
859 :     say "STARTSTATE ";
860 :     say (Int.toString n); say ";\n"; make y)
861 :     in say "\n(* start state definitions *)\n\n"; make(listofdict(!StateTab))
862 :     end
863 :    
864 :     structure L =
865 :     struct
866 :     nonfix >
867 :     type key = int list * string
868 :     fun > ((key,item:string),(key',item')) =
869 :     let fun f ((a:int)::a') (b::b') = if Int.> (a,b) then true
870 :     else if a=b then f a' b'
871 :     else false
872 :     | f _ _ = false
873 :     in f key key'
874 :     end
875 :     end
876 :    
877 :     structure RB = RedBlack(L)
878 :    
879 :     fun maketable (fins:(int * (int list)) list,
880 :     tcs :(int * (int list)) list,
881 :     tcpairs: (int * int) list,
882 :     trans : (int*(int list)) list) : unit =
883 :    
884 :     (* Fins = (state #, list of final leaves for the state) list
885 :     tcs = (state #, list of trailing context leaves which begin in this state)
886 :     list
887 :     tcpairs = (trailing context leaf, end leaf) list
888 :     trans = (state #,list of transitions for state) list *)
889 :    
890 :     let datatype elem = N of int | T of int | D of int
891 :     val count = ref 0
892 :     val _ = (if length(trans)<256 then CharFormat := true
893 :     else CharFormat := false;
894 :     if !UsesTrailingContext then
895 :     (say "\ndatatype yyfinstate = N of int | \
896 :     \ T of int | D of int\n")
897 :     else say "\ndatatype yyfinstate = N of int";
898 :     say "\ntype statedata = {fin : yyfinstate list, trans: ";
899 :     case !CharFormat of
900 :     true => say "string}"
901 :     | false => say "int Vector.vector}";
902 :     say "\n(* transition & final state table *)\nval tab = let\n";
903 :     case !CharFormat of
904 :     true => ()
905 :     | false =>
906 :     (say "fun decode s k =\n";
907 :     say " let val k' = k + k\n";
908 :     say " val hi = Char.ord(String.sub(s, k'))\n";
909 :     say " val lo = Char.ord(String.sub(s, k' + 1))\n";
910 :     say " in hi * 256 + lo end\n"))
911 :    
912 :     val newfins =
913 :     let fun IsEndLeaf t =
914 :     let fun f ((l,e)::r) = if (e=t) then true else f r
915 :     | f nil = false in f tcpairs end
916 :    
917 : blume 515 fun GetEndLeaf t =
918 : monnier 249 let fun f ((tl,el)::r) = if (tl=t) then el else f r
919 : blume 515 | f _ = raise Match
920 :     in f tcpairs
921 : monnier 249 end
922 :     fun GetTrConLeaves s =
923 :     let fun f ((s',l)::r) = if (s = s') then l else f r
924 :     | f nil = nil
925 :     in f tcs
926 :     end
927 :     fun sort_leaves s =
928 :     let fun insert (x:int) (a::b) =
929 :     if (x <= a) then x::(a::b)
930 :     else a::(insert x b)
931 :     | insert x nil = [x]
932 :     in List.foldr (fn (x,r) => insert x r) [] s
933 :     end
934 :     fun conv a = if (IsEndLeaf a) then (D a) else (N a)
935 :     fun merge (a::a',b::b') =
936 :     if (a <= b) then (conv a)::merge(a',b::b')
937 :     else (T b)::(merge(a::a',b'))
938 :     | merge (a::a',nil) = (conv a)::(merge (a',nil))
939 :     | merge (nil,b::b') = (T b)::(merge (b',nil))
940 :     | merge (nil,nil) = nil
941 :    
942 :     in map (fn (x,l) =>
943 :     rev (merge (l,
944 :     sort_leaves (map (fn x => GetEndLeaf x) (GetTrConLeaves x)))))
945 :     fins
946 :     end
947 :    
948 :     val rs =
949 :     let open RB
950 :     fun makeItems x =
951 :     let fun emit8(x, pos) =
952 :     let val s = StringCvt.padLeft #"0" 3 (Int.toString x)
953 :     in
954 :     case pos
955 :     of 16 => (say "\\\n\\\\"; say s; 1)
956 :     | _ => (say "\\"; say s; pos+1)
957 :     end
958 :     fun emit16(x, pos) =
959 :     let val hi8 = x div 256
960 :     val lo8 = x - hi8 * 256 (* x rem 256 *)
961 :     in
962 :     emit8(lo8, emit8(hi8, pos))
963 :     end
964 :     fun MakeString([], _, _) = ()
965 :     | MakeString(x::xs, emitter, pos) =
966 :     MakeString(xs, emitter, emitter(x, pos))
967 :     in case !CharFormat of
968 :     true => (say " \n\""; MakeString(x,emit8,0); say "\"\n")
969 :     | false => (say (Int.toString(length x));
970 :     say ", \n\""; MakeString(x,emit16,0); say "\"\n")
971 :     end
972 :    
973 :     fun makeEntry(nil,rs,t) = rev rs
974 :     | makeEntry(((l:int,x)::y),rs,t) =
975 :     let val name = (Int.toString l)
976 :     in let val (r,n) = lookup ((x,name),t)
977 :     in makeEntry(y,(n::rs),t)
978 :     end handle notfound _ =>
979 :     (count := !count+1;
980 :     say " ("; say name; say ",";
981 :     makeItems x; say "),\n";
982 :     makeEntry(y,(name::rs),(insert ((x,name),t))))
983 :     end
984 :    
985 :     val _ = say "val s = [ \n"
986 :     val res = makeEntry(trans,nil,empty)
987 :     val _ =
988 :     case !CharFormat
989 :     of true => (say "(0, \"\")]\n"; say "fun f x = x \n")
990 :     | false => (say "(0, 0, \"\")]\n";
991 :     say "fun f(n, i, x) = (n, Vector.tabulate(i, decode x)) \n")
992 :    
993 :     val _ = say "val s = map f (rev (tl (rev s))) \n"
994 :     val _ = say "exception LexHackingError \n"
995 : blume 515 val _ = say "fun look ((j,x)::r, i: int) = if i = j then x else look(r, i) \n"
996 : monnier 249 val _ = say " | look ([], i) = raise LexHackingError\n"
997 :    
998 :     val _ = say "fun g {fin=x, trans=i} = {fin=x, trans=look(s,i)} \n"
999 :     in res
1000 :     end
1001 :    
1002 : blume 515 fun makeTable args = let
1003 :     fun makeOne (a, b) = let
1004 :     fun item (N i) = ("N", i)
1005 :     | item (T i) = ("T", i)
1006 :     | item (D i) = ("D", i)
1007 :     fun makeItem x = let
1008 :     val (t, n) = item x
1009 :     in
1010 :     app say ["(", t, " ", Int.toString n, ")"]
1011 :     end
1012 :     fun makeItems [] = ()
1013 :     | makeItems [x] = makeItem x
1014 :     | makeItems (hd :: tl) =
1015 :     (makeItem hd; say ","; makeItems tl)
1016 :     in
1017 :     say "{fin = [";
1018 :     makeItems b;
1019 :     app say ["], trans = ", a, "}"]
1020 :     end
1021 :     fun mt ([], []) = ()
1022 :     | mt ([a], [b]) = makeOne (a, b)
1023 :     | mt (a :: a', b :: b') =
1024 :     (makeOne (a, b); say ",\n"; mt (a', b'))
1025 :     | mt _ = raise Match
1026 :     in
1027 :     mt args
1028 :     end
1029 :    
1030 :     (*
1031 : monnier 249 fun makeTable(nil,nil) = ()
1032 :     | makeTable(a::a',b::b') =
1033 :     let fun makeItems nil = ()
1034 :     | makeItems (hd::tl) =
1035 :     let val (t,n) =
1036 :     case hd of
1037 :     (N i) => ("(N ",i)
1038 :     | (T i) => ("(T ",i)
1039 :     | (D i) => ("(D ",i)
1040 :     in (say t; say (Int.toString n); say ")";
1041 :     if null tl
1042 :     then ()
1043 :     else (say ","; makeItems tl))
1044 :     end
1045 :     in (say "{fin = ["; makeItems b;
1046 :     say "], trans = "; say a; say "}";
1047 :     if null a'
1048 :     then ()
1049 :     else (say ",\n"; makeTable(a',b')))
1050 :     end
1051 : blume 515 *)
1052 : monnier 249
1053 :     fun msg x = TextIO.output(TextIO.stdOut, x)
1054 :    
1055 :     in (say "in Vector.fromList(map g \n["; makeTable(rs,newfins);
1056 :     say "])\nend\n";
1057 :     msg ("\nNumber of states = " ^ (Int.toString (length trans)));
1058 :     msg ("\nNumber of distinct rows = " ^ (Int.toString (!count)));
1059 :     msg ("\nApprox. memory size of trans. table = " ^
1060 :     (Int.toString (!count*(!CharSetSize)*(if !CharFormat then 1 else 8))));
1061 :     msg " bytes\n")
1062 :     end
1063 :    
1064 :     (* makeaccept: Takes a (string,string) dictionary, prints case statement for
1065 :     accepting leaf actions. The key strings are the leaf #'s, the data strings
1066 :     are the actions *)
1067 :    
1068 :     fun makeaccept ends =
1069 :     let fun startline f = if f then say " " else say "| "
1070 :     fun make(nil,f) = (startline f; say "_ => raise Internal.LexerError\n")
1071 :     | make((x,a)::y,f) = (startline f; say x; say " => ";
1072 :     if Substring.size(#2 (Substring.position "yytext" (Substring.all a))) = 0
1073 :     then
1074 :     (say "("; say a; say ")")
1075 :     else (say "let val yytext=yymktext() in ";
1076 :     say a; say " end");
1077 :     say "\n"; make(y,false))
1078 :     in make (listofdict(ends),true)
1079 :     end
1080 :    
1081 :     fun leafdata(e:(int list * exp) list) =
1082 :     let val fp = array(!LeafNum + 1,nil)
1083 :     and leaf = array(!LeafNum + 1,EPS)
1084 :     and tcpairs = ref nil
1085 :     and trailmark = ref ~1;
1086 :     val rec add = fn
1087 :     (nil,x) => ()
1088 :     | (hd::tl,x) => (update(fp,hd,union(fp sub hd,x));
1089 :     add(tl,x))
1090 :     and moredata = fn
1091 :     CLOSURE(e1) =>
1092 :     (moredata(e1); add(lastpos(e1),firstpos(e1)))
1093 :     | ALT(e1,e2) => (moredata(e1); moredata(e2))
1094 :     | CAT(e1,e2) => (moredata(e1); moredata(e2);
1095 :     add(lastpos(e1),firstpos(e2)))
1096 :     | CLASS(x,i) => update(leaf,i,CLASS(x,i))
1097 :     | TRAIL(i) => (update(leaf,i,TRAIL(i)); if !trailmark = ~1
1098 :     then trailmark := i else ())
1099 :     | END(i) => (update(leaf,i,END(i)); if !trailmark <> ~1
1100 :     then (tcpairs := (!trailmark,i)::(!tcpairs);
1101 :     trailmark := ~1) else ())
1102 :     | _ => ()
1103 :     and makedata = fn
1104 :     nil => ()
1105 :     | (_,x)::tl => (moredata(x);makedata(tl))
1106 :     in trailmark := ~1; makedata(e); (fp,leaf,!tcpairs)
1107 :     end;
1108 :    
1109 :     fun makedfa(rules) =
1110 :     let val StateTab = ref (create(String.<=)) : (string,int) dictionary ref
1111 :     val fintab = ref (create(Int.<=)) : (int,(int list)) dictionary ref
1112 :     val transtab = ref (create(Int.<=)) : (int,int list) dictionary ref
1113 :     val tctab = ref (create(Int.<=)) : (int,(int list)) dictionary ref
1114 :     val (fp, leaf, tcpairs) = leafdata(rules);
1115 :    
1116 :     fun visit (state,statenum) =
1117 :     let val transitions = gettrans(state) in
1118 :     fintab := enter(!fintab)(statenum,getfin(state));
1119 :     tctab := enter(!tctab)(statenum,gettc(state));
1120 :     transtab := enter(!transtab)(statenum,transitions)
1121 :     end
1122 :    
1123 :     and visitstarts (states) =
1124 :     let fun vs nil i = ()
1125 :     | vs (hd::tl) i = (visit (hd,i); vs tl (i+1))
1126 :     in vs states 0
1127 :     end
1128 :    
1129 :     and hashstate(s: int list) =
1130 :     let val rec hs =
1131 :     fn (nil,z) => z
1132 :     | ((x:int)::y,z) => hs(y,z ^ " " ^ (Int.toString x))
1133 :     in hs(s,"")
1134 :     end
1135 :    
1136 :     and find(s) = lookup(!StateTab)(hashstate(s))
1137 :    
1138 :     and add(s,n) = StateTab := enter(!StateTab)(hashstate(s),n)
1139 :    
1140 :     and getstate (state) =
1141 :     find(state)
1142 :     handle LOOKUP => let val n = ++StateNum in
1143 :     add(state,n); visit(state,n); n
1144 :     end
1145 :    
1146 :     and getfin state =
1147 :     let fun f nil fins = fins
1148 :     | f (hd::tl) fins =
1149 :     case (leaf sub hd)
1150 :     of END _ => f tl (hd::fins)
1151 :     | _ => f tl fins
1152 :     in f state nil
1153 :     end
1154 :    
1155 :     and gettc state =
1156 :     let fun f nil fins = fins
1157 :     | f (hd::tl) fins =
1158 :     case (leaf sub hd)
1159 :     of TRAIL _ => f tl (hd::fins)
1160 :     | _ => f tl fins
1161 :     in f state nil
1162 :     end
1163 :    
1164 :     and gettrans (state) =
1165 :     let fun loop c tlist =
1166 :     let fun cktrans nil r = r
1167 :     | cktrans (hd::tl) r =
1168 :     case (leaf sub hd) of
1169 :     CLASS(i,_)=>
1170 :     (if (i sub c) then cktrans tl (union(r,fp sub hd))
1171 :     else cktrans tl r handle Subscript =>
1172 :     cktrans tl r
1173 :     )
1174 :     | _ => cktrans tl r
1175 :     in if c >= 0 then
1176 :     let val v=cktrans state nil
1177 :     in loop (c-1) (if v=nil then 0::tlist else (getstate v)::tlist)
1178 :     end
1179 :     else tlist
1180 :     end
1181 :     in loop ((!CharSetSize) - 1) nil
1182 :     end
1183 :    
1184 :     and startstates() =
1185 :     let val startarray = array(!StateNum + 1, nil);
1186 :     fun listofarray(a,n) =
1187 :     let fun f i l = if i >= 0 then f (i-1) ((a sub i)::l) else l
1188 :     in f (n-1) nil end
1189 :     val rec makess = fn
1190 :     nil => ()
1191 :     | (startlist,e)::tl => (fix(startlist,firstpos(e));makess(tl))
1192 :     and fix = fn
1193 :     (nil,_) => ()
1194 :     | (s::tl,firsts) => (update(startarray,s,
1195 :     union(firsts,startarray sub s));
1196 :     fix(tl,firsts))
1197 :     in makess(rules);listofarray(startarray, !StateNum + 1)
1198 :     end
1199 :    
1200 :     in visitstarts(startstates());
1201 :     (listofdict(!fintab),listofdict(!transtab),listofdict(!tctab),tcpairs)
1202 :     end
1203 :    
1204 :     val skel_hd =
1205 :     " struct\n\
1206 :     \ structure UserDeclarations =\n\
1207 :     \ struct\n\
1208 :     \"
1209 :    
1210 :     val skel_mid2 =
1211 :     " | Internal.D k => action (i,(acts::l),k::rs)\n\
1212 :     \ | Internal.T k =>\n\
1213 :     \ let fun f (a::b,r) =\n\
1214 :     \ if a=k\n\
1215 :     \ then action(i,(((Internal.N a)::acts)::l),(b@r))\n\
1216 :     \ else f (b,a::r)\n\
1217 :     \ | f (nil,r) = action(i,(acts::l),rs)\n\
1218 :     \ in f (rs,nil)\n\
1219 :     \ end\n\
1220 :     \"
1221 :    
1222 :     fun lexGen(infile) =
1223 :     let val outfile = infile ^ ".sml"
1224 :     fun PrintLexer (ends) =
1225 :     let val sayln = fn x => (say x; say "\n")
1226 :     in case !ArgCode
1227 :     of NONE => (sayln "fun lex () : Internal.result =";
1228 :     sayln "let fun continue() = lex() in")
1229 :     | SOME s => (say "fun lex "; say "(yyarg as ("; say s; sayln ")) =";
1230 :     sayln "let fun continue() : Internal.result = ");
1231 :     say " let fun scan (s,AcceptingLeaves : Internal.yyfinstate";
1232 :     sayln " list list,l,i0) =";
1233 :     if !UsesTrailingContext
1234 :     then say "\tlet fun action (i,nil,rs)"
1235 :     else say "\tlet fun action (i,nil)";
1236 :     sayln " = raise LexError";
1237 :     if !UsesTrailingContext
1238 :     then sayln "\t| action (i,nil::l,rs) = action(i-1,l,rs)"
1239 :     else sayln "\t| action (i,nil::l) = action (i-1,l)";
1240 :     if !UsesTrailingContext
1241 :     then sayln "\t| action (i,(node::acts)::l,rs) ="
1242 :     else sayln "\t| action (i,(node::acts)::l) =";
1243 :     sayln "\t\tcase node of";
1244 :     sayln "\t\t Internal.N yyk => ";
1245 :     sayln "\t\t\t(let fun yymktext() = substring(!yyb,i0,i-i0)\n\
1246 :     \\t\t\t val yypos = i0+ !yygone";
1247 :     if !CountNewLines
1248 : monnier 418 then (sayln "\t\t\tval _ = yylineno := CharVector.foldli";
1249 : monnier 249 sayln "\t\t\t\t(fn (_,#\"\\n\", n) => n+1 | (_,_, n) => n) (!yylineno) (!yyb,i0,SOME(i-i0))")
1250 :     else ();
1251 :     if !HaveReject
1252 :     then (say "\t\t\tfun REJECT() = action(i,acts::l";
1253 :     if !UsesTrailingContext
1254 :     then sayln ",rs)" else sayln ")")
1255 :     else ();
1256 :     sayln "\t\t\topen UserDeclarations Internal.StartStates";
1257 :     sayln " in (yybufpos := i; case yyk of ";
1258 :     sayln "";
1259 :     sayln "\t\t\t(* Application actions *)\n";
1260 :     makeaccept(ends);
1261 :     say "\n\t\t) end ";
1262 :     say ")\n\n";
1263 :     if (!UsesTrailingContext) then say skel_mid2 else ();
1264 :     sayln "\tval {fin,trans} = Unsafe.Vector.sub(Internal.tab, s)";
1265 :     sayln "\tval NewAcceptingLeaves = fin::AcceptingLeaves";
1266 :     sayln "\tin if l = !yybl then";
1267 :     sayln "\t if trans = #trans(Vector.sub(Internal.tab,0))";
1268 :     sayln "\t then action(l,NewAcceptingLeaves";
1269 :     if !UsesTrailingContext then say ",nil" else ();
1270 :     say ") else";
1271 :     sayln "\t let val newchars= if !yydone then \"\" else yyinput 1024";
1272 :     sayln "\t in if (size newchars)=0";
1273 :     sayln "\t\t then (yydone := true;";
1274 :     say "\t\t if (l=i0) then UserDeclarations.eof ";
1275 :     sayln (case !ArgCode of NONE => "()" | SOME _ => "yyarg");
1276 :     say "\t\t else action(l,NewAcceptingLeaves";
1277 :     if !UsesTrailingContext then
1278 :     sayln ",nil))" else sayln "))";
1279 :     sayln "\t\t else (if i0=l then yyb := newchars";
1280 :     sayln "\t\t else yyb := substring(!yyb,i0,l-i0)^newchars;";
1281 :     sayln "\t\t yygone := !yygone+i0;";
1282 :     sayln "\t\t yybl := size (!yyb);";
1283 :     sayln "\t\t scan (s,AcceptingLeaves,l-i0,0))";
1284 :     sayln "\t end";
1285 :     sayln "\t else let val NewChar = Char.ord(Unsafe.CharVector.sub(!yyb,l))";
1286 :     if !CharSetSize=129
1287 :     then sayln "\t\tval NewChar = if NewChar<128 then NewChar else 128"
1288 :     else ();
1289 :     say "\t\tval NewState = ";
1290 :     sayln (if !CharFormat
1291 :     then "Char.ord(Unsafe.CharVector.sub(trans,NewChar))"
1292 :     else "Unsafe.Vector.sub(trans, NewChar)");
1293 :     say "\t\tin if NewState=0 then action(l,NewAcceptingLeaves";
1294 :     if !UsesTrailingContext then sayln ",nil)" else sayln ")";
1295 :     sayln "\t\telse scan(NewState,NewAcceptingLeaves,l+1,i0)";
1296 :     sayln "\tend";
1297 :     sayln "\tend";
1298 :     if !UsesPrevNewLine then () else sayln "(*";
1299 :     sayln "\tval start= if substring(!yyb,!yybufpos-1,1)=\"\\n\"";
1300 :     sayln "then !yybegin+1 else !yybegin";
1301 :     if !UsesPrevNewLine then () else sayln "*)";
1302 :     say "\tin scan(";
1303 :     if !UsesPrevNewLine then say "start"
1304 :     else say "!yybegin (* start *)";
1305 :     sayln ",nil,!yybufpos,!yybufpos)";
1306 :     sayln " end";
1307 :     sayln (case !ArgCode of NONE => "end" | SOME _ => "in continue end");
1308 :     sayln " in lex";
1309 :     sayln " end";
1310 :     sayln "end"
1311 :     end
1312 :    
1313 :     in (UsesPrevNewLine := false;
1314 :     ResetFlags();
1315 :     LexBuf := make_ibuf(TextIO.openIn infile);
1316 :     NextTok := BOF;
1317 :     inquote := false;
1318 :     LexOut := TextIO.openOut(outfile);
1319 :     StateNum := 2;
1320 :     LineNum := 1;
1321 :     StateTab := enter(create(String.<=))("INITIAL",1);
1322 :     LeafNum := ~1;
1323 :     let
1324 :     val (user_code,rules,ends) =
1325 :     parse() handle x =>
1326 :     (close_ibuf(!LexBuf);
1327 :     TextIO.closeOut(!LexOut);
1328 :     OS.FileSys.remove outfile;
1329 :     raise x)
1330 :     val (fins,trans,tctab,tcpairs) = makedfa(rules)
1331 :     val _ = if !UsesTrailingContext then
1332 :     (close_ibuf(!LexBuf);
1333 :     TextIO.closeOut(!LexOut);
1334 :     OS.FileSys.remove outfile;
1335 :     prErr "lookahead is unimplemented")
1336 :     else ()
1337 :     in
1338 :     if (!HeaderDecl)
1339 :     then say (!HeaderCode)
1340 :     else say ("structure " ^ (!StrName));
1341 :     say "=\n";
1342 :     say skel_hd;
1343 :     say user_code;
1344 :     say "end (* end of user routines *)\n";
1345 :     say "exception LexError (* raised if illegal leaf ";
1346 :     say "action tried *)\n";
1347 :     say "structure Internal =\n\tstruct\n";
1348 :     maketable(fins,tctab,tcpairs,trans);
1349 :     say "structure StartStates =\n\tstruct\n";
1350 :     say "\tdatatype yystartstate = STARTSTATE of int\n";
1351 :     makebegin();
1352 :     say "\nend\n";
1353 :     say "type result = UserDeclarations.lexresult\n";
1354 :     say "\texception LexerError (* raised if illegal leaf ";
1355 :     say "action tried *)\n";
1356 :     say "end\n\n";
1357 :     say (if (!PosArg) then "fun makeLexer (yyinput,yygone0:int) =\nlet\n"
1358 :     else "fun makeLexer yyinput =\nlet\tval yygone0=1\n");
1359 :     if !CountNewLines then say "\tval yylineno = ref 0\n\n" else ();
1360 :     say "\tval yyb = ref \"\\n\" \t\t(* buffer *)\n\
1361 :     \\tval yybl = ref 1\t\t(*buffer length *)\n\
1362 :     \\tval yybufpos = ref 1\t\t(* location of next character to use *)\n\
1363 :     \\tval yygone = ref yygone0\t(* position in file of beginning of buffer *)\n\
1364 :     \\tval yydone = ref false\t\t(* eof found yet? *)\n\
1365 :     \\tval yybegin = ref 1\t\t(*Current 'start state' for lexer *)\n\
1366 :     \\n\tval YYBEGIN = fn (Internal.StartStates.STARTSTATE x) =>\n\
1367 :     \\t\t yybegin := x\n\n";
1368 :     PrintLexer(ends);
1369 :     close_ibuf(!LexBuf);
1370 :     TextIO.closeOut(!LexOut)
1371 :     end)
1372 :     end
1373 :     end

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0