src/Pure/Isar/locale.ML
author ballarin
Thu Jul 07 15:52:31 2005 +0200 (2005-07-07)
changeset 16736 1e792b32abef
parent 16620 2a7f46324218
child 16787 b6b6e2faaa41
permissions -rw-r--r--
Preparations for interpretation of locales in locales.
wenzelm@12014
     1
(*  Title:      Pure/Isar/locale.ML
wenzelm@11896
     2
    ID:         $Id$
ballarin@15206
     3
    Author:     Clemens Ballarin, TU Muenchen; Markus Wenzel, LMU/TU Muenchen
wenzelm@11896
     4
wenzelm@12058
     5
Locales -- Isar proof contexts as meta-level predicates, with local
wenzelm@12529
     6
syntax and implicit structures.
wenzelm@12529
     7
ballarin@14215
     8
Draws some basic ideas from Florian Kammueller's original version of
wenzelm@12529
     9
locales, but uses the richer infrastructure of Isar instead of the raw
wenzelm@12529
    10
meta-logic.  Furthermore, we provide structured import of contexts
ballarin@14215
    11
(with merge and rename operations), as well as type-inference of the
wenzelm@13375
    12
signature parts, and predicate definitions of the specification text.
ballarin@14446
    13
ballarin@14446
    14
See also:
ballarin@14446
    15
ballarin@14446
    16
[1] Clemens Ballarin. Locales and Locale Expressions in Isabelle/Isar.
ballarin@14446
    17
    In Stefano Berardi et al., Types for Proofs and Programs: International
ballarin@15099
    18
    Workshop, TYPES 2003, Torino, Italy, LNCS 3085, pages 34-50, 2004.
wenzelm@11896
    19
*)
wenzelm@11896
    20
ballarin@16169
    21
(* TODO:
ballarin@16169
    22
- beta-eta normalisation of interpretation parameters
ballarin@16169
    23
- dangling type frees in locales
ballarin@16620
    24
- test subsumption of interpretations when merging theories
ballarin@16169
    25
*)
ballarin@16169
    26
wenzelm@11896
    27
signature LOCALE =
wenzelm@11896
    28
sig
wenzelm@12046
    29
  type context
wenzelm@15703
    30
  datatype ('typ, 'term, 'fact) elem =
wenzelm@12058
    31
    Fixes of (string * 'typ option * mixfix option) list |
ballarin@16169
    32
    Constrains of (string * 'typ) list |
wenzelm@15703
    33
    Assumes of ((string * Attrib.src list) * ('term * ('term list * 'term list)) list) list |
wenzelm@15703
    34
    Defines of ((string * Attrib.src list) * ('term * 'term list)) list |
wenzelm@15703
    35
    Notes of ((string * Attrib.src list) * ('fact * Attrib.src list) list) list
wenzelm@12273
    36
  datatype expr =
wenzelm@12273
    37
    Locale of string |
ballarin@16102
    38
    Rename of expr * (string * mixfix option) option list |
wenzelm@12273
    39
    Merge of expr list
wenzelm@12273
    40
  val empty: expr
ballarin@15206
    41
  datatype 'a elem_expr = Elem of 'a | Expr of expr
ballarin@15206
    42
ballarin@15206
    43
  (* Abstract interface to locales *)
wenzelm@15703
    44
  type element
wenzelm@15703
    45
  type element_i
wenzelm@12046
    46
  type locale
wenzelm@16458
    47
  val intern: theory -> xstring -> string
wenzelm@16458
    48
  val extern: theory -> string -> xstring
wenzelm@12502
    49
  val the_locale: theory -> string -> locale
wenzelm@15703
    50
  val intern_attrib_elem: theory ->
wenzelm@15703
    51
    ('typ, 'term, 'fact) elem -> ('typ, 'term, 'fact) elem
wenzelm@15703
    52
  val intern_attrib_elem_expr: theory ->
wenzelm@15703
    53
    ('typ, 'term, 'fact) elem elem_expr -> ('typ, 'term, 'fact) elem elem_expr
ballarin@15206
    54
ballarin@15596
    55
  (* Processing of locale statements *)
wenzelm@15703
    56
  val read_context_statement: xstring option -> element elem_expr list ->
wenzelm@12529
    57
    (string * (string list * string list)) list list -> context ->
ballarin@15206
    58
    string option * (cterm list * cterm list) * context * context * 
ballarin@15206
    59
      (term * (term list * term list)) list list
wenzelm@15703
    60
  val cert_context_statement: string option -> element_i elem_expr list ->
wenzelm@12529
    61
    (term * (term list * term list)) list list -> context ->
ballarin@15206
    62
    string option * (cterm list * cterm list) * context * context *
ballarin@15206
    63
      (term * (term list * term list)) list list
ballarin@15596
    64
ballarin@15596
    65
  (* Diagnostic functions *)
wenzelm@12758
    66
  val print_locales: theory -> unit
wenzelm@15703
    67
  val print_locale: theory -> expr -> element list -> unit
ballarin@15624
    68
  val print_global_registrations: string -> theory -> unit
wenzelm@15703
    69
  val print_local_registrations': string -> context -> unit
ballarin@15624
    70
  val print_local_registrations: string -> context -> unit
ballarin@15596
    71
ballarin@15696
    72
  (* Storing results *)
wenzelm@15703
    73
  val add_locale: bool -> bstring -> expr -> element list -> theory -> theory
wenzelm@15703
    74
  val add_locale_i: bool -> bstring -> expr -> element_i list -> theory -> theory
wenzelm@15703
    75
  val smart_note_thmss: string -> string option ->
wenzelm@12958
    76
    ((bstring * theory attribute list) * (thm list * theory attribute list) list) list ->
wenzelm@12958
    77
    theory -> theory * (bstring * thm list) list
wenzelm@15703
    78
  val note_thmss: string -> xstring ->
wenzelm@15703
    79
    ((bstring * Attrib.src list) * (thmref * Attrib.src list) list) list ->
wenzelm@12711
    80
    theory -> theory * (bstring * thm list) list
wenzelm@15703
    81
  val note_thmss_i: string -> string ->
wenzelm@15703
    82
    ((bstring * Attrib.src list) * (thm list * Attrib.src list) list) list ->
wenzelm@12711
    83
    theory -> theory * (bstring * thm list) list
wenzelm@15703
    84
  val add_thmss: string -> string -> ((string * thm list) * Attrib.src list) list ->
wenzelm@13375
    85
    theory * context -> (theory * context) * (string * thm list) list
ballarin@15596
    86
ballarin@15624
    87
  (* Locale interpretation *)
ballarin@15624
    88
  val prep_global_registration:
wenzelm@15703
    89
    string * Attrib.src list -> expr -> string option list -> theory ->
ballarin@15596
    90
    theory * ((string * term list) * term list) list * (theory -> theory)
ballarin@16736
    91
(*
ballarin@16736
    92
  val prep_registration_in_locale:
ballarin@16736
    93
    string -> expr -> string option list -> theory ->
ballarin@16736
    94
*)
ballarin@15624
    95
  val prep_local_registration:
wenzelm@15703
    96
    string * Attrib.src list -> expr -> string option list -> context ->
ballarin@15624
    97
    context * ((string * term list) * term list) list * (context -> context)
ballarin@15624
    98
  val add_global_witness:
ballarin@15596
    99
    string * term list -> thm -> theory -> theory
ballarin@15624
   100
  val add_local_witness:
ballarin@15624
   101
    string * term list -> thm -> context -> context
wenzelm@11896
   102
end;
wenzelm@12839
   103
wenzelm@12289
   104
structure Locale: LOCALE =
wenzelm@11896
   105
struct
wenzelm@11896
   106
wenzelm@12273
   107
(** locale elements and expressions **)
wenzelm@11896
   108
wenzelm@12014
   109
type context = ProofContext.context;
wenzelm@11896
   110
wenzelm@15703
   111
datatype ('typ, 'term, 'fact) elem =
wenzelm@12058
   112
  Fixes of (string * 'typ option * mixfix option) list |
ballarin@16169
   113
  Constrains of (string * 'typ) list |
wenzelm@15703
   114
  Assumes of ((string * Attrib.src list) * ('term * ('term list * 'term list)) list) list |
wenzelm@15703
   115
  Defines of ((string * Attrib.src list) * ('term * 'term list)) list |
wenzelm@15703
   116
  Notes of ((string * Attrib.src list) * ('fact * Attrib.src list) list) list;
wenzelm@12273
   117
wenzelm@12273
   118
datatype expr =
wenzelm@12273
   119
  Locale of string |
ballarin@16102
   120
  Rename of expr * (string * mixfix option) option list |
wenzelm@12273
   121
  Merge of expr list;
wenzelm@11896
   122
wenzelm@12273
   123
val empty = Merge [];
wenzelm@12273
   124
ballarin@15206
   125
datatype 'a elem_expr =
ballarin@15206
   126
  Elem of 'a | Expr of expr;
wenzelm@12273
   127
wenzelm@15703
   128
type element = (string, string, thmref) elem;
wenzelm@15703
   129
type element_i = (typ, term, thm list) elem;
wenzelm@12070
   130
wenzelm@12070
   131
type locale =
ballarin@15206
   132
 {predicate: cterm list * thm list,
ballarin@16736
   133
    (* CB: For locales with "(open)" this entry is ([], []).
ballarin@15206
   134
       For new-style locales, which declare predicates, if the locale declares
ballarin@15206
   135
       no predicates, this is also ([], []).
ballarin@15206
   136
       If the locale declares predicates, the record field is
ballarin@15206
   137
       ([statement], axioms), where statement is the locale predicate applied
ballarin@15206
   138
       to the (assumed) locale parameters.  Axioms contains the projections
ballarin@15206
   139
       from the locale predicate to the normalised assumptions of the locale
ballarin@15206
   140
       (cf. [1], normalisation of locale expressions.)
ballarin@15206
   141
    *)
ballarin@15206
   142
  import: expr,                                       (*dynamic import*)
wenzelm@15703
   143
  elems: (element_i * stamp) list,                    (*static content*)
ballarin@16736
   144
  params: ((string * typ) * mixfix option) list * string list,
ballarin@16102
   145
                                                      (*all/local params*)
ballarin@16736
   146
  regs: ((string * string list) * thm list) list}
ballarin@16736
   147
    (* Registrations: indentifiers and witness theorems of locales interpreted
ballarin@16736
   148
       in the locale.
ballarin@16736
   149
    *)
wenzelm@12063
   150
wenzelm@11896
   151
wenzelm@15703
   152
(* CB: an internal (Int) locale element was either imported or included,
wenzelm@15703
   153
   an external (Ext) element appears directly in the locale text. *)
wenzelm@15703
   154
wenzelm@15703
   155
datatype ('a, 'b) int_ext = Int of 'a | Ext of 'b;
wenzelm@15703
   156
wenzelm@15703
   157
wenzelm@15703
   158
ballarin@15837
   159
(** term and type instantiation, using symbol tables **)
ballarin@16620
   160
(** functions for term instantiation beta-reduce the result
ballarin@16620
   161
    unless the instantiation table is empty (inst_tab_term)
ballarin@16620
   162
    or the instantiation has no effect (inst_tab_thm) **)
ballarin@15837
   163
ballarin@15837
   164
(* instantiate TFrees *)
ballarin@15837
   165
ballarin@15837
   166
fun tinst_tab_type tinst T = if Symtab.is_empty tinst
ballarin@15837
   167
      then T
ballarin@15837
   168
      else Term.map_type_tfree
ballarin@15837
   169
        (fn (v as (x, _)) => getOpt (Symtab.lookup (tinst, x), (TFree v))) T;
ballarin@15837
   170
ballarin@15837
   171
fun tinst_tab_term tinst t = if Symtab.is_empty tinst
ballarin@15837
   172
      then t
ballarin@15837
   173
      else Term.map_term_types (tinst_tab_type tinst) t;
ballarin@15837
   174
wenzelm@16458
   175
fun tinst_tab_thm thy tinst thm = if Symtab.is_empty tinst
ballarin@15837
   176
      then thm
ballarin@15837
   177
      else let
wenzelm@16458
   178
          val cert = Thm.cterm_of thy;
wenzelm@16458
   179
          val certT = Thm.ctyp_of thy;
ballarin@15837
   180
          val {hyps, prop, ...} = Thm.rep_thm thm;
ballarin@15837
   181
          val tfrees = foldr Term.add_term_tfree_names [] (prop :: hyps);
ballarin@15837
   182
          val tinst' = Symtab.dest tinst |>
ballarin@15837
   183
                List.filter (fn (a, _) => a mem_string tfrees);
ballarin@15837
   184
        in
ballarin@15837
   185
          if null tinst' then thm
ballarin@15837
   186
          else thm |> Drule.implies_intr_list (map cert hyps)
ballarin@15837
   187
            |> Drule.tvars_intr_list (map #1 tinst')
ballarin@15837
   188
            |> (fn (th, al) => th |> Thm.instantiate
ballarin@15837
   189
                ((map (fn (a, T) => (certT (TVar (valOf (assoc (al, a)))), certT T)) tinst'),
ballarin@15837
   190
                  []))
ballarin@15837
   191
            |> (fn th => Drule.implies_elim_list th
ballarin@15837
   192
                 (map (Thm.assume o cert o tinst_tab_term tinst) hyps))
ballarin@15837
   193
        end;
ballarin@15837
   194
ballarin@15837
   195
ballarin@15837
   196
(* instantiate TFrees and Frees *)
ballarin@15837
   197
ballarin@15837
   198
fun inst_tab_term (inst, tinst) = if Symtab.is_empty inst
ballarin@15837
   199
      then tinst_tab_term tinst
ballarin@15837
   200
      else (* instantiate terms and types simultaneously *)
ballarin@15837
   201
        let
ballarin@15837
   202
          fun instf (Const (x, T)) = Const (x, tinst_tab_type tinst T)
ballarin@15837
   203
            | instf (Free (x, T)) = (case Symtab.lookup (inst, x) of
ballarin@15837
   204
                 NONE => Free (x, tinst_tab_type tinst T)
ballarin@15837
   205
               | SOME t => t)
ballarin@15837
   206
            | instf (Var (xi, T)) = Var (xi, tinst_tab_type tinst T)
ballarin@15837
   207
            | instf (b as Bound _) = b
ballarin@15837
   208
            | instf (Abs (x, T, t)) = Abs (x, tinst_tab_type tinst T, instf t)
ballarin@15837
   209
            | instf (s $ t) = instf s $ instf t
ballarin@16620
   210
        in Envir.beta_norm o instf end;
ballarin@15837
   211
wenzelm@16458
   212
fun inst_tab_thm thy (inst, tinst) thm = if Symtab.is_empty inst
wenzelm@16458
   213
      then tinst_tab_thm thy tinst thm
ballarin@15837
   214
      else let
wenzelm@16458
   215
          val cert = Thm.cterm_of thy;
wenzelm@16458
   216
          val certT = Thm.ctyp_of thy;
ballarin@15837
   217
          val {hyps, prop, ...} = Thm.rep_thm thm;
ballarin@15837
   218
          (* type instantiations *)
ballarin@15837
   219
          val tfrees = foldr Term.add_term_tfree_names [] (prop :: hyps);
ballarin@15837
   220
          val tinst' = Symtab.dest tinst |>
ballarin@15837
   221
                List.filter (fn (a, _) => a mem_string tfrees);
ballarin@15837
   222
          (* term instantiations;
ballarin@15837
   223
             note: lhss are type instantiated, because
ballarin@15837
   224
                   type insts will be done first*)
ballarin@15837
   225
          val frees = foldr Term.add_term_frees [] (prop :: hyps);
ballarin@15837
   226
          val inst' = Symtab.dest inst |>
ballarin@15837
   227
                List.mapPartial (fn (a, t) =>
ballarin@15837
   228
                  get_first (fn (Free (x, T)) => 
ballarin@15837
   229
                    if a = x then SOME (Free (x, tinst_tab_type tinst T), t)
ballarin@15837
   230
                    else NONE) frees);
ballarin@15837
   231
        in
wenzelm@16458
   232
          if null tinst' andalso null inst' then tinst_tab_thm thy tinst thm
ballarin@15837
   233
          else thm |> Drule.implies_intr_list (map cert hyps)
ballarin@15837
   234
            |> Drule.tvars_intr_list (map #1 tinst')
ballarin@15837
   235
            |> (fn (th, al) => th |> Thm.instantiate
ballarin@15837
   236
                ((map (fn (a, T) => (certT (TVar (valOf (assoc (al, a)))), certT T)) tinst'),
ballarin@15837
   237
                  []))
ballarin@15837
   238
            |> Drule.forall_intr_list (map (cert o #1) inst')
ballarin@15837
   239
            |> Drule.forall_elim_list (map (cert o #2) inst') 
ballarin@16620
   240
            |> Drule.fconv_rule (Thm.beta_conversion true)
ballarin@15837
   241
            |> (fn th => Drule.implies_elim_list th
ballarin@15837
   242
                 (map (Thm.assume o cert o inst_tab_term (inst, tinst)) hyps))
ballarin@15837
   243
        end;
ballarin@15837
   244
ballarin@15837
   245
ballarin@16736
   246
(** management of registrations in theories and proof contexts **)
wenzelm@11896
   247
ballarin@15837
   248
structure Registrations :
ballarin@15837
   249
  sig
ballarin@15837
   250
    type T
ballarin@15837
   251
    val empty: T
ballarin@15837
   252
    val join: T * T -> T
ballarin@15837
   253
    val dest: T -> (term list * ((string * Attrib.src list) * thm list)) list
wenzelm@16458
   254
    val lookup: theory -> T * term list ->
ballarin@15837
   255
      ((string * Attrib.src list) * thm list) option
wenzelm@16458
   256
    val insert: theory -> term list * (string * Attrib.src list) -> T ->
ballarin@15837
   257
      T * (term list * ((string * Attrib.src list) * thm list)) list
ballarin@15837
   258
    val add_witness: term list -> thm -> T -> T
ballarin@15837
   259
  end =
ballarin@15837
   260
struct
ballarin@15837
   261
  (* a registration consists of theorems instantiating locale assumptions
ballarin@15837
   262
     and prefix and attributes, indexed by parameter instantiation *)
ballarin@15837
   263
  type T = ((string * Attrib.src list) * thm list) Termtab.table;
ballarin@15837
   264
ballarin@15837
   265
  val empty = Termtab.empty;
ballarin@15837
   266
ballarin@15837
   267
  (* term list represented as single term, for simultaneous matching *)
ballarin@15837
   268
  fun termify ts =
ballarin@15837
   269
    Library.foldl (op $) (Const ("", map fastype_of ts ---> propT), ts);
ballarin@15837
   270
  fun untermify t =
ballarin@15837
   271
    let fun ut (Const _) ts = ts
ballarin@15837
   272
          | ut (s $ t) ts = ut s (t::ts)
ballarin@15837
   273
    in ut t [] end;
ballarin@15837
   274
ballarin@16620
   275
  (* joining of registrations: prefix and attributes of left theory,
ballarin@15837
   276
     thms are equal, no attempt to subsumption testing *)
wenzelm@16458
   277
  fun join (r1, r2) = Termtab.join (fn _ => fn (reg, _) => SOME reg) (r1, r2);
ballarin@15837
   278
ballarin@15837
   279
  fun dest regs = map (apfst untermify) (Termtab.dest regs);
ballarin@15837
   280
ballarin@15837
   281
  (* registrations that subsume t *)
ballarin@15837
   282
  fun subsumers tsig t regs =
ballarin@15837
   283
    List.filter (fn (t', _) => Pattern.matches tsig (t', t)) (Termtab.dest regs);
ballarin@15837
   284
ballarin@15837
   285
  (* look up registration, pick one that subsumes the query *)
ballarin@15837
   286
  fun lookup sign (regs, ts) =
ballarin@15837
   287
    let
ballarin@15837
   288
      val tsig = Sign.tsig_of sign;
ballarin@15837
   289
      val t = termify ts;
ballarin@15837
   290
      val subs = subsumers tsig t regs;
ballarin@15837
   291
    in (case subs of
ballarin@15837
   292
        [] => NONE
ballarin@15837
   293
      | ((t', (attn, thms)) :: _) => let
ballarin@15837
   294
            val (tinst, inst) = Pattern.match tsig (t', t);
ballarin@15837
   295
            (* thms contain Frees, not Vars *)
ballarin@15837
   296
            val tinst' = tinst |> Vartab.dest
ballarin@15837
   297
                 |> map (fn ((x, 0), (_, T)) => (x, Type.unvarifyT T))
ballarin@15837
   298
                 |> Symtab.make;
ballarin@15837
   299
            val inst' = inst |> Vartab.dest
ballarin@15837
   300
                 |> map (fn ((x, 0), (_, t)) => (x, Logic.unvarify t))
ballarin@15837
   301
                 |> Symtab.make;
ballarin@15837
   302
          in
ballarin@15837
   303
            SOME (attn, map (inst_tab_thm sign (inst', tinst')) thms)
ballarin@15837
   304
          end)
ballarin@15837
   305
    end;
ballarin@15837
   306
ballarin@15837
   307
  (* add registration if not subsumed by ones already present,
ballarin@15837
   308
     additionally returns registrations that are strictly subsumed *)
ballarin@15837
   309
  fun insert sign (ts, attn) regs =
ballarin@15837
   310
    let
ballarin@15837
   311
      val tsig = Sign.tsig_of sign;
ballarin@15837
   312
      val t = termify ts;
ballarin@15837
   313
      val subs = subsumers tsig t regs ;
ballarin@15837
   314
    in (case subs of
ballarin@15837
   315
        [] => let
ballarin@15837
   316
                val sups =
ballarin@15837
   317
                  List.filter (fn (t', _) => Pattern.matches tsig (t, t')) (Termtab.dest regs);
ballarin@15837
   318
                val sups' = map (apfst untermify) sups
ballarin@15837
   319
              in (Termtab.update ((t, (attn, [])), regs), sups') end
ballarin@15837
   320
      | _ => (regs, []))
ballarin@15837
   321
    end;
ballarin@15837
   322
ballarin@15837
   323
  (* add witness theorem to registration,
ballarin@16169
   324
     only if instantiation is exact, otherwise exception Option raised *)
ballarin@15837
   325
  fun add_witness ts thm regs =
ballarin@15837
   326
    let
ballarin@15837
   327
      val t = termify ts;
ballarin@15837
   328
      val (x, thms) = valOf (Termtab.lookup (regs, t));
ballarin@15837
   329
    in
ballarin@15837
   330
      Termtab.update ((t, (x, thm::thms)), regs)
ballarin@15837
   331
    end;
ballarin@15837
   332
end;
ballarin@15837
   333
ballarin@16736
   334
ballarin@15837
   335
(** theory data **)
ballarin@15596
   336
wenzelm@16458
   337
structure GlobalLocalesData = TheoryDataFun
wenzelm@16458
   338
(struct
wenzelm@12014
   339
  val name = "Isar/locales";
ballarin@15837
   340
  type T = NameSpace.T * locale Symtab.table * Registrations.T Symtab.table;
ballarin@15596
   341
    (* 1st entry: locale namespace,
ballarin@15596
   342
       2nd entry: locales of the theory,
ballarin@15837
   343
       3rd entry: registrations, indexed by locale name *)
wenzelm@11896
   344
ballarin@15596
   345
  val empty = (NameSpace.empty, Symtab.empty, Symtab.empty);
wenzelm@12063
   346
  val copy = I;
wenzelm@16458
   347
  val extend = I;
wenzelm@12289
   348
ballarin@16736
   349
  fun join_locs _ ({predicate, import, elems, params, regs}: locale,
ballarin@16736
   350
      {elems = elems', regs = regs', ...}: locale) =
ballarin@15596
   351
    SOME {predicate = predicate, import = import,
ballarin@15596
   352
      elems = gen_merge_lists eq_snd elems elems',
ballarin@16736
   353
      params = params,
ballarin@16736
   354
      regs = merge_alists regs regs'};
wenzelm@16458
   355
  fun merge _ ((space1, locs1, regs1), (space2, locs2, regs2)) =
ballarin@15596
   356
    (NameSpace.merge (space1, space2), Symtab.join join_locs (locs1, locs2),
wenzelm@16458
   357
     Symtab.join (K (SOME o Registrations.join)) (regs1, regs2));
wenzelm@12289
   358
ballarin@15596
   359
  fun print _ (space, locs, _) =
wenzelm@16346
   360
    Pretty.strs ("locales:" :: map #1 (NameSpace.extern_table (space, locs)))
wenzelm@12014
   361
    |> Pretty.writeln;
wenzelm@16458
   362
end);
wenzelm@11896
   363
wenzelm@15801
   364
val _ = Context.add_setup [GlobalLocalesData.init];
wenzelm@15801
   365
wenzelm@15801
   366
ballarin@15624
   367
ballarin@15624
   368
(** context data **)
wenzelm@11896
   369
wenzelm@16458
   370
structure LocalLocalesData = ProofDataFun
wenzelm@16458
   371
(struct
ballarin@15624
   372
  val name = "Isar/locales";
ballarin@15837
   373
  type T = Registrations.T Symtab.table;
ballarin@15837
   374
    (* registrations, indexed by locale name *)
ballarin@15624
   375
  fun init _ = Symtab.empty;
ballarin@15624
   376
  fun print _ _ = ();
wenzelm@16458
   377
end);
ballarin@15624
   378
wenzelm@15801
   379
val _ = Context.add_setup [LocalLocalesData.init];
wenzelm@12289
   380
wenzelm@12277
   381
wenzelm@12277
   382
(* access locales *)
wenzelm@12277
   383
ballarin@15624
   384
val print_locales = GlobalLocalesData.print;
ballarin@15624
   385
wenzelm@16458
   386
val intern = NameSpace.intern o #1 o GlobalLocalesData.get;
wenzelm@16458
   387
val extern = NameSpace.extern o #1 o GlobalLocalesData.get;
ballarin@15624
   388
wenzelm@16144
   389
fun declare_locale name thy =
wenzelm@16144
   390
  thy |> GlobalLocalesData.map (fn (space, locs, regs) =>
wenzelm@16458
   391
    (Sign.declare_name thy name space, locs, regs));
wenzelm@11896
   392
ballarin@15596
   393
fun put_locale name loc =
ballarin@15624
   394
  GlobalLocalesData.map (fn (space, locs, regs) =>
ballarin@15596
   395
    (space, Symtab.update ((name, loc), locs), regs));
ballarin@15596
   396
ballarin@15624
   397
fun get_locale thy name = Symtab.lookup (#2 (GlobalLocalesData.get thy), name);
wenzelm@11896
   398
wenzelm@12014
   399
fun the_locale thy name =
wenzelm@12014
   400
  (case get_locale thy name of
skalberg@15531
   401
    SOME loc => loc
skalberg@15531
   402
  | NONE => error ("Unknown locale " ^ quote name));
wenzelm@11896
   403
wenzelm@12046
   404
ballarin@15596
   405
(* access registrations *)
ballarin@15596
   406
ballarin@15696
   407
(* Ids of global registrations are varified,
ballarin@15696
   408
   Ids of local registrations are not.
ballarin@15696
   409
   Thms of registrations are never varified. *)
ballarin@15696
   410
ballarin@15624
   411
(* retrieve registration from theory or context *)
ballarin@15624
   412
ballarin@15696
   413
fun gen_get_registrations get thy_ctxt name =
ballarin@15696
   414
  case Symtab.lookup (get thy_ctxt, name) of
ballarin@15696
   415
      NONE => []
ballarin@15837
   416
    | SOME reg => Registrations.dest reg;
ballarin@15696
   417
ballarin@15696
   418
val get_global_registrations =
ballarin@15696
   419
     gen_get_registrations (#3 o GlobalLocalesData.get);
ballarin@15696
   420
val get_local_registrations =
ballarin@15696
   421
     gen_get_registrations LocalLocalesData.get;
ballarin@15696
   422
wenzelm@16458
   423
fun gen_get_registration get thy_of thy_ctxt (name, ps) =
ballarin@15624
   424
  case Symtab.lookup (get thy_ctxt, name) of
ballarin@15624
   425
      NONE => NONE
wenzelm@16458
   426
    | SOME reg => Registrations.lookup (thy_of thy_ctxt) (reg, ps);
ballarin@15624
   427
ballarin@15624
   428
val get_global_registration =
wenzelm@16458
   429
     gen_get_registration (#3 o GlobalLocalesData.get) I;
ballarin@15624
   430
val get_local_registration =
wenzelm@16458
   431
     gen_get_registration LocalLocalesData.get ProofContext.theory_of;
ballarin@15596
   432
ballarin@15624
   433
val test_global_registration = isSome oo get_global_registration;
ballarin@15624
   434
val test_local_registration = isSome oo get_local_registration;
ballarin@15624
   435
fun smart_test_registration ctxt id =
ballarin@15624
   436
  let
ballarin@15624
   437
    val thy = ProofContext.theory_of ctxt;
ballarin@15624
   438
  in
ballarin@15624
   439
    test_global_registration thy id orelse test_local_registration ctxt id
ballarin@15624
   440
  end;
ballarin@15624
   441
ballarin@15624
   442
ballarin@15837
   443
(* add registration to theory or context, ignored if subsumed *)
ballarin@15624
   444
wenzelm@16458
   445
fun gen_put_registration map_data thy_of (name, ps) attn thy_ctxt =
ballarin@15837
   446
  map_data (fn regs =>
ballarin@15837
   447
    let
wenzelm@16458
   448
      val thy = thy_of thy_ctxt;
ballarin@15837
   449
      val reg = getOpt (Symtab.lookup (regs, name), Registrations.empty);
wenzelm@16458
   450
      val (reg', sups) = Registrations.insert thy (ps, attn) reg;
ballarin@15837
   451
      val _ = if not (null sups) then warning
ballarin@15837
   452
                ("Subsumed interpretation(s) of locale " ^
wenzelm@16458
   453
                 quote (extern thy name) ^
ballarin@15837
   454
                 "\nby interpretation(s) with the following prefix(es):\n" ^
ballarin@15837
   455
                  commas_quote (map (fn (_, ((s, _), _)) => s) sups))
ballarin@15837
   456
              else ();
ballarin@15837
   457
    in Symtab.update ((name, reg'), regs) end) thy_ctxt;
ballarin@15624
   458
ballarin@15624
   459
val put_global_registration =
ballarin@15624
   460
     gen_put_registration (fn f =>
wenzelm@16458
   461
       GlobalLocalesData.map (fn (space, locs, regs) => (space, locs, f regs))) I;
ballarin@15837
   462
val put_local_registration =
wenzelm@16458
   463
     gen_put_registration LocalLocalesData.map ProofContext.theory_of;
ballarin@15596
   464
ballarin@15624
   465
ballarin@15624
   466
(* add witness theorem to registration in theory or context,
ballarin@15596
   467
   ignored if registration not present *)
ballarin@15596
   468
ballarin@15624
   469
fun gen_add_witness map (name, ps) thm =
ballarin@15624
   470
  map (fn regs =>
ballarin@15624
   471
      let
ballarin@15837
   472
        val reg = valOf (Symtab.lookup (regs, name));
ballarin@15596
   473
      in
ballarin@15837
   474
        Symtab.update ((name, Registrations.add_witness ps thm reg), regs)
ballarin@15624
   475
      end handle Option => regs);
ballarin@15596
   476
ballarin@15624
   477
val add_global_witness =
ballarin@15624
   478
     gen_add_witness (fn f =>
ballarin@15624
   479
       GlobalLocalesData.map (fn (space, locs, regs) =>
ballarin@15624
   480
         (space, locs, f regs)));
ballarin@15624
   481
val add_local_witness = gen_add_witness LocalLocalesData.map;
ballarin@15596
   482
ballarin@15596
   483
ballarin@14215
   484
(* import hierarchy
ballarin@14215
   485
   implementation could be more efficient, eg. by maintaining a database
ballarin@14215
   486
   of dependencies *)
ballarin@14215
   487
ballarin@14215
   488
fun imports thy (upper, lower) =
ballarin@14215
   489
  let
ballarin@14215
   490
    fun imps (Locale name) low = (name = low) orelse
ballarin@14215
   491
      (case get_locale thy name of
skalberg@15531
   492
           NONE => false
skalberg@15531
   493
         | SOME {import, ...} => imps import low)
ballarin@14215
   494
      | imps (Rename (expr, _)) low = imps expr low
ballarin@14215
   495
      | imps (Merge es) low = exists (fn e => imps e low) es;
ballarin@14215
   496
  in
wenzelm@16458
   497
    imps (Locale (intern thy upper)) (intern thy lower)
ballarin@14215
   498
  end;
ballarin@14215
   499
ballarin@14215
   500
ballarin@15624
   501
(* printing of registrations *)
ballarin@15596
   502
wenzelm@15703
   503
fun gen_print_registrations get_regs mk_ctxt msg loc thy_ctxt =
ballarin@15596
   504
  let
wenzelm@15703
   505
    val ctxt = mk_ctxt thy_ctxt;
wenzelm@15703
   506
    val thy = ProofContext.theory_of ctxt;
wenzelm@15703
   507
wenzelm@15703
   508
    val prt_term = Pretty.quote o ProofContext.pretty_term ctxt;
wenzelm@15703
   509
    val prt_atts = Args.pretty_attribs ctxt;
wenzelm@15703
   510
    fun prt_inst (ts, (("", []), thms)) =
wenzelm@15703
   511
          Pretty.enclose "(" ")" (Pretty.breaks (map prt_term ts))
wenzelm@15703
   512
      | prt_inst (ts, ((prfx, atts), thms)) =
ballarin@15837
   513
          Pretty.block (
ballarin@15837
   514
            (Pretty.breaks (Pretty.str prfx :: prt_atts atts) @
ballarin@15837
   515
              [Pretty.str ":", Pretty.brk 1,
ballarin@15837
   516
                Pretty.enclose "(" ")" (Pretty.breaks (map prt_term ts))]));
wenzelm@15703
   517
wenzelm@16458
   518
    val loc_int = intern thy loc;
ballarin@15624
   519
    val regs = get_regs thy_ctxt;
ballarin@15596
   520
    val loc_regs = Symtab.lookup (regs, loc_int);
ballarin@15596
   521
  in
ballarin@15596
   522
    (case loc_regs of
ballarin@15624
   523
        NONE => Pretty.str ("No interpretations in " ^ msg ^ ".")
ballarin@15763
   524
      | SOME r => let
ballarin@15837
   525
            val r' = Registrations.dest r;
ballarin@15763
   526
            val r'' = Library.sort_wrt (fn (_, ((prfx, _), _)) => prfx) r';
ballarin@15763
   527
          in Pretty.big_list ("Interpretations in " ^ msg ^ ":")
ballarin@15763
   528
            (map prt_inst r'')
ballarin@15763
   529
          end)
ballarin@15596
   530
    |> Pretty.writeln
ballarin@15596
   531
  end;
ballarin@15596
   532
ballarin@15624
   533
val print_global_registrations =
ballarin@15624
   534
     gen_print_registrations (#3 o GlobalLocalesData.get)
wenzelm@15703
   535
       ProofContext.init "theory";
ballarin@15624
   536
val print_local_registrations' =
ballarin@15624
   537
     gen_print_registrations LocalLocalesData.get
wenzelm@15703
   538
       I "context";
ballarin@15624
   539
fun print_local_registrations loc ctxt =
ballarin@15624
   540
  (print_global_registrations loc (ProofContext.theory_of ctxt);
ballarin@15624
   541
   print_local_registrations' loc ctxt);
ballarin@15624
   542
ballarin@15596
   543
wenzelm@12277
   544
(* diagnostics *)
wenzelm@12273
   545
wenzelm@12277
   546
fun err_in_locale ctxt msg ids =
wenzelm@12277
   547
  let
wenzelm@16458
   548
    val thy = ProofContext.theory_of ctxt;
wenzelm@12529
   549
    fun prt_id (name, parms) =
wenzelm@16458
   550
      [Pretty.block (Pretty.breaks (map Pretty.str (extern thy name :: parms)))];
skalberg@15570
   551
    val prt_ids = List.concat (separate [Pretty.str " +", Pretty.brk 1] (map prt_id ids));
wenzelm@12502
   552
    val err_msg =
wenzelm@12529
   553
      if forall (equal "" o #1) ids then msg
wenzelm@12502
   554
      else msg ^ "\n" ^ Pretty.string_of (Pretty.block
wenzelm@12502
   555
        (Pretty.str "The error(s) above occurred in locale:" :: Pretty.brk 1 :: prt_ids));
wenzelm@12502
   556
  in raise ProofContext.CONTEXT (err_msg, ctxt) end;
wenzelm@12063
   557
ballarin@15206
   558
(* Version for identifiers with axioms *)
ballarin@15206
   559
ballarin@15206
   560
fun err_in_locale' ctxt msg ids' = err_in_locale ctxt msg (map fst ids');
wenzelm@12277
   561
wenzelm@12277
   562
wenzelm@12529
   563
(** primitives **)
wenzelm@12046
   564
wenzelm@15703
   565
(* map elements *)
wenzelm@15703
   566
wenzelm@15703
   567
fun map_elem {name, var, typ, term, fact, attrib} =
wenzelm@15703
   568
  fn Fixes fixes => Fixes (fixes |> map (fn (x, T, mx) =>
wenzelm@15703
   569
       let val (x', mx') = var (x, mx) in (x', Option.map typ T, mx') end))
ballarin@16169
   570
   | Constrains csts => Constrains (csts |> map (fn (x, T) =>
ballarin@16169
   571
       let val (x', _) = var (x, SOME Syntax.NoSyn) in (x', typ T) end))
wenzelm@15703
   572
   | Assumes asms => Assumes (asms |> map (fn ((a, atts), propps) =>
wenzelm@15703
   573
      ((name a, map attrib atts), propps |> map (fn (t, (ps, qs)) =>
wenzelm@15703
   574
        (term t, (map term ps, map term qs))))))
wenzelm@15703
   575
   | Defines defs => Defines (defs |> map (fn ((a, atts), (t, ps)) =>
wenzelm@15703
   576
      ((name a, map attrib atts), (term t, map term ps))))
wenzelm@15703
   577
   | Notes facts => Notes (facts |> map (fn ((a, atts), bs) =>
wenzelm@15703
   578
      ((name a, map attrib atts), bs |> map (fn (ths, btts) => (fact ths, map attrib btts)))));
wenzelm@15703
   579
wenzelm@15703
   580
fun map_values typ term thm = map_elem
wenzelm@15703
   581
  {name = I, var = I, typ = typ, term = term, fact = map thm,
wenzelm@15703
   582
    attrib = Args.map_values I typ term thm};
wenzelm@15703
   583
wenzelm@15703
   584
wenzelm@15703
   585
(* map attributes *)
wenzelm@15703
   586
wenzelm@15703
   587
fun map_attrib_specs f = map (apfst (apsnd (map f)));
wenzelm@15703
   588
fun map_attrib_facts f = map (apfst (apsnd (map f)) o apsnd (map (apsnd (map f))));
wenzelm@15703
   589
wenzelm@15703
   590
fun map_attrib_elem f = map_elem {name = I, var = I, typ = I, term = I, fact = I, attrib = f};
wenzelm@15703
   591
wenzelm@16458
   592
fun intern_attrib_elem thy = map_attrib_elem (Attrib.intern_src thy);
wenzelm@15703
   593
wenzelm@15703
   594
fun intern_attrib_elem_expr thy (Elem elem) = Elem (intern_attrib_elem thy elem)
wenzelm@15703
   595
  | intern_attrib_elem_expr _ (Expr expr) = Expr expr;
wenzelm@15703
   596
wenzelm@15703
   597
wenzelm@12277
   598
(* renaming *)
wenzelm@12263
   599
ballarin@16102
   600
(* ren maps names to (new) names and syntax; represented as association list *)
wenzelm@12263
   601
wenzelm@15703
   602
fun rename_var ren (x, mx) =
ballarin@16102
   603
  case assoc_string (ren, x) of
ballarin@16102
   604
      NONE => (x, mx)
ballarin@16102
   605
    | SOME (x', NONE) =>
ballarin@16102
   606
        (x', if mx = NONE then mx else SOME Syntax.NoSyn)     (*drop syntax*)
ballarin@16102
   607
    | SOME (x', SOME mx') =>
ballarin@16102
   608
        if mx = NONE then raise ERROR_MESSAGE
ballarin@16102
   609
          ("Attempt to change syntax of structure parameter " ^ quote x)
ballarin@16102
   610
        else (x', SOME mx');                                (*change syntax*)
ballarin@16102
   611
ballarin@16102
   612
fun rename ren x =
ballarin@16102
   613
  case assoc_string (ren, x) of
ballarin@16102
   614
      NONE => x
ballarin@16102
   615
    | SOME (x', _) => x';                                   (*ignore syntax*)
wenzelm@15703
   616
wenzelm@12263
   617
fun rename_term ren (Free (x, T)) = Free (rename ren x, T)
wenzelm@12263
   618
  | rename_term ren (t $ u) = rename_term ren t $ rename_term ren u
wenzelm@12263
   619
  | rename_term ren (Abs (x, T, t)) = Abs (x, T, rename_term ren t)
wenzelm@12263
   620
  | rename_term _ a = a;
wenzelm@12263
   621
wenzelm@12263
   622
fun rename_thm ren th =
wenzelm@12263
   623
  let
wenzelm@16458
   624
    val {thy, hyps, prop, maxidx, ...} = Thm.rep_thm th;
wenzelm@16458
   625
    val cert = Thm.cterm_of thy;
skalberg@15570
   626
    val (xs, Ts) = Library.split_list (Library.foldl Term.add_frees ([], prop :: hyps));
wenzelm@12263
   627
    val xs' = map (rename ren) xs;
wenzelm@12263
   628
    fun cert_frees names = map (cert o Free) (names ~~ Ts);
wenzelm@12263
   629
    fun cert_vars names = map (cert o Var o apfst (rpair (maxidx + 1))) (names ~~ Ts);
wenzelm@12263
   630
  in
wenzelm@12263
   631
    if xs = xs' then th
wenzelm@12263
   632
    else
wenzelm@12263
   633
      th
wenzelm@12263
   634
      |> Drule.implies_intr_list (map cert hyps)
wenzelm@12263
   635
      |> Drule.forall_intr_list (cert_frees xs)
wenzelm@12263
   636
      |> Drule.forall_elim_list (cert_vars xs)
wenzelm@12263
   637
      |> Thm.instantiate ([], cert_vars xs ~~ cert_frees xs')
wenzelm@12263
   638
      |> (fn th' => Drule.implies_elim_list th' (map (Thm.assume o cert o rename_term ren) hyps))
wenzelm@12263
   639
  end;
wenzelm@12263
   640
wenzelm@15703
   641
fun rename_elem ren =
wenzelm@15703
   642
  map_values I (rename_term ren) (rename_thm ren) o
wenzelm@15703
   643
  map_elem {name = I, typ = I, term = I, fact = I, attrib = I, var = rename_var ren};
wenzelm@12263
   644
wenzelm@16144
   645
fun rename_facts prfx =
wenzelm@16144
   646
  map_elem {var = I, typ = I, term = I, fact = I, attrib = I, name = NameSpace.qualified prfx};
wenzelm@12307
   647
wenzelm@12263
   648
wenzelm@12502
   649
(* type instantiation *)
wenzelm@12502
   650
wenzelm@12502
   651
fun inst_type [] T = T
skalberg@15570
   652
  | inst_type env T = Term.map_type_tfree (fn v => getOpt (assoc (env, v), TFree v)) T;
wenzelm@12502
   653
wenzelm@12502
   654
fun inst_term [] t = t
wenzelm@12502
   655
  | inst_term env t = Term.map_term_types (inst_type env) t;
wenzelm@12502
   656
wenzelm@13211
   657
fun inst_thm _ [] th = th
wenzelm@13211
   658
  | inst_thm ctxt env th =
wenzelm@12502
   659
      let
wenzelm@16458
   660
        val thy = ProofContext.theory_of ctxt;
wenzelm@16458
   661
        val cert = Thm.cterm_of thy;
wenzelm@16458
   662
        val certT = Thm.ctyp_of thy;
wenzelm@13211
   663
        val {hyps, prop, maxidx, ...} = Thm.rep_thm th;
skalberg@15574
   664
        val tfrees = foldr Term.add_term_tfree_names [] (prop :: hyps);
skalberg@15570
   665
        val env' = List.filter (fn ((a, _), _) => a mem_string tfrees) env;
wenzelm@12502
   666
      in
wenzelm@12502
   667
        if null env' then th
wenzelm@12502
   668
        else
wenzelm@12502
   669
          th
wenzelm@12502
   670
          |> Drule.implies_intr_list (map cert hyps)
wenzelm@12575
   671
          |> Drule.tvars_intr_list (map (#1 o #1) env')
wenzelm@12502
   672
          |> (fn (th', al) => th' |>
berghofe@15798
   673
            Thm.instantiate ((map (fn ((a, _), T) =>
berghofe@15798
   674
              (certT (TVar (valOf (assoc (al, a)))), certT T)) env'), []))
wenzelm@12502
   675
          |> (fn th'' => Drule.implies_elim_list th''
wenzelm@12502
   676
              (map (Thm.assume o cert o inst_term env') hyps))
wenzelm@12502
   677
      end;
wenzelm@12502
   678
wenzelm@15703
   679
fun inst_elem ctxt env =
wenzelm@15703
   680
  map_values (inst_type env) (inst_term env) (inst_thm ctxt env);
wenzelm@12502
   681
wenzelm@12502
   682
ballarin@15696
   683
(* term and type instantiation, variant using symbol tables *)
ballarin@15696
   684
ballarin@15696
   685
(* instantiate TFrees *)
ballarin@15696
   686
wenzelm@16458
   687
fun tinst_tab_elem thy tinst =
wenzelm@16458
   688
  map_values (tinst_tab_type tinst) (tinst_tab_term tinst) (tinst_tab_thm thy tinst);
wenzelm@15749
   689
ballarin@15696
   690
(* instantiate TFrees and Frees *)
ballarin@15696
   691
wenzelm@16458
   692
fun inst_tab_elem thy (inst as (_, tinst)) =
wenzelm@16458
   693
  map_values (tinst_tab_type tinst) (inst_tab_term inst) (inst_tab_thm thy inst);
ballarin@15696
   694
wenzelm@16458
   695
fun inst_tab_elems thy inst ((n, ps), elems) =
wenzelm@16458
   696
      ((n, map (inst_tab_term inst) ps), map (inst_tab_elem thy inst) elems);
ballarin@15696
   697
wenzelm@12529
   698
wenzelm@12529
   699
(** structured contexts: rename + merge + implicit type instantiation **)
wenzelm@12529
   700
wenzelm@12529
   701
(* parameter types *)
wenzelm@12529
   702
ballarin@14508
   703
(* CB: frozen_tvars has the following type:
berghofe@15798
   704
  ProofContext.context -> Term.typ list -> (Term.indexname * (sort * Term.typ)) list *)
ballarin@14508
   705
wenzelm@12529
   706
fun frozen_tvars ctxt Ts =
wenzelm@12529
   707
  let
skalberg@15570
   708
    val tvars = rev (Library.foldl Term.add_tvarsT ([], Ts));
wenzelm@12529
   709
    val tfrees = map TFree
wenzelm@14695
   710
      (Term.invent_names (ProofContext.used_types ctxt) "'a" (length tvars) ~~ map #2 tvars);
berghofe@15798
   711
  in map (fn ((x, S), y) => (x, (S, y))) (tvars ~~ tfrees) end;
wenzelm@12529
   712
wenzelm@12529
   713
fun unify_frozen ctxt maxidx Ts Us =
wenzelm@12529
   714
  let
skalberg@15531
   715
    fun paramify (i, NONE) = (i, NONE)
skalberg@15531
   716
      | paramify (i, SOME T) = apsnd SOME (TypeInfer.paramify_dummies (i, T));
wenzelm@12529
   717
wenzelm@12529
   718
    val (maxidx', Ts') = foldl_map paramify (maxidx, Ts);
wenzelm@12727
   719
    val (maxidx'', Us') = foldl_map paramify (maxidx', Us);
wenzelm@16458
   720
    val tsig = Sign.tsig_of (ProofContext.theory_of ctxt);
ballarin@14215
   721
skalberg@15531
   722
    fun unify (env, (SOME T, SOME U)) = (Type.unify tsig env (U, T)
ballarin@14215
   723
          handle Type.TUNIFY =>
ballarin@14215
   724
            raise TYPE ("unify_frozen: failed to unify types", [U, T], []))
ballarin@14215
   725
      | unify (env, _) = env;
skalberg@15570
   726
    val (unifier, _) = Library.foldl unify ((Vartab.empty, maxidx''), Ts' ~~ Us');
skalberg@15570
   727
    val Vs = map (Option.map (Envir.norm_type unifier)) Us';
skalberg@15570
   728
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (List.mapPartial I Vs));
skalberg@15570
   729
  in map (Option.map (Envir.norm_type unifier')) Vs end;
wenzelm@12529
   730
skalberg@15570
   731
fun params_of elemss = gen_distinct eq_fst (List.concat (map (snd o fst) elemss));
skalberg@15570
   732
fun params_of' elemss = gen_distinct eq_fst (List.concat (map (snd o fst o fst) elemss));
ballarin@16102
   733
fun params_syn_of syn elemss =
ballarin@16102
   734
  gen_distinct eq_fst (List.concat (map (snd o fst) elemss)) |>
ballarin@16102
   735
    map (apfst (fn x => (x, valOf (Symtab.lookup (syn, x)))));
ballarin@16102
   736
ballarin@14508
   737
ballarin@14508
   738
(* CB: param_types has the following type:
skalberg@15531
   739
  ('a * 'b option) list -> ('a * 'b) list *)
skalberg@15570
   740
fun param_types ps = List.mapPartial (fn (_, NONE) => NONE | (x, SOME T) => SOME (x, T)) ps;
wenzelm@12529
   741
wenzelm@12529
   742
ballarin@16102
   743
fun merge_syntax ctxt ids ss = Symtab.merge (op =) ss
ballarin@16102
   744
  handle Symtab.DUPS xs => err_in_locale ctxt
ballarin@16105
   745
    ("Conflicting syntax for parameter(s): " ^ commas_quote xs) (map fst ids);
ballarin@16102
   746
ballarin@16102
   747
wenzelm@12529
   748
(* flatten expressions *)
wenzelm@11896
   749
wenzelm@12510
   750
local
wenzelm@12502
   751
ballarin@15206
   752
(* CB: OUTDATED unique_parms has the following type:
ballarin@14508
   753
     'a ->
ballarin@14508
   754
     (('b * (('c * 'd) list * Symtab.key list)) * 'e) list ->
ballarin@14508
   755
     (('b * ('c * 'd) list) * 'e) list  *)
ballarin@14508
   756
wenzelm@12529
   757
fun unique_parms ctxt elemss =
wenzelm@12529
   758
  let
wenzelm@12529
   759
    val param_decls =
skalberg@15570
   760
      List.concat (map (fn (((name, (ps, qs)), _), _) => map (rpair (name, ps)) qs) elemss)
wenzelm@12529
   761
      |> Symtab.make_multi |> Symtab.dest;
wenzelm@12529
   762
  in
wenzelm@12529
   763
    (case find_first (fn (_, ids) => length ids > 1) param_decls of
skalberg@15531
   764
      SOME (q, ids) => err_in_locale ctxt ("Multiple declaration of parameter " ^ quote q)
wenzelm@12529
   765
          (map (apsnd (map fst)) ids)
skalberg@15531
   766
    | NONE => map (apfst (apfst (apsnd #1))) elemss)
wenzelm@12529
   767
  end;
wenzelm@12529
   768
ballarin@16102
   769
fun unify_parms ctxt (fixed_parms : (string * typ) list)
ballarin@16102
   770
  (raw_parmss : (string * typ option) list list) =
wenzelm@12502
   771
  let
wenzelm@16458
   772
    val thy = ProofContext.theory_of ctxt;
wenzelm@16458
   773
    val tsig = Sign.tsig_of thy;
wenzelm@12502
   774
    val maxidx = length raw_parmss;
wenzelm@12502
   775
    val idx_parmss = (0 upto maxidx - 1) ~~ raw_parmss;
wenzelm@12502
   776
wenzelm@12502
   777
    fun varify i = Term.map_type_tfree (fn (a, S) => TVar ((a, i), S));
wenzelm@12529
   778
    fun varify_parms (i, ps) = map (apsnd (varify i)) (param_types ps);
skalberg@15570
   779
    val parms = fixed_parms @ List.concat (map varify_parms idx_parmss);
wenzelm@12502
   780
ballarin@15206
   781
    fun unify T ((env, maxidx), U) =
ballarin@15206
   782
      Type.unify tsig (env, maxidx) (U, T)
ballarin@15206
   783
      handle Type.TUNIFY =>
wenzelm@16458
   784
        let val prt = Sign.string_of_typ thy
ballarin@15206
   785
        in raise TYPE ("unify_parms: failed to unify types " ^
ballarin@15206
   786
          prt U ^ " and " ^ prt T, [U, T], [])
ballarin@15206
   787
        end
skalberg@15570
   788
    fun unify_list (envir, T :: Us) = Library.foldl (unify T) (envir, Us)
wenzelm@12502
   789
      | unify_list (envir, []) = envir;
skalberg@15570
   790
    val (unifier, _) = Library.foldl unify_list
wenzelm@12502
   791
      ((Vartab.empty, maxidx), map #2 (Symtab.dest (Symtab.make_multi parms)));
wenzelm@12502
   792
wenzelm@12502
   793
    val parms' = map (apsnd (Envir.norm_type unifier)) (gen_distinct eq_fst parms);
wenzelm@12502
   794
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map #2 parms'));
wenzelm@12502
   795
wenzelm@12502
   796
    fun inst_parms (i, ps) =
skalberg@15574
   797
      foldr Term.add_typ_tfrees [] (List.mapPartial snd ps)
skalberg@15570
   798
      |> List.mapPartial (fn (a, S) =>
wenzelm@12502
   799
          let val T = Envir.norm_type unifier' (TVar ((a, i), S))
skalberg@15531
   800
          in if T = TFree (a, S) then NONE else SOME ((a, S), T) end)
ballarin@16102
   801
  in map inst_parms idx_parmss end : ((string * Term.sort) * Term.typ) list list;
wenzelm@12502
   802
wenzelm@12529
   803
in
wenzelm@12502
   804
wenzelm@12529
   805
fun unify_elemss _ _ [] = []
wenzelm@12529
   806
  | unify_elemss _ [] [elems] = [elems]
wenzelm@12529
   807
  | unify_elemss ctxt fixed_parms elemss =
wenzelm@12502
   808
      let
ballarin@15206
   809
        val envs = unify_parms ctxt fixed_parms (map (#2 o #1 o #1) elemss);
ballarin@15206
   810
        fun inst ((((name, ps), axs), elems), env) =
skalberg@15570
   811
          (((name, map (apsnd (Option.map (inst_type env))) ps), 
ballarin@15206
   812
            map (inst_thm ctxt env) axs), map (inst_elem ctxt env) elems);
wenzelm@12839
   813
      in map inst (elemss ~~ envs) end;
wenzelm@12502
   814
ballarin@16736
   815
(* like unify_elemss, but does not touch axioms, additional
ballarin@16736
   816
   parameter c_parms for enforcing further constraints (eg. syntax) *)
ballarin@16102
   817
ballarin@16102
   818
fun unify_elemss' _ _ [] [] = []
ballarin@16102
   819
  | unify_elemss' _ [] [elems] [] = [elems]
ballarin@16102
   820
  | unify_elemss' ctxt fixed_parms elemss c_parms =
ballarin@16102
   821
      let
ballarin@16102
   822
        val envs = unify_parms ctxt fixed_parms (map (#2 o #1 o #1) elemss @ map single c_parms);
ballarin@16102
   823
        fun inst ((((name, ps), axs), elems), env) =
ballarin@16102
   824
          (((name, map (apsnd (Option.map (inst_type env))) ps),  axs),
ballarin@16102
   825
           map (inst_elem ctxt env) elems);
ballarin@16102
   826
      in map inst (elemss ~~ (Library.take (length elemss, envs))) end;
ballarin@16102
   827
ballarin@15596
   828
(* flatten_expr:
ballarin@15596
   829
   Extend list of identifiers by those new in locale expression expr.
ballarin@15596
   830
   Compute corresponding list of lists of locale elements (one entry per
ballarin@15596
   831
   identifier).
ballarin@15596
   832
ballarin@15596
   833
   Identifiers represent locale fragments and are in an extended form:
ballarin@15596
   834
     ((name, ps), (ax_ps, axs))
ballarin@15596
   835
   (name, ps) is the locale name with all its parameters.
ballarin@15596
   836
   (ax_ps, axs) is the locale axioms with its parameters;
ballarin@15596
   837
     axs are always taken from the top level of the locale hierarchy,
ballarin@15596
   838
     hence axioms may contain additional parameters from later fragments:
ballarin@15596
   839
     ps subset of ax_ps.  axs is either singleton or empty.
ballarin@15596
   840
ballarin@15596
   841
   Elements are enriched by identifier-like information:
ballarin@15596
   842
     (((name, ax_ps), axs), elems)
ballarin@15596
   843
   The parameters in ax_ps are the axiom parameters, but enriched by type
ballarin@15596
   844
   info: now each entry is a pair of string and typ option.  Axioms are
ballarin@15596
   845
   type-instantiated.
ballarin@15596
   846
ballarin@15596
   847
*)
ballarin@15596
   848
ballarin@16102
   849
fun flatten_expr ctxt ((prev_idents, prev_syntax), expr) =
wenzelm@12014
   850
  let
wenzelm@12014
   851
    val thy = ProofContext.theory_of ctxt;
ballarin@15596
   852
    (* thy used for retrieval of locale info,
ballarin@15596
   853
       ctxt for error messages, parameter unification and instantiation
ballarin@15596
   854
       of axioms *)
wenzelm@12263
   855
skalberg@15531
   856
    fun renaming (SOME x :: xs) (y :: ys) = (y, x) :: renaming xs ys
skalberg@15531
   857
      | renaming (NONE :: xs) (y :: ys) = renaming xs ys
wenzelm@12273
   858
      | renaming [] _ = []
wenzelm@12289
   859
      | renaming xs [] = raise ERROR_MESSAGE ("Too many arguments in renaming: " ^
ballarin@16102
   860
          commas (map (fn NONE => "_" | SOME x => quote (fst x)) xs));
wenzelm@12289
   861
ballarin@15206
   862
    fun rename_parms top ren ((name, ps), (parms, axs)) =
wenzelm@12289
   863
      let val ps' = map (rename ren) ps in
ballarin@15206
   864
        (case duplicates ps' of [] => ((name, ps'),
ballarin@15206
   865
          if top then (map (rename ren) parms, map (rename_thm ren) axs)
ballarin@15206
   866
          else (parms, axs))
wenzelm@12289
   867
        | dups => err_in_locale ctxt ("Duplicate parameters: " ^ commas_quote dups) [(name, ps')])
wenzelm@12289
   868
      end;
wenzelm@12263
   869
ballarin@15206
   870
    fun identify top (Locale name) =
ballarin@15596
   871
    (* CB: ids_ax is a list of tuples of the form ((name, ps), axs),
ballarin@15206
   872
       where name is a locale name, ps a list of parameter names and axs
ballarin@15206
   873
       a list of axioms relating to the identifier, axs is empty unless
ballarin@15206
   874
       identify at top level (top = true);
ballarin@14215
   875
       parms is accumulated list of parameters *)
wenzelm@12289
   876
          let
ballarin@15206
   877
            val {predicate = (_, axioms), import, params, ...} =
ballarin@15206
   878
              the_locale thy name;
ballarin@16102
   879
            val ps = map (#1 o #1) (#1 params);
ballarin@16102
   880
            val (ids', parms', _) = identify false import;
ballarin@15206
   881
                (* acyclic import dependencies *)
ballarin@15206
   882
            val ids'' = ids' @ [((name, ps), ([], []))];
ballarin@15206
   883
            val ids_ax = if top then snd
ballarin@16102
   884
                 (* get the right axioms, only if at top level *)
ballarin@15206
   885
                 (foldl_map (fn (axs, ((name, parms), _)) => let
ballarin@15206
   886
                   val {elems, ...} = the_locale thy name;
skalberg@15570
   887
                   val ts = List.concat (List.mapPartial (fn (Assumes asms, _) =>
skalberg@15570
   888
                     SOME (List.concat (map (map #1 o #2) asms)) | _ => NONE) elems);
ballarin@15206
   889
                   val (axs1, axs2) = splitAt (length ts, axs);
ballarin@15206
   890
                 in (axs2, ((name, parms), (ps, axs1))) end) (axioms, ids''))
ballarin@15206
   891
               else ids'';
ballarin@16102
   892
            val syn = Symtab.make (map (apfst fst) (#1 params));
ballarin@16102
   893
          in (ids_ax, merge_lists parms' ps, syn) end
ballarin@15206
   894
      | identify top (Rename (e, xs)) =
wenzelm@12273
   895
          let
ballarin@16102
   896
            val (ids', parms', syn') = identify top e;
wenzelm@12839
   897
            val ren = renaming xs parms'
ballarin@15206
   898
              handle ERROR_MESSAGE msg => err_in_locale' ctxt msg ids';
ballarin@15206
   899
            val ids'' = gen_distinct eq_fst (map (rename_parms top ren) ids');
skalberg@15570
   900
            val parms'' = distinct (List.concat (map (#2 o #1) ids''));
ballarin@16102
   901
            val syn'' = syn' |> Symtab.dest |> map (rename_var ren) |>
ballarin@16102
   902
                  Symtab.make;
ballarin@16102
   903
            (* check for conflicting syntax? *)
ballarin@16102
   904
          in (ids'', parms'', syn'') end
ballarin@15206
   905
      | identify top (Merge es) =
ballarin@16102
   906
          Library.foldl (fn ((ids, parms, syn), e) => let
ballarin@16102
   907
                     val (ids', parms', syn') = identify top e
ballarin@16736
   908
                   in (merge_alists ids ids',
ballarin@16102
   909
                       merge_lists parms parms',
ballarin@16102
   910
                       merge_syntax ctxt ids' (syn, syn')) end)
ballarin@16102
   911
            (([], [], Symtab.empty), es);
wenzelm@12014
   912
ballarin@15206
   913
    (* CB: enrich identifiers by parameter types and 
ballarin@16102
   914
       the corresponding elements (with renamed parameters),
ballarin@16102
   915
       also takes care of parameter syntax *)
ballarin@15206
   916
ballarin@16102
   917
    fun eval syn ((name, xs), axs) =
wenzelm@12273
   918
      let
wenzelm@13308
   919
        val {params = (ps, qs), elems, ...} = the_locale thy name;
ballarin@16620
   920
        val ps' = map (apsnd SOME o #1) ps;
ballarin@16102
   921
        val ren = map #1 ps' ~~
ballarin@16102
   922
              map (fn x => (x, valOf (Symtab.lookup (syn, x)))) xs;
wenzelm@13308
   923
        val (params', elems') =
ballarin@16102
   924
          if null ren then ((ps', qs), map #1 elems)
ballarin@16102
   925
          else ((map (apfst (rename ren)) ps', map (rename ren) qs),
wenzelm@13308
   926
            map (rename_elem ren o #1) elems);
wenzelm@13375
   927
        val elems'' = map (rename_facts (space_implode "_" xs)) elems';
ballarin@15206
   928
      in (((name, params'), axs), elems'') end;
wenzelm@12307
   929
ballarin@16102
   930
    (* type constraint for renamed parameter with syntax *)
ballarin@16102
   931
    fun type_syntax NONE = NONE
ballarin@16102
   932
      | type_syntax (SOME mx) = let
ballarin@16102
   933
            val Ts = map (fn x => TFree (x, [])) (Term.invent_names [] "'mxa"
ballarin@16102
   934
              (Syntax.mixfix_args mx + 1))
ballarin@16102
   935
          in Ts |> Library.split_last |> op ---> |> SOME end;
ballarin@16102
   936
ballarin@16102
   937
    (* compute identifiers and syntax, merge with previous ones *)
ballarin@16102
   938
    val (ids, _, syn) = identify true expr;
ballarin@16102
   939
    val idents = gen_rems eq_fst (ids, prev_idents);
ballarin@16102
   940
    val syntax = merge_syntax ctxt ids (syn, prev_syntax);
ballarin@15206
   941
    (* add types to params, check for unique params and unify them *)
ballarin@16102
   942
    val raw_elemss = unique_parms ctxt (map (eval syntax) idents);
ballarin@16102
   943
    val elemss = unify_elemss' ctxt [] raw_elemss
ballarin@16102
   944
         (map (apsnd type_syntax) (Symtab.dest syntax));
ballarin@15206
   945
    (* replace params in ids by params from axioms,
ballarin@15206
   946
       adjust types in axioms *)
ballarin@15206
   947
    val all_params' = params_of' elemss;
ballarin@15206
   948
    val all_params = param_types all_params';
ballarin@15206
   949
    val elemss' = map (fn (((name, _), (ps, axs)), elems) =>
ballarin@15206
   950
         (((name, map (fn p => (p, assoc (all_params, p))) ps), axs), elems))
ballarin@15206
   951
         elemss;
ballarin@15206
   952
    fun inst_ax th = let
ballarin@15206
   953
         val {hyps, prop, ...} = Thm.rep_thm th;
skalberg@15570
   954
         val ps = map (apsnd SOME) (Library.foldl Term.add_frees ([], prop :: hyps));
ballarin@15206
   955
         val [env] = unify_parms ctxt all_params [ps];
ballarin@15206
   956
         val th' = inst_thm ctxt env th;
ballarin@15206
   957
       in th' end;
ballarin@15206
   958
    val final_elemss = map (fn ((id, axs), elems) =>
ballarin@15206
   959
         ((id, map inst_ax axs), elems)) elemss';
ballarin@16102
   960
  in ((prev_idents @ idents, syntax), final_elemss) end;
wenzelm@12046
   961
wenzelm@12510
   962
end;
wenzelm@12510
   963
wenzelm@12070
   964
wenzelm@12529
   965
(* activate elements *)
wenzelm@12273
   966
wenzelm@12510
   967
local
wenzelm@12510
   968
wenzelm@13399
   969
fun export_axioms axs _ hyps th =
wenzelm@13399
   970
  th |> Drule.satisfy_hyps axs
ballarin@15206
   971
     (* CB: replace meta-hyps, using axs, by a single meta-hyp. *)
wenzelm@13399
   972
  |> Drule.implies_intr_list (Library.drop (length axs, hyps))
ballarin@15206
   973
     (* CB: turn remaining hyps into assumptions. *)
ballarin@15206
   974
  |> Seq.single
wenzelm@12263
   975
wenzelm@14643
   976
fun activate_elem _ ((ctxt, axs), Fixes fixes) =
wenzelm@14643
   977
      ((ctxt |> ProofContext.add_fixes fixes, axs), [])
ballarin@16169
   978
  | activate_elem _ ((ctxt, axs), Constrains _) = ((ctxt, axs), [])
wenzelm@13399
   979
  | activate_elem _ ((ctxt, axs), Assumes asms) =
wenzelm@13399
   980
      let
wenzelm@15703
   981
        val asms' = map_attrib_specs (Attrib.context_attribute_i ctxt) asms;
wenzelm@15703
   982
        val ts = List.concat (map (map #1 o #2) asms');
wenzelm@15703
   983
        val (ps, qs) = splitAt (length ts, axs);
wenzelm@13420
   984
        val (ctxt', _) =
wenzelm@13399
   985
          ctxt |> ProofContext.fix_frees ts
wenzelm@15703
   986
          |> ProofContext.assume_i (export_axioms ps) asms';
nipkow@13629
   987
      in ((ctxt', qs), []) end
wenzelm@13399
   988
  | activate_elem _ ((ctxt, axs), Defines defs) =
ballarin@15596
   989
      let
wenzelm@15703
   990
        val defs' = map_attrib_specs (Attrib.context_attribute_i ctxt) defs;
ballarin@15596
   991
        val (ctxt', _) =
wenzelm@13399
   992
        ctxt |> ProofContext.assume_i ProofContext.export_def
wenzelm@15703
   993
          (defs' |> map (fn ((name, atts), (t, ps)) =>
wenzelm@13399
   994
            let val (c, t') = ProofContext.cert_def ctxt t
wenzelm@13399
   995
            in ((if name = "" then Thm.def_name c else name, atts), [(t', (ps, []))]) end))
wenzelm@13420
   996
      in ((ctxt', axs), []) end
wenzelm@13399
   997
  | activate_elem is_ext ((ctxt, axs), Notes facts) =
ballarin@15596
   998
      let
wenzelm@15703
   999
        val facts' = map_attrib_facts (Attrib.context_attribute_i ctxt) facts;
wenzelm@15703
  1000
        val (ctxt', res) = ctxt |> ProofContext.note_thmss_i facts';
wenzelm@13420
  1001
      in ((ctxt', axs), if is_ext then res else []) end;
wenzelm@12502
  1002
ballarin@15206
  1003
fun activate_elems (((name, ps), axs), elems) ctxt =
ballarin@15206
  1004
  let val ((ctxt', _), res) =
wenzelm@16144
  1005
    foldl_map (activate_elem (name = "")) ((ProofContext.qualified_names ctxt, axs), elems)
wenzelm@13399
  1006
      handle ProofContext.CONTEXT (msg, ctxt) => err_in_locale ctxt msg [(name, map fst ps)]
ballarin@15696
  1007
    val ctxt'' = if name = "" then ctxt'
ballarin@15696
  1008
          else let
ballarin@15696
  1009
              val ps' = map (fn (n, SOME T) => Free (n, T)) ps;
ballarin@15696
  1010
              val ctxt'' = put_local_registration (name, ps') ("", []) ctxt'
ballarin@15696
  1011
            in foldl (fn (ax, ctxt) =>
ballarin@15696
  1012
              add_local_witness (name, ps') (Thm.assume (Thm.cprop_of ax)) ctxt) ctxt'' axs
ballarin@15696
  1013
            end
wenzelm@16144
  1014
  in (ProofContext.restore_naming ctxt ctxt'', res) end;
wenzelm@13399
  1015
ballarin@15206
  1016
fun activate_elemss prep_facts = foldl_map (fn (ctxt, (((name, ps), axs), raw_elems)) =>
wenzelm@12834
  1017
  let
wenzelm@12834
  1018
    val elems = map (prep_facts ctxt) raw_elems;
skalberg@15570
  1019
    val (ctxt', res) = apsnd List.concat (activate_elems (((name, ps), axs), elems) ctxt);
wenzelm@15703
  1020
    val elems' = map (map_attrib_elem Args.closure) elems;
wenzelm@15703
  1021
  in (ctxt', (((name, ps), elems'), res)) end);
wenzelm@12834
  1022
wenzelm@12546
  1023
in
wenzelm@12546
  1024
ballarin@15206
  1025
(* CB: activate_facts prep_facts (ctxt, elemss),
ballarin@15206
  1026
   where elemss is a list of pairs consisting of identifiers and
ballarin@15206
  1027
   context elements, extends ctxt by the context elements yielding
ballarin@15206
  1028
   ctxt' and returns (ctxt', (elemss', facts)).
ballarin@15206
  1029
   Identifiers in the argument are of the form ((name, ps), axs) and
ballarin@15206
  1030
   assumptions use the axioms in the identifiers to set up exporters
ballarin@15206
  1031
   in ctxt'.  elemss' does not contain identifiers and is obtained
ballarin@15206
  1032
   from elemss and the intermediate context with prep_facts.
wenzelm@15703
  1033
   If read_facts or cert_facts is used for prep_facts, these also remove
ballarin@14508
  1034
   the internal/external markers from elemss. *)
ballarin@14508
  1035
wenzelm@13399
  1036
fun activate_facts prep_facts arg =
skalberg@15570
  1037
  apsnd (apsnd List.concat o Library.split_list) (activate_elemss prep_facts arg);
wenzelm@12546
  1038
wenzelm@15703
  1039
fun activate_note prep_facts (ctxt, args) =
wenzelm@15703
  1040
  let
wenzelm@15703
  1041
    val (ctxt', ([(_, [Notes args'])], facts)) =
wenzelm@15703
  1042
      activate_facts prep_facts (ctxt, [((("", []), []), [Ext (Notes args)])]);
wenzelm@15703
  1043
  in (ctxt', (args', facts)) end;
wenzelm@15703
  1044
wenzelm@12510
  1045
end;
wenzelm@12510
  1046
wenzelm@12307
  1047
ballarin@15696
  1048
(* register elements *)
ballarin@15696
  1049
ballarin@15696
  1050
fun register_elems (((_, ps), (((name, ax_ps), axs), _)), ctxt) =
ballarin@15696
  1051
  if name = "" then ctxt
ballarin@15696
  1052
      else let val ps' = map (fn (n, SOME T) => Free (n, T)) ax_ps
ballarin@15696
  1053
          val ctxt' = put_local_registration (name, ps') ("", []) ctxt
ballarin@15696
  1054
        in foldl (fn (ax, ctxt) =>
ballarin@15696
  1055
          add_local_witness (name, ps') ax ctxt) ctxt' axs
ballarin@15696
  1056
        end;
ballarin@15696
  1057
ballarin@15696
  1058
fun register_elemss id_elemss ctxt = 
ballarin@15696
  1059
  foldl register_elems ctxt id_elemss;
ballarin@15696
  1060
ballarin@15696
  1061
wenzelm@12529
  1062
(** prepare context elements **)
wenzelm@12529
  1063
wenzelm@12529
  1064
(* expressions *)
wenzelm@12529
  1065
wenzelm@16458
  1066
fun intern_expr thy (Locale xname) = Locale (intern thy xname)
wenzelm@16458
  1067
  | intern_expr thy (Merge exprs) = Merge (map (intern_expr thy) exprs)
wenzelm@16458
  1068
  | intern_expr thy (Rename (expr, xs)) = Rename (intern_expr thy expr, xs);
wenzelm@12529
  1069
wenzelm@12529
  1070
wenzelm@12529
  1071
(* parameters *)
wenzelm@12502
  1072
wenzelm@12502
  1073
local
wenzelm@12502
  1074
ballarin@16169
  1075
fun prep_parms prep_vars ctxt parms =
ballarin@16169
  1076
  let val vars = snd (foldl_map prep_vars (ctxt, map (fn (x, T) => ([x], T)) parms))
ballarin@16169
  1077
  in map (fn ([x'], T') => (x', T')) vars end;
wenzelm@12529
  1078
wenzelm@12529
  1079
in
wenzelm@12529
  1080
ballarin@16169
  1081
fun read_parms x = prep_parms ProofContext.read_vars x;
ballarin@16169
  1082
fun cert_parms x = prep_parms ProofContext.cert_vars x;
wenzelm@12529
  1083
wenzelm@12529
  1084
end;
wenzelm@12529
  1085
wenzelm@12529
  1086
wenzelm@12529
  1087
(* propositions and bindings *)
wenzelm@12529
  1088
ballarin@16102
  1089
(* flatten ((ids, syn), expr) normalises expr (which is either a locale
ballarin@14508
  1090
   expression or a single context element) wrt.
ballarin@14508
  1091
   to the list ids of already accumulated identifiers.
ballarin@16102
  1092
   It returns (ids', syn', elemss) where ids' is an extension of ids
ballarin@14508
  1093
   with identifiers generated for expr, and elemss is the list of
ballarin@16102
  1094
   context elements generated from expr.
ballarin@16102
  1095
   syn and syn' are symtabs mapping parameter names to their syntax.  syn'
ballarin@16102
  1096
   is an extension of syn.
ballarin@16102
  1097
   For details, see flatten_expr.
ballarin@16102
  1098
ballarin@15596
  1099
   Additionally, for a locale expression, the elems are grouped into a single
ballarin@15596
  1100
   Int; individual context elements are marked Ext.  In this case, the
ballarin@15596
  1101
   identifier-like information of the element is as follows:
ballarin@15596
  1102
   - for Fixes: (("", ps), []) where the ps have type info NONE
ballarin@15596
  1103
   - for other elements: (("", []), []).
ballarin@15206
  1104
   The implementation of activate_facts relies on identifier names being
ballarin@15206
  1105
   empty strings for external elements.
ballarin@15596
  1106
*)
ballarin@14508
  1107
ballarin@16102
  1108
fun flatten (ctxt, _) ((ids, syn), Elem (Fixes fixes)) = let
ballarin@16102
  1109
	val ids' = ids @ [(("", map #1 fixes), ([], []))]
ballarin@16102
  1110
      in
ballarin@16102
  1111
	((ids',
ballarin@16102
  1112
	 merge_syntax ctxt ids'
ballarin@16102
  1113
	   (syn, Symtab.make (map (fn fx => (#1 fx, #3 fx)) fixes))
ballarin@16102
  1114
	   handle Symtab.DUPS xs => err_in_locale ctxt
ballarin@16102
  1115
	     ("Conflicting syntax for parameters: " ^ commas_quote xs)
ballarin@16102
  1116
             (map #1 ids')),
ballarin@16102
  1117
	 [((("", map (rpair NONE o #1) fixes), []), Ext (Fixes fixes))])
ballarin@16102
  1118
      end
ballarin@16102
  1119
  | flatten _ ((ids, syn), Elem elem) =
ballarin@16102
  1120
      ((ids @ [(("", []), ([], []))], syn), [((("", []), []), Ext elem)])
ballarin@16102
  1121
  | flatten (ctxt, prep_expr) ((ids, syn), Expr expr) =
ballarin@16102
  1122
      apsnd (map (apsnd Int)) (flatten_expr ctxt ((ids, syn), prep_expr expr));
ballarin@14508
  1123
wenzelm@12529
  1124
local
wenzelm@12529
  1125
wenzelm@12839
  1126
local
wenzelm@12839
  1127
wenzelm@12727
  1128
fun declare_int_elem (ctxt, Fixes fixes) =
wenzelm@12575
  1129
      (ctxt |> ProofContext.add_fixes (map (fn (x, T, mx) =>
skalberg@15570
  1130
        (x, Option.map (Term.map_type_tfree (TypeInfer.param 0)) T, mx)) fixes), [])
wenzelm@12727
  1131
  | declare_int_elem (ctxt, _) = (ctxt, []);
wenzelm@12529
  1132
ballarin@16169
  1133
fun declare_ext_elem prep_parms (ctxt, Fixes fixes) =
ballarin@16169
  1134
      let
ballarin@16169
  1135
        val parms = map (fn (x, T, _) => (x, T)) fixes;
ballarin@16169
  1136
        val parms' = prep_parms ctxt parms;
ballarin@16169
  1137
        val fixes' = map (fn ((x, T), (_, _, mx)) => (x, T, mx)) (parms' ~~ fixes);
ballarin@16169
  1138
      in (ctxt |> ProofContext.add_fixes fixes', []) end
ballarin@16169
  1139
  | declare_ext_elem prep_parms (ctxt, Constrains csts) =
ballarin@16169
  1140
      let
ballarin@16169
  1141
        val parms = map (fn (x, T) => (x, SOME T)) csts;
ballarin@16169
  1142
        val parms' = prep_parms ctxt parms;
ballarin@16169
  1143
        val ts = map (fn (x, SOME T) => Free (x, T)) parms';
ballarin@16169
  1144
      in (Library.fold ProofContext.declare_term ts ctxt, []) end
wenzelm@12529
  1145
  | declare_ext_elem _ (ctxt, Assumes asms) = (ctxt, map #2 asms)
wenzelm@12529
  1146
  | declare_ext_elem _ (ctxt, Defines defs) = (ctxt, map (fn (_, (t, ps)) => [(t, (ps, []))]) defs)
wenzelm@12529
  1147
  | declare_ext_elem _ (ctxt, Notes facts) = (ctxt, []);
wenzelm@12529
  1148
ballarin@16169
  1149
fun declare_elems prep_parms (ctxt, (((name, ps), _), elems)) =
wenzelm@12529
  1150
  let val (ctxt', propps) =
wenzelm@12529
  1151
    (case elems of
wenzelm@13308
  1152
      Int es => foldl_map declare_int_elem (ctxt, es)
ballarin@16169
  1153
    | Ext e => foldl_map (declare_ext_elem prep_parms) (ctxt, [e]))
wenzelm@12529
  1154
    handle ProofContext.CONTEXT (msg, ctxt) => err_in_locale ctxt msg [(name, map fst ps)]
wenzelm@12727
  1155
  in (ctxt', propps) end;
wenzelm@12727
  1156
wenzelm@12839
  1157
in
wenzelm@12839
  1158
ballarin@14215
  1159
(* CB: only called by prep_elemss. *)
ballarin@14215
  1160
ballarin@16169
  1161
fun declare_elemss prep_parms fixed_params raw_elemss ctxt =
wenzelm@12727
  1162
  let
ballarin@14215
  1163
    (* CB: fix of type bug of goal in target with context elements.
ballarin@14215
  1164
       Parameters new in context elements must receive types that are
ballarin@14215
  1165
       distinct from types of parameters in target (fixed_params).  *)
ballarin@14215
  1166
    val ctxt_with_fixed =
wenzelm@16028
  1167
      fold ProofContext.declare_term (map Free fixed_params) ctxt;
wenzelm@12727
  1168
    val int_elemss =
wenzelm@12727
  1169
      raw_elemss
skalberg@15570
  1170
      |> List.mapPartial (fn (id, Int es) => SOME (id, es) | _ => NONE)
ballarin@14215
  1171
      |> unify_elemss ctxt_with_fixed fixed_params;
wenzelm@12727
  1172
    val (_, raw_elemss') =
wenzelm@12727
  1173
      foldl_map (fn ((_, es) :: elemss, (id, Int _)) => (elemss, (id, Int es)) | x => x)
wenzelm@12727
  1174
        (int_elemss, raw_elemss);
ballarin@16169
  1175
  in foldl_map (declare_elems prep_parms) (ctxt, raw_elemss') end;
wenzelm@12529
  1176
wenzelm@12839
  1177
end;
wenzelm@12529
  1178
wenzelm@12839
  1179
local
wenzelm@12839
  1180
ballarin@15596
  1181
(* CB: normalise Assumes and Defines wrt. previous definitions *)
ballarin@14508
  1182
wenzelm@12839
  1183
val norm_term = Envir.beta_norm oo Term.subst_atomic;
wenzelm@12839
  1184
ballarin@15596
  1185
(* CB: following code (abstract_term, abstract_thm, bind_def)
ballarin@15596
  1186
   used in eval_text for Defines elements. *)
ballarin@15596
  1187
wenzelm@13336
  1188
fun abstract_term eq =    (*assumes well-formedness according to ProofContext.cert_def*)
wenzelm@12839
  1189
  let
wenzelm@12839
  1190
    val body = Term.strip_all_body eq;
wenzelm@12839
  1191
    val vars = map Free (Term.rename_wrt_term body (Term.strip_all_vars eq));
wenzelm@12839
  1192
    val (lhs, rhs) = Logic.dest_equals (Term.subst_bounds (vars, body));
wenzelm@12839
  1193
    val (f, xs) = Term.strip_comb lhs;
wenzelm@13336
  1194
    val eq' = Term.list_abs_free (map Term.dest_Free xs, rhs);
wenzelm@13336
  1195
  in (Term.dest_Free f, eq') end;
wenzelm@13336
  1196
wenzelm@16458
  1197
fun abstract_thm thy eq =
wenzelm@16458
  1198
  Thm.assume (Thm.cterm_of thy eq) |> Drule.gen_all |> Drule.abs_def;
wenzelm@12502
  1199
wenzelm@13336
  1200
fun bind_def ctxt (name, ps) ((xs, env, ths), eq) =
wenzelm@12839
  1201
  let
wenzelm@13336
  1202
    val ((y, T), b) = abstract_term eq;
wenzelm@13308
  1203
    val b' = norm_term env b;
wenzelm@16458
  1204
    val th = abstract_thm (ProofContext.theory_of ctxt) eq;
wenzelm@13308
  1205
    fun err msg = err_in_locale ctxt (msg ^ ": " ^ quote y) [(name, map fst ps)];
wenzelm@12839
  1206
  in
wenzelm@13308
  1207
    conditional (exists (equal y o #1) xs) (fn () =>
wenzelm@13308
  1208
      err "Attempt to define previously specified variable");
wenzelm@13308
  1209
    conditional (exists (fn (Free (y', _), _) => y = y' | _ => false) env) (fn () =>
wenzelm@13308
  1210
      err "Attempt to redefine variable");
wenzelm@13336
  1211
    (Term.add_frees (xs, b'), (Free (y, T), b') :: env, th :: ths)
wenzelm@12839
  1212
  end;
wenzelm@12575
  1213
ballarin@15206
  1214
(* CB: for finish_elems (Int and Ext) *)
ballarin@15206
  1215
wenzelm@13308
  1216
fun eval_text _ _ _ (text, Fixes _) = text
ballarin@16169
  1217
  | eval_text _ _ _ (text, Constrains _) = text
wenzelm@13394
  1218
  | eval_text _ _ is_ext ((((exts, exts'), (ints, ints')), (xs, env, defs)), Assumes asms) =
wenzelm@13394
  1219
      let
skalberg@15570
  1220
        val ts = List.concat (map (map #1 o #2) asms);
wenzelm@13394
  1221
        val ts' = map (norm_term env) ts;
wenzelm@13394
  1222
        val spec' =
wenzelm@13394
  1223
          if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
wenzelm@13394
  1224
          else ((exts, exts'), (ints @ ts, ints' @ ts'));
skalberg@15570
  1225
      in (spec', (Library.foldl Term.add_frees (xs, ts'), env, defs)) end
ballarin@15206
  1226
  | eval_text ctxt (id, _) _ ((spec, binds), Defines defs) =
skalberg@15570
  1227
      (spec, Library.foldl (bind_def ctxt id) (binds, map (#1 o #2) defs))
wenzelm@13308
  1228
  | eval_text _ _ _ (text, Notes _) = text;
wenzelm@13308
  1229
ballarin@15206
  1230
(* CB: for finish_elems (Ext) *)
ballarin@15206
  1231
wenzelm@13308
  1232
fun closeup _ false elem = elem
wenzelm@13308
  1233
  | closeup ctxt true elem =
wenzelm@12839
  1234
      let
wenzelm@13308
  1235
        fun close_frees t =
wenzelm@13308
  1236
          let val frees = rev (filter_out (ProofContext.is_fixed ctxt o #1)
wenzelm@13308
  1237
            (Term.add_frees ([], t)))
wenzelm@13308
  1238
          in Term.list_all_free (frees, t) end;
wenzelm@13308
  1239
wenzelm@13308
  1240
        fun no_binds [] = []
wenzelm@13308
  1241
          | no_binds _ =
wenzelm@13308
  1242
              raise ProofContext.CONTEXT ("Illegal term bindings in locale element", ctxt);
wenzelm@13308
  1243
      in
wenzelm@13308
  1244
        (case elem of
wenzelm@13308
  1245
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
wenzelm@13308
  1246
            (a, map (fn (t, (ps, qs)) => (close_frees t, (no_binds ps, no_binds qs))) propps)))
wenzelm@13308
  1247
        | Defines defs => Defines (defs |> map (fn (a, (t, ps)) =>
wenzelm@13308
  1248
            (a, (close_frees (#2 (ProofContext.cert_def ctxt t)), no_binds ps))))
wenzelm@13308
  1249
        | e => e)
wenzelm@13308
  1250
      end;
wenzelm@12839
  1251
wenzelm@12502
  1252
wenzelm@12839
  1253
fun finish_ext_elem parms _ (Fixes fixes, _) = Fixes (map (fn (x, _, mx) =>
wenzelm@12727
  1254
      (x, assoc_string (parms, x), mx)) fixes)
ballarin@16169
  1255
  | finish_ext_elem parms _ (Constrains csts, _) =
ballarin@16169
  1256
      Constrains (map (fn (x, _) => (x, valOf (assoc_string (parms, x)))) csts)
wenzelm@12839
  1257
  | finish_ext_elem _ close (Assumes asms, propp) =
wenzelm@12839
  1258
      close (Assumes (map #1 asms ~~ propp))
wenzelm@12839
  1259
  | finish_ext_elem _ close (Defines defs, propp) =
wenzelm@12727
  1260
      close (Defines (map #1 defs ~~ map (fn [(t, (ps, []))] => (t, ps)) propp))
wenzelm@12839
  1261
  | finish_ext_elem _ _ (Notes facts, _) = Notes facts;
wenzelm@12839
  1262
ballarin@15206
  1263
(* CB: finish_parms introduces type info from parms to identifiers *)
skalberg@15531
  1264
(* CB: only needed for types that have been NONE so far???
ballarin@15206
  1265
   If so, which are these??? *)
ballarin@15206
  1266
ballarin@15206
  1267
fun finish_parms parms (((name, ps), axs), elems) =
ballarin@15206
  1268
  (((name, map (fn (x, _) => (x, assoc (parms, x))) ps), axs), elems);
wenzelm@12839
  1269
wenzelm@13375
  1270
fun finish_elems ctxt parms _ (text, ((id, Int e), _)) =
wenzelm@12839
  1271
      let
ballarin@15206
  1272
        val [(id', es)] = unify_elemss ctxt parms [(id, e)];
skalberg@15570
  1273
        val text' = Library.foldl (eval_text ctxt id' false) (text, es);
ballarin@15206
  1274
      in (text', (id', map Int es)) end
wenzelm@13375
  1275
  | finish_elems ctxt parms do_close (text, ((id, Ext e), [propp])) =
wenzelm@13308
  1276
      let
wenzelm@13308
  1277
        val e' = finish_ext_elem parms (closeup ctxt do_close) (e, propp);
wenzelm@13375
  1278
        val text' = eval_text ctxt id true (text, e');
wenzelm@13308
  1279
      in (text', (id, [Ext e'])) end;
wenzelm@12839
  1280
wenzelm@12839
  1281
in
wenzelm@12510
  1282
ballarin@15206
  1283
(* CB: only called by prep_elemss *)
ballarin@15206
  1284
wenzelm@13375
  1285
fun finish_elemss ctxt parms do_close =
wenzelm@13375
  1286
  foldl_map (apsnd (finish_parms parms) o finish_elems ctxt parms do_close);
wenzelm@12839
  1287
wenzelm@12839
  1288
end;
wenzelm@12839
  1289
ballarin@16736
  1290
ballarin@16736
  1291
(* CB: type inference and consistency checks for locales.
ballarin@16736
  1292
ballarin@16736
  1293
   Works by building a context (through declare_elemss), extracting the
ballarin@16736
  1294
   required information and adjusting the context elements (finish_elemss).
ballarin@16736
  1295
   Can also universally close free vars in assms and defs.  This is only
ballarin@16736
  1296
   needed for Ext elements and controlled by parameter do_close.  
ballarin@16736
  1297
*)
ballarin@15127
  1298
ballarin@16169
  1299
fun prep_elemss prep_parms prepp do_close context fixed_params raw_elemss raw_concl =
wenzelm@12529
  1300
  let
ballarin@15127
  1301
    (* CB: contexts computed in the course of this function are discarded.
ballarin@15127
  1302
       They are used for type inference and consistency checks only. *)
ballarin@15206
  1303
    (* CB: fixed_params are the parameters (with types) of the target locale,
ballarin@15206
  1304
       empty list if there is no target. *)
ballarin@14508
  1305
    (* CB: raw_elemss are list of pairs consisting of identifiers and
ballarin@14508
  1306
       context elements, the latter marked as internal or external. *)
ballarin@16169
  1307
    val (raw_ctxt, raw_proppss) = declare_elemss prep_parms fixed_params raw_elemss context;
ballarin@14508
  1308
    (* CB: raw_ctxt is context with additional fixed variables derived from
ballarin@14508
  1309
       the fixes elements in raw_elemss,
ballarin@14508
  1310
       raw_proppss contains assumptions and definitions from the
ballarin@15206
  1311
       external elements in raw_elemss. *)
skalberg@15570
  1312
    val raw_propps = map List.concat raw_proppss;
skalberg@15570
  1313
    val raw_propp = List.concat raw_propps;
ballarin@15206
  1314
wenzelm@16028
  1315
    (* CB: add type information from fixed_params to context (declare_term) *)
ballarin@15206
  1316
    (* CB: process patterns (conclusion and external elements only) *)
wenzelm@12529
  1317
    val (ctxt, all_propp) =
wenzelm@16028
  1318
      prepp (fold ProofContext.declare_term (map Free fixed_params) raw_ctxt, raw_concl @ raw_propp);
ballarin@15206
  1319
    (* CB: add type information from conclusion and external elements
ballarin@15206
  1320
       to context *)
wenzelm@16028
  1321
    val ctxt = fold ProofContext.declare_term (List.concat (map (map fst) all_propp)) ctxt;
wenzelm@12502
  1322
ballarin@15206
  1323
    (* CB: resolve schematic variables (patterns) in conclusion and external
ballarin@15206
  1324
       elements. *)
wenzelm@12529
  1325
    val all_propp' = map2 (op ~~)
wenzelm@12529
  1326
      (#1 (#2 (ProofContext.bind_propp_schematic_i (ctxt, all_propp))), map (map snd) all_propp);
nipkow@13629
  1327
    val (concl, propp) = splitAt(length raw_concl, all_propp');
wenzelm@12529
  1328
    val propps = unflat raw_propps propp;
wenzelm@12839
  1329
    val proppss = map (uncurry unflat) (raw_proppss ~~ propps);
wenzelm@12502
  1330
ballarin@15206
  1331
    (* CB: obtain all parameters from identifier part of raw_elemss *)
ballarin@15206
  1332
    val xs = map #1 (params_of' raw_elemss);
wenzelm@12727
  1333
    val typing = unify_frozen ctxt 0
wenzelm@12529
  1334
      (map (ProofContext.default_type raw_ctxt) xs)
wenzelm@12529
  1335
      (map (ProofContext.default_type ctxt) xs);
wenzelm@12529
  1336
    val parms = param_types (xs ~~ typing);
ballarin@14508
  1337
    (* CB: parms are the parameters from raw_elemss, with correct typing. *)
wenzelm@12273
  1338
ballarin@14508
  1339
    (* CB: extract information from assumes and defines elements
ballarin@16169
  1340
       (fixes, constrains and notes in raw_elemss don't have an effect on
ballarin@16169
  1341
       text and elemss), compute final form of context elements. *)
wenzelm@13394
  1342
    val (text, elemss) = finish_elemss ctxt parms do_close
wenzelm@13394
  1343
      (((([], []), ([], [])), ([], [], [])), raw_elemss ~~ proppss);
ballarin@14508
  1344
    (* CB: text has the following structure:
ballarin@14508
  1345
           (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@14508
  1346
       where
ballarin@14508
  1347
         exts: external assumptions (terms in external assumes elements)
ballarin@14508
  1348
         exts': dito, normalised wrt. env
ballarin@14508
  1349
         ints: internal assumptions (terms in internal assumes elements)
ballarin@14508
  1350
         ints': dito, normalised wrt. env
ballarin@14508
  1351
         xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@14508
  1352
           this includes parameters except defined parameters
ballarin@14508
  1353
         env: list of term pairs encoding substitutions, where the first term
ballarin@14508
  1354
           is a free variable; substitutions represent defines elements and
ballarin@14508
  1355
           the rhs is normalised wrt. the previous env
ballarin@14508
  1356
         defs: theorems representing the substitutions from defines elements
ballarin@14508
  1357
           (thms are normalised wrt. env).
ballarin@14508
  1358
       elemss is an updated version of raw_elemss:
ballarin@16169
  1359
         - type info added to Fixes and modified in Constrains
ballarin@14508
  1360
         - axiom and definition statement replaced by corresponding one
ballarin@14508
  1361
           from proppss in Assumes and Defines
ballarin@14508
  1362
         - Facts unchanged
ballarin@14508
  1363
       *)
wenzelm@13308
  1364
  in ((parms, elemss, concl), text) end;
wenzelm@12502
  1365
wenzelm@12502
  1366
in
wenzelm@12502
  1367
ballarin@16169
  1368
fun read_elemss x = prep_elemss read_parms ProofContext.read_propp_schematic x;
ballarin@16169
  1369
fun cert_elemss x = prep_elemss cert_parms ProofContext.cert_propp_schematic x;
wenzelm@12529
  1370
wenzelm@12529
  1371
end;
wenzelm@12529
  1372
wenzelm@12529
  1373
wenzelm@15703
  1374
(* facts and attributes *)
wenzelm@12529
  1375
wenzelm@12529
  1376
local
wenzelm@12529
  1377
wenzelm@15703
  1378
fun prep_name ctxt name =
ballarin@15206
  1379
  (* CB: reject qualified theorem names in locale declarations *)
wenzelm@12529
  1380
  if NameSpace.is_qualified name then
wenzelm@12529
  1381
    raise ProofContext.CONTEXT ("Illegal qualified name: " ^ quote name, ctxt)
wenzelm@15703
  1382
  else name;
wenzelm@12529
  1383
wenzelm@15703
  1384
fun prep_facts _ _ ctxt (Int elem) =
wenzelm@15703
  1385
      map_values I I (Thm.transfer (ProofContext.theory_of ctxt)) elem
wenzelm@15703
  1386
  | prep_facts get intern ctxt (Ext elem) = elem |> map_elem
wenzelm@15703
  1387
     {var = I, typ = I, term = I,
wenzelm@15703
  1388
      name = prep_name ctxt,
wenzelm@15703
  1389
      fact = get ctxt,
wenzelm@16458
  1390
      attrib = Args.assignable o intern (ProofContext.theory_of ctxt)};
wenzelm@12529
  1391
wenzelm@12529
  1392
in
wenzelm@12529
  1393
wenzelm@15703
  1394
fun read_facts x = prep_facts ProofContext.get_thms Attrib.intern_src x;
wenzelm@15703
  1395
fun cert_facts x = prep_facts (K I) (K I) x;
wenzelm@12529
  1396
wenzelm@12529
  1397
end;
wenzelm@12529
  1398
wenzelm@12529
  1399
wenzelm@12546
  1400
(* full context statements: import + elements + conclusion *)
wenzelm@12529
  1401
wenzelm@12529
  1402
local
wenzelm@12529
  1403
wenzelm@12529
  1404
fun prep_context_statement prep_expr prep_elemss prep_facts
ballarin@15206
  1405
    do_close fixed_params import elements raw_concl context =
wenzelm@12529
  1406
  let
wenzelm@16458
  1407
    val thy = ProofContext.theory_of context;
wenzelm@13375
  1408
wenzelm@16458
  1409
    val ((import_ids, import_syn), raw_import_elemss) =
wenzelm@16458
  1410
      flatten (context, prep_expr thy) (([], Symtab.empty), Expr import);
ballarin@14215
  1411
    (* CB: normalise "includes" among elements *)
wenzelm@16458
  1412
    val ((ids, syn), raw_elemsss) = foldl_map (flatten (context, prep_expr thy))
ballarin@16102
  1413
      ((import_ids, import_syn), elements);
ballarin@15696
  1414
ballarin@15696
  1415
    val raw_elemss = List.concat raw_elemsss;
ballarin@14508
  1416
    (* CB: raw_import_elemss @ raw_elemss is the normalised list of
ballarin@14508
  1417
       context elements obtained from import and elements. *)
wenzelm@13375
  1418
    val ((parms, all_elemss, concl), (spec, (_, _, defs))) = prep_elemss do_close
wenzelm@13336
  1419
      context fixed_params (raw_import_elemss @ raw_elemss) raw_concl;
ballarin@15696
  1420
    (* replace extended ids (for axioms) by ids *)
ballarin@15696
  1421
    val all_elemss' = map (fn (((_, ps), _), (((n, ps'), ax), elems)) =>
ballarin@15696
  1422
        (((n, List.filter (fn (p, _) => p mem ps) ps'), ax), elems))
ballarin@15696
  1423
      (ids ~~ all_elemss);
ballarin@15696
  1424
ballarin@15206
  1425
    (* CB: all_elemss and parms contain the correct parameter types *)
ballarin@15696
  1426
    val (ps,qs) = splitAt(length raw_import_elemss, all_elemss')
ballarin@15206
  1427
    val (import_ctxt, (import_elemss, _)) =
ballarin@15206
  1428
      activate_facts prep_facts (context, ps);
ballarin@14215
  1429
ballarin@15206
  1430
    val (ctxt, (elemss, _)) =
ballarin@15206
  1431
      activate_facts prep_facts (import_ctxt, qs);
ballarin@15212
  1432
    val stmt = gen_distinct Term.aconv
skalberg@15570
  1433
       (List.concat (map (fn ((_, axs), _) =>
skalberg@15570
  1434
         List.concat (map (#hyps o Thm.rep_thm) axs)) qs));
wenzelm@16458
  1435
    val cstmt = map (cterm_of thy) stmt;
wenzelm@12834
  1436
  in
ballarin@16102
  1437
    ((((import_ctxt, import_elemss), (ctxt, elemss, syn)), (parms, spec, defs)), (cstmt, concl))
wenzelm@12834
  1438
  end;
wenzelm@12529
  1439
wenzelm@15703
  1440
val gen_context = prep_context_statement intern_expr read_elemss read_facts;
wenzelm@15703
  1441
val gen_context_i = prep_context_statement (K I) cert_elemss cert_facts;
wenzelm@12529
  1442
wenzelm@12529
  1443
fun gen_statement prep_locale prep_ctxt raw_locale elems concl ctxt =
wenzelm@12529
  1444
  let
wenzelm@12529
  1445
    val thy = ProofContext.theory_of ctxt;
wenzelm@16458
  1446
    val locale = Option.map (prep_locale thy) raw_locale;
ballarin@15206
  1447
    val (target_stmt, fixed_params, import) =
skalberg@15531
  1448
      (case locale of NONE => ([], [], empty)
skalberg@15531
  1449
      | SOME name =>
ballarin@15206
  1450
          let val {predicate = (stmt, _), params = (ps, _), ...} =
ballarin@15206
  1451
            the_locale thy name
ballarin@16620
  1452
          in (stmt, map fst ps, Locale name) end);
ballarin@16102
  1453
    val ((((locale_ctxt, locale_elemss), (elems_ctxt, _, _)), _), (elems_stmt, concl')) =
ballarin@15206
  1454
      prep_ctxt false fixed_params import elems concl ctxt;
ballarin@15206
  1455
  in (locale, (target_stmt, elems_stmt), locale_ctxt, elems_ctxt, concl') end;
wenzelm@13399
  1456
wenzelm@12529
  1457
in
wenzelm@12529
  1458
ballarin@15127
  1459
(* CB: processing of locales for add_locale(_i) and print_locale *)
ballarin@15127
  1460
  (* CB: arguments are: x->import, y->body (elements), z->context *)
ballarin@15206
  1461
fun read_context x y z = #1 (gen_context true [] x (map Elem y) [] z);
ballarin@15206
  1462
fun cert_context x y z = #1 (gen_context_i true [] x (map Elem y) [] z);
ballarin@14215
  1463
ballarin@15127
  1464
(* CB: processing of locales for note_thmss(_i),
ballarin@15127
  1465
   Proof.multi_theorem(_i) and antiquotations with option "locale" *)
wenzelm@12529
  1466
val read_context_statement = gen_statement intern gen_context;
wenzelm@12529
  1467
val cert_context_statement = gen_statement (K I) gen_context_i;
wenzelm@12502
  1468
wenzelm@12502
  1469
end;
wenzelm@11896
  1470
wenzelm@11896
  1471
wenzelm@13336
  1472
(** define locales **)
wenzelm@13336
  1473
wenzelm@13336
  1474
(* print locale *)
wenzelm@12070
  1475
wenzelm@12758
  1476
fun print_locale thy import body =
wenzelm@12070
  1477
  let
wenzelm@12289
  1478
    val thy_ctxt = ProofContext.init thy;
ballarin@16102
  1479
    val (((_, import_elemss), (ctxt, elemss, _)), _) = read_context import body thy_ctxt;
skalberg@15570
  1480
    val all_elems = List.concat (map #2 (import_elemss @ elemss));
wenzelm@12070
  1481
wenzelm@12307
  1482
    val prt_typ = Pretty.quote o ProofContext.pretty_typ ctxt;
wenzelm@12307
  1483
    val prt_term = Pretty.quote o ProofContext.pretty_term ctxt;
wenzelm@12307
  1484
    val prt_thm = Pretty.quote o ProofContext.pretty_thm ctxt;
wenzelm@15703
  1485
    val prt_atts = Args.pretty_attribs ctxt;
wenzelm@12070
  1486
wenzelm@12070
  1487
    fun prt_syn syn =
skalberg@15531
  1488
      let val s = (case syn of NONE => "(structure)" | SOME mx => Syntax.string_of_mixfix mx)
wenzelm@12575
  1489
      in if s = "" then [] else [Pretty.brk 2, Pretty.str s] end;
skalberg@15531
  1490
    fun prt_fix (x, SOME T, syn) = Pretty.block (Pretty.str (x ^ " ::") :: Pretty.brk 1 ::
wenzelm@12070
  1491
          prt_typ T :: Pretty.brk 1 :: prt_syn syn)
skalberg@15531
  1492
      | prt_fix (x, NONE, syn) = Pretty.block (Pretty.str x :: Pretty.brk 1 :: prt_syn syn);
ballarin@16169
  1493
    fun prt_cst (x, T) = Pretty.block [Pretty.str (x ^ " ::"), prt_typ T];
wenzelm@12070
  1494
wenzelm@16346
  1495
    fun prt_name name = Pretty.str (ProofContext.extern_thm ctxt name);
wenzelm@15703
  1496
    fun prt_name_atts (name, atts) =
wenzelm@15703
  1497
      if name = "" andalso null atts then []
wenzelm@15703
  1498
      else [Pretty.block (Pretty.breaks (prt_name name :: prt_atts atts @ [Pretty.str ":"]))];
wenzelm@15703
  1499
wenzelm@15703
  1500
    fun prt_asm (a, ts) =
wenzelm@15703
  1501
      Pretty.block (Pretty.breaks (prt_name_atts a @ map (prt_term o fst) ts));
wenzelm@15703
  1502
    fun prt_def (a, (t, _)) =
wenzelm@15703
  1503
      Pretty.block (Pretty.breaks (prt_name_atts a @ [prt_term t]));
wenzelm@15703
  1504
wenzelm@15703
  1505
    fun prt_fact (ths, []) = map prt_thm ths
wenzelm@15703
  1506
      | prt_fact (ths, atts) =
wenzelm@15703
  1507
          Pretty.enclose "(" ")" (Pretty.breaks (map prt_thm ths)) :: prt_atts atts;
wenzelm@15703
  1508
    fun prt_note (a, ths) =
wenzelm@15703
  1509
      Pretty.block (Pretty.breaks (List.concat (prt_name_atts a :: map prt_fact ths)));
wenzelm@12070
  1510
wenzelm@12289
  1511
    fun items _ [] = []
wenzelm@12289
  1512
      | items prfx (x :: xs) = Pretty.block [Pretty.str prfx, Pretty.brk 1, x] :: items "  and" xs;
wenzelm@12289
  1513
    fun prt_elem (Fixes fixes) = items "fixes" (map prt_fix fixes)
ballarin@16169
  1514
      | prt_elem (Constrains csts) = items "constrains" (map prt_cst csts)
wenzelm@12289
  1515
      | prt_elem (Assumes asms) = items "assumes" (map prt_asm asms)
wenzelm@12289
  1516
      | prt_elem (Defines defs) = items "defines" (map prt_def defs)
wenzelm@15703
  1517
      | prt_elem (Notes facts) = items "notes" (map prt_note facts);
wenzelm@12277
  1518
  in
wenzelm@13336
  1519
    Pretty.big_list "context elements:" (map (Pretty.chunks o prt_elem) all_elems)
wenzelm@13336
  1520
    |> Pretty.writeln
wenzelm@12277
  1521
  end;
wenzelm@12070
  1522
wenzelm@12070
  1523
wenzelm@12706
  1524
wenzelm@16144
  1525
(** store results **)
wenzelm@12702
  1526
wenzelm@16144
  1527
(* note_thmss_qualified *)
ballarin@15696
  1528
wenzelm@14564
  1529
fun note_thmss_qualified kind name args thy =
wenzelm@12706
  1530
  thy
wenzelm@13375
  1531
  |> Theory.add_path (Sign.base_name name)
wenzelm@16144
  1532
  |> Theory.no_base_names
wenzelm@14564
  1533
  |> PureThy.note_thmss_i (Drule.kind kind) args
wenzelm@16144
  1534
  |>> Theory.restore_naming thy;
wenzelm@16144
  1535
wenzelm@12706
  1536
ballarin@15696
  1537
(* accesses of interpreted theorems *)
ballarin@15696
  1538
wenzelm@16144
  1539
local
wenzelm@16144
  1540
wenzelm@16144
  1541
(*fully qualified name in theory is T.p.r.n where
wenzelm@16144
  1542
  T: theory name, p: interpretation prefix, r: renaming prefix, n: name*)
wenzelm@16144
  1543
fun global_accesses _ [] = []
wenzelm@16144
  1544
  | global_accesses "" [T, n] = [[T, n], [n]]
wenzelm@16144
  1545
  | global_accesses "" [T, r, n] = [[T, r, n], [T, n], [r, n], [n]]
wenzelm@16144
  1546
  | global_accesses _ [T, p, n] = [[T, p, n], [p, n]]
wenzelm@16144
  1547
  | global_accesses _ [T, p, r, n] = [[T, p, r, n], [T, p, n], [p, r, n], [p, n]]
wenzelm@16144
  1548
  | global_accesses _ names = error ("Bad name declaration " ^ quote (NameSpace.pack names));
ballarin@15696
  1549
wenzelm@16144
  1550
(*fully qualified name in context is p.r.n where
wenzelm@16144
  1551
  p: interpretation prefix, r: renaming prefix, n: name*)
wenzelm@16144
  1552
fun local_accesses _ [] = []
wenzelm@16144
  1553
  | local_accesses "" [n] = [[n]]
wenzelm@16144
  1554
  | local_accesses "" [r, n] = [[r, n], [n]]
wenzelm@16144
  1555
  | local_accesses _ [p, n] = [[p, n]]
wenzelm@16144
  1556
  | local_accesses _ [p, r, n] = [[p, r, n], [p, n]]
wenzelm@16144
  1557
  | local_accesses _ names = error ("Bad name declaration " ^ quote (NameSpace.pack names));
wenzelm@16144
  1558
wenzelm@16144
  1559
in
ballarin@15696
  1560
wenzelm@16144
  1561
fun global_note_accesses_i kind prfx args thy =
wenzelm@16144
  1562
  thy
wenzelm@16144
  1563
  |> Theory.qualified_names
wenzelm@16144
  1564
  |> Theory.custom_accesses (global_accesses prfx)
wenzelm@16144
  1565
  |> PureThy.note_thmss_i kind args
wenzelm@16144
  1566
  |>> Theory.restore_naming thy;
ballarin@15696
  1567
wenzelm@16144
  1568
fun local_note_accesses_i prfx args ctxt =
wenzelm@16144
  1569
  ctxt
wenzelm@16144
  1570
  |> ProofContext.qualified_names
wenzelm@16144
  1571
  |> ProofContext.custom_accesses (local_accesses prfx)
wenzelm@16144
  1572
  |> ProofContext.note_thmss_i args
wenzelm@16144
  1573
  |>> ProofContext.restore_naming ctxt;
wenzelm@16144
  1574
wenzelm@16144
  1575
end;
ballarin@15696
  1576
ballarin@15696
  1577
ballarin@15696
  1578
(* store instantiations of args for all registered interpretations
ballarin@15696
  1579
   of the theory *)
ballarin@15696
  1580
ballarin@15696
  1581
fun note_thmss_registrations kind target args thy =
ballarin@15596
  1582
  let
ballarin@16620
  1583
    val (parms, parmTs) =
ballarin@16102
  1584
          the_locale thy target |> #params |> fst |> map fst |> split_list;
ballarin@16620
  1585
    val parmvTs = map Type.varifyT parmTs;
wenzelm@16458
  1586
    val ids = flatten (ProofContext.init thy, intern_expr thy)
wenzelm@16144
  1587
      (([], Symtab.empty), Expr (Locale target)) |> fst |> fst |> map fst;
ballarin@15696
  1588
ballarin@15696
  1589
    val regs = get_global_registrations thy target;
ballarin@15696
  1590
ballarin@15696
  1591
    (* add args to thy for all registrations *)
ballarin@15596
  1592
ballarin@15696
  1593
    fun activate (thy, (vts, ((prfx, atts2), _))) =
ballarin@15696
  1594
      let
ballarin@15696
  1595
        val ts = map Logic.unvarify vts;
ballarin@15696
  1596
        (* type instantiation *)
wenzelm@16458
  1597
        val vtinst = Library.foldl (Type.typ_match (Sign.tsig_of thy))
ballarin@15696
  1598
             (Vartab.empty, (parmvTs ~~ map Term.fastype_of ts));
berghofe@15798
  1599
        val tinst = Vartab.dest vtinst |> map (fn ((x, 0), (_, T)) => (x, T))
ballarin@15696
  1600
             |> Symtab.make;            
ballarin@15696
  1601
        (* replace parameter names in ids by instantiations *)
ballarin@15696
  1602
        val vinst = Symtab.make (parms ~~ vts);
ballarin@15696
  1603
        fun vinst_names ps = map (fn p => Symtab.lookup (vinst, p) |> valOf) ps;
ballarin@15696
  1604
        val inst = Symtab.make (parms ~~ ts);
ballarin@15696
  1605
        val ids' = map (apsnd vinst_names) ids;
ballarin@15696
  1606
        val prems = List.concat (map (snd o valOf o get_global_registration thy) ids');
ballarin@15696
  1607
        val args' = map (fn ((n, atts), [(ths, [])]) =>
wenzelm@16144
  1608
            ((if prfx = "" orelse n = "" then "" else NameSpace.pack [prfx, n],  (* FIXME *)
wenzelm@15703
  1609
              map (Attrib.global_attribute_i thy) (atts @ atts2)),
wenzelm@16458
  1610
             [(map (Drule.standard o Drule.satisfy_hyps prems o inst_tab_thm thy (inst, tinst)) ths, [])]))
ballarin@15696
  1611
          args;
wenzelm@16144
  1612
      in global_note_accesses_i (Drule.kind kind) prfx args' thy |> fst end;
ballarin@15696
  1613
  in Library.foldl activate (thy, regs) end;
ballarin@15596
  1614
ballarin@15596
  1615
skalberg@15531
  1616
fun smart_note_thmss kind NONE = PureThy.note_thmss_i (Drule.kind kind)
wenzelm@15703
  1617
  | smart_note_thmss kind (SOME loc) = note_thmss_qualified kind loc;
wenzelm@12958
  1618
wenzelm@12958
  1619
wenzelm@12958
  1620
local
wenzelm@12958
  1621
ballarin@15696
  1622
(* add facts to locale in theory *)
ballarin@15696
  1623
wenzelm@12958
  1624
fun put_facts loc args thy =
wenzelm@12958
  1625
  let
ballarin@16736
  1626
    val {predicate, import, elems, params, regs} = the_locale thy loc;
wenzelm@15703
  1627
    val note = Notes (map (fn ((a, atts), bs) =>
wenzelm@15703
  1628
      ((a, atts), map (apfst (map (curry Thm.name_thm a))) bs)) args);
wenzelm@15703
  1629
  in
wenzelm@15703
  1630
    thy |> put_locale loc {predicate = predicate, import = import,
ballarin@16736
  1631
      elems = elems @ [(note, stamp ())], params = params, regs = regs}
wenzelm@15703
  1632
  end;
wenzelm@12958
  1633
ballarin@15696
  1634
(* add theorem to locale and theory,
ballarin@15696
  1635
   base for theorems (in loc) and declare (in loc) *)
ballarin@15696
  1636
wenzelm@15703
  1637
fun gen_note_thmss prep_locale prep_facts kind raw_loc args thy =
wenzelm@12706
  1638
  let
wenzelm@12706
  1639
    val thy_ctxt = ProofContext.init thy;
wenzelm@16458
  1640
    val loc = prep_locale thy raw_loc;
wenzelm@15703
  1641
    val (_, (stmt, _), loc_ctxt, _, _) = cert_context_statement (SOME loc) [] [] thy_ctxt;
ballarin@15206
  1642
    val export = ProofContext.export_standard stmt loc_ctxt thy_ctxt;
wenzelm@15703
  1643
wenzelm@15703
  1644
    val (args', facts) = #2 (activate_note prep_facts (loc_ctxt, args));
wenzelm@15703
  1645
    val facts' =
wenzelm@15703
  1646
      map (rpair [] o #1 o #1) args' ~~
wenzelm@15703
  1647
      map (single o Thm.no_attributes o map export o #2) facts;
wenzelm@12706
  1648
  in
wenzelm@12706
  1649
    thy
wenzelm@15703
  1650
    |> put_facts loc args'
wenzelm@15703
  1651
    |> note_thmss_registrations kind loc args'
wenzelm@15703
  1652
    |> note_thmss_qualified kind loc facts'
wenzelm@12706
  1653
  end;
wenzelm@12706
  1654
wenzelm@12706
  1655
in
wenzelm@12706
  1656
wenzelm@15703
  1657
val note_thmss = gen_note_thmss intern read_facts;
wenzelm@15703
  1658
val note_thmss_i = gen_note_thmss (K I) cert_facts;
wenzelm@12711
  1659
ballarin@15696
  1660
fun add_thmss kind loc args (thy, ctxt) =
wenzelm@12958
  1661
  let
wenzelm@15703
  1662
    val (ctxt', (args', facts)) = activate_note cert_facts
wenzelm@15703
  1663
      (ctxt, args |> map (fn ((a, ths), atts) => ((a, atts), [(ths, [])])));
wenzelm@15703
  1664
    val thy' =
wenzelm@15703
  1665
      thy
wenzelm@15703
  1666
      |> put_facts loc args'
wenzelm@15703
  1667
      |> note_thmss_registrations kind loc args';
wenzelm@15703
  1668
  in ((thy', ctxt'), facts) end;
wenzelm@12702
  1669
wenzelm@12706
  1670
end;
wenzelm@12063
  1671
wenzelm@11896
  1672
wenzelm@13336
  1673
(* predicate text *)
ballarin@15596
  1674
(* CB: generate locale predicates and delta predicates *)
wenzelm@13336
  1675
wenzelm@13375
  1676
local
wenzelm@13375
  1677
ballarin@15206
  1678
(* introN: name of theorems for introduction rules of locale and
ballarin@15206
  1679
     delta predicates;
ballarin@15206
  1680
   axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@15206
  1681
     also name suffix of delta predicates. *)
ballarin@15206
  1682
wenzelm@13375
  1683
val introN = "intro";
ballarin@15206
  1684
val axiomsN = "axioms";
wenzelm@13375
  1685
wenzelm@16458
  1686
fun atomize_spec thy ts =
wenzelm@13375
  1687
  let
skalberg@15574
  1688
    val t = foldr1 Logic.mk_conjunction ts;
wenzelm@16458
  1689
    val body = ObjectLogic.atomize_term thy t;
wenzelm@13375
  1690
    val bodyT = Term.fastype_of body;
wenzelm@13375
  1691
  in
wenzelm@16458
  1692
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
wenzelm@16458
  1693
    else (body, bodyT, ObjectLogic.atomize_rule thy (Thm.cterm_of thy t))
wenzelm@13375
  1694
  end;
wenzelm@13375
  1695
wenzelm@13394
  1696
fun aprop_tr' n c = (c, fn args =>
wenzelm@13394
  1697
  if length args = n then Syntax.const "_aprop" $ Term.list_comb (Syntax.free c, args)
wenzelm@13394
  1698
  else raise Match);
wenzelm@13336
  1699
ballarin@15104
  1700
(* CB: define one predicate including its intro rule and axioms
ballarin@15104
  1701
   - bname: predicate name
ballarin@15104
  1702
   - parms: locale parameters
ballarin@15104
  1703
   - defs: thms representing substitutions from defines elements
ballarin@15104
  1704
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@15104
  1705
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@15104
  1706
   - thy: the theory
ballarin@15104
  1707
*)
ballarin@15104
  1708
wenzelm@13420
  1709
fun def_pred bname parms defs ts norm_ts thy =
wenzelm@13375
  1710
  let
wenzelm@16458
  1711
    val name = Sign.full_name thy bname;
wenzelm@13375
  1712
wenzelm@16458
  1713
    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
wenzelm@13394
  1714
    val env = Term.add_term_free_names (body, []);
skalberg@15570
  1715
    val xs = List.filter (fn (x, _) => x mem_string env) parms;
wenzelm@13394
  1716
    val Ts = map #2 xs;
skalberg@15574
  1717
    val extraTs = (Term.term_tfrees body \\ foldr Term.add_typ_tfrees [] Ts)
wenzelm@13394
  1718
      |> Library.sort_wrt #1 |> map TFree;
wenzelm@13399
  1719
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
wenzelm@13336
  1720
wenzelm@13394
  1721
    val args = map Logic.mk_type extraTs @ map Free xs;
wenzelm@13394
  1722
    val head = Term.list_comb (Const (name, predT), args);
wenzelm@16458
  1723
    val statement = ObjectLogic.assert_propT thy head;
wenzelm@13375
  1724
wenzelm@13375
  1725
    val (defs_thy, [pred_def]) =
wenzelm@13375
  1726
      thy
wenzelm@13394
  1727
      |> (if bodyT <> propT then I else
wenzelm@13394
  1728
        Theory.add_trfuns ([], [], map (aprop_tr' (length args)) (NameSpace.accesses' name), []))
wenzelm@13375
  1729
      |> Theory.add_consts_i [(bname, predT, Syntax.NoSyn)]
wenzelm@13375
  1730
      |> PureThy.add_defs_i false [((Thm.def_name bname, Logic.mk_equals (head, body)), [])];
wenzelm@13394
  1731
wenzelm@16458
  1732
    val cert = Thm.cterm_of defs_thy;
wenzelm@13375
  1733
wenzelm@16458
  1734
    val intro = Tactic.prove_standard defs_thy [] norm_ts statement (fn _ =>
wenzelm@13375
  1735
      Tactic.rewrite_goals_tac [pred_def] THEN
wenzelm@13375
  1736
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
wenzelm@13420
  1737
      Tactic.compose_tac (false, Drule.conj_intr_list (map (Thm.assume o cert) norm_ts), 0) 1);
wenzelm@13375
  1738
wenzelm@13375
  1739
    val conjuncts =
wenzelm@13399
  1740
      Drule.equal_elim_rule1 OF [Thm.symmetric body_eq,
wenzelm@13399
  1741
        Tactic.rewrite_rule [pred_def] (Thm.assume (cert statement))]
wenzelm@13375
  1742
      |> Drule.conj_elim_precise (length ts);
wenzelm@13394
  1743
    val axioms = (ts ~~ conjuncts) |> map (fn (t, ax) =>
wenzelm@16458
  1744
      Tactic.prove_plain defs_thy [] [] t (fn _ =>
wenzelm@13375
  1745
        Tactic.rewrite_goals_tac defs THEN
wenzelm@13375
  1746
        Tactic.compose_tac (false, ax, 0) 1));
wenzelm@13394
  1747
  in (defs_thy, (statement, intro, axioms)) end;
wenzelm@13375
  1748
ballarin@15104
  1749
(* CB: modify the locale elements:
ballarin@15623
  1750
   - assumes elements become notes elements,
ballarin@15104
  1751
   - notes elements are lifted
ballarin@15104
  1752
*)
ballarin@15104
  1753
wenzelm@15703
  1754
fun change_elem (axms, Assumes asms) =
wenzelm@13394
  1755
      apsnd Notes ((axms, asms) |> foldl_map (fn (axs, (a, spec)) =>
nipkow@13629
  1756
        let val (ps,qs) = splitAt(length spec, axs)
nipkow@13629
  1757
        in (qs, (a, [(ps, [])])) end))
wenzelm@15703
  1758
  | change_elem e = e;
wenzelm@13394
  1759
ballarin@15206
  1760
(* CB: changes only "new" elems, these have identifier ("", _). *)
ballarin@15206
  1761
wenzelm@13394
  1762
fun change_elemss axioms elemss = (axioms, elemss) |> foldl_map
wenzelm@13394
  1763
  (fn (axms, (id as ("", _), es)) =>
wenzelm@15703
  1764
    foldl_map change_elem (axms, map (map_values I I (Drule.satisfy_hyps axioms)) es)
wenzelm@15703
  1765
    |> apsnd (pair id)
wenzelm@13394
  1766
  | x => x) |> #2;
wenzelm@13394
  1767
wenzelm@13394
  1768
in
wenzelm@13375
  1769
ballarin@15104
  1770
(* CB: main predicate definition function *)
ballarin@15104
  1771
wenzelm@13394
  1772
fun define_preds bname (parms, ((exts, exts'), (ints, ints')), defs) elemss thy =
wenzelm@13394
  1773
  let
wenzelm@13394
  1774
    val (thy', (elemss', more_ts)) =
skalberg@15531
  1775
      if null exts then (thy, (elemss, []))
wenzelm@13394
  1776
      else
wenzelm@13394
  1777
        let
skalberg@15531
  1778
          val aname = if null ints then bname else bname ^ "_" ^ axiomsN;
wenzelm@13394
  1779
          val (def_thy, (statement, intro, axioms)) =
wenzelm@13394
  1780
            thy |> def_pred aname parms defs exts exts';
ballarin@16325
  1781
          val elemss' = change_elemss (map (Drule.zero_var_indexes o Drule.gen_all) axioms) elemss @
wenzelm@13420
  1782
            [(("", []), [Assumes [((bname ^ "_" ^ axiomsN, []), [(statement, ([], []))])]])];
wenzelm@13394
  1783
        in
wenzelm@14564
  1784
          def_thy |> note_thmss_qualified "" aname
ballarin@14254
  1785
            [((introN, []), [([intro], [])])]
wenzelm@13394
  1786
          |> #1 |> rpair (elemss', [statement])
wenzelm@13394
  1787
        end;
ballarin@15206
  1788
    val (thy'', predicate) =
skalberg@15531
  1789
      if null ints then (thy', ([], []))
wenzelm@13394
  1790
      else
wenzelm@13394
  1791
        let
wenzelm@13394
  1792
          val (def_thy, (statement, intro, axioms)) =
wenzelm@13394
  1793
            thy' |> def_pred bname parms defs (ints @ more_ts) (ints' @ more_ts);
wenzelm@16458
  1794
          val cstatement = Thm.cterm_of def_thy statement;
wenzelm@13394
  1795
        in
wenzelm@14564
  1796
          def_thy |> note_thmss_qualified "" bname
ballarin@14254
  1797
            [((introN, []), [([intro], [])]),
ballarin@14254
  1798
             ((axiomsN, []), [(map Drule.standard axioms, [])])]
wenzelm@13415
  1799
          |> #1 |> rpair ([cstatement], axioms)
wenzelm@13394
  1800
        end;
ballarin@15206
  1801
  in (thy'', (elemss', predicate)) end;
wenzelm@13375
  1802
wenzelm@13375
  1803
end;
wenzelm@13336
  1804
wenzelm@13336
  1805
wenzelm@13297
  1806
(* add_locale(_i) *)
wenzelm@13297
  1807
wenzelm@13297
  1808
local
wenzelm@13297
  1809
wenzelm@13394
  1810
fun gen_add_locale prep_ctxt prep_expr do_pred bname raw_import raw_body thy =
ballarin@15596
  1811
  (* CB: do_pred controls generation of predicates.
ballarin@15596
  1812
         true -> with, false -> without predicates. *)
wenzelm@13297
  1813
  let
wenzelm@16458
  1814
    val name = Sign.full_name thy bname;
skalberg@15570
  1815
    val _ = conditional (isSome (get_locale thy name)) (fn () =>
wenzelm@13297
  1816
      error ("Duplicate definition of locale " ^ quote name));
wenzelm@13297
  1817
wenzelm@13297
  1818
    val thy_ctxt = ProofContext.init thy;
ballarin@16102
  1819
    val (((import_ctxt, import_elemss), (body_ctxt, body_elemss, syn)), text) =
wenzelm@13375
  1820
      prep_ctxt raw_import raw_body thy_ctxt;
wenzelm@13375
  1821
    val elemss = import_elemss @ body_elemss;
wenzelm@16458
  1822
    val import = prep_expr thy raw_import;
wenzelm@13297
  1823
ballarin@15206
  1824
    val (pred_thy, (elemss', predicate as (predicate_statement, predicate_axioms))) =
wenzelm@13394
  1825
      if do_pred then thy |> define_preds bname text elemss
wenzelm@13415
  1826
      else (thy, (elemss, ([], [])));
wenzelm@13375
  1827
    val pred_ctxt = ProofContext.init pred_thy;
wenzelm@13420
  1828
ballarin@15206
  1829
    fun axiomify axioms elemss = 
ballarin@15206
  1830
      (axioms, elemss) |> foldl_map (fn (axs, (id, elems)) => let
skalberg@15570
  1831
                   val ts = List.concat (List.mapPartial (fn (Assumes asms) =>
skalberg@15570
  1832
                     SOME (List.concat (map (map #1 o #2) asms)) | _ => NONE) elems);
ballarin@15206
  1833
                   val (axs1, axs2) = splitAt (length ts, axs);
ballarin@15206
  1834
                 in (axs2, ((id, axs1), elems)) end)
ballarin@15206
  1835
        |> snd;
ballarin@15206
  1836
    val (ctxt, (_, facts)) = activate_facts (K I)
ballarin@15206
  1837
      (pred_ctxt, axiomify predicate_axioms elemss');
ballarin@15206
  1838
    val export = ProofContext.export_standard predicate_statement ctxt pred_ctxt;
wenzelm@13420
  1839
    val facts' = facts |> map (fn (a, ths) => ((a, []), [(map export ths, [])]));
wenzelm@13297
  1840
  in
wenzelm@13375
  1841
    pred_thy
wenzelm@14564
  1842
    |> note_thmss_qualified "" name facts' |> #1
wenzelm@13297
  1843
    |> declare_locale name
wenzelm@16458
  1844
    |> put_locale name {predicate = predicate, import = import,
skalberg@15570
  1845
        elems = map (fn e => (e, stamp ())) (List.concat (map #2 (List.filter (equal "" o #1 o #1) elemss'))),
ballarin@16102
  1846
        params = (params_of elemss' |>
ballarin@16736
  1847
          map (fn (x, SOME T) => ((x, T), valOf (Symtab.lookup (syn, x)))), map #1 (params_of body_elemss)),
ballarin@16736
  1848
        regs = []}
wenzelm@13297
  1849
  end;
wenzelm@13297
  1850
wenzelm@13297
  1851
in
wenzelm@13297
  1852
wenzelm@13297
  1853
val add_locale = gen_add_locale read_context intern_expr;
wenzelm@13297
  1854
val add_locale_i = gen_add_locale cert_context (K I);
wenzelm@13297
  1855
wenzelm@13297
  1856
end;
wenzelm@13297
  1857
wenzelm@15801
  1858
val _ = Context.add_setup
wenzelm@15801
  1859
 [add_locale_i true "var" empty [Fixes [(Syntax.internal "x", NONE, SOME Syntax.NoSyn)]],
wenzelm@15801
  1860
  add_locale_i true "struct" empty [Fixes [(Syntax.internal "S", NONE, NONE)]]];
wenzelm@15801
  1861
wenzelm@13297
  1862
wenzelm@12730
  1863
ballarin@15598
  1864
(** Interpretation commands **)
ballarin@15596
  1865
ballarin@15596
  1866
local
ballarin@15596
  1867
ballarin@15596
  1868
(* extract proof obligations (assms and defs) from elements *)
ballarin@15596
  1869
ballarin@15596
  1870
fun extract_asms_elem (ts, Fixes _) = ts
ballarin@16169
  1871
  | extract_asms_elem (ts, Constrains _) = ts
ballarin@15596
  1872
  | extract_asms_elem (ts, Assumes asms) =
ballarin@15596
  1873
      ts @ List.concat (map (fn (_, ams) => map (fn (t, _) => t) ams) asms)
ballarin@15596
  1874
  | extract_asms_elem (ts, Defines defs) =
ballarin@16169
  1875
      ts @ map (fn (_, (def, _)) => def) defs
ballarin@15596
  1876
  | extract_asms_elem (ts, Notes _) = ts;
ballarin@15596
  1877
ballarin@15596
  1878
fun extract_asms_elems (id, elems) =
ballarin@15596
  1879
      (id, Library.foldl extract_asms_elem ([], elems));
ballarin@15596
  1880
ballarin@15596
  1881
fun extract_asms_elemss elemss =
ballarin@15596
  1882
      map extract_asms_elems elemss;
ballarin@15596
  1883
ballarin@15624
  1884
(* activate instantiated facts in theory or context *)
ballarin@15596
  1885
ballarin@15624
  1886
fun activate_facts_elem _ _ _ _ (thy_ctxt, Fixes _) = thy_ctxt
ballarin@16169
  1887
  | activate_facts_elem _ _ _ _ (thy_ctxt, Constrains _) = thy_ctxt
ballarin@15624
  1888
  | activate_facts_elem _ _ _ _ (thy_ctxt, Assumes _) = thy_ctxt
ballarin@15624
  1889
  | activate_facts_elem _ _ _ _ (thy_ctxt, Defines _) = thy_ctxt
wenzelm@15703
  1890
  | activate_facts_elem note_thmss attrib
ballarin@15624
  1891
        disch (prfx, atts) (thy_ctxt, Notes facts) =
ballarin@15596
  1892
      let
wenzelm@15703
  1893
        val reg_atts = map (attrib thy_ctxt) atts;
ballarin@15763
  1894
        (* discharge hyps in attributes *)
ballarin@15763
  1895
        val facts = map_attrib_facts (attrib thy_ctxt o Args.map_values I I I disch) facts;
wenzelm@15703
  1896
        val facts' = map (apfst (apsnd (fn a => a @ reg_atts))) facts;
wenzelm@15703
  1897
        (* discharge hyps *)
ballarin@15624
  1898
        val facts'' = map (apsnd (map (apfst (map disch)))) facts';
ballarin@15624
  1899
        (* prefix names *)
wenzelm@16144
  1900
        val facts''' = map (apfst (apfst (NameSpace.qualified prfx))) facts'';
ballarin@15596
  1901
      in
ballarin@15624
  1902
        fst (note_thmss prfx facts''' thy_ctxt)
ballarin@15596
  1903
      end;
ballarin@15596
  1904
wenzelm@15703
  1905
fun activate_facts_elems get_reg note_thmss attrib
ballarin@15624
  1906
        disch (thy_ctxt, (id, elems)) =
ballarin@15596
  1907
      let
ballarin@15624
  1908
        val ((prfx, atts2), _) = valOf (get_reg thy_ctxt id)
ballarin@15596
  1909
          handle Option => error ("(internal) unknown registration of " ^
ballarin@15596
  1910
            quote (fst id) ^ " while activating facts.");
ballarin@15596
  1911
      in
wenzelm@15703
  1912
        Library.foldl (activate_facts_elem note_thmss attrib
ballarin@15624
  1913
          disch (prfx, atts2)) (thy_ctxt, elems)
ballarin@15596
  1914
      end;
ballarin@15596
  1915
wenzelm@15703
  1916
fun gen_activate_facts_elemss get_reg note_thmss attrib standard
ballarin@15624
  1917
        all_elemss new_elemss thy_ctxt =
ballarin@15596
  1918
      let
ballarin@15596
  1919
        val prems = List.concat (List.mapPartial (fn (id, _) =>
ballarin@15624
  1920
              Option.map snd (get_reg thy_ctxt id)
ballarin@15596
  1921
                handle Option => error ("(internal) unknown registration of " ^
ballarin@15596
  1922
                  quote (fst id) ^ " while activating facts.")) all_elemss);
wenzelm@15703
  1923
      in Library.foldl (activate_facts_elems get_reg note_thmss attrib
ballarin@15839
  1924
        (standard o Drule.fconv_rule (Thm.beta_conversion true) o
ballarin@15837
  1925
          Drule.satisfy_hyps prems)) (thy_ctxt, new_elemss) end;
ballarin@15596
  1926
ballarin@15624
  1927
val global_activate_facts_elemss = gen_activate_facts_elemss
ballarin@15696
  1928
      (fn thy => fn (name, ps) =>
ballarin@15696
  1929
        get_global_registration thy (name, map Logic.varify ps))
wenzelm@16144
  1930
      (global_note_accesses_i (Drule.kind ""))
wenzelm@15703
  1931
      Attrib.global_attribute_i Drule.standard;
wenzelm@16144
  1932
ballarin@15624
  1933
val local_activate_facts_elemss = gen_activate_facts_elemss
ballarin@15696
  1934
      get_local_registration
wenzelm@16144
  1935
      local_note_accesses_i
wenzelm@15703
  1936
      Attrib.context_attribute_i I;
ballarin@15624
  1937
ballarin@15696
  1938
fun gen_prep_registration mk_ctxt is_local read_terms test_reg put_reg activate
ballarin@15624
  1939
    attn expr insts thy_ctxt =
ballarin@15596
  1940
  let
ballarin@15624
  1941
    val ctxt = mk_ctxt thy_ctxt;
wenzelm@16458
  1942
    val thy = ProofContext.theory_of ctxt;
ballarin@15596
  1943
ballarin@15696
  1944
    val ctxt' = ctxt |> ProofContext.theory_of |> ProofContext.init;
wenzelm@16458
  1945
    val ((ids, _), raw_elemss) = flatten (ctxt', intern_expr thy)
ballarin@16102
  1946
          (([], Symtab.empty), Expr expr);
ballarin@15596
  1947
    val ((parms, all_elemss, _), (spec, (xs, defs, _))) =
ballarin@16736
  1948
          read_elemss false ctxt' [] raw_elemss [];
ballarin@15596
  1949
ballarin@15596
  1950
ballarin@15596
  1951
    (** compute instantiation **)
ballarin@15596
  1952
ballarin@15696
  1953
    (* user input *)
ballarin@15596
  1954
    val insts = if length parms < length insts
ballarin@15596
  1955
         then error "More arguments than parameters in instantiation."
ballarin@15596
  1956
         else insts @ replicate (length parms - length insts) NONE;
ballarin@15596
  1957
    val (ps, pTs) = split_list parms;
ballarin@15596
  1958
    val pvTs = map Type.varifyT pTs;
ballarin@15598
  1959
ballarin@15598
  1960
    (* instantiations given by user *)
ballarin@15596
  1961
    val given = List.mapPartial (fn (_, (NONE, _)) => NONE
ballarin@15596
  1962
         | (x, (SOME inst, T)) => SOME (x, (inst, T))) (ps ~~ (insts ~~ pvTs));
ballarin@15596
  1963
    val (given_ps, given_insts) = split_list given;
ballarin@15596
  1964
    val tvars = foldr Term.add_typ_tvars [] pvTs;
ballarin@15596
  1965
    val used = foldr Term.add_typ_varnames [] pvTs;
ballarin@15596
  1966
    fun sorts (a, i) = assoc (tvars, (a, i));
ballarin@15624
  1967
    val (vs, vinst) = read_terms thy_ctxt sorts used given_insts;
ballarin@15696
  1968
    val vars = foldl Term.add_term_tvar_ixns [] vs \\ map fst tvars;
ballarin@15696
  1969
    val vars' = Library.foldl Term.add_term_varnames (vars, vs);
ballarin@15696
  1970
    val _ = if null vars' then ()
ballarin@15696
  1971
         else error ("Illegal schematic variable(s) in instantiation: " ^
ballarin@15696
  1972
           commas_quote (map Syntax.string_of_vname vars'));
ballarin@15598
  1973
    (* replace new types (which are TFrees) by ones with new names *)
ballarin@15598
  1974
    val new_Tnames = foldr Term.add_term_tfree_names [] vs;
ballarin@15598
  1975
    val new_Tnames' = Term.invent_names used "'a" (length new_Tnames);
ballarin@15696
  1976
    val renameT =
ballarin@15696
  1977
          if is_local then I
ballarin@15696
  1978
          else Type.unvarifyT o Term.map_type_tfree (fn (a, s) =>
ballarin@15696
  1979
            TFree (valOf (assoc (new_Tnames ~~ new_Tnames', a)), s));
ballarin@15696
  1980
    val rename =
ballarin@15696
  1981
          if is_local then I
ballarin@15696
  1982
          else Term.map_term_types renameT;
ballarin@15598
  1983
ballarin@15598
  1984
    val tinst = Symtab.make (map
ballarin@15696
  1985
                (fn ((x, 0), T) => (x, T |> renameT)
ballarin@15696
  1986
                  | ((_, n), _) => error "Internal error var in prep_registration") vinst);
ballarin@15696
  1987
    val inst = Symtab.make (given_ps ~~ map rename vs);
ballarin@15596
  1988
ballarin@15596
  1989
    (* defined params without user input *)
ballarin@15596
  1990
    val not_given = List.mapPartial (fn (x, (NONE, T)) => SOME (x, T)
ballarin@15596
  1991
         | (_, (SOME _, _)) => NONE) (ps ~~ (insts ~~ pTs));
ballarin@15596
  1992
    fun add_def ((inst, tinst), (p, pT)) =
ballarin@15596
  1993
      let
ballarin@15596
  1994
        val (t, T) = case find_first (fn (Free (a, _), _) => a = p) defs of
ballarin@15596
  1995
               NONE => error ("Instance missing for parameter " ^ quote p)
ballarin@15596
  1996
             | SOME (Free (_, T), t) => (t, T);
ballarin@15696
  1997
        val d = t |> inst_tab_term (inst, tinst) |> Envir.beta_norm;
ballarin@15596
  1998
      in (Symtab.update_new ((p, d), inst), tinst) end;
ballarin@15596
  1999
    val (inst, tinst) = Library.foldl add_def ((inst, tinst), not_given);
ballarin@15696
  2000
    (* Note: inst and tinst contain no vars. *)
ballarin@15596
  2001
ballarin@15596
  2002
    (** compute proof obligations **)
ballarin@15596
  2003
ballarin@15598
  2004
    (* restore "small" ids *)
ballarin@15596
  2005
    val ids' = map (fn ((n, ps), _) =>
ballarin@15596
  2006
          (n, map (fn p => Free (p, valOf (assoc (parms, p)))) ps)) ids;
ballarin@15596
  2007
ballarin@15596
  2008
    (* instantiate ids and elements *)
ballarin@15596
  2009
    val inst_elemss = map
wenzelm@16458
  2010
          (fn (id, (_, elems)) => inst_tab_elems thy (inst, tinst) (id, 
ballarin@15596
  2011
            map (fn Int e => e) elems)) 
ballarin@15596
  2012
          (ids' ~~ all_elemss);
ballarin@15596
  2013
ballarin@15624
  2014
    (* remove fragments already registered with theory or context *)
ballarin@15596
  2015
    val new_inst_elemss = List.filter (fn (id, _) =>
ballarin@15624
  2016
          not (test_reg thy_ctxt id)) inst_elemss;
wenzelm@15703
  2017
    val new_ids = map #1 new_inst_elemss;
ballarin@15596
  2018
ballarin@15596
  2019
    val propss = extract_asms_elemss new_inst_elemss;
ballarin@15596
  2020
wenzelm@15703
  2021
    val bind_attrib = Attrib.crude_closure ctxt o Args.assignable;
wenzelm@16458
  2022
    val attn' = apsnd (map (bind_attrib o Attrib.intern_src thy)) attn;
ballarin@15596
  2023
ballarin@15696
  2024
    (** add registrations to theory or context,
ballarin@15596
  2025
        without theorems, these are added after the proof **)
ballarin@15696
  2026
    (* TODO: this is potentially problematic, since a proof of the
ballarin@15696
  2027
       interpretation might contain a reference to the incomplete
ballarin@15696
  2028
       registration. *)
ballarin@15596
  2029
ballarin@15624
  2030
    val thy_ctxt' = Library.foldl (fn (thy_ctxt, (id, _)) =>
wenzelm@15703
  2031
          put_reg id attn' thy_ctxt) (thy_ctxt, new_inst_elemss);
ballarin@15624
  2032
ballarin@15624
  2033
  in (thy_ctxt', propss, activate inst_elemss new_inst_elemss) end;
ballarin@15624
  2034
ballarin@15624
  2035
in
ballarin@15596
  2036
ballarin@15624
  2037
val prep_global_registration = gen_prep_registration
ballarin@15696
  2038
     ProofContext.init false
ballarin@15624
  2039
     (fn thy => fn sorts => fn used =>
wenzelm@16458
  2040
       Sign.read_def_terms (thy, K NONE, sorts) used true)
ballarin@15696
  2041
     (fn thy => fn (name, ps) =>
ballarin@15696
  2042
       test_global_registration thy (name, map Logic.varify ps))
ballarin@15696
  2043
     (fn (name, ps) => put_global_registration (name, map Logic.varify ps))
ballarin@15624
  2044
     global_activate_facts_elemss;
ballarin@15624
  2045
ballarin@15624
  2046
val prep_local_registration = gen_prep_registration
ballarin@15696
  2047
     I true
ballarin@15624
  2048
     (fn ctxt => ProofContext.read_termTs ctxt (K false) (K NONE))
ballarin@15624
  2049
     smart_test_registration
ballarin@15624
  2050
     put_local_registration
ballarin@15624
  2051
     local_activate_facts_elemss;
ballarin@15596
  2052
ballarin@15596
  2053
end;  (* local *)
ballarin@15596
  2054
ballarin@15596
  2055
wenzelm@11896
  2056
end;