-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproglr.sml
1654 lines (1556 loc) · 64.6 KB
/
proglr.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
structure Parse = ParseFun(Lexer)
structure Util = struct
(* list as set *)
fun mem x xs = List.exists (fn y => y = x) xs
fun add (x, xs) = if mem x xs then xs else x::xs
fun union [] ys = ys
| union (x::xs) ys = union xs (add (x, ys))
fun remove (x, []) = []
| remove (x, y::ys) = if x = y then remove (x, ys) else y::(remove (x, ys))
fun minus (xs, ys) = List.foldr (fn (y, xs) => remove (y, xs)) xs ys
fun uniq xs = List.foldr add [] xs
(* addIndex : 'a list -> (int * 'a) list *)
fun addIndex xs =
let
fun addIndex' (n, [], acc) = rev acc
| addIndex' (n, x::xs, acc) = addIndex' (n + 1, xs, (n, x)::acc)
in
addIndex' (0, xs, [])
end
fun dropWhile p [] = []
| dropWhile p (x::xs) = if p x then dropWhile p xs else x::xs
fun chopDigit s =
let
val cs = rev (String.explode s)
val cs' = dropWhile Char.isDigit cs
in
String.implode (rev cs')
end
fun toLower s = String.implode (List.map Char.toLower (String.explode s))
fun toUpper s = String.implode (List.map Char.toUpper (String.explode s))
fun escapeUnicode s =
let
fun pad d =
case String.size d of
4 => "\\u" ^ d
| 8 => "\\U" ^ d
| l => if l < 8 then pad ("0" ^ d)
else raise Fail (d ^ ": too large for unicode")
val wchars = UTF8.explode s
fun isAlphaNum c =
UTF8.isAscii c andalso Char.isAlphaNum (UTF8.toAscii c)
fun escapeWChar c =
if isAlphaNum c
then UTF8.toString c
else pad (Word.toString c)
in
concat (map escapeWChar (UTF8.explode s))
end
fun bracket acquire release use =
let
val resource = acquire
in
use resource before release resource
handle e => (release resource; raise e)
end
fun withTextIn name = bracket (TextIO.openIn name) TextIO.closeIn
fun withTextOut name = bracket (TextIO.openOut name) TextIO.closeOut
fun withBinIn name = bracket (BinIO.openIn name) BinIO.closeIn
fun withBinOut name = bracket (BinIO.openOut name) BinIO.closeOut
fun iota n =
let
fun iota' (0, l) = l
| iota' (n, l) = iota' (n - 1, (n - 1)::l)
in
iota' (n, [])
end
end
signature INTERN = sig
type ''a pool
val emptyPool : ''a pool
val intern : ''a -> ''a pool -> int * ''a pool
val internAll : ''a list -> ''a pool -> int list * ''a pool
val present : int -> ''a pool -> bool
val valueOf : int -> ''a pool -> ''a
val numbersOf : ''a pool -> int list
val toList : ''a pool -> (int * ''a) list
end
structure Intern :> INTERN = struct
type ''a pool = (int * ''a) list
val emptyPool = []
fun nextNumber [] = 0
| nextNumber ((number, _)::values) = number + 1
fun intern value pool =
case List.find (fn (_, value') => value = value') pool of
SOME (number, _) => (number, pool)
| NONE =>
let
val number = nextNumber pool
val pool' = (number, value)::pool
in
(number, pool')
end
fun internAll values pool =
let
fun loop [] pool numbers = (rev numbers, pool)
| loop (value::values) pool numbers =
let val (number, pool') = intern value pool in
loop values pool' (number::numbers)
end
in
loop values pool []
end
fun present number [] = false
| present number ((number', _)::pool) =
number = number' orelse present number pool
fun valueOf number pool =
let
val (_, value) = valOf (List.find (fn (number', _) => number = number') pool)
in
value
end
fun numbersOf pool = List.map (fn (n, _) => n) pool
fun toList pool = pool
end
signature GRAMMAR = sig
(* constructor is 'label' of LBNF; 'EInt' part of 'EInt. Exp ::= Integer' *)
datatype constructor = Id of string | Wild | ListE | ListCons | ListOne
type rule
type grammar
(* a symbol may be a nonterminal (Nonterm), a terminal bearing no value (UnitTerm)
* or a terminal bearing a value *)
datatype kind = Nonterm | UnitTerm | IntTerm | StrTerm | CharTerm
eqtype symbol
(* constructor functions for GRAMMAR types *)
val fromAst : Parse.Ast.grammar -> grammar
val makeRule : constructor * symbol * symbol list -> rule
(* a rule consists of label(cons), value category(lhs),
* and production rules(rhs) *)
val consOf : rule -> constructor
val lhsOf : rule -> symbol
val rhsOf : rule -> symbol list
(* a grammar consists of one start symbol, rules, terminal symbols and
* nonterminal symbols *)
val startSymbolOf : grammar -> symbol
val rulesOf : grammar -> rule list
val termsOf : grammar -> symbol list
val nontermsOf : grammar -> symbol list
(* a symbol may be a terminal or a nonterminal *)
val isTerm : symbol -> bool
val kindOf : symbol -> kind
(* a symbol has level if it is nonterminal, e.g. Cat, [Cat], [[Cat]]... *)
val levelOf : symbol -> int
val identOfSymbol : symbol -> string
(* pretty printers *)
val showCons : constructor -> string
val showRule : rule -> string
val showSymbol : symbol -> string
val printGrammar : TextIO.outstream -> grammar -> unit
(* special symbols *)
val S' : symbol
val EOF : symbol
end
structure Grammar :> GRAMMAR = struct
structure Handle (* :> HASHABLE where type t = string * int *) = struct
(* handle for grammatical symbol.
T = ("T", 0), [T] = ("T", 1), [[T]] = ("T", 2), ... *)
type t = string * int
fun eq (a, b) = a = b
fun hash (ident, level) =
let
val word8ToWord = Word.fromLarge o Word8.toLarge
fun hash (ch, h) = JenkinsHash.hashInc h (word8ToWord ch)
in
Word8Vector.foldl hash (Word.fromInt level) (Byte.stringToBytes ident)
end
fun show (str, ~1) = str
| show (ident, 0) = ident
| show (ident, level) = "[" ^ show (ident, level - 1) ^ "]"
end
structure SymbolHashTable = HashTable(Handle)
datatype kind = Nonterm | UnitTerm | IntTerm | StrTerm | CharTerm
type symbol = Handle.t * kind
datatype constructor = Id of string | Wild | ListE | ListCons | ListOne
type lhs = symbol
type rhs = symbol list
type rule = constructor * lhs * rhs
type grammar = {
terms : symbol list,
nonterms : symbol list,
rules : rule list,
start : symbol}
fun isTerm (_, Nonterm) = false
| isTerm ((_, 0), _) = true
| isTerm ((_, _), _) = false
fun showSymbol ((ident, 0), _) = ident
| showSymbol ((ident, level), kind) = "[" ^ showSymbol ((ident, level - 1), kind) ^ "]"
fun kindOf (_, kind) = kind
fun levelOf ((_, level), _) = level
fun identOfSymbol ((ident, _), _) = ident
val S' = (("S'", 0), Nonterm)
val EOF = (("EOF", 0), UnitTerm)
fun makeRule (rule as (constructor, lhs, rhs)) =
if isTerm lhs then raise Fail "non-terminal cannot be lhs of a rule"
else rule
fun rulesOf ({rules,...} : grammar) = rules
fun consOf (constructor, _, _) = constructor
fun lhsOf (_, lhs, _) = lhs
fun rhsOf (_, _, rhs) = rhs
fun fromAst ast =
(* Construct a grammar from an AST.
* A grammar consists of terms, nonterms, rules and a start symbol.
* Create them in order. *)
let
(* utility functions *)
fun catToHandle (Parse.Ast.IdCat (_, ident)) = (ident, 0)
| catToHandle (Parse.Ast.ListCat (_, cat)) =
let val (ident, level) = catToHandle cat in
(ident, level + 1)
end
fun itemToHandle (Parse.Ast.Terminal (_, str)) = (str, ~1)
| itemToHandle (Parse.Ast.NTerminal (_, cat)) = catToHandle cat
fun labelToCons (Parse.Ast.Id (_, ident)) = Id ident
| labelToCons (Parse.Ast.Wild _) = Wild
| labelToCons (Parse.Ast.ListE _) = ListE
| labelToCons (Parse.Ast.ListCons _) = ListCons
| labelToCons (Parse.Ast.ListOne _) = ListOne
(* a hash table in which all terms and nonterms will be stored
* for checking duplicate *)
val table = SymbolHashTable.table 256
(* visit token definitions and collect terms *)
val terms =
let
fun termsOfGrammar (Parse.Ast.Grammar (_, tokens, _)) terms =
termsOfTokens tokens terms
and termsOfTokens [] terms = []
| termsOfTokens (token::tokens) terms =
termsOfToken token (termsOfTokens tokens terms)
and termsOfToken (Parse.Ast.Keyword (_, name, literal)) terms =
let
val hand = (name, 0)
val symbol = (hand, UnitTerm)
val (term, present) = SymbolHashTable.lookupOrInsert' table hand (fn () => symbol)
val literalHand = (literal, ~1)
in
(* 'literal' form can be used as an 'alias' of token name *)
(SymbolHashTable.lookupOrInsert table literalHand (fn () => symbol);
if present then terms else term::terms)
end
| termsOfToken (Parse.Ast.AttrToken (_, name, attr)) terms =
let
val hand = (name, 0)
val kind =
case attr of
"string" => StrTerm
| "int" => IntTerm
| "char" => CharTerm
| t => raise Fail ("unknown type: " ^ t)
val symbol = (hand, kind)
val (term, present) = SymbolHashTable.lookupOrInsert' table hand (fn () => symbol)
in
if present then terms else term::terms
end
| termsOfToken (Parse.Ast.NoAttrToken (_, name)) terms =
let
val hand = (name, 0)
val symbol = (hand, UnitTerm)
val (term, present) = SymbolHashTable.lookupOrInsert' table hand (fn () => symbol)
in
if present then terms else term::terms
end
in
termsOfGrammar ast []
end
(* visit rules and collect nonterms *)
val nonterms =
let
fun nontermsOfGrammar (Parse.Ast.Grammar (_, _, defs)) syms =
nontermsOfDefs defs syms
and nontermsOfDefs [] syms = []
| nontermsOfDefs (def::defs) syms =
nontermsOfDef def (nontermsOfDefs defs syms)
and nontermsOfDef (Parse.Ast.Rule (_, label, cat, items)) syms =
nontermsOfCat cat syms
| nontermsOfDef (Parse.Ast.Comment (span, _)) syms = syms
| nontermsOfDef (Parse.Ast.Comments (span, _, _)) syms = syms
| nontermsOfDef (Parse.Ast.Separator (span, minimumsize, cat, separator)) syms =
nontermsOfCat (Parse.Ast.ListCat (span, cat)) syms
| nontermsOfDef (Parse.Ast.Terminator (span, minimumsize, cat, terminator)) syms =
nontermsOfCat (Parse.Ast.ListCat (span, cat)) syms
| nontermsOfDef (Parse.Ast.Coercions (span, ident, level)) syms =
let
fun coerce 0 syms = nontermsOfCat (Parse.Ast.IdCat (span, ident)) syms
| coerce level syms =
coerce (level - 1) (nontermsOfCat (Parse.Ast.IdCat (span, ident ^ Int.toString level)) syms)
in
coerce level syms
end
and nontermsOfCat cat syms =
let
val hand as (ident, level) = catToHandle cat
fun symf ()= case SymbolHashTable.find table (ident, 0) of
SOME (_, kind) => (hand, kind)
| NONE => (hand, Nonterm)
val (sym, present) = SymbolHashTable.lookupOrInsert' table hand symf
in
if present then syms else sym::syms
end
in
nontermsOfGrammar ast []
end
(* collect rules, expand macros if needed *)
val rules =
let
(* constructor functions for polymorphic list rules *)
fun makeNilRule span cat =
Parse.Ast.Rule
(span, Parse.Ast.ListE span, Parse.Ast.ListCat (span, cat), [])
fun makeOneRule span cat separator =
Parse.Ast.Rule
(span,
Parse.Ast.ListOne span,
Parse.Ast.ListCat (span, cat),
[Parse.Ast.NTerminal (span, cat)]
@ (if separator = "" then []
else [Parse.Ast.Terminal (span, separator)]))
fun makeConsRule span cat separator =
Parse.Ast.Rule
(span,
Parse.Ast.ListCons span,
Parse.Ast.ListCat (span, cat),
[Parse.Ast.NTerminal (span, cat)]
@ (if separator = "" then []
else [Parse.Ast.Terminal (span, separator)])
@ [Parse.Ast.NTerminal (span, Parse.Ast.ListCat (span, cat))])
(* visitors *)
fun rulesOfGrammar (Parse.Ast.Grammar (_, terminals, defs)) rules = rulesOfDefs defs rules
and rulesOfDefs [] rules = []
| rulesOfDefs (def::defs) rules =
rulesOfDef def (rulesOfDefs defs rules)
and rulesOfDef (Parse.Ast.Rule (_, label, cat, items)) rules =
let
val cons = labelToCons label
val lhs = SymbolHashTable.lookup table (catToHandle cat)
handle Absent => raise Fail "error while constructing a grammar from AST. (possible bug)"
fun l i =
let
val h = itemToHandle i
in
SymbolHashTable.lookup table h
handle Absent => raise Fail ("symbol " ^ (Handle.show h) ^ " not defined.")
end
val rhs = map l items
in
(cons, lhs, rhs)::rules
end
| rulesOfDef (Parse.Ast.Comment (span, _)) rules = rules
| rulesOfDef (Parse.Ast.Comments (span, _, _)) rules = rules
| rulesOfDef (Parse.Ast.Separator (span, minimumsize, cat, separator)) rules =
(* expand separator macro *)
let
val emptyCase = makeNilRule span cat
val oneCase = makeOneRule span cat ""
val consCase = makeConsRule span cat separator
in
case minimumsize of
Parse.Ast.MEmpty _ =>
if separator = "" then
rulesOfDef consCase (rulesOfDef emptyCase rules)
else
rulesOfDef consCase (rulesOfDef oneCase (rulesOfDef emptyCase rules))
| Parse.Ast.MNonempty _ =>
rulesOfDef consCase (rulesOfDef oneCase rules)
end
| rulesOfDef (Parse.Ast.Terminator (span, minimumsize, cat, terminator)) rules =
(* expand terminator macro *)
let
val emptyCase = makeNilRule span cat
val oneCase = makeOneRule span cat terminator
val consCase = makeConsRule span cat terminator
in
case minimumsize of
Parse.Ast.MEmpty _ =>
rulesOfDef consCase (rulesOfDef emptyCase rules)
| Parse.Ast.MNonempty _ =>
rulesOfDef consCase (rulesOfDef oneCase rules)
end
| rulesOfDef (Parse.Ast.Coercions (span, ident, level)) rules =
(* expand coercions macro *)
let
val atomicRule =
Parse.Ast.Rule
(span,
Parse.Ast.Wild span,
Parse.Ast.IdCat (span, ident ^ Int.toString level),
[Parse.Ast.Terminal (span, "("),
Parse.Ast.NTerminal (span, Parse.Ast.IdCat (span, ident)),
Parse.Ast.Terminal (span, ")")])
fun levelToString 0 = ""
| levelToString level = Int.toString level
fun makeCoerceRule level =
Parse.Ast.Rule
(span,
Parse.Ast.Wild span,
Parse.Ast.IdCat (span, ident ^ levelToString (level - 1)),
[Parse.Ast.NTerminal (span, Parse.Ast.IdCat (span, ident ^ levelToString level))])
fun coerce 1 rules =
rulesOfDef (makeCoerceRule 1) rules
| coerce level rules =
coerce (level - 1) (rulesOfDef (makeCoerceRule level) rules)
in
coerce level (rulesOfDef atomicRule rules)
end
in
rulesOfGrammar ast []
end
(* the start symbols is lhs of the first rule *)
val start = lhsOf (hd rules)
in
{terms = terms, nonterms = nonterms, rules = rules, start = start}
end
fun startSymbolOf ({start,...} : grammar) = start
fun termsOf ({terms,...} : grammar) = terms
fun nontermsOf ({nonterms,...} : grammar) = nonterms
fun showCons (Id s) = s
| showCons Wild = "_"
| showCons ListE = "[]"
| showCons ListCons = "(:)"
| showCons ListOne = "(:[])"
fun showRule (con, lhs, rhs) =
showCons con ^ ". "
^ showSymbol lhs ^ " ::= "
^ String.concatWith " " (List.map showSymbol rhs) ^ ";"
fun printGrammar out ({terms, nonterms, rules, start} : grammar) =
let
fun println s =
(TextIO.output (out, s); TextIO.output (out, "\n"); TextIO.flushOut out)
val printRule = println o showRule
in
println ("terms = {" ^ String.concatWith ", " (map showSymbol terms) ^
"}");
println ("nonterms = {" ^ String.concatWith ", " (map showSymbol nonterms)
^ "}");
println ("start = " ^ (showSymbol start));
List.app printRule rules
end
end
signature LRITEM = sig
eqtype item
type items = item list
val fromRule : Grammar.rule -> item
val expand : items -> Grammar.rule list -> items
val moveOver : items -> Grammar.symbol -> Grammar.rule list -> items
val nextSymbols : items -> Grammar.symbol list
val partition :items -> items * items
val consOf : item -> Grammar.constructor
val lhsOf : item -> Grammar.symbol
val rhsBeforeDot : item -> Grammar.symbol list
val show : item -> string
end
structure LrItem :> LRITEM = struct
local
open Grammar
type lhs = symbol
type rhs_before_dot = symbol list
type rhs_after_dot = symbol list
in
type item = constructor * lhs * rhs_before_dot * rhs_after_dot
type items = item list
end
fun fromRule rule = (Grammar.consOf rule, Grammar.lhsOf rule, [], Grammar.rhsOf rule)
fun expand (lrItems : items) (rules : Grammar.rule list) =
let
(* 1st = unexpanded items, 2nd = expanded items *)
fun loop [] expanded = expanded
| loop (lrItem::lrItems) expanded =
if Util.mem lrItem expanded then loop lrItems expanded
else
case lrItem of
(* if the dot is not in front of a non-terminal *)
(_, _, _, []) => loop lrItems (lrItem::expanded)
| (_, _, _, sym::_) =>
if Grammar.isTerm sym then
(* if the dot is not in front of a non-terminal *)
loop lrItems (lrItem::expanded)
else
(* if the dot is in front of a non-terminal *)
let
(* all grammar rules of the form sym->... *)
val rules = List.filter (fn rule => Grammar.lhsOf rule = sym) rules
(* convert the rules to LR items *)
val newLrItems = map fromRule rules
in
(* lrItem is expanded now, since it generated new items.
The new items are possibly unexpanded. *)
loop (newLrItems @ lrItems) (lrItem::expanded)
end
in
loop lrItems []
end
fun moveOver items symbol grammar =
let
fun move (c, n, l, []) = NONE
| move (c, n, l, next::rest) =
if next = symbol then SOME (c, n, l @ [next], rest)
else NONE
val moved = List.mapPartial move items
in
expand moved grammar
end
fun endsWithDot (_, _, _, []) = true
| endsWithDot _ = false
fun nextSymbols lrItems =
let
fun loop [] symbols = symbols
| loop ((_, _, _, [])::lrItems) symbols = loop lrItems symbols
| loop ((_, _, _, nextSymbol::_)::lrItems) symbols =
loop lrItems (Util.add (nextSymbol, symbols))
in
loop lrItems []
end
fun partition lrItems =
List.partition endsWithDot lrItems
fun consOf (cons, _, _, _) = cons
fun lhsOf (_, lhs, _, _) = lhs
fun rhsBeforeDot (_, _, rhs, []) = rhs
fun show (_, lhs, rhs1, rhs2) =
Grammar.showSymbol lhs ^ " -> "
^ String.concatWith " " (List.map Grammar.showSymbol rhs1)
^ " . "
^ String.concatWith " " (List.map Grammar.showSymbol rhs2)
end
structure State = struct
type state = LrItem.items * LrItem.items
end
signature AUTOMATON = sig
type state
type state_number = int
eqtype alphabet
type transition = state_number * alphabet * state_number
type automaton
val makeAutomaton : Grammar.grammar -> automaton
val stateNumbers : automaton -> state_number list
val stateOf : state_number -> automaton -> state
val nextStatesOf : state_number -> automaton -> (alphabet * state_number) list
val numbersAndStates : automaton -> (state_number * state) list
val printAutomaton : TextIO.outstream -> automaton -> unit
end
structure Automaton :> AUTOMATON where
type state = State.state
and type alphabet = Grammar.symbol
= struct
open State
type state = State.state
type state_number = int
type alphabet = Grammar.symbol
type transition = state_number * alphabet * state_number
type automaton = LrItem.items Intern.pool * transition list
fun stateOfLrItems lrItems = LrItem.partition lrItems
fun makeAutomaton grammar =
let
val startRule = Grammar.makeRule (Grammar.Wild , Grammar.S', [Grammar.startSymbolOf grammar])
val rules = Grammar.rulesOf grammar
val startState = LrItem.expand [LrItem.fromRule startRule] rules
val (startStateNumber, pool) = Intern.intern startState Intern.emptyPool
(* loop U S T
where U = numbers of unprocessed state,
S = a list of states and numbers,
T = trnasitions *)
fun loop [] pool transitions = (pool, transitions)
| loop (number::numbers) pool transitions =
let
val state = Intern.valueOf number pool
val nextSymbols = LrItem.nextSymbols state
val nextStates = map (fn symbol => LrItem.moveOver state symbol rules) nextSymbols
val (nextStateNumbers, pool') = Intern.internAll nextStates pool
(* State numbers which are not present in old S are new *)
val newStateNumbers = List.filter (fn number => not (Intern.present number pool)) nextStateNumbers
val newTransitions =
map
(fn (symbol, nextStateNumber) => (number, symbol, nextStateNumber))
(ListPair.zip (nextSymbols, nextStateNumbers))
in
loop (newStateNumbers @ numbers) pool' (newTransitions @ transitions)
end
in
loop [startStateNumber] pool []
end
fun stateNumbers (pool, _) = Intern.numbersOf pool
fun stateOf number (pool, _) = stateOfLrItems (Intern.valueOf number pool)
fun numbersAndStates (pool, _) = List.map (fn (n, items) => (n, stateOfLrItems items)) (Intern.toList pool)
fun nextStatesOf state (_, transitions) =
List.map (fn (_, symbol, next) => (symbol, next)) (List.filter (fn (s', _, _) => state = s') transitions)
fun printStates outs states =
let
fun printLrItem lrItem = TextIO.output (outs, LrItem.show lrItem ^ "\\n")
fun printState (n, state) = (
TextIO.output (outs, ("State" ^ Int.toString n ^ " [ label=\"State" ^
Int.toString n ^ "\\n"));
List.app printLrItem state;
TextIO.output (outs, "\"]\n"))
in
List.app printState (Intern.toList states)
end
fun printTransitions outs transitions =
let
fun printTransition (s1, symbol, s2) = (
TextIO.output (outs, "State" ^ Int.toString s1);
TextIO.output (outs, " -> State" ^ Int.toString s2);
TextIO.output (outs, " [ label=\"");
TextIO.output (outs, Grammar.showSymbol symbol);
TextIO.output (outs, "\"]\n"))
in
List.app printTransition transitions
end
fun printAutomaton outs (states, transitions) = (
TextIO.output (outs, "digraph automaton {\n");
TextIO.output (outs, "graph [ rankdir = LR ];\n");
TextIO.output (outs, "node [shape = box ];\n");
printStates outs states;
printTransitions outs transitions;
TextIO.output (outs, "}\n"))
end
structure MLAst = struct
type ident = string
type tycon = string
datatype
ty =
Tycon of tycon
| TupleType of ty list
| AsisType of string
and strexp = Struct of strdec list
and strdec =
Structure of strbind
| Dec of dec
and sigdec = Signature of sigbind
and dec =
Datatype of datbind list
| Fun of fvalbind list
| Val of pat * exp
| AsisDec of string
and exp =
AsisExp of string
| Let of dec list * exp
| Case of exp * mrule list
| TupleExp of exp list
| AppExp of exp * exp
and pat = AsisPat of string
and fundec = Functor of funbind
and sigexp =
Sig of spec list
| SigId of ident * (ident * ty) list
and spec =
ValSpec of valdesc
| TypeSpec of typedesc
| EqTypeSpec of typedesc
withtype
datbind = ident * (ident * ty option) list
and fvalbind = ident * (pat list * exp) list
and strbind = (ident * strexp) list
and sigbind = (ident * sigexp) list
and mrule = pat * exp
and funbind = (ident * ident * sigexp * strexp) list
and valdesc = (ident * ty) list
and typedesc = ident list
fun p out s = (TextIO.output (out, s); TextIO.flushOut out)
fun printIndent out 0 = ()
| printIndent out n = (p out " "; printIndent out (n - 1))
fun out outs indent str = (printIndent outs indent; p outs str; p outs "\n")
exception BlockExp
fun showTy (Tycon tycon) = tycon
| showTy (TupleType tys) =
let
fun prepend [] = "unit"
| prepend [ty] = showTy ty
| prepend (ty::tys) = (showTy ty) ^ " * " ^ prepend tys
in
prepend tys
end
| showTy (AsisType ty) = ty
fun showPat (AsisPat string) = string
fun showExp (AsisExp string) = string
| showExp (Let _) = raise BlockExp
| showExp (Case _) = raise BlockExp
| showExp (TupleExp []) = "()"
| showExp (TupleExp (first::rest)) =
let
fun addComma exp = ", " ^ showExp exp
in
"(" ^ showExp first ^ concat (map addComma rest) ^ ")"
end
| showExp (AppExp (e1, e2)) = "(" ^ showExp e1 ^ " " ^ showExp e2 ^ ")"
fun showSigExp (SigId (sigid, [])) = sigid
| showSigExp (SigId (sigid, first::rest)) =
let
fun showWh (t, tycon) = " type " ^ t ^ " = " ^ (showTy tycon)
in
sigid ^ " where" ^ (showWh first)
^ List.foldl (fn (wh, acc) => acc ^ " and" ^ showWh wh) "" rest
end
fun printExp outs indent (exp as AsisExp string) = out outs indent (showExp exp)
| printExp outs indent (Let (decs, exp)) =
(out outs indent "let";
List.app (printDec outs (indent + 2)) decs;
out outs indent "in";
printExp outs (indent + 2) exp;
out outs indent "end")
| printExp outs indent (Case (exp, mrules)) =
let
fun printMrule indent pre (pat, exp) =
out outs indent (pre ^ showPat pat ^ " => " ^ showExp exp)
handle BlockExp =>
(out outs indent (pre ^ showPat pat ^ " =>");
printExp outs (indent + 2) exp)
fun printMrules indent [] = ()
| printMrules indent (first::rest) =
(printMrule indent " " first;
List.app (printMrule indent "| ") rest)
in
out outs indent ("case " ^ showExp exp ^ " of");
printMrules indent mrules
end
| printExp outs indent exp = out outs indent (showExp exp)
and printDec outs indent (Datatype []) = ()
| printDec outs indent (Datatype (first::rest)) =
let
fun printConbind indent pre (vid, ty) =
out outs indent (pre ^ vid ^ (case ty of NONE => "" | SOME ty => " of " ^ showTy ty))
fun printConbinds indent [] = ()
| printConbinds indent (first::rest) =
(printConbind indent " " first;
List.app (printConbind indent "| ") rest)
fun printDatbind indent pre (tycon, conbind) =
(out outs indent (pre ^ " " ^ tycon ^ " =");
printConbinds indent conbind)
in
(printDatbind indent "datatype" first;
List.app (printDatbind indent "and") rest)
end
| printDec outs indent (Fun []) = ()
| printDec outs indent (Fun (first::rest)) =
let
fun printFvalbind indent pre (ident, []) = out outs indent (pre ^ " " ^ ident ^ " _ = raise Fail \"unimplemented\"")
| printFvalbind indent pre (ident, (first::rest)) =
let
fun printClause indent pre (patseq, exp) =
let
val patterns = List.foldl (fn (a,b) => b ^ " " ^ showPat a) "" patseq
in
let val expstr = showExp exp in
if (indent + String.size ident + String.size patterns + String.size expstr) > 70 then
raise BlockExp
else
out outs indent (pre ^ " " ^ ident ^ patterns ^ " = " ^ expstr)
end
handle BlockExp =>
(out outs indent (pre ^ " " ^ ident ^ patterns ^ " =");
printExp outs (indent + 4) exp)
end
in
printClause indent pre first;
List.app (printClause indent " |") rest
end
in
(printFvalbind indent "fun" first;
List.app (printFvalbind indent "and") rest)
end
| printDec outs indent (AsisDec s) = out outs indent s
fun printStrdec outs indent (Structure []) = ()
| printStrdec outs indent (Structure (first::rest)) =
let
fun printStrbind indent pre (ident, Struct strdecseq) =
(out outs indent (pre ^ " " ^ ident ^ " = struct");
List.app (printStrdec outs (indent + 2)) strdecseq;
out outs indent "end")
in
printStrbind indent "structure" first;
List.app (printStrbind indent "and") rest
end
| printStrdec outs indent (Dec dec) = printDec outs indent dec
fun printSpec outs indent (ValSpec []) = ()
| printSpec outs indent (ValSpec (first::rest)) =
let
fun printValSpec pre (ident, ty) =
out outs indent (pre ^ " " ^ ident ^ " : " ^ showTy ty)
in
(printValSpec "val" first;
List.app (printValSpec "and") rest)
end
| printSpec outs indent (TypeSpec []) = ()
| printSpec outs indent (TypeSpec (first::rest)) =
let
fun printTypeSpec pre ty =
out outs indent (pre ^ " " ^ ty)
in
(printTypeSpec "type" first;
List.app (printTypeSpec "and") rest)
end
| printSpec outs indent (EqTypeSpec []) = ()
| printSpec outs indent (EqTypeSpec (first::rest)) =
let
fun printEqTypeSpec pre ty =
out outs indent (pre ^ " " ^ ty)
in
(printEqTypeSpec "eqtype" first;
List.app (printEqTypeSpec "and") rest)
end
fun printSigdec outs indent (Signature []) = ()
| printSigdec outs indent (Signature (first::rest)) =
let
fun printSigbind indent pre (ident, Sig specs) =
(out outs indent (pre ^ " " ^ ident ^ " = sig");
List.app (printSpec outs (indent + 2)) specs;
out outs indent "end")
in
printSigbind indent "signature" first;
List.app (printSigbind indent "and") rest
end
fun printFundec outs indent (Functor []) = ()
| printFundec outs indent (Functor (first::rest)) =
let
fun printFunbind indent pre (funid, sigid, sigexp, Struct strdecs) =
(out outs indent (pre ^ " " ^ funid ^ "(" ^ sigid ^ " : " ^ showSigExp sigexp ^ ") = struct");
List.app (printStrdec outs (indent + 2)) strdecs;
out outs indent "end")
in
printFunbind indent "functor" first;
List.app (printFunbind indent "and") rest
end
end
structure CodeGenerator = struct
fun nt2dt nonterm =
Util.toLower (Util.chopDigit (Grammar.identOfSymbol nonterm))
(* Terms: appropriate atomic types
Nonerms: T => T, [T] => T list ... *)
fun symToTycon prefix sym =
let
fun suffix 0 = ""
| suffix n = suffix (n - 1) ^ " list"
val level = Grammar.levelOf sym
in
case Grammar.kindOf sym of
Grammar.UnitTerm => NONE
| Grammar.IntTerm => SOME (MLAst.Tycon ("int" ^ suffix level))
| Grammar.StrTerm => SOME (MLAst.Tycon ("string" ^ suffix level))
| Grammar.CharTerm => SOME (MLAst.Tycon ("char" ^ suffix level))
| Grammar.Nonterm => SOME (MLAst.Tycon (prefix ^ (nt2dt sym) ^ suffix level))
end
fun addPrimes s 0 = s
| addPrimes s n = addPrimes s (n - 1) ^ "'"
fun symToCategory sym =
addPrimes (Grammar.identOfSymbol sym) (Grammar.levelOf sym)
(* string -> Grammar.symbol list -> MLAst.dec *)
(* example output: datatype token = EOF | ... *)
fun makeTokenDatatype typeName tokens =
let
fun f symbol = (Grammar.identOfSymbol symbol, (symToTycon "") symbol)
fun makeTycons tokens = List.map f tokens
in
MLAst.Datatype [(typeName, makeTycons tokens)]
end
(* symbol list -> MLAst.dec *)
(* example outpu: fun show (EOF) = "EOF" | ... *)
fun makeShowFun tokens =
let
fun makePat symbol =
let val cat = symToCategory symbol in
case (Grammar.kindOf symbol, Grammar.levelOf symbol) of
(Grammar.Nonterm, _) => MLAst.AsisPat ("(" ^ symToCategory symbol ^ " a)")
| (Grammar.UnitTerm, _) => MLAst.AsisPat ("(" ^ symToCategory symbol ^ ")")
| (_, 0) => MLAst.AsisPat ("(" ^ symToCategory symbol ^ " a)")
| (_, _) => MLAst.AsisPat ("(" ^ symToCategory symbol ^ " a)")
end
fun makeBody symbol =
let val cat = symToCategory symbol in
case (Grammar.kindOf symbol, Grammar.levelOf symbol) of
(Grammar.UnitTerm, _) => MLAst.AsisExp ("\"" ^ cat ^ "\"")
| (Grammar.IntTerm, 0) => MLAst.AsisExp ("\"" ^ cat ^ "(\" ^ Int.toString a ^ \")\"")
| (Grammar.StrTerm, 0) => MLAst.AsisExp ("\"" ^ cat ^ "(\" ^ a ^ \")\"")
| (Grammar.CharTerm, 0) => MLAst.AsisExp ("\"" ^ cat ^ "(\" ^ String.str a ^ \")\"")
| (Grammar.Nonterm, _) => MLAst.AsisExp ("\"" ^ cat ^ "(\" ^ Ast.show" ^ Util.chopDigit cat ^ " a ^ \")\"")
| (_, _) => MLAst.AsisExp ("\"" ^ cat ^ "(\" ^ Ast.show" ^ Util.chopDigit cat ^ " a ^ \")\"")
end
val patExps = List.map (fn token => ([makePat token], makeBody token)) tokens
in
MLAst.Fun [("show", patExps)]
end
(* makeAstDatatype : string list -> Grammar.rule list -> MLAst.dec *)
(* example output:
datatype grammar =
Grammar of Lex.span * defs
and defs = ... *)
fun makeAstDatatype idents rules =
let
fun makeDatatype name =
let
val rules =
List.filter
(fn rule =>
name = Util.chopDigit (Grammar.identOfSymbol (Grammar.lhsOf rule))
andalso Grammar.levelOf (Grammar.lhsOf rule) = 0)
rules
fun ruleToCons rule =
case Grammar.consOf rule of
Grammar.Wild => NONE
| Grammar.ListE => NONE
| Grammar.ListCons => NONE
| Grammar.ListOne => NONE
| Grammar.Id ident =>
case List.mapPartial (symToTycon "") (Grammar.rhsOf rule) of
[] => SOME (ident, SOME (MLAst.Tycon "Lex.span"))
| tys => SOME (ident, SOME (MLAst.TupleType (MLAst.Tycon "Lex.span"::tys)))
in
(* type name and constructors *)
(Util.toLower name, List.mapPartial ruleToCons rules)
end
in
(* this makes mutually recursive datatypes *)
MLAst.Datatype (List.map makeDatatype idents)
end
fun makeShowAstFun rules =
let
val lhss = map Grammar.lhsOf rules
val typeNameOfSym = Util.chopDigit o Grammar.identOfSymbol
fun symToTriple sym =
let
val typeName = typeNameOfSym sym
val level = Grammar.levelOf sym
val kind = Grammar.kindOf sym
in
(typeName, level, kind)
end
val triples = Util.uniq (map symToTriple lhss)
(* string * int -> fvalbind i.e. ident * (pat list * exp) list *)
fun makeFun (typeName, level, kind) =
let
fun funNameOf (typeName, 0, Grammar.IntTerm) =
"Int.toString"
| funNameOf (typeName, 0, Grammar.StrTerm) =
"String.toString"
| funNameOf (typeName, 0, Grammar.CharTerm) =
"String.str"
| funNameOf (typeName, level, _) =
"show" ^ addPrimes typeName level
val rules = List.filter (fn rule => (typeNameOfSym o Grammar.lhsOf) rule = typeName) rules
fun ruleToBody rule =
case Grammar.consOf rule of
Grammar.Wild => NONE
| Grammar.ListE => NONE