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 DictConst of string * dict list list
19 | DictVar of string list * (vname * (int * int));
21 `%% of string * itype list
23 type const = string * ((itype list * dict list list) * itype list (*types of arguments*))
28 | `|-> of (vname * itype) * iterm
29 | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
30 (*((term, type), [(selector pattern, body term )]), primitive term)*)
31 val `$$ : iterm * iterm list -> iterm;
32 val `|--> : (vname * itype) list * iterm -> iterm;
33 type typscheme = (vname * sort) list * itype;
36 signature CODE_THINGOL =
38 include BASIC_CODE_THINGOL
39 val unfoldl: ('a -> ('a * 'b) option) -> 'a -> 'a * 'b list
40 val unfoldr: ('a -> ('b * 'a) option) -> 'a -> 'b list * 'a
41 val unfold_fun: itype -> itype list * itype
42 val unfold_app: iterm -> iterm * iterm list
43 val split_abs: iterm -> (((vname * iterm option) * itype) * iterm) option
44 val unfold_abs: iterm -> ((vname * iterm option) * itype) list * iterm
45 val split_let: iterm -> (((iterm * itype) * iterm) * iterm) option
46 val unfold_let: iterm -> ((iterm * itype) * iterm) list * iterm
47 val unfold_const_app: iterm -> (const * iterm list) option
48 val collapse_let: ((vname * itype) * iterm) * iterm
49 -> (iterm * itype) * (iterm * iterm) list
50 val eta_expand: int -> const * iterm list -> iterm
51 val contains_dictvar: iterm -> bool
52 val locally_monomorphic: iterm -> bool
53 val fold_constnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
54 val fold_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
55 val fold_unbound_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
58 val empty_naming: naming
59 val lookup_class: naming -> class -> string option
60 val lookup_classrel: naming -> class * class -> string option
61 val lookup_tyco: naming -> string -> string option
62 val lookup_instance: naming -> class * string -> string option
63 val lookup_const: naming -> string -> string option
64 val ensure_declared_const: theory -> string -> naming -> string * naming
68 | Fun of string * (typscheme * ((iterm list * iterm) * (thm * bool)) list)
69 | Datatype of string * ((vname * sort) list * (string * itype list) list)
70 | Datatypecons of string * string
71 | Class of class * (vname * ((class * string) list * (string * itype) list))
72 | Classrel of class * class
73 | Classparam of string * class
74 | Classinst of (class * (string * (vname * sort) list))
75 * ((class * (string * (string * dict list list))) list
76 * ((string * const) * (thm * bool)) list)
77 type program = stmt Graph.T
78 val empty_funs: program -> string list
79 val map_terms_bottom_up: (iterm -> iterm) -> iterm -> iterm
80 val map_terms_stmt: (iterm -> iterm) -> stmt -> stmt
81 val is_cons: program -> string -> bool
82 val contr_classparam_typs: program -> string -> itype option list
84 val read_const_exprs: theory -> string list -> string list * string list
85 val consts_program: theory -> string list -> string list * (naming * program)
86 val cached_program: theory -> naming * program
87 val eval_conv: theory -> (sort -> sort)
88 -> (naming -> program -> ((string * sort) list * typscheme) * iterm -> string list -> cterm -> thm)
90 val eval: theory -> (sort -> sort) -> ((term -> term) -> 'a -> 'a)
91 -> (naming -> program -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
95 structure Code_Thingol: CODE_THINGOL =
104 let val (x', xs') = unfoldl dest x1 in (x', xs' @ [x2]) end;
110 let val (xs', x') = unfoldr dest x2 in (x1::xs', x') end;
113 (** language core - types, terms **)
118 DictConst of string * dict list list
119 | DictVar of string list * (vname * (int * int));
122 `%% of string * itype list
125 type const = string * ((itype list * dict list list) * itype list (*types of arguments*))
130 | `$ of iterm * iterm
131 | `|-> of (vname * itype) * iterm
132 | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
133 (*see also signature*)
135 val op `$$ = Library.foldl (op `$);
136 val op `|--> = Library.foldr (op `|->);
138 val unfold_app = unfoldl
139 (fn op `$ t => SOME t
143 (fn (v, ty) `|-> (t as ICase (((IVar w, _), [(p, t')]), _)) =>
144 if v = w then SOME (((v, SOME p), ty), t') else SOME (((v, NONE), ty), t)
145 | (v, ty) `|-> t => SOME (((v, NONE), ty), t)
148 val unfold_abs = unfoldr split_abs;
151 (fn ICase (((td, ty), [(p, t)]), _) => SOME (((p, ty), td), t)
154 val unfold_let = unfoldr split_let;
156 fun unfold_const_app t =
158 of (IConst c, ts) => SOME (c, ts)
161 fun fold_aiterms f (t as IConst _) = f t
162 | fold_aiterms f (t as IVar _) = f t
163 | fold_aiterms f (t1 `$ t2) = fold_aiterms f t1 #> fold_aiterms f t2
164 | fold_aiterms f (t as _ `|-> t') = f t #> fold_aiterms f t'
165 | fold_aiterms f (ICase (_, t)) = fold_aiterms f t;
167 fun fold_constnames f =
169 fun add (IConst (c, _)) = f c
171 in fold_aiterms add end;
173 fun fold_varnames f =
175 fun add (IVar v) = f v
176 | add ((v, _) `|-> _) = f v
178 in fold_aiterms add end;
180 fun fold_unbound_varnames f =
182 fun add _ (IConst _) = I
183 | add vs (IVar v) = if not (member (op =) vs v) then f v else I
184 | add vs (t1 `$ t2) = add vs t1 #> add vs t2
185 | add vs ((v, _) `|-> t) = add (insert (op =) v vs) t
186 | add vs (ICase (_, t)) = add vs t;
189 fun collapse_let (((v, ty), se), be as ICase (((IVar w, _), ds), _)) =
191 fun exists_v t = fold_unbound_varnames (fn w => fn b =>
192 b orelse v = w) t false;
193 in if v = w andalso forall (fn (t1, t2) =>
194 exists_v t1 orelse not (exists_v t2)) ds
196 else ((se, ty), [(IVar v, be)])
198 | collapse_let (((v, ty), se), be) =
199 ((se, ty), [(IVar v, be)])
201 fun eta_expand k (c as (_, (_, tys)), ts) =
205 val ctxt = (fold o fold_varnames) Name.declare ts Name.context;
206 val vs_tys = Name.names ctxt "a" ((curry Library.take l o curry Library.drop j) tys);
207 in vs_tys `|--> IConst c `$$ ts @ map (fn (v, _) => IVar v) vs_tys end;
209 fun contains_dictvar t =
211 fun contains (DictConst (_, dss)) = (fold o fold) contains dss
212 | contains (DictVar _) = K true;
215 (fn IConst (_, ((_, dss), _)) => (fold o fold) contains dss | _ => I) t false
218 fun locally_monomorphic (IConst _) = false
219 | locally_monomorphic (IVar _) = true
220 | locally_monomorphic (t `$ _) = locally_monomorphic t
221 | locally_monomorphic (_ `|-> t) = locally_monomorphic t
222 | locally_monomorphic (ICase ((_, ds), _)) = exists (locally_monomorphic o snd) ds;
230 fun thyname_of thy f x = the (AList.lookup (op =) (f x) Markup.theory_nameN);
231 fun thyname_of_class thy =
232 thyname_of thy (ProofContext.query_class (ProofContext.init thy));
233 fun thyname_of_tyco thy =
234 thyname_of thy (Type.the_tags (Sign.tsig_of thy));
235 fun thyname_of_instance thy inst = case AxClass.arity_property thy inst Markup.theory_nameN
236 of [] => error ("no such instance: " ^ quote (snd inst ^ " :: " ^ fst inst))
237 | thyname :: _ => thyname;
238 fun thyname_of_const thy c = case AxClass.class_of_param thy c
239 of SOME class => thyname_of_class thy class
240 | NONE => (case Code.get_datatype_of_constr thy c
241 of SOME dtco => thyname_of_tyco thy dtco
242 | NONE => thyname_of thy (Consts.the_tags (Sign.consts_of thy)) c);
243 fun purify_base "op &" = "and"
244 | purify_base "op |" = "or"
245 | purify_base "op -->" = "implies"
246 | purify_base "op :" = "member"
247 | purify_base "op =" = "eq"
248 | purify_base "*" = "product"
249 | purify_base "+" = "sum"
250 | purify_base s = Name.desymbolize false s;
251 fun namify thy get_basename get_thyname name =
253 val prefix = get_thyname thy name;
254 val base = (purify_base o get_basename) name;
255 in Long_Name.append prefix base end;
258 fun namify_class thy = namify thy Long_Name.base_name thyname_of_class;
259 fun namify_classrel thy = namify thy (fn (class1, class2) =>
260 Long_Name.base_name class2 ^ "_" ^ Long_Name.base_name class1) (fn thy => thyname_of_class thy o fst);
261 (*order fits nicely with composed projections*)
262 fun namify_tyco thy "fun" = "Pure.fun"
263 | namify_tyco thy tyco = namify thy Long_Name.base_name thyname_of_tyco tyco;
264 fun namify_instance thy = namify thy (fn (class, tyco) =>
265 Long_Name.base_name class ^ "_" ^ Long_Name.base_name tyco) thyname_of_instance;
266 fun namify_const thy = namify thy Long_Name.base_name thyname_of_const;
273 datatype naming = Naming of {
274 class: class Symtab.table * Name.context,
275 classrel: string Symreltab.table * Name.context,
276 tyco: string Symtab.table * Name.context,
277 instance: string Symreltab.table * Name.context,
278 const: string Symtab.table * Name.context
281 fun dest_Naming (Naming naming) = naming;
283 val empty_naming = Naming {
284 class = (Symtab.empty, Name.context),
285 classrel = (Symreltab.empty, Name.context),
286 tyco = (Symtab.empty, Name.context),
287 instance = (Symreltab.empty, Name.context),
288 const = (Symtab.empty, Name.context)
292 fun mk_naming (class, classrel, tyco, instance, const) =
293 Naming { class = class, classrel = classrel,
294 tyco = tyco, instance = instance, const = const };
295 fun map_naming f (Naming { class, classrel, tyco, instance, const }) =
296 mk_naming (f (class, classrel, tyco, instance, const));
298 fun map_class f = map_naming
299 (fn (class, classrel, tyco, inst, const) =>
300 (f class, classrel, tyco, inst, const));
301 fun map_classrel f = map_naming
302 (fn (class, classrel, tyco, inst, const) =>
303 (class, f classrel, tyco, inst, const));
304 fun map_tyco f = map_naming
305 (fn (class, classrel, tyco, inst, const) =>
306 (class, classrel, f tyco, inst, const));
307 fun map_instance f = map_naming
308 (fn (class, classrel, tyco, inst, const) =>
309 (class, classrel, tyco, f inst, const));
310 fun map_const f = map_naming
311 (fn (class, classrel, tyco, inst, const) =>
312 (class, classrel, tyco, inst, f const));
315 fun add_variant update (thing, name) (tab, used) =
317 val (name', used') = yield_singleton Name.variants name used;
318 val tab' = update (thing, name') tab;
319 in (tab', used') end;
321 fun declare thy mapp lookup update namify thing =
322 mapp (add_variant update (thing, namify thy thing))
323 #> `(fn naming => the (lookup naming thing));
326 (* lookup and declare *)
330 val suffix_class = "class";
331 val suffix_classrel = "classrel"
332 val suffix_tyco = "tyco";
333 val suffix_instance = "inst";
334 val suffix_const = "const";
336 fun add_suffix nsp NONE = NONE
337 | add_suffix nsp (SOME name) = SOME (Long_Name.append name nsp);
341 val lookup_class = add_suffix suffix_class
342 oo Symtab.lookup o fst o #class o dest_Naming;
343 val lookup_classrel = add_suffix suffix_classrel
344 oo Symreltab.lookup o fst o #classrel o dest_Naming;
345 val lookup_tyco = add_suffix suffix_tyco
346 oo Symtab.lookup o fst o #tyco o dest_Naming;
347 val lookup_instance = add_suffix suffix_instance
348 oo Symreltab.lookup o fst o #instance o dest_Naming;
349 val lookup_const = add_suffix suffix_const
350 oo Symtab.lookup o fst o #const o dest_Naming;
352 fun declare_class thy = declare thy map_class
353 lookup_class Symtab.update_new namify_class;
354 fun declare_classrel thy = declare thy map_classrel
355 lookup_classrel Symreltab.update_new namify_classrel;
356 fun declare_tyco thy = declare thy map_tyco
357 lookup_tyco Symtab.update_new namify_tyco;
358 fun declare_instance thy = declare thy map_instance
359 lookup_instance Symreltab.update_new namify_instance;
360 fun declare_const thy = declare thy map_const
361 lookup_const Symtab.update_new namify_const;
363 fun ensure_declared_const thy const naming =
364 case lookup_const naming const
365 of SOME const' => (const', naming)
366 | NONE => declare_const thy const naming;
368 val unfold_fun = unfoldr
369 (fn "Pure.fun.tyco" `%% [ty1, ty2] => SOME (ty1, ty2)
370 | _ => NONE); (*depends on suffix_tyco and namify_tyco!*)
375 (** statements, abstract programs **)
377 type typscheme = (vname * sort) list * itype;
380 | Fun of string * (typscheme * ((iterm list * iterm) * (thm * bool)) list)
381 | Datatype of string * ((vname * sort) list * (string * itype list) list)
382 | Datatypecons of string * string
383 | Class of class * (vname * ((class * string) list * (string * itype) list))
384 | Classrel of class * class
385 | Classparam of string * class
386 | Classinst of (class * (string * (vname * sort) list))
387 * ((class * (string * (string * dict list list))) list
388 * ((string * const) * (thm * bool)) list);
390 type program = stmt Graph.T;
392 fun empty_funs program =
393 Graph.fold (fn (name, (Fun (c, (_, [])), _)) => cons c
394 | _ => I) program [];
396 fun map_terms_bottom_up f (t as IConst _) = f t
397 | map_terms_bottom_up f (t as IVar _) = f t
398 | map_terms_bottom_up f (t1 `$ t2) = f
399 (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
400 | map_terms_bottom_up f ((v, ty) `|-> t) = f
401 ((v, ty) `|-> map_terms_bottom_up f t)
402 | map_terms_bottom_up f (ICase (((t, ty), ps), t0)) = f
403 (ICase (((map_terms_bottom_up f t, ty), (map o pairself)
404 (map_terms_bottom_up f) ps), map_terms_bottom_up f t0));
406 fun map_terms_stmt f NoStmt = NoStmt
407 | map_terms_stmt f (Fun (c, (tysm, eqs))) = Fun (c, (tysm, (map o apfst)
408 (fn (ts, t) => (map f ts, f t)) eqs))
409 | map_terms_stmt f (stmt as Datatype _) = stmt
410 | map_terms_stmt f (stmt as Datatypecons _) = stmt
411 | map_terms_stmt f (stmt as Class _) = stmt
412 | map_terms_stmt f (stmt as Classrel _) = stmt
413 | map_terms_stmt f (stmt as Classparam _) = stmt
414 | map_terms_stmt f (Classinst (arity, (superarities, classparms))) =
415 Classinst (arity, (superarities, (map o apfst o apsnd) (fn const =>
416 case f (IConst const) of IConst const' => const') classparms));
418 fun is_cons program name = case Graph.get_node program name
419 of Datatypecons _ => true
422 fun contr_classparam_typs program name = case Graph.get_node program name
423 of Classparam (_, class) => let
424 val Class (_, (_, (_, params))) = Graph.get_node program class;
425 val SOME ty = AList.lookup (op =) params name;
426 val (tys, res_ty) = unfold_fun ty;
427 fun no_tyvar (_ `%% tys) = forall no_tyvar tys
428 | no_tyvar (ITyVar _) = false;
429 in if no_tyvar res_ty
430 then map (fn ty => if no_tyvar ty then NONE else SOME ty) tys
436 (** translation kernel **)
438 (* generic mechanisms *)
440 fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
442 fun add_dep name = case dep of NONE => I
443 | SOME dep => Graph.add_edge (dep, name);
444 val (name, naming') = case lookup naming thing
445 of SOME name => (name, naming)
446 | NONE => declare thing naming;
447 in case try (Graph.get_node program) name
448 of SOME stmt => program
454 |> Graph.default_node (name, NoStmt)
457 |> curry generate (SOME name)
459 |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
464 fun not_wellsorted thy thm ty sort e =
466 val err_class = Sorts.class_error (Syntax.pp_global thy) e;
467 val err_thm = case thm
468 of SOME thm => "\n(in code equation " ^ Display.string_of_thm thm ^ ")" | NONE => "";
469 val err_typ = "Type " ^ Syntax.string_of_typ_global thy ty ^ " not of sort "
470 ^ Syntax.string_of_sort_global thy sort;
471 in error ("Wellsortedness error" ^ err_thm ^ ":\n" ^ err_typ ^ "\n" ^ err_class) end;
476 fun ensure_tyco thy algbr funcgr tyco =
480 val (vs, cos) = Code.get_datatype thy tyco;
482 fold_map (translate_tyvar_sort thy algbr funcgr) vs
483 ##>> fold_map (fn (c, tys) =>
484 ensure_const thy algbr funcgr c
485 ##>> fold_map (translate_typ thy algbr funcgr) tys) cos
486 #>> (fn info => Datatype (tyco, info))
488 in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
489 and ensure_const thy algbr funcgr c =
491 fun stmt_datatypecons tyco =
492 ensure_tyco thy algbr funcgr tyco
493 #>> (fn tyco => Datatypecons (c, tyco));
494 fun stmt_classparam class =
495 ensure_class thy algbr funcgr class
496 #>> (fn class => Classparam (c, class));
497 fun stmt_fun ((vs, ty), raw_thms) =
499 val thms = if null (Term.add_tfreesT ty []) orelse (null o fst o strip_type) ty
501 else (map o apfst) (Code.expand_eta thy 1) raw_thms;
503 fold_map (translate_tyvar_sort thy algbr funcgr) vs
504 ##>> translate_typ thy algbr funcgr ty
505 ##>> fold_map (translate_eq thy algbr funcgr) thms
506 #>> (fn info => Fun (c, info))
508 val stmt_const = case Code.get_datatype_of_constr thy c
509 of SOME tyco => stmt_datatypecons tyco
510 | NONE => (case AxClass.class_of_param thy c
511 of SOME class => stmt_classparam class
512 | NONE => stmt_fun (Code_Preproc.typ funcgr c, Code_Preproc.eqns funcgr c))
513 in ensure_stmt lookup_const (declare_const thy) stmt_const c end
514 and ensure_class thy (algbr as (_, algebra)) funcgr class =
516 val superclasses = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
517 val cs = #params (AxClass.get_info thy class);
519 fold_map (fn superclass => ensure_class thy algbr funcgr superclass
520 ##>> ensure_classrel thy algbr funcgr (class, superclass)) superclasses
521 ##>> fold_map (fn (c, ty) => ensure_const thy algbr funcgr c
522 ##>> translate_typ thy algbr funcgr ty) cs
523 #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
524 in ensure_stmt lookup_class (declare_class thy) stmt_class class end
525 and ensure_classrel thy algbr funcgr (subclass, superclass) =
528 ensure_class thy algbr funcgr subclass
529 ##>> ensure_class thy algbr funcgr superclass
531 in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (subclass, superclass) end
532 and ensure_inst thy (algbr as (_, algebra)) funcgr (class, tyco) =
534 val superclasses = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
535 val classparams = these (try (#params o AxClass.get_info thy) class);
536 val vs = Name.names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
537 val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
538 val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
539 Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
540 val arity_typ = Type (tyco, map TFree vs);
541 val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
542 fun translate_superarity superclass =
543 ensure_class thy algbr funcgr superclass
544 ##>> ensure_classrel thy algbr funcgr (class, superclass)
545 ##>> translate_dicts thy algbr funcgr NONE (arity_typ, [superclass])
546 #>> (fn ((superclass, classrel), [DictConst (inst, dss)]) =>
547 (superclass, (classrel, (inst, dss))));
548 fun translate_classparam_inst (c, ty) =
550 val c_inst = Const (c, map_type_tfree (K arity_typ') ty);
551 val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy c_inst);
552 val c_ty = (apsnd Logic.unvarifyT o dest_Const o snd
553 o Logic.dest_equals o Thm.prop_of) thm;
555 ensure_const thy algbr funcgr c
556 ##>> translate_const thy algbr funcgr (SOME thm) c_ty
557 #>> (fn (c, IConst c_inst) => ((c, c_inst), (thm, true)))
560 ensure_class thy algbr funcgr class
561 ##>> ensure_tyco thy algbr funcgr tyco
562 ##>> fold_map (translate_tyvar_sort thy algbr funcgr) vs
563 ##>> fold_map translate_superarity superclasses
564 ##>> fold_map translate_classparam_inst classparams
565 #>> (fn ((((class, tyco), arity), superarities), classparams) =>
566 Classinst ((class, (tyco, arity)), (superarities, classparams)));
567 in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
568 and translate_typ thy algbr funcgr (TFree (v, _)) =
569 pair (ITyVar (unprefix "'" v))
570 | translate_typ thy algbr funcgr (Type (tyco, tys)) =
571 ensure_tyco thy algbr funcgr tyco
572 ##>> fold_map (translate_typ thy algbr funcgr) tys
573 #>> (fn (tyco, tys) => tyco `%% tys)
574 and translate_term thy algbr funcgr thm (Const (c, ty)) =
575 translate_app thy algbr funcgr thm ((c, ty), [])
576 | translate_term thy algbr funcgr thm (Free (v, _)) =
578 | translate_term thy algbr funcgr thm (Abs (abs as (_, ty, _))) =
580 val (v, t) = Syntax.variant_abs abs;
582 translate_typ thy algbr funcgr ty
583 ##>> translate_term thy algbr funcgr thm t
584 #>> (fn (ty, t) => (v, ty) `|-> t)
586 | translate_term thy algbr funcgr thm (t as _ $ _) =
588 of (Const (c, ty), ts) =>
589 translate_app thy algbr funcgr thm ((c, ty), ts)
591 translate_term thy algbr funcgr thm t'
592 ##>> fold_map (translate_term thy algbr funcgr thm) ts
593 #>> (fn (t, ts) => t `$$ ts)
594 and translate_eq thy algbr funcgr (thm, proper) =
596 val (args, rhs) = (apfst (snd o strip_comb) o Logic.dest_equals
597 o Logic.unvarify o prop_of) thm;
599 fold_map (translate_term thy algbr funcgr (SOME thm)) args
600 ##>> translate_term thy algbr funcgr (SOME thm) rhs
601 #>> rpair (thm, proper)
603 and translate_const thy algbr funcgr thm (c, ty) =
605 val tys = Sign.const_typargs thy (c, ty);
606 val sorts = (map snd o fst o Code_Preproc.typ funcgr) c;
607 val tys_args = (fst o Term.strip_type) ty;
609 ensure_const thy algbr funcgr c
610 ##>> fold_map (translate_typ thy algbr funcgr) tys
611 ##>> fold_map (translate_dicts thy algbr funcgr thm) (tys ~~ sorts)
612 ##>> fold_map (translate_typ thy algbr funcgr) tys_args
613 #>> (fn (((c, tys), iss), tys_args) => IConst (c, ((tys, iss), tys_args)))
615 and translate_app_const thy algbr funcgr thm (c_ty, ts) =
616 translate_const thy algbr funcgr thm c_ty
617 ##>> fold_map (translate_term thy algbr funcgr thm) ts
618 #>> (fn (t, ts) => t `$$ ts)
619 and translate_case thy algbr funcgr thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
621 val (tys, _) = (chop num_args o fst o strip_type o snd) c_ty;
622 val t = nth ts t_pos;
623 val ty = nth tys t_pos;
624 val ts_clause = nth_drop t_pos ts;
625 fun mk_clause (co, num_co_args) t =
627 val (vs, body) = Term.strip_abs_eta num_co_args t;
628 val not_undefined = case body
629 of (Const (c, _)) => not (Code.is_undefined thy c)
631 val pat = list_comb (Const (co, map snd vs ---> ty), map Free vs);
632 in (not_undefined, (pat, body)) end;
633 val clauses = if null case_pats then let val ([v_ty], body) =
634 Term.strip_abs_eta 1 (the_single ts_clause)
635 in [(true, (Free v_ty, body))] end
636 else map (uncurry mk_clause)
637 (AList.make (Code.no_args thy) case_pats ~~ ts_clause);
638 fun retermify ty (_, (IVar x, body)) =
640 | retermify _ (_, (pat, body)) =
642 val (IConst (_, (_, tys)), ts) = unfold_app pat;
643 val vs = map2 (fn IVar x => fn ty => (x, ty)) ts tys;
644 in vs `|--> body end;
645 fun mk_icase const t ty clauses =
647 val (ts1, ts2) = chop t_pos (map (retermify ty) clauses);
649 ICase (((t, ty), map_filter (fn (b, d) => if b then SOME d else NONE) clauses),
650 const `$$ (ts1 @ t :: ts2))
653 translate_const thy algbr funcgr thm c_ty
654 ##>> translate_term thy algbr funcgr thm t
655 ##>> translate_typ thy algbr funcgr ty
656 ##>> fold_map (fn (b, (pat, body)) => translate_term thy algbr funcgr thm pat
657 ##>> translate_term thy algbr funcgr thm body
659 #>> (fn (((const, t), ty), ds) => mk_icase const t ty ds)
661 and translate_app_case thy algbr funcgr thm (case_scheme as (num_args, _)) ((c, ty), ts) =
662 if length ts < num_args then
665 val tys = (curry Library.take (num_args - k) o curry Library.drop k o fst o strip_type) ty;
666 val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
667 val vs = Name.names ctxt "a" tys;
669 fold_map (translate_typ thy algbr funcgr) tys
670 ##>> translate_case thy algbr funcgr thm case_scheme ((c, ty), ts @ map Free vs)
671 #>> (fn (tys, t) => map2 (fn (v, _) => pair v) vs tys `|--> t)
673 else if length ts > num_args then
674 translate_case thy algbr funcgr thm case_scheme ((c, ty), Library.take (num_args, ts))
675 ##>> fold_map (translate_term thy algbr funcgr thm) (Library.drop (num_args, ts))
676 #>> (fn (t, ts) => t `$$ ts)
678 translate_case thy algbr funcgr thm case_scheme ((c, ty), ts)
679 and translate_app thy algbr funcgr thm (c_ty_ts as ((c, _), _)) =
680 case Code.get_case_scheme thy c
681 of SOME case_scheme => translate_app_case thy algbr funcgr thm case_scheme c_ty_ts
682 | NONE => translate_app_const thy algbr funcgr thm c_ty_ts
683 and translate_tyvar_sort thy (algbr as (proj_sort, _)) funcgr (v, sort) =
684 fold_map (ensure_class thy algbr funcgr) (proj_sort sort)
685 #>> (fn sort => (unprefix "'" v, sort))
686 and translate_dicts thy (algbr as (proj_sort, algebra)) funcgr thm (ty, sort) =
688 val pp = Syntax.pp_global thy;
690 Global of (class * string) * typarg list list
691 | Local of (class * class) list * (string * (int * sort));
692 fun class_relation (Global ((_, tyco), yss), _) class =
693 Global ((class, tyco), yss)
694 | class_relation (Local (classrels, v), subclass) superclass =
695 Local ((subclass, superclass) :: classrels, v);
696 fun type_constructor tyco yss class =
697 Global ((class, tyco), (map o map) fst yss);
698 fun type_variable (TFree (v, sort)) =
700 val sort' = proj_sort sort;
701 in map_index (fn (n, class) => (Local ([], (v, (n, sort'))), class)) sort' end;
702 val typargs = Sorts.of_sort_derivation pp algebra
703 {class_relation = class_relation, type_constructor = type_constructor,
704 type_variable = type_variable} (ty, proj_sort sort)
705 handle Sorts.CLASS_ERROR e => not_wellsorted thy thm ty sort e;
706 fun mk_dict (Global (inst, yss)) =
707 ensure_inst thy algbr funcgr inst
708 ##>> (fold_map o fold_map) mk_dict yss
709 #>> (fn (inst, dss) => DictConst (inst, dss))
710 | mk_dict (Local (classrels, (v, (k, sort)))) =
711 fold_map (ensure_classrel thy algbr funcgr) classrels
712 #>> (fn classrels => DictVar (classrels, (unprefix "'" v, (k, length sort))))
713 in fold_map mk_dict typargs end;
718 structure Program = CodeDataFun
720 type T = naming * program;
721 val empty = (empty_naming, Graph.empty);
722 fun purge thy cs (naming, program) =
724 val names_delete = cs
725 |> map_filter (lookup_const naming)
726 |> filter (can (Graph.get_node program))
727 |> Graph.all_preds program;
728 val program' = Graph.del_nodes names_delete program;
729 in (naming, program') end;
732 val cached_program = Program.get;
734 fun invoke_generation thy (algebra, funcgr) f name =
735 Program.change_yield thy (fn naming_program => (NONE, naming_program)
736 |> f thy algebra funcgr name
737 |-> (fn name => fn (_, naming_program) => (name, naming_program)));
740 (* program generation *)
742 fun consts_program thy cs =
744 fun project_consts cs (naming, program) =
746 val cs_all = Graph.all_succs program cs;
747 in (cs, (naming, Graph.subgraph (member (op =) cs_all) program)) end;
748 fun generate_consts thy algebra funcgr =
749 fold_map (ensure_const thy algebra funcgr);
751 invoke_generation thy (Code_Preproc.obtain thy cs []) generate_consts cs
756 (* value evaluation *)
758 fun ensure_value thy algbr funcgr t =
760 val ty = fastype_of t;
761 val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
762 o dest_TFree))) t [];
764 fold_map (translate_tyvar_sort thy algbr funcgr) vs
765 ##>> translate_typ thy algbr funcgr ty
766 ##>> translate_term thy algbr funcgr NONE t
767 #>> (fn ((vs, ty), t) => Fun
768 (Term.dummy_patternN, ((vs, ty), [(([], t), (Drule.dummy_thm, true))])));
769 fun term_value (dep, (naming, program1)) =
771 val Fun (_, (vs_ty, [(([], t), _)])) =
772 Graph.get_node program1 Term.dummy_patternN;
773 val deps = Graph.imm_succs program1 Term.dummy_patternN;
774 val program2 = Graph.del_nodes [Term.dummy_patternN] program1;
775 val deps_all = Graph.all_succs program2 deps;
776 val program3 = Graph.subgraph (member (op =) deps_all) program2;
777 in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
779 ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
784 fun base_evaluator thy evaluator algebra funcgr vs t =
786 val (((naming, program), (((vs', ty'), t'), deps)), _) =
787 invoke_generation thy (algebra, funcgr) ensure_value t;
788 val vs'' = map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v)) vs';
789 in evaluator naming program ((vs'', (vs', ty')), t') deps end;
791 fun eval_conv thy prep_sort = Code_Preproc.eval_conv thy prep_sort o base_evaluator thy;
792 fun eval thy prep_sort postproc = Code_Preproc.eval thy prep_sort postproc o base_evaluator thy;
795 (** diagnostic commands **)
797 fun read_const_exprs thy =
799 fun consts_of some_thyname =
801 val thy' = case some_thyname
802 of SOME thyname => ThyInfo.the_theory thyname thy
804 val cs = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
805 ((snd o #constants o Consts.dest o #consts o Sign.rep_sg) thy') [];
807 not (exists (fn thy'' => Sign.declared_const thy'' c) (Theory.parents_of thy'))
810 | SOME thyname => filter belongs_here cs
812 fun read_const_expr "*" = ([], consts_of NONE)
813 | read_const_expr s = if String.isSuffix ".*" s
814 then ([], consts_of (SOME (unsuffix ".*" s)))
815 else ([Code.read_const thy s], []);
816 in pairself flat o split_list o map read_const_expr end;
818 fun code_depgr thy consts =
820 val (_, eqngr) = Code_Preproc.obtain thy consts [];
821 val select = Graph.all_succs eqngr consts;
824 |> not (null consts) ? Graph.subgraph (member (op =) select)
825 |> Graph.map_nodes ((apsnd o map o apfst) (AxClass.overload thy))
828 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
830 fun code_deps thy consts =
832 val eqngr = code_depgr thy consts;
833 val constss = Graph.strong_conn eqngr;
834 val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
835 Symtab.update (const, consts)) consts) constss;
836 fun succs consts = consts
837 |> maps (Graph.imm_succs eqngr)
838 |> subtract (op =) consts
839 |> map (the o Symtab.lookup mapping)
841 val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
842 fun namify consts = map (Code.string_of_const thy) consts
844 val prgr = map (fn (consts, constss) =>
845 { name = namify consts, ID = namify consts, dir = "", unfold = true,
846 path = "", parents = map namify constss }) conn;
847 in Present.display_graph prgr end;
851 structure P = OuterParse
854 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
855 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
860 OuterSyntax.improper_command "code_thms" "print system of code equations for code" OuterKeyword.diag
861 (Scan.repeat P.term_group
862 >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
863 o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
866 OuterSyntax.improper_command "code_deps" "visualize dependencies of code equations for code" OuterKeyword.diag
867 (Scan.repeat P.term_group
868 >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
869 o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
876 structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;