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