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