src/Tools/code/code_wellsorted.ML
changeset 31125 80218ee73167
parent 31124 58bc773c60e2
child 31126 d8a6122affd7
equal deleted inserted replaced
31124:58bc773c60e2 31125:80218ee73167
     1 (*  Title:      Tools/code/code_wellsorted.ML
       
     2     Author:     Florian Haftmann, TU Muenchen
       
     3 
       
     4 Producing well-sorted systems of code equations in a graph
       
     5 with explicit dependencies -- the Waisenhaus algorithm.
       
     6 *)
       
     7 
       
     8 signature CODE_WELLSORTED =
       
     9 sig
       
    10   type code_algebra
       
    11   type code_graph
       
    12   val eqns: code_graph -> string -> (thm * bool) list
       
    13   val typ: code_graph -> string -> (string * sort) list * typ
       
    14   val all: code_graph -> string list
       
    15   val pretty: theory -> code_graph -> Pretty.T
       
    16   val obtain: theory -> string list -> term list -> code_algebra * code_graph
       
    17   val eval_conv: theory -> (sort -> sort)
       
    18     -> (code_algebra -> code_graph -> (string * sort) list -> term -> cterm -> thm) -> cterm -> thm
       
    19   val eval: theory -> (sort -> sort) -> ((term -> term) -> 'a -> 'a)
       
    20     -> (code_algebra -> code_graph -> (string * sort) list -> term -> 'a) -> term -> 'a
       
    21 end
       
    22 
       
    23 structure Code_Wellsorted : CODE_WELLSORTED =
       
    24 struct
       
    25 
       
    26 (** the algebra and code equation graph types **)
       
    27 
       
    28 type code_algebra = (sort -> sort) * Sorts.algebra;
       
    29 type code_graph = (((string * sort) list * typ) * (thm * bool) list) Graph.T;
       
    30 
       
    31 fun eqns eqngr = these o Option.map snd o try (Graph.get_node eqngr);
       
    32 fun typ eqngr = fst o Graph.get_node eqngr;
       
    33 fun all eqngr = Graph.keys eqngr;
       
    34 
       
    35 fun pretty thy eqngr =
       
    36   AList.make (snd o Graph.get_node eqngr) (Graph.keys eqngr)
       
    37   |> (map o apfst) (Code_Unit.string_of_const thy)
       
    38   |> sort (string_ord o pairself fst)
       
    39   |> map (fn (s, thms) =>
       
    40        (Pretty.block o Pretty.fbreaks) (
       
    41          Pretty.str s
       
    42          :: map (Display.pretty_thm o fst) thms
       
    43        ))
       
    44   |> Pretty.chunks;
       
    45 
       
    46 
       
    47 (** the Waisenhaus algorithm **)
       
    48 
       
    49 (* auxiliary *)
       
    50 
       
    51 fun is_proper_class thy = can (AxClass.get_info thy);
       
    52 
       
    53 fun complete_proper_sort thy =
       
    54   Sign.complete_sort thy #> filter (is_proper_class thy);
       
    55 
       
    56 fun inst_params thy tyco =
       
    57   map (fn (c, _) => AxClass.param_of_inst thy (c, tyco))
       
    58     o maps (#params o AxClass.get_info thy);
       
    59 
       
    60 fun consts_of thy eqns = [] |> (fold o fold o fold_aterms)
       
    61   (fn Const (c, ty) => insert (op =) (c, Sign.const_typargs thy (c, Logic.unvarifyT ty)) | _ => I)
       
    62     (map (op :: o swap o apfst (snd o strip_comb) o Logic.dest_equals o Thm.plain_prop_of o fst) eqns);
       
    63 
       
    64 fun tyscm_rhss_of thy c eqns =
       
    65   let
       
    66     val tyscm = case eqns of [] => Code.default_typscheme thy c
       
    67       | ((thm, _) :: _) => Code_Unit.typscheme_eqn thy thm;
       
    68     val rhss = consts_of thy eqns;
       
    69   in (tyscm, rhss) end;
       
    70 
       
    71 
       
    72 (* data structures *)
       
    73 
       
    74 datatype const = Fun of string | Inst of class * string;
       
    75 
       
    76 fun const_ord (Fun c1, Fun c2) = fast_string_ord (c1, c2)
       
    77   | const_ord (Inst class_tyco1, Inst class_tyco2) =
       
    78       prod_ord fast_string_ord fast_string_ord (class_tyco1, class_tyco2)
       
    79   | const_ord (Fun _, Inst _) = LESS
       
    80   | const_ord (Inst _, Fun _) = GREATER;
       
    81 
       
    82 type var = const * int;
       
    83 
       
    84 structure Vargraph =
       
    85   GraphFun(type key = var val ord = prod_ord const_ord int_ord);
       
    86 
       
    87 datatype styp = Tyco of string * styp list | Var of var | Free;
       
    88 
       
    89 fun styp_of c_lhs (Type (tyco, tys)) = Tyco (tyco, map (styp_of c_lhs) tys)
       
    90   | styp_of c_lhs (TFree (v, _)) = case c_lhs
       
    91      of SOME (c, lhs) => Var (Fun c, find_index (fn (v', _) => v = v') lhs)
       
    92       | NONE => Free;
       
    93 
       
    94 type vardeps_data = ((string * styp list) list * class list) Vargraph.T
       
    95   * (((string * sort) list * (thm * bool) list) Symtab.table
       
    96     * (class * string) list);
       
    97 
       
    98 val empty_vardeps_data : vardeps_data =
       
    99   (Vargraph.empty, (Symtab.empty, []));
       
   100 
       
   101 
       
   102 (* retrieving equations and instances from the background context *)
       
   103 
       
   104 fun obtain_eqns thy eqngr c =
       
   105   case try (Graph.get_node eqngr) c
       
   106    of SOME ((lhs, _), eqns) => ((lhs, []), [])
       
   107     | NONE => let
       
   108         val eqns = Code.these_eqns thy c
       
   109           |> burrow_fst (Code_Unit.norm_args thy)
       
   110           |> burrow_fst (Code_Unit.norm_varnames thy);
       
   111         val ((lhs, _), rhss) = tyscm_rhss_of thy c eqns;
       
   112       in ((lhs, rhss), eqns) end;
       
   113 
       
   114 fun obtain_instance thy arities (inst as (class, tyco)) =
       
   115   case AList.lookup (op =) arities inst
       
   116    of SOME classess => (classess, ([], []))
       
   117     | NONE => let
       
   118         val all_classes = complete_proper_sort thy [class];
       
   119         val superclasses = remove (op =) class all_classes
       
   120         val classess = map (complete_proper_sort thy)
       
   121           (Sign.arity_sorts thy tyco [class]);
       
   122         val inst_params = inst_params thy tyco all_classes;
       
   123       in (classess, (superclasses, inst_params)) end;
       
   124 
       
   125 
       
   126 (* computing instantiations *)
       
   127 
       
   128 fun add_classes thy arities eqngr c_k new_classes vardeps_data =
       
   129   let
       
   130     val (styps, old_classes) = Vargraph.get_node (fst vardeps_data) c_k;
       
   131     val diff_classes = new_classes |> subtract (op =) old_classes;
       
   132   in if null diff_classes then vardeps_data
       
   133   else let
       
   134     val c_ks = Vargraph.imm_succs (fst vardeps_data) c_k |> insert (op =) c_k;
       
   135   in
       
   136     vardeps_data
       
   137     |> (apfst o Vargraph.map_node c_k o apsnd) (append diff_classes)
       
   138     |> fold (fn styp => fold (assert_typmatch_inst thy arities eqngr styp) new_classes) styps
       
   139     |> fold (fn c_k => add_classes thy arities eqngr c_k diff_classes) c_ks
       
   140   end end
       
   141 and add_styp thy arities eqngr c_k tyco_styps vardeps_data =
       
   142   let
       
   143     val (old_styps, classes) = Vargraph.get_node (fst vardeps_data) c_k;
       
   144   in if member (op =) old_styps tyco_styps then vardeps_data
       
   145   else
       
   146     vardeps_data
       
   147     |> (apfst o Vargraph.map_node c_k o apfst) (cons tyco_styps)
       
   148     |> fold (assert_typmatch_inst thy arities eqngr tyco_styps) classes
       
   149   end
       
   150 and add_dep thy arities eqngr c_k c_k' vardeps_data =
       
   151   let
       
   152     val (_, classes) = Vargraph.get_node (fst vardeps_data) c_k;
       
   153   in
       
   154     vardeps_data
       
   155     |> add_classes thy arities eqngr c_k' classes
       
   156     |> apfst (Vargraph.add_edge (c_k, c_k'))
       
   157   end
       
   158 and assert_typmatch_inst thy arities eqngr (tyco, styps) class vardeps_data =
       
   159   if can (Sign.arity_sorts thy tyco) [class]
       
   160   then vardeps_data
       
   161     |> assert_inst thy arities eqngr (class, tyco)
       
   162     |> fold_index (fn (k, styp) =>
       
   163          assert_typmatch thy arities eqngr styp (Inst (class, tyco), k)) styps
       
   164   else vardeps_data (*permissive!*)
       
   165 and assert_inst thy arities eqngr (inst as (class, tyco)) (vardeps_data as (_, (_, insts))) =
       
   166   if member (op =) insts inst then vardeps_data
       
   167   else let
       
   168     val (classess, (superclasses, inst_params)) =
       
   169       obtain_instance thy arities inst;
       
   170   in
       
   171     vardeps_data
       
   172     |> (apsnd o apsnd) (insert (op =) inst)
       
   173     |> fold_index (fn (k, _) =>
       
   174          apfst (Vargraph.new_node ((Inst (class, tyco), k), ([] ,[])))) classess
       
   175     |> fold (fn superclass => assert_inst thy arities eqngr (superclass, tyco)) superclasses
       
   176     |> fold (assert_fun thy arities eqngr) inst_params
       
   177     |> fold_index (fn (k, classes) =>
       
   178          add_classes thy arities eqngr (Inst (class, tyco), k) classes
       
   179          #> fold (fn superclass =>
       
   180              add_dep thy arities eqngr (Inst (superclass, tyco), k)
       
   181              (Inst (class, tyco), k)) superclasses
       
   182          #> fold (fn inst_param =>
       
   183              add_dep thy arities eqngr (Fun inst_param, k)
       
   184              (Inst (class, tyco), k)
       
   185              ) inst_params
       
   186          ) classess
       
   187   end
       
   188 and assert_typmatch thy arities eqngr (Tyco tyco_styps) c_k vardeps_data =
       
   189       vardeps_data
       
   190       |> add_styp thy arities eqngr c_k tyco_styps
       
   191   | assert_typmatch thy arities eqngr (Var c_k') c_k vardeps_data =
       
   192       vardeps_data
       
   193       |> add_dep thy arities eqngr c_k c_k'
       
   194   | assert_typmatch thy arities eqngr Free c_k vardeps_data =
       
   195       vardeps_data
       
   196 and assert_rhs thy arities eqngr (c', styps) vardeps_data =
       
   197   vardeps_data
       
   198   |> assert_fun thy arities eqngr c'
       
   199   |> fold_index (fn (k, styp) =>
       
   200        assert_typmatch thy arities eqngr styp (Fun c', k)) styps
       
   201 and assert_fun thy arities eqngr c (vardeps_data as (_, (eqntab, _))) =
       
   202   if Symtab.defined eqntab c then vardeps_data
       
   203   else let
       
   204     val ((lhs, rhss), eqns) = obtain_eqns thy eqngr c;
       
   205     val rhss' = (map o apsnd o map) (styp_of (SOME (c, lhs))) rhss;
       
   206   in
       
   207     vardeps_data
       
   208     |> (apsnd o apfst) (Symtab.update_new (c, (lhs, eqns)))
       
   209     |> fold_index (fn (k, _) =>
       
   210          apfst (Vargraph.new_node ((Fun c, k), ([] ,[])))) lhs
       
   211     |> fold_index (fn (k, (_, sort)) =>
       
   212          add_classes thy arities eqngr (Fun c, k) (complete_proper_sort thy sort)) lhs
       
   213     |> fold (assert_rhs thy arities eqngr) rhss'
       
   214   end;
       
   215 
       
   216 
       
   217 (* applying instantiations *)
       
   218 
       
   219 fun dicts_of thy (proj_sort, algebra) (T, sort) =
       
   220   let
       
   221     fun class_relation (x, _) _ = x;
       
   222     fun type_constructor tyco xs class =
       
   223       inst_params thy tyco (Sorts.complete_sort algebra [class])
       
   224         @ (maps o maps) fst xs;
       
   225     fun type_variable (TFree (_, sort)) = map (pair []) (proj_sort sort);
       
   226   in
       
   227     flat (Sorts.of_sort_derivation (Syntax.pp_global thy) algebra
       
   228       { class_relation = class_relation, type_constructor = type_constructor,
       
   229         type_variable = type_variable } (T, proj_sort sort)
       
   230        handle Sorts.CLASS_ERROR _ => [] (*permissive!*))
       
   231   end;
       
   232 
       
   233 fun add_arity thy vardeps (class, tyco) =
       
   234   AList.default (op =)
       
   235     ((class, tyco), map (fn k => (snd o Vargraph.get_node vardeps) (Inst (class, tyco), k))
       
   236       (0 upto Sign.arity_number thy tyco - 1));
       
   237 
       
   238 fun add_eqs thy vardeps (c, (proto_lhs, proto_eqns)) (rhss, eqngr) =
       
   239   if can (Graph.get_node eqngr) c then (rhss, eqngr)
       
   240   else let
       
   241     val lhs = map_index (fn (k, (v, _)) =>
       
   242       (v, snd (Vargraph.get_node vardeps (Fun c, k)))) proto_lhs;
       
   243     val inst_tab = Vartab.empty |> fold (fn (v, sort) =>
       
   244       Vartab.update ((v, 0), sort)) lhs;
       
   245     val eqns = proto_eqns
       
   246       |> (map o apfst) (Code_Unit.inst_thm thy inst_tab);
       
   247     val (tyscm, rhss') = tyscm_rhss_of thy c eqns;
       
   248     val eqngr' = Graph.new_node (c, (tyscm, eqns)) eqngr;
       
   249   in (map (pair c) rhss' @ rhss, eqngr') end;
       
   250 
       
   251 fun extend_arities_eqngr thy cs ts (arities, eqngr) =
       
   252   let
       
   253     val cs_rhss = (fold o fold_aterms) (fn Const (c_ty as (c, _)) =>
       
   254       insert (op =) (c, (map (styp_of NONE) o Sign.const_typargs thy) c_ty) | _ => I) ts [];
       
   255     val (vardeps, (eqntab, insts)) = empty_vardeps_data
       
   256       |> fold (assert_fun thy arities eqngr) cs
       
   257       |> fold (assert_rhs thy arities eqngr) cs_rhss;
       
   258     val arities' = fold (add_arity thy vardeps) insts arities;
       
   259     val pp = Syntax.pp_global thy;
       
   260     val algebra = Sorts.subalgebra pp (is_proper_class thy)
       
   261       (AList.lookup (op =) arities') (Sign.classes_of thy);
       
   262     val (rhss, eqngr') = Symtab.fold (add_eqs thy vardeps) eqntab ([], eqngr);
       
   263     fun deps_of (c, rhs) = c :: maps (dicts_of thy algebra)
       
   264       (rhs ~~ (map snd o fst o fst o Graph.get_node eqngr') c);
       
   265     val eqngr'' = fold (fn (c, rhs) => fold
       
   266       (curry Graph.add_edge c) (deps_of rhs)) rhss eqngr';
       
   267   in (algebra, (arities', eqngr'')) end;
       
   268 
       
   269 
       
   270 (** store **)
       
   271 
       
   272 structure Wellsorted = CodeDataFun
       
   273 (
       
   274   type T = ((string * class) * sort list) list * code_graph;
       
   275   val empty = ([], Graph.empty);
       
   276   fun purge thy cs (arities, eqngr) =
       
   277     let
       
   278       val del_cs = ((Graph.all_preds eqngr
       
   279         o filter (can (Graph.get_node eqngr))) cs);
       
   280       val del_arities = del_cs
       
   281         |> map_filter (AxClass.inst_of_param thy)
       
   282         |> maps (fn (c, tyco) =>
       
   283              (map (rpair tyco) o Sign.complete_sort thy o the_list
       
   284                o AxClass.class_of_param thy) c);
       
   285       val arities' = fold (AList.delete (op =)) del_arities arities;
       
   286       val eqngr' = Graph.del_nodes del_cs eqngr;
       
   287     in (arities', eqngr') end;
       
   288 );
       
   289 
       
   290 
       
   291 (** retrieval interfaces **)
       
   292 
       
   293 fun obtain thy cs ts = apsnd snd
       
   294   (Wellsorted.change_yield thy (extend_arities_eqngr thy cs ts));
       
   295 
       
   296 fun prepare_sorts_typ prep_sort
       
   297   = map_type_tfree (fn (v, sort) => TFree (v, prep_sort sort));
       
   298 
       
   299 fun prepare_sorts prep_sort (Const (c, ty)) =
       
   300       Const (c, prepare_sorts_typ prep_sort ty)
       
   301   | prepare_sorts prep_sort (t1 $ t2) =
       
   302       prepare_sorts prep_sort t1 $ prepare_sorts prep_sort t2
       
   303   | prepare_sorts prep_sort (Abs (v, ty, t)) =
       
   304       Abs (v, prepare_sorts_typ prep_sort ty, prepare_sorts prep_sort t)
       
   305   | prepare_sorts _ (t as Bound _) = t;
       
   306 
       
   307 fun gen_eval thy cterm_of conclude_evaluation prep_sort evaluator proto_ct =
       
   308   let
       
   309     val pp = Syntax.pp_global thy;
       
   310     val ct = cterm_of proto_ct;
       
   311     val _ = (Sign.no_frees pp o map_types (K dummyT) o Sign.no_vars pp)
       
   312       (Thm.term_of ct);
       
   313     val thm = Code.preprocess_conv thy ct;
       
   314     val ct' = Thm.rhs_of thm;
       
   315     val t' = Thm.term_of ct';
       
   316     val vs = Term.add_tfrees t' [];
       
   317     val consts = fold_aterms
       
   318       (fn Const (c, _) => insert (op =) c | _ => I) t' [];
       
   319  
       
   320     val t'' = prepare_sorts prep_sort t';
       
   321     val (algebra', eqngr') = obtain thy consts [t''];
       
   322   in conclude_evaluation (evaluator algebra' eqngr' vs t'' ct') thm end;
       
   323 
       
   324 fun simple_evaluator evaluator algebra eqngr vs t ct =
       
   325   evaluator algebra eqngr vs t;
       
   326 
       
   327 fun eval_conv thy =
       
   328   let
       
   329     fun conclude_evaluation thm2 thm1 =
       
   330       let
       
   331         val thm3 = Code.postprocess_conv thy (Thm.rhs_of thm2);
       
   332       in
       
   333         Thm.transitive thm1 (Thm.transitive thm2 thm3) handle THM _ =>
       
   334           error ("could not construct evaluation proof:\n"
       
   335           ^ (cat_lines o map Display.string_of_thm) [thm1, thm2, thm3])
       
   336       end;
       
   337   in gen_eval thy I conclude_evaluation end;
       
   338 
       
   339 fun eval thy prep_sort postproc evaluator = gen_eval thy (Thm.cterm_of thy)
       
   340   (K o postproc (Code.postprocess_term thy)) prep_sort (simple_evaluator evaluator);
       
   341 
       
   342 end; (*struct*)