1 (* Title: Pure/Syntax/parser.ML
3 Author: Carsten Clasohm, Sonia Mahjoub, and Markus Wenzel, TU Muenchen
5 General context-free parser for the inner syntax of terms, types, etc.
12 val extend_gram: gram -> SynExt.xprod list -> gram
13 val make_gram: SynExt.xprod list -> gram
14 val merge_grams: gram -> gram -> gram
15 val pretty_gram: gram -> Pretty.T list
17 Node of string * parsetree list |
19 val parse: gram -> string -> Lexicon.token list -> parsetree list
20 val branching_level: int ref
23 structure Parser: PARSER =
31 type nt_tag = int; (*production for the NTs are stored in an array
32 so we can identify NTs by their index*)
34 datatype symb = Terminal of token
35 | Nonterminal of nt_tag * int; (*(tag, precedence)*)
37 type nt_gram = ((nt_tag list * token list) *
38 (token option * (symb list * string * int) list) list);
39 (*(([dependent_nts], [start_tokens]),
40 [(start_token, [(rhs, name, prio)])])*)
41 (*depent_nts is a list of all NTs whose lookahead
42 depends on this NT's lookahead*)
45 Gram of {nt_count: int, prod_count: int,
46 tags: nt_tag Symtab.table,
47 chains: (nt_tag * nt_tag list) list, (*[(to, [from])]*)
49 prods: nt_gram Array.array};
50 (*"tags" is used to map NT names (i.e. strings) to tags;
51 chain productions are not stored as normal productions
52 but instead as an entry in "chains";
53 lambda productions are stored as normal productions
54 and also as an entry in "lambdas"*)
56 val UnknownStart = EndToken; (*productions for which no starting token is
57 known yet are associated with this token*)
59 (* get all NTs that are connected with a list of NTs
60 (used for expanding chain list)*)
61 fun connected_with _ [] relatives = relatives
62 | connected_with chains (root :: roots) relatives =
63 let val branches = subtract (op =) relatives (these (AList.lookup (op =) chains root));
64 in connected_with chains (branches @ roots) (branches @ relatives) end;
66 (* convert productions to grammar;
67 N.B. that the chains parameter has the form [(from, [to])];
68 prod_count is of type "int option" and is only updated if it is <> NONE*)
69 fun add_prods _ chains lambdas prod_count [] = (chains, lambdas, prod_count)
70 | add_prods prods chains lambdas prod_count
71 ((lhs, new_prod as (rhs, name, pri)) :: ps) =
73 val chain_from = case (pri, rhs) of (~1, [Nonterminal (id, ~1)]) => SOME id | _ => NONE;
75 (*store chain if it does not already exist*)
76 val (new_chain, chains') = case chain_from of NONE => (NONE, chains) | SOME from =>
77 let val old_tos = these (AList.lookup (op =) chains from) in
78 if member (op =) old_tos lhs then (NONE, chains)
79 else (SOME from, AList.update (op =) (from, insert (op =) lhs old_tos) chains)
82 (*propagate new chain in lookahead and lambda lists;
83 added_starts is used later to associate existing
84 productions with new starting tokens*)
85 val (added_starts, lambdas') =
86 if is_none new_chain then ([], lambdas) else
87 let (*lookahead of chain's source*)
88 val ((from_nts, from_tks), _) = Array.sub (prods, the new_chain);
90 (*copy from's lookahead to chain's destinations*)
91 fun copy_lookahead [] added = added
92 | copy_lookahead (to :: tos) added =
94 val ((to_nts, to_tks), ps) = Array.sub (prods, to);
96 val new_tks = subtract (op =) to_tks from_tks; (*added lookahead tokens*)
97 in Array.update (prods, to, ((to_nts, to_tks @ new_tks), ps));
98 copy_lookahead tos (if null new_tks then added
99 else (to, new_tks) :: added)
102 val tos = connected_with chains' [lhs] [lhs];
103 in (copy_lookahead tos [],
104 (if member (op =) lambdas lhs then tos else []) union lambdas)
107 (*test if new production can produce lambda
108 (rhs must either be empty or only consist of lambda NTs)*)
109 val (new_lambda, lambdas') =
110 if forall (fn (Nonterminal (id, _)) => member (op =) lambdas' id
111 | (Terminal _) => false) rhs then
112 (true, lambdas' union (connected_with chains' [lhs] [lhs]))
116 (*list optional terminal and all nonterminals on which the lookahead
117 of a production depends*)
118 fun lookahead_dependency _ [] nts = (NONE, nts)
119 | lookahead_dependency _ ((Terminal tk) :: _) nts = (SOME tk, nts)
120 | lookahead_dependency lambdas ((Nonterminal (nt, _)) :: symbs) nts =
121 if member (op =) lambdas nt then
122 lookahead_dependency lambdas symbs (nt :: nts)
123 else (NONE, nt :: nts);
125 (*get all known starting tokens for a nonterminal*)
126 fun starts_for_nt nt = snd (fst (Array.sub (prods, nt)));
128 val token_union = gen_union matching_tokens;
130 (*update prods, lookaheads, and lambdas according to new lambda NTs*)
131 val (added_starts', lambdas') =
133 (*propagate added lambda NT*)
134 fun propagate_lambda [] added_starts lambdas= (added_starts, lambdas)
135 | propagate_lambda (l :: ls) added_starts lambdas =
137 (*get lookahead for lambda NT*)
138 val ((dependent, l_starts), _) = Array.sub (prods, l);
140 (*check productions whose lookahead may depend on lambda NT*)
141 fun examine_prods [] add_lambda nt_dependencies added_tks
143 (add_lambda, nt_dependencies, added_tks, nt_prods)
144 | examine_prods ((p as (rhs, _, _)) :: ps) add_lambda
145 nt_dependencies added_tks nt_prods =
146 let val (tk, nts) = lookahead_dependency lambdas rhs [];
148 if member (op =) nts l then (*update production's lookahead*)
150 val new_lambda = is_none tk andalso nts subset lambdas;
152 val new_tks = subtract (op =) l_starts
153 ((if is_some tk then [the tk] else []) @
154 Library.foldl token_union ([], map starts_for_nt nts));
156 val added_tks' = token_union (new_tks, added_tks);
158 val nt_dependencies' = nts union nt_dependencies;
160 (*associate production with new starting tokens*)
161 fun copy [] nt_prods = nt_prods
162 | copy (tk :: tks) nt_prods =
163 let val old_prods = these (AList.lookup (op =) nt_prods tk);
165 val prods' = p :: old_prods;
167 |> AList.update (op =) (tk, prods')
172 let val new_opt_tks = map SOME new_tks;
173 in copy ((if new_lambda then [NONE] else []) @
174 new_opt_tks) nt_prods
176 in examine_prods ps (add_lambda orelse new_lambda)
177 nt_dependencies' added_tks' nt_prods'
179 else (*skip production*)
180 examine_prods ps add_lambda nt_dependencies
184 (*check each NT whose lookahead depends on new lambda NT*)
185 fun process_nts [] added_lambdas added_starts =
186 (added_lambdas, added_starts)
187 | process_nts (nt :: nts) added_lambdas added_starts =
189 val (lookahead as (old_nts, old_tks), nt_prods) =
190 Array.sub (prods, nt);
192 (*existing productions whose lookahead may depend on l*)
194 (these o AList.lookup (op =) nt_prods)
195 (SOME (hd l_starts handle Empty => UnknownStart));
197 (*add_lambda is true if an existing production of the nt
198 produces lambda due to the new lambda NT l*)
199 val (add_lambda, nt_dependencies, added_tks, nt_prods') =
200 examine_prods tk_prods false [] [] nt_prods;
202 val added_nts = subtract (op =) old_nts nt_dependencies;
205 if add_lambda then nt :: added_lambdas
207 in Array.update (prods, nt,
208 ((added_nts @ old_nts, old_tks @ added_tks),
210 (*N.B. that because the tks component
211 is used to access existing
212 productions we have to add new
213 tokens at the _end_ of the list*)
215 if null added_tks then
216 process_nts nts added_lambdas' added_starts
218 process_nts nts added_lambdas'
219 ((nt, added_tks) :: added_starts)
222 val (added_lambdas, added_starts') =
223 process_nts dependent [] added_starts;
225 val added_lambdas' = subtract (op =) lambdas added_lambdas;
226 in propagate_lambda (ls @ added_lambdas') added_starts'
227 (added_lambdas' @ lambdas)
229 in propagate_lambda (subtract (op =) lambdas lambdas') added_starts lambdas' end;
231 (*insert production into grammar*)
232 val (added_starts', prod_count') =
233 if is_some chain_from then (added_starts', prod_count) (*don't store chain production*)
235 (*lookahead tokens of new production and on which
236 NTs lookahead depends*)
237 val (start_tk, start_nts) = lookahead_dependency lambdas' rhs [];
239 val start_tks = Library.foldl token_union
240 (if is_some start_tk then [the start_tk] else [],
241 map starts_for_nt start_nts);
243 val opt_starts = (if new_lambda then [NONE]
244 else if null start_tks then [SOME UnknownStart]
245 else []) @ (map SOME start_tks);
247 (*add lhs NT to list of dependent NTs in lookahead*)
249 | add_nts (nt :: nts) =
250 let val ((old_nts, old_tks), ps) = Array.sub (prods, nt);
251 in if member (op =) old_nts lhs then ()
252 else Array.update (prods, nt, ((lhs :: old_nts, old_tks), ps))
255 (*add new start tokens to chained NTs' lookahead list;
256 also store new production for lhs NT*)
257 fun add_tks [] added prod_count = (added, prod_count)
258 | add_tks (nt :: nts) added prod_count =
260 val ((old_nts, old_tks), nt_prods) = Array.sub (prods, nt);
262 val new_tks = subtract matching_tokens old_tks start_tks;
264 (*store new production*)
265 fun store [] prods is_new =
266 (prods, if is_some prod_count andalso is_new then
267 Option.map (fn x => x+1) prod_count
268 else prod_count, is_new)
269 | store (tk :: tks) prods is_new =
270 let val tk_prods = (these o AList.lookup (op =) prods) tk;
272 (*if prod_count = NONE then we can assume that
273 grammar does not contain new production already*)
274 val (tk_prods', is_new') =
275 if is_some prod_count then
276 if member (op =) tk_prods new_prod then (tk_prods, false)
277 else (new_prod :: tk_prods, true)
278 else (new_prod :: tk_prods, true);
281 |> is_new' ? AList.update (op =) (tk, tk_prods');
282 in store tks prods' (is_new orelse is_new') end;
284 val (nt_prods', prod_count', changed) =
285 if nt = lhs then store opt_starts nt_prods false
286 else (nt_prods, prod_count, false);
287 in if not changed andalso null new_tks then ()
288 else Array.update (prods, nt, ((old_nts, old_tks @ new_tks),
290 add_tks nts (if null new_tks then added
291 else (nt, new_tks) :: added) prod_count'
293 in add_nts start_nts;
294 add_tks (connected_with chains' [lhs] [lhs]) [] prod_count
297 (*associate productions with new lookaheads*)
300 (*propagate added start tokens*)
301 fun add_starts [] = ()
302 | add_starts ((changed_nt, new_tks) :: starts) =
304 (*token under which old productions which
305 depend on changed_nt could be stored*)
307 case find_first (not o member (op =) new_tks)
308 (starts_for_nt changed_nt) of
309 NONE => SOME UnknownStart
312 (*copy productions whose lookahead depends on changed_nt;
313 if key = SOME UnknownToken then tk_prods is used to hold
314 the productions not copied*)
315 fun update_prods [] result = result
316 | update_prods ((p as (rhs, _, _)) :: ps)
317 (tk_prods, nt_prods) =
319 (*lookahead dependency for production*)
320 val (tk, depends) = lookahead_dependency lambdas' rhs [];
322 (*test if this production has to be copied*)
323 val update = member (op =) depends changed_nt;
325 (*test if production could already be associated with
326 a member of new_tks*)
327 val lambda = length depends > 1 orelse
328 not (null depends) andalso is_some tk
329 andalso member (op =) new_tks (the tk);
331 (*associate production with new starting tokens*)
332 fun copy [] nt_prods = nt_prods
333 | copy (tk :: tks) nt_prods =
335 val tk_prods = (these o AList.lookup (op =) nt_prods) (SOME tk);
338 if not lambda then p :: tk_prods
339 else insert (op =) p tk_prods;
340 (*if production depends on lambda NT we
341 have to look for duplicates*)
344 |> AList.update (op =) (SOME tk, tk_prods')
349 (tk_prods, copy new_tks nt_prods)
350 else if key = SOME UnknownStart then
351 (p :: tk_prods, nt_prods)
352 else (tk_prods, nt_prods);
353 in update_prods ps result end;
355 (*copy existing productions for new starting tokens*)
356 fun process_nts [] added = added
357 | process_nts (nt :: nts) added =
359 val (lookahead as (old_nts, old_tks), nt_prods) =
360 Array.sub (prods, nt);
362 val tk_prods = (these o AList.lookup (op =) nt_prods) key;
364 (*associate productions with new lookahead tokens*)
365 val (tk_prods', nt_prods') =
366 update_prods tk_prods ([], nt_prods);
370 |> (key = SOME UnknownStart) ? AList.update (op =) (key, tk_prods')
373 subtract matching_tokens old_tks new_tks;
374 in if null added_tks then
375 (Array.update (prods, nt, (lookahead, nt_prods'));
376 process_nts nts added)
378 (Array.update (prods, nt,
379 ((old_nts, added_tks @ old_tks), nt_prods'));
380 process_nts nts ((nt, added_tks) :: added))
383 val ((dependent, _), _) = Array.sub (prods, changed_nt);
384 in add_starts (starts @ (process_nts dependent [])) end;
385 in add_starts added_starts' end;
386 in add_prods prods chains' lambdas' prod_count ps end;
391 fun pretty_gram (Gram {tags, prods, chains, ...}) =
393 fun pretty_name name = [Pretty.str (name ^ " =")];
395 val taglist = Symtab.dest tags;
397 fun pretty_symb (Terminal (Token s)) = Pretty.quote (Pretty.str s)
398 | pretty_symb (Terminal tok) = Pretty.str (str_of_token tok)
399 | pretty_symb (Nonterminal (tag, p)) =
400 let val name = fst (the (find_first (fn (n, t) => t = tag) taglist));
401 in Pretty.str (name ^ "[" ^ string_of_int p ^ "]") end;
403 fun pretty_const "" = []
404 | pretty_const c = [Pretty.str ("=> " ^ Library.quote c)];
406 fun pretty_pri p = [Pretty.str ("(" ^ string_of_int p ^ ")")];
408 fun pretty_prod name (symbs, const, pri) =
409 Pretty.block (Pretty.breaks (pretty_name name @
410 map pretty_symb symbs @ pretty_const const @ pretty_pri pri));
412 fun pretty_nt (name, tag) =
414 fun prod_of_chain from = ([Nonterminal (from, ~1)], "", ~1);
417 Library.foldl (op union) ([], map snd (snd (Array.sub (prods, tag)))) @
418 map prod_of_chain ((these o AList.lookup (op =) chains) tag);
419 in map (pretty_prod name) nt_prods end;
421 in maps pretty_nt taglist end;
424 (** Operations on gramars **)
426 (*The mother of all grammars*)
427 val empty_gram = Gram {nt_count = 0, prod_count = 0,
428 tags = Symtab.empty, chains = [], lambdas = [],
429 prods = Array.array (0, (([], []), []))};
432 (*Invert list of chain productions*)
433 fun inverse_chains [] result = result
434 | inverse_chains ((root, branches) :: cs) result =
435 let fun add [] result = result
436 | add (id :: ids) result =
437 let val old = (these o AList.lookup (op =) result) id;
438 in add ids (AList.update (op =) (id, root :: old) result) end;
439 in inverse_chains cs (add branches result) end;
442 (*Add productions to a grammar*)
443 fun extend_gram gram [] = gram
444 | extend_gram (Gram {nt_count, prod_count, tags, chains, lambdas, prods})
447 (*Get tag for existing nonterminal or create a new one*)
448 fun get_tag nt_count tags nt =
449 case Symtab.lookup tags nt of
450 SOME tag => (nt_count, tags, tag)
451 | NONE => (nt_count+1, Symtab.update_new (nt, nt_count) tags,
454 (*Convert symbols to the form used by the parser;
455 delimiters and predefined terms are stored as terminals,
456 nonterminals are converted to integer tags*)
457 fun symb_of [] nt_count tags result = (nt_count, tags, rev result)
458 | symb_of ((Delim s) :: ss) nt_count tags result =
459 symb_of ss nt_count tags ((Terminal (Token s)) :: result)
460 | symb_of ((Argument (s, p)) :: ss) nt_count tags result =
462 val (nt_count', tags', new_symb) =
463 case predef_term s of
465 let val (nt_count', tags', s_tag) = get_tag nt_count tags s;
466 in (nt_count', tags', Nonterminal (s_tag, p)) end
467 | SOME tk => (nt_count, tags, Terminal tk);
468 in symb_of ss nt_count' tags' (new_symb :: result) end
469 | symb_of (_ :: ss) nt_count tags result =
470 symb_of ss nt_count tags result;
472 (*Convert list of productions by invoking symb_of for each of them*)
473 fun prod_of [] nt_count prod_count tags result =
474 (nt_count, prod_count, tags, result)
475 | prod_of ((XProd (lhs, xsymbs, const, pri)) :: ps)
476 nt_count prod_count tags result =
477 let val (nt_count', tags', lhs_tag) = get_tag nt_count tags lhs;
479 val (nt_count'', tags'', prods) =
480 symb_of xsymbs nt_count' tags' [];
481 in prod_of ps nt_count'' (prod_count+1) tags''
482 ((lhs_tag, (prods, const, pri)) :: result)
485 val (nt_count', prod_count', tags', xprods') =
486 prod_of xprods nt_count prod_count tags [];
488 (*Copy array containing productions of old grammar;
489 this has to be done to preserve the old grammar while being able
490 to change the array's content*)
492 let fun get_prod i = if i < nt_count then Array.sub (prods, i)
494 in Array.tabulate (nt_count', get_prod) end;
496 val fromto_chains = inverse_chains chains [];
498 (*Add new productions to old ones*)
499 val (fromto_chains', lambdas', _) =
500 add_prods prods' fromto_chains lambdas NONE xprods';
502 val chains' = inverse_chains fromto_chains' [];
503 in Gram {nt_count = nt_count', prod_count = prod_count', tags = tags',
504 chains = chains', lambdas = lambdas', prods = prods'}
507 val make_gram = extend_gram empty_gram;
510 (*Merge two grammars*)
511 fun merge_grams gram_a gram_b =
513 (*find out which grammar is bigger*)
514 val (Gram {nt_count = nt_count1, prod_count = prod_count1, tags = tags1,
515 chains = chains1, lambdas = lambdas1, prods = prods1},
516 Gram {nt_count = nt_count2, prod_count = prod_count2, tags = tags2,
517 chains = chains2, lambdas = lambdas2, prods = prods2}) =
518 let val Gram {prod_count = count_a, ...} = gram_a;
519 val Gram {prod_count = count_b, ...} = gram_b;
520 in if count_a > count_b then (gram_a, gram_b)
521 else (gram_b, gram_a)
524 (*get existing tag from grammar1 or create a new one*)
525 fun get_tag nt_count tags nt =
526 case Symtab.lookup tags nt of
527 SOME tag => (nt_count, tags, tag)
528 | NONE => (nt_count+1, Symtab.update_new (nt, nt_count) tags,
531 val ((nt_count1', tags1'), tag_table) =
532 let val tag_list = Symtab.dest tags2;
534 val table = Array.array (nt_count2, ~1);
536 fun store_tag nt_count tags ~1 = (nt_count, tags)
537 | store_tag nt_count tags tag =
538 let val (nt_count', tags', tag') =
539 get_tag nt_count tags
540 (fst (the (find_first (fn (n, t) => t = tag) tag_list)));
541 in Array.update (table, tag, tag');
542 store_tag nt_count' tags' (tag-1)
544 in (store_tag nt_count1 tags1 (nt_count2-1), table) end;
546 (*convert grammar2 tag to grammar1 tag*)
547 fun convert_tag tag = Array.sub (tag_table, tag);
549 (*convert chain list to raw productions*)
550 fun mk_chain_prods [] result = result
551 | mk_chain_prods ((to, froms) :: cs) result =
553 val to_tag = convert_tag to;
555 fun make [] result = result
556 | make (from :: froms) result = make froms ((to_tag,
557 ([Nonterminal (convert_tag from, ~1)], "", ~1)) :: result);
558 in mk_chain_prods cs (make froms [] @ result) end;
560 val chain_prods = mk_chain_prods chains2 [];
562 (*convert prods2 array to productions*)
563 fun process_nt ~1 result = result
564 | process_nt nt result =
566 val nt_prods = Library.foldl (op union)
567 ([], map snd (snd (Array.sub (prods2, nt))));
568 val lhs_tag = convert_tag nt;
570 (*convert tags in rhs*)
571 fun process_rhs [] result = result
572 | process_rhs (Terminal tk :: rhs) result =
573 process_rhs rhs (result @ [Terminal tk])
574 | process_rhs (Nonterminal (nt, prec) :: rhs) result =
576 (result @ [Nonterminal (convert_tag nt, prec)]);
578 (*convert tags in productions*)
579 fun process_prods [] result = result
580 | process_prods ((rhs, id, prec) :: ps) result =
581 process_prods ps ((lhs_tag, (process_rhs rhs [], id, prec))
583 in process_nt (nt-1) (process_prods nt_prods [] @ result) end;
585 val raw_prods = chain_prods @ process_nt (nt_count2-1) [];
588 let fun get_prod i = if i < nt_count1 then Array.sub (prods1, i)
590 in Array.tabulate (nt_count1', get_prod) end;
592 val fromto_chains = inverse_chains chains1 [];
594 val (fromto_chains', lambdas', SOME prod_count1') =
595 add_prods prods1' fromto_chains lambdas1 (SOME prod_count1) raw_prods;
597 val chains' = inverse_chains fromto_chains' [];
598 in Gram {nt_count = nt_count1', prod_count = prod_count1',
599 tags = tags1', chains = chains', lambdas = lambdas',
607 Node of string * parsetree list |
611 nt_tag * int * (*identification and production precedence*)
612 parsetree list * (*already parsed nonterminals on rhs*)
613 symb list * (*rest of rhs*)
614 string * (*name of production*)
615 int; (*index for previous state list*)
618 (*Get all rhss with precedence >= minPrec*)
619 fun getRHS minPrec = List.filter (fn (_, _, prec:int) => prec >= minPrec);
621 (*Get all rhss with precedence >= minPrec and < maxPrec*)
622 fun getRHS' minPrec maxPrec =
623 List.filter (fn (_, _, prec:int) => prec >= minPrec andalso prec < maxPrec);
625 (*Make states using a list of rhss*)
626 fun mkStates i minPrec lhsID rhss =
627 let fun mkState (rhs, id, prodPrec) = (lhsID, prodPrec, [], rhs, id, i);
628 in map mkState rhss end;
630 (*Add parse tree to list and eliminate duplicates
631 saving the maximum precedence*)
632 fun conc (t: parsetree list, prec:int) [] = (NONE, [(t, prec)])
633 | conc (t, prec) ((t', prec') :: ts) =
635 (SOME prec', if prec' >= prec then (t', prec') :: ts
636 else (t, prec) :: ts)
638 let val (n, ts') = conc (t, prec) ts
639 in (n, (t', prec') :: ts') end;
641 (*Update entry in used*)
642 fun update_trees ((B: nt_tag, (i, ts)) :: used) (A, t) =
644 let val (n, ts') = conc t ts
645 in ((A, (i, ts')) :: used, n) end
647 let val (used', n) = update_trees used (A, t)
648 in ((B, (i, ts)) :: used', n) end;
650 (*Replace entry in used*)
651 fun update_prec (A: nt_tag, prec) used =
652 let fun update ((hd as (B, (_, ts))) :: used, used') =
654 then used' @ ((A, (prec, ts)) :: used)
655 else update (used, hd :: used')
656 in update (used, []) end;
658 fun getS A maxPrec Si =
660 (fn (_, _, _, Nonterminal (B, prec) :: _, _, _)
661 => A = B andalso prec <= maxPrec
664 fun getS' A maxPrec minPrec Si =
666 (fn (_, _, _, Nonterminal (B, prec) :: _, _, _)
667 => A = B andalso prec > minPrec andalso prec <= maxPrec
670 fun getStates Estate i ii A maxPrec =
672 (fn (_, _, _, Nonterminal (B, prec) :: _, _, _)
673 => A = B andalso prec <= maxPrec
675 (Array.sub (Estate, ii));
678 fun movedot_term (A, j, ts, Terminal a :: sa, id, i) c =
679 if valued_token c then
680 (A, j, ts @ [Tip c], sa, id, i)
681 else (A, j, ts, sa, id, i);
683 fun movedot_nonterm ts (A, j, tss, Nonterminal _ :: sa, id, i) =
684 (A, j, tss @ ts, sa, id, i);
686 fun movedot_lambda _ [] = []
687 | movedot_lambda (B, j, tss, Nonterminal (A, k) :: sa, id, i) ((t, ki) :: ts) =
689 (B, j, tss @ t, sa, id, i) ::
690 movedot_lambda (B, j, tss, Nonterminal (A, k) :: sa, id, i) ts
691 else movedot_lambda (B, j, tss, Nonterminal (A, k) :: sa, id, i) ts;
694 val warned = ref false; (*flag for warning message*)
695 val branching_level = ref 600; (*trigger value for warnings*)
697 (*get all productions of a NT and NTs chained to it which can
698 be started by specified token*)
699 fun prods_for prods chains include_none tk nts =
701 fun token_assoc (list, key) =
702 let fun assoc [] result = result
703 | assoc ((keyi, pi) :: pairs) result =
704 if is_some keyi andalso matching_tokens (the keyi, key)
705 orelse include_none andalso is_none keyi then
706 assoc pairs (pi @ result)
707 else assoc pairs result;
708 in assoc list [] end;
710 fun get_prods [] result = result
711 | get_prods (nt :: nts) result =
712 let val nt_prods = snd (Array.sub (prods, nt));
713 in get_prods nts ((token_assoc (nt_prods, tk)) @ result) end;
714 in get_prods (connected_with chains nts nts) [] end;
717 fun PROCESSS prods chains Estate i c states =
719 fun all_prods_for nt = prods_for prods chains true c [nt];
721 fun processS used [] (Si, Sii) = (Si, Sii)
722 | processS used (S :: States) (Si, Sii) =
724 (_, _, _, Nonterminal (nt, minPrec) :: _, _, _) =>
725 let (*predictor operation*)
726 val (used', new_states) =
727 (case AList.lookup (op =) used nt of
728 SOME (usedPrec, l) => (*nonterminal has been processed*)
729 if usedPrec <= minPrec then
730 (*wanted precedence has been processed*)
731 (used, movedot_lambda S l)
732 else (*wanted precedence hasn't been parsed yet*)
734 val tk_prods = all_prods_for nt;
736 val States' = mkStates i minPrec nt
737 (getRHS' minPrec usedPrec tk_prods);
738 in (update_prec (nt, minPrec) used,
739 movedot_lambda S l @ States')
742 | NONE => (*nonterminal is parsed for the first time*)
743 let val tk_prods = all_prods_for nt;
744 val States' = mkStates i minPrec nt
745 (getRHS minPrec tk_prods);
746 in ((nt, (minPrec, [])) :: used, States') end);
749 if not (!warned) andalso
750 length (new_states @ States) > (!branching_level) then
751 (warning "Currently parsed expression could be extremely ambiguous.";
755 processS used' (new_states @ States) (S :: Si, Sii)
757 | (_, _, _, Terminal a :: _, _, _) => (*scanner operation*)
760 if matching_tokens (a, c) then movedot_term S c :: Sii else Sii)
761 | (A, prec, ts, [], id, j) => (*completer operation*)
762 let val tt = if id = "" then ts else [Node (id, ts)] in
763 if j = i then (*lambda production?*)
765 val (used', O) = update_trees used (A, (tt, prec));
769 let val Slist = getS A prec Si;
770 val States' = map (movedot_nonterm tt) Slist;
771 in processS used' (States' @ States) (S :: Si, Sii) end
773 if n >= prec then processS used' States (S :: Si, Sii)
775 let val Slist = getS' A prec n Si;
776 val States' = map (movedot_nonterm tt) Slist;
777 in processS used' (States' @ States) (S :: Si, Sii) end
780 let val Slist = getStates Estate i j A prec
781 in processS used (map (movedot_nonterm tt) Slist @ States)
785 in processS [] states ([], []) end;
788 fun syntax_error toks allowed =
791 if null toks then Pretty.str "Inner syntax error: unexpected end of input"
793 Pretty.block (Pretty.str "Inner syntax error at: \"" ::
794 Pretty.breaks (map (Pretty.str o str_of_token)
795 (rev (tl (rev toks)))) @
798 Pretty.strs ("Expected tokens: " :: map (quote o str_of_token) allowed);
800 error (Pretty.string_of (Pretty.blk (0, [msg, Pretty.fbrk, expected])))
803 fun produce prods chains stateset i indata prev_token =
804 (*prev_token is used for error messages*)
805 (case Array.sub (stateset, i) of
806 [] => let fun some_prods_for tk nt = prods_for prods chains false tk [nt];
808 (*test if tk is a lookahead for a given minimum precedence*)
809 fun reduction _ minPrec _ (Terminal _ :: _, _, prec:int) =
810 if prec >= minPrec then true
812 | reduction tk minPrec checked
813 (Nonterminal (nt, nt_prec) :: _, _, prec) =
814 if prec >= minPrec andalso not (member (op =) checked nt) then
815 let val chained = connected_with chains [nt] [nt];
817 (reduction tk nt_prec (chained @ checked))
818 (some_prods_for tk nt)
822 (*compute a list of allowed starting tokens
823 for a list of nonterminals considering precedence*)
824 fun get_starts [] result = result
825 | get_starts ((nt, minPrec:int) :: nts) result =
826 let fun get [] result = result
827 | get ((SOME tk, prods) :: ps) result =
828 if not (null prods) andalso
829 exists (reduction tk minPrec [nt]) prods
830 then get ps (tk :: result)
832 | get ((NONE, _) :: ps) result = get ps result;
834 val (_, nt_prods) = Array.sub (prods, nt);
836 val chained = map (fn nt => (nt, minPrec))
837 ((these o AList.lookup (op =) chains) nt);
838 in get_starts (chained @ nts)
839 ((get nt_prods []) union result)
843 map_filter (fn (_, _, _, Nonterminal (a, prec) :: _, _, _) =>
844 SOME (a, prec) | _ => NONE)
845 (Array.sub (stateset, i-1));
847 distinct (op =) (get_starts nts [] @
848 (map_filter (fn (_, _, _, Terminal a :: _, _, _) => SOME a
850 (Array.sub (stateset, i-1))));
851 in syntax_error (if prev_token = EndToken then indata
852 else prev_token :: indata) allowed
856 [] => Array.sub (stateset, i)
858 let val (si, sii) = PROCESSS prods chains stateset i c s;
859 in Array.update (stateset, i, si);
860 Array.update (stateset, i + 1, sii);
861 produce prods chains stateset (i + 1) cs c
865 fun get_trees l = map_filter (fn (_, _, [pt], _, _, _) => SOME pt | _ => NONE)
868 fun earley prods tags chains startsymbol indata =
870 val start_tag = case Symtab.lookup tags startsymbol of
872 | NONE => error ("parse: Unknown startsymbol " ^
874 val S0 = [(~1, 0, [], [Nonterminal (start_tag, 0), Terminal EndToken],
876 val s = length indata + 1;
877 val Estate = Array.array (s, []);
879 Array.update (Estate, 0, S0);
881 get_trees (produce prods chains Estate 0 indata EndToken)
885 fun parse (Gram {tags, prods, chains, ...}) start toks =
887 (case earley prods tags chains start toks of
888 [] => sys_error "parse: no parse trees"