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 (_, (Fun (c, ((_, []), _)), _)) => cons c | _ => I) program [];
441 fun map_terms_bottom_up f (t as IConst _) = f t
442 | map_terms_bottom_up f (t as IVar _) = f t
443 | map_terms_bottom_up f (t1 `$ t2) = f
444 (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
445 | map_terms_bottom_up f ((v, ty) `|=> t) = f
446 ((v, ty) `|=> map_terms_bottom_up f t)
447 | map_terms_bottom_up f (ICase (((t, ty), ps), t0)) = f
448 (ICase (((map_terms_bottom_up f t, ty), (map o pairself)
449 (map_terms_bottom_up f) ps), map_terms_bottom_up f t0));
451 fun map_classparam_instances_as_term f =
452 (map o apfst o apsnd) (fn const => case f (IConst const) of IConst const' => const')
454 fun map_terms_stmt f NoStmt = NoStmt
455 | map_terms_stmt f (Fun (c, ((tysm, eqs), case_cong))) = Fun (c, ((tysm, (map o apfst)
456 (fn (ts, t) => (map f ts, f t)) eqs), case_cong))
457 | map_terms_stmt f (stmt as Datatype _) = stmt
458 | map_terms_stmt f (stmt as Datatypecons _) = stmt
459 | map_terms_stmt f (stmt as Class _) = stmt
460 | map_terms_stmt f (stmt as Classrel _) = stmt
461 | map_terms_stmt f (stmt as Classparam _) = stmt
462 | map_terms_stmt f (Classinst (arity, (super_instances, classparam_instances))) =
463 Classinst (arity, (super_instances, (pairself o map_classparam_instances_as_term) f classparam_instances));
465 fun is_cons program name = case Graph.get_node program name
466 of Datatypecons _ => true
469 fun is_case (Fun (_, (_, SOME _))) = true
472 fun labelled_name thy program name =
473 let val ctxt = Proof_Context.init_global thy in
474 case Graph.get_node program name of
475 Fun (c, _) => quote (Code.string_of_const thy c)
476 | Datatype (tyco, _) => "type " ^ quote (Proof_Context.extern_type ctxt tyco)
477 | Datatypecons (c, _) => quote (Code.string_of_const thy c)
478 | Class (class, _) => "class " ^ quote (Proof_Context.extern_class ctxt class)
479 | Classrel (sub, super) =>
481 val Class (sub, _) = Graph.get_node program sub;
482 val Class (super, _) = Graph.get_node program super;
484 quote (Proof_Context.extern_class ctxt sub ^ " < " ^ Proof_Context.extern_class ctxt super)
486 | Classparam (c, _) => quote (Code.string_of_const thy c)
487 | Classinst ((class, (tyco, _)), _) =>
489 val Class (class, _) = Graph.get_node program class;
490 val Datatype (tyco, _) = Graph.get_node program tyco;
492 quote (Proof_Context.extern_type ctxt tyco ^ " :: " ^ Proof_Context.extern_class ctxt class)
496 fun linear_stmts program =
497 rev (Graph.strong_conn program)
498 |> map (AList.make (Graph.get_node program));
500 fun group_stmts thy program =
502 fun is_fun (_, Fun _) = true | is_fun _ = false;
503 fun is_datatypecons (_, Datatypecons _) = true | is_datatypecons _ = false;
504 fun is_datatype (_, Datatype _) = true | is_datatype _ = false;
505 fun is_class (_, Class _) = true | is_class _ = false;
506 fun is_classrel (_, Classrel _) = true | is_classrel _ = false;
507 fun is_classparam (_, Classparam _) = true | is_classparam _ = false;
508 fun is_classinst (_, Classinst _) = true | is_classinst _ = false;
510 if forall (is_datatypecons orf is_datatype) stmts
511 then (filter is_datatype stmts, [], ([], []))
512 else if forall (is_class orf is_classrel orf is_classparam) stmts
513 then ([], filter is_class stmts, ([], []))
514 else if forall (is_fun orf is_classinst) stmts
515 then ([], [], List.partition is_fun stmts)
516 else error ("Illegal mutual dependencies: " ^
517 (commas o map (labelled_name thy program o fst)) stmts)
524 (** translation kernel **)
526 (* generic mechanisms *)
528 fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
530 fun add_dep name = case dep of NONE => I
531 | SOME dep => Graph.add_edge (dep, name);
532 val (name, naming') = case lookup naming thing
533 of SOME name => (name, naming)
534 | NONE => declare thing naming;
536 if can (Graph.get_node program) name
545 |> Graph.default_node (name, NoStmt)
548 |> curry generate (SOME name)
550 |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
555 exception PERMISSIVE of unit;
557 fun translation_error thy permissive some_thm msg sub_msg =
559 then raise PERMISSIVE ()
564 SOME thm => "\n(in code equation " ^ Display.string_of_thm_global thy thm ^ ")"
566 in error (msg ^ err_thm ^ ":\n" ^ sub_msg) end;
568 fun not_wellsorted thy permissive some_thm ty sort e =
570 val err_class = Sorts.class_error (Context.pretty_global thy) e;
572 "Type " ^ Syntax.string_of_typ_global thy ty ^ " not of sort " ^
573 Syntax.string_of_sort_global thy sort;
575 translation_error thy permissive some_thm "Wellsortedness error"
576 (err_typ ^ "\n" ^ err_class)
580 (* inference of type annotations for disambiguation with type classes *)
582 fun mk_tagged_type (true, T) = Type ("", [T])
583 | mk_tagged_type (false, T) = T;
585 fun dest_tagged_type (Type ("", [T])) = (true, T)
586 | dest_tagged_type T = (false, T);
588 val untag_term = map_types (snd o dest_tagged_type);
590 fun tag_term (proj_sort, _) eqngr =
592 val has_sort_constraints = exists (not o null) o map proj_sort o Code_Preproc.sortargs eqngr;
593 fun tag (Const (_, T')) (Const (c, T)) =
595 mk_tagged_type (not (null (Term.add_tvarsT T' [])) andalso has_sort_constraints c, T))
596 | tag (t1 $ u1) (t $ u) = tag t1 t $ tag u1 u
597 | tag (Abs (_, _, t1)) (Abs (x, T, t)) = Abs (x, T, tag t1 t)
598 | tag (Free _) (t as Free _) = t
599 | tag (Var _) (t as Var _) = t
600 | tag (Bound _) (t as Bound _) = t;
605 fun annotate thy algbr eqngr (c, ty) args rhs =
607 val ctxt = Proof_Context.init_global thy |> Config.put Type_Infer_Context.const_sorts false
608 val erase = map_types (fn _ => Type_Infer.anyT [])
609 val reinfer = singleton (Type_Infer_Context.infer_types ctxt)
610 val lhs = list_comb (Const (c, ty), map (map_types Type.strip_sorts o fst) args)
611 val reinferred_rhs = snd (Logic.dest_equals (reinfer (Logic.mk_equals (lhs, erase rhs))))
613 tag_term algbr eqngr reinferred_rhs rhs
616 fun annotate_eqns thy algbr eqngr (c, ty) eqns =
617 map (apfst (fn (args, (rhs, some_abs)) => (args,
618 (annotate thy algbr eqngr (c, ty) args rhs, some_abs)))) eqns
623 fun ensure_tyco thy algbr eqngr permissive tyco =
625 val ((vs, cos), _) = Code.get_type thy tyco;
627 fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
628 ##>> fold_map (fn (c, (vs, tys)) =>
629 ensure_const thy algbr eqngr permissive c
630 ##>> pair (map (unprefix "'" o fst) vs)
631 ##>> fold_map (translate_typ thy algbr eqngr permissive) tys) cos
632 #>> (fn info => Datatype (tyco, info));
633 in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
634 and ensure_const thy algbr eqngr permissive c =
636 fun stmt_datatypecons tyco =
637 ensure_tyco thy algbr eqngr permissive tyco
638 #>> (fn tyco => Datatypecons (c, tyco));
639 fun stmt_classparam class =
640 ensure_class thy algbr eqngr permissive class
641 #>> (fn class => Classparam (c, class));
644 val ((vs, ty), eqns) = Code.equations_of_cert thy cert;
645 val eqns' = annotate_eqns thy algbr eqngr (c, ty) eqns
646 val some_case_cong = Code.get_case_cong thy c;
648 fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
649 ##>> translate_typ thy algbr eqngr permissive ty
650 ##>> translate_eqns thy algbr eqngr permissive eqns'
651 #>> (fn info => Fun (c, (info, some_case_cong)))
653 val stmt_const = case Code.get_type_of_constr_or_abstr thy c
654 of SOME (tyco, _) => stmt_datatypecons tyco
655 | NONE => (case AxClass.class_of_param thy c
656 of SOME class => stmt_classparam class
657 | NONE => stmt_fun (Code_Preproc.cert eqngr c))
658 in ensure_stmt lookup_const (declare_const thy) stmt_const c end
659 and ensure_class thy (algbr as (_, algebra)) eqngr permissive class =
661 val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
662 val cs = #params (AxClass.get_info thy class);
664 fold_map (fn super_class => ensure_class thy algbr eqngr permissive super_class
665 ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)) super_classes
666 ##>> fold_map (fn (c, ty) => ensure_const thy algbr eqngr permissive c
667 ##>> translate_typ thy algbr eqngr permissive ty) cs
668 #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
669 in ensure_stmt lookup_class (declare_class thy) stmt_class class end
670 and ensure_classrel thy algbr eqngr permissive (sub_class, super_class) =
673 ensure_class thy algbr eqngr permissive sub_class
674 ##>> ensure_class thy algbr eqngr permissive super_class
676 in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (sub_class, super_class) end
677 and ensure_inst thy (algbr as (_, algebra)) eqngr permissive (class, tyco) =
679 val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
680 val these_classparams = these o try (#params o AxClass.get_info thy);
681 val classparams = these_classparams class;
682 val further_classparams = maps these_classparams
683 ((Sorts.complete_sort algebra o Sorts.super_classes algebra) class);
684 val vs = Name.invent_names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
685 val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
686 val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
687 Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
688 val arity_typ = Type (tyco, map TFree vs);
689 val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
690 fun translate_super_instance super_class =
691 ensure_class thy algbr eqngr permissive super_class
692 ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)
693 ##>> translate_dicts thy algbr eqngr permissive NONE (arity_typ, [super_class])
694 #>> (fn ((super_class, classrel), [Dict ([], Dict_Const (inst, dss))]) =>
695 (super_class, (classrel, (inst, dss))));
696 fun translate_classparam_instance (c, ty) =
698 val raw_const = Const (c, map_type_tfree (K arity_typ') ty);
699 val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy raw_const);
700 val const = (apsnd Logic.unvarifyT_global o dest_Const o snd
701 o Logic.dest_equals o Thm.prop_of) thm;
703 ensure_const thy algbr eqngr permissive c
704 ##>> translate_const thy algbr eqngr permissive (SOME thm) (const, NONE)
705 #>> (fn (c, IConst const') => ((c, const'), (thm, true)))
708 ensure_class thy algbr eqngr permissive class
709 ##>> ensure_tyco thy algbr eqngr permissive tyco
710 ##>> fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
711 ##>> fold_map translate_super_instance super_classes
712 ##>> fold_map translate_classparam_instance classparams
713 ##>> fold_map translate_classparam_instance further_classparams
714 #>> (fn (((((class, tyco), arity_args), super_instances),
715 classparam_instances), further_classparam_instances) =>
716 Classinst ((class, (tyco, arity_args)), (super_instances,
717 (classparam_instances, further_classparam_instances))));
718 in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
719 and translate_typ thy algbr eqngr permissive (TFree (v, _)) =
720 pair (ITyVar (unprefix "'" v))
721 | translate_typ thy algbr eqngr permissive (Type (tyco, tys)) =
722 ensure_tyco thy algbr eqngr permissive tyco
723 ##>> fold_map (translate_typ thy algbr eqngr permissive) tys
724 #>> (fn (tyco, tys) => tyco `%% tys)
725 and translate_term thy algbr eqngr permissive some_thm (Const (c, ty), some_abs) =
726 translate_app thy algbr eqngr permissive some_thm (((c, ty), []), some_abs)
727 | translate_term thy algbr eqngr permissive some_thm (Free (v, _), some_abs) =
729 | translate_term thy algbr eqngr permissive some_thm (Abs (v, ty, t), some_abs) =
731 val (v', t') = Syntax_Trans.variant_abs (Name.desymbolize false v, ty, t);
732 val v'' = if member (op =) (Term.add_free_names t' []) v'
733 then SOME v' else NONE
735 translate_typ thy algbr eqngr permissive ty
736 ##>> translate_term thy algbr eqngr permissive some_thm (t', some_abs)
737 #>> (fn (ty, t) => (v'', ty) `|=> t)
739 | translate_term thy algbr eqngr permissive some_thm (t as _ $ _, some_abs) =
741 of (Const (c, ty), ts) =>
742 translate_app thy algbr eqngr permissive some_thm (((c, ty), ts), some_abs)
744 translate_term thy algbr eqngr permissive some_thm (t', some_abs)
745 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
746 #>> (fn (t, ts) => t `$$ ts)
747 and translate_eqn thy algbr eqngr permissive ((args, (rhs, some_abs)), (some_thm, proper)) =
748 fold_map (translate_term thy algbr eqngr permissive some_thm) args
749 ##>> translate_term thy algbr eqngr permissive some_thm (rhs, some_abs)
750 #>> rpair (some_thm, proper)
751 and translate_eqns thy algbr eqngr permissive eqns prgrm =
752 prgrm |> fold_map (translate_eqn thy algbr eqngr permissive) eqns
753 handle PERMISSIVE () => ([], prgrm)
754 and translate_const thy algbr eqngr permissive some_thm ((c, ty), some_abs) =
756 val _ = if (case some_abs of NONE => true | SOME abs => not (c = abs))
757 andalso Code.is_abstr thy c
758 then translation_error thy permissive some_thm
759 "Abstraction violation" ("constant " ^ Code.string_of_const thy c)
761 val (annotate, ty') = dest_tagged_type ty
762 val arg_typs = Sign.const_typargs thy (c, ty');
763 val sorts = Code_Preproc.sortargs eqngr c;
764 val (function_typs, body_typ) = Term.strip_type ty';
766 ensure_const thy algbr eqngr permissive c
767 ##>> fold_map (translate_typ thy algbr eqngr permissive) arg_typs
768 ##>> fold_map (translate_dicts thy algbr eqngr permissive some_thm) (arg_typs ~~ sorts)
769 ##>> fold_map (translate_typ thy algbr eqngr permissive) (body_typ :: function_typs)
770 #>> (fn (((c, arg_typs), dss), body_typ :: function_typs) =>
771 IConst (c, (((arg_typs, dss), (function_typs, body_typ)), annotate)))
773 and translate_app_const thy algbr eqngr permissive some_thm ((c_ty, ts), some_abs) =
774 translate_const thy algbr eqngr permissive some_thm (c_ty, some_abs)
775 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
776 #>> (fn (t, ts) => t `$$ ts)
777 and translate_case thy algbr eqngr permissive some_thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
779 fun arg_types num_args ty = fst (chop num_args (binder_types ty));
780 val tys = arg_types num_args (snd c_ty);
781 val ty = nth tys t_pos;
782 fun mk_constr NONE t = NONE
783 | mk_constr (SOME c) t =
785 val n = Code.args_number thy c;
786 in SOME ((c, arg_types n (fastype_of (untag_term t)) ---> ty), n) end;
788 if null case_pats then []
789 else map_filter I (map2 mk_constr case_pats (nth_drop t_pos ts));
790 fun casify naming constrs ty ts =
792 val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
793 fun collapse_clause vs_map ts body =
796 of IConst (c, _) => if member (op =) undefineds c
799 | ICase (((IVar (SOME v), _), subclauses), _) =>
800 if forall (fn (pat', body') => exists_var pat' v
801 orelse not (exists_var body' v)) subclauses
802 then case AList.lookup (op =) vs_map v
803 of SOME i => maps (fn (pat', body') =>
804 collapse_clause (AList.delete (op =) v vs_map)
805 (nth_map i (K pat') ts) body') subclauses
806 | NONE => [(ts, body)]
810 fun mk_clause mk tys t =
812 val (vs, body) = unfold_abs_eta tys t;
813 val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
814 val ts = map (IVar o fst) vs;
815 in map mk (collapse_clause vs_map ts body) end;
816 val t = nth ts t_pos;
817 val ts_clause = nth_drop t_pos ts;
818 val clauses = if null case_pats
819 then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
820 else maps (fn ((constr as IConst (_, ((_, (tys, _)), _)), n), t) =>
821 mk_clause (fn (ts, body) => (constr `$$ ts, body)) (take n tys) t)
822 (constrs ~~ (map_filter (fn (NONE, _) => NONE | (SOME _, t) => SOME t)
823 (case_pats ~~ ts_clause)));
824 in ((t, ty), clauses) end;
826 translate_const thy algbr eqngr permissive some_thm (c_ty, NONE)
827 ##>> fold_map (fn (constr, n) => translate_const thy algbr eqngr permissive some_thm (constr, NONE)
829 ##>> translate_typ thy algbr eqngr permissive ty
830 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
831 #-> (fn (((t, constrs), ty), ts) =>
832 `(fn (_, (naming, _)) => ICase (casify naming constrs ty ts, t `$$ ts)))
834 and translate_app_case thy algbr eqngr permissive some_thm (case_scheme as (num_args, _)) ((c, ty), ts) =
835 if length ts < num_args then
838 val tys = (take (num_args - k) o drop k o fst o strip_type) ty;
839 val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
840 val vs = Name.invent_names ctxt "a" tys;
842 fold_map (translate_typ thy algbr eqngr permissive) tys
843 ##>> translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts @ map Free vs)
844 #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
846 else if length ts > num_args then
847 translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), take num_args ts)
848 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) (drop num_args ts)
849 #>> (fn (t, ts) => t `$$ ts)
851 translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts)
852 and translate_app thy algbr eqngr permissive some_thm (c_ty_ts as ((c, _), _), some_abs) =
853 case Code.get_case_scheme thy c
854 of SOME case_scheme => translate_app_case thy algbr eqngr permissive some_thm case_scheme c_ty_ts
855 | NONE => translate_app_const thy algbr eqngr permissive some_thm (c_ty_ts, some_abs)
856 and translate_tyvar_sort thy (algbr as (proj_sort, _)) eqngr permissive (v, sort) =
857 fold_map (ensure_class thy algbr eqngr permissive) (proj_sort sort)
858 #>> (fn sort => (unprefix "'" v, sort))
859 and translate_dicts thy (algbr as (proj_sort, algebra)) eqngr permissive some_thm (ty, sort) =
861 datatype typarg_witness =
862 Weakening of (class * class) list * plain_typarg_witness
863 and plain_typarg_witness =
864 Global of (class * string) * typarg_witness list list
865 | Local of string * (int * sort);
866 fun class_relation ((Weakening (classrels, x)), sub_class) super_class =
867 Weakening ((sub_class, super_class) :: classrels, x);
868 fun type_constructor (tyco, _) dss class =
869 Weakening ([], Global ((class, tyco), (map o map) fst dss));
870 fun type_variable (TFree (v, sort)) =
872 val sort' = proj_sort sort;
873 in map_index (fn (n, class) => (Weakening ([], Local (v, (n, sort'))), class)) sort' end;
874 val typarg_witnesses = Sorts.of_sort_derivation algebra
875 {class_relation = K (Sorts.classrel_derivation algebra class_relation),
876 type_constructor = type_constructor,
877 type_variable = type_variable} (ty, proj_sort sort)
878 handle Sorts.CLASS_ERROR e => not_wellsorted thy permissive some_thm ty sort e;
879 fun mk_dict (Weakening (classrels, x)) =
880 fold_map (ensure_classrel thy algbr eqngr permissive) classrels
883 and mk_plain_dict (Global (inst, dss)) =
884 ensure_inst thy algbr eqngr permissive inst
885 ##>> (fold_map o fold_map) mk_dict dss
886 #>> (fn (inst, dss) => Dict_Const (inst, dss))
887 | mk_plain_dict (Local (v, (n, sort))) =
888 pair (Dict_Var (unprefix "'" v, (n, length sort)))
889 in fold_map mk_dict typarg_witnesses end;
894 structure Program = Code_Data
896 type T = naming * program;
897 val empty = (empty_naming, Graph.empty);
900 fun invoke_generation ignore_cache thy (algebra, eqngr) generate thing =
901 Program.change_yield (if ignore_cache then NONE else SOME thy)
902 (fn naming_program => (NONE, naming_program)
903 |> generate thy algebra eqngr thing
904 |-> (fn thing => fn (_, naming_program) => (thing, naming_program)));
907 (* program generation *)
909 fun consts_program thy permissive consts =
911 fun project_consts consts (naming, program) =
912 if permissive then (consts, (naming, program))
913 else (consts, (naming, Graph.restrict
914 (member (op =) (Graph.all_succs program consts)) program));
915 fun generate_consts thy algebra eqngr =
916 fold_map (ensure_const thy algebra eqngr permissive);
918 invoke_generation permissive thy (Code_Preproc.obtain false thy consts [])
919 generate_consts consts
924 (* value evaluation *)
926 fun ensure_value thy algbr eqngr t =
928 val ty = fastype_of t;
929 val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
930 o dest_TFree))) t [];
931 val t' = annotate thy algbr eqngr (Term.dummy_patternN, ty) [] t;
933 fold_map (translate_tyvar_sort thy algbr eqngr false) vs
934 ##>> translate_typ thy algbr eqngr false ty
935 ##>> translate_term thy algbr eqngr false NONE (t', NONE)
936 #>> (fn ((vs, ty), t) => Fun
937 (Term.dummy_patternN, (((vs, ty), [(([], t), (NONE, true))]), NONE)));
938 fun term_value (dep, (naming, program1)) =
940 val Fun (_, ((vs_ty, [(([], t), _)]), _)) =
941 Graph.get_node program1 Term.dummy_patternN;
942 val deps = Graph.immediate_succs program1 Term.dummy_patternN;
943 val program2 = Graph.del_node Term.dummy_patternN program1;
944 val deps_all = Graph.all_succs program2 deps;
945 val program3 = Graph.restrict (member (op =) deps_all) program2;
946 in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
948 ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
953 fun original_sorts vs =
954 map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v));
956 fun dynamic_evaluator thy evaluator algebra eqngr vs t =
958 val (((naming, program), (((vs', ty'), t'), deps)), _) =
959 invoke_generation false thy (algebra, eqngr) ensure_value t;
960 in evaluator naming program ((original_sorts vs vs', (vs', ty')), t') deps end;
962 fun dynamic_conv thy evaluator =
963 Code_Preproc.dynamic_conv thy (dynamic_evaluator thy evaluator);
965 fun dynamic_value thy postproc evaluator =
966 Code_Preproc.dynamic_value thy postproc (dynamic_evaluator thy evaluator);
968 fun lift_evaluation thy evaluation' algebra eqngr naming program vs t =
970 val (((_, _), (((vs', ty'), t'), deps)), _) =
971 ensure_value thy algebra eqngr t (NONE, (naming, program));
972 in evaluation' ((original_sorts vs vs', (vs', ty')), t') deps end;
974 fun lift_evaluator thy evaluator' consts algebra eqngr =
976 fun generate_consts thy algebra eqngr =
977 fold_map (ensure_const thy algebra eqngr false);
978 val (consts', (naming, program)) =
979 invoke_generation true thy (algebra, eqngr) generate_consts consts;
980 val evaluation' = evaluator' naming program consts';
981 in lift_evaluation thy evaluation' algebra eqngr naming program end;
983 fun lift_evaluator_simple thy evaluator' consts algebra eqngr =
985 fun generate_consts thy algebra eqngr =
986 fold_map (ensure_const thy algebra eqngr false);
987 val (_, (_, program)) =
988 invoke_generation true thy (algebra, eqngr) generate_consts consts;
989 in evaluator' program end;
991 fun static_conv thy consts conv =
992 Code_Preproc.static_conv thy consts (lift_evaluator thy conv consts);
994 fun static_conv_simple thy consts conv =
995 Code_Preproc.static_conv thy consts (lift_evaluator_simple thy conv consts);
997 fun static_value thy postproc consts evaluator =
998 Code_Preproc.static_value thy postproc consts (lift_evaluator thy evaluator consts);
1001 (** diagnostic commands **)
1003 fun read_const_exprs thy =
1005 fun consts_of thy' = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
1006 ((snd o #constants o Consts.dest o Sign.consts_of) thy') [];
1007 fun belongs_here thy' c = forall
1008 (fn thy'' => not (Sign.declared_const thy'' c)) (Theory.parents_of thy');
1009 fun consts_of_select thy' = filter (belongs_here thy') (consts_of thy');
1010 fun read_const_expr "_" = ([], consts_of thy)
1011 | read_const_expr s = if String.isSuffix "._" s
1012 then ([], consts_of_select (Context.this_theory thy (unsuffix "._" s)))
1013 else ([Code.read_const thy s], []);
1014 in pairself flat o split_list o map read_const_expr end;
1016 fun code_depgr thy consts =
1018 val (_, eqngr) = Code_Preproc.obtain true thy consts [];
1019 val all_consts = Graph.all_succs eqngr consts;
1020 in Graph.restrict (member (op =) all_consts) eqngr end;
1022 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
1024 fun code_deps thy consts =
1026 val eqngr = code_depgr thy consts;
1027 val constss = Graph.strong_conn eqngr;
1028 val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
1029 Symtab.update (const, consts)) consts) constss;
1030 fun succs consts = consts
1031 |> maps (Graph.immediate_succs eqngr)
1032 |> subtract (op =) consts
1033 |> map (the o Symtab.lookup mapping)
1035 val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
1036 fun namify consts = map (Code.string_of_const thy) consts
1038 val prgr = map (fn (consts, constss) =>
1039 { name = namify consts, ID = namify consts, dir = "", unfold = true,
1040 path = "", parents = map namify constss }) conn;
1041 in Present.display_graph prgr end;
1045 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
1046 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
1051 Outer_Syntax.improper_command @{command_spec "code_thms"}
1052 "print system of code equations for code"
1053 (Scan.repeat1 Parse.term_group
1054 >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
1055 o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
1058 Outer_Syntax.improper_command @{command_spec "code_deps"}
1059 "visualize dependencies of code equations for code"
1060 (Scan.repeat1 Parse.term_group
1061 >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
1062 o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
1069 structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;