Debian Codegraph @

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

raw
1 (* gla.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 * An interpretation of Parr's Grammar Lookahead Automata.
9 * MORE COMMENTS COMING SOON
10 *)
11
12 structure GLA :>
13 sig
14
15 type gla
16 type prepath = Token.Set.set list
17
18 val mkGLA : LLKSpec.grammar -> gla
19 val lookK : (gla * LLKSpec.prod * prepath * Int.int) -> Token.Set.set
20 val lookKFollow : (gla * LLKSpec.nonterm * prepath * Int.int) -> Token.Set.set
21
22 val dumpGraph : (string * LLKSpec.grammar * gla) -> unit
23
24 end = struct
25
26 structure S = LLKSpec
27 structure NMap = Nonterm.Map
28 structure PMap = Prod.Map
29 structure TSet = Token.Set
30
31 datatype node_type
32 = Initial
33 | Final
34 | Normal
35
36 datatype node = Node of {
37 id : Int.int,
38 edges : edge list ref,
39 ty : node_type,
40 nt : S.nonterm
41 }
42 and edge = Edge of (label * node)
43 and label
44 = Epsilon
45 | Tok of Token.token
46 | Call of S.nonterm
47
48 datatype gla = GLA of {
49 nodes : node list,
50 prodMap : node PMap.map,
51 startOf : S.nonterm -> node,
52 finEBNF : S.nonterm -> node
53 }
54
55 type prepath = Token.Set.set list
56
57 fun isFinal (Node {ty = Final, ...}) = true
58 | isFinal _ = false
59 fun isInitial (Node {ty = Initial, ...}) = true
60 | isInitial _ = false
61 fun edgesOf (Node {edges, ...}) = !edges
62 fun idOf (Node {id, ...}) = id
63 fun ntOf (Node {nt, ...}) = nt
64 fun sameNode (n1, n2) = (idOf n1 = idOf n2)
65
66 structure Ord =
67 struct
68 type ord_key = node
69 fun compare (Node {id = id1, ...}, Node {id = id2, ...}) = Int.compare (id1, id2)
70 end
71
72 structure SCC = GraphSCCFn(Ord)
73 structure NodeSet = RedBlackSetFn (Ord)
74
75 (* Build an NFA for the grammar *)
76 fun mkGLA grm = let
77 val S.Grammar {toks, nterms, prods, eof, startnt, ...} = grm
78 val nextId = ref 0
79 val nodes : node list ref = ref []
80 fun newNode (nt, ty) = let
81 val _ = nextId := !nextId + 1
82 val n = Node {id = !nextId, edges = ref [], ty = ty, nt = nt}
83 in
84 nodes := n :: (!nodes);
85 n
86 end
87 fun makeNTs (f) = List.foldl NMap.insert' NMap.empty
88 (ListPair.zip (nterms, List.map f nterms))
89 (* create initial, final state for each nonterminal *)
90 val ntMap = makeNTs (fn nt => newNode (nt, Initial))
91 val finalMap = makeNTs (fn nt => newNode (nt, Final))
92 fun mkOf map nt = valOf (NMap.find (map, nt))
93 val startOf = mkOf ntMap
94 val finalOf = mkOf finalMap
95 val finEBNF = ref NMap.empty
96 fun addFinEBNF (nt, n) = (finEBNF := NMap.insert (!finEBNF, nt, n))
97 fun addEdge (Node {edges, ...}, target, label) = (
98 edges := (Edge (label, target))::(!edges);
99 case label
100 of Call nt =>
101 (* add follow edge *)
102 addEdge (finalOf nt, target, Epsilon)
103 | _ => ())
104 (* iterate through the items of a production, creating both nodes
105 * and edges.
106 *)
107 fun iter (nt, lastNode, []) = addEdge (lastNode, finalOf nt, Epsilon)
108 | iter (nt, lastNode, itm::itms) = let
109 val n = newNode (nt, Normal)
110 in
111 (case Item.sym itm
112 of S.TOK t =>
113 addEdge (lastNode, n, Tok t)
114 | S.NONTERM (nt, _) =>
115 addEdge (lastNode, n, Call nt)
116 | S.CLOS nt => let
117 val nback = newNode (nt, Normal)
118 in
119 addEdge (lastNode, n, Epsilon);
120 addEdge (lastNode, nback, Call nt);
121 addEdge (nback, lastNode, Epsilon);
122 addFinEBNF (nt, n)
123 end
124 | S.POSCLOS nt => let
125 val nback = newNode (nt, Normal)
126 in
127 addEdge (lastNode, nback, Call nt);
128 addEdge (nback, n, Epsilon);
129 addEdge (nback, lastNode, Epsilon);
130 addFinEBNF (nt, n)
131 end
132 | S.OPT nt => (
133 addEdge (lastNode, n, Epsilon);
134 addEdge (lastNode, n, Call nt);
135 addFinEBNF (nt, n))
136 (* end case *));
137 iter (nt, n, itms)
138 end
139 (* process a production *)
140 fun doProd prod = let
141 val lhs = Prod.lhs prod
142 val n = newNode (lhs, Normal)
143 in
144 iter (lhs, n, Prod.items prod);
145 addEdge (startOf lhs, n, Epsilon);
146 (prod, n)
147 end
148 val prodMap = foldl PMap.insert' PMap.empty (map doProd prods)
149 val eofNode = newNode (startnt, Normal)
150 in
151 addEdge (eofNode, eofNode, Tok eof);
152 addEdge (finalOf startnt, eofNode, Epsilon);
153 GLA {nodes = !nodes, prodMap = prodMap,
154 startOf = startOf, finEBNF = mkOf (!finEBNF)}
155 end
156
157 fun unionAll sets = foldl TSet.union TSet.empty sets
158
159 (* Traverse the GLA, finding all possible tokens that can appear
160 * k tokens ahead of node n. The stack holds sharper follow information
161 * when available. See the implementation notes for more detail.
162 *)
163 fun look (startOf, n, k, stack, prePath, leftSet, acc) = let
164 val leftSet' = NodeSet.add (leftSet, n)
165 val lookRepl = (fn (tokSet, leftSet) => (tokSet, leftSet')) o look
166 fun follow (Edge (Tok t, n'), (tokSet, leftSet)) =
167 if k = 1 then (TSet.add (tokSet, t), leftSet)
168 else if TSet.member(hd prePath, t) then
169 lookRepl (startOf, n', k - 1, stack,
170 tl prePath, NodeSet.empty, tokSet)
171 else (tokSet, leftSet)
172 | follow (Edge (Epsilon, n'), (tokSet, leftSet)) =
173 look (startOf, n', k, stack, prePath, leftSet, tokSet)
174 | follow (Edge (Call nt, n'), (tokSet, leftSet)) =
175 lookRepl (startOf, startOf nt, k,
176 n'::stack, prePath, leftSet, tokSet)
177 in
178 if NodeSet.member (leftSet, n) then
179 if isInitial n then (
180 Err.leftRecur (Nonterm.qualName (ntOf n));
181 (TSet.empty, leftSet'))
182 else
183 (acc, leftSet')
184 else if isFinal n andalso length stack > 0 then
185 look (startOf, hd stack, k, tl stack, prePath, leftSet', acc)
186 else
187 foldl follow (acc, leftSet') (edgesOf n)
188 end
189
190 (* compute lookahead set k tokens into the given production *)
191 fun lookK (GLA {prodMap, startOf, ...}, prod, prePath, k) =
192 #1 (look (startOf, valOf (PMap.find (prodMap, prod)), k, [],
193 prePath, NodeSet.singleton (startOf (Prod.lhs prod)),
194 TSet.empty))
195
196 (* compute lookahead set k tokens AFTER the given EBNF subrule *)
197 fun lookKFollow (GLA {finEBNF, startOf, ...}, nt, prePath, k) =
198 #1 (look (startOf, finEBNF nt, k, [], prePath, NodeSet.empty, TSet.empty))
199
200 (* the below code dumps the graph to a .DOT file *)
201 (* TODO: move this to its own module *)
202
203 datatype attribute = ATTR of string * string
204 datatype d_node = NODE of string * attribute list
205 datatype di_edge = EDGE of string * string * attribute list
206 datatype di_graph = GRAPH of string * d_node list * di_edge list * attribute list
207
208 fun replBS str =
209 String.translate
210 (fn #"\\" => "\\\\" | c => String.str c)
211 str
212
213 fun writeGraph (out, graph) = let
214 (* output a string *)
215 fun wr s = TextIO.output (out, s)
216 (* output a string list *)
217 fun wrs ss = wr (String.concat ss)
218 (* indent to some level *)
219 fun wrIndent 0 = ()
220 | wrIndent lvl = (wr " "; wrIndent (lvl - 1))
221 (* apply output functions, indenting each time *)
222 fun app indent f list =
223 List.app (fn x => (wrIndent indent; f x)) list
224 fun wrAttr (ATTR (name, value)) = wrs ([
225 "[ ", name, " = \"", value, "\" ]", "\n"
226 ])
227 fun wrNode (NODE (name, atts)) =
228 (wr name;
229 wr "\n";
230 app 2 wrAttr atts)
231 fun wrEdge (EDGE (no1, no2, atts)) =
232 (wrs ([no1, " -> ", no2, "\n"]);
233 app 2 wrAttr atts)
234 fun wrGraphAttr attr =
235 (wr "graph\n";
236 wrIndent 2;
237 wrAttr attr)
238 fun wrGraph (GRAPH (name, nodes, edges, atts)) =
239 (wrs (["digraph ", name, " {\n"]);
240 app 1 wrGraphAttr atts;
241 app 1 wrNode nodes;
242 app 1 wrEdge edges;
243 wr "}")
244 in wrGraph graph
245 end
246
247 fun dumpGraph (fname, grm, gla) = let
248 val S.Grammar {toks, nterms, prods, eof, ...} = grm
249 val GLA {startOf, nodes, ...} = gla
250 val seen = ref NodeSet.empty
251 fun addSeen n = seen := NodeSet.add (!seen, n)
252 fun idOf (Node {id, ...}) = id
253 fun nameOf n = Int.toString (idOf n)
254 fun doNode n =
255 if NodeSet.member(!seen, n) then
256 []
257 else (
258 addSeen n;
259 if isFinal n then []
260 else List.concat (map (doEdge n) (edgesOf n)))
261 (*
262 and doEdge n (Edge (Call nt, _)) =
263 [EDGE (nameOf n, nameOf (startOf nt), [])]
264 | doEdge n (Edge (lbl, n')) =
265 (EDGE (nameOf n, nameOf n', [
266 ATTR ("label", case lbl
267 of Epsilon => ""
268 | Tok t => Token.name t)]))
269 :: (doNode n')
270 *)
271 and doEdge n (Edge (lbl, n')) =
272 (EDGE (nameOf n, nameOf n', [
273 ATTR ("label", case lbl
274 of Epsilon => ""
275 | Tok t => Token.name t
276 | Call nt => Nonterm.qualName nt)]))
277 :: (doNode n')
278 val edges = List.concat (map (doNode o startOf) nterms)
279 fun doNT nt = NODE (nameOf (startOf nt), [ATTR ("label", Nonterm.qualName nt), ATTR ("shape", "box")])
280 fun doFinal node = if isFinal node then
281 SOME (NODE (nameOf node,
282 [ATTR ("shape", "doublecircle")]))
283 else NONE
284 val nodes = (map doNT nterms) @ (List.mapPartial doFinal nodes)
285 val graph = GRAPH ("dump", nodes, edges, [ATTR ("rankdir", "LR")])
286 val out = TextIO.openOut (fname ^ ".dot")
287 in
288 TextIO.output (TextIO.stdErr, concat[" writing ", fname, ".dot\n"]);
289 writeGraph (out, graph)
290 before TextIO.closeOut out
291 end
292
293 end