src/Pure/Syntax/parser.ML
author clasohm
Tue May 17 14:42:34 1994 +0200 (1994-05-17 ago)
changeset 373 68400ea32f7b
parent 372 40d565e51dea
child 377 ab8917806779
permissions -rw-r--r--
fixed a bug in syntax_error, added "Building new grammar" message;
automatically generated nonterminals now start with "@"
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@330
   181
        let fun look [] _ = []
clasohm@330
   182
              | look ((symbs, _, _) :: todos) done =
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@330
   188
                      fun look2 [] todos = look todos (done union skipped)
clasohm@330
   189
                        | look2 (rhss_ref :: ls) todos =
clasohm@330
   190
                            if rhss_ref mem done then look2 ls todos
clasohm@330
   191
                            else case assoc (starts, rhss_ref) of
clasohm@330
   192
                                Some tks => tks union (look2 ls todos)
clasohm@330
   193
                              | None => let val (_, rhss) = hd (!rhss_ref);
clasohm@330
   194
                                        in look2 ls (rhss union todos) end;
clasohm@330
   195
                  in case start_token of
clasohm@330
   196
                         Some tk => start_token ins (look2 skipped todos)
clasohm@330
   197
                       | None => look2 skipped todos
clasohm@330
   198
                  end;
clasohm@330
   199
 
clasohm@330
   200
            val (_, rhss) = hd (!rhss_ref);
clasohm@330
   201
        in look rhss [rhss_ref] end;                       
clasohm@330
   202
clasohm@330
   203
      (*make a table that contains all possible starting terminals
clasohm@330
   204
        for each nonterminal*)
clasohm@330
   205
      fun mk_starts [] starts = starts
clasohm@330
   206
        | mk_starts ((_, rhss_ref) :: ps) starts =
clasohm@330
   207
            mk_starts ps ((rhss_ref, look_rhss starts rhss_ref) :: starts);
clasohm@330
   208
clasohm@330
   209
      val starts = mk_starts ref_gram [];
clasohm@330
   210
clasohm@330
   211
      (*add list of allowed starting tokens to productions*)
clasohm@330
   212
      fun mk_lookahead (_, rhss_ref) =
clasohm@330
   213
        let (*add item to lookahead list (a list containing pairs of token and 
clasohm@345
   214
              rhss that can be started with it*)
clasohm@345
   215
            fun add_start new_rhs tokens table =
clasohm@345
   216
                  let fun add [] [] = []
clasohm@345
   217
                        | add (tk :: tks) [] =
clasohm@345
   218
                            (tk, [new_rhs]) :: (add tks [])
clasohm@345
   219
                        | add tokens ((tk, rhss) :: ss) =
clasohm@345
   220
                            if tk mem tokens then 
clasohm@345
   221
                              (tk, new_rhs :: rhss) :: (add (tokens \ tk) ss)
clasohm@330
   222
                            else
clasohm@345
   223
                              (tk, rhss) :: (add tokens ss);
clasohm@345
   224
                  in add tokens table end;
clasohm@330
   225
clasohm@330
   226
            (*combine all lookaheads of a list of nonterminals*)
clasohm@345
   227
            fun combine_starts rhss_refs =
clasohm@345
   228
              foldr (op union) 
clasohm@345
   229
              ((map (fn rhss_ref => let val Some tks = assoc (starts, rhss_ref)
clasohm@345
   230
                                    in tks end) rhss_refs), []);
clasohm@330
   231
clasohm@330
   232
            (*get lookahead for a rhs and update lhs' lookahead list*)
clasohm@330
   233
            fun look_rhss [] table = table
clasohm@330
   234
              | look_rhss ((rhs as (symbs, id, prec)) :: rs) table =
clasohm@330
   235
                  let val (start_token, skipped) = rhss_start symbs [];
clasohm@330
   236
                      val starts = case start_token of
clasohm@330
   237
                                     Some tk => Some tk 
clasohm@330
   238
                                                ins (combine_starts skipped)
clasohm@345
   239
                                   | None => if skipped subset lambdas then
clasohm@330
   240
                                               [None]
clasohm@330
   241
                                             else
clasohm@330
   242
                                               combine_starts skipped;
clasohm@330
   243
                  in look_rhss rs (add_start rhs starts table) end;
clasohm@330
   244
clasohm@330
   245
             val (_, rhss) = hd (!rhss_ref);
clasohm@330
   246
        in rhss_ref := look_rhss rhss [] end;
clasohm@330
   247
clasohm@330
   248
  in map mk_lookahead ref_gram;
clasohm@330
   249
     Gram (prods, ref_gram)
clasohm@330
   250
  end;
wenzelm@18
   251
wenzelm@18
   252
wenzelm@237
   253
(* empty, extend, merge grams *)
wenzelm@18
   254
wenzelm@237
   255
val empty_gram = mk_gram [];
wenzelm@18
   256
wenzelm@237
   257
fun extend_gram (gram1 as Gram (prods1, _)) _ xprods2 =
wenzelm@18
   258
  let
wenzelm@237
   259
    fun symb_of (Delim s) = Some (Terminal (Token s))
wenzelm@237
   260
      | symb_of (Argument (s, p)) =
wenzelm@18
   261
          (case predef_term s of
wenzelm@237
   262
            None => Some (Nonterminal (s, p))
wenzelm@237
   263
          | Some tk => Some (Terminal tk))
wenzelm@18
   264
      | symb_of _ = None;
wenzelm@18
   265
wenzelm@237
   266
    fun prod_of (XProd (lhs, xsymbs, const, pri)) =
wenzelm@237
   267
      (lhs, (mapfilter symb_of xsymbs, const, pri));
wenzelm@18
   268
wenzelm@237
   269
    val prods2 = distinct (map prod_of xprods2);
wenzelm@18
   270
  in
wenzelm@237
   271
    if prods2 subset prods1 then gram1
wenzelm@237
   272
    else mk_gram (extend_list prods1 prods2)
wenzelm@18
   273
  end;
wenzelm@18
   274
wenzelm@237
   275
fun merge_grams (gram1 as Gram (prods1, _)) (gram2 as Gram (prods2, _)) =
wenzelm@237
   276
  if prods2 subset prods1 then gram1
wenzelm@237
   277
  else if prods1 subset prods2 then gram2
wenzelm@237
   278
  else mk_gram (merge_lists prods1 prods2);
wenzelm@237
   279
wenzelm@18
   280
wenzelm@237
   281
(* pretty_gram *)
wenzelm@18
   282
wenzelm@237
   283
fun pretty_gram (Gram (prods, _)) =
wenzelm@237
   284
  let
wenzelm@237
   285
    fun pretty_name name = [Pretty.str (name ^ " =")];
wenzelm@18
   286
wenzelm@237
   287
    fun pretty_symb (Terminal (Token s)) = Pretty.str (quote s)
wenzelm@237
   288
      | pretty_symb (Terminal tok) = Pretty.str (str_of_token tok)
wenzelm@237
   289
      | pretty_symb (Nonterminal (s, p)) =
wenzelm@237
   290
          Pretty.str (s ^ "[" ^ string_of_int p ^ "]");
wenzelm@18
   291
wenzelm@237
   292
    fun pretty_const "" = []
wenzelm@237
   293
      | pretty_const c = [Pretty.str ("=> " ^ quote c)];
wenzelm@237
   294
wenzelm@237
   295
    fun pretty_pri p = [Pretty.str ("(" ^ string_of_int p ^ ")")];
wenzelm@237
   296
wenzelm@237
   297
    fun pretty_prod (name, (symbs, const, pri)) =
wenzelm@237
   298
      Pretty.block (Pretty.breaks (pretty_name name @
wenzelm@237
   299
        map pretty_symb symbs @ pretty_const const @ pretty_pri pri));
wenzelm@18
   300
  in
wenzelm@237
   301
    map pretty_prod prods
wenzelm@18
   302
  end;
wenzelm@18
   303
wenzelm@18
   304
wenzelm@18
   305
wenzelm@18
   306
(** parse **)
wenzelm@18
   307
wenzelm@237
   308
datatype parsetree =
wenzelm@237
   309
  Node of string * parsetree list |
wenzelm@237
   310
  Tip of token;
wenzelm@237
   311
wenzelm@18
   312
type state =
clasohm@330
   313
  rhss_ref * int      (*lhs: identification and production precedence*)
clasohm@330
   314
  * parsetree list    (*already parsed nonterminals on rhs*)
clasohm@330
   315
  * refsymb list      (*rest of rhs*)
clasohm@330
   316
  * string            (*name of production*)
clasohm@330
   317
  * int;              (*index for previous state list*)
wenzelm@18
   318
wenzelm@18
   319
type earleystate = state list Array.array;
wenzelm@18
   320
wenzelm@18
   321
clasohm@330
   322
(*Get all rhss with precedence >= minPrec*)
clasohm@330
   323
fun getRHS minPrec = filter (fn (_, _, prec:int) => prec >= minPrec);
wenzelm@237
   324
clasohm@330
   325
(*Get all rhss with precedence >= minPrec and < maxPrec*)
clasohm@330
   326
fun getRHS' minPrec maxPrec =
clasohm@330
   327
  filter (fn (_, _, prec:int) => prec >= minPrec andalso prec < maxPrec);
wenzelm@18
   328
clasohm@330
   329
(*Make states using a list of rhss*)
clasohm@330
   330
fun mkStates i minPrec lhsID rhss =
clasohm@330
   331
  let fun mkState (rhs, id, prodPrec) = (lhsID, prodPrec, [], rhs, id, i);
clasohm@330
   332
  in map mkState rhss end;
clasohm@330
   333
	
clasohm@330
   334
(*Add parse tree to list and eliminate duplicates 
clasohm@330
   335
  saving the maximum precedence*)
clasohm@330
   336
fun conc (t, prec:int) [] = (None, [(t, prec)])
clasohm@330
   337
  | conc (t, prec) ((t', prec') :: ts) =
clasohm@330
   338
      if t = t' then
clasohm@330
   339
        (Some prec', if prec' >= prec then (t', prec') :: ts 
clasohm@330
   340
                     else (t, prec) :: ts)
clasohm@330
   341
      else
clasohm@330
   342
        let val (n, ts') = conc (t, prec) ts
clasohm@330
   343
        in (n, (t', prec') :: ts') end;
wenzelm@18
   344
clasohm@330
   345
(*Update entry in used*)
wenzelm@237
   346
fun update_tree ((B, (i, ts)) :: used) (A, t) =
wenzelm@237
   347
  if A = B then
wenzelm@237
   348
    let val (n, ts') = conc t ts
wenzelm@237
   349
    in ((A, (i, ts')) :: used, n) end
wenzelm@237
   350
  else
wenzelm@237
   351
    let val (used', n) = update_tree used (A, t)
wenzelm@237
   352
    in ((B, (i, ts)) :: used', n) end;
wenzelm@18
   353
clasohm@330
   354
(*Replace entry in used*)
clasohm@330
   355
fun update_index (A, prec) used =
clasohm@330
   356
  let fun update((hd as (B, (_, ts))) :: used, used') =
clasohm@330
   357
        if A = B
clasohm@330
   358
        then used' @ ((A, (prec, ts)) :: used)
clasohm@330
   359
        else update (used, hd :: used')
clasohm@330
   360
  in update (used, []) end;
wenzelm@18
   361
clasohm@330
   362
fun getS A maxPrec Si =
wenzelm@237
   363
  filter
clasohm@330
   364
    (fn (_, _, _, Nonterm (B, prec) :: _, _, _)
clasohm@330
   365
          => A = B andalso prec <= maxPrec
wenzelm@237
   366
      | _ => false) Si;
wenzelm@18
   367
clasohm@330
   368
fun getS' A maxPrec minPrec Si =
wenzelm@237
   369
  filter
clasohm@330
   370
    (fn (_, _, _, Nonterm (B, prec) :: _, _, _)
clasohm@330
   371
          => A = B andalso prec > minPrec andalso prec <= maxPrec
wenzelm@237
   372
      | _ => false) Si;
wenzelm@18
   373
clasohm@330
   374
fun getStates Estate i ii A maxPrec =
wenzelm@237
   375
  filter
clasohm@330
   376
    (fn (_, _, _, Nonterm (B, prec) :: _, _, _)
clasohm@330
   377
          => A = B andalso prec <= maxPrec
wenzelm@237
   378
      | _ => false)
wenzelm@237
   379
    (Array.sub (Estate, ii));
wenzelm@18
   380
wenzelm@18
   381
clasohm@330
   382
fun movedot_term (A, j, ts, Term a :: sa, id, i) c =
wenzelm@237
   383
  if valued_token c then
wenzelm@237
   384
    (A, j, (ts @ [Tip c]), sa, id, i)
wenzelm@237
   385
  else (A, j, ts, sa, id, i);
wenzelm@18
   386
clasohm@330
   387
fun movedot_nonterm ts (A, j, tss, Nonterm _ :: sa, id, i) =
wenzelm@237
   388
  (A, j, tss @ ts, sa, id, i);
wenzelm@18
   389
wenzelm@237
   390
fun movedot_lambda _ [] = []
clasohm@330
   391
  | movedot_lambda (B, j, tss, Nonterm (A, k) :: sa, id, i) ((t, ki) :: ts) =
wenzelm@237
   392
      if k <= ki then
wenzelm@237
   393
        (B, j, tss @ t, sa, id, i) ::
clasohm@330
   394
          movedot_lambda (B, j, tss, Nonterm (A, k) :: sa, id, i) ts
clasohm@330
   395
      else movedot_lambda (B, j, tss, Nonterm (A, k) :: sa, id, i) ts;
wenzelm@18
   396
wenzelm@18
   397
wenzelm@18
   398
clasohm@330
   399
fun PROCESSS Estate i c states =
wenzelm@18
   400
let
clasohm@330
   401
fun get_lookahead rhss_ref = token_assoc (!rhss_ref, c);
clasohm@330
   402
wenzelm@237
   403
fun processS used [] (Si, Sii) = (Si, Sii)
wenzelm@237
   404
  | processS used (S :: States) (Si, Sii) =
wenzelm@237
   405
      (case S of
clasohm@330
   406
        (_, _, _, Nonterm (rhss_ref, minPrec) :: _, _, _) =>
clasohm@330
   407
          let                                       (*predictor operation*)
clasohm@330
   408
            val (used_new, States_new) =
clasohm@330
   409
              (case assoc (used, rhss_ref) of
clasohm@330
   410
                Some (usedPrec, l) =>       (*nonterminal has been processed*)
clasohm@330
   411
                  if usedPrec <= minPrec then
clasohm@330
   412
                                      (*wanted precedence has been processed*)
clasohm@330
   413
                    (used, movedot_lambda S l)
clasohm@330
   414
                  else            (*wanted precedence hasn't been parsed yet*)
clasohm@330
   415
                    let val rhss = get_lookahead rhss_ref;
clasohm@330
   416
                      val States' = mkStates i minPrec rhss_ref
clasohm@330
   417
                                      (getRHS' minPrec usedPrec rhss);
clasohm@330
   418
                    in (update_index (rhss_ref, minPrec) used, 
clasohm@330
   419
                        movedot_lambda S l @ States')
wenzelm@237
   420
                    end
wenzelm@18
   421
clasohm@330
   422
              | None =>           (*nonterminal is parsed for the first time*)
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 rhss);
clasohm@330
   426
                  in ((rhss_ref, (minPrec, [])) :: used, States') end)
wenzelm@18
   427
          in
clasohm@330
   428
            processS used_new (States_new @ States) (S :: Si, Sii)
wenzelm@18
   429
          end
clasohm@330
   430
      | (_, _, _, Term a :: _, _, _) =>               (*scanner operation*)
wenzelm@237
   431
          processS used States
wenzelm@237
   432
            (S :: Si,
wenzelm@237
   433
              if matching_tokens (a, c) then movedot_term S c :: Sii else Sii)
wenzelm@18
   434
clasohm@330
   435
      | (A, prec, ts, [], id, j) =>                   (*completer operation*)
wenzelm@237
   436
          let
wenzelm@237
   437
            val tt = if id = "" then ts else [Node (id, ts)]
wenzelm@18
   438
          in
clasohm@330
   439
            if j = i then                             (*lambda production?*)
wenzelm@237
   440
              let
clasohm@330
   441
                val (used', O) = update_tree used (A, (tt, prec));
wenzelm@237
   442
              in
wenzelm@237
   443
                (case O of
wenzelm@237
   444
                  None =>
wenzelm@237
   445
                    let
clasohm@330
   446
                      val Slist = getS A prec Si;
wenzelm@237
   447
                      val States' = map (movedot_nonterm tt) Slist;
wenzelm@237
   448
                    in
clasohm@330
   449
                      processS used' (States' @ States) (S :: Si, Sii)
wenzelm@237
   450
                    end
wenzelm@237
   451
                | Some n =>
clasohm@330
   452
                    if n >= prec then
wenzelm@237
   453
                      processS used' States (S :: Si, Sii)
wenzelm@237
   454
                    else
wenzelm@237
   455
                      let
clasohm@330
   456
                        val Slist = getS' A prec n Si;
wenzelm@237
   457
                        val States' = map (movedot_nonterm tt) Slist;
wenzelm@237
   458
                      in
clasohm@330
   459
                        processS used' (States' @ States) (S :: Si, Sii)
wenzelm@237
   460
                      end)
clasohm@330
   461
              end 
wenzelm@237
   462
            else
wenzelm@237
   463
              processS used
clasohm@330
   464
                (map (movedot_nonterm tt) (getStates Estate i j A prec) @ States)
wenzelm@237
   465
                (S :: Si, Sii)
wenzelm@237
   466
          end)
wenzelm@18
   467
in
wenzelm@237
   468
  processS [] states ([], [])
wenzelm@18
   469
end;
wenzelm@18
   470
wenzelm@18
   471
wenzelm@18
   472
clasohm@362
   473
fun syntax_error toks allowed =
clasohm@362
   474
  error 
clasohm@362
   475
  ((if toks = [] then
clasohm@362
   476
      "error: unexpected end of input\n"
clasohm@362
   477
    else
clasohm@367
   478
      "Syntax error at: " ^ quote (space_implode " " (map str_of_token 
clasohm@367
   479
        ((rev o tl o rev) toks)))
clasohm@362
   480
      ^ "\n")
clasohm@362
   481
   ^ "Expected tokens: " 
clasohm@362
   482
   ^ space_implode ", " (map (quote o str_of_token) allowed));
wenzelm@18
   483
clasohm@362
   484
fun produce stateset i indata prev_token =
clasohm@362
   485
                     (*the argument prev_token is only used for error messages*)
wenzelm@237
   486
  (case Array.sub (stateset, i) of
clasohm@373
   487
    [] => let (*similar to token_assoc but does not automatically 
clasohm@373
   488
                include 'None' key*)
clasohm@373
   489
              fun token_assoc2 (list, key) =
clasohm@373
   490
                let fun assoc [] = []
clasohm@373
   491
                      | assoc ((keyi, xi) :: pairs) =
clasohm@373
   492
                          if is_some keyi andalso
clasohm@373
   493
                             matching_tokens (the keyi, key) then 
clasohm@373
   494
                            (assoc pairs) @ xi
clasohm@373
   495
                          else assoc pairs;
clasohm@373
   496
                          in assoc list end;
clasohm@373
   497
clasohm@373
   498
              (*test if tk is a lookahead for a given minimum precedence*)
clasohm@373
   499
              fun reduction minPrec tk _ (Term _ :: _, _, prec:int) =
clasohm@373
   500
                    if prec >= minPrec then true
clasohm@373
   501
                    else false
clasohm@373
   502
                | reduction minPrec tk checked 
clasohm@373
   503
                            (Nonterm (rhss_ref, NTprec)::_,_, prec) =
clasohm@373
   504
                    if prec >= minPrec andalso not (rhss_ref mem checked) then
clasohm@373
   505
                      exists (reduction NTprec tk (rhss_ref :: checked)) 
clasohm@373
   506
                             (token_assoc2 (!rhss_ref, tk))
clasohm@373
   507
                    else false;
clasohm@373
   508
clasohm@373
   509
              (*compute a list of allowed starting tokens 
clasohm@373
   510
                for a list of nonterminals considering precedence*)
clasohm@362
   511
              fun get_starts [] = []
clasohm@372
   512
                | get_starts ((rhss_ref, minPrec:int) :: refs) =
clasohm@362
   513
                    let fun get [] = []
clasohm@373
   514
                          | get ((Some tk, prods) :: rhss) =
clasohm@373
   515
                              if exists (reduction minPrec tk [rhss_ref]) prods
clasohm@373
   516
                              then tk :: (get rhss)
clasohm@372
   517
                              else get rhss
clasohm@362
   518
                          | get ((None, _) :: rhss) =
clasohm@362
   519
                              get rhss;
clasohm@362
   520
                    in (get (!rhss_ref)) union (get_starts refs) end;
clasohm@362
   521
clasohm@372
   522
              val NTs = map (fn (_, _, _, Nonterm (a, prec) :: _, _, _) => 
clasohm@372
   523
                              (a, prec))
clasohm@362
   524
                            (filter (fn (_, _, _, Nonterm _ :: _, _, _) => true
clasohm@362
   525
                                     | _ => false) (Array.sub (stateset, i-1)));
clasohm@367
   526
              val allowed = distinct (get_starts NTs @
clasohm@362
   527
                            (map (fn (_, _, _, Term a :: _, _, _) => a)
clasohm@362
   528
                            (filter (fn (_, _, _, Term _ :: _, _, _) => true
clasohm@367
   529
                                   | _ => false) (Array.sub (stateset, i-1)))));
clasohm@362
   530
          in syntax_error (if prev_token = EndToken then indata
clasohm@362
   531
                           else prev_token :: indata) allowed
clasohm@362
   532
          end
wenzelm@237
   533
  | s =>
wenzelm@237
   534
    (case indata of
wenzelm@237
   535
      [] => Array.sub (stateset, i)
wenzelm@237
   536
    | c :: cs =>
wenzelm@237
   537
      let
clasohm@330
   538
        val (si, sii) = PROCESSS stateset i c s;
wenzelm@237
   539
      in
wenzelm@237
   540
        Array.update (stateset, i, si);
wenzelm@237
   541
        Array.update (stateset, i + 1, sii);
clasohm@362
   542
        produce stateset (i + 1) cs c
wenzelm@237
   543
      end));
wenzelm@18
   544
wenzelm@18
   545
wenzelm@237
   546
val get_trees = mapfilter (fn (_, _, [pt], _, _, _) => Some pt | _ => None);
wenzelm@237
   547
wenzelm@18
   548
wenzelm@18
   549
fun earley grammar startsymbol indata =
wenzelm@237
   550
  let
clasohm@330
   551
    val rhss_ref = case assoc (grammar, startsymbol) of
clasohm@330
   552
                       Some r => r
clasohm@330
   553
                     | None => error ("parse: Unknown startsymbol " ^ 
clasohm@330
   554
                                      quote startsymbol);
clasohm@330
   555
    val S0 = [(ref [], 0, [], [Nonterm (rhss_ref, 0), Term EndToken], "", 0)];
clasohm@330
   556
    val s = length indata + 1;
wenzelm@237
   557
    val Estate = Array.array (s, []);
wenzelm@237
   558
  in
wenzelm@237
   559
    Array.update (Estate, 0, S0);
wenzelm@237
   560
    let
clasohm@362
   561
      val l = produce Estate 0 indata EndToken(*dummy*);
wenzelm@237
   562
      val p_trees = get_trees l;
wenzelm@237
   563
    in p_trees end
wenzelm@237
   564
  end;
wenzelm@18
   565
wenzelm@18
   566
wenzelm@237
   567
fun parse (Gram (_, prod_tab)) start toks =
wenzelm@237
   568
  (case earley prod_tab start toks of
wenzelm@237
   569
    [] => sys_error "parse: no parse trees"
clasohm@330
   570
  | pts => pts);
wenzelm@18
   571
wenzelm@18
   572
end;
wenzelm@18
   573