Debian Codegraph @

lib/mllpt-lib/ml-lpt/ml-antlr/check-grammar.sml

raw
1 (* check-grammar.sml
2 *
3 * COPYRIGHT (c) 2005
4 * John Reppy (http://www.cs.uchicago.edu/~jhr)
5 * Aaron Turon (http://www.cs.uchicago.edu/~adrassi)
6 * All rights reserved.
7 *
8 * Check a parse tree, returning a grammar.
9 *)
10
11 structure CheckGrammar : sig
12
13 val check : GrammarSyntax.grammar option -> LLKSpec.grammar
14
15 end = struct
16
17 structure Syn = GrammarSyntax
18 structure S = LLKSpec
19 structure ATbl = AtomTable
20 structure AMap = AtomMap
21 structure ASet = AtomSet
22
23 fun nextId (r : int ref) () = let val id = !r in r := id+1; id end
24
25 (* auto-number the bindings for repeated variable names *)
26 local
27 fun addNumbers(acc, _, _, []) = rev acc
28 | addNumbers(acc, n, s, s'::bs) =
29 if s = s' then
30 addNumbers((s' ^ (Int.toString n))::acc, n+1, s, bs)
31 else addNumbers(s'::acc, n, s, bs)
32 fun numberBindings([]) = []
33 | numberBindings(b::bs) =
34 if List.exists (fn b' => b = b') bs
35 then (b ^ "1")::numberBindings(addNumbers([], 2, b, bs))
36 else b::(numberBindings bs)
37 (* assign a binding to an item *)
38 fun binding tokTbl (_, Syn.SYMBOL (name, _)) = (case ATbl.find tokTbl name
39 of SOME tok => (Token.name tok, Token.hasTy tok)
40 | NONE => (Atom.toString name, true)
41 (* end case *))
42 | binding tokTbl (_, Syn.SUBRULE _) = ("SR", true)
43 | binding tokTbl (_, Syn.CLOS itm) = binding tokTbl itm
44 | binding tokTbl (_, Syn.POSCLOS itm) = binding tokTbl itm
45 | binding tokTbl (_, Syn.OPT itm) = binding tokTbl itm
46 in
47 (* assign bindings to a list of items *)
48 fun bindings (userNames, items, tokTbl) = let
49 (* all symbols with user-assigned names should yield a result
50 * for default actions
51 *)
52 val userBindings = map (Option.map (fn nm => (nm, true))) userNames
53 val autoBindings = map (binding tokTbl) items
54 val (autoNames, autoYields) = ListPair.unzip autoBindings
55 val autoNames' = numberBindings autoNames
56 val autoBindings' = ListPair.zip (autoNames', autoYields)
57 in
58 ListPair.map getOpt (userBindings, autoBindings')
59 end
60 end
61
62 fun flatten [] = []
63 | flatten ((_, Syn.IMPORT {filename, dropping}) :: ds) = let
64 val dropSet = ASet.fromList (map (fn (_, s) => s) dropping)
65 fun keep s = not (ASet.member (dropSet, s))
66 fun shouldImport (_, Syn.KEYWORD _) = true
67 | shouldImport (_, Syn.VALUE _) = true
68 | shouldImport (_, Syn.DEFS _) = true
69 | shouldImport (_, Syn.TOKEN (sym, _, SOME abbrev)) =
70 keep sym andalso keep abbrev
71 | shouldImport (_, Syn.TOKEN (sym, _, NONE)) = keep sym
72 | shouldImport (_, Syn.REFCELL _) = true
73 | shouldImport (_, Syn.RULE {lhs, ...}) = keep lhs
74 | shouldImport _ = false
75 val imp = case ParseFile.parse filename
76 of SOME ds' => flatten ds'
77 | NONE => []
78 in
79 (List.filter shouldImport imp) @ flatten ds
80 end
81 | flatten (d::ds) = d :: flatten ds
82
83 (* check a GrammarSyntax.grammar value for errors, while transforming
84 * it into an LLKSpec.grammar suitable for analysis and parser generation.
85 *)
86 fun check (SOME (g : Syn.grammar)) = let
87 val _ = Err.status "checking grammar"
88 val ds = flatten g (* flatten import directives *)
89 (* val _ = print (Syn.ppGrammar ds) *)
90 (* ref cells used to incrementally build grammar representation *)
91 val nextGlobalID = nextId (ref 0)
92 val tokTbl : S.token ATbl.hash_table = ATbl.mkTable (128, Fail "tokens table")
93 val tokList : S.token list ref = ref []
94 val keywords : Err.span ATbl.hash_table = ATbl.mkTable (64, Fail "keywords table")
95 val prefers : Err.span ATbl.hash_table = ATbl.mkTable (64, Fail "prefers table")
96 val changeList : (S.token list * S.token list) list ref = ref []
97 val defaults : (Err.span * string) ATbl.hash_table = ATbl.mkTable (32, Fail "defaults table")
98 val entryPts : Err.span ATbl.hash_table = ATbl.mkTable (16, Fail "entryPts table")
99 val name : (string * Err.span) option ref = ref NONE
100 val header : Syn.code option ref = ref NONE
101 val startSym : (Atom.atom * Err.span) option ref = ref NONE
102 val defs : Action.action ref = ref Action.empty
103 val toksImport : Action.action option ref = ref NONE
104 val refCells : S.refcell ATbl.hash_table = ATbl.mkTable (4, Fail "refCells table")
105 val ntTbl : (S.nonterm * (unit -> int)) ATbl.hash_table =
106 ATbl.mkTable (64, Fail "ntTbl table")
107 val ntList : S.nonterm list ref = ref []
108 val prodList : S.prod list ref = ref []
109 (* error message for duplicate declarations *)
110 fun dupeErr (origSpan, newSpan, whatDupe) =
111 Err.spanErr (newSpan,
112 "duplicate " :: whatDupe
113 @ [", originally declared at ", Err.span2str origSpan])
114 (* PHASE 1: record basic directives, checking for duplicates *)
115 fun doDecl1 (span, Syn.NAME n) = (case !name
116 of SOME (_, span') => dupeErr (span', span, ["%name declaration"])
117 | NONE => name := SOME (n, span)
118 (* end case *))
119 | doDecl1 (span, Syn.HEADER h) = (case !header
120 of SOME(span', _) => dupeErr (span', span, ["%header declaration"])
121 | NONE => header := SOME h
122 (* end case *))
123 | doDecl1 (span, Syn.START sym) = (case !startSym
124 of SOME (_, span') => dupeErr (span', span, ["%start declaration"])
125 | NONE => startSym := SOME (sym, span)
126 (* end case *))
127 | doDecl1 (span, Syn.ENTRY sym) = (case ATbl.find entryPts sym
128 of NONE => ATbl.insert entryPts (sym, span)
129 | SOME span' => dupeErr (span', span, [
130 "%entry declaration for '", Atom.toString sym, "'"
131 ])
132 (* end case *))
133 | doDecl1 (span, Syn.KEYWORD sym) = (case ATbl.find keywords sym
134 of NONE => ATbl.insert keywords (sym, span)
135 | SOME span' => dupeErr (span', span, [
136 "%keyword declaration for '", Atom.toString sym, "'"
137 ])
138 (* end case *))
139 | doDecl1 (span, Syn.PREFER sym) = (case ATbl.find prefers sym
140 of NONE => ATbl.insert prefers (sym, span)
141 | SOME span' => dupeErr (span', span, [
142 "%prefer declaration for '", Atom.toString sym, "'"
143 ])
144 (* end case *))
145 | doDecl1 (span, Syn.VALUE(sym, (_, code))) = (case ATbl.find defaults sym
146 of NONE => ATbl.insert defaults (sym, (span, code))
147 | SOME(span', _) => dupeErr (span', span, [
148 "%value declaration for '", Atom.toString sym, "'"
149 ])
150 (* end case *))
151 | doDecl1 (span, Syn.REFCELL (name, ty, code)) = (
152 case ATbl.find refCells (Atom.atom name)
153 of NONE => ATbl.insert refCells
154 (Atom.atom name,
155 S.REFCELL {
156 name = name, ty = ty,
157 initCode = Action.action code, loc = span})
158 | SOME (S.REFCELL {loc, ...}) =>
159 dupeErr (loc, span, ["%refcell declaration for '", name, "'"])
160 (* end case *))
161 | doDecl1 (span, Syn.DEFS code) =
162 defs := Action.concat (!defs, Action.action code)
163 | doDecl1 (span, Syn.TOKENTYPE ty) = (case !toksImport
164 of NONE => toksImport := SOME(Action.action(span, ty))
165 | SOME act => dupeErr (span, Action.span act, ["%tokentype declaration"])
166 (* end case *))
167 | doDecl1 _ = ()
168 val _ = app doDecl1 ds
169 (* PHASE 2: record %tokens declarations *)
170 val kwSet = ASet.addList (ASet.empty, map (fn (x, _) => x) (ATbl.listItemsi keywords))
171 fun isKW s = ASet.member (kwSet, s)
172 fun doDecl2 (span, Syn.TOKEN (sym, tyOpt, abbrevOpt)) = (
173 case ATbl.find tokTbl sym
174 of NONE => let
175 val _ = (case abbrevOpt
176 of SOME a => (case ATbl.find tokTbl a
177 of SOME (S.T{loc, ...}) =>
178 dupeErr (loc, span, [
179 "%tokens declaration with abbreviation ",
180 Atom.toString a
181 ])
182 | NONE => ()
183 (* end case *))
184 | NONE => ()
185 (* end case *))
186 (* check for default argument for non-nullary tokens *)
187 val dfltOpt = (case ATbl.find defaults sym
188 of SOME(span, code) => if Option.isSome tyOpt
189 then SOME code
190 else (
191 Err.spanErr (span, [
192 "value declaration for nullary token '",
193 Atom.toString sym, "'"
194 ]);
195 NONE)
196 | NONE => NONE
197 (* end case *))
198 val tok = S.T {
199 id = nextGlobalID(),
200 name = sym,
201 loc = span,
202 ty = tyOpt,
203 abbrev = abbrevOpt,
204 keyword = isKW sym orelse getOpt(Option.map isKW abbrevOpt, false),
205 default = dfltOpt
206 }
207 in
208 ATbl.insert tokTbl (sym, tok);
209 Option.app (fn a => ATbl.insert tokTbl (a, tok)) abbrevOpt;
210 tokList := tok :: !tokList
211 end
212 | SOME (S.T{loc, ...}) =>
213 dupeErr (loc, span, ["%tokens declaration for '", Atom.toString sym, "'"])
214 (* end case *))
215 | doDecl2 _ = ()
216 val _ = app doDecl2 ds
217 val _ = if List.length (!tokList) = 0 then
218 Err.errMsg ["Error: no tokens defined"]
219 else ()
220 val eofTok = S.T {
221 id = nextGlobalID(), name = Atom.atom "EOF", loc = Err.emptySpan, ty = NONE,
222 abbrev = NONE, keyword = false, default = NONE
223 }
224 val _ = (ATbl.insert tokTbl (Atom.atom "EOF", eofTok);
225 tokList := eofTok :: !tokList)
226 (* check for symbols in a %keyword, %prefer, %value, or %change declaration that
227 * are note defined as tokens.
228 *)
229 val tokSet = ASet.addList (ASet.empty, #1 (ListPair.unzip (ATbl.listItemsi tokTbl)))
230 fun undefErr spanOf kind name =
231 Err.spanErr (spanOf name, [kind, " '", Atom.toString name, "' is not declared as a token"])
232 val _ = ASet.app (undefErr (fn name => ATbl.lookup keywords name) "keyword") (ASet.difference (kwSet, tokSet))
233 val prefSet = ASet.addList (ASet.empty, map (fn (x, _) => x) (ATbl.listItemsi prefers))
234 val _ = ASet.app (undefErr (fn name => ATbl.lookup prefers name) "preferred token") (ASet.difference (prefSet, tokSet))
235 val dfltSet = ASet.addList (ASet.empty, map (fn (x, _) => x) (ATbl.listItemsi defaults))
236 val _ = ASet.app (undefErr (fn name => #1(ATbl.lookup defaults name)) "value") (ASet.difference (dfltSet, tokSet))
237 fun doChange (span, Syn.CHANGE(fromToks, toToks)) = let
238 fun toTok name = (case ATbl.find tokTbl name
239 of NONE => (
240 Err.spanErr (span, [
241 "'", Atom.toString name,
242 "' in %change declaration is not declared as a token"
243 ]);
244 eofTok)
245 | SOME tok => tok
246 (* end case *))
247 val change = (List.map toTok fromToks, List.map toTok toToks)
248 in
249 changeList := change :: !changeList
250 end
251 | doChange _ = ()
252 val _ = List.app doChange ds
253 (* FIXME: need to check that any value-carrying token that might be inserted has a default value *)
254 (* PHASE 3: load nonterminals *)
255 fun insNTerm (nt as S.NT{name, ...}) = let
256 val nid = nextId (ref 1)
257 in
258 ATbl.insert ntTbl (name, (nt, nid));
259 ntList := nt :: !ntList;
260 (nt, nid)
261 end
262 (* map a non-terminal name to its info record, creating a new nonterminal
263 * record if none is found.
264 *)
265 fun lookupNTerm name = (case ATbl.find ntTbl name
266 of NONE => (
267 if ASet.member (tokSet, name) then
268 Err.errMsg ["Error: symbol ", Atom.toString name,
269 " defined as both a token and a nonterminal."]
270 else ();
271 insNTerm (S.NT{name = name, id = nextGlobalID(), formals = ref [], ty = ref NONE,
272 binding = S.TOP, prods = ref[], isEBNF = false, loc = ref NONE}))
273 | SOME info => info
274 (* end case *))
275 (* check and load a rules and type annotations *)
276 fun doDecl3 (span, Syn.RULE {lhs, formals = newFormals, rhs}) = let
277 val (nt as S.NT{prods, formals, loc = ntLoc, ...}, nextProdID) =
278 lookupNTerm lhs
279 val nextSRID = nextId (ref 1)
280 val prodName = concat [Nonterm.name nt, "_PROD_", Int.toString (nextProdID())]
281 (* check the rhs, creating a production *)
282 val Syn.RHS {items, action, try, predicate, loc = rhsLoc} = rhs
283 val (userNames, items) = ListPair.unzip items
284 val finishedRHS : S.item list ref = ref []
285 val prod = S.PROD{
286 name = prodName,
287 lhs = nt,
288 rhs = finishedRHS,
289 rhsBindings = bindings (userNames, items, tokTbl),
290 try = try,
291 id = nextGlobalID(),
292 action = Option.map Action.action action,
293 pred = Option.map Action.action predicate,
294 loc = rhsLoc
295 }
296 fun doPreitem (Syn.SYMBOL (name, args)) =
297 if ATbl.inDomain tokTbl name
298 then if not (isSome args)
299 then S.TOK(valOf (ATbl.find tokTbl name))
300 else (Err.errMsg ["Attempted to apply arguments to token ",
301 Atom.toString name, "."];
302 S.TOK eofTok)
303 else S.NONTERM(#1 (lookupNTerm name), Option.map Action.action args)
304 | doPreitem (Syn.SUBRULE alts) = S.NONTERM(doSubrule (false, alts), NONE)
305 | doPreitem (Syn.CLOS itm) = S.CLOS(doSubrule (true, mkAlts itm))
306 | doPreitem (Syn.POSCLOS itm) = S.POSCLOS(doSubrule (true, mkAlts itm))
307 | doPreitem (Syn.OPT itm) = S.OPT(doSubrule (true, mkAlts itm))
308 and doItem (span, s) = S.ITEM {sym = doPreitem s,
309 id = nextGlobalID(),
310 loc = span}
311 and mkAlts (_, Syn.SUBRULE alts) = alts
312 | mkAlts (span, itm) = [Syn.RHS {
313 items = [(NONE, (span, itm))], loc = span,
314 action = NONE, try = false, predicate = NONE
315 }]
316 and doSubrule (isEBNF, alts) = let
317 val prods = ref []
318 val srName = Atom.atom (concat [prodName,
319 "_SUBRULE_", Int.toString (nextSRID())])
320 val sr = S.NT{
321 name = srName, formals = ref [], binding = S.WITHIN prod,
322 id = nextGlobalID(), prods = prods, isEBNF = isEBNF,
323 loc = ref NONE, ty = ref NONE}
324 fun altToRule alt = let
325 val Syn.RHS {loc, ...} = alt
326 in
327 (loc, Syn.RULE {lhs = srName, formals = [], rhs = alt})
328 end
329 in
330 ignore (insNTerm sr);
331 app (doDecl3 o altToRule) alts;
332 sr
333 end
334 in
335 finishedRHS := map doItem items; (* actually process the RHS *)
336 prodList := prod :: !prodList; (* add to global prod list *)
337 prods := prod :: !prods; (* add to lhs's prod list *)
338 formals := (map Atom.atom newFormals) (* TODO: check for agreement *)
339 end
340 | doDecl3 (span, Syn.NONTERM (nt, tyAnn)) = let
341 val (S.NT{ty, ...}, _) = lookupNTerm nt
342 in case !ty
343 of NONE => ty := SOME tyAnn
344 | SOME _ => Err.spanErr (span, [
345 "duplicate type annotation for nonterminal ",
346 Atom.toString nt, "."])
347 end
348 | doDecl3 _ = ()
349 val _ = app doDecl3 ds
350 val nterms = rev(!ntList)
351 (* check the grammar *)
352 val _ = if List.length (!prodList) = 0 then (
353 Err.errMsg ["Error: no rules defined."];
354 raise Err.Abort)
355 else ()
356 (* check for undefined nonterminals, while reversing the order of productions *)
357 fun chkNT (S.NT{name, prods, ...}) = (case !prods
358 of [] => Err.errMsg ["Error: symbol ", Atom.toString name, " is not defined."]
359 | l => prods := List.rev l
360 (* end case *))
361 val _ = app chkNT nterms
362 (* note: safe to assume length nterms > 0, otherwise aborted above *)
363 fun findNT errStr (sym, span) = (case ATbl.find ntTbl sym
364 of NONE => (Err.spanErr (span, ["Error: ", errStr, " symbol ",
365 Atom.toString sym,
366 " is not defined."]);
367 hd nterms)
368 | SOME (nt, _) => nt
369 (* end case *))
370 val startnt = (case !startSym
371 of NONE => hd nterms
372 | SOME s => findNT "%start" s
373 (* end case *))
374 val entryPoints = map (findNT "%entry") (ATbl.listItemsi entryPts)
375 val sortedTops = Nonterm.topsort (startnt::entryPoints)
376 val topsSet = AtomSet.addList
377 (AtomSet.empty,
378 map (Atom.atom o Nonterm.name) (List.concat sortedTops))
379 (* check that all defined nonterminals are used *)
380 fun checkNTInTops nt =
381 if Nonterm.isSubrule nt = false
382 andalso AtomSet.member (topsSet, Atom.atom (Nonterm.name nt)) = false
383 then Err.warning ["Warning: nonterminal ", Nonterm.name nt,
384 " is not reachable from any entry point."]
385 else ()
386 val _ = app checkNTInTops nterms
387 val _ = Err.abortIfErr()
388 in
389 S.Grammar{
390 name = getOpt (Option.map #1 (!name), ""),
391 header = Option.map #2 (!header),
392 defs = !defs,
393 toks = List.rev (!tokList),
394 toksImport = !toksImport,
395 changes = let (* add the %prefer tokens to the changes list *)
396 fun preferChange (tok, _, changes) =
397 ([], [ATbl.lookup tokTbl tok]) :: changes
398 in
399 ATbl.foldi preferChange (List.rev (!changeList)) prefers
400 end,
401 nterms = nterms,
402 prods = List.rev(!prodList),
403 eof = eofTok,
404 sortedTops = sortedTops,
405 startnt = startnt,
406 entryPoints = entryPoints,
407 refcells = ATbl.listItems refCells
408 }
409 end
410 | check NONE = raise Err.Abort
411
412 end