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 656 - (view) (download)
Original Path: sml/trunk/src/ml-lex/lexgen.sml

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

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