src/Tools/isac/BaseDefinitions/Know_Store.thy
author wneuper <Walther.Neuper@jku.at>
Wed, 11 Jan 2023 09:23:18 +0100
changeset 60649 b2ff1902420f
parent 60639 b8bb7d8800e8
child 60655 f73460617c3d
permissions -rw-r--r--
eliminate use of Thy_Info 12: prep.arg. ctxt in TermC, UnparseC
     1 (*  Title:      src/Tools/isac/Know_Store.thy
     2     Author:     Mathias Lehnfeld
     3 
     4 Store of Theory_Data of all knowledge required by the Lucas-Interpreter.
     5 
     6 Types of elements are defined in "xxxxx-def.sml". These files have companion files "xxxxx.sml" 
     7 with all further code, located at appropriate positions in the file structure.
     8 (The separation of "xxxxx-def.sml" from "xxxxx.sml" should be overcome by
     9 appropriate use of polymorphic high order functions.)
    10 
    11 Notable are Problem.T and MethodC.T; these are trees with a structure different from
    12 Isabelle's theories dependencies.
    13 *)
    14 
    15 theory Know_Store
    16   imports Complex_Main
    17   keywords "rule_set_knowledge" "calculation" :: thy_decl
    18 begin
    19 
    20 setup \<open>
    21   ML_Antiquotation.conditional \<^binding>\<open>isac_test\<close>
    22     (fn _ => Options.default_bool \<^system_option>\<open>isac_test\<close>)
    23 \<close>
    24 
    25 ML_file libraryC.sml
    26 ML_file theoryC.sml
    27 ML_file unparseC.sml
    28 ML_file "rule-def.sml"
    29 ML_file "thmC-def.sml"
    30 ML_file "eval-def.sml"
    31 ML_file "rewrite-order.sml"
    32 ML_file rule.sml
    33 ML_file "references-def.sml"
    34 ML_file "cas-def.sml"
    35 ML_file "model-pattern.sml"
    36 ML_file "error-pattern-def.sml"
    37 ML_file "rule-set.sml"
    38 
    39 ML_file "store.sml"
    40 ML_file "check-unique.sml"
    41 ML_file "problem-def.sml"
    42 ML_file "method-def.sml"
    43 ML_file "formalise.sml"
    44 ML_file "example.sml"
    45 
    46 ML \<open>
    47 \<close> ML \<open>
    48 \<close> ML \<open>
    49 \<close>
    50 section \<open>Knowledge elements for problems and methods\<close>
    51 text \<open>
    52   \<open>ML_structure Problem\<close>, \<open>ML_structure MethodC\<close> and \<open>Example\<close>s are held by "Know_Store".
    53 
    54   The structure of \<open>ML_structure Problem\<close> and \<open>ML_structure MethodC\<close> is independent from 
    55   theories' dependency graph. Thus the respective elements are stored as \<open>TermC.as_string\<close>
    56   and parsed on the fly within the current @{ML_structure Context},
    57   while being loaded into \<open>ML_structure Calc\<close>.
    58 
    59   Note: From the children of eb89f586b0b2 onwards the old functions (\<open>term TermC.typ_a2real\<close> etc)
    60   are adapted for "adapt_to_type on the fly" until further clarification.
    61   Why \<open>ML_structure Problem\<close> and \<open>ML_structure MethodC\<close> are not parsed on the fly
    62   within the current \<open>ML_structure Context\<close> see \<open>ML_structure Refine\<close>
    63 \<open>\<close>
    64   Most elements of \<open>ML_structure Problem\<close> and \<open>ML_structure MethodC\<close> are implemented in 
    65   \<open>directory Knowledge/\<close> but some of them are implemented in \<open>directory ProgLang/\<close>already; 
    66   thus \<open>theory Know_Store\<close> got this location in the directory structure.
    67 
    68   \<open>term Know_Store.get_*\<close> retrieves all * of the respective theory PLUS of all ancestor theories.
    69 \<close> ML \<open>
    70 signature KNOW_STORE =
    71 sig
    72   val get_rew_ords: theory -> Rewrite_Ord.T list
    73   val add_rew_ords: Rewrite_Ord.T list -> theory -> theory
    74   val get_rlss: theory -> (Rule_Set.id * (ThyC.id * Rule_Set.T)) list
    75   val add_rlss: (Rule_Set.id * (ThyC.id * Rule_Set.T)) list -> theory -> theory
    76   val get_calcs: theory -> (Eval_Def.prog_id * (Eval_Def.const_id * Eval_Def.ml_fun)) list
    77   val add_calcs: (Eval_Def.prog_id * (Eval_Def.const_id * Eval_Def.ml_fun)) list -> theory -> theory
    78   val get_cass: theory -> CAS_Def.T list
    79   val add_cass: CAS_Def.T list -> theory -> theory
    80   val get_pbls: theory -> Probl_Def.store
    81   val add_pbls: Proof.context -> (Probl_Def.T * References_Def.id) list -> theory -> theory
    82   val get_mets: theory -> Meth_Def.store
    83   val add_mets: Proof.context -> (Meth_Def.T * References_Def.id) list -> theory -> theory
    84   val get_expls: theory -> Example.store
    85   val add_expls: (Example.T * Store.key) list -> theory -> theory
    86   val get_ref_last_thy: unit -> theory
    87   val set_ref_last_thy: theory -> unit
    88   val get_via_last_thy: ThyC.id -> theory (*only used for * (Sub-)problem retrieving respective thy
    89                                                           * problem refinement                    
    90                                                           * (test-)code to be deleted            *)
    91 end;
    92 
    93 structure Know_Store(**): KNOW_STORE(**) =
    94 struct
    95   structure Data = Theory_Data (
    96     type T = Rewrite_Ord.T list;
    97     val empty = [];
    98     val merge = merge Rewrite_Ord.equal;
    99     );  
   100   fun get_rew_ords thy = Data.get thy
   101   fun add_rew_ords rlss = Data.map (curry (Library.merge Rewrite_Ord.equal) rlss)
   102 
   103   structure Data = Theory_Data (
   104     type T = (Rule_Set.id * (ThyC.id * Rule_Set.T)) list;
   105                             (* ^^^^^ would allow same Rls_Set.id for different thys, NOT impl. *)
   106     val empty = [];
   107     val merge = Rule_Set.to_kestore;
   108     );  
   109   fun get_rlss thy = Data.get thy
   110   fun add_rlss rlss = Data.map (curry (Library.merge Rule_Set.equal) rlss)
   111 
   112   structure Data = Theory_Data (
   113     type T = (Eval_Def.prog_id * (Eval_Def.const_id * Eval_Def.ml_fun)) list;
   114     val empty = [];
   115     val merge = merge Eval_Def.equal;
   116     );                                                              
   117   fun get_calcs thy = Data.get thy
   118   fun add_calcs calcs = Data.map (curry (Library.merge Eval_Def.equal) calcs)
   119 
   120   structure Data = Theory_Data (
   121     type T = (term * (References_Def.T * CAS_Def.generate_fn)) list;
   122     val empty = [];
   123     val merge = merge CAS_Def.equal;
   124     );                                                              
   125   fun get_cass thy = Data.get thy
   126   fun add_cass cas = Data.map (curry (Library.merge CAS_Def.equal) cas)
   127 
   128   structure Data = Theory_Data (
   129     type T = Probl_Def.store;
   130     val empty = [Probl_Def.empty_store];
   131     val merge = Store.merge;
   132     );
   133   fun get_pbls thy = Data.get thy;
   134   fun add_pbls ctxt pbts thy =
   135     let
   136       fun add_pbt (pbt as {guh,...}, pblID) =
   137         (* the pblID has the leaf-element as first; better readability achieved *)
   138         (if (Config.get ctxt check_unique) then Probl_Def.check_unique guh (Data.get thy) else ();
   139           rev pblID |> Store.insert pblID pbt);
   140     in Data.map (fold add_pbt pbts) thy end;
   141 
   142   structure Data = Theory_Data (
   143     type T = Meth_Def.store;
   144     val empty = [Meth_Def.empty_store];
   145     val merge = Store.merge;
   146     );
   147   val get_mets = Data.get;
   148   fun add_mets ctxt mets thy =
   149     let
   150       fun add_met (met as {guh,...}, metID) =
   151         (if (Config.get ctxt check_unique) then Meth_Def.check_unique guh (Data.get thy) else ();
   152           Store.insert metID met metID);
   153     in Data.map (fold add_met mets) thy end;
   154 
   155   structure Data = Theory_Data (
   156     type T = Example.store;
   157     val empty = [Example.empty_store];
   158     val merge = Store.merge;
   159     );
   160   val get_expls = Data.get;
   161   fun add_expls expls thy =
   162     let
   163       fun add_expl (expl, expl_id) = Store.insert expl_id expl expl_id;
   164     in Data.map (fold add_expl expls) thy end;
   165 
   166 
   167   val last_thy = Synchronized.var "finally_knowledge_complete" @{theory};
   168   fun set_ref_last_thy thy = Synchronized.change last_thy (fn _ => thy); (* never RE-set ! *)
   169   fun get_ref_last_thy () = Synchronized.value last_thy;
   170 
   171 fun get_via_last_thy thy_id =
   172   let
   173     val last_thy = get_ref_last_thy ()
   174     val known_thys = Theory.nodes_of last_thy
   175   in 
   176     (find_first (fn thy => Context.theory_name thy = thy_id) known_thys
   177       |> the)
   178     handle Option.Option => raise ERROR ("get_via_last_thy fails with " ^ quote thy_id)
   179   end
   180 
   181 (**)end(*struct*);
   182 \<close>
   183 
   184 
   185 subsection \<open>Isar command syntax\<close>
   186 
   187 ML \<open>
   188 local
   189 
   190 val parse_rule = Parse.name -- Parse.!!! (\<^keyword>\<open>=\<close> |-- Parse.ML_source);
   191 
   192 val ml = ML_Lex.read;
   193 
   194 fun ml_rule thy (name, source) =
   195   ml "(" @ ml (ML_Syntax.print_string name) @ ml ", " @
   196   ml "(" @ ml (ML_Syntax.print_string (Context.theory_name thy)) @ ml ", " @
   197   ML_Lex.read_source source @ ml "))";
   198 
   199 fun ml_rules thy args =
   200   ml "Theory.setup (Know_Store.add_rlss [" @
   201     flat (separate (ml ",") (map (ml_rule thy) args)) @ ml "])";
   202 
   203 val _ =
   204   Outer_Syntax.command \<^command_keyword>\<open>rule_set_knowledge\<close> "register ISAC rule set to Knowledge Store"
   205     (Parse.and_list1 parse_rule >> (fn args => Toplevel.theory (fn thy =>
   206       thy |> Context.theory_map
   207         (ML_Context.expression (Position.thread_data ()) (ml_rules thy args)))));
   208 
   209 val calc_name =
   210   Parse.name -- (\<^keyword>\<open>(\<close> |-- Parse.const --| \<^keyword>\<open>)\<close>) ||
   211   Scan.ahead Parse.name -- Parse.const;
   212 
   213 val _ =
   214   Outer_Syntax.command \<^command_keyword>\<open>calculation\<close>
   215     "prepare ISAC calculation and register it to Knowledge Store"
   216     (calc_name -- (\<^keyword>\<open>=\<close> |-- Parse.!!! Parse.ML_source) >> (fn ((calcID, const), source) =>
   217       Toplevel.theory (fn thy =>
   218         let
   219           val ctxt = Proof_Context.init_global thy;
   220           val Const (c, _) = Proof_Context.read_const {proper = true, strict = true} ctxt const;
   221           val set_data =
   222             ML_Context.expression (Input.pos_of source)
   223               (ml "Theory.setup (Eval_Def.ml_fun_to_store (" @ ML_Lex.read_source source @ ml "))")
   224             |> Context.theory_map;
   225           val eval = Eval_Def.ml_fun_from_store (set_data thy);
   226         in Know_Store.add_calcs [(calcID, (c, eval))] thy end)))
   227 
   228 in end;
   229 \<close>
   230 
   231 
   232 section \<open>Re-use existing access functions for knowledge elements\<close>
   233 text \<open>
   234   The independence of problems' and methods' structure from theory dependency structure
   235   enforces the access functions to use "Isac_Knowledge",
   236   the final theory which comprises all knowledge defined.
   237 \<close>
   238 ML \<open>
   239 val get_ref_last_thy = Know_Store.get_ref_last_thy;
   240 
   241 (*val get_rew_ord: Proof.context -> string -> Rewrite_Ord.function*)
   242 fun get_rew_ord ctxt (id: Rewrite_Ord.id) = 
   243   case AList.lookup (op =) (Know_Store.get_rew_ords (Proof_Context.theory_of ctxt)) id of
   244     SOME function => function: Rewrite_Ord.function
   245   | NONE => raise ERROR ("rewrite-order \"" ^ id ^ "\" missing in theory \"" ^ 
   246     (ctxt |> Proof_Context.theory_of |> Context.theory_name) ^ "\" (and ancestors)" ^
   247     "\nTODO exception hierarchy needs to be established.")
   248 
   249 (*val get_rls: Proof.context -> Rule_Set.id -> Rule_Def.rule_set*)
   250 fun get_rls ctxt (id : Rule_Set.id) =
   251   case AList.lookup (op =) (Know_Store.get_rlss (Proof_Context.theory_of ctxt)) id of
   252     SOME (_, rls) => rls
   253   | NONE => raise ERROR ("rls \"" ^ id ^ "\" missing in theory \"" ^ 
   254     (ctxt |> Proof_Context.theory_of |> Context.theory_name) ^ "\" (and ancestors)" ^
   255     "\nTODO exception hierarchy needs to be established.")
   256 
   257 (*val get_calc: Proof.context -> Eval_Def.prog_id -> 
   258   Eval_Def.prog_id * (Eval_Def.const_id * Eval_Def.ml_fun)*)
   259 fun get_calc ctxt (id: Eval_Def.prog_id) = 
   260   case AList.lookup (op =) (Know_Store.get_calcs (Proof_Context.theory_of ctxt)) id of
   261     SOME const_id__ml_fun => (id, const_id__ml_fun)
   262   | NONE => raise ERROR ("ml-calculation \"" ^ id ^ "\" missing in theory \"" ^ 
   263     (ctxt |> Proof_Context.theory_of |> Context.theory_name) ^ "\" (and ancestors)" ^
   264     "\nTODO exception hierarchy needs to be established.")
   265 
   266 (*val get_calc_prog_id: Proof.context -> Eval_Def.const_id -> Eval_Def.prog_id*)
   267 fun get_calc_prog_id ctxt (const_id: Eval_Def.const_id) =
   268   let
   269     fun assoc ([], prog_id) =
   270         raise ERROR ("ml-calculation \"" ^ prog_id ^ "\" missing in theory \"" ^ 
   271           (ctxt |> Proof_Context.theory_of |> Context.theory_name) ^ "\" (and ancestors)." ^
   272           "\nThus " ^ quote const_id  ^ " cannot be retrieved." ^
   273           "\nTODO exception hierarchy needs to be established.")
   274       | assoc ((prog_id, (const_id, _)) :: pairs, key) =
   275           if key = const_id then prog_id else assoc (pairs, key);
   276   in assoc (ctxt |> Proof_Context.theory_of |> Know_Store.get_calcs, const_id) end;
   277 
   278 (*val get_cas: Proof.context -> term -> References_Def.T * CAS_Def.generate_fn*)
   279 fun get_cas ctxt tm = 
   280   case AList.lookup (op =) (Know_Store.get_cass (Proof_Context.theory_of ctxt)) tm of
   281     SOME refs__gen_fun => refs__gen_fun: References_Def.T * CAS_Def.generate_fn
   282   | NONE => raise ERROR ("CAS_Cmd \"" ^ 
   283     UnparseC.term_in_thy (get_ref_last_thy ()) tm ^ "\" missing in theory \"" ^ 
   284     (ctxt |> Proof_Context.theory_of |> Context.theory_name) ^ "\" (and ancestors)" ^
   285     "\nTODO exception hierarchy needs to be established.")
   286 
   287 (*for starting an Exmaple by CAS_Cmd*)
   288 (*val get_cas_global: term -> References_Def.T * CAS_Def.generate_fn*)
   289 fun get_cas_global tm =
   290   let
   291     val thy = get_ref_last_thy ()
   292   in
   293     case AList.lookup (op =) (Know_Store.get_cass thy) tm of
   294       NONE => (writeln ("CAS_Cmd \"" ^ 
   295           UnparseC.term_in_thy thy tm ^ "\" missing in theory \"" ^ 
   296           (thy |> Context.theory_name) ^ "\" (and ancestors).");
   297         NONE)
   298     | SOME refs__gen_fun => SOME refs__gen_fun
   299   end
   300 
   301 
   302 fun get_pbls () = get_ref_last_thy () |> Know_Store.get_pbls;
   303 fun get_mets () = get_ref_last_thy () |> Know_Store.get_mets;
   304 fun get_expls () = get_ref_last_thy () |> Know_Store.get_expls;
   305 \<close>
   306 
   307 rule_set_knowledge
   308   empty = \<open>Rule_Set.empty\<close> and
   309   e_rrls = \<open>Rule_Set.e_rrls\<close>
   310 
   311 section \<open>Functions for checking Know_Store\<close>
   312 ML \<open>
   313 fun short_string_of_rls Rule_Set.Empty = "Erls"
   314   | short_string_of_rls (Rule_Def.Repeat {calc, rules, ...}) =
   315     "Rls {#calc = " ^ string_of_int (length calc) ^
   316     ", #rules = " ^ string_of_int (length rules) ^ ", ..."
   317   | short_string_of_rls (Rule_Set.Sequence {calc, rules, ...}) =
   318     "Seq {#calc = " ^ string_of_int (length calc) ^
   319     ", #rules = " ^ string_of_int (length rules) ^ ", ..."
   320   | short_string_of_rls (Rule_Set.Rrls _) = "Rrls {...}";
   321 fun check_kestore_rls (rls', (thyID, rls)) =
   322   "(" ^ rls' ^ ", (" ^ thyID ^ ", " ^ short_string_of_rls rls ^ "))";
   323 
   324 fun check_kestore_calc ((id, (c, _)) : Rule_Def.eval_ml_from_prog)  = "(" ^ id ^ ", (" ^ c ^ ", fn))";
   325 
   326 (* we avoid term_to_string''' defined later *)
   327 fun check_kestore_cas ((t, (s, _)) : CAS_Def.T) =
   328   "(" ^ (Print_Mode.setmp [] (Syntax.string_of_term (Config.put show_markup false
   329   (Proof_Context.init_global @{theory})))) t ^ ", " ^ References_Def.to_string s ^ ")";
   330 
   331 fun count_kestore_ptyps [] = 0
   332   | count_kestore_ptyps ((Store.Node (_, _, ps)) :: ps') =
   333       1 + count_kestore_ptyps ps  + count_kestore_ptyps ps';
   334 fun check_kestore_ptyp' strfun (Store.Node (key, pbts, pts)) = "Ptyp (" ^ (quote key) ^ ", " ^
   335       (strfun pbts) ^ ", " ^ (map (check_kestore_ptyp' strfun) pts |> list2str) ^ ")" |> linefeed;
   336 val check_kestore_ptyp = check_kestore_ptyp' Probl_Def.s_to_string;
   337 fun ptyp_ord ((Store.Node (s1, _, _)), (Store.Node (s2, _, _))) = string_ord (s1, s2);
   338 fun pbt_ord ({guh = guh'1, ...} : Probl_Def.T, {guh = guh'2, ...} : Probl_Def.T) = string_ord (guh'1, guh'2);
   339 fun sort_kestore_ptyp' _ [] = []
   340   | sort_kestore_ptyp' ordfun ((Store.Node (key, pbts, ps)) :: ps') =
   341      ((Store.Node (key, sort ordfun pbts, sort_kestore_ptyp' ordfun ps |> sort ptyp_ord))
   342        :: sort_kestore_ptyp' ordfun ps');
   343 val sort_kestore_ptyp = sort_kestore_ptyp' pbt_ord;
   344 
   345 fun metguh2str ({guh,...} : Meth_Def.T) = guh : string;
   346 fun check_kestore_met (mp: Meth_Def.T Store.node) =
   347       check_kestore_ptyp' (fn xs => map metguh2str xs |> strs2str) mp;
   348 fun met_ord ({guh = guh'1, ...} : Meth_Def.T, {guh = guh'2, ...} : Meth_Def.T) = string_ord (guh'1, guh'2);
   349 val sort_kestore_met = sort_kestore_ptyp' met_ord;
   350 \<close>
   351 
   352 ML \<open>
   353 \<close> ML \<open>
   354 \<close> ML \<open>
   355 \<close>
   356 end