src/Pure/Syntax/parser.ML
author clasohm
Mon, 15 Jan 1996 15:00:14 +0100
changeset 1438 3cc22794ce71
parent 1177 58e4d9221db7
child 1507 f600215b6ea7
permissions -rw-r--r--
added comments
wenzelm@18
     1
(*  Title:      Pure/Syntax/parser.ML
wenzelm@46
     2
    ID:         $Id$
clasohm@1147
     3
    Author:     Sonia Mahjoub, Markus Wenzel, and Carsten Clasohm, TU Muenchen
wenzelm@18
     4
wenzelm@552
     5
Isabelle's main parser (used for terms and types).
wenzelm@18
     6
*)
wenzelm@18
     7
wenzelm@18
     8
signature PARSER =
wenzelm@18
     9
sig
wenzelm@237
    10
  structure Lexicon: LEXICON
wenzelm@237
    11
  structure SynExt: SYN_EXT
wenzelm@237
    12
  local open Lexicon SynExt SynExt.Ast in
wenzelm@18
    13
    type gram
wenzelm@18
    14
    val empty_gram: gram
clasohm@1147
    15
    val extend_gram: gram -> xprod list -> gram
wenzelm@237
    16
    val merge_grams: gram -> gram -> gram
wenzelm@237
    17
    val pretty_gram: gram -> Pretty.T list
wenzelm@237
    18
    datatype parsetree =
wenzelm@237
    19
      Node of string * parsetree list |
wenzelm@237
    20
      Tip of token
clasohm@330
    21
    val parse: gram -> string -> token list -> parsetree list
wenzelm@18
    22
  end
clasohm@682
    23
  val branching_level: int ref;
wenzelm@18
    24
end;
wenzelm@18
    25
wenzelm@237
    26
functor ParserFun(structure Symtab: SYMTAB and Lexicon: LEXICON
wenzelm@552
    27
  and SynExt: SYN_EXT): PARSER =
wenzelm@18
    28
struct
wenzelm@18
    29
wenzelm@237
    30
structure Pretty = SynExt.Ast.Pretty;
wenzelm@237
    31
structure Lexicon = Lexicon;
wenzelm@237
    32
structure SynExt = SynExt;
wenzelm@237
    33
open Lexicon SynExt;
wenzelm@18
    34
wenzelm@18
    35
wenzelm@18
    36
(** datatype gram **)
wenzelm@18
    37
clasohm@1175
    38
type nt_tag = int;              (*production for the NTs are stored in an array
clasohm@1175
    39
                                  so we can identify NTs by their index*)
wenzelm@18
    40
clasohm@1147
    41
datatype symb = Terminal of token
clasohm@1175
    42
              | Nonterminal of nt_tag * int;              (*(tag, precedence)*)
wenzelm@18
    43
clasohm@1175
    44
type nt_gram = ((nt_tag list * token list) *
clasohm@1147
    45
                (token option * (symb list * string * int) list) list);
clasohm@1147
    46
                                     (*(([dependent_nts], [start_tokens]),
clasohm@1147
    47
                                        [(start_token, [(rhs, name, prio)])])*)
clasohm@1175
    48
                              (*depent_nts is a list of all NTs whose lookahead
clasohm@1175
    49
                                depends on this NT's lookahead*)
clasohm@330
    50
clasohm@1147
    51
datatype gram =
clasohm@1147
    52
  Gram of {nt_count: int, prod_count: int,
clasohm@1147
    53
           tags: nt_tag Symtab.table,
clasohm@1147
    54
           chains: (nt_tag * nt_tag list) list,              (*[(to, [from])]*)
clasohm@1147
    55
           lambdas: nt_tag list,
clasohm@1175
    56
           prods: nt_gram Array.array};
clasohm@1175
    57
                       (*"tags" is used to map NT names (i.e. strings) to tags;
clasohm@1175
    58
                         chain productions are not stored as normal productions
clasohm@1175
    59
                         but instead as an entry in "chains";
clasohm@1175
    60
                         lambda productions are stored as normal productions
clasohm@1175
    61
                         and also as an entry in "lambdas"*)
clasohm@330
    62
clasohm@1175
    63
val UnknownStart = EndToken;       (*productions for which no starting token is
clasohm@1175
    64
                                     known yet are associated with this token*)
clasohm@330
    65
clasohm@1175
    66
(* get all NTs that are connected with a list of NTs 
clasohm@1175
    67
   (used for expanding chain list)*)
clasohm@1147
    68
fun connected_with _ [] relatives = relatives
clasohm@1147
    69
  | connected_with chains (root :: roots) relatives =
clasohm@1147
    70
    let val branches = (assocs chains root) \\ relatives;
clasohm@1147
    71
    in connected_with chains (branches @ roots) (branches @ relatives) end;
clasohm@330
    72
clasohm@1147
    73
(* convert productions to grammar;
clasohm@1175
    74
   N.B. that the chains parameter has the form [(from, [to])];
clasohm@1175
    75
   prod_count is of type "int option" and is only updated if it is <> None*)
clasohm@1147
    76
fun add_prods _ chains lambdas prod_count [] = (chains, lambdas, prod_count)
clasohm@1147
    77
  | add_prods prods chains lambdas prod_count
clasohm@1147
    78
              ((lhs, new_prod as (rhs, name, pri)) :: ps) =
clasohm@1147
    79
    let
clasohm@1175
    80
      (*test if new_prod is a chain production*)
clasohm@1147
    81
      val (new_chain, chains') =
clasohm@1175
    82
        let (*store chain if it does not already exist*)
clasohm@1175
    83
            fun store_chain from =
clasohm@1175
    84
              let val old_tos = assocs chains from;
clasohm@1175
    85
              in if lhs mem old_tos then (None, chains)
clasohm@1175
    86
                 else (Some from, overwrite (chains, (from, lhs ins old_tos)))
clasohm@1175
    87
              end;
clasohm@1175
    88
        in if pri = ~1 then
clasohm@1175
    89
             case rhs of [Nonterminal (id, ~1)] => store_chain id
clasohm@1175
    90
                       | _ => (None, chains)
clasohm@1175
    91
           else (None, chains)
clasohm@1175
    92
        end;
clasohm@330
    93
clasohm@1175
    94
      (*propagate new chain in lookahead and lambda lists;
clasohm@1175
    95
        added_starts is used later to associate existing
clasohm@1175
    96
        productions with new starting tokens*)
clasohm@1147
    97
      val (added_starts, lambdas') =
clasohm@1147
    98
        if is_none new_chain then ([], lambdas) else
clasohm@1175
    99
        let (*lookahead of chain's source*)
clasohm@1175
   100
            val ((from_nts, from_tks), _) = Array.sub (prods, the new_chain);
clasohm@330
   101
clasohm@1175
   102
            (*copy from's lookahead to chain's destinations*)
clasohm@1147
   103
            fun copy_lookahead [] added = added
clasohm@1147
   104
              | copy_lookahead (to :: tos) added =
clasohm@1175
   105
                let
clasohm@1175
   106
                  val ((to_nts, to_tks), ps) = Array.sub (prods, to);
clasohm@1147
   107
clasohm@1175
   108
                  val new_tks = from_tks \\ to_tks;  (*added lookahead tokens*)
clasohm@1175
   109
                in Array.update (prods, to, ((to_nts, to_tks @ new_tks), ps));
clasohm@1147
   110
                   copy_lookahead tos (if null new_tks then added
clasohm@1147
   111
                                       else (to, new_tks) :: added)
clasohm@1147
   112
                end;
clasohm@1147
   113
clasohm@1147
   114
            val tos = connected_with chains' [lhs] [lhs];
clasohm@1175
   115
        in (copy_lookahead tos [],
clasohm@1175
   116
            (if lhs mem lambdas then tos else []) union lambdas)
clasohm@1147
   117
        end;
clasohm@1147
   118
clasohm@1175
   119
      (*test if new production can produce lambda
clasohm@1175
   120
        (rhs must either be empty or only consist of lambda NTs)*)
clasohm@1175
   121
      val (new_lambda, lambdas') =
clasohm@1175
   122
        if forall (fn (Nonterminal (id, _)) => id mem lambdas'
clasohm@1175
   123
                    | (Terminal _) => false) rhs then
clasohm@1175
   124
          (true, lambdas' union (connected_with chains' [lhs] [lhs]))
clasohm@1175
   125
        else
clasohm@1175
   126
          (false, lambdas');
clasohm@1147
   127
clasohm@1175
   128
      (*list optional terminal and all nonterminals on which the lookahead
clasohm@1175
   129
        of a production depends*)
clasohm@1147
   130
      fun lookahead_dependency _ [] nts = (None, nts)
clasohm@1147
   131
        | lookahead_dependency _ ((Terminal tk) :: _) nts = (Some tk, nts)
clasohm@1147
   132
        | lookahead_dependency lambdas ((Nonterminal (nt, _)) :: symbs) nts =
clasohm@1147
   133
            if nt mem lambdas then
clasohm@1147
   134
              lookahead_dependency lambdas symbs (nt :: nts)
clasohm@1147
   135
            else (None, nt :: nts);
clasohm@1147
   136
clasohm@1175
   137
      (*get all known starting tokens for a nonterminal*)
clasohm@1175
   138
      fun starts_for_nt nt = snd (fst (Array.sub (prods, nt)));
clasohm@1175
   139
clasohm@1147
   140
      val token_union = gen_union matching_tokens;
clasohm@1147
   141
clasohm@1147
   142
      (*update prods, lookaheads, and lambdas according to new lambda NTs*)
clasohm@1147
   143
      val (added_starts', lambdas') =
clasohm@1147
   144
        let
clasohm@1147
   145
          (*propagate added lambda NT*)
clasohm@1175
   146
          fun propagate_lambda [] added_starts lambdas= (added_starts, lambdas)
clasohm@1147
   147
            | propagate_lambda (l :: ls) added_starts lambdas =
clasohm@1147
   148
              let
clasohm@1175
   149
                (*get lookahead for lambda NT*)
clasohm@1175
   150
                val ((dependent, l_starts), _) = Array.sub (prods, l);
clasohm@1147
   151
clasohm@1147
   152
                (*check productions whose lookahead may depend on lamdba NT*)
clasohm@1147
   153
                fun examine_prods [] add_lambda nt_dependencies added_tks
clasohm@1175
   154
                                  nt_prods =
clasohm@1147
   155
                      (add_lambda, nt_dependencies, added_tks, nt_prods)
clasohm@1147
   156
                  | examine_prods ((p as (rhs, _, _)) :: ps) add_lambda
clasohm@1147
   157
                      nt_dependencies added_tks nt_prods =
clasohm@1147
   158
                    let val (tk, nts) = lookahead_dependency lambdas rhs [];
clasohm@1147
   159
                    in
clasohm@1175
   160
                      if l mem nts then       (*update production's lookahead*)
clasohm@1147
   161
                      let
clasohm@1147
   162
                        val new_lambda = is_none tk andalso nts subset lambdas;
clasohm@1147
   163
clasohm@1147
   164
                        val new_tks = (if is_some tk then [the tk] else []) @
clasohm@1175
   165
                          foldl token_union ([], map starts_for_nt nts) \\
clasohm@1147
   166
                          l_starts;
clasohm@1147
   167
  
clasohm@1147
   168
                        val added_tks' = token_union (new_tks, added_tks);
clasohm@1147
   169
clasohm@1147
   170
                        val nt_dependencies' = nts union nt_dependencies;
clasohm@1147
   171
clasohm@1175
   172
                        (*associate production with new starting tokens*)
clasohm@1175
   173
                        fun copy [] nt_prods = nt_prods
clasohm@1175
   174
                          | copy (tk :: tks) nt_prods =
clasohm@1175
   175
                            let val old_prods = assocs nt_prods tk;
clasohm@1175
   176
clasohm@1175
   177
                                val prods' = p :: old_prods;
clasohm@1175
   178
                            in copy tks (overwrite (nt_prods, (tk, prods')))
clasohm@1175
   179
                            end;
clasohm@1175
   180
  
clasohm@1147
   181
                        val nt_prods' =
clasohm@1147
   182
                          let val new_opt_tks = map Some new_tks;
clasohm@1175
   183
                          in copy ((if new_lambda then [None] else []) @
clasohm@1175
   184
                                   new_opt_tks) nt_prods
clasohm@1147
   185
                          end;
clasohm@1147
   186
                      in examine_prods ps (add_lambda orelse new_lambda)
clasohm@1147
   187
                           nt_dependencies' added_tks' nt_prods'
clasohm@1147
   188
                      end
clasohm@1175
   189
                      else                                  (*skip production*)
clasohm@1175
   190
                        examine_prods ps add_lambda nt_dependencies
clasohm@1175
   191
                                      added_tks nt_prods
clasohm@1147
   192
                    end;
clasohm@1147
   193
clasohm@1147
   194
                (*check each NT whose lookahead depends on new lambda NT*)
clasohm@1147
   195
                fun process_nts [] added_lambdas added_starts =
clasohm@1147
   196
                      (added_lambdas, added_starts)
clasohm@1147
   197
                  | process_nts (nt :: nts) added_lambdas added_starts =
clasohm@1147
   198
                    let
clasohm@1147
   199
                      val (lookahead as (old_nts, old_tks), nt_prods) =
clasohm@1147
   200
                        Array.sub (prods, nt);
clasohm@1147
   201
clasohm@1175
   202
                      (*existing productions whose lookahead may depend on l*)
clasohm@1175
   203
                      val tk_prods =
clasohm@1175
   204
                        assocs nt_prods
clasohm@1175
   205
                               (Some (hd l_starts  handle Hd => UnknownStart));
clasohm@1147
   206
clasohm@1175
   207
                      (*add_lambda is true if an existing production of the nt
clasohm@1175
   208
                        produces lambda due to the new lambda NT l*)
clasohm@1147
   209
                      val (add_lambda, nt_dependencies, added_tks, nt_prods') =
clasohm@1147
   210
                        examine_prods tk_prods false [] [] nt_prods;
clasohm@1147
   211
clasohm@1147
   212
                      val added_nts = nt_dependencies \\ old_nts;
clasohm@1147
   213
clasohm@1147
   214
                      val added_lambdas' =
clasohm@1147
   215
                        if add_lambda then nt :: added_lambdas
clasohm@1147
   216
                        else added_lambdas;
clasohm@1147
   217
                    in Array.update (prods, nt,
clasohm@1175
   218
                                   ((added_nts @ old_nts, old_tks @ added_tks),
clasohm@1175
   219
                                    nt_prods'));
clasohm@1175
   220
                                          (*N.B. that because the tks component
clasohm@1175
   221
                                            is used to access existing
clasohm@1175
   222
                                            productions we have to add new
clasohm@1175
   223
                                            tokens at the _end_ of the list*)
clasohm@1175
   224
clasohm@1147
   225
                       if null added_tks then
clasohm@1147
   226
                         process_nts nts added_lambdas' added_starts
clasohm@1147
   227
                       else
clasohm@1147
   228
                         process_nts nts added_lambdas'
clasohm@1147
   229
                                      ((nt, added_tks) :: added_starts)
clasohm@1147
   230
                    end;
clasohm@1147
   231
clasohm@1147
   232
                val (added_lambdas, added_starts') =
clasohm@1147
   233
                  process_nts dependent [] added_starts;
clasohm@1147
   234
clasohm@1147
   235
                val added_lambdas' = added_lambdas \\ lambdas;
clasohm@1147
   236
              in propagate_lambda (ls @ added_lambdas') added_starts'
clasohm@1147
   237
                                  (added_lambdas' @ lambdas)
clasohm@1147
   238
              end;
clasohm@1147
   239
        in propagate_lambda (lambdas' \\ lambdas) added_starts lambdas' end;
clasohm@1147
   240
clasohm@1147
   241
      (*insert production into grammar*)
clasohm@1147
   242
      val (added_starts', prod_count') =
clasohm@1147
   243
        if is_some new_chain then (added_starts', prod_count)
clasohm@1175
   244
                                               (*don't store chain production*)
clasohm@1147
   245
        else let
clasohm@1175
   246
          (*lookahead tokens of new production and on which
clasohm@1175
   247
            NTs lookahead depends*)
clasohm@1175
   248
          val (start_tk, start_nts) = lookahead_dependency lambdas' rhs [];
clasohm@1147
   249
clasohm@1175
   250
          val start_tks = foldl token_union
clasohm@1175
   251
                          (if is_some start_tk then [the start_tk] else [],
clasohm@1175
   252
                           map starts_for_nt start_nts);
clasohm@1175
   253
clasohm@1147
   254
          val opt_starts = (if new_lambda then [None]
clasohm@1175
   255
                            else if null start_tks then [Some UnknownStart]
clasohm@1147
   256
                            else []) @ (map Some start_tks);
clasohm@1147
   257
clasohm@1147
   258
          (*add lhs NT to list of dependent NTs in lookahead*)
clasohm@1147
   259
          fun add_nts [] = ()
clasohm@1147
   260
            | add_nts (nt :: nts) =
clasohm@1147
   261
              let val ((old_nts, old_tks), ps) = Array.sub (prods, nt);
clasohm@1175
   262
              in if lhs mem old_nts then ()
clasohm@1175
   263
                 else Array.update (prods, nt, ((lhs :: old_nts, old_tks), ps))
clasohm@1147
   264
              end;
clasohm@1147
   265
clasohm@1175
   266
          (*add new start tokens to chained NTs' lookahead list;
clasohm@1147
   267
            also store new production for lhs NT*)
clasohm@1147
   268
          fun add_tks [] added prod_count = (added, prod_count)
clasohm@1147
   269
            | add_tks (nt :: nts) added prod_count =
clasohm@1147
   270
              let
clasohm@1175
   271
                val ((old_nts, old_tks), nt_prods) = Array.sub (prods, nt);
clasohm@1147
   272
clasohm@1175
   273
                val new_tks = gen_rems matching_tokens (start_tks, old_tks);
clasohm@1147
   274
clasohm@1175
   275
                (*store new production*)
clasohm@1147
   276
                fun store [] prods is_new =
clasohm@1147
   277
                      (prods, if is_some prod_count andalso is_new then
clasohm@1175
   278
                                apsome (fn x => x+1) prod_count
clasohm@1175
   279
                              else prod_count, is_new)
clasohm@1175
   280
                  | store (tk :: tks) prods is_new =
clasohm@1147
   281
                    let val tk_prods = assocs prods tk;
clasohm@1147
   282
clasohm@1175
   283
                        (*if prod_count = None then we can assume that
clasohm@1175
   284
                          grammar does not contain new production already*)
clasohm@1175
   285
                        val (tk_prods', is_new') =
clasohm@1147
   286
                          if is_some prod_count then
clasohm@1147
   287
                            if new_prod mem tk_prods then (tk_prods, false)
clasohm@1147
   288
                            else (new_prod :: tk_prods, true)
clasohm@1147
   289
                          else (new_prod :: tk_prods, true);
clasohm@1147
   290
clasohm@1175
   291
                        val prods' = if is_new' then
clasohm@1175
   292
                                       overwrite (prods, (tk, tk_prods'))
clasohm@1175
   293
                                     else prods;
clasohm@1175
   294
                    in store tks prods' (is_new orelse is_new') end;
clasohm@1175
   295
clasohm@1175
   296
                val (nt_prods', prod_count', changed) =
clasohm@1175
   297
                  if nt = lhs then store opt_starts nt_prods false
clasohm@1175
   298
                              else (nt_prods, prod_count, false);
clasohm@1175
   299
              in if not changed andalso null new_tks then ()
clasohm@1175
   300
                 else Array.update (prods, nt, ((old_nts, old_tks @ new_tks),
clasohm@1175
   301
                                                nt_prods'));
clasohm@1147
   302
                 add_tks nts (if null new_tks then added
clasohm@1147
   303
                              else (nt, new_tks) :: added) prod_count'
clasohm@1147
   304
              end;
clasohm@1147
   305
        in add_nts start_nts;
clasohm@1147
   306
           add_tks (connected_with chains' [lhs] [lhs]) [] prod_count
clasohm@330
   307
        end;
clasohm@330
   308
clasohm@1175
   309
      (*associate productions with new lookaheads*)
clasohm@1147
   310
      val dummy =
clasohm@1147
   311
        let
clasohm@1147
   312
          (*propagate added start tokens*)
clasohm@1147
   313
          fun add_starts [] = ()
clasohm@1147
   314
            | add_starts ((changed_nt, new_tks) :: starts) =
clasohm@1147
   315
              let
clasohm@1175
   316
                (*token under which old productions which
clasohm@1175
   317
                  depend on changed_nt could be stored*)
clasohm@1175
   318
                val key =
clasohm@1175
   319
                 case find_first (fn t => not (t mem new_tks))
clasohm@1175
   320
                                 (starts_for_nt changed_nt) of
clasohm@1175
   321
                      None => Some UnknownStart
clasohm@1175
   322
                    | t => t;
clasohm@1175
   323
clasohm@1175
   324
                (*copy productions whose lookahead depends on changed_nt;
clasohm@1175
   325
                  if key = Some UnknownToken then tk_prods is used to hold
clasohm@1175
   326
                  the productions not copied*)
clasohm@1147
   327
                fun update_prods [] result = result
clasohm@1147
   328
                  | update_prods ((p as (rhs, _, _)) :: ps)
clasohm@1147
   329
                      (tk_prods, nt_prods) =
clasohm@1147
   330
                    let
clasohm@1175
   331
                      (*lookahead dependency for production*)
clasohm@1147
   332
                      val (tk, depends) = lookahead_dependency lambdas' rhs [];
clasohm@330
   333
clasohm@1175
   334
                      (*test if this production has to be copied*)
clasohm@1175
   335
                      val update = changed_nt mem depends;
clasohm@1175
   336
clasohm@1175
   337
                      (*test if production could already be associated with
clasohm@1175
   338
                        a member of new_tks*)
clasohm@1147
   339
                      val lambda = length depends > 1 orelse
clasohm@1175
   340
                                   not (null depends) andalso is_some tk
clasohm@1175
   341
                                   andalso the tk mem new_tks;
clasohm@330
   342
clasohm@1175
   343
                      (*associate production with new starting tokens*)
clasohm@1147
   344
                      fun copy [] nt_prods = nt_prods
clasohm@1147
   345
                        | copy (tk :: tks) nt_prods =
clasohm@1147
   346
                          let
clasohm@1147
   347
                            val tk_prods = assocs nt_prods (Some tk);
clasohm@1147
   348
clasohm@1147
   349
                            val tk_prods' =
clasohm@1147
   350
                              if not lambda then p :: tk_prods
clasohm@1147
   351
                              else p ins tk_prods;
clasohm@1147
   352
                                      (*if production depends on lambda NT we
clasohm@1147
   353
                                        have to look for duplicates*)
clasohm@1147
   354
                         in copy tks
clasohm@1147
   355
                                 (overwrite (nt_prods, (Some tk, tk_prods')))
clasohm@1147
   356
                         end;
clasohm@1147
   357
                      val result =
clasohm@1175
   358
                        if update then
clasohm@1175
   359
                          (tk_prods, copy new_tks nt_prods)
clasohm@1175
   360
                        else if key = Some UnknownStart then
clasohm@1175
   361
                          (p :: tk_prods, nt_prods)
clasohm@1175
   362
                        else (tk_prods, nt_prods);
clasohm@1147
   363
                    in update_prods ps result end;
clasohm@1147
   364
clasohm@1147
   365
                (*copy existing productions for new starting tokens*)
clasohm@1175
   366
                fun process_nts [] added = added
clasohm@1175
   367
                  | process_nts (nt :: nts) added =
clasohm@1147
   368
                    let
clasohm@1147
   369
                      val (lookahead as (old_nts, old_tks), nt_prods) =
clasohm@1147
   370
                        Array.sub (prods, nt);
clasohm@1147
   371
clasohm@1147
   372
                      val tk_prods = assocs nt_prods key;
clasohm@1147
   373
clasohm@1175
   374
                      (*associate productions with new lookahead tokens*)
clasohm@1147
   375
                      val (tk_prods', nt_prods') =
clasohm@1147
   376
                        update_prods tk_prods ([], nt_prods);
clasohm@1147
   377
clasohm@1147
   378
                      val nt_prods' =
clasohm@1175
   379
                        if key = Some UnknownStart then
clasohm@1147
   380
                          overwrite (nt_prods', (key, tk_prods'))
clasohm@1147
   381
                        else nt_prods';
clasohm@1147
   382
clasohm@1175
   383
                      val added_tks =
clasohm@1175
   384
                        gen_rems matching_tokens (new_tks, old_tks);
clasohm@1147
   385
                    in if null added_tks then
clasohm@1147
   386
                         (Array.update (prods, nt, (lookahead, nt_prods'));
clasohm@1175
   387
                          process_nts nts added)
clasohm@1147
   388
                       else
clasohm@1147
   389
                         (Array.update (prods, nt,
clasohm@1147
   390
                            ((old_nts, added_tks @ old_tks), nt_prods'));
clasohm@1175
   391
                          process_nts nts ((nt, added_tks) :: added))
clasohm@330
   392
                    end;
clasohm@330
   393
clasohm@1175
   394
                val ((dependent, _), _) = Array.sub (prods, changed_nt);
clasohm@1175
   395
              in add_starts (starts @ (process_nts dependent [])) end;
clasohm@1147
   396
        in add_starts added_starts' end;
clasohm@1147
   397
  in add_prods prods chains' lambdas' prod_count ps end;
wenzelm@18
   398
wenzelm@18
   399
wenzelm@237
   400
(* pretty_gram *)
wenzelm@18
   401
clasohm@1147
   402
fun pretty_gram (Gram {tags, prods, chains, ...}) =
wenzelm@237
   403
  let
wenzelm@237
   404
    fun pretty_name name = [Pretty.str (name ^ " =")];
wenzelm@18
   405
clasohm@1147
   406
    val taglist = Symtab.dest tags;
clasohm@1147
   407
wenzelm@237
   408
    fun pretty_symb (Terminal (Token s)) = Pretty.str (quote s)
wenzelm@237
   409
      | pretty_symb (Terminal tok) = Pretty.str (str_of_token tok)
clasohm@1147
   410
      | pretty_symb (Nonterminal (tag, p)) =
clasohm@1147
   411
        let val name = fst (the (find_first (fn (n, t) => t = tag) taglist));
clasohm@1147
   412
        in Pretty.str (name ^ "[" ^ string_of_int p ^ "]") end;
wenzelm@18
   413
wenzelm@237
   414
    fun pretty_const "" = []
wenzelm@237
   415
      | pretty_const c = [Pretty.str ("=> " ^ quote c)];
wenzelm@237
   416
wenzelm@237
   417
    fun pretty_pri p = [Pretty.str ("(" ^ string_of_int p ^ ")")];
wenzelm@237
   418
clasohm@1147
   419
    fun pretty_prod name (symbs, const, pri) =
wenzelm@237
   420
      Pretty.block (Pretty.breaks (pretty_name name @
wenzelm@237
   421
        map pretty_symb symbs @ pretty_const const @ pretty_pri pri));
clasohm@1147
   422
clasohm@1147
   423
    fun pretty_nt (name, tag) =
clasohm@1147
   424
      let
clasohm@1147
   425
        fun prod_of_chain from = ([Nonterminal (from, ~1)], "", ~1);
clasohm@1147
   426
clasohm@1147
   427
        val nt_prods =
clasohm@1147
   428
          foldl (op union) ([], map snd (snd (Array.sub (prods, tag)))) @
clasohm@1147
   429
          map prod_of_chain (assocs chains tag);
clasohm@1147
   430
      in map (pretty_prod name) nt_prods end;
clasohm@1147
   431
        
clasohm@1147
   432
  in flat (map pretty_nt taglist) end;
clasohm@1147
   433
clasohm@1147
   434
clasohm@1438
   435
(** Operations on gramars **)
clasohm@1147
   436
clasohm@1438
   437
(*The mother of all grammars*)
clasohm@1147
   438
val empty_gram = Gram {nt_count = 0, prod_count = 0,
clasohm@1147
   439
                       tags = Symtab.null, chains = [], lambdas = [],
clasohm@1147
   440
                       prods = Array.array (0, (([], []), []))};
clasohm@1147
   441
clasohm@1438
   442
clasohm@1438
   443
(*Invert list of chain productions*)
clasohm@1147
   444
fun inverse_chains [] result = result
clasohm@1147
   445
  | inverse_chains ((root, branches) :: cs) result =
clasohm@1147
   446
    let fun add [] result = result
clasohm@1147
   447
          | add (id :: ids) result =
clasohm@1147
   448
            let val old = assocs result id;
clasohm@1147
   449
            in add ids (overwrite (result, (id, root :: old))) end;
clasohm@1147
   450
    in inverse_chains cs (add branches result) end;
clasohm@1147
   451
clasohm@1438
   452
clasohm@1438
   453
(*Add productions to a grammar*)
clasohm@1147
   454
fun extend_gram gram [] = gram
clasohm@1147
   455
  | extend_gram (Gram {nt_count, prod_count, tags, chains, lambdas, prods})
clasohm@1147
   456
                xprods =
clasohm@1147
   457
  let
clasohm@1438
   458
    (*Get tag for existing nonterminal or create a new one*)
clasohm@1147
   459
    fun get_tag nt_count tags nt =
clasohm@1147
   460
      case Symtab.lookup (tags, nt) of
clasohm@1147
   461
        Some tag => (nt_count, tags, tag)
clasohm@1147
   462
      | None => (nt_count+1, Symtab.update_new ((nt, nt_count), tags),
clasohm@1147
   463
                 nt_count);
clasohm@1438
   464
clasohm@1438
   465
    (*Convert symbols to the form used by the parser;
clasohm@1438
   466
      delimiters and predefined terms are stored as terminals,
clasohm@1438
   467
      nonterminals are converted to integer tags*)
clasohm@1147
   468
    fun symb_of [] nt_count tags result = (nt_count, tags, rev result)
clasohm@1147
   469
      | symb_of ((Delim s) :: ss) nt_count tags result =
clasohm@1147
   470
          symb_of ss nt_count tags ((Terminal (Token s)) :: result)
clasohm@1147
   471
      | symb_of ((Argument (s, p)) :: ss) nt_count tags result =
clasohm@1147
   472
          let
clasohm@1147
   473
            val (nt_count', tags', new_symb) =
clasohm@1147
   474
              case predef_term s of
clasohm@1147
   475
                None =>
clasohm@1147
   476
                  let val (nt_count', tags', s_tag) = get_tag nt_count tags s;
clasohm@1147
   477
                  in (nt_count', tags', Nonterminal (s_tag, p)) end
clasohm@1147
   478
              | Some tk => (nt_count, tags, Terminal tk);
clasohm@1147
   479
          in symb_of ss nt_count' tags' (new_symb :: result) end
clasohm@1147
   480
      | symb_of (_ :: ss) nt_count tags result =
clasohm@1147
   481
          symb_of ss nt_count tags result;
clasohm@1147
   482
clasohm@1438
   483
    (*Convert list of productions by invoking symb_of for each of them*)
clasohm@1147
   484
    fun prod_of [] nt_count prod_count tags result =
clasohm@1147
   485
          (nt_count, prod_count, tags, result)
clasohm@1147
   486
      | prod_of ((XProd (lhs, xsymbs, const, pri)) :: ps)
clasohm@1147
   487
                nt_count prod_count tags result =
clasohm@1147
   488
        let val (nt_count', tags', lhs_tag) = get_tag nt_count tags lhs;
clasohm@1147
   489
clasohm@1147
   490
            val (nt_count'', tags'', prods) =
clasohm@1147
   491
              symb_of xsymbs nt_count' tags' [];
clasohm@1147
   492
        in prod_of ps nt_count'' (prod_count+1) tags''
clasohm@1147
   493
                   ((lhs_tag, (prods, const, pri)) :: result)
clasohm@1147
   494
        end;
clasohm@1147
   495
clasohm@1438
   496
    val (nt_count', prod_count', tags', xprods') =
clasohm@1147
   497
      prod_of xprods nt_count prod_count tags [];
clasohm@1147
   498
clasohm@1147
   499
    val dummy = writeln "Building new grammar...";
clasohm@1147
   500
clasohm@1438
   501
    (*Copy array containing productions of old grammar;
clasohm@1438
   502
      this has to be done to preserve the old grammar while being able
clasohm@1438
   503
      to change the array's content*)
clasohm@1147
   504
    val prods' =
clasohm@1147
   505
      let fun get_prod i = if i < nt_count then Array.sub (prods, i)
clasohm@1147
   506
                           else (([], []), []);
clasohm@1147
   507
      in Array.tabulate (nt_count', get_prod) end;
clasohm@1147
   508
clasohm@1147
   509
    val fromto_chains = inverse_chains chains [];
clasohm@1147
   510
clasohm@1438
   511
    (*Add new productions to old ones*)
clasohm@1147
   512
    val (fromto_chains', lambdas', _) =
clasohm@1438
   513
      add_prods prods' fromto_chains lambdas None xprods';
clasohm@1147
   514
clasohm@1147
   515
    val chains' = inverse_chains fromto_chains' [];
clasohm@1177
   516
  in Gram {nt_count = nt_count', prod_count = prod_count', tags = tags',
clasohm@1147
   517
           chains = chains', lambdas = lambdas', prods = prods'}
wenzelm@18
   518
  end;
wenzelm@18
   519
wenzelm@18
   520
clasohm@1438
   521
(*Merge two grammars*)
clasohm@1147
   522
fun merge_grams gram_a gram_b =
clasohm@1147
   523
  let
clasohm@1147
   524
    val dummy = writeln "Building new grammar...";
clasohm@1147
   525
clasohm@1147
   526
    (*find out which grammar is bigger*)
clasohm@1147
   527
    val (Gram {nt_count = nt_count1, prod_count = prod_count1, tags = tags1,
clasohm@1147
   528
               chains = chains1, lambdas = lambdas1, prods = prods1},
clasohm@1147
   529
         Gram {nt_count = nt_count2, prod_count = prod_count2, tags = tags2,
clasohm@1147
   530
               chains = chains2, lambdas = lambdas2, prods = prods2}) =
clasohm@1147
   531
      let val Gram {prod_count = count_a, ...} = gram_a;
clasohm@1147
   532
          val Gram {prod_count = count_b, ...} = gram_b;
clasohm@1147
   533
      in if count_a > count_b then (gram_a, gram_b)
clasohm@1147
   534
                              else (gram_b, gram_a)
clasohm@1147
   535
      end;
clasohm@1147
   536
clasohm@1147
   537
    (*get existing tag from grammar1 or create a new one*)
clasohm@1147
   538
    fun get_tag nt_count tags nt =
clasohm@1147
   539
      case Symtab.lookup (tags, nt) of
clasohm@1147
   540
        Some tag => (nt_count, tags, tag)
clasohm@1147
   541
      | None => (nt_count+1, Symtab.update_new ((nt, nt_count), tags),
clasohm@1147
   542
                nt_count)
clasohm@1147
   543
clasohm@1147
   544
    val ((nt_count1', tags1'), tag_table) =
clasohm@1147
   545
      let val tag_list = Symtab.dest tags2;
clasohm@1147
   546
clasohm@1147
   547
          val table = Array.array (nt_count2, ~1);
clasohm@1147
   548
clasohm@1147
   549
          fun store_tag nt_count tags ~1 = (nt_count, tags)
clasohm@1147
   550
            | store_tag nt_count tags tag =
clasohm@1147
   551
              let val (nt_count', tags', tag') =
clasohm@1147
   552
                   get_tag nt_count tags
clasohm@1147
   553
                     (fst (the (find_first (fn (n, t) => t = tag) tag_list)));
clasohm@1147
   554
              in Array.update (table, tag, tag');
clasohm@1147
   555
                 store_tag nt_count' tags' (tag-1)
clasohm@1147
   556
              end;
clasohm@1147
   557
      in (store_tag nt_count1 tags1 (nt_count2-1), table) end;
clasohm@1147
   558
    
clasohm@1147
   559
    (*convert grammar2 tag to grammar1 tag*)
clasohm@1147
   560
    fun convert_tag tag = Array.sub (tag_table, tag);
clasohm@1147
   561
clasohm@1147
   562
    (*convert chain list to raw productions*)
clasohm@1147
   563
    fun mk_chain_prods [] result = result
clasohm@1147
   564
      | mk_chain_prods ((to, froms) :: cs) result =
clasohm@1147
   565
        let
clasohm@1147
   566
          val to_tag = convert_tag to;
clasohm@1147
   567
clasohm@1147
   568
          fun make [] result = result
clasohm@1147
   569
            | make (from :: froms) result = make froms ((to_tag,
clasohm@1147
   570
                ([Nonterminal (convert_tag from, ~1)], "", ~1)) :: result);
clasohm@1147
   571
        in mk_chain_prods cs (make froms [] @ result) end;
clasohm@1147
   572
        
clasohm@1147
   573
    val chain_prods = mk_chain_prods chains2 [];
clasohm@1147
   574
clasohm@1147
   575
    (*convert prods2 array to productions*)
clasohm@1147
   576
    fun process_nt ~1 result = result
clasohm@1147
   577
      | process_nt nt result =
clasohm@1147
   578
        let
clasohm@1147
   579
          val nt_prods = foldl (op union)
clasohm@1147
   580
                             ([], map snd (snd (Array.sub (prods2, nt))));
clasohm@1147
   581
          val lhs_tag = convert_tag nt;
clasohm@1147
   582
clasohm@1147
   583
          (*convert tags in rhs*)
clasohm@1147
   584
          fun process_rhs [] result = result
clasohm@1147
   585
            | process_rhs (Terminal tk :: rhs) result =
clasohm@1147
   586
                process_rhs rhs (result @ [Terminal tk])
clasohm@1147
   587
            | process_rhs (Nonterminal (nt, prec) :: rhs) result =
clasohm@1147
   588
                process_rhs rhs
clasohm@1147
   589
                            (result @ [Nonterminal (convert_tag nt, prec)]);
clasohm@1147
   590
clasohm@1147
   591
          (*convert tags in productions*)
clasohm@1147
   592
          fun process_prods [] result = result
clasohm@1147
   593
            | process_prods ((rhs, id, prec) :: ps) result =
clasohm@1147
   594
                process_prods ps ((lhs_tag, (process_rhs rhs [], id, prec))
clasohm@1147
   595
                                  :: result);
clasohm@1147
   596
        in process_nt (nt-1) (process_prods nt_prods [] @ result) end;
clasohm@1147
   597
clasohm@1147
   598
    val raw_prods = chain_prods @ process_nt (nt_count2-1) [];
clasohm@1147
   599
clasohm@1147
   600
    val prods1' =
clasohm@1147
   601
      let fun get_prod i = if i < nt_count1 then Array.sub (prods1, i)
clasohm@1147
   602
                           else (([], []), []);
clasohm@1147
   603
      in Array.tabulate (nt_count1', get_prod) end;
clasohm@1147
   604
clasohm@1147
   605
    val fromto_chains = inverse_chains chains1 [];
clasohm@1147
   606
clasohm@1147
   607
    val (fromto_chains', lambdas', Some prod_count1') =
clasohm@1147
   608
      add_prods prods1' fromto_chains lambdas1 (Some prod_count1) raw_prods;
clasohm@1147
   609
clasohm@1147
   610
    val chains' = inverse_chains fromto_chains' [];
clasohm@1147
   611
  in Gram {nt_count = nt_count1', prod_count = prod_count1',
clasohm@1147
   612
           tags = tags1', chains = chains', lambdas = lambdas',
clasohm@1147
   613
           prods = prods1'}
clasohm@1147
   614
  end;
clasohm@1147
   615
wenzelm@18
   616
clasohm@1438
   617
(** Parser **)
wenzelm@18
   618
wenzelm@237
   619
datatype parsetree =
wenzelm@237
   620
  Node of string * parsetree list |
wenzelm@237
   621
  Tip of token;
wenzelm@237
   622
wenzelm@18
   623
type state =
clasohm@1147
   624
  nt_tag * int *                (*identification and production precedence*)
clasohm@1147
   625
  parsetree list *              (*already parsed nonterminals on rhs*)
clasohm@1147
   626
  symb list *                   (*rest of rhs*)
clasohm@1147
   627
  string *                      (*name of production*)
clasohm@1147
   628
  int;                          (*index for previous state list*)
wenzelm@18
   629
wenzelm@18
   630
clasohm@330
   631
(*Get all rhss with precedence >= minPrec*)
clasohm@330
   632
fun getRHS minPrec = filter (fn (_, _, prec:int) => prec >= minPrec);
wenzelm@18
   633
clasohm@330
   634
(*Get all rhss with precedence >= minPrec and < maxPrec*)
clasohm@330
   635
fun getRHS' minPrec maxPrec =
clasohm@330
   636
  filter (fn (_, _, prec:int) => prec >= minPrec andalso prec < maxPrec);
wenzelm@237
   637
clasohm@330
   638
(*Make states using a list of rhss*)
clasohm@330
   639
fun mkStates i minPrec lhsID rhss =
clasohm@330
   640
  let fun mkState (rhs, id, prodPrec) = (lhsID, prodPrec, [], rhs, id, i);
clasohm@330
   641
  in map mkState rhss end;
clasohm@697
   642
clasohm@330
   643
(*Add parse tree to list and eliminate duplicates 
clasohm@330
   644
  saving the maximum precedence*)
clasohm@330
   645
fun conc (t, prec:int) [] = (None, [(t, prec)])
clasohm@330
   646
  | conc (t, prec) ((t', prec') :: ts) =
clasohm@330
   647
      if t = t' then
clasohm@330
   648
        (Some prec', if prec' >= prec then (t', prec') :: ts 
clasohm@330
   649
                     else (t, prec) :: ts)
clasohm@330
   650
      else
clasohm@330
   651
        let val (n, ts') = conc (t, prec) ts
clasohm@330
   652
        in (n, (t', prec') :: ts') end;
wenzelm@18
   653
clasohm@330
   654
(*Update entry in used*)
clasohm@697
   655
fun update_trees ((B, (i, ts)) :: used) (A, t) =
wenzelm@237
   656
  if A = B then
wenzelm@237
   657
    let val (n, ts') = conc t ts
wenzelm@237
   658
    in ((A, (i, ts')) :: used, n) end
wenzelm@237
   659
  else
clasohm@697
   660
    let val (used', n) = update_trees used (A, t)
wenzelm@237
   661
    in ((B, (i, ts)) :: used', n) end;
wenzelm@18
   662
clasohm@330
   663
(*Replace entry in used*)
clasohm@697
   664
fun update_prec (A, prec) used =
clasohm@697
   665
  let fun update ((hd as (B, (_, ts))) :: used, used') =
clasohm@330
   666
        if A = B
clasohm@330
   667
        then used' @ ((A, (prec, ts)) :: used)
clasohm@330
   668
        else update (used, hd :: used')
clasohm@330
   669
  in update (used, []) end;
wenzelm@18
   670
clasohm@330
   671
fun getS A maxPrec Si =
wenzelm@237
   672
  filter
clasohm@1147
   673
    (fn (_, _, _, Nonterminal (B, prec) :: _, _, _)
clasohm@330
   674
          => A = B andalso prec <= maxPrec
wenzelm@237
   675
      | _ => false) Si;
wenzelm@18
   676
clasohm@330
   677
fun getS' A maxPrec minPrec Si =
wenzelm@237
   678
  filter
clasohm@1147
   679
    (fn (_, _, _, Nonterminal (B, prec) :: _, _, _)
clasohm@330
   680
          => A = B andalso prec > minPrec andalso prec <= maxPrec
wenzelm@237
   681
      | _ => false) Si;
wenzelm@18
   682
clasohm@330
   683
fun getStates Estate i ii A maxPrec =
wenzelm@237
   684
  filter
clasohm@1147
   685
    (fn (_, _, _, Nonterminal (B, prec) :: _, _, _)
clasohm@330
   686
          => A = B andalso prec <= maxPrec
wenzelm@237
   687
      | _ => false)
wenzelm@237
   688
    (Array.sub (Estate, ii));
wenzelm@18
   689
wenzelm@18
   690
clasohm@1147
   691
fun movedot_term (A, j, ts, Terminal a :: sa, id, i) c =
wenzelm@237
   692
  if valued_token c then
clasohm@697
   693
    (A, j, ts @ [Tip c], sa, id, i)
wenzelm@237
   694
  else (A, j, ts, sa, id, i);
wenzelm@18
   695
clasohm@1147
   696
fun movedot_nonterm ts (A, j, tss, Nonterminal _ :: sa, id, i) =
wenzelm@237
   697
  (A, j, tss @ ts, sa, id, i);
wenzelm@18
   698
wenzelm@237
   699
fun movedot_lambda _ [] = []
clasohm@1147
   700
  | movedot_lambda (B, j, tss, Nonterminal (A, k) :: sa, id, i) ((t, ki) :: ts) =
wenzelm@237
   701
      if k <= ki then
wenzelm@237
   702
        (B, j, tss @ t, sa, id, i) ::
clasohm@1147
   703
          movedot_lambda (B, j, tss, Nonterminal (A, k) :: sa, id, i) ts
clasohm@1147
   704
      else movedot_lambda (B, j, tss, Nonterminal (A, k) :: sa, id, i) ts;
wenzelm@18
   705
wenzelm@18
   706
clasohm@1147
   707
val warned = ref false;                            (*flag for warning message*)
clasohm@1147
   708
val branching_level = ref 200;                   (*trigger value for warnings*)
wenzelm@18
   709
clasohm@1147
   710
(*get all productions of a NT and NTs chained to it which can
clasohm@1147
   711
  be started by specified token*)
clasohm@1147
   712
fun prods_for prods chains include_none tk nts =
clasohm@1147
   713
let (*similar to token_assoc but does not automatically include 'None' key*)
clasohm@1147
   714
    fun token_assoc2 (list, key) =
clasohm@1147
   715
      let fun assoc [] result = result
clasohm@1147
   716
            | assoc ((keyi, pi) :: pairs) result =
clasohm@1147
   717
                if is_some keyi andalso matching_tokens (the keyi, key)
clasohm@1147
   718
                   orelse include_none andalso is_none keyi then 
clasohm@1147
   719
                  assoc pairs (pi @ result)
clasohm@1147
   720
                else assoc pairs result;
clasohm@1147
   721
      in assoc list [] end;
clasohm@1147
   722
clasohm@1147
   723
    fun get_prods [] result = result
clasohm@1147
   724
      | get_prods (nt :: nts) result =
clasohm@1147
   725
        let val nt_prods = snd (Array.sub (prods, nt));
clasohm@1147
   726
        in get_prods nts ((token_assoc2 (nt_prods, tk)) @ result) end;
clasohm@1147
   727
in get_prods (connected_with chains nts nts) [] end;
clasohm@1147
   728
clasohm@1147
   729
clasohm@1147
   730
fun PROCESSS prods chains Estate i c states =
wenzelm@18
   731
let
clasohm@1147
   732
fun all_prods_for nt = prods_for prods chains true c [nt];
clasohm@330
   733
wenzelm@237
   734
fun processS used [] (Si, Sii) = (Si, Sii)
wenzelm@237
   735
  | processS used (S :: States) (Si, Sii) =
wenzelm@237
   736
      (case S of
clasohm@1147
   737
        (_, _, _, Nonterminal (nt, minPrec) :: _, _, _) =>
clasohm@330
   738
          let                                       (*predictor operation*)
clasohm@697
   739
            val (used', new_states) =
clasohm@1147
   740
              (case assoc (used, nt) of
clasohm@330
   741
                Some (usedPrec, l) =>       (*nonterminal has been processed*)
clasohm@330
   742
                  if usedPrec <= minPrec then
clasohm@330
   743
                                      (*wanted precedence has been processed*)
clasohm@330
   744
                    (used, movedot_lambda S l)
clasohm@330
   745
                  else            (*wanted precedence hasn't been parsed yet*)
clasohm@1147
   746
                    let
clasohm@1147
   747
                      val tk_prods = all_prods_for nt;
clasohm@1147
   748
                      
clasohm@1147
   749
                      val States' = mkStates i minPrec nt
clasohm@1147
   750
                                      (getRHS' minPrec usedPrec tk_prods);
clasohm@1147
   751
                    in (update_prec (nt, minPrec) used, 
clasohm@330
   752
                        movedot_lambda S l @ States')
wenzelm@237
   753
                    end
wenzelm@18
   754
clasohm@330
   755
              | None =>           (*nonterminal is parsed for the first time*)
clasohm@1147
   756
                  let val tk_prods = all_prods_for nt;
clasohm@1147
   757
                      val States' = mkStates i minPrec nt
clasohm@1147
   758
                                      (getRHS minPrec tk_prods);
clasohm@1147
   759
                  in ((nt, (minPrec, [])) :: used, States') end);
clasohm@697
   760
clasohm@1147
   761
            val dummy =
clasohm@1147
   762
              if not (!warned) andalso
clasohm@1147
   763
                 length (new_states @ States) > (!branching_level) then
clasohm@1147
   764
                (writeln "Warning: Currently parsed expression could be \
clasohm@1147
   765
                         \extremely ambiguous.";
clasohm@1147
   766
                 warned := true)
clasohm@1147
   767
              else ();
wenzelm@237
   768
          in
clasohm@697
   769
            processS used' (new_states @ States) (S :: Si, Sii)
wenzelm@237
   770
          end
clasohm@1147
   771
      | (_, _, _, Terminal a :: _, _, _) =>               (*scanner operation*)
wenzelm@237
   772
          processS used States
wenzelm@237
   773
            (S :: Si,
wenzelm@237
   774
              if matching_tokens (a, c) then movedot_term S c :: Sii else Sii)
clasohm@330
   775
      | (A, prec, ts, [], id, j) =>                   (*completer operation*)
clasohm@697
   776
          let val tt = if id = "" then ts else [Node (id, ts)] in
clasohm@330
   777
            if j = i then                             (*lambda production?*)
wenzelm@237
   778
              let
clasohm@697
   779
                val (used', O) = update_trees used (A, (tt, prec));
wenzelm@237
   780
              in
clasohm@1147
   781
                case O of
wenzelm@237
   782
                  None =>
clasohm@1147
   783
                    let val Slist = getS A prec Si;
clasohm@1147
   784
                        val States' = map (movedot_nonterm tt) Slist;
clasohm@1147
   785
                    in processS used' (States' @ States) (S :: Si, Sii) end
wenzelm@237
   786
                | Some n =>
clasohm@1147
   787
                    if n >= prec then processS used' States (S :: Si, Sii)
wenzelm@237
   788
                    else
clasohm@1147
   789
                      let val Slist = getS' A prec n Si;
clasohm@1147
   790
                          val States' = map (movedot_nonterm tt) Slist;
clasohm@1147
   791
                      in processS used' (States' @ States) (S :: Si, Sii) end
clasohm@330
   792
              end 
wenzelm@237
   793
            else
clasohm@1147
   794
              let val Slist = getStates Estate i j A prec
clasohm@1147
   795
              in processS used (map (movedot_nonterm tt) Slist @ States)
clasohm@1147
   796
                          (S :: Si, Sii)
clasohm@682
   797
              end
wenzelm@237
   798
          end)
clasohm@682
   799
in processS [] states ([], []) end;
wenzelm@18
   800
wenzelm@18
   801
clasohm@362
   802
fun syntax_error toks allowed =
clasohm@362
   803
  error 
clasohm@362
   804
  ((if toks = [] then
clasohm@362
   805
      "error: unexpected end of input\n"
clasohm@362
   806
    else
clasohm@367
   807
      "Syntax error at: " ^ quote (space_implode " " (map str_of_token 
clasohm@367
   808
        ((rev o tl o rev) toks)))
clasohm@362
   809
      ^ "\n")
clasohm@362
   810
   ^ "Expected tokens: " 
clasohm@362
   811
   ^ space_implode ", " (map (quote o str_of_token) allowed));
wenzelm@18
   812
clasohm@1147
   813
fun produce prods chains stateset i indata prev_token =
clasohm@1147
   814
                                      (*prev_token is used for error messages*)
wenzelm@237
   815
  (case Array.sub (stateset, i) of
clasohm@1147
   816
    [] => let fun some_prods_for tk nt = prods_for prods chains false tk [nt];
clasohm@373
   817
clasohm@373
   818
              (*test if tk is a lookahead for a given minimum precedence*)
clasohm@1147
   819
              fun reduction _ minPrec _ (Terminal _ :: _, _, prec:int) =
clasohm@373
   820
                    if prec >= minPrec then true
clasohm@373
   821
                    else false
clasohm@1147
   822
                | reduction tk minPrec checked 
clasohm@1147
   823
                            (Nonterminal (nt, nt_prec) :: _, _, prec) =
clasohm@1147
   824
                  if prec >= minPrec andalso not (nt mem checked) then
clasohm@1147
   825
                    let val chained = connected_with chains [nt] [nt];
clasohm@1147
   826
                    in exists
clasohm@1147
   827
                         (reduction tk nt_prec (chained @ checked))
clasohm@1147
   828
                         (some_prods_for tk nt)
clasohm@1147
   829
                    end
clasohm@1147
   830
                  else false;
clasohm@373
   831
clasohm@373
   832
              (*compute a list of allowed starting tokens 
clasohm@373
   833
                for a list of nonterminals considering precedence*)
clasohm@1147
   834
              fun get_starts [] result = result
clasohm@1147
   835
                | get_starts ((nt, minPrec:int) :: nts) result =
clasohm@1147
   836
                  let fun get [] result = result
clasohm@1147
   837
                        | get ((Some tk, prods) :: ps) result =
clasohm@1147
   838
                            if not (null prods) andalso
clasohm@1147
   839
                               exists (reduction tk minPrec [nt]) prods
clasohm@1147
   840
                            then get ps (tk :: result)
clasohm@1147
   841
                            else get ps result
clasohm@1147
   842
                        | get ((None, _) :: ps) result = get ps result;
clasohm@362
   843
clasohm@1147
   844
                      val (_, nt_prods) = Array.sub (prods, nt);
clasohm@1147
   845
clasohm@1147
   846
                      val chained = map (fn nt => (nt, minPrec))
clasohm@1147
   847
                                        (assocs chains nt);
clasohm@1147
   848
                  in get_starts (chained @ nts)
clasohm@1147
   849
                                ((get nt_prods []) union result)
clasohm@1147
   850
                  end;
clasohm@1147
   851
clasohm@1147
   852
              val nts =
clasohm@1147
   853
                mapfilter (fn (_, _, _, Nonterminal (a, prec) :: _, _, _) => 
clasohm@1147
   854
                           Some (a, prec) | _ => None)
clasohm@1147
   855
                          (Array.sub (stateset, i-1));
clasohm@1147
   856
              val allowed =
clasohm@1147
   857
                distinct (get_starts nts [] @
clasohm@1147
   858
                  (mapfilter (fn (_, _, _, Terminal a :: _, _, _) => Some a
clasohm@1147
   859
                               | _ => None)
clasohm@1147
   860
                             (Array.sub (stateset, i-1))));
clasohm@362
   861
          in syntax_error (if prev_token = EndToken then indata
clasohm@362
   862
                           else prev_token :: indata) allowed
clasohm@362
   863
          end
wenzelm@237
   864
  | s =>
wenzelm@237
   865
    (case indata of
clasohm@1147
   866
       [] => Array.sub (stateset, i)
clasohm@1147
   867
     | c :: cs =>
clasohm@1147
   868
       let val (si, sii) = PROCESSS prods chains stateset i c s;
clasohm@1147
   869
       in Array.update (stateset, i, si);
clasohm@1147
   870
          Array.update (stateset, i + 1, sii);
clasohm@1147
   871
          produce prods chains stateset (i + 1) cs c
clasohm@1147
   872
       end));
wenzelm@18
   873
wenzelm@18
   874
wenzelm@237
   875
val get_trees = mapfilter (fn (_, _, [pt], _, _, _) => Some pt | _ => None);
wenzelm@237
   876
wenzelm@18
   877
clasohm@1147
   878
fun earley prods tags chains startsymbol indata =
wenzelm@237
   879
  let
clasohm@1147
   880
    val start_tag = case Symtab.lookup (tags, startsymbol) of
clasohm@1147
   881
                       Some tag => tag
clasohm@624
   882
                     | None   => error ("parse: Unknown startsymbol " ^ 
clasohm@624
   883
                                        quote startsymbol);
clasohm@1147
   884
    val S0 = [(~1, 0, [], [Nonterminal (start_tag, 0), Terminal EndToken],
clasohm@1147
   885
               "", 0)];
clasohm@330
   886
    val s = length indata + 1;
wenzelm@237
   887
    val Estate = Array.array (s, []);
wenzelm@237
   888
  in
wenzelm@237
   889
    Array.update (Estate, 0, S0);
clasohm@1147
   890
    warned := false;
clasohm@1147
   891
    get_trees (produce prods chains Estate 0 indata EndToken)
wenzelm@237
   892
  end;
wenzelm@18
   893
wenzelm@18
   894
clasohm@1147
   895
fun parse (Gram {tags, prods, chains, ...}) start toks =
clasohm@624
   896
let val r =
clasohm@1147
   897
  (case earley prods tags chains start toks of
wenzelm@237
   898
    [] => sys_error "parse: no parse trees"
clasohm@330
   899
  | pts => pts);
clasohm@624
   900
in r end
wenzelm@18
   901
wenzelm@18
   902
end;