src/Pure/Isar/attrib.ML
author wenzelm
Thu Nov 17 21:31:29 2011 +0100 (2011-11-17)
changeset 45537 8e3e004f1c31
parent 45527 d2b3d16b673a
child 45584 41a768a431a6
permissions -rw-r--r--
partial evaluation in invisible context;
     1 (*  Title:      Pure/Isar/attrib.ML
     2     Author:     Markus Wenzel, TU Muenchen
     3 
     4 Symbolic representation of attributes -- with name and syntax.
     5 *)
     6 
     7 signature ATTRIB =
     8 sig
     9   type src = Args.src
    10   type binding = binding * src list
    11   val empty_binding: binding
    12   val print_attributes: theory -> unit
    13   val intern: theory -> xstring -> string
    14   val intern_src: theory -> src -> src
    15   val pretty_attribs: Proof.context -> src list -> Pretty.T list
    16   val defined: theory -> string -> bool
    17   val attribute: theory -> src -> attribute
    18   val attribute_i: theory -> src -> attribute
    19   val map_specs: ('a list -> 'att list) ->
    20     (('c * 'a list) * 'b) list -> (('c * 'att list) * 'b) list
    21   val map_facts: ('a list -> 'att list) ->
    22     (('c * 'a list) * ('d * 'a list) list) list ->
    23     (('c * 'att list) * ('d * 'att list) list) list
    24   val map_facts_refs: ('a list -> 'att list) -> ('b -> 'fact) ->
    25     (('c * 'a list) * ('b * 'a list) list) list ->
    26     (('c * 'att list) * ('fact * 'att list) list) list
    27   val eval_thms: Proof.context -> (Facts.ref * src list) list -> thm list
    28   val setup: Binding.binding -> attribute context_parser -> string -> theory -> theory
    29   val attribute_setup: bstring * Position.T -> Symbol_Pos.text * Position.T -> string ->
    30     theory -> theory
    31   val add_del: attribute -> attribute -> attribute context_parser
    32   val thm_sel: Facts.interval list parser
    33   val thm: thm context_parser
    34   val thms: thm list context_parser
    35   val multi_thm: thm list context_parser
    36   val partial_evaluation: Proof.context ->
    37     (binding * (thm list * Args.src list) list) list ->
    38     (binding * (thm list * Args.src list) list) list
    39   val internal: (morphism -> attribute) -> src
    40   val print_configs: Proof.context -> unit
    41   val config_bool: Binding.binding ->
    42     (Context.generic -> bool) -> bool Config.T * (theory -> theory)
    43   val config_int: Binding.binding ->
    44     (Context.generic -> int) -> int Config.T * (theory -> theory)
    45   val config_real: Binding.binding ->
    46     (Context.generic -> real) -> real Config.T * (theory -> theory)
    47   val config_string: Binding.binding ->
    48     (Context.generic -> string) -> string Config.T * (theory -> theory)
    49   val setup_config_bool: Binding.binding -> (Context.generic -> bool) -> bool Config.T
    50   val setup_config_int: Binding.binding -> (Context.generic -> int) -> int Config.T
    51   val setup_config_string: Binding.binding -> (Context.generic -> string) -> string Config.T
    52   val setup_config_real: Binding.binding -> (Context.generic -> real) -> real Config.T
    53 end;
    54 
    55 structure Attrib: ATTRIB =
    56 struct
    57 
    58 (* source and bindings *)
    59 
    60 type src = Args.src;
    61 
    62 type binding = binding * src list;
    63 val empty_binding: binding = (Binding.empty, []);
    64 
    65 
    66 
    67 (** named attributes **)
    68 
    69 (* theory data *)
    70 
    71 structure Attributes = Theory_Data
    72 (
    73   type T = ((src -> attribute) * string) Name_Space.table;
    74   val empty : T = Name_Space.empty_table "attribute";
    75   val extend = I;
    76   fun merge data : T = Name_Space.merge_tables data;
    77 );
    78 
    79 fun print_attributes thy =
    80   let
    81     val ctxt = Proof_Context.init_global thy;
    82     val attribs = Attributes.get thy;
    83     fun prt_attr (name, (_, "")) = Pretty.str name
    84       | prt_attr (name, (_, comment)) =
    85           Pretty.block [Pretty.str (name ^ ":"), Pretty.brk 2, Pretty.str comment];
    86   in
    87     [Pretty.big_list "attributes:" (map prt_attr (Name_Space.extern_table ctxt attribs))]
    88     |> Pretty.chunks |> Pretty.writeln
    89   end;
    90 
    91 fun add_attribute name att comment thy = thy
    92   |> Attributes.map
    93     (Name_Space.define (Proof_Context.init_global thy) true (Sign.naming_of thy)
    94       (name, (att, comment)) #> snd);
    95 
    96 
    97 (* name space *)
    98 
    99 val intern = Name_Space.intern o #1 o Attributes.get;
   100 val intern_src = Args.map_name o intern;
   101 
   102 fun extern ctxt = Name_Space.extern ctxt (#1 (Attributes.get (Proof_Context.theory_of ctxt)));
   103 
   104 
   105 (* pretty printing *)
   106 
   107 fun pretty_attribs _ [] = []
   108   | pretty_attribs ctxt srcs =
   109       [Pretty.enum "," "[" "]" (map (Args.pretty_src ctxt o Args.map_name (extern ctxt)) srcs)];
   110 
   111 
   112 (* get attributes *)
   113 
   114 val defined = Symtab.defined o #2 o Attributes.get;
   115 
   116 fun attribute_i thy =
   117   let
   118     val (space, tab) = Attributes.get thy;
   119     fun attr src =
   120       let val ((name, _), pos) = Args.dest_src src in
   121         (case Symtab.lookup tab name of
   122           NONE => error ("Unknown attribute: " ^ quote name ^ Position.str_of pos)
   123         | SOME (att, _) => (Position.report pos (Name_Space.markup space name); att src))
   124       end;
   125   in attr end;
   126 
   127 fun attribute thy = attribute_i thy o intern_src thy;
   128 
   129 
   130 (* attributed declarations *)
   131 
   132 fun map_specs f = map (apfst (apsnd f));
   133 
   134 fun map_facts f = map (apfst (apsnd f) o apsnd (map (apsnd f)));
   135 fun map_facts_refs f g = map_facts f #> map (apsnd (map (apfst g)));
   136 
   137 
   138 (* fact expressions *)
   139 
   140 fun eval_thms ctxt srcs = ctxt
   141   |> Proof_Context.note_thmss ""
   142     (map_facts_refs (map (attribute (Proof_Context.theory_of ctxt))) (Proof_Context.get_fact ctxt)
   143       [((Binding.empty, []), srcs)])
   144   |> fst |> maps snd;
   145 
   146 
   147 (* attribute setup *)
   148 
   149 fun syntax scan = Args.syntax "attribute" scan;
   150 
   151 fun setup name scan =
   152   add_attribute name
   153     (fn src => fn (ctxt, th) => let val (a, ctxt') = syntax scan src ctxt in a (ctxt', th) end);
   154 
   155 fun attribute_setup name (txt, pos) cmt =
   156   Context.theory_map (ML_Context.expression pos
   157     "val (name, scan, comment): binding * attribute context_parser * string"
   158     "Context.map_theory (Attrib.setup name scan comment)"
   159     (ML_Lex.read Position.none ("(" ^ ML_Syntax.make_binding name ^ ", ") @
   160       ML_Lex.read pos txt @
   161       ML_Lex.read Position.none (", " ^ ML_Syntax.print_string cmt ^ ")")));
   162 
   163 
   164 (* add/del syntax *)
   165 
   166 fun add_del add del = Scan.lift (Args.add >> K add || Args.del >> K del || Scan.succeed add);
   167 
   168 
   169 
   170 (** parsing attributed theorems **)
   171 
   172 val thm_sel = Parse.$$$ "(" |-- Parse.list1
   173  (Parse.nat --| Parse.minus -- Parse.nat >> Facts.FromTo ||
   174   Parse.nat --| Parse.minus >> Facts.From ||
   175   Parse.nat >> Facts.Single) --| Parse.$$$ ")";
   176 
   177 local
   178 
   179 val fact_name = Args.internal_fact >> K "<fact>" || Args.name;
   180 
   181 fun gen_thm pick = Scan.depend (fn context =>
   182   let
   183     val thy = Context.theory_of context;
   184     val get = Context.cases (Global_Theory.get_fact context) Proof_Context.get_fact context;
   185     val get_fact = get o Facts.Fact;
   186     fun get_named pos name = get (Facts.Named ((name, pos), NONE));
   187   in
   188     Parse.$$$ "[" |-- Args.attribs (intern thy) --| Parse.$$$ "]" >> (fn srcs =>
   189       let
   190         val atts = map (attribute_i thy) srcs;
   191         val (context', th') =
   192           Library.apply (map Thm.apply_attribute atts) (context, Drule.dummy_thm);
   193       in (context', pick "" [th']) end)
   194     ||
   195     (Scan.ahead Args.alt_name -- Args.named_fact get_fact
   196       >> (fn (s, fact) => ("", Facts.Fact s, fact)) ||
   197      Scan.ahead (Parse.position fact_name) :|-- (fn (name, pos) =>
   198       Args.named_fact (get_named pos) -- Scan.option thm_sel
   199         >> (fn (fact, sel) => (name, Facts.Named ((name, pos), sel), fact))))
   200     -- Args.opt_attribs (intern thy) >> (fn ((name, thmref, fact), srcs) =>
   201       let
   202         val ths = Facts.select thmref fact;
   203         val atts = map (attribute_i thy) srcs;
   204         val (context', ths') =
   205           Library.foldl_map (Library.apply (map Thm.apply_attribute atts)) (context, ths);
   206       in (context', pick name ths') end)
   207   end);
   208 
   209 in
   210 
   211 val thm = gen_thm Facts.the_single;
   212 val multi_thm = gen_thm (K I);
   213 val thms = Scan.repeat multi_thm >> flat;
   214 
   215 end;
   216 
   217 
   218 
   219 (** partial evaluation **)
   220 
   221 local
   222 
   223 val strict_thm_eq = op = o pairself Thm.rep_thm;
   224 
   225 fun apply_att src (context, th) =
   226   let
   227     val src1 = Args.assignable src;
   228     val result = attribute_i (Context.theory_of context) src1 (context, th);
   229     val src2 = Args.closure src1;
   230   in (src2, result) end;
   231 
   232 fun err msg src =
   233   let val ((name, _), pos) = Args.dest_src src
   234   in error (msg ^ " " ^ quote name ^ Position.str_of pos) end;
   235 
   236 fun eval src ((th, dyn), (decls, context)) =
   237   (case (apply_att src (context, th), dyn) of
   238     ((_, (NONE, SOME th')), NONE) => ((th', NONE), (decls, context))
   239   | ((_, (NONE, SOME _)), SOME _) => err "Mixed dynamic attribute followed by static rule" src
   240   | ((src', (SOME context', NONE)), NONE) =>
   241       let
   242         val decls' =
   243           (case decls of
   244             [] => [(th, [src'])]
   245           | (th2, srcs2) :: rest =>
   246               if strict_thm_eq (th, th2)
   247               then ((th2, src' :: srcs2) :: rest)
   248               else (th, [src']) :: (th2, srcs2) :: rest);
   249       in ((th, NONE), (decls', context')) end
   250   | ((src', (opt_context', opt_th')), _) =>
   251       let
   252         val context' = the_default context opt_context';
   253         val th' = the_default th opt_th';
   254         val dyn' =
   255           (case dyn of
   256             NONE => SOME (th, [src'])
   257           | SOME (dyn_th, srcs) => SOME (dyn_th, src' :: srcs));
   258       in ((th', dyn'), (decls, context')) end);
   259 
   260 in
   261 
   262 fun partial_evaluation ctxt facts =
   263   let
   264     val (facts', (decls, _)) =
   265       (facts, ([], Context.Proof (Context_Position.set_visible false ctxt))) |->
   266         fold_map (fn ((b, more_atts), fact) => fn res =>
   267           let
   268             val (fact', res') =
   269               (fact, res) |-> fold_map (fn (ths, atts) => fn res1 =>
   270                 (ths, res1) |-> fold_map (fn th => fn res2 =>
   271                   let
   272                     val ((th', dyn'), res3) = fold eval (atts @ more_atts) ((th, NONE), res2);
   273                     val th_atts' =
   274                       (case dyn' of
   275                         NONE => ([th'], [])
   276                       | SOME (dyn_th', atts') => ([dyn_th'], rev atts'));
   277                   in (th_atts', res3) end))
   278               |>> flat;
   279           in (((b, []), fact'), res') end);
   280     val decl_fact = (empty_binding, rev (map (fn (th, atts) => ([th], rev atts)) decls));
   281   in decl_fact :: facts' end;
   282 
   283 end;
   284 
   285 
   286 
   287 (** basic attributes **)
   288 
   289 (* internal *)
   290 
   291 fun internal att = Args.src (("Pure.attribute", [Token.mk_attribute att]), Position.none);
   292 
   293 
   294 (* rule composition *)
   295 
   296 val COMP_att =
   297   Scan.lift (Scan.optional (Args.bracks Parse.nat) 1) -- thm
   298     >> (fn (i, B) => Thm.rule_attribute (fn _ => fn A => Drule.compose_single (A, i, B)));
   299 
   300 val THEN_att =
   301   Scan.lift (Scan.optional (Args.bracks Parse.nat) 1) -- thm
   302     >> (fn (i, B) => Thm.rule_attribute (fn _ => fn A => A RSN (i, B)));
   303 
   304 val OF_att =
   305   thms >> (fn Bs => Thm.rule_attribute (fn _ => fn A => Bs MRS A));
   306 
   307 
   308 (* rename_abs *)
   309 
   310 val rename_abs =
   311   Scan.repeat (Args.maybe Args.name)
   312   >> (fn args => Thm.rule_attribute (K (Drule.rename_bvars' args)));
   313 
   314 
   315 (* unfold / fold definitions *)
   316 
   317 fun unfolded_syntax rule =
   318   thms >> (fn ths => Thm.rule_attribute (fn context => rule (Context.proof_of context) ths));
   319 
   320 val unfolded = unfolded_syntax Local_Defs.unfold;
   321 val folded = unfolded_syntax Local_Defs.fold;
   322 
   323 
   324 (* rule format *)
   325 
   326 val rule_format = Args.mode "no_asm"
   327   >> (fn true => Object_Logic.rule_format_no_asm | false => Object_Logic.rule_format);
   328 
   329 val elim_format = Thm.rule_attribute (K Tactic.make_elim);
   330 
   331 
   332 (* case names *)
   333 
   334 val case_names =
   335   Scan.repeat1 (Args.name --
   336     Scan.optional (Parse.$$$ "[" |-- Scan.repeat1 (Args.maybe Args.name) --| Parse.$$$ "]") []) >>
   337   (fn cs =>
   338     Rule_Cases.cases_hyp_names (map fst cs)
   339       (map (map (the_default Rule_Cases.case_hypsN) o snd) cs));
   340 
   341 
   342 (* misc rules *)
   343 
   344 val no_vars = Thm.rule_attribute (fn context => fn th =>
   345   let
   346     val ctxt = Variable.set_body false (Context.proof_of context);
   347     val ((_, [th']), _) = Variable.import true [th] ctxt;
   348   in th' end);
   349 
   350 val eta_long =
   351   Thm.rule_attribute (K (Conv.fconv_rule Drule.eta_long_conversion));
   352 
   353 val rotated = Scan.optional Parse.int 1 >> (fn n => Thm.rule_attribute (K (rotate_prems n)));
   354 
   355 
   356 (* theory setup *)
   357 
   358 val _ = Context.>> (Context.map_theory
   359  (setup (Binding.name "attribute") (Scan.lift Args.internal_attribute >> Morphism.form)
   360     "internal attribute" #>
   361   setup (Binding.name "tagged") (Scan.lift (Args.name -- Args.name) >> Thm.tag) "tagged theorem" #>
   362   setup (Binding.name "untagged") (Scan.lift Args.name >> Thm.untag) "untagged theorem" #>
   363   setup (Binding.name "kind") (Scan.lift Args.name >> Thm.kind) "theorem kind" #>
   364   setup (Binding.name "COMP") COMP_att "direct composition with rules (no lifting)" #>
   365   setup (Binding.name "THEN") THEN_att "resolution with rule" #>
   366   setup (Binding.name "OF") OF_att "rule applied to facts" #>
   367   setup (Binding.name "rename_abs") (Scan.lift rename_abs)
   368     "rename bound variables in abstractions" #>
   369   setup (Binding.name "unfolded") unfolded "unfolded definitions" #>
   370   setup (Binding.name "folded") folded "folded definitions" #>
   371   setup (Binding.name "consumes") (Scan.lift (Scan.optional Parse.nat 1) >> Rule_Cases.consumes)
   372     "number of consumed facts" #>
   373   setup (Binding.name "constraints") (Scan.lift Parse.nat >> Rule_Cases.constraints)
   374     "number of equality constraints" #>
   375   setup (Binding.name "case_names") (Scan.lift case_names) "named rule cases" #>
   376   setup (Binding.name "case_conclusion")
   377     (Scan.lift (Args.name -- Scan.repeat Args.name) >> Rule_Cases.case_conclusion)
   378     "named conclusion of rule cases" #>
   379   setup (Binding.name "params")
   380     (Scan.lift (Parse.and_list1 (Scan.repeat Args.name)) >> Rule_Cases.params)
   381     "named rule parameters" #>
   382   setup (Binding.name "standard") (Scan.succeed (Thm.rule_attribute (K Drule.export_without_context)))
   383     "result put into standard form (legacy)" #>
   384   setup (Binding.name "rule_format") rule_format "result put into canonical rule format" #>
   385   setup (Binding.name "elim_format") (Scan.succeed elim_format)
   386     "destruct rule turned into elimination rule format" #>
   387   setup (Binding.name "no_vars") (Scan.succeed no_vars) "frozen schematic vars" #>
   388   setup (Binding.name "eta_long") (Scan.succeed eta_long)
   389     "put theorem into eta long beta normal form" #>
   390   setup (Binding.name "atomize") (Scan.succeed Object_Logic.declare_atomize)
   391     "declaration of atomize rule" #>
   392   setup (Binding.name "rulify") (Scan.succeed Object_Logic.declare_rulify)
   393     "declaration of rulify rule" #>
   394   setup (Binding.name "rotated") (Scan.lift rotated) "rotated theorem premises" #>
   395   setup (Binding.name "defn") (add_del Local_Defs.defn_add Local_Defs.defn_del)
   396     "declaration of definitional transformations" #>
   397   setup (Binding.name "abs_def") (Scan.succeed (Thm.rule_attribute (K Drule.abs_def)))
   398     "abstract over free variables of a definition"));
   399 
   400 
   401 
   402 (** configuration options **)
   403 
   404 (* naming *)
   405 
   406 structure Configs = Theory_Data
   407 (
   408   type T = Config.raw Symtab.table;
   409   val empty = Symtab.empty;
   410   val extend = I;
   411   fun merge data = Symtab.merge (K true) data;
   412 );
   413 
   414 fun print_configs ctxt =
   415   let
   416     val thy = Proof_Context.theory_of ctxt;
   417     fun prt (name, config) =
   418       let val value = Config.get ctxt config in
   419         Pretty.block [Pretty.str (name ^ ": " ^ Config.print_type value ^ " ="), Pretty.brk 1,
   420           Pretty.str (Config.print_value value)]
   421       end;
   422     val configs = Name_Space.extern_table ctxt (#1 (Attributes.get thy), Configs.get thy);
   423   in Pretty.writeln (Pretty.big_list "configuration options" (map prt configs)) end;
   424 
   425 
   426 (* concrete syntax *)
   427 
   428 local
   429 
   430 val equals = Parse.$$$ "=";
   431 
   432 fun scan_value (Config.Bool _) =
   433       equals -- Args.$$$ "false" >> K (Config.Bool false) ||
   434       equals -- Args.$$$ "true" >> K (Config.Bool true) ||
   435       Scan.succeed (Config.Bool true)
   436   | scan_value (Config.Int _) = equals |-- Parse.int >> Config.Int
   437   | scan_value (Config.Real _) = equals |-- Parse.real >> Config.Real
   438   | scan_value (Config.String _) = equals |-- Args.name >> Config.String;
   439 
   440 fun scan_config thy config =
   441   let val config_type = Config.get_global thy config
   442   in scan_value config_type >> (K o Thm.declaration_attribute o K o Config.put_generic config) end;
   443 
   444 fun register binding config thy =
   445   let val name = Sign.full_name thy binding in
   446     thy
   447     |> setup binding (Scan.lift (scan_config thy config) >> Morphism.form) "configuration option"
   448     |> Configs.map (Symtab.update (name, config))
   449   end;
   450 
   451 fun declare make coerce binding default =
   452   let
   453     val name = Binding.name_of binding;
   454     val config_value = Config.declare_generic {global = false} name (make o default);
   455     val config = coerce config_value;
   456   in (config, register binding config_value) end;
   457 
   458 in
   459 
   460 val config_bool = declare Config.Bool Config.bool;
   461 val config_int = declare Config.Int Config.int;
   462 val config_real = declare Config.Real Config.real;
   463 val config_string = declare Config.String Config.string;
   464 
   465 fun register_config config = register (Binding.name (Config.name_of config)) config;
   466 
   467 end;
   468 
   469 
   470 (* implicit setup *)
   471 
   472 local
   473 
   474 fun setup_config declare_config binding default =
   475   let
   476     val (config, setup) = declare_config binding default;
   477     val _ = Context.>> (Context.map_theory setup);
   478   in config end;
   479 
   480 in
   481 
   482 val setup_config_bool = setup_config config_bool;
   483 val setup_config_int = setup_config config_int;
   484 val setup_config_string = setup_config config_string;
   485 val setup_config_real = setup_config config_real;
   486 
   487 end;
   488 
   489 
   490 (* theory setup *)
   491 
   492 val _ = Context.>> (Context.map_theory
   493  (register_config Ast.trace_raw #>
   494   register_config Ast.stats_raw #>
   495   register_config Syntax.positions_raw #>
   496   register_config Printer.show_brackets_raw #>
   497   register_config Printer.show_sorts_raw #>
   498   register_config Printer.show_types_raw #>
   499   register_config Printer.show_structs_raw #>
   500   register_config Printer.show_question_marks_raw #>
   501   register_config Syntax.ambiguity_level_raw #>
   502   register_config Syntax.ambiguity_warnings_raw #>
   503   register_config Syntax_Trans.eta_contract_raw #>
   504   register_config Name_Space.names_long_raw #>
   505   register_config Name_Space.names_short_raw #>
   506   register_config Name_Space.names_unique_raw #>
   507   register_config ML_Context.trace_raw #>
   508   register_config Proof_Context.show_abbrevs_raw #>
   509   register_config Goal_Display.goals_limit_raw #>
   510   register_config Goal_Display.show_main_goal_raw #>
   511   register_config Goal_Display.show_consts_raw #>
   512   register_config Display.show_hyps_raw #>
   513   register_config Display.show_tags_raw #>
   514   register_config Unify.trace_bound_raw #>
   515   register_config Unify.search_bound_raw #>
   516   register_config Unify.trace_simp_raw #>
   517   register_config Unify.trace_types_raw #>
   518   register_config Raw_Simplifier.simp_depth_limit_raw #>
   519   register_config Raw_Simplifier.simp_trace_depth_limit_raw #>
   520   register_config Raw_Simplifier.simp_debug_raw #>
   521   register_config Raw_Simplifier.simp_trace_raw));
   522 
   523 end;