Debian Codegraph @

mllex/lexgen.sml

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