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