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