src/HOL/Tools/BNF/bnf_gfp_rec_sugar.ML
author blanchet
Mon, 15 Feb 2016 12:47:35 +0100
changeset 62318 b42858e540bb
parent 61841 4d3527b94f2a
child 62497 5b5b704f4811
permissions -rw-r--r--
clearer error message
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
55061
a0adf838e2d1 adjusted comments
blanchet
parents: 55060
diff changeset
     1
(*  Title:      HOL/Tools/BNF/bnf_gfp_rec_sugar.ML
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
     2
    Author:     Lorenz Panny, TU Muenchen
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
     3
    Author:     Jasmin Blanchette, TU Muenchen
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
     4
    Copyright   2013
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
     5
55538
blanchet
parents: 55529
diff changeset
     6
Corecursor sugar ("primcorec" and "primcorecursive").
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
     7
*)
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
     8
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
     9
signature BNF_GFP_REC_SUGAR =
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
    10
sig
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
    11
  datatype corec_option =
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
    12
    Plugins_Option of Proof.context -> Plugin_Name.filter |
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
    13
    Sequential_Option |
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
    14
    Exhaustive_Option |
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
    15
    Transfer_Option
54899
7a01387c47d5 added tactic to prove 'disc_iff' properties in 'primcorec'
blanchet
parents: 54883
diff changeset
    16
58223
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    17
  datatype corec_call =
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    18
    Dummy_No_Corec of int |
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    19
    No_Corec of int |
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    20
    Mutual_Corec of int * int * int |
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    21
    Nested_Corec of int
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    22
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    23
  type corec_ctr_spec =
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    24
    {ctr: term,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    25
     disc: term,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    26
     sels: term list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    27
     pred: int option,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    28
     calls: corec_call list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    29
     discI: thm,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    30
     sel_thms: thm list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    31
     distinct_discss: thm list list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    32
     collapse: thm,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    33
     corec_thm: thm,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    34
     corec_disc: thm,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    35
     corec_sels: thm list}
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    36
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    37
  type corec_spec =
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
    38
    {T: typ,
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
    39
     corec: term,
58223
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    40
     exhaust_discs: thm list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    41
     sel_defs: thm list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    42
     fp_nesting_maps: thm list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    43
     fp_nesting_map_ident0s: thm list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    44
     fp_nesting_map_comps: thm list,
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    45
     ctr_specs: corec_ctr_spec list}
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    46
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    47
  val abstract_over_list: term list -> term -> term
59945
cfbaee8cdf1d export ML function
blanchet
parents: 59936
diff changeset
    48
  val abs_tuple_balanced: term list -> term -> term
cfbaee8cdf1d export ML function
blanchet
parents: 59936
diff changeset
    49
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    50
  val mk_conjs: term list -> term
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    51
  val mk_disjs: term list -> term
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    52
  val mk_dnf: term list list -> term
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    53
  val conjuncts_s: term -> term list
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    54
  val s_not: term -> term
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    55
  val s_not_conj: term list -> term list
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    56
  val s_conjs: term list -> term
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    57
  val s_disjs: term list -> term
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    58
  val s_dnf: term list list -> term list
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
    59
59674
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    60
  val fold_rev_let_if_case: Proof.context -> (term list -> term -> 'a -> 'a) -> typ list ->
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    61
    term -> 'a -> 'a
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    62
  val massage_let_if_case: Proof.context -> (term -> bool) -> (typ list -> term -> term) ->
62318
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
    63
    (typ list -> term -> unit) -> (typ list -> term -> term) -> typ list -> term -> term
59674
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    64
  val massage_nested_corec_call: Proof.context -> (term -> bool) ->
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
    65
    (typ list -> typ -> typ -> term -> term) -> (typ list -> typ -> typ -> term -> term) ->
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
    66
    typ list -> typ -> typ -> term -> term
60683
d34e1b0b331a tuned ML signature
blanchet
parents: 60362
diff changeset
    67
  val expand_to_ctr_term: Proof.context -> typ -> term -> term
59674
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    68
  val massage_corec_code_rhs: Proof.context -> (typ list -> term -> term list -> term) ->
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    69
    typ list -> term -> term
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    70
  val fold_rev_corec_code_rhs: Proof.context -> (term list -> term -> term list -> 'a -> 'a) ->
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    71
    typ list -> term -> 'a -> 'a
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    72
  val case_thms_of_term: Proof.context -> term ->
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    73
    thm list * thm list * thm list * thm list * thm list
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    74
  val map_thms_of_type: Proof.context -> typ -> thm list
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
    75
58223
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    76
  val corec_specs_of: binding list -> typ list -> typ list -> term list ->
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
    77
    (term * term list list) list list -> local_theory ->
58283
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
    78
    corec_spec list * typ list * thm * thm * thm list * thm list * (Token.src list * Token.src list)
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
    79
    * bool * local_theory
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
    80
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
    81
  val gfp_rec_sugar_interpretation: string ->
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
    82
    (BNF_FP_Rec_Sugar_Util.fp_rec_sugar -> local_theory -> local_theory) -> theory -> theory
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
    83
61301
484f7878ede4 export '_cmd' functions
blanchet
parents: 61271
diff changeset
    84
  val primcorec_ursive_cmd: bool -> corec_option list ->
484f7878ede4 export '_cmd' functions
blanchet
parents: 61271
diff changeset
    85
    (binding * string option * mixfix) list * ((Attrib.binding * string) * string option) list ->
484f7878ede4 export '_cmd' functions
blanchet
parents: 61271
diff changeset
    86
    Proof.context ->
484f7878ede4 export '_cmd' functions
blanchet
parents: 61271
diff changeset
    87
    (term * 'a list) list list * (thm list list -> local_theory -> local_theory) * local_theory
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
    88
  val primcorecursive_cmd: corec_option list ->
53831
80423b9080cf support "of" syntax to disambiguate selector equations
panny
parents: 53830
diff changeset
    89
    (binding * string option * mixfix) list * ((Attrib.binding * string) * string option) list ->
80423b9080cf support "of" syntax to disambiguate selector equations
panny
parents: 53830
diff changeset
    90
    Proof.context -> Proof.state
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
    91
  val primcorec_cmd: corec_option list ->
53831
80423b9080cf support "of" syntax to disambiguate selector equations
panny
parents: 53830
diff changeset
    92
    (binding * string option * mixfix) list * ((Attrib.binding * string) * string option) list ->
80423b9080cf support "of" syntax to disambiguate selector equations
panny
parents: 53830
diff changeset
    93
    local_theory -> local_theory
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
    94
end;
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
    95
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
    96
structure BNF_GFP_Rec_Sugar : BNF_GFP_REC_SUGAR =
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
    97
struct
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
    98
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
    99
open Ctr_Sugar_General_Tactics
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   100
open Ctr_Sugar
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   101
open BNF_Util
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   102
open BNF_Def
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   103
open BNF_FP_Util
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   104
open BNF_FP_Def_Sugar
54243
a596292be9a8 more robust n2m w.r.t. 'let's
blanchet
parents: 54239
diff changeset
   105
open BNF_FP_N2M_Sugar
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   106
open BNF_FP_Rec_Sugar_Util
59276
blanchet
parents: 59275
diff changeset
   107
open BNF_FP_Rec_Sugar_Transfer
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   108
open BNF_GFP_Rec_Sugar_Tactics
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   109
58387
blanchet
parents: 58335
diff changeset
   110
val codeN = "code";
blanchet
parents: 58335
diff changeset
   111
val ctrN = "ctr";
blanchet
parents: 58335
diff changeset
   112
val discN = "disc";
blanchet
parents: 58335
diff changeset
   113
val disc_iffN = "disc_iff";
blanchet
parents: 58335
diff changeset
   114
val excludeN = "exclude";
blanchet
parents: 58335
diff changeset
   115
val selN = "sel";
53791
0ddf045113c9 tuned code
blanchet
parents: 53753
diff changeset
   116
54145
297d1c603999 make sure that registered code equations are actually equations
blanchet
parents: 54133
diff changeset
   117
val nitpicksimp_attrs = @{attributes [nitpick_simp]};
53794
af7d1533a25b undid copy-paste
blanchet
parents: 53793
diff changeset
   118
val simp_attrs = @{attributes [simp]};
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   119
59599
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   120
fun extra_variable ctxt ts var =
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   121
  error_at ctxt ts ("Extra variable " ^ quote (Syntax.string_of_term ctxt var));
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   122
fun not_codatatype ctxt T =
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   123
  error ("Not a codatatype: " ^ Syntax.string_of_typ ctxt T);
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   124
fun ill_formed_corec_call ctxt t =
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   125
  error ("Ill-formed corecursive call " ^ quote (Syntax.string_of_term ctxt t));
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   126
fun invalid_map ctxt t =
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   127
  error_at ctxt [t] "Invalid map function";
59598
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
   128
fun nonprimitive_corec ctxt eqns =
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
   129
  error_at ctxt eqns "Nonprimitive corecursive specification";
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   130
fun unexpected_corec_call ctxt eqns t =
59596
c067eba942e7 no quick_and_dirty for goals that may fail + tuned messages
blanchet
parents: 59595
diff changeset
   131
  error_at ctxt eqns ("Unexpected corecursive call in " ^ quote (Syntax.string_of_term ctxt t));
62318
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   132
fun unsupported_case_around_corec_call ctxt eqns t =
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   133
  error_at ctxt eqns ("Unsupported corecursive call under case expression " ^
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   134
    quote (Syntax.string_of_term ctxt t) ^ "\n(Define " ^
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   135
    quote (Syntax.string_of_typ ctxt (domain_type (fastype_of t))) ^
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   136
    " with  discriminators and selectors to circumvent this limitation.)");
59597
70a68edcc79b helpful error message when 'auto' fails
blanchet
parents: 59596
diff changeset
   137
fun use_primcorecursive () =
59936
b8ffc3dc9e24 @{command_spec} is superseded by @{command_keyword};
wenzelm
parents: 59873
diff changeset
   138
  error ("\"auto\" failed (try " ^ quote (#1 @{command_keyword primcorecursive}) ^ " instead of " ^
b8ffc3dc9e24 @{command_spec} is superseded by @{command_keyword};
wenzelm
parents: 59873
diff changeset
   139
    quote (#1 @{command_keyword primcorec}) ^ ")");
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   140
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   141
datatype corec_option =
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   142
  Plugins_Option of Proof.context -> Plugin_Name.filter |
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   143
  Sequential_Option |
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   144
  Exhaustive_Option |
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   145
  Transfer_Option;
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
   146
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   147
datatype corec_call =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   148
  Dummy_No_Corec of int |
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   149
  No_Corec of int |
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   150
  Mutual_Corec of int * int * int |
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   151
  Nested_Corec of int;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   152
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   153
type basic_corec_ctr_spec =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   154
  {ctr: term,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   155
   disc: term,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   156
   sels: term list};
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   157
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   158
type corec_ctr_spec =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   159
  {ctr: term,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   160
   disc: term,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   161
   sels: term list,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   162
   pred: int option,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   163
   calls: corec_call list,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   164
   discI: thm,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   165
   sel_thms: thm list,
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   166
   distinct_discss: thm list list,
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   167
   collapse: thm,
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   168
   corec_thm: thm,
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   169
   corec_disc: thm,
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   170
   corec_sels: thm list};
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   171
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   172
type corec_spec =
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
   173
  {T: typ,
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
   174
   corec: term,
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   175
   exhaust_discs: thm list,
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
   176
   sel_defs: thm list,
57397
5004aca20821 tuned variable names
blanchet
parents: 57303
diff changeset
   177
   fp_nesting_maps: thm list,
57399
cfc19f0a6261 compile
blanchet
parents: 57397
diff changeset
   178
   fp_nesting_map_ident0s: thm list,
57397
5004aca20821 tuned variable names
blanchet
parents: 57303
diff changeset
   179
   fp_nesting_map_comps: thm list,
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   180
   ctr_specs: corec_ctr_spec list};
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   181
58223
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
   182
exception NO_MAP of term;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   183
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   184
fun abstract_over_list rev_vs =
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   185
  let
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   186
    val vs = rev rev_vs;
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   187
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   188
    fun abs n (t $ u) = abs n t $ abs n u
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   189
      | abs n (Abs (s, T, t)) = Abs (s, T, abs (n + 1) t)
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   190
      | abs n t =
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   191
        let val j = find_index (curry (op =) t) vs in
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   192
          if j < 0 then t else Bound (n + j)
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   193
        end;
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   194
  in
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   195
    abs 0
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   196
  end;
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   197
59945
cfbaee8cdf1d export ML function
blanchet
parents: 59936
diff changeset
   198
val abs_tuple_balanced = HOLogic.tupled_lambda o mk_tuple_balanced;
cfbaee8cdf1d export ML function
blanchet
parents: 59936
diff changeset
   199
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   200
fun curried_type (Type (@{type_name fun}, [Type (@{type_name prod}, Ts), T])) =
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   201
  Ts ---> T;
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   202
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
   203
fun sort_list_duplicates xs = map snd (sort (int_ord o apply2 fst) xs);
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
   204
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   205
val mk_conjs = try (foldr1 HOLogic.mk_conj) #> the_default @{const True};
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   206
val mk_disjs = try (foldr1 HOLogic.mk_disj) #> the_default @{const False};
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
   207
val mk_dnf = mk_disjs o map mk_conjs;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   208
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
   209
val conjuncts_s = filter_out (curry (op aconv) @{const True}) o HOLogic.conjuncts;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   210
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   211
fun s_not @{const True} = @{const False}
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   212
  | s_not @{const False} = @{const True}
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   213
  | s_not (@{const Not} $ t) = t
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   214
  | s_not (@{const conj} $ t $ u) = @{const disj} $ s_not t $ s_not u
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   215
  | s_not (@{const disj} $ t $ u) = @{const conj} $ s_not t $ s_not u
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   216
  | s_not t = @{const Not} $ t;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   217
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   218
val s_not_conj = conjuncts_s o s_not o mk_conjs;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   219
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   220
fun propagate_unit_pos u cs = if member (op aconv) cs u then [@{const False}] else cs;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   221
fun propagate_unit_neg not_u cs = remove (op aconv) not_u cs;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   222
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   223
fun propagate_units css =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   224
  (case List.partition (can the_single) css of
58393
blanchet
parents: 58387
diff changeset
   225
    ([], _) => css
blanchet
parents: 58387
diff changeset
   226
  | ([u] :: uss, css') =>
blanchet
parents: 58387
diff changeset
   227
    [u] :: propagate_units (map (propagate_unit_neg (s_not u))
blanchet
parents: 58387
diff changeset
   228
      (map (propagate_unit_pos u) (uss @ css'))));
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   229
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   230
fun s_conjs cs =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   231
  if member (op aconv) cs @{const False} then @{const False}
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   232
  else mk_conjs (remove (op aconv) @{const True} cs);
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   233
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   234
fun s_disjs ds =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   235
  if member (op aconv) ds @{const True} then @{const True}
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   236
  else mk_disjs (remove (op aconv) @{const False} ds);
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   237
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   238
fun s_dnf css0 =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   239
  let val css = propagate_units css0 in
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   240
    if null css then
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   241
      [@{const False}]
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   242
    else if exists null css then
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   243
      []
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   244
    else
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   245
      map (fn c :: cs => (c, cs)) css
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   246
      |> AList.coalesce (op =)
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   247
      |> map (fn (c, css) => c :: s_dnf css)
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   248
      |> (fn [cs] => cs | css => [s_disjs (map s_conjs css)])
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   249
  end;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   250
55341
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
   251
fun fold_rev_let_if_case ctxt f bound_Ts =
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   252
  let
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   253
    val thy = Proof_Context.theory_of ctxt;
53794
af7d1533a25b undid copy-paste
blanchet
parents: 53793
diff changeset
   254
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   255
    fun fld conds t =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   256
      (case Term.strip_comb t of
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
   257
        (Const (@{const_name Let}, _), [_, _]) => fld conds (unfold_lets_splits t)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   258
      | (Const (@{const_name If}, _), [cond, then_branch, else_branch]) =>
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   259
        fld (conds @ conjuncts_s cond) then_branch o fld (conds @ s_not_conj [cond]) else_branch
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   260
      | (Const (c, _), args as _ :: _ :: _) =>
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   261
        let val n = num_binder_types (Sign.the_const_type thy c) - 1 in
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   262
          if n >= 0 andalso n < length args then
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   263
            (case fastype_of1 (bound_Ts, nth args n) of
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   264
              Type (s, Ts) =>
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   265
              (case dest_case ctxt s Ts t of
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   266
                SOME ({split_sels = _ :: _, ...}, conds', branches) =>
55341
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
   267
                fold_rev (uncurry fld) (map (append conds o conjuncts_s) conds' ~~ branches)
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
   268
              | _ => f conds t)
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
   269
            | _ => f conds t)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   270
          else
55341
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
   271
            f conds t
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   272
        end
55342
blanchet
parents: 55341
diff changeset
   273
      | _ => f conds t);
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   274
  in
55341
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
   275
    fld []
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   276
  end;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   277
54970
891141de5672 only destruct cases equipped with the right stuff (in particular, 'sel_split')
blanchet
parents: 54969
diff changeset
   278
fun case_of ctxt s =
891141de5672 only destruct cases equipped with the right stuff (in particular, 'sel_split')
blanchet
parents: 54969
diff changeset
   279
  (case ctr_sugar_of ctxt s of
62318
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   280
    SOME {casex = Const (s', _), split_sels, ...} => SOME (s', not (null split_sels))
54970
891141de5672 only destruct cases equipped with the right stuff (in particular, 'sel_split')
blanchet
parents: 54969
diff changeset
   281
  | _ => NONE);
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   282
62318
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   283
fun massage_let_if_case ctxt has_call massage_leaf unexpected_call unsupported_case bound_Ts t0 =
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   284
  let
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   285
    val thy = Proof_Context.theory_of ctxt;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   286
60001
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   287
    fun check_no_call bound_Ts t = if has_call t then unexpected_call bound_Ts t else ();
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   288
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   289
    fun massage_abs bound_Ts 0 t = massage_rec bound_Ts t
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   290
      | massage_abs bound_Ts m (Abs (s, T, t)) = Abs (s, T, massage_abs (T :: bound_Ts) (m - 1) t)
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   291
      | massage_abs bound_Ts m t =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   292
        let val T = domain_type (fastype_of1 (bound_Ts, t)) in
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   293
          Abs (Name.uu, T, massage_abs (T :: bound_Ts) (m - 1) (incr_boundvars 1 t $ Bound 0))
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   294
        end
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   295
    and massage_rec bound_Ts t =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   296
      let val typof = curry fastype_of1 bound_Ts in
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   297
        (case Term.strip_comb t of
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
   298
          (Const (@{const_name Let}, _), [_, _]) => massage_rec bound_Ts (unfold_lets_splits t)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   299
        | (Const (@{const_name If}, _), obj :: (branches as [_, _])) =>
59612
7ea413656b64 avoid needless 'if ... undefined' in generated theorems
blanchet
parents: 59609
diff changeset
   300
          (case List.partition Term.is_dummy_pattern (map (massage_rec bound_Ts) branches) of
7ea413656b64 avoid needless 'if ... undefined' in generated theorems
blanchet
parents: 59609
diff changeset
   301
            (dummy_branch' :: _, []) => dummy_branch'
7ea413656b64 avoid needless 'if ... undefined' in generated theorems
blanchet
parents: 59609
diff changeset
   302
          | (_, [branch']) => branch'
7ea413656b64 avoid needless 'if ... undefined' in generated theorems
blanchet
parents: 59609
diff changeset
   303
          | (_, branches') =>
60001
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   304
            Term.list_comb (If_const (typof (hd branches')) $ tap (check_no_call bound_Ts) obj,
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   305
              branches'))
61424
c3658c18b7bc prod_case as canonical name for product type eliminator
haftmann
parents: 61348
diff changeset
   306
        | (c as Const (@{const_name case_prod}, _), arg :: args) =>
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
   307
          massage_rec bound_Ts
57895
a85e0ab840c1 less aggressive unfolding; removed debugging;
blanchet
parents: 57551
diff changeset
   308
            (unfold_splits_lets (Term.list_comb (c $ Envir.eta_long bound_Ts arg, args)))
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   309
        | (Const (c, _), args as _ :: _ :: _) =>
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   310
          (case try strip_fun_type (Sign.the_const_type thy c) of
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   311
            SOME (gen_branch_Ts, gen_body_fun_T) =>
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   312
            let
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   313
              val gen_branch_ms = map num_binder_types gen_branch_Ts;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   314
              val n = length gen_branch_ms;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   315
            in
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   316
              if n < length args then
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   317
                (case gen_body_fun_T of
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   318
                  Type (_, [Type (T_name, _), _]) =>
62318
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   319
                  (case case_of ctxt T_name of
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   320
                    SOME (c', has_split_sels) =>
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   321
                    if c' = c then
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   322
                      if has_split_sels then
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   323
                        let
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   324
                          val (branches, obj_leftovers) = chop n args;
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   325
                          val branches' = map2 (massage_abs bound_Ts) gen_branch_ms branches;
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   326
                          val branch_Ts' = map typof branches';
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   327
                          val body_T' = snd (strip_typeN (hd gen_branch_ms) (hd branch_Ts'));
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   328
                          val casex' =
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   329
                            Const (c, branch_Ts' ---> map typof obj_leftovers ---> body_T');
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   330
                        in
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   331
                          Term.list_comb (casex',
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   332
                            branches' @ tap (List.app (check_no_call bound_Ts)) obj_leftovers)
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   333
                        end
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   334
                      else
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   335
                        unsupported_case bound_Ts t
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   336
                    else
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   337
                      massage_leaf bound_Ts t
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   338
                  | NONE => massage_leaf bound_Ts t)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   339
                | _ => massage_leaf bound_Ts t)
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   340
              else
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   341
                massage_leaf bound_Ts t
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   342
            end
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   343
          | NONE => massage_leaf bound_Ts t)
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   344
        | _ => massage_leaf bound_Ts t)
55342
blanchet
parents: 55341
diff changeset
   345
      end;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   346
  in
59596
c067eba942e7 no quick_and_dirty for goals that may fail + tuned messages
blanchet
parents: 59595
diff changeset
   347
    massage_rec bound_Ts t0
59612
7ea413656b64 avoid needless 'if ... undefined' in generated theorems
blanchet
parents: 59609
diff changeset
   348
    |> Term.map_aterms (fn t =>
7ea413656b64 avoid needless 'if ... undefined' in generated theorems
blanchet
parents: 59609
diff changeset
   349
      if Term.is_dummy_pattern t then Const (@{const_name undefined}, fastype_of t) else t)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   350
  end;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   351
60001
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   352
fun massage_let_if_case_corec ctxt has_call massage_leaf bound_Ts t0 =
62318
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   353
  massage_let_if_case ctxt has_call massage_leaf (K (unexpected_corec_call ctxt [t0]))
b42858e540bb clearer error message
blanchet
parents: 61841
diff changeset
   354
    (K (unsupported_case_around_corec_call ctxt [t0])) bound_Ts t0;
60001
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   355
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   356
fun massage_nested_corec_call ctxt has_call massage_call massage_noncall bound_Ts U T t0 =
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   357
  let
59596
c067eba942e7 no quick_and_dirty for goals that may fail + tuned messages
blanchet
parents: 59595
diff changeset
   358
    fun check_no_call t = if has_call t then unexpected_corec_call ctxt [t0] t else ();
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   359
59609
7892ffd1c39d deal better with corecursion through functions
blanchet
parents: 59608
diff changeset
   360
    fun massage_mutual_call bound_Ts (Type (@{type_name fun}, [_, U2]))
7892ffd1c39d deal better with corecursion through functions
blanchet
parents: 59608
diff changeset
   361
        (Type (@{type_name fun}, [T1, T2])) t =
7892ffd1c39d deal better with corecursion through functions
blanchet
parents: 59608
diff changeset
   362
        Abs (Name.uu, T1, massage_mutual_call bound_Ts U2 T2 (incr_boundvars 1 t $ Bound 0))
7892ffd1c39d deal better with corecursion through functions
blanchet
parents: 59608
diff changeset
   363
      | massage_mutual_call bound_Ts U T t =
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   364
        (if has_call t then massage_call else massage_noncall) bound_Ts U T t;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   365
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   366
    fun massage_map bound_Ts (Type (_, Us)) (Type (s, Ts)) t =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   367
        (case try (dest_map ctxt s) t of
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   368
          SOME (map0, fs) =>
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   369
          let
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   370
            val Type (_, dom_Ts) = domain_type (fastype_of1 (bound_Ts, t));
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   371
            val map' = mk_map (length fs) dom_Ts Us map0;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   372
            val fs' =
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
   373
              map_flattened_map_args ctxt s (@{map 3} (massage_map_or_map_arg bound_Ts) Us Ts) fs;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   374
          in
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   375
            Term.list_comb (map', fs')
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   376
          end
58223
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
   377
        | NONE => raise NO_MAP t)
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
   378
      | massage_map _ _ _ t = raise NO_MAP t
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   379
    and massage_map_or_map_arg bound_Ts U T t =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   380
      if T = U then
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   381
        tap check_no_call t
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   382
      else
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   383
        massage_map bound_Ts U T t
58223
ba7a2d19880c export useful functions for users of (co)recursors
blanchet
parents: 58211
diff changeset
   384
        handle NO_MAP _ => massage_mutual_fun bound_Ts U T t
55339
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   385
    and massage_mutual_fun bound_Ts U T t =
60741
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   386
      let
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   387
        val j = Term.maxidx_of_term t + 1;
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   388
        val var = Var ((Name.uu, j), domain_type (fastype_of1 (bound_Ts, t)));
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   389
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   390
        fun massage_body () =
59947
09317aff0ff9 generalized code
blanchet
parents: 59946
diff changeset
   391
          Term.lambda var (Term.incr_boundvars 1 (massage_any_call bound_Ts U T
60741
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   392
            (betapply (t, var))));
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   393
      in
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   394
        (case t of
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   395
          Const (@{const_name comp}, _) $ t1 $ t2 =>
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   396
          if has_call t2 then massage_body ()
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   397
          else mk_comp bound_Ts (massage_mutual_fun bound_Ts U T t1, t2)
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   398
        | _ => massage_body ())
6349a28af772 made code less loopy
blanchet
parents: 60739
diff changeset
   399
      end
59947
09317aff0ff9 generalized code
blanchet
parents: 59946
diff changeset
   400
    and massage_any_call bound_Ts U T =
60001
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   401
      massage_let_if_case_corec ctxt has_call (fn bound_Ts => fn t =>
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   402
        if has_call t then
54955
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   403
          (case U of
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   404
            Type (s, Us) =>
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   405
            (case try (dest_ctr ctxt s) t of
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   406
              SOME (f, args) =>
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   407
              let
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   408
                val typof = curry fastype_of1 bound_Ts;
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   409
                val f' = mk_ctr Us f
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   410
                val f'_T = typof f';
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   411
                val arg_Ts = map typof args;
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   412
              in
59598
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
   413
                Term.list_comb (f',
59947
09317aff0ff9 generalized code
blanchet
parents: 59946
diff changeset
   414
                  @{map 3} (massage_any_call bound_Ts) (binder_types f'_T) arg_Ts args)
54955
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   415
              end
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   416
            | NONE =>
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   417
              (case t of
61424
c3658c18b7bc prod_case as canonical name for product type eliminator
haftmann
parents: 61348
diff changeset
   418
                Const (@{const_name case_prod}, _) $ t' =>
54955
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   419
                let
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   420
                  val U' = curried_type U;
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   421
                  val T' = curried_type T;
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   422
                in
61424
c3658c18b7bc prod_case as canonical name for product type eliminator
haftmann
parents: 61348
diff changeset
   423
                  Const (@{const_name case_prod}, U' --> U) $ massage_any_call bound_Ts U' T' t'
54955
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   424
                end
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   425
              | t1 $ t2 =>
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   426
                (if has_call t2 then
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   427
                   massage_mutual_call bound_Ts U T t
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   428
                 else
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   429
                   massage_map bound_Ts U T t1 $ t2
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   430
                   handle NO_MAP _ => massage_mutual_call bound_Ts U T t)
54955
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   431
              | Abs (s, T', t') =>
59947
09317aff0ff9 generalized code
blanchet
parents: 59946
diff changeset
   432
                Abs (s, T', massage_any_call (T' :: bound_Ts) (range_type U) (range_type T) t')
54955
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   433
              | _ => massage_mutual_call bound_Ts U T t))
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   434
          | _ => ill_formed_corec_call ctxt t)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   435
        else
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   436
          massage_noncall bound_Ts U T t) bound_Ts;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   437
  in
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   438
    (if has_call t0 then massage_any_call else massage_noncall) bound_Ts U T t0
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   439
  end;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   440
60683
d34e1b0b331a tuned ML signature
blanchet
parents: 60362
diff changeset
   441
fun expand_to_ctr_term ctxt (T as Type (s, Ts)) t =
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   442
  (case ctr_sugar_of ctxt s of
60683
d34e1b0b331a tuned ML signature
blanchet
parents: 60362
diff changeset
   443
    SOME {ctrs, casex, ...} => Term.list_comb (mk_case Ts T casex, map (mk_ctr Ts) ctrs) $ t
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   444
  | NONE => raise Fail "expand_to_ctr_term");
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   445
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   446
fun expand_corec_code_rhs ctxt has_call bound_Ts t =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   447
  (case fastype_of1 (bound_Ts, t) of
60683
d34e1b0b331a tuned ML signature
blanchet
parents: 60362
diff changeset
   448
    T as Type (s, _) =>
60001
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   449
    massage_let_if_case_corec ctxt has_call (fn _ => fn t =>
60683
d34e1b0b331a tuned ML signature
blanchet
parents: 60362
diff changeset
   450
      if can (dest_ctr ctxt s) t then t else expand_to_ctr_term ctxt T t) bound_Ts t
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   451
  | _ => raise Fail "expand_corec_code_rhs");
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   452
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   453
fun massage_corec_code_rhs ctxt massage_ctr =
60001
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   454
  massage_let_if_case_corec ctxt (K false)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   455
    (fn bound_Ts => uncurry (massage_ctr bound_Ts) o Term.strip_comb);
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   456
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   457
fun fold_rev_corec_code_rhs ctxt f =
55341
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
   458
  fold_rev_let_if_case ctxt (fn conds => uncurry (f conds) o Term.strip_comb);
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   459
55400
blanchet
parents: 55344
diff changeset
   460
fun case_thms_of_term ctxt t =
blanchet
parents: 55344
diff changeset
   461
  let val ctr_sugars = map_filter (Ctr_Sugar.ctr_sugar_of_case ctxt o fst) (Term.add_consts t []) in
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   462
    (maps #distincts ctr_sugars, maps #discIs ctr_sugars, maps #exhaust_discs ctr_sugars,
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   463
     maps #split_sels ctr_sugars, maps #split_sel_asms ctr_sugars)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   464
  end;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   465
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   466
fun basic_corec_specs_of ctxt res_T =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   467
  (case res_T of
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   468
    Type (T_name, _) =>
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   469
    (case Ctr_Sugar.ctr_sugar_of ctxt T_name of
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   470
      NONE => not_codatatype ctxt res_T
58187
d2ddd401d74d fixed infinite loops in 'register' functions + more uniform API
blanchet
parents: 58131
diff changeset
   471
    | SOME {T = fpT, ctrs, discs, selss, ...} =>
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   472
      let
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   473
        val thy = Proof_Context.theory_of ctxt;
54272
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
   474
58187
d2ddd401d74d fixed infinite loops in 'register' functions + more uniform API
blanchet
parents: 58131
diff changeset
   475
        val As_rho = tvar_subst thy [fpT] [res_T];
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   476
        val substA = Term.subst_TVars As_rho;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   477
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   478
        fun mk_spec ctr disc sels = {ctr = substA ctr, disc = substA disc, sels = map substA sels};
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   479
      in
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
   480
        @{map 3} mk_spec ctrs discs selss
54911
6a6980245ce0 robustness
blanchet
parents: 54910
diff changeset
   481
        handle ListPair.UnequalLengths => not_codatatype ctxt res_T
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   482
      end)
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   483
  | _ => not_codatatype ctxt res_T);
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   484
59674
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
   485
fun map_thms_of_type ctxt (Type (s, _)) =
58462
b46874f2090f refactor fp_sugar move theorems
desharna
parents: 58461
diff changeset
   486
    (case fp_sugar_of ctxt s of SOME {fp_bnf_sugar = {map_thms, ...}, ...} => map_thms | NONE => [])
59674
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
   487
  | map_thms_of_type _ _ = [];
54955
cf8d429dc24e reintroduce recursive calls under constructors, taken out in 8dd0e0316881 mainly and in subsequent changes
blanchet
parents: 54954
diff changeset
   488
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   489
structure GFP_Rec_Sugar_Plugin = Plugin(type T = fp_rec_sugar);
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
   490
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   491
fun gfp_rec_sugar_interpretation name f =
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   492
  GFP_Rec_Sugar_Plugin.interpretation name (fn fp_rec_sugar => fn lthy =>
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   493
    f (transfer_fp_rec_sugar (Proof_Context.theory_of lthy) fp_rec_sugar) lthy);
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
   494
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
   495
val interpret_gfp_rec_sugar = GFP_Rec_Sugar_Plugin.data;
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
   496
55772
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   497
fun corec_specs_of bs arg_Ts res_Ts callers callssss0 lthy0 =
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   498
  let
55005
38ea5ee18a06 use the right context in 'unfold_thms id_def'
blanchet
parents: 54979
diff changeset
   499
    val thy = Proof_Context.theory_of lthy0;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   500
57397
5004aca20821 tuned variable names
blanchet
parents: 57303
diff changeset
   501
    val ((missing_res_Ts, perm0_kks, fp_sugars as {fp_nesting_bnfs,
58461
75ee8d49c724 refactor fp_sugar move theorems
desharna
parents: 58460
diff changeset
   502
          fp_co_induct_sugar = {common_co_inducts = common_coinduct_thms, ...}, ...} :: _,
75ee8d49c724 refactor fp_sugar move theorems
desharna
parents: 58460
diff changeset
   503
          (_, gfp_sugar_thms)), lthy) =
58335
a5a3b576fcfb generate 'code' attribute only if 'code' plugin is enabled
blanchet
parents: 58286
diff changeset
   504
      nested_to_mutual_fps (K true) Greatest_FP bs res_Ts callers callssss0 lthy0;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   505
58286
a15731cf1835 compile
blanchet
parents: 58283
diff changeset
   506
    val coinduct_attrs_pair =
a15731cf1835 compile
blanchet
parents: 58283
diff changeset
   507
      (case gfp_sugar_thms of SOME ((_, attrs_pair), _, _, _, _) => attrs_pair | NONE => ([], []));
58283
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
   508
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
   509
    val perm_fp_sugars = sort (int_ord o apply2 #fp_res_index) fp_sugars;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   510
55539
0819931d652d simplified data structure by reducing the incidence of clumsy indices
blanchet
parents: 55538
diff changeset
   511
    val indices = map #fp_res_index fp_sugars;
0819931d652d simplified data structure by reducing the incidence of clumsy indices
blanchet
parents: 55538
diff changeset
   512
    val perm_indices = map #fp_res_index perm_fp_sugars;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   513
58187
d2ddd401d74d fixed infinite loops in 'register' functions + more uniform API
blanchet
parents: 58131
diff changeset
   514
    val perm_fpTs = map #T perm_fp_sugars;
58460
a88eb33058f7 refactor fp_sugar move theorems
desharna
parents: 58459
diff changeset
   515
    val perm_ctrXs_Tsss' =
a88eb33058f7 refactor fp_sugar move theorems
desharna
parents: 58459
diff changeset
   516
      map (repair_nullary_single_ctr o #ctrXs_Tss o #fp_ctr_sugar) perm_fp_sugars;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   517
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   518
    val nn0 = length res_Ts;
58187
d2ddd401d74d fixed infinite loops in 'register' functions + more uniform API
blanchet
parents: 58131
diff changeset
   519
    val nn = length perm_fpTs;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   520
    val kks = 0 upto nn - 1;
55772
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   521
    val perm_ns' = map length perm_ctrXs_Tsss';
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   522
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   523
    val perm_Ts = map #T perm_fp_sugars;
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   524
    val perm_Xs = map #X perm_fp_sugars;
58461
75ee8d49c724 refactor fp_sugar move theorems
desharna
parents: 58460
diff changeset
   525
    val perm_Cs =
75ee8d49c724 refactor fp_sugar move theorems
desharna
parents: 58460
diff changeset
   526
      map (domain_type o body_fun_type o fastype_of o #co_rec o #fp_co_induct_sugar) perm_fp_sugars;
55772
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   527
    val Xs_TCs = perm_Xs ~~ (perm_Ts ~~ perm_Cs);
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   528
55772
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   529
    fun zip_corecT (Type (s, Us)) = [Type (s, map (mk_sumTN o zip_corecT) Us)]
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   530
      | zip_corecT U =
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   531
        (case AList.lookup (op =) Xs_TCs U of
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   532
          SOME (T, C) => [T, C]
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   533
        | NONE => [U]);
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   534
55869
54ddb003e128 rationalized internals
blanchet
parents: 55863
diff changeset
   535
    val perm_p_Tss = mk_corec_p_pred_types perm_Cs perm_ns';
55772
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   536
    val perm_f_Tssss =
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   537
      map2 (fn C => map (map (map (curry (op -->) C) o zip_corecT))) perm_Cs perm_ctrXs_Tsss';
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   538
    val perm_q_Tssss =
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
   539
      map (map (map (fn [_] => [] | [_, T] => [mk_pred1T (domain_type T)]))) perm_f_Tssss;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   540
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   541
    val (perm_p_hss, h) = indexedd perm_p_Tss 0;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   542
    val (perm_q_hssss, h') = indexedddd perm_q_Tssss h;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   543
    val (perm_f_hssss, _) = indexedddd perm_f_Tssss h';
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   544
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   545
    val fun_arg_hs =
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
   546
      flat (@{map 3} flat_corec_preds_predsss_gettersss perm_p_hss perm_q_hssss perm_f_hssss);
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   547
55480
59cc4a8bc28a allow different functions to recurse on the same type, like in the old package
blanchet
parents: 55462
diff changeset
   548
    fun unpermute0 perm0_xs = permute_like_unique (op =) perm0_kks kks perm0_xs;
59cc4a8bc28a allow different functions to recurse on the same type, like in the old package
blanchet
parents: 55462
diff changeset
   549
    fun unpermute perm_xs = permute_like_unique (op =) perm_indices indices perm_xs;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   550
55539
0819931d652d simplified data structure by reducing the incidence of clumsy indices
blanchet
parents: 55538
diff changeset
   551
    val coinduct_thmss = map (unpermute0 o conj_dests nn) common_coinduct_thms;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   552
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   553
    val p_iss = map (map (find_index_eq fun_arg_hs)) (unpermute perm_p_hss);
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   554
    val q_issss = map (map (map (map (find_index_eq fun_arg_hs)))) (unpermute perm_q_hssss);
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   555
    val f_issss = map (map (map (map (find_index_eq fun_arg_hs)))) (unpermute perm_f_hssss);
53358
b46e6cd75dc6 improved interfaces
panny
parents: 53357
diff changeset
   556
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   557
    val f_Tssss = unpermute perm_f_Tssss;
58187
d2ddd401d74d fixed infinite loops in 'register' functions + more uniform API
blanchet
parents: 58131
diff changeset
   558
    val fpTs = unpermute perm_fpTs;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   559
    val Cs = unpermute perm_Cs;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   560
58187
d2ddd401d74d fixed infinite loops in 'register' functions + more uniform API
blanchet
parents: 58131
diff changeset
   561
    val As_rho = tvar_subst thy (take nn0 fpTs) res_Ts;
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   562
    val Cs_rho = map (fst o dest_TVar) Cs ~~ pad_list HOLogic.unitT nn arg_Ts;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   563
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   564
    val substA = Term.subst_TVars As_rho;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   565
    val substAT = Term.typ_subst_TVars As_rho;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   566
    val substCT = Term.typ_subst_TVars Cs_rho;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   567
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   568
    val perm_Cs' = map substCT perm_Cs;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   569
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   570
    fun call_of nullary [] [g_i] [Type (@{type_name fun}, [_, T])] =
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   571
        (if exists_subtype_in Cs T then Nested_Corec
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   572
         else if nullary then Dummy_No_Corec
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   573
         else No_Corec) g_i
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   574
      | call_of _ [q_i] [g_i, g_i'] _ = Mutual_Corec (q_i, g_i, g_i');
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   575
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   576
    fun mk_ctr_spec ctr disc sels p_io q_iss f_iss f_Tss discI sel_thms distinct_discss collapse
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   577
        corec_thm corec_disc corec_sels =
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   578
      let val nullary = not (can dest_funT (fastype_of ctr)) in
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
   579
        {ctr = substA ctr, disc = substA disc, sels = map substA sels, pred = p_io,
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
   580
         calls = @{map 3} (call_of nullary) q_iss f_iss f_Tss, discI = discI, sel_thms = sel_thms,
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   581
         distinct_discss = distinct_discss, collapse = collapse, corec_thm = corec_thm,
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   582
         corec_disc = corec_disc, corec_sels = corec_sels}
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   583
      end;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   584
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   585
    fun mk_ctr_specs ({ctrs, discs, selss, discIs, sel_thmss, distinct_discsss, collapses, ...}
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   586
        : ctr_sugar) p_is q_isss f_isss f_Tsss corec_thms corec_discs corec_selss =
55863
fa3a1ec69a1b rationalize internals
blanchet
parents: 55860
diff changeset
   587
      let val p_ios = map SOME p_is @ [NONE] in
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
   588
        @{map 14} mk_ctr_spec ctrs discs selss p_ios q_isss f_isss f_Tsss discIs sel_thmss
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   589
          distinct_discsss collapses corec_thms corec_discs corec_selss
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   590
      end;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   591
58461
75ee8d49c724 refactor fp_sugar move theorems
desharna
parents: 58460
diff changeset
   592
    fun mk_spec ({T, fp_ctr_sugar = {ctr_sugar as {exhaust_discs, sel_defs, ...}, ...},
75ee8d49c724 refactor fp_sugar move theorems
desharna
parents: 58460
diff changeset
   593
        fp_co_induct_sugar = {co_rec = corec, co_rec_thms = corec_thms, co_rec_discs = corec_discs,
58459
f70bffabd7cf refactor fp_sugar move theorems
desharna
parents: 58394
diff changeset
   594
        co_rec_selss = corec_selss, ...}, ...} : fp_sugar) p_is q_isss f_isss f_Tsss =
59598
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
   595
      {T = T, corec = mk_co_rec thy Greatest_FP perm_Cs' (substAT T) corec,
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
   596
       exhaust_discs = exhaust_discs, sel_defs = sel_defs,
59674
198eaf28a8b8 export more functions (for future 'corec')
blanchet
parents: 59673
diff changeset
   597
       fp_nesting_maps = maps (map_thms_of_type lthy o T_of_bnf) fp_nesting_bnfs,
57399
cfc19f0a6261 compile
blanchet
parents: 57397
diff changeset
   598
       fp_nesting_map_ident0s = map map_ident0_of_bnf fp_nesting_bnfs,
57397
5004aca20821 tuned variable names
blanchet
parents: 57303
diff changeset
   599
       fp_nesting_map_comps = map map_comp_of_bnf fp_nesting_bnfs,
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   600
       ctr_specs = mk_ctr_specs ctr_sugar p_is q_isss f_isss f_Tsss corec_thms corec_discs
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
   601
         corec_selss};
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   602
  in
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
   603
    (@{map 5} mk_spec fp_sugars p_iss q_issss f_issss f_Tssss, missing_res_Ts,
58283
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
   604
     co_induct_of common_coinduct_thms, strong_co_induct_of common_coinduct_thms,
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
   605
     co_induct_of coinduct_thmss, strong_co_induct_of coinduct_thmss, coinduct_attrs_pair,
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
   606
     is_some gfp_sugar_thms, lthy)
54246
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   607
  end;
8fdb4dc08ed1 split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet
parents: 54243
diff changeset
   608
53358
b46e6cd75dc6 improved interfaces
panny
parents: 53357
diff changeset
   609
val undef_const = Const (@{const_name undefined}, dummyT);
53357
46b0c7a08af7 simplified rewriting of map arguments
panny
parents: 53354
diff changeset
   610
58393
blanchet
parents: 58387
diff changeset
   611
type coeqn_data_disc =
blanchet
parents: 58387
diff changeset
   612
  {fun_name: string,
blanchet
parents: 58387
diff changeset
   613
   fun_T: typ,
blanchet
parents: 58387
diff changeset
   614
   fun_args: term list,
blanchet
parents: 58387
diff changeset
   615
   ctr: term,
blanchet
parents: 58387
diff changeset
   616
   ctr_no: int,
blanchet
parents: 58387
diff changeset
   617
   disc: term,
blanchet
parents: 58387
diff changeset
   618
   prems: term list,
blanchet
parents: 58387
diff changeset
   619
   auto_gen: bool,
blanchet
parents: 58387
diff changeset
   620
   ctr_rhs_opt: term option,
blanchet
parents: 58387
diff changeset
   621
   code_rhs_opt: term option,
blanchet
parents: 58387
diff changeset
   622
   eqn_pos: int,
blanchet
parents: 58387
diff changeset
   623
   user_eqn: term};
54001
65fc58793ed5 made SML/NJ happier
blanchet
parents: 53925
diff changeset
   624
58393
blanchet
parents: 58387
diff changeset
   625
type coeqn_data_sel =
blanchet
parents: 58387
diff changeset
   626
  {fun_name: string,
blanchet
parents: 58387
diff changeset
   627
   fun_T: typ,
blanchet
parents: 58387
diff changeset
   628
   fun_args: term list,
blanchet
parents: 58387
diff changeset
   629
   ctr: term,
blanchet
parents: 58387
diff changeset
   630
   sel: term,
blanchet
parents: 58387
diff changeset
   631
   rhs_term: term,
blanchet
parents: 58387
diff changeset
   632
   ctr_rhs_opt: term option,
blanchet
parents: 58387
diff changeset
   633
   code_rhs_opt: term option,
blanchet
parents: 58387
diff changeset
   634
   eqn_pos: int,
blanchet
parents: 58387
diff changeset
   635
   user_eqn: term};
54001
65fc58793ed5 made SML/NJ happier
blanchet
parents: 53925
diff changeset
   636
59602
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
   637
fun ctr_sel_of ({ctr, sel, ...} : coeqn_data_sel) = (ctr, sel);
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
   638
54153
67487a607ce2 avoid 'co_' prefix with underscore meaning 'co', since it is our only possible identifier representation of '(co)'
blanchet
parents: 54145
diff changeset
   639
datatype coeqn_data =
67487a607ce2 avoid 'co_' prefix with underscore meaning 'co', since it is our only possible identifier representation of '(co)'
blanchet
parents: 54145
diff changeset
   640
  Disc of coeqn_data_disc |
67487a607ce2 avoid 'co_' prefix with underscore meaning 'co', since it is our only possible identifier representation of '(co)'
blanchet
parents: 54145
diff changeset
   641
  Sel of coeqn_data_sel;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   642
59948
c8860ec6fc80 generalized slightly
blanchet
parents: 59947
diff changeset
   643
fun is_free_in frees (Free (s, _)) = member (op =) frees s
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   644
  | is_free_in _ _ = false;
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   645
59948
c8860ec6fc80 generalized slightly
blanchet
parents: 59947
diff changeset
   646
fun is_catch_all_prem (Free (s, _)) = s = Name.uu_
59799
0b21e85fd9ba clarified role of Name.uu_, which happens to be the internal replacement of the first underscore under certain assumptions about the context;
wenzelm
parents: 59674
diff changeset
   647
  | is_catch_all_prem _ = false;
0b21e85fd9ba clarified role of Name.uu_, which happens to be the internal replacement of the first underscore under certain assumptions about the context;
wenzelm
parents: 59674
diff changeset
   648
59599
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   649
fun add_extra_frees ctxt frees names =
59948
c8860ec6fc80 generalized slightly
blanchet
parents: 59947
diff changeset
   650
  fold_aterms (fn x as Free (s, _) =>
c8860ec6fc80 generalized slightly
blanchet
parents: 59947
diff changeset
   651
    (not (member (op =) frees x) andalso not (member (op =) names s) andalso
c8860ec6fc80 generalized slightly
blanchet
parents: 59947
diff changeset
   652
     not (Variable.is_fixed ctxt s) andalso not (is_catch_all_prem x))
59599
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   653
    ? cons x | _ => I);
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   654
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   655
fun check_extra_frees ctxt frees names t =
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   656
  let val bads = add_extra_frees ctxt frees names t [] in
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   657
    null bads orelse extra_variable ctxt [t] (hd bads)
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   658
  end;
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   659
59604
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   660
fun check_fun_args ctxt eqn fun_args =
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   661
  let
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   662
    val dups = duplicates (op =) fun_args;
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   663
    val _ = null dups orelse error_at ctxt [eqn]
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   664
        ("Duplicate variable " ^ quote (Syntax.string_of_term ctxt (hd dups)));
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   665
59607
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
   666
    val _ = forall is_Free fun_args orelse
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
   667
      error_at ctxt [eqn] ("Non-variable function argument on left-hand side " ^
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
   668
        quote (Syntax.string_of_term ctxt (the (find_first (not o is_Free) fun_args))));
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
   669
59604
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   670
    val fixeds = filter (Variable.is_fixed ctxt o fst o dest_Free) fun_args;
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   671
    val _ = null fixeds orelse error_at ctxt [eqn] ("Function argument " ^
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   672
        quote (Syntax.string_of_term ctxt (hd fixeds)) ^ " is fixed in context");
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   673
  in () end;
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   674
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   675
fun dissect_coeqn_disc ctxt fun_names sequentials
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   676
    (basic_ctr_specss : basic_corec_ctr_spec list list) eqn_pos ctr_rhs_opt code_rhs_opt prems0
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   677
    concl matchedsss =
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   678
  let
54272
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
   679
    fun find_subterm p =
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
   680
      let (* FIXME \<exists>? *)
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
   681
        fun find (t as u $ v) = if p t then SOME t else merge_options (find u, find v)
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
   682
          | find t = if p t then SOME t else NONE;
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
   683
      in find end;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   684
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   685
    val applied_fun = concl
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
   686
      |> find_subterm (member (op = o apsnd SOME) fun_names o try (fst o dest_Free o head_of))
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   687
      |> the
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   688
      handle Option.Option => error_at ctxt [concl] "Ill-formed discriminator formula";
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
   689
    val ((fun_name, fun_T), fun_args) = strip_comb applied_fun |>> dest_Free;
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   690
59604
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   691
    val _ = check_fun_args ctxt concl fun_args;
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   692
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   693
    val bads = filter (Term.exists_subterm (is_free_in fun_names)) prems0;
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   694
    val _ = null bads orelse error_at ctxt bads "Corecursive call(s) in condition(s)";
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   695
58393
blanchet
parents: 58387
diff changeset
   696
    val (sequential, basic_ctr_specs) =
blanchet
parents: 58387
diff changeset
   697
      the (AList.lookup (op =) (fun_names ~~ (sequentials ~~ basic_ctr_specss)) fun_name);
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   698
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
   699
    val discs = map #disc basic_ctr_specs;
a179353111db generate callssss
panny
parents: 54157
diff changeset
   700
    val ctrs = map #ctr basic_ctr_specs;
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   701
    val not_disc = head_of concl = @{term Not};
53401
2101a97e6220 various refactoring;
panny
parents: 53360
diff changeset
   702
    val _ = not_disc andalso length ctrs <> 2 andalso
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   703
      error_at ctxt [concl] "Negated discriminator for a type with \<noteq> 2 constructors";
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
   704
    val disc' = find_subterm (member (op =) discs o head_of) concl;
54209
blanchet
parents: 54208
diff changeset
   705
    val eq_ctr0 = concl |> perhaps (try HOLogic.dest_not) |> try (HOLogic.dest_eq #> snd)
59598
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
   706
      |> (fn SOME t => let val n = find_index (curry (op =) t) ctrs in
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
   707
        if n >= 0 then SOME n else NONE end | _ => NONE);
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   708
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   709
    val _ = is_none disc' orelse perhaps (try HOLogic.dest_not) concl = the disc' orelse
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   710
      error_at ctxt [concl] "Ill-formed discriminator formula";
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   711
    val _ = is_some disc' orelse is_some eq_ctr0 orelse
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   712
      error_at ctxt [concl] "No discriminator in equation";
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   713
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   714
    val ctr_no' =
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
   715
      if is_none disc' then the eq_ctr0 else find_index (curry (op =) (head_of (the disc'))) discs;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   716
    val ctr_no = if not_disc then 1 - ctr_no' else ctr_no';
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
   717
    val {ctr, disc, ...} = nth basic_ctr_specs ctr_no;
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   718
59605
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   719
    val catch_all =
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   720
      (case prems0 of
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   721
        [prem] => is_catch_all_prem prem
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   722
      | _ =>
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   723
        if exists is_catch_all_prem prems0 then error_at ctxt [concl] "Superfluous premises"
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   724
        else false);
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
   725
    val matchedss = AList.lookup (op =) matchedsss fun_name |> the_default [];
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   726
    val prems = map (abstract_over_list fun_args) prems0;
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
   727
    val actual_prems =
54901
0b8871677e0b use same name for feature internally as in user interface, to facilitate grepping
blanchet
parents: 54900
diff changeset
   728
      (if catch_all orelse sequential then maps s_not_conj matchedss else []) @
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   729
      (if catch_all then [] else prems);
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   730
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
   731
    val matchedsss' = AList.delete (op =) fun_name matchedsss
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
   732
      |> cons (fun_name, if sequential then matchedss @ [prems] else matchedss @ [actual_prems]);
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   733
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   734
    val user_eqn =
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
   735
      (actual_prems, concl)
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   736
      |>> map HOLogic.mk_Trueprop ||> HOLogic.mk_Trueprop o abstract_over_list fun_args
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
   737
      |> curry Logic.list_all (map dest_Free fun_args) o Logic.list_implies;
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   738
59599
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   739
    val _ = check_extra_frees ctxt fun_args fun_names user_eqn;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   740
  in
58393
blanchet
parents: 58387
diff changeset
   741
    (Disc {fun_name = fun_name, fun_T = fun_T, fun_args = fun_args, ctr = ctr, ctr_no = ctr_no,
blanchet
parents: 58387
diff changeset
   742
       disc = disc, prems = actual_prems, auto_gen = catch_all, ctr_rhs_opt = ctr_rhs_opt,
blanchet
parents: 58387
diff changeset
   743
       code_rhs_opt = code_rhs_opt, eqn_pos = eqn_pos, user_eqn = user_eqn},
blanchet
parents: 58387
diff changeset
   744
     matchedsss')
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   745
  end;
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   746
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   747
fun dissect_coeqn_sel ctxt fun_names (basic_ctr_specss : basic_corec_ctr_spec list list) eqn_pos
54951
e25b4d22082b for code equations that coincide with ctr equations, make sure the usr's input is preserved for both
blanchet
parents: 54948
diff changeset
   748
    ctr_rhs_opt code_rhs_opt eqn0 of_spec_opt eqn =
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   749
  let
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   750
    val (lhs, rhs) = HOLogic.dest_eq eqn
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   751
      handle TERM _ => error_at ctxt [eqn] "Ill-formed equation (expected \"lhs = rhs\")";
59604
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   752
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   753
    val sel = head_of lhs;
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
   754
    val ((fun_name, fun_T), fun_args) = dest_comb lhs |> snd |> strip_comb |> apfst dest_Free
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   755
      handle TERM _ => error_at ctxt [eqn] "Ill-formed selector argument in left-hand side";
59604
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   756
    val _ = check_fun_args ctxt eqn fun_args;
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   757
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
   758
    val basic_ctr_specs = the (AList.lookup (op =) (fun_names ~~ basic_ctr_specss) fun_name)
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   759
      handle Option.Option => error_at ctxt [eqn] "Ill-formed selector argument in left-hand side";
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
   760
    val {ctr, ...} =
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
   761
      (case of_spec_opt of
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
   762
        SOME of_spec => the (find_first (curry (op =) of_spec o #ctr) basic_ctr_specs)
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
   763
      | NONE => filter (exists (curry (op =) sel) o #sels) basic_ctr_specs |> the_single
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   764
          handle List.Empty => error_at ctxt [eqn] "Ambiguous selector (without \"of\")");
54979
d7593bfccf25 correctly extract code RHS, with loose bound variables
blanchet
parents: 54978
diff changeset
   765
    val user_eqn = drop_all eqn0;
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   766
59599
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   767
    val _ = check_extra_frees ctxt fun_args fun_names user_eqn;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   768
  in
58393
blanchet
parents: 58387
diff changeset
   769
    Sel {fun_name = fun_name, fun_T = fun_T, fun_args = fun_args, ctr = ctr, sel = sel,
blanchet
parents: 58387
diff changeset
   770
      rhs_term = rhs, ctr_rhs_opt = ctr_rhs_opt, code_rhs_opt = code_rhs_opt, eqn_pos = eqn_pos,
blanchet
parents: 58387
diff changeset
   771
      user_eqn = user_eqn}
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   772
  end;
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   773
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   774
fun dissect_coeqn_ctr ctxt fun_names sequentials (basic_ctr_specss : basic_corec_ctr_spec list list)
54951
e25b4d22082b for code equations that coincide with ctr equations, make sure the usr's input is preserved for both
blanchet
parents: 54948
diff changeset
   775
    eqn_pos eqn0 code_rhs_opt prems concl matchedsss =
53910
2c5055a3583d strengthen tactic
blanchet
parents: 53909
diff changeset
   776
  let
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   777
    val (lhs, rhs) = HOLogic.dest_eq concl;
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
   778
    val (fun_name, fun_args) = strip_comb lhs |>> fst o dest_Free;
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   779
59604
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   780
    val _ = check_fun_args ctxt concl fun_args;
59599
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   781
    val _ = check_extra_frees ctxt fun_args fun_names (drop_all eqn0);
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   782
58393
blanchet
parents: 58387
diff changeset
   783
    val basic_ctr_specs = the (AList.lookup (op =) (fun_names ~~ basic_ctr_specss) fun_name);
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
   784
    val (ctr, ctr_args) = strip_comb (unfold_lets_splits rhs);
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
   785
    val {disc, sels, ...} = the (find_first (curry (op =) ctr o #ctr) basic_ctr_specs)
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   786
      handle Option.Option => error_at ctxt [ctr] "Not a constructor";
53341
63015d035301 handle selector formulae with no corecursive calls
panny
parents: 53335
diff changeset
   787
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   788
    val disc_concl = betapply (disc, lhs);
54976
b502f04c0442 repair 'exhaustive' feature for one-constructor types
blanchet
parents: 54975
diff changeset
   789
    val (eqn_data_disc_opt, matchedsss') =
59042
ef0074e812cd smoothly handle unit codatatypes in 'primcorec'
blanchet
parents: 59041
diff changeset
   790
      if null (tl basic_ctr_specs) andalso not (null sels) then
54976
b502f04c0442 repair 'exhaustive' feature for one-constructor types
blanchet
parents: 54975
diff changeset
   791
        (NONE, matchedsss)
b502f04c0442 repair 'exhaustive' feature for one-constructor types
blanchet
parents: 54975
diff changeset
   792
      else
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   793
        apfst SOME (dissect_coeqn_disc ctxt fun_names sequentials basic_ctr_specss eqn_pos
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   794
          (SOME (abstract_over_list fun_args rhs)) code_rhs_opt prems disc_concl matchedsss);
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   795
54159
eb5d58c99049 set stage for more flexible 'primrec' syntax for recursion through functions
blanchet
parents: 54157
diff changeset
   796
    val sel_concls = sels ~~ ctr_args
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   797
      |> map (fn (sel, ctr_arg) => HOLogic.mk_eq (betapply (sel, lhs), ctr_arg))
59595
2d90b85b9264 tuned new primrec messages
blanchet
parents: 59594
diff changeset
   798
      handle ListPair.UnequalLengths =>
2d90b85b9264 tuned new primrec messages
blanchet
parents: 59594
diff changeset
   799
        error_at ctxt [rhs] "Partially applied constructor in right-hand side";
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   800
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
   801
    val eqns_data_sel =
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   802
      map (dissect_coeqn_sel ctxt fun_names basic_ctr_specss eqn_pos
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   803
          (SOME (abstract_over_list fun_args rhs)) code_rhs_opt eqn0 (SOME ctr))
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   804
        sel_concls;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   805
  in
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
   806
    (the_list eqn_data_disc_opt @ eqns_data_sel, matchedsss')
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   807
  end;
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   808
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   809
fun dissect_coeqn_code ctxt has_call fun_names basic_ctr_specss eqn_pos eqn0 concl matchedsss =
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   810
  let
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   811
    val (lhs, (rhs', rhs)) = HOLogic.dest_eq concl ||> `(expand_corec_code_rhs ctxt has_call []);
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
   812
    val (fun_name, fun_args) = strip_comb lhs |>> fst o dest_Free;
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   813
59604
b44f128d24f2 improved primcorec messages
blanchet
parents: 59603
diff changeset
   814
    val _ = check_fun_args ctxt concl fun_args;
59599
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
   815
    val _ = check_extra_frees ctxt fun_args fun_names concl;
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
   816
58393
blanchet
parents: 58387
diff changeset
   817
    val basic_ctr_specs = the (AList.lookup (op =) (fun_names ~~ basic_ctr_specss) fun_name);
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   818
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   819
    val cond_ctrs = fold_rev_corec_code_rhs ctxt (fn cs => fn ctr => fn _ =>
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
   820
        if member (op = o apsnd #ctr) basic_ctr_specs ctr then cons (ctr, cs)
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   821
        else error ("Not a constructor: " ^ quote (Syntax.string_of_term ctxt ctr))) [] rhs' []
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   822
      |> AList.group (op =);
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   823
54068
447354985f6a generate optimized DNF formula
blanchet
parents: 54067
diff changeset
   824
    val ctr_premss = (case cond_ctrs of [_] => [[]] | _ => map (s_dnf o snd) cond_ctrs);
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   825
    val ctr_concls = cond_ctrs |> map (fn (ctr, _) =>
58393
blanchet
parents: 58387
diff changeset
   826
      binder_types (fastype_of ctr)
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   827
      |> map_index (fn (n, T) => massage_corec_code_rhs ctxt (fn _ => fn ctr' => fn args =>
59612
7ea413656b64 avoid needless 'if ... undefined' in generated theorems
blanchet
parents: 59609
diff changeset
   828
        if ctr' = ctr then nth args n else Term.dummy_pattern T) [] rhs')
58393
blanchet
parents: 58387
diff changeset
   829
      |> curry Term.list_comb ctr
blanchet
parents: 58387
diff changeset
   830
      |> curry HOLogic.mk_eq lhs);
54902
a9291e4d2366 internally allow different values for 'sequential' for different constructors
blanchet
parents: 54901
diff changeset
   831
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   832
    val bads = maps (filter (Term.exists_subterm (is_free_in fun_names))) ctr_premss;
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   833
    val _ = null bads orelse unexpected_corec_call ctxt [eqn0] rhs;
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   834
54902
a9291e4d2366 internally allow different values for 'sequential' for different constructors
blanchet
parents: 54901
diff changeset
   835
    val sequentials = replicate (length fun_names) false;
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   836
  in
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   837
    @{fold_map 2} (dissect_coeqn_ctr ctxt fun_names sequentials basic_ctr_specss eqn_pos eqn0
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   838
        (SOME (abstract_over_list fun_args rhs)))
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
   839
      ctr_premss ctr_concls matchedsss
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   840
  end;
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   841
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   842
fun dissect_coeqn ctxt has_call fun_names sequentials
54951
e25b4d22082b for code equations that coincide with ctr equations, make sure the usr's input is preserved for both
blanchet
parents: 54948
diff changeset
   843
    (basic_ctr_specss : basic_corec_ctr_spec list list) (eqn_pos, eqn0) of_spec_opt matchedsss =
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   844
  let
54979
d7593bfccf25 correctly extract code RHS, with loose bound variables
blanchet
parents: 54978
diff changeset
   845
    val eqn = drop_all eqn0
59600
1716da11a11c more precise primcorec messages
blanchet
parents: 59599
diff changeset
   846
      handle TERM _ => error_at ctxt [eqn0] "Ill-formed formula";
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   847
    val (prems, concl) = Logic.strip_horn eqn
57527
1b07ca054327 add helper function map_prod
desharna
parents: 57399
diff changeset
   848
      |> map_prod (map HOLogic.dest_Trueprop) HOLogic.dest_Trueprop
59607
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
   849
        handle TERM _ => error_at ctxt [eqn] "Ill-formed equation";
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   850
54065
e30e63d05e58 process code-style inputs
panny
parents: 54044
diff changeset
   851
    val head = concl
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   852
      |> perhaps (try HOLogic.dest_not) |> perhaps (try (fst o HOLogic.dest_eq))
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   853
      |> head_of;
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   854
59601
25ae098d8de2 more precise primcorec messages
blanchet
parents: 59600
diff changeset
   855
    val rhs_opt = concl |> perhaps (try HOLogic.dest_not) |> try (HOLogic.dest_eq #> snd);
59605
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   856
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   857
    fun check_num_args () =
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   858
      is_none rhs_opt orelse not (can dest_funT (fastype_of (the rhs_opt))) orelse
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   859
        error_at ctxt [eqn] "Expected more arguments to function on left-hand side";
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   860
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
   861
    val discs = maps (map #disc) basic_ctr_specss;
a179353111db generate callssss
panny
parents: 54157
diff changeset
   862
    val sels = maps (maps #sels) basic_ctr_specss;
a179353111db generate callssss
panny
parents: 54157
diff changeset
   863
    val ctrs = maps (map #ctr) basic_ctr_specss;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   864
  in
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   865
    if member (op =) discs head orelse
58393
blanchet
parents: 58387
diff changeset
   866
       (is_some rhs_opt andalso
blanchet
parents: 58387
diff changeset
   867
        member (op =) (map SOME fun_names) (try (fst o dest_Free) head) andalso
blanchet
parents: 58387
diff changeset
   868
        member (op =) (filter (null o binder_types o fastype_of) ctrs) (the rhs_opt)) then
59608
e41ac095f99d removed too strict checks
blanchet
parents: 59607
diff changeset
   869
      (dissect_coeqn_disc ctxt fun_names sequentials basic_ctr_specss eqn_pos NONE NONE prems concl
59605
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   870
         matchedsss
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   871
       |>> single)
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   872
    else if member (op =) sels head then
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   873
      (null prems orelse error_at ctxt [eqn] "Unexpected condition in selector formula";
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   874
       ([dissect_coeqn_sel ctxt fun_names basic_ctr_specss eqn_pos NONE NONE eqn0 of_spec_opt
57550
934a54d04a9a throw error for bad input
panny
parents: 57527
diff changeset
   875
           concl], matchedsss))
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   876
    else if is_some rhs_opt andalso is_Free head andalso is_free_in fun_names head then
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
   877
      if member (op =) ctrs (head_of (unfold_lets_splits (the rhs_opt))) then
59605
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   878
        (check_num_args ();
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   879
         dissect_coeqn_ctr ctxt fun_names sequentials basic_ctr_specss eqn_pos eqn0
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   880
           (if null prems then
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   881
              SOME (snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (Logic.strip_assums_concl eqn0))))
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   882
            else
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   883
              NONE)
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   884
           prems concl matchedsss)
54951
e25b4d22082b for code equations that coincide with ctr equations, make sure the usr's input is preserved for both
blanchet
parents: 54948
diff changeset
   885
      else if null prems then
59605
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   886
        (check_num_args ();
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   887
         dissect_coeqn_code ctxt has_call fun_names basic_ctr_specss eqn_pos eqn0 concl matchedsss
bd66d9b93a6b improved primcorec messages
blanchet
parents: 59604
diff changeset
   888
         |>> flat)
54951
e25b4d22082b for code equations that coincide with ctr equations, make sure the usr's input is preserved for both
blanchet
parents: 54948
diff changeset
   889
      else
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   890
        error_at ctxt [eqn] "Cannot mix constructor and code views"
59600
1716da11a11c more precise primcorec messages
blanchet
parents: 59599
diff changeset
   891
    else if is_some rhs_opt then
59607
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
   892
      error_at ctxt [eqn] ("Ill-formed equation head: " ^ quote (Syntax.string_of_term ctxt head))
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   893
    else
59607
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
   894
      error_at ctxt [eqn] "Expected equation or discriminator formula"
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   895
  end;
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   896
54002
01c8f9d3b084 made SML/NJ happy
blanchet
parents: 54001
diff changeset
   897
fun build_corec_arg_disc (ctr_specs : corec_ctr_spec list)
54153
67487a607ce2 avoid 'co_' prefix with underscore meaning 'co', since it is our only possible identifier representation of '(co)'
blanchet
parents: 54145
diff changeset
   898
    ({fun_args, ctr_no, prems, ...} : coeqn_data_disc) =
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
   899
  if is_none (#pred (nth ctr_specs ctr_no)) then
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
   900
    I
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
   901
  else
54068
447354985f6a generate optimized DNF formula
blanchet
parents: 54067
diff changeset
   902
    s_conjs prems
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   903
    |> curry subst_bounds (List.rev fun_args)
55969
8820ddb8f9f4 use balanced tuples in 'primcorec'
blanchet
parents: 55966
diff changeset
   904
    |> abs_tuple_balanced fun_args
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   905
    |> K |> nth_map (the (#pred (nth ctr_specs ctr_no)));
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   906
54153
67487a607ce2 avoid 'co_' prefix with underscore meaning 'co', since it is our only possible identifier representation of '(co)'
blanchet
parents: 54145
diff changeset
   907
fun build_corec_arg_no_call (sel_eqns : coeqn_data_sel list) sel =
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
   908
  find_first (curry (op =) sel o #sel) sel_eqns
55969
8820ddb8f9f4 use balanced tuples in 'primcorec'
blanchet
parents: 55966
diff changeset
   909
  |> try (fn SOME {fun_args, rhs_term, ...} => abs_tuple_balanced fun_args rhs_term)
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
   910
  |> the_default undef_const
53411
ab4edf89992f support indirect corecursion
panny
parents: 53401
diff changeset
   911
  |> K;
53360
7ffc4a746a73 handle direct corecursion
panny
parents: 53358
diff changeset
   912
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   913
fun build_corec_args_mutual_call ctxt has_call (sel_eqns : coeqn_data_sel list) sel =
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
   914
  (case find_first (curry (op =) sel o #sel) sel_eqns of
54208
blanchet
parents: 54207
diff changeset
   915
    NONE => (I, I, I)
blanchet
parents: 54207
diff changeset
   916
  | SOME {fun_args, rhs_term, ... } =>
53876
fabf04d43a75 simplified code
panny
parents: 53875
diff changeset
   917
    let
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
   918
      val bound_Ts = List.rev (map fastype_of fun_args);
59946
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   919
54207
9296ebf40db0 tuned names (to make them independent from temporary naming convention used in characteristic theorems)
blanchet
parents: 54206
diff changeset
   920
      fun rewrite_stop _ t = if has_call t then @{term False} else @{term True};
9296ebf40db0 tuned names (to make them independent from temporary naming convention used in characteristic theorems)
blanchet
parents: 54206
diff changeset
   921
      fun rewrite_end _ t = if has_call t then undef_const else t;
9296ebf40db0 tuned names (to make them independent from temporary naming convention used in characteristic theorems)
blanchet
parents: 54206
diff changeset
   922
      fun rewrite_cont bound_Ts t =
55969
8820ddb8f9f4 use balanced tuples in 'primcorec'
blanchet
parents: 55966
diff changeset
   923
        if has_call t then mk_tuple1_balanced bound_Ts (snd (strip_comb t)) else undef_const;
60001
0e1b220ec4c9 generalized code
blanchet
parents: 59989
diff changeset
   924
      fun massage f _ = massage_let_if_case_corec ctxt has_call f bound_Ts rhs_term
55969
8820ddb8f9f4 use balanced tuples in 'primcorec'
blanchet
parents: 55966
diff changeset
   925
        |> abs_tuple_balanced fun_args;
53876
fabf04d43a75 simplified code
panny
parents: 53875
diff changeset
   926
    in
54207
9296ebf40db0 tuned names (to make them independent from temporary naming convention used in characteristic theorems)
blanchet
parents: 54206
diff changeset
   927
      (massage rewrite_stop, massage rewrite_end, massage rewrite_cont)
54208
blanchet
parents: 54207
diff changeset
   928
    end);
53360
7ffc4a746a73 handle direct corecursion
panny
parents: 53358
diff changeset
   929
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   930
fun build_corec_arg_nested_call ctxt has_call (sel_eqns : coeqn_data_sel list) sel =
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
   931
  (case find_first (curry (op =) sel o #sel) sel_eqns of
54208
blanchet
parents: 54207
diff changeset
   932
    NONE => I
blanchet
parents: 54207
diff changeset
   933
  | SOME {fun_args, rhs_term, ...} =>
53899
e55b634ff9fb simplified code
panny
parents: 53890
diff changeset
   934
    let
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   935
      fun massage_call bound_Ts U T t0 =
55339
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   936
        let
59946
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   937
          val U2 =
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   938
            (case try dest_sumT U of
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   939
              SOME (U1, U2) => if U1 = T then U2 else invalid_map ctxt t0
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   940
            | NONE => invalid_map ctxt t0);
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   941
59948
c8860ec6fc80 generalized slightly
blanchet
parents: 59947
diff changeset
   942
          fun rewrite bound_Ts (Abs (s, T', t')) = Abs (s, T', rewrite (T' :: bound_Ts) t')
55339
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   943
            | rewrite bound_Ts (t as _ $ _) =
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   944
              let val (u, vs) = strip_comb t in
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   945
                if is_Free u andalso has_call u then
59946
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   946
                  Inr_const T U2 $ mk_tuple1_balanced bound_Ts vs
61424
c3658c18b7bc prod_case as canonical name for product type eliminator
haftmann
parents: 61348
diff changeset
   947
                else if try (fst o dest_Const) u = SOME @{const_name case_prod} then
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
   948
                  map (rewrite bound_Ts) vs |> chop 1
61424
c3658c18b7bc prod_case as canonical name for product type eliminator
haftmann
parents: 61348
diff changeset
   949
                  |>> HOLogic.mk_case_prod o the_single
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
   950
                  |> Term.list_comb
55339
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   951
                else
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
   952
                  Term.list_comb (rewrite bound_Ts u, map (rewrite bound_Ts) vs)
55339
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   953
              end
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   954
            | rewrite _ t =
59946
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   955
              if is_Free t andalso has_call t then Inr_const T U2 $ HOLogic.unit else t;
55339
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   956
          in
59946
c18df9eea901 generalized code
blanchet
parents: 59945
diff changeset
   957
            rewrite bound_Ts t0
55339
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   958
          end;
f09037306f25 properly massage 'if's / 'case's etc. under lambdas
blanchet
parents: 55100
diff changeset
   959
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   960
      fun massage_noncall U T t =
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   961
        build_map ctxt [] (uncurry Inl_const o dest_sumT o snd) (T, U) $ t;
59947
09317aff0ff9 generalized code
blanchet
parents: 59946
diff changeset
   962
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
   963
      val bound_Ts = List.rev (map fastype_of fun_args);
53899
e55b634ff9fb simplified code
panny
parents: 53890
diff changeset
   964
    in
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   965
      fn t =>
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   966
      rhs_term
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
   967
      |> massage_nested_corec_call ctxt has_call massage_call (K massage_noncall) bound_Ts
59989
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   968
        (range_type (fastype_of t)) (fastype_of1 (bound_Ts, rhs_term))
7b80ddb65e3e tuned signature
blanchet
parents: 59948
diff changeset
   969
      |> abs_tuple_balanced fun_args
54208
blanchet
parents: 54207
diff changeset
   970
    end);
53360
7ffc4a746a73 handle direct corecursion
panny
parents: 53358
diff changeset
   971
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   972
fun build_corec_args_sel ctxt has_call (all_sel_eqns : coeqn_data_sel list)
54002
01c8f9d3b084 made SML/NJ happy
blanchet
parents: 54001
diff changeset
   973
    (ctr_spec : corec_ctr_spec) =
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
   974
  (case filter (curry (op =) (#ctr ctr_spec) o #ctr) all_sel_eqns of
54208
blanchet
parents: 54207
diff changeset
   975
    [] => I
blanchet
parents: 54207
diff changeset
   976
  | sel_eqns =>
blanchet
parents: 54207
diff changeset
   977
    let
blanchet
parents: 54207
diff changeset
   978
      val sel_call_list = #sels ctr_spec ~~ #calls ctr_spec;
blanchet
parents: 54207
diff changeset
   979
      val no_calls' = map_filter (try (apsnd (fn No_Corec n => n))) sel_call_list;
blanchet
parents: 54207
diff changeset
   980
      val mutual_calls' = map_filter (try (apsnd (fn Mutual_Corec n => n))) sel_call_list;
blanchet
parents: 54207
diff changeset
   981
      val nested_calls' = map_filter (try (apsnd (fn Nested_Corec n => n))) sel_call_list;
blanchet
parents: 54207
diff changeset
   982
    in
blanchet
parents: 54207
diff changeset
   983
      I
blanchet
parents: 54207
diff changeset
   984
      #> fold (fn (sel, n) => nth_map n (build_corec_arg_no_call sel_eqns sel)) no_calls'
blanchet
parents: 54207
diff changeset
   985
      #> fold (fn (sel, (q, g, h)) =>
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   986
        let val (fq, fg, fh) = build_corec_args_mutual_call ctxt has_call sel_eqns sel in
54208
blanchet
parents: 54207
diff changeset
   987
          nth_map q fq o nth_map g fg o nth_map h fh end) mutual_calls'
blanchet
parents: 54207
diff changeset
   988
      #> fold (fn (sel, n) => nth_map n
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
   989
        (build_corec_arg_nested_call ctxt has_call sel_eqns sel)) nested_calls'
54208
blanchet
parents: 54207
diff changeset
   990
    end);
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
   991
59673
blanchet
parents: 59662
diff changeset
   992
fun build_defs ctxt bs mxs has_call arg_Tss (corec_specs : corec_spec list)
54153
67487a607ce2 avoid 'co_' prefix with underscore meaning 'co', since it is our only possible identifier representation of '(co)'
blanchet
parents: 54145
diff changeset
   993
    (disc_eqnss : coeqn_data_disc list list) (sel_eqnss : coeqn_data_sel list list) =
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
   994
  let
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
   995
    val corecs = map #corec corec_specs;
a179353111db generate callssss
panny
parents: 54157
diff changeset
   996
    val ctr_specss = map #ctr_specs corec_specs;
53360
7ffc4a746a73 handle direct corecursion
panny
parents: 53358
diff changeset
   997
    val corec_args = hd corecs
7ffc4a746a73 handle direct corecursion
panny
parents: 53358
diff changeset
   998
      |> fst o split_last o binder_types o fastype_of
59044
c04eccae1de8 tuned whitespace
blanchet
parents: 59043
diff changeset
   999
      |> map (fn T =>
c04eccae1de8 tuned whitespace
blanchet
parents: 59043
diff changeset
  1000
          if range_type T = HOLogic.boolT then Abs (Name.uu_, domain_type T, @{term False})
54806
a0f024caa04c pass auto-proved exhaustiveness properties to tactic;
panny
parents: 54628
diff changeset
  1001
          else Const (@{const_name undefined}, T))
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1002
      |> fold2 (fold o build_corec_arg_disc) ctr_specss disc_eqnss
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
  1003
      |> fold2 (fold o build_corec_args_sel ctxt has_call) sel_eqnss ctr_specss;
59041
2a23235632b2 careful with de Bruijn indices
blanchet
parents: 58634
diff changeset
  1004
59599
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
  1005
    val bad = fold (add_extra_frees ctxt [] []) corec_args [];
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
  1006
    val _ = null bad orelse
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
  1007
      (if exists has_call corec_args then nonprimitive_corec ctxt []
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
  1008
       else extra_variable ctxt [] (hd bad));
6a7e11fc6ee2 better primcorec messages
blanchet
parents: 59598
diff changeset
  1009
54835
431133d07192 note manually proved exclusiveness property
blanchet
parents: 54834
diff changeset
  1010
    val excludess' =
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1011
      disc_eqnss
53822
6304b12c7627 add "primcorec" command (cf. ae7f50e70c09)
panny
parents: 53811
diff changeset
  1012
      |> map (map (fn x => (#fun_args x, #ctr_no x, #prems x, #auto_gen x))
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1013
        #> fst o (fn xs => fold_map (fn x => fn ys => ((x, ys), ys @ [x])) xs [])
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1014
        #> maps (uncurry (map o pair)
53822
6304b12c7627 add "primcorec" command (cf. ae7f50e70c09)
panny
parents: 53811
diff changeset
  1015
          #> map (fn ((fun_args, c, x, a), (_, c', y, a')) =>
54068
447354985f6a generate optimized DNF formula
blanchet
parents: 54067
diff changeset
  1016
              ((c, c', a orelse a'), (x, s_not (s_conjs y)))
57527
1b07ca054327 add helper function map_prod
desharna
parents: 57399
diff changeset
  1017
            ||> map_prod (map HOLogic.mk_Trueprop) HOLogic.mk_Trueprop
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1018
            ||> Logic.list_implies
55342
blanchet
parents: 55341
diff changeset
  1019
            ||> curry Logic.list_all (map dest_Free fun_args))));
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1020
  in
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
  1021
    map (Term.list_comb o rpair corec_args) corecs
59873
2d929c178283 simplified code
blanchet
parents: 59859
diff changeset
  1022
    |> map2 abs_curried_balanced arg_Tss
59598
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
  1023
    |> (fn ts => Syntax.check_terms ctxt ts
c9d304d6ae98 more 'primcorec' error handling
blanchet
parents: 59597
diff changeset
  1024
      handle ERROR _ => nonprimitive_corec ctxt [])
61760
1647bb489522 tuned whitespace
blanchet
parents: 61424
diff changeset
  1025
    |> @{map 3} (fn b => fn mx => fn t =>
1647bb489522 tuned whitespace
blanchet
parents: 61424
diff changeset
  1026
      ((b, mx), ((Binding.concealed (Thm.def_binding b), []), t))) bs mxs
54835
431133d07192 note manually proved exclusiveness property
blanchet
parents: 54834
diff changeset
  1027
    |> rpair excludess'
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1028
  end;
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1029
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1030
fun mk_actual_disc_eqns fun_binding arg_Ts exhaustive ({ctr_specs, ...} : corec_spec)
54153
67487a607ce2 avoid 'co_' prefix with underscore meaning 'co', since it is our only possible identifier representation of '(co)'
blanchet
parents: 54145
diff changeset
  1031
    (sel_eqns : coeqn_data_sel list) (disc_eqns : coeqn_data_disc list) =
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1032
  let
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1033
    val fun_name = Binding.name_of fun_binding;
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1034
    val num_disc_eqns = length disc_eqns;
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1035
    val num_ctrs = length ctr_specs;
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1036
  in
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1037
    if (exhaustive andalso num_disc_eqns <> 0) orelse num_disc_eqns <> num_ctrs - 1 then
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1038
      (num_disc_eqns > 0 orelse error ("Missing discriminator formula for " ^ quote fun_name);
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1039
       disc_eqns)
54910
0ec2cccbf8ad properly synchronize parallel lists
blanchet
parents: 54909
diff changeset
  1040
    else
0ec2cccbf8ad properly synchronize parallel lists
blanchet
parents: 54909
diff changeset
  1041
      let
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1042
        val ctr_no = 0 upto length ctr_specs
55342
blanchet
parents: 55341
diff changeset
  1043
          |> the o find_first (fn j => not (exists (curry (op =) j o #ctr_no) disc_eqns));
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1044
        val {ctr, disc, ...} = nth ctr_specs ctr_no;
58393
blanchet
parents: 58387
diff changeset
  1045
        val sel_eqn_opt = find_first (equal ctr o #ctr) sel_eqns;
blanchet
parents: 58387
diff changeset
  1046
blanchet
parents: 58387
diff changeset
  1047
        val fun_T = arg_Ts ---> body_type (fastype_of (#ctr (hd ctr_specs)));
54910
0ec2cccbf8ad properly synchronize parallel lists
blanchet
parents: 54909
diff changeset
  1048
        val fun_args = (try (#fun_args o hd) disc_eqns, try (#fun_args o hd) sel_eqns)
0ec2cccbf8ad properly synchronize parallel lists
blanchet
parents: 54909
diff changeset
  1049
          |> the_default (map (curry Free Name.uu) arg_Ts) o merge_options;
58393
blanchet
parents: 58387
diff changeset
  1050
        val prems = maps (s_not_conj o #prems) disc_eqns;
blanchet
parents: 58387
diff changeset
  1051
        val ctr_rhs_opt = Option.map #ctr_rhs_opt sel_eqn_opt |> the_default NONE;
blanchet
parents: 58387
diff changeset
  1052
        val code_rhs_opt = Option.map #code_rhs_opt sel_eqn_opt |> the_default NONE;
61760
1647bb489522 tuned whitespace
blanchet
parents: 61424
diff changeset
  1053
        val eqn_pos = Option.map (curry (op +) 1 o #eqn_pos) sel_eqn_opt
1647bb489522 tuned whitespace
blanchet
parents: 61424
diff changeset
  1054
          |> the_default 100000; (* FIXME *)
58393
blanchet
parents: 58387
diff changeset
  1055
blanchet
parents: 58387
diff changeset
  1056
        val extra_disc_eqn =
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1057
          {fun_name = fun_name, fun_T = fun_T, fun_args = fun_args, ctr = ctr, ctr_no = ctr_no,
58393
blanchet
parents: 58387
diff changeset
  1058
           disc = disc, prems = prems, auto_gen = true, ctr_rhs_opt = ctr_rhs_opt,
blanchet
parents: 58387
diff changeset
  1059
           code_rhs_opt = code_rhs_opt, eqn_pos = eqn_pos, user_eqn = undef_const};
54910
0ec2cccbf8ad properly synchronize parallel lists
blanchet
parents: 54909
diff changeset
  1060
      in
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1061
        chop ctr_no disc_eqns ||> cons extra_disc_eqn |> op @
54910
0ec2cccbf8ad properly synchronize parallel lists
blanchet
parents: 54909
diff changeset
  1062
      end
0ec2cccbf8ad properly synchronize parallel lists
blanchet
parents: 54909
diff changeset
  1063
  end;
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1064
55100
697b41533e1a made SML/NJ happier
blanchet
parents: 55061
diff changeset
  1065
fun find_corec_calls ctxt has_call (basic_ctr_specs : basic_corec_ctr_spec list)
697b41533e1a made SML/NJ happier
blanchet
parents: 55061
diff changeset
  1066
    ({ctr, sel, rhs_term, ...} : coeqn_data_sel) =
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1067
  let
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1068
    val sel_no = find_first (curry (op =) ctr o #ctr) basic_ctr_specs
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1069
      |> find_index (curry (op =) sel) o #sels o the;
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1070
  in
55341
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
  1071
    K (if has_call rhs_term then fold_rev_let_if_case ctxt (K cons) [] rhs_term [] else [])
3d2c97392e25 adapted tactic to correctly handle 'if ... then ...' and 'case ...' under lambdas
blanchet
parents: 55339
diff changeset
  1072
    |> nth_map sel_no |> AList.map_entry (op =) ctr
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1073
  end;
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1074
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1075
fun applied_fun_of fun_name fun_T fun_args =
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
  1076
  Term.list_comb (Free (fun_name, fun_T), map Bound (length fun_args - 1 downto 0));
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1077
54921
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1078
fun is_trivial_implies thm =
54967
78de75e3e52a exhaustive rules like '(False ==> P) ==> P ==> P' are now filtered out as trivial
blanchet
parents: 54959
diff changeset
  1079
  uncurry (member (op aconv)) (Logic.strip_horn (Thm.prop_of thm));
54921
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1080
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
  1081
fun primcorec_ursive auto opts fixes specs of_specs_opt lthy =
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1082
  let
54272
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
  1083
    val thy = Proof_Context.theory_of lthy;
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
  1084
53352
43a1cc050943 honor mixfix specifications
traytel
parents: 53341
diff changeset
  1085
    val (bs, mxs) = map_split (apfst fst) fixes;
55969
8820ddb8f9f4 use balanced tuples in 'primcorec'
blanchet
parents: 55966
diff changeset
  1086
    val (arg_Ts, res_Ts) = map (strip_type o snd o fst #>> mk_tupleT_balanced) fixes |> split_list;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1087
56254
a2dd9200854d more antiquotations;
wenzelm
parents: 56152
diff changeset
  1088
    val _ = (case filter_out (fn (_, T) => Sign.of_sort thy (T, @{sort type})) (bs ~~ arg_Ts) of
54272
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
  1089
        [] => ()
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
  1090
      | (b, _) :: _ => error ("Type of " ^ Binding.print b ^ " contains top sort"));
54272
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
  1091
54902
a9291e4d2366 internally allow different values for 'sequential' for different constructors
blanchet
parents: 54901
diff changeset
  1092
    val actual_nn = length bs;
a9291e4d2366 internally allow different values for 'sequential' for different constructors
blanchet
parents: 54901
diff changeset
  1093
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1094
    val plugins = get_first (fn Plugins_Option f => SOME (f lthy) | _ => NONE) (rev opts)
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1095
      |> the_default Plugin_Name.default_filter;
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1096
    val sequentials = replicate actual_nn (exists (can (fn Sequential_Option => ())) opts);
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1097
    val exhaustives = replicate actual_nn (exists (can (fn Exhaustive_Option => ())) opts);
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1098
    val transfers = replicate actual_nn (exists (can (fn Transfer_Option => ())) opts);
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1099
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1100
    val fun_names = map Binding.name_of bs;
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1101
    val basic_ctr_specss = map (basic_corec_specs_of lthy) res_Ts;
55772
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
  1102
    val frees = map (fst #>> Binding.name_of #> Free) fixes;
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
  1103
    val has_call = Term.exists_subterm (member (op =) frees);
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1104
    val eqns_data =
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1105
      @{fold_map 2} (dissect_coeqn lthy has_call fun_names sequentials basic_ctr_specss)
55871
a28817253b31 removed (co)iterators from documentation
blanchet
parents: 55870
diff changeset
  1106
        (tag_list 0 (map snd specs)) of_specs_opt []
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1107
      |> flat o fst;
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1108
59662
blanchet
parents: 59612
diff changeset
  1109
    val missing = fun_names
blanchet
parents: 59612
diff changeset
  1110
      |> filter (map (fn Disc x => #fun_name x | Sel x => #fun_name x) eqns_data
blanchet
parents: 59612
diff changeset
  1111
        |> not oo member (op =));
blanchet
parents: 59612
diff changeset
  1112
    val _ = null missing orelse error ("Missing equations for " ^ commas missing);
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
  1113
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1114
    val callssss =
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1115
      map_filter (try (fn Sel x => x)) eqns_data
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
  1116
      |> partition_eq (op = o apply2 #fun_name)
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1117
      |> fst o finds (fn (x, ({fun_name, ...} :: _)) => x = fun_name) fun_names
54161
panny
parents: 54160 54159
diff changeset
  1118
      |> map (flat o snd)
54243
a596292be9a8 more robust n2m w.r.t. 'let's
blanchet
parents: 54239
diff changeset
  1119
      |> map2 (fold o find_corec_calls lthy has_call) basic_ctr_specss
54160
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1120
      |> map2 (curry (op |>)) (map (map (fn {ctr, sels, ...} =>
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1121
        (ctr, map (K []) sels))) basic_ctr_specss);
a179353111db generate callssss
panny
parents: 54157
diff changeset
  1122
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1123
    val (corec_specs0, _, coinduct_thm, coinduct_strong_thm, coinduct_thms, coinduct_strong_thms,
61334
8d40ddaa427f collect the names from goals in favor of fragile exports
traytel
parents: 61301
diff changeset
  1124
         (coinduct_attrs, common_coinduct_attrs), n2m, lthy) =
55772
367ec44763fd correct most general type for mutual recursion when several identical types are involved
blanchet
parents: 55571
diff changeset
  1125
      corec_specs_of bs arg_Ts res_Ts frees callssss lthy;
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1126
    val corec_specs = take actual_nn corec_specs0;
54178
d6dc359426b7 more informative abort
blanchet
parents: 54177
diff changeset
  1127
    val ctr_specss = map #ctr_specs corec_specs;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1128
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1129
    val disc_eqnss0 = map_filter (try (fn Disc x => x)) eqns_data
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
  1130
      |> partition_eq (op = o apply2 #fun_name)
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1131
      |> fst o finds (fn (x, ({fun_name, ...} :: _)) => x = fun_name) fun_names
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
  1132
      |> map (sort (op < o apply2 #ctr_no |> make_ord) o flat o snd);
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
  1133
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1134
    val _ = disc_eqnss0 |> map (fn x =>
59602
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1135
      let val dups = duplicates (op = o apply2 #ctr_no) x in
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1136
        null dups orelse
59600
1716da11a11c more precise primcorec messages
blanchet
parents: 59599
diff changeset
  1137
        error_at lthy
59602
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1138
          (maps (fn t => filter (curry (op =) (#ctr_no t) o #ctr_no) x) dups
59600
1716da11a11c more precise primcorec messages
blanchet
parents: 59599
diff changeset
  1139
           |> map (fn {ctr_rhs_opt = SOME t, ...} => t | {user_eqn, ...} => user_eqn))
59606
blanchet
parents: 59605
diff changeset
  1140
          "Overspecified case(s)"
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
  1141
      end);
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1142
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1143
    val sel_eqnss = map_filter (try (fn Sel x => x)) eqns_data
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
  1144
      |> partition_eq (op = o apply2 #fun_name)
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1145
      |> fst o finds (fn (x, ({fun_name, ...} :: _)) => x = fun_name) fun_names
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1146
      |> map (flat o snd);
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1147
59602
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1148
    val _ = sel_eqnss |> map (fn x =>
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1149
      let val dups = duplicates (op = o apply2 ctr_sel_of) x in
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1150
        null dups orelse
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1151
        error_at lthy
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1152
          (maps (fn t => filter (curry (op =) (ctr_sel_of t) o ctr_sel_of) x) dups
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1153
           |> map (fn {ctr_rhs_opt = SOME t, ...} => t | {user_eqn, ...} => user_eqn))
59606
blanchet
parents: 59605
diff changeset
  1154
          "Overspecified case(s)"
59602
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1155
      end);
2a6226d89fa3 more primcorec messages
blanchet
parents: 59601
diff changeset
  1156
53360
7ffc4a746a73 handle direct corecursion
panny
parents: 53358
diff changeset
  1157
    val arg_Tss = map (binder_types o snd o fst) fixes;
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1158
    val disc_eqnss = @{map 6} mk_actual_disc_eqns bs arg_Tss exhaustives corec_specs sel_eqnss
59603
427511b3d575 better primcorec messages
blanchet
parents: 59602
diff changeset
  1159
      disc_eqnss0;
54835
431133d07192 note manually proved exclusiveness property
blanchet
parents: 54834
diff changeset
  1160
    val (defs, excludess') =
61334
8d40ddaa427f collect the names from goals in favor of fragile exports
traytel
parents: 61301
diff changeset
  1161
      build_defs lthy bs mxs has_call arg_Tss corec_specs disc_eqnss sel_eqnss;
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1162
55009
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1163
    val tac_opts =
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1164
      map (fn {code_rhs_opt, ...} :: _ =>
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1165
        if auto orelse is_some code_rhs_opt then SOME (auto_tac o #context) else NONE) disc_eqnss;
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1166
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1167
    fun exclude_tac tac_opt sequential (c, c', a) =
54901
0b8871677e0b use same name for feature internally as in user interface, to facilitate grepping
blanchet
parents: 54900
diff changeset
  1168
      if a orelse c = c' orelse sequential then
61271
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1169
        SOME (fn {context = ctxt, prems = _} => HEADGOAL (mk_primcorec_assumption_tac ctxt []))
54901
0b8871677e0b use same name for feature internally as in user interface, to facilitate grepping
blanchet
parents: 54900
diff changeset
  1170
      else
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1171
        tac_opt;
53822
6304b12c7627 add "primcorec" command (cf. ae7f50e70c09)
panny
parents: 53811
diff changeset
  1172
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1173
    val excludess'' = @{map 3} (fn tac_opt => fn sequential => map (fn (j, goal) =>
59597
70a68edcc79b helpful error message when 'auto' fails
blanchet
parents: 59596
diff changeset
  1174
          (j, (Option.map (Goal.prove (*no sorry*) lthy [] [] goal #> Thm.close_derivation)
70a68edcc79b helpful error message when 'auto' fails
blanchet
parents: 59596
diff changeset
  1175
             (exclude_tac tac_opt sequential j), goal))))
70a68edcc79b helpful error message when 'auto' fails
blanchet
parents: 59596
diff changeset
  1176
        tac_opts sequentials excludess'
70a68edcc79b helpful error message when 'auto' fails
blanchet
parents: 59596
diff changeset
  1177
      handle ERROR _ => use_primcorecursive ();
56152
2a31945b9a58 add error messages for invalid inputs
panny
parents: 55969
diff changeset
  1178
54835
431133d07192 note manually proved exclusiveness property
blanchet
parents: 54834
diff changeset
  1179
    val taut_thmss = map (map (apsnd (the o fst)) o filter (is_some o fst o snd)) excludess'';
55009
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1180
    val (goal_idxss, exclude_goalss) = excludess''
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1181
      |> map (map (apsnd (rpair [] o snd)) o filter (is_none o fst o snd))
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1182
      |> split_list o map split_list;
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1183
54921
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1184
    fun list_all_fun_args extras =
54910
0ec2cccbf8ad properly synchronize parallel lists
blanchet
parents: 54909
diff changeset
  1185
      map2 (fn [] => I
54921
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1186
          | {fun_args, ...} :: _ => map (curry Logic.list_all (extras @ map dest_Free fun_args)))
54903
c664bd02bf94 internally allow different values for 'exhaustive' for different constructors
blanchet
parents: 54902
diff changeset
  1187
        disc_eqnss;
54844
630ba4d8a206 generate exhaust from nchotomy
blanchet
parents: 54842
diff changeset
  1188
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1189
    val syntactic_exhaustives =
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1190
      map (fn disc_eqns => forall (null o #prems orf is_some o #code_rhs_opt) disc_eqns
54913
7b18c41df27a consider code as exhaustive
blanchet
parents: 54912
diff changeset
  1191
          orelse exists #auto_gen disc_eqns)
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1192
        disc_eqnss;
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1193
    val de_facto_exhaustives =
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1194
      map2 (fn b => fn b' => b orelse b') exhaustives syntactic_exhaustives;
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1195
54903
c664bd02bf94 internally allow different values for 'exhaustive' for different constructors
blanchet
parents: 54902
diff changeset
  1196
    val nchotomy_goalss =
54904
5d965f17b0e4 detect syntactic exhaustiveness
blanchet
parents: 54903
diff changeset
  1197
      map2 (fn false => K [] | true => single o HOLogic.mk_Trueprop o mk_dnf o map #prems)
5d965f17b0e4 detect syntactic exhaustiveness
blanchet
parents: 54903
diff changeset
  1198
        de_facto_exhaustives disc_eqnss
54921
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1199
      |> list_all_fun_args []
54903
c664bd02bf94 internally allow different values for 'exhaustive' for different constructors
blanchet
parents: 54902
diff changeset
  1200
    val nchotomy_taut_thmss =
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1201
      @{map 5} (fn tac_opt => fn {exhaust_discs = res_exhaust_discs, ...} =>
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1202
          fn {code_rhs_opt, ...} :: _ => fn [] => K []
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1203
            | [goal] => fn true =>
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1204
              let
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
  1205
                val (_, _, arg_exhaust_discs, _, _) =
55400
blanchet
parents: 55344
diff changeset
  1206
                  case_thms_of_term lthy (the_default Term.dummy code_rhs_opt);
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1207
              in
59596
c067eba942e7 no quick_and_dirty for goals that may fail + tuned messages
blanchet
parents: 59595
diff changeset
  1208
                [Goal.prove (*no sorry*) lthy [] [] goal (fn {context = ctxt, ...} =>
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
  1209
                   mk_primcorec_nchotomy_tac ctxt (res_exhaust_discs @ arg_exhaust_discs))
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1210
                 |> Thm.close_derivation]
59597
70a68edcc79b helpful error message when 'auto' fails
blanchet
parents: 59596
diff changeset
  1211
                handle ERROR _ => use_primcorecursive ()
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1212
              end
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1213
            | false =>
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1214
              (case tac_opt of
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1215
                SOME tac => [Goal.prove_sorry lthy [] [] goal tac |> Thm.close_derivation]
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1216
              | NONE => []))
55400
blanchet
parents: 55344
diff changeset
  1217
        tac_opts corec_specs disc_eqnss nchotomy_goalss syntactic_exhaustives;
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1218
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1219
    val syntactic_exhaustives =
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1220
      map (fn disc_eqns => forall (null o #prems orf is_some o #code_rhs_opt) disc_eqns
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1221
          orelse exists #auto_gen disc_eqns)
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1222
        disc_eqnss;
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1223
55009
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1224
    val nchotomy_goalss =
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1225
      map2 (fn (NONE, false) => map (rpair []) | _ => K []) (tac_opts ~~ syntactic_exhaustives)
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1226
        nchotomy_goalss;
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1227
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1228
    val goalss = nchotomy_goalss @ exclude_goalss;
54844
630ba4d8a206 generate exhaust from nchotomy
blanchet
parents: 54842
diff changeset
  1229
55462
78a06c7b5b87 added 'Spec_Rules' for 'primcorec'
blanchet
parents: 55414
diff changeset
  1230
    fun prove thmss'' def_infos lthy =
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1231
      let
55462
78a06c7b5b87 added 'Spec_Rules' for 'primcorec'
blanchet
parents: 55414
diff changeset
  1232
        val def_thms = map (snd o snd) def_infos;
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
  1233
        val ts = map fst def_infos;
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1234
54972
5747fdd4ad3b fix 'primcorec' (as opposed to 'primcorecursive') with 'exhaustive')
blanchet
parents: 54970
diff changeset
  1235
        val (nchotomy_thmss, exclude_thmss) =
55009
d4b69107a86a automatically solve proof obligations produced for code equations
blanchet
parents: 55008
diff changeset
  1236
          (map2 append (take actual_nn thmss'') nchotomy_taut_thmss, drop actual_nn thmss'');
54613
985f8b49c050 more work towards "exhaustive"
panny
parents: 54591
diff changeset
  1237
54927
a5a2598f0651 proper name generation to avoid clash with 'P' in user specification
blanchet
parents: 54926
diff changeset
  1238
        val ps =
a5a2598f0651 proper name generation to avoid clash with 'P' in user specification
blanchet
parents: 54926
diff changeset
  1239
          Variable.variant_frees lthy (maps (maps #fun_args) disc_eqnss) [("P", HOLogic.boolT)];
a5a2598f0651 proper name generation to avoid clash with 'P' in user specification
blanchet
parents: 54926
diff changeset
  1240
54903
c664bd02bf94 internally allow different values for 'exhaustive' for different constructors
blanchet
parents: 54902
diff changeset
  1241
        val exhaust_thmss =
c664bd02bf94 internally allow different values for 'exhaustive' for different constructors
blanchet
parents: 54902
diff changeset
  1242
          map2 (fn false => K []
54921
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1243
              | true => fn disc_eqns as {fun_args, ...} :: _ =>
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1244
                let
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1245
                  val p = Bound (length fun_args);
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1246
                  fun mk_imp_p Qs = Logic.list_implies (Qs, HOLogic.mk_Trueprop p);
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1247
                in
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1248
                  [mk_imp_p (map (mk_imp_p o map HOLogic.mk_Trueprop o #prems) disc_eqns)]
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1249
                end)
54904
5d965f17b0e4 detect syntactic exhaustiveness
blanchet
parents: 54903
diff changeset
  1250
            de_facto_exhaustives disc_eqnss
54927
a5a2598f0651 proper name generation to avoid clash with 'P' in user specification
blanchet
parents: 54926
diff changeset
  1251
          |> list_all_fun_args ps
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1252
          |> @{map 3} (fn disc_eqns as {fun_args, ...} :: _ => fn [] => K []
54903
c664bd02bf94 internally allow different values for 'exhaustive' for different constructors
blanchet
parents: 54902
diff changeset
  1253
              | [nchotomy_thm] => fn [goal] =>
61271
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1254
                [Goal.prove_sorry lthy [] [] goal
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1255
                  (fn {context = ctxt, prems = _} =>
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1256
                    mk_primcorec_exhaust_tac ctxt
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1257
                      ("" (* for "P" *) :: map (fst o dest_Free) fun_args)
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1258
                      (length disc_eqns) nchotomy_thm)
54903
c664bd02bf94 internally allow different values for 'exhaustive' for different constructors
blanchet
parents: 54902
diff changeset
  1259
                 |> Thm.close_derivation])
c664bd02bf94 internally allow different values for 'exhaustive' for different constructors
blanchet
parents: 54902
diff changeset
  1260
            disc_eqnss nchotomy_thmss;
54921
862c36b6e57c avoid schematic variable in goal, which sometimes gets instantiated by tactic
blanchet
parents: 54917
diff changeset
  1261
        val nontriv_exhaust_thmss = map (filter_out is_trivial_implies) exhaust_thmss;
54844
630ba4d8a206 generate exhaust from nchotomy
blanchet
parents: 54842
diff changeset
  1262
54835
431133d07192 note manually proved exclusiveness property
blanchet
parents: 54834
diff changeset
  1263
        val excludess' = map (op ~~) (goal_idxss ~~ exclude_thmss);
431133d07192 note manually proved exclusiveness property
blanchet
parents: 54834
diff changeset
  1264
        fun mk_excludesss excludes n =
54973
b35859240103 tuning (no need for |-> here)
blanchet
parents: 54972
diff changeset
  1265
          fold (fn ((c, c', _), thm) => nth_map c (nth_map c' (K [thm])))
54974
d1c76303244e use correct default for exclude rules to avoid weird tactic failures
blanchet
parents: 54973
diff changeset
  1266
            excludes (map (fn k => replicate k [asm_rl] @ replicate (n - k) []) (0 upto n - 1));
54973
b35859240103 tuning (no need for |-> here)
blanchet
parents: 54972
diff changeset
  1267
        val excludessss =
b35859240103 tuning (no need for |-> here)
blanchet
parents: 54972
diff changeset
  1268
          map2 (fn excludes => mk_excludesss excludes o length o #ctr_specs)
b35859240103 tuning (no need for |-> here)
blanchet
parents: 54972
diff changeset
  1269
            (map2 append excludess' taut_thmss) corec_specs;
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1270
54835
431133d07192 note manually proved exclusiveness property
blanchet
parents: 54834
diff changeset
  1271
        fun prove_disc ({ctr_specs, ...} : corec_spec) excludesss
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
  1272
            ({fun_name, fun_T, fun_args, ctr_no, prems, eqn_pos, ...} : coeqn_data_disc) =
54272
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
  1273
          if Term.aconv_untyped (#disc (nth ctr_specs ctr_no), @{term "\<lambda>x. x = x"}) then
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
  1274
            []
9d623cada37f avoid subtle failure in the presence of top sort
blanchet
parents: 54271
diff changeset
  1275
          else
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1276
            let
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
  1277
              val {disc, corec_disc, ...} = nth ctr_specs ctr_no;
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1278
              val k = 1 + ctr_no;
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1279
              val m = length prems;
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1280
              val goal =
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1281
                applied_fun_of fun_name fun_T fun_args
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1282
                |> curry betapply disc
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1283
                |> HOLogic.mk_Trueprop
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1284
                |> curry Logic.list_implies (map HOLogic.mk_Trueprop prems)
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1285
                |> curry Logic.list_all (map dest_Free fun_args);
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1286
            in
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1287
              if prems = [@{term False}] then
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1288
                []
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1289
              else
61271
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1290
                Goal.prove_sorry lthy [] [] goal
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1291
                  (fn {context = ctxt, prems = _} =>
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1292
                    mk_primcorec_disc_tac ctxt def_thms corec_disc k m excludesss)
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1293
                |> Thm.close_derivation
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1294
                |> pair (#disc (nth ctr_specs ctr_no))
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
  1295
                |> pair eqn_pos
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1296
                |> single
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1297
            end;
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1298
57399
cfc19f0a6261 compile
blanchet
parents: 57397
diff changeset
  1299
        fun prove_sel ({sel_defs, fp_nesting_maps, fp_nesting_map_ident0s, fp_nesting_map_comps,
57397
5004aca20821 tuned variable names
blanchet
parents: 57303
diff changeset
  1300
              ctr_specs, ...} : corec_spec) (disc_eqns : coeqn_data_disc list) excludesss
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1301
            ({fun_name, fun_T, fun_args, ctr, sel, rhs_term, code_rhs_opt, eqn_pos, ...}
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1302
             : coeqn_data_sel) =
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1303
          let
58393
blanchet
parents: 58387
diff changeset
  1304
            val ctr_spec = the (find_first (curry (op =) ctr o #ctr) ctr_specs);
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1305
            val ctr_no = find_index (curry (op =) ctr o #ctr) ctr_specs;
54067
7be49e2bfccc rationalized negation code
blanchet
parents: 54065
diff changeset
  1306
            val prems = the_default (maps (s_not_conj o #prems) disc_eqns)
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1307
              (find_first (curry (op =) ctr_no o #ctr_no) disc_eqns |> Option.map #prems);
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
  1308
            val corec_sel = find_index (curry (op =) sel) (#sels ctr_spec)
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
  1309
              |> nth (#corec_sels ctr_spec);
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1310
            val k = 1 + ctr_no;
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1311
            val m = length prems;
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1312
            val goal =
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1313
              applied_fun_of fun_name fun_T fun_args
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1314
              |> curry betapply sel
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
  1315
              |> rpair (abstract_over_list fun_args rhs_term)
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1316
              |> HOLogic.mk_Trueprop o HOLogic.mk_eq
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1317
              |> curry Logic.list_implies (map HOLogic.mk_Trueprop prems)
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1318
              |> curry Logic.list_all (map dest_Free fun_args);
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
  1319
            val (distincts, _, _, split_sels, split_sel_asms) = case_thms_of_term lthy rhs_term;
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1320
          in
61271
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1321
            Goal.prove_sorry lthy [] [] goal
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1322
              (fn {context = ctxt, prems = _} =>
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1323
                mk_primcorec_sel_tac ctxt def_thms distincts split_sels split_sel_asms
61760
1647bb489522 tuned whitespace
blanchet
parents: 61424
diff changeset
  1324
                  fp_nesting_maps fp_nesting_map_ident0s fp_nesting_map_comps corec_sel k m
1647bb489522 tuned whitespace
blanchet
parents: 61424
diff changeset
  1325
                  excludesss)
54176
8039bd7e98b1 systematically close derivations in BNF package
blanchet
parents: 54175
diff changeset
  1326
            |> Thm.close_derivation
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1327
            |> `(is_some code_rhs_opt ? fold_thms lthy sel_defs) (*mildly too aggressive*)
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1328
            |> pair sel
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
  1329
            |> pair eqn_pos
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1330
          end;
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1331
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1332
        fun prove_ctr disc_alist sel_alist ({sel_defs, ...} : corec_spec)
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1333
            (disc_eqns : coeqn_data_disc list) (sel_eqns : coeqn_data_sel list)
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1334
            ({ctr, disc, sels, collapse, ...} : corec_ctr_spec) =
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1335
          (* don't try to prove theorems when some sel_eqns are missing *)
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1336
          if not (exists (curry (op =) ctr o #ctr) disc_eqns)
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1337
              andalso not (exists (curry (op =) ctr o #ctr) sel_eqns)
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1338
            orelse
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1339
              filter (curry (op =) ctr o #ctr) sel_eqns
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1340
              |> fst o finds (op = o apsnd #sel) sels
54951
e25b4d22082b for code equations that coincide with ctr equations, make sure the usr's input is preserved for both
blanchet
parents: 54948
diff changeset
  1341
              |> exists (null o snd) then
e25b4d22082b for code equations that coincide with ctr equations, make sure the usr's input is preserved for both
blanchet
parents: 54948
diff changeset
  1342
            []
e25b4d22082b for code equations that coincide with ctr equations, make sure the usr's input is preserved for both
blanchet
parents: 54948
diff changeset
  1343
          else
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1344
            let
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1345
              val (fun_name, fun_T, fun_args, prems, ctr_rhs_opt, code_rhs_opt, eqn_pos) =
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1346
                (find_first (curry (op =) ctr o #ctr) disc_eqns,
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1347
                 find_first (curry (op =) ctr o #ctr) sel_eqns)
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1348
                |>> Option.map (fn x => (#fun_name x, #fun_T x, #fun_args x, #prems x,
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1349
                  #ctr_rhs_opt x, #code_rhs_opt x, #eqn_pos x))
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1350
                ||> Option.map (fn x => (#fun_name x, #fun_T x, #fun_args x, [],
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1351
                  #ctr_rhs_opt x, #code_rhs_opt x, #eqn_pos x))
53722
e176d6d3345f generate more theorems (e.g. for types with only one constructor)
panny
parents: 53720
diff changeset
  1352
                |> the o merge_options;
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1353
              val m = length prems;
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1354
              val goal =
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1355
                (case ctr_rhs_opt of
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1356
                  SOME rhs => rhs
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1357
                | NONE =>
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1358
                  filter (curry (op =) ctr o #ctr) sel_eqns
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1359
                  |> fst o finds (op = o apsnd #sel) sels
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
  1360
                  |> map (snd #> (fn [x] => (#fun_args x, #rhs_term x))
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
  1361
                    #-> abstract_over_list)
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
  1362
                  |> curry Term.list_comb ctr)
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1363
                |> curry mk_Trueprop_eq (applied_fun_of fun_name fun_T fun_args)
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1364
                |> curry Logic.list_implies (map HOLogic.mk_Trueprop prems)
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1365
                |> curry Logic.list_all (map dest_Free fun_args);
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1366
              val disc_thm_opt = AList.lookup (op =) disc_alist disc;
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1367
              val sel_thms = map (snd o snd) (filter (member (op =) sels o fst) sel_alist);
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1368
            in
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1369
              if prems = [@{term False}] then
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1370
                []
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1371
              else
61271
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1372
                Goal.prove_sorry lthy [] [] goal
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1373
                  (fn {context = ctxt, prems = _} =>
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1374
                    mk_primcorec_ctr_tac ctxt m collapse disc_thm_opt sel_thms)
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1375
                |> is_some code_rhs_opt ? fold_thms lthy sel_defs (*mildly too aggressive*)
54176
8039bd7e98b1 systematically close derivations in BNF package
blanchet
parents: 54175
diff changeset
  1376
                |> Thm.close_derivation
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1377
                |> pair ctr
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
  1378
                |> pair eqn_pos
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1379
                |> single
53876
fabf04d43a75 simplified code
panny
parents: 53875
diff changeset
  1380
            end;
53720
03fac7082137 generate constructor view theorems
panny
parents: 53699
diff changeset
  1381
55100
697b41533e1a made SML/NJ happier
blanchet
parents: 55061
diff changeset
  1382
        fun prove_code exhaustive (disc_eqns : coeqn_data_disc list)
697b41533e1a made SML/NJ happier
blanchet
parents: 55061
diff changeset
  1383
            (sel_eqns : coeqn_data_sel list) nchotomys ctr_alist ctr_specs =
54098
07a8145aaeba pass the right theorems to tactic
panny
parents: 54097
diff changeset
  1384
          let
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1385
            val fun_data_opt =
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1386
              (find_first (member (op =) (map #ctr ctr_specs) o #ctr) disc_eqns,
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1387
               find_first (member (op =) (map #ctr ctr_specs) o #ctr) sel_eqns)
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1388
              |>> Option.map (fn x => (#fun_name x, #fun_T x, #fun_args x, #code_rhs_opt x))
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1389
              ||> Option.map (fn x => (#fun_name x, #fun_T x, #fun_args x, #code_rhs_opt x))
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1390
              |> merge_options;
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1391
          in
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1392
            (case fun_data_opt of
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1393
              NONE => []
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1394
            | SOME (fun_name, fun_T, fun_args, rhs_opt) =>
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1395
              let
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1396
                val bound_Ts = List.rev (map fastype_of fun_args);
54173
blanchet
parents: 54172
diff changeset
  1397
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1398
                val lhs = applied_fun_of fun_name fun_T fun_args;
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1399
                val rhs_info_opt =
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1400
                  (case rhs_opt of
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1401
                    SOME rhs =>
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1402
                    let
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1403
                      val raw_rhs = expand_corec_code_rhs lthy has_call bound_Ts rhs;
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1404
                      val cond_ctrs =
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1405
                        fold_rev_corec_code_rhs lthy (K oo (cons oo pair)) bound_Ts raw_rhs [];
54978
afc156c7e4f7 cope gracefully with missing ctr equations by plugging in 'False ==> ...'
blanchet
parents: 54976
diff changeset
  1406
                      val ctr_thms =
afc156c7e4f7 cope gracefully with missing ctr equations by plugging in 'False ==> ...'
blanchet
parents: 54976
diff changeset
  1407
                        map (the_default FalseE o AList.lookup (op =) ctr_alist o snd) cond_ctrs;
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1408
                    in SOME (false, rhs, raw_rhs, ctr_thms) end
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1409
                  | NONE =>
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1410
                    let
55100
697b41533e1a made SML/NJ happier
blanchet
parents: 55061
diff changeset
  1411
                      fun prove_code_ctr ({ctr, sels, ...} : corec_ctr_spec) =
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1412
                        if not (exists (curry (op =) ctr o fst) ctr_alist) then
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1413
                          NONE
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1414
                        else
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1415
                          let
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1416
                            val prems = find_first (curry (op =) ctr o #ctr) disc_eqns
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1417
                              |> Option.map #prems |> the_default [];
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1418
                            val t =
54923
ffed2452f5f6 instantiate schematics as projections to avoid HOU trouble
blanchet
parents: 54921
diff changeset
  1419
                              filter (curry (op =) ctr o #ctr) sel_eqns
55008
b5b2e193ca33 use 'disc_exhausts' property both from types on which 'case's take place and on return type
blanchet
parents: 55005
diff changeset
  1420
                              |> fst o finds (op = o apsnd #sel) sels
60704
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
  1421
                              |> map (snd #> (fn [x] => (#fun_args x, #rhs_term x))
fdd965b35bcd tuned ML signature (and rationalized code a bit)
blanchet
parents: 60683
diff changeset
  1422
                                #-> abstract_over_list)
55343
5ebf832b58a1 expand 'split' in direct corecursion as well
blanchet
parents: 55342
diff changeset
  1423
                              |> curry Term.list_comb ctr;
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1424
                          in
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1425
                            SOME (prems, t)
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1426
                          end;
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1427
                      val ctr_conds_argss_opt = map prove_code_ctr ctr_specs;
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1428
                      val exhaustive_code =
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1429
                        exhaustive
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
  1430
                        orelse exists (is_some andf (null o fst o the)) ctr_conds_argss_opt
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1431
                        orelse forall is_some ctr_conds_argss_opt
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1432
                          andalso exists #auto_gen disc_eqns;
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1433
                      val rhs =
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1434
                        (if exhaustive_code then
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1435
                           split_last (map_filter I ctr_conds_argss_opt) ||> snd
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1436
                         else
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1437
                           Const (@{const_name Code.abort}, @{typ String.literal} -->
55966
972f0aa7091b balance tuples that represent curried functions
blanchet
parents: 55871
diff changeset
  1438
                               (HOLogic.unitT --> body_type fun_T) --> body_type fun_T) $
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1439
                             HOLogic.mk_literal fun_name $
55966
972f0aa7091b balance tuples that represent curried functions
blanchet
parents: 55871
diff changeset
  1440
                             absdummy HOLogic.unitT (incr_boundvars 1 lhs)
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1441
                           |> pair (map_filter I ctr_conds_argss_opt))
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1442
                         |-> fold_rev (fn (prems, u) => mk_If (s_conjs prems) u)
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1443
                    in
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1444
                      SOME (exhaustive_code, rhs, rhs, map snd ctr_alist)
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1445
                    end);
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1446
              in
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1447
                (case rhs_info_opt of
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1448
                  NONE => []
54905
2fdec6c29eb7 don't generate any proof obligation for implicit (de facto) exclusiveness
blanchet
parents: 54904
diff changeset
  1449
                | SOME (exhaustive_code, rhs, raw_rhs, ctr_thms) =>
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1450
                  let
59582
0fbed69ff081 tuned signature -- prefer qualified names;
wenzelm
parents: 59283
diff changeset
  1451
                    val ms = map (Logic.count_prems o Thm.prop_of) ctr_thms;
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1452
                    val (raw_goal, goal) = (raw_rhs, rhs)
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
  1453
                      |> apply2 (curry mk_Trueprop_eq (applied_fun_of fun_name fun_T fun_args)
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1454
                        #> curry Logic.list_all (map dest_Free fun_args));
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
  1455
                    val (distincts, discIs, _, split_sels, split_sel_asms) =
55400
blanchet
parents: 55344
diff changeset
  1456
                      case_thms_of_term lthy raw_rhs;
54098
07a8145aaeba pass the right theorems to tactic
panny
parents: 54097
diff changeset
  1457
61271
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1458
                    val raw_code_thm = 
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1459
                      Goal.prove_sorry lthy [] [] raw_goal
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1460
                        (fn {context = ctxt, prems = _} =>
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1461
                          mk_primcorec_raw_code_tac ctxt distincts discIs split_sels split_sel_asms
61760
1647bb489522 tuned whitespace
blanchet
parents: 61424
diff changeset
  1462
                            ms ctr_thms
1647bb489522 tuned whitespace
blanchet
parents: 61424
diff changeset
  1463
                            (if exhaustive_code then try the_single nchotomys else NONE))
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1464
                      |> Thm.close_derivation;
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1465
                  in
61271
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1466
                    Goal.prove_sorry lthy [] [] goal
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1467
                      (fn {context = ctxt, prems = _} =>
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1468
                        mk_primcorec_code_tac ctxt distincts split_sels raw_code_thm)
54591
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1469
                    |> Thm.close_derivation
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1470
                    |> single
c822230fd22b prevent exception when equations for a function are missing;
panny
parents: 54279
diff changeset
  1471
                  end)
54173
blanchet
parents: 54172
diff changeset
  1472
              end)
blanchet
parents: 54172
diff changeset
  1473
          end;
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1474
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1475
        val disc_alistss = @{map 3} (map oo prove_disc) corec_specs excludessss disc_eqnss;
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
  1476
        val disc_alists = map (map snd o flat) disc_alistss;
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1477
        val sel_alists = @{map 4} (map ooo prove_sel) corec_specs disc_eqnss excludessss sel_eqnss;
55870
2f90476e3e61 avoid duplicate 'disc_iff' theorems
blanchet
parents: 55869
diff changeset
  1478
        val disc_thmss = map (map snd o sort_list_duplicates o flat) disc_alistss;
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
  1479
        val disc_thmsss' = map (map (map (snd o snd))) disc_alistss;
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1480
        val sel_thmss = map (map (fst o snd) o sort_list_duplicates) sel_alists;
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1481
54959
30ded82ff806 fixed 'disc_iff' tactic in the case where different equations use different variable names for the function arguments
blanchet
parents: 54958
diff changeset
  1482
        fun prove_disc_iff ({ctr_specs, ...} : corec_spec) exhaust_thms disc_thmss'
30ded82ff806 fixed 'disc_iff' tactic in the case where different equations use different variable names for the function arguments
blanchet
parents: 54958
diff changeset
  1483
            (({fun_args = exhaust_fun_args, ...} : coeqn_data_disc) :: _) disc_thms
54948
516adecd99dd match order of generated theorems to user input;
panny
parents: 54927
diff changeset
  1484
            ({fun_name, fun_T, fun_args, ctr_no, prems, eqn_pos, ...} : coeqn_data_disc) =
55870
2f90476e3e61 avoid duplicate 'disc_iff' theorems
blanchet
parents: 55869
diff changeset
  1485
          if null exhaust_thms orelse null disc_thms then
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1486
            []
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1487
          else
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1488
            let
57983
6edc3529bb4e reordered some (co)datatype property names for more consistency
blanchet
parents: 57895
diff changeset
  1489
              val {disc, distinct_discss, ...} = nth ctr_specs ctr_no;
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1490
              val goal =
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1491
                mk_Trueprop_eq (applied_fun_of fun_name fun_T fun_args |> curry betapply disc,
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1492
                  mk_conjs prems)
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1493
                |> curry Logic.list_all (map dest_Free fun_args);
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1494
            in
61271
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1495
              Goal.prove_sorry lthy [] [] goal
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1496
                (fn {context = ctxt, prems = _} =>
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1497
                  mk_primcorec_disc_iff_tac ctxt (map (fst o dest_Free) exhaust_fun_args)
0478ba10152a more canonical context threading
traytel
parents: 61125
diff changeset
  1498
                    (the_single exhaust_thms) disc_thms disc_thmss' (flat distinct_discss))
54969
0ac0b6576d21 generate 'disc_iff' for all discriminators
blanchet
parents: 54968
diff changeset
  1499
              |> Thm.close_derivation
60362
befdc10ebb42 clarified context;
wenzelm
parents: 60003
diff changeset
  1500
              |> fold (fn rule => perhaps (try (fn thm => Meson.first_order_resolve lthy thm rule)))
54969
0ac0b6576d21 generate 'disc_iff' for all discriminators
blanchet
parents: 54968
diff changeset
  1501
                @{thms eqTrueE eq_False[THEN iffD1] notnotD}
0ac0b6576d21 generate 'disc_iff' for all discriminators
blanchet
parents: 54968
diff changeset
  1502
              |> pair eqn_pos
0ac0b6576d21 generate 'disc_iff' for all discriminators
blanchet
parents: 54968
diff changeset
  1503
              |> single
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1504
            end;
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1505
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1506
        val disc_iff_thmss = @{map 6} (flat ooo map2 oooo prove_disc_iff) corec_specs exhaust_thmss
54959
30ded82ff806 fixed 'disc_iff' tactic in the case where different equations use different variable names for the function arguments
blanchet
parents: 54958
diff changeset
  1507
          disc_thmsss' disc_eqnss disc_thmsss' disc_eqnss
55870
2f90476e3e61 avoid duplicate 'disc_iff' theorems
blanchet
parents: 55869
diff changeset
  1508
          |> map sort_list_duplicates;
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1509
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1510
        val ctr_alists = @{map 6} (fn disc_alist => maps oooo prove_ctr disc_alist) disc_alists
56858
0c3d0bc98abe simplify selectors in code views
blanchet
parents: 56806
diff changeset
  1511
          (map (map snd) sel_alists) corec_specs disc_eqnss sel_eqnss ctr_specss;
59043
a00110bdb4a3 keep all 'ctr' theorems
blanchet
parents: 59042
diff changeset
  1512
        val ctr_thmss0 = map (map snd) ctr_alists;
59058
a78612c67ec0 renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm
parents: 59044
diff changeset
  1513
        val ctr_thmss = map (map (snd o snd) o sort (int_ord o apply2 fst)) ctr_alists;
54097
92c5bd3b342d prove user-supplied equations for ctr and code reductions, preserving "let"s, "case"s etc.;
panny
parents: 54074
diff changeset
  1514
58634
9f10d82e8188 added parameterized ML antiquotations @{map N}, @{fold N}, @{fold_map N}, @{split_list N};
wenzelm
parents: 58462
diff changeset
  1515
        val code_thmss =
59043
a00110bdb4a3 keep all 'ctr' theorems
blanchet
parents: 59042
diff changeset
  1516
          @{map 6} prove_code exhaustives disc_eqnss sel_eqnss nchotomy_thmss ctr_thmss0 ctr_specss;
53791
0ddf045113c9 tuned code
blanchet
parents: 53753
diff changeset
  1517
54968
baa2baf29eff use 'disc_iff' as simp rules whenever possible + clean up '= True', '= False', etc.
blanchet
parents: 54967
diff changeset
  1518
        val disc_iff_or_disc_thmss =
baa2baf29eff use 'disc_iff' as simp rules whenever possible + clean up '= True', '= False', etc.
blanchet
parents: 54967
diff changeset
  1519
          map2 (fn [] => I | disc_iffs => K disc_iffs) disc_iff_thmss disc_thmss;
baa2baf29eff use 'disc_iff' as simp rules whenever possible + clean up '= True', '= False', etc.
blanchet
parents: 54967
diff changeset
  1520
        val simp_thmss = map2 append disc_iff_or_disc_thmss sel_thmss;
53795
dfa1108368ad generate "simps" from "primcorec"
blanchet
parents: 53794
diff changeset
  1521
53797
576f9637dc7a note coinduct theorems in "primcorec"
blanchet
parents: 53795
diff changeset
  1522
        val common_name = mk_common_name fun_names;
576f9637dc7a note coinduct theorems in "primcorec"
blanchet
parents: 53795
diff changeset
  1523
59283
5ca195783da8 generate [code] only with 'code' plugin enabled
blanchet
parents: 59281
diff changeset
  1524
        val code_attrs = if plugins code_plugin then [Code.add_default_eqn_attrib] else [];
5ca195783da8 generate [code] only with 'code' plugin enabled
blanchet
parents: 59281
diff changeset
  1525
55860
756275b550d9 make 'diff_iff' a simp rule if available
blanchet
parents: 55859
diff changeset
  1526
        val anonymous_notes =
756275b550d9 make 'diff_iff' a simp rule if available
blanchet
parents: 55859
diff changeset
  1527
          [(flat disc_iff_or_disc_thmss, simp_attrs)]
756275b550d9 make 'diff_iff' a simp rule if available
blanchet
parents: 55859
diff changeset
  1528
          |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
756275b550d9 make 'diff_iff' a simp rule if available
blanchet
parents: 55859
diff changeset
  1529
58283
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1530
        val common_notes =
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1531
          [(coinductN, if n2m then [coinduct_thm] else [], common_coinduct_attrs),
58286
a15731cf1835 compile
blanchet
parents: 58283
diff changeset
  1532
           (coinduct_strongN, if n2m then [coinduct_strong_thm] else [], common_coinduct_attrs)]
58283
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1533
          |> filter_out (null o #2)
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1534
          |> map (fn (thmN, thms, attrs) =>
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1535
            ((Binding.qualify true common_name (Binding.name thmN), attrs), [(thms, [])]));
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1536
53791
0ddf045113c9 tuned code
blanchet
parents: 53753
diff changeset
  1537
        val notes =
58283
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1538
          [(coinductN, map (if n2m then single else K []) coinduct_thms, coinduct_attrs),
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1539
           (coinduct_strongN, map (if n2m then single else K []) coinduct_strong_thms,
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1540
            coinduct_attrs),
59283
5ca195783da8 generate [code] only with 'code' plugin enabled
blanchet
parents: 59281
diff changeset
  1541
           (codeN, code_thmss, code_attrs @ nitpicksimp_attrs),
53797
576f9637dc7a note coinduct theorems in "primcorec"
blanchet
parents: 53795
diff changeset
  1542
           (ctrN, ctr_thmss, []),
55860
756275b550d9 make 'diff_iff' a simp rule if available
blanchet
parents: 55859
diff changeset
  1543
           (discN, disc_thmss, []),
54900
136fe16e726a generate 'disc_iff' property in 'primcorec'
blanchet
parents: 54899
diff changeset
  1544
           (disc_iffN, disc_iff_thmss, []),
54835
431133d07192 note manually proved exclusiveness property
blanchet
parents: 54834
diff changeset
  1545
           (excludeN, exclude_thmss, []),
54909
63db983c6953 graceful handling of one-constructor case
blanchet
parents: 54907
diff changeset
  1546
           (exhaustN, nontriv_exhaust_thmss, []),
53795
dfa1108368ad generate "simps" from "primcorec"
blanchet
parents: 53794
diff changeset
  1547
           (selN, sel_thmss, simp_attrs),
58283
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1548
           (simpsN, simp_thmss, [])]
53791
0ddf045113c9 tuned code
blanchet
parents: 53753
diff changeset
  1549
          |> maps (fn (thmN, thmss, attrs) =>
0ddf045113c9 tuned code
blanchet
parents: 53753
diff changeset
  1550
            map2 (fn fun_name => fn thms =>
0ddf045113c9 tuned code
blanchet
parents: 53753
diff changeset
  1551
                ((Binding.qualify true fun_name (Binding.name thmN), attrs), [(thms, [])]))
53830
ed2eb7df2aac don't note more induction principles than there are functions + tuning
blanchet
parents: 53822
diff changeset
  1552
              fun_names (take actual_nn thmss))
53791
0ddf045113c9 tuned code
blanchet
parents: 53753
diff changeset
  1553
          |> filter_out (null o fst o hd o snd);
60718
blanchet
parents: 60704
diff changeset
  1554
blanchet
parents: 60704
diff changeset
  1555
        val fun_ts0 = map fst def_infos;
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1556
      in
55462
78a06c7b5b87 added 'Spec_Rules' for 'primcorec'
blanchet
parents: 55414
diff changeset
  1557
        lthy
60718
blanchet
parents: 60704
diff changeset
  1558
        |> Spec_Rules.add Spec_Rules.Equational (fun_ts0, flat sel_thmss)
blanchet
parents: 60704
diff changeset
  1559
        |> Spec_Rules.add Spec_Rules.Equational (fun_ts0, flat ctr_thmss)
blanchet
parents: 60704
diff changeset
  1560
        |> Spec_Rules.add Spec_Rules.Equational (fun_ts0, flat code_thmss)
58283
71d74e641538 preserve case names in '(co)induct' theorems generated by prim(co)rec'
blanchet
parents: 58223
diff changeset
  1561
        |> Local_Theory.notes (anonymous_notes @ common_notes @ notes)
55462
78a06c7b5b87 added 'Spec_Rules' for 'primcorec'
blanchet
parents: 55414
diff changeset
  1562
        |> snd
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
  1563
        |> (fn lthy =>
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
  1564
          let
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
  1565
            val phi = Local_Theory.target_morphism lthy;
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
  1566
            val Ts = take actual_nn (map #T corec_specs);
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1567
            val fp_rec_sugar =
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1568
              {transfers = transfers, fun_names = fun_names, funs = map (Morphism.term phi) ts,
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1569
               fun_defs = Morphism.fact phi def_thms, fpTs = Ts};
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
  1570
          in
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1571
            interpret_gfp_rec_sugar plugins fp_rec_sugar lthy
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
  1572
          end)
53654
8b9ea4420f81 prove simp theorems for newly generated definitions
panny
parents: 53411
diff changeset
  1573
      end;
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1574
53822
6304b12c7627 add "primcorec" command (cf. ae7f50e70c09)
panny
parents: 53811
diff changeset
  1575
    fun after_qed thmss' = fold_map Local_Theory.define defs #-> prove thmss';
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1576
  in
61334
8d40ddaa427f collect the names from goals in favor of fragile exports
traytel
parents: 61301
diff changeset
  1577
    (goalss, after_qed, lthy)
53822
6304b12c7627 add "primcorec" command (cf. ae7f50e70c09)
panny
parents: 53811
diff changeset
  1578
  end;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1579
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
  1580
fun primcorec_ursive_cmd auto opts (raw_fixes, raw_specs_of) lthy =
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1581
  let
59607
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
  1582
    val dups = duplicates (op =) (map (Binding.name_of o #1) raw_fixes);
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
  1583
    val _ = null dups orelse error ("Duplicate function name " ^ quote (hd dups));
a93592aedce4 message tuning
blanchet
parents: 59606
diff changeset
  1584
54926
28b621fce2f9 more SML-ish (less Haskell-ish) naming convention
blanchet
parents: 54925
diff changeset
  1585
    val (raw_specs, of_specs_opt) =
56945
blanchet
parents: 56858
diff changeset
  1586
      split_list raw_specs_of ||> map (Option.map (Syntax.read_term lthy));
blanchet
parents: 56858
diff changeset
  1587
    val (fixes, specs) = fst (Specification.read_spec raw_fixes raw_specs lthy);
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1588
  in
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
  1589
    primcorec_ursive auto opts fixes specs of_specs_opt lthy
59594
43f0c669302d reworked primcorec error messages
blanchet
parents: 59582
diff changeset
  1590
  end;
53822
6304b12c7627 add "primcorec" command (cf. ae7f50e70c09)
panny
parents: 53811
diff changeset
  1591
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
  1592
val primcorecursive_cmd = (fn (goalss, after_qed, lthy) =>
54177
blanchet
parents: 54176
diff changeset
  1593
  lthy
blanchet
parents: 54176
diff changeset
  1594
  |> Proof.theorem NONE after_qed goalss
61841
4d3527b94f2a more general types Proof.method / context_tactic;
wenzelm
parents: 61760
diff changeset
  1595
  |> Proof.refine_singleton (Method.primitive_text (K I))) ooo primcorec_ursive_cmd false;
54177
blanchet
parents: 54176
diff changeset
  1596
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
  1597
val primcorec_cmd = (fn (goalss, after_qed, lthy) =>
59597
70a68edcc79b helpful error message when 'auto' fails
blanchet
parents: 59596
diff changeset
  1598
    lthy |> after_qed (map (fn [] => [] | _ => use_primcorecursive ()) goalss)) ooo
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
  1599
  primcorec_ursive_cmd true;
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1600
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1601
val corec_option_parser = Parse.group (K "option")
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1602
  (Plugin_Name.parse_filter >> Plugins_Option
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1603
   || Parse.reserved "sequential" >> K Sequential_Option
59279
blanchet
parents: 59276
diff changeset
  1604
   || Parse.reserved "exhaustive" >> K Exhaustive_Option
blanchet
parents: 59276
diff changeset
  1605
   || Parse.reserved "transfer" >> K Transfer_Option);
55529
51998cb9d6b8 tuning: moved code where it belongs
blanchet
parents: 55527
diff changeset
  1606
59794
blanchet
parents: 59674
diff changeset
  1607
val where_alt_props_of_parser = Parse.where_ |-- Parse.!!! (Parse.enum1 "|"
58394
f0c51576964a more honest 'primcorec' -- don't parse a theorem name that is then ignored
blanchet
parents: 58393
diff changeset
  1608
  ((Parse.prop >> pair Attrib.empty_binding) -- Scan.option (Parse.reserved "of" |-- Parse.const)));
55529
51998cb9d6b8 tuning: moved code where it belongs
blanchet
parents: 55527
diff changeset
  1609
59936
b8ffc3dc9e24 @{command_spec} is superseded by @{command_keyword};
wenzelm
parents: 59873
diff changeset
  1610
val _ = Outer_Syntax.local_theory_to_proof @{command_keyword primcorecursive}
55529
51998cb9d6b8 tuning: moved code where it belongs
blanchet
parents: 55527
diff changeset
  1611
  "define primitive corecursive functions"
51998cb9d6b8 tuning: moved code where it belongs
blanchet
parents: 55527
diff changeset
  1612
  ((Scan.optional (@{keyword "("} |--
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1613
      Parse.!!! (Parse.list1 corec_option_parser) --| @{keyword ")"}) []) --
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
  1614
    (Parse.fixes -- where_alt_props_of_parser) >> uncurry primcorecursive_cmd);
55529
51998cb9d6b8 tuning: moved code where it belongs
blanchet
parents: 55527
diff changeset
  1615
59936
b8ffc3dc9e24 @{command_spec} is superseded by @{command_keyword};
wenzelm
parents: 59873
diff changeset
  1616
val _ = Outer_Syntax.local_theory @{command_keyword primcorec}
55529
51998cb9d6b8 tuning: moved code where it belongs
blanchet
parents: 55527
diff changeset
  1617
  "define primitive corecursive functions"
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1618
  ((Scan.optional (@{keyword "("} |-- Parse.!!! (Parse.list1 corec_option_parser)
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1619
      --| @{keyword ")"}) []) --
60003
ba8fa0c38d66 renamed ML funs
blanchet
parents: 60001
diff changeset
  1620
    (Parse.fixes -- where_alt_props_of_parser) >> uncurry primcorec_cmd);
55529
51998cb9d6b8 tuning: moved code where it belongs
blanchet
parents: 55527
diff changeset
  1621
61348
d7215449be83 disable generation of 'case_transfer' for 'nibble', due to quadratic proof -- to make 'HOL-Proofs' happier
blanchet
parents: 61334
diff changeset
  1622
val _ = Theory.setup (gfp_rec_sugar_interpretation transfer_plugin
59281
1b4dc8a9f7d9 added plugins syntax to prim(co)rec
blanchet
parents: 59279
diff changeset
  1623
  gfp_rec_sugar_transfer_interpretation);
59275
77cd4992edcd Add plugin to generate transfer theorem for primrec and primcorec
desharna
parents: 59058
diff changeset
  1624
53303
ae49b835ca01 moved files related to "primrec_new", "primcorec", and "datatype_compat" from bitbucket co-rec repository
blanchet
parents:
diff changeset
  1625
end;