src/Pure/Syntax/parser.ML
author clasohm
Thu May 19 13:13:27 1994 +0200 (1994-05-19 ago)
changeset 377 ab8917806779
parent 373 68400ea32f7b
child 395 712dceb1ecc7
permissions -rw-r--r--
lookaheads are now computed faster (during the grammar is built)
wenzelm@18
     1
(*  Title:      Pure/Syntax/parser.ML
wenzelm@46
     2
    ID:         $Id$
clasohm@345
     3
    Author:     Sonia Mahjoub, Markus Wenzel and Carsten Clasohm, TU Muenchen
wenzelm@18
     4
wenzelm@18
     5
Isabelle's main parser (used for terms and typs).
wenzelm@18
     6
wenzelm@18
     7
TODO:
wenzelm@237
     8
  extend_gram: remove 'roots' arg
wenzelm@18
     9
*)
wenzelm@18
    10
wenzelm@18
    11
signature PARSER =
wenzelm@18
    12
sig
wenzelm@237
    13
  structure Lexicon: LEXICON
wenzelm@237
    14
  structure SynExt: SYN_EXT
wenzelm@237
    15
  local open Lexicon SynExt SynExt.Ast in
wenzelm@18
    16
    type gram
wenzelm@18
    17
    val empty_gram: gram
wenzelm@237
    18
    val extend_gram: gram -> string list -> xprod list -> gram
wenzelm@237
    19
    val merge_grams: gram -> gram -> gram
wenzelm@237
    20
    val pretty_gram: gram -> Pretty.T list
wenzelm@237
    21
    datatype parsetree =
wenzelm@237
    22
      Node of string * parsetree list |
wenzelm@237
    23
      Tip of token
clasohm@330
    24
    val parse: gram -> string -> token list -> parsetree list
wenzelm@18
    25
  end
wenzelm@18
    26
end;
wenzelm@18
    27
wenzelm@237
    28
functor ParserFun(structure Symtab: SYMTAB and Lexicon: LEXICON
clasohm@330
    29
  and SynExt: SYN_EXT) =
wenzelm@18
    30
struct
wenzelm@18
    31
wenzelm@237
    32
structure Pretty = SynExt.Ast.Pretty;
wenzelm@237
    33
structure Lexicon = Lexicon;
wenzelm@237
    34
structure SynExt = SynExt;
wenzelm@237
    35
open Lexicon SynExt;
wenzelm@18
    36
wenzelm@18
    37
wenzelm@18
    38
(** datatype gram **)
wenzelm@18
    39
wenzelm@237
    40
datatype symb =
wenzelm@237
    41
  Terminal of token |
wenzelm@237
    42
  Nonterminal of string * int;
wenzelm@18
    43
clasohm@330
    44
datatype refsymb = Term of token | Nonterm of rhss_ref * int
clasohm@330
    45
                                (*reference to production list instead of name*)
clasohm@330
    46
and gram = Gram of (string * (symb list * string * int)) list *
clasohm@330
    47
                   (string * rhss_ref) list
clasohm@330
    48
withtype rhss_ref = (token option * (refsymb list * string * int) list) list ref
clasohm@330
    49
                                      (*lookahead table: token and productions*)
clasohm@330
    50
clasohm@330
    51
(* convert productions to reference grammar with lookaheads and eliminate
clasohm@330
    52
   chain productions *)
clasohm@373
    53
fun mk_gram prods =
clasohm@373
    54
  let val _ = writeln "Building new grammar...";
clasohm@373
    55
clasohm@373
    56
      (*get reference on list of all possible rhss for nonterminal lhs
clasohm@330
    57
        (if it doesn't exist a new one is created and added to the nonterminal
clasohm@330
    58
         list)*)
clasohm@330
    59
      fun get_rhss ref_prods lhs =
clasohm@330
    60
        case assoc (ref_prods, lhs) of
clasohm@330
    61
            None =>
clasohm@330
    62
              let val l = ref [(None, [])]
clasohm@330
    63
              in (l, (lhs, l) :: ref_prods) end
clasohm@330
    64
          | Some l => (l, ref_prods);
clasohm@330
    65
clasohm@330
    66
      (*convert symb list to refsymb list*)
clasohm@330
    67
      fun mk_refsymbs ref_prods [] rs = (rs, ref_prods)
clasohm@330
    68
        | mk_refsymbs ref_prods (Terminal tk :: symbs) rs =
clasohm@330
    69
            mk_refsymbs ref_prods symbs (rs @ [Term tk])
clasohm@330
    70
        | mk_refsymbs ref_prods (Nonterminal (name, prec) :: symbs) rs =
clasohm@330
    71
            let val (rhss, ref_prods') = get_rhss ref_prods name
clasohm@330
    72
            in mk_refsymbs ref_prods' symbs (rs @ [Nonterm (rhss, prec)])
clasohm@330
    73
            end;
clasohm@330
    74
clasohm@330
    75
      (*convert prod list to (string * rhss_ref) list
clasohm@330
    76
        without computing lookaheads*)
clasohm@330
    77
      fun mk_ref_gram [] ref_prods = ref_prods
clasohm@330
    78
        | mk_ref_gram ((lhs, (rhs, name, prec)) :: ps) ref_prods =
clasohm@330
    79
            let val (rhs', ref_prods') = get_rhss ref_prods lhs;
clasohm@330
    80
                val (dummy, rhss) = hd (!rhs');
clasohm@330
    81
                val (ref_symbs, ref_prods'') = mk_refsymbs ref_prods' rhs [];
clasohm@330
    82
            in rhs' := [(dummy, (ref_symbs, name, prec) :: rhss)];
clasohm@330
    83
               mk_ref_gram ps ref_prods''
clasohm@330
    84
            end;
clasohm@330
    85
clasohm@330
    86
      (*eliminate chain productions*)
clasohm@330
    87
      fun elim_chain ref_gram =
clasohm@330
    88
        let (*make a list of pairs representing chain productions and delete
clasohm@330
    89
              these productions*)
clasohm@330
    90
            fun list_chain [] = []
clasohm@330
    91
              | list_chain ((_, rhss_ref) :: ps) =
clasohm@330
    92
                  let fun lists [] new_rhss chains = (new_rhss, chains)
clasohm@330
    93
                        | lists (([Nonterm (id2, ~1)], _, ~1) :: rs) 
clasohm@330
    94
                                new_rhss chains =
clasohm@330
    95
                            lists rs new_rhss ((rhss_ref, id2) :: chains)
clasohm@330
    96
                        | lists (rhs :: rs) new_rhss chains = 
clasohm@330
    97
                            lists rs (rhs :: new_rhss) chains;
clasohm@330
    98
clasohm@330
    99
                      val (dummy, rhss) = hd (!rhss_ref);
clasohm@330
   100
clasohm@330
   101
                      val (new_rhss, chains) = lists rhss [] [];
clasohm@330
   102
                  in rhss_ref := [(dummy, new_rhss)];
clasohm@330
   103
                     chains @ (list_chain ps)
clasohm@330
   104
                  end;
clasohm@330
   105
clasohm@345
   106
            (*convert a list of pairs to an association list
clasohm@345
   107
              by using the first element as the key*)
clasohm@345
   108
            fun mk_assoc pairs =
clasohm@330
   109
              let fun doit [] result = result
clasohm@330
   110
                    | doit ((id1, id2) :: ps) result =
clasohm@330
   111
                        doit ps 
clasohm@330
   112
                        (overwrite (result, (id1, id2 :: (assocs result id1))));
clasohm@345
   113
              in doit pairs [] end;
clasohm@330
   114
clasohm@330
   115
            (*replace reference by list of rhss in chain pairs*)
clasohm@345
   116
            fun deref (id1, ids) =
clasohm@345
   117
              let fun deref1 [] = []
clasohm@345
   118
                    | deref1 (id :: ids) =
clasohm@330
   119
                        let val (_, rhss) = hd (!id);
clasohm@345
   120
                        in rhss @ (deref1 ids) end;
clasohm@345
   121
              in (id1, deref1 ids) end;
clasohm@330
   122
clasohm@330
   123
            val chain_pairs = 
clasohm@345
   124
               map deref (transitive_closure (mk_assoc (list_chain ref_gram)));
clasohm@330
   125
clasohm@330
   126
            (*add new rhss to productions*)
clasohm@345
   127
            fun elim (rhss_ref, rhss) =
clasohm@330
   128
              let val (dummy, old_rhss) = hd (!rhss_ref);
clasohm@330
   129
              in rhss_ref := [(dummy, old_rhss @ rhss)] end;
clasohm@345
   130
        in map elim chain_pairs;
clasohm@330
   131
           ref_gram
clasohm@330
   132
        end;
clasohm@330
   133
clasohm@330
   134
      val ref_gram = elim_chain (mk_ref_gram prods []);
wenzelm@18
   135
clasohm@330
   136
      (*make a list of all lambda NTs 
clasohm@330
   137
        (i.e. nonterminals that can produce lambda*)
clasohm@330
   138
      val lambdas =
clasohm@330
   139
        let fun lambda [] result = result
clasohm@330
   140
              | lambda ((_, rhss_ref) :: nts) result =
clasohm@330
   141
                  if rhss_ref mem result then
clasohm@330
   142
                    lambda nts result
clasohm@330
   143
                  else
clasohm@345
   144
                    let (*list all NTs that can be produced by a rhs
clasohm@345
   145
                          containing only lambda NTs*)
clasohm@345
   146
                        fun only_lambdas [] result = result
clasohm@345
   147
                          | only_lambdas ((_, rhss_ref) :: ps) result =
clasohm@330
   148
                              let fun only (symbs, _, _) =
clasohm@330
   149
                                   forall (fn (Nonterm (id, _)) => id mem result
clasohm@330
   150
                                            | (Term _)          => false) symbs;
clasohm@330
   151
                          
clasohm@330
   152
                                  val (_, rhss) = hd (!rhss_ref);
clasohm@330
   153
                              in if not (rhss_ref mem result) andalso
clasohm@330
   154
                                    exists only rhss then
clasohm@345
   155
                                   only_lambdas ref_gram (rhss_ref :: result)
clasohm@330
   156
                                 else
clasohm@345
   157
                                   only_lambdas ps result
clasohm@330
   158
                              end;
clasohm@330
   159
clasohm@330
   160
                        val (_, rhss) = hd (!rhss_ref);
clasohm@330
   161
                    in if exists (fn (symbs, _, _) => null symbs) rhss
clasohm@330
   162
                       then lambda nts
clasohm@345
   163
                              (only_lambdas ref_gram (rhss_ref :: result))
clasohm@330
   164
                       else lambda nts result
clasohm@330
   165
                    end;
clasohm@330
   166
         in lambda ref_gram [] end;
clasohm@330
   167
clasohm@330
   168
      (*list all nonterminals on which the lookahead depends (due to lambda 
clasohm@330
   169
        NTs this can be more than one)
clasohm@330
   170
        and report if there is a terminal at the 'start'*)
clasohm@330
   171
      fun rhss_start [] skipped = (None, skipped)
clasohm@330
   172
        | rhss_start (Term tk :: _) skipped = (Some tk, skipped)
clasohm@330
   173
        | rhss_start (Nonterm (rhss_ref, _) :: rest) skipped =
clasohm@330
   174
            if rhss_ref mem lambdas then 
clasohm@330
   175
              rhss_start rest (rhss_ref ins skipped)
clasohm@330
   176
            else
clasohm@330
   177
              (None, rhss_ref ins skipped);
clasohm@330
   178
clasohm@330
   179
      (*list all terminals that can start the given rhss*)
clasohm@330
   180
      fun look_rhss starts rhss_ref =
clasohm@377
   181
        let fun look [] _ result = result
clasohm@377
   182
              | look ((symbs, _, _) :: todos) done result =
clasohm@330
   183
                  let val (start_token, skipped) = rhss_start symbs [];
clasohm@330
   184
clasohm@330
   185
                      (*process all nonterminals on which the lookahead
clasohm@330
   186
                        depends and build the new todo and done lists for
clasohm@330
   187
                        the look function*)
clasohm@377
   188
                      fun look2 [] todos result = 
clasohm@377
   189
                            look todos (done union skipped) result
clasohm@377
   190
                        | look2 (rhss_ref :: ls) todos result =
clasohm@377
   191
                            if rhss_ref mem done then look2 ls todos result
clasohm@330
   192
                            else case assoc (starts, rhss_ref) of
clasohm@377
   193
                                Some tks => look2 ls todos (tks union result)
clasohm@377
   194
                              | None => 
clasohm@377
   195
                                  let val (_, rhss) = hd (!rhss_ref);
clasohm@377
   196
                                  in look2 ls (rhss @ todos) result end;
clasohm@330
   197
                  in case start_token of
clasohm@377
   198
                         Some tk => look2 skipped todos (start_token ins result)
clasohm@377
   199
                       | None => look2 skipped todos result
clasohm@330
   200
                  end;
clasohm@330
   201
 
clasohm@330
   202
            val (_, rhss) = hd (!rhss_ref);
clasohm@377
   203
        in look rhss [rhss_ref] [] end;                       
clasohm@330
   204
clasohm@330
   205
      (*make a table that contains all possible starting terminals
clasohm@330
   206
        for each nonterminal*)
clasohm@330
   207
      fun mk_starts [] starts = starts
clasohm@330
   208
        | mk_starts ((_, rhss_ref) :: ps) starts =
clasohm@330
   209
            mk_starts ps ((rhss_ref, look_rhss starts rhss_ref) :: starts);
clasohm@330
   210
clasohm@330
   211
      val starts = mk_starts ref_gram [];
clasohm@330
   212
clasohm@330
   213
      (*add list of allowed starting tokens to productions*)
clasohm@330
   214
      fun mk_lookahead (_, rhss_ref) =
clasohm@377
   215
        let (*compares two values of type token option 
clasohm@377
   216
              (used for speed reasons)*)
clasohm@377
   217
            fun matching_opt_tks (Some tk1, Some tk2) =
clasohm@377
   218
                  matching_tokens (tk1, tk2)
clasohm@377
   219
              | matching_opt_tks _ = false;
clasohm@377
   220
clasohm@377
   221
            (*add item to lookahead list (a list containing pairs of token and 
clasohm@377
   222
              rhss that can be started with it)*)
clasohm@345
   223
            fun add_start new_rhs tokens table =
clasohm@345
   224
                  let fun add [] [] = []
clasohm@345
   225
                        | add (tk :: tks) [] =
clasohm@345
   226
                            (tk, [new_rhs]) :: (add tks [])
clasohm@345
   227
                        | add tokens ((tk, rhss) :: ss) =
clasohm@377
   228
                            if gen_mem matching_opt_tks (tk, tokens) then 
clasohm@345
   229
                              (tk, new_rhs :: rhss) :: (add (tokens \ tk) ss)
clasohm@330
   230
                            else
clasohm@345
   231
                              (tk, rhss) :: (add tokens ss);
clasohm@345
   232
                  in add tokens table end;
clasohm@330
   233
clasohm@330
   234
            (*combine all lookaheads of a list of nonterminals*)
clasohm@345
   235
            fun combine_starts rhss_refs =
clasohm@377
   236
              foldr (gen_union matching_opt_tks)
clasohm@345
   237
              ((map (fn rhss_ref => let val Some tks = assoc (starts, rhss_ref)
clasohm@345
   238
                                    in tks end) rhss_refs), []);
clasohm@330
   239
clasohm@330
   240
            (*get lookahead for a rhs and update lhs' lookahead list*)
clasohm@330
   241
            fun look_rhss [] table = table
clasohm@330
   242
              | look_rhss ((rhs as (symbs, id, prec)) :: rs) table =
clasohm@330
   243
                  let val (start_token, skipped) = rhss_start symbs [];
clasohm@330
   244
                      val starts = case start_token of
clasohm@377
   245
                                     Some tk => gen_ins matching_opt_tks 
clasohm@377
   246
                                             (Some tk, combine_starts skipped)
clasohm@345
   247
                                   | None => if skipped subset lambdas then
clasohm@330
   248
                                               [None]
clasohm@330
   249
                                             else
clasohm@330
   250
                                               combine_starts skipped;
clasohm@330
   251
                  in look_rhss rs (add_start rhs starts table) end;
clasohm@330
   252
clasohm@330
   253
             val (_, rhss) = hd (!rhss_ref);
clasohm@330
   254
        in rhss_ref := look_rhss rhss [] end;
clasohm@330
   255
clasohm@330
   256
  in map mk_lookahead ref_gram;
clasohm@330
   257
     Gram (prods, ref_gram)
clasohm@330
   258
  end;
wenzelm@18
   259
wenzelm@18
   260
wenzelm@237
   261
(* empty, extend, merge grams *)
wenzelm@18
   262
wenzelm@237
   263
val empty_gram = mk_gram [];
wenzelm@18
   264
wenzelm@237
   265
fun extend_gram (gram1 as Gram (prods1, _)) _ xprods2 =
wenzelm@18
   266
  let
wenzelm@237
   267
    fun symb_of (Delim s) = Some (Terminal (Token s))
wenzelm@237
   268
      | symb_of (Argument (s, p)) =
wenzelm@18
   269
          (case predef_term s of
wenzelm@237
   270
            None => Some (Nonterminal (s, p))
wenzelm@237
   271
          | Some tk => Some (Terminal tk))
wenzelm@18
   272
      | symb_of _ = None;
wenzelm@18
   273
wenzelm@237
   274
    fun prod_of (XProd (lhs, xsymbs, const, pri)) =
wenzelm@237
   275
      (lhs, (mapfilter symb_of xsymbs, const, pri));
wenzelm@18
   276
wenzelm@237
   277
    val prods2 = distinct (map prod_of xprods2);
wenzelm@18
   278
  in
wenzelm@237
   279
    if prods2 subset prods1 then gram1
wenzelm@237
   280
    else mk_gram (extend_list prods1 prods2)
wenzelm@18
   281
  end;
wenzelm@18
   282
wenzelm@237
   283
fun merge_grams (gram1 as Gram (prods1, _)) (gram2 as Gram (prods2, _)) =
wenzelm@237
   284
  if prods2 subset prods1 then gram1
wenzelm@237
   285
  else if prods1 subset prods2 then gram2
wenzelm@237
   286
  else mk_gram (merge_lists prods1 prods2);
wenzelm@237
   287
wenzelm@18
   288
wenzelm@237
   289
(* pretty_gram *)
wenzelm@18
   290
wenzelm@237
   291
fun pretty_gram (Gram (prods, _)) =
wenzelm@237
   292
  let
wenzelm@237
   293
    fun pretty_name name = [Pretty.str (name ^ " =")];
wenzelm@18
   294
wenzelm@237
   295
    fun pretty_symb (Terminal (Token s)) = Pretty.str (quote s)
wenzelm@237
   296
      | pretty_symb (Terminal tok) = Pretty.str (str_of_token tok)
wenzelm@237
   297
      | pretty_symb (Nonterminal (s, p)) =
wenzelm@237
   298
          Pretty.str (s ^ "[" ^ string_of_int p ^ "]");
wenzelm@18
   299
wenzelm@237
   300
    fun pretty_const "" = []
wenzelm@237
   301
      | pretty_const c = [Pretty.str ("=> " ^ quote c)];
wenzelm@237
   302
wenzelm@237
   303
    fun pretty_pri p = [Pretty.str ("(" ^ string_of_int p ^ ")")];
wenzelm@237
   304
wenzelm@237
   305
    fun pretty_prod (name, (symbs, const, pri)) =
wenzelm@237
   306
      Pretty.block (Pretty.breaks (pretty_name name @
wenzelm@237
   307
        map pretty_symb symbs @ pretty_const const @ pretty_pri pri));
wenzelm@18
   308
  in
wenzelm@237
   309
    map pretty_prod prods
wenzelm@18
   310
  end;
wenzelm@18
   311
wenzelm@18
   312
wenzelm@18
   313
wenzelm@18
   314
(** parse **)
wenzelm@18
   315
wenzelm@237
   316
datatype parsetree =
wenzelm@237
   317
  Node of string * parsetree list |
wenzelm@237
   318
  Tip of token;
wenzelm@237
   319
wenzelm@18
   320
type state =
clasohm@330
   321
  rhss_ref * int      (*lhs: identification and production precedence*)
clasohm@330
   322
  * parsetree list    (*already parsed nonterminals on rhs*)
clasohm@330
   323
  * refsymb list      (*rest of rhs*)
clasohm@330
   324
  * string            (*name of production*)
clasohm@330
   325
  * int;              (*index for previous state list*)
wenzelm@18
   326
wenzelm@18
   327
type earleystate = state list Array.array;
wenzelm@18
   328
wenzelm@18
   329
clasohm@330
   330
(*Get all rhss with precedence >= minPrec*)
clasohm@330
   331
fun getRHS minPrec = filter (fn (_, _, prec:int) => prec >= minPrec);
wenzelm@237
   332
clasohm@330
   333
(*Get all rhss with precedence >= minPrec and < maxPrec*)
clasohm@330
   334
fun getRHS' minPrec maxPrec =
clasohm@330
   335
  filter (fn (_, _, prec:int) => prec >= minPrec andalso prec < maxPrec);
wenzelm@18
   336
clasohm@330
   337
(*Make states using a list of rhss*)
clasohm@330
   338
fun mkStates i minPrec lhsID rhss =
clasohm@330
   339
  let fun mkState (rhs, id, prodPrec) = (lhsID, prodPrec, [], rhs, id, i);
clasohm@330
   340
  in map mkState rhss end;
clasohm@330
   341
	
clasohm@330
   342
(*Add parse tree to list and eliminate duplicates 
clasohm@330
   343
  saving the maximum precedence*)
clasohm@330
   344
fun conc (t, prec:int) [] = (None, [(t, prec)])
clasohm@330
   345
  | conc (t, prec) ((t', prec') :: ts) =
clasohm@330
   346
      if t = t' then
clasohm@330
   347
        (Some prec', if prec' >= prec then (t', prec') :: ts 
clasohm@330
   348
                     else (t, prec) :: ts)
clasohm@330
   349
      else
clasohm@330
   350
        let val (n, ts') = conc (t, prec) ts
clasohm@330
   351
        in (n, (t', prec') :: ts') end;
wenzelm@18
   352
clasohm@330
   353
(*Update entry in used*)
wenzelm@237
   354
fun update_tree ((B, (i, ts)) :: used) (A, t) =
wenzelm@237
   355
  if A = B then
wenzelm@237
   356
    let val (n, ts') = conc t ts
wenzelm@237
   357
    in ((A, (i, ts')) :: used, n) end
wenzelm@237
   358
  else
wenzelm@237
   359
    let val (used', n) = update_tree used (A, t)
wenzelm@237
   360
    in ((B, (i, ts)) :: used', n) end;
wenzelm@18
   361
clasohm@330
   362
(*Replace entry in used*)
clasohm@330
   363
fun update_index (A, prec) used =
clasohm@330
   364
  let fun update((hd as (B, (_, ts))) :: used, used') =
clasohm@330
   365
        if A = B
clasohm@330
   366
        then used' @ ((A, (prec, ts)) :: used)
clasohm@330
   367
        else update (used, hd :: used')
clasohm@330
   368
  in update (used, []) end;
wenzelm@18
   369
clasohm@330
   370
fun getS A maxPrec Si =
wenzelm@237
   371
  filter
clasohm@330
   372
    (fn (_, _, _, Nonterm (B, prec) :: _, _, _)
clasohm@330
   373
          => A = B andalso prec <= maxPrec
wenzelm@237
   374
      | _ => false) Si;
wenzelm@18
   375
clasohm@330
   376
fun getS' A maxPrec minPrec Si =
wenzelm@237
   377
  filter
clasohm@330
   378
    (fn (_, _, _, Nonterm (B, prec) :: _, _, _)
clasohm@330
   379
          => A = B andalso prec > minPrec andalso prec <= maxPrec
wenzelm@237
   380
      | _ => false) Si;
wenzelm@18
   381
clasohm@330
   382
fun getStates Estate i ii A maxPrec =
wenzelm@237
   383
  filter
clasohm@330
   384
    (fn (_, _, _, Nonterm (B, prec) :: _, _, _)
clasohm@330
   385
          => A = B andalso prec <= maxPrec
wenzelm@237
   386
      | _ => false)
wenzelm@237
   387
    (Array.sub (Estate, ii));
wenzelm@18
   388
wenzelm@18
   389
clasohm@330
   390
fun movedot_term (A, j, ts, Term a :: sa, id, i) c =
wenzelm@237
   391
  if valued_token c then
wenzelm@237
   392
    (A, j, (ts @ [Tip c]), sa, id, i)
wenzelm@237
   393
  else (A, j, ts, sa, id, i);
wenzelm@18
   394
clasohm@330
   395
fun movedot_nonterm ts (A, j, tss, Nonterm _ :: sa, id, i) =
wenzelm@237
   396
  (A, j, tss @ ts, sa, id, i);
wenzelm@18
   397
wenzelm@237
   398
fun movedot_lambda _ [] = []
clasohm@330
   399
  | movedot_lambda (B, j, tss, Nonterm (A, k) :: sa, id, i) ((t, ki) :: ts) =
wenzelm@237
   400
      if k <= ki then
wenzelm@237
   401
        (B, j, tss @ t, sa, id, i) ::
clasohm@330
   402
          movedot_lambda (B, j, tss, Nonterm (A, k) :: sa, id, i) ts
clasohm@330
   403
      else movedot_lambda (B, j, tss, Nonterm (A, k) :: sa, id, i) ts;
wenzelm@18
   404
wenzelm@18
   405
wenzelm@18
   406
clasohm@330
   407
fun PROCESSS Estate i c states =
wenzelm@18
   408
let
clasohm@330
   409
fun get_lookahead rhss_ref = token_assoc (!rhss_ref, c);
clasohm@330
   410
wenzelm@237
   411
fun processS used [] (Si, Sii) = (Si, Sii)
wenzelm@237
   412
  | processS used (S :: States) (Si, Sii) =
wenzelm@237
   413
      (case S of
clasohm@330
   414
        (_, _, _, Nonterm (rhss_ref, minPrec) :: _, _, _) =>
clasohm@330
   415
          let                                       (*predictor operation*)
clasohm@330
   416
            val (used_new, States_new) =
clasohm@330
   417
              (case assoc (used, rhss_ref) of
clasohm@330
   418
                Some (usedPrec, l) =>       (*nonterminal has been processed*)
clasohm@330
   419
                  if usedPrec <= minPrec then
clasohm@330
   420
                                      (*wanted precedence has been processed*)
clasohm@330
   421
                    (used, movedot_lambda S l)
clasohm@330
   422
                  else            (*wanted precedence hasn't been parsed yet*)
clasohm@330
   423
                    let val rhss = get_lookahead rhss_ref;
clasohm@330
   424
                      val States' = mkStates i minPrec rhss_ref
clasohm@330
   425
                                      (getRHS' minPrec usedPrec rhss);
clasohm@330
   426
                    in (update_index (rhss_ref, minPrec) used, 
clasohm@330
   427
                        movedot_lambda S l @ States')
wenzelm@237
   428
                    end
wenzelm@18
   429
clasohm@330
   430
              | None =>           (*nonterminal is parsed for the first time*)
clasohm@330
   431
                  let val rhss = get_lookahead rhss_ref;
clasohm@330
   432
                      val States' = mkStates i minPrec rhss_ref
clasohm@330
   433
                                      (getRHS minPrec rhss);
clasohm@330
   434
                  in ((rhss_ref, (minPrec, [])) :: used, States') end)
wenzelm@18
   435
          in
clasohm@330
   436
            processS used_new (States_new @ States) (S :: Si, Sii)
wenzelm@18
   437
          end
clasohm@330
   438
      | (_, _, _, Term a :: _, _, _) =>               (*scanner operation*)
wenzelm@237
   439
          processS used States
wenzelm@237
   440
            (S :: Si,
wenzelm@237
   441
              if matching_tokens (a, c) then movedot_term S c :: Sii else Sii)
wenzelm@18
   442
clasohm@330
   443
      | (A, prec, ts, [], id, j) =>                   (*completer operation*)
wenzelm@237
   444
          let
wenzelm@237
   445
            val tt = if id = "" then ts else [Node (id, ts)]
wenzelm@18
   446
          in
clasohm@330
   447
            if j = i then                             (*lambda production?*)
wenzelm@237
   448
              let
clasohm@330
   449
                val (used', O) = update_tree used (A, (tt, prec));
wenzelm@237
   450
              in
wenzelm@237
   451
                (case O of
wenzelm@237
   452
                  None =>
wenzelm@237
   453
                    let
clasohm@330
   454
                      val Slist = getS A prec Si;
wenzelm@237
   455
                      val States' = map (movedot_nonterm tt) Slist;
wenzelm@237
   456
                    in
clasohm@330
   457
                      processS used' (States' @ States) (S :: Si, Sii)
wenzelm@237
   458
                    end
wenzelm@237
   459
                | Some n =>
clasohm@330
   460
                    if n >= prec then
wenzelm@237
   461
                      processS used' States (S :: Si, Sii)
wenzelm@237
   462
                    else
wenzelm@237
   463
                      let
clasohm@330
   464
                        val Slist = getS' A prec n Si;
wenzelm@237
   465
                        val States' = map (movedot_nonterm tt) Slist;
wenzelm@237
   466
                      in
clasohm@330
   467
                        processS used' (States' @ States) (S :: Si, Sii)
wenzelm@237
   468
                      end)
clasohm@330
   469
              end 
wenzelm@237
   470
            else
wenzelm@237
   471
              processS used
clasohm@330
   472
                (map (movedot_nonterm tt) (getStates Estate i j A prec) @ States)
wenzelm@237
   473
                (S :: Si, Sii)
wenzelm@237
   474
          end)
wenzelm@18
   475
in
wenzelm@237
   476
  processS [] states ([], [])
wenzelm@18
   477
end;
wenzelm@18
   478
wenzelm@18
   479
wenzelm@18
   480
clasohm@362
   481
fun syntax_error toks allowed =
clasohm@362
   482
  error 
clasohm@362
   483
  ((if toks = [] then
clasohm@362
   484
      "error: unexpected end of input\n"
clasohm@362
   485
    else
clasohm@367
   486
      "Syntax error at: " ^ quote (space_implode " " (map str_of_token 
clasohm@367
   487
        ((rev o tl o rev) toks)))
clasohm@362
   488
      ^ "\n")
clasohm@362
   489
   ^ "Expected tokens: " 
clasohm@362
   490
   ^ space_implode ", " (map (quote o str_of_token) allowed));
wenzelm@18
   491
clasohm@362
   492
fun produce stateset i indata prev_token =
clasohm@362
   493
                     (*the argument prev_token is only used for error messages*)
wenzelm@237
   494
  (case Array.sub (stateset, i) of
clasohm@373
   495
    [] => let (*similar to token_assoc but does not automatically 
clasohm@373
   496
                include 'None' key*)
clasohm@373
   497
              fun token_assoc2 (list, key) =
clasohm@373
   498
                let fun assoc [] = []
clasohm@373
   499
                      | assoc ((keyi, xi) :: pairs) =
clasohm@373
   500
                          if is_some keyi andalso
clasohm@373
   501
                             matching_tokens (the keyi, key) then 
clasohm@373
   502
                            (assoc pairs) @ xi
clasohm@373
   503
                          else assoc pairs;
clasohm@373
   504
                          in assoc list end;
clasohm@373
   505
clasohm@373
   506
              (*test if tk is a lookahead for a given minimum precedence*)
clasohm@373
   507
              fun reduction minPrec tk _ (Term _ :: _, _, prec:int) =
clasohm@373
   508
                    if prec >= minPrec then true
clasohm@373
   509
                    else false
clasohm@373
   510
                | reduction minPrec tk checked 
clasohm@373
   511
                            (Nonterm (rhss_ref, NTprec)::_,_, prec) =
clasohm@373
   512
                    if prec >= minPrec andalso not (rhss_ref mem checked) then
clasohm@373
   513
                      exists (reduction NTprec tk (rhss_ref :: checked)) 
clasohm@373
   514
                             (token_assoc2 (!rhss_ref, tk))
clasohm@373
   515
                    else false;
clasohm@373
   516
clasohm@373
   517
              (*compute a list of allowed starting tokens 
clasohm@373
   518
                for a list of nonterminals considering precedence*)
clasohm@362
   519
              fun get_starts [] = []
clasohm@372
   520
                | get_starts ((rhss_ref, minPrec:int) :: refs) =
clasohm@362
   521
                    let fun get [] = []
clasohm@373
   522
                          | get ((Some tk, prods) :: rhss) =
clasohm@373
   523
                              if exists (reduction minPrec tk [rhss_ref]) prods
clasohm@373
   524
                              then tk :: (get rhss)
clasohm@372
   525
                              else get rhss
clasohm@362
   526
                          | get ((None, _) :: rhss) =
clasohm@362
   527
                              get rhss;
clasohm@362
   528
                    in (get (!rhss_ref)) union (get_starts refs) end;
clasohm@362
   529
clasohm@372
   530
              val NTs = map (fn (_, _, _, Nonterm (a, prec) :: _, _, _) => 
clasohm@372
   531
                              (a, prec))
clasohm@362
   532
                            (filter (fn (_, _, _, Nonterm _ :: _, _, _) => true
clasohm@362
   533
                                     | _ => false) (Array.sub (stateset, i-1)));
clasohm@367
   534
              val allowed = distinct (get_starts NTs @
clasohm@362
   535
                            (map (fn (_, _, _, Term a :: _, _, _) => a)
clasohm@362
   536
                            (filter (fn (_, _, _, Term _ :: _, _, _) => true
clasohm@367
   537
                                   | _ => false) (Array.sub (stateset, i-1)))));
clasohm@362
   538
          in syntax_error (if prev_token = EndToken then indata
clasohm@362
   539
                           else prev_token :: indata) allowed
clasohm@362
   540
          end
wenzelm@237
   541
  | s =>
wenzelm@237
   542
    (case indata of
wenzelm@237
   543
      [] => Array.sub (stateset, i)
wenzelm@237
   544
    | c :: cs =>
wenzelm@237
   545
      let
clasohm@330
   546
        val (si, sii) = PROCESSS stateset i c s;
wenzelm@237
   547
      in
wenzelm@237
   548
        Array.update (stateset, i, si);
wenzelm@237
   549
        Array.update (stateset, i + 1, sii);
clasohm@362
   550
        produce stateset (i + 1) cs c
wenzelm@237
   551
      end));
wenzelm@18
   552
wenzelm@18
   553
wenzelm@237
   554
val get_trees = mapfilter (fn (_, _, [pt], _, _, _) => Some pt | _ => None);
wenzelm@237
   555
wenzelm@18
   556
wenzelm@18
   557
fun earley grammar startsymbol indata =
wenzelm@237
   558
  let
clasohm@330
   559
    val rhss_ref = case assoc (grammar, startsymbol) of
clasohm@330
   560
                       Some r => r
clasohm@330
   561
                     | None => error ("parse: Unknown startsymbol " ^ 
clasohm@330
   562
                                      quote startsymbol);
clasohm@330
   563
    val S0 = [(ref [], 0, [], [Nonterm (rhss_ref, 0), Term EndToken], "", 0)];
clasohm@330
   564
    val s = length indata + 1;
wenzelm@237
   565
    val Estate = Array.array (s, []);
wenzelm@237
   566
  in
wenzelm@237
   567
    Array.update (Estate, 0, S0);
wenzelm@237
   568
    let
clasohm@362
   569
      val l = produce Estate 0 indata EndToken(*dummy*);
wenzelm@237
   570
      val p_trees = get_trees l;
wenzelm@237
   571
    in p_trees end
wenzelm@237
   572
  end;
wenzelm@18
   573
wenzelm@18
   574
wenzelm@237
   575
fun parse (Gram (_, prod_tab)) start toks =
wenzelm@237
   576
  (case earley prod_tab start toks of
wenzelm@237
   577
    [] => sys_error "parse: no parse trees"
clasohm@330
   578
  | pts => pts);
wenzelm@18
   579
wenzelm@18
   580
end;
wenzelm@18
   581