-
Notifications
You must be signed in to change notification settings - Fork 127
/
lexgen.sml
1488 lines (1361 loc) · 59 KB
/
lexgen.sml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(* Modified by Matthew Fluet on 2011-06-17.
* Use simple file name (rather than absolute paths) in line directives in output.
*)
(* Modified by Vesa Karvonen on 2007-12-19.
* Create line directives in output.
*)
(* Modified by Matthew Fluet on 2007-11-07.
* Add %posint command.
*)
(* Modified by StephenWeeks on 2005-08-18.
* Fix file starting position
*)
(* Modified by Stephen Weeks on 2004-10-19.
* Do not create references to Unsafe structure.
*)
(* Lexical analyzer generator for Standard ML.
Version 1.7.0, June 1998
Copyright (c) 1989-1992 by Andrew W. Appel,
David R. Tarditi, James S. Mattson
This software comes with ABSOLUTELY NO WARRANTY.
This software is subject only to the PRINCETON STANDARD ML SOFTWARE LIBRARY
COPYRIGHT NOTICE, LICENSE AND DISCLAIMER, (in the file "COPYRIGHT",
distributed with this software). You may copy and distribute this software;
see the COPYRIGHT NOTICE for details and restrictions.
Changes:
07/25/89 (drt): added %header declaration, code to place
user declarations at same level as makeLexer, etc.
This is needed for the parser generator.
/10/89 (appel): added %arg declaration (see lexgen.doc).
/04/90 (drt): fixed following bug: couldn't use the lexer after an
error occurred -- NextTok and inquote weren't being reset
10/22/91 (drt): disabled use of lookahead
10/23/92 (drt): disabled use of $ operator (which involves lookahead),
added handlers for dictionary lookup routine
11/02/92 (drt): changed handler for exception Reject in generated lexer
to Internal.Reject
02/01/94 (appel): Moved the exception handler for Reject in such
a way as to allow tail-recursion (improves performance
wonderfully!).
02/01/94 (appel): Fixed a bug in parsing of state names.
05/19/94 (Mikael Pettersson, [email protected]):
Transition tables are usually represented as strings, but
when the range is too large, int vectors constructed by
code like "Vector.vector[1,2,3,...]" are used instead.
The problem with this isn't that the vector itself takes
a lot of space, but that the code generated by SML/NJ to
construct the intermediate list at run-time is *HUGE*. My
fix is to encode an int vector as a string literal (using
two bytes per int) and emit code to decode the string to
a vector at run-time. SML/NJ compiles string literals into
substrings in the code, so this uses much less space.
06/02/94 (jhr): Modified export-lex.sml to conform to new installation
scheme. Also removed tab characters from string literals.
10/05/94 (jhr): Changed generator to produce code that uses the new
basis style strings and characters.
10/06/94 (jhr) Modified code to compile under new basis style strings
and characters.
02/08/95 (jhr) Modified to use new List module interface.
05/18/95 (jhr) changed Vector.vector to Vector.fromList
04/07/20 (jhr) Switch to using RedBlackMapFn from SML/NJ Library
04/07/20 (jhr) Replaced uses of polymorphic equality with pattern
matching.
* Revision 1.9 1998/01/06 19:23:53 appel
* added %posarg feature to permit position-within-file to be passed
* as a parameter to makeLexer
*
# Revision 1.8 1998/01/06 19:01:48 appel
# repaired error messages like "cannot have both %structure and %header"
#
# Revision 1.7 1998/01/06 18:55:49 appel
# permit %% to be unescaped within regular expressions
#
# Revision 1.6 1998/01/06 18:46:13 appel
# removed undocumented feature that permitted extra %% at end of rules
#
# Revision 1.5 1998/01/06 18:29:23 appel
# put yylineno variable inside makeLexer function
#
# Revision 1.4 1998/01/06 18:19:59 appel
# check for newline inside quoted string
#
# Revision 1.3 1997/10/04 03:52:13 dbm
# Fix to remove output file if ml-lex fails.
#
10/17/02 (jhr) changed bad character error message to properly
print the bad character.
10/17/02 (jhr) fixed skipws to use Char.isSpace test.
07/27/05 (jhr) add \r as a recognized escape sequence.
*)
(* Subject: lookahead in sml-lex
Reply-to: [email protected]
Date: Mon, 21 Oct 91 14:13:26 -0400
There is a serious bug in the implementation of lookahead,
as done in sml-lex, and described in Aho, Sethi, and Ullman,
p. 134 "Implementing the Lookahead Operator"
We have disallowed the use of lookahead for now because
of this bug.
As a counter-example to the implementation described in
ASU, consider the following specification with the
input string "aba" (this example is taken from
a comp.compilers message from Dec. 1989, I think):
type lexresult=unit
val linenum = ref 1
fun error x = TextIO.output(TextIO.stdErr, x ^ "\n")
val eof = fn () => ()
%%
%structure Lex
%%
(a|ab)/ba => (print yytext; print "\n"; ());
The ASU proposal works as follows. Suppose that we are
using NFA's to represent our regular expressions. Then to
build an NFA for e1 / e2, we build an NFA n1 for e1
and an NFA n2 for e2, and add an epsilon transition
from e1 to e2.
When lexing, when we encounter the end state of e1e2,
we take as the end of the string the position in
the string that was the last occurrence of the state of
the NFA having a transition on the epsilon introduced
for /.
Using the example we have above, we'll have an NFA
with the following states:
1 -- a --> 2 -- b --> 3
| |
| epsilon | epsilon
| |
|------------> 4 -- b --> 5 -- a --> 6
On our example, we get the following list of transitions:
a : 2, 4 (make an epsilon transition from 2 to 4)
ab : 3, 4, 5 (make an epsilon transition from 3 to 4)
aba : 6
If we chose the last state in which we made an epsilon transition,
we'll chose the transition from 3 to 4, and end up with "ab"
as our token, when we should have "a" as our token.
*)
(*
functor RedBlack(B : sig type key
val > : key*key->bool
end):
sig type tree
type key
val empty : tree
val insert : key * tree -> tree
val lookup : key * tree -> key
exception notfound of key
end =
struct
open B
datatype color = RED | BLACK
datatype tree = empty | tree of key * color * tree * tree
exception notfound of key
fun insert (key,t) =
let fun f empty = tree(key,RED,empty,empty)
| f (tree(k,BLACK,l,r)) =
if key>k
then case f r
of r as tree(rk,RED, rl as tree(rlk,RED,rll,rlr),rr) =>
(case l
of tree(lk,RED,ll,lr) =>
tree(k,RED,tree(lk,BLACK,ll,lr),
tree(rk,BLACK,rl,rr))
| _ => tree(rlk,BLACK,tree(k,RED,l,rll),
tree(rk,RED,rlr,rr)))
| r as tree(rk,RED,rl, rr as tree(rrk,RED,rrl,rrr)) =>
(case l
of tree(lk,RED,ll,lr) =>
tree(k,RED,tree(lk,BLACK,ll,lr),
tree(rk,BLACK,rl,rr))
| _ => tree(rk,BLACK,tree(k,RED,l,rl),rr))
| r => tree(k,BLACK,l,r)
else if k>key
then case f l
of l as tree(lk,RED,ll, lr as tree(lrk,RED,lrl,lrr)) =>
(case r
of tree(rk,RED,rl,rr) =>
tree(k,RED,tree(lk,BLACK,ll,lr),
tree(rk,BLACK,rl,rr))
| _ => tree(lrk,BLACK,tree(lk,RED,ll,lrl),
tree(k,RED,lrr,r)))
| l as tree(lk,RED, ll as tree(llk,RED,lll,llr), lr) =>
(case r
of tree(rk,RED,rl,rr) =>
tree(k,RED,tree(lk,BLACK,ll,lr),
tree(rk,BLACK,rl,rr))
| _ => tree(lk,BLACK,ll,tree(k,RED,lr,r)))
| l => tree(k,BLACK,l,r)
else tree(key,BLACK,l,r)
| f (tree(k,RED,l,r)) =
if key>k then tree(k,RED,l, f r)
else if k>key then tree(k,RED, f l, r)
else tree(key,RED,l,r)
in case f t
of tree(k,RED, l as tree(_,RED,_,_), r) => tree(k,BLACK,l,r)
| tree(k,RED, l, r as tree(_,RED,_,_)) => tree(k,BLACK,l,r)
| t => t
end
fun lookup (key,t) =
let fun look empty = raise (notfound key)
| look (tree(k,_,l,r)) =
if k>key then look l
else if key>k then look r
else k
in look t
end
end
*)
signature LEXGEN =
sig
val lexGen: string -> unit
end
structure LexGen: LEXGEN =
struct
val sub = Array.sub
infix 9 sub
type pos = {line : int, col : int}
datatype token = CHARS of bool array | QMARK | STAR | PLUS | BAR
| LP | RP | CARAT | DOLLAR | SLASH | STATE of string list
| REPS of int * int | ID of string | ACTION of pos * string
| BOF | EOF | ASSIGN | SEMI | ARROW | LEXMARK | LEXSTATES
| COUNT | REJECT | FULLCHARSET | STRUCT | HEADER | ARG | POSARG
| POSINT
datatype exp = EPS | CLASS of bool array * int | CLOSURE of exp
| ALT of exp * exp | CAT of exp * exp | TRAIL of int
| END of int
(* flags describing input Lex spec. - unnecessary code is omitted *)
(* if possible *)
val CharFormat = ref false;
val UsesTrailingContext = ref false;
val UsesPrevNewLine = ref false;
(* flags for various bells & whistles that Lex has. These slow the
lexer down and should be omitted from production lexers (if you
really want speed) *)
val CountNewLines = ref false;
val PosArg = ref false;
val HaveReject = ref false;
(* Can increase size of character set *)
val CharSetSize = ref 129;
(* Can name structure or declare header code *)
val StrName = ref "Mlex"
val HeaderCode = ref ""
val HeaderPos = ref {line = 0, col = 0}
val HeaderDecl = ref false
val ArgCode = ref (NONE: (pos * string) option)
val StrDecl = ref false
(* Can define INTEGER structure for yypos variable. *)
val PosIntName = ref "Int"
val PosIntDecl = ref false
val ResetFlags = fn () => (CountNewLines := false; HaveReject := false;
PosArg := false;
UsesTrailingContext := false;
CharSetSize := 129; StrName := "Mlex";
HeaderCode := ""; HeaderDecl:= false;
ArgCode := NONE;
StrDecl := false;
PosIntName := "Int"; PosIntDecl := false)
val LexOut = ref(TextIO.stdOut)
val LexOutLine = ref 1
fun setLexOut s = (LexOut := s; LexOutLine := 1)
fun say x =
(TextIO.output (!LexOut, x)
; CharVector.app
(fn #"\n" => LexOutLine := !LexOutLine + 1 | _ => ())
x)
val InFile = ref ""
val OutFile = ref ""
fun fmtLineDir {line, col} file =
String.concat ["(*#line ", Int.toString line, ".", Int.toString (col+1),
" \"", file, "\"*)"]
val sayPos =
fn SOME pos => say (fmtLineDir pos (!InFile))
| NONE => (say (fmtLineDir {line = !LexOutLine, col = 0} (!OutFile));
say "\n")
(* Union: merge two sorted lists of integers *)
fun union(a,b) = let val rec merge = fn
(nil,nil,z) => z
| (nil,el::more,z) => merge(nil,more,el::z)
| (el::more,nil,z) => merge(more,nil,el::z)
| (x::morex,y::morey,z) => if (x:int)=(y:int)
then merge(morex,morey,x::z)
else if x>y then merge(morex,y::morey,x::z)
else merge(x::morex,morey,y::z)
in merge(rev a,rev b,nil)
end
(* Nullable: compute if a important expression parse tree node is nullable *)
val rec nullable = fn
EPS => true
| CLASS(_) => false
| CLOSURE(_) => true
| ALT(n1,n2) => nullable(n1) orelse nullable(n2)
| CAT(n1,n2) => nullable(n1) andalso nullable(n2)
| TRAIL(_) => true
| END(_) => false
(* FIRSTPOS: firstpos function for parse tree expressions *)
and firstpos = fn
EPS => nil
| CLASS(_,i) => [i]
| CLOSURE(n) => firstpos(n)
| ALT(n1,n2) => union(firstpos(n1),firstpos(n2))
| CAT(n1,n2) => if nullable(n1) then union(firstpos(n1),firstpos(n2))
else firstpos(n1)
| TRAIL(i) => [i]
| END(i) => [i]
(* LASTPOS: Lastpos function for parse tree expressions *)
and lastpos = fn
EPS => nil
| CLASS(_,i) => [i]
| CLOSURE(n) => lastpos(n)
| ALT(n1,n2) => union(lastpos(n1),lastpos(n2))
| CAT(n1,n2) => if nullable(n2) then union(lastpos(n1),lastpos(n2))
else lastpos(n2)
| TRAIL(i) => [i]
| END(i) => [i]
;
(* ++: Increment an integer reference *)
fun ++(x) : int = (x := !x + 1; !x);
structure dict =
struct
type 'a relation = 'a * 'a -> bool
abstype ('b,'a) dictionary = DATA of { Table : ('b * 'a) list,
Leq : 'b * 'b -> bool }
with
exception LOOKUP
fun create Leqfunc = DATA { Table = nil, Leq = Leqfunc }
fun lookup (DATA { Table = entrylist, Leq = leq }) key =
let fun search [] = raise LOOKUP
| search((k,item)::entries) =
if leq(key,k)
then if leq(k,key) then item else raise LOOKUP
else search entries
in search entrylist
end
fun enter (DATA { Table = entrylist, Leq = leq })
(newentry as (key : 'b,item :'a)) : ('b,'a) dictionary =
let val gt = fn a => fn b => not (leq(a,b))
val eq = fn k => fn k' => (leq(k,k')) andalso (leq(k',k))
fun update nil = [ newentry ]
| update ((entry as (k,_))::entries) =
if (eq key k) then newentry::entries
else if gt k key then newentry::(entry::entries)
else entry::(update entries)
in DATA { Table = update entrylist, Leq = leq }
end
fun listofdict (DATA { Table = entrylist,Leq = leq}) =
let fun f (nil,r) = rev r
| f (a::b,r) = f (b,a::r)
in f(entrylist,nil)
end
end
end
open dict;
(* INPUT.ML : Input w/ one character push back capability *)
val LineNum = ref 1;
abstype ibuf =
BUF of TextIO.instream * {b : string ref, p : int ref}
with
local
val pos = ref 0
val linePos = ref 0 (* incorrect after ungetch newline, non fatal *)
in
fun resetLexPos () = (LineNum := 1; pos := 0; linePos :=0)
fun getLexPos () = {line = !LineNum, col = !pos - !linePos}
fun make_ibuf(s) = BUF (s, {b=ref"", p = ref 0})
fun close_ibuf (BUF (s,_)) = TextIO.closeIn(s)
exception eof
fun getch (a as (BUF(s,{b,p}))) =
if (!p = (size (!b)))
then (b := TextIO.inputN(s, 1024);
p := 0;
if (size (!b))=0
then raise eof
else getch a)
else (let val ch = String.sub(!b,!p)
in (pos := !pos + 1;
if ch = #"\n"
then (LineNum := !LineNum + 1;
linePos := !pos)
else ();
p := !p + 1;
ch)
end)
fun ungetch(BUF(s,{b,p})) = (
pos := !pos - 1;
p := !p - 1;
if String.sub(!b,!p) = #"\n"
then LineNum := !LineNum - 1
else ())
end
end;
exception Error
fun prErr x = (
TextIO.output (TextIO.stdErr, String.concat [
"ml-lex: error, line ", (Int.toString (!LineNum)), ": ", x, "\n"
]);
raise Error)
fun prSynErr x = (
TextIO.output (TextIO.stdErr, String.concat [
"ml-lex: syntax error, line ", (Int.toString (!LineNum)), ": ", x, "\n"
]);
raise Error)
exception SyntaxError; (* error in user's input file *)
exception LexError; (* unexpected error in lexer *)
val LexBuf = ref(make_ibuf(TextIO.stdIn));
val LexState = ref 0;
val NextTok = ref BOF;
val inquote = ref false;
fun AdvanceTok () : unit = let
fun isLetter c =
((c >= #"a") andalso (c <= #"z")) orelse
((c >= #"A") andalso (c <= #"Z"))
fun isDigit c = (c >= #"0") andalso (c <= #"9")
(* check for valid (non-leading) identifier character (added by JHR) *)
fun isIdentChr c =
((isLetter c) orelse (isDigit c) orelse (c = #"_") orelse (c = #"'"))
fun atoi s = let
fun num (c::r, n) = if isDigit c
then num (r, 10*n + (Char.ord c - Char.ord #"0"))
else n
| num ([], n) = n
in
num (explode s, 0)
end
fun skipws () = let val ch = nextch()
in
if Char.isSpace ch
then skipws()
else ch
end
and nextch () = getch(!LexBuf)
and escaped () = (case nextch()
of #"b" => #"\008"
| #"n" => #"\n"
| #"r" => #"\r"
| #"t" => #"\t"
| #"h" => #"\128"
| x => let
fun err t = prErr("illegal ascii escape '"^(implode(rev t))^"'")
fun cvt c = (Char.ord c - Char.ord #"0")
fun f (n, c, t) = if c=3
then if n >= (!CharSetSize)
then err t
else Char.chr n
else let val ch=nextch()
in
if isDigit ch
then f(n*10+(cvt ch), c+1, ch::t)
else err t
end
in
if isDigit x then f(cvt x, 1, [x]) else x
end
(* end case *))
and onechar x = let val c = Array.array(!CharSetSize, false)
in
Array.update(c, Char.ord(x), true); CHARS(c)
end
in case !LexState of 0 => let val makeTok = fn () =>
case skipws()
(* Lex % operators *)
of #"%" => (case nextch() of
#"%" => LEXMARK
| a => let fun f s =
let val a = nextch()
in if isLetter a then f(a::s)
else (ungetch(!LexBuf);
implode(rev s))
end
in case f [a]
of "reject" => REJECT
| "count" => COUNT
| "full" => FULLCHARSET
| "s" => LEXSTATES
| "S" => LEXSTATES
| "structure" => STRUCT
| "header" => HEADER
| "arg" => ARG
| "posarg" => POSARG
| "posint" => POSINT
| _ => prErr "unknown % operator "
end
)
(* semicolon (for end of LEXSTATES) *)
| #";" => SEMI
(* anything else *)
| ch => if isLetter(ch) then
let fun getID matched =
let val x = nextch()
(**** fix by JHR
in if isLetter(x) orelse isDigit(x) orelse
x = "_" orelse x = "'"
****)
in if (isIdentChr x)
then getID (x::matched)
else (ungetch(!LexBuf); implode(rev matched))
end
in ID(getID [ch])
end
else prSynErr (String.concat[
"bad character: \"", Char.toString ch, "\""
])
in NextTok := makeTok()
end
| 1 => let val rec makeTok = fn () =>
if !inquote then case nextch() of
(* inside quoted string *)
#"\\" => onechar(escaped())
| #"\"" => (inquote := false; makeTok())
| #"\n" => (prSynErr "end-of-line inside quoted string";
inquote := false; makeTok())
| x => onechar(x)
else case skipws() of
(* single character operators *)
#"?" => QMARK
| #"*" => STAR
| #"+" => PLUS
| #"|" => BAR
| #"(" => LP
| #")" => RP
| #"^" => CARAT
| #"$" => DOLLAR
| #"/" => SLASH
| #";" => SEMI
| #"." => let val c = Array.array(!CharSetSize,true) in
Array.update(c,10,false); CHARS(c)
end
(* assign and arrow *)
| #"=" => let val c = nextch() in
if c = #">" then ARROW else (ungetch(!LexBuf); ASSIGN)
end
(* character set *)
| #"[" => let val rec classch = fn () => let val x = skipws()
in if x = #"\\" then escaped() else x
end;
val first = classch();
val flag = (first <> #"^");
val c = Array.array(!CharSetSize,not flag);
fun add NONE = ()
| add (SOME x) = Array.update(c, Char.ord(x), flag)
and range (x, y) = if x>y
then (prErr "bad char. range")
else let
val i = ref(Char.ord(x)) and j = Char.ord(y)
in while !i<=j do (
add (SOME(Char.chr(!i)));
i := !i + 1)
end
and getClass last = (case classch()
of #"]" => (add(last); c)
| #"-" => (case last
of NONE => getClass(SOME #"-")
| (SOME last') => let val x = classch()
in
if x = #"]"
then (add(last); add(SOME #"-"); c)
else (range(last',x); getClass(NONE))
end
(* end case *))
| x => (add(last); getClass(SOME x))
(* end case *))
in CHARS(getClass(if first = #"^" then NONE else SOME first))
end
(* Start States specification *)
| #"<" => let val rec get_state = fn (prev,matched) =>
case nextch() of
#">" => matched::prev
| #"," => get_state(matched::prev,"")
| x => if isIdentChr(x)
then get_state(prev,matched ^ String.str x)
else (prSynErr "bad start state list")
in STATE(get_state(nil,""))
end
(* {id} or repititions *)
| #"{" => let val ch = nextch() in if isLetter(ch) then
let fun getID matched = (case nextch()
of #"}" => matched
| x => if (isIdentChr x) then
getID(matched ^ String.str x)
else (prErr "invalid char. class name")
(* end case *))
in ID(getID(String.str ch))
end
else if isDigit(ch) then
let fun get_r (matched, r1) = (case nextch()
of #"}" => let val n = atoi(matched) in
if r1 = ~1 then (n,n) else (r1,n)
end
| #"," => if r1 = ~1 then get_r("",atoi(matched))
else (prErr "invalid repetitions spec.")
| x => if isDigit(x)
then get_r(matched ^ String.str x,r1)
else (prErr "invalid char in repetitions spec")
(* end case *))
in REPS(get_r(String.str ch,~1))
end
else (prErr "bad repetitions spec")
end
(* Lex % operators *)
| #"\\" => onechar(escaped())
(* start quoted string *)
| #"\"" => (inquote := true; makeTok())
(* anything else *)
| ch => onechar(ch)
in NextTok := makeTok()
end
| 2 => NextTok :=
(case skipws() of
#"(" =>
let
fun loop_to_end (backslash, x) =
let
val c = getch (! LexBuf)
val notb = not backslash
val nstr = c :: x
in
case c of
#"\"" => if notb then nstr
else loop_to_end (false, nstr)
| _ => loop_to_end (c = #"\\" andalso notb, nstr)
end
fun GetAct (lpct, x) =
let
val c = getch (! LexBuf)
val nstr = c :: x
in
case c of
#"\"" => GetAct (lpct, loop_to_end (false, nstr))
| #"(" => GetAct (lpct + 1, nstr)
| #")" => if lpct = 0 then implode (rev x)
else GetAct(lpct - 1, nstr)
| _ => GetAct(lpct, nstr)
end
in
ACTION (getLexPos (), GetAct (0,nil))
end
| #";" => SEMI
| c => (prSynErr ("invalid character " ^ String.str c)))
| _ => raise LexError
end
handle eof => NextTok := EOF ;
fun GetTok (_:unit) : token =
let val t = !NextTok in AdvanceTok(); t
end;
val SymTab = ref (create String.<=) : (string,exp) dictionary ref
fun GetExp () : exp =
let val rec optional = fn e => ALT(EPS,e)
and lookup' = fn name =>
lookup(!SymTab) name
handle LOOKUP => prErr ("bad regular expression name: "^
name)
and newline = fn () => let val c = Array.array(!CharSetSize,false) in
Array.update(c,10,true); c
end
and endline = fn e => trail(e,CLASS(newline(),0))
and trail = fn (e1,e2) => CAT(CAT(e1,TRAIL(0)),e2)
and closure1 = fn e => CAT(e,CLOSURE(e))
and repeat = fn (min,max,e) => let val rec rep = fn
(0,0) => EPS
| (0,1) => ALT(e,EPS)
| (0,i) => CAT(rep(0,1),rep(0,i-1))
| (i,j) => CAT(e,rep(i-1,j-1))
in rep(min,max)
end
and exp0 = fn () => case GetTok()
of CHARS(c) => exp1(CLASS(c,0))
| LP => let
val e = exp0()
in
case !NextTok
of RP => (AdvanceTok(); exp1(e))
| _ => (prSynErr "missing ')'")
end
| ID(name) => exp1(lookup' name)
| _ => raise SyntaxError
and exp1 = fn (e) => case !NextTok of
SEMI => e
| ARROW => e
| EOF => e
| LP => exp2(e,exp0())
| RP => e
| t => (AdvanceTok(); case t of
QMARK => exp1(optional(e))
| STAR => exp1(CLOSURE(e))
| PLUS => exp1(closure1(e))
| CHARS(c) => exp2(e,CLASS(c,0))
| BAR => ALT(e,exp0())
| DOLLAR => (UsesTrailingContext := true; endline(e))
| SLASH => (UsesTrailingContext := true;
trail(e,exp0()))
| REPS(i,j) => exp1(repeat(i,j,e))
| ID(name) => exp2(e,lookup' name)
| _ => raise SyntaxError)
and exp2 = fn (e1,e2) => case !NextTok of
SEMI => CAT(e1,e2)
| ARROW => CAT(e1,e2)
| EOF => CAT(e1,e2)
| LP => exp2(CAT(e1,e2),exp0())
| RP => CAT(e1,e2)
| t => (AdvanceTok(); case t of
QMARK => exp1(CAT(e1,optional(e2)))
| STAR => exp1(CAT(e1,CLOSURE(e2)))
| PLUS => exp1(CAT(e1,closure1(e2)))
| CHARS(c) => exp2(CAT(e1,e2),CLASS(c,0))
| BAR => ALT(CAT(e1,e2),exp0())
| DOLLAR => (UsesTrailingContext := true;
endline(CAT(e1,e2)))
| SLASH => (UsesTrailingContext := true;
trail(CAT(e1,e2),exp0()))
| REPS(i,j) => exp1(CAT(e1,repeat(i,j,e2)))
| ID(name) => exp2(CAT(e1,e2),lookup' name)
| _ => raise SyntaxError)
in exp0()
end;
val StateTab = ref(create(String.<=)) : (string,int) dictionary ref
val StateNum = ref 0;
fun GetStates () : int list =
let fun add nil sl = sl
| add (x::y) sl = add y (union ([lookup (!StateTab)(x)
handle LOOKUP =>
prErr ("bad state name: "^x)
],sl))
fun addall i sl =
if i <= !StateNum then addall (i+2) (union ([i],sl))
else sl
fun incall (x::y) = (x+1)::incall y
| incall nil = nil
fun addincs nil = nil
| addincs (x::y) = x::(x+1)::addincs y
val state_list =
case !NextTok of
STATE s => (AdvanceTok(); LexState := 1; add s nil)
| _ => addall 1 nil
in case !NextTok
of CARAT => (LexState := 1; AdvanceTok(); UsesPrevNewLine := true;
incall state_list)
| _ => addincs state_list
end
val LeafNum = ref ~1;
fun renum(e : exp) : exp =
let val rec label = fn
EPS => EPS
| CLASS(x,_) => CLASS(x,++LeafNum)
| CLOSURE(e) => CLOSURE(label(e))
| ALT(e1,e2) => ALT(label(e1),label(e2))
| CAT(e1,e2) => CAT(label(e1),label(e2))
| TRAIL(i) => TRAIL(++LeafNum)
| END(i) => END(++LeafNum)
in label(e)
end;
exception ParseError;
fun parse() : (string * (int list * exp) list * ((string,pos*string) dictionary)) = let
fun isSEMI SEMI = true | isSEMI _ = false
val Accept = ref (create String.<=) : (string,pos*string) dictionary ref
val rec ParseRtns = fn l => case getch(!LexBuf) of
#"%" => let val c = getch(!LexBuf) in
if c = #"%" then (implode (rev l))
else ParseRtns(c :: #"%" :: l)
end
| c => ParseRtns(c::l)
and ParseDefs = fn () =>
(LexState:=0; AdvanceTok(); case !NextTok of
LEXMARK => ()
| LEXSTATES =>
let fun f () = (case !NextTok of (ID i) =>
(StateTab := enter(!StateTab)(i,++StateNum);
++StateNum; AdvanceTok(); f())
| _ => ())
in AdvanceTok(); f ();
if isSEMI (!NextTok) then ParseDefs() else
(prSynErr "expected ';'")
end
| ID x => (
LexState:=1; AdvanceTok();
case GetTok()
of ASSIGN => (
SymTab := enter(!SymTab)(x,GetExp());
if isSEMI (!NextTok) then ParseDefs()
else (prSynErr "expected ';'"))
| _ => raise SyntaxError)
| REJECT => (HaveReject := true; ParseDefs())
| COUNT => (CountNewLines := true; ParseDefs())
| FULLCHARSET => (CharSetSize := 256; ParseDefs())
| HEADER => (LexState := 2; AdvanceTok();
case GetTok()
of ACTION (p, s) =>
if (!StrDecl) then
(prErr "cannot have both %structure and %header \
\declarations")
else if (!HeaderDecl) then
(prErr "duplicate %header declarations")
else
(HeaderCode := s; LexState := 0;
HeaderPos := p;
HeaderDecl := true; ParseDefs())
| _ => raise SyntaxError)
| POSARG => (PosArg := true; ParseDefs())
| POSINT => (AdvanceTok();
case !NextTok of
(ID i) =>
if (!PosIntDecl) then
(prErr "duplicate %posint declarations")
else (PosIntName := i; PosIntDecl := true)
| _ => (prErr "expected ID");
ParseDefs())
| ARG => (LexState := 2; AdvanceTok();
case GetTok()
of ACTION s =>
(case !ArgCode
of SOME _ => prErr "duplicate %arg declarations"
| NONE => ArgCode := SOME s;
LexState := 0;
ParseDefs())
| _ => raise SyntaxError)
| STRUCT => (AdvanceTok();
case !NextTok of
(ID i) =>
if (!HeaderDecl) then
(prErr "cannot have both %structure and %header \
\declarations")
else if (!StrDecl) then
(prErr "duplicate %structure declarations")
else (StrName := i; StrDecl := true)
| _ => (prErr "expected ID");
ParseDefs())
| _ => raise SyntaxError)
and ParseRules =
fn rules => (LexState:=1; AdvanceTok(); case !NextTok of
EOF => rules
| _ =>
let val s = GetStates()
val e = renum(CAT(GetExp(),END(0)))
in
case !NextTok
of ARROW => (LexState:=2; AdvanceTok();
case GetTok() of ACTION(act) =>
if isSEMI (!NextTok) then
(Accept:=enter(!Accept) (Int.toString (!LeafNum),act);
ParseRules((s,e)::rules))
else (prSynErr "expected ';'")
| _ => raise SyntaxError)
| _ => (prSynErr "expected '=>'")
end)
in let val usercode = ParseRtns nil
in (ParseDefs(); (usercode,ParseRules(nil),!Accept))
end
end handle SyntaxError => (prSynErr "")
fun makebegin () : unit =
let fun make nil = ()
| make ((x,n:int)::y)=(say "val "; say x; say " = " ;
say "STARTSTATE ";
say (Int.toString n); say ";\n"; make y)
in say "\n(* start state definitions *)\n\n"; make(listofdict(!StateTab))
end
(*
structure L =
struct
nonfix >
type key = int list * string
fun > ((key,item:string),(key',item')) =
let fun f ((a:int)::a') (b::b') = if Int.> (a,b) then true
else if a=b then f a' b'
else false
| f _ _ = false
in f key key'
end
end
structure RB = RedBlack(L)
*)
(* a finite map implementation that replaces the original version, but
* keeps the same interface.
*)
structure RB : sig
type tree
type key
val empty : tree
val insert : key * tree -> tree
val lookup : key * tree -> key
exception notfound of key
end = struct
structure Map = RedBlackMapFn (
struct
type ord_key = int list
val compare = List.collate Int.compare
end)
type key = (int list * string)
type tree = string Map.map
val empty = Map.empty
val insert = Map.insert'
exception notfound of key
fun lookup (arg as (key, _), t) = (case Map.find(t, key)
of SOME item => (key, item)
| NONE => raise notfound arg
(* end case *))
end
fun maketable (fins:(int * (int list)) list,
tcs :(int * (int list)) list,
tcpairs: (int * int) list,
trans : (int*(int list)) list) : unit =
(* Fins = (state #, list of final leaves for the state) list
tcs = (state #, list of trailing context leaves which begin in this state)
list
tcpairs = (trailing context leaf, end leaf) list
trans = (state #,list of transitions for state) list *)
let datatype elem = N of int | T of int | D of int
val count = ref 0
val _ = (if length(trans)<256 then CharFormat := true
else CharFormat := false;