src/Tools/isac/Interpret/calchead.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Wed, 24 Aug 2016 17:27:54 +0200
changeset 59230 57593b2a9d41
parent 59186 d9c3e373f8f5
child 59235 a40a06a23fc1
permissions -rw-r--r--
tuned
     1 (* Title:  Specify-phase: specifying and modeling a problem or a subproblem. The
     2            most important types are declared in mstools.sml.
     3    Author: Walther Neuper 991122, Mathias Lehnfeld
     4    (c) due to copyright terms
     5 
     6 12345678901234567890123456789012345678901234567890123456789012345678901234567890
     7         10        20        30        40        50        60        70        80
     8 *)
     9 
    10 (* TODO interne Funktionen aus sig entfernen *)
    11 signature CALC_HEAD =
    12   sig
    13     datatype additm = Add of SpecifyTools.itm | Err of string
    14     val all_dsc_in : SpecifyTools.itm_ list -> Term.term list
    15     val all_modspec : ptree * pos' -> ptree * pos'
    16     datatype appl = Appl of tac_ | Notappl of string
    17     val appl_add :
    18        Proof.context ->
    19        string ->
    20        SpecifyTools.ori list ->
    21        SpecifyTools.itm list ->
    22        (string * (Term.term * Term.term)) list -> cterm' -> additm
    23     type calcstate
    24     type calcstate'
    25     val chk_vars : term ppc -> string * Term.term list
    26     val chktyp :
    27        theory -> int * term list * term list -> term
    28     val chktyps :
    29        theory -> term list * term list -> term list
    30     val complete_metitms :
    31    SpecifyTools.ori list ->
    32    SpecifyTools.itm list ->
    33    SpecifyTools.itm list -> pat list -> SpecifyTools.itm list
    34     val complete_mod_ : ori list * pat list * pat list * itm list ->
    35 			itm list * itm list
    36     val complete_mod : ptree * pos' -> ptree * (pos * pos_)
    37     val complete_spec : ptree * pos' -> ptree * pos'
    38     val cpy_nam :
    39        pat list -> preori list -> pat -> preori
    40     val e_calcstate : calcstate
    41     val e_calcstate' : calcstate'
    42     val eq1 : ''a -> 'b * (''a * 'c) -> bool
    43     val eq3 :
    44        ''a -> Term.term -> 'b * 'c * 'd * ''a * SpecifyTools.itm_ -> bool
    45     val eq4 : ''a -> 'b * ''a list * 'c * 'd * 'e -> bool
    46     val eq5 :
    47        'a * 'b * 'c * 'd * SpecifyTools.itm_ ->
    48        'e * 'f * 'g * Term.term * 'h -> bool
    49     val eq_dsc : SpecifyTools.itm * SpecifyTools.itm -> bool
    50     val eq_pos' : ''a * pos_ -> ''a * pos_ -> bool
    51     val f_mout : theory -> mout -> Term.term
    52     val filter_outs :
    53        SpecifyTools.ori list ->
    54        SpecifyTools.itm list -> SpecifyTools.ori list
    55     val filter_pbt :
    56        SpecifyTools.ori list ->
    57        ('a * (Term.term * 'b)) list -> SpecifyTools.ori list
    58     val foldl1 : ('a * 'a -> 'a) -> 'a list -> 'a
    59     val foldr1 : ('a * 'a -> 'a) -> 'a list -> 'a
    60     val form : 'a -> ptree -> (string * ('a * pos_) * Term.term) list
    61     val formres : 'a -> ptree -> (string * ('a * pos_) * Term.term) list
    62     val gen_ins' : ('a * 'a -> bool) -> 'a * 'a list -> 'a list
    63     val get_formress :
    64        (string * (pos * pos_) * Term.term) list list ->
    65        pos -> ptree list -> (string * (pos * pos_) * Term.term) list
    66     val get_forms :
    67        (string * (pos * pos_) * Term.term) list list ->
    68        posel list -> ptree list -> (string * (pos * pos_) * Term.term) list
    69     val get_interval : pos' -> pos' -> int -> ptree -> (pos' * term) list
    70     val get_ocalhd : ptree * pos' -> ocalhd
    71     val get_spec_form : tac_ -> pos' -> ptree -> mout
    72     val geti_ct :
    73        theory ->
    74        SpecifyTools.ori -> SpecifyTools.itm -> string * cterm'
    75     val getr_ct : theory -> SpecifyTools.ori -> string * cterm'
    76     val has_list_type : Term.term -> bool
    77     val header : pos_ -> pblID -> metID -> pblmet
    78     val insert_ppc :
    79        theory ->
    80        int * SpecifyTools.vats * bool * string * SpecifyTools.itm_ ->
    81        SpecifyTools.itm list -> SpecifyTools.itm list
    82     val insert_ppc' :
    83        SpecifyTools.itm -> SpecifyTools.itm list -> SpecifyTools.itm list
    84     val is_complete_mod : ptree * pos' -> bool
    85     val is_complete_mod_ : SpecifyTools.itm list -> bool
    86     val is_complete_modspec : ptree * pos' -> bool
    87     val is_complete_spec : ptree * pos' -> bool
    88     val is_copy_named : 'a * ('b * Term.term) -> bool
    89     val is_copy_named_idstr : string -> bool
    90     val is_error : SpecifyTools.itm_ -> bool
    91     val is_field_correct : ''a -> ''b -> (''a * ''b list) list -> bool
    92     val is_known :
    93        Proof.context ->
    94        string ->
    95        SpecifyTools.ori list ->
    96        Term.term -> string * SpecifyTools.ori * Term.term list
    97     val is_list_type : Term.typ -> bool
    98     val is_notyet_input :
    99        Proof.context ->
   100        SpecifyTools.itm list ->
   101        Term.term list ->
   102        SpecifyTools.ori ->
   103        ('a * (Term.term * Term.term)) list -> string * SpecifyTools.itm
   104     val is_parsed : SpecifyTools.itm_ -> bool
   105     val is_untouched : SpecifyTools.itm -> bool
   106     val matc :
   107        theory ->
   108        pat list ->
   109        Term.term list ->
   110        (int list * string * Term.term * Term.term list) list ->
   111        (int list * string * Term.term * Term.term list) list
   112     val match_ags :
   113        theory -> pat list -> Term.term list -> SpecifyTools.ori list
   114     val oris2fmz_vals : ori list -> string list * term list
   115     val maxl : int list -> int
   116     val match_ags_msg : string list -> Term.term -> Term.term list -> unit
   117     val memI : ''a list -> ''a -> bool
   118     val mk_additem : string -> cterm' -> tac
   119     val mk_delete : theory -> string -> SpecifyTools.itm_ -> tac
   120     val mtc :
   121        theory -> pat -> Term.term -> SpecifyTools.preori option
   122     val nxt_add :
   123        theory ->
   124        SpecifyTools.ori list ->
   125        (string * (Term.term * 'a)) list ->
   126        SpecifyTools.itm list -> (string * cterm') option
   127     val nxt_model_pbl : tac_ -> ptree * (int list * pos_) -> tac_
   128     val nxt_spec :
   129        pos_ ->
   130        bool ->
   131        SpecifyTools.ori list ->
   132        spec ->
   133        SpecifyTools.itm list * SpecifyTools.itm list ->
   134        (string * (Term.term * 'a)) list * (string * (Term.term * 'b)) list ->
   135        spec -> pos_ * tac
   136     val nxt_specif : tac -> ptree * (int list * pos_) -> calcstate'
   137     val nxt_specif_additem :
   138        string -> cterm' -> ptree * (int list * pos_) -> calcstate'
   139     val nxt_specify_init_calc : fmz -> calcstate
   140     val ocalhd_complete :
   141        SpecifyTools.itm list ->
   142        (bool * Term.term) list -> domID * pblID * metID -> bool
   143     val ori2Coritm :
   144 	pat list -> ori -> itm
   145     val ori_2itm :
   146        SpecifyTools.itm_ ->
   147        Term.term -> Term.term list -> SpecifyTools.ori -> SpecifyTools.itm
   148     val overwrite_ppc :
   149        theory ->
   150        int * SpecifyTools.vats * bool * string * SpecifyTools.itm_ ->
   151        SpecifyTools.itm list ->
   152        (int * SpecifyTools.vats * bool * string * SpecifyTools.itm_) list
   153     val parse_ok : SpecifyTools.itm_ list -> bool
   154     val posform2str : pos' * ptform -> string
   155     val posforms2str : (pos' * ptform) list -> string
   156     val posterms2str : (pos' * term) list -> string (*tests only*)
   157     val ppc135list : 'a SpecifyTools.ppc -> 'a list
   158     val ppc2list : 'a SpecifyTools.ppc -> 'a list
   159     val pt_extract :
   160        ptree * (int list * pos_) ->
   161        ptform * tac option * Term.term list
   162     val pt_form : ppobj -> ptform
   163     val pt_model : ppobj -> pos_ -> ptform
   164     val reset_calchead : ptree * pos' -> ptree * pos'
   165     val seek_oridts :
   166        Proof.context ->
   167        string ->
   168        Term.term * Term.term list ->
   169        (int * SpecifyTools.vats * string * Term.term * Term.term list) list
   170        -> string * SpecifyTools.ori * Term.term list
   171     val seek_orits :
   172        Proof.context ->
   173        string ->
   174        Term.term list ->
   175        (int * SpecifyTools.vats * string * Term.term * Term.term list) list
   176        -> string * SpecifyTools.ori * Term.term list
   177     val seek_ppc :
   178        int -> SpecifyTools.itm list -> SpecifyTools.itm option
   179     val show_pt : ptree -> unit
   180     val some_spec : spec -> spec -> spec
   181     val specify :
   182        tac_ ->
   183        pos' ->
   184        cid ->
   185        ptree ->
   186        (posel list * pos_) * ((posel list * pos_) * istate) * mout * tac *
   187        safe * ptree
   188     val specify_additem :
   189        string ->
   190        cterm' * 'a ->
   191        int list * pos_ ->
   192        'b ->
   193        ptree ->
   194        (pos * pos_) * ((pos * pos_) * istate) * mout * tac * safe * ptree
   195     val tag_form : theory -> term * term -> term
   196     val test_types : Proof.context -> Term.term * Term.term list -> string
   197     val typeless : Term.term -> Term.term
   198     val unbound_ppc : term SpecifyTools.ppc -> Term.term list
   199     val vals_of_oris : SpecifyTools.ori list -> Term.term list
   200     val variants_in : Term.term list -> int
   201     val vars_of_pbl_ : ('a * ('b * Term.term)) list -> Term.term list
   202     val vars_of_pbl_' : ('a * ('b * Term.term)) list -> Term.term list
   203   end
   204  
   205 
   206 
   207 
   208 
   209 structure CalcHead (**): CALC_HEAD(**) =
   210 
   211 struct
   212 
   213 (* datatypes *)
   214 
   215 (*.the state wich is stored after each step of calculation; it contains
   216    the calc-state and a list of [tac,istate](="tacis") to be applied next.
   217    the last_elem tacis is the first to apply to the calc-state and
   218    the (only) one shown to the front-end as the 'proposed tac'.
   219    the calc-state resulting from the application of tacis is not stored,
   220    because the tacis hold enough information for efficiently rebuilding
   221    this state just by "fun generate ".*)
   222 type calcstate = 
   223      (ptree * pos') *    (*the calc-state to which the tacis could be applied*)
   224      (taci list);        (*ev. several (hidden) steps; 
   225                            in REVERSE order: first tac_ to apply is last_elem*)
   226 val e_calcstate = ((EmptyPtree, e_pos'), [e_taci]):calcstate;
   227 
   228 (*the state used during one calculation within the mathengine; it contains
   229   a list of [tac,istate](="tacis") which generated the the calc-state;
   230   while this state's tacis are extended by each (internal) step,
   231   the calc-state is used for creating new nodes in the calc-tree
   232   (eg. applicable_in requires several particular nodes of the calc-tree)
   233   and then replaced by the the newly created;
   234   on leave of the mathengine the resuing calc-state is dropped anyway,
   235   because the tacis hold enought information for efficiently rebuilding
   236   this state just by "fun generate ".*)
   237 type calcstate' = 
   238      taci list *        (*cas. several (hidden) steps; 
   239                           in REVERSE order: first tac_ to apply is last_elem*)
   240      pos' list *        (*a "continuous" sequence of pos',
   241 			 deleted by application of taci list*)     
   242      (ptree * pos');    (*the calc-state resulting from the application of tacis*)
   243 val e_calcstate' = ([e_taci], [e_pos'], (EmptyPtree, e_pos')):calcstate';
   244 
   245 (*FIXXXME.WN020430 intermediate hack for fun ass_up*)
   246 fun f_mout thy (Form' (FormKF (_,_,_,_,f))) = (Thm.term_of o the o (parse thy)) f
   247   | f_mout thy _ = error "f_mout: not called with formula";
   248 
   249 
   250 (*.is the calchead complete ?.*)
   251 fun ocalhd_complete (its: itm list) (pre: (bool * term) list) (dI,pI,mI) = 
   252     foldl and_ (true, map #3 its) andalso 
   253     foldl and_ (true, map #1 pre) andalso 
   254     dI<>e_domID andalso pI<>e_pblID andalso mI<>e_metID;
   255 
   256 (*["BOOL (1+x=2)","REAL x"] --match_ags--> oris 
   257   --oris2fmz_vals--> ["equality (1+x=2)","boundVariable x","solutions L"]*)
   258 fun oris2fmz_vals oris =
   259     let fun ori2fmz_vals ((_,_,_,dsc,ts):ori) = 
   260 	    ((term2str o comp_dts') (dsc, ts), last_elem ts) 
   261 	    handle _ => error ("ori2fmz_env called with "^terms2str ts)
   262     in (split_list o (map ori2fmz_vals)) oris end;
   263 
   264 (* make a term 'typeless' for comparing with another 'typeless' term;
   265    'type-less' usually is illtyped                                  *)
   266 fun typeless (Const(s,_)) = (Const(s,e_type)) 
   267   | typeless (Free(s,_)) = (Free(s,e_type))
   268   | typeless (Var(n,_)) = (Var(n,e_type))
   269   | typeless (Bound i) = (Bound i)
   270   | typeless (Abs(s,_,t)) = Abs(s,e_type, typeless t)
   271   | typeless (t1 $ t2) = (typeless t1) $ (typeless t2);
   272 (*
   273 > val (SOME ct) = parse thy "max_relation (A=#2*a*b - a^^^#2)";
   274 > val (_,t1) = split_dsc_t hs (Thm.term_of ct);
   275 > val (SOME ct) = parse thy "A=#2*a*b - a^^^#2";
   276 > val (_,t2) = split_dsc_t hs (Thm.term_of ct);
   277 > typeless t1 = typeless t2;
   278 val it = true : bool
   279 *)
   280 
   281 
   282 
   283 (*.to an input (d,ts) find the according ori and insert the ts.*)
   284 (*WN.11.03: + dont take first inter<>[]*)
   285 fun seek_oridts ctxt sel (d,ts) [] =
   286     ("seek_oridts: input ('" ^
   287         (term_to_string' ctxt (comp_dts (d,ts))) ^ "') not found in oris (typed)",
   288       (0, [], sel, d, ts),
   289       [])
   290   | seek_oridts ctxt sel (d,ts) ((id, vat, sel', d', ts')::oris) =
   291     if sel = sel' andalso d = d' andalso (inter op = ts ts') <> [] then
   292       ("", (id, vat, sel, d, inter op = ts ts'), ts') else
   293       seek_oridts ctxt sel (d, ts) oris;
   294 
   295 (*.to an input (_,ts) find the according ori and insert the ts.*)
   296 fun seek_orits ctxt sel ts [] = 
   297     ("seek_orits: input (_, '" ^ strs2str (map (term_to_string' ctxt) ts) ^
   298     "') not found in oris (typed)", e_ori_, [])
   299   | seek_orits ctxt sel ts ((id,vat,sel',d,ts')::(oris:ori list)) =
   300     if sel = sel' andalso (inter op = ts ts') <> [] 
   301     then if sel = sel' 
   302 	  then ("", (id,vat,sel,d, inter op = ts ts'):ori, ts')
   303 	  else (((strs2str' o map (term_to_string' ctxt)) ts) ^ " not for " ^ sel, e_ori_, [])
   304     else seek_orits ctxt sel ts oris;
   305 (* false
   306 > val ((id,vat,sel',d,ts')::(ori':ori)) = ori;
   307 > seek_orits thy sel ts [(id,vat,sel',d,ts')];
   308 uncaught exception TYPE
   309 > seek_orits thy sel ts [];
   310 uncaught exception TYPE
   311 *)
   312 
   313 (*find_first item with #1 equal to id*)
   314 fun seek_ppc id [] = NONE
   315   | seek_ppc id (p::(ppc:itm list)) =
   316     if id = #1 p then SOME p else seek_ppc id ppc;
   317 
   318 
   319 datatype appl = Appl of tac_ | Notappl of string;
   320 
   321 fun ppc2list ({Given=gis,Where=whs,Find=fis,
   322 	       With=wis,Relate=res}: 'a ppc) =
   323   gis @ whs @ fis @ wis @ res;
   324 fun ppc135list ({Given=gis,Find=fis,Relate=res,...}: 'a ppc) =
   325   gis @ fis @ res;
   326 
   327 
   328 
   329 
   330 (* get the number of variants in a problem in 'original',
   331    assumes equal descriptions in immediate sequence    *)
   332 fun variants_in ts =
   333   let fun eq(x,y) = head_of x = head_of y;
   334     fun cnt eq [] y n = ([n],[])
   335       | cnt eq (x::xs) y n = if eq(x,y) then cnt eq xs y (n+1)
   336 			     else ([n], x::xs);
   337     fun coll eq  xs [] = xs
   338       | coll eq  xs (y::ys) = 
   339       let val (n,ys') = cnt eq (y::ys) y 0;
   340       in if ys' = [] then xs @ n else coll eq  (xs @ n) ys' end;
   341     val vts = subtract op = [1] (distinct (coll eq [] ts));
   342   in case vts of [] => 1 | [n] => n
   343       | _ => error "different variants in formalization" end;
   344 (*
   345 > cnt (op=) [2,2,2,4,5,5,5,5,5] 2 0;
   346 val it = ([3],[4,5,5,5,5,5]) : int list * int list
   347 > coll (op=) [] [1,2,2,2,4,5,5,5,5,5];
   348 val it = [1,3,1,5] : int list
   349 *)
   350 
   351 fun is_list_type (Type("List.list",_)) = true
   352   | is_list_type _ = false;
   353 (* fun destr (Type(str,sort)) = (str,sort);
   354 > val (SOME ct) = parse thy "lll::real list";
   355 > val ty = (#T o rep_cterm) ct;
   356 > is_list_type ty;
   357 val it = true : bool 
   358 > destr ty;
   359 val it = ("List.list",["RealDef.real"]) : string * typ list
   360 > atomty ((#t o rep_cterm) ct);
   361 *** -------------
   362 *** Free ( lll, real list)
   363 val it = () : unit
   364  
   365 > val (SOME ct) = parse thy "[lll::real]";
   366 > val ty = (#T o rep_cterm) ct;
   367 > is_list_type ty;
   368 val it = true : bool 
   369 > destr ty;
   370 val it = ("List.list",["'a"]) : string * typ list
   371 > atomty ((#t o rep_cterm) ct);
   372 *** -------------
   373 *** Const ( List.list.Cons, [real, real list] => real list)
   374 ***   Free ( lll, real)
   375 ***   Const ( List.list.Nil, real list) 
   376 
   377 > val (SOME ct) = parse thy "lll";
   378 > val ty = (#T o rep_cterm) ct;
   379 > is_list_type ty;
   380 val it = false : bool  *)
   381 
   382 
   383 fun has_list_type (Free(_,T)) = is_list_type T
   384   | has_list_type _ = false;
   385 (*
   386 > val (SOME ct) = parse thy "lll::real list";
   387 > has_list_type (Thm.term_of ct);
   388 val it = true : bool
   389 > val (SOME ct) = parse thy "[lll::real]";
   390 > has_list_type (Thm.term_of ct);
   391 val it = false : bool *)
   392 
   393 fun is_parsed (Syn _) = false
   394   | is_parsed _ = true;
   395 fun parse_ok its = foldl and_ (true, map is_parsed its);
   396 
   397 fun all_dsc_in itm_s =
   398   let    
   399     fun d_in (Cor ((d,_),_)) = [d]
   400       | d_in (Syn c) = []
   401       | d_in (Typ c) = []
   402       | d_in (Inc ((d,_),_)) = [d]
   403       | d_in (Sup (d,_)) = [d]
   404       | d_in (Mis (d,_)) = [d];
   405   in (flat o (map d_in)) itm_s end;  
   406 
   407 (* 30.1.00 ---
   408 fun is_Syn (Syn _) = true
   409   | is_Syn (Typ _) = true
   410   | is_Syn _ = false;
   411  --- *)
   412 fun is_error (Cor (_,ts)) = false
   413   | is_error (Sup (_,ts)) = false
   414   | is_error (Inc (_,ts)) = false
   415   | is_error (Mis (_,ts)) = false
   416   | is_error _ = true;
   417 
   418 (* 30.1.00 ---
   419 fun ct_in (Syn (c)) = c
   420   | ct_in (Typ (c)) = c
   421   | ct_in _ = error "ct_in called for Cor .. Sup";
   422  --- *)
   423 
   424 (*#############################################################*)
   425 (*#############################################################*)
   426 (* vvv--- aus nnewcode.sml am 30.1.00 ---vvv *)
   427 
   428 
   429 (* testdaten besorgen:
   430    use"test-coil-kernel.sml";
   431    val (PblObj{origin=(oris,_,_),meth={ppc=itms,...},...}) = 
   432         get_obj I pt p;
   433   *)
   434 
   435 (* given oris, ppc, 
   436    variant V: oris union ppc => int, id ID: oris union ppc => int
   437 
   438    ppc is_complete == 
   439      EX vt:V. ALL r:oris --> EX i:ppc. ID r = ID i  &  complete i
   440 
   441    and
   442      @vt = max sum(i : ppc) V i
   443 *)
   444 
   445 
   446 
   447 (*
   448 > ((vts_cnt (vts_in itms))) itms;
   449 
   450 
   451 
   452 ---^^--test 10.3.
   453 > val vts = vts_in itms;
   454 val vts = [1,2,3] : int list
   455 > val nvts = vts_cnt vts itms;
   456 val nvts = [(1,6),(2,5),(3,7)] : (int * int) list
   457 > val mx = max2 nvts;
   458 val mx = (3,7) : int * int
   459 > val v = max_vt itms;
   460 val v = 3 : int
   461 --------------------------
   462 > 
   463 *)
   464 
   465 (*.get the first term in ts from ori.*)
   466 (* val (_,_,fd,d,ts) = hd miss;
   467    *)
   468 fun getr_ct thy ((_, _, fd, d, ts) : ori) =
   469   (fd, ((term_to_string''' thy) o comp_dts) (d,[hd ts]) : cterm');
   470 (* val t = comp_dts (d,[hd ts]);
   471    *)
   472 
   473 (* get a term from ori, notyet input in itm.
   474    the term from ori is thrown back to a string in order to reuse
   475    machinery for immediate input by the user. *)
   476 fun geti_ct thy ((_, _, _, d, ts) : ori) ((_, _, _, fd, itm_) : itm) =
   477   (fd, ((term_to_string''' thy) o comp_dts) (d, subtract op = (ts_in itm_) ts) : cterm')
   478 
   479 (* in FE dsc, not dat: this is in itms ...*)
   480 fun is_untouched ((_,_,false,_,Inc((_,[]),_)):itm) = true
   481   | is_untouched _ = false;
   482 
   483 
   484 (* select an item in oris, notyet input in itms 
   485    (precondition: in itms are only Cor, Sup, Inc) *)
   486 local infix mem;
   487 fun x mem [] = false
   488   | x mem (y :: ys) = x = y orelse x mem ys;
   489 in 
   490 fun nxt_add thy ([]:ori list) pbt itms = (*root (only) ori...fmz=[]*)
   491   let
   492     fun test_d d ((i,_,_,_,itm_):itm) = (d = (d_in itm_)) andalso i<>0; 
   493     fun is_elem itms (f,(d,t)) = 
   494       case find_first (test_d d) itms of 
   495 	SOME _ => true | NONE => false;
   496   in case filter_out (is_elem itms) pbt of
   497 (* val ((f,(d,_))::itms) = filter_out (is_elem itms) pbt;
   498    *)
   499     (f,(d,_))::itms => 
   500     SOME (f : string, ((term_to_string''' thy) o comp_dts) (d, []) : cterm')
   501   | _ => NONE end
   502 
   503 (* val (thy,itms) = (assoc_thy (if dI=e_domID then dI' else dI),pbl);
   504    *)
   505   | nxt_add thy oris pbt itms =
   506   let
   507     fun testr_vt v ori = (curry (op mem) v) (#2 (ori:ori))
   508       andalso (#3 ori) <>"#undef";
   509     fun testi_vt v itm = (curry (op mem) v) (#2 (itm:itm));
   510     fun test_id ids r = curry (op mem) (#1 (r:ori)) ids;
   511     fun test_subset (itm:itm) ((_,_,_,d,ts):ori) = 
   512 	(d_in (#5 itm)) = d andalso subset op = (ts_in (#5 itm), ts);
   513     fun false_and_not_Sup((i,v,false,f,Sup _):itm) = false
   514       | false_and_not_Sup (i,v,false,f, _) = true
   515       | false_and_not_Sup  _ = false;
   516 
   517     val v = if itms = [] then 1 else max_vt itms;
   518     val vors = if v = 0 then oris else filter (testr_vt v) oris;(*oris..vat*)
   519     val vits = if v = 0 then itms (*because of dsc without dat*)
   520 	       else filter (testi_vt v) itms;                   (*itms..vat*)
   521     val icl = filter false_and_not_Sup vits; (* incomplete *)
   522   in if icl = [] 
   523      then case filter_out (test_id (map #1 vits)) vors of
   524 	      [] => NONE
   525 	    (* val miss = filter_out (test_id (map #1 vits)) vors;
   526 	       *)
   527 	    | miss => SOME (getr_ct thy (hd miss))
   528      else
   529 	 case find_first (test_subset (hd icl)) vors of
   530 	     (* val SOME ori = find_first (test_subset (hd icl)) vors;
   531 	      *)
   532 	     NONE => error "nxt_add: EX itm. not(dat(itm)<=dat(ori))"
   533 	   | SOME ori => SOME (geti_ct thy ori (hd icl))
   534   end
   535 end;
   536 
   537 
   538 
   539 fun mk_delete thy "#Given"  itm_ = Del_Given   (itm_out thy itm_)
   540   | mk_delete thy "#Find"   itm_ = Del_Find    (itm_out thy itm_)
   541   | mk_delete thy "#Relate" itm_ = Del_Relation(itm_out thy itm_)
   542   | mk_delete thy str _ = 
   543   error ("mk_delete: called with field '"^str^"'");
   544 fun mk_additem "#Given" ct = Add_Given ct
   545   | mk_additem "#Find"  ct = Add_Find ct    
   546   | mk_additem "#Relate"ct = Add_Relation ct
   547   | mk_additem str _ = 
   548   error ("mk_additem: called with field '"^str^"'");
   549 
   550 
   551 (* determine the next step of specification;
   552    not done here: Refine_Tacitly (otherwise *** unknown method: (..., no_met))
   553    eg. in rootpbl 'no_met': 
   554 args:
   555   preok          predicates are _all_ ok (and problem matches completely)
   556   oris           immediately from formalization 
   557   (dI',pI',mI')  specification coming from author/parent-problem
   558   (pbl,          item lists specified by user
   559    met)          -"-, tacitly completed by copy_probl
   560   (dI,pI,mI)     specification explicitly done by the user
   561   (pbt, mpc)     problem type, guard of method
   562 *)
   563 fun nxt_spec Pbl preok (oris : ori list) ((dI', pI', mI') : spec)
   564   ((pbl : itm list), (met : itm list)) (pbt, mpc) ((dI, pI, mI) : spec) = 
   565     ((*tracing"### nxt_spec Pbl";*)
   566      if dI' = e_domID andalso dI = e_domID then (Pbl, Specify_Theory dI')
   567      else if pI' = e_pblID andalso pI = e_pblID then (Pbl, Specify_Problem pI')
   568      else case find_first (is_error o #5) (pbl:itm list) of
   569 	      SOME (_, _, _, fd, itm_) => 
   570 	      (Pbl, mk_delete 
   571 	                (assoc_thy (if dI = e_domID then dI' else dI)) fd itm_)
   572 	    | NONE => 
   573 	      ((*tracing"### nxt_spec is_error NONE";*)
   574 	       case nxt_add (assoc_thy (if dI = e_domID then dI' else dI)) 
   575 		            oris pbt pbl of
   576 	           SOME (fd,ct') => ((*tracing"### nxt_spec nxt_add SOME";*)
   577 				     (Pbl, mk_additem fd ct'))
   578 	         | NONE => (*pbl-items complete*)
   579 	           if not preok then (Pbl, Refine_Problem pI')
   580 	           else
   581 		       if dI = e_domID then (Pbl, Specify_Theory dI')
   582 		       else if pI = e_pblID then (Pbl, Specify_Problem pI')
   583 		       else if mI = e_metID then (Pbl, Specify_Method mI')
   584 		       else
   585 			   case find_first (is_error o #5) met of
   586 			       SOME (_,_,_,fd,itm_) => 
   587 			       (Met, mk_delete (assoc_thy dI) fd itm_)
   588 			     | NONE => 
   589 			       (case nxt_add (assoc_thy dI) oris mpc met of
   590 				    SOME (fd,ct') => (*30.8.01: pre?!?*)
   591 				    (Met, mk_additem fd ct')
   592 				  | NONE => 
   593 				    ((*Solv 3.4.00*)Met, Apply_Method mI))))
   594 
   595   | nxt_spec Met preok oris (dI',pI',mI') (pbl, met) (pbt,mpc) (dI,pI,mI) = 
   596   ((*tracing"### nxt_spec Met"; *)
   597    case find_first (is_error o #5) met of
   598      SOME (_,_,_,fd,itm_) => 
   599 	 (Met, mk_delete (assoc_thy (if dI=e_domID then dI' else dI)) fd itm_)
   600    | NONE => 
   601        case nxt_add (assoc_thy (if dI=e_domID then dI' else dI))oris mpc met of
   602 	 SOME (fd,ct') => (Met, mk_additem fd ct')
   603        | NONE => 
   604 	   ((*tracing"### nxt_spec Met: nxt_add NONE";*)
   605 	    if dI = e_domID then (Met, Specify_Theory dI')
   606 	    else if pI = e_pblID then (Met, Specify_Problem pI')
   607 		 else if not preok then (Met, Specify_Method mI)
   608 		      else (Met, Apply_Method mI)));
   609 	  
   610 (* di_ pI_ mI_ pos_
   611 val itms = [(1,[1],true,"#Find",Cor(e_term,[e_term])):itm,
   612 	    (2,[2],true,"#Find",Syn("empty"))];
   613 *)
   614 
   615 fun is_field_correct sel d dscpbt =
   616   case assoc (dscpbt, sel) of
   617     NONE => false
   618   | SOME ds => member op = ds d;
   619 
   620 (*. update the itm_ already input, all..from ori .*)
   621 (* val (id,vt,fd,d,ts) = (i,v,f,d,ts\\ts');
   622    *)
   623 fun ori_2itm itm_ pid all ((id,vt,fd,d,ts):ori) = 
   624   let 
   625     val ts' = union op = (ts_in itm_) ts;
   626     val pval = pbl_ids' d ts'
   627 	(*WN.9.5.03: FIXXXME [#0, epsilon]
   628 	  here would upd_penv be called for [#0, epsilon] etc. *)
   629     val complete = if eq_set op = (ts', all) then true else false;
   630   in case itm_ of
   631     (Cor _) => 
   632 	(if fd = "#undef" then (id,vt,complete,fd,Sup(d,ts')) 
   633 	 else (id,vt,complete,fd,Cor((d,ts'),(pid, pval)))):itm
   634   | (Syn c)     => error ("ori_2itm wants to overwrite "^c)
   635   | (Typ c)     => error ("ori_2itm wants to overwrite "^c)
   636   | (Inc _) => if complete
   637 	       then (id,vt,true ,fd, Cor ((d,ts'),(pid, pval)))
   638 	       else (id,vt,false,fd, Inc ((d,ts'),(pid, pval)))
   639   | (Sup ((*_,_*)d,ts')) => (*4.9.01 lost env*)
   640 	 (*if fd = "#undef" then*) (id,vt,complete,fd,Sup(d,ts'))
   641 	 (*else (id,vt,complete,fd,Cor((d,ts'),e))*)
   642 (* 28.1.00: not completely clear ---^^^ etc.*)
   643 (* 4.9.01: Mis just copied---vvv *)
   644   | (Mis _) => if complete
   645 		     then (id,vt,true ,fd, Cor ((d,ts'),(pid, pval)))
   646 		     else (id,vt,false,fd, Inc ((d,ts'),(pid, pval)))
   647   end;
   648 
   649 
   650 fun eq1 d (_,(d',_)) = (d = d');
   651 fun eq3 f d (_,_,_,f',itm_) = f = f' andalso d = (d_in itm_); 
   652 
   653 
   654 (* 'all' ts from ori; ts is the input; (ori carries rest of info)
   655    9.01: this + ori_2itm is _VERY UNCLEAR_ ? overhead ?
   656    pval: value for problem-environment _NOT_ checked for 'inter' --
   657    -- FIXXME.WN.11.03 the generation of penv has to go to insert_ppc
   658   (as it has been done for input_icalhd+insert_ppc' in 11.03)*)
   659 (*. is_input ori itms <=> 
   660     EX itm. (1) ori(field,dsc) = itm(field,dsc) & (2..4)
   661             (2) ori(ts) subset itm(ts)        --- Err "already input"       
   662 	    (3) ori(ts) inter itm(ts) = empty --- new: ori(ts)
   663 	    (4) -"- <> empty                  --- new: ori(ts) \\ inter .*)
   664 (* val(itms,(i,v,f,d,ts)) = (ppc,ori');
   665    *)
   666 fun is_notyet_input ctxt (itms:itm list) all ((i,v,f,d,ts):ori) pbt =
   667   case find_first (eq1 d) pbt of
   668     SOME (_,(_,pid)) =>
   669       (case find_first (eq3 f d) itms of
   670         SOME (_,_,_,_,itm_) =>
   671           let 
   672             val ts' = inter op = (ts_in itm_) ts;
   673             in 
   674               if subset op = (ts, ts') 
   675               then (((strs2str' o map (term_to_string' ctxt)) ts') ^ " already input", e_itm)(*2*)
   676 	            else ("", ori_2itm itm_ pid all (i,v,f,d, subtract op = ts' ts))             (*3,4*)
   677 	          end
   678 	    | NONE => ("", ori_2itm (Inc ((e_term,[]),(pid,[]))) pid all (i,v,f,d,ts)))            (*1*)
   679   | NONE => ("", ori_2itm (Sup (d,ts)) e_term all (i,v,f,d,ts));
   680 
   681 fun test_types ctxt (d,ts) =
   682   let 
   683     val opt = (try comp_dts) (d,ts);
   684     val msg = case opt of 
   685       SOME _ => "" 
   686     | NONE => (term_to_string' ctxt d ^ " " ^
   687 	       (strs2str' o map (term_to_string' ctxt)) ts ^ " is illtyped");
   688   in msg end;
   689 
   690 fun maxl [] = error "maxl of []"
   691   | maxl (y::ys) =
   692   let fun mx x [] = x
   693 	| mx x (y::ys) = if x < (y:int) then mx y ys else mx x ys
   694   in mx y ys end;
   695 
   696 
   697 (*. is the input term t known in oris ? 
   698     give feedback on all(?) strange input;
   699     return _all_ terms already input to this item (e.g. valuesFor a,b) .*)
   700 fun is_known ctxt sel ori t =
   701   let
   702     val _ = tracing ("RM is_known: t=" ^ term2str t);
   703     val ots = (distinct o flat o (map #5)) (ori:ori list);
   704     val oids = ((map (fst o dest_Free)) o distinct o 
   705 		  flat o (map vars)) ots;
   706     val (d, ts) = split_dts t;
   707     val ids = map (fst o dest_Free) 
   708       ((distinct o (flat o (map vars))) ts);
   709   in if (subtract op = oids ids) <> []
   710      then (("identifiers "^(strs2str' (subtract op = oids ids)) ^
   711 	     " not in example"), e_ori_, [])
   712      else 
   713 	     if d = e_term 
   714 	     then 
   715 	       if not (subset op = (map typeless ts, map typeless ots))
   716 	       then ("terms '" ^ (strs2str' o (map (term_to_string' ctxt))) ts ^
   717 		       "' not in example (typeless)", e_ori_, [])
   718 	       else 
   719            (case seek_orits ctxt sel ts ori of
   720 		          ("", ori_ as (_,_,_,d,ts), all) =>
   721 		             (case test_types ctxt (d,ts) of
   722 			              "" => ("", ori_, all)
   723 			            | msg => (msg, e_ori_, []))
   724 		        | (msg,_,_) => (msg, e_ori_, []))
   725 	     else 
   726 	       if member op = (map #4 ori) d
   727 	       then seek_oridts ctxt sel (d,ts) ori
   728 	       else (term_to_string' ctxt d ^ " not in example", (0, [], sel, d, ts), [])
   729   end;
   730 
   731 (*. for return-value of appl_add .*)
   732 datatype additm =
   733 	 Add of itm
   734        | Err of string;    (*error-message*)
   735 
   736 
   737 (** add an item to the model; check wrt. oris and pbt **)
   738 (* in contrary to oris<>[] below, this part handles user-input
   739    extremely acceptive, i.e. accept input instead error-msg *)
   740 fun appl_add ctxt sel [] ppc pbt ct =
   741       let
   742         val i = 1 + (if ppc = [] then 0 else map #1 ppc |> maxl);
   743         in 
   744           case parseNEW ctxt ct of
   745             NONE => Add (i, [], false, sel, Syn ct)
   746           | SOME t =>
   747               let val (d, ts) = split_dts t;
   748               in 
   749                 if d = e_term 
   750                 then Add (i, [], false, sel, Mis (dsc_unknown, hd ts)) 
   751                 else
   752                   (case find_first (eq1 d) pbt of
   753                      NONE => Add (i, [], true, sel, Sup (d,ts))
   754                    | SOME (f, (_, id)) =>
   755                        let fun eq2 d (i, _, _, _, itm_) =
   756                              d = (d_in itm_) andalso i <> 0;
   757                        in case find_first (eq2 d) ppc of
   758                             NONE => Add (i, [], true, f,Cor ((d, ts), (id, pbl_ids' d ts)))
   759                           | SOME (i', _, _, _, itm_) => 
   760                               if is_list_dsc d 
   761                               then 
   762                                 let
   763                                   val in_itm = ts_in itm_;
   764                                   val ts' = union op = ts in_itm;
   765                                   val i'' = if in_itm = [] then i else i';
   766                                 in Add (i'', [], true, f, Cor ((d, ts'), (id, pbl_ids' d ts'))) end
   767                               else Add (i', [], true, f, Cor ((d, ts),(id, pbl_ids' d ts)))
   768                        end)
   769               end
   770       end
   771   | appl_add ctxt sel oris ppc pbt str =
   772       case parseNEW ctxt str of
   773         NONE => Err ("appl_add: syntax error in '" ^ str ^ "'")
   774       | SOME t => 
   775           case is_known ctxt sel oris t of
   776             ("", ori', all) => 
   777               (case is_notyet_input ctxt ppc all ori' pbt of
   778                  ("", itm) => Add itm
   779                | (msg, _) => Err ("[error] appl_add: is_notyet_input: " ^ msg))
   780           | (msg, _, _) => Err ("[error] appl_add: is_known: " ^ msg);
   781 
   782 
   783 (** make oris from args of the stac SubProblem and from pbt **)
   784 (* can this formal argument (of a model-pattern) be omitted in the arg-list
   785    of a SubProblem ? see calcelems.sml 'type met ' *)
   786 fun is_copy_named_idstr str =
   787     case (rev o Symbol.explode) str of
   788 	"'":: _ ::"'"::_ => (tracing ((strs2str o (rev o Symbol.explode)) 
   789                                   "is_copy_named_idstr: " ^ str ^ " T"); true)
   790       | _ => (tracing ((strs2str o (rev o Symbol.explode)) 
   791                                   "is_copy_named_idstr: " ^ str ^ " F"); false);
   792 fun is_copy_named (_, (_, t)) = (is_copy_named_idstr o free2str) t;
   793 
   794 (*.should this formal argument (of a model-pattern) create a new identifier?.*)
   795 fun is_copy_named_generating_idstr str =
   796     if is_copy_named_idstr str
   797     then case (rev o Symbol.explode) str of
   798 	"'"::"'"::"'"::_ => false
   799       | _ => true
   800     else false;
   801 fun is_copy_named_generating (_, (_, t)) = 
   802     (is_copy_named_generating_idstr o free2str) t;
   803 
   804 (*.split type-wrapper from scr-arg and build part of an ori;
   805    an type-error is reported immediately, raises an exn, 
   806    subsequent handling of exn provides 2nd part of error message.*)
   807 fun mtc thy ((str, (dsc, _)):pat) (ty $ var) =
   808     (* val (thy, (str, (dsc, _)), (ty $ var)) =
   809 	   (thy,  p,               a);
   810        *)
   811     (Thm.global_cterm_of thy (dsc $ var);(*type check*)
   812      SOME ((([1], str, dsc, (*[var]*)
   813 	    split_dts' (dsc, var))): preori)(*:ori without leading #*))
   814     handle e as TYPE _ => 
   815 	   (tracing (dashs 70 ^ "\n"
   816 	^"*** ERROR while creating the items for the model of the ->problem\n"
   817 	^"*** from the ->stac with ->typeconstructor in arglist:\n"
   818 	^"*** item (->description ->value): "^term2str dsc^" "^term2str var^"\n"
   819 	^"*** description: "^(term_detail2str dsc)
   820 	^"*** value: "^(term_detail2str var)
   821 	^"*** typeconstructor in script: "^(term_detail2str ty)
   822 	^"*** checked by theory: "^(theory2str thy)^"\n"
   823 	^"*** " ^ dots 66);
   824 	    (*OldGoals.print_exn e; raises exn again*)
   825             writeln (PolyML.makestring e);
   826             reraise e;
   827 	(*raise ERROR "actual args do not match formal args";FIXXXME.WN100916*)
   828 	NONE);
   829 
   830 (*.match each pat of the model-pattern with an actual argument;
   831    precondition: copy-named vars are filtered out.*)
   832 fun matc thy ([]:pat list)  _  (oris:preori list) = oris
   833   | matc thy pbt [] _ =
   834     (tracing (dashs 70);
   835      error ("actual arg(s) missing for '"^pats2str pbt
   836 		 ^"' i.e. should be 'copy-named' by '*_._'"))
   837   | matc thy ((p as (s,(d,t)))::pbt) (a::ags) oris =
   838     (* val (thy, ((p as (s,(d,t)))::pbt), (a::ags), oris) =
   839 	   (thy,  pbt',                    ags,     []);
   840        (*recursion..*)
   841        val (thy, ((p as (s,(d,t)))::pbt), (a::ags), oris) =
   842 	   (thy,  pbt,                     ags,    (oris @ [ori]));
   843        *)
   844     (*del?..*)if (is_copy_named_idstr o free2str) t then oris
   845     else(*..del?*) let val opt = mtc thy p a;  
   846 	 in case opt of
   847 		(* val SOME ori = mtc thy p a;
   848 		   *)
   849 		SOME ori => matc thy pbt ags (oris @ [ori])
   850 	      | NONE => [](*WN050903 skipped by exn handled in match_ags*)
   851 	 end; 
   852 (* run subp-rooteq.sml until Init_Proof before ...
   853 > val Nd (PblObj {origin=(oris,_,_),...},_) = pt;(*from test/subp-rooteq.sml*)
   854 > fun xxxfortest (_,a,b,c,d) = (a,b,c,d);val oris = map xxxfortest oris;
   855 
   856  other vars as in mtc ..
   857 > matc thy (drop_last pbt) ags [];
   858 val it = ([[1],"#Given",Const #,[#]),(0,[#],"#Given",Const #,[#])],2)*)
   859 
   860 
   861 (* generate a new variable "x_i" name from a related given one "x"
   862    by use of oris relating "v_i_" (is_copy_named!) to "v_"
   863    e.g. (v_, x) & (v_i_, ?) --> (v_i_, x_i) *)
   864 
   865 (* generate a new variable "x_i" name from a related given one "x"
   866    by use of oris relating "v_v'i'" (is_copy_named!) to "v_v"
   867    e.g. (v_v, x) & (v_v'i', ?) --> (v_v'i', x_i),
   868    but leave is_copy_named_generating as is, e.t. ss''' *)
   869 fun cpy_nam (pbt:pat list) (oris:preori list) (p as (field,(dsc,t)):pat) =
   870   (if is_copy_named_generating p
   871    then (*WN051014 kept strange old code ...*)
   872        let fun sel (_,_,d,ts) = comp_ts (d, ts) 
   873 	   val cy' = (implode o (drop_last_n 3) o Symbol.explode o free2str) t
   874 	   val ext = (last_elem o drop_last o Symbol.explode o free2str) t
   875 	   val vars' = map (free2str o snd o snd) pbt (*cpy-nam filtered_out*)
   876 	   val vals = map sel oris
   877 	   val cy_ext = (free2str o the) (assoc (vars'~~vals, cy'))^"_"^ext
   878        in ([1], field, dsc, [mk_free (type_of t) cy_ext]):preori end
   879    else ([1], field, dsc, [t])
   880 	)
   881   handle _ => error ("cpy_nam: for "^(term2str t));
   882 
   883 (*.match the actual arguments of a SubProblem with a model-pattern
   884    and create an ori list (in root-pbl created from formalization).
   885    expects ags:pats = 1:1, while copy-named are filtered out of pats;
   886    if no 1:1 the exn raised by matc/mtc and handled at call.
   887    copy-named pats are appended in order to get them into the model-items.*)
   888 fun match_ags thy (pbt:pat list) ags =
   889     let fun flattup (i,(var,bool,str,itm_)) = (i,var,bool,str,itm_);
   890 	val pbt' = filter_out is_copy_named pbt;
   891 	val cy = filter is_copy_named pbt;
   892 	val oris' = matc thy pbt' ags [];
   893 	val cy' = map (cpy_nam pbt' oris') cy;
   894 	val ors = add_id (oris' @ cy'); 
   895     (*appended in order to get ^^^^^ into the model-items*)
   896     in (map flattup ors):ori list end;
   897 
   898 (*.report part of the error-msg which is not available in match_args.*)
   899 fun match_ags_msg pI stac ags =
   900     let (*val s = !show_types
   901 	val _ = show_types:= true*)
   902 	val pats = (#ppc o get_pbt) pI
   903 	val msg = (dots 70^"\n"
   904 		 ^"*** problem "^strs2str pI^" has the ...\n"
   905 		 ^"*** model-pattern "^pats2str pats^"\n"
   906 		 ^"*** stac   '"^term2str stac^"' has the ...\n"
   907 		 ^"*** arg-list "^terms2str ags^"\n"
   908 		 ^dashs 70)
   909 	(*WN100921 ^^^^ expect TYPE errormsg below; lost with Isa09*)
   910 	(*val _ = show_types:= s*)
   911     in tracing msg end;
   912 
   913 
   914 (*get the variables out of a pbl_; FIXME.WN.0311: is_copy_named ...obscure!!!*)
   915 fun vars_of_pbl_ pbl_ = 
   916     let fun var_of_pbl_ (gfr,(dsc,t)) = t
   917     in ((map var_of_pbl_) o (filter_out is_copy_named)) pbl_ end;
   918 fun vars_of_pbl_' pbl_ = 
   919     let fun var_of_pbl_ (gfr,(dsc,t)) = t:term
   920     in ((map var_of_pbl_)(* o (filter_out is_copy_named)*)) pbl_ end;
   921 
   922 fun overwrite_ppc thy itm ppc =
   923   let 
   924     fun repl ppc' (_,_,_,_,itm_) [] =
   925       error ("overwrite_ppc: " ^ (itm_2str_ (thy2ctxt thy) itm_) ^ 
   926                    " not found")
   927       | repl ppc' itm (p::ppc) =
   928 	if (#1 itm) = (#1 (p:itm)) then ppc' @ [itm] @ ppc
   929 	else repl (ppc' @ [p]) itm ppc
   930   in repl [] itm ppc end;
   931 
   932 (*10.3.00: insert the already compiled itm into model;
   933    ev. filter_out  untouched (in FE: (0,...)) item related to insert-item *)
   934 (* val ppc=pbl;
   935    *)
   936 fun insert_ppc thy itm ppc =
   937     let 
   938 	fun eq_untouched d ((0,_,_,_,itm_):itm) = (d = d_in itm_)
   939 	  | eq_untouched _ _ = false;
   940 	    val ppc' = 
   941 		(
   942 		 (*tracing("### insert_ppc: itm= "^(itm2str_ itm));*)       
   943 		 case seek_ppc (#1 itm) ppc of
   944 		     (* val SOME xxx = seek_ppc (#1 itm) ppc;
   945 		        *)
   946 		     SOME _ => (*itm updated in is_notyet_input WN.11.03*)
   947 		     overwrite_ppc thy itm ppc
   948 		   | NONE => (ppc @ [itm]));
   949     in filter_out (eq_untouched ((d_in o #5) itm)) ppc' end;
   950 
   951 (*from Isabelle/src/Pure/library.ML, _appends_ a new element*)
   952 fun gen_ins' eq (x, xs) = if gen_mem eq (x, xs) then xs else xs @ [x];
   953 
   954 fun eq_dsc ((_,_,_,_,itm_):itm, (_,_,_,_,iitm_):itm) = 
   955     (d_in itm_) = (d_in iitm_);
   956 (*insert_ppc = insert_ppc' for appl_add', input_icalhd 11.03,
   957     handles superfluous items carelessly*)
   958 fun insert_ppc' itm itms = gen_ins' eq_dsc (itm, itms);
   959 (* val eee = op=;
   960  > gen_ins' eee (4,[1,3,5,7]);
   961 val it = [1, 3, 5, 7, 4] : int list*)
   962 
   963 
   964 (*. output the headline to a ppc .*)
   965 fun header p_ pI mI =
   966     case p_ of Pbl => Problem (if pI = e_pblID then [] else pI) 
   967 	     | Met => Method mI
   968 	     | pos => error ("header called with "^ pos_2str pos);
   969 
   970 
   971 fun specify_additem sel (ct,_) (p, Met) c pt = 
   972       let
   973         val (PblObj{meth=met,origin=(oris,(dI',pI',mI'),_),
   974   		    probl=pbl,spec=(dI,pI,mI), ctxt, ...}) = get_obj I pt p;
   975         val thy = if dI = e_domID then assoc_thy dI' else assoc_thy dI;
   976         val cpI = if pI = e_pblID then pI' else pI;
   977         val cmI = if mI = e_metID then mI' else mI;
   978         val {ppc,pre,prls,...} = get_met cmI;
   979       in 
   980         case appl_add ctxt sel oris met ppc ct of
   981           Add itm (*..union old input *) =>
   982   	        let
   983               val met' = insert_ppc thy itm met;
   984   	          val ((p, Met), _, _, pt') = 
   985   	            generate1 thy (case sel of
   986   				                       "#Given" => Add_Given'   (ct, met')
   987   			                       | "#Find"  => Add_Find'    (ct, met')
   988   			                       | "#Relate"=> Add_Relation'(ct, met')) 
   989   			        (Uistate, ctxt) (p, Met) pt
   990   	          val pre' = check_preconds thy prls pre met'
   991   	          val pb = foldl and_ (true, map fst pre')
   992   	          val (p_, nxt) =
   993   	            nxt_spec Met pb oris (dI',pI',mI') (pbl,met') 
   994   	              ((#ppc o get_pbt) cpI,ppc) (dI,pI,mI);
   995   	        in ((p, p_), ((p, p_), Uistate),
   996   	          Form' (PpcKF (0,EdUndef,(length p),Nundef,
   997   			        (Method cmI, itms2itemppc thy met' pre'))), nxt,Safe,pt')
   998             end
   999         | Err msg =>
  1000   	        let
  1001               val pre' = check_preconds thy prls pre met
  1002   	          val pb = foldl and_ (true, map fst pre')
  1003   	          val (p_, nxt) =
  1004   	            nxt_spec Met pb oris (dI',pI',mI') (pbl,met) 
  1005   	              ((#ppc o get_pbt) cpI,(#ppc o get_met) cmI) (dI,pI,mI);
  1006   	        in ((p,p_), ((p,p_),Uistate), Error' (Error_ msg), nxt, Safe,pt) end
  1007       end
  1008 
  1009   | specify_additem sel (ct,_) (pos as (p,_(*Frm, Pbl*))) c pt = 
  1010       let
  1011         val (PblObj{meth=met,origin=(oris,(dI',pI',mI'),_),
  1012 		      probl=pbl,spec=(dI,pI,mI), ctxt, ...}) = get_obj I pt p;
  1013         val thy = if dI = e_domID then assoc_thy dI' else assoc_thy dI;
  1014         val cpI = if pI = e_pblID then pI' else pI;
  1015         val cmI = if mI = e_metID then mI' else mI;
  1016         val {ppc,where_,prls,...} = get_pbt cpI;
  1017       in
  1018         case appl_add ctxt sel oris pbl ppc ct of
  1019           Add itm (*..union old input *) =>
  1020 	          let
  1021 	            val pbl' = insert_ppc thy itm pbl
  1022 	            val ((p, Pbl), _, _, pt') = 
  1023 	              generate1 thy (case sel of
  1024 				                         "#Given" => Add_Given'   (ct, pbl')
  1025 			                         | "#Find"  => Add_Find'    (ct, pbl')
  1026 			                         | "#Relate"=> Add_Relation'(ct, pbl')) 
  1027 			           (Uistate, ctxt) (p,Pbl) pt
  1028 	            val pre = check_preconds thy prls where_ pbl'
  1029 	            val pb = foldl and_ (true, map fst pre)
  1030 	            val (p_, nxt) =
  1031 	              nxt_spec Pbl pb oris (dI',pI',mI') (pbl',met) 
  1032 		              (ppc,(#ppc o get_met) cmI) (dI,pI,mI);
  1033 	            val ppc = if p_= Pbl then pbl' else met;
  1034 	          in ((p,p_), ((p,p_),Uistate),
  1035 	            Form' (PpcKF (0,EdUndef,(length p),Nundef,
  1036 			          (header p_ pI cmI, itms2itemppc thy ppc pre))), nxt,Safe,pt')
  1037             end
  1038         | Err msg =>
  1039 	          let
  1040               val pre = check_preconds thy prls where_ pbl
  1041 	            val pb = foldl and_ (true, map fst pre)
  1042 	            val (p_, nxt) =
  1043 	              nxt_spec Pbl pb oris (dI',pI',mI') (pbl,met) 
  1044 	                (ppc,(#ppc o get_met) cmI) (dI,pI,mI);
  1045 	          in ((p,p_), ((p,p_),Uistate), Error' (Error_ msg), nxt, Safe,pt) end
  1046       end;
  1047 
  1048 fun specify (Init_Proof' (fmz,(dI',pI',mI'))) (_:pos') (_:cid) (_:ptree)= 
  1049     let          (* either """"""""""""""" all empty or complete *)
  1050       val thy = assoc_thy dI';
  1051       val (oris, ctxt) = 
  1052         if dI' = e_domID orelse pI' = e_pblID  (*andalso? WN110511*)
  1053         then ([], e_ctxt)
  1054   	    else pI' |> #ppc o get_pbt |> prep_ori fmz thy
  1055       val (pt,c) = cappend_problem e_ptree [] (e_istate, ctxt) (fmz,(dI',pI',mI'))
  1056   			(oris, (dI',pI',mI'), e_term)
  1057       val pt = update_ctxt pt [] ctxt
  1058       val {ppc, prls, where_, ...} = get_pbt pI'
  1059       val (pbl, pre, pb) = ([], [], false)
  1060     in 
  1061       case mI' of
  1062   	    ["no_met"] => 
  1063   	      (([], Pbl), (([], Pbl), Uistate),
  1064   	        Form' (PpcKF (0, EdUndef, (length []), Nundef,
  1065 			        (Problem [], itms2itemppc (assoc_thy dI') pbl pre))),
  1066   	        Refine_Tacitly pI', Safe, pt)
  1067        | _ => 
  1068   	      (([], Pbl), (([], Pbl), Uistate),
  1069   	        Form' (PpcKF (0, EdUndef, (length []), Nundef,
  1070   			      (Problem [], itms2itemppc (assoc_thy dI') pbl pre))),
  1071   	        Model_Problem, Safe, pt)
  1072   end
  1073 
  1074     (*ONLY for STARTING modeling phase*)
  1075   | specify (Model_Problem' (_,pbl,met)) (pos as (p,p_)) c pt =
  1076       let 
  1077         val (PblObj{origin=(oris,(dI',pI',mI'),_), spec=(dI,_,_), ctxt, ...}) = get_obj I pt p
  1078         val thy' = if dI = e_domID then dI' else dI
  1079         val thy = assoc_thy thy'
  1080         val {ppc,prls,where_,...} = get_pbt pI'
  1081         val pre = check_preconds thy prls where_ pbl
  1082         val pb = foldl and_ (true, map fst pre)
  1083         val ((p,_),_,_,pt) =
  1084           generate1 thy (Model_Problem'([],pbl,met)) (Uistate, ctxt) pos pt
  1085         val (_,nxt) = nxt_spec Pbl pb oris (dI',pI',mI') (pbl,met) 
  1086 		      (ppc,(#ppc o get_met) mI') (dI',pI',mI');
  1087       in ((p, Pbl), ((p, p_), Uistate), 
  1088           Form' (PpcKF (0, EdUndef, length p, Nundef,
  1089 		       (Problem pI', itms2itemppc (assoc_thy dI') pbl pre))),
  1090           nxt, Safe, pt)
  1091       end
  1092 
  1093     (*. called only if no_met is specified .*)     
  1094   | specify (Refine_Tacitly' (pI,pIre,_,_,_)) (pos as (p,_)) c pt =
  1095       let
  1096         val (PblObj{origin=(oris,(dI',pI',mI'),_), meth=met, ctxt, ...}) = get_obj I pt p;
  1097         val {prls,met,ppc,thy,where_,...} = get_pbt pIre
  1098         val (domID, metID) = 
  1099           (string_of_thy thy, if length met = 0 then e_metID else hd met)
  1100         val ((p,_),_,_,pt) = 
  1101 	        generate1 thy (Refine_Tacitly'(pI,pIre,domID,metID,(*pbl*)[])) 
  1102 		        (Uistate, ctxt) pos pt
  1103         val (pbl, pre, pb) = ([], [], false)
  1104       in ((p, Pbl), (pos, Uistate),
  1105         Form' (PpcKF (0,EdUndef,(length p),Nundef,
  1106 		      (Problem pIre, itms2itemppc (assoc_thy dI') pbl pre))),
  1107         Model_Problem, Safe, pt)
  1108       end
  1109 
  1110   | specify (Refine_Problem' (rfd as (pI,_))) pos c pt =
  1111       let
  1112         val ctxt = get_ctxt pt pos
  1113         val (pos,_,_,pt) =
  1114           generate1 (assoc_thy "Isac") (Refine_Problem' rfd) (Uistate, ctxt) pos pt
  1115       in (pos(*p,Pbl*), (pos(*p,Pbl*),Uistate), Problems (RefinedKF rfd), 
  1116 	      Model_Problem, Safe, pt)
  1117       end
  1118     (*WN110515 initialise ctxt again from itms and add preconds*)
  1119   | specify (Specify_Problem' (pI, (ok, (itms, pre)))) (pos as (p,_)) c pt =
  1120       let
  1121         val (PblObj {origin=(oris,(dI',pI',mI'),_), spec=(dI,_,mI), 
  1122 		      meth=met, ctxt, ...}) = get_obj I pt p;
  1123         val thy = assoc_thy dI
  1124         val ((p,Pbl),_,_,pt)= 
  1125 	        generate1 thy (Specify_Problem' (pI, (ok, (itms, pre)))) (Uistate, ctxt) pos pt
  1126         val dI'' = assoc_thy (if dI=e_domID then dI' else dI);
  1127         val mI'' = if mI=e_metID then mI' else mI;
  1128         val (_, nxt) =
  1129           nxt_spec Pbl ok oris (dI',pI',mI') (itms, met) 
  1130 		        ((#ppc o get_pbt) pI,(#ppc o get_met) mI'') (dI,pI,mI);
  1131       in ((p,Pbl), (pos,Uistate),
  1132         Form' (PpcKF (0,EdUndef,(length p),Nundef, (Problem pI, itms2itemppc dI'' itms pre))),
  1133           nxt, Safe, pt)
  1134       end    
  1135     (*WN110515 initialise ctxt again from itms and add preconds*)
  1136   | specify (Specify_Method' (mID,_,_)) (pos as (p,_)) c pt =
  1137       let
  1138         val (PblObj {origin=(oris,(dI',pI',mI'),_), probl=pbl, spec=(dI,pI,mI), 
  1139 		      meth=met, ctxt, ...}) = get_obj I pt p;
  1140         val {ppc,pre,prls,...} = get_met mID
  1141         val thy = assoc_thy dI
  1142         val oris = add_field' thy ppc oris;
  1143         val dI'' = if dI=e_domID then dI' else dI;
  1144         val pI'' = if pI = e_pblID then pI' else pI;
  1145         val met = if met=[] then pbl else met;
  1146         val (ok, (itms, pre')) = match_itms_oris thy met (ppc,pre,prls ) oris;
  1147         val (pos, _, _, pt) = 
  1148 	        generate1 thy (Specify_Method' (mID, oris, itms)) (Uistate, ctxt) pos pt
  1149         val (_,nxt) =
  1150           nxt_spec Met (*ok*)true oris (dI',pI',mI') (pbl, itms) 
  1151 		        ((#ppc o get_pbt) pI'',ppc) (dI'',pI'',mID);
  1152       in (pos, (pos,Uistate),
  1153         Form' (PpcKF (0,EdUndef,(length p),Nundef,
  1154 		      (Method mID, itms2itemppc (assoc_thy dI'') itms pre'))),
  1155            nxt, Safe, pt)
  1156       end    
  1157 
  1158   | specify (Add_Given' ct) p c pt = specify_additem "#Given" ct p c pt
  1159   | specify (Add_Find'  ct) p c pt = specify_additem "#Find"  ct p c pt
  1160   | specify (Add_Relation' ct) p c pt=specify_additem"#Relate"ct p c pt
  1161 
  1162   | specify (Specify_Theory' domID) (pos as (p,p_)) c pt =
  1163       let
  1164         val p_ = case p_ of Met => Met | _ => Pbl
  1165         val thy = assoc_thy domID;
  1166         val (PblObj{origin=(oris,(dI',pI',mI'),_), meth=met,
  1167 		      probl=pbl, spec=(dI,pI,mI), ctxt, ...}) = get_obj I pt p;
  1168         val mppc = case p_ of Met => met | _ => pbl;
  1169         val cpI = if pI = e_pblID then pI' else pI;
  1170         val {prls=per,ppc,where_=pwh,...} = get_pbt cpI
  1171         val cmI = if mI = e_metID then mI' else mI;
  1172         val {prls=mer,ppc=mpc,pre=mwh,...} = get_met cmI
  1173         val pre = 
  1174 	        case p_ of
  1175 	          Met => (check_preconds thy mer mwh met)
  1176 	        | _ => (check_preconds thy per pwh pbl)
  1177         val pb = foldl and_ (true, map fst pre)
  1178       in
  1179         if domID = dI
  1180         then
  1181           let val (p_,nxt) = nxt_spec p_ pb oris (dI',pI',mI') 
  1182 				    (pbl,met) (ppc,mpc) (dI,pI,mI);
  1183 	        in ((p,p_), (pos,Uistate), 
  1184 		        Form'(PpcKF (0,EdUndef,(length p), Nundef,
  1185 			        (header p_ pI cmI, itms2itemppc thy mppc pre))),
  1186 		        nxt,Safe,pt)
  1187           end
  1188         else (*FIXME: check ppc wrt. (new!) domID ..? still parsable?*)
  1189 	        let 
  1190 	          val ((p,p_),_,_,pt) =
  1191               generate1 thy (Specify_Theory' domID) (Uistate, ctxt) (p,p_) pt
  1192 	          val (p_,nxt) =
  1193               nxt_spec p_ pb oris (dI',pI',mI') (pbl,met) (ppc,mpc) (domID,pI,mI);
  1194 	        in ((p,p_), (pos,Uistate), 
  1195 	          Form' (PpcKF (0, EdUndef, (length p),Nundef,
  1196 			        (header p_ pI cmI, itms2itemppc thy mppc pre))),
  1197 	          nxt, Safe,pt)
  1198           end
  1199       end
  1200 
  1201   | specify m' _ _ _ = 
  1202       error ("specify: not impl. for " ^ tac_2str m');
  1203 
  1204 (*FIXME.WN110515 declare_constraints for ct (without dsc) into PblObj{ctxt, ...}
  1205   -- for input from scratch*)
  1206 fun nxt_specif_additem sel ct (ptp as (pt, (p, Pbl))) = 
  1207       let
  1208         val (PblObj{meth=met,origin=(oris,(dI',pI',_),_),
  1209 		      probl=pbl,spec=(dI,pI,_), ctxt, ...}) = get_obj I pt p;
  1210         val thy = if dI = e_domID then assoc_thy dI' else assoc_thy dI;
  1211         val cpI = if pI = e_pblID then pI' else pI;
  1212       in
  1213         case appl_add ctxt sel oris pbl ((#ppc o get_pbt) cpI) ct of
  1214 	        Add itm (*..union old input *) =>
  1215 	          let
  1216 	            (*val _=tracing("###nxt_specif_additem: itm= "^(itm2str_ itm));*)
  1217 	            val pbl' = insert_ppc thy itm pbl
  1218 	            val (tac,tac_) = 
  1219 		            case sel of
  1220 		              "#Given" => (Add_Given    ct, Add_Given'   (ct, pbl'))
  1221 		            | "#Find"  => (Add_Find     ct, Add_Find'    (ct, pbl'))
  1222 		            | "#Relate"=> (Add_Relation ct, Add_Relation'(ct, pbl'))
  1223 	            val ((p,Pbl),c,_,pt') = 
  1224 		            generate1 thy tac_ (Uistate, ctxt) (p,Pbl) pt
  1225 	          in ([(tac,tac_,((p,Pbl),(Uistate, ctxt)))], c, (pt',(p,Pbl))):calcstate' 
  1226             end	       
  1227 	      | Err msg => (*TODO.WN03 pass error-msgs to the frontend..
  1228                        FIXME ..and dont abuse a tactic for that purpose*)
  1229 	          ([(Tac msg, Tac_ (Thy_Info.get_theory "Pure", msg,msg,msg),
  1230 	            (e_pos', (e_istate, e_ctxt)))], [], ptp) 
  1231       end
  1232 
  1233   | nxt_specif_additem sel ct (ptp as (pt,(p,Met))) = 
  1234       let
  1235         val (PblObj{meth=met,origin=(oris,(dI',pI',mI'),_),
  1236 		      probl=pbl,spec=(dI,pI,mI), ctxt, ...}) = get_obj I pt p;
  1237         val thy = if dI = e_domID then assoc_thy dI' else assoc_thy dI;
  1238         val cmI = if mI = e_metID then mI' else mI;
  1239       in 
  1240         case appl_add ctxt sel oris met ((#ppc o get_met) cmI) ct of
  1241           Add itm (*..union old input *) =>
  1242 	          let
  1243 	            val met' = insert_ppc thy itm met;
  1244 	            val (tac,tac_) = 
  1245 	              case sel of
  1246 		              "#Given" => (Add_Given    ct, Add_Given'   (ct, met'))
  1247 		            | "#Find"  => (Add_Find     ct, Add_Find'    (ct, met'))
  1248 		            | "#Relate"=> (Add_Relation ct, Add_Relation'(ct, met'))
  1249 	            val ((p,Met),c,_,pt') = 
  1250 	              generate1 thy tac_ (Uistate, ctxt) (p,Met) pt
  1251 	          in ([(tac,tac_,((p,Met), (Uistate, ctxt)))], c, (pt',(p,Met))) end
  1252         | Err msg => ([(*tacis*)], [], ptp) 
  1253           (*nxt_me collects tacis until not hide; here just no progress*)
  1254       end;
  1255 
  1256 fun ori2Coritm pbt ((i,v,f,d,ts):ori) =
  1257     (i,v,true,f, Cor ((d,ts),(((snd o snd o the o (find_first (eq1 d))) pbt) 
  1258 			      handle _ => error ("ori2Coritm: dsc "^
  1259 						term2str d^
  1260 						"in ori, but not in pbt")
  1261 			      ,ts))):itm;
  1262 fun ori2Coritm (pbt:pat list) ((i,v,f,d,ts):ori) =
  1263     ((i,v,true,f, Cor ((d,ts),((snd o snd o the o 
  1264 			       (find_first (eq1 d))) pbt,ts))):itm)
  1265     handle _ => (*dsc in oris, but not in pbl pat list: keep this dsc*)
  1266     ((i,v,true,f, Cor ((d,ts),(d,ts))):itm);
  1267 
  1268 
  1269 (*filter out oris which have same description in itms*)
  1270 fun filter_outs oris [] = oris
  1271   | filter_outs oris (i::itms) = 
  1272     let val ors = filter_out ((curry op= ((d_in o #5) (i:itm))) o 
  1273 			      (#4:ori -> term)) oris;
  1274     in filter_outs ors itms end;
  1275 
  1276 fun memI a b = member op = a b;
  1277 (*filter oris which are in pbt, too*)
  1278 fun filter_pbt oris pbt =
  1279     let val dscs = map (fst o snd) pbt
  1280     in filter ((memI dscs) o (#4: ori -> term)) oris end;
  1281 
  1282 (*.combine itms from pbl + met and complete them wrt. pbt.*)
  1283 (*FIXXXME.WN031205 complete_metitms doesnt handle incorrect itms !*)
  1284 local infix mem;
  1285 fun x mem [] = false
  1286   | x mem (y :: ys) = x = y orelse x mem ys;
  1287 in 
  1288 fun complete_metitms (oris:ori list) (pits:itm list) (mits:itm list) met = 
  1289 (* val met = (#ppc o get_met) ["DiffApp","max_by_calculus"];
  1290    *)
  1291     let val vat = max_vt pits;
  1292         val itms = pits @ 
  1293 		   (filter ((curry (op mem) vat) o (#2:itm -> int list)) mits);
  1294 	val ors = filter ((curry (op mem) vat) o (#2:ori -> int list)) oris;
  1295         val os = filter_outs ors itms;
  1296     (*WN.12.03?: does _NOT_ add itms from met ?!*)
  1297     in itms @ (map (ori2Coritm met) os) end
  1298 end;
  1299 
  1300 
  1301 
  1302 (*.complete model and guard of a calc-head .*)
  1303 local infix mem;
  1304 fun x mem [] = false
  1305   | x mem (y :: ys) = x = y orelse x mem ys;
  1306 in 
  1307 fun complete_mod_ (oris, mpc, ppc, probl) =
  1308     let	val pits = filter_out ((curry op= false) o (#3: itm -> bool)) probl
  1309 	val vat = if probl = [] then 1 else max_vt probl
  1310 	val pors = filter ((curry (op mem) vat) o (#2:ori -> int list)) oris
  1311 	val pors = filter_outs pors pits (*which are in pbl already*)
  1312         val pors = (filter_pbt pors ppc) (*which are in pbt, too*)
  1313 
  1314 	val pits = pits @ (map (ori2Coritm ppc) pors)
  1315 	val mits = complete_metitms oris pits [] mpc
  1316     in (pits, mits) end
  1317 end;
  1318 
  1319 fun some_spec ((odI, opI, omI):spec) ((dI, pI, mI):spec) =
  1320     (if dI = e_domID then odI else dI,
  1321      if pI = e_pblID then opI else pI,
  1322      if mI = e_metID then omI else mI):spec;
  1323 
  1324 
  1325 (*.find a next applicable tac (for calcstate) and update ptree
  1326  (for ev. finding several more tacs due to hide).*)
  1327 (*FIXXXME: unify ... fun nxt_specif = nxt_spec + applicable_in + specify !!*)
  1328 (*WN.24.10.03        ~~~~~~~~~~~~~~   -> tac     -> tac_      -> -"- as arg*)
  1329 (*WN.24.10.03        fun nxt_solv   = ...................................??*)
  1330 fun nxt_specif (tac as Model_Problem) (pt, pos as (p,p_)) =
  1331     let
  1332       val PblObj {origin = (oris, ospec, _), probl, spec, ctxt, ...} = get_obj I pt p
  1333       val (dI, pI, mI) = some_spec ospec spec
  1334       val thy = assoc_thy dI
  1335       val mpc = (#ppc o get_met) mI (* just for reuse complete_mod_ *)
  1336       val {cas, ppc, ...} = get_pbt pI
  1337       val pbl = init_pbl ppc (* fill in descriptions *)
  1338       (*----------------if you think, this should be done by the Dialog 
  1339        in the java front-end, search there for WN060225-modelProblem----*)
  1340       val (pbl, met) = 
  1341         case cas of NONE => (pbl, [])
  1342   			| _ => complete_mod_ (oris, mpc, ppc, probl)
  1343       (*----------------------------------------------------------------*)
  1344       val tac_ = Model_Problem' (pI, pbl, met)
  1345       val (pos,c,_,pt) = generate1 thy tac_ (Uistate, ctxt) pos pt
  1346     in ([(tac,tac_, (pos, (Uistate, e_ctxt)))], c, (pt,pos)):calcstate' end
  1347 
  1348   | nxt_specif (Add_Given ct) ptp = nxt_specif_additem "#Given" ct ptp
  1349   | nxt_specif (Add_Find  ct) ptp = nxt_specif_additem "#Find"  ct ptp
  1350   | nxt_specif (Add_Relation ct) ptp = nxt_specif_additem"#Relate" ct ptp
  1351 
  1352     (*. called only if no_met is specified .*)     
  1353   | nxt_specif (Refine_Tacitly pI) (ptp as (pt, pos as (p,_))) =
  1354       let 
  1355         val (PblObj {origin = (oris, (dI,_,_),_), ctxt, ...}) = get_obj I pt p
  1356         val opt = refine_ori oris pI
  1357       in 
  1358         case opt of
  1359 	        SOME pI' => 
  1360 	          let 
  1361               val {met,ppc,...} = get_pbt pI'
  1362 	            val pbl = init_pbl ppc
  1363 	            (*val pt = update_pbl pt p pbl ..done by Model_Problem*)
  1364 	            val mI = if length met = 0 then e_metID else hd met
  1365               val thy = assoc_thy dI
  1366 	            val (pos,c,_,pt) = 
  1367 		            generate1 thy (Refine_Tacitly' (pI,pI',dI,mI,(*pbl*)[])) 
  1368 			            (Uistate, ctxt) pos pt
  1369 	          in ([(Refine_Tacitly pI, Refine_Tacitly' (pI,pI',dI,mI,(*pbl*)[]),
  1370 		          (pos, (Uistate, e_ctxt)))], c, (pt,pos)) 
  1371             end
  1372 	      | NONE => ([], [], ptp)
  1373       end
  1374 
  1375   | nxt_specif (Refine_Problem pI) (ptp as (pt, pos as (p,_))) =
  1376       let
  1377         val (PblObj {origin=(_,(dI,_,_),_),spec=(dI',_,_), probl, ctxt, ...}) = get_obj I pt p
  1378 	      val thy = if dI' = e_domID then dI else dI'
  1379       in 
  1380         case refine_pbl (assoc_thy thy) pI probl of
  1381 	        NONE => ([], [], ptp)
  1382 	      | SOME (rfd as (pI',_)) => 
  1383 	          let 
  1384               val (pos,c,_,pt) = generate1 (assoc_thy thy) 
  1385 			          (Refine_Problem' rfd) (Uistate, ctxt) pos pt
  1386 	          in ([(Refine_Problem pI, Refine_Problem' rfd,
  1387 			        (pos, (Uistate, e_ctxt)))], c, (pt,pos))
  1388             end
  1389       end
  1390 
  1391   | nxt_specif (Specify_Problem pI) (pt, pos as (p,_)) =
  1392       let
  1393         val (PblObj {origin=(oris,(dI,_,_),_),spec=(dI',pI',_), probl, ctxt, ...}) = get_obj I pt p;
  1394 	      val thy = assoc_thy (if dI' = e_domID then dI else dI');
  1395         val {ppc,where_,prls,...} = get_pbt pI
  1396 	      val pbl as (_,(itms,_)) = 
  1397 	        if pI'=e_pblID andalso pI=e_pblID
  1398 	        then (false, (init_pbl ppc, []))
  1399 	        else match_itms_oris thy probl (ppc,where_,prls) oris(*FIXXXXXME?*)
  1400 	        (*FIXXXME~~~~~~~~~~~~~~~: take pbl and compare with new pI WN.8.03*)
  1401 	      val ((p,Pbl),c,_,pt) = 
  1402 	        generate1 thy (Specify_Problem' (pI, pbl)) (Uistate, ctxt) pos pt
  1403       in ([(Specify_Problem pI, Specify_Problem' (pI, pbl),
  1404 		    (pos,(Uistate, e_ctxt)))], c, (pt,pos))
  1405       end
  1406 
  1407   (*transfers oris (not required in pbl) to met-model for script-env
  1408     FIXME.WN.8.03: application of several mIDs to SAME model?*)
  1409   | nxt_specif (Specify_Method mID) (ptp as (pt, pos as (p,_))) = 
  1410       let
  1411         val (PblObj {origin=(oris,(dI',pI',mI'),_), probl=pbl, spec=(dI,pI,mI), 
  1412           meth=met, ctxt, ...}) = get_obj I pt p;
  1413         val {ppc,pre,prls,...} = get_met mID
  1414         val thy = assoc_thy dI
  1415         val oris = add_field' thy ppc oris;
  1416         val dI'' = if dI=e_domID then dI' else dI;
  1417         val pI'' = if pI = e_pblID then pI' else pI;
  1418         val met = if met=[] then pbl else met;(*WN0602 what if more itms in met?*)
  1419         val (ok, (itms, pre')) = match_itms_oris thy met (ppc,pre,prls ) oris;
  1420         val (pos,c,_,pt)= 
  1421 	        generate1 thy (Specify_Method' (mID, oris, itms)) (Uistate, ctxt) pos pt
  1422       in ([(Specify_Method mID, Specify_Method' (mID, oris, itms),
  1423 		    (pos,(Uistate, e_ctxt)))], c, (pt,pos)) 
  1424       end    
  1425 
  1426   | nxt_specif (Specify_Theory dI) (pt, pos as (p,Pbl)) =
  1427       let
  1428         val ctxt = get_ctxt pt pos
  1429         val (dI',_,_) = get_obj g_spec pt p
  1430 	      val (pos,c,_,pt) = 
  1431 	        generate1 (assoc_thy "Isac") (Specify_Theory' dI)  (Uistate, ctxt) pos pt
  1432       in  (*FIXXXME: check if pbl can still be parsed*)
  1433 	      ([(Specify_Theory dI, Specify_Theory' dI, (pos,(Uistate, ctxt)))], c,
  1434 	        (pt, pos))
  1435       end
  1436 
  1437   | nxt_specif (Specify_Theory dI) (pt, pos as (p,Met)) =
  1438       let
  1439         val ctxt = get_ctxt pt pos
  1440         val (dI',_,_) = get_obj g_spec pt p
  1441 	      val (pos,c,_,pt) = 
  1442 	        generate1 (assoc_thy "Isac") (Specify_Theory' dI) (Uistate, ctxt) pos pt
  1443       in  (*FIXXXME: check if met can still be parsed*)
  1444 	      ([(Specify_Theory dI, Specify_Theory' dI, (pos,(Uistate, ctxt)))], c,
  1445 	        (pt, pos))
  1446       end
  1447 
  1448   | nxt_specif m' _ = 
  1449     error ("nxt_specif: not impl. for "^tac2str m');
  1450 
  1451 (* get the values from oris; handle the term list w.r.t. penv *)
  1452 local infix mem;
  1453 fun x mem [] = false
  1454   | x mem (y :: ys) = x = y orelse x mem ys;
  1455 in 
  1456 fun vals_of_oris oris =
  1457     ((map (mkval' o (#5:ori -> term list))) o 
  1458      (filter ((curry (op mem) 1) o (#2:ori -> int list)))) oris
  1459 end;
  1460 
  1461 (* create a calc-tree with oris via an cas.refined pbl *)
  1462 fun nxt_specify_init_calc (([], (dI, pI, mI)) : fmz) =
  1463       if pI <> [] 
  1464       then (* from pbl-browser or from CAS cmd with pI=[e_pblID] *)
  1465 	      let 
  1466           val {cas, met, ppc, thy, ...} = get_pbt pI
  1467 	        val dI = if dI = "" then theory2theory' thy else dI
  1468 	        val thy = assoc_thy dI
  1469 	        val mI = if mI = [] then hd met else mI
  1470 	        val hdl = case cas of NONE => pblterm dI pI | SOME t => t
  1471 	        val (pt,_) = cappend_problem e_ptree [] (Uistate, e_ctxt) ([], (dI,pI,mI))
  1472 					  ([], (dI,pI,mI), hdl)
  1473 	        val pt = update_spec pt [] (dI,pI,mI)
  1474 	        val pits = init_pbl' ppc
  1475 	        val pt = update_pbl pt [] pits
  1476 	      in ((pt, ([] ,Pbl)), []) : calcstate end
  1477       else 
  1478         if mI <> [] 
  1479         then (* from met-browser *)
  1480 	        let 
  1481             val {ppc,...} = get_met mI
  1482 	          val dI = if dI = "" then "Isac" else dI
  1483 	          val thy = assoc_thy dI;
  1484 	          val (pt,_) = cappend_problem e_ptree [] (e_istate, e_ctxt) ([], (dI,pI,mI))
  1485 					    ([], (dI,pI,mI), e_term(*FIXME met*));
  1486 	          val pt = update_spec pt [] (dI,pI,mI);
  1487 	          val mits = init_pbl' ppc;
  1488 	          val pt = update_met pt [] mits;
  1489 	        in ((pt, ([], Met)), []) : calcstate end
  1490         else (* new example, pepare for interactive modeling *)
  1491 	        let val (pt,_) = cappend_problem e_ptree [] (e_istate, e_ctxt) ([], e_spec)
  1492 					  ([], e_spec, e_term)
  1493 	        in ((pt, ([], Pbl)), []) : calcstate end
  1494 
  1495   | nxt_specify_init_calc (fmz : fmz_, (dI, pI, mI) : spec) = 
  1496       let           (* both """"""""""""""""""""""""" either empty or complete *)
  1497 	      val thy = assoc_thy dI
  1498 	      val (pI, (pors, pctxt), mI) = 
  1499 	        if mI = ["no_met"] 
  1500 	        then 
  1501             let 
  1502               val (pors, pctxt) = get_pbt pI |> #ppc |> prep_ori fmz thy;
  1503 		          val pI' = refine_ori' pors pI;
  1504 		        in (pI', (pors(*refinement over models with diff.precond only*), pctxt),
  1505 		          (hd o #met o get_pbt) pI') end
  1506 	        else (pI, get_pbt pI |> #ppc |> prep_ori fmz thy, mI)
  1507 	      val {cas, ppc, thy=thy',...} = get_pbt pI (*take dI from _refined_ pbl*)
  1508 	      val dI = theory2theory' (maxthy thy thy')
  1509 	      val hdl = 
  1510           case cas of
  1511 		        NONE => pblterm dI pI
  1512 		      | SOME t => subst_atomic ((vars_of_pbl_' ppc) ~~~ vals_of_oris pors) t;
  1513         val (pt, _) = cappend_problem e_ptree [] (e_istate, pctxt) (fmz, (dI, pI, mI))
  1514 				  (pors, (dI, pI, mI), hdl)
  1515         val pt = update_ctxt pt [] pctxt
  1516       in ((pt, ([], Pbl)), 
  1517         fst3 (nxt_specif Model_Problem (pt, ([], Pbl)))) : calcstate
  1518       end;
  1519 
  1520 
  1521 
  1522 (*18.12.99*)
  1523 fun get_spec_form (m:tac_) ((p,p_):pos') (pt:ptree) = 
  1524 (*  case appl_spec p pt m of           /// 19.1.00
  1525     Notappl e => Error' (Error_ e)
  1526   | Appl => 
  1527 *)    let val (_,_,f,_,_,_) = specify m (p,p_) [] pt
  1528       in f end;
  1529 
  1530 
  1531 (*fun tag_form thy (formal, given) = Thm.global_cterm_of thy
  1532 	      (((head_of o Thm.term_of) given) $ (Thm.term_of formal)); WN100819*)
  1533 fun tag_form thy (formal, given) =
  1534  (let
  1535     val gf = (head_of given) $ formal;
  1536     val _ = Thm.global_cterm_of thy gf
  1537   in gf end)
  1538   handle _ => error ("calchead.tag_form: " ^ term_to_string''' thy given ^
  1539     " .. " ^ term_to_string''' thy formal ^ " ..types do not match");
  1540 (* val formal = (the o (parse thy)) "[R::real]";
  1541 > val given = (the o (parse thy)) "fixed_values (cs::real list)";
  1542 > tag_form thy (formal, given);
  1543 val it = "fixed_values [R]" : cterm
  1544 *)
  1545 
  1546 fun chktyp thy (n, fs, gs) = 
  1547   ((writeln o (term_to_string'''  thy) o (nth n)) fs;
  1548    (writeln o (term_to_string''' thy) o (nth n)) gs;
  1549    tag_form thy (nth n fs, nth n gs));
  1550 fun chktyps thy (fs, gs) = map (tag_form thy) (fs ~~ gs);
  1551 
  1552 (* #####################################################
  1553    find the failing item:
  1554 > val n = 2;
  1555 > val tag__form = chktyp (n,formals,givens);
  1556 > (type_of o Thm.term_of o (nth n)) formals; 
  1557 > (type_of o Thm.term_of o (nth n)) givens;
  1558 > atomty ((Thm.term_of o (nth n)) formals);
  1559 > atomty ((Thm.term_of o (nth n)) givens);
  1560 > atomty (Thm.term_of tag__form);
  1561 > use_thy"isa-98-1-HOL-plus/knowl-base/DiffAppl";
  1562  ##################################################### *)
  1563 
  1564 (* #####################################################
  1565    testdata setup
  1566 val origin = ["sqrt(9+4*x)=sqrt x + sqrt(5+x)","x::rat","(+0)"];
  1567 val formals = map (the o (parse thy)) origin;
  1568 
  1569 val given  = ["equation (lhs=rhs)",
  1570 	     "bound_variable bdv",   (* TODO type *) 
  1571 	     "error_bound apx"];
  1572 val where_ = ["e is_root_equation_in bdv",
  1573 	      "bdv is_var",
  1574 	      "apx is_const_expr"];
  1575 val find   = ["L::rat set"];
  1576 val with_  = ["L = {bdv. || ((%x. lhs) bdv) - ((%x. rhs) bdv) || < apx}"];
  1577 val chkpbl = map (the o (parse thy)) (given @ where_ @ find @ with_);
  1578 val givens = map (the o (parse thy)) given;
  1579 
  1580 val tag__forms = chktyps (formals, givens);
  1581 map ((atomty) o Thm.term_of) tag__forms;
  1582  ##################################################### *)
  1583 
  1584 
  1585 (* check pbltypes, announces one failure a time *)
  1586 (*fun chk_vars ctppc = 
  1587   let val {Given=gi,Where=wh,Find=fi,With=wi,Relate=re} = 
  1588     appc flat (mappc (vars o Thm.term_of) ctppc)
  1589   in if (wh\\gi) <> [] then ("wh\\gi",wh\\gi)
  1590      else if (re\\(gi union fi)) <> [] 
  1591 	    then ("re\\(gi union fi)",re\\(gi union fi))
  1592 	  else ("ok",[]) end;*)
  1593 fun chk_vars ctppc = 
  1594   let val {Given=gi,Where=wh,Find=fi,With=wi,Relate=re} = 
  1595           appc flat (mappc vars ctppc)
  1596       val chked = subtract op = gi wh
  1597   in if chked <> [] then ("wh\\gi", chked)
  1598      else let val chked = subtract op = (union op = gi fi) re
  1599           in if chked  <> []
  1600 	     then ("re\\(gi union fi)", chked)
  1601 	     else ("ok", []) 
  1602           end
  1603   end;
  1604 
  1605 (* check a new pbltype: variables (Free) unbound by given, find*) 
  1606 fun unbound_ppc ctppc =
  1607   let val {Given=gi,Find=fi,Relate=re,...} = 
  1608     appc flat (mappc vars ctppc)
  1609   in distinct (*re\\(gi union fi)*) 
  1610               (subtract op = (union op = gi fi) re) end;
  1611 (*
  1612 > val org = {Given=["[R=(R::real)]"],Where=[],
  1613 	   Find=["[A::real]"],With=[],
  1614 	   Relate=["[A=#2*a*b - a^^^#2, (a//#2)^^^#2 + (b//#2)^^^#2 = R^^^#2]"]
  1615 	   }:string ppc;
  1616 > val ctppc = mappc (the o (parse thy)) org;
  1617 > unbound_ppc ctppc;
  1618 val it = [("a","RealDef.real"),("b","RealDef.real")] : (string * typ) list
  1619 *)
  1620 
  1621 
  1622 (* f, a binary operator, is nested rightassociative *)
  1623 fun foldr1 f xs =
  1624   let
  1625     fun fld f (x::[]) = x
  1626       | fld f (x::x'::[]) = f (x',x)
  1627       | fld f (x::x'::xs) = f (fld f (x'::xs),x);
  1628   in ((fld f) o rev) xs end;
  1629 (*
  1630 > val (SOME ct) = parse thy "[a=b,c=d,e=f]";
  1631 > val ces = map (Thm.global_cterm_of thy) (isalist2list (Thm.term_of ct));
  1632 > val conj = foldr1 HOLogic.mk_conj (isalist2list (Thm.term_of ct));
  1633 > Thm.global_cterm_of thy conj;
  1634 val it = "(a = b & c = d) & e = f" : cterm
  1635 *)
  1636 
  1637 (* f, a binary operator, is nested leftassociative *)
  1638 fun foldl1 f (x::[]) = x
  1639   | foldl1 f (x::x'::[]) = f (x,x')
  1640   | foldl1 f (x::x'::xs) = f (x,foldl1 f (x'::xs));
  1641 (*
  1642 > val (SOME ct) = parse thy "[a=b,c=d,e=f,g=h]";
  1643 > val ces = map (Thm.global_cterm_of thy) (isalist2list (Thm.term_of ct));
  1644 > val conj = foldl1 HOLogic.mk_conj (isalist2list (Thm.term_of ct));
  1645 > Thm.global_cterm_of thy conj;
  1646 val it = "a = b & c = d & e = f & g = h" : cterm
  1647 *)
  1648 
  1649 
  1650 (* called only once, if a Subproblem has been located in the script*)
  1651 fun nxt_model_pbl (Subproblem'((_,pblID,metID),_,_,_,_,_)) ptp =
  1652      (case metID of
  1653 	      ["no_met"] => 
  1654 	        (snd3 o hd o fst3) (nxt_specif (Refine_Tacitly pblID) ptp)
  1655       | _ => (snd3 o hd o fst3) (nxt_specif Model_Problem ptp))
  1656         (*all stored in tac_ itms^^^^^^^^^^*)
  1657   | nxt_model_pbl tac_ _ = 
  1658       error ("nxt_model_pbl: called by tac= " ^ tac_2str tac_);
  1659 
  1660 (*fun eq1 d (_,(d',_)) = (d = d'); ---modspec.sml*)
  1661 fun eq4 v (_,vts,_,_,_) = member op = vts v;
  1662 fun eq5 (_,_,_,_,itm_) (_,_,_,d,_) = d_in itm_ = d;
  1663 
  1664  
  1665 (*.complete _NON_empty calc-head for autocalc (sub-)pbl from oris
  1666   + met from fmz; assumes pos on PblObj, meth = [].*)
  1667 fun complete_mod (pt, pos as (p, p_):pos') =
  1668 (* val (pt, (p, _)) = (pt, p);
  1669    val (pt, (p, _)) = (pt, pos);
  1670    *)
  1671     let val _= if p_ <> Pbl 
  1672 	       then tracing("###complete_mod: only impl.for Pbl, called with "^
  1673 			    pos'2str pos) else ()
  1674 	val (PblObj{origin=(oris, ospec, hdl), probl, spec, ...}) =
  1675 	    get_obj I pt p
  1676 	val (dI,pI,mI) = some_spec ospec spec
  1677 	val mpc = (#ppc o get_met) mI
  1678 	val ppc = (#ppc o get_pbt) pI
  1679 	val (pits, mits) = complete_mod_ (oris, mpc, ppc, probl)
  1680         val pt = update_pblppc pt p pits
  1681 	val pt = update_metppc pt p mits
  1682     in (pt, (p,Met):pos') end
  1683 ;
  1684 (*| complete_mod (pt, pos as (p, Met):pos') =
  1685     error ("###complete_mod: only impl.for Pbl, called with "^
  1686 		 pos'2str pos);*)
  1687 
  1688 (*.complete _EMPTY_ calc-head for autocalc (sub-)pbl from oris(+met from fmz);
  1689    oris and spec (incl. pbl-refinement) given from init_calc or SubProblem .*)
  1690 fun all_modspec (pt, (p,_):pos') =
  1691   let 
  1692     val (PblObj {fmz = (fmz_, _), origin = (pors, spec as (dI,pI,mI), hdl), ...}) = get_obj I pt p;
  1693     val thy = assoc_thy dI;
  1694 	  val {ppc, ...} = get_met mI;
  1695     val (fmz_, vals) = oris2fmz_vals pors;
  1696 	  val ctxt = dI |> Thy_Info.get_theory |> Proof_Context.init_global 
  1697       |> declare_constraints' vals
  1698     val pt = update_pblppc pt p (map (ori2Coritm ppc) pors);
  1699 	  val pt = update_metppc pt p (map (ori2Coritm ppc) pors); (*WN110716 = _pblppc ?!?*)
  1700 	  val pt = update_spec pt p (dI,pI,mI);
  1701     val pt = update_ctxt pt p ctxt
  1702 (*
  1703 	  val mors = prep_ori fmz_ thy ppc |> #1;
  1704     val pt = update_pblppc pt p (map (ori2Coritm ppc) pors);
  1705 	  val pt = update_metppc pt p (map (ori2Coritm ppc) mors);
  1706     (*WN110715: why pors, mors handled so differently?*)
  1707 	  val pt = update_spec pt p (dI,pI,mI);
  1708 *)
  1709   in (pt, (p,Met): pos') end;
  1710 
  1711 (*WN0312: use in nxt_spec, too ? what about variants ???*)
  1712 fun is_complete_mod_ ([]: itm list) = false
  1713   | is_complete_mod_ itms = 
  1714     foldl and_ (true, (map #3 itms));
  1715 
  1716 fun is_complete_mod (pt, pos as (p, Pbl): pos') =
  1717       if (is_pblobj o (get_obj I pt)) p 
  1718       then (is_complete_mod_ o (get_obj g_pbl pt)) p
  1719       else error ("is_complete_mod: called by PrfObj at "^pos'2str pos)
  1720   | is_complete_mod (pt, pos as (p, Met)) = 
  1721       if (is_pblobj o (get_obj I pt)) p 
  1722       then (is_complete_mod_ o (get_obj g_met pt)) p
  1723       else error ("is_complete_mod: called by PrfObj at "^pos'2str pos)
  1724   | is_complete_mod (_, pos) =
  1725       error ("is_complete_mod called by " ^ pos'2str pos ^
  1726 		    " (should be Pbl or Met)");
  1727 
  1728 (*.have (thy, pbl, met) _all_ been specified explicitly ?.*)
  1729 fun is_complete_spec (pt, pos as (p,_): pos') = 
  1730     if (not o is_pblobj o (get_obj I pt)) p 
  1731     then error ("is_complete_spec: called by PrfObj at "^pos'2str pos)
  1732     else let val (dI,pI,mI) = get_obj g_spec pt p
  1733 	 in dI<>e_domID andalso pI<>e_pblID andalso mI<>e_metID end;
  1734 (*.complete empty items in specification from origin (pbl, met ev.refined);
  1735   assumes 'is_complete_mod'.*)
  1736 fun complete_spec (pt, pos as (p,_): pos') = 
  1737     let val PblObj {origin = (_,ospec,_), spec,...} = get_obj I pt p
  1738 	val pt = update_spec pt p (some_spec ospec spec)
  1739     in (pt, pos) end;
  1740 
  1741 fun is_complete_modspec ptp = 
  1742     is_complete_mod ptp andalso is_complete_spec ptp;
  1743 
  1744 
  1745 
  1746 
  1747 fun pt_model (PblObj {meth,spec,origin=(_,spec',hdl),...}) Met =
  1748 (* val ((PblObj {meth,spec,origin=(_,spec',hdl),...}), Met) = (ppobj, p_);
  1749    *)
  1750     let val (_,_,metID) = get_somespec' spec spec'
  1751 	val pre = 
  1752 	    if metID = e_metID then []
  1753 	    else let val {prls,pre=where_,...} = get_met metID
  1754 		     val pre = check_preconds' prls where_ meth 0
  1755 		 in pre end
  1756 	val allcorrect = is_complete_mod_ meth
  1757 			 andalso foldl and_ (true, (map #1 pre))
  1758     in ModSpec (allcorrect, Met, hdl, meth, pre, spec) end
  1759   | pt_model (PblObj {probl,spec,origin=(_,spec',hdl),...}) _(*Frm,Pbl*) =
  1760 (* val ((PblObj {probl,spec,origin=(_,spec',hdl),...}),_) = (ppobj, p_);
  1761    *)
  1762     let val (_,pI,_) = get_somespec' spec spec'
  1763 	val pre =
  1764 	    if pI = e_pblID then []
  1765 	    else let val {prls,where_,cas,...} = get_pbt pI
  1766 		     val pre = check_preconds' prls where_ probl 0
  1767 		 in pre end
  1768 	val allcorrect = is_complete_mod_ probl
  1769 			 andalso foldl and_ (true, (map #1 pre))
  1770     in ModSpec (allcorrect, Pbl, hdl, probl, pre, spec) end;
  1771 
  1772 
  1773 fun pt_form (PrfObj {form,...}) = Form form
  1774   | pt_form (PblObj {probl,spec,origin=(_,spec',_),...}) =
  1775     let val (dI, pI, _) = get_somespec' spec spec'
  1776 	val {cas,...} = get_pbt pI
  1777     in case cas of
  1778 	   NONE => Form (pblterm dI pI)
  1779 	 | SOME t => Form (subst_atomic (mk_env probl) t)
  1780     end;
  1781 (*vvv takes the tac _generating_ the formula=result, asm ok....
  1782 fun pt_result (PrfObj {result=(t,asm), tac,...}) = 
  1783     (Form t, 
  1784      if null asm then NONE else SOME asm, 
  1785      SOME tac)
  1786   | pt_result (PblObj {result=(t,asm), origin = (_,ospec,_), spec,...}) =
  1787     let val (_,_,metID) = some_spec ospec spec
  1788     in (Form t, 
  1789 	if null asm then NONE else SOME asm, 
  1790 	if metID = e_metID then NONE else SOME (Apply_Method metID)) end;
  1791 -------------------------------------------------------------------------*)
  1792 
  1793 
  1794 (*.pt_extract returns
  1795       # the formula at pos
  1796       # the tactic applied to this formula
  1797       # the list of assumptions generated at this formula
  1798 	(by application of another tac to the preceding formula !)
  1799    pos is assumed to come from the frontend, ie. generated by moveDown.*)
  1800 (*cannot be in ctree.sml, because ModSpec has to be calculated*)
  1801 fun pt_extract (pt,([],Res)) = (* WN120512: --returns--> Check_Postcondition WRONGLY
  1802                                   see --- build fun is_exactly_equal*)
  1803     (* ML_TODO 110417 get assumptions from ctxt !? *)
  1804       let val (f, asm) = get_obj g_result pt []
  1805       in (Form f, NONE, asm) end
  1806   | pt_extract (pt,(p,Res)) =
  1807       let
  1808         val (f, asm) = get_obj g_result pt p
  1809         val tac =
  1810           if last_onlev pt p
  1811           then
  1812             if is_pblobj' pt (lev_up p)
  1813             then
  1814               let
  1815                 val (PblObj{spec=(_,pI,_),...}) = get_obj I pt (lev_up p)
  1816               in if pI = e_pblID then NONE else SOME (Check_Postcond pI) end
  1817 		        else SOME End_Trans (*WN0502 TODO for other branches*)
  1818 		      else
  1819 		        let val p' = lev_on p
  1820 		        in
  1821 		          if is_pblobj' pt p'
  1822 		          then
  1823 		            let val (PblObj{origin = (_,(dI,pI,_),_),...}) = get_obj I pt p'
  1824 		            in SOME (Subproblem (dI, pI)) end
  1825 		          else
  1826 		            if f = get_obj g_form pt p'
  1827 		            then SOME (get_obj g_tac pt p') (*because this Frm ~~~is not on worksheet*)
  1828 		            else SOME (Take (term2str (get_obj g_form pt p')))
  1829 		        end
  1830       in (Form f, tac, asm) end
  1831   | pt_extract (pt, pos as (p,p_(*Frm,Pbl*))) =
  1832       let
  1833         val ppobj = get_obj I pt p
  1834         val f = if is_pblobj ppobj then pt_model ppobj p_ else get_obj pt_form pt p
  1835         val tac = g_tac ppobj
  1836       in (f, SOME tac, []) end;
  1837 
  1838 
  1839 (**. get the formula from a ctree-node:
  1840  take form+res from PblObj and 1.PrfObj and (PrfObj after PblObj)
  1841  take res from all other PrfObj's .**)
  1842 (*designed for interSteps, outcommented 04 in favour of calcChangedEvent*)
  1843 fun formres p (Nd (PblObj {origin = (_,_, h), result = (r, _),...}, _)) =
  1844     [("headline", (p, Frm), h), 
  1845      ("stepform", (p, Res), r)]
  1846   | formres p (Nd (PrfObj {form, result = (r, _),...}, _)) = 
  1847     [("stepform", (p, Frm), form), 
  1848      ("stepform", (p, Res), r)];
  1849 
  1850 fun form p (Nd (PrfObj {result = (r, _),...}, _)) = 
  1851     [("stepform", (p, Res), r)]
  1852 
  1853 (*assumes to take whole level, in particular hd -- for use in interSteps*)
  1854 fun get_formress fs p [] = flat fs
  1855   | get_formress fs p (nd::nds) =
  1856     (* start with   'form+res'       and continue with trying 'res' only*)
  1857     get_forms (fs @ [formres p nd]) (lev_on p) nds
  1858 and get_forms fs p [] = flat fs
  1859   | get_forms fs p (nd::nds) =
  1860     if is_pblnd nd
  1861     (* start again with      'form+res' ///ugly repeat with Check_elementwise
  1862     then get_formress (fs @ [formres p nd]) (lev_on p) nds                   *)
  1863     then get_forms    (fs @ [formres p nd]) (lev_on p) nds
  1864     (* continue with trying 'res' only*)
  1865     else get_forms    (fs @ [form    p nd]) (lev_on p) nds;
  1866 
  1867 (**.get an 'interval' 'from' 'to' of formulae from a ptree.**)
  1868 (*WN050219 made robust against _'to' below or after Complete nodes
  1869 	   by handling exn caused by move_dn*)
  1870 (*WN0401 this functionality belongs to ctree.sml, 
  1871 but fetching a calc_head requires calculations defined in modspec.sml
  1872 transfer to ME/me.sml !!!
  1873 WN051224 ^^^ doesnt hold any longer, since only the headline of a calc_head
  1874 is returned !!!!!!!!!!!!!
  1875 *)
  1876 fun eq_pos' (p1,Frm) (p2,Frm) = p1 = p2
  1877   | eq_pos' (p1,Res) (p2,Res) = p1 = p2
  1878   | eq_pos' (p1,Pbl) (p2,p2_) = p1 = p2 andalso (case p2_ of
  1879 						     Pbl => true
  1880 						   | Met => true
  1881 						   | _ => false)
  1882   | eq_pos' (p1,Met) (p2,p2_) = p1 = p2 andalso (case p2_ of
  1883 						     Pbl => true
  1884 						   | Met => true
  1885 						   | _ => false)
  1886   | eq_pos' _ _ = false;
  1887 
  1888 (*.get an 'interval' from the ctree; 'interval' is w.r.t. the 
  1889    total ordering Position#compareTo(Position p) in the java-code
  1890 val get_interval = fn
  1891     : pos' ->     : from is "move_up 1st-element" to return
  1892       pos' -> 	  : to the last element to be returned; from < to
  1893       int -> 	  : level: 0 gets the flattest sub-tree possible
  1894 			   >999 gets the deepest sub-tree possible
  1895       ptree -> 	  : 
  1896       (pos' * 	  : of the formula
  1897        Term.term) : the formula
  1898 	  list
  1899 .*)
  1900 fun get_interval from to level pt =
  1901   let
  1902     fun get_inter c (from:pos') (to:pos') lev pt =
  1903 	    if eq_pos' from to orelse from = ([],Res)
  1904 	    (*orelse ... avoids Exception- PTREE "end of calculation" raised,
  1905 	     if 'to' has values NOT generated by move_dn, see systest/me.sml
  1906              TODO.WN0501: introduce an order on pos' and check "from > to"..
  1907              ...there is an order in Java! 
  1908              WN051224 the hack got worse with returning term instead ptform*)
  1909 	    then
  1910 	      let val (f,_,_) = pt_extract (pt, from)
  1911 	      in
  1912 	        case f of
  1913 	          ModSpec (_,_,headline,_,_,_) => c @ [(from, headline)] 
  1914 	        | Form t => c @ [(from, t)]
  1915 	      end
  1916 	    else 
  1917 	      if lev < lev_of from
  1918 	      then (get_inter c (move_dn [] pt from) to lev pt)
  1919 		      handle (PTREE _(*from move_dn too far*)) => c
  1920 		    else
  1921 		      let
  1922 		        val (f,_,_) = pt_extract (pt, from)
  1923 		        val term = case f of
  1924 		          ModSpec (_,_,headline,_,_,_) => headline
  1925 				    | Form t => t
  1926 		      in (get_inter (c @ [(from, term)]) (move_dn [] pt from) to lev pt)
  1927 		        handle (PTREE _(*from move_dn too far*)) => c @ [(from, term)]
  1928 		      end
  1929   in get_inter [] from to level pt end;
  1930 
  1931 (*for tests*)
  1932 fun posform2str (pos:pos', form) =
  1933     "("^ pos'2str pos ^", "^
  1934     (case form of 
  1935 	 Form f => term2str f
  1936        | ModSpec c => term2str (#3 c(*the headline*)))
  1937     ^")";
  1938 fun posforms2str pfs = (strs2str' o (map (curry op ^ "\n")) o 
  1939 			(map posform2str)) pfs;
  1940 fun posterm2str (pos:pos', t) =
  1941     "("^ pos'2str pos ^", "^term2str t^")";
  1942 fun posterms2str pfs = (strs2str' o (map (curry op ^ "\n")) o 
  1943 			(map posterm2str)) pfs;
  1944 
  1945 
  1946 (*WN050225 omits the last step, if pt is incomplete*)
  1947 fun show_pt pt = 
  1948     tracing (posterms2str (get_interval ([],Frm) ([],Res) 99999 pt));
  1949 
  1950 (*.get a calchead from a PblObj-node in the ctree; 
  1951    preconditions must be calculated.*)
  1952 fun get_ocalhd (pt, pos' as (p,Pbl):pos') = 
  1953     let val PblObj {origin = (oris, ospec, hdf'), spec, probl,...} = 
  1954 	    get_obj I pt p
  1955 	val {prls,where_,...} = get_pbt (#2 (some_spec ospec spec))
  1956 	val pre = check_preconds (assoc_thy"Isac") prls where_ probl
  1957     in (ocalhd_complete probl pre spec, Pbl, hdf', probl, pre, spec):ocalhd end
  1958 | get_ocalhd (pt, pos' as (p,Met):pos') = 
  1959     let val PblObj {fmz = fmz as (fmz_,_), origin = (oris, ospec, hdf'), 
  1960 		    spec, meth, ...} = 
  1961 	    get_obj I pt p
  1962 	val {prls,pre,...} = get_met (#3 (some_spec ospec spec))
  1963 	val pre = check_preconds (assoc_thy"Isac") prls pre meth
  1964     in (ocalhd_complete meth pre spec, Met, hdf', meth, pre, spec):ocalhd end;
  1965 
  1966 (*.at the activeFormula set the Model, the Guard and the Specification 
  1967    to empty and return a CalcHead;
  1968    the 'origin' remains (for reconstructing all that).*)
  1969 fun reset_calchead (pt, pos' as (p,_):pos') = 
  1970     let val PblObj {origin = (_, _, hdf'),...} = get_obj I pt p
  1971 	val pt = update_pbl pt p []
  1972 	val pt = update_met pt p []
  1973 	val pt = update_spec pt p e_spec
  1974     in (pt, (p,Pbl):pos') end;
  1975 
  1976 end
  1977 
  1978 open CalcHead;