Debian Codegraph @

lib/mllpt-lib/ml-lpt/ml-antlr/nonterm.sml

raw
1 (* nonterm.sml
2 *
3 * COPYRIGHT (c) 2006
4 * John Reppy (http://www.cs.uchicago.edu/~jhr)
5 * Aaron Turon (http://www.cs.uchicago.edu/~adrassi)
6 * All rights reserved.
7 *
8 * Utility functions for the nonterm datatype.
9 *)
10
11 structure Nonterm =
12 struct
13
14 datatype nonterm = datatype LLKSpec.nonterm
15
16 fun name (NT{name, ...}) = Atom.toString name
17 fun toString nt = name nt
18
19 fun qualName (nt as NT{binding = LLKSpec.WITHIN (LLKSpec.PROD {lhs, ...}), ...}) =
20 (qualName lhs) ^ "_" ^ (name nt)
21 | qualName nt = name nt
22
23 fun isSubrule (NT{binding = LLKSpec.TOP, ...}) = false
24 | isSubrule _ = true
25
26 fun parent (NT{binding = LLKSpec.WITHIN prod, ...}) = SOME prod
27 | parent _ = NONE
28
29 fun isEBNF (NT{isEBNF = v, ...}) = v
30 fun prods (NT{prods, ...}) = !prods
31 fun formals (NT{formals, ...}) = !formals
32 fun ty (NT{ty, ...}) = !ty
33
34 fun span (NT{loc, ...}) = !loc
35
36 fun compare (NT{id=a, ...}, NT{id=b, ...}) = Int.compare(a, b)
37 fun lexCompare (NT{name=a, ...}, NT{name=b, ...}) =
38 String.compare(Atom.toString a, Atom.toString b)
39 fun same (NT{id=a, ...}, NT{id=b, ...}) = (a = b)
40
41 structure Ord =
42 struct
43 type ord_key = nonterm
44 val compare = compare
45 end
46
47 structure Set = RedBlackSetFn (Ord)
48 structure Map = RedBlackMapFn (Ord)
49
50 fun setToString s = let
51 (* simple insertion sort to lexically order the set *)
52 fun ins (nt, []) = [nt]
53 | ins (nt, nt'::nts) = (case lexCompare(nt, nt')
54 of LESS => nt::nt'::nts
55 | _ => nt'::ins(nt, nts)
56 (* end case *))
57 val nts = Set.foldl ins [] s
58 in
59 String.concat[
60 "{", String.concatWith "," (List.map toString nts), "}"
61 ]
62 end
63
64 structure SCC = GraphSCCFn (Ord)
65 structure S = LLKSpec
66
67 (* topologically sort the nonterminal dependency graph
68 * rooted at starts; return a list of nonterm lists
69 *)
70 fun topsort (starts) = let
71 fun prodItems (S.PROD {rhs, ...}) = !rhs
72 fun sym (S.ITEM {sym, ...}) = sym
73 fun followItem (S.NONTERM (nt, _)) =
74 if isSubrule nt then follow nt
75 else [nt]
76 | followItem (S.CLOS nt) = follow nt
77 | followItem (S.POSCLOS nt) = follow nt
78 | followItem (S.OPT nt) = follow nt
79 | followItem (S.TOK _) = []
80 and followItems itms = List.concat (map (followItem o sym) itms)
81 and follow nt =
82 List.concat (map (followItems o prodItems)
83 (prods nt))
84 val scc = SCC.topOrder' {roots = starts, follow = follow}
85 fun compToList (SCC.SIMPLE nt) = [nt]
86 | compToList (SCC.RECURSIVE nts) = nts
87 in
88 map compToList scc
89 end
90
91 end