src/Pure/Isar/locale.ML
author wenzelm
Fri Apr 08 16:34:14 2011 +0200 (2011-04-08)
changeset 42290 b1f544c84040
parent 41435 12585dfb86fe
child 42358 b47d41d9f4b5
permissions -rw-r--r--
discontinued special treatment of structure Lexicon;
haftmann@29361
     1
(*  Title:      Pure/Isar/locale.ML
haftmann@29361
     2
    Author:     Clemens Ballarin, TU Muenchen
haftmann@29361
     3
wenzelm@30725
     4
Locales -- managed Isar proof contexts, based on Pure predicates.
haftmann@29361
     5
haftmann@29361
     6
Draws basic ideas from Florian Kammueller's original version of
haftmann@29361
     7
locales, but uses the richer infrastructure of Isar instead of the raw
haftmann@29361
     8
meta-logic.  Furthermore, structured import of contexts (with merge
haftmann@29361
     9
and rename operations) are provided, as well as type-inference of the
haftmann@29361
    10
signature parts, and predicate definitions of the specification text.
haftmann@29361
    11
haftmann@29361
    12
Interpretation enables the reuse of theorems of locales in other
haftmann@29361
    13
contexts, namely those defined by theories, structured proofs and
haftmann@29361
    14
locales themselves.
haftmann@29361
    15
haftmann@29361
    16
See also:
haftmann@29361
    17
haftmann@29361
    18
[1] Clemens Ballarin. Locales and Locale Expressions in Isabelle/Isar.
haftmann@29361
    19
    In Stefano Berardi et al., Types for Proofs and Programs: International
haftmann@29361
    20
    Workshop, TYPES 2003, Torino, Italy, LNCS 3085, pages 34-50, 2004.
haftmann@29361
    21
[2] Clemens Ballarin. Interpretation of Locales in Isabelle: Managing
haftmann@29361
    22
    Dependencies between Locales. Technical Report TUM-I0607, Technische
haftmann@29361
    23
    Universitaet Muenchen, 2006.
haftmann@29361
    24
[3] Clemens Ballarin. Interpretation of Locales in Isabelle: Theories and
haftmann@29361
    25
    Proof Contexts. In J.M. Borwein and W.M. Farmer, MKM 2006, LNAI 4108,
haftmann@29361
    26
    pages 31-43, 2006.
haftmann@29361
    27
*)
haftmann@29361
    28
haftmann@29361
    29
signature LOCALE =
haftmann@29361
    30
sig
haftmann@29576
    31
  (* Locale specification *)
wenzelm@30344
    32
  val register_locale: binding ->
wenzelm@30755
    33
    (string * sort) list * ((string * typ) * mixfix) list ->
haftmann@29361
    34
    term option * term list ->
haftmann@29441
    35
    thm option * thm option -> thm list ->
wenzelm@35798
    36
    declaration list ->
wenzelm@30725
    37
    (string * (Attrib.binding * (thm list * Attrib.src list) list) list) list ->
wenzelm@30725
    38
    (string * morphism) list -> theory -> theory
haftmann@29361
    39
  val intern: theory -> xstring -> string
haftmann@29361
    40
  val extern: theory -> string -> xstring
haftmann@29392
    41
  val defined: theory -> string -> bool
wenzelm@30755
    42
  val params_of: theory -> string -> ((string * typ) * mixfix) list
haftmann@29441
    43
  val intros_of: theory -> string -> thm option * thm option
haftmann@29441
    44
  val axioms_of: theory -> string -> thm list
haftmann@29544
    45
  val instance_of: theory -> string -> morphism -> term list
haftmann@29361
    46
  val specification_of: theory -> string -> term option * term list
haftmann@29361
    47
haftmann@29361
    48
  (* Storing results *)
haftmann@29361
    49
  val add_thmss: string -> string -> (Attrib.binding * (thm list * Attrib.src list) list) list ->
haftmann@29361
    50
    Proof.context -> Proof.context
haftmann@29361
    51
  val add_declaration: string -> declaration -> Proof.context -> Proof.context
wenzelm@35798
    52
  val add_syntax_declaration: string -> declaration -> Proof.context -> Proof.context
haftmann@29361
    53
haftmann@29361
    54
  (* Activation *)
wenzelm@30764
    55
  val activate_declarations: string * morphism -> Proof.context -> Proof.context
ballarin@38316
    56
  val activate_facts: morphism option -> string * morphism -> Context.generic -> Context.generic
haftmann@29361
    57
  val init: string -> theory -> Proof.context
haftmann@29361
    58
haftmann@29361
    59
  (* Reasoning about locales *)
wenzelm@30725
    60
  val get_witnesses: Proof.context -> thm list
wenzelm@30725
    61
  val get_intros: Proof.context -> thm list
wenzelm@30725
    62
  val get_unfolds: Proof.context -> thm list
wenzelm@30725
    63
  val witness_add: attribute
wenzelm@30725
    64
  val intro_add: attribute
wenzelm@30725
    65
  val unfold_add: attribute
haftmann@29361
    66
  val intro_locales_tac: bool -> Proof.context -> thm list -> tactic
haftmann@29361
    67
haftmann@31988
    68
  (* Registrations and dependencies *)
ballarin@32845
    69
  val add_registration: string * morphism -> (morphism * bool) option ->
ballarin@38107
    70
    morphism -> Context.generic -> Context.generic
ballarin@32845
    71
  val amend_registration: string * morphism -> morphism * bool ->
ballarin@38107
    72
    morphism -> Context.generic -> Context.generic
ballarin@38111
    73
  val registrations_of: Context.generic -> string -> (string * morphism) list
ballarin@41270
    74
  val add_dependency: string -> string * morphism -> (morphism * bool) option ->
ballarin@41270
    75
    morphism -> theory -> theory
haftmann@29361
    76
haftmann@29361
    77
  (* Diagnostic *)
haftmann@37471
    78
  val all_locales: theory -> string list
haftmann@29361
    79
  val print_locales: theory -> unit
wenzelm@30344
    80
  val print_locale: theory -> bool -> xstring -> unit
ballarin@38109
    81
  val print_registrations: Proof.context -> string -> unit
ballarin@41435
    82
  val print_dependencies: Proof.context -> bool -> morphism -> (string * morphism) list -> unit
haftmann@37897
    83
  val locale_deps: theory ->
wenzelm@40782
    84
    {params: ((string * typ) * mixfix) list, axioms: term list, registrations: term list list} Graph.T
haftmann@37897
    85
      * term list list Symtab.table Symtab.table
haftmann@29361
    86
end;
haftmann@29361
    87
haftmann@29361
    88
structure Locale: LOCALE =
haftmann@29361
    89
struct
haftmann@29361
    90
haftmann@29361
    91
datatype ctxt = datatype Element.ctxt;
haftmann@29361
    92
haftmann@29392
    93
ballarin@38211
    94
(*** Locales ***)
haftmann@29361
    95
ballarin@41272
    96
type mixins = (((morphism * bool) * serial) list) Inttab.table;
ballarin@41272
    97
  (* table of mixin lists, per list mixins in reverse order of declaration;
ballarin@41272
    98
     lists indexed by registration/dependency serial,
ballarin@41272
    99
     entries for empty lists may be omitted *)
ballarin@41272
   100
ballarin@41272
   101
fun lookup_mixins serial' mixins = the_default [] (Inttab.lookup mixins serial');
ballarin@41272
   102
ballarin@41272
   103
fun merge_mixins (mix1, mix2) = Inttab.join (K (Library.merge (eq_snd op =))) (mix1, mix2);
ballarin@41272
   104
ballarin@41272
   105
fun insert_mixin serial' mixin =
ballarin@41272
   106
  Inttab.map_default (serial', []) (cons (mixin, serial ()));
ballarin@41272
   107
ballarin@41272
   108
fun rename_mixin (old, new) mix =
ballarin@41272
   109
  case Inttab.lookup mix old of
ballarin@41272
   110
    NONE => mix |
ballarin@41272
   111
    SOME mxs => Inttab.delete old mix |> Inttab.update_new (new, mxs);
ballarin@41272
   112
ballarin@41272
   113
fun compose_mixins mixins =
ballarin@41272
   114
  fold_rev Morphism.compose (map (fst o fst) mixins) Morphism.identity;
ballarin@41272
   115
haftmann@29361
   116
datatype locale = Loc of {
haftmann@29392
   117
  (** static part **)
wenzelm@30755
   118
  parameters: (string * sort) list * ((string * typ) * mixfix) list,
haftmann@29361
   119
    (* type and term parameters *)
haftmann@29361
   120
  spec: term option * term list,
haftmann@29361
   121
    (* assumptions (as a single predicate expression) and defines *)
haftmann@29441
   122
  intros: thm option * thm option,
haftmann@29441
   123
  axioms: thm list,
haftmann@29392
   124
  (** dynamic part **)
ballarin@36096
   125
  syntax_decls: (declaration * serial) list,
wenzelm@35798
   126
    (* syntax declarations *)
ballarin@36096
   127
  notes: ((string * (Attrib.binding * (thm list * Attrib.src list) list) list) * serial) list,
haftmann@29361
   128
    (* theorem declarations *)
ballarin@36651
   129
  dependencies: ((string * (morphism * morphism)) * serial) list
ballarin@41272
   130
    (* locale dependencies (sublocale relation) in reverse order *),
ballarin@41272
   131
  mixins: mixins
ballarin@41272
   132
    (* mixin part of dependencies *)
haftmann@29392
   133
};
haftmann@29361
   134
ballarin@41272
   135
fun mk_locale ((parameters, spec, intros, axioms),
ballarin@41272
   136
    ((syntax_decls, notes), (dependencies, mixins))) =
haftmann@29441
   137
  Loc {parameters = parameters, intros = intros, axioms = axioms, spec = spec,
ballarin@41272
   138
    syntax_decls = syntax_decls, notes = notes, dependencies = dependencies, mixins = mixins};
wenzelm@35798
   139
ballarin@41272
   140
fun map_locale f (Loc {parameters, spec, intros, axioms,
ballarin@41272
   141
    syntax_decls, notes, dependencies, mixins}) =
ballarin@41272
   142
  mk_locale (f ((parameters, spec, intros, axioms),
ballarin@41272
   143
    ((syntax_decls, notes), (dependencies, mixins))));
wenzelm@30754
   144
wenzelm@35798
   145
fun merge_locale
ballarin@41272
   146
 (Loc {parameters, spec, intros, axioms, syntax_decls, notes, dependencies, mixins},
ballarin@41272
   147
  Loc {syntax_decls = syntax_decls', notes = notes',
ballarin@41272
   148
      dependencies = dependencies', mixins = mixins', ...}) =
wenzelm@35798
   149
    mk_locale
haftmann@29441
   150
      ((parameters, spec, intros, axioms),
wenzelm@35798
   151
        ((merge (eq_snd op =) (syntax_decls, syntax_decls'),
haftmann@29441
   152
          merge (eq_snd op =) (notes, notes')),
ballarin@41272
   153
            (merge (eq_snd op =) (dependencies, dependencies'),
ballarin@41272
   154
              (merge_mixins (mixins, mixins')))));
haftmann@29361
   155
wenzelm@33522
   156
structure Locales = Theory_Data
haftmann@29361
   157
(
wenzelm@33095
   158
  type T = locale Name_Space.table;
wenzelm@33159
   159
  val empty : T = Name_Space.empty_table "locale";
haftmann@29361
   160
  val extend = I;
wenzelm@33522
   161
  val merge = Name_Space.join_tables (K merge_locale);
haftmann@29361
   162
);
haftmann@29361
   163
wenzelm@33095
   164
val intern = Name_Space.intern o #1 o Locales.get;
wenzelm@33095
   165
val extern = Name_Space.extern o #1 o Locales.get;
haftmann@29392
   166
wenzelm@30725
   167
val get_locale = Symtab.lookup o #2 o Locales.get;
wenzelm@30725
   168
val defined = Symtab.defined o #2 o Locales.get;
haftmann@29361
   169
wenzelm@30725
   170
fun the_locale thy name =
wenzelm@30725
   171
  (case get_locale thy name of
wenzelm@30725
   172
    SOME (Loc loc) => loc
wenzelm@30725
   173
  | NONE => error ("Unknown locale " ^ quote name));
haftmann@29361
   174
wenzelm@35798
   175
fun register_locale binding parameters spec intros axioms syntax_decls notes dependencies thy =
wenzelm@33095
   176
  thy |> Locales.map (Name_Space.define true (Sign.naming_of thy)
wenzelm@30725
   177
    (binding,
wenzelm@30725
   178
      mk_locale ((parameters, spec, intros, axioms),
ballarin@36096
   179
        ((map (fn decl => (decl, serial ())) syntax_decls, map (fn n => (n, serial ())) notes),
ballarin@41272
   180
          (map (fn d => (d |> apsnd (rpair Morphism.identity), serial ())) dependencies,
ballarin@41272
   181
            Inttab.empty)))) #> snd);
ballarin@41272
   182
          (* FIXME Morphism.identity *)
haftmann@29361
   183
haftmann@29392
   184
fun change_locale name =
wenzelm@30725
   185
  Locales.map o apsnd o Symtab.map_entry name o map_locale o apsnd;
haftmann@29361
   186
haftmann@29361
   187
ballarin@38211
   188
(** Primitive operations **)
haftmann@29361
   189
haftmann@29392
   190
fun params_of thy = snd o #parameters o the_locale thy;
haftmann@29361
   191
haftmann@29441
   192
fun intros_of thy = #intros o the_locale thy;
haftmann@29441
   193
haftmann@29441
   194
fun axioms_of thy = #axioms o the_locale thy;
haftmann@29441
   195
haftmann@29392
   196
fun instance_of thy name morph = params_of thy name |>
wenzelm@30755
   197
  map (Morphism.term morph o Free o #1);
haftmann@29361
   198
haftmann@29392
   199
fun specification_of thy = #spec o the_locale thy;
haftmann@29361
   200
haftmann@29544
   201
fun dependencies_of thy name = the_locale thy name |>
ballarin@41272
   202
  #dependencies;
ballarin@41272
   203
ballarin@41272
   204
fun mixins_of thy name serial = the_locale thy name |>
ballarin@41272
   205
  #mixins |> lookup_mixins serial;
ballarin@41272
   206
ballarin@41272
   207
(* unused *)
ballarin@41272
   208
fun identity_on thy name morph =
ballarin@41272
   209
  let val mk_instance = instance_of thy name
ballarin@41272
   210
  in
ballarin@41272
   211
    forall2 (curry Term.aconv_untyped) (mk_instance Morphism.identity) (mk_instance morph)
ballarin@41272
   212
  end;
haftmann@29544
   213
ballarin@37133
   214
(* Print instance and qualifiers *)
ballarin@37133
   215
ballarin@41435
   216
fun pretty_reg ctxt (name, morph) =
ballarin@37133
   217
  let
ballarin@41435
   218
    val thy = ProofContext.theory_of ctxt;
ballarin@37133
   219
    val name' = extern thy name;
ballarin@37133
   220
    fun prt_qual (qual, mand) = Pretty.str (qual ^ (if mand then "!" else "?"));
ballarin@37133
   221
    fun prt_quals qs = Pretty.separate "." (map prt_qual qs) |> Pretty.block;
ballarin@37133
   222
    val prt_term = Pretty.quote o Syntax.pretty_term ctxt;
wenzelm@39134
   223
    fun prt_term' t =
wenzelm@39134
   224
      if Config.get ctxt show_types
ballarin@37133
   225
      then Pretty.block [prt_term t, Pretty.brk 1, Pretty.str "::",
ballarin@37133
   226
        Pretty.brk 1, (Pretty.quote o Syntax.pretty_typ ctxt) (type_of t)]
ballarin@37133
   227
      else prt_term t;
ballarin@37133
   228
    fun prt_inst ts =
ballarin@37133
   229
      Pretty.block (Pretty.breaks (Pretty.str name' :: map prt_term' ts));
ballarin@37133
   230
ballarin@37133
   231
    val qs = Binding.name "x" |> Morphism.binding morph |> Binding.prefix_of;
ballarin@37133
   232
    val ts = instance_of thy name morph;
ballarin@37133
   233
  in
wenzelm@40782
   234
    (case qs of
wenzelm@40782
   235
      [] => prt_inst ts
wenzelm@40782
   236
    | qs => Pretty.block [prt_quals qs, Pretty.brk 1, Pretty.str ":", Pretty.brk 1, prt_inst ts])
ballarin@37133
   237
  end;
ballarin@37133
   238
haftmann@29361
   239
ballarin@38211
   240
(*** Identifiers: activated locales in theory or proof context ***)
haftmann@29361
   241
ballarin@37105
   242
(* subsumption *)
ballarin@37103
   243
fun ident_le thy ((n: string, ts), (m, ss)) = (m = n) andalso Pattern.matchess thy (ss, ts);
ballarin@37105
   244
  (* smaller term is more general *)
ballarin@37105
   245
ballarin@37105
   246
(* total order *)
ballarin@37105
   247
fun ident_ord ((n: string, ts), (m, ss)) =
wenzelm@40782
   248
  (case fast_string_ord (m, n) of
wenzelm@40782
   249
    EQUAL => list_ord Term_Ord.fast_term_ord (ts, ss)
wenzelm@40782
   250
  | ord => ord);
haftmann@29361
   251
haftmann@29361
   252
local
haftmann@29361
   253
wenzelm@30754
   254
datatype 'a delayed = Ready of 'a | ToDo of 'a delayed * 'a delayed;
haftmann@29361
   255
wenzelm@33519
   256
structure Identifiers = Generic_Data
haftmann@29361
   257
(
wenzelm@30754
   258
  type T = (string * term list) list delayed;
wenzelm@30754
   259
  val empty = Ready [];
haftmann@29361
   260
  val extend = I;
wenzelm@33519
   261
  val merge = ToDo;
haftmann@29361
   262
);
haftmann@29361
   263
ballarin@37103
   264
fun finish thy (ToDo (i1, i2)) = merge (ident_le thy) (finish thy i1, finish thy i2)
haftmann@29361
   265
  | finish _ (Ready ids) = ids;
haftmann@29361
   266
haftmann@29361
   267
val _ = Context.>> (Context.map_theory (Theory.at_begin (fn thy =>
wenzelm@30725
   268
  (case Identifiers.get (Context.Theory thy) of
wenzelm@30725
   269
    Ready _ => NONE
wenzelm@30725
   270
  | ids => SOME (Context.theory_map (Identifiers.put (Ready (finish thy ids))) thy)))));
haftmann@29361
   271
wenzelm@30764
   272
in
haftmann@29361
   273
wenzelm@30764
   274
val get_idents = (fn Ready ids => ids) o Identifiers.get;
wenzelm@30764
   275
val put_idents = Identifiers.put o Ready;
haftmann@29361
   276
haftmann@29361
   277
end;
haftmann@29361
   278
haftmann@29361
   279
haftmann@29361
   280
(** Resolve locale dependencies in a depth-first fashion **)
haftmann@29361
   281
haftmann@29361
   282
local
haftmann@29361
   283
haftmann@29361
   284
val roundup_bound = 120;
haftmann@29361
   285
ballarin@41272
   286
fun add thy depth stem export (name, morph, mixins) (deps, marked) =
haftmann@29361
   287
  if depth > roundup_bound
haftmann@29361
   288
  then error "Roundup bound exceeded (sublocale relation probably not terminating)."
haftmann@29361
   289
  else
haftmann@29361
   290
    let
ballarin@41272
   291
      val instance = instance_of thy name (morph $> stem $> export);
haftmann@29361
   292
    in
ballarin@37103
   293
      if member (ident_le thy) marked (name, instance)
haftmann@29361
   294
      then (deps, marked)
haftmann@29361
   295
      else
haftmann@29361
   296
        let
ballarin@41272
   297
          val full_morph = morph $> compose_mixins mixins $> stem;
ballarin@41272
   298
          (* no inheritance of mixins, regardless of requests by clients *)
ballarin@41272
   299
          val dependencies = dependencies_of thy name |>
ballarin@41272
   300
            map (fn ((name', (morph', export')), serial') =>
ballarin@41272
   301
              (name', morph' $> export', mixins_of thy name serial'));
haftmann@29361
   302
          val marked' = (name, instance) :: marked;
ballarin@41272
   303
          val (deps', marked'') =
ballarin@41272
   304
            fold_rev (add thy (depth + 1) full_morph export) dependencies
ballarin@41272
   305
              ([], marked');
haftmann@29361
   306
        in
ballarin@41272
   307
          ((name, full_morph) :: deps' @ deps, marked'')
haftmann@29361
   308
        end
haftmann@29361
   309
    end;
haftmann@29361
   310
haftmann@29361
   311
in
haftmann@29361
   312
ballarin@33541
   313
(* Note that while identifiers always have the external (exported) view, activate_dep
ballarin@32803
   314
  is presented with the internal view. *)
ballarin@32803
   315
ballarin@32803
   316
fun roundup thy activate_dep export (name, morph) (marked, input) =
haftmann@29361
   317
  let
ballarin@41272
   318
    (* Find all dependencies including new ones (which are dependencies enriching
haftmann@29361
   319
      existing registrations). *)
ballarin@41272
   320
    val (dependencies, marked') =
ballarin@41272
   321
      add thy 0 Morphism.identity export (name, morph, []) ([], []);
ballarin@32800
   322
    (* Filter out fragments from marked; these won't be activated. *)
haftmann@29361
   323
    val dependencies' = filter_out (fn (name, morph) =>
ballarin@37103
   324
      member (ident_le thy) marked (name, instance_of thy name (morph $> export))) dependencies;
haftmann@29361
   325
  in
ballarin@37103
   326
    (merge (ident_le thy) (marked, marked'), input |> fold_rev activate_dep dependencies')
haftmann@29361
   327
  end;
haftmann@29361
   328
haftmann@29361
   329
end;
haftmann@29361
   330
haftmann@29361
   331
ballarin@38211
   332
(*** Registrations: interpretations in theories or proof contexts ***)
haftmann@29361
   333
ballarin@37105
   334
structure Idtab = Table(type key = string * term list val ord = ident_ord);
ballarin@37105
   335
ballarin@38107
   336
structure Registrations = Generic_Data
haftmann@29361
   337
(
ballarin@41272
   338
  type T = ((morphism * morphism) * serial) Idtab.table * mixins;
ballarin@37105
   339
    (* registrations, indexed by locale name and instance;
ballarin@41272
   340
       unique registration serial points to mixin list *)
ballarin@37105
   341
  val empty = (Idtab.empty, Inttab.empty);
haftmann@29361
   342
  val extend = I;
ballarin@37133
   343
  fun merge ((reg1, mix1), (reg2, mix2)) : T =
ballarin@37133
   344
    (Idtab.join (fn id => fn (r1 as (_, s1), r2 as (_, s2)) =>
ballarin@37133
   345
        if s1 = s2 then raise Idtab.SAME else raise Idtab.DUP id) (reg1, reg2),
ballarin@41272
   346
      merge_mixins (mix1, mix2))
ballarin@37133
   347
    handle Idtab.DUP id =>
ballarin@37133
   348
      (* distinct interpretations with same base: merge their mixins *)
ballarin@37133
   349
      let
ballarin@37133
   350
        val (_, s1) = Idtab.lookup reg1 id |> the;
ballarin@37133
   351
        val (morph2, s2) = Idtab.lookup reg2 id |> the;
ballarin@37133
   352
        val reg2' = Idtab.update (id, (morph2, s1)) reg2;
ballarin@37133
   353
        val _ = warning "Removed duplicate interpretation after retrieving its mixins.";
ballarin@37133
   354
        (* FIXME print interpretations,
ballarin@37133
   355
           which is not straightforward without theory context *)
ballarin@41272
   356
      in merge ((reg1, mix1), (reg2', rename_mixin (s2, s1) mix2)) end;
haftmann@29361
   357
    (* FIXME consolidate with dependencies, consider one data slot only *)
haftmann@29361
   358
);
haftmann@29361
   359
ballarin@32801
   360
ballarin@32801
   361
(* Primitive operations *)
ballarin@32801
   362
ballarin@37104
   363
fun add_reg thy export (name, morph) =
ballarin@37105
   364
  Registrations.map (apfst (Idtab.insert (K false)
ballarin@37105
   365
    ((name, instance_of thy name (morph $> export)), ((morph, export), serial ()))));
haftmann@31988
   366
ballarin@36095
   367
fun add_mixin serial' mixin =
ballarin@36095
   368
  (* registration to be amended identified by its serial id *)
ballarin@41272
   369
  Registrations.map (apsnd (insert_mixin serial' mixin));
ballarin@32801
   370
ballarin@38107
   371
fun get_mixins context (name, morph) =
ballarin@32804
   372
  let
ballarin@38107
   373
    val thy = Context.theory_of context;
ballarin@38107
   374
    val (regs, mixins) = Registrations.get context;
ballarin@32804
   375
  in
wenzelm@40782
   376
    (case Idtab.lookup regs (name, instance_of thy name morph) of
ballarin@32804
   377
      NONE => []
ballarin@41272
   378
    | SOME (_, serial) => lookup_mixins serial mixins)
ballarin@32804
   379
  end;
ballarin@32804
   380
ballarin@38107
   381
fun collect_mixins context (name, morph) =
ballarin@38107
   382
  let
ballarin@38107
   383
    val thy = Context.theory_of context;
ballarin@38107
   384
  in
ballarin@38107
   385
    roundup thy (fn dep => fn mixins => merge (eq_snd op =) (mixins, get_mixins context dep))
ballarin@38107
   386
      Morphism.identity (name, morph) ([(name, instance_of thy name morph)], [])
ballarin@38107
   387
    |> snd |> filter (snd o fst)  (* only inheritable mixins *)
ballarin@38107
   388
    |> (fn x => merge (eq_snd op =) (x, get_mixins context (name, morph)))
ballarin@38107
   389
    |> compose_mixins
ballarin@38107
   390
  end;
ballarin@36091
   391
ballarin@38107
   392
fun get_registrations context select = Registrations.get context
ballarin@37491
   393
  |>> Idtab.dest |>> select
ballarin@36095
   394
  (* with inherited mixins *)
ballarin@37105
   395
  |-> (fn regs => fn _ => map (fn ((name, _), ((base, export) ,_)) =>
ballarin@38107
   396
    (name, base $> (collect_mixins context (name, base $> export)) $> export)) regs);
ballarin@36091
   397
ballarin@38111
   398
fun registrations_of context name =
ballarin@38107
   399
  get_registrations context (filter (curry (op =) name o fst o fst));
ballarin@37491
   400
ballarin@38107
   401
fun all_registrations context = get_registrations context I;
haftmann@37973
   402
ballarin@38211
   403
ballarin@38211
   404
(*** Activate context elements of locale ***)
ballarin@38211
   405
ballarin@38211
   406
(* Declarations, facts and entire locale content *)
ballarin@38211
   407
ballarin@38211
   408
fun activate_syntax_decls (name, morph) context =
ballarin@38211
   409
  let
ballarin@38211
   410
    val thy = Context.theory_of context;
ballarin@38211
   411
    val {syntax_decls, ...} = the_locale thy name;
ballarin@38211
   412
  in
ballarin@38211
   413
    context
ballarin@38211
   414
    |> fold_rev (fn (decl, _) => decl morph) syntax_decls
ballarin@38211
   415
  end;
ballarin@38211
   416
ballarin@38211
   417
fun activate_notes activ_elem transfer context export' (name, morph) input =
ballarin@32804
   418
  let
ballarin@38107
   419
    val thy = Context.theory_of context;
ballarin@32804
   420
    val {notes, ...} = the_locale thy name;
ballarin@32804
   421
    fun activate ((kind, facts), _) input =
ballarin@32804
   422
      let
wenzelm@40782
   423
        val mixin =
wenzelm@40782
   424
          (case export' of
wenzelm@40782
   425
            NONE => Morphism.identity
wenzelm@40782
   426
          | SOME export => collect_mixins context (name, morph $> export) $> export);
wenzelm@40782
   427
        val facts' = facts
wenzelm@40782
   428
          |> Element.facts_map (Element.morph_ctxt (transfer input $> morph $> mixin));
ballarin@32804
   429
      in activ_elem (Notes (kind, facts')) input end;
ballarin@32804
   430
  in
ballarin@32804
   431
    fold_rev activate notes input
ballarin@32804
   432
  end;
ballarin@32804
   433
ballarin@38211
   434
fun activate_all name thy activ_elem transfer (marked, input) =
ballarin@38211
   435
  let
ballarin@38211
   436
    val {parameters = (_, params), spec = (asm, defs), ...} = the_locale thy name;
ballarin@38211
   437
    val input' = input |>
ballarin@38211
   438
      (not (null params) ?
ballarin@38211
   439
        activ_elem (Fixes (map (fn ((x, T), mx) => (Binding.name x, SOME T, mx)) params))) |>
ballarin@38211
   440
      (* FIXME type parameters *)
ballarin@38211
   441
      (case asm of SOME A => activ_elem (Assumes [(Attrib.empty_binding, [(A, [])])]) | _ => I) |>
wenzelm@40782
   442
      (not (null defs) ?
wenzelm@40782
   443
        activ_elem (Defines (map (fn def => (Attrib.empty_binding, (def, []))) defs)));
ballarin@38211
   444
    val activate = activate_notes activ_elem transfer (Context.Theory thy) NONE;
ballarin@38211
   445
  in
ballarin@38211
   446
    roundup thy activate Morphism.identity (name, Morphism.identity) (marked, input')
ballarin@38211
   447
  end;
ballarin@38211
   448
ballarin@38211
   449
ballarin@38211
   450
(** Public activation functions **)
ballarin@38211
   451
ballarin@38211
   452
fun activate_declarations dep = Context.proof_map (fn context =>
ballarin@32804
   453
  let
ballarin@32804
   454
    val thy = Context.theory_of context;
ballarin@38211
   455
  in
ballarin@38211
   456
    roundup thy activate_syntax_decls Morphism.identity dep (get_idents context, context)
ballarin@38211
   457
    |-> put_idents
ballarin@38211
   458
  end);
ballarin@38211
   459
ballarin@38211
   460
fun activate_facts export dep context =
ballarin@38211
   461
  let
ballarin@38211
   462
    val thy = Context.theory_of context;
ballarin@38316
   463
    val activate = activate_notes Element.init (Element.transfer_morphism o Context.theory_of) context export;
ballarin@38316
   464
  in
ballarin@38316
   465
    roundup thy activate (case export of NONE => Morphism.identity | SOME export => export)
ballarin@38316
   466
      dep (get_idents context, context)
ballarin@38316
   467
    |-> put_idents
ballarin@38316
   468
  end;
ballarin@32804
   469
ballarin@38211
   470
fun init name thy =
ballarin@38211
   471
  activate_all name thy Element.init (Element.transfer_morphism o Context.theory_of)
ballarin@38211
   472
    ([], Context.Proof (ProofContext.init_global thy)) |-> put_idents |> Context.proof_of;
ballarin@32804
   473
ballarin@38211
   474
ballarin@38211
   475
(*** Add and extend registrations ***)
ballarin@32801
   476
ballarin@38107
   477
fun amend_registration (name, morph) mixin export context =
ballarin@32804
   478
  let
ballarin@38107
   479
    val thy = Context.theory_of context;
ballarin@38107
   480
    val regs = Registrations.get context |> fst;
ballarin@32804
   481
    val base = instance_of thy name (morph $> export);
ballarin@32804
   482
  in
wenzelm@40782
   483
    (case Idtab.lookup regs (name, base) of
wenzelm@40782
   484
      NONE =>
wenzelm@40782
   485
        error ("No interpretation of locale " ^
ballarin@41272
   486
          quote (extern thy name) ^ " with\nparameter instantiation " ^
ballarin@32804
   487
          space_implode " " (map (quote o Syntax.string_of_term_global thy) base) ^
ballarin@32804
   488
          " available")
wenzelm@40782
   489
    | SOME (_, serial') => add_mixin serial' mixin context)
ballarin@32804
   490
  end;
ballarin@32804
   491
ballarin@32801
   492
(* Note that a registration that would be subsumed by an existing one will not be
ballarin@32801
   493
   generated, and it will not be possible to amend it. *)
ballarin@32801
   494
ballarin@38107
   495
fun add_registration (name, base_morph) mixin export context =
ballarin@32801
   496
  let
ballarin@38107
   497
    val thy = Context.theory_of context;
wenzelm@40782
   498
    val mix = (case mixin of NONE => Morphism.identity | SOME (mix, _) => mix);
ballarin@37102
   499
    val morph = base_morph $> mix;
ballarin@37102
   500
    val inst = instance_of thy name morph;
ballarin@32801
   501
  in
ballarin@38107
   502
    if member (ident_le thy) (get_idents context) (name, inst)
ballarin@41272
   503
    then context  (* FIXME amend mixins? *)
ballarin@32801
   504
    else
ballarin@38107
   505
      (get_idents context, context)
ballarin@36095
   506
      (* add new registrations with inherited mixins *)
ballarin@37104
   507
      |> roundup thy (add_reg thy export) export (name, morph)
ballarin@36095
   508
      |> snd
ballarin@36095
   509
      (* add mixin *)
wenzelm@40782
   510
      |>
wenzelm@40782
   511
        (case mixin of
wenzelm@40782
   512
          NONE => I
wenzelm@40782
   513
        | SOME mixin => amend_registration (name, morph) mixin export)
ballarin@36095
   514
      (* activate import hierarchy as far as not already active *)
ballarin@38316
   515
      |> activate_facts (SOME export) (name, morph)
ballarin@32801
   516
  end;
ballarin@32801
   517
haftmann@29361
   518
haftmann@31988
   519
(*** Dependencies ***)
haftmann@31988
   520
ballarin@41272
   521
(*
ballarin@41272
   522
fun amend_dependency loc (name, morph) mixin export thy =
ballarin@41272
   523
  let
ballarin@41272
   524
    val deps = dependencies_of thy loc;
ballarin@41272
   525
  in
ballarin@41272
   526
    case AList.lookup (fn ((name, morph), ((name', (morph', _)), _)) =>
ballarin@41272
   527
      ident_ord ((name, instance_of thy name morph), (name', instance_of thy name' morph')) = EQUAL) deps (name, morph) of
ballarin@41272
   528
        NONE => error ("Locale " ^
ballarin@41272
   529
          quote (extern thy name) ^ " with\parameter instantiation " ^
ballarin@41272
   530
          space_implode " " (map (quote o Syntax.string_of_term_global thy) morph) ^
ballarin@41272
   531
          " not a sublocale of " ^ quote (extern thy loc))
ballarin@41272
   532
      | SOME (_, serial') => change_locale ...
ballarin@41272
   533
  end;
ballarin@41272
   534
*)
ballarin@41272
   535
ballarin@41270
   536
fun add_dependency loc (name, morph) mixin export thy =
ballarin@37102
   537
  let
ballarin@41272
   538
    val serial' = serial ();
ballarin@41272
   539
    val thy' = thy |>
ballarin@41272
   540
      (change_locale loc o apsnd)
ballarin@41272
   541
        (apfst (cons ((name, (morph, export)), serial')) #>
ballarin@41272
   542
          apsnd (case mixin of NONE => I | SOME mixin => insert_mixin serial' mixin));
ballarin@38107
   543
    val context' = Context.Theory thy';
ballarin@37102
   544
    val (_, regs) = fold_rev (roundup thy' cons export)
ballarin@38783
   545
      (registrations_of context' loc) (get_idents (context'), []);
ballarin@37102
   546
  in
ballarin@37102
   547
    thy'
ballarin@38107
   548
    |> fold_rev (fn dep => Context.theory_map (add_registration dep NONE export)) regs
ballarin@37102
   549
  end;
haftmann@31988
   550
haftmann@31988
   551
haftmann@29361
   552
(*** Storing results ***)
haftmann@29361
   553
haftmann@29361
   554
(* Theorems *)
haftmann@29361
   555
haftmann@29361
   556
fun add_thmss loc kind args ctxt =
haftmann@29361
   557
  let
wenzelm@30777
   558
    val (Notes args', ctxt') = Element.activate_i (Notes (kind, args)) ctxt;
wenzelm@38757
   559
    val ctxt'' = ctxt' |> ProofContext.background_theory
wenzelm@38757
   560
     ((change_locale loc o apfst o apsnd) (cons (args', serial ()))
haftmann@29392
   561
        #>
haftmann@29361
   562
      (* Registrations *)
haftmann@31988
   563
      (fn thy => fold_rev (fn (_, morph) =>
haftmann@29361
   564
            let
haftmann@29361
   565
              val args'' = snd args' |> Element.facts_map (Element.morph_ctxt morph) |>
haftmann@29361
   566
                Attrib.map_facts (Attrib.attribute_i thy)
wenzelm@39557
   567
            in Global_Theory.note_thmss kind args'' #> snd end)
ballarin@38111
   568
        (registrations_of (Context.Theory thy) loc) thy))
haftmann@29361
   569
  in ctxt'' end;
haftmann@29361
   570
haftmann@29361
   571
haftmann@29361
   572
(* Declarations *)
haftmann@29361
   573
wenzelm@35798
   574
fun add_declaration loc decl =
wenzelm@33643
   575
  add_thmss loc ""
wenzelm@35798
   576
    [((Binding.conceal Binding.empty,
wenzelm@35798
   577
        [Attrib.internal (fn phi => Thm.declaration_attribute (K (decl phi)))]),
wenzelm@33278
   578
      [([Drule.dummy_thm], [])])];
haftmann@29361
   579
wenzelm@35798
   580
fun add_syntax_declaration loc decl =
wenzelm@38756
   581
  ProofContext.background_theory ((change_locale loc o apfst o apfst) (cons (decl, serial ())))
wenzelm@35798
   582
  #> add_declaration loc decl;
haftmann@29361
   583
wenzelm@30725
   584
haftmann@29361
   585
(*** Reasoning about locales ***)
haftmann@29361
   586
wenzelm@30725
   587
(* Storage for witnesses, intro and unfold rules *)
haftmann@29361
   588
wenzelm@33519
   589
structure Thms = Generic_Data
wenzelm@30725
   590
(
wenzelm@30725
   591
  type T = thm list * thm list * thm list;
wenzelm@30725
   592
  val empty = ([], [], []);
wenzelm@30725
   593
  val extend = I;
wenzelm@33519
   594
  fun merge ((witnesses1, intros1, unfolds1), (witnesses2, intros2, unfolds2)) =
wenzelm@30725
   595
   (Thm.merge_thms (witnesses1, witnesses2),
wenzelm@30725
   596
    Thm.merge_thms (intros1, intros2),
wenzelm@30725
   597
    Thm.merge_thms (unfolds1, unfolds2));
wenzelm@30725
   598
);
haftmann@29361
   599
wenzelm@30725
   600
val get_witnesses = #1 o Thms.get o Context.Proof;
wenzelm@30725
   601
val get_intros = #2 o Thms.get o Context.Proof;
wenzelm@30725
   602
val get_unfolds = #3 o Thms.get o Context.Proof;
haftmann@29361
   603
wenzelm@30725
   604
val witness_add =
wenzelm@30725
   605
  Thm.declaration_attribute (fn th => Thms.map (fn (x, y, z) => (Thm.add_thm th x, y, z)));
wenzelm@30725
   606
val intro_add =
wenzelm@30725
   607
  Thm.declaration_attribute (fn th => Thms.map (fn (x, y, z) => (x, Thm.add_thm th y, z)));
wenzelm@30725
   608
val unfold_add =
wenzelm@30725
   609
  Thm.declaration_attribute (fn th => Thms.map (fn (x, y, z) => (x, y, Thm.add_thm th z)));
haftmann@29361
   610
wenzelm@30725
   611
wenzelm@40782
   612
(* Tactics *)
wenzelm@30725
   613
ballarin@36093
   614
fun gen_intro_locales_tac intros_tac eager ctxt =
ballarin@36093
   615
  intros_tac
wenzelm@30725
   616
    (get_witnesses ctxt @ get_intros ctxt @ (if eager then get_unfolds ctxt else []));
haftmann@29361
   617
ballarin@36093
   618
val intro_locales_tac = gen_intro_locales_tac Method.intros_tac;
ballarin@36093
   619
val try_intro_locales_tac= gen_intro_locales_tac Method.try_intros_tac;
ballarin@36093
   620
haftmann@29361
   621
val _ = Context.>> (Context.map_theory
ballarin@36093
   622
 (Method.setup (Binding.name "intro_locales") (Scan.succeed (METHOD o try_intro_locales_tac false))
wenzelm@30515
   623
    "back-chain introduction rules of locales without unfolding predicates" #>
ballarin@36093
   624
  Method.setup (Binding.name "unfold_locales") (Scan.succeed (METHOD o try_intro_locales_tac true))
wenzelm@30515
   625
    "back-chain all introduction rules of locales"));
haftmann@29361
   626
haftmann@37471
   627
haftmann@37471
   628
(*** diagnostic commands and interfaces ***)
haftmann@37471
   629
haftmann@37897
   630
val all_locales = Symtab.keys o snd o Locales.get;
haftmann@37471
   631
haftmann@37471
   632
fun print_locales thy =
haftmann@37897
   633
  Pretty.strs ("locales:" :: map #1 (Name_Space.extern_table (Locales.get thy)))
haftmann@37471
   634
  |> Pretty.writeln;
haftmann@37471
   635
haftmann@37471
   636
fun print_locale thy show_facts raw_name =
haftmann@37471
   637
  let
haftmann@37471
   638
    val name = intern thy raw_name;
haftmann@37471
   639
    val ctxt = init name thy;
haftmann@37471
   640
    fun cons_elem (elem as Notes _) = show_facts ? cons elem
haftmann@37471
   641
      | cons_elem elem = cons elem;
haftmann@37471
   642
    val elems =
haftmann@37471
   643
      activate_all name thy cons_elem (K (Element.transfer_morphism thy)) ([], [])
haftmann@37471
   644
      |> snd |> rev;
haftmann@37471
   645
  in
haftmann@37471
   646
    Pretty.big_list "locale elements:" (map (Pretty.chunks o Element.pretty_ctxt ctxt) elems)
haftmann@37471
   647
    |> Pretty.writeln
haftmann@37471
   648
  end;
haftmann@37471
   649
ballarin@38109
   650
fun print_registrations ctxt raw_name =
ballarin@38109
   651
  let
ballarin@38109
   652
    val thy = ProofContext.theory_of ctxt;
ballarin@41435
   653
    val name = intern thy raw_name;
ballarin@41435
   654
    val _ = the_locale thy name;  (* error if locale unknown *)
ballarin@38109
   655
  in
ballarin@41435
   656
    (case registrations_of (Context.Proof ctxt) (* FIXME *) name of
wenzelm@40782
   657
      [] => Pretty.str ("no interpretations")
ballarin@41435
   658
    | regs => Pretty.big_list "interpretations:" (map (pretty_reg ctxt) (rev regs)))
ballarin@41435
   659
  end |> Pretty.writeln;
ballarin@41435
   660
ballarin@41435
   661
fun print_dependencies ctxt clean export insts =
ballarin@41435
   662
  let
ballarin@41435
   663
    val thy = ProofContext.theory_of ctxt;
ballarin@41435
   664
    val idents = if clean then [] else get_idents (Context.Proof ctxt);
ballarin@41435
   665
  in
ballarin@41435
   666
    (case fold (roundup thy cons export) insts (idents, []) |> snd of
ballarin@41435
   667
      [] => Pretty.str ("no dependencies")
ballarin@41435
   668
    | deps => Pretty.big_list "dependencies:" (map (pretty_reg ctxt) (rev deps)))
wenzelm@40782
   669
  end |> Pretty.writeln;
haftmann@37471
   670
haftmann@37897
   671
fun locale_deps thy =
haftmann@37897
   672
  let
haftmann@37897
   673
    val names = all_locales thy
haftmann@37897
   674
    fun add_locale_node name =
haftmann@37897
   675
      let
haftmann@37897
   676
        val params = params_of thy name;
wenzelm@40782
   677
        val axioms =
wenzelm@40782
   678
          these (Option.map (Logic.strip_imp_prems o Thm.prop_of) (fst (intros_of thy name)));
wenzelm@40782
   679
        val registrations =
wenzelm@40782
   680
          map (instance_of thy name o snd) (registrations_of (Context.Theory thy) name);
wenzelm@40782
   681
      in
wenzelm@40782
   682
        Graph.new_node (name, {params = params, axioms = axioms, registrations = registrations})
haftmann@37897
   683
      end;
haftmann@37897
   684
    fun add_locale_deps name =
haftmann@37897
   685
      let
wenzelm@40782
   686
        val dependencies =
ballarin@41272
   687
          (map o apsnd) (instance_of thy name o op $>) (dependencies_of thy name |> map fst);
haftmann@37897
   688
      in
haftmann@37897
   689
        fold (fn (super, ts) => fn (gr, deps) => (gr |> Graph.add_edge (super, name),
haftmann@37897
   690
          deps |> Symtab.map_default (super, Symtab.empty) (Symtab.cons_list (name, ts))))
haftmann@37897
   691
            dependencies
haftmann@37897
   692
      end;
haftmann@37897
   693
  in
haftmann@37897
   694
    Graph.empty
haftmann@37897
   695
    |> fold add_locale_node names
haftmann@37897
   696
    |> rpair Symtab.empty
haftmann@37897
   697
    |> fold add_locale_deps names
haftmann@37897
   698
  end;
haftmann@37897
   699
haftmann@29361
   700
end;