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