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/releases/release-110.60/lexgen.sml
ViewVC logotype

Annotation of /ml-lex/releases/release-110.60/lexgen.sml

Parent Directory Parent Directory | Revision Log Revision Log


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

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