1 (* Title: Tools/Code/code_thingol.ML
2 Author: Florian Haftmann, TU Muenchen
4 Intermediate language ("Thin-gol") representing executable code.
5 Representation and translation.
14 signature BASIC_CODE_THINGOL =
18 Dict of string list * plain_dict
20 Dict_Const of string * dict list list
21 | Dict_Var of vname * (int * int)
23 `%% of string * itype list
25 type const = string * (((itype list * dict list list) * (itype list * itype)) * bool)
26 (* (f [T1..Tn] {dicts} (_::S1) .. (_::Sm)) :: S =^= (f, ((([T1..Tn], dicts), ([S1..Sm], S)), ambiguous)) *)
29 | IVar of vname option
31 | `|=> of (vname option * itype) * iterm
32 | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
33 (*((term, type), [(selector pattern, body term )]), primitive term)*)
34 val `$$ : iterm * iterm list -> iterm;
35 val `|==> : (vname option * itype) list * iterm -> iterm;
36 type typscheme = (vname * sort) list * itype;
39 signature CODE_THINGOL =
41 include BASIC_CODE_THINGOL
43 val unfoldl: ('a -> ('a * 'b) option) -> 'a -> 'a * 'b list
44 val unfoldr: ('a -> ('b * 'a) option) -> 'a -> 'b list * 'a
45 val unfold_fun: itype -> itype list * itype
46 val unfold_fun_n: int -> itype -> itype list * itype
47 val unfold_app: iterm -> iterm * iterm list
48 val unfold_abs: iterm -> (vname option * itype) list * iterm
49 val split_let: iterm -> (((iterm * itype) * iterm) * iterm) option
50 val unfold_let: iterm -> ((iterm * itype) * iterm) list * iterm
51 val split_pat_abs: iterm -> ((iterm * itype) * iterm) option
52 val unfold_pat_abs: iterm -> (iterm * itype) list * iterm
53 val unfold_const_app: iterm -> (const * iterm list) option
54 val is_IVar: iterm -> bool
55 val is_IAbs: iterm -> bool
56 val eta_expand: int -> const * iterm list -> iterm
57 val contains_dict_var: iterm -> bool
58 val add_constnames: iterm -> string list -> string list
59 val add_tyconames: iterm -> string list -> string list
60 val fold_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
63 val empty_naming: naming
64 val lookup_class: naming -> class -> string option
65 val lookup_classrel: naming -> class * class -> string option
66 val lookup_tyco: naming -> string -> string option
67 val lookup_instance: naming -> class * string -> string option
68 val lookup_const: naming -> string -> string option
69 val ensure_declared_const: theory -> string -> naming -> string * naming
73 | Fun of string * ((typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option)
74 | Datatype of string * ((vname * sort) list *
75 ((string * vname list (*type argument wrt. canonical order*)) * itype list) list)
76 | Datatypecons of string * string
77 | Class of class * (vname * ((class * string) list * (string * itype) list))
78 | Classrel of class * class
79 | Classparam of string * class
80 | Classinst of (class * (string * (vname * sort) list) (*class and arity*))
81 * ((class * (string * (string * dict list list))) list (*super instances*)
82 * (((string * const) * (thm * bool)) list (*class parameter instances*)
83 * ((string * const) * (thm * bool)) list (*super class parameter instances*)))
84 type program = stmt Graph.T
85 val empty_funs: program -> string list
86 val map_terms_bottom_up: (iterm -> iterm) -> iterm -> iterm
87 val map_terms_stmt: (iterm -> iterm) -> stmt -> stmt
88 val is_cons: program -> string -> bool
89 val is_case: stmt -> bool
90 val labelled_name: theory -> program -> string -> string
91 val group_stmts: theory -> program
92 -> ((string * stmt) list * (string * stmt) list
93 * ((string * stmt) list * (string * stmt) list)) list
95 val read_const_exprs: theory -> string list -> string list * string list
96 val consts_program: theory -> bool -> string list -> string list * (naming * program)
97 val dynamic_conv: theory -> (naming -> program
98 -> ((string * sort) list * typscheme) * iterm -> string list -> conv)
100 val dynamic_value: theory -> ((term -> term) -> 'a -> 'a) -> (naming -> program
101 -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
103 val static_conv: theory -> string list -> (naming -> program -> string list
104 -> ((string * sort) list * typscheme) * iterm -> string list -> conv)
106 val static_conv_simple: theory -> string list
107 -> (program -> (string * sort) list -> term -> conv) -> conv
108 val static_value: theory -> ((term -> term) -> 'a -> 'a) -> string list ->
109 (naming -> program -> string list
110 -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
114 structure Code_Thingol: CODE_THINGOL =
123 let val (x', xs') = unfoldl dest x1 in (x', xs' @ [x2]) end;
129 let val (xs', x') = unfoldr dest x2 in (x1::xs', x') end;
132 (** language core - types, terms **)
137 Dict of string list * plain_dict
139 Dict_Const of string * dict list list
140 | Dict_Var of vname * (int * int)
143 `%% of string * itype list
146 type const = string * (((itype list * dict list list) *
147 (itype list (*types of arguments*) * itype (*result type*))) * bool (*requires type annotation*))
151 | IVar of vname option
152 | `$ of iterm * iterm
153 | `|=> of (vname option * itype) * iterm
154 | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
155 (*see also signature*)
157 fun is_IVar (IVar _) = true
160 fun is_IAbs (_ `|=> _) = true
163 val op `$$ = Library.foldl (op `$);
164 val op `|==> = Library.foldr (op `|=>);
166 val unfold_app = unfoldl
167 (fn op `$ t => SOME t
170 val unfold_abs = unfoldr
171 (fn op `|=> t => SOME t
175 (fn ICase (((td, ty), [(p, t)]), _) => SOME (((p, ty), td), t)
178 val unfold_let = unfoldr split_let;
180 fun unfold_const_app t =
182 of (IConst c, ts) => SOME (c, ts)
185 fun fold_constexprs f =
187 fun fold' (IConst c) = f c
189 | fold' (t1 `$ t2) = fold' t1 #> fold' t2
190 | fold' (_ `|=> t) = fold' t
191 | fold' (ICase (((t, _), ds), _)) = fold' t
192 #> fold (fn (pat, body) => fold' pat #> fold' body) ds
195 val add_constnames = fold_constexprs (fn (c, _) => insert (op =) c);
197 fun add_tycos (tyco `%% tys) = insert (op =) tyco #> fold add_tycos tys
198 | add_tycos (ITyVar _) = I;
200 val add_tyconames = fold_constexprs (fn (_, (((tys, _), _), _)) => fold add_tycos tys);
202 fun fold_varnames f =
206 fun fold_term _ (IConst _) = I
207 | fold_term vs (IVar (SOME v)) = if member (op =) vs v then I else f v
208 | fold_term _ (IVar NONE) = I
209 | fold_term vs (t1 `$ t2) = fold_term vs t1 #> fold_term vs t2
210 | fold_term vs ((SOME v, _) `|=> t) = fold_term (insert (op =) v vs) t
211 | fold_term vs ((NONE, _) `|=> t) = fold_term vs t
212 | fold_term vs (ICase (((t, _), ds), _)) = fold_term vs t #> fold (fold_case vs) ds
213 and fold_case vs (p, t) = fold_term (add p vs) t;
215 fun add t = fold_aux add (insert (op =)) t;
216 in fold_aux add f end;
218 fun exists_var t v = fold_varnames (fn w => fn b => v = w orelse b) t false;
220 fun split_pat_abs ((NONE, ty) `|=> t) = SOME ((IVar NONE, ty), t)
221 | split_pat_abs ((SOME v, ty) `|=> t) = SOME (case t
222 of ICase (((IVar (SOME w), _), [(p, t')]), _) =>
223 if v = w andalso (exists_var p v orelse not (exists_var t' v))
225 else ((IVar (SOME v), ty), t)
226 | _ => ((IVar (SOME v), ty), t))
227 | split_pat_abs _ = NONE;
229 val unfold_pat_abs = unfoldr split_pat_abs;
231 fun unfold_abs_eta [] t = ([], t)
232 | unfold_abs_eta (_ :: tys) (v_ty `|=> t) =
234 val (vs_tys, t') = unfold_abs_eta tys t;
235 in (v_ty :: vs_tys, t') end
236 | unfold_abs_eta tys t =
238 val ctxt = fold_varnames Name.declare t Name.context;
239 val vs_tys = (map o apfst) SOME (Name.invent_names ctxt "a" tys);
240 in (vs_tys, t `$$ map (IVar o fst) vs_tys) end;
242 fun eta_expand k (c as (name, ((_, (tys, _)), _)), ts) =
246 val _ = if l > length tys
247 then error ("Impossible eta-expansion for constant " ^ quote name) else ();
248 val ctxt = (fold o fold_varnames) Name.declare ts Name.context;
249 val vs_tys = (map o apfst) SOME
250 (Name.invent_names ctxt "a" ((take l o drop j) tys));
251 in vs_tys `|==> IConst c `$$ ts @ map (IVar o fst) vs_tys end;
253 fun contains_dict_var t =
255 fun cont_dict (Dict (_, d)) = cont_plain_dict d
256 and cont_plain_dict (Dict_Const (_, dss)) = (exists o exists) cont_dict dss
257 | cont_plain_dict (Dict_Var _) = true;
258 fun cont_term (IConst (_, (((_, dss), _), _))) = (exists o exists) cont_dict dss
259 | cont_term (IVar _) = false
260 | cont_term (t1 `$ t2) = cont_term t1 orelse cont_term t2
261 | cont_term (_ `|=> t) = cont_term t
262 | cont_term (ICase (_, t)) = cont_term t;
271 fun thyname_of_type thy = #theory_name o Name_Space.the_entry (Sign.type_space thy);
272 fun thyname_of_class thy = #theory_name o Name_Space.the_entry (Sign.class_space thy);
273 fun thyname_of_instance thy inst = case AxClass.thynames_of_arity thy inst
274 of [] => error ("No such instance: " ^ quote (snd inst ^ " :: " ^ fst inst))
275 | thyname :: _ => thyname;
276 fun thyname_of_const thy c = case AxClass.class_of_param thy c
277 of SOME class => thyname_of_class thy class
278 | NONE => (case Code.get_type_of_constr_or_abstr thy c
279 of SOME (tyco, _) => thyname_of_type thy tyco
280 | NONE => #theory_name (Name_Space.the_entry (Sign.const_space thy) c));
281 fun purify_base "==>" = "follows"
282 | purify_base "==" = "meta_eq"
283 | purify_base s = Name.desymbolize false s;
284 fun namify thy get_basename get_thyname name =
286 val prefix = get_thyname thy name;
287 val base = (purify_base o get_basename) name;
288 in Long_Name.append prefix base end;
291 fun namify_class thy = namify thy Long_Name.base_name thyname_of_class;
292 fun namify_classrel thy = namify thy (fn (sub_class, super_class) =>
293 Long_Name.base_name super_class ^ "_" ^ Long_Name.base_name sub_class)
294 (fn thy => thyname_of_class thy o fst);
295 (*order fits nicely with composed projections*)
296 fun namify_tyco thy "fun" = "Pure.fun"
297 | namify_tyco thy tyco = namify thy Long_Name.base_name thyname_of_type tyco;
298 fun namify_instance thy = namify thy (fn (class, tyco) =>
299 Long_Name.base_name class ^ "_" ^ Long_Name.base_name tyco) thyname_of_instance;
300 fun namify_const thy = namify thy Long_Name.base_name thyname_of_const;
307 datatype naming = Naming of {
308 class: class Symtab.table * Name.context,
309 classrel: string Symreltab.table * Name.context,
310 tyco: string Symtab.table * Name.context,
311 instance: string Symreltab.table * Name.context,
312 const: string Symtab.table * Name.context
315 fun dest_Naming (Naming naming) = naming;
317 val empty_naming = Naming {
318 class = (Symtab.empty, Name.context),
319 classrel = (Symreltab.empty, Name.context),
320 tyco = (Symtab.empty, Name.context),
321 instance = (Symreltab.empty, Name.context),
322 const = (Symtab.empty, Name.context)
326 fun mk_naming (class, classrel, tyco, instance, const) =
327 Naming { class = class, classrel = classrel,
328 tyco = tyco, instance = instance, const = const };
329 fun map_naming f (Naming { class, classrel, tyco, instance, const }) =
330 mk_naming (f (class, classrel, tyco, instance, const));
332 fun map_class f = map_naming
333 (fn (class, classrel, tyco, inst, const) =>
334 (f class, classrel, tyco, inst, const));
335 fun map_classrel f = map_naming
336 (fn (class, classrel, tyco, inst, const) =>
337 (class, f classrel, tyco, inst, const));
338 fun map_tyco f = map_naming
339 (fn (class, classrel, tyco, inst, const) =>
340 (class, classrel, f tyco, inst, const));
341 fun map_instance f = map_naming
342 (fn (class, classrel, tyco, inst, const) =>
343 (class, classrel, tyco, f inst, const));
344 fun map_const f = map_naming
345 (fn (class, classrel, tyco, inst, const) =>
346 (class, classrel, tyco, inst, f const));
349 fun add_variant update (thing, name) (tab, used) =
351 val (name', used') = Name.variant name used;
352 val tab' = update (thing, name') tab;
353 in (tab', used') end;
355 fun declare thy mapp lookup update namify thing =
356 mapp (add_variant update (thing, namify thy thing))
357 #> `(fn naming => the (lookup naming thing));
360 (* lookup and declare *)
364 val suffix_class = "class";
365 val suffix_classrel = "classrel"
366 val suffix_tyco = "tyco";
367 val suffix_instance = "inst";
368 val suffix_const = "const";
370 fun add_suffix nsp NONE = NONE
371 | add_suffix nsp (SOME name) = SOME (Long_Name.append name nsp);
375 val lookup_class = add_suffix suffix_class
376 oo Symtab.lookup o fst o #class o dest_Naming;
377 val lookup_classrel = add_suffix suffix_classrel
378 oo Symreltab.lookup o fst o #classrel o dest_Naming;
379 val lookup_tyco = add_suffix suffix_tyco
380 oo Symtab.lookup o fst o #tyco o dest_Naming;
381 val lookup_instance = add_suffix suffix_instance
382 oo Symreltab.lookup o fst o #instance o dest_Naming;
383 val lookup_const = add_suffix suffix_const
384 oo Symtab.lookup o fst o #const o dest_Naming;
386 fun declare_class thy = declare thy map_class
387 lookup_class Symtab.update_new namify_class;
388 fun declare_classrel thy = declare thy map_classrel
389 lookup_classrel Symreltab.update_new namify_classrel;
390 fun declare_tyco thy = declare thy map_tyco
391 lookup_tyco Symtab.update_new namify_tyco;
392 fun declare_instance thy = declare thy map_instance
393 lookup_instance Symreltab.update_new namify_instance;
394 fun declare_const thy = declare thy map_const
395 lookup_const Symtab.update_new namify_const;
397 fun ensure_declared_const thy const naming =
398 case lookup_const naming const
399 of SOME const' => (const', naming)
400 | NONE => declare_const thy const naming;
402 val fun_tyco = Long_Name.append (namify_tyco Pure.thy "fun") suffix_tyco
403 (*depends on add_suffix*);
405 val unfold_fun = unfoldr
406 (fn tyco `%% [ty1, ty2] => if tyco = fun_tyco then SOME (ty1, ty2) else NONE
409 fun unfold_fun_n n ty =
411 val (tys1, ty1) = unfold_fun ty;
412 val (tys3, tys2) = chop n tys1;
413 val ty3 = Library.foldr (fn (ty1, ty2) => fun_tyco `%% [ty1, ty2]) (tys2, ty1);
419 (** statements, abstract programs **)
421 type typscheme = (vname * sort) list * itype;
424 | Fun of string * ((typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option)
425 | Datatype of string * ((vname * sort) list * ((string * vname list) * itype list) list)
426 | Datatypecons of string * string
427 | Class of class * (vname * ((class * string) list * (string * itype) list))
428 | Classrel of class * class
429 | Classparam of string * class
430 | Classinst of (class * (string * (vname * sort) list))
431 * ((class * (string * (string * dict list list))) list
432 * (((string * const) * (thm * bool)) list
433 * ((string * const) * (thm * bool)) list))
434 (*see also signature*);
436 type program = stmt Graph.T;
438 fun empty_funs program =
439 Graph.fold (fn (name, (Fun (c, ((_, []), _)), _)) => cons c
440 | _ => I) program [];
442 fun map_terms_bottom_up f (t as IConst _) = f t
443 | map_terms_bottom_up f (t as IVar _) = f t
444 | map_terms_bottom_up f (t1 `$ t2) = f
445 (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
446 | map_terms_bottom_up f ((v, ty) `|=> t) = f
447 ((v, ty) `|=> map_terms_bottom_up f t)
448 | map_terms_bottom_up f (ICase (((t, ty), ps), t0)) = f
449 (ICase (((map_terms_bottom_up f t, ty), (map o pairself)
450 (map_terms_bottom_up f) ps), map_terms_bottom_up f t0));
452 fun map_classparam_instances_as_term f =
453 (map o apfst o apsnd) (fn const => case f (IConst const) of IConst const' => const')
455 fun map_terms_stmt f NoStmt = NoStmt
456 | map_terms_stmt f (Fun (c, ((tysm, eqs), case_cong))) = Fun (c, ((tysm, (map o apfst)
457 (fn (ts, t) => (map f ts, f t)) eqs), case_cong))
458 | map_terms_stmt f (stmt as Datatype _) = stmt
459 | map_terms_stmt f (stmt as Datatypecons _) = stmt
460 | map_terms_stmt f (stmt as Class _) = stmt
461 | map_terms_stmt f (stmt as Classrel _) = stmt
462 | map_terms_stmt f (stmt as Classparam _) = stmt
463 | map_terms_stmt f (Classinst (arity, (super_instances, classparam_instances))) =
464 Classinst (arity, (super_instances, (pairself o map_classparam_instances_as_term) f classparam_instances));
466 fun is_cons program name = case Graph.get_node program name
467 of Datatypecons _ => true
470 fun is_case (Fun (_, (_, SOME _))) = true
473 fun labelled_name thy program name =
474 let val ctxt = Proof_Context.init_global thy in
475 case Graph.get_node program name of
476 Fun (c, _) => quote (Code.string_of_const thy c)
477 | Datatype (tyco, _) => "type " ^ quote (Proof_Context.extern_type ctxt tyco)
478 | Datatypecons (c, _) => quote (Code.string_of_const thy c)
479 | Class (class, _) => "class " ^ quote (Proof_Context.extern_class ctxt class)
480 | Classrel (sub, super) =>
482 val Class (sub, _) = Graph.get_node program sub;
483 val Class (super, _) = Graph.get_node program super;
485 quote (Proof_Context.extern_class ctxt sub ^ " < " ^ Proof_Context.extern_class ctxt super)
487 | Classparam (c, _) => quote (Code.string_of_const thy c)
488 | Classinst ((class, (tyco, _)), _) =>
490 val Class (class, _) = Graph.get_node program class;
491 val Datatype (tyco, _) = Graph.get_node program tyco;
493 quote (Proof_Context.extern_type ctxt tyco ^ " :: " ^ Proof_Context.extern_class ctxt class)
497 fun linear_stmts program =
498 rev (Graph.strong_conn program)
499 |> map (AList.make (Graph.get_node program));
501 fun group_stmts thy program =
503 fun is_fun (_, Fun _) = true | is_fun _ = false;
504 fun is_datatypecons (_, Datatypecons _) = true | is_datatypecons _ = false;
505 fun is_datatype (_, Datatype _) = true | is_datatype _ = false;
506 fun is_class (_, Class _) = true | is_class _ = false;
507 fun is_classrel (_, Classrel _) = true | is_classrel _ = false;
508 fun is_classparam (_, Classparam _) = true | is_classparam _ = false;
509 fun is_classinst (_, Classinst _) = true | is_classinst _ = false;
511 if forall (is_datatypecons orf is_datatype) stmts
512 then (filter is_datatype stmts, [], ([], []))
513 else if forall (is_class orf is_classrel orf is_classparam) stmts
514 then ([], filter is_class stmts, ([], []))
515 else if forall (is_fun orf is_classinst) stmts
516 then ([], [], List.partition is_fun stmts)
517 else error ("Illegal mutual dependencies: " ^
518 (commas o map (labelled_name thy program o fst)) stmts)
525 (** translation kernel **)
527 (* generic mechanisms *)
529 fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
531 fun add_dep name = case dep of NONE => I
532 | SOME dep => Graph.add_edge (dep, name);
533 val (name, naming') = case lookup naming thing
534 of SOME name => (name, naming)
535 | NONE => declare thing naming;
536 in case try (Graph.get_node program) name
537 of SOME stmt => program
543 |> Graph.default_node (name, NoStmt)
546 |> curry generate (SOME name)
548 |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
553 exception PERMISSIVE of unit;
555 fun translation_error thy permissive some_thm msg sub_msg =
557 then raise PERMISSIVE ()
562 SOME thm => "\n(in code equation " ^ Display.string_of_thm_global thy thm ^ ")"
564 in error (msg ^ err_thm ^ ":\n" ^ sub_msg) end;
566 fun not_wellsorted thy permissive some_thm ty sort e =
568 val err_class = Sorts.class_error (Context.pretty_global thy) e;
570 "Type " ^ Syntax.string_of_typ_global thy ty ^ " not of sort " ^
571 Syntax.string_of_sort_global thy sort;
573 translation_error thy permissive some_thm "Wellsortedness error"
574 (err_typ ^ "\n" ^ err_class)
578 (* inference of type annotations for disambiguation with type classes *)
580 fun mk_tagged_type (true, T) = Type ("", [T])
581 | mk_tagged_type (false, T) = T;
583 fun dest_tagged_type (Type ("", [T])) = (true, T)
584 | dest_tagged_type T = (false, T);
586 val untag_term = map_types (snd o dest_tagged_type);
588 fun tag_term (proj_sort, _) eqngr =
590 val has_sort_constraints = exists (not o null) o map proj_sort o Code_Preproc.sortargs eqngr;
591 fun tag (Const (c', T')) (Const (c, T)) =
593 mk_tagged_type (not (null (Term.add_tvarsT T' [])) andalso has_sort_constraints c, T))
594 | tag (t1 $ u1) (t $ u) = tag t1 t $ tag u1 u
595 | tag (Abs (_, _, t1)) (Abs (x, T, t)) = Abs (x, T, tag t1 t)
596 | tag (Free _) (t as Free _) = t
597 | tag (Var _) (t as Var _) = t
598 | tag (Bound _) (t as Bound _) = t;
603 fun annotate thy algbr eqngr (c, ty) args rhs =
605 val ctxt = Proof_Context.init_global thy |> Config.put Type_Infer_Context.const_sorts false
606 val erase = map_types (fn _ => Type_Infer.anyT [])
607 val reinfer = singleton (Type_Infer_Context.infer_types ctxt)
608 val lhs = list_comb (Const (c, ty), map (map_types Type.strip_sorts o fst) args)
609 val reinferred_rhs = snd (Logic.dest_equals (reinfer (Logic.mk_equals (lhs, erase rhs))))
611 tag_term algbr eqngr reinferred_rhs rhs
614 fun annotate_eqns thy algbr eqngr (c, ty) eqns =
615 map (apfst (fn (args, (rhs, some_abs)) => (args,
616 (annotate thy algbr eqngr (c, ty) args rhs, some_abs)))) eqns
621 fun ensure_tyco thy algbr eqngr permissive tyco =
623 val ((vs, cos), _) = Code.get_type thy tyco;
625 fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
626 ##>> fold_map (fn (c, (vs, tys)) =>
627 ensure_const thy algbr eqngr permissive c
628 ##>> pair (map (unprefix "'" o fst) vs)
629 ##>> fold_map (translate_typ thy algbr eqngr permissive) tys) cos
630 #>> (fn info => Datatype (tyco, info));
631 in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
632 and ensure_const thy algbr eqngr permissive c =
634 fun stmt_datatypecons tyco =
635 ensure_tyco thy algbr eqngr permissive tyco
636 #>> (fn tyco => Datatypecons (c, tyco));
637 fun stmt_classparam class =
638 ensure_class thy algbr eqngr permissive class
639 #>> (fn class => Classparam (c, class));
642 val ((vs, ty), eqns) = Code.equations_of_cert thy cert;
643 val eqns' = annotate_eqns thy algbr eqngr (c, ty) eqns
644 val some_case_cong = Code.get_case_cong thy c;
646 fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
647 ##>> translate_typ thy algbr eqngr permissive ty
648 ##>> translate_eqns thy algbr eqngr permissive eqns'
649 #>> (fn info => Fun (c, (info, some_case_cong)))
651 val stmt_const = case Code.get_type_of_constr_or_abstr thy c
652 of SOME (tyco, _) => stmt_datatypecons tyco
653 | NONE => (case AxClass.class_of_param thy c
654 of SOME class => stmt_classparam class
655 | NONE => stmt_fun (Code_Preproc.cert eqngr c))
656 in ensure_stmt lookup_const (declare_const thy) stmt_const c end
657 and ensure_class thy (algbr as (_, algebra)) eqngr permissive class =
659 val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
660 val cs = #params (AxClass.get_info thy class);
662 fold_map (fn super_class => ensure_class thy algbr eqngr permissive super_class
663 ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)) super_classes
664 ##>> fold_map (fn (c, ty) => ensure_const thy algbr eqngr permissive c
665 ##>> translate_typ thy algbr eqngr permissive ty) cs
666 #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
667 in ensure_stmt lookup_class (declare_class thy) stmt_class class end
668 and ensure_classrel thy algbr eqngr permissive (sub_class, super_class) =
671 ensure_class thy algbr eqngr permissive sub_class
672 ##>> ensure_class thy algbr eqngr permissive super_class
674 in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (sub_class, super_class) end
675 and ensure_inst thy (algbr as (_, algebra)) eqngr permissive (class, tyco) =
677 val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
678 val these_classparams = these o try (#params o AxClass.get_info thy);
679 val classparams = these_classparams class;
680 val further_classparams = maps these_classparams
681 ((Sorts.complete_sort algebra o Sorts.super_classes algebra) class);
682 val vs = Name.invent_names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
683 val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
684 val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
685 Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
686 val arity_typ = Type (tyco, map TFree vs);
687 val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
688 fun translate_super_instance super_class =
689 ensure_class thy algbr eqngr permissive super_class
690 ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)
691 ##>> translate_dicts thy algbr eqngr permissive NONE (arity_typ, [super_class])
692 #>> (fn ((super_class, classrel), [Dict ([], Dict_Const (inst, dss))]) =>
693 (super_class, (classrel, (inst, dss))));
694 fun translate_classparam_instance (c, ty) =
696 val raw_const = Const (c, map_type_tfree (K arity_typ') ty);
697 val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy raw_const);
698 val const = (apsnd Logic.unvarifyT_global o dest_Const o snd
699 o Logic.dest_equals o Thm.prop_of) thm;
701 ensure_const thy algbr eqngr permissive c
702 ##>> translate_const thy algbr eqngr permissive (SOME thm) (const, NONE)
703 #>> (fn (c, IConst const') => ((c, const'), (thm, true)))
706 ensure_class thy algbr eqngr permissive class
707 ##>> ensure_tyco thy algbr eqngr permissive tyco
708 ##>> fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
709 ##>> fold_map translate_super_instance super_classes
710 ##>> fold_map translate_classparam_instance classparams
711 ##>> fold_map translate_classparam_instance further_classparams
712 #>> (fn (((((class, tyco), arity_args), super_instances),
713 classparam_instances), further_classparam_instances) =>
714 Classinst ((class, (tyco, arity_args)), (super_instances,
715 (classparam_instances, further_classparam_instances))));
716 in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
717 and translate_typ thy algbr eqngr permissive (TFree (v, _)) =
718 pair (ITyVar (unprefix "'" v))
719 | translate_typ thy algbr eqngr permissive (Type (tyco, tys)) =
720 ensure_tyco thy algbr eqngr permissive tyco
721 ##>> fold_map (translate_typ thy algbr eqngr permissive) tys
722 #>> (fn (tyco, tys) => tyco `%% tys)
723 and translate_term thy algbr eqngr permissive some_thm (Const (c, ty), some_abs) =
724 translate_app thy algbr eqngr permissive some_thm (((c, ty), []), some_abs)
725 | translate_term thy algbr eqngr permissive some_thm (Free (v, _), some_abs) =
727 | translate_term thy algbr eqngr permissive some_thm (Abs (v, ty, t), some_abs) =
729 val (v', t') = Syntax_Trans.variant_abs (Name.desymbolize false v, ty, t);
730 val v'' = if member (op =) (Term.add_free_names t' []) v'
731 then SOME v' else NONE
733 translate_typ thy algbr eqngr permissive ty
734 ##>> translate_term thy algbr eqngr permissive some_thm (t', some_abs)
735 #>> (fn (ty, t) => (v'', ty) `|=> t)
737 | translate_term thy algbr eqngr permissive some_thm (t as _ $ _, some_abs) =
739 of (Const (c, ty), ts) =>
740 translate_app thy algbr eqngr permissive some_thm (((c, ty), ts), some_abs)
742 translate_term thy algbr eqngr permissive some_thm (t', some_abs)
743 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
744 #>> (fn (t, ts) => t `$$ ts)
745 and translate_eqn thy algbr eqngr permissive ((args, (rhs, some_abs)), (some_thm, proper)) =
746 fold_map (translate_term thy algbr eqngr permissive some_thm) args
747 ##>> translate_term thy algbr eqngr permissive some_thm (rhs, some_abs)
748 #>> rpair (some_thm, proper)
749 and translate_eqns thy algbr eqngr permissive eqns prgrm =
750 prgrm |> fold_map (translate_eqn thy algbr eqngr permissive) eqns
751 handle PERMISSIVE () => ([], prgrm)
752 and translate_const thy algbr eqngr permissive some_thm ((c, ty), some_abs) =
754 val _ = if (case some_abs of NONE => true | SOME abs => not (c = abs))
755 andalso Code.is_abstr thy c
756 then translation_error thy permissive some_thm
757 "Abstraction violation" ("constant " ^ Code.string_of_const thy c)
759 val (annotate, ty') = dest_tagged_type ty
760 val arg_typs = Sign.const_typargs thy (c, ty');
761 val sorts = Code_Preproc.sortargs eqngr c;
762 val (function_typs, body_typ) = Term.strip_type ty';
764 ensure_const thy algbr eqngr permissive c
765 ##>> fold_map (translate_typ thy algbr eqngr permissive) arg_typs
766 ##>> fold_map (translate_dicts thy algbr eqngr permissive some_thm) (arg_typs ~~ sorts)
767 ##>> fold_map (translate_typ thy algbr eqngr permissive) (body_typ :: function_typs)
768 #>> (fn (((c, arg_typs), dss), body_typ :: function_typs) =>
769 IConst (c, (((arg_typs, dss), (function_typs, body_typ)), annotate)))
771 and translate_app_const thy algbr eqngr permissive some_thm ((c_ty, ts), some_abs) =
772 translate_const thy algbr eqngr permissive some_thm (c_ty, some_abs)
773 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
774 #>> (fn (t, ts) => t `$$ ts)
775 and translate_case thy algbr eqngr permissive some_thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
777 fun arg_types num_args ty = fst (chop num_args (binder_types ty));
778 val tys = arg_types num_args (snd c_ty);
779 val ty = nth tys t_pos;
780 fun mk_constr NONE t = NONE
781 | mk_constr (SOME c) t =
783 val n = Code.args_number thy c;
784 in SOME ((c, arg_types n (fastype_of (untag_term t)) ---> ty), n) end;
786 if null case_pats then []
787 else map_filter I (map2 mk_constr case_pats (nth_drop t_pos ts));
788 fun casify naming constrs ty ts =
790 val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
791 fun collapse_clause vs_map ts body =
794 of IConst (c, _) => if member (op =) undefineds c
797 | ICase (((IVar (SOME v), _), subclauses), _) =>
798 if forall (fn (pat', body') => exists_var pat' v
799 orelse not (exists_var body' v)) subclauses
800 then case AList.lookup (op =) vs_map v
801 of SOME i => maps (fn (pat', body') =>
802 collapse_clause (AList.delete (op =) v vs_map)
803 (nth_map i (K pat') ts) body') subclauses
804 | NONE => [(ts, body)]
808 fun mk_clause mk tys t =
810 val (vs, body) = unfold_abs_eta tys t;
811 val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
812 val ts = map (IVar o fst) vs;
813 in map mk (collapse_clause vs_map ts body) end;
814 val t = nth ts t_pos;
815 val ts_clause = nth_drop t_pos ts;
816 val clauses = if null case_pats
817 then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
818 else maps (fn ((constr as IConst (_, ((_, (tys, _)), _)), n), t) =>
819 mk_clause (fn (ts, body) => (constr `$$ ts, body)) (take n tys) t)
820 (constrs ~~ (map_filter (fn (NONE, _) => NONE | (SOME _, t) => SOME t)
821 (case_pats ~~ ts_clause)));
822 in ((t, ty), clauses) end;
824 translate_const thy algbr eqngr permissive some_thm (c_ty, NONE)
825 ##>> fold_map (fn (constr, n) => translate_const thy algbr eqngr permissive some_thm (constr, NONE)
827 ##>> translate_typ thy algbr eqngr permissive ty
828 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
829 #-> (fn (((t, constrs), ty), ts) =>
830 `(fn (_, (naming, _)) => ICase (casify naming constrs ty ts, t `$$ ts)))
832 and translate_app_case thy algbr eqngr permissive some_thm (case_scheme as (num_args, _)) ((c, ty), ts) =
833 if length ts < num_args then
836 val tys = (take (num_args - k) o drop k o fst o strip_type) ty;
837 val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
838 val vs = Name.invent_names ctxt "a" tys;
840 fold_map (translate_typ thy algbr eqngr permissive) tys
841 ##>> translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts @ map Free vs)
842 #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
844 else if length ts > num_args then
845 translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), take num_args ts)
846 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) (drop num_args ts)
847 #>> (fn (t, ts) => t `$$ ts)
849 translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts)
850 and translate_app thy algbr eqngr permissive some_thm (c_ty_ts as ((c, _), _), some_abs) =
851 case Code.get_case_scheme thy c
852 of SOME case_scheme => translate_app_case thy algbr eqngr permissive some_thm case_scheme c_ty_ts
853 | NONE => translate_app_const thy algbr eqngr permissive some_thm (c_ty_ts, some_abs)
854 and translate_tyvar_sort thy (algbr as (proj_sort, _)) eqngr permissive (v, sort) =
855 fold_map (ensure_class thy algbr eqngr permissive) (proj_sort sort)
856 #>> (fn sort => (unprefix "'" v, sort))
857 and translate_dicts thy (algbr as (proj_sort, algebra)) eqngr permissive some_thm (ty, sort) =
859 datatype typarg_witness =
860 Weakening of (class * class) list * plain_typarg_witness
861 and plain_typarg_witness =
862 Global of (class * string) * typarg_witness list list
863 | Local of string * (int * sort);
864 fun class_relation ((Weakening (classrels, x)), sub_class) super_class =
865 Weakening ((sub_class, super_class) :: classrels, x);
866 fun type_constructor (tyco, _) dss class =
867 Weakening ([], Global ((class, tyco), (map o map) fst dss));
868 fun type_variable (TFree (v, sort)) =
870 val sort' = proj_sort sort;
871 in map_index (fn (n, class) => (Weakening ([], Local (v, (n, sort'))), class)) sort' end;
872 val typarg_witnesses = Sorts.of_sort_derivation algebra
873 {class_relation = K (Sorts.classrel_derivation algebra class_relation),
874 type_constructor = type_constructor,
875 type_variable = type_variable} (ty, proj_sort sort)
876 handle Sorts.CLASS_ERROR e => not_wellsorted thy permissive some_thm ty sort e;
877 fun mk_dict (Weakening (classrels, x)) =
878 fold_map (ensure_classrel thy algbr eqngr permissive) classrels
881 and mk_plain_dict (Global (inst, dss)) =
882 ensure_inst thy algbr eqngr permissive inst
883 ##>> (fold_map o fold_map) mk_dict dss
884 #>> (fn (inst, dss) => Dict_Const (inst, dss))
885 | mk_plain_dict (Local (v, (n, sort))) =
886 pair (Dict_Var (unprefix "'" v, (n, length sort)))
887 in fold_map mk_dict typarg_witnesses end;
892 structure Program = Code_Data
894 type T = naming * program;
895 val empty = (empty_naming, Graph.empty);
898 fun invoke_generation ignore_cache thy (algebra, eqngr) generate thing =
899 Program.change_yield (if ignore_cache then NONE else SOME thy)
900 (fn naming_program => (NONE, naming_program)
901 |> generate thy algebra eqngr thing
902 |-> (fn thing => fn (_, naming_program) => (thing, naming_program)));
905 (* program generation *)
907 fun consts_program thy permissive consts =
909 fun project_consts consts (naming, program) =
910 if permissive then (consts, (naming, program))
911 else (consts, (naming, Graph.restrict
912 (member (op =) (Graph.all_succs program consts)) program));
913 fun generate_consts thy algebra eqngr =
914 fold_map (ensure_const thy algebra eqngr permissive);
916 invoke_generation permissive thy (Code_Preproc.obtain false thy consts [])
917 generate_consts consts
922 (* value evaluation *)
924 fun ensure_value thy algbr eqngr t =
926 val ty = fastype_of t;
927 val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
928 o dest_TFree))) t [];
929 val t' = annotate thy algbr eqngr (Term.dummy_patternN, ty) [] t;
931 fold_map (translate_tyvar_sort thy algbr eqngr false) vs
932 ##>> translate_typ thy algbr eqngr false ty
933 ##>> translate_term thy algbr eqngr false NONE (t', NONE)
934 #>> (fn ((vs, ty), t) => Fun
935 (Term.dummy_patternN, (((vs, ty), [(([], t), (NONE, true))]), NONE)));
936 fun term_value (dep, (naming, program1)) =
938 val Fun (_, ((vs_ty, [(([], t), _)]), _)) =
939 Graph.get_node program1 Term.dummy_patternN;
940 val deps = Graph.immediate_succs program1 Term.dummy_patternN;
941 val program2 = Graph.del_node Term.dummy_patternN program1;
942 val deps_all = Graph.all_succs program2 deps;
943 val program3 = Graph.restrict (member (op =) deps_all) program2;
944 in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
946 ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
951 fun original_sorts vs =
952 map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v));
954 fun dynamic_evaluator thy evaluator algebra eqngr vs t =
956 val (((naming, program), (((vs', ty'), t'), deps)), _) =
957 invoke_generation false thy (algebra, eqngr) ensure_value t;
958 in evaluator naming program ((original_sorts vs vs', (vs', ty')), t') deps end;
960 fun dynamic_conv thy evaluator =
961 Code_Preproc.dynamic_conv thy (dynamic_evaluator thy evaluator);
963 fun dynamic_value thy postproc evaluator =
964 Code_Preproc.dynamic_value thy postproc (dynamic_evaluator thy evaluator);
966 fun lift_evaluation thy evaluation' algebra eqngr naming program vs t =
968 val (((_, program'), (((vs', ty'), t'), deps)), _) =
969 ensure_value thy algebra eqngr t (NONE, (naming, program));
970 in evaluation' ((original_sorts vs vs', (vs', ty')), t') deps end;
972 fun lift_evaluator thy evaluator' consts algebra eqngr =
974 fun generate_consts thy algebra eqngr =
975 fold_map (ensure_const thy algebra eqngr false);
976 val (consts', (naming, program)) =
977 invoke_generation true thy (algebra, eqngr) generate_consts consts;
978 val evaluation' = evaluator' naming program consts';
979 in lift_evaluation thy evaluation' algebra eqngr naming program end;
981 fun lift_evaluator_simple thy evaluator' consts algebra eqngr =
983 fun generate_consts thy algebra eqngr =
984 fold_map (ensure_const thy algebra eqngr false);
985 val (consts', (naming, program)) =
986 invoke_generation true thy (algebra, eqngr) generate_consts consts;
987 in evaluator' program end;
989 fun static_conv thy consts conv =
990 Code_Preproc.static_conv thy consts (lift_evaluator thy conv consts);
992 fun static_conv_simple thy consts conv =
993 Code_Preproc.static_conv thy consts (lift_evaluator_simple thy conv consts);
995 fun static_value thy postproc consts evaluator =
996 Code_Preproc.static_value thy postproc consts (lift_evaluator thy evaluator consts);
999 (** diagnostic commands **)
1001 fun read_const_exprs thy =
1003 fun consts_of thy' = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
1004 ((snd o #constants o Consts.dest o Sign.consts_of) thy') [];
1005 fun belongs_here thy' c = forall
1006 (fn thy'' => not (Sign.declared_const thy'' c)) (Theory.parents_of thy');
1007 fun consts_of_select thy' = filter (belongs_here thy') (consts_of thy');
1008 fun read_const_expr "_" = ([], consts_of thy)
1009 | read_const_expr s = if String.isSuffix "._" s
1010 then ([], consts_of_select (Context.this_theory thy (unsuffix "._" s)))
1011 else ([Code.read_const thy s], []);
1012 in pairself flat o split_list o map read_const_expr end;
1014 fun code_depgr thy consts =
1016 val (_, eqngr) = Code_Preproc.obtain true thy consts [];
1017 val all_consts = Graph.all_succs eqngr consts;
1018 in Graph.restrict (member (op =) all_consts) eqngr end;
1020 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
1022 fun code_deps thy consts =
1024 val eqngr = code_depgr thy consts;
1025 val constss = Graph.strong_conn eqngr;
1026 val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
1027 Symtab.update (const, consts)) consts) constss;
1028 fun succs consts = consts
1029 |> maps (Graph.immediate_succs eqngr)
1030 |> subtract (op =) consts
1031 |> map (the o Symtab.lookup mapping)
1033 val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
1034 fun namify consts = map (Code.string_of_const thy) consts
1036 val prgr = map (fn (consts, constss) =>
1037 { name = namify consts, ID = namify consts, dir = "", unfold = true,
1038 path = "", parents = map namify constss }) conn;
1039 in Present.display_graph prgr end;
1043 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
1044 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
1049 Outer_Syntax.improper_command @{command_spec "code_thms"}
1050 "print system of code equations for code"
1051 (Scan.repeat1 Parse.term_group
1052 >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
1053 o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
1056 Outer_Syntax.improper_command @{command_spec "code_deps"}
1057 "visualize dependencies of code equations for code"
1058 (Scan.repeat1 Parse.term_group
1059 >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
1060 o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
1067 structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;