src/Pure/Isar/locale.ML
author wenzelm
Sat May 01 22:08:57 2004 +0200 (2004-05-01)
changeset 14695 9c78044b99c3
parent 14643 130076a81b84
child 14777 5bb4bbdb6529
permissions -rw-r--r--
improved Term.invent_names;
wenzelm@12014
     1
(*  Title:      Pure/Isar/locale.ML
wenzelm@11896
     2
    ID:         $Id$
ballarin@14215
     3
    Author:     Markus Wenzel, LMU/TU Muenchen
wenzelm@11896
     4
    License:    GPL (GNU GENERAL PUBLIC LICENSE)
wenzelm@11896
     5
wenzelm@12058
     6
Locales -- Isar proof contexts as meta-level predicates, with local
wenzelm@12529
     7
syntax and implicit structures.
wenzelm@12529
     8
ballarin@14215
     9
Draws some basic ideas from Florian Kammueller's original version of
wenzelm@12529
    10
locales, but uses the richer infrastructure of Isar instead of the raw
wenzelm@12529
    11
meta-logic.  Furthermore, we provide structured import of contexts
ballarin@14215
    12
(with merge and rename operations), as well as type-inference of the
wenzelm@13375
    13
signature parts, and predicate definitions of the specification text.
ballarin@14446
    14
ballarin@14446
    15
See also:
ballarin@14446
    16
ballarin@14446
    17
[1] Clemens Ballarin. Locales and Locale Expressions in Isabelle/Isar.
ballarin@14446
    18
    In Stefano Berardi et al., Types for Proofs and Programs: International
ballarin@14446
    19
    Workshop, TYPES 2003, Torino, Italy, pages ??-??, in press.
wenzelm@11896
    20
*)
wenzelm@11896
    21
wenzelm@11896
    22
signature LOCALE =
wenzelm@11896
    23
sig
wenzelm@12046
    24
  type context
wenzelm@12046
    25
  datatype ('typ, 'term, 'fact, 'att) elem =
wenzelm@12058
    26
    Fixes of (string * 'typ option * mixfix option) list |
wenzelm@12046
    27
    Assumes of ((string * 'att list) * ('term * ('term list * 'term list)) list) list |
wenzelm@12046
    28
    Defines of ((string * 'att list) * ('term * 'term list)) list |
wenzelm@12273
    29
    Notes of ((string * 'att list) * ('fact * 'att list) list) list
wenzelm@12273
    30
  datatype expr =
wenzelm@12273
    31
    Locale of string |
wenzelm@12273
    32
    Rename of expr * string option list |
wenzelm@12273
    33
    Merge of expr list
wenzelm@12273
    34
  val empty: expr
wenzelm@12273
    35
  datatype ('typ, 'term, 'fact, 'att) elem_expr =
wenzelm@12273
    36
    Elem of ('typ, 'term, 'fact, 'att) elem | Expr of expr
wenzelm@12046
    37
  type 'att element
wenzelm@12046
    38
  type 'att element_i
wenzelm@12046
    39
  type locale
wenzelm@12046
    40
  val intern: Sign.sg -> xstring -> string
wenzelm@12014
    41
  val cond_extern: Sign.sg -> string -> xstring
wenzelm@12502
    42
  val the_locale: theory -> string -> locale
wenzelm@12273
    43
  val attribute: ('att -> context attribute) -> ('typ, 'term, 'thm, 'att) elem_expr
wenzelm@12273
    44
    -> ('typ, 'term, 'thm, context attribute) elem_expr
wenzelm@12529
    45
  val read_context_statement: xstring option -> context attribute element list ->
wenzelm@12529
    46
    (string * (string list * string list)) list list -> context ->
wenzelm@13415
    47
    string option * cterm list * context * context * (term * (term list * term list)) list list
wenzelm@12529
    48
  val cert_context_statement: string option -> context attribute element_i list ->
wenzelm@12529
    49
    (term * (term list * term list)) list list -> context ->
wenzelm@13415
    50
    string option * cterm list * context * context * (term * (term list * term list)) list list
wenzelm@12758
    51
  val print_locales: theory -> unit
wenzelm@12758
    52
  val print_locale: theory -> expr -> context attribute element list -> unit
wenzelm@13394
    53
  val add_locale: bool -> bstring -> expr -> context attribute element list -> theory -> theory
wenzelm@13394
    54
  val add_locale_i: bool -> bstring -> expr -> context attribute element_i list
wenzelm@13394
    55
    -> theory -> theory
wenzelm@14564
    56
  val smart_note_thmss: string -> (string * 'a) Library.option ->
wenzelm@12958
    57
    ((bstring * theory attribute list) * (thm list * theory attribute list) list) list ->
wenzelm@12958
    58
    theory -> theory * (bstring * thm list) list
wenzelm@14564
    59
  val note_thmss: string -> xstring ->
wenzelm@12711
    60
    ((bstring * context attribute list) * (xstring * context attribute list) list) list ->
wenzelm@12711
    61
    theory -> theory * (bstring * thm list) list
wenzelm@14564
    62
  val note_thmss_i: string -> string ->
wenzelm@12711
    63
    ((bstring * context attribute list) * (thm list * context attribute list) list) list ->
wenzelm@12711
    64
    theory -> theory * (bstring * thm list) list
wenzelm@12958
    65
  val add_thmss: string -> ((string * thm list) * context attribute list) list ->
wenzelm@13375
    66
    theory * context -> (theory * context) * (string * thm list) list
ballarin@14215
    67
  val prune_prems: theory -> thm -> thm
ballarin@14528
    68
  val instantiate: string -> string * context attribute list
ballarin@14528
    69
    -> thm list option -> context -> context
wenzelm@11896
    70
  val setup: (theory -> theory) list
wenzelm@11896
    71
end;
wenzelm@12839
    72
wenzelm@12289
    73
structure Locale: LOCALE =
wenzelm@11896
    74
struct
wenzelm@11896
    75
wenzelm@12273
    76
(** locale elements and expressions **)
wenzelm@11896
    77
wenzelm@12014
    78
type context = ProofContext.context;
wenzelm@11896
    79
wenzelm@12046
    80
datatype ('typ, 'term, 'fact, 'att) elem =
wenzelm@12058
    81
  Fixes of (string * 'typ option * mixfix option) list |
wenzelm@12046
    82
  Assumes of ((string * 'att list) * ('term * ('term list * 'term list)) list) list |
wenzelm@12046
    83
  Defines of ((string * 'att list) * ('term * 'term list)) list |
wenzelm@12273
    84
  Notes of ((string * 'att list) * ('fact * 'att list) list) list;
wenzelm@12273
    85
wenzelm@12273
    86
datatype expr =
wenzelm@12273
    87
  Locale of string |
wenzelm@12273
    88
  Rename of expr * string option list |
wenzelm@12273
    89
  Merge of expr list;
wenzelm@11896
    90
wenzelm@12273
    91
val empty = Merge [];
wenzelm@12273
    92
wenzelm@12273
    93
datatype ('typ, 'term, 'fact, 'att) elem_expr =
wenzelm@12273
    94
  Elem of ('typ, 'term, 'fact, 'att) elem | Expr of expr;
wenzelm@12273
    95
wenzelm@12273
    96
type 'att element = (string, string, string, 'att) elem_expr;
wenzelm@12273
    97
type 'att element_i = (typ, term, thm list, 'att) elem_expr;
wenzelm@12070
    98
wenzelm@12070
    99
type locale =
ballarin@14291
   100
 {view: cterm list * thm list,
ballarin@14508
   101
    (* CB: If locale "loc" contains assumptions, either via import or in the
ballarin@14446
   102
       locale body, a locale predicate "loc" is defined capturing all the
ballarin@14446
   103
       assumptions.  If both import and body contain assumptions, additionally
ballarin@14446
   104
       a delta predicate "loc_axioms" is defined that abbreviates the
ballarin@14446
   105
       assumptions of the body.
ballarin@14446
   106
       The context generated when entering "loc" contains not (necessarily) a
ballarin@14446
   107
       single assumption "loc", but a list of assumptions of all locale
ballarin@14446
   108
       predicates of locales without import and all delta predicates of
ballarin@14446
   109
       locales with import from the import hierarchy (duplicates removed,
ballarin@14446
   110
       cf. [1], normalisation of locale expressions).
ballarin@14446
   111
ballarin@14508
   112
       The record entry view is either ([], []) or ([statement], axioms)
ballarin@14508
   113
       where statement is the predicate "loc" applied to the parameters,
ballarin@14508
   114
       and axioms contains projections from "loc" to the list of assumptions
ballarin@14508
   115
       generated when entering the locale.
ballarin@14508
   116
       It appears that an axiom of the form A [A] is never generated.
ballarin@14446
   117
     *)
wenzelm@13399
   118
  import: expr,                                                         (*dynamic import*)
wenzelm@12289
   119
  elems: ((typ, term, thm list, context attribute) elem * stamp) list,  (*static content*)
wenzelm@13399
   120
  params: (string * typ option) list * string list};                  (*all/local params*)
wenzelm@12063
   121
wenzelm@13399
   122
fun make_locale view import elems params =
wenzelm@13399
   123
 {view = view, import = import, elems = elems, params = params}: locale;
wenzelm@12063
   124
wenzelm@11896
   125
wenzelm@11896
   126
(** theory data **)
wenzelm@11896
   127
wenzelm@11896
   128
structure LocalesArgs =
wenzelm@11896
   129
struct
wenzelm@12014
   130
  val name = "Isar/locales";
wenzelm@12063
   131
  type T = NameSpace.T * locale Symtab.table;
wenzelm@11896
   132
wenzelm@12063
   133
  val empty = (NameSpace.empty, Symtab.empty);
wenzelm@12063
   134
  val copy = I;
wenzelm@12118
   135
  val prep_ext = I;
wenzelm@12289
   136
wenzelm@12289
   137
  (*joining of locale elements: only facts may be added later!*)
wenzelm@13399
   138
  fun join ({view, import, elems, params}: locale, {elems = elems', ...}: locale) =
wenzelm@13399
   139
    Some (make_locale view import (gen_merge_lists eq_snd elems elems') params);
wenzelm@12273
   140
  fun merge ((space1, locs1), (space2, locs2)) =
wenzelm@12289
   141
    (NameSpace.merge (space1, space2), Symtab.join join (locs1, locs2));
wenzelm@12289
   142
wenzelm@12273
   143
  fun print _ (space, locs) =
wenzelm@12273
   144
    Pretty.strs ("locales:" :: map (NameSpace.cond_extern space o #1) (Symtab.dest locs))
wenzelm@12014
   145
    |> Pretty.writeln;
wenzelm@11896
   146
end;
wenzelm@11896
   147
wenzelm@11896
   148
structure LocalesData = TheoryDataFun(LocalesArgs);
wenzelm@11896
   149
val print_locales = LocalesData.print;
wenzelm@11896
   150
wenzelm@12289
   151
val intern = NameSpace.intern o #1 o LocalesData.get_sg;
wenzelm@12289
   152
val cond_extern = NameSpace.cond_extern o #1 o LocalesData.get_sg;
wenzelm@12289
   153
wenzelm@12277
   154
wenzelm@12277
   155
(* access locales *)
wenzelm@12277
   156
wenzelm@12063
   157
fun declare_locale name =
wenzelm@12063
   158
  LocalesData.map (apfst (fn space => (NameSpace.extend (space, [name]))));
wenzelm@11896
   159
wenzelm@12273
   160
fun put_locale name loc = LocalesData.map (apsnd (fn locs => Symtab.update ((name, loc), locs)));
wenzelm@12063
   161
fun get_locale thy name = Symtab.lookup (#2 (LocalesData.get thy), name);
wenzelm@11896
   162
wenzelm@12014
   163
fun the_locale thy name =
wenzelm@12014
   164
  (case get_locale thy name of
wenzelm@12014
   165
    Some loc => loc
wenzelm@12014
   166
  | None => error ("Unknown locale " ^ quote name));
wenzelm@11896
   167
wenzelm@12046
   168
ballarin@14215
   169
(* import hierarchy
ballarin@14215
   170
   implementation could be more efficient, eg. by maintaining a database
ballarin@14215
   171
   of dependencies *)
ballarin@14215
   172
ballarin@14215
   173
fun imports thy (upper, lower) =
ballarin@14215
   174
  let
ballarin@14215
   175
    val sign = sign_of thy;
ballarin@14215
   176
    fun imps (Locale name) low = (name = low) orelse
ballarin@14215
   177
      (case get_locale thy name of
ballarin@14215
   178
           None => false
ballarin@14215
   179
         | Some {import, ...} => imps import low)
ballarin@14215
   180
      | imps (Rename (expr, _)) low = imps expr low
ballarin@14215
   181
      | imps (Merge es) low = exists (fn e => imps e low) es;
ballarin@14215
   182
  in
ballarin@14215
   183
    imps (Locale (intern sign upper)) (intern sign lower)
ballarin@14215
   184
  end;
ballarin@14215
   185
ballarin@14215
   186
(** Name suffix of internal delta predicates.
ballarin@14215
   187
    These specify additional assumptions in a locale with import.
ballarin@14215
   188
    Also name of theorem set with destruct rules for locale main
ballarin@14215
   189
    predicates. **)
ballarin@14215
   190
ballarin@14215
   191
val axiomsN = "axioms";
ballarin@14215
   192
ballarin@14215
   193
local
ballarin@14215
   194
ballarin@14215
   195
(* A trie-like structure is used to compute a cover of a normalised
ballarin@14215
   196
   locale specification.  Entries of the trie will be identifiers:
ballarin@14215
   197
   locale names with parameter lists. *)
ballarin@14215
   198
ballarin@14215
   199
datatype 'a trie = Trie of ('a * 'a trie) list;
ballarin@14215
   200
ballarin@14215
   201
(* Subsumption relation on identifiers *)
ballarin@14215
   202
ballarin@14215
   203
fun subsumes thy ((name1, args1), (name2, args2)) =
ballarin@14215
   204
  (name2 = "" andalso null args2) orelse
ballarin@14215
   205
  ((name2 = name1 orelse imports thy (name1, name2)) andalso
ballarin@14215
   206
    (args2 prefix args1));
ballarin@14215
   207
ballarin@14215
   208
(* Insert into trie, wherever possible but avoiding branching *)
ballarin@14215
   209
ballarin@14215
   210
fun insert_ident subs id (Trie trie) =
ballarin@14215
   211
  let
ballarin@14215
   212
    fun insert id [] = [(id, Trie [])]
ballarin@14215
   213
      | insert id ((id', Trie t')::ts) =
ballarin@14215
   214
          if subs (id, id')
ballarin@14215
   215
          then if null ts
ballarin@14215
   216
            then [(id', Trie (insert id t'))] (* avoid new branch *)
ballarin@14215
   217
            else (id', Trie (insert id t'))::insert id ts
ballarin@14215
   218
          else (id', Trie t')::insert id ts
ballarin@14215
   219
  in Trie (insert id trie) end;
ballarin@14215
   220
ballarin@14215
   221
(* List of leaves of a trie, removing duplicates *)
ballarin@14215
   222
ballarin@14215
   223
fun leaves _ (Trie []) = []
ballarin@14215
   224
  | leaves eq (Trie ((id, Trie [])::ts)) =
ballarin@14215
   225
      gen_ins eq (id, leaves eq (Trie ts))
ballarin@14215
   226
  | leaves eq (Trie ((id, ts')::ts)) =
ballarin@14215
   227
      gen_merge_lists eq (leaves eq ts') (leaves eq (Trie ts));
ballarin@14215
   228
ballarin@14215
   229
in 
ballarin@14215
   230
ballarin@14291
   231
(** Prune premises:
ballarin@14291
   232
   Remove internal delta predicates (generated by "includes") from the
ballarin@14291
   233
   premises of a theorem.
ballarin@14215
   234
ballarin@14508
   235
   Assumes no outer quantifiers and no flex-flex pairs.
ballarin@14215
   236
   May change names of TVars.
ballarin@14291
   237
   Performs compress and close_derivation on result, if modified. **)
ballarin@14291
   238
ballarin@14291
   239
(* Note: reconstruction of the correct premises fails for subspace_normed_vs
ballarin@14291
   240
   in HOL/Real/HahnBanach/NormedSpace.thy.  This cannot be fixed since in the
ballarin@14291
   241
   current setup there is no way of distinguishing whether the theorem
ballarin@14291
   242
   statement involved "includes subspace F E + normed_vectorspace E" or
ballarin@14291
   243
   "includes subspace F E + vectorspace E + norm E norm".
ballarin@14291
   244
*)
ballarin@14215
   245
ballarin@14215
   246
fun prune_prems thy thm = let
ballarin@14215
   247
  val sign = Theory.sign_of thy;
ballarin@14215
   248
  fun analyse cprem =
ballarin@14215
   249
    (* Returns None if head of premise is not a predicate defined by a locale,
ballarin@14291
   250
       returns also None if locale has a view but predicate is not *_axioms
ballarin@14215
   251
       since this is a premise that wasn't generated by includes.  *)
ballarin@14215
   252
    case Term.strip_comb (ObjectLogic.drop_judgment sign (term_of cprem)) of
ballarin@14215
   253
	(Const (raw_name, T), args) => let
ballarin@14215
   254
            val name = unsuffix ("_" ^ axiomsN) raw_name
ballarin@14215
   255
              handle LIST _ => raw_name
ballarin@14215
   256
          in case get_locale thy name of
ballarin@14215
   257
		None => None
ballarin@14291
   258
	      | Some {view = (_, axioms), ...} =>
ballarin@14291
   259
                  if name = raw_name andalso not (null axioms)
ballarin@14215
   260
                  then None
ballarin@14215
   261
                  else Some (((name, args), T), name = raw_name)
ballarin@14215
   262
          end
ballarin@14215
   263
      | _ => None;
ballarin@14215
   264
  val TFrees = add_term_tfree_names (prop_of thm, []);
ballarin@14215
   265
    (* Ignores TFrees in flex-flex pairs ! *)
ballarin@14215
   266
  val (frozen, thaw) = Drule.freeze_thaw thm;
ballarin@14215
   267
  val cprop = cprop_of frozen;
ballarin@14215
   268
  val cprems = Drule.strip_imp_prems cprop;
ballarin@14215
   269
  val analysis = map analyse cprems;
ballarin@14215
   270
in
ballarin@14215
   271
  if foldl (fn (b, None) => b | (b, Some (_, b')) => b andalso b')
ballarin@14215
   272
           (true, analysis)
ballarin@14215
   273
  then thm   (* No premise contains *_axioms predicate
ballarin@14215
   274
                ==> no changes necessary. *)
ballarin@14215
   275
  else let
ballarin@14215
   276
    val ids = map (apsome fst) analysis;
ballarin@14215
   277
    (* Analyse dependencies of locale premises: store in trie. *)
ballarin@14215
   278
    fun subs ((x, _), (y, _)) = subsumes thy (x, y);
ballarin@14215
   279
    val Trie depcs = foldl (fn (trie, None) => trie
ballarin@14215
   280
			     | (trie, Some id) => insert_ident subs id trie)
ballarin@14215
   281
			   (Trie [], ids);
ballarin@14215
   282
    (* Assemble new theorem; new prems will be hyps.
ballarin@14291
   283
       Axioms is an intermediate list of locale axioms required to
ballarin@14215
   284
       replace old premises by new ones. *)
ballarin@14215
   285
    fun scan ((roots, thm, cprems', axioms), (cprem, id)) =
ballarin@14215
   286
	  case id of
ballarin@14215
   287
	      None => (roots, implies_elim thm (assume cprem),
ballarin@14215
   288
		       cprems' @ [cprem], [])
ballarin@14215
   289
					       (* Normal premise: keep *)
ballarin@14215
   290
	    | Some id =>                       (* Locale premise *)
ballarin@14215
   291
		let
ballarin@14215
   292
		  fun elim_ax [] thm =  (* locale has no axioms *)
ballarin@14215
   293
		      implies_elim thm (assume cprem)
ballarin@14215
   294
		    | elim_ax axs thm = let
ballarin@14215
   295
		    (* Eliminate first premise of thm, which is of the form
ballarin@14215
   296
                       id.  Add hyp of the used axiom to thm. *)
ballarin@14215
   297
		    val ax = the (assoc (axs, fst (fst id)))
ballarin@14215
   298
	              handle _ => error ("Internal error in Locale.prune_\
ballarin@14215
   299
                        \prems: axiom for premise" ^
ballarin@14215
   300
                        fst (fst id) ^ " not found.");
ballarin@14215
   301
		    val [ax_cprem] = Drule.strip_imp_prems (cprop_of ax)
ballarin@14215
   302
		      handle _ => error ("Internal error in Locale.prune_\
ballarin@14215
   303
                        \prems: exactly one premise in axiom expected.");
ballarin@14215
   304
		    val ax_hyp = implies_elim ax (assume (ax_cprem))
ballarin@14215
   305
		  in implies_elim thm ax_hyp
ballarin@14215
   306
		  end
ballarin@14215
   307
		in
ballarin@14215
   308
		  if null roots
ballarin@14215
   309
		  then (roots, elim_ax axioms thm, cprems', axioms)
ballarin@14215
   310
					       (* Remaining premise: drop *)
ballarin@14215
   311
		  else let
ballarin@14215
   312
		      fun mk_cprem ((name, args), T) = cterm_of sign
ballarin@14215
   313
                        (ObjectLogic.assert_propT sign
ballarin@14215
   314
			  (Term.list_comb (Const (name, T), args)));
ballarin@14215
   315
		      fun get_axs ((name, args), _) = let
ballarin@14215
   316
			  val {view = (_, axioms), ...} = the_locale thy name;
ballarin@14215
   317
			  fun inst ax =
ballarin@14215
   318
			    let
ballarin@14215
   319
			      val std = standard ax;
ballarin@14215
   320
                              val (prem, concl) =
ballarin@14215
   321
                                Logic.dest_implies (prop_of std);
ballarin@14215
   322
			      val (Const (name2, _), _) = Term.strip_comb
ballarin@14215
   323
				(ObjectLogic.drop_judgment sign concl);
ballarin@14215
   324
                              val (_, vars) = Term.strip_comb
ballarin@14215
   325
				(ObjectLogic.drop_judgment sign prem);
ballarin@14215
   326
			      val cert = map (cterm_of sign);
ballarin@14215
   327
			    in (unsuffix ("_" ^ axiomsN) name2
ballarin@14215
   328
                                  handle LIST _ => name2,
ballarin@14215
   329
			       cterm_instantiate (cert vars ~~ cert args) std)
ballarin@14215
   330
			    end;
ballarin@14215
   331
			in map inst axioms end;
ballarin@14215
   332
		      val (id', trie) = hd roots;
ballarin@14215
   333
		    in if id = id'
ballarin@14215
   334
		      then                     (* Initial premise *)
ballarin@14215
   335
			let
ballarin@14215
   336
			  val lvs = leaves eq_fst (Trie [(id', trie)]);
ballarin@14215
   337
			  val axioms' = flat (map get_axs lvs)
ballarin@14215
   338
			in (tl roots, elim_ax axioms' thm,
ballarin@14215
   339
                            cprems' @ map (mk_cprem) lvs, axioms')
ballarin@14215
   340
			end
ballarin@14215
   341
		      else (roots, elim_ax axioms thm, cprems', axioms)
ballarin@14215
   342
					       (* Remaining premise: drop *)
ballarin@14215
   343
		    end
ballarin@14215
   344
		end;
ballarin@14215
   345
    val (_, thm', cprems', _) =
ballarin@14215
   346
      (foldl scan ((depcs, frozen, [], []), cprems ~~ ids));
ballarin@14215
   347
    val thm'' = implies_intr_list cprems' thm';
ballarin@14215
   348
  in
ballarin@14215
   349
    fst (varifyT' TFrees (thaw thm''))
ballarin@14215
   350
    |> Thm.compress |> Drule.close_derivation
ballarin@14215
   351
  end
ballarin@14215
   352
end;
ballarin@14215
   353
ballarin@14215
   354
end (* local *)
ballarin@14215
   355
ballarin@14215
   356
wenzelm@12277
   357
(* diagnostics *)
wenzelm@12273
   358
wenzelm@12277
   359
fun err_in_locale ctxt msg ids =
wenzelm@12277
   360
  let
wenzelm@12529
   361
    val sign = ProofContext.sign_of ctxt;
wenzelm@12529
   362
    fun prt_id (name, parms) =
wenzelm@12529
   363
      [Pretty.block (Pretty.breaks (map Pretty.str (cond_extern sign name :: parms)))];
wenzelm@12289
   364
    val prt_ids = flat (separate [Pretty.str " +", Pretty.brk 1] (map prt_id ids));
wenzelm@12502
   365
    val err_msg =
wenzelm@12529
   366
      if forall (equal "" o #1) ids then msg
wenzelm@12502
   367
      else msg ^ "\n" ^ Pretty.string_of (Pretty.block
wenzelm@12502
   368
        (Pretty.str "The error(s) above occurred in locale:" :: Pretty.brk 1 :: prt_ids));
wenzelm@12502
   369
  in raise ProofContext.CONTEXT (err_msg, ctxt) end;
wenzelm@12063
   370
wenzelm@12277
   371
wenzelm@12277
   372
wenzelm@12529
   373
(** primitives **)
wenzelm@12046
   374
wenzelm@12277
   375
(* renaming *)
wenzelm@12263
   376
wenzelm@12263
   377
fun rename ren x = if_none (assoc_string (ren, x)) x;
wenzelm@12263
   378
wenzelm@12263
   379
fun rename_term ren (Free (x, T)) = Free (rename ren x, T)
wenzelm@12263
   380
  | rename_term ren (t $ u) = rename_term ren t $ rename_term ren u
wenzelm@12263
   381
  | rename_term ren (Abs (x, T, t)) = Abs (x, T, rename_term ren t)
wenzelm@12263
   382
  | rename_term _ a = a;
wenzelm@12263
   383
wenzelm@12263
   384
fun rename_thm ren th =
wenzelm@12263
   385
  let
wenzelm@12263
   386
    val {sign, hyps, prop, maxidx, ...} = Thm.rep_thm th;
wenzelm@12263
   387
    val cert = Thm.cterm_of sign;
wenzelm@12502
   388
    val (xs, Ts) = Library.split_list (foldl Term.add_frees ([], prop :: hyps));
wenzelm@12263
   389
    val xs' = map (rename ren) xs;
wenzelm@12263
   390
    fun cert_frees names = map (cert o Free) (names ~~ Ts);
wenzelm@12263
   391
    fun cert_vars names = map (cert o Var o apfst (rpair (maxidx + 1))) (names ~~ Ts);
wenzelm@12263
   392
  in
wenzelm@12263
   393
    if xs = xs' then th
wenzelm@12263
   394
    else
wenzelm@12263
   395
      th
wenzelm@12263
   396
      |> Drule.implies_intr_list (map cert hyps)
wenzelm@12263
   397
      |> Drule.forall_intr_list (cert_frees xs)
wenzelm@12263
   398
      |> Drule.forall_elim_list (cert_vars xs)
wenzelm@12263
   399
      |> Thm.instantiate ([], cert_vars xs ~~ cert_frees xs')
wenzelm@12263
   400
      |> (fn th' => Drule.implies_elim_list th' (map (Thm.assume o cert o rename_term ren) hyps))
wenzelm@12263
   401
  end;
wenzelm@12263
   402
wenzelm@12529
   403
fun rename_elem ren (Fixes fixes) = Fixes (fixes |> map (fn (x, T, mx) =>
wenzelm@12529
   404
      let val x' = rename ren x in
wenzelm@12529
   405
        if x = x' then (x, T, mx)
wenzelm@12529
   406
        else (x', T, if mx = None then mx else Some Syntax.NoSyn)    (*drop syntax*)
wenzelm@12529
   407
      end))
wenzelm@12263
   408
  | rename_elem ren (Assumes asms) = Assumes (map (apsnd (map (fn (t, (ps, qs)) =>
wenzelm@12263
   409
      (rename_term ren t, (map (rename_term ren) ps, map (rename_term ren) qs))))) asms)
wenzelm@12263
   410
  | rename_elem ren (Defines defs) = Defines (map (apsnd (fn (t, ps) =>
wenzelm@12263
   411
      (rename_term ren t, map (rename_term ren) ps))) defs)
wenzelm@12273
   412
  | rename_elem ren (Notes facts) = Notes (map (apsnd (map (apfst (map (rename_thm ren))))) facts);
wenzelm@12263
   413
wenzelm@12529
   414
fun rename_facts prfx elem =
wenzelm@12307
   415
  let
wenzelm@12323
   416
    fun qualify (arg as ((name, atts), x)) =
wenzelm@13394
   417
      if prfx = "" orelse name = "" then arg
wenzelm@13375
   418
      else ((NameSpace.pack [prfx, name], atts), x);
wenzelm@12307
   419
  in
wenzelm@12307
   420
    (case elem of
wenzelm@12307
   421
      Fixes fixes => Fixes fixes
wenzelm@12307
   422
    | Assumes asms => Assumes (map qualify asms)
wenzelm@12307
   423
    | Defines defs => Defines (map qualify defs)
wenzelm@12307
   424
    | Notes facts => Notes (map qualify facts))
wenzelm@12307
   425
  end;
wenzelm@12307
   426
wenzelm@12263
   427
wenzelm@12502
   428
(* type instantiation *)
wenzelm@12502
   429
wenzelm@12502
   430
fun inst_type [] T = T
wenzelm@12502
   431
  | inst_type env T = Term.map_type_tfree (fn v => if_none (assoc (env, v)) (TFree v)) T;
wenzelm@12502
   432
wenzelm@12502
   433
fun inst_term [] t = t
wenzelm@12502
   434
  | inst_term env t = Term.map_term_types (inst_type env) t;
wenzelm@12502
   435
wenzelm@13211
   436
fun inst_thm _ [] th = th
wenzelm@13211
   437
  | inst_thm ctxt env th =
wenzelm@12502
   438
      let
wenzelm@13211
   439
        val sign = ProofContext.sign_of ctxt;
wenzelm@12575
   440
        val cert = Thm.cterm_of sign;
wenzelm@12575
   441
        val certT = Thm.ctyp_of sign;
wenzelm@13211
   442
        val {hyps, prop, maxidx, ...} = Thm.rep_thm th;
wenzelm@12579
   443
        val tfrees = foldr Term.add_term_tfree_names (prop :: hyps, []);
wenzelm@12579
   444
        val env' = filter (fn ((a, _), _) => a mem_string tfrees) env;
wenzelm@12502
   445
      in
wenzelm@12502
   446
        if null env' then th
wenzelm@12502
   447
        else
wenzelm@12502
   448
          th
wenzelm@12502
   449
          |> Drule.implies_intr_list (map cert hyps)
wenzelm@12575
   450
          |> Drule.tvars_intr_list (map (#1 o #1) env')
wenzelm@12502
   451
          |> (fn (th', al) => th' |>
wenzelm@12502
   452
            Thm.instantiate ((map (fn ((a, _), T) => (the (assoc (al, a)), certT T)) env'), []))
wenzelm@12502
   453
          |> (fn th'' => Drule.implies_elim_list th''
wenzelm@12502
   454
              (map (Thm.assume o cert o inst_term env') hyps))
wenzelm@12502
   455
      end;
wenzelm@12502
   456
wenzelm@13211
   457
fun inst_elem _ env (Fixes fixes) =
wenzelm@12502
   458
      Fixes (map (fn (x, T, mx) => (x, apsome (inst_type env) T, mx)) fixes)
wenzelm@13211
   459
  | inst_elem _ env (Assumes asms) = Assumes (map (apsnd (map (fn (t, (ps, qs)) =>
wenzelm@12502
   460
      (inst_term env t, (map (inst_term env) ps, map (inst_term env) qs))))) asms)
wenzelm@13211
   461
  | inst_elem _ env (Defines defs) = Defines (map (apsnd (fn (t, ps) =>
wenzelm@12502
   462
      (inst_term env t, map (inst_term env) ps))) defs)
wenzelm@13211
   463
  | inst_elem ctxt env (Notes facts) =
wenzelm@13211
   464
      Notes (map (apsnd (map (apfst (map (inst_thm ctxt env))))) facts);
wenzelm@12502
   465
wenzelm@12502
   466
wenzelm@12529
   467
wenzelm@12529
   468
(** structured contexts: rename + merge + implicit type instantiation **)
wenzelm@12529
   469
wenzelm@12529
   470
(* parameter types *)
wenzelm@12529
   471
ballarin@14508
   472
(* CB: frozen_tvars has the following type:
ballarin@14508
   473
  ProofContext.context -> Term.typ list -> (Term.indexname * Term.typ) list *)
ballarin@14508
   474
wenzelm@12529
   475
fun frozen_tvars ctxt Ts =
wenzelm@12529
   476
  let
wenzelm@12529
   477
    val tvars = rev (foldl Term.add_tvarsT ([], Ts));
wenzelm@12529
   478
    val tfrees = map TFree
wenzelm@14695
   479
      (Term.invent_names (ProofContext.used_types ctxt) "'a" (length tvars) ~~ map #2 tvars);
wenzelm@12529
   480
  in map #1 tvars ~~ tfrees end;
wenzelm@12529
   481
wenzelm@12529
   482
fun unify_frozen ctxt maxidx Ts Us =
wenzelm@12529
   483
  let
wenzelm@12529
   484
    fun paramify (i, None) = (i, None)
wenzelm@12529
   485
      | paramify (i, Some T) = apsnd Some (Type.paramify_dummies (i, T));
wenzelm@12529
   486
wenzelm@12529
   487
    val (maxidx', Ts') = foldl_map paramify (maxidx, Ts);
wenzelm@12727
   488
    val (maxidx'', Us') = foldl_map paramify (maxidx', Us);
ballarin@14215
   489
    val tsig = Sign.tsig_of (ProofContext.sign_of ctxt);
ballarin@14215
   490
ballarin@14215
   491
    fun unify (env, (Some T, Some U)) = (Type.unify tsig env (U, T)
ballarin@14215
   492
          handle Type.TUNIFY =>
ballarin@14215
   493
            raise TYPE ("unify_frozen: failed to unify types", [U, T], []))
ballarin@14215
   494
      | unify (env, _) = env;
wenzelm@12529
   495
    val (unifier, _) = foldl unify ((Vartab.empty, maxidx''), Ts' ~~ Us');
wenzelm@12529
   496
    val Vs = map (apsome (Envir.norm_type unifier)) Us';
wenzelm@12529
   497
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (mapfilter I Vs));
wenzelm@12532
   498
  in map (apsome (Envir.norm_type unifier')) Vs end;
wenzelm@12529
   499
wenzelm@12730
   500
fun params_of elemss = gen_distinct eq_fst (flat (map (snd o fst) elemss));
ballarin@14508
   501
ballarin@14508
   502
(* CB: param_types has the following type:
ballarin@14508
   503
  ('a * 'b Library.option) list -> ('a * 'b) list *)
wenzelm@12529
   504
fun param_types ps = mapfilter (fn (_, None) => None | (x, Some T) => Some (x, T)) ps;
wenzelm@12529
   505
wenzelm@12529
   506
wenzelm@12529
   507
(* flatten expressions *)
wenzelm@11896
   508
wenzelm@12510
   509
local
wenzelm@12502
   510
ballarin@14508
   511
(* CB: unique_parms has the following type:
ballarin@14508
   512
     'a ->
ballarin@14508
   513
     (('b * (('c * 'd) list * Symtab.key list)) * 'e) list ->
ballarin@14508
   514
     (('b * ('c * 'd) list) * 'e) list  *)
ballarin@14508
   515
wenzelm@12529
   516
fun unique_parms ctxt elemss =
wenzelm@12529
   517
  let
wenzelm@12529
   518
    val param_decls =
wenzelm@12529
   519
      flat (map (fn ((name, (ps, qs)), _) => map (rpair (name, ps)) qs) elemss)
wenzelm@12529
   520
      |> Symtab.make_multi |> Symtab.dest;
wenzelm@12529
   521
  in
wenzelm@12529
   522
    (case find_first (fn (_, ids) => length ids > 1) param_decls of
wenzelm@12529
   523
      Some (q, ids) => err_in_locale ctxt ("Multiple declaration of parameter " ^ quote q)
wenzelm@12529
   524
          (map (apsnd (map fst)) ids)
wenzelm@12529
   525
    | None => map (apfst (apsnd #1)) elemss)
wenzelm@12529
   526
  end;
wenzelm@12529
   527
ballarin@14508
   528
(* CB: unify_parms has the following type:
ballarin@14508
   529
     ProofContext.context ->
ballarin@14508
   530
     (string * Term.typ) list ->
ballarin@14508
   531
     (string * Term.typ Library.option) list list ->
ballarin@14508
   532
     ((string * Term.sort) * Term.typ) list list *)
ballarin@14508
   533
wenzelm@12529
   534
fun unify_parms ctxt fixed_parms raw_parmss =
wenzelm@12502
   535
  let
wenzelm@12502
   536
    val tsig = Sign.tsig_of (ProofContext.sign_of ctxt);
wenzelm@12502
   537
    val maxidx = length raw_parmss;
wenzelm@12502
   538
    val idx_parmss = (0 upto maxidx - 1) ~~ raw_parmss;
wenzelm@12502
   539
wenzelm@12502
   540
    fun varify i = Term.map_type_tfree (fn (a, S) => TVar ((a, i), S));
wenzelm@12529
   541
    fun varify_parms (i, ps) = map (apsnd (varify i)) (param_types ps);
wenzelm@12529
   542
    val parms = fixed_parms @ flat (map varify_parms idx_parmss);
wenzelm@12502
   543
wenzelm@12529
   544
    fun unify T ((env, maxidx), U) = Type.unify tsig (env, maxidx) (U, T)
wenzelm@12529
   545
      handle Type.TUNIFY => raise TYPE ("unify_parms: failed to unify types", [U, T], []);
wenzelm@12502
   546
    fun unify_list (envir, T :: Us) = foldl (unify T) (envir, Us)
wenzelm@12502
   547
      | unify_list (envir, []) = envir;
wenzelm@12502
   548
    val (unifier, _) = foldl unify_list
wenzelm@12502
   549
      ((Vartab.empty, maxidx), map #2 (Symtab.dest (Symtab.make_multi parms)));
wenzelm@12502
   550
wenzelm@12502
   551
    val parms' = map (apsnd (Envir.norm_type unifier)) (gen_distinct eq_fst parms);
wenzelm@12502
   552
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map #2 parms'));
wenzelm@12502
   553
wenzelm@12502
   554
    fun inst_parms (i, ps) =
wenzelm@12502
   555
      foldr Term.add_typ_tfrees (mapfilter snd ps, [])
wenzelm@12502
   556
      |> mapfilter (fn (a, S) =>
wenzelm@12502
   557
          let val T = Envir.norm_type unifier' (TVar ((a, i), S))
ballarin@14215
   558
          in if T = TFree (a, S) then None else Some ((a, S), T) end)
wenzelm@12502
   559
  in map inst_parms idx_parmss end;
wenzelm@12502
   560
wenzelm@12529
   561
in
wenzelm@12502
   562
wenzelm@12529
   563
fun unify_elemss _ _ [] = []
wenzelm@12529
   564
  | unify_elemss _ [] [elems] = [elems]
wenzelm@12529
   565
  | unify_elemss ctxt fixed_parms elemss =
wenzelm@12502
   566
      let
wenzelm@12529
   567
        val envs = unify_parms ctxt fixed_parms (map (#2 o #1) elemss);
wenzelm@13308
   568
        fun inst (((name, ps), elems), env) =
wenzelm@13308
   569
          ((name, map (apsnd (apsome (inst_type env))) ps), (map (inst_elem ctxt env) elems));
wenzelm@12839
   570
      in map inst (elemss ~~ envs) end;
wenzelm@12502
   571
wenzelm@12575
   572
fun flatten_expr ctxt (prev_idents, expr) =
wenzelm@12014
   573
  let
wenzelm@12014
   574
    val thy = ProofContext.theory_of ctxt;
wenzelm@12263
   575
wenzelm@12289
   576
    fun renaming (Some x :: xs) (y :: ys) = (y, x) :: renaming xs ys
wenzelm@12289
   577
      | renaming (None :: xs) (y :: ys) = renaming xs ys
wenzelm@12273
   578
      | renaming [] _ = []
wenzelm@12289
   579
      | renaming xs [] = raise ERROR_MESSAGE ("Too many arguments in renaming: " ^
wenzelm@12289
   580
          commas (map (fn None => "_" | Some x => quote x) xs));
wenzelm@12289
   581
wenzelm@12289
   582
    fun rename_parms ren (name, ps) =
wenzelm@12289
   583
      let val ps' = map (rename ren) ps in
wenzelm@12289
   584
        (case duplicates ps' of [] => (name, ps')
wenzelm@12289
   585
        | dups => err_in_locale ctxt ("Duplicate parameters: " ^ commas_quote dups) [(name, ps')])
wenzelm@12289
   586
      end;
wenzelm@12263
   587
wenzelm@12273
   588
    fun identify ((ids, parms), Locale name) =
ballarin@14215
   589
    (* CB: ids is list of pairs: locale name and list of parameter renamings,
ballarin@14215
   590
       parms is accumulated list of parameters *)
wenzelm@12289
   591
          let
wenzelm@12289
   592
            val {import, params, ...} = the_locale thy name;
wenzelm@12289
   593
            val ps = map #1 (#1 params);
wenzelm@12289
   594
          in
wenzelm@12273
   595
            if (name, ps) mem ids then (ids, parms)
wenzelm@12277
   596
            else
wenzelm@12289
   597
              let val (ids', parms') = identify ((ids, parms), import);  (*acyclic dependencies!*)
wenzelm@12289
   598
              in (ids' @ [(name, ps)], merge_lists parms' ps) end
wenzelm@12273
   599
          end
wenzelm@12273
   600
      | identify ((ids, parms), Rename (e, xs)) =
wenzelm@12273
   601
          let
wenzelm@12273
   602
            val (ids', parms') = identify (([], []), e);
wenzelm@12839
   603
            val ren = renaming xs parms'
wenzelm@12839
   604
              handle ERROR_MESSAGE msg => err_in_locale ctxt msg ids';
wenzelm@12289
   605
            val ids'' = distinct (map (rename_parms ren) ids');
wenzelm@12289
   606
            val parms'' = distinct (flat (map #2 ids''));
wenzelm@12289
   607
          in (merge_lists ids ids'', merge_lists parms parms'') end
wenzelm@12273
   608
      | identify (arg, Merge es) = foldl identify (arg, es);
wenzelm@12014
   609
wenzelm@12307
   610
    fun eval (name, xs) =
wenzelm@12273
   611
      let
wenzelm@13308
   612
        val {params = (ps, qs), elems, ...} = the_locale thy name;
wenzelm@12307
   613
        val ren = filter_out (op =) (map #1 ps ~~ xs);
wenzelm@13308
   614
        val (params', elems') =
wenzelm@13308
   615
          if null ren then ((ps, qs), map #1 elems)
wenzelm@12502
   616
          else ((map (apfst (rename ren)) ps, map (rename ren) qs),
wenzelm@13308
   617
            map (rename_elem ren o #1) elems);
wenzelm@13375
   618
        val elems'' = map (rename_facts (space_implode "_" xs)) elems';
wenzelm@13308
   619
      in ((name, params'), elems'') end;
wenzelm@12307
   620
wenzelm@12575
   621
    val idents = gen_rems (op =) (#1 (identify (([], []), expr)), prev_idents);
wenzelm@12575
   622
    val raw_elemss = unique_parms ctxt (map eval idents);
wenzelm@12529
   623
    val elemss = unify_elemss ctxt [] raw_elemss;
wenzelm@12575
   624
  in (prev_idents @ idents, elemss) end;
wenzelm@12046
   625
wenzelm@12510
   626
end;
wenzelm@12510
   627
wenzelm@12070
   628
wenzelm@12529
   629
(* activate elements *)
wenzelm@12273
   630
wenzelm@12510
   631
local
wenzelm@12510
   632
wenzelm@13399
   633
fun export_axioms axs _ hyps th =
wenzelm@13399
   634
  th |> Drule.satisfy_hyps axs
wenzelm@13399
   635
  |> Drule.implies_intr_list (Library.drop (length axs, hyps))
wenzelm@13399
   636
  |> Seq.single;
wenzelm@12263
   637
wenzelm@14643
   638
fun activate_elem _ ((ctxt, axs), Fixes fixes) =
wenzelm@14643
   639
      ((ctxt |> ProofContext.add_fixes fixes, axs), [])
wenzelm@13399
   640
  | activate_elem _ ((ctxt, axs), Assumes asms) =
wenzelm@13399
   641
      let
wenzelm@13399
   642
        val ts = flat (map (map #1 o #2) asms);
nipkow@13629
   643
        val (ps,qs) = splitAt (length ts, axs)
wenzelm@13420
   644
        val (ctxt', _) =
wenzelm@13399
   645
          ctxt |> ProofContext.fix_frees ts
nipkow@13629
   646
          |> ProofContext.assume_i (export_axioms ps) asms;
nipkow@13629
   647
      in ((ctxt', qs), []) end
wenzelm@13399
   648
  | activate_elem _ ((ctxt, axs), Defines defs) =
wenzelm@13420
   649
      let val (ctxt', _) =
wenzelm@13399
   650
        ctxt |> ProofContext.assume_i ProofContext.export_def
wenzelm@13399
   651
          (defs |> map (fn ((name, atts), (t, ps)) =>
wenzelm@13399
   652
            let val (c, t') = ProofContext.cert_def ctxt t
wenzelm@13399
   653
            in ((if name = "" then Thm.def_name c else name, atts), [(t', (ps, []))]) end))
wenzelm@13420
   654
      in ((ctxt', axs), []) end
wenzelm@13399
   655
  | activate_elem is_ext ((ctxt, axs), Notes facts) =
wenzelm@14564
   656
      let val (ctxt', res) = ctxt |> ProofContext.note_thmss_i facts
wenzelm@13420
   657
      in ((ctxt', axs), if is_ext then res else []) end;
wenzelm@12502
   658
wenzelm@13399
   659
fun activate_elems ((name, ps), elems) (ctxt, axs) =
wenzelm@13399
   660
  let val ((ctxt', axs'), res) =
wenzelm@13399
   661
    foldl_map (activate_elem (name = "")) ((ProofContext.qualified true ctxt, axs), elems)
wenzelm@13399
   662
      handle ProofContext.CONTEXT (msg, ctxt) => err_in_locale ctxt msg [(name, map fst ps)]
wenzelm@13399
   663
  in ((ProofContext.restore_qualified ctxt ctxt', axs'), res) end;
wenzelm@13399
   664
wenzelm@13399
   665
fun activate_elemss prep_facts = foldl_map (fn ((ctxt, axs), ((name, ps), raw_elems)) =>
wenzelm@12834
   666
  let
wenzelm@12834
   667
    val elems = map (prep_facts ctxt) raw_elems;
wenzelm@13399
   668
    val ((ctxt', axs'), res) = apsnd flat (activate_elems ((name, ps), elems) (ctxt, axs));
wenzelm@13399
   669
  in ((ctxt', axs'), (((name, ps), elems), res)) end);
wenzelm@12834
   670
wenzelm@12546
   671
in
wenzelm@12546
   672
ballarin@14508
   673
(* CB: activate_facts prep_facts ((ctxt, axioms), elemss),
ballarin@14508
   674
   where elemss is a list of pairs consisting of identifiers and context
ballarin@14508
   675
   elements, extends ctxt by the context elements yielding ctxt' and returns
ballarin@14508
   676
   ((ctxt', axioms'), (elemss', facts)).
ballarin@14508
   677
   Assumptions use entries from axioms to set up exporters in ctxt'.  Unused
ballarin@14508
   678
   axioms are returned as axioms'; elemss' is obtained from elemss (without
ballarin@14508
   679
   identifier) and the intermediate context with prep_facts.
ballarin@14508
   680
   If get_facts or get_facts_i is used for prep_facts, these also remove
ballarin@14508
   681
   the internal/external markers from elemss. *)
ballarin@14508
   682
wenzelm@13399
   683
fun activate_facts prep_facts arg =
wenzelm@13399
   684
  apsnd (apsnd flat o Library.split_list) (activate_elemss prep_facts arg);
wenzelm@12546
   685
wenzelm@12510
   686
end;
wenzelm@12510
   687
wenzelm@12307
   688
wenzelm@12529
   689
(** prepare context elements **)
wenzelm@12529
   690
wenzelm@12529
   691
(* expressions *)
wenzelm@12529
   692
wenzelm@12529
   693
fun intern_expr sg (Locale xname) = Locale (intern sg xname)
wenzelm@12529
   694
  | intern_expr sg (Merge exprs) = Merge (map (intern_expr sg) exprs)
wenzelm@12529
   695
  | intern_expr sg (Rename (expr, xs)) = Rename (intern_expr sg expr, xs);
wenzelm@12529
   696
wenzelm@12529
   697
wenzelm@12546
   698
(* attributes *)
wenzelm@12546
   699
wenzelm@12546
   700
local fun read_att attrib (x, srcs) = (x, map attrib srcs) in
wenzelm@12546
   701
ballarin@14508
   702
(* CB: Map attrib over
ballarin@14446
   703
   * A context element: add attrib to attribute lists of assumptions,
ballarin@14446
   704
     definitions and facts (on both sides for facts).
ballarin@14446
   705
   * Locale expression: no effect. *)
ballarin@14446
   706
ballarin@14446
   707
wenzelm@12546
   708
fun attribute _ (Elem (Fixes fixes)) = Elem (Fixes fixes)
wenzelm@12546
   709
  | attribute attrib (Elem (Assumes asms)) = Elem (Assumes (map (apfst (read_att attrib)) asms))
wenzelm@12546
   710
  | attribute attrib (Elem (Defines defs)) = Elem (Defines (map (apfst (read_att attrib)) defs))
wenzelm@12546
   711
  | attribute attrib (Elem (Notes facts)) =
wenzelm@12546
   712
      Elem (Notes (map (apfst (read_att attrib) o apsnd (map (read_att attrib))) facts))
wenzelm@12546
   713
  | attribute _ (Expr expr) = Expr expr;
wenzelm@12546
   714
wenzelm@12546
   715
end;
wenzelm@12546
   716
wenzelm@12546
   717
wenzelm@12529
   718
(* parameters *)
wenzelm@12502
   719
wenzelm@12502
   720
local
wenzelm@12502
   721
wenzelm@12529
   722
fun prep_fixes prep_vars ctxt fixes =
wenzelm@12529
   723
  let val vars = snd (foldl_map prep_vars (ctxt, map (fn (x, T, _) => ([x], T)) fixes))
wenzelm@12529
   724
  in map (fn (([x'], T'), (_, _, mx)) => (x', T', mx)) (vars ~~ fixes) end;
wenzelm@12529
   725
wenzelm@12529
   726
in
wenzelm@12529
   727
wenzelm@12529
   728
fun read_fixes x = prep_fixes ProofContext.read_vars x;
wenzelm@12529
   729
fun cert_fixes x = prep_fixes ProofContext.cert_vars x;
wenzelm@12529
   730
wenzelm@12529
   731
end;
wenzelm@12529
   732
wenzelm@12529
   733
wenzelm@12529
   734
(* propositions and bindings *)
wenzelm@12529
   735
wenzelm@12529
   736
datatype ('a, 'b) int_ext = Int of 'a | Ext of 'b;
wenzelm@12529
   737
ballarin@14508
   738
(* CB: flatten (ids, expr) normalises expr (which is either a locale
ballarin@14508
   739
   expression or a single context element) wrt.
ballarin@14508
   740
   to the list ids of already accumulated identifiers.
ballarin@14508
   741
   It returns (ids', elemss) where ids' is an extension of ids
ballarin@14508
   742
   with identifiers generated for expr, and elemss is the list of
ballarin@14508
   743
   context elements generated from expr, decorated with additional
ballarin@14508
   744
   information (the identifiers?), including parameter names.
ballarin@14508
   745
   It appears that the identifier name is empty for external elements
ballarin@14508
   746
   (this is suggested by the implementation of activate_facts). *)
ballarin@14508
   747
ballarin@14508
   748
fun flatten _ (ids, Elem (Fixes fixes)) =
ballarin@14508
   749
      (ids, [(("", map (rpair None o #1) fixes), Ext (Fixes fixes))])
ballarin@14508
   750
  | flatten _ (ids, Elem elem) = (ids, [(("", []), Ext elem)])
ballarin@14508
   751
  | flatten (ctxt, prep_expr) (ids, Expr expr) =
ballarin@14508
   752
      apsnd (map (apsnd Int)) (flatten_expr ctxt (ids, prep_expr expr));
ballarin@14508
   753
wenzelm@12529
   754
local
wenzelm@12529
   755
wenzelm@12839
   756
local
wenzelm@12839
   757
wenzelm@12727
   758
fun declare_int_elem (ctxt, Fixes fixes) =
wenzelm@12575
   759
      (ctxt |> ProofContext.add_fixes (map (fn (x, T, mx) =>
wenzelm@12727
   760
        (x, apsome (Term.map_type_tfree (Type.param 0)) T, mx)) fixes), [])
wenzelm@12727
   761
  | declare_int_elem (ctxt, _) = (ctxt, []);
wenzelm@12529
   762
wenzelm@12529
   763
fun declare_ext_elem prep_fixes (ctxt, Fixes fixes) =
wenzelm@12575
   764
      (ctxt |> ProofContext.add_fixes (prep_fixes ctxt fixes), [])
wenzelm@12529
   765
  | declare_ext_elem _ (ctxt, Assumes asms) = (ctxt, map #2 asms)
wenzelm@12529
   766
  | declare_ext_elem _ (ctxt, Defines defs) = (ctxt, map (fn (_, (t, ps)) => [(t, (ps, []))]) defs)
wenzelm@12529
   767
  | declare_ext_elem _ (ctxt, Notes facts) = (ctxt, []);
wenzelm@12529
   768
wenzelm@12727
   769
fun declare_elems prep_fixes (ctxt, ((name, ps), elems)) =
wenzelm@12529
   770
  let val (ctxt', propps) =
wenzelm@12529
   771
    (case elems of
wenzelm@13308
   772
      Int es => foldl_map declare_int_elem (ctxt, es)
wenzelm@12546
   773
    | Ext e => foldl_map (declare_ext_elem prep_fixes) (ctxt, [e]))
wenzelm@12529
   774
    handle ProofContext.CONTEXT (msg, ctxt) => err_in_locale ctxt msg [(name, map fst ps)]
wenzelm@12727
   775
  in (ctxt', propps) end;
wenzelm@12727
   776
wenzelm@12839
   777
in
wenzelm@12839
   778
ballarin@14215
   779
(* CB: only called by prep_elemss. *)
ballarin@14215
   780
wenzelm@12727
   781
fun declare_elemss prep_fixes fixed_params raw_elemss ctxt =
wenzelm@12727
   782
  let
ballarin@14215
   783
    (* CB: fix of type bug of goal in target with context elements.
ballarin@14215
   784
       Parameters new in context elements must receive types that are
ballarin@14215
   785
       distinct from types of parameters in target (fixed_params).  *)
ballarin@14215
   786
    val ctxt_with_fixed =
ballarin@14215
   787
      ProofContext.declare_terms (map Free fixed_params) ctxt;
wenzelm@12727
   788
    val int_elemss =
wenzelm@12727
   789
      raw_elemss
wenzelm@12727
   790
      |> mapfilter (fn (id, Int es) => Some (id, es) | _ => None)
ballarin@14215
   791
      |> unify_elemss ctxt_with_fixed fixed_params;
wenzelm@12727
   792
    val (_, raw_elemss') =
wenzelm@12727
   793
      foldl_map (fn ((_, es) :: elemss, (id, Int _)) => (elemss, (id, Int es)) | x => x)
wenzelm@12727
   794
        (int_elemss, raw_elemss);
wenzelm@12727
   795
  in foldl_map (declare_elems prep_fixes) (ctxt, raw_elemss') end;
wenzelm@12529
   796
wenzelm@12839
   797
end;
wenzelm@12529
   798
wenzelm@12839
   799
local
wenzelm@12839
   800
ballarin@14508
   801
(* CB: following code (norm_term, abstract_term, abstract_thm, bind_def)
ballarin@14508
   802
   used in eval_text for defines elements. *)
ballarin@14508
   803
wenzelm@12839
   804
val norm_term = Envir.beta_norm oo Term.subst_atomic;
wenzelm@12839
   805
wenzelm@13336
   806
fun abstract_term eq =    (*assumes well-formedness according to ProofContext.cert_def*)
wenzelm@12839
   807
  let
wenzelm@12839
   808
    val body = Term.strip_all_body eq;
wenzelm@12839
   809
    val vars = map Free (Term.rename_wrt_term body (Term.strip_all_vars eq));
wenzelm@12839
   810
    val (lhs, rhs) = Logic.dest_equals (Term.subst_bounds (vars, body));
wenzelm@12839
   811
    val (f, xs) = Term.strip_comb lhs;
wenzelm@13336
   812
    val eq' = Term.list_abs_free (map Term.dest_Free xs, rhs);
wenzelm@13336
   813
  in (Term.dest_Free f, eq') end;
wenzelm@13336
   814
wenzelm@13336
   815
fun abstract_thm sign eq =
wenzelm@13336
   816
  Thm.assume (Thm.cterm_of sign eq) |> Drule.gen_all |> Drule.abs_def;
wenzelm@12502
   817
wenzelm@13336
   818
fun bind_def ctxt (name, ps) ((xs, env, ths), eq) =
wenzelm@12839
   819
  let
wenzelm@13336
   820
    val ((y, T), b) = abstract_term eq;
wenzelm@13308
   821
    val b' = norm_term env b;
wenzelm@13336
   822
    val th = abstract_thm (ProofContext.sign_of ctxt) eq;
wenzelm@13308
   823
    fun err msg = err_in_locale ctxt (msg ^ ": " ^ quote y) [(name, map fst ps)];
wenzelm@12839
   824
  in
wenzelm@13308
   825
    conditional (exists (equal y o #1) xs) (fn () =>
wenzelm@13308
   826
      err "Attempt to define previously specified variable");
wenzelm@13308
   827
    conditional (exists (fn (Free (y', _), _) => y = y' | _ => false) env) (fn () =>
wenzelm@13308
   828
      err "Attempt to redefine variable");
wenzelm@13336
   829
    (Term.add_frees (xs, b'), (Free (y, T), b') :: env, th :: ths)
wenzelm@12839
   830
  end;
wenzelm@12575
   831
wenzelm@13308
   832
fun eval_text _ _ _ (text, Fixes _) = text
wenzelm@13394
   833
  | eval_text _ _ is_ext ((((exts, exts'), (ints, ints')), (xs, env, defs)), Assumes asms) =
wenzelm@13394
   834
      let
wenzelm@13394
   835
        val ts = flat (map (map #1 o #2) asms);
wenzelm@13394
   836
        val ts' = map (norm_term env) ts;
wenzelm@13394
   837
        val spec' =
wenzelm@13394
   838
          if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
wenzelm@13394
   839
          else ((exts, exts'), (ints @ ts, ints' @ ts'));
wenzelm@13394
   840
      in (spec', (foldl Term.add_frees (xs, ts'), env, defs)) end
wenzelm@13308
   841
  | eval_text ctxt id _ ((spec, binds), Defines defs) =
wenzelm@13308
   842
      (spec, foldl (bind_def ctxt id) (binds, map (#1 o #2) defs))
wenzelm@13308
   843
  | eval_text _ _ _ (text, Notes _) = text;
wenzelm@13308
   844
wenzelm@13308
   845
fun closeup _ false elem = elem
wenzelm@13308
   846
  | closeup ctxt true elem =
wenzelm@12839
   847
      let
wenzelm@13308
   848
        fun close_frees t =
wenzelm@13308
   849
          let val frees = rev (filter_out (ProofContext.is_fixed ctxt o #1)
wenzelm@13308
   850
            (Term.add_frees ([], t)))
wenzelm@13308
   851
          in Term.list_all_free (frees, t) end;
wenzelm@13308
   852
wenzelm@13308
   853
        fun no_binds [] = []
wenzelm@13308
   854
          | no_binds _ =
wenzelm@13308
   855
              raise ProofContext.CONTEXT ("Illegal term bindings in locale element", ctxt);
wenzelm@13308
   856
      in
wenzelm@13308
   857
        (case elem of
wenzelm@13308
   858
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
wenzelm@13308
   859
            (a, map (fn (t, (ps, qs)) => (close_frees t, (no_binds ps, no_binds qs))) propps)))
wenzelm@13308
   860
        | Defines defs => Defines (defs |> map (fn (a, (t, ps)) =>
wenzelm@13308
   861
            (a, (close_frees (#2 (ProofContext.cert_def ctxt t)), no_binds ps))))
wenzelm@13308
   862
        | e => e)
wenzelm@13308
   863
      end;
wenzelm@12839
   864
wenzelm@12502
   865
wenzelm@12839
   866
fun finish_ext_elem parms _ (Fixes fixes, _) = Fixes (map (fn (x, _, mx) =>
wenzelm@12727
   867
      (x, assoc_string (parms, x), mx)) fixes)
wenzelm@12839
   868
  | finish_ext_elem _ close (Assumes asms, propp) =
wenzelm@12839
   869
      close (Assumes (map #1 asms ~~ propp))
wenzelm@12839
   870
  | finish_ext_elem _ close (Defines defs, propp) =
wenzelm@12727
   871
      close (Defines (map #1 defs ~~ map (fn [(t, (ps, []))] => (t, ps)) propp))
wenzelm@12839
   872
  | finish_ext_elem _ _ (Notes facts, _) = Notes facts;
wenzelm@12839
   873
wenzelm@12839
   874
fun finish_parms parms ((name, ps), elems) =
wenzelm@12839
   875
  ((name, map (fn (x, _) => (x, assoc (parms, x))) ps), elems);
wenzelm@12839
   876
wenzelm@13375
   877
fun finish_elems ctxt parms _ (text, ((id, Int e), _)) =
wenzelm@12839
   878
      let
wenzelm@13308
   879
        val [(_, es)] = unify_elemss ctxt parms [(id, e)];
wenzelm@13308
   880
        val text' = foldl (eval_text ctxt id false) (text, es);
wenzelm@13308
   881
      in (text', (id, map Int es)) end
wenzelm@13375
   882
  | finish_elems ctxt parms do_close (text, ((id, Ext e), [propp])) =
wenzelm@13308
   883
      let
wenzelm@13308
   884
        val e' = finish_ext_elem parms (closeup ctxt do_close) (e, propp);
wenzelm@13375
   885
        val text' = eval_text ctxt id true (text, e');
wenzelm@13308
   886
      in (text', (id, [Ext e'])) end;
wenzelm@12839
   887
wenzelm@12839
   888
in
wenzelm@12510
   889
wenzelm@13375
   890
fun finish_elemss ctxt parms do_close =
wenzelm@13375
   891
  foldl_map (apsnd (finish_parms parms) o finish_elems ctxt parms do_close);
wenzelm@12839
   892
wenzelm@12839
   893
end;
wenzelm@12839
   894
wenzelm@13375
   895
fun prep_elemss prep_fixes prepp do_close context fixed_params raw_elemss raw_concl =
wenzelm@12529
   896
  let
ballarin@14508
   897
    (* CB: raw_elemss are list of pairs consisting of identifiers and
ballarin@14508
   898
       context elements, the latter marked as internal or external. *)
wenzelm@12727
   899
    val (raw_ctxt, raw_proppss) = declare_elemss prep_fixes fixed_params raw_elemss context;
ballarin@14508
   900
    (* CB: raw_ctxt is context with additional fixed variables derived from
ballarin@14508
   901
       the fixes elements in raw_elemss,
ballarin@14508
   902
       raw_proppss contains assumptions and definitions from the
ballarin@14508
   903
       (external?) elements in raw_elemss. *)
wenzelm@12529
   904
    val raw_propps = map flat raw_proppss;
wenzelm@12529
   905
    val raw_propp = flat raw_propps;
wenzelm@12529
   906
    val (ctxt, all_propp) =
wenzelm@12529
   907
      prepp (ProofContext.declare_terms (map Free fixed_params) raw_ctxt, raw_concl @ raw_propp);
ballarin@14508
   908
    (* CB: read/cert entire proposition (conclusion and premises from
ballarin@14508
   909
       the context elements). *)
wenzelm@12529
   910
    val ctxt = ProofContext.declare_terms (flat (map (map fst) all_propp)) ctxt;
ballarin@14508
   911
    (* CB: it appears that terms declared in the propositions are added
ballarin@14508
   912
       to the context here. *)
wenzelm@12502
   913
wenzelm@12529
   914
    val all_propp' = map2 (op ~~)
wenzelm@12529
   915
      (#1 (#2 (ProofContext.bind_propp_schematic_i (ctxt, all_propp))), map (map snd) all_propp);
nipkow@13629
   916
    val (concl, propp) = splitAt(length raw_concl, all_propp');
wenzelm@12529
   917
    val propps = unflat raw_propps propp;
wenzelm@12839
   918
    val proppss = map (uncurry unflat) (raw_proppss ~~ propps);
wenzelm@12502
   919
wenzelm@12529
   920
    val xs = map #1 (params_of raw_elemss);
wenzelm@12727
   921
    val typing = unify_frozen ctxt 0
wenzelm@12529
   922
      (map (ProofContext.default_type raw_ctxt) xs)
wenzelm@12529
   923
      (map (ProofContext.default_type ctxt) xs);
wenzelm@12529
   924
    val parms = param_types (xs ~~ typing);
ballarin@14508
   925
    (* CB: parms are the parameters from raw_elemss, with correct typing. *)
wenzelm@12273
   926
ballarin@14508
   927
    (* CB: extract information from assumes and defines elements
ballarin@14508
   928
       (fixes and notes in raw_elemss don't have an effect on text and elemss),
ballarin@14508
   929
       compute final form of context elements. *)
wenzelm@13394
   930
    val (text, elemss) = finish_elemss ctxt parms do_close
wenzelm@13394
   931
      (((([], []), ([], [])), ([], [], [])), raw_elemss ~~ proppss);
ballarin@14508
   932
    (* CB: text has the following structure:
ballarin@14508
   933
           (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@14508
   934
       where
ballarin@14508
   935
         exts: external assumptions (terms in external assumes elements)
ballarin@14508
   936
         exts': dito, normalised wrt. env
ballarin@14508
   937
         ints: internal assumptions (terms in internal assumes elements)
ballarin@14508
   938
         ints': dito, normalised wrt. env
ballarin@14508
   939
         xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@14508
   940
           this includes parameters except defined parameters
ballarin@14508
   941
         env: list of term pairs encoding substitutions, where the first term
ballarin@14508
   942
           is a free variable; substitutions represent defines elements and
ballarin@14508
   943
           the rhs is normalised wrt. the previous env
ballarin@14508
   944
         defs: theorems representing the substitutions from defines elements
ballarin@14508
   945
           (thms are normalised wrt. env).
ballarin@14508
   946
       elemss is an updated version of raw_elemss:
ballarin@14508
   947
         - type info added to Fixes
ballarin@14508
   948
         - axiom and definition statement replaced by corresponding one
ballarin@14508
   949
           from proppss in Assumes and Defines
ballarin@14508
   950
         - Facts unchanged
ballarin@14508
   951
       *)
wenzelm@13308
   952
  in ((parms, elemss, concl), text) end;
wenzelm@12502
   953
wenzelm@12502
   954
in
wenzelm@12502
   955
wenzelm@12529
   956
fun read_elemss x = prep_elemss read_fixes ProofContext.read_propp_schematic x;
wenzelm@12529
   957
fun cert_elemss x = prep_elemss cert_fixes ProofContext.cert_propp_schematic x;
wenzelm@12529
   958
wenzelm@12529
   959
end;
wenzelm@12529
   960
wenzelm@12529
   961
wenzelm@12529
   962
(* facts *)
wenzelm@12529
   963
wenzelm@12529
   964
local
wenzelm@12529
   965
wenzelm@12529
   966
fun prep_name ctxt (name, atts) =
ballarin@14508
   967
  (* CB: reject qualified names in locale declarations *)
wenzelm@12529
   968
  if NameSpace.is_qualified name then
wenzelm@12529
   969
    raise ProofContext.CONTEXT ("Illegal qualified name: " ^ quote name, ctxt)
wenzelm@12529
   970
  else (name, atts);
wenzelm@12529
   971
wenzelm@13375
   972
fun prep_facts _ _ (Int elem) = elem
wenzelm@13375
   973
  | prep_facts _ _ (Ext (Fixes fixes)) = Fixes fixes
wenzelm@13375
   974
  | prep_facts _ ctxt (Ext (Assumes asms)) = Assumes (map (apfst (prep_name ctxt)) asms)
wenzelm@13375
   975
  | prep_facts _ ctxt (Ext (Defines defs)) = Defines (map (apfst (prep_name ctxt)) defs)
wenzelm@13375
   976
  | prep_facts get ctxt (Ext (Notes facts)) = Notes (facts |> map (fn (a, bs) =>
wenzelm@13375
   977
      (prep_name ctxt a, map (apfst (get ctxt)) bs)));
wenzelm@12529
   978
wenzelm@12529
   979
in
wenzelm@12529
   980
wenzelm@12529
   981
fun get_facts x = prep_facts ProofContext.get_thms x;
wenzelm@12529
   982
fun get_facts_i x = prep_facts (K I) x;
wenzelm@12529
   983
wenzelm@12529
   984
end;
wenzelm@12529
   985
wenzelm@12529
   986
wenzelm@12546
   987
(* full context statements: import + elements + conclusion *)
wenzelm@12529
   988
wenzelm@12529
   989
local
wenzelm@12529
   990
wenzelm@12529
   991
fun prep_context_statement prep_expr prep_elemss prep_facts
wenzelm@13399
   992
    do_close axioms fixed_params import elements raw_concl context =
wenzelm@12529
   993
  let
wenzelm@12529
   994
    val sign = ProofContext.sign_of context;
wenzelm@13375
   995
ballarin@14508
   996
    val (import_ids, raw_import_elemss) = flatten (context, prep_expr sign) ([], Expr import);
ballarin@14215
   997
    (* CB: normalise "includes" among elements *)
ballarin@14508
   998
    val raw_elemss = flat (#2 ((foldl_map (flatten (context, prep_expr sign))
ballarin@14508
   999
      (import_ids, elements))));
ballarin@14508
  1000
    (* CB: raw_import_elemss @ raw_elemss is the normalised list of
ballarin@14508
  1001
       context elements obtained from import and elements. *)
wenzelm@13375
  1002
    val ((parms, all_elemss, concl), (spec, (_, _, defs))) = prep_elemss do_close
wenzelm@13336
  1003
      context fixed_params (raw_import_elemss @ raw_elemss) raw_concl;
nipkow@13629
  1004
    val (ps,qs) = splitAt(length raw_import_elemss, all_elemss)
wenzelm@13420
  1005
    val ((import_ctxt, axioms'), (import_elemss, _)) =
nipkow@13629
  1006
      activate_facts prep_facts ((context, axioms), ps);
ballarin@14215
  1007
wenzelm@13420
  1008
    val ((ctxt, _), (elemss, _)) =
nipkow@13629
  1009
      activate_facts prep_facts ((import_ctxt, axioms'), qs);
wenzelm@12834
  1010
  in
wenzelm@13420
  1011
    ((((import_ctxt, import_elemss), (ctxt, elemss)), (parms, spec, defs)), concl)
wenzelm@12834
  1012
  end;
wenzelm@12529
  1013
wenzelm@12529
  1014
val gen_context = prep_context_statement intern_expr read_elemss get_facts;
wenzelm@12529
  1015
val gen_context_i = prep_context_statement (K I) cert_elemss get_facts_i;
wenzelm@12529
  1016
wenzelm@12529
  1017
fun gen_statement prep_locale prep_ctxt raw_locale elems concl ctxt =
wenzelm@12529
  1018
  let
wenzelm@12529
  1019
    val thy = ProofContext.theory_of ctxt;
wenzelm@12529
  1020
    val locale = apsome (prep_locale (Theory.sign_of thy)) raw_locale;
wenzelm@13415
  1021
    val ((view_statement, view_axioms), fixed_params, import) =
ballarin@14508
  1022
(* CB: view_axioms are xxx.axioms of locale xxx *)
wenzelm@13415
  1023
      (case locale of None => (([], []), [], empty)
wenzelm@13399
  1024
      | Some name =>
wenzelm@13420
  1025
          let val {view, params = (ps, _), ...} = the_locale thy name
wenzelm@13420
  1026
          in (view, param_types ps, Locale name) end);
wenzelm@12730
  1027
    val ((((locale_ctxt, _), (elems_ctxt, _)), _), concl') =
wenzelm@13415
  1028
      prep_ctxt false view_axioms fixed_params import elems concl ctxt;
wenzelm@13415
  1029
  in (locale, view_statement, locale_ctxt, elems_ctxt, concl') end;
wenzelm@13399
  1030
wenzelm@12529
  1031
in
wenzelm@12529
  1032
ballarin@14508
  1033
(* CB: arguments are: x->import, y->body (elements), z->context *)
wenzelm@13399
  1034
fun read_context x y z = #1 (gen_context true [] [] x y [] z);
wenzelm@13399
  1035
fun cert_context x y z = #1 (gen_context_i true [] [] x y [] z);
ballarin@14215
  1036
wenzelm@12529
  1037
val read_context_statement = gen_statement intern gen_context;
wenzelm@12529
  1038
val cert_context_statement = gen_statement (K I) gen_context_i;
wenzelm@12502
  1039
wenzelm@12502
  1040
end;
wenzelm@11896
  1041
wenzelm@11896
  1042
ballarin@14508
  1043
(** CB: experimental instantiation mechanism **)
ballarin@14508
  1044
ballarin@14528
  1045
fun instantiate loc_name (prfx, attribs) raw_inst ctxt =
ballarin@14508
  1046
  let
ballarin@14508
  1047
    val thy = ProofContext.theory_of ctxt;
ballarin@14508
  1048
    val sign = Theory.sign_of thy;
ballarin@14508
  1049
    val tsig = Sign.tsig_of sign;
ballarin@14508
  1050
    val cert = cterm_of sign;
ballarin@14508
  1051
ballarin@14508
  1052
    (** process the locale **)
ballarin@14508
  1053
ballarin@14508
  1054
    val {view = (_, axioms), params = (ps, _), ...} =
ballarin@14508
  1055
      the_locale thy (intern sign loc_name);
ballarin@14508
  1056
    val fixed_params = param_types ps;
ballarin@14528
  1057
    val init = ProofContext.init thy;
ballarin@14508
  1058
    val (ids, raw_elemss) =
ballarin@14528
  1059
          flatten (init, intern_expr sign) ([], Expr (Locale loc_name));
ballarin@14508
  1060
    val ((parms, all_elemss, concl),
ballarin@14508
  1061
         (spec as (_, (ints, _)), (xs, env, defs))) =
ballarin@14528
  1062
      read_elemss false (* do_close *) init
ballarin@14508
  1063
        fixed_params (* could also put [] here??? *) raw_elemss
ballarin@14508
  1064
        [] (* concl *);
ballarin@14508
  1065
ballarin@14508
  1066
    (** analyse the instantiation theorem inst **)
ballarin@14508
  1067
ballarin@14508
  1068
    val inst = case raw_inst of
ballarin@14508
  1069
        None => if null ints
ballarin@14508
  1070
	  then None
ballarin@14508
  1071
	  else error "Locale has assumptions but no chained fact was found"
ballarin@14508
  1072
      | Some [] => if null ints
ballarin@14508
  1073
	  then None
ballarin@14508
  1074
	  else error "Locale has assumptions but no chained fact was found"
ballarin@14508
  1075
      | Some [thm] => if null ints
ballarin@14508
  1076
	  then (warning "Locale has no assumptions: fact ignored"; None)
ballarin@14508
  1077
	  else Some thm
ballarin@14508
  1078
      | Some _ => error "Multiple facts are not allowed";
ballarin@14508
  1079
ballarin@14508
  1080
    val args = case inst of
ballarin@14508
  1081
            None => []
ballarin@14508
  1082
          | Some thm => thm |> prop_of |> ObjectLogic.drop_judgment sign
ballarin@14528
  1083
              |> Term.strip_comb
ballarin@14528
  1084
              |>> (fn t as (Const (s, _)) => if (intern sign loc_name = s)
ballarin@14528
  1085
                        then t
ballarin@14528
  1086
                        else error ("Constant " ^ quote loc_name ^
ballarin@14528
  1087
                          " expected but constant " ^ quote s ^ " was found")
ballarin@14528
  1088
                    | t => error ("Constant " ^ quote loc_name ^ " expected \
ballarin@14528
  1089
                          \but term " ^ quote (Sign.string_of_term sign t) ^
ballarin@14528
  1090
                          " was found"))
ballarin@14528
  1091
              |> snd;
ballarin@14508
  1092
    val cargs = map cert args;
ballarin@14508
  1093
ballarin@14508
  1094
    (* process parameters: match their types with those of arguments *)
ballarin@14508
  1095
ballarin@14508
  1096
    val def_names = map (fn (Free (s, _), _) => s) env;
ballarin@14508
  1097
    val (defined, assumed) = partition
ballarin@14508
  1098
          (fn (s, _) => s mem def_names) fixed_params;
ballarin@14508
  1099
    val cassumed = map (cert o Free) assumed;
ballarin@14508
  1100
    val cdefined = map (cert o Free) defined;
ballarin@14508
  1101
ballarin@14508
  1102
    val param_types = map snd assumed;
ballarin@14508
  1103
    val v_param_types = map Type.varifyT param_types;
ballarin@14508
  1104
    val arg_types = map Term.fastype_of args;
ballarin@14508
  1105
    val Tenv = foldl (Type.typ_match tsig)
ballarin@14508
  1106
          (Vartab.empty, v_param_types ~~ arg_types)
ballarin@14528
  1107
          handle Library.LIST "~~" => error "Number of parameters does not \
ballarin@14528
  1108
            \match number of arguments of chained fact";
ballarin@14508
  1109
    (* get their sorts *)
ballarin@14508
  1110
    val tfrees = foldr Term.add_typ_tfrees (param_types, []);
ballarin@14508
  1111
    val Tenv' = map
ballarin@14508
  1112
          (fn ((a, i), T) => ((a, the (assoc_string (tfrees, a))), T))
ballarin@14508
  1113
          (Vartab.dest Tenv);
ballarin@14508
  1114
ballarin@14508
  1115
    (* process (internal) elements *)
ballarin@14508
  1116
ballarin@14508
  1117
    fun inst_type [] T = T
ballarin@14508
  1118
      | inst_type env T =
ballarin@14508
  1119
          Term.map_type_tfree (fn v => if_none (assoc (env, v)) (TFree v)) T;
ballarin@14508
  1120
ballarin@14508
  1121
    fun inst_term [] t = t
ballarin@14508
  1122
      | inst_term env t = Term.map_term_types (inst_type env) t;
ballarin@14508
  1123
ballarin@14508
  1124
    (* parameters with argument types *)
ballarin@14508
  1125
ballarin@14508
  1126
    val cparams' = map (cterm_of sign o inst_term Tenv' o term_of) cassumed;
ballarin@14508
  1127
    val cdefined' = map (cert o inst_term Tenv' o term_of) cdefined;
ballarin@14508
  1128
    val cdefining = map (cert o inst_term Tenv' o snd) env;
ballarin@14508
  1129
ballarin@14508
  1130
    fun inst_thm _ [] th = th
ballarin@14508
  1131
      | inst_thm ctxt Tenv th =
ballarin@14508
  1132
	  let
ballarin@14508
  1133
	    val sign = ProofContext.sign_of ctxt;
ballarin@14508
  1134
	    val cert = Thm.cterm_of sign;
ballarin@14508
  1135
	    val certT = Thm.ctyp_of sign;
ballarin@14508
  1136
	    val {hyps, prop, maxidx, ...} = Thm.rep_thm th;
ballarin@14508
  1137
	    val tfrees = foldr Term.add_term_tfree_names (prop :: hyps, []);
ballarin@14508
  1138
	    val Tenv' = filter (fn ((a, _), _) => a mem_string tfrees) Tenv;
ballarin@14508
  1139
	  in
ballarin@14508
  1140
	    if null Tenv' then th
ballarin@14508
  1141
	    else
ballarin@14508
  1142
	      th
ballarin@14508
  1143
	      |> Drule.implies_intr_list (map cert hyps)
ballarin@14508
  1144
	      |> Drule.tvars_intr_list (map (#1 o #1) Tenv')
ballarin@14508
  1145
	      |> (fn (th', al) => th' |>
ballarin@14508
  1146
		Thm.instantiate ((map (fn ((a, _), T) =>
ballarin@14508
  1147
                  (the (assoc (al, a)), certT T)) Tenv'), []))
ballarin@14508
  1148
	      |> (fn th'' => Drule.implies_elim_list th''
ballarin@14508
  1149
		  (map (Thm.assume o cert o inst_term Tenv') hyps))
ballarin@14508
  1150
	  end;
ballarin@14508
  1151
ballarin@14508
  1152
    fun inst_thm' thm =
ballarin@14508
  1153
      let
ballarin@14508
  1154
        (* not all axs are normally applicable *)
ballarin@14508
  1155
        val hyps = #hyps (rep_thm thm);
ballarin@14508
  1156
        val ass = map (fn ax => (prop_of ax, ax)) axioms;
ballarin@14508
  1157
        val axs' = foldl (fn (axs, hyp) => 
ballarin@14528
  1158
              (case gen_assoc (op aconv) (ass, hyp) of None => axs
ballarin@14508
  1159
                 | Some ax => axs @ [ax])) ([], hyps);
ballarin@14508
  1160
        val thm' = Drule.satisfy_hyps axs' thm;
ballarin@14508
  1161
        (* instantiate types *)
ballarin@14508
  1162
        val thm'' = inst_thm ctxt Tenv' thm';
ballarin@14508
  1163
        (* substitute arguments and discharge hypotheses *)
ballarin@14508
  1164
        val thm''' = case inst of
ballarin@14508
  1165
                None => thm''
ballarin@14508
  1166
              | Some inst_thm => let
ballarin@14508
  1167
		    val hyps = #hyps (rep_thm thm'');
ballarin@14508
  1168
		    val th = thm'' |> implies_intr_hyps
ballarin@14508
  1169
		      |> forall_intr_list (cparams' @ cdefined')
ballarin@14508
  1170
		      |> forall_elim_list (cargs @ cdefining)
ballarin@14508
  1171
		    (* th has premises of the form either inst_thm or x==x *)
ballarin@14508
  1172
		    fun mk hyp = if Logic.is_equals hyp
ballarin@14508
  1173
			  then hyp |> Logic.dest_equals |> snd |> cert
ballarin@14508
  1174
				 |> reflexive
ballarin@14508
  1175
			  else inst_thm
ballarin@14508
  1176
                  in implies_elim_list th (map mk hyps)
ballarin@14508
  1177
                  end;
ballarin@14508
  1178
      in thm''' end;
ballarin@14508
  1179
ballarin@14528
  1180
    val prefix_fact =
ballarin@14528
  1181
      if prfx = "" then I
ballarin@14528
  1182
      else (fn "" => ""
ballarin@14528
  1183
             | s => NameSpace.append prfx s);
ballarin@14528
  1184
ballarin@14508
  1185
    fun inst_elem (ctxt, (Ext _)) = ctxt
ballarin@14508
  1186
      | inst_elem (ctxt, (Int (Notes facts))) =
ballarin@14508
  1187
              (* instantiate fact *)
ballarin@14508
  1188
          let val facts' =
ballarin@14528
  1189
                map (apsnd (map (apfst (map inst_thm')))) facts
ballarin@14528
  1190
		handle THM (msg, n, thms) => error ("Exception THM " ^
ballarin@14528
  1191
		  string_of_int n ^ " raised\n" ^
ballarin@14528
  1192
		  "Note: instantiate does not support old-style locales \
ballarin@14528
  1193
                  \declared with (open)\n" ^ msg ^ "\n" ^
ballarin@14528
  1194
		  cat_lines (map string_of_thm thms))
ballarin@14508
  1195
              (* rename fact *)
ballarin@14528
  1196
              val facts'' = map (apfst (apfst prefix_fact)) facts'
ballarin@14528
  1197
              (* add attributes *)
ballarin@14528
  1198
              val facts''' = map (apfst (apsnd (fn atts => atts @ attribs))) facts''
wenzelm@14564
  1199
          in fst (ProofContext.note_thmss_i facts''' ctxt)
ballarin@14508
  1200
          end
ballarin@14508
  1201
      | inst_elem (ctxt, (Int _)) = ctxt;
ballarin@14508
  1202
ballarin@14508
  1203
    fun inst_elems (ctxt, (id, elems)) = foldl inst_elem (ctxt, elems);
ballarin@14508
  1204
ballarin@14508
  1205
    fun inst_elemss ctxt elemss = foldl inst_elems (ctxt, elemss);
ballarin@14508
  1206
ballarin@14508
  1207
    (* main part *)
ballarin@14508
  1208
ballarin@14508
  1209
    val ctxt' = ProofContext.qualified true ctxt;
ballarin@14508
  1210
  in ProofContext.restore_qualified ctxt (inst_elemss ctxt' all_elemss)
ballarin@14508
  1211
  end;
ballarin@14508
  1212
wenzelm@11896
  1213
wenzelm@13336
  1214
(** define locales **)
wenzelm@13336
  1215
wenzelm@13336
  1216
(* print locale *)
wenzelm@12070
  1217
wenzelm@12758
  1218
fun print_locale thy import body =
wenzelm@12070
  1219
  let
wenzelm@12289
  1220
    val thy_ctxt = ProofContext.init thy;
wenzelm@13420
  1221
    val (((_, import_elemss), (ctxt, elemss)), _) = read_context import body thy_ctxt;
wenzelm@13375
  1222
    val all_elems = flat (map #2 (import_elemss @ elemss));
wenzelm@12070
  1223
wenzelm@12307
  1224
    val prt_typ = Pretty.quote o ProofContext.pretty_typ ctxt;
wenzelm@12307
  1225
    val prt_term = Pretty.quote o ProofContext.pretty_term ctxt;
wenzelm@12307
  1226
    val prt_thm = Pretty.quote o ProofContext.pretty_thm ctxt;
wenzelm@12070
  1227
wenzelm@12070
  1228
    fun prt_syn syn =
wenzelm@12070
  1229
      let val s = (case syn of None => "(structure)" | Some mx => Syntax.string_of_mixfix mx)
wenzelm@12575
  1230
      in if s = "" then [] else [Pretty.brk 2, Pretty.str s] end;
wenzelm@12070
  1231
    fun prt_fix (x, Some T, syn) = Pretty.block (Pretty.str (x ^ " ::") :: Pretty.brk 1 ::
wenzelm@12070
  1232
          prt_typ T :: Pretty.brk 1 :: prt_syn syn)
wenzelm@12070
  1233
      | prt_fix (x, None, syn) = Pretty.block (Pretty.str x :: Pretty.brk 1 :: prt_syn syn);
wenzelm@12070
  1234
wenzelm@12307
  1235
    fun prt_name "" = [Pretty.brk 1]
wenzelm@12307
  1236
      | prt_name name = [Pretty.str (ProofContext.cond_extern ctxt name ^ ":"), Pretty.brk 1];
wenzelm@12307
  1237
    fun prt_asm ((a, _), ts) = Pretty.block (prt_name a @ Pretty.breaks (map (prt_term o fst) ts));
wenzelm@12307
  1238
    fun prt_def ((a, _), (t, _)) = Pretty.block (prt_name a @ [prt_term t]);
wenzelm@12307
  1239
    fun prt_fact ((a, _), ths) = Pretty.block
wenzelm@12307
  1240
      (prt_name a @ Pretty.breaks (map prt_thm (flat (map fst ths))));
wenzelm@12070
  1241
wenzelm@12289
  1242
    fun items _ [] = []
wenzelm@12289
  1243
      | items prfx (x :: xs) = Pretty.block [Pretty.str prfx, Pretty.brk 1, x] :: items "  and" xs;
wenzelm@12289
  1244
    fun prt_elem (Fixes fixes) = items "fixes" (map prt_fix fixes)
wenzelm@12289
  1245
      | prt_elem (Assumes asms) = items "assumes" (map prt_asm asms)
wenzelm@12289
  1246
      | prt_elem (Defines defs) = items "defines" (map prt_def defs)
wenzelm@12289
  1247
      | prt_elem (Notes facts) = items "notes" (map prt_fact facts);
wenzelm@12277
  1248
  in
wenzelm@13336
  1249
    Pretty.big_list "context elements:" (map (Pretty.chunks o prt_elem) all_elems)
wenzelm@13336
  1250
    |> Pretty.writeln
wenzelm@12277
  1251
  end;
wenzelm@12070
  1252
wenzelm@12070
  1253
wenzelm@12730
  1254
(* store results *)
wenzelm@11896
  1255
wenzelm@12706
  1256
local
wenzelm@12706
  1257
wenzelm@12702
  1258
fun hide_bound_names names thy =
wenzelm@12702
  1259
  thy |> PureThy.hide_thms false
wenzelm@12702
  1260
    (map (Sign.full_name (Theory.sign_of thy)) (filter_out (equal "") names));
wenzelm@12702
  1261
wenzelm@12958
  1262
in
wenzelm@12958
  1263
wenzelm@14564
  1264
fun note_thmss_qualified kind name args thy =
wenzelm@12706
  1265
  thy
wenzelm@13375
  1266
  |> Theory.add_path (Sign.base_name name)
wenzelm@14564
  1267
  |> PureThy.note_thmss_i (Drule.kind kind) args
wenzelm@12706
  1268
  |>> hide_bound_names (map (#1 o #1) args)
wenzelm@12706
  1269
  |>> Theory.parent_path;
wenzelm@12706
  1270
wenzelm@14564
  1271
fun smart_note_thmss kind None = PureThy.note_thmss_i (Drule.kind kind)
wenzelm@14564
  1272
  | smart_note_thmss kind (Some (loc, _)) = note_thmss_qualified kind loc;
ballarin@14508
  1273
  (* CB: only used in Proof.finish_global. *)
wenzelm@12958
  1274
wenzelm@12958
  1275
end;
wenzelm@12958
  1276
wenzelm@12958
  1277
local
wenzelm@12958
  1278
wenzelm@12958
  1279
fun put_facts loc args thy =
wenzelm@12958
  1280
  let
wenzelm@13399
  1281
    val {view, import, elems, params} = the_locale thy loc;
wenzelm@12958
  1282
    val note = Notes (map (fn ((a, more_atts), th_atts) =>
wenzelm@12958
  1283
      ((a, more_atts), map (apfst (map (curry Thm.name_thm a))) th_atts)) args);
wenzelm@13399
  1284
  in thy |> put_locale loc (make_locale view import (elems @ [(note, stamp ())]) params) end;
wenzelm@12958
  1285
wenzelm@14564
  1286
fun gen_note_thmss prep_locale get_thms kind raw_loc raw_args thy =
wenzelm@12706
  1287
  let
wenzelm@12706
  1288
    val thy_ctxt = ProofContext.init thy;
wenzelm@12706
  1289
    val loc = prep_locale (Theory.sign_of thy) raw_loc;
wenzelm@13399
  1290
    val (_, view, loc_ctxt, _, _) = cert_context_statement (Some loc) [] [] thy_ctxt;
wenzelm@12706
  1291
    val args = map (apsnd (map (apfst (get_thms loc_ctxt)))) raw_args;
wenzelm@13399
  1292
    val export = ProofContext.export_standard view loc_ctxt thy_ctxt;
wenzelm@14564
  1293
    val results = map (map export o #2) (#2 (ProofContext.note_thmss_i args loc_ctxt));
wenzelm@12706
  1294
    val args' = map (rpair [] o #1 o #1) args ~~ map (single o Thm.no_attributes) results;
wenzelm@12706
  1295
  in
wenzelm@12706
  1296
    thy
wenzelm@12706
  1297
    |> put_facts loc args
wenzelm@14564
  1298
    |> note_thmss_qualified kind loc args'
wenzelm@12706
  1299
  end;
wenzelm@12706
  1300
wenzelm@12706
  1301
in
wenzelm@12706
  1302
wenzelm@14564
  1303
val note_thmss = gen_note_thmss intern ProofContext.get_thms;
wenzelm@14564
  1304
val note_thmss_i = gen_note_thmss (K I) (K I);
wenzelm@14564
  1305
  (* CB: note_thmss(_i) is the base for the Isar commands
ballarin@14508
  1306
     "theorems (in loc)" and "declare (in loc)". *)
wenzelm@12711
  1307
wenzelm@13336
  1308
fun add_thmss loc args (thy, ctxt) =
wenzelm@12958
  1309
  let
wenzelm@12958
  1310
    val args' = map (fn ((a, ths), atts) => ((a, atts), [(ths, [])])) args;
wenzelm@13336
  1311
    val thy' = put_facts loc args' thy;
wenzelm@13415
  1312
    val {view = (_, view_axioms), ...} = the_locale thy loc;
wenzelm@13399
  1313
    val ((ctxt', _), (_, facts')) =
wenzelm@13420
  1314
      activate_facts (K I) ((ctxt, view_axioms), [(("", []), [Notes args'])]);
wenzelm@13420
  1315
  in ((thy', ctxt'), facts') end;
ballarin@14508
  1316
  (* CB: only used in Proof.finish_global. *)
wenzelm@12702
  1317
wenzelm@12706
  1318
end;
wenzelm@12063
  1319
wenzelm@11896
  1320
wenzelm@13336
  1321
(* predicate text *)
wenzelm@13336
  1322
wenzelm@13375
  1323
local
wenzelm@13375
  1324
wenzelm@13375
  1325
val introN = "intro";
wenzelm@13375
  1326
wenzelm@13375
  1327
fun atomize_spec sign ts =
wenzelm@13375
  1328
  let
wenzelm@13375
  1329
    val t = Library.foldr1 Logic.mk_conjunction ts;
wenzelm@13375
  1330
    val body = ObjectLogic.atomize_term sign t;
wenzelm@13375
  1331
    val bodyT = Term.fastype_of body;
wenzelm@13375
  1332
  in
wenzelm@13375
  1333
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of sign t))
wenzelm@13375
  1334
    else (body, bodyT, ObjectLogic.atomize_rule sign (Thm.cterm_of sign t))
wenzelm@13375
  1335
  end;
wenzelm@13375
  1336
wenzelm@13394
  1337
fun aprop_tr' n c = (c, fn args =>
wenzelm@13394
  1338
  if length args = n then Syntax.const "_aprop" $ Term.list_comb (Syntax.free c, args)
wenzelm@13394
  1339
  else raise Match);
wenzelm@13336
  1340
wenzelm@13420
  1341
fun def_pred bname parms defs ts norm_ts thy =
wenzelm@13375
  1342
  let
wenzelm@13375
  1343
    val sign = Theory.sign_of thy;
wenzelm@13375
  1344
    val name = Sign.full_name sign bname;
wenzelm@13375
  1345
wenzelm@13420
  1346
    val (body, bodyT, body_eq) = atomize_spec sign norm_ts;
wenzelm@13394
  1347
    val env = Term.add_term_free_names (body, []);
wenzelm@13394
  1348
    val xs = filter (fn (x, _) => x mem_string env) parms;
wenzelm@13394
  1349
    val Ts = map #2 xs;
wenzelm@13394
  1350
    val extraTs = (Term.term_tfrees body \\ foldr Term.add_typ_tfrees (Ts, []))
wenzelm@13394
  1351
      |> Library.sort_wrt #1 |> map TFree;
wenzelm@13399
  1352
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
wenzelm@13336
  1353
wenzelm@13394
  1354
    val args = map Logic.mk_type extraTs @ map Free xs;
wenzelm@13394
  1355
    val head = Term.list_comb (Const (name, predT), args);
wenzelm@13375
  1356
    val statement = ObjectLogic.assert_propT sign head;
wenzelm@13375
  1357
wenzelm@13375
  1358
    val (defs_thy, [pred_def]) =
wenzelm@13375
  1359
      thy
wenzelm@13394
  1360
      |> (if bodyT <> propT then I else
wenzelm@13394
  1361
        Theory.add_trfuns ([], [], map (aprop_tr' (length args)) (NameSpace.accesses' name), []))
wenzelm@13375
  1362
      |> Theory.add_consts_i [(bname, predT, Syntax.NoSyn)]
wenzelm@13375
  1363
      |> PureThy.add_defs_i false [((Thm.def_name bname, Logic.mk_equals (head, body)), [])];
wenzelm@13394
  1364
wenzelm@13375
  1365
    val defs_sign = Theory.sign_of defs_thy;
wenzelm@13375
  1366
    val cert = Thm.cterm_of defs_sign;
wenzelm@13375
  1367
wenzelm@13420
  1368
    val intro = Tactic.prove_standard defs_sign [] norm_ts statement (fn _ =>
wenzelm@13375
  1369
      Tactic.rewrite_goals_tac [pred_def] THEN
wenzelm@13375
  1370
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
wenzelm@13420
  1371
      Tactic.compose_tac (false, Drule.conj_intr_list (map (Thm.assume o cert) norm_ts), 0) 1);
wenzelm@13375
  1372
wenzelm@13375
  1373
    val conjuncts =
wenzelm@13399
  1374
      Drule.equal_elim_rule1 OF [Thm.symmetric body_eq,
wenzelm@13399
  1375
        Tactic.rewrite_rule [pred_def] (Thm.assume (cert statement))]
wenzelm@13375
  1376
      |> Drule.conj_elim_precise (length ts);
wenzelm@13394
  1377
    val axioms = (ts ~~ conjuncts) |> map (fn (t, ax) =>
wenzelm@13375
  1378
      Tactic.prove defs_sign [] [] t (fn _ =>
wenzelm@13375
  1379
        Tactic.rewrite_goals_tac defs THEN
wenzelm@13375
  1380
        Tactic.compose_tac (false, ax, 0) 1));
wenzelm@13394
  1381
  in (defs_thy, (statement, intro, axioms)) end;
wenzelm@13375
  1382
wenzelm@13394
  1383
fun change_elem _ (axms, Assumes asms) =
wenzelm@13394
  1384
      apsnd Notes ((axms, asms) |> foldl_map (fn (axs, (a, spec)) =>
nipkow@13629
  1385
        let val (ps,qs) = splitAt(length spec, axs)
nipkow@13629
  1386
        in (qs, (a, [(ps, [])])) end))
wenzelm@13394
  1387
  | change_elem f (axms, Notes facts) = (axms, Notes (map (apsnd (map (apfst (map f)))) facts))
wenzelm@13394
  1388
  | change_elem _ e = e;
wenzelm@13394
  1389
wenzelm@13394
  1390
fun change_elemss axioms elemss = (axioms, elemss) |> foldl_map
wenzelm@13394
  1391
  (fn (axms, (id as ("", _), es)) =>
wenzelm@13394
  1392
    foldl_map (change_elem (Drule.satisfy_hyps axioms)) (axms, es) |> apsnd (pair id)
wenzelm@13394
  1393
  | x => x) |> #2;
wenzelm@13394
  1394
wenzelm@13394
  1395
in
wenzelm@13375
  1396
wenzelm@13394
  1397
fun define_preds bname (parms, ((exts, exts'), (ints, ints')), defs) elemss thy =
wenzelm@13394
  1398
  let
wenzelm@13394
  1399
    val (thy', (elemss', more_ts)) =
wenzelm@13394
  1400
      if Library.null exts then (thy, (elemss, []))
wenzelm@13394
  1401
      else
wenzelm@13394
  1402
        let
wenzelm@13420
  1403
          val aname = if Library.null ints then bname else bname ^ "_" ^ axiomsN;
wenzelm@13394
  1404
          val (def_thy, (statement, intro, axioms)) =
wenzelm@13394
  1405
            thy |> def_pred aname parms defs exts exts';
wenzelm@13394
  1406
          val elemss' = change_elemss axioms elemss @
wenzelm@13420
  1407
            [(("", []), [Assumes [((bname ^ "_" ^ axiomsN, []), [(statement, ([], []))])]])];
wenzelm@13394
  1408
        in
wenzelm@14564
  1409
          def_thy |> note_thmss_qualified "" aname
ballarin@14254
  1410
            [((introN, []), [([intro], [])])]
wenzelm@13394
  1411
          |> #1 |> rpair (elemss', [statement])
wenzelm@13394
  1412
        end;
wenzelm@13394
  1413
    val (thy'', view) =
wenzelm@13420
  1414
      if Library.null ints then (thy', ([], []))
wenzelm@13394
  1415
      else
wenzelm@13394
  1416
        let
wenzelm@13394
  1417
          val (def_thy, (statement, intro, axioms)) =
wenzelm@13394
  1418
            thy' |> def_pred bname parms defs (ints @ more_ts) (ints' @ more_ts);
wenzelm@13399
  1419
          val cstatement = Thm.cterm_of (Theory.sign_of def_thy) statement;
wenzelm@13394
  1420
        in
wenzelm@14564
  1421
          def_thy |> note_thmss_qualified "" bname
ballarin@14254
  1422
            [((introN, []), [([intro], [])]),
ballarin@14254
  1423
             ((axiomsN, []), [(map Drule.standard axioms, [])])]
wenzelm@13415
  1424
          |> #1 |> rpair ([cstatement], axioms)
wenzelm@13394
  1425
        end;
wenzelm@13394
  1426
  in (thy'', (elemss', view)) end;
wenzelm@13375
  1427
wenzelm@13375
  1428
end;
wenzelm@13336
  1429
wenzelm@13336
  1430
wenzelm@13297
  1431
(* add_locale(_i) *)
wenzelm@13297
  1432
wenzelm@13297
  1433
local
wenzelm@13297
  1434
wenzelm@13394
  1435
fun gen_add_locale prep_ctxt prep_expr do_pred bname raw_import raw_body thy =
ballarin@14528
  1436
  (* CB: do_pred = false means old-style locale, declared with (open).
ballarin@14528
  1437
     Old-style locales don't define predicates. *)
wenzelm@13297
  1438
  let
wenzelm@13297
  1439
    val sign = Theory.sign_of thy;
wenzelm@13297
  1440
    val name = Sign.full_name sign bname;
wenzelm@13297
  1441
    val _ = conditional (is_some (get_locale thy name)) (fn () =>
wenzelm@13297
  1442
      error ("Duplicate definition of locale " ^ quote name));
wenzelm@13297
  1443
wenzelm@13297
  1444
    val thy_ctxt = ProofContext.init thy;
wenzelm@13420
  1445
    val (((import_ctxt, import_elemss), (body_ctxt, body_elemss)), text) =
wenzelm@13375
  1446
      prep_ctxt raw_import raw_body thy_ctxt;
wenzelm@13375
  1447
    val elemss = import_elemss @ body_elemss;
wenzelm@13297
  1448
wenzelm@13415
  1449
    val (pred_thy, (elemss', view as (view_statement, view_axioms))) =
wenzelm@13394
  1450
      if do_pred then thy |> define_preds bname text elemss
wenzelm@13415
  1451
      else (thy, (elemss, ([], [])));
wenzelm@13375
  1452
    val pred_ctxt = ProofContext.init pred_thy;
wenzelm@13420
  1453
wenzelm@13420
  1454
    val ((ctxt, _), (_, facts)) = activate_facts (K I) ((pred_ctxt, view_axioms), elemss');
wenzelm@13415
  1455
    val export = ProofContext.export_standard view_statement ctxt pred_ctxt;
wenzelm@13420
  1456
    val facts' = facts |> map (fn (a, ths) => ((a, []), [(map export ths, [])]));
wenzelm@13297
  1457
  in
wenzelm@13375
  1458
    pred_thy
wenzelm@14564
  1459
    |> note_thmss_qualified "" name facts' |> #1
wenzelm@13297
  1460
    |> declare_locale name
wenzelm@13399
  1461
    |> put_locale name (make_locale view (prep_expr sign raw_import)
wenzelm@13394
  1462
        (map (fn e => (e, stamp ())) (flat (map #2 (filter (equal "" o #1 o #1) elemss'))))
wenzelm@13375
  1463
        (params_of elemss', map #1 (params_of body_elemss)))
wenzelm@13297
  1464
  end;
wenzelm@13297
  1465
wenzelm@13297
  1466
in
wenzelm@13297
  1467
wenzelm@13297
  1468
val add_locale = gen_add_locale read_context intern_expr;
ballarin@14215
  1469
wenzelm@13297
  1470
val add_locale_i = gen_add_locale cert_context (K I);
wenzelm@13297
  1471
wenzelm@13297
  1472
end;
wenzelm@13297
  1473
wenzelm@13297
  1474
wenzelm@12730
  1475
wenzelm@11896
  1476
(** locale theory setup **)
wenzelm@12063
  1477
wenzelm@11896
  1478
val setup =
wenzelm@13460
  1479
 [LocalesData.init,
wenzelm@13460
  1480
  add_locale_i true "var" empty [Elem (Fixes [(Syntax.internal "x", None, Some Syntax.NoSyn)])],
wenzelm@13460
  1481
  add_locale_i true "struct" empty [Elem (Fixes [(Syntax.internal "S", None, None)])]];
wenzelm@11896
  1482
wenzelm@11896
  1483
end;