src/Tools/isac/calcelems.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Sun, 25 Mar 2018 11:57:33 +0200
changeset 59414 97790a8e6ef2
parent 59413 081cfeaf2568
child 59415 d1b52fcd4023
permissions -rw-r--r--
Celem: clean source file
neuper@37906
     1
(* elements of calculations.
neuper@37906
     2
   they are partially held in association lists as ref's for
wneuper@59405
     3
   switching language levels (meta-string, object-values).                                  
wneuper@59405
     4
   in order to keep these ref's during re-evaluation of code,                       
neuper@42399
     5
   they are defined here at the beginning of the code.
neuper@42399
     6
   Author: Walther Neuper 2003
neuper@42399
     7
   (c) copyright due to lincense terms
neuper@37906
     8
*)
neuper@37906
     9
wneuper@59405
    10
signature CALC_ELEMENT =
wneuper@59405
    11
  sig
wneuper@59413
    12
    type eval_fn
wneuper@59413
    13
    type rew_ord
wneuper@59405
    14
    eqtype errpatID
wneuper@59413
    15
    type calc
wneuper@59405
    16
        datatype rule = Cal1 of string * eval_fn | Calc of string * eval_fn | Erule | Rls_ of rls 
wneuper@59405
    17
      | Thm of string * thm
wneuper@59405
    18
    and scr
wneuper@59405
    19
      = EmptyScr
wneuper@59405
    20
      | Prog of term
wneuper@59405
    21
      | Rfuns of
wneuper@59405
    22
          {attach_form: rule list list -> term -> term -> (rule * (term * term list)) list,
wneuper@59405
    23
           init_state: term -> term * term * rule list list * (rule * (term * term list)) list,
wneuper@59405
    24
           locate_rule: rule list list -> term -> rule -> (rule * (term * term list)) list,
wneuper@59405
    25
           next_rule: rule list list -> term -> rule option,
wneuper@59405
    26
           normal_form: term -> (term * term list) option}
wneuper@59405
    27
    and rls =
wneuper@59405
    28
        Erls
wneuper@59405
    29
      | Rls of {calc: calc list, erls: rls, errpatts: errpatID list, id: string, preconds: term list, 
wneuper@59405
    30
        rew_ord: rew_ord, rules: rule list, scr: scr, srls: rls}
wneuper@59414
    31
      | Seq of {calc: calc list, erls: rls, errpatts: errpatID list, id: string, preconds: term list,
wneuper@59414
    32
        rew_ord: rew_ord, rules: rule list, scr: scr, srls: rls}
wneuper@59405
    33
      | Rrls of {calc: calc list, erls: rls, errpatts: errpatID list, 
wneuper@59405
    34
        id: string, prepat: (term list * term) list, rew_ord: rew_ord, scr: scr}
wneuper@59405
    35
wneuper@59405
    36
    eqtype rls'
wneuper@59405
    37
    eqtype theory'
wneuper@59405
    38
    eqtype prog_calcID
wneuper@59405
    39
    eqtype calID
wneuper@59413
    40
    type cas_elem
wneuper@59413
    41
    type pbt
wneuper@59413
    42
    type ptyps
wneuper@59413
    43
    type metID
wneuper@59413
    44
    type pblID
wneuper@59413
    45
    type mets
wneuper@59413
    46
    type met
wneuper@59405
    47
    datatype 'a ptyp = Ptyp of string * 'a list * 'a ptyp list
wneuper@59405
    48
wneuper@59405
    49
    type cal = calID * eval_fn
wneuper@59413
    50
    type authors
wneuper@59405
    51
    type guh
wneuper@59413
    52
    type subst
wneuper@59414
    53
    val env2str: subst -> string
wneuper@59414
    54
    val subst2str: subst -> string
wneuper@59414
    55
    val subst2str': subst -> string
wneuper@59414
    56
wneuper@59405
    57
    eqtype thyID
wneuper@59413
    58
    type fillpat
wneuper@59405
    59
    datatype thydata
wneuper@59405
    60
      = Hcal of {calc: calc, coursedesign: authors, guh: guh, mathauthors: authors}
wneuper@59405
    61
      | Hord of {coursedesign: authors, guh: guh, mathauthors: authors, ord: subst -> term * term -> bool}
wneuper@59405
    62
      | Hrls of {coursedesign: authors, guh: guh, mathauthors: authors, thy_rls: thyID * rls}
wneuper@59405
    63
      | Hthm of {coursedesign: authors, fillpats: fillpat list, guh: guh, mathauthors: authors, thm: thm}
wneuper@59405
    64
      | Html of {coursedesign: authors, guh: guh, html: string, mathauthors: authors}
wneuper@59413
    65
    type theID
wneuper@59413
    66
    type rlss_elem
wneuper@59405
    67
    val merge_rlss: rlss_elem list * rlss_elem list -> rlss_elem list
wneuper@59405
    68
    val rls_eq: (''a * ('b * 'c)) * (''a * ('d * 'e)) -> bool
wneuper@59413
    69
    type calc_elem
wneuper@59405
    70
    val calc_eq: calc_elem * calc_elem -> bool
wneuper@59413
    71
    type spec
wneuper@59405
    72
    val cas_eq: cas_elem * cas_elem -> bool
wneuper@59405
    73
    val e_Ptyp: pbt ptyp
wneuper@59405
    74
    val merge_ptyps: 'a ptyp list * 'a ptyp list -> 'a ptyp list
wneuper@59405
    75
    val check_guhs_unique: bool Unsynchronized.ref
wneuper@59405
    76
    val check_pblguh_unique: guh -> pbt ptyp list -> unit
wneuper@59405
    77
    val insrt: pblID -> 'a -> string list -> 'a ptyp list -> 'a ptyp list
wneuper@59405
    78
    val e_Mets: met ptyp
wneuper@59405
    79
    val check_metguh_unique: guh -> met ptyp list -> unit
wneuper@59405
    80
    val add_thydata: string list * string list -> thydata -> thydata ptyp list -> thydata ptyp list
wneuper@59405
    81
    val get_py: 'a ptyp list -> pblID -> string list -> 'a
wneuper@59405
    82
    val update_hthm: thydata -> fillpat list -> thydata
wneuper@59405
    83
    val update_ptyps: string list -> string list -> 'a -> 'a ptyp list -> 'a ptyp list
wneuper@59405
    84
    val e_rls: rls
wneuper@59405
    85
    val e_rrls: rls
wneuper@59405
    86
    val part2guh: theID -> guh
wneuper@59405
    87
    val spec2str: string * string list * string list -> string
wneuper@59405
    88
    val term_to_string''': theory -> term -> string
wneuper@59405
    89
    val linefeed: string -> string
wneuper@59405
    90
    val pbts2str: pbt list -> string
wneuper@59405
    91
    val thes2str: thydata list -> string
wneuper@59405
    92
    val theID2str: string list -> string
wneuper@59405
    93
    val the2str: thydata -> string
wneuper@59405
    94
    val Thy_Info_get_theory: string -> theory
wneuper@59405
    95
    val string_of_typ: typ -> string
wneuper@59405
    96
    val string_of_typ_thy: thyID -> typ -> string
wneuper@59405
    97
    val term2str: term -> string
wneuper@59405
    98
    val thy2ctxt: theory -> Proof.context
wneuper@59405
    99
    val trace_calc: bool Unsynchronized.ref
wneuper@59405
   100
    eqtype thmID
wneuper@59413
   101
    type thm'
wneuper@59405
   102
    datatype lrd = D | L | R
wneuper@59405
   103
    val trace_rewrite: bool Unsynchronized.ref
wneuper@59405
   104
    val depth: int Unsynchronized.ref
wneuper@59405
   105
    val t2str: theory -> term -> string
wneuper@59405
   106
    val ts2str: theory -> term list -> string
wneuper@59405
   107
    val terms2str: term list -> string
wneuper@59405
   108
    val id_rls: rls -> string
wneuper@59405
   109
    val rls2str: rls -> string
wneuper@59414
   110
    type errpat
wneuper@59414
   111
    val rep_rls: rls -> {calc: calc list, erls: rls, errpats: errpatID list, id: string,
wneuper@59414
   112
      preconds: term list, rew_ord: rew_ord, rules: rule list, scr: scr, srls: rls}
wneuper@59405
   113
    val string_of_thmI: thm -> string
wneuper@59405
   114
    val rule2str: rule -> string
wneuper@59405
   115
    val e_term: term
wneuper@59405
   116
    val dummy_ord: subst -> term * term -> bool
wneuper@59405
   117
    val theory2domID: theory -> theory'
wneuper@59405
   118
    val assoc_thy: theory' -> theory
wneuper@59405
   119
    val append_rls: string -> rls -> rule list -> rls
wneuper@59405
   120
    eqtype domID
wneuper@59405
   121
    val get_rules: rls -> rule list
wneuper@59405
   122
    val id_rule: rule -> string
wneuper@59405
   123
    eqtype cterm'
wneuper@59405
   124
    val term_to_string': Proof.context -> term -> string
wneuper@59405
   125
    val thy2ctxt': string -> Proof.context
wneuper@59405
   126
    type rrlsstate = term * term * rule list list * (rule * (term * term list)) list
wneuper@59413
   127
    type loc_
wneuper@59405
   128
    val loc_2str: loc_ -> string
wneuper@59405
   129
    val termopt2str: term option -> string
wneuper@59405
   130
    eqtype rew_ord'
wneuper@59413
   131
    type thm''
wneuper@59413
   132
    type rew_ord_
wneuper@59405
   133
    val metID2str: string list -> string
wneuper@59405
   134
    val e_domID: domID
wneuper@59405
   135
    val e_pblID: pblID
wneuper@59405
   136
    val e_metID: metID
wneuper@59405
   137
    val empty_spec: spec
wneuper@59414
   138
    val e_spec: spec
wneuper@59405
   139
    datatype ketype = Exp_ | Met_ | Pbl_ | Thy_
wneuper@59413
   140
    type kestoreID
wneuper@59405
   141
    val app_py: 'a ptyp list -> ('a ptyp -> 'b) -> pblID -> string list -> 'b
wneuper@59405
   142
    val ketype2str: ketype -> string
wneuper@59405
   143
    val coll_pblguhs: pbt ptyp list -> guh list
wneuper@59405
   144
    val coll_metguhs: met ptyp list -> guh list
wneuper@59413
   145
    type pat
wneuper@59405
   146
    val e_type: typ
wneuper@59405
   147
    val theory2str: theory -> theory'
wneuper@59405
   148
    val pats2str: pat list -> string
wneuper@59405
   149
    val string_of_thy: theory -> theory'
wneuper@59405
   150
    val theory2theory': theory -> theory'
wneuper@59405
   151
    val maxthy: theory -> theory -> theory
wneuper@59405
   152
    val e_evalfn: 'a -> term -> theory -> (string * term) option
wneuper@59405
   153
    val assoc_rew_ord: string -> subst -> term * term -> bool
wneuper@59405
   154
    eqtype filename
wneuper@59405
   155
    val rule2str': rule -> string
wneuper@59405
   156
    val lim_deriv: int Unsynchronized.ref
wneuper@59405
   157
    val id_of_thm: rule -> string
wneuper@59405
   158
    val isabthys: unit -> theory list
wneuper@59405
   159
    val thyID_of_derivation_name: string -> string
wneuper@59405
   160
    val partID': theory' -> string
wneuper@59405
   161
    val Isac: 'a -> theory
wneuper@59405
   162
    val theory'2thyID: theory' -> theory'
wneuper@59405
   163
    val thm2guh: string * thyID -> thmID -> guh
wneuper@59405
   164
    val thmID_of_derivation_name: string -> string
wneuper@59405
   165
    val rls2guh: string * thyID -> rls' -> guh
wneuper@59405
   166
    val eq_rule: rule * rule -> bool
wneuper@59405
   167
    val e_rew_ordX: rew_ord
wneuper@59405
   168
    val theID2guh: theID -> guh
wneuper@59405
   169
    val thyID2theory': thyID -> thyID
wneuper@59405
   170
    val e_rule: rule
wneuper@59405
   171
    val scr2str: scr -> string
wneuper@59405
   172
    val type2str: typ -> string
wneuper@59405
   173
    eqtype fillpatID
wneuper@59405
   174
    type pbt_ = string * (term * term)
wneuper@59405
   175
    val e_rew_ord: subst -> term * term -> bool
wneuper@59405
   176
    eqtype xml
wneuper@59405
   177
    val cal2guh: string * thyID -> string -> guh
wneuper@59405
   178
    val ketype2str': ketype -> string
wneuper@59405
   179
    val str2ketype': string -> ketype
wneuper@59405
   180
    val thmID_of_derivation_name': thm -> string
wneuper@59405
   181
    eqtype path
wneuper@59405
   182
    val theID2thyID: theID -> thyID
wneuper@59405
   183
    val thy2guh: theID -> guh
wneuper@59405
   184
    val theory2thyID: theory -> thyID
wneuper@59405
   185
    val thypart2guh: theID -> guh
wneuper@59405
   186
    val ord2guh: string * thyID -> rew_ord' -> guh
wneuper@59405
   187
    val update_hrls: thydata -> errpatID list -> thydata
wneuper@59405
   188
    eqtype iterID
wneuper@59405
   189
    eqtype calcID
wneuper@59405
   190
    val thm''_of_thm: thm -> thm''
wneuper@59405
   191
    val rew_ord': (rew_ord' * (subst -> term * term -> bool)) list Unsynchronized.ref
wneuper@59406
   192
    val merge_rls: string -> rls -> rls -> rls
wneuper@59406
   193
    val e_rrlsstate: rrlsstate
wneuper@59406
   194
    val thm_of_thm: rule -> thm
wneuper@59406
   195
    val remove_rls: string -> rls -> rule list -> rls
wneuper@59408
   196
(* ---- for tests only: shifted from below to remove the Warning "unused" at fun.def. --------- *)
wneuper@59414
   197
    val thm2str: thm -> string
wneuper@59414
   198
    val term_to_string'': thyID -> term -> string
wneuper@59414
   199
    val terms2str': term list -> string
wneuper@59414
   200
    val insert_fillpats: thydata ptyp list -> (pblID * fillpat list) list -> thydata ptyp list ->
wneuper@59414
   201
      thydata ptyp list
wneuper@59408
   202
(*/-------------------------------------------------------- ! aktivate for Test_Isac BEGIN ---\* )
wneuper@59410
   203
    val terms2strs: term list -> string list
wneuper@59411
   204
    val string_of_thm': theory -> thm -> string
wneuper@59411
   205
    val string_of_thm: thm -> string
wneuper@59411
   206
    val knowthys: unit -> theory list
wneuper@59411
   207
    val e_pbt: pbt
wneuper@59408
   208
( *\--- ! aktivate for Test_Isac END ----------------------------------------------------------/*)
wneuper@59414
   209
wneuper@59414
   210
(*----- unused code, kept as hints to design ideas ---------------------------------------------*)
wneuper@59414
   211
val overwritelthy: theory -> (rls' * (string * rls)) list * (rls' * rls) list ->
wneuper@59414
   212
  (rls' * (string * rls)) list  end
wneuper@59414
   213
wneuper@59408
   214
wneuper@59405
   215
(**)
wneuper@59405
   216
structure Celem(**): CALC_ELEMENT(**) =
neuper@38061
   217
struct
wneuper@59405
   218
(**)
wneuper@59405
   219
wneuper@59414
   220
val linefeed = (curry op^) "\n"; (* ?\<longrightarrow> libraryC ?*)
neuper@37906
   221
type authors = string list;
neuper@37906
   222
neuper@37906
   223
type cterm' = string;
wneuper@59414
   224
type iterID = int;
wneuper@59414
   225
type calcID = int;
neuper@42399
   226
neuper@55481
   227
(* TODO CLEANUP Thm:
neuper@55487
   228
type rule = 
neuper@55487
   229
Thm (string, thm): (a) needs string to identify sym_thmID for handling in front-end;
neuper@55487
   230
                   (b) investigate if ""RS sym" attaches a [.]" still occurs: string_of_thmI
neuper@55487
   231
thmID            : type for data from user input + program
neuper@55487
   232
thmDeriv         : type for thy_hierarchy ONLY
neuper@55487
   233
obsolete types   : thm' (SEE "ad thm'"), thm''. 
wneuper@59250
   234
revise funs      : id_of_thm, thm_of_thm, rep_thm_G', eq_thmI, eq_thmI', thm''_of_thm thm.
neuper@55487
   235
activate         : thmID_of_derivation_name'
neuper@55481
   236
*)
neuper@42399
   237
type thmID = string;    (* identifier for a thm (the shortest possible identifier)       *)
neuper@42434
   238
type thmDeriv = string; (* WN120524 deprecated
neuper@42434
   239
  thyID ^"."^ xxx ^"."^ thmID, see fun thmID_of_derivation_name 
neuper@42434
   240
  WN120524: dont use Thm.derivation_name, this is destroyed by num_str;
neuper@42434
   241
  Thm.get_name_hint survives num_str and seems perfectly reliable *)
neuper@42399
   242
wneuper@59414
   243
type thm' = thmID * cterm';(*WN060610 deprecated in favour of thm''; WN180324: used in TODO review:
wneuper@59414
   244
val thm'2xml : int -> Celem.thm' -> Celem.xml
wneuper@59414
   245
val assoc_thm': theory -> Celem.thm' -> thm
wneuper@59414
   246
| Calculate' of Celem.theory' * string * term * (term * Celem.thm')
wneuper@59414
   247
*)
wneuper@59251
   248
(* tricky combination of (string, term) for theorems in Isac:
wneuper@59251
   249
  * case 1 general: frontend + lucin, e.g. applicable_in..Rewrite: (thmID, _) --> (thmID, thm)
wneuper@59251
   250
    by Global_Theory.get_thm, special cases ("add_commute",..) see convert_metaview_to_thmid.
wneuper@59251
   251
  * case 2 "sym_..": Global_Theory.get_thm..RS sym
wneuper@59251
   252
  * case 3 ad-hoc thm "#..." mk_thm from ad-hoc term (numerals only) in calculate_:
wneuper@59255
   253
    from applicable_in..Calculate: opstr --calculate_/adhoc_thm--> (thmID, thm)
wneuper@59251
   254
*)
wneuper@59253
   255
type thm'' = thmID * thm; (* only for transport via libisabelle isac-java <--- ME *)
neuper@37906
   256
type rls' = string;
neuper@42399
   257
neuper@40836
   258
(*.a 'guh'='globally unique handle' is a string unique for each element
neuper@37906
   259
   of isac's KEStore and persistent over time
neuper@37906
   260
   (in particular under shifts within the respective hierarchy);
neuper@40836
   261
   specialty for thys:
neuper@37906
   262
   # guh NOT resistant agains shifts from one thy to another
neuper@37906
   263
   (which is the price for Isabelle's design: thy's overwrite ids of subthy's)
neuper@37906
   264
   # requirement for matchTheory: induce guh from tac + current thy
neuper@37906
   265
   (see 'fun thy_containing_thm', 'fun thy_containing_rls' etc.)
neuper@40836
   266
   TODO: introduce to pbl, met.*)
neuper@37906
   267
type guh = string;
neuper@37906
   268
wneuper@59141
   269
type xml = string; (* rm together with old code replaced by XML.tree *)
neuper@37906
   270
neuper@52154
   271
(* eval function calling sml code during rewriting.
neuper@52154
   272
Unifying "type cal" and "type calc" would make Lucas-Interpretation more efficient,
neuper@52154
   273
  see "fun rule2stac": instead of 
neuper@52154
   274
    Calc: calID * eval_fn -> rule
neuper@52154
   275
  would be better
neuper@52154
   276
    Calc: prog_calcID * (calID * eval_fn)) -> rule*)
neuper@37906
   277
type eval_fn = (string -> term -> theory -> (string * term) option);
wneuper@59414
   278
fun e_evalfn (_ : 'a) (_ : term) (_ : theory) = NONE : (string * term) option;
wneuper@59414
   279
(* op in isa-term "Const(op,_)" *)
neuper@37906
   280
type calID = string;
wneuper@59414
   281
type cal = calID * eval_fn;
neuper@52117
   282
type prog_calcID = string;
neuper@52117
   283
type calc = (prog_calcID * cal);
wneuper@59414
   284
type calc_elem =  (* fun calculate_ fetches the evaluation-function via this list *)
neuper@52141
   285
  prog_calcID *   (* a simple identifier used in programs *)
neuper@52141
   286
  (calID *        (* a long identifier used in Const *)
neuper@52141
   287
    eval_fn)      (* an ML function *)
wneuper@59414
   288
fun calc_eq ((pi1, (ci1, _)), (pi2, (ci2, _))) =
neuper@52141
   289
  if pi1 = pi2
neuper@52141
   290
  then if ci1 = ci2 then true else error ("calc_eq: " ^ ci1 ^ " <> " ^ ci2)
neuper@52141
   291
  else false
neuper@52141
   292
wneuper@59414
   293
(*WN180324 TODO clean types subst, *)
neuper@37906
   294
type subs' = (cterm' * cterm') list; (*16.11.00 for FE-KE*)
neuper@37906
   295
type subst = (term * term) list; (*here for ets2str*)
neuper@37906
   296
neuper@37906
   297
(*TODO.WN060610 make use of "type rew_ord" total*)
neuper@37906
   298
type rew_ord' = string;
neuper@37906
   299
val e_rew_ord' = "e_rew_ord" : rew_ord';
neuper@37906
   300
type rew_ord_ = subst -> Term.term * Term.term -> bool;
neuper@37906
   301
fun dummy_ord (_:subst) (_:term,_:term) = true;
neuper@37906
   302
val e_rew_ord_ = dummy_ord;
neuper@37906
   303
type rew_ord = rew_ord' * rew_ord_;
neuper@37906
   304
val e_rew_ord = dummy_ord; (* TODO.WN071231 clarify identifiers..e_rew_ordX*)
neuper@37906
   305
val e_rew_ordX = (e_rew_ord', e_rew_ord_) : rew_ord;
neuper@37906
   306
neuper@42451
   307
(* error patterns and fill patterns *)
neuper@42451
   308
type errpatID = string
neuper@42451
   309
type errpat =
neuper@42451
   310
  errpatID    (* one identifier for a list of patterns                       
neuper@42451
   311
                 DESIGN ?TODO: errpatID list for hierarchy of errpats ?      *)
neuper@42451
   312
  * term list (* error patterns                                              *)
neuper@42451
   313
  * thm list  (* thms related to error patterns; note that respective lhs 
neuper@42451
   314
                 do not match (which reflects student's error).
neuper@42451
   315
                 fillpatterns are stored with these thms.                    *)
neuper@42451
   316
neuper@42451
   317
(* for (at least) 2 kinds of access:
neuper@42451
   318
  (1) given an errpatID, find the respective fillpats (e.g. in fun find_fill_pats)
neuper@42451
   319
  (2) given a thm, find respective fillpats *)
neuper@42451
   320
type fillpatID = string
neuper@42451
   321
type fillpat =
neuper@42451
   322
  fillpatID   (* DESIGN ?TODO: give an order w.r.t difficulty ? *)
neuper@42451
   323
  * term      (* the pattern with fill-in gaps                  *)
neuper@42451
   324
  * errpatID; (* which the fillpat would be a help for          
neuper@42451
   325
                 DESIGN ?TODO: list for several patterns ?      *)
neuper@37906
   326
neuper@40836
   327
datatype rule =
neuper@37906
   328
  Erule                (*.the empty rule                     .*)
neuper@55481
   329
| Thm of (string * Basic_Thm.thm) (* see TODO CLEANUP Thm     *)
neuper@37906
   330
| Calc of string *     (*.sml-code manipulating a (sub)term  .*)
neuper@55487
   331
	  eval_fn
neuper@37906
   332
| Cal1 of string *     (*.sml-code applied only to whole term
neuper@37906
   333
                          or left/right-hand-side of eqality .*)
neuper@55487
   334
	  eval_fn
neuper@37906
   335
| Rls_ of rls          (*.ie. rule sets may be nested.*)
neuper@40836
   336
and scr =
neuper@40836
   337
    EmptyScr
wneuper@59257
   338
  | Prog of term (* a leaf is either a tactic or an 'exp' in 'let v = expr' 
wneuper@59257
   339
                    where 'exp' does not contain a tactic. *)
neuper@52101
   340
  | Rfuns of     (* for Rrls, usage see rational.sml ----- reverse rewrite -----      *)
neuper@52084
   341
    {init_state : (* initialise for reverse rewriting by the Interpreter              *)
neuper@52084
   342
      term ->         (* for this the rrlsstate is initialised:                       *)
neuper@52084
   343
      term *          (* the current formula: goes locate_gen -> next_tac via istate  *)
neuper@52084
   344
      term *          (* the final formula                                            *)
neuper@52084
   345
      rule list       (* of reverse rewrite set (#1#)                                 *)
neuper@52084
   346
        list *        (*   may be serveral, eg. in norm_rational                      *)
neuper@52084
   347
      ( rule *        (* Thm (+ Thm generated from Calc) resulting in ...             *)
neuper@52084
   348
        (term *       (*   ... rewrite with ...                                       *)
neuper@52084
   349
        term list))   (*   ... assumptions                                            *)
neuper@52084
   350
      list,           (* derivation from given term to normalform
neuper@52084
   351
                         in reverse order with sym_thm;
neuper@52084
   352
                                                (#1#) could be extracted from here #1 *)  
neuper@52084
   353
	  normal_form:  (* the function which drives the Rrls ##############################*)
neuper@52084
   354
	    term -> (term * term list) option,
neuper@52084
   355
	  locate_rule:  (* checks a rule R for being a cancel-rule, and if it is,
neuper@52084
   356
                     then return the list of rules (+ the terms they are rewriting to)
neuper@52084
   357
                     which need to be applied before R should be applied.
neuper@52084
   358
                     precondition: the rule is applicable to the argument-term.       *)
neuper@52084
   359
	    rule list list -> (* the reverse rule list                                      *)
neuper@52084
   360
	    term ->         (* ... to which the rule shall be applied                       *)
neuper@52084
   361
	    rule ->         (* ... to be applied to term                                    *)
neuper@52084
   362
	    ( rule *        (* value: a rule rewriting to ...                               *)
neuper@52084
   363
	      (term *       (*   ... the resulting term ...                                 *)
neuper@52084
   364
	      term list))   (*   ... with the assumptions ( //#0)                           *)
neuper@52084
   365
	    list,           (*   there may be several such rules; the list is empty,          
neuper@52084
   366
                           if the rule has nothing to do with e.g. cancelation        *)
neuper@52084
   367
	  next_rule:    (* for a given term return the next rules to be done for cancelling *)
neuper@52084
   368
	    rule list list->(* the reverse rule list                                        *)
neuper@52084
   369
	    term ->         (* the term for which ...                                       *)
neuper@52084
   370
	    rule option,    (* ... this rule is appropriate for cancellation;
neuper@52084
   371
		                     there may be no such rule (if the term is eg.canceled already*)
neuper@52084
   372
	  attach_form:  (* checks an input term TI, if it may belong to e.g. a current 
neuper@52084
   373
                     cancellation, by trying to derive it from the given term TG.     
neuper@52084
   374
                     NOT IMPLEMENTED                                                 *)
neuper@52084
   375
	    rule list list->(**)
neuper@52084
   376
	    term ->         (* TG, the last one agreed upon by user + math-eng              *)
neuper@52084
   377
	    term ->         (* TI, the next one input by the user                           *)
neuper@52084
   378
	    ( rule *        (* the rule to be applied in order to reach TI                  *) 
neuper@52084
   379
	      (term *       (* ... obtained by applying the rule ...                        *)
neuper@52084
   380
	      term list))   (* ... and the respective assumptions                           *) 
neuper@52084
   381
	    list}           (* there may be several such rules; the list is empty, if the 
neuper@52084
   382
                         users term does not belong to e.g. a cancellation of the term 
neuper@52084
   383
                         last agreed upon.                                            *)
neuper@37906
   384
and rls =
neuper@37906
   385
    Erls                          (*for init e_rls*)
neuper@40836
   386
neuper@37906
   387
  | Rls of (*a confluent and terminating ruleset, in general         *)
neuper@37906
   388
    {id : string,          (*for trace_rewrite:=true                 *)
neuper@37906
   389
     preconds : term list, (*unused WN020820                         *)
neuper@37906
   390
     (*WN060616 for efficiency...
s1210629013@55444
   391
      bdvs    : false,       (*set in prep_rls' for get_bdvs *)*)
neuper@37906
   392
     rew_ord  : rew_ord,   (*for rules*)
neuper@37906
   393
     erls     : rls,       (*for the conditions in rules             *)
neuper@37906
   394
     srls     : rls,       (*for evaluation of list_fns in script    *)
s1210629013@55444
   395
     calc     : calc list, (*for Calculate in scr, set by prep_rls'   *)
neuper@37906
   396
     rules    : rule list,
neuper@42451
   397
     errpatts : errpatID list,(*dialog-authoring in Build_Thydata.thy*)
neuper@48763
   398
     scr      : scr}       (*Prog term: generating intermed.steps  *)
neuper@37906
   399
  | Seq of (*a sequence of rules to be tried only once               *)
neuper@37906
   400
    {id : string,          (*for trace_rewrite:=true                 *)
neuper@37906
   401
     preconds : term list, (*unused 20.8.02                          *)
neuper@37906
   402
     (*WN060616 for efficiency...
s1210629013@55444
   403
      bdvs    : false,       (*set in prep_rls' for get_bdvs *)*)
neuper@37906
   404
     rew_ord  : rew_ord,   (*for rules                               *)
neuper@37906
   405
     erls     : rls,       (*for the conditions in rules             *)
neuper@37906
   406
     srls     : rls,       (*for evaluation of list_fns in script    *)
s1210629013@55444
   407
     calc     : calc list, (*for Calculate in scr, set by prep_rls'   *)
neuper@37906
   408
     rules    : rule list,
neuper@42451
   409
     errpatts : errpatID list,(*dialog-authoring in Build_Thydata.thy*)
neuper@48763
   410
     scr      : scr}  (*Prog term  (how to restrict type ???)*)
neuper@52084
   411
neuper@37906
   412
  (*Rrls call SML-code and simulate an rls
neuper@37906
   413
    difference: there is always _ONE_ redex rewritten in 1 call,
neuper@37906
   414
    thus wrap Rrls by: Rls (Rls_ ...)*)
neuper@52084
   415
  | Rrls of (* SML-functions within rewriting; step-wise execution provided;   
neuper@52084
   416
               Rrls simulate an rls
neuper@52084
   417
               difference: there is always _ONE_ redex rewritten in 1 call,
neuper@52084
   418
               thus wrap Rrls by: Rls (Rls_ ...)                              *)
neuper@38036
   419
    {id : string,          (* for trace_rewrite := true                       *)
neuper@40836
   420
     prepat  : (term list *(* preconds, eval with subst from pattern;
neuper@52084
   421
                              if [@{term True}], match decides alone          *)
neuper@52084
   422
		            term )     (* pattern matched with current (sub)term          *)
neuper@52084
   423
		   list,               (* meta-conjunction is or                          *)
neuper@38036
   424
     rew_ord  : rew_ord,   (* for rules                                       *)
neuper@38036
   425
     erls     : rls,       (* for the conditions in rules and preconds        *)
s1210629013@55444
   426
     calc     : calc list, (* for Calculate in scr, set automatic.in prep_rls' *)
neuper@42451
   427
     errpatts : errpatID list,(*dialog-authoring in Build_Thydata.thy*)
neuper@38036
   428
     scr      : scr};      (* Rfuns {...}  (how to restrict type ???)         *)
wneuper@59414
   429
fun id_rls Erls = "e_rls" (*WN060714 quick and dirty: recursive defs! TODO "Erls" *)
wneuper@59414
   430
  | id_rls (Rls {id, ...}) = id
wneuper@59414
   431
  | id_rls (Seq {id, ...}) = id
wneuper@59414
   432
  | id_rls (Rrls {id, ...}) = id;
wneuper@59414
   433
val rls2str = id_rls;
wneuper@59414
   434
fun id_rule (Thm (id, _)) = id
wneuper@59414
   435
  | id_rule (Calc (id, _)) = id
wneuper@59414
   436
  | id_rule (Cal1 (id, _)) = id
wneuper@59414
   437
  | id_rule (Rls_ rls) = id_rls rls
wneuper@59414
   438
  | id_rule Erule = "Erule";
wneuper@59414
   439
fun eq_rule (Thm (thm1, _), Thm (thm2, _)) = thm1 = thm2
wneuper@59414
   440
  | eq_rule (Calc (id1, _), Calc (id2, _)) = id1 = id2
wneuper@59414
   441
  | eq_rule (Rls_ rls1, Rls_ rls2) = id_rls rls1 = id_rls rls2
wneuper@59414
   442
  | eq_rule _ = false;
neuper@37906
   443
neuper@55477
   444
(*ad thm':
neuper@55477
   445
   there are two kinds of theorems ...
neuper@55477
   446
   (1) known by isabelle
neuper@55477
   447
   (2) not known, eg. calc_thm, instantiated rls
neuper@55477
   448
       the latter have a thmid "#..."
neuper@55481
   449
   and thus outside isa we ALWAYS transport both (thmID, string_of_thmI)
neuper@55477
   450
   and have a special assoc_thm / assoc_rls in this interface      *)
neuper@55477
   451
type theory' = string; (* = domID ^".thy" WN.101011 ABOLISH !*)
neuper@55477
   452
type domID = string;   (* domID ^".thy" = theory' WN.101011 replace by thyID*)
wneuper@59414
   453
type thyID = string;   (* WN.3.11.03 TODO: replace domID with thyID*)
wneuper@59414
   454
val e_domID = "e_domID" : domID;
wneuper@59352
   455
wneuper@59352
   456
(* Since Isabelle2017 sessions in theory identifiers are enforced.
wneuper@59352
   457
  However, we leave theory identifiers short, in particular in use as keys into KEStore. *)
wneuper@59355
   458
fun Thy_Info_get_theory thyID = Thy_Info.get_theory ("Isac." ^ thyID)
wneuper@59352
   459
fun thy2ctxt' thy' = Proof_Context.init_global (Thy_Info_get_theory thy');(*FIXXXME thy-ctxt*)
neuper@48760
   460
fun thy2ctxt thy = Proof_Context.init_global thy;(*FIXXXME thy-ctxt*)
neuper@48760
   461
fun Isac _ = Proof_Context.theory_of (thy2ctxt' "Isac"); (*@{theory "Isac"}*)
neuper@37906
   462
neuper@37906
   463
fun string_of_thy thy = Context.theory_name thy: theory';
neuper@37906
   464
val theory2domID = string_of_thy;
neuper@37906
   465
val theory2thyID = (get_thy o string_of_thy) : theory -> thyID;
neuper@37906
   466
val theory2theory' = string_of_thy;
neuper@37906
   467
val theory2str = string_of_thy; (*WN050903 ..most consistent naming*)
neuper@37906
   468
neuper@38058
   469
fun thyID2theory' (thyID:thyID) = thyID;
neuper@38058
   470
fun theory'2thyID (theory':theory') = theory';
wneuper@59414
   471
(*  WN0509 discussion:
neuper@37906
   472
#############################################################################
neuper@37906
   473
#   How to manage theorys in subproblems wrt. the requirement,              #
neuper@37906
   474
#   that scripts should be re-usable ?                                      #
neuper@37906
   475
#############################################################################
neuper@37906
   476
neuper@37988
   477
    eg. 'Script Solve_rat_equation' calls 'SubProblem (RatEq',..'
neuper@37906
   478
    which would not allow to 'solve (y'' = -M_b / EI, M_b)' by this script
neuper@40836
   479
    because Biegelinie.thy is subthy of RatEq.thy and thus Biegelinie.M_b
neuper@37906
   480
    is unknown in RatEq.thy and M_b cannot be parsed into the scripts guard
neuper@37906
   481
    (see match_ags).
neuper@37906
   482
neuper@37906
   483
    Preliminary solution:
neuper@38011
   484
    # the thy in 'SubProblem (thy', pbl, arglist)' is not taken automatically,
neuper@38011
   485
    # instead the 'maxthy (rootthy pt) thy' is taken for each subpbl
neuper@40836
   486
    # however, a thy specified by the user in the rootpbl may lead to
neuper@40836
   487
      errors in far-off subpbls (which are not yet reported properly !!!)
neuper@37906
   488
      and interactively specifiying thys in subpbl is not very relevant.
neuper@37906
   489
neuper@37906
   490
    Other solutions possible:
wneuper@59352
   491
    # always parse and type-check with Thy_Info_get_theory "Isac"
wneuper@59414
   492
      (rejected due to the vague idea eg. to re-use equations for R in C etc.)
neuper@37906
   493
    # regard the subthy-relation in specifying thys of subpbls
neuper@38011
   494
    # specifically handle 'SubProblem (undefined, pbl, arglist)'
neuper@37906
   495
    # ???
wneuper@59414
   496
*)
wneuper@59414
   497
wneuper@59414
   498
wneuper@59414
   499
wneuper@59414
   500
wneuper@59414
   501
wneuper@59414
   502
fun thm2str thm =
wneuper@59414
   503
  let
wneuper@59414
   504
    val t = Thm.prop_of thm
wneuper@59414
   505
    val ctxt = Proof_Context.init_global (Thy_Info.get_theory ("Isac.Isac"))
wneuper@59414
   506
    val ctxt' = Config.put show_markup false ctxt
wneuper@59414
   507
  in Print_Mode.setmp [] (Syntax.string_of_term ctxt') t end;
wneuper@59414
   508
fun term_to_string' ctxt t =
wneuper@59414
   509
  let
wneuper@59414
   510
    val ctxt' = Config.put show_markup false ctxt
wneuper@59414
   511
  in Print_Mode.setmp [] (Syntax.string_of_term ctxt') t end;
wneuper@59414
   512
fun term_to_string'' thyID t =
wneuper@59414
   513
  let
wneuper@59414
   514
    val ctxt' = Config.put show_markup false (Proof_Context.init_global (Thy_Info_get_theory thyID))
wneuper@59414
   515
  in Print_Mode.setmp [] (Syntax.string_of_term ctxt') t end;
wneuper@59414
   516
fun term_to_string''' thy t =
wneuper@59414
   517
  let
wneuper@59414
   518
    val ctxt' = Config.put show_markup false (Proof_Context.init_global thy)
wneuper@59414
   519
  in Print_Mode.setmp [] (Syntax.string_of_term ctxt') t end;
wneuper@59414
   520
wneuper@59414
   521
fun term2str t = term_to_string' (thy2ctxt' "Isac") t;
wneuper@59414
   522
fun t2str thy t = term_to_string' (thy2ctxt thy) t;
wneuper@59414
   523
fun ts2str thy ts = ts |> map (t2str thy) |> strs2str';
wneuper@59414
   524
fun terms2strs ts = map term2str ts;     (* terms2strs [t1,t2] = ["1 + 2", "abc"];      *)
wneuper@59414
   525
val terms2str = strs2str o terms2strs;   (* terms2str  [t1,t2] = "[\"1 + 2\",\"abc\"]"; *)
wneuper@59414
   526
val terms2str' = strs2str' o terms2strs; (* terms2str' [t1,t2] = "[1 + 2,abc]";         *)
wneuper@59414
   527
fun termopt2str (SOME t) = "(SOME " ^ term2str t ^ ")"
wneuper@59414
   528
  | termopt2str NONE = "NONE";
wneuper@59414
   529
wneuper@59414
   530
fun type_to_string'' (thyID : thyID) t =
wneuper@59414
   531
  let
wneuper@59414
   532
    val ctxt' = Config.put show_markup false (Proof_Context.init_global (Thy_Info_get_theory thyID))
wneuper@59414
   533
  in Print_Mode.setmp [] (Syntax.string_of_typ ctxt') t end;
wneuper@59414
   534
fun type2str typ = type_to_string'' "Isac" typ; (*TODO legacy*)
wneuper@59414
   535
val string_of_typ = type2str; (*legacy*)
wneuper@59414
   536
fun string_of_typ_thy thy typ = type_to_string'' thy typ; (*legacy*)
wneuper@59414
   537
                 
wneuper@59414
   538
val e_rule = Thm ("refl", @{thm refl});
wneuper@59414
   539
fun id_of_thm (Thm (id, _)) = id  (* TODO re-arrange code for rule2str *)
wneuper@59414
   540
  | id_of_thm _ = raise ERROR ("id_of_thm: uncovered case " (* ^ rule2str r *))
wneuper@59414
   541
fun thm_of_thm (Thm (_, thm)) = thm  (* TODO re-arrange code for rule2str *)
wneuper@59414
   542
  | thm_of_thm _ = raise ERROR ("thm_of_thm: uncovered case " (* ^ rule2str r *))
wneuper@59414
   543
wneuper@59414
   544
fun thmID_of_derivation_name dn = last_elem (space_explode "." dn);
wneuper@59414
   545
fun thmID_of_derivation_name' thm = (thmID_of_derivation_name o Thm.get_name_hint) thm
wneuper@59414
   546
fun thyID_of_derivation_name dn = hd (space_explode "." dn);
wneuper@59414
   547
fun thm''_of_thm thm = (thmID_of_derivation_name' thm, thm) : thm''
wneuper@59414
   548
wneuper@59414
   549
(*check for [.] as caused by "fun assoc_thm'"*)
wneuper@59414
   550
fun string_of_thm thm = term_to_string' (thy2ctxt' "Isac") (Thm.prop_of thm)
wneuper@59414
   551
fun string_of_thm' thy thm = term_to_string' (thy2ctxt thy) (Thm.prop_of thm)
wneuper@59414
   552
fun string_of_thmI thm =
wneuper@59414
   553
  let 
wneuper@59414
   554
    val str = (de_quote o string_of_thm) thm
wneuper@59414
   555
    val (a, b) = split_nlast (5, Symbol.explode str)
wneuper@59414
   556
  in 
wneuper@59414
   557
    case b of
wneuper@59414
   558
      [" ", " ","[", ".", "]"] => implode a
wneuper@59414
   559
    | _ => str
wneuper@59414
   560
  end
wneuper@59414
   561
wneuper@59414
   562
fun get_rules Erls = []
wneuper@59414
   563
  | get_rules (Rls {rules, ...}) = rules
wneuper@59414
   564
  | get_rules (Seq {rules, ...}) = rules
wneuper@59414
   565
  | get_rules (Rrls _) = [];
wneuper@59414
   566
fun rule2str Erule = "Erule"
wneuper@59414
   567
  | rule2str (Thm (str, thm)) = "Thm (\""^str^"\","^(string_of_thmI thm)^")"
wneuper@59414
   568
  | rule2str (Calc (str, _)) = "Calc (\""^str^"\",fn)"
wneuper@59414
   569
  | rule2str (Cal1 (str, _)) = "Cal1 (\""^str^"\",fn)"
wneuper@59414
   570
  | rule2str (Rls_ rls) = "Rls_ (\""^id_rls rls^"\")";
wneuper@59414
   571
fun rule2str' Erule = "Erule"
wneuper@59414
   572
  | rule2str' (Thm (str, _)) = "Thm (\""^str^"\",\"\")"
wneuper@59414
   573
  | rule2str' (Calc (str, _)) = "Calc (\""^str^"\",fn)"
wneuper@59414
   574
  | rule2str' (Cal1 (str, _)) = "Cal1 (\""^str^"\",fn)"
wneuper@59414
   575
  | rule2str' (Rls_ rls) = "Rls_ (\""^id_rls rls^"\")";
wneuper@59414
   576
wneuper@59414
   577
type rrlsstate =  (* state for reverse rewriting, comments see type rule and scr | Rfuns *)
wneuper@59414
   578
  (term * term * rule list list * (rule * (term * term list)) list);
wneuper@59414
   579
wneuper@59414
   580
val e_type = Type ("empty",[]);
wneuper@59414
   581
val e_term = Const ("empty", e_type);
wneuper@59414
   582
val e_rrlsstate = (e_term,e_term, [[e_rule]], [(e_rule, (e_term, []))]);
wneuper@59414
   583
val e_term = Const ("empty", Type("'a", []));
neuper@37906
   584
neuper@37906
   585
(*the key into the hierarchy ob theory elements*)
neuper@37906
   586
type theID = string list;
wneuper@59414
   587
val theID2str = strs2str; (*theID eg. is ["IsacKnowledge", "Test", "Rulesets", "ac_plus_times"]*)
wneuper@59414
   588
fun theID2thyID theID =
wneuper@59414
   589
  if length theID >= 3 then (last_elem o (drop_last_n 2)) theID
wneuper@59414
   590
  else error ("theID2thyID called with " ^ theID2str theID);
neuper@37906
   591
neuper@37906
   592
(*the key into the hierarchy ob problems*)
wneuper@59414
   593
type pblID = string list; (* domID :: ...*)
wneuper@59414
   594
val e_pblID = ["e_pblID"];
neuper@37906
   595
neuper@37906
   596
(*the key into the hierarchy ob methods*)
neuper@37906
   597
type metID = string list;
wneuper@59414
   598
type spec = domID * pblID * metID;
wneuper@59414
   599
fun spec2str (dom, pbl, met) = 
wneuper@59414
   600
  "(" ^ quote dom  ^ ", " ^ strs2str pbl ^ ", " ^ strs2str met ^ ")";
wneuper@59414
   601
val e_metID = ["e_metID"];
neuper@37906
   602
val metID2str = strs2str;
wneuper@59414
   603
val empty_spec = (e_domID, e_pblID, e_metID);
s1210629013@52171
   604
val e_spec = empty_spec;
s1210629013@52171
   605
wneuper@59414
   606
(* association list with cas-commands, for generating a complete calc-head *)
neuper@52169
   607
type generate_fn = 
neuper@52169
   608
  (term list ->    (* the arguments of the cas-command, eg. (x+1=2, x) *)
neuper@52169
   609
    (term *        (* description of an element                        *)
neuper@52169
   610
      term list)   (* value of the element (always put into a list)    *)
neuper@52169
   611
  list)            (* of elements in the formalization                 *)
neuper@52169
   612
type cas_elem = 
neuper@52169
   613
  (term *          (* cas-command, eg. 'solve'                         *)
neuper@52169
   614
    (spec *        (* theory, problem, method                          *)
s1210629013@52174
   615
    generate_fn))
neuper@52169
   616
fun cas_eq ((t1, (_, _)) : cas_elem, (t2, (_, _)) : cas_elem) = t1 = t2
s1210629013@52167
   617
neuper@37906
   618
(*either theID or pblID or metID*)
neuper@37906
   619
type kestoreID = string list;
neuper@37906
   620
wneuper@59414
   621
(* for distinction of contexts WN130621: disambiguate with Isabelle's Context *)
neuper@37906
   622
datatype ketype = Exp_ | Thy_ | Pbl_ | Met_;
neuper@37906
   623
fun ketype2str Exp_ = "Exp_"
neuper@40836
   624
  | ketype2str Thy_ = "Thy_"
neuper@40836
   625
  | ketype2str Pbl_ = "Pbl_"
neuper@37906
   626
  | ketype2str Met_ = "Met_";
neuper@37906
   627
fun ketype2str' Exp_ = "Example"
neuper@40836
   628
  | ketype2str' Thy_ = "Theory"
neuper@40836
   629
  | ketype2str' Pbl_ = "Problem"
neuper@37906
   630
  | ketype2str' Met_ = "Method";
wneuper@59172
   631
(* for conversion from XML *)
wneuper@59172
   632
fun str2ketype' "exp" = Exp_
wneuper@59172
   633
  | str2ketype' "thy" = Thy_
wneuper@59172
   634
  | str2ketype' "pbl" = Pbl_
wneuper@59172
   635
  | str2ketype' "met" = Met_
wneuper@59172
   636
  | str2ketype' str = raise ERROR ("str2ketype': WRONG arg = " ^ str)
neuper@37906
   637
wneuper@59414
   638
(* rewrite orders, also stored in 'type met' and type 'and rls'
wneuper@59414
   639
  The association list is required for 'rewrite.."rew_ord"..' *)
neuper@55432
   640
val rew_ord' = Unsynchronized.ref
wneuper@59411
   641
  ([("e_rew_ord", e_rew_ord), ("dummy_ord", dummy_ord)]
wneuper@59411
   642
	: (rew_ord' *         (* the key for the association list         *)
wneuper@59411
   643
	    (subst 	          (* the bound variables - they get high order*)
wneuper@59411
   644
	     -> (term * term) (* (t1, t2) to be compared                  *)
wneuper@59411
   645
	     -> bool))        (* if t1 <= t2 then true else false         *)
wneuper@59411
   646
		list);              (* association list                         *)
neuper@38061
   647
neuper@48887
   648
(* A tree for storing data defined in different theories 
neuper@48887
   649
  for access from the Interpreter and from dialogue authoring 
neuper@48887
   650
  using a string list as key.
wneuper@59414
   651
  'a is for pbt | met | thydata; after WN030424 naming "pbt" became inappropriate *)
neuper@40836
   652
datatype 'a ptyp =
wneuper@59414
   653
	Ptyp of string *  (* element of the key                                                        *)
wneuper@59414
   654
		'a list *       (* several pbts with different domIDs/thy TODO: select by subthy (isaref.p.69)
wneuper@59414
   655
			                 presently only _ONE_ elem FOR ALL KINDS OF CONTENT pbt | met | thydata    *)
wneuper@59414
   656
		('a ptyp) list; (* the children nodes                                                        *)
neuper@37906
   657
wneuper@59414
   658
(* datatype for collecting thydata for hierarchy *)
neuper@37906
   659
(*WN060720 more consistent naming would be 'type thyelem' or 'thelem'*)
wneuper@59414
   660
datatype thydata =
wneuper@59414
   661
  Html of {guh: guh, coursedesign: authors, mathauthors: authors, html: string}
wneuper@59414
   662
| Hthm of {guh: guh, coursedesign: authors, mathauthors: authors, fillpats: fillpat list,
wneuper@59414
   663
   thm: thm} (* here no sym_thm, thus no thmID required *)
wneuper@59414
   664
| Hrls of {guh: guh, coursedesign: authors, mathauthors: authors, thy_rls: (thyID * rls)}
wneuper@59414
   665
| Hcal of {guh: guh, coursedesign: authors, mathauthors: authors, calc: calc}
wneuper@59414
   666
| Hord of {guh: guh, coursedesign: authors, mathauthors: authors,
wneuper@59414
   667
    ord: (subst -> (term * term) -> bool)};
wneuper@59414
   668
fun the2str (Html {guh, ...}) = guh
wneuper@59414
   669
  | the2str (Hthm {guh, ...}) = guh
wneuper@59414
   670
  | the2str (Hrls {guh, ...}) = guh
wneuper@59414
   671
  | the2str (Hcal {guh, ...}) = guh
wneuper@59414
   672
  | the2str (Hord {guh, ...}) = guh
neuper@55435
   673
fun thes2str thes = map the2str thes |> list2str;
neuper@37906
   674
neuper@55483
   675
(* notes on thehier concerning sym_thmID theorems (created in derivations, reverse rewriting)
neuper@55487
   676
     (a): thehier does not contain sym_thmID theorems
neuper@55485
   677
     (b): lookup for sym_thmID directly from Isabelle using sym_thm
neuper@55485
   678
          (within math-engine NO lookup in thehier -- within java in *.xml only!)
neuper@55483
   679
TODO (c): export from thehier to xml
neuper@55483
   680
TODO (c1)   creates one entry for "thmID" (and NONE for "sym_thmID") in the hierarchy
neuper@55483
   681
TODO (c2)   creates 2 files "thy_*-thm-thmID.xml" and "thy_*-thm-sym_thmID.xml"
neuper@55483
   682
TODO (d): 1 entry in the MiniBrowser's hierarchy (generated from xml)
neuper@55483
   683
          stands for both, "thmID" and "sym_thmID" 
neuper@55483
   684
TODO (d1)   lookup from calctxt          
neuper@55483
   685
TODO (d1)   lookup from from rule set in MiniBrowser *)
neuper@37906
   686
type thehier = (thydata ptyp) list;
neuper@55405
   687
(* required to determine sequence of main nodes of thehier in KEStore.thy *)
wneuper@59414
   688
fun part2guh [str] = (case str of
wneuper@59414
   689
	  "Isabelle" => "thy_isab_" ^ str ^ "-part" : guh
neuper@55405
   690
      | "IsacScripts" => "thy_scri_" ^ str ^ "-part"
neuper@55405
   691
      | "IsacKnowledge" => "thy_isac_" ^ str ^ "-part"
wneuper@59414
   692
      | str => raise ERROR ("thy2guh: called with \""^ str ^"\""))
wneuper@59414
   693
  | part2guh theID = raise ERROR ("part2guh called with theID = \"" ^ theID2str theID ^ "'");
neuper@37906
   694
wneuper@59414
   695
fun thy2guh [part, thyID] = (case part of
wneuper@59414
   696
      "Isabelle" => "thy_isab_" ^ thyID
neuper@55437
   697
    | "IsacScripts" => "thy_scri_" ^ thyID
neuper@55437
   698
    | "IsacKnowledge" => "thy_isac_" ^ thyID
wneuper@59414
   699
    | str => raise ERROR ("thy2guh: called with \"" ^ str ^ "\""))
wneuper@59414
   700
  | thy2guh theID = raise ERROR ("thy2guh called with \"" ^ strs2str' theID ^ "\"");
neuper@55437
   701
			
wneuper@59414
   702
fun thypart2guh ([part, thyID, thypart] : theID) = (case part of
wneuper@59414
   703
      "Isabelle" => "thy_isab_" ^ thyID ^ "-" ^ thypart : guh
wneuper@59414
   704
    | "IsacScripts" => "thy_scri_" ^ thyID ^ "-" ^ thypart
wneuper@59414
   705
    | "IsacKnowledge" => "thy_isac_" ^ thyID ^ "-" ^ thypart
wneuper@59414
   706
    | str => raise ERROR ("thypart2guh: called with '" ^ str ^ "'"))
wneuper@59414
   707
  | thypart2guh strs = raise ERROR ("thypart2guh called with \"" ^ strs2str' strs ^ "\"");
wneuper@59414
   708
neuper@55437
   709
  
wneuper@59414
   710
(* convert the data got via contextToThy to a globally unique handle.
wneuper@59414
   711
   there is another way to get the guh: get out of the 'theID' in the hierarchy *)
wneuper@59414
   712
fun thm2guh (isa, thyID) thmID = case isa of
neuper@55437
   713
    "Isabelle" => "thy_isab_" ^ theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID : guh
neuper@55437
   714
  | "IsacKnowledge" => "thy_isac_" ^ theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID
neuper@55437
   715
  | "IsacScripts" => "thy_scri_" ^ theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID
wneuper@59414
   716
  | _ => raise ERROR
wneuper@59414
   717
    ("thm2guh called with (isa, thyID) = (" ^ isa ^ ", " ^ thyID ^ ") for thm = \"" ^ thmID ^ "\"");
neuper@55437
   718
wneuper@59414
   719
fun rls2guh (isa, thyID) rls' = case isa of
neuper@55437
   720
    "Isabelle" => "thy_isab_" ^ theory'2thyID thyID ^ "-rls-" ^ rls' : guh
neuper@55437
   721
  | "IsacKnowledge" => "thy_isac_" ^ theory'2thyID thyID ^ "-rls-" ^ rls'
neuper@55437
   722
  | "IsacScripts" => "thy_scri_" ^ theory'2thyID thyID ^ "-rls-" ^ rls'
wneuper@59414
   723
  | _ => raise ERROR
wneuper@59414
   724
    ("rls2guh called with (isa, thyID) = (" ^ isa ^ ", " ^ thyID ^ ") for rls = \"" ^ rls' ^ "\"");
neuper@55437
   725
			  
wneuper@59414
   726
fun cal2guh (isa, thyID) calID = case isa of
neuper@55437
   727
    "Isabelle" => "thy_isab_" ^ theory'2thyID thyID ^ "-cal-" ^ calID : guh
neuper@55437
   728
  | "IsacKnowledge" => "thy_isac_" ^ theory'2thyID thyID ^ "-cal-" ^ calID
neuper@55437
   729
  | "IsacScripts" => "thy_scri_" ^ theory'2thyID thyID ^ "-cal-" ^ calID
wneuper@59414
   730
  | _ => raise ERROR
wneuper@59414
   731
    ("cal2guh called with (isa, thyID) = (" ^ isa ^ ", " ^ thyID ^ ") for cal = \"" ^ calID ^ "\"");
neuper@55437
   732
			  
wneuper@59414
   733
fun ord2guh (isa, thyID) rew_ord' = case isa of
neuper@55437
   734
    "Isabelle" => "thy_isab_" ^ theory'2thyID thyID ^ "-ord-" ^ rew_ord' : guh
neuper@55437
   735
  | "IsacKnowledge" => "thy_isac_" ^ theory'2thyID thyID ^ "-ord-" ^ rew_ord'
neuper@55437
   736
  | "IsacScripts" => "thy_scri_" ^ theory'2thyID thyID ^ "-ord-" ^ rew_ord'
wneuper@59414
   737
  | _ => raise ERROR
wneuper@59414
   738
    ("ord2guh called with (isa, thyID) = (" ^ isa ^ ", " ^ thyID ^ ") for ord = \"" ^ rew_ord' ^ "\"");
neuper@55437
   739
neuper@55437
   740
(* not only for thydata, but also for thy's etc *)
wneuper@59414
   741
(* TODO
wneuper@59414
   742
fun theID2guh theID = case length theID of
neuper@55437
   743
    0 => error ("theID2guh: called with theID = " ^ strs2str' theID)
neuper@55437
   744
  | 1 => part2guh theID
neuper@55437
   745
  | 2 => thy2guh theID
neuper@55437
   746
  | 3 => thypart2guh theID
neuper@55437
   747
  | 4 => 
neuper@55437
   748
    let val [isa, thyID, typ, elemID] = theID
neuper@55437
   749
    in case typ of
neuper@55437
   750
        "Theorems" => thm2guh (isa, thyID) elemID
neuper@55437
   751
      | "Rulesets" => rls2guh (isa, thyID) elemID
neuper@55437
   752
      | "Calculations" => cal2guh (isa, thyID) elemID
neuper@55437
   753
      | "Orders" => ord2guh (isa, thyID) elemID
neuper@55437
   754
      | "Theorems" => thy2guh [isa, thyID]
wneuper@59414
   755
      | str => raise ERROR ("theID2guh: called with theID = " ^ strs2str' theID)
neuper@55437
   756
    end
wneuper@59414
   757
  | n => raise ERROR ("theID2guh called with theID = " ^ strs2str' theID);
wneuper@59414
   758
*)
wneuper@59414
   759
(* not only for thydata, but also for thy's etc *)
wneuper@59414
   760
fun theID2guh [] = raise ERROR ("theID2guh: called with []")
wneuper@59414
   761
  | theID2guh [str] = part2guh [str]
wneuper@59414
   762
  | theID2guh [s1, s2] = thy2guh [s1, s2]
wneuper@59414
   763
  | theID2guh [s1, s2, s3] = thypart2guh [s1, s2, s3]
wneuper@59414
   764
  | theID2guh (strs as [isa, thyID, typ, elemID]) = (case typ of
wneuper@59414
   765
      "Theorems" => thm2guh (isa, thyID) elemID
wneuper@59414
   766
    | "Rulesets" => rls2guh (isa, thyID) elemID
wneuper@59414
   767
    | "Calculations" => cal2guh (isa, thyID) elemID
wneuper@59414
   768
    | "Orders" => ord2guh (isa, thyID) elemID
wneuper@59414
   769
    | _ => raise ERROR ("theID2guh: called with theID = " ^ strs2str' strs))
wneuper@59414
   770
  | theID2guh strs = raise ERROR ("theID2guh called with theID = " ^ strs2str' strs);
neuper@55437
   771
neuper@37906
   772
type path = string;
neuper@37906
   773
type filename = string;
neuper@37906
   774
neuper@37906
   775
local
wneuper@59414
   776
    fun ii (_: term) = e_rrlsstate;
wneuper@59414
   777
    fun no (_: term) = SOME (e_term, [e_term]);
wneuper@59414
   778
    fun lo (_: rule list list) (_: term) (_: rule) = [(e_rule, (e_term, [e_term]))];
wneuper@59414
   779
    fun ne (_: rule list list) (_: term) = SOME e_rule;
wneuper@59414
   780
    fun fo (_: rule list list) (_: term) (_: term) = [(e_rule, (e_term, [e_term]))];
neuper@37906
   781
in
wneuper@59414
   782
val e_rfuns = Rfuns {init_state = ii, normal_form = no, locate_rule = lo,
wneuper@59414
   783
		  next_rule = ne, attach_form = fo};
neuper@37906
   784
end;
neuper@42458
   785
val e_rls =
neuper@42458
   786
  Rls {id = "e_rls", preconds = [], rew_ord = ("dummy_ord", dummy_ord), erls = Erls,
neuper@42458
   787
    srls = Erls, calc = [], rules = [], errpatts = [], scr = EmptyScr}: rls;
neuper@42458
   788
val e_rrls =
neuper@42458
   789
  Rrls {id = "e_rrls", prepat = [], rew_ord = ("dummy_ord", dummy_ord), erls = Erls,
neuper@42458
   790
    calc = [], errpatts = [], scr=e_rfuns}:rls;
neuper@42451
   791
wneuper@59414
   792
fun rep_rls Erls = rep_rls e_rls
wneuper@59414
   793
  | rep_rls (Rls {id, preconds, rew_ord, erls, srls, calc, errpatts, rules, scr}) =
wneuper@59414
   794
    {id = id, preconds = preconds, rew_ord = rew_ord, erls = erls, srls = srls, errpats = errpatts,
wneuper@59414
   795
      calc = calc, rules = rules, scr = scr}
wneuper@59414
   796
  | rep_rls (Seq {id, preconds, rew_ord, erls, srls, calc, errpatts, rules, scr}) =
wneuper@59414
   797
    {id = id, preconds = preconds, rew_ord = rew_ord, erls = erls, srls = srls, errpats = errpatts,
wneuper@59414
   798
      calc = calc, rules = rules, scr = scr}
wneuper@59414
   799
  | rep_rls (Rrls _)  = rep_rls e_rls
neuper@37906
   800
wneuper@59414
   801
fun append_rls id Erls _ = raise ERROR ("append_rls: with \"" ^ id ^ "\" not for Erls")
wneuper@59414
   802
  | append_rls id (Rls {id = _, preconds = pc, rew_ord = ro, erls = er, srls = sr, calc = ca,
wneuper@59414
   803
			rules = rs, errpatts = errpatts, scr = sc}) r =
wneuper@59414
   804
    Rls {id = id, preconds = pc, rew_ord = ro, erls = er, srls = sr, calc = ca,
wneuper@59414
   805
      rules = rs @ r, errpatts = errpatts, scr = sc}
wneuper@59414
   806
  | append_rls id (Seq {id = _, preconds = pc, rew_ord = ro, erls = er, srls = sr, calc = ca,
wneuper@59414
   807
			rules = rs, errpatts = errpatts, scr = sc}) r =
wneuper@59414
   808
    Seq {id = id, preconds = pc, rew_ord = ro, erls = er, srls = sr, calc = ca,
wneuper@59414
   809
      rules = rs @ r, errpatts = errpatts, scr = sc}
wneuper@59414
   810
  | append_rls id (Rrls _) _ = raise ERROR ("append_rls: not for reverse-rewrite-rule-set " ^ id);
neuper@37906
   811
neuper@37906
   812
neuper@52141
   813
fun merge_ids rls1 rls2 =
neuper@52141
   814
  let 
neuper@52141
   815
    val id1 = (#id o rep_rls) rls1
neuper@52141
   816
    val id2 = (#id o rep_rls) rls2
neuper@52141
   817
  in
wneuper@59414
   818
    if id1 = id2 then id1 else "merged_" ^ id1 ^ "_" ^ id2
neuper@52141
   819
  end
neuper@37906
   820
fun merge_rls _ Erls rls = rls
neuper@37906
   821
  | merge_rls _ rls Erls = rls
neuper@52141
   822
  | merge_rls _ (Rrls x) _ = Rrls x (* required for merging Theory_Data *)
neuper@52141
   823
  | merge_rls _ _ (Rrls x) = Rrls x
neuper@37906
   824
  | merge_rls id
neuper@52141
   825
	  (Rls {preconds = pc1, rew_ord = ro1, erls = er1, srls = sr1, calc = ca1,
neuper@52141
   826
	    rules = rs1, errpatts = eps1, scr = sc1, ...})
neuper@52141
   827
	  (Rls {preconds = pc2, erls = er2, srls = sr2, calc = ca2,
neuper@52141
   828
	    rules = rs2, errpatts = eps2, ...})
neuper@52141
   829
    =
wneuper@59414
   830
	  Rls {id = id, rew_ord = ro1, scr = sc1,
neuper@52141
   831
	    preconds = union (op =) pc1 pc2,	    
neuper@52141
   832
	    erls = merge_rls (merge_ids er1 er2) er1 er2,
neuper@52141
   833
	    srls = merge_rls (merge_ids sr1 sr2) sr1 sr2,
neuper@52141
   834
	    calc = union calc_eq ca1 ca2,
neuper@52141
   835
		  rules = union eq_rule rs1 rs2,
wneuper@59414
   836
      errpatts = union (op =) eps1 eps2}
neuper@37906
   837
  | merge_rls id
neuper@52141
   838
	  (Seq {preconds = pc1, rew_ord = ro1, erls = er1, srls = sr1, calc = ca1,
neuper@52141
   839
	    rules = rs1, errpatts = eps1, scr = sc1, ...})
neuper@52141
   840
	  (Seq {preconds = pc2, erls = er2, srls = sr2, calc = ca2,
neuper@52141
   841
	    rules = rs2, errpatts = eps2, ...})
neuper@52141
   842
    =
wneuper@59414
   843
	  Seq {id = id, rew_ord = ro1, scr = sc1,
neuper@52141
   844
	    preconds = union (op =) pc1 pc2,	    
neuper@52141
   845
	    erls = merge_rls (merge_ids er1 er2) er1 er2,
neuper@52141
   846
	    srls = merge_rls (merge_ids sr1 sr2) sr1 sr2,
neuper@52141
   847
	    calc = union calc_eq ca1 ca2,
neuper@52141
   848
		  rules = union eq_rule rs1 rs2,
wneuper@59414
   849
      errpatts = union (op =) eps1 eps2}
neuper@52141
   850
  | merge_rls id _ _ = error ("merge_rls: \"" ^ id ^ 
neuper@52141
   851
    "\"; not for reverse-rewrite-rule-sets and not for mixed Rls -- Seq");
neuper@42451
   852
wneuper@59414
   853
(* used only for one hack TODO remove *)
wneuper@59414
   854
fun remove_rls id (Rls {id = _, preconds = pc, rew_ord = ro, erls = er, srls = sr, calc = ca,
wneuper@59414
   855
		  rules = rs, errpatts = eps, scr = sc}) r =
wneuper@59414
   856
    Rls {id = id, preconds = pc, rew_ord = ro, erls = er, srls = sr, calc = ca,
wneuper@59414
   857
	    rules = gen_rems eq_rule (rs, r),
wneuper@59414
   858
	    errpatts = eps,
wneuper@59414
   859
	    scr = sc}
wneuper@59414
   860
  | remove_rls id (Seq {id = _, preconds = pc, rew_ord = ro, erls = er, srls = sr, calc = ca,
wneuper@59414
   861
		  rules = rs, errpatts = eps, scr = sc}) r =
wneuper@59414
   862
    Seq {id = id, preconds = pc, rew_ord = ro, erls = er, srls = sr, calc = ca,
wneuper@59414
   863
	    rules = gen_rems eq_rule (rs, r),
wneuper@59414
   864
	    errpatts = eps,
wneuper@59414
   865
	    scr = sc}
wneuper@59414
   866
  | remove_rls id (Rrls _) _ = raise ERROR ("remove_rls: not for reverse-rewrite-rule-set "^id)
wneuper@59414
   867
  | remove_rls _ rls _ = raise ERROR ("remove_rls called with " ^ rls2str rls);
neuper@37906
   868
neuper@52141
   869
(* datastructure for KEStore_Elems, intermediate for thehier *)
neuper@52141
   870
type rlss_elem = 
neuper@52141
   871
  (rls' *     (* identifier unique within Isac *)
neuper@52141
   872
  (theory' *  (* just for assignment in thehier, not appropriate for parsing etc *)
neuper@52141
   873
    rls))     (* ((#id o rep_rls) rls) = rls'   by coding discipline *)
neuper@52141
   874
fun rls_eq ((id1, (_, _)), (id2, (_, _))) = id1 = id2
neuper@37906
   875
neuper@52141
   876
fun insert_merge_rls (re as (id, (thyID, r1)) : rlss_elem) ys = 
wneuper@59414
   877
    case get_index (fn y => if curry rls_eq re y then SOME y else NONE) ys of
wneuper@59414
   878
      NONE => re :: ys
wneuper@59414
   879
    | SOME (i, (_, (_, r2))) => 
neuper@52141
   880
      let
neuper@52141
   881
        val r12 = merge_rls id r1 r2
neuper@52141
   882
      in list_update ys i (id, (thyID, r12)) end
neuper@52141
   883
fun merge_rlss (s1, s2) = fold insert_merge_rls s1 s2;
neuper@52141
   884
wneuper@59414
   885
fun assoc' ([], key) = raise ERROR ("ME_Isa: \"" ^ key ^ "\" not known")
wneuper@59414
   886
  | assoc' ((keyi, xi) :: pairs, key) =
wneuper@59414
   887
    if key = keyi then SOME xi else assoc' (pairs, key);
neuper@52141
   888
wneuper@59414
   889
fun assoc_thy thy =
wneuper@59414
   890
    if thy = "e_domID"
wneuper@59414
   891
    then (Thy_Info_get_theory "Script") (*lower bound of Knowledge*)
wneuper@59414
   892
    else (Thy_Info_get_theory thy) handle _ => error ("ME_Isa: thy \"" ^ thy ^ "\" not in system");
neuper@37906
   893
wneuper@59414
   894
(* overwrite an element in an association list and pair it with a thyID
neuper@37906
   895
   in order to create the thy_hierarchy;
neuper@37906
   896
   overwrites existing rls' even if they are defined in a different thy;
wneuper@59414
   897
   this is related to assoc_rls, TODO.WN060120: assoc_rew_ord, assoc_calc *)
wneuper@59414
   898
(* WN060120 ...these are NOT compatible to "fun assoc_thm'" in that
neuper@37906
   899
   they do NOT handle overlays by re-using an identifier in different thys;
neuper@37906
   900
   "thyID.rlsID" would be a good solution, if the "." would be possible
neuper@37906
   901
   in scripts...
wneuper@59414
   902
   actually a hack to get alltogether run again with minimal effort *)
neuper@37906
   903
fun insthy thy' (rls', rls) = (rls', (thy', rls));
neuper@37906
   904
fun overwritelthy thy (al, bl:(rls' * rls) list) =
neuper@37906
   905
    let val bl' = map (insthy ((get_thy o theory2theory') thy)) bl
neuper@37906
   906
    in overwritel (al, bl') end;
neuper@37906
   907
neuper@37906
   908
fun assoc_rew_ord ro = ((the o assoc') (!rew_ord',ro))
wneuper@59414
   909
  handle _ => error ("ME_Isa: rew_ord '" ^ ro ^ "' not in system");
neuper@37906
   910
wneuper@59414
   911
fun subst2str s =
neuper@40836
   912
    (strs2str o
wneuper@59414
   913
      (map (
wneuper@59414
   914
        linefeed o pair2str o (apsnd term2str) o (apfst term2str)))) s;
neuper@40836
   915
fun subst2str' (s:subst) =
neuper@40836
   916
    (strs2str' o
wneuper@59414
   917
     (map (
wneuper@59414
   918
       pair2str o (apsnd term2str) o (apfst term2str)))) s;
neuper@37906
   919
val env2str = subst2str;
neuper@37906
   920
wneuper@59414
   921
fun scr2str EmptyScr = "EmptyScr"
wneuper@59414
   922
  | scr2str (Prog s) = "Prog " ^ term2str s
neuper@37906
   923
  | scr2str (Rfuns _)  = "Rfuns";
neuper@37906
   924
wneuper@59332
   925
fun maxthy thy1 thy2 = if Context.subthy (thy1, thy2) then thy2 else thy1;
neuper@37906
   926
neuper@37906
   927
wneuper@59387
   928
(* trace internal steps of isac's numeral calculations *)
wneuper@59387
   929
val trace_calc = Unsynchronized.ref false;
wneuper@59414
   930
(* trace internal steps of isac's rewriter *)
neuper@38006
   931
val trace_rewrite = Unsynchronized.ref false;
wneuper@59414
   932
(* depth of recursion in traces of the rewriter, if trace_rewrite:=true *)
neuper@38006
   933
val depth = Unsynchronized.ref 99999;
wneuper@59414
   934
(* no of rewrites exceeding this int -> NO rewrite *)
neuper@38006
   935
val lim_deriv = Unsynchronized.ref 100;
wneuper@59414
   936
(* switch for checking guhs unique before storing a pbl or met;
neuper@37906
   937
   set true at startup (done at begin of ROOT.ML)
wneuper@59414
   938
   set false for editing IsacKnowledge (done at end of ROOT.ML) *)
neuper@41905
   939
val check_guhs_unique = Unsynchronized.ref true;
neuper@37906
   940
neuper@37906
   941
wneuper@59414
   942
datatype lrd = (*elements of "type loc_" into an Isabelle term*)
wneuper@59414
   943
	L   (*go left at $*)
wneuper@59414
   944
| R   (*go right at $*)
wneuper@59414
   945
| D;  (*go down at Abs*)
neuper@37906
   946
type loc_ = lrd list;
neuper@37906
   947
fun ldr2str L = "L"
neuper@37906
   948
  | ldr2str R = "R"
neuper@37906
   949
  | ldr2str D = "D";
wneuper@59414
   950
fun loc_2str k = (strs2str' o (map ldr2str)) k;
neuper@37906
   951
neuper@55335
   952
neuper@55335
   953
(* the pattern for an item of a problems model or a methods guard *)
neuper@55335
   954
type pat =
neuper@55335
   955
  (string *     (* field               *)
neuper@55335
   956
	  (term *     (* description         *)
neuper@55335
   957
	     term))   (* id | arbitrary term *);
neuper@55335
   958
fun pat2str ((field, (dsc, id)) : pat) = 
neuper@55335
   959
  pair2str (field, pair2str (term2str dsc, term2str id))
neuper@55335
   960
fun pats2str pats = (strs2str o (map pat2str)) pats
neuper@55335
   961
neuper@55357
   962
(* types for problems models (TODO rename to specification models) *)
neuper@55335
   963
type pbt_ =
neuper@55335
   964
  (string *   (* field "#Given",..*)(*deprecated due to 'type pat'*)
neuper@55335
   965
    (term *   (* description      *)
neuper@55335
   966
      term)); (* id | struct-var  *)
neuper@55335
   967
type pbt = 
wneuper@59414
   968
  {guh : guh,         (* unique within this isac-knowledge                               *)
wneuper@59414
   969
  mathauthors : string list, (* copyright                                                *)
wneuper@59414
   970
  init : pblID,       (* to start refinement with                                        *)
neuper@55335
   971
  thy  : theory,      (* which allows to compile that pbt
wneuper@59414
   972
                        TODO: search generalized for subthy (ref.p.69*)
wneuper@59414
   973
                        (*^^^ WN050912 NOT used during application of the problem,
wneuper@59414
   974
                        because applied terms may be from 'subthy' as well as from super;
wneuper@59414
   975
                        thus we take 'maxthy'; see match_ags !                           *)
wneuper@59414
   976
  cas : term option,  (* 'CAS-command'                                                   *)
wneuper@59414
   977
  prls : rls,         (* for preds in where_                                             *)
wneuper@59414
   978
  where_ : term list, (* where - predicates                                              *)
neuper@55335
   979
  ppc : pat list,     (* this is the model-pattern; 
wneuper@59414
   980
                         it contains "#Given","#Where","#Find","#Relate"-patterns
wneuper@59414
   981
                         for constraints on identifiers see "fun cpy_nam"                *)
wneuper@59414
   982
  met : metID list}   (* methods solving the pbt                                         *)
neuper@55335
   983
wneuper@59397
   984
val e_pbt = {guh = "pbl_empty", mathauthors = [], init = e_pblID, thy = Thy_Info.get_theory "Pure",
wneuper@59414
   985
  cas = NONE, prls = Erls, where_ = [], ppc = [], met = []}
wneuper@59414
   986
fun pbt2str ({cas = cas', guh = guh', init = init', mathauthors = ma', met = met', ppc = ppc',
wneuper@59414
   987
      prls = prls', thy = thy', where_ = w'} : pbt)
wneuper@59414
   988
    = "{cas = " ^ (termopt2str cas') ^  ", guh = \"" ^ guh'  ^ "\", init = "
wneuper@59414
   989
      ^ (strs2str init') ^ ", mathauthors = " ^ (strs2str ma' |> quote) ^ ", met = "
wneuper@59414
   990
      ^ (strslist2strs met') ^ ", ppc = " ^ pats2str ppc' ^ ", prls = "
wneuper@59414
   991
      ^ (rls2str prls' |> quote) ^ ", thy = {" ^ (theory2str thy') ^ "}, where_ = "
wneuper@59414
   992
      ^ (terms2str w') ^ "}" |> linefeed;
s1210629013@55345
   993
fun pbts2str pbts = map pbt2str pbts |> list2str;
neuper@55335
   994
neuper@55335
   995
val e_Ptyp = Ptyp ("e_pblID",[e_pbt],[])
neuper@55335
   996
type ptyps = (pbt ptyp) list
neuper@55335
   997
neuper@55357
   998
fun coll_pblguhs pbls =
wneuper@59414
   999
  let
wneuper@59414
  1000
    fun node coll (Ptyp (_, [n], ns)) = [(#guh : pbt -> guh) n] @ (nodes coll ns)
wneuper@59414
  1001
      | node _ _ = raise ERROR "coll_pblguhs - node"
wneuper@59414
  1002
	  and nodes coll [] = coll
wneuper@59414
  1003
      | nodes coll (n :: ns) = (node coll n) @ (nodes coll ns);
wneuper@59414
  1004
  in nodes [] pbls end;
wneuper@59414
  1005
fun check_pblguh_unique guh pbls =
wneuper@59414
  1006
  if member op = (coll_pblguhs pbls) guh
wneuper@59414
  1007
  then error ("check_guh_unique failed with \""^ guh ^"\";\n"^
wneuper@59414
  1008
	      "use \"sort_pblguhs()\" for a list of guhs;\n"^
wneuper@59414
  1009
	      "consider setting \"check_guhs_unique := false\"")
wneuper@59414
  1010
  else ();
s1210629013@55339
  1011
neuper@55453
  1012
fun insrt _ pbt [k] [] = [Ptyp (k, [pbt], [])]
neuper@55453
  1013
  | insrt d pbt [k] ((Ptyp (k', [p], ps)) :: pys) =
wneuper@59414
  1014
    ((*writeln ("### insert 1: ks = " ^ strs2str [k] ^ "    k'= " ^ k');*)
wneuper@59414
  1015
    if k = k'
wneuper@59414
  1016
    then ((Ptyp (k', [pbt], ps)) :: pys)
wneuper@59414
  1017
    else  ((Ptyp (k', [p], ps)) :: (insrt d pbt [k] pys))
wneuper@59414
  1018
    )			 
wneuper@59414
  1019
  | insrt d pbt (k::ks) ((Ptyp (k', [p], ps)) :: pys) =
wneuper@59414
  1020
    ((*writeln ("### insert 2: ks = "^(strs2str (k::ks))^"    k'= "^k');*)
wneuper@59414
  1021
    if k = k'
wneuper@59414
  1022
    then ((Ptyp (k', [p], insrt d pbt ks ps)) :: pys)
wneuper@59414
  1023
    else 
wneuper@59414
  1024
      if length pys = 0
wneuper@59414
  1025
      then error ("insert: not found " ^ (strs2str (d : pblID)))
wneuper@59414
  1026
      else ((Ptyp (k', [p], ps)) :: (insrt d pbt (k :: ks) pys))
wneuper@59414
  1027
    )
wneuper@59414
  1028
  | insrt _ _ _ _ = raise ERROR "";
s1210629013@55339
  1029
neuper@55448
  1030
fun update_ptyps ID _ _ [] =
neuper@55448
  1031
    error ("update_ptyps: " ^ strs2str' ID ^ " does not exist")
neuper@55448
  1032
  | update_ptyps ID [i] data ((py as Ptyp (key, _, pys)) :: pyss) =
neuper@55448
  1033
    if i = key
neuper@55448
  1034
    then 
neuper@55448
  1035
      if length pys = 0
neuper@55448
  1036
      then ((Ptyp (key, [data], [])) :: pyss)
neuper@55448
  1037
      else error ("update_ptyps: " ^ strs2str' ID ^ " has descendants")
neuper@55448
  1038
    else py :: update_ptyps ID [i] data pyss
neuper@55448
  1039
  | update_ptyps ID (i :: is) data ((py as Ptyp (key, d, pys)) :: pyss) =
neuper@55448
  1040
    if i = key
neuper@55448
  1041
    then ((Ptyp (key,  d, update_ptyps ID is data pys)) :: pyss)
neuper@55448
  1042
    else (py :: (update_ptyps ID (i :: is) data pyss))
wneuper@59414
  1043
  | update_ptyps _ _ _ _ = raise ERROR "update_ptyps called with undef pattern.";
neuper@55448
  1044
s1210629013@55339
  1045
(* this function only works wrt. the way Isabelle evaluates Theories and is not a general merge
s1210629013@55339
  1046
  function for trees / ptyps *)
s1210629013@55339
  1047
fun merge_ptyps ([], pt) = pt
s1210629013@55339
  1048
  | merge_ptyps (pt, []) = pt
wneuper@59414
  1049
  | merge_ptyps ((x' as Ptyp (k, _, ps)) :: xs, (xs' as Ptyp (k', y, ps') :: ys)) =
s1210629013@55346
  1050
      if k = k'
s1210629013@55346
  1051
      then Ptyp (k, y, merge_ptyps (ps, ps')) :: merge_ptyps (xs, ys)
s1210629013@55346
  1052
      else x' :: merge_ptyps (xs, xs');
s1210629013@55372
  1053
s1210629013@55372
  1054
(* data for methods stored in 'methods'-database*)
s1210629013@55372
  1055
type met = 
s1210629013@55372
  1056
     {guh        : guh,        (*unique within this isac-knowledge           *)
s1210629013@55372
  1057
      mathauthors: string list,(*copyright                                   *)
s1210629013@55372
  1058
      init       : pblID,      (*WN060721 introduced mistakenly--TODO.REMOVE!*)
s1210629013@55372
  1059
      rew_ord'   : rew_ord',   (*for rules in Detail
s1210629013@55372
  1060
			                           TODO.WN0509 store fun itself, see 'type pbt'*)
s1210629013@55372
  1061
      erls       : rls,        (*the eval_rls for cond. in rules FIXME "rls'
s1210629013@55372
  1062
				                         instead erls in "fun prep_met"              *)
s1210629013@55372
  1063
      srls       : rls,        (*for evaluating list expressions in scr      *)
s1210629013@55372
  1064
      prls       : rls,        (*for evaluating predicates in modelpattern   *)
s1210629013@55372
  1065
      crls       : rls,        (*for check_elementwise, ie. formulae in calc.*)
s1210629013@55372
  1066
      nrls       : rls,        (*canonical simplifier specific for this met  *)
s1210629013@55372
  1067
      errpats    : errpat list,(*error patterns expected in this method      *)
s1210629013@55372
  1068
      calc       : calc list,  (*Theory_Data in fun prep_met                 *)
s1210629013@55372
  1069
      (*branch   : TransitiveB set in append_problem at generation ob pblobj
s1210629013@55372
  1070
          FIXXXME.0308: set branch from met in Apply_Method ?                *)
s1210629013@55372
  1071
      ppc        : pat list,   (*.items in given, find, relate;
s1210629013@55372
  1072
	      items (in "#Find") which need not occur in the arg-list of a SubProblem
s1210629013@55372
  1073
        are 'copy-named' with an identifier "*'.'".
s1210629013@55372
  1074
        copy-named items are 'generating' if they are NOT "*'''" ?WN120516??
s1210629013@55372
  1075
        see ME/calchead.sml 'fun is_copy_named'.                              *)
s1210629013@55372
  1076
      pre        : term list,  (*preconditions in where                       *)
s1210629013@55372
  1077
      scr        : scr         (*prep_met gets progam or string "empty_script"*)
s1210629013@55372
  1078
	   };
wneuper@59414
  1079
val e_met = {guh = "met_empty", mathauthors = [], init = e_metID, rew_ord' = "e_rew_ord'",
wneuper@59414
  1080
	erls = e_rls, srls = e_rls, prls = e_rls, calc = [], crls = e_rls, errpats = [], nrls= e_rls,
wneuper@59414
  1081
	ppc = [], pre = [], scr = EmptyScr};
wneuper@59414
  1082
val e_Mets = Ptyp ("e_metID", [e_met],[]);
s1210629013@55372
  1083
s1210629013@55372
  1084
type mets = (met ptyp) list;
s1210629013@55373
  1085
fun coll_metguhs mets =
wneuper@59414
  1086
  let
wneuper@59414
  1087
    fun node coll (Ptyp (_, [n], ns)) = [(#guh : met -> guh) n] @ (nodes coll ns)
wneuper@59414
  1088
      | node _ _ = raise ERROR "coll_pblguhs - node"
wneuper@59414
  1089
  	and nodes coll [] = coll
wneuper@59414
  1090
  	  | nodes coll (n :: ns) = (node coll n) @ (nodes coll ns);
s1210629013@55373
  1091
    in nodes [] mets end;
s1210629013@55373
  1092
fun check_metguh_unique (guh:guh) (mets: (met ptyp) list) =
s1210629013@55373
  1093
    if member op = (coll_metguhs mets) guh
wneuper@59414
  1094
    then raise ERROR ("check_guh_unique failed with \"" ^ guh ^"\";\n"^
wneuper@59414
  1095
		  "use \"sort_metguhs()\" for a list of guhs;\n" ^
wneuper@59414
  1096
		  "consider setting \"check_guhs_unique := false\"")
s1210629013@55373
  1097
    else ();
s1210629013@55373
  1098
neuper@55450
  1099
fun Html_default exist = (Html {guh = theID2guh exist, 
neuper@55450
  1100
  coursedesign = ["isac team 2006"], mathauthors = [], html = ""})
neuper@55450
  1101
wneuper@59414
  1102
fun fill_parents (_, [i]) thydata = Ptyp (i, [thydata], [])
neuper@55450
  1103
  | fill_parents (exist, i :: is) thydata =
neuper@55450
  1104
    Ptyp (i, [Html_default (exist @ [i])], [fill_parents (exist @ [i], is) thydata])
wneuper@59414
  1105
  | fill_parents _ _ = raise ERROR "Html_default: avoid ML warning: Matches are not exhaustive"
neuper@55450
  1106
neuper@55450
  1107
fun add_thydata (exist, is) thydata [] = [fill_parents (exist, is) thydata]
neuper@55450
  1108
  | add_thydata (exist, [i]) data (pys as (py as Ptyp (key, _, _)) :: pyss) = 
neuper@55450
  1109
    if i = key
neuper@55450
  1110
    then pys (* preserve existing thydata *) 
neuper@55450
  1111
    else py :: add_thydata (exist, [i]) data pyss
neuper@55450
  1112
  | add_thydata (exist, iss as (i :: is)) data ((py as Ptyp (key, d, pys)) :: pyss) = 
neuper@55450
  1113
    if i = key
neuper@55450
  1114
    then       
neuper@55450
  1115
      if length pys = 0
neuper@55450
  1116
      then Ptyp (key, d, [fill_parents (exist @ [i], is) data]) :: pyss
neuper@55450
  1117
      else Ptyp (key, d, add_thydata (exist @ [i], is) data pys) :: pyss
neuper@55450
  1118
    else py :: add_thydata (exist, iss) data pyss
wneuper@59414
  1119
  | add_thydata _ _ _ = raise ERROR "add_thydata: avoid ML warning: Matches are not exhaustive"
neuper@55448
  1120
neuper@55448
  1121
fun update_hthm (Hthm {guh, coursedesign, mathauthors, thm, ...}) fillpats' =
neuper@55448
  1122
  Hthm {guh = guh, coursedesign = coursedesign, mathauthors = mathauthors,
neuper@55448
  1123
    fillpats = fillpats', thm = thm}
wneuper@59414
  1124
  | update_hthm _ _ = raise ERROR "update_hthm: wrong arguments";
neuper@55448
  1125
wneuper@59414
  1126
(* for dialog-authoring *)
neuper@55448
  1127
fun update_hrls (Hrls {guh, coursedesign, mathauthors, thy_rls = (thyID, rls)}) errpatIDs =
wneuper@59414
  1128
    let
wneuper@59414
  1129
      val rls' = 
wneuper@59414
  1130
        case rls of
wneuper@59414
  1131
          Rls {id, preconds, rew_ord, erls, srls, calc, rules, scr, ...}
wneuper@59414
  1132
          => Rls {id = id, preconds = preconds, rew_ord = rew_ord, erls = erls, srls = srls,
wneuper@59414
  1133
               calc = calc, rules = rules, scr = scr, errpatts = errpatIDs}
wneuper@59414
  1134
        | Seq {id, preconds, rew_ord, erls, srls, calc, rules, scr, ...}
wneuper@59414
  1135
          => Seq {id = id, preconds = preconds, rew_ord = rew_ord, erls = erls, srls = srls,
wneuper@59414
  1136
               calc = calc, rules = rules, scr = scr, errpatts = errpatIDs}
wneuper@59414
  1137
        | Rrls {id, prepat, rew_ord, erls, calc, scr, ...}
wneuper@59414
  1138
          => Rrls {id = id, prepat = prepat, rew_ord = rew_ord, erls = erls, calc = calc,
wneuper@59414
  1139
               scr = scr, errpatts = errpatIDs}
wneuper@59414
  1140
        | Erls => Erls
wneuper@59414
  1141
    in
wneuper@59414
  1142
      Hrls {guh = guh, coursedesign = coursedesign, mathauthors = mathauthors,
wneuper@59414
  1143
        thy_rls = (thyID, rls')}
wneuper@59414
  1144
    end
wneuper@59414
  1145
  | update_hrls _ _ = raise ERROR "update_hrls: wrong arguments";
wneuper@59414
  1146
wneuper@59414
  1147
fun app_py p f (d:pblID) (k(*:pblRD*)) =
neuper@55448
  1148
  let
wneuper@59414
  1149
    fun py_err _ = raise ERROR ("app_py: not found: " ^ strs2str d);
neuper@55448
  1150
    fun app_py' _ [] = py_err ()
neuper@55448
  1151
      | app_py' [] _ = py_err ()
wneuper@59414
  1152
      | app_py' [k0] ((p' as Ptyp (k', _, _  )) :: ps) =
wneuper@59414
  1153
        if k0 = k' then f p' else app_py' [k0] ps
wneuper@59414
  1154
      | app_py' (k' as (k0 :: ks)) (Ptyp (k'', _, ps) :: ps') =
wneuper@59414
  1155
        if k0 = k'' then app_py' ks ps else app_py' k' ps';
neuper@55448
  1156
  in app_py' k p end;
wneuper@59414
  1157
fun get_py p =
wneuper@59414
  1158
  let
wneuper@59414
  1159
    fun extract_py (Ptyp (_, [py], _)) = py
wneuper@59414
  1160
      | extract_py _ = raise ERROR ("extract_py: Ptyp has wrong format.");
wneuper@59414
  1161
  in app_py p extract_py end;
neuper@55448
  1162
neuper@55448
  1163
fun (*KEStore_Elems.*)insert_fillpats th fis = (* for tests bypassing setup KEStore_Elems *)
neuper@55448
  1164
  let
neuper@55448
  1165
    fun update_elem th (theID, fillpats) =
neuper@55437
  1166
      let
neuper@55448
  1167
        val hthm = get_py th theID theID
neuper@55448
  1168
        val hthm' = update_hthm hthm fillpats
neuper@55448
  1169
          handle ERROR _ => error ("insert_fillpats: " ^ strs2str theID ^ "must address a theorem")
neuper@55448
  1170
      in update_ptyps theID theID hthm' end
neuper@55448
  1171
  in fold (update_elem th) fis end
neuper@55456
  1172
neuper@55456
  1173
(* group the theories defined in Isac, compare Build_Thydata:
neuper@55456
  1174
  section "Get and group the theories defined in Isac" *) 
wneuper@59397
  1175
fun isabthys () = (*["Complex_Main", "Taylor", .., "Pure"]*)
neuper@55456
  1176
  let
wneuper@59352
  1177
    val allthys = Theory.ancestors_of (Thy_Info_get_theory "Build_Thydata")
neuper@55456
  1178
  in
wneuper@59366
  1179
    drop ((find_index (curry Context.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), allthys)
neuper@55456
  1180
  end
neuper@55456
  1181
fun knowthys () = (*["Isac", .., "Descript", "Delete"]*)
neuper@55456
  1182
  let
neuper@55456
  1183
    fun isacthys () = (* ["Isac", .., "KEStore"] without Build_Isac thys: "Interpret" etc *)
neuper@55456
  1184
      let
wneuper@59332
  1185
        val allthys = filter_out (member Context.eq_thy
wneuper@59352
  1186
          [(*Thy_Info_get_theory "ProgLang",*) Thy_Info_get_theory "Interpret", 
wneuper@59352
  1187
            Thy_Info_get_theory "xmlsrc", Thy_Info_get_theory "Frontend"]) 
wneuper@59352
  1188
          (Theory.ancestors_of (Thy_Info_get_theory "Build_Thydata"))
neuper@55456
  1189
      in
wneuper@59366
  1190
        take ((find_index (curry Context.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), 
neuper@55456
  1191
        allthys)
neuper@55456
  1192
      end
neuper@55456
  1193
    val isacthys' = isacthys ()
wneuper@59352
  1194
    val proglang_parent = Thy_Info_get_theory "ProgLang"
neuper@55456
  1195
  in
wneuper@59332
  1196
    take ((find_index (curry Context.eq_thy proglang_parent) isacthys'), isacthys')
neuper@55456
  1197
  end
wneuper@59414
  1198
neuper@55456
  1199
fun progthys () = (*["Isac", .., "Descript", "Delete"]*)
neuper@55456
  1200
  let
neuper@55456
  1201
    fun isacthys () = (* ["Isac", .., "KEStore"] without Build_Isac thys: "Interpret" etc *)
neuper@55456
  1202
      let
wneuper@59332
  1203
        val allthys = filter_out (member Context.eq_thy
wneuper@59352
  1204
          [(*Thy_Info_get_theory "ProgLang",*) Thy_Info_get_theory "Interpret", 
wneuper@59352
  1205
            Thy_Info_get_theory "xmlsrc", Thy_Info_get_theory "Frontend"]) 
wneuper@59352
  1206
          (Theory.ancestors_of (Thy_Info_get_theory "Build_Thydata"))
neuper@55456
  1207
      in
wneuper@59366
  1208
        take ((find_index (curry Context.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), 
neuper@55456
  1209
        allthys)
neuper@55456
  1210
      end
neuper@55456
  1211
    val isacthys' = isacthys ()
wneuper@59352
  1212
    val proglang_parent = Thy_Info_get_theory "ProgLang"
neuper@55456
  1213
  in
wneuper@59332
  1214
    drop ((find_index (curry Context.eq_thy proglang_parent) isacthys') + 1(*ProgLang*), isacthys')
neuper@55456
  1215
  end
neuper@55456
  1216
neuper@55456
  1217
fun partID thy = 
wneuper@59332
  1218
  if member Context.eq_thy (knowthys ()) thy then "IsacKnowledge"
wneuper@59332
  1219
  else if member Context.eq_thy (progthys ()) thy then "IsacScripts"
wneuper@59332
  1220
  else if member Context.eq_thy (isabthys ()) thy then "Isabelle"
neuper@55456
  1221
  else error ("closure of thys in Isac is broken by " ^ string_of_thy thy)
wneuper@59352
  1222
fun partID' (thy' : theory') = partID (Thy_Info_get_theory thy')
wneuper@59405
  1223
neuper@38061
  1224
end (*struct*)
wneuper@59405
  1225