src/Tools/isac/Interpret/ptyps.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Thu, 22 Aug 2019 11:26:14 +0200
changeset 59582 23984b62804f
parent 59581 8733ecc08913
permissions -rw-r--r--
lucin: clarify initialisation of ctxt by ContextC.initialise, initialise'

notes:
* this required more type constraints in formalisations
* this required partially replacing thy --> ctxt
* additional extensions of certain tests for future devel.
* additional code polishing makes CS longer than necessary
     1 (* the problems and methods as stored in hierarchies
     2    author Walther Neuper 1998, Mathias Lehnfeld
     3    (c) due to copyright terms
     4 *)
     5 
     6 signature MODEL_SPECIFY =
     7 sig
     8   val get_fun_ids : theory -> (string * typ) list
     9   type field
    10   (* for calchead.sml, if below at left margin *)
    11   val prep_ori : Selem.fmz_ -> theory -> field list -> Model.ori list * Proof.context
    12   val add_id : 'a list -> (int * 'a) list
    13   val add_field' : theory -> field list -> Model.ori list -> Model.ori list
    14   val match_itms_oris : theory -> Model.itm list -> field list * term list * Rule.rls ->
    15     Model.ori list -> bool * (Model.itm list * (bool * term) list)
    16   val refine_ori : Model.ori list -> Celem.pblID -> Celem.pblID option
    17   val refine_ori' : Model.ori list -> Celem.pblID -> Celem.pblID
    18   val refine_pbl : theory -> Celem.pblID -> Model.itm list ->
    19     (Celem.pblID * (Model.itm list * (bool * term) list)) option
    20 
    21   val appc : ('a list -> 'b list) -> 'a Model.ppc -> 'b Model.ppc
    22   val mappc : ('a -> 'b) -> 'a Model.ppc -> 'b Model.ppc
    23   val itms2itemppc : theory -> Model.itm list -> (bool * term) list -> Model.item Model.ppc   (* for generate.sml *)
    24 
    25   val get_pbt : Celem.pblID -> Celem.pbt
    26   val get_met : Celem.metID -> Celem.met                                    (* for generate.sml *)
    27   val get_met' : theory -> Celem.metID -> Celem.met                (* for pbl-met-hierarchy.sml *)
    28   val get_the : Celem.theID -> Celem.thydata                                  (* for inform.sml *)
    29   
    30   type pblRD = string list                                         (* for pbl-met-hierarchy.sml *)
    31   val format_pblIDl : string list list -> string                       (* for thy-hierarchy.sml *)
    32   val scan : string list -> 'a Celem.ptyp list -> string list list     (* for thy-hierarchy.sml *)
    33   val itm_out : theory -> Model.itm_ -> string
    34   val dsc_unknown : term
    35   
    36   val pblID2guh : Celem.pblID -> Celem.guh                                 (* for datatypes.sml *)
    37   val metID2guh : Celem.metID -> Celem.guh                                 (* for datatypes.sml *)
    38   val kestoreID2guh : Celem.ketype -> Celem.kestoreID -> Celem.guh         (* for datatypes.sml *)
    39   val guh2kestoreID : Celem.guh -> string list                             (* for interface.sml *)
    40   (* for Knowledge/, if below at left margin *)
    41   val prep_pbt : theory -> Celem.guh -> string list -> Celem.pblID ->
    42     string list * (string * string list) list * Rule.rls * string option * Celem.metID list ->
    43       Celem.pbt * Celem.pblID
    44   val prep_met : theory -> string -> string list -> Celem.pblID ->
    45      string list * (string * string list) list *
    46        {calc: 'a, crls: Rule.rls, errpats: Rule.errpat list, nrls: Rule.rls, prls: Rule.rls,
    47          rew_ord': Rule.rew_ord', rls': Rule.rls, srls: Rule.rls} * thm ->
    48      Celem.met * Celem.metID
    49 (* ---- for tests only: shifted from below to remove the Warning "unused" at fun.def. --------- *)
    50   val show_ptyps : unit -> unit
    51   val show_mets : unit -> unit
    52   datatype match' = Matches' of Model.item Model.ppc | NoMatch' of Model.item Model.ppc
    53   val match_pbl : Selem.fmz_ -> Celem.pbt -> match'
    54   val refine : Selem.fmz_ -> Celem.pblID -> Stool.match list
    55   val e_errpat : Rule.errpat
    56   val show_pblguhs : unit -> unit
    57   val sort_pblguhs : unit -> unit
    58 (*/-------------------------------------------------------- ! aktivate for Test_Isac BEGIN ---\* )
    59   val add_field : theory -> Celem.pat list -> term * 'b -> string * term * 'b
    60   val add_variants : ('a * ''b * 'c) list -> (int * ('a * ''b * 'c)) list
    61   val coll_variants: ('a * ''b) list -> ('a list * ''b) list
    62   val flattup: 'a * ('b * ('c * 'd * 'e)) -> 'a * 'b * 'c * 'd * 'e
    63   val max: int list -> int
    64   val replace_0: int -> int list -> int list
    65 ( *\--- ! aktivate for Test_Isac END ----------------------------------------------------------/*)
    66 
    67 (*----- unused code, kept as hints to design ideas ---------------------------------------------*)
    68   val e_fillpat : string * term * string
    69   val coll_vats : ''a list * ('b * ''a list * 'c * 'd * 'e) -> ''a list
    70   val filter_vat : Model.ori list -> int -> Model.ori list
    71   val show_metguhs : unit -> unit
    72   val sort_metguhs : unit -> unit
    73 end
    74 
    75 structure Specify(**) : MODEL_SPECIFY(**) =
    76 struct
    77 open Model
    78 
    79 fun fun_id_of ({scr = prog, ...} : Celem.met) = 
    80   case prog of
    81     Rule.EmptyScr => NONE
    82   | Rule.Prog t => 
    83     (case t of
    84       Const ("HOL.eq", _) $ Free ("t", _) $ Free ("t", _) (*=@{thm refl}*) => NONE
    85     | _ => SOME (LTool.get_fun_id t))
    86   | Rule.Rfuns _ => NONE
    87 
    88 (* get all data from a Ptyp tree *)
    89 fun get_data ptyp =
    90 let
    91   fun scan [] = []
    92     | scan ((Celem.Ptyp ((_, data, []))) :: []) = data
    93     | scan ((Celem.Ptyp ((_, data, pl))) :: []) = data @ scan pl
    94     | scan ((Celem.Ptyp ((_, data, []))) :: ps) = data @ scan ps
    95     | scan ((Celem.Ptyp ((_, data, pl))) :: ps) = data @ scan pl @ scan ps
    96 in scan ptyp end
    97 
    98 fun get_fun_ids thy =
    99   let 
   100     val mets = get_data (KEStore_Elems.get_mets thy)
   101     (* all mets of the respective theory PLUS of all ancestor theories*)
   102     val fun_ids = mets |> map fun_id_of |> filter is_some |> map the
   103   in 
   104     filter (fn (str, _) => Celem.thyID_of_derivation_name str = Context.theory_name thy) fun_ids 
   105   end
   106 
   107 type field = string * (term * term)
   108 val dsc_unknown = (Thm.term_of o the o (TermC.parseold @{theory})) "unknown::'a => unknow";
   109 
   110 fun itm_2item (_: theory) (Model.Cor ((d, ts), _)) = Model.Correct (Rule.term2str (Model.comp_dts (d, ts)))
   111   | itm_2item _ (Model.Syn c) = Model.SyntaxE c
   112   | itm_2item _ (Model.Typ c) = Model.TypeE c
   113   | itm_2item _ (Model.Inc ((d, ts), _)) = Model.Incompl (Rule.term2str (Model.comp_dts (d, ts)))
   114   | itm_2item _ (Model.Sup (d, ts)) = Model.Superfl (Rule.term2str (Model.comp_dts (d, ts)))
   115   | itm_2item _ (Model.Mis (d, pid)) = Model.Missing (Rule.term2str d ^ " " ^ Rule.term2str pid)
   116   | itm_2item _ _ = error "itm_2item: uncovered definition"
   117 
   118 fun mappc f {Given = gi, Where = wh, Find = fi, With = wi, Relate = re} = 
   119   {Given= map f gi, Where = map f wh, Find = map f fi, With = map f wi, Relate = map f re}
   120 fun appc f {Given = gi, Where = wh, Find = fi, With = wi, Relate = re} = 
   121   {Given = f gi, Where = f wh, Find = f fi, With = f wi, Relate = f re}
   122 
   123 fun add_sel_ppc (_: theory) sel {Given = gi, Where = wh, Find = fi, With = wi, Relate = re} x =
   124   case sel of
   125     "#Given" => {Given = gi @ [x], Where = wh, Find = fi, With = wi,Relate = re}
   126   | "#Where" => {Given = gi, Where = wh @ [x], Find = fi, With = wi, Relate = re}
   127   | "#Find"  => {Given = gi, Where = wh, Find = fi @ [x], With = wi, Relate = re}
   128   | "#Relate"=> {Given = gi, Where = wh, Find = fi, With = wi, Relate = re @ [x]}
   129   | "#undef" => {Given = gi @ [x], Where = wh, Find = fi, With = wi, Relate = re} (*ori2itmSup*)
   130   | _  => error ("add_sel_ppc tried to select by \"" ^ sel ^ "\"")
   131 fun add_where {Given = gi, Where = _, Find = fi, With = wi, Relate = re} wh =
   132   {Given = gi, Where = wh, Find= fi ,With = wi, Relate = re}
   133 
   134 (* split a term into description and (id | structured variable) for pbt, met.ppc *)
   135 fun split_did t =
   136   let
   137     val (hd, arg) = case strip_comb t of
   138       (hd, [arg]) => (hd, arg)
   139     | _ => error ("split_did: doesn't match (hd,[arg]) for t = " ^ Rule.term2str t)
   140   in (hd, arg) end
   141 
   142 (*create output-string for itm_*)
   143 fun itm_out _ (Model.Cor ((d, ts), _)) = Rule.term2str (Model.comp_dts (d, ts))
   144   | itm_out _ (Model.Syn c) = c
   145   | itm_out _ (Model.Typ c) = c
   146   | itm_out _ (Model.Inc ((d, ts), _)) = Rule.term2str (Model.comp_dts (d, ts))
   147   | itm_out _ (Model.Sup (d, ts)) = Rule.term2str (Model.comp_dts (d, ts))
   148   | itm_out _ (Model.Mis (d, pid)) = Rule.term2str d ^ " " ^ Rule.term2str pid
   149   | itm_out _ _ = error "itm_out: uncovered definition"
   150 
   151 fun boolterm2item (true, term) = Model.Correct (Rule.term2str term)
   152   | boolterm2item (false, term) = Model.False (Rule.term2str term);
   153 
   154 fun itms2itemppc thy itms pre =
   155   let
   156     fun coll ppc [] = ppc
   157       | coll ppc ((_,_,_,field,itm_)::itms) =
   158         coll (add_sel_ppc thy field ppc (itm_2item thy itm_)) itms;
   159     val gfr = coll Model.empty_ppc itms;
   160   in add_where gfr (map boolterm2item pre) end;
   161 
   162 (* compare d and dsc in pbt and transfer field to pre-ori *)
   163 fun add_field (_: theory) pbt (d,ts) = 
   164   let fun eq d pt = (d = (fst o snd) pt);
   165   in case filter (eq d) pbt of
   166        [(fi, (_, _))] => (fi, d, ts)
   167      | [] => ("#undef", d, ts)   (*may come with met.ppc*)
   168      | _ => error ("add_field: " ^ Rule.term2str d ^ " more than once in pbt")
   169   end;
   170 
   171 (* take over field from met.ppc at 'Specify_Method' into ori,
   172    i.e. also removes "#undef" fields                        *)
   173 fun add_field' (_: theory) mpc ori =
   174   let
   175     fun eq d pt = (d = (fst o snd) pt);
   176     fun repl mpc (i, v, _, d, ts) = 
   177       case filter (eq d) mpc of
   178 	      [(fi, (_, _))] => [(i, v, fi, d, ts)]
   179       | [] => [] (*25.2.02: dsc in ori, but not in met -> superfluous*)    
   180       | _ => error ("add_field': " ^ Rule.term2str d ^ " more than once in met");
   181   in flat ((map (repl mpc)) ori) end;
   182 
   183 (* mark an element with the position within a plateau;
   184    a plateau with length 1 is marked with 0         *)
   185 fun mark _ [] = error "mark []"
   186   | mark eq xs =
   187     let
   188       fun mar xx _ [x] n = xx @ [(if n = 1 then 0 else n, x)]
   189         | mar _ _ [] _ = error "mark []"
   190         | mar xx eq (x:: x' :: xs) n = 
   191         if eq(x, x') then mar (xx @ [(n, x)]) eq (x' :: xs) (n + 1)
   192         else mar (xx @ [(if n = 1 then 0 else n, x)]) eq (x' :: xs) 1;
   193     in mar [] eq xs 1 end;
   194 
   195 (* assumes equal descriptions to be in adjacent 'plateaus',
   196    items at a certain position within the plateaus form a variant;
   197    length = 1 ... marked with 0: covers all variants            *)
   198 fun add_variants fdts = 
   199   let 
   200     fun eq (a, b) = curry op= (snd3 a) (snd3 b);
   201   in mark eq fdts end;
   202 
   203 fun max [] = error "max of []"
   204   | max (y :: ys) =
   205   let fun mx x [] = x
   206 	| mx x (y :: ys) = if x < y then mx y ys else mx x ys;
   207 in mx y ys end;
   208 
   209 fun coll_variants (((v,x) :: vxs)) =
   210     let
   211       fun col xs (vs, x) [] = xs @ [(vs, x)]
   212         | col xs (vs, x) ((v', x') :: vxs') = 
   213         if x = x' then col xs (vs @ [v'], x') vxs'
   214         else col (xs @ [(vs, x)]) ([v'], x') vxs';
   215     in col [] ([v], x) vxs end
   216   | coll_variants _ = error "coll_variants: called with []";
   217 
   218 fun replace_0 vm [0] = intsto vm
   219   | replace_0 _ vs = vs;
   220 
   221 fun add_id [] = error "add_id []"
   222   | add_id xs =
   223     let
   224       fun add _ [] = []
   225         | add n (x :: xs) = (n, x) :: add (n + 1) xs;
   226     in add 1 xs end;
   227 
   228 fun flattup (a, (b, (c, d, e))) = (a, b, c, d, e);
   229 
   230 fun prep_ori [] _ _ = ([], ContextC.e_ctxt)
   231   | prep_ori fmz thy pbt =
   232     let
   233       val ctxt = ContextC.initialise' thy fmz;
   234       val ori = map (add_field thy pbt o Model.split_dts o TermC.parseNEW' ctxt) fmz
   235         |> add_variants;
   236       val maxv = map fst ori |> max;
   237       val maxv = if maxv = 0 then 1 else maxv;
   238       val oris = coll_variants ori
   239         |> map (replace_0 maxv |> apfst)
   240         |> add_id
   241         |> map flattup;
   242     in (oris, ctxt) end;
   243 
   244 val e_errpat = ("e_errpatID", [TermC.parse_patt @{theory} "?a = ?b"], [@{thm refl}]): Rule.errpat
   245 val e_fillpat = ("e_fillpatID", TermC.parse_patt @{theory} "?a = _", "e_errpatID")
   246 
   247 (** breadth-first search on hierarchy of problem-types **)
   248 
   249 (* pblID are reverted _on calling_ the retrieve-funs *)
   250 type pblRD =   (*e.g. ["equations","univariate","normalise"] for internal retrieval *)
   251   Celem.pblID; (*e.g. ["normalise","univariate","equations"] presented to student   *)
   252 
   253 (* apply a fun to a ptyps node *)
   254 fun app_ptyp x = Celem.app_py (get_ptyps ()) x;
   255 
   256 (* TODO: generalize search for subthy *)
   257 fun get_pbt (pblID: Celem.pblID) = Celem.get_py (get_ptyps ()) pblID (rev pblID)
   258 
   259 (* TODO: throws exn 'get_pbt not found: ' ... confusing !! take 'ketype' as an argument *)
   260 fun get_met metID = Celem.get_py (get_mets ()) metID metID;
   261 fun get_met' thy metID = Celem.get_py (KEStore_Elems.get_mets thy) metID metID;
   262 fun get_the theID = Celem.get_py (get_thes ()) theID theID;
   263 
   264 (* lookup a guh in hierarchy of problems / methods depending on fst 4 chars in guh *)
   265 fun guh2kestoreID guh =
   266   case (implode o (take_fromto 1 4) o Symbol.explode) guh of
   267 	  "pbl_" =>
   268 	    let
   269 	      fun node ids gu (Celem.Ptyp (id, [{guh, ...}], ns)) =
   270 	        if gu = guh then SOME (ids @ [id]) else nodes (ids @ [id]) gu ns
   271 	        | node _ _ _ = error "guh2kestoreID node: uncovered fun def."
   272 	      and nodes _ _ [] = NONE 
   273 	        | nodes ids gu (n :: ns) = case node ids gu n of
   274 	            SOME id => SOME id
   275 			      | NONE =>  nodes ids gu ns
   276 	    in case nodes [] guh (get_ptyps ()) of
   277 	      SOME id => rev id
   278 	    | NONE => error ("guh2kestoreID: \"" ^ guh ^ "\" " ^ "not found in ptyps")
   279       end
   280   | "met_" =>
   281 	    let
   282 	      fun node ids gu (Celem.Ptyp (id, [{guh, ...}], ns)) =
   283 	        if gu = guh then SOME (ids @ [id]) else nodes (ids @ [id]) gu ns
   284 	        | node _ _ _ = error "guh2kestoreID node: uncovered fun def."
   285 	      and nodes _ _ [] = NONE 
   286 	        | nodes ids gu (n :: ns) = case node ids gu n of
   287 	            SOME id => SOME id
   288 				    | NONE =>  nodes ids gu ns
   289 	    in case nodes [] guh (get_mets ()) of
   290 	      SOME id => id
   291 	    | NONE => error ("guh2kestoreID: \"" ^ guh ^ "\" " ^ "not found in mets")
   292       end
   293   | _ => error ("guh2kestoreID called with \"" ^ guh ^ "\":");
   294 
   295 (* prepare problem-types before storing in pbltypes; 
   296    dont forget to "check_guh_unique" before ins   *)
   297 fun prep_pbt thy guh maa init (pblID, dsc_dats, ev, ca, metIDs) =
   298     let
   299       fun eq f (f', _) = f = f';
   300       val gi = filter (eq "#Given") dsc_dats;
   301       val gi = (case gi of
   302 		    [] => []
   303 		  | ((_, gi') :: []) => (map (split_did o Thm.term_of o the o (TermC.parse thy)) gi'
   304 		      handle _ => error ("prep_pbt: syntax error in '#Given' of " ^ strs2str pblID))
   305 		  | _ => error ("prep_pbt: more than one '#Given' in " ^ strs2str pblID));
   306 		  val gi = map (pair "#Given") gi;
   307 
   308 		  val fi = filter (eq "#Find") dsc_dats;
   309 		  val fi = (case fi of
   310 		    [] => []
   311 		  | ((_, fi') :: []) => (map (split_did o Thm.term_of o the o (TermC.parse thy)) fi'
   312 		      handle _ => error ("prep_pbt: syntax error in '#Find' of " ^ strs2str pblID))
   313 		  | _ => error ("prep_pbt: more than one '#Find' in " ^ strs2str pblID));
   314 		  val fi = map (pair "#Find") fi;
   315 
   316 		  val re = filter (eq "#Relate") dsc_dats;
   317 		  val re = (case re of
   318 		    [] => []
   319 		  | ((_, re') :: []) => (map (split_did o Thm.term_of o the o (TermC.parse thy)) re'
   320 		      handle _ => error ("prep_pbt: syntax error in '#Relate' of " ^ strs2str pblID))
   321 		  | _ => error ("prep_pbt: more than one '#Relate' in " ^ strs2str pblID));
   322 		  val re = map (pair "#Relate") re;
   323 
   324 		  val wh = filter (eq "#Where") dsc_dats;
   325 		  val wh = (case wh of
   326 		    [] => []
   327 		  | ((_, wh') :: []) => (map (TermC.parse_patt thy) wh'
   328 		      handle _ => error ("prep_pbt: syntax error in '#Where' of " ^ strs2str pblID))
   329 		  | _ => error ("prep_pbt: more than one '#Where' in " ^ strs2str pblID));
   330     in
   331       ({guh = guh, mathauthors = maa, init = init, thy = thy,
   332         cas= case ca of
   333           NONE => NONE
   334 			  | SOME s => SOME ((Thm.term_of o the o (TermC.parse thy)) s),
   335 			  prls = ev, where_ = wh, ppc = gi @ fi @ re, met = metIDs}, pblID)
   336     end;
   337 
   338 (* prepare met for storage analogous to pbt *)
   339 fun prep_met thy guh maa init
   340 	    (metID, ppc,
   341         {rew_ord' = ro, rls' = rls, srls = srls, prls = prls, calc = _(*scr_isa_fns*), crls = cr,
   342           errpats = ep, nrls = nr}, scr) =
   343     let
   344       fun eq f (f', _) = f = f';
   345       val gi = filter (eq "#Given") ppc;
   346       val gi = (case gi of
   347 		    [] => (writeln ("prep_met: in " ^ guh ^ " #Given is empty ?!?"); [])
   348 		  | ((_, gi') :: []) => (map (split_did o Thm.term_of o the o (TermC.parse thy)) gi'
   349 		      handle _ => error ("prep_pbt: syntax error in '#Given' of " ^ strs2str metID))
   350 		  | _ => error ("prep_pbt: more than one '#Given' in " ^ strs2str metID));
   351 		  val gi = map (pair "#Given") gi;
   352 
   353 		  val fi = filter (eq "#Find") ppc;
   354 		  val fi = (case fi of
   355 		    [] => (writeln ("prep_met: in " ^ guh ^ " #Find is empty ?!?"); [])
   356 		  | ((_, fi') :: []) =>  (map (split_did o Thm.term_of o the o (TermC.parse thy)) fi'
   357 		      handle _ => error ("prep_pbt: syntax error in '#Find' of " ^ strs2str metID))
   358 		  | _ => error ("prep_pbt: more than one '#Find' in " ^ strs2str metID));
   359 		  val fi = map (pair "#Find") fi;
   360 
   361 		  val re = filter (eq "#Relate") ppc;
   362 		  val re = (case re of
   363 		    [] => (writeln ("prep_met: in " ^ guh ^ " #Relate is empty ?!?"); [])
   364 		  | ((_,re') :: []) => (map (split_did o Thm.term_of o the o (TermC.parse thy)) re'
   365 		      handle _ => error ("prep_pbt: syntax error in '#Relate' of " ^ strs2str metID))
   366 		  | _ => error ("prep_pbt: more than one '#Relate' in " ^ strs2str metID));
   367 		  val re = map (pair "#Relate") re;
   368 
   369 		  val wh = filter (eq "#Where") ppc;
   370 		  val wh = (case wh of
   371 		    [] => (writeln ("prep_met: in " ^ guh ^ " #Where is empty ?!?"); [])
   372 		  | ((_, wh') :: []) => (map (TermC.parse_patt thy) wh'
   373 		      handle _ => error ("prep_pbt: syntax error in '#Where' of " ^ strs2str metID))
   374 		  | _ => error ("prep_pbt: more than one '#Where' in " ^ strs2str metID));
   375 		  val sc = LTool.prep_program scr
   376 		  val calc = if Thm.eq_thm (scr, @{thm refl}) then [] else LTool.get_calcs thy sc
   377     in
   378        ({guh = guh, mathauthors = maa, init = init, ppc = gi @ fi @ re, pre = wh, rew_ord' = ro,
   379          erls = rls, srls = srls, prls = prls, calc = calc,
   380          crls = cr, errpats = ep, nrls = nr, scr = Rule.Prog sc}, metID)
   381     end;
   382 
   383 
   384 (** get pblIDs of all entries in mat3D **)
   385 
   386 fun format_pblID strl = enclose " [" "]" (commas_quote strl);
   387 fun format_pblIDl strll = enclose "[\n" "\n]\n" (space_implode ",\n" (map format_pblID strll));
   388 
   389 fun scan _  [] = [] (* no base case, for empty doms only *)
   390   | scan id ((Celem.Ptyp ((i, _, []))) :: []) = [id @ [i]]
   391   | scan id ((Celem.Ptyp ((i, _, pl))) :: []) = scan (id @ [i]) pl
   392   | scan id ((Celem.Ptyp ((i, _, []))) :: ps) = [id @ [i]] @ (scan id ps)
   393   | scan id ((Celem.Ptyp ((i, _, pl))) :: ps) = (scan (id @ [i]) pl) @ (scan id ps);
   394 
   395 fun show_ptyps () = (writeln o format_pblIDl o (scan [])) (get_ptyps ()); (* for tests *)
   396 fun show_mets () = (writeln o format_pblIDl o (scan [])) (get_mets ()); (* for tests *)
   397 
   398 (* transform oris *)
   399 
   400 fun coll_vats (vats, (_, vs, _, _, _)) = union op = vats vs;
   401 fun filter_vat oris i = filter ((member_swap op = i) o (#2 : Model.ori -> int list)) oris;
   402 
   403 (** check a problem (ie. itm list) for matching a problemtype **)
   404 
   405 fun eq1 d (_, (d', _)) = (d = d');
   406 fun ori2itmSup (i, v, _, d, ts) = (i, v, true, "#Given", Model.Sup (d, ts));
   407 (*see + add_sel_ppc                                    ~~~~~~~*)
   408 
   409 fun field_eq f (_, _, f', _, _) = f = f';
   410 
   411 (* check an item (with arbitrary itm_ from previous matchings) 
   412    for matching a problemtype; returns true only for itms found in pbt *)
   413 fun chk_ (_: theory) pbt (i, vats, b, f, Model.Cor ((d, vs), _)) =
   414     (case find_first (eq1 d) pbt of 
   415       SOME (_, (_, id)) => (i, vats, b, f, Model.Cor ((d, vs), (id, Model.pbl_ids' d vs)))
   416     | NONE =>  (i, vats, false, f, Model.Sup (d, vs)))
   417   | chk_ _ pbt (i, vats, b, f, Model.Inc ((d, vs), _)) =
   418     (case find_first (eq1 d) pbt of 
   419       SOME (_, (_, id)) => (i, vats, b, f, Model.Cor ((d, vs), (id, Model.pbl_ids' d vs)))
   420     | NONE => (i, vats, false, f, Model.Sup (d, vs)))
   421   | chk_ _ _ (itm as (_, _, _, _, Model.Syn _)) = itm
   422   | chk_ _ _ (itm as (_, _, _, _, Model.Typ _)) = itm
   423   | chk_ _ pbt (i, vats, b, f, Model.Sup (d, vs)) =
   424     (case find_first (eq1 d) pbt of 
   425       SOME (_, (_, id)) => (i, vats, b, f, Model.Cor ((d,vs), (id, Model.pbl_ids' d vs)))
   426     | NONE => (i, vats, false, f, Model.Sup (d, vs)))
   427   | chk_ _ pbt (i, vats, _, f, Model.Mis (d, vs)) =
   428     (case find_first (eq1 d) pbt of
   429       SOME (_, _) => error "chk_: ((i,vats,b,f,Model.Cor ((d,vs),(id, Model.pbl_ids' d vs))):itm)"
   430     | NONE => (i, vats, false, f, Model.Sup (d, [vs])))
   431   | chk_ _ _ _ = error "chk_: uncovered fun def.";
   432 
   433 fun eq2 (_, (d, _)) (_, _, _, _, itm_) = d = Model.d_in itm_;
   434 fun eq2' (_, (d, _)) (_, _, _, d', _) = d = d';
   435 fun eq0 (0, _, _, _, _) = true
   436   | eq0 _ = false;
   437 fun max_i i [] = i
   438   | max_i i ((id, _, _, _, _) :: is) = if i > id then max_i i is else max_i id is;
   439 fun max_id [] = 0
   440   | max_id ((id, _, _, _, _) :: is) = max_i id is;
   441 fun add_idvat itms _ _ [] = itms
   442   | add_idvat itms i mvat ((_, _, b, f, itm_) :: its) =
   443     add_idvat (itms @ [(i,[],b,f,itm_)]) (i + 1) mvat its;
   444                        (* ^^ mvat ...meaningless with pbl-identifier *)
   445 
   446 (* find elements of pbt not contained in itms;
   447    if such one is untouched, return this one, otherwise create new itm *)
   448 fun chk_m itms untouched (p as (f, (d, id))) = 
   449   case find_first (eq2 p) itms of
   450 	  SOME _ => []
   451   | NONE =>
   452       (case find_first (eq2 p) untouched of
   453         SOME itm => [itm]
   454       | NONE => [(0, [], false, f, Model.Mis (d, id))]);
   455 
   456 fun chk_mis mvat itms untouched pbt = 
   457     let val mis = (flat o (map (chk_m itms untouched))) pbt; 
   458         val mid = max_id itms;
   459     in add_idvat [] (mid + 1) mvat mis end;
   460 
   461 (* check a problem (ie. itm list) for matching a problemtype, 
   462    takes the Model.max_vt for concluding completeness (could be another!) *)
   463 fun match_itms thy itms (pbt, pre, prls) = 
   464   let
   465     fun okv mvat (_, vats, b, _, _) = member op = vats mvat andalso b;
   466     val itms' = map (chk_ thy pbt) itms; (* all found are #3 true *)
   467     val mvat = Model.max_vt itms';
   468 	  val itms'' = filter (okv mvat) itms';
   469 	  val untouched = filter eq0 itms; (* i.e. dsc only (from init)*)
   470 	  val mis = chk_mis mvat itms'' untouched pbt;
   471 	  val pre' = Stool.check_preconds' prls pre itms'' mvat
   472 	  val pb = foldl and_ (true, map fst pre')
   473   in (length mis = 0 andalso pb, (itms'@ mis, pre')) end;
   474 
   475 (* check a problem (or method) pbl (ie. itm list) for matching a problemtype pbt,
   476    for missing items get data from formalization (ie. ori list); 
   477    takes the Model.max_vt for concluding completeness (could be another!)
   478  
   479   (0) determine the most frequent variant mv in pbl
   480    ALL pbt. (1) dsc(pbt) notmem dsc(pbls) =>
   481             (2) filter (dsc(pbt) = dsc(oris)) oris; -> news;
   482             (3) newitms = filter (mv mem vat(news)) news 
   483    (4) pbt @ newitms                                           *)
   484 fun match_itms_oris (_: theory) pbl (pbt, pre, prls) oris =
   485   let 
   486  (*0*)val mv = Model.max_vt pbl;
   487 
   488       fun eqdsc_pbt_itm ((_,(d,_))) (_, _, _, _, itm_) = d = Model.d_in itm_;
   489       fun notmem pbl pbt1 = case find_first (eqdsc_pbt_itm pbt1) pbl of
   490 				SOME _ => false | NONE => true;
   491  (*1*)val mis = (filter (notmem pbl)) pbt;
   492 
   493       fun eqdsc_ori (_,(d,_)) (_, _, _, d', _) = d = d';
   494       fun ori2itmMis (f, (d, pid)) (i, v, _, _, _) = (i, v, false, f, Model.Mis (d, pid));
   495  (*2*)fun oris2itms oris mis1 = ((map (ori2itmMis mis1)) o (filter (eqdsc_ori mis1))) oris;
   496       val news = (flat o (map (oris2itms oris))) mis;
   497  (*3*)fun mem_vat (_, vats, _, _, _) = member op = vats mv;
   498       val newitms = filter mem_vat news;
   499  (*4*)val itms' = pbl @ newitms;
   500       val pre' = Stool.check_preconds' prls pre itms' mv;
   501       val pb = foldl and_ (true, map fst pre');
   502   in (length mis = 0 andalso pb, (itms', pre')) end;
   503 
   504 
   505 (** check a problem (ie. itm list) for matching a problemtype **)
   506 
   507 (* check an ori for matching a problemtype by description; 
   508    returns true only for itms found in pbt              *)
   509 fun chk1_ (_: theory) pbt (i, vats, f, d, vs) =
   510   case find_first (eq1 d) pbt of 
   511 	  SOME (_, (_, id)) => [(i, vats, true, f, Model.Cor ((d, vs), (id, Model.pbl_ids' d vs)))]
   512   | NONE => [];
   513 
   514 (* elem 'p' of pbt contained in itms ? *)
   515 fun chk1_m itms p = case find_first (eq2 p) itms of SOME _ => true | NONE => false;
   516 fun chk1_m' oris (p as (f, (d, t))) = 
   517   case find_first (eq2' p) oris of
   518 	  SOME _ => []
   519   | NONE => [(f, Model.Mis (d, t))];
   520 fun pair0vatsfalse (f, itm_) = (0, [], false, f, itm_);
   521 
   522 fun chk1_mis _(*mvat*) itms ppc = foldl and_ (true, map (chk1_m itms) ppc);
   523 fun chk1_mis' oris ppc = map pair0vatsfalse ((flat o (map (chk1_m' oris))) ppc);
   524   
   525 (* check a problem (ie. ori list) for matching a problemtype, 
   526    takes the Model.max_vt for concluding completeness (FIXME could be another!) *)
   527 fun match_oris thy prls oris (pbt,pre) = 
   528   let
   529     val itms = (flat o (map (chk1_ thy pbt))) oris;
   530     val mvat = Model.max_vt itms;
   531     val complete = chk1_mis mvat itms pbt;
   532     val pre' = Stool.check_preconds' prls pre itms mvat;
   533     val pb = foldl and_ (true, map fst pre');
   534   in if complete andalso pb then true else false end;
   535 
   536 (* check a problem (ie. ori list) for matching a problemtype, 
   537    returns items for output to math-experts *)
   538 fun match_oris' thy oris (ppc,pre,prls) =
   539   let
   540     val itms = (flat o (map (chk1_ thy ppc))) oris;
   541     val sups = ((map ori2itmSup) o (filter (field_eq "#undef"))) oris;
   542     val mvat = Model.max_vt itms;
   543     val miss = chk1_mis' oris ppc;
   544     val pre' = Stool.check_preconds' prls pre itms mvat;
   545     val pb = foldl and_ (true, map fst pre');
   546   in (miss = [] andalso pb, (itms @ miss @ sups, pre')) end;
   547 
   548 datatype match' = (* for the user *)
   549   Matches' of Model.item Model.ppc
   550 | NoMatch' of Model.item Model.ppc;
   551 
   552 (* match a formalization with a problem type, for tests *)
   553 fun match_pbl fmz {thy = thy, where_ = pre, ppc, prls = er, ...} =
   554   let
   555     val oris = prep_ori fmz thy ppc |> #1;
   556     val (bool, (itms, pre')) = match_oris' thy oris (ppc, pre, er);
   557   in
   558     if bool
   559     then Matches' (itms2itemppc thy itms pre')
   560     else NoMatch' (itms2itemppc thy itms pre')
   561   end;
   562 
   563 (* refine a problem; construct pblRD while scanning *)
   564 fun refin (pblRD: pblRD) ori (Celem.Ptyp (pI, [py], [])) =
   565     if match_oris (#thy py) (#prls py) ori (#ppc py, #where_ py) 
   566     then SOME ((pblRD @ [pI]): pblRD)
   567     else NONE
   568   | refin pblRD ori (Celem.Ptyp (pI, [py], pys)) =
   569     if match_oris (#thy py) (#prls py) ori (#ppc py, #where_ py) 
   570     then (case refins (pblRD @ [pI]) ori pys of
   571 	      SOME pblRD' => SOME pblRD'
   572 	    | NONE => SOME (pblRD @ [pI]))
   573     else NONE
   574   | refin _ _ _ = error "refin: uncovered fun def."
   575 and refins _ _ [] = NONE
   576   | refins pblRD ori ((p as Celem.Ptyp _) :: pts) =
   577     (case refin pblRD ori p of
   578       SOME pblRD' => SOME pblRD'
   579     | NONE => refins pblRD ori pts);
   580 
   581 (* refine a problem; version providing output for math-experts *)
   582 fun refin' (pblRD: pblRD) fmz pbls (Celem.Ptyp (pI, [py], [])) =
   583     let
   584       val _ = (tracing o ((curry op ^) "*** pass ") o strs2str) (pblRD @ [pI])
   585       val {thy, ppc, where_, prls, ...} = py 
   586       val oris = prep_ori fmz thy ppc |> #1;
   587       (* WN020803: itms!: oris might _not_ be complete here *)
   588       val (b, (itms, pre')) = match_oris' thy oris (ppc, where_, prls)
   589     in
   590       if b
   591       then pbls @ [Stool.Matches (rev (pblRD @ [pI]), itms2itemppc thy itms pre')]
   592       else pbls @ [Stool.NoMatch (rev (pblRD @ [pI]), itms2itemppc thy itms pre')]
   593     end
   594   | refin' pblRD fmz pbls (Celem.Ptyp (pI, [py], pys)) =
   595     let
   596       val _ = (tracing o ((curry op ^)"*** pass ") o strs2str) (pblRD @ [pI])
   597       val {thy, ppc, where_, prls, ...} = py 
   598       val oris = prep_ori fmz thy ppc |> #1;
   599       (* WN020803: itms!: oris might _not_ be complete here *)
   600       val(b, (itms, pre')) = match_oris' thy oris (ppc,where_,prls);
   601     in
   602       if b 
   603       then
   604         let val pbl = Stool.Matches (rev (pblRD @ [pI]), itms2itemppc thy itms pre')
   605 	      in refins' (pblRD @ [pI]) fmz (pbls @ [pbl]) pys end
   606       else (pbls @ [Stool.NoMatch (rev (pblRD @ [pI]), itms2itemppc thy itms pre')])
   607     end
   608   | refin' _ _ _ _ = error "refin': uncovered fun def."
   609 and refins' _ _ pbls [] = pbls
   610   | refins' pblRD fmz pbls ((p as Celem.Ptyp _) :: pts) =
   611     let
   612       val pbls' = refin' pblRD fmz pbls p
   613     in
   614       case last_elem pbls' of
   615         Stool.Matches _ => pbls'
   616       | Stool.NoMatch _ => refins' pblRD fmz pbls' pts
   617     end;
   618 
   619 (* refine a problem; version for tactic Refine_Problem *)
   620 fun refin'' _ (pblRD: pblRD) itms pbls (Celem.Ptyp (pI, [py], [])) =
   621     let
   622 	    val {thy, ppc, where_, prls, ...} = py 
   623 	    val (b, (itms', pre')) = match_itms thy itms (ppc, where_, prls);
   624     in
   625       if b
   626       then pbls @ [Stool.Match_ (rev (pblRD @ [pI]), (itms', pre'))]
   627       else pbls @ [Stool.NoMatch_] 
   628     end
   629   | refin'' _ pblRD itms pbls (Celem.Ptyp (pI, [py], pys)) =
   630     let
   631       val {thy, ppc, where_, prls, ...} = py 
   632       val (b, (itms', pre')) = match_itms thy itms (ppc, where_, prls);
   633     in if b 
   634        then let val pbl = Stool.Match_ (rev (pblRD @ [pI]), (itms', pre'))
   635 	    in refins'' thy (pblRD @ [pI]) itms (pbls @ [pbl]) pys end
   636        else (pbls @ [Stool.NoMatch_])
   637     end
   638   | refin'' _ _ _ _ _ = error "refin': uncovered fun def."
   639 and refins'' _ _ _ pbls [] = pbls
   640   | refins'' thy pblRD itms pbls ((p as Celem.Ptyp _) :: pts) =
   641     let
   642       val pbls' = refin'' thy pblRD itms pbls p
   643     in case last_elem pbls' of
   644       Stool.Match_ _ => pbls'
   645     | Stool.NoMatch_ => refins'' thy pblRD itms pbls' pts
   646   end;
   647 
   648 (* for tactic Refine_Tacitly
   649    oris are already created wrt. some pbt; pbt contains thy for parsing *)
   650 fun refine_ori oris pblID =
   651   let
   652     val opt = app_ptyp (refin ((rev o tl) pblID) oris) pblID (rev pblID);
   653     in case opt of 
   654       SOME pblRD =>
   655         let val pblID': Celem.pblID = rev pblRD
   656 			  in if pblID' = pblID then NONE else SOME pblID' end
   657 	  | NONE => NONE
   658 	end;
   659 fun refine_ori' oris pI = (the (refine_ori oris pI)) handle _ => pI;
   660 
   661 (* for tactic Refine_Problem
   662    10.03: returnvalue -> (pIrefined, itm list) would be sufficient *)
   663 fun refine_pbl thy pblID itms =
   664   case Stool.refined_ (app_ptyp (refin'' thy ((rev o tl) pblID) itms []) pblID (rev pblID)) of
   665 	  NONE => NONE
   666   | SOME (Stool.Match_ (rfd as (pI', _))) => if pblID = pI' then NONE else SOME rfd
   667   | _ => error "refine_pbl: uncovered case refined_";
   668 
   669 
   670 (* for math-experts and test;
   671    FIXME.WN021019: needs thy for parsing fmz *)
   672 fun refine fmz pblID =
   673   app_ptyp (refin' ((rev o tl) pblID) fmz []) pblID (rev pblID);
   674 
   675 (* make a guh from a reference to an element in the kestore;
   676    EXCEPT theory hierarchy ... compare 'fun keref2xml'    *)
   677 fun pblID2guh pblID = (((#guh o get_pbt) pblID)
   678   handle _ => error ("pblID2guh: not for \"" ^ strs2str' pblID ^ "\""));
   679 fun metID2guh metID = (((#guh o get_met) metID)
   680   handle _ => error ("metID2guh: no 'Met_' for \"" ^ strs2str' metID ^ "\""));
   681 fun kestoreID2guh Celem.Pbl_ kestoreID = pblID2guh kestoreID
   682   | kestoreID2guh Celem.Met_ kestoreID = metID2guh kestoreID
   683   | kestoreID2guh ketype kestoreID =
   684     error ("kestoreID2guh: \"" ^ Celem.ketype2str ketype ^ "\" not for \"" ^ strs2str' kestoreID ^ "\"");
   685 
   686 fun show_pblguhs () = (* for tests *)
   687   (tracing o strs2str o (map Celem.linefeed)) (Celem.coll_pblguhs (get_ptyps ()))
   688 fun sort_pblguhs () = (* for tests *)
   689   (tracing o strs2str o (map Celem.linefeed)) (((sort string_ord) o Celem.coll_pblguhs) (get_ptyps ()))
   690 
   691 fun show_metguhs () = (* for tests *)
   692   (tracing o strs2str o (map Celem.linefeed)) (Celem.coll_metguhs (get_mets ()))
   693 fun sort_metguhs () = (* for tests *)
   694   (tracing o strs2str o (map Celem.linefeed)) (((sort string_ord) o Celem.coll_metguhs) (get_mets ()))
   695 
   696 end