removing previous crude approximation to add type annotations to disambiguate types
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) =^= (f, (([T1..Tn], dicts), [S1..Sm]) *)
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 locally_monomorphic: iterm -> bool
59 val add_constnames: iterm -> string list -> string list
60 val add_tyconames: iterm -> string list -> string list
61 val fold_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
64 val empty_naming: naming
65 val lookup_class: naming -> class -> string option
66 val lookup_classrel: naming -> class * class -> string option
67 val lookup_tyco: naming -> string -> string option
68 val lookup_instance: naming -> class * string -> string option
69 val lookup_const: naming -> string -> string option
70 val ensure_declared_const: theory -> string -> naming -> string * naming
74 | Fun of string * ((typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option)
75 | Datatype of string * ((vname * sort) list *
76 ((string * vname list (*type argument wrt. canonical order*)) * itype list) list)
77 | Datatypecons of string * string
78 | Class of class * (vname * ((class * string) list * (string * itype) list))
79 | Classrel of class * class
80 | Classparam of string * class
81 | Classinst of (class * (string * (vname * sort) list) (*class and arity*))
82 * ((class * (string * (string * dict list list))) list (*super instances*)
83 * (((string * const) * (thm * bool)) list (*class parameter instances*)
84 * ((string * const) * (thm * bool)) list (*super class parameter instances*)))
85 type program = stmt Graph.T
86 val empty_funs: program -> string list
87 val map_terms_bottom_up: (iterm -> iterm) -> iterm -> iterm
88 val map_terms_stmt: (iterm -> iterm) -> stmt -> stmt
89 val is_cons: program -> string -> bool
90 val is_case: stmt -> bool
91 val labelled_name: theory -> program -> string -> string
92 val group_stmts: theory -> program
93 -> ((string * stmt) list * (string * stmt) list
94 * ((string * stmt) list * (string * stmt) list)) list
96 val read_const_exprs: theory -> string list -> string list * string list
97 val consts_program: theory -> bool -> string list -> string list * (naming * program)
98 val dynamic_conv: theory -> (naming -> program
99 -> ((string * sort) list * typscheme) * iterm -> string list -> conv)
101 val dynamic_value: theory -> ((term -> term) -> 'a -> 'a) -> (naming -> program
102 -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
104 val static_conv: theory -> string list -> (naming -> program -> string list
105 -> ((string * sort) list * typscheme) * iterm -> string list -> conv)
107 val static_conv_simple: theory -> string list
108 -> (program -> (string * sort) list -> term -> conv) -> conv
109 val static_value: theory -> ((term -> term) -> 'a -> 'a) -> string list ->
110 (naming -> program -> string list
111 -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
115 structure Code_Thingol: CODE_THINGOL =
124 let val (x', xs') = unfoldl dest x1 in (x', xs' @ [x2]) end;
130 let val (xs', x') = unfoldr dest x2 in (x1::xs', x') end;
133 (** language core - types, terms **)
138 Dict of string list * plain_dict
140 Dict_Const of string * dict list list
141 | Dict_Var of vname * (int * int)
144 `%% of string * itype list
147 type const = string * (((itype list * dict list list) *
148 (itype list (*types of arguments*) * itype (*body type*))) * bool (*requires type annotation*))
152 | IVar of vname option
153 | `$ of iterm * iterm
154 | `|=> of (vname option * itype) * iterm
155 | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
156 (*see also signature*)
158 fun is_IVar (IVar _) = true
161 fun is_IAbs (_ `|=> _) = true
164 val op `$$ = Library.foldl (op `$);
165 val op `|==> = Library.foldr (op `|=>);
167 val unfold_app = unfoldl
168 (fn op `$ t => SOME t
171 val unfold_abs = unfoldr
172 (fn op `|=> t => SOME t
176 (fn ICase (((td, ty), [(p, t)]), _) => SOME (((p, ty), td), t)
179 val unfold_let = unfoldr split_let;
181 fun unfold_const_app t =
183 of (IConst c, ts) => SOME (c, ts)
186 fun fold_constexprs f =
188 fun fold' (IConst c) = f c
190 | fold' (t1 `$ t2) = fold' t1 #> fold' t2
191 | fold' (_ `|=> t) = fold' t
192 | fold' (ICase (((t, _), ds), _)) = fold' t
193 #> fold (fn (pat, body) => fold' pat #> fold' body) ds
196 val add_constnames = fold_constexprs (fn (c, _) => insert (op =) c);
198 fun add_tycos (tyco `%% tys) = insert (op =) tyco #> fold add_tycos tys
199 | add_tycos (ITyVar _) = I;
201 val add_tyconames = fold_constexprs (fn (_, (((tys, _), _), _)) => fold add_tycos tys);
203 fun fold_varnames f =
207 fun fold_term _ (IConst _) = I
208 | fold_term vs (IVar (SOME v)) = if member (op =) vs v then I else f v
209 | fold_term _ (IVar NONE) = I
210 | fold_term vs (t1 `$ t2) = fold_term vs t1 #> fold_term vs t2
211 | fold_term vs ((SOME v, _) `|=> t) = fold_term (insert (op =) v vs) t
212 | fold_term vs ((NONE, _) `|=> t) = fold_term vs t
213 | fold_term vs (ICase (((t, _), ds), _)) = fold_term vs t #> fold (fold_case vs) ds
214 and fold_case vs (p, t) = fold_term (add p vs) t;
216 fun add t = fold_aux add (insert (op =)) t;
217 in fold_aux add f end;
219 fun exists_var t v = fold_varnames (fn w => fn b => v = w orelse b) t false;
221 fun split_pat_abs ((NONE, ty) `|=> t) = SOME ((IVar NONE, ty), t)
222 | split_pat_abs ((SOME v, ty) `|=> t) = SOME (case t
223 of ICase (((IVar (SOME w), _), [(p, t')]), _) =>
224 if v = w andalso (exists_var p v orelse not (exists_var t' v))
226 else ((IVar (SOME v), ty), t)
227 | _ => ((IVar (SOME v), ty), t))
228 | split_pat_abs _ = NONE;
230 val unfold_pat_abs = unfoldr split_pat_abs;
232 fun unfold_abs_eta [] t = ([], t)
233 | unfold_abs_eta (_ :: tys) (v_ty `|=> t) =
235 val (vs_tys, t') = unfold_abs_eta tys t;
236 in (v_ty :: vs_tys, t') end
237 | unfold_abs_eta tys t =
239 val ctxt = fold_varnames Name.declare t Name.context;
240 val vs_tys = (map o apfst) SOME (Name.invent_names ctxt "a" tys);
241 in (vs_tys, t `$$ map (IVar o fst) vs_tys) end;
243 fun eta_expand k (c as (name, ((_, (tys, _)), _)), ts) =
247 val _ = if l > length tys
248 then error ("Impossible eta-expansion for constant " ^ quote name) else ();
249 val ctxt = (fold o fold_varnames) Name.declare ts Name.context;
250 val vs_tys = (map o apfst) SOME
251 (Name.invent_names ctxt "a" ((take l o drop j) tys));
252 in vs_tys `|==> IConst c `$$ ts @ map (IVar o fst) vs_tys end;
254 fun contains_dict_var t =
256 fun cont_dict (Dict (_, d)) = cont_plain_dict d
257 and cont_plain_dict (Dict_Const (_, dss)) = (exists o exists) cont_dict dss
258 | cont_plain_dict (Dict_Var _) = true;
259 fun cont_term (IConst (_, (((_, dss), _), _))) = (exists o exists) cont_dict dss
260 | cont_term (IVar _) = false
261 | cont_term (t1 `$ t2) = cont_term t1 orelse cont_term t2
262 | cont_term (_ `|=> t) = cont_term t
263 | cont_term (ICase (_, t)) = cont_term t;
266 fun locally_monomorphic (IConst _) = false
267 | locally_monomorphic (IVar _) = true
268 | locally_monomorphic (t `$ _) = locally_monomorphic t
269 | locally_monomorphic (_ `|=> t) = locally_monomorphic t
270 | locally_monomorphic (ICase ((_, ds), _)) = exists (locally_monomorphic o snd) ds;
278 fun thyname_of_class thy = #theory_name o Name_Space.the_entry (Sign.class_space thy);
279 fun thyname_of_instance thy inst = case AxClass.thynames_of_arity thy inst
280 of [] => error ("No such instance: " ^ quote (snd inst ^ " :: " ^ fst inst))
281 | thyname :: _ => thyname;
282 fun thyname_of_const thy c = case AxClass.class_of_param thy c
283 of SOME class => thyname_of_class thy class
284 | NONE => (case Code.get_type_of_constr_or_abstr thy c
285 of SOME (tyco, _) => Codegen.thyname_of_type thy tyco
286 | NONE => Codegen.thyname_of_const thy c);
287 fun purify_base "==>" = "follows"
288 | purify_base "==" = "meta_eq"
289 | purify_base s = Name.desymbolize false s;
290 fun namify thy get_basename get_thyname name =
292 val prefix = get_thyname thy name;
293 val base = (purify_base o get_basename) name;
294 in Long_Name.append prefix base end;
297 fun namify_class thy = namify thy Long_Name.base_name thyname_of_class;
298 fun namify_classrel thy = namify thy (fn (sub_class, super_class) =>
299 Long_Name.base_name super_class ^ "_" ^ Long_Name.base_name sub_class)
300 (fn thy => thyname_of_class thy o fst);
301 (*order fits nicely with composed projections*)
302 fun namify_tyco thy "fun" = "Pure.fun"
303 | namify_tyco thy tyco = namify thy Long_Name.base_name Codegen.thyname_of_type tyco;
304 fun namify_instance thy = namify thy (fn (class, tyco) =>
305 Long_Name.base_name class ^ "_" ^ Long_Name.base_name tyco) thyname_of_instance;
306 fun namify_const thy = namify thy Long_Name.base_name thyname_of_const;
313 datatype naming = Naming of {
314 class: class Symtab.table * Name.context,
315 classrel: string Symreltab.table * Name.context,
316 tyco: string Symtab.table * Name.context,
317 instance: string Symreltab.table * Name.context,
318 const: string Symtab.table * Name.context
321 fun dest_Naming (Naming naming) = naming;
323 val empty_naming = Naming {
324 class = (Symtab.empty, Name.context),
325 classrel = (Symreltab.empty, Name.context),
326 tyco = (Symtab.empty, Name.context),
327 instance = (Symreltab.empty, Name.context),
328 const = (Symtab.empty, Name.context)
332 fun mk_naming (class, classrel, tyco, instance, const) =
333 Naming { class = class, classrel = classrel,
334 tyco = tyco, instance = instance, const = const };
335 fun map_naming f (Naming { class, classrel, tyco, instance, const }) =
336 mk_naming (f (class, classrel, tyco, instance, const));
338 fun map_class f = map_naming
339 (fn (class, classrel, tyco, inst, const) =>
340 (f class, classrel, tyco, inst, const));
341 fun map_classrel f = map_naming
342 (fn (class, classrel, tyco, inst, const) =>
343 (class, f classrel, tyco, inst, const));
344 fun map_tyco f = map_naming
345 (fn (class, classrel, tyco, inst, const) =>
346 (class, classrel, f tyco, inst, const));
347 fun map_instance f = map_naming
348 (fn (class, classrel, tyco, inst, const) =>
349 (class, classrel, tyco, f inst, const));
350 fun map_const f = map_naming
351 (fn (class, classrel, tyco, inst, const) =>
352 (class, classrel, tyco, inst, f const));
355 fun add_variant update (thing, name) (tab, used) =
357 val (name', used') = Name.variant name used;
358 val tab' = update (thing, name') tab;
359 in (tab', used') end;
361 fun declare thy mapp lookup update namify thing =
362 mapp (add_variant update (thing, namify thy thing))
363 #> `(fn naming => the (lookup naming thing));
366 (* lookup and declare *)
370 val suffix_class = "class";
371 val suffix_classrel = "classrel"
372 val suffix_tyco = "tyco";
373 val suffix_instance = "inst";
374 val suffix_const = "const";
376 fun add_suffix nsp NONE = NONE
377 | add_suffix nsp (SOME name) = SOME (Long_Name.append name nsp);
381 val lookup_class = add_suffix suffix_class
382 oo Symtab.lookup o fst o #class o dest_Naming;
383 val lookup_classrel = add_suffix suffix_classrel
384 oo Symreltab.lookup o fst o #classrel o dest_Naming;
385 val lookup_tyco = add_suffix suffix_tyco
386 oo Symtab.lookup o fst o #tyco o dest_Naming;
387 val lookup_instance = add_suffix suffix_instance
388 oo Symreltab.lookup o fst o #instance o dest_Naming;
389 val lookup_const = add_suffix suffix_const
390 oo Symtab.lookup o fst o #const o dest_Naming;
392 fun declare_class thy = declare thy map_class
393 lookup_class Symtab.update_new namify_class;
394 fun declare_classrel thy = declare thy map_classrel
395 lookup_classrel Symreltab.update_new namify_classrel;
396 fun declare_tyco thy = declare thy map_tyco
397 lookup_tyco Symtab.update_new namify_tyco;
398 fun declare_instance thy = declare thy map_instance
399 lookup_instance Symreltab.update_new namify_instance;
400 fun declare_const thy = declare thy map_const
401 lookup_const Symtab.update_new namify_const;
403 fun ensure_declared_const thy const naming =
404 case lookup_const naming const
405 of SOME const' => (const', naming)
406 | NONE => declare_const thy const naming;
408 val fun_tyco = Long_Name.append (namify_tyco Pure.thy "fun") suffix_tyco
409 (*depends on add_suffix*);
411 val unfold_fun = unfoldr
412 (fn tyco `%% [ty1, ty2] => if tyco = fun_tyco then SOME (ty1, ty2) else NONE
415 fun unfold_fun_n n ty =
417 val (tys1, ty1) = unfold_fun ty;
418 val (tys3, tys2) = chop n tys1;
419 val ty3 = Library.foldr (fn (ty1, ty2) => fun_tyco `%% [ty1, ty2]) (tys2, ty1);
425 (** statements, abstract programs **)
427 type typscheme = (vname * sort) list * itype;
430 | Fun of string * ((typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option)
431 | Datatype of string * ((vname * sort) list * ((string * vname list) * itype list) list)
432 | Datatypecons of string * string
433 | Class of class * (vname * ((class * string) list * (string * itype) list))
434 | Classrel of class * class
435 | Classparam of string * class
436 | Classinst of (class * (string * (vname * sort) list))
437 * ((class * (string * (string * dict list list))) list
438 * (((string * const) * (thm * bool)) list
439 * ((string * const) * (thm * bool)) list))
440 (*see also signature*);
442 type program = stmt Graph.T;
444 fun empty_funs program =
445 Graph.fold (fn (name, (Fun (c, ((_, []), _)), _)) => cons c
446 | _ => I) program [];
448 fun map_terms_bottom_up f (t as IConst _) = f t
449 | map_terms_bottom_up f (t as IVar _) = f t
450 | map_terms_bottom_up f (t1 `$ t2) = f
451 (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
452 | map_terms_bottom_up f ((v, ty) `|=> t) = f
453 ((v, ty) `|=> map_terms_bottom_up f t)
454 | map_terms_bottom_up f (ICase (((t, ty), ps), t0)) = f
455 (ICase (((map_terms_bottom_up f t, ty), (map o pairself)
456 (map_terms_bottom_up f) ps), map_terms_bottom_up f t0));
458 fun map_classparam_instances_as_term f =
459 (map o apfst o apsnd) (fn const => case f (IConst const) of IConst const' => const')
461 fun map_terms_stmt f NoStmt = NoStmt
462 | map_terms_stmt f (Fun (c, ((tysm, eqs), case_cong))) = Fun (c, ((tysm, (map o apfst)
463 (fn (ts, t) => (map f ts, f t)) eqs), case_cong))
464 | map_terms_stmt f (stmt as Datatype _) = stmt
465 | map_terms_stmt f (stmt as Datatypecons _) = stmt
466 | map_terms_stmt f (stmt as Class _) = stmt
467 | map_terms_stmt f (stmt as Classrel _) = stmt
468 | map_terms_stmt f (stmt as Classparam _) = stmt
469 | map_terms_stmt f (Classinst (arity, (super_instances, classparam_instances))) =
470 Classinst (arity, (super_instances, (pairself o map_classparam_instances_as_term) f classparam_instances));
472 fun is_cons program name = case Graph.get_node program name
473 of Datatypecons _ => true
476 fun is_case (Fun (_, (_, SOME _))) = true
479 fun lookup_classparam_instance program name = program |> Graph.get_first
480 (fn (_, (Classinst ((class, _), (_, (param_insts, _))), _)) =>
481 Option.map (fn ((const, _), _) => (class, const))
482 (find_first (fn ((_, (inst_const, _)), _) => inst_const = name) param_insts) | _ => NONE)
484 fun labelled_name thy program name =
485 let val ctxt = Proof_Context.init_global thy in
486 case Graph.get_node program name of
487 Fun (c, _) => quote (Code.string_of_const thy c)
488 | Datatype (tyco, _) => "type " ^ quote (Proof_Context.extern_type ctxt tyco)
489 | Datatypecons (c, _) => quote (Code.string_of_const thy c)
490 | Class (class, _) => "class " ^ quote (Proof_Context.extern_class ctxt class)
491 | Classrel (sub, super) =>
493 val Class (sub, _) = Graph.get_node program sub;
494 val Class (super, _) = Graph.get_node program super;
496 quote (Proof_Context.extern_class ctxt sub ^ " < " ^ Proof_Context.extern_class ctxt super)
498 | Classparam (c, _) => quote (Code.string_of_const thy c)
499 | Classinst ((class, (tyco, _)), _) =>
501 val Class (class, _) = Graph.get_node program class;
502 val Datatype (tyco, _) = Graph.get_node program tyco;
504 quote (Proof_Context.extern_type ctxt tyco ^ " :: " ^ Proof_Context.extern_class ctxt class)
508 fun linear_stmts program =
509 rev (Graph.strong_conn program)
510 |> map (AList.make (Graph.get_node program));
512 fun group_stmts thy program =
514 fun is_fun (_, Fun _) = true | is_fun _ = false;
515 fun is_datatypecons (_, Datatypecons _) = true | is_datatypecons _ = false;
516 fun is_datatype (_, Datatype _) = true | is_datatype _ = false;
517 fun is_class (_, Class _) = true | is_class _ = false;
518 fun is_classrel (_, Classrel _) = true | is_classrel _ = false;
519 fun is_classparam (_, Classparam _) = true | is_classparam _ = false;
520 fun is_classinst (_, Classinst _) = true | is_classinst _ = false;
522 if forall (is_datatypecons orf is_datatype) stmts
523 then (filter is_datatype stmts, [], ([], []))
524 else if forall (is_class orf is_classrel orf is_classparam) stmts
525 then ([], filter is_class stmts, ([], []))
526 else if forall (is_fun orf is_classinst) stmts
527 then ([], [], List.partition is_fun stmts)
528 else error ("Illegal mutual dependencies: " ^
529 (commas o map (labelled_name thy program o fst)) stmts)
536 (** translation kernel **)
538 (* generic mechanisms *)
540 fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
542 fun add_dep name = case dep of NONE => I
543 | SOME dep => Graph.add_edge (dep, name);
544 val (name, naming') = case lookup naming thing
545 of SOME name => (name, naming)
546 | NONE => declare thing naming;
547 in case try (Graph.get_node program) name
548 of SOME stmt => program
554 |> Graph.default_node (name, NoStmt)
557 |> curry generate (SOME name)
559 |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
564 exception PERMISSIVE of unit;
566 fun translation_error thy permissive some_thm msg sub_msg =
568 then raise PERMISSIVE ()
573 SOME thm => "\n(in code equation " ^ Display.string_of_thm_global thy thm ^ ")"
575 in error (msg ^ err_thm ^ ":\n" ^ sub_msg) end;
577 fun not_wellsorted thy permissive some_thm ty sort e =
579 val ctxt = Syntax.init_pretty_global thy;
580 val err_class = Sorts.class_error ctxt e;
582 "Type " ^ Syntax.string_of_typ ctxt ty ^ " not of sort " ^
583 Syntax.string_of_sort_global thy sort;
585 translation_error thy permissive some_thm "Wellsortedness error"
586 (err_typ ^ "\n" ^ err_class)
589 (* inference of type annotations for disambiguation with type classes *)
591 fun annotate_term (Const (c', T'), Const (c, T)) tvar_names =
593 val tvar_names' = Term.add_tvar_namesT T' tvar_names
595 (Const (c, if eq_set (op =) (tvar_names, tvar_names') then T else Type("", [T])), tvar_names')
597 | annotate_term (t1 $ u1, t $ u) tvar_names =
599 val (u', tvar_names') = annotate_term (u1, u) tvar_names
600 val (t', tvar_names'') = annotate_term (t1, t) tvar_names'
602 (t' $ u', tvar_names'')
604 | annotate_term (Abs (_, _, t1) , Abs (x, T, t)) tvar_names =
605 apfst (fn t => Abs (x, T, t)) (annotate_term (t1, t) tvar_names)
606 | annotate_term (_, t) tvar_names = (t, tvar_names)
608 fun annotate_eqns thy eqns =
610 val ctxt = ProofContext.init_global thy
611 val erase = map_types (fn _ => Type_Infer.anyT [])
612 val reinfer = singleton (Type_Infer_Context.infer_types ctxt)
613 fun add_annotations ((args, (rhs, some_abs)), (SOME th, proper)) =
615 val (lhs, drhs) = Logic.dest_equals (prop_of (Thm.unvarify_global th))
616 val drhs' = snd (Logic.dest_equals (reinfer (Logic.mk_equals (lhs, erase drhs))))
617 val (rhs', _) = annotate_term (drhs', rhs) []
619 ((args, (rhs', some_abs)), (SOME th, proper))
621 | add_annotations eqn = eqn
623 map add_annotations eqns
628 fun ensure_tyco thy algbr eqngr permissive tyco =
630 val ((vs, cos), _) = Code.get_type thy tyco;
632 fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
633 ##>> fold_map (fn (c, (vs, tys)) =>
634 ensure_const thy algbr eqngr permissive c
635 ##>> pair (map (unprefix "'" o fst) vs)
636 ##>> fold_map (translate_typ thy algbr eqngr permissive) tys) cos
637 #>> (fn info => Datatype (tyco, info));
638 in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
639 and ensure_const thy algbr eqngr permissive c =
641 fun stmt_datatypecons tyco =
642 ensure_tyco thy algbr eqngr permissive tyco
643 #>> (fn tyco => Datatypecons (c, tyco));
644 fun stmt_classparam class =
645 ensure_class thy algbr eqngr permissive class
646 #>> (fn class => Classparam (c, class));
649 val ((vs, ty), eqns) = Code.equations_of_cert thy cert;
650 val eqns' = annotate_eqns thy eqns
651 val some_case_cong = Code.get_case_cong thy c;
653 fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
654 ##>> translate_typ thy algbr eqngr permissive ty
655 ##>> translate_eqns thy algbr eqngr permissive eqns'
656 #>> (fn info => Fun (c, (info, some_case_cong)))
658 val stmt_const = case Code.get_type_of_constr_or_abstr thy c
659 of SOME (tyco, _) => stmt_datatypecons tyco
660 | NONE => (case AxClass.class_of_param thy c
661 of SOME class => stmt_classparam class
662 | NONE => stmt_fun (Code_Preproc.cert eqngr c))
663 in ensure_stmt lookup_const (declare_const thy) stmt_const c end
664 and ensure_class thy (algbr as (_, algebra)) eqngr permissive class =
666 val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
667 val cs = #params (AxClass.get_info thy class);
669 fold_map (fn super_class => ensure_class thy algbr eqngr permissive super_class
670 ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)) super_classes
671 ##>> fold_map (fn (c, ty) => ensure_const thy algbr eqngr permissive c
672 ##>> translate_typ thy algbr eqngr permissive ty) cs
673 #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
674 in ensure_stmt lookup_class (declare_class thy) stmt_class class end
675 and ensure_classrel thy algbr eqngr permissive (sub_class, super_class) =
678 ensure_class thy algbr eqngr permissive sub_class
679 ##>> ensure_class thy algbr eqngr permissive super_class
681 in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (sub_class, super_class) end
682 and ensure_inst thy (algbr as (_, algebra)) eqngr permissive (class, tyco) =
684 val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
685 val these_classparams = these o try (#params o AxClass.get_info thy);
686 val classparams = these_classparams class;
687 val further_classparams = maps these_classparams
688 ((Sorts.complete_sort algebra o Sorts.super_classes algebra) class);
689 val vs = Name.invent_names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
690 val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
691 val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
692 Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
693 val arity_typ = Type (tyco, map TFree vs);
694 val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
695 fun translate_super_instance super_class =
696 ensure_class thy algbr eqngr permissive super_class
697 ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)
698 ##>> translate_dicts thy algbr eqngr permissive NONE (arity_typ, [super_class])
699 #>> (fn ((super_class, classrel), [Dict ([], Dict_Const (inst, dss))]) =>
700 (super_class, (classrel, (inst, dss))));
701 fun translate_classparam_instance (c, ty) =
703 val raw_const = Const (c, map_type_tfree (K arity_typ') ty);
704 val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy raw_const);
705 val const = (apsnd Logic.unvarifyT_global o dest_Const o snd
706 o Logic.dest_equals o Thm.prop_of) thm;
708 ensure_const thy algbr eqngr permissive c
709 ##>> translate_const thy algbr eqngr permissive (SOME thm) (const, NONE)
710 #>> (fn (c, IConst const') => ((c, const'), (thm, true)))
713 ensure_class thy algbr eqngr permissive class
714 ##>> ensure_tyco thy algbr eqngr permissive tyco
715 ##>> fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
716 ##>> fold_map translate_super_instance super_classes
717 ##>> fold_map translate_classparam_instance classparams
718 ##>> fold_map translate_classparam_instance further_classparams
719 #>> (fn (((((class, tyco), arity_args), super_instances),
720 classparam_instances), further_classparam_instances) =>
721 Classinst ((class, (tyco, arity_args)), (super_instances,
722 (classparam_instances, further_classparam_instances))));
723 in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
724 and translate_typ thy algbr eqngr permissive (TFree (v, _)) =
725 pair (ITyVar (unprefix "'" v))
726 | translate_typ thy algbr eqngr permissive (Type (tyco, tys)) =
727 ensure_tyco thy algbr eqngr permissive tyco
728 ##>> fold_map (translate_typ thy algbr eqngr permissive) tys
729 #>> (fn (tyco, tys) => tyco `%% tys)
730 and translate_term thy algbr eqngr permissive some_thm (Const (c, ty), some_abs) =
731 translate_app thy algbr eqngr permissive some_thm (((c, ty), []), some_abs)
732 | translate_term thy algbr eqngr permissive some_thm (Free (v, _), some_abs) =
734 | translate_term thy algbr eqngr permissive some_thm (Abs (v, ty, t), some_abs) =
736 val (v', t') = Syntax_Trans.variant_abs (Name.desymbolize false v, ty, t);
737 val v'' = if member (op =) (Term.add_free_names t' []) v'
738 then SOME v' else NONE
740 translate_typ thy algbr eqngr permissive ty
741 ##>> translate_term thy algbr eqngr permissive some_thm (t', some_abs)
742 #>> (fn (ty, t) => (v'', ty) `|=> t)
744 | translate_term thy algbr eqngr permissive some_thm (t as _ $ _, some_abs) =
746 of (Const (c, ty), ts) =>
747 translate_app thy algbr eqngr permissive some_thm (((c, ty), ts), some_abs)
749 translate_term thy algbr eqngr permissive some_thm (t', some_abs)
750 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
751 #>> (fn (t, ts) => t `$$ ts)
752 and translate_eqn thy algbr eqngr permissive ((args, (rhs, some_abs)), (some_thm, proper)) =
753 fold_map (translate_term thy algbr eqngr permissive some_thm) args
754 ##>> translate_term thy algbr eqngr permissive some_thm (rhs, some_abs)
755 #>> rpair (some_thm, proper)
756 and translate_eqns thy algbr eqngr permissive eqns prgrm =
757 prgrm |> fold_map (translate_eqn thy algbr eqngr permissive) eqns
758 handle PERMISSIVE () => ([], prgrm)
759 and translate_const thy algbr eqngr permissive some_thm ((c, ty), some_abs) =
761 val _ = if (case some_abs of NONE => true | SOME abs => not (c = abs))
762 andalso Code.is_abstr thy c
763 then translation_error thy permissive some_thm
764 "Abstraction violation" ("constant " ^ Code.string_of_const thy c)
766 val (annotate, ty') = (case ty of Type("", [ty']) => (true, ty') | ty' => (false, ty'))
767 val arg_typs = Sign.const_typargs thy (c, ty');
768 val sorts = Code_Preproc.sortargs eqngr c;
769 val (function_typs, body_typ) = Term.strip_type ty';
771 ensure_const thy algbr eqngr permissive c
772 ##>> fold_map (translate_typ thy algbr eqngr permissive) arg_typs
773 ##>> fold_map (translate_dicts thy algbr eqngr permissive some_thm) (arg_typs ~~ sorts)
774 ##>> fold_map (translate_typ thy algbr eqngr permissive) (body_typ :: function_typs)
775 #>> (fn (((c, arg_typs), dss), body_typ :: function_typs) =>
776 IConst (c, (((arg_typs, dss), (function_typs, body_typ)), annotate)))
778 and translate_app_const thy algbr eqngr permissive some_thm ((c_ty, ts), some_abs) =
779 translate_const thy algbr eqngr permissive some_thm (c_ty, some_abs)
780 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
781 #>> (fn (t, ts) => t `$$ ts)
782 and translate_case thy algbr eqngr permissive some_thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
784 fun arg_types num_args ty = fst (chop num_args (binder_types ty));
785 val tys = arg_types num_args (snd c_ty);
786 val ty = nth tys t_pos;
787 fun mk_constr c t = let val n = Code.args_number thy c
788 in ((c, arg_types n (fastype_of t) ---> ty), n) end;
789 val constrs = if null case_pats then []
790 else map2 mk_constr case_pats (nth_drop t_pos ts);
791 fun casify naming constrs ty ts =
793 val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
794 fun collapse_clause vs_map ts body =
797 of IConst (c, _) => if member (op =) undefineds c
800 | ICase (((IVar (SOME v), _), subclauses), _) =>
801 if forall (fn (pat', body') => exists_var pat' v
802 orelse not (exists_var body' v)) subclauses
803 then case AList.lookup (op =) vs_map v
804 of SOME i => maps (fn (pat', body') =>
805 collapse_clause (AList.delete (op =) v vs_map)
806 (nth_map i (K pat') ts) body') subclauses
807 | NONE => [(ts, body)]
811 fun mk_clause mk tys t =
813 val (vs, body) = unfold_abs_eta tys t;
814 val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
815 val ts = map (IVar o fst) vs;
816 in map mk (collapse_clause vs_map ts body) end;
817 val t = nth ts t_pos;
818 val ts_clause = nth_drop t_pos ts;
819 val clauses = if null case_pats
820 then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
821 else maps (fn ((constr as IConst (_, ((_, (tys, _)), _)), n), t) =>
822 mk_clause (fn (ts, body) => (constr `$$ ts, body)) (take n tys) t)
823 (constrs ~~ 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) f name =
901 Program.change_yield (if ignore_cache then NONE else SOME thy)
902 (fn naming_program => (NONE, naming_program)
903 |> f thy algebra eqngr name
904 |-> (fn name => fn (_, naming_program) => (name, 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.subgraph
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 [];
932 fold_map (translate_tyvar_sort thy algbr eqngr false) vs
933 ##>> translate_typ thy algbr eqngr false ty
934 ##>> translate_term thy algbr eqngr false NONE (Code.subst_signatures thy t, NONE)
935 #>> (fn ((vs, ty), t) => Fun
936 (Term.dummy_patternN, (((vs, ty), [(([], t), (NONE, true))]), NONE)));
937 fun term_value (dep, (naming, program1)) =
939 val Fun (_, ((vs_ty, [(([], t), _)]), _)) =
940 Graph.get_node program1 Term.dummy_patternN;
941 val deps = Graph.immediate_succs program1 Term.dummy_patternN;
942 val program2 = Graph.del_nodes [Term.dummy_patternN] program1;
943 val deps_all = Graph.all_succs program2 deps;
944 val program3 = Graph.subgraph (member (op =) deps_all) program2;
945 in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
947 ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
952 fun original_sorts vs =
953 map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v));
955 fun dynamic_evaluator thy evaluator algebra eqngr vs t =
957 val (((naming, program), (((vs', ty'), t'), deps)), _) =
958 invoke_generation false thy (algebra, eqngr) ensure_value t;
959 in evaluator naming program ((original_sorts vs vs', (vs', ty')), t') deps end;
961 fun dynamic_conv thy evaluator =
962 Code_Preproc.dynamic_conv thy (dynamic_evaluator thy evaluator);
964 fun dynamic_value thy postproc evaluator =
965 Code_Preproc.dynamic_value thy postproc (dynamic_evaluator thy evaluator);
967 fun lift_evaluation thy evaluation' algebra eqngr naming program vs t =
969 val (((_, program'), (((vs', ty'), t'), deps)), _) =
970 ensure_value thy algebra eqngr t (NONE, (naming, program));
971 in evaluation' ((original_sorts vs vs', (vs', ty')), t') deps end;
973 fun lift_evaluator thy evaluator' consts algebra eqngr =
975 fun generate_consts thy algebra eqngr =
976 fold_map (ensure_const thy algebra eqngr false);
977 val (consts', (naming, program)) =
978 invoke_generation true thy (algebra, eqngr) generate_consts consts;
979 val evaluation' = evaluator' naming program consts';
980 in lift_evaluation thy evaluation' algebra eqngr naming program end;
982 fun lift_evaluator_simple thy evaluator' consts algebra eqngr =
984 fun generate_consts thy algebra eqngr =
985 fold_map (ensure_const thy algebra eqngr false);
986 val (consts', (naming, program)) =
987 invoke_generation true thy (algebra, eqngr) generate_consts consts;
988 in evaluator' program end;
990 fun static_conv thy consts conv =
991 Code_Preproc.static_conv thy consts (lift_evaluator thy conv consts);
993 fun static_conv_simple thy consts conv =
994 Code_Preproc.static_conv thy consts (lift_evaluator_simple thy conv consts);
996 fun static_value thy postproc consts evaluator =
997 Code_Preproc.static_value thy postproc consts (lift_evaluator thy evaluator consts);
1000 (** diagnostic commands **)
1002 fun read_const_exprs thy =
1004 fun consts_of thy' = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
1005 ((snd o #constants o Consts.dest o #consts o Sign.rep_sg) thy') [];
1006 fun belongs_here thy' c = forall
1007 (fn thy'' => not (Sign.declared_const thy'' c)) (Theory.parents_of thy');
1008 fun consts_of_select thy' = filter (belongs_here thy') (consts_of thy');
1009 fun read_const_expr "_" = ([], consts_of thy)
1010 | read_const_expr s = if String.isSuffix "._" s
1011 then ([], consts_of_select (Context.this_theory thy (unsuffix "._" s)))
1012 else ([Code.read_const thy s], []);
1013 in pairself flat o split_list o map read_const_expr end;
1015 fun code_depgr thy consts =
1017 val (_, eqngr) = Code_Preproc.obtain true thy consts [];
1018 val all_consts = Graph.all_succs eqngr consts;
1019 in Graph.subgraph (member (op =) all_consts) eqngr end;
1021 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
1023 fun code_deps thy consts =
1025 val eqngr = code_depgr thy consts;
1026 val constss = Graph.strong_conn eqngr;
1027 val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
1028 Symtab.update (const, consts)) consts) constss;
1029 fun succs consts = consts
1030 |> maps (Graph.immediate_succs eqngr)
1031 |> subtract (op =) consts
1032 |> map (the o Symtab.lookup mapping)
1034 val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
1035 fun namify consts = map (Code.string_of_const thy) consts
1037 val prgr = map (fn (consts, constss) =>
1038 { name = namify consts, ID = namify consts, dir = "", unfold = true,
1039 path = "", parents = map namify constss }) conn;
1040 in Present.display_graph prgr end;
1044 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
1045 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
1050 Outer_Syntax.improper_command "code_thms" "print system of code equations for code" Keyword.diag
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 "code_deps" "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;