src/Pure/Thy/export_theory.ML
author wenzelm
Sat Jul 20 12:52:29 2019 +0200 (2 months ago)
changeset 70384 8ce08b154aa1
parent 70015 c8e08d8ffb93
child 70386 6af87375b95f
permissions -rw-r--r--
clarified export of sort algebra: avoid logical operations in Isabelle/Scala;
     1 (*  Title:      Pure/Thy/export_theory.ML
     2     Author:     Makarius
     3 
     4 Export foundational theory content and locale/class structure.
     5 *)
     6 
     7 signature EXPORT_THEORY =
     8 sig
     9   val setup_presentation: (Thy_Info.presentation_context -> theory -> unit) -> unit
    10   val export_body: theory -> string -> XML.body -> unit
    11 end;
    12 
    13 structure Export_Theory: EXPORT_THEORY =
    14 struct
    15 
    16 (* approximative syntax *)
    17 
    18 val get_syntax = Syntax.get_approx o Proof_Context.syn_of;
    19 fun get_syntax_type ctxt = get_syntax ctxt o Lexicon.mark_type;
    20 fun get_syntax_const ctxt = get_syntax ctxt o Lexicon.mark_const;
    21 fun get_syntax_fixed ctxt = get_syntax ctxt o Lexicon.mark_fixed;
    22 
    23 fun get_syntax_param ctxt loc x =
    24   let val thy = Proof_Context.theory_of ctxt in
    25     if Class.is_class thy loc then
    26       (case AList.lookup (op =) (Class.these_params thy [loc]) x of
    27         NONE => NONE
    28       | SOME (_, (c, _)) => get_syntax_const ctxt c)
    29     else get_syntax_fixed ctxt x
    30   end;
    31 
    32 val encode_syntax =
    33   XML.Encode.variant
    34    [fn NONE => ([], []),
    35     fn SOME (Syntax.Prefix delim) => ([delim], []),
    36     fn SOME (Syntax.Infix {assoc, delim, pri}) =>
    37       let
    38         val ass =
    39           (case assoc of
    40             Printer.No_Assoc => 0
    41           | Printer.Left_Assoc => 1
    42           | Printer.Right_Assoc => 2);
    43         open XML.Encode Term_XML.Encode;
    44       in ([], triple int string int (ass, delim, pri)) end];
    45 
    46 
    47 (* standardization of variables: only frees and named bounds *)
    48 
    49 local
    50 
    51 fun declare_names (Abs (_, _, b)) = declare_names b
    52   | declare_names (t $ u) = declare_names t #> declare_names u
    53   | declare_names (Const (c, _)) = Name.declare (Long_Name.base_name c)
    54   | declare_names (Free (x, _)) = Name.declare x
    55   | declare_names _ = I;
    56 
    57 fun variant_abs bs (Abs (x, T, t)) =
    58       let
    59         val names = fold Name.declare bs (declare_names t Name.context);
    60         val x' = #1 (Name.variant x names);
    61         val t' = variant_abs (x' :: bs) t;
    62       in Abs (x', T, t') end
    63   | variant_abs bs (t $ u) = variant_abs bs t $ variant_abs bs u
    64   | variant_abs _ t = t;
    65 
    66 in
    67 
    68 fun standard_vars used =
    69   let
    70     fun zero_var_indexes tm =
    71       Term_Subst.instantiate (Term_Subst.zero_var_indexes_inst used [tm]) tm;
    72 
    73     fun unvarifyT ty = ty |> Term.map_atyps
    74       (fn TVar ((a, _), S) => TFree (a, S)
    75         | T as TFree (a, _) =>
    76             if Name.is_declared used a then T
    77             else raise TYPE (Logic.bad_fixed a, [ty], []));
    78 
    79     fun unvarify tm = tm |> Term.map_aterms
    80       (fn Var ((x, _), T) => Free (x, T)
    81         | t as Free (x, _) =>
    82             if Name.is_declared used x then t
    83             else raise TERM (Logic.bad_fixed x, [tm])
    84         | t => t);
    85 
    86   in zero_var_indexes #> map_types unvarifyT #> unvarify #> variant_abs [] end;
    87 
    88 val standard_vars_global = standard_vars Name.context;
    89 
    90 end;
    91 
    92 
    93 (* free variables: not declared in the context *)
    94 
    95 val is_free = not oo Name.is_declared;
    96 
    97 fun add_frees used =
    98   fold_aterms (fn Free (x, T) => is_free used x ? insert (op =) (x, T) | _ => I);
    99 
   100 fun add_tfrees used =
   101   (fold_types o fold_atyps) (fn TFree (a, S) => is_free used a ? insert (op =) (a, S) | _ => I);
   102 
   103 
   104 (* spec rules *)
   105 
   106 fun primrec_types ctxt const =
   107   Spec_Rules.retrieve ctxt (Const const)
   108   |> get_first
   109     (fn (Spec_Rules.Equational (Spec_Rules.Primrec types), _) => SOME (types, false)
   110       | (Spec_Rules.Equational (Spec_Rules.Primcorec types), _) => SOME (types, true)
   111       | _ => NONE)
   112   |> the_default ([], false);
   113 
   114 
   115 (* locales content *)
   116 
   117 fun locale_content thy loc =
   118   let
   119     val ctxt = Locale.init loc thy;
   120     val args =
   121       Locale.params_of thy loc
   122       |> map (fn ((x, T), _) => ((x, T), get_syntax_param ctxt loc x));
   123     val axioms =
   124       let
   125         val (asm, defs) = Locale.specification_of thy loc;
   126         val cprops = map (Thm.cterm_of ctxt) (the_list asm @ defs);
   127         val (intro1, intro2) = Locale.intros_of thy loc;
   128         val intros_tac = Method.try_intros_tac ctxt (the_list intro1 @ the_list intro2) [];
   129         val res =
   130           Goal.init (Conjunction.mk_conjunction_balanced cprops)
   131           |> (ALLGOALS Goal.conjunction_tac THEN intros_tac)
   132           |> try Seq.hd;
   133       in
   134         (case res of
   135           SOME goal => Thm.prems_of goal
   136         | NONE => raise Fail ("Cannot unfold locale " ^ quote loc))
   137       end;
   138     val typargs = rev (fold Term.add_tfrees (map (Free o #1) args @ axioms) []);
   139   in {typargs = typargs, args = args, axioms = axioms} end;
   140 
   141 fun get_locales thy =
   142   Locale.get_locales thy |> map_filter (fn loc =>
   143     if Experiment.is_experiment thy loc then NONE else SOME (loc, ()));
   144 
   145 fun get_dependencies prev_thys thy =
   146   Locale.dest_dependencies prev_thys thy |> map_filter (fn dep =>
   147     if Experiment.is_experiment thy (#source dep) orelse
   148       Experiment.is_experiment thy (#target dep) then NONE
   149     else
   150       let
   151         val (type_params, params) = Locale.parameters_of thy (#source dep);
   152         val typargs = fold (Term.add_tfreesT o #2 o #1) params type_params;
   153         val substT =
   154           typargs |> map_filter (fn v =>
   155             let
   156               val T = TFree v;
   157               val T' = Morphism.typ (#morphism dep) T;
   158             in if T = T' then NONE else SOME (v, T') end);
   159         val subst =
   160           params |> map_filter (fn (v, _) =>
   161             let
   162               val t = Free v;
   163               val t' = Morphism.term (#morphism dep) t;
   164             in if t aconv t' then NONE else SOME (v, t') end);
   165       in SOME (dep, (substT, subst)) end);
   166 
   167 
   168 (* general setup *)
   169 
   170 fun setup_presentation f =
   171   Theory.setup (Thy_Info.add_presentation (fn context => fn thy =>
   172     if Options.bool (#options context) "export_theory" then f context thy else ()));
   173 
   174 fun export_body thy name body =
   175   Export.export thy (Path.binding0 (Path.make ["theory", name]))
   176     (Buffer.chunks (YXML.buffer_body body Buffer.empty));
   177 
   178 
   179 (* presentation *)
   180 
   181 val _ = setup_presentation (fn {adjust_pos, ...} => fn thy =>
   182   let
   183     val parents = Theory.parents_of thy;
   184     val rep_tsig = Type.rep_tsig (Sign.tsig_of thy);
   185 
   186     val thy_ctxt = Proof_Context.init_global thy;
   187 
   188 
   189     (* entities *)
   190 
   191     fun make_entity_markup name xname pos serial =
   192       let
   193         val props =
   194           Position.offset_properties_of (adjust_pos pos) @
   195           Position.id_properties_of pos @
   196           Markup.serial_properties serial;
   197       in (Markup.entityN, (Markup.nameN, name) :: (Markup.xnameN, xname) :: props) end;
   198 
   199     fun entity_markup space name =
   200       let
   201         val xname = Name_Space.extern_shortest thy_ctxt space name;
   202         val {serial, pos, ...} = Name_Space.the_entry space name;
   203       in make_entity_markup name xname pos serial end;
   204 
   205     fun export_entities export_name export get_space decls =
   206       let val elems =
   207         let
   208           val parent_spaces = map get_space parents;
   209           val space = get_space thy;
   210         in
   211           (decls, []) |-> fold (fn (name, decl) =>
   212             if exists (fn space => Name_Space.declared space name) parent_spaces then I
   213             else
   214               (case export name decl of
   215                 NONE => I
   216               | SOME body =>
   217                   cons (#serial (Name_Space.the_entry space name),
   218                     XML.Elem (entity_markup space name, body))))
   219           |> sort (int_ord o apply2 #1) |> map #2
   220         end;
   221       in if null elems then () else export_body thy export_name elems end;
   222 
   223 
   224     (* types *)
   225 
   226     val encode_type =
   227       let open XML.Encode Term_XML.Encode
   228       in triple encode_syntax (list string) (option typ) end;
   229 
   230     fun export_type c (Type.LogicalType n) =
   231           SOME (encode_type (get_syntax_type thy_ctxt c, Name.invent Name.context Name.aT n, NONE))
   232       | export_type c (Type.Abbreviation (args, U, false)) =
   233           SOME (encode_type (get_syntax_type thy_ctxt c, args, SOME U))
   234       | export_type _ _ = NONE;
   235 
   236     val _ =
   237       export_entities "types" export_type Sign.type_space
   238         (Name_Space.dest_table (#types rep_tsig));
   239 
   240 
   241     (* consts *)
   242 
   243     val encode_const =
   244       let open XML.Encode Term_XML.Encode in
   245         pair encode_syntax
   246           (pair (list string)
   247             (pair typ (pair (option term) (pair bool (pair (list string) bool)))))
   248       end;
   249 
   250     fun export_const c (T, abbrev) =
   251       let
   252         val syntax = get_syntax_const thy_ctxt c;
   253         val U = Logic.unvarifyT_global T;
   254         val U0 = Type.strip_sorts U;
   255         val recursion = primrec_types thy_ctxt (c, U);
   256         val abbrev' = abbrev |> Option.map (standard_vars_global #> map_types Type.strip_sorts);
   257         val args = map (#1 o dest_TFree) (Consts.typargs (Sign.consts_of thy) (c, U0));
   258         val propositional = Object_Logic.is_propositional thy_ctxt (Term.body_type U0);
   259       in encode_const (syntax, (args, (U0, (abbrev', (propositional, recursion))))) end;
   260 
   261     val _ =
   262       export_entities "consts" (SOME oo export_const) Sign.const_space
   263         (#constants (Consts.dest (Sign.consts_of thy)));
   264 
   265 
   266     (* axioms and facts *)
   267 
   268     fun prop_of raw_thm =
   269       let
   270         val thm = raw_thm
   271           |> Thm.transfer thy
   272           |> Thm.check_hyps (Context.Theory thy)
   273           |> Thm.strip_shyps;
   274         val prop = thm
   275           |> Thm.full_prop_of;
   276       in (Thm.extra_shyps thm, prop) end;
   277 
   278     fun encode_prop used (Ss, raw_prop) =
   279       let
   280         val prop = standard_vars used raw_prop;
   281         val args = rev (add_frees used prop []);
   282         val typargs = rev (add_tfrees used prop []);
   283         val used' = fold (Name.declare o #1) typargs used;
   284         val sorts = Name.invent used' Name.aT (length Ss) ~~ Ss;
   285       in
   286         (sorts @ typargs, args, prop) |>
   287           let open XML.Encode Term_XML.Encode
   288           in triple (list (pair string sort)) (list (pair string typ)) term end
   289       end;
   290 
   291     fun encode_axiom used t = encode_prop used ([], t);
   292 
   293     val encode_fact_single = encode_prop Name.context o prop_of;
   294     val encode_fact_multi = XML.Encode.list (encode_prop Name.context) o map prop_of;
   295 
   296     val _ =
   297       export_entities "axioms" (fn _ => fn t => SOME (encode_axiom Name.context t))
   298         Theory.axiom_space (Theory.axioms_of thy);
   299     val _ =
   300       export_entities "facts" (K (SOME o encode_fact_multi))
   301         (Facts.space_of o Global_Theory.facts_of)
   302         (Facts.dest_static true [] (Global_Theory.facts_of thy));
   303 
   304 
   305     (* type classes *)
   306 
   307     val encode_class =
   308       let open XML.Encode Term_XML.Encode
   309       in pair (list (pair string typ)) (list encode_fact_single) end;
   310 
   311     fun export_class name =
   312       (case try (Axclass.get_info thy) name of
   313         NONE => ([], [])
   314       | SOME {params, axioms, ...} => (params, axioms))
   315       |> encode_class |> SOME;
   316 
   317     val _ =
   318       export_entities "classes" (fn name => fn () => export_class name)
   319         Sign.class_space (map (rpair ()) (Graph.keys (Sorts.classes_of (#2 (#classes rep_tsig)))));
   320 
   321 
   322     (* sort algebra *)
   323 
   324     val {classrel, arities} =
   325       Sorts.dest_algebra (map (#2 o #classes o Type.rep_tsig o Sign.tsig_of) parents)
   326         (#2 (#classes rep_tsig));
   327 
   328     val encode_prop0 =
   329       encode_axiom Name.context o Logic.varify_global;
   330 
   331     val encode_classrel =
   332       let open XML.Encode
   333       in list (pair encode_prop0 (pair string string)) end;
   334 
   335     val encode_arities =
   336       let open XML.Encode Term_XML.Encode
   337       in list (pair encode_prop0 (triple string (list sort) string)) end;
   338 
   339     val export_classrel =
   340       maps (fn (c, cs) => map (pair c) cs) #> map (`Logic.mk_classrel) #> encode_classrel;
   341 
   342     val export_arities = map (`Logic.mk_arity) #> encode_arities;
   343 
   344     val _ = if null classrel then () else export_body thy "classrel" (export_classrel classrel);
   345     val _ = if null arities then () else export_body thy "arities" (export_arities arities);
   346 
   347 
   348     (* locales *)
   349 
   350     fun encode_locale used =
   351       let open XML.Encode Term_XML.Encode in
   352         triple (list (pair string sort)) (list (pair (pair string typ) encode_syntax))
   353           (list (encode_axiom used))
   354       end;
   355 
   356     fun export_locale loc =
   357       let
   358         val {typargs, args, axioms} = locale_content thy loc;
   359         val used = fold Name.declare (map #1 typargs @ map (#1 o #1) args) Name.context;
   360       in encode_locale used (typargs, args, axioms) end
   361       handle ERROR msg =>
   362         cat_error msg ("The error(s) above occurred in locale " ^
   363           quote (Locale.markup_name thy_ctxt loc));
   364 
   365     val _ =
   366       export_entities "locales" (fn loc => fn () => SOME (export_locale loc))
   367         Locale.locale_space (get_locales thy);
   368 
   369 
   370     (* locale dependencies *)
   371 
   372     fun encode_locale_dependency (dep: Locale.locale_dependency, subst) =
   373       (#source dep, (#target dep, (#prefix dep, subst))) |>
   374         let
   375           open XML.Encode Term_XML.Encode;
   376           val encode_subst =
   377             pair (list (pair (pair string sort) typ)) (list (pair (pair string typ) term));
   378         in pair string (pair string (pair (list (pair string bool)) encode_subst)) end;
   379 
   380     val _ =
   381       (case get_dependencies parents thy of
   382         [] => ()
   383       | deps =>
   384           deps |> map_index (fn (i, dep) =>
   385             let
   386               val xname = string_of_int (i + 1);
   387               val name = Long_Name.implode [Context.theory_name thy, xname];
   388               val markup = make_entity_markup name xname (#pos (#1 dep)) (#serial (#1 dep));
   389               val body = encode_locale_dependency dep;
   390             in XML.Elem (markup, body) end)
   391           |> export_body thy "locale_dependencies");
   392 
   393 
   394     (* parents *)
   395 
   396     val _ =
   397       export_body thy "parents"
   398         (XML.Encode.string (cat_lines (map Context.theory_long_name parents)));
   399 
   400   in () end);
   401 
   402 end;