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_const' thy = #theory_name o Name_Space.the_entry (Sign.const_space thy);
274 fun thyname_of_instance thy inst = case AxClass.thynames_of_arity thy inst
275 of [] => error ("No such instance: " ^ quote (snd inst ^ " :: " ^ fst inst))
276 | thyname :: _ => thyname;
277 fun thyname_of_const thy c = case AxClass.class_of_param thy c
278 of SOME class => thyname_of_class thy class
279 | NONE => (case Code.get_type_of_constr_or_abstr thy c
280 of SOME (tyco, _) => thyname_of_type thy tyco
281 | NONE => thyname_of_const' thy c);
282 fun purify_base "==>" = "follows"
283 | purify_base "==" = "meta_eq"
284 | purify_base s = Name.desymbolize false s;
285 fun namify thy get_basename get_thyname name =
287 val prefix = get_thyname thy name;
288 val base = (purify_base o get_basename) name;
289 in Long_Name.append prefix base end;
292 fun namify_class thy = namify thy Long_Name.base_name thyname_of_class;
293 fun namify_classrel thy = namify thy (fn (sub_class, super_class) =>
294 Long_Name.base_name super_class ^ "_" ^ Long_Name.base_name sub_class)
295 (fn thy => thyname_of_class thy o fst);
296 (*order fits nicely with composed projections*)
297 fun namify_tyco thy "fun" = "Pure.fun"
298 | namify_tyco thy tyco = namify thy Long_Name.base_name thyname_of_type tyco;
299 fun namify_instance thy = namify thy (fn (class, tyco) =>
300 Long_Name.base_name class ^ "_" ^ Long_Name.base_name tyco) thyname_of_instance;
301 fun namify_const thy = namify thy Long_Name.base_name thyname_of_const;
308 datatype naming = Naming of {
309 class: class Symtab.table * Name.context,
310 classrel: string Symreltab.table * Name.context,
311 tyco: string Symtab.table * Name.context,
312 instance: string Symreltab.table * Name.context,
313 const: string Symtab.table * Name.context
316 fun dest_Naming (Naming naming) = naming;
318 val empty_naming = Naming {
319 class = (Symtab.empty, Name.context),
320 classrel = (Symreltab.empty, Name.context),
321 tyco = (Symtab.empty, Name.context),
322 instance = (Symreltab.empty, Name.context),
323 const = (Symtab.empty, Name.context)
327 fun mk_naming (class, classrel, tyco, instance, const) =
328 Naming { class = class, classrel = classrel,
329 tyco = tyco, instance = instance, const = const };
330 fun map_naming f (Naming { class, classrel, tyco, instance, const }) =
331 mk_naming (f (class, classrel, tyco, instance, const));
333 fun map_class f = map_naming
334 (fn (class, classrel, tyco, inst, const) =>
335 (f class, classrel, tyco, inst, const));
336 fun map_classrel f = map_naming
337 (fn (class, classrel, tyco, inst, const) =>
338 (class, f classrel, tyco, inst, const));
339 fun map_tyco f = map_naming
340 (fn (class, classrel, tyco, inst, const) =>
341 (class, classrel, f tyco, inst, const));
342 fun map_instance f = map_naming
343 (fn (class, classrel, tyco, inst, const) =>
344 (class, classrel, tyco, f inst, const));
345 fun map_const f = map_naming
346 (fn (class, classrel, tyco, inst, const) =>
347 (class, classrel, tyco, inst, f const));
350 fun add_variant update (thing, name) (tab, used) =
352 val (name', used') = Name.variant name used;
353 val tab' = update (thing, name') tab;
354 in (tab', used') end;
356 fun declare thy mapp lookup update namify thing =
357 mapp (add_variant update (thing, namify thy thing))
358 #> `(fn naming => the (lookup naming thing));
361 (* lookup and declare *)
365 val suffix_class = "class";
366 val suffix_classrel = "classrel"
367 val suffix_tyco = "tyco";
368 val suffix_instance = "inst";
369 val suffix_const = "const";
371 fun add_suffix nsp NONE = NONE
372 | add_suffix nsp (SOME name) = SOME (Long_Name.append name nsp);
376 val lookup_class = add_suffix suffix_class
377 oo Symtab.lookup o fst o #class o dest_Naming;
378 val lookup_classrel = add_suffix suffix_classrel
379 oo Symreltab.lookup o fst o #classrel o dest_Naming;
380 val lookup_tyco = add_suffix suffix_tyco
381 oo Symtab.lookup o fst o #tyco o dest_Naming;
382 val lookup_instance = add_suffix suffix_instance
383 oo Symreltab.lookup o fst o #instance o dest_Naming;
384 val lookup_const = add_suffix suffix_const
385 oo Symtab.lookup o fst o #const o dest_Naming;
387 fun declare_class thy = declare thy map_class
388 lookup_class Symtab.update_new namify_class;
389 fun declare_classrel thy = declare thy map_classrel
390 lookup_classrel Symreltab.update_new namify_classrel;
391 fun declare_tyco thy = declare thy map_tyco
392 lookup_tyco Symtab.update_new namify_tyco;
393 fun declare_instance thy = declare thy map_instance
394 lookup_instance Symreltab.update_new namify_instance;
395 fun declare_const thy = declare thy map_const
396 lookup_const Symtab.update_new namify_const;
398 fun ensure_declared_const thy const naming =
399 case lookup_const naming const
400 of SOME const' => (const', naming)
401 | NONE => declare_const thy const naming;
403 val fun_tyco = Long_Name.append (namify_tyco Pure.thy "fun") suffix_tyco
404 (*depends on add_suffix*);
406 val unfold_fun = unfoldr
407 (fn tyco `%% [ty1, ty2] => if tyco = fun_tyco then SOME (ty1, ty2) else NONE
410 fun unfold_fun_n n ty =
412 val (tys1, ty1) = unfold_fun ty;
413 val (tys3, tys2) = chop n tys1;
414 val ty3 = Library.foldr (fn (ty1, ty2) => fun_tyco `%% [ty1, ty2]) (tys2, ty1);
420 (** statements, abstract programs **)
422 type typscheme = (vname * sort) list * itype;
425 | Fun of string * ((typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option)
426 | Datatype of string * ((vname * sort) list * ((string * vname list) * itype list) list)
427 | Datatypecons of string * string
428 | Class of class * (vname * ((class * string) list * (string * itype) list))
429 | Classrel of class * class
430 | Classparam of string * class
431 | Classinst of (class * (string * (vname * sort) list))
432 * ((class * (string * (string * dict list list))) list
433 * (((string * const) * (thm * bool)) list
434 * ((string * const) * (thm * bool)) list))
435 (*see also signature*);
437 type program = stmt Graph.T;
439 fun empty_funs program =
440 Graph.fold (fn (name, (Fun (c, ((_, []), _)), _)) => cons c
441 | _ => I) program [];
443 fun map_terms_bottom_up f (t as IConst _) = f t
444 | map_terms_bottom_up f (t as IVar _) = f t
445 | map_terms_bottom_up f (t1 `$ t2) = f
446 (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
447 | map_terms_bottom_up f ((v, ty) `|=> t) = f
448 ((v, ty) `|=> map_terms_bottom_up f t)
449 | map_terms_bottom_up f (ICase (((t, ty), ps), t0)) = f
450 (ICase (((map_terms_bottom_up f t, ty), (map o pairself)
451 (map_terms_bottom_up f) ps), map_terms_bottom_up f t0));
453 fun map_classparam_instances_as_term f =
454 (map o apfst o apsnd) (fn const => case f (IConst const) of IConst const' => const')
456 fun map_terms_stmt f NoStmt = NoStmt
457 | map_terms_stmt f (Fun (c, ((tysm, eqs), case_cong))) = Fun (c, ((tysm, (map o apfst)
458 (fn (ts, t) => (map f ts, f t)) eqs), case_cong))
459 | map_terms_stmt f (stmt as Datatype _) = stmt
460 | map_terms_stmt f (stmt as Datatypecons _) = stmt
461 | map_terms_stmt f (stmt as Class _) = stmt
462 | map_terms_stmt f (stmt as Classrel _) = stmt
463 | map_terms_stmt f (stmt as Classparam _) = stmt
464 | map_terms_stmt f (Classinst (arity, (super_instances, classparam_instances))) =
465 Classinst (arity, (super_instances, (pairself o map_classparam_instances_as_term) f classparam_instances));
467 fun is_cons program name = case Graph.get_node program name
468 of Datatypecons _ => true
471 fun is_case (Fun (_, (_, SOME _))) = true
474 fun lookup_classparam_instance program name = program |> Graph.get_first
475 (fn (_, (Classinst ((class, _), (_, (param_insts, _))), _)) =>
476 Option.map (fn ((const, _), _) => (class, const))
477 (find_first (fn ((_, (inst_const, _)), _) => inst_const = name) param_insts) | _ => NONE)
479 fun labelled_name thy program name =
480 let val ctxt = Proof_Context.init_global thy in
481 case Graph.get_node program name of
482 Fun (c, _) => quote (Code.string_of_const thy c)
483 | Datatype (tyco, _) => "type " ^ quote (Proof_Context.extern_type ctxt tyco)
484 | Datatypecons (c, _) => quote (Code.string_of_const thy c)
485 | Class (class, _) => "class " ^ quote (Proof_Context.extern_class ctxt class)
486 | Classrel (sub, super) =>
488 val Class (sub, _) = Graph.get_node program sub;
489 val Class (super, _) = Graph.get_node program super;
491 quote (Proof_Context.extern_class ctxt sub ^ " < " ^ Proof_Context.extern_class ctxt super)
493 | Classparam (c, _) => quote (Code.string_of_const thy c)
494 | Classinst ((class, (tyco, _)), _) =>
496 val Class (class, _) = Graph.get_node program class;
497 val Datatype (tyco, _) = Graph.get_node program tyco;
499 quote (Proof_Context.extern_type ctxt tyco ^ " :: " ^ Proof_Context.extern_class ctxt class)
503 fun linear_stmts program =
504 rev (Graph.strong_conn program)
505 |> map (AList.make (Graph.get_node program));
507 fun group_stmts thy program =
509 fun is_fun (_, Fun _) = true | is_fun _ = false;
510 fun is_datatypecons (_, Datatypecons _) = true | is_datatypecons _ = false;
511 fun is_datatype (_, Datatype _) = true | is_datatype _ = false;
512 fun is_class (_, Class _) = true | is_class _ = false;
513 fun is_classrel (_, Classrel _) = true | is_classrel _ = false;
514 fun is_classparam (_, Classparam _) = true | is_classparam _ = false;
515 fun is_classinst (_, Classinst _) = true | is_classinst _ = false;
517 if forall (is_datatypecons orf is_datatype) stmts
518 then (filter is_datatype stmts, [], ([], []))
519 else if forall (is_class orf is_classrel orf is_classparam) stmts
520 then ([], filter is_class stmts, ([], []))
521 else if forall (is_fun orf is_classinst) stmts
522 then ([], [], List.partition is_fun stmts)
523 else error ("Illegal mutual dependencies: " ^
524 (commas o map (labelled_name thy program o fst)) stmts)
531 (** translation kernel **)
533 (* generic mechanisms *)
535 fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
537 fun add_dep name = case dep of NONE => I
538 | SOME dep => Graph.add_edge (dep, name);
539 val (name, naming') = case lookup naming thing
540 of SOME name => (name, naming)
541 | NONE => declare thing naming;
542 in case try (Graph.get_node program) name
543 of SOME stmt => program
549 |> Graph.default_node (name, NoStmt)
552 |> curry generate (SOME name)
554 |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
559 exception PERMISSIVE of unit;
561 fun translation_error thy permissive some_thm msg sub_msg =
563 then raise PERMISSIVE ()
568 SOME thm => "\n(in code equation " ^ Display.string_of_thm_global thy thm ^ ")"
570 in error (msg ^ err_thm ^ ":\n" ^ sub_msg) end;
572 fun not_wellsorted thy permissive some_thm ty sort e =
574 val err_class = Sorts.class_error (Context.pretty_global thy) e;
576 "Type " ^ Syntax.string_of_typ_global thy ty ^ " not of sort " ^
577 Syntax.string_of_sort_global thy sort;
579 translation_error thy permissive some_thm "Wellsortedness error"
580 (err_typ ^ "\n" ^ err_class)
584 (* inference of type annotations for disambiguation with type classes *)
586 fun mk_tagged_type (true, T) = Type ("", [T])
587 | mk_tagged_type (false, T) = T;
589 fun dest_tagged_type (Type ("", [T])) = (true, T)
590 | dest_tagged_type T = (false, T);
592 val untag_term = map_types (snd o dest_tagged_type);
594 fun tag_term (proj_sort, _) eqngr =
596 val has_sort_constraints = exists (not o null) o map proj_sort o Code_Preproc.sortargs eqngr;
597 fun tag (Const (c', T')) (Const (c, T)) =
599 mk_tagged_type (not (null (Term.add_tvarsT T' [])) andalso has_sort_constraints c, T))
600 | tag (t1 $ u1) (t $ u) = tag t1 t $ tag u1 u
601 | tag (Abs (_, _, t1)) (Abs (x, T, t)) = Abs (x, T, tag t1 t)
602 | tag (Free _) (t as Free _) = t
603 | tag (Var _) (t as Var _) = t
604 | tag (Bound _) (t as Bound _) = t;
609 fun annotate thy algbr eqngr (c, ty) args rhs =
611 val ctxt = Proof_Context.init_global thy |> Config.put Type_Infer_Context.const_sorts false
612 val erase = map_types (fn _ => Type_Infer.anyT [])
613 val reinfer = singleton (Type_Infer_Context.infer_types ctxt)
614 val lhs = list_comb (Const (c, ty), map (map_types Type.strip_sorts o fst) args)
615 val reinferred_rhs = snd (Logic.dest_equals (reinfer (Logic.mk_equals (lhs, erase rhs))))
617 tag_term algbr eqngr reinferred_rhs rhs
620 fun annotate_eqns thy algbr eqngr (c, ty) eqns =
621 map (apfst (fn (args, (rhs, some_abs)) => (args,
622 (annotate thy algbr eqngr (c, ty) args rhs, some_abs)))) eqns
627 fun ensure_tyco thy algbr eqngr permissive tyco =
629 val ((vs, cos), _) = Code.get_type thy tyco;
631 fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
632 ##>> fold_map (fn (c, (vs, tys)) =>
633 ensure_const thy algbr eqngr permissive c
634 ##>> pair (map (unprefix "'" o fst) vs)
635 ##>> fold_map (translate_typ thy algbr eqngr permissive) tys) cos
636 #>> (fn info => Datatype (tyco, info));
637 in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
638 and ensure_const thy algbr eqngr permissive c =
640 fun stmt_datatypecons tyco =
641 ensure_tyco thy algbr eqngr permissive tyco
642 #>> (fn tyco => Datatypecons (c, tyco));
643 fun stmt_classparam class =
644 ensure_class thy algbr eqngr permissive class
645 #>> (fn class => Classparam (c, class));
648 val ((vs, ty), eqns) = Code.equations_of_cert thy cert;
649 val eqns' = annotate_eqns thy algbr eqngr (c, ty) eqns
650 val some_case_cong = Code.get_case_cong thy c;
652 fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
653 ##>> translate_typ thy algbr eqngr permissive ty
654 ##>> translate_eqns thy algbr eqngr permissive eqns'
655 #>> (fn info => Fun (c, (info, some_case_cong)))
657 val stmt_const = case Code.get_type_of_constr_or_abstr thy c
658 of SOME (tyco, _) => stmt_datatypecons tyco
659 | NONE => (case AxClass.class_of_param thy c
660 of SOME class => stmt_classparam class
661 | NONE => stmt_fun (Code_Preproc.cert eqngr c))
662 in ensure_stmt lookup_const (declare_const thy) stmt_const c end
663 and ensure_class thy (algbr as (_, algebra)) eqngr permissive class =
665 val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
666 val cs = #params (AxClass.get_info thy class);
668 fold_map (fn super_class => ensure_class thy algbr eqngr permissive super_class
669 ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)) super_classes
670 ##>> fold_map (fn (c, ty) => ensure_const thy algbr eqngr permissive c
671 ##>> translate_typ thy algbr eqngr permissive ty) cs
672 #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
673 in ensure_stmt lookup_class (declare_class thy) stmt_class class end
674 and ensure_classrel thy algbr eqngr permissive (sub_class, super_class) =
677 ensure_class thy algbr eqngr permissive sub_class
678 ##>> ensure_class thy algbr eqngr permissive super_class
680 in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (sub_class, super_class) end
681 and ensure_inst thy (algbr as (_, algebra)) eqngr permissive (class, tyco) =
683 val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
684 val these_classparams = these o try (#params o AxClass.get_info thy);
685 val classparams = these_classparams class;
686 val further_classparams = maps these_classparams
687 ((Sorts.complete_sort algebra o Sorts.super_classes algebra) class);
688 val vs = Name.invent_names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
689 val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
690 val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
691 Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
692 val arity_typ = Type (tyco, map TFree vs);
693 val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
694 fun translate_super_instance super_class =
695 ensure_class thy algbr eqngr permissive super_class
696 ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)
697 ##>> translate_dicts thy algbr eqngr permissive NONE (arity_typ, [super_class])
698 #>> (fn ((super_class, classrel), [Dict ([], Dict_Const (inst, dss))]) =>
699 (super_class, (classrel, (inst, dss))));
700 fun translate_classparam_instance (c, ty) =
702 val raw_const = Const (c, map_type_tfree (K arity_typ') ty);
703 val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy raw_const);
704 val const = (apsnd Logic.unvarifyT_global o dest_Const o snd
705 o Logic.dest_equals o Thm.prop_of) thm;
707 ensure_const thy algbr eqngr permissive c
708 ##>> translate_const thy algbr eqngr permissive (SOME thm) (const, NONE)
709 #>> (fn (c, IConst const') => ((c, const'), (thm, true)))
712 ensure_class thy algbr eqngr permissive class
713 ##>> ensure_tyco thy algbr eqngr permissive tyco
714 ##>> fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
715 ##>> fold_map translate_super_instance super_classes
716 ##>> fold_map translate_classparam_instance classparams
717 ##>> fold_map translate_classparam_instance further_classparams
718 #>> (fn (((((class, tyco), arity_args), super_instances),
719 classparam_instances), further_classparam_instances) =>
720 Classinst ((class, (tyco, arity_args)), (super_instances,
721 (classparam_instances, further_classparam_instances))));
722 in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
723 and translate_typ thy algbr eqngr permissive (TFree (v, _)) =
724 pair (ITyVar (unprefix "'" v))
725 | translate_typ thy algbr eqngr permissive (Type (tyco, tys)) =
726 ensure_tyco thy algbr eqngr permissive tyco
727 ##>> fold_map (translate_typ thy algbr eqngr permissive) tys
728 #>> (fn (tyco, tys) => tyco `%% tys)
729 and translate_term thy algbr eqngr permissive some_thm (Const (c, ty), some_abs) =
730 translate_app thy algbr eqngr permissive some_thm (((c, ty), []), some_abs)
731 | translate_term thy algbr eqngr permissive some_thm (Free (v, _), some_abs) =
733 | translate_term thy algbr eqngr permissive some_thm (Abs (v, ty, t), some_abs) =
735 val (v', t') = Syntax_Trans.variant_abs (Name.desymbolize false v, ty, t);
736 val v'' = if member (op =) (Term.add_free_names t' []) v'
737 then SOME v' else NONE
739 translate_typ thy algbr eqngr permissive ty
740 ##>> translate_term thy algbr eqngr permissive some_thm (t', some_abs)
741 #>> (fn (ty, t) => (v'', ty) `|=> t)
743 | translate_term thy algbr eqngr permissive some_thm (t as _ $ _, some_abs) =
745 of (Const (c, ty), ts) =>
746 translate_app thy algbr eqngr permissive some_thm (((c, ty), ts), some_abs)
748 translate_term thy algbr eqngr permissive some_thm (t', some_abs)
749 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
750 #>> (fn (t, ts) => t `$$ ts)
751 and translate_eqn thy algbr eqngr permissive ((args, (rhs, some_abs)), (some_thm, proper)) =
752 fold_map (translate_term thy algbr eqngr permissive some_thm) args
753 ##>> translate_term thy algbr eqngr permissive some_thm (rhs, some_abs)
754 #>> rpair (some_thm, proper)
755 and translate_eqns thy algbr eqngr permissive eqns prgrm =
756 prgrm |> fold_map (translate_eqn thy algbr eqngr permissive) eqns
757 handle PERMISSIVE () => ([], prgrm)
758 and translate_const thy algbr eqngr permissive some_thm ((c, ty), some_abs) =
760 val _ = if (case some_abs of NONE => true | SOME abs => not (c = abs))
761 andalso Code.is_abstr thy c
762 then translation_error thy permissive some_thm
763 "Abstraction violation" ("constant " ^ Code.string_of_const thy c)
765 val (annotate, ty') = dest_tagged_type ty
766 val arg_typs = Sign.const_typargs thy (c, ty');
767 val sorts = Code_Preproc.sortargs eqngr c;
768 val (function_typs, body_typ) = Term.strip_type ty';
770 ensure_const thy algbr eqngr permissive c
771 ##>> fold_map (translate_typ thy algbr eqngr permissive) arg_typs
772 ##>> fold_map (translate_dicts thy algbr eqngr permissive some_thm) (arg_typs ~~ sorts)
773 ##>> fold_map (translate_typ thy algbr eqngr permissive) (body_typ :: function_typs)
774 #>> (fn (((c, arg_typs), dss), body_typ :: function_typs) =>
775 IConst (c, (((arg_typs, dss), (function_typs, body_typ)), annotate)))
777 and translate_app_const thy algbr eqngr permissive some_thm ((c_ty, ts), some_abs) =
778 translate_const thy algbr eqngr permissive some_thm (c_ty, some_abs)
779 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
780 #>> (fn (t, ts) => t `$$ ts)
781 and translate_case thy algbr eqngr permissive some_thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
783 fun arg_types num_args ty = fst (chop num_args (binder_types ty));
784 val tys = arg_types num_args (snd c_ty);
785 val ty = nth tys t_pos;
786 fun mk_constr NONE t = NONE
787 | mk_constr (SOME c) t =
789 val n = Code.args_number thy c;
790 in SOME ((c, arg_types n (fastype_of (untag_term t)) ---> ty), n) end;
792 if null case_pats then []
793 else map_filter I (map2 mk_constr case_pats (nth_drop t_pos ts));
794 fun casify naming constrs ty ts =
796 val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
797 fun collapse_clause vs_map ts body =
800 of IConst (c, _) => if member (op =) undefineds c
803 | ICase (((IVar (SOME v), _), subclauses), _) =>
804 if forall (fn (pat', body') => exists_var pat' v
805 orelse not (exists_var body' v)) subclauses
806 then case AList.lookup (op =) vs_map v
807 of SOME i => maps (fn (pat', body') =>
808 collapse_clause (AList.delete (op =) v vs_map)
809 (nth_map i (K pat') ts) body') subclauses
810 | NONE => [(ts, body)]
814 fun mk_clause mk tys t =
816 val (vs, body) = unfold_abs_eta tys t;
817 val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
818 val ts = map (IVar o fst) vs;
819 in map mk (collapse_clause vs_map ts body) end;
820 val t = nth ts t_pos;
821 val ts_clause = nth_drop t_pos ts;
822 val clauses = if null case_pats
823 then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
824 else maps (fn ((constr as IConst (_, ((_, (tys, _)), _)), n), t) =>
825 mk_clause (fn (ts, body) => (constr `$$ ts, body)) (take n tys) t)
826 (constrs ~~ (map_filter (fn (NONE, _) => NONE | (SOME _, t) => SOME t)
827 (case_pats ~~ ts_clause)));
828 in ((t, ty), clauses) end;
830 translate_const thy algbr eqngr permissive some_thm (c_ty, NONE)
831 ##>> fold_map (fn (constr, n) => translate_const thy algbr eqngr permissive some_thm (constr, NONE)
833 ##>> translate_typ thy algbr eqngr permissive ty
834 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
835 #-> (fn (((t, constrs), ty), ts) =>
836 `(fn (_, (naming, _)) => ICase (casify naming constrs ty ts, t `$$ ts)))
838 and translate_app_case thy algbr eqngr permissive some_thm (case_scheme as (num_args, _)) ((c, ty), ts) =
839 if length ts < num_args then
842 val tys = (take (num_args - k) o drop k o fst o strip_type) ty;
843 val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
844 val vs = Name.invent_names ctxt "a" tys;
846 fold_map (translate_typ thy algbr eqngr permissive) tys
847 ##>> translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts @ map Free vs)
848 #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
850 else if length ts > num_args then
851 translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), take num_args ts)
852 ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) (drop num_args ts)
853 #>> (fn (t, ts) => t `$$ ts)
855 translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts)
856 and translate_app thy algbr eqngr permissive some_thm (c_ty_ts as ((c, _), _), some_abs) =
857 case Code.get_case_scheme thy c
858 of SOME case_scheme => translate_app_case thy algbr eqngr permissive some_thm case_scheme c_ty_ts
859 | NONE => translate_app_const thy algbr eqngr permissive some_thm (c_ty_ts, some_abs)
860 and translate_tyvar_sort thy (algbr as (proj_sort, _)) eqngr permissive (v, sort) =
861 fold_map (ensure_class thy algbr eqngr permissive) (proj_sort sort)
862 #>> (fn sort => (unprefix "'" v, sort))
863 and translate_dicts thy (algbr as (proj_sort, algebra)) eqngr permissive some_thm (ty, sort) =
865 datatype typarg_witness =
866 Weakening of (class * class) list * plain_typarg_witness
867 and plain_typarg_witness =
868 Global of (class * string) * typarg_witness list list
869 | Local of string * (int * sort);
870 fun class_relation ((Weakening (classrels, x)), sub_class) super_class =
871 Weakening ((sub_class, super_class) :: classrels, x);
872 fun type_constructor (tyco, _) dss class =
873 Weakening ([], Global ((class, tyco), (map o map) fst dss));
874 fun type_variable (TFree (v, sort)) =
876 val sort' = proj_sort sort;
877 in map_index (fn (n, class) => (Weakening ([], Local (v, (n, sort'))), class)) sort' end;
878 val typarg_witnesses = Sorts.of_sort_derivation algebra
879 {class_relation = K (Sorts.classrel_derivation algebra class_relation),
880 type_constructor = type_constructor,
881 type_variable = type_variable} (ty, proj_sort sort)
882 handle Sorts.CLASS_ERROR e => not_wellsorted thy permissive some_thm ty sort e;
883 fun mk_dict (Weakening (classrels, x)) =
884 fold_map (ensure_classrel thy algbr eqngr permissive) classrels
887 and mk_plain_dict (Global (inst, dss)) =
888 ensure_inst thy algbr eqngr permissive inst
889 ##>> (fold_map o fold_map) mk_dict dss
890 #>> (fn (inst, dss) => Dict_Const (inst, dss))
891 | mk_plain_dict (Local (v, (n, sort))) =
892 pair (Dict_Var (unprefix "'" v, (n, length sort)))
893 in fold_map mk_dict typarg_witnesses end;
898 structure Program = Code_Data
900 type T = naming * program;
901 val empty = (empty_naming, Graph.empty);
904 fun invoke_generation ignore_cache thy (algebra, eqngr) generate thing =
905 Program.change_yield (if ignore_cache then NONE else SOME thy)
906 (fn naming_program => (NONE, naming_program)
907 |> generate thy algebra eqngr thing
908 |-> (fn thing => fn (_, naming_program) => (thing, naming_program)));
911 (* program generation *)
913 fun consts_program thy permissive consts =
915 fun project_consts consts (naming, program) =
916 if permissive then (consts, (naming, program))
917 else (consts, (naming, Graph.restrict
918 (member (op =) (Graph.all_succs program consts)) program));
919 fun generate_consts thy algebra eqngr =
920 fold_map (ensure_const thy algebra eqngr permissive);
922 invoke_generation permissive thy (Code_Preproc.obtain false thy consts [])
923 generate_consts consts
928 (* value evaluation *)
930 fun ensure_value thy algbr eqngr t =
932 val ty = fastype_of t;
933 val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
934 o dest_TFree))) t [];
935 val t' = annotate thy algbr eqngr (Term.dummy_patternN, ty) [] t;
937 fold_map (translate_tyvar_sort thy algbr eqngr false) vs
938 ##>> translate_typ thy algbr eqngr false ty
939 ##>> translate_term thy algbr eqngr false NONE (t', NONE)
940 #>> (fn ((vs, ty), t) => Fun
941 (Term.dummy_patternN, (((vs, ty), [(([], t), (NONE, true))]), NONE)));
942 fun term_value (dep, (naming, program1)) =
944 val Fun (_, ((vs_ty, [(([], t), _)]), _)) =
945 Graph.get_node program1 Term.dummy_patternN;
946 val deps = Graph.immediate_succs program1 Term.dummy_patternN;
947 val program2 = Graph.del_node Term.dummy_patternN program1;
948 val deps_all = Graph.all_succs program2 deps;
949 val program3 = Graph.restrict (member (op =) deps_all) program2;
950 in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
952 ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
957 fun original_sorts vs =
958 map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v));
960 fun dynamic_evaluator thy evaluator algebra eqngr vs t =
962 val (((naming, program), (((vs', ty'), t'), deps)), _) =
963 invoke_generation false thy (algebra, eqngr) ensure_value t;
964 in evaluator naming program ((original_sorts vs vs', (vs', ty')), t') deps end;
966 fun dynamic_conv thy evaluator =
967 Code_Preproc.dynamic_conv thy (dynamic_evaluator thy evaluator);
969 fun dynamic_value thy postproc evaluator =
970 Code_Preproc.dynamic_value thy postproc (dynamic_evaluator thy evaluator);
972 fun lift_evaluation thy evaluation' algebra eqngr naming program vs t =
974 val (((_, program'), (((vs', ty'), t'), deps)), _) =
975 ensure_value thy algebra eqngr t (NONE, (naming, program));
976 in evaluation' ((original_sorts vs vs', (vs', ty')), t') deps end;
978 fun lift_evaluator thy evaluator' consts algebra eqngr =
980 fun generate_consts thy algebra eqngr =
981 fold_map (ensure_const thy algebra eqngr false);
982 val (consts', (naming, program)) =
983 invoke_generation true thy (algebra, eqngr) generate_consts consts;
984 val evaluation' = evaluator' naming program consts';
985 in lift_evaluation thy evaluation' algebra eqngr naming program end;
987 fun lift_evaluator_simple thy evaluator' consts algebra eqngr =
989 fun generate_consts thy algebra eqngr =
990 fold_map (ensure_const thy algebra eqngr false);
991 val (consts', (naming, program)) =
992 invoke_generation true thy (algebra, eqngr) generate_consts consts;
993 in evaluator' program end;
995 fun static_conv thy consts conv =
996 Code_Preproc.static_conv thy consts (lift_evaluator thy conv consts);
998 fun static_conv_simple thy consts conv =
999 Code_Preproc.static_conv thy consts (lift_evaluator_simple thy conv consts);
1001 fun static_value thy postproc consts evaluator =
1002 Code_Preproc.static_value thy postproc consts (lift_evaluator thy evaluator consts);
1005 (** diagnostic commands **)
1007 fun read_const_exprs thy =
1009 fun consts_of thy' = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
1010 ((snd o #constants o Consts.dest o Sign.consts_of) thy') [];
1011 fun belongs_here thy' c = forall
1012 (fn thy'' => not (Sign.declared_const thy'' c)) (Theory.parents_of thy');
1013 fun consts_of_select thy' = filter (belongs_here thy') (consts_of thy');
1014 fun read_const_expr "_" = ([], consts_of thy)
1015 | read_const_expr s = if String.isSuffix "._" s
1016 then ([], consts_of_select (Context.this_theory thy (unsuffix "._" s)))
1017 else ([Code.read_const thy s], []);
1018 in pairself flat o split_list o map read_const_expr end;
1020 fun code_depgr thy consts =
1022 val (_, eqngr) = Code_Preproc.obtain true thy consts [];
1023 val all_consts = Graph.all_succs eqngr consts;
1024 in Graph.restrict (member (op =) all_consts) eqngr end;
1026 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
1028 fun code_deps thy consts =
1030 val eqngr = code_depgr thy consts;
1031 val constss = Graph.strong_conn eqngr;
1032 val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
1033 Symtab.update (const, consts)) consts) constss;
1034 fun succs consts = consts
1035 |> maps (Graph.immediate_succs eqngr)
1036 |> subtract (op =) consts
1037 |> map (the o Symtab.lookup mapping)
1039 val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
1040 fun namify consts = map (Code.string_of_const thy) consts
1042 val prgr = map (fn (consts, constss) =>
1043 { name = namify consts, ID = namify consts, dir = "", unfold = true,
1044 path = "", parents = map namify constss }) conn;
1045 in Present.display_graph prgr end;
1049 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
1050 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
1055 Outer_Syntax.improper_command @{command_spec "code_thms"}
1056 "print system of code equations for code"
1057 (Scan.repeat1 Parse.term_group
1058 >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
1059 o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
1062 Outer_Syntax.improper_command @{command_spec "code_deps"}
1063 "visualize dependencies of code equations for code"
1064 (Scan.repeat1 Parse.term_group
1065 >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
1066 o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
1073 structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;