src/Pure/Isar/attrib.ML
author wenzelm
Thu Jan 05 20:26:01 2012 +0100 (2012-01-05)
changeset 46126 bab00660539d
parent 45619 76c5f277b234
child 46506 c7faa011bfa7
permissions -rw-r--r--
discontinued Syntax.positions -- atomic parse trees are always annotated;
     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
    96     (Name_Space.define (Proof_Context.init_global thy) true (Sign.naming_of thy)
    97       (name, (att, comment)) #> snd);
    98 
    99 
   100 (* name space *)
   101 
   102 val intern = Name_Space.intern o #1 o Attributes.get;
   103 val intern_src = Args.map_name o intern;
   104 
   105 fun extern ctxt = Name_Space.extern ctxt (#1 (Attributes.get (Proof_Context.theory_of ctxt)));
   106 
   107 
   108 (* pretty printing *)
   109 
   110 fun pretty_attribs _ [] = []
   111   | pretty_attribs ctxt srcs =
   112       [Pretty.enum "," "[" "]" (map (Args.pretty_src ctxt o Args.map_name (extern ctxt)) srcs)];
   113 
   114 
   115 (* get attributes *)
   116 
   117 val defined = Symtab.defined o #2 o Attributes.get;
   118 
   119 fun attribute_i thy =
   120   let
   121     val (space, tab) = Attributes.get thy;
   122     fun attr src =
   123       let val ((name, _), pos) = Args.dest_src src in
   124         (case Symtab.lookup tab name of
   125           NONE => error ("Unknown attribute: " ^ quote name ^ Position.str_of pos)
   126         | SOME (att, _) => (Position.report pos (Name_Space.markup space name); att src))
   127       end;
   128   in attr end;
   129 
   130 fun attribute thy = attribute_i thy o intern_src thy;
   131 
   132 
   133 (* attributed declarations *)
   134 
   135 fun map_specs f = map (apfst (apsnd f));
   136 
   137 fun map_facts f = map (apfst (apsnd f) o apsnd (map (apsnd f)));
   138 fun map_facts_refs f g = map_facts f #> map (apsnd (map (apfst g)));
   139 
   140 
   141 (* fact expressions *)
   142 
   143 fun eval_thms ctxt srcs = ctxt
   144   |> Proof_Context.note_thmss ""
   145     (map_facts_refs (map (attribute (Proof_Context.theory_of ctxt))) (Proof_Context.get_fact ctxt)
   146       [((Binding.empty, []), srcs)])
   147   |> fst |> maps snd;
   148 
   149 
   150 (* attribute setup *)
   151 
   152 fun syntax scan = Args.syntax "attribute" scan;
   153 
   154 fun setup name scan =
   155   add_attribute name
   156     (fn src => fn (ctxt, th) => let val (a, ctxt') = syntax scan src ctxt in a (ctxt', th) end);
   157 
   158 fun attribute_setup name (txt, pos) cmt =
   159   Context.theory_map (ML_Context.expression pos
   160     "val (name, scan, comment): binding * attribute context_parser * string"
   161     "Context.map_theory (Attrib.setup name scan comment)"
   162     (ML_Lex.read Position.none ("(" ^ ML_Syntax.make_binding name ^ ", ") @
   163       ML_Lex.read pos txt @
   164       ML_Lex.read Position.none (", " ^ ML_Syntax.print_string cmt ^ ")")));
   165 
   166 
   167 (* add/del syntax *)
   168 
   169 fun add_del add del = Scan.lift (Args.add >> K add || Args.del >> K del || Scan.succeed add);
   170 
   171 
   172 
   173 (** parsing attributed theorems **)
   174 
   175 val thm_sel = Parse.$$$ "(" |-- Parse.list1
   176  (Parse.nat --| Parse.minus -- Parse.nat >> Facts.FromTo ||
   177   Parse.nat --| Parse.minus >> Facts.From ||
   178   Parse.nat >> Facts.Single) --| Parse.$$$ ")";
   179 
   180 local
   181 
   182 val fact_name = Args.internal_fact >> K "<fact>" || Args.name;
   183 
   184 fun gen_thm pick = Scan.depend (fn context =>
   185   let
   186     val thy = Context.theory_of context;
   187     val get = Context.cases (Global_Theory.get_fact context) Proof_Context.get_fact context;
   188     val get_fact = get o Facts.Fact;
   189     fun get_named pos name = get (Facts.Named ((name, pos), NONE));
   190   in
   191     Parse.$$$ "[" |-- Args.attribs (intern thy) --| Parse.$$$ "]" >> (fn srcs =>
   192       let
   193         val atts = map (attribute_i thy) srcs;
   194         val (context', th') =
   195           Library.apply (map Thm.apply_attribute atts) (context, Drule.dummy_thm);
   196       in (context', pick "" [th']) end)
   197     ||
   198     (Scan.ahead Args.alt_name -- Args.named_fact get_fact
   199       >> (fn (s, fact) => ("", Facts.Fact s, fact)) ||
   200      Scan.ahead (Parse.position fact_name) :|-- (fn (name, pos) =>
   201       Args.named_fact (get_named pos) -- Scan.option thm_sel
   202         >> (fn (fact, sel) => (name, Facts.Named ((name, pos), sel), fact))))
   203     -- Args.opt_attribs (intern thy) >> (fn ((name, thmref, fact), srcs) =>
   204       let
   205         val ths = Facts.select thmref fact;
   206         val atts = map (attribute_i thy) srcs;
   207         val (context', ths') =
   208           Library.foldl_map (Library.apply (map Thm.apply_attribute atts)) (context, ths);
   209       in (context', pick name ths') end)
   210   end);
   211 
   212 in
   213 
   214 val thm = gen_thm Facts.the_single;
   215 val multi_thm = gen_thm (K I);
   216 val thms = Scan.repeat multi_thm >> flat;
   217 
   218 end;
   219 
   220 
   221 
   222 (** partial evaluation -- observing rule/declaration/mixed attributes **)
   223 
   224 local
   225 
   226 val strict_eq_thm = op = o pairself Thm.rep_thm;
   227 
   228 fun apply_att src (context, th) =
   229   let
   230     val src1 = Args.assignable src;
   231     val result = attribute_i (Context.theory_of context) src1 (context, th);
   232     val src2 = Args.closure src1;
   233   in (src2, result) end;
   234 
   235 fun err msg src =
   236   let val ((name, _), pos) = Args.dest_src src
   237   in error (msg ^ " " ^ quote name ^ Position.str_of pos) end;
   238 
   239 fun eval src ((th, dyn), (decls, context)) =
   240   (case (apply_att src (context, th), dyn) of
   241     ((_, (NONE, SOME th')), NONE) => ((th', NONE), (decls, context))
   242   | ((_, (NONE, SOME _)), SOME _) => err "Mixed dynamic attribute followed by static rule" src
   243   | ((src', (SOME context', NONE)), NONE) =>
   244       let
   245         val decls' =
   246           (case decls of
   247             [] => [(th, [src'])]
   248           | (th2, srcs2) :: rest =>
   249               if strict_eq_thm (th, th2)
   250               then ((th2, src' :: srcs2) :: rest)
   251               else (th, [src']) :: (th2, srcs2) :: rest);
   252       in ((th, NONE), (decls', context')) end
   253   | ((src', (opt_context', opt_th')), _) =>
   254       let
   255         val context' = the_default context opt_context';
   256         val th' = the_default th opt_th';
   257         val dyn' =
   258           (case dyn of
   259             NONE => SOME (th, [src'])
   260           | SOME (dyn_th, srcs) => SOME (dyn_th, src' :: srcs));
   261       in ((th', dyn'), (decls, context')) end);
   262 
   263 in
   264 
   265 fun partial_evaluation ctxt facts =
   266   (facts, Context.Proof (Context_Position.set_visible false ctxt)) |->
   267     fold_map (fn ((b, more_atts), fact) => fn context =>
   268       let
   269         val (fact', (decls, context')) =
   270           (fact, ([], context)) |-> fold_map (fn (ths, atts) => fn res1 =>
   271             (ths, res1) |-> fold_map (fn th => fn res2 =>
   272               let
   273                 val ((th', dyn'), res3) = fold eval (atts @ more_atts) ((th, NONE), res2);
   274                 val th_atts' =
   275                   (case dyn' of
   276                     NONE => (th', [])
   277                   | SOME (dyn_th', atts') => (dyn_th', rev atts'));
   278               in (th_atts', res3) end))
   279           |>> flat;
   280         val decls' = rev (map (apsnd rev) decls);
   281         val facts' =
   282           if eq_list (eq_fst strict_eq_thm) (decls', fact') then
   283             [((b, []), map2 (fn (th, atts1) => fn (_, atts2) => (th, atts1 @ atts2)) decls' fact')]
   284           else if null decls' then [((b, []), fact')]
   285           else [(empty_binding, decls'), ((b, []), fact')];
   286       in (facts', context') end)
   287   |> fst |> flat |> map (apsnd (map (apfst single)));
   288 
   289 end;
   290 
   291 
   292 
   293 (** basic attributes **)
   294 
   295 (* internal *)
   296 
   297 fun internal att = Args.src (("Pure.attribute", [Token.mk_attribute att]), Position.none);
   298 
   299 
   300 (* rule composition *)
   301 
   302 val COMP_att =
   303   Scan.lift (Scan.optional (Args.bracks Parse.nat) 1) -- thm
   304     >> (fn (i, B) => Thm.rule_attribute (fn _ => fn A => Drule.compose_single (A, i, B)));
   305 
   306 val THEN_att =
   307   Scan.lift (Scan.optional (Args.bracks Parse.nat) 1) -- thm
   308     >> (fn (i, B) => Thm.rule_attribute (fn _ => fn A => A RSN (i, B)));
   309 
   310 val OF_att =
   311   thms >> (fn Bs => Thm.rule_attribute (fn _ => fn A => Bs MRS A));
   312 
   313 
   314 (* rename_abs *)
   315 
   316 val rename_abs =
   317   Scan.repeat (Args.maybe Args.name)
   318   >> (fn args => Thm.rule_attribute (K (Drule.rename_bvars' args)));
   319 
   320 
   321 (* unfold / fold definitions *)
   322 
   323 fun unfolded_syntax rule =
   324   thms >> (fn ths => Thm.rule_attribute (fn context => rule (Context.proof_of context) ths));
   325 
   326 val unfolded = unfolded_syntax Local_Defs.unfold;
   327 val folded = unfolded_syntax Local_Defs.fold;
   328 
   329 
   330 (* rule format *)
   331 
   332 val rule_format = Args.mode "no_asm"
   333   >> (fn true => Object_Logic.rule_format_no_asm | false => Object_Logic.rule_format);
   334 
   335 val elim_format = Thm.rule_attribute (K Tactic.make_elim);
   336 
   337 
   338 (* case names *)
   339 
   340 val case_names =
   341   Scan.repeat1 (Args.name --
   342     Scan.optional (Parse.$$$ "[" |-- Scan.repeat1 (Args.maybe Args.name) --| Parse.$$$ "]") []) >>
   343   (fn cs =>
   344     Rule_Cases.cases_hyp_names (map fst cs)
   345       (map (map (the_default Rule_Cases.case_hypsN) o snd) cs));
   346 
   347 
   348 (* misc rules *)
   349 
   350 val no_vars = Thm.rule_attribute (fn context => fn th =>
   351   let
   352     val ctxt = Variable.set_body false (Context.proof_of context);
   353     val ((_, [th']), _) = Variable.import true [th] ctxt;
   354   in th' end);
   355 
   356 val eta_long =
   357   Thm.rule_attribute (K (Conv.fconv_rule Drule.eta_long_conversion));
   358 
   359 val rotated = Scan.optional Parse.int 1 >> (fn n => Thm.rule_attribute (K (rotate_prems n)));
   360 
   361 
   362 (* theory setup *)
   363 
   364 val _ = Context.>> (Context.map_theory
   365  (setup (Binding.name "attribute") (Scan.lift Args.internal_attribute >> Morphism.form)
   366     "internal attribute" #>
   367   setup (Binding.name "tagged") (Scan.lift (Args.name -- Args.name) >> Thm.tag) "tagged theorem" #>
   368   setup (Binding.name "untagged") (Scan.lift Args.name >> Thm.untag) "untagged theorem" #>
   369   setup (Binding.name "kind") (Scan.lift Args.name >> Thm.kind) "theorem kind" #>
   370   setup (Binding.name "COMP") COMP_att "direct composition with rules (no lifting)" #>
   371   setup (Binding.name "THEN") THEN_att "resolution with rule" #>
   372   setup (Binding.name "OF") OF_att "rule applied to facts" #>
   373   setup (Binding.name "rename_abs") (Scan.lift rename_abs)
   374     "rename bound variables in abstractions" #>
   375   setup (Binding.name "unfolded") unfolded "unfolded definitions" #>
   376   setup (Binding.name "folded") folded "folded definitions" #>
   377   setup (Binding.name "consumes") (Scan.lift (Scan.optional Parse.nat 1) >> Rule_Cases.consumes)
   378     "number of consumed facts" #>
   379   setup (Binding.name "constraints") (Scan.lift Parse.nat >> Rule_Cases.constraints)
   380     "number of equality constraints" #>
   381   setup (Binding.name "case_names") (Scan.lift case_names) "named rule cases" #>
   382   setup (Binding.name "case_conclusion")
   383     (Scan.lift (Args.name -- Scan.repeat Args.name) >> Rule_Cases.case_conclusion)
   384     "named conclusion of rule cases" #>
   385   setup (Binding.name "params")
   386     (Scan.lift (Parse.and_list1 (Scan.repeat Args.name)) >> Rule_Cases.params)
   387     "named rule parameters" #>
   388   setup (Binding.name "standard") (Scan.succeed (Thm.rule_attribute (K Drule.export_without_context)))
   389     "result put into standard form (legacy)" #>
   390   setup (Binding.name "rule_format") rule_format "result put into canonical rule format" #>
   391   setup (Binding.name "elim_format") (Scan.succeed elim_format)
   392     "destruct rule turned into elimination rule format" #>
   393   setup (Binding.name "no_vars") (Scan.succeed no_vars) "frozen schematic vars" #>
   394   setup (Binding.name "eta_long") (Scan.succeed eta_long)
   395     "put theorem into eta long beta normal form" #>
   396   setup (Binding.name "atomize") (Scan.succeed Object_Logic.declare_atomize)
   397     "declaration of atomize rule" #>
   398   setup (Binding.name "rulify") (Scan.succeed Object_Logic.declare_rulify)
   399     "declaration of rulify rule" #>
   400   setup (Binding.name "rotated") (Scan.lift rotated) "rotated theorem premises" #>
   401   setup (Binding.name "defn") (add_del Local_Defs.defn_add Local_Defs.defn_del)
   402     "declaration of definitional transformations" #>
   403   setup (Binding.name "abs_def") (Scan.succeed (Thm.rule_attribute (K Drule.abs_def)))
   404     "abstract over free variables of a definition"));
   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_level_raw #>
   507   register_config Syntax.ambiguity_warnings_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;