berghofe@11520: (* Title: Pure/codegen.ML berghofe@11520: ID: $Id$ wenzelm@11539: Author: Stefan Berghofer, TU Muenchen berghofe@11520: wenzelm@11539: Generic code generator. berghofe@11520: *) berghofe@11520: berghofe@11520: signature CODEGEN = berghofe@11520: sig berghofe@11520: val quiet_mode : bool ref berghofe@11520: val message : string -> unit berghofe@13753: val mode : string list ref berghofe@13886: val margin : int ref berghofe@11520: berghofe@12452: datatype 'a mixfix = berghofe@11520: Arg berghofe@11520: | Ignore berghofe@11520: | Pretty of Pretty.T berghofe@12452: | Quote of 'a; berghofe@11520: berghofe@12452: type 'a codegen berghofe@12452: berghofe@12452: val add_codegen: string -> term codegen -> theory -> theory berghofe@12452: val add_tycodegen: string -> typ codegen -> theory -> theory berghofe@14197: val add_attribute: string -> (Args.T list -> theory attribute * Args.T list) -> theory -> theory berghofe@15261: val add_preprocessor: (theory -> thm list -> thm list) -> theory -> theory berghofe@15261: val preprocess: theory -> thm list -> thm list berghofe@11520: val print_codegens: theory -> unit berghofe@11520: val generate_code: theory -> (string * string) list -> string berghofe@11520: val generate_code_i: theory -> (string * term) list -> string berghofe@12452: val assoc_consts: (xstring * string option * term mixfix list) list -> theory -> theory berghofe@12452: val assoc_consts_i: (xstring * typ option * term mixfix list) list -> theory -> theory berghofe@12452: val assoc_types: (xstring * typ mixfix list) list -> theory -> theory berghofe@12452: val get_assoc_code: theory -> string -> typ -> term mixfix list option berghofe@12452: val get_assoc_type: theory -> string -> typ mixfix list option berghofe@12452: val invoke_codegen: theory -> string -> bool -> berghofe@12452: (exn option * string) Graph.T * term -> (exn option * string) Graph.T * Pretty.T berghofe@12452: val invoke_tycodegen: theory -> string -> bool -> berghofe@12452: (exn option * string) Graph.T * typ -> (exn option * string) Graph.T * Pretty.T berghofe@14858: val mk_id: string -> string berghofe@11520: val mk_const_id: Sign.sg -> string -> string berghofe@11520: val mk_type_id: Sign.sg -> string -> string berghofe@11520: val rename_term: term -> term berghofe@15398: val new_names: term -> string list -> string list berghofe@15398: val new_name: term -> string -> string berghofe@11520: val get_defn: theory -> string -> typ -> ((term list * term) * int option) option berghofe@11520: val is_instance: theory -> typ -> typ -> bool berghofe@11520: val parens: Pretty.T -> Pretty.T berghofe@11520: val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T berghofe@11520: val eta_expand: term -> term list -> int -> term berghofe@14105: val strip_tname: string -> string berghofe@13753: val mk_type: bool -> typ -> Pretty.T berghofe@13753: val mk_term_of: Sign.sg -> bool -> typ -> Pretty.T berghofe@14105: val mk_gen: Sign.sg -> bool -> string list -> string -> typ -> Pretty.T berghofe@14105: val test_fn: (int -> (string * term) list option) ref berghofe@14105: val test_term: theory -> int -> int -> term -> (string * term) list option berghofe@12452: val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list berghofe@11520: val parsers: OuterSyntax.parser list berghofe@11520: val setup: (theory -> theory) list berghofe@11520: end; berghofe@11520: berghofe@11520: structure Codegen : CODEGEN = berghofe@11520: struct berghofe@11520: berghofe@11520: val quiet_mode = ref true; berghofe@11520: fun message s = if !quiet_mode then () else writeln s; berghofe@11520: berghofe@13753: val mode = ref ([] : string list); berghofe@13753: berghofe@13886: val margin = ref 80; berghofe@13886: berghofe@11520: (**** Mixfix syntax ****) berghofe@11520: berghofe@12452: datatype 'a mixfix = berghofe@11520: Arg berghofe@11520: | Ignore berghofe@11520: | Pretty of Pretty.T berghofe@12452: | Quote of 'a; berghofe@11520: berghofe@11520: fun is_arg Arg = true berghofe@11520: | is_arg Ignore = true berghofe@11520: | is_arg _ = false; berghofe@11520: berghofe@12452: fun quotes_of [] = [] berghofe@12452: | quotes_of (Quote q :: ms) = q :: quotes_of ms berghofe@12452: | quotes_of (_ :: ms) = quotes_of ms; berghofe@12452: berghofe@12452: fun args_of [] xs = ([], xs) berghofe@12452: | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs) berghofe@12452: | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs berghofe@12452: | args_of (_ :: ms) xs = args_of ms xs; berghofe@11520: wenzelm@12490: fun num_args x = length (filter is_arg x); berghofe@11520: berghofe@11520: berghofe@11520: (**** theory data ****) berghofe@11520: berghofe@14105: (* type of code generators *) berghofe@11520: berghofe@12452: type 'a codegen = theory -> (exn option * string) Graph.T -> berghofe@12452: string -> bool -> 'a -> ((exn option * string) Graph.T * Pretty.T) option; berghofe@12452: berghofe@14105: (* parameters for random testing *) berghofe@14105: berghofe@14105: type test_params = berghofe@14105: {size: int, iterations: int, default_type: typ option}; berghofe@14105: berghofe@14105: fun merge_test_params berghofe@14105: {size = size1, iterations = iterations1, default_type = default_type1} berghofe@14105: {size = size2, iterations = iterations2, default_type = default_type2} = berghofe@14105: {size = Int.max (size1, size2), berghofe@14105: iterations = Int.max (iterations1, iterations2), berghofe@14105: default_type = case default_type1 of berghofe@14105: None => default_type2 berghofe@14105: | _ => default_type1}; berghofe@14105: berghofe@14105: val default_test_params : test_params = berghofe@14105: {size = 10, iterations = 100, default_type = None}; berghofe@14105: berghofe@14105: fun set_size size ({iterations, default_type, ...} : test_params) = berghofe@14105: {size = size, iterations = iterations, default_type = default_type}; berghofe@14105: berghofe@14105: fun set_iterations iterations ({size, default_type, ...} : test_params) = berghofe@14105: {size = size, iterations = iterations, default_type = default_type}; berghofe@14105: berghofe@14105: fun set_default_type s sg ({size, iterations, ...} : test_params) = berghofe@14105: {size = size, iterations = iterations, berghofe@14105: default_type = Some (typ_of (read_ctyp sg s))}; berghofe@14105: berghofe@14105: (* data kind 'Pure/codegen' *) berghofe@14105: berghofe@11520: structure CodegenArgs = berghofe@11520: struct berghofe@11520: val name = "Pure/codegen"; berghofe@11520: type T = berghofe@12452: {codegens : (string * term codegen) list, berghofe@12452: tycodegens : (string * typ codegen) list, berghofe@12452: consts : ((string * typ) * term mixfix list) list, berghofe@12555: types : (string * typ mixfix list) list, berghofe@14197: attrs: (string * (Args.T list -> theory attribute * Args.T list)) list, berghofe@15261: preprocs: (stamp * (theory -> thm list -> thm list)) list, berghofe@14105: test_params: test_params}; berghofe@11520: berghofe@12555: val empty = berghofe@14105: {codegens = [], tycodegens = [], consts = [], types = [], attrs = [], berghofe@15261: preprocs = [], test_params = default_test_params}; berghofe@11520: val copy = I; berghofe@11520: val prep_ext = I; berghofe@11520: berghofe@12555: fun merge berghofe@12555: ({codegens = codegens1, tycodegens = tycodegens1, berghofe@14105: consts = consts1, types = types1, attrs = attrs1, berghofe@15261: preprocs = preprocs1, test_params = test_params1}, berghofe@12555: {codegens = codegens2, tycodegens = tycodegens2, berghofe@14105: consts = consts2, types = types2, attrs = attrs2, berghofe@15261: preprocs = preprocs2, test_params = test_params2}) = berghofe@15261: {codegens = merge_alists' codegens1 codegens2, berghofe@15261: tycodegens = merge_alists' tycodegens1 tycodegens2, berghofe@12555: consts = merge_alists consts1 consts2, berghofe@12555: types = merge_alists types1 types2, berghofe@14105: attrs = merge_alists attrs1 attrs2, berghofe@15261: preprocs = merge_alists' preprocs1 preprocs2, berghofe@14105: test_params = merge_test_params test_params1 test_params2}; berghofe@11520: berghofe@12452: fun print sg ({codegens, tycodegens, ...} : T) = berghofe@12452: Pretty.writeln (Pretty.chunks berghofe@12452: [Pretty.strs ("term code generators:" :: map fst codegens), berghofe@12452: Pretty.strs ("type code generators:" :: map fst tycodegens)]); berghofe@11520: end; berghofe@11520: berghofe@11520: structure CodegenData = TheoryDataFun(CodegenArgs); berghofe@11520: val print_codegens = CodegenData.print; berghofe@11520: berghofe@11520: berghofe@14105: (**** access parameters for random testing ****) berghofe@14105: berghofe@14105: fun get_test_params thy = #test_params (CodegenData.get thy); berghofe@14105: berghofe@14105: fun map_test_params f thy = berghofe@15261: let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} = berghofe@14105: CodegenData.get thy; berghofe@14105: in CodegenData.put {codegens = codegens, tycodegens = tycodegens, berghofe@15261: consts = consts, types = types, attrs = attrs, preprocs = preprocs, berghofe@14105: test_params = f test_params} thy berghofe@14105: end; berghofe@14105: berghofe@14105: berghofe@12452: (**** add new code generators to theory ****) berghofe@11520: berghofe@11520: fun add_codegen name f thy = berghofe@15261: let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} = berghofe@14105: CodegenData.get thy berghofe@11520: in (case assoc (codegens, name) of berghofe@12452: None => CodegenData.put {codegens = (name, f) :: codegens, berghofe@12555: tycodegens = tycodegens, consts = consts, types = types, berghofe@15261: attrs = attrs, preprocs = preprocs, test_params = test_params} thy berghofe@12452: | Some _ => error ("Code generator " ^ name ^ " already declared")) berghofe@12452: end; berghofe@12452: berghofe@12452: fun add_tycodegen name f thy = berghofe@15261: let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} = berghofe@14105: CodegenData.get thy berghofe@12452: in (case assoc (tycodegens, name) of berghofe@12452: None => CodegenData.put {tycodegens = (name, f) :: tycodegens, berghofe@12555: codegens = codegens, consts = consts, types = types, berghofe@15261: attrs = attrs, preprocs = preprocs, test_params = test_params} thy berghofe@11520: | Some _ => error ("Code generator " ^ name ^ " already declared")) berghofe@11520: end; berghofe@11520: berghofe@11520: berghofe@12555: (**** code attribute ****) berghofe@12555: berghofe@12555: fun add_attribute name att thy = berghofe@15261: let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} = berghofe@14105: CodegenData.get thy berghofe@12555: in (case assoc (attrs, name) of berghofe@12555: None => CodegenData.put {tycodegens = tycodegens, berghofe@12555: codegens = codegens, consts = consts, types = types, berghofe@15261: attrs = if name = "" then attrs @ [(name, att)] else (name, att) :: attrs, berghofe@15261: preprocs = preprocs, berghofe@15261: test_params = test_params} thy berghofe@12555: | Some _ => error ("Code attribute " ^ name ^ " already declared")) berghofe@12555: end; berghofe@12555: berghofe@14197: fun mk_parser (a, p) = (if a = "" then Scan.succeed "" else Args.$$$ a) |-- p; berghofe@14197: berghofe@12555: val code_attr = berghofe@14197: Attrib.syntax (Scan.depend (fn thy => foldr op || (map mk_parser berghofe@14197: (#attrs (CodegenData.get thy)), Scan.fail) >> pair thy)); berghofe@12555: berghofe@12555: berghofe@15261: (**** preprocessors ****) berghofe@15261: berghofe@15261: fun add_preprocessor p thy = berghofe@15261: let val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} = berghofe@15261: CodegenData.get thy berghofe@15261: in CodegenData.put {tycodegens = tycodegens, berghofe@15261: codegens = codegens, consts = consts, types = types, berghofe@15261: attrs = attrs, preprocs = (stamp (), p) :: preprocs, berghofe@15261: test_params = test_params} thy berghofe@15261: end; berghofe@15261: berghofe@15261: fun preprocess thy ths = berghofe@15261: let val {preprocs, ...} = CodegenData.get thy berghofe@15261: in foldl (fn (ths, (_, f)) => f thy ths) (ths, preprocs) end; berghofe@15261: berghofe@15261: fun unfold_attr (thy, eqn) = berghofe@15261: let berghofe@15261: val (name, _) = dest_Const (head_of berghofe@15261: (fst (Logic.dest_equals (prop_of eqn)))); berghofe@15261: fun prep thy = map (fn th => berghofe@15261: if name mem term_consts (prop_of th) then berghofe@15398: rewrite_rule [eqn] (Thm.transfer thy th) berghofe@15261: else th) berghofe@15261: in (add_preprocessor prep thy, eqn) end; berghofe@15261: berghofe@15261: berghofe@11520: (**** associate constants with target language code ****) berghofe@11520: berghofe@11520: fun gen_assoc_consts prep_type xs thy = foldl (fn (thy, (s, tyopt, syn)) => berghofe@11520: let berghofe@11520: val sg = sign_of thy; berghofe@15261: val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} = berghofe@14105: CodegenData.get thy; berghofe@11520: val cname = Sign.intern_const sg s; berghofe@11520: in berghofe@11520: (case Sign.const_type sg cname of berghofe@11520: Some T => berghofe@11520: let val T' = (case tyopt of berghofe@11520: None => T berghofe@11520: | Some ty => berghofe@11520: let val U = prep_type sg ty wenzelm@14769: in if Sign.typ_instance sg (U, T) then U berghofe@11520: else error ("Illegal type constraint for constant " ^ cname) berghofe@11520: end) berghofe@11520: in (case assoc (consts, (cname, T')) of berghofe@11520: None => CodegenData.put {codegens = codegens, berghofe@12452: tycodegens = tycodegens, berghofe@12555: consts = ((cname, T'), syn) :: consts, berghofe@15261: types = types, attrs = attrs, preprocs = preprocs, berghofe@15261: test_params = test_params} thy berghofe@11520: | Some _ => error ("Constant " ^ cname ^ " already associated with code")) berghofe@11520: end berghofe@11520: | _ => error ("Not a constant: " ^ s)) berghofe@11520: end) (thy, xs); berghofe@11520: berghofe@11520: val assoc_consts_i = gen_assoc_consts (K I); berghofe@11520: val assoc_consts = gen_assoc_consts (fn sg => typ_of o read_ctyp sg); berghofe@11520: berghofe@11520: (**** associate types with target language types ****) berghofe@11520: berghofe@11520: fun assoc_types xs thy = foldl (fn (thy, (s, syn)) => berghofe@11520: let berghofe@15261: val {codegens, tycodegens, consts, types, attrs, preprocs, test_params} = berghofe@14105: CodegenData.get thy; berghofe@11520: val tc = Sign.intern_tycon (sign_of thy) s berghofe@11520: in berghofe@11520: (case assoc (types, tc) of berghofe@12452: None => CodegenData.put {codegens = codegens, berghofe@12452: tycodegens = tycodegens, consts = consts, berghofe@14105: types = (tc, syn) :: types, attrs = attrs, berghofe@15261: preprocs = preprocs, test_params = test_params} thy berghofe@11520: | Some _ => error ("Type " ^ tc ^ " already associated with code")) berghofe@11520: end) (thy, xs); berghofe@11520: berghofe@12452: fun get_assoc_type thy s = assoc (#types (CodegenData.get thy), s); wenzelm@11546: berghofe@11520: berghofe@11520: (**** make valid ML identifiers ****) berghofe@11520: berghofe@14858: fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse berghofe@14858: Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x; berghofe@14858: berghofe@14858: fun dest_sym s = (case split_last (snd (take_prefix (equal "\\") (explode s))) of berghofe@14858: ("<" :: "^" :: xs, ">") => (true, implode xs) berghofe@14858: | ("<" :: xs, ">") => (false, implode xs) berghofe@14858: | _ => sys_error "dest_sym"); berghofe@14858: berghofe@14858: fun mk_id s = if s = "" then "" else berghofe@11520: let berghofe@14858: fun check_str [] = [] berghofe@14858: | check_str xs = (case take_prefix is_ascii_letdig xs of berghofe@14858: ([], " " :: zs) => check_str zs berghofe@14858: | ([], z :: zs) => berghofe@14858: if size z = 1 then string_of_int (ord z) :: check_str zs berghofe@14858: else (case dest_sym z of berghofe@14858: (true, "isub") => check_str zs berghofe@14858: | (true, "isup") => "" :: check_str zs berghofe@14858: | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs) berghofe@14858: | (ys, zs) => implode ys :: check_str zs); berghofe@14858: val s' = space_implode "_" berghofe@14858: (flat (map (check_str o Symbol.explode) (NameSpace.unpack s))) berghofe@11520: in berghofe@14858: if Symbol.is_ascii_letter (hd (explode s')) then s' else "id_" ^ s' berghofe@11520: end; berghofe@11520: berghofe@14858: fun mk_const_id sg s = berghofe@14858: let val s' = mk_id (Sign.cond_extern sg Sign.constK s) berghofe@14858: in if s' mem ThmDatabase.ml_reserved then s' ^ "_const" else s' end; berghofe@13073: berghofe@14858: fun mk_type_id sg s = berghofe@14858: let val s' = mk_id (Sign.cond_extern sg Sign.typeK s) berghofe@14858: in if s' mem ThmDatabase.ml_reserved then s' ^ "_type" else s' end; berghofe@11520: berghofe@13731: fun rename_terms ts = berghofe@11520: let berghofe@13731: val names = foldr add_term_names berghofe@13731: (ts, map (fst o fst) (Drule.vars_of_terms ts)); berghofe@14858: val reserved = names inter ThmDatabase.ml_reserved; berghofe@14858: val (illegal, alt_names) = split_list (mapfilter (fn s => berghofe@14858: let val s' = mk_id s in if s = s' then None else Some (s, s') end) names) berghofe@14858: val ps = (reserved @ illegal) ~~ berghofe@14858: variantlist (map (suffix "'") reserved @ alt_names, names); berghofe@11520: berghofe@14858: fun rename_id s = if_none (assoc (ps, s)) s; berghofe@14858: berghofe@14858: fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T) berghofe@14858: | rename (Free (a, T)) = Free (rename_id a, T) berghofe@11520: | rename (Abs (s, T, t)) = Abs (s, T, rename t) berghofe@11520: | rename (t $ u) = rename t $ rename u berghofe@11520: | rename t = t; berghofe@11520: in berghofe@13731: map rename ts berghofe@13731: end; berghofe@13731: berghofe@13731: val rename_term = hd o rename_terms o single; berghofe@13731: berghofe@13731: berghofe@13731: (**** retrieve definition of constant ****) berghofe@13731: berghofe@13731: fun is_instance thy T1 T2 = wenzelm@14769: Sign.typ_instance (sign_of thy) (T1, Type.varifyT T2); berghofe@13731: berghofe@13731: fun get_assoc_code thy s T = apsome snd (find_first (fn ((s', T'), _) => berghofe@13731: s = s' andalso is_instance thy T T') (#consts (CodegenData.get thy))); berghofe@13731: berghofe@13731: fun get_defn thy s T = berghofe@13731: let berghofe@13731: val axms = flat (map (Symtab.dest o #axioms o Theory.rep_theory) berghofe@13731: (thy :: Theory.ancestors_of thy)); berghofe@15261: fun prep_def def = (case preprocess thy [def] of berghofe@15261: [def'] => prop_of def' | _ => error "get_defn: bad preprocessor"); berghofe@15261: fun dest t = berghofe@15261: let berghofe@15261: val (lhs, rhs) = Logic.dest_equals t; berghofe@15261: val (c, args) = strip_comb lhs; berghofe@15261: val (s', T') = dest_Const c berghofe@15261: in if s = s' then Some (T', (args, rhs)) else None berghofe@15261: end handle TERM _ => None; berghofe@15261: val defs = mapfilter (fn (name, t) => apsome (pair name) (dest t)) axms; berghofe@15261: val i = find_index (is_instance thy T o fst o snd) defs berghofe@13731: in berghofe@15261: if i >= 0 then berghofe@15261: let val (name, (T', (args, _))) = nth_elem (i, defs) berghofe@15261: in case dest (prep_def (Thm.get_axiom thy name)) of berghofe@15261: None => None berghofe@15261: | Some (T'', p as (args', rhs)) => berghofe@15261: if T' = T'' andalso args = args' then berghofe@15261: Some (split_last (rename_terms (args @ [rhs])), berghofe@15261: if length defs = 1 then None else Some i) berghofe@15261: else None berghofe@15261: end berghofe@13731: else None berghofe@11520: end; berghofe@11520: berghofe@11520: berghofe@12452: (**** invoke suitable code generator for term / type ****) berghofe@11520: berghofe@12452: fun invoke_codegen thy dep brack (gr, t) = (case get_first berghofe@11520: (fn (_, f) => f thy gr dep brack t) (#codegens (CodegenData.get thy)) of berghofe@11520: None => error ("Unable to generate code for term:\n" ^ berghofe@11520: Sign.string_of_term (sign_of thy) t ^ "\nrequired by:\n" ^ berghofe@11520: commas (Graph.all_succs gr [dep])) berghofe@12452: | Some x => x); berghofe@12452: berghofe@12452: fun invoke_tycodegen thy dep brack (gr, T) = (case get_first berghofe@12452: (fn (_, f) => f thy gr dep brack T) (#tycodegens (CodegenData.get thy)) of berghofe@12452: None => error ("Unable to generate code for type:\n" ^ berghofe@12452: Sign.string_of_typ (sign_of thy) T ^ "\nrequired by:\n" ^ berghofe@12452: commas (Graph.all_succs gr [dep])) berghofe@12452: | Some x => x); berghofe@11520: berghofe@11520: berghofe@11520: (**** code generator for mixfix expressions ****) berghofe@11520: berghofe@11520: fun parens p = Pretty.block [Pretty.str "(", p, Pretty.str ")"]; berghofe@11520: berghofe@11520: fun pretty_fn [] p = [p] berghofe@11520: | pretty_fn (x::xs) p = Pretty.str ("fn " ^ x ^ " =>") :: berghofe@11520: Pretty.brk 1 :: pretty_fn xs p; berghofe@11520: berghofe@11520: fun pretty_mixfix [] [] _ = [] berghofe@11520: | pretty_mixfix (Arg :: ms) (p :: ps) qs = p :: pretty_mixfix ms ps qs berghofe@12452: | pretty_mixfix (Ignore :: ms) ps qs = pretty_mixfix ms ps qs berghofe@11520: | pretty_mixfix (Pretty p :: ms) ps qs = p :: pretty_mixfix ms ps qs berghofe@12452: | pretty_mixfix (Quote _ :: ms) ps (q :: qs) = q :: pretty_mixfix ms ps qs; berghofe@11520: berghofe@11520: berghofe@12452: (**** default code generators ****) berghofe@11520: berghofe@11520: fun eta_expand t ts i = berghofe@11520: let berghofe@11520: val (Ts, _) = strip_type (fastype_of t); berghofe@11520: val j = i - length ts berghofe@11520: in berghofe@11520: foldr (fn (T, t) => Abs ("x", T, t)) berghofe@11520: (take (j, Ts), list_comb (t, ts @ map Bound (j-1 downto 0))) berghofe@11520: end; berghofe@11520: berghofe@11520: fun mk_app _ p [] = p berghofe@11520: | mk_app brack p ps = if brack then berghofe@11520: Pretty.block (Pretty.str "(" :: berghofe@11520: separate (Pretty.brk 1) (p :: ps) @ [Pretty.str ")"]) berghofe@11520: else Pretty.block (separate (Pretty.brk 1) (p :: ps)); berghofe@11520: berghofe@14858: fun new_names t xs = variantlist (map mk_id xs, berghofe@11520: map (fst o fst o dest_Var) (term_vars t) union berghofe@11520: add_term_names (t, ThmDatabase.ml_reserved)); berghofe@11520: berghofe@11520: fun new_name t x = hd (new_names t [x]); berghofe@11520: berghofe@11520: fun default_codegen thy gr dep brack t = berghofe@11520: let berghofe@11520: val (u, ts) = strip_comb t; berghofe@12452: fun codegens brack = foldl_map (invoke_codegen thy dep brack) berghofe@11520: in (case u of berghofe@14105: Var ((s, i), T) => berghofe@14105: let berghofe@14105: val (gr', ps) = codegens true (gr, ts); berghofe@14105: val (gr'', _) = invoke_tycodegen thy dep false (gr', T) berghofe@14105: in Some (gr'', mk_app brack (Pretty.str (s ^ berghofe@11520: (if i=0 then "" else string_of_int i))) ps) berghofe@11520: end berghofe@11520: berghofe@14105: | Free (s, T) => berghofe@14105: let berghofe@14105: val (gr', ps) = codegens true (gr, ts); berghofe@14105: val (gr'', _) = invoke_tycodegen thy dep false (gr', T) berghofe@14105: in Some (gr'', mk_app brack (Pretty.str s) ps) end berghofe@11520: berghofe@11520: | Const (s, T) => berghofe@11520: (case get_assoc_code thy s T of berghofe@11520: Some ms => berghofe@11520: let val i = num_args ms berghofe@11520: in if length ts < i then berghofe@11520: default_codegen thy gr dep brack (eta_expand u ts i) berghofe@11520: else berghofe@11520: let berghofe@12452: val (ts1, ts2) = args_of ms ts; berghofe@12452: val (gr1, ps1) = codegens false (gr, ts1); berghofe@12452: val (gr2, ps2) = codegens true (gr1, ts2); berghofe@12452: val (gr3, ps3) = codegens false (gr2, quotes_of ms); berghofe@11520: in berghofe@11520: Some (gr3, mk_app brack (Pretty.block (pretty_mixfix ms ps1 ps3)) ps2) berghofe@11520: end berghofe@11520: end berghofe@11520: | None => (case get_defn thy s T of berghofe@11520: None => None berghofe@11520: | Some ((args, rhs), k) => berghofe@11520: let berghofe@11520: val id = mk_const_id (sign_of thy) s ^ (case k of berghofe@11520: None => "" | Some i => "_def" ^ string_of_int i); berghofe@12452: val (gr', ps) = codegens true (gr, ts); berghofe@11520: in berghofe@11520: Some (Graph.add_edge (id, dep) gr' handle Graph.UNDEF _ => berghofe@11520: let berghofe@11520: val _ = message ("expanding definition of " ^ s); berghofe@11520: val (Ts, _) = strip_type T; berghofe@11520: val (args', rhs') = berghofe@11520: if not (null args) orelse null Ts then (args, rhs) else berghofe@11520: let val v = Free (new_name rhs "x", hd Ts) berghofe@11520: in ([v], betapply (rhs, v)) end; berghofe@12452: val (gr1, p) = invoke_codegen thy id false berghofe@12452: (Graph.add_edge (id, dep) berghofe@12452: (Graph.new_node (id, (None, "")) gr'), rhs'); berghofe@12452: val (gr2, xs) = codegens false (gr1, args'); berghofe@12580: val (gr3, ty) = invoke_tycodegen thy id false (gr2, T); wenzelm@14980: in Graph.map_node id (K (None, Pretty.string_of (Pretty.block berghofe@12580: (separate (Pretty.brk 1) (if null args' then berghofe@12580: [Pretty.str ("val " ^ id ^ " :"), ty] berghofe@12580: else Pretty.str ("fun " ^ id) :: xs) @ wenzelm@14980: [Pretty.str " =", Pretty.brk 1, p, Pretty.str ";"])) ^ "\n\n")) gr3 berghofe@11520: end, mk_app brack (Pretty.str id) ps) berghofe@11520: end)) berghofe@11520: berghofe@11520: | Abs _ => berghofe@11520: let berghofe@11520: val (bs, Ts) = ListPair.unzip (strip_abs_vars u); berghofe@11520: val t = strip_abs_body u berghofe@11520: val bs' = new_names t bs; berghofe@12452: val (gr1, ps) = codegens true (gr, ts); berghofe@12452: val (gr2, p) = invoke_codegen thy dep false berghofe@12452: (gr1, subst_bounds (map Free (rev (bs' ~~ Ts)), t)); berghofe@11520: in berghofe@11520: Some (gr2, mk_app brack (Pretty.block (Pretty.str "(" :: pretty_fn bs' p @ berghofe@11520: [Pretty.str ")"])) ps) berghofe@11520: end berghofe@11520: berghofe@11520: | _ => None) berghofe@11520: end; berghofe@11520: berghofe@12452: fun default_tycodegen thy gr dep brack (TVar ((s, i), _)) = berghofe@12452: Some (gr, Pretty.str (s ^ (if i = 0 then "" else string_of_int i))) berghofe@12452: | default_tycodegen thy gr dep brack (TFree (s, _)) = Some (gr, Pretty.str s) berghofe@12452: | default_tycodegen thy gr dep brack (Type (s, Ts)) = berghofe@12452: (case assoc (#types (CodegenData.get thy), s) of berghofe@12452: None => None berghofe@12452: | Some ms => berghofe@12452: let berghofe@12452: val (gr', ps) = foldl_map berghofe@12452: (invoke_tycodegen thy dep false) (gr, fst (args_of ms Ts)); berghofe@12452: val (gr'', qs) = foldl_map berghofe@12452: (invoke_tycodegen thy dep false) (gr', quotes_of ms) berghofe@12452: in Some (gr'', Pretty.block (pretty_mixfix ms ps qs)) end); berghofe@12452: berghofe@11520: berghofe@11520: fun output_code gr xs = implode (map (snd o Graph.get_node gr) berghofe@11520: (rev (Graph.all_preds gr xs))); berghofe@11520: berghofe@14598: fun gen_generate_code prep_term thy = berghofe@14598: setmp print_mode [] (Pretty.setmp_margin (!margin) (fn xs => berghofe@11520: let berghofe@11520: val sg = sign_of thy; berghofe@11520: val gr = Graph.new_node ("", (None, "")) Graph.empty; berghofe@11520: val (gr', ps) = foldl_map (fn (gr, (s, t)) => apsnd (pair s) berghofe@12452: (invoke_codegen thy "" false (gr, t))) berghofe@12452: (gr, map (apsnd (prep_term sg)) xs) wenzelm@14818: val code = wenzelm@14818: "structure Generated =\nstruct\n\n" ^ wenzelm@14818: output_code gr' [""] ^ wenzelm@14818: space_implode "\n\n" (map (fn (s', p) => Pretty.string_of (Pretty.block wenzelm@14818: [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1, p, Pretty.str ";"])) ps) ^ wenzelm@14818: "\n\nend;\n\nopen Generated;\n"; wenzelm@14980: in code end)); berghofe@11520: berghofe@11520: val generate_code_i = gen_generate_code (K I); berghofe@11520: val generate_code = gen_generate_code berghofe@11520: (fn sg => term_of o read_cterm sg o rpair TypeInfer.logicT); berghofe@11520: berghofe@12452: berghofe@13753: (**** Reflection ****) berghofe@13753: berghofe@13753: val strip_tname = implode o tl o explode; berghofe@13753: berghofe@13753: fun pretty_list xs = Pretty.block (Pretty.str "[" :: berghofe@13753: flat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @ berghofe@13753: [Pretty.str "]"]); berghofe@13753: berghofe@13753: fun mk_type p (TVar ((s, i), _)) = Pretty.str berghofe@13753: (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T") berghofe@13753: | mk_type p (TFree (s, _)) = Pretty.str (strip_tname s ^ "T") berghofe@13753: | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block berghofe@13753: [Pretty.str "Type", Pretty.brk 1, Pretty.str ("(\"" ^ s ^ "\","), berghofe@13753: Pretty.brk 1, pretty_list (map (mk_type false) Ts), Pretty.str ")"]); berghofe@13753: berghofe@13753: fun mk_term_of sg p (TVar ((s, i), _)) = Pretty.str berghofe@13753: (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F") berghofe@13753: | mk_term_of sg p (TFree (s, _)) = Pretty.str (strip_tname s ^ "F") berghofe@13753: | mk_term_of sg p (Type (s, Ts)) = (if p then parens else I) (Pretty.block berghofe@13753: (separate (Pretty.brk 1) (Pretty.str ("term_of_" ^ mk_type_id sg s) :: berghofe@13753: flat (map (fn T => [mk_term_of sg true T, mk_type true T]) Ts)))); berghofe@13753: berghofe@13753: berghofe@14105: (**** Test data generators ****) berghofe@14105: berghofe@14105: fun mk_gen sg p xs a (TVar ((s, i), _)) = Pretty.str berghofe@14105: (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G") berghofe@14105: | mk_gen sg p xs a (TFree (s, _)) = Pretty.str (strip_tname s ^ "G") berghofe@14105: | mk_gen sg p xs a (Type (s, Ts)) = (if p then parens else I) (Pretty.block berghofe@14105: (separate (Pretty.brk 1) (Pretty.str ("gen_" ^ mk_type_id sg s ^ berghofe@14105: (if s mem xs then "'" else "")) :: map (mk_gen sg true xs a) Ts @ berghofe@14105: (if s mem xs then [Pretty.str a] else [])))); berghofe@14105: berghofe@14105: val test_fn : (int -> (string * term) list option) ref = ref (fn _ => None); berghofe@14105: berghofe@15029: fun test_term thy sz i = setmp print_mode [] (fn t => berghofe@14105: let berghofe@14105: val _ = assert (null (term_tvars t) andalso null (term_tfrees t)) berghofe@14105: "Term to be tested contains type variables"; berghofe@14105: val _ = assert (null (term_vars t)) berghofe@14105: "Term to be tested contains schematic variables"; berghofe@14105: val sg = sign_of thy; berghofe@14105: val frees = map dest_Free (term_frees t); berghofe@14140: val szname = variant (map fst frees) "i"; berghofe@14105: val s = "structure TestTerm =\nstruct\n\n" ^ berghofe@14105: setmp mode ["term_of", "test"] (generate_code_i thy) berghofe@14105: [("testf", list_abs_free (frees, t))] ^ wenzelm@14980: "\n" ^ Pretty.string_of berghofe@14105: (Pretty.block [Pretty.str "val () = Codegen.test_fn :=", berghofe@14140: Pretty.brk 1, Pretty.str ("(fn " ^ szname ^ " =>"), Pretty.brk 1, berghofe@14105: Pretty.blk (0, [Pretty.str "let", Pretty.brk 1, berghofe@14105: Pretty.blk (0, separate Pretty.fbrk (map (fn (s, T) => berghofe@14886: Pretty.block [Pretty.str ("val " ^ mk_id s ^ " ="), Pretty.brk 1, berghofe@14105: mk_gen sg false [] "" T, Pretty.brk 1, berghofe@14140: Pretty.str (szname ^ ";")]) frees)), berghofe@14105: Pretty.brk 1, Pretty.str "in", Pretty.brk 1, berghofe@14105: Pretty.block [Pretty.str "if ", berghofe@14886: mk_app false (Pretty.str "testf") (map (Pretty.str o mk_id o fst) frees), kleing@14110: Pretty.brk 1, Pretty.str "then Library.None", berghofe@14105: Pretty.brk 1, Pretty.str "else ", kleing@14110: Pretty.block [Pretty.str "Library.Some ", Pretty.block (Pretty.str "[" :: berghofe@14105: flat (separate [Pretty.str ",", Pretty.brk 1] berghofe@14105: (map (fn (s, T) => [Pretty.block berghofe@15326: [Pretty.str ("(" ^ Library.quote (Symbol.escape s) ^ ","), Pretty.brk 1, berghofe@14105: mk_app false (mk_term_of sg false T) berghofe@14886: [Pretty.str (mk_id s)], Pretty.str ")"]]) frees)) @ berghofe@14105: [Pretty.str "]"])]], wenzelm@14980: Pretty.brk 1, Pretty.str "end"]), Pretty.str ");"]) ^ berghofe@14105: "\n\nend;\n"; berghofe@14105: val _ = use_text Context.ml_output false s; berghofe@14105: fun iter f k = if k > i then None berghofe@14135: else (case (f () handle Match => berghofe@14135: (warning "Exception Match raised in generated code"; None)) of berghofe@14135: None => iter f (k+1) | Some x => Some x); berghofe@14105: fun test k = if k > sz then None berghofe@14105: else (priority ("Test data size: " ^ string_of_int k); berghofe@14105: case iter (fn () => !test_fn k) 1 of berghofe@14105: None => test (k+1) | Some x => Some x); berghofe@15029: in test 0 end); berghofe@14105: berghofe@14105: fun test_goal ({size, iterations, default_type}, tvinsts) i st = berghofe@14105: let berghofe@14105: val sg = Toplevel.sign_of st; berghofe@14105: fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t berghofe@14105: | strip t = t; berghofe@14105: val (gi, frees) = Logic.goal_params berghofe@14105: (prop_of (snd (snd (Proof.get_goal (Toplevel.proof_of st))))) i; berghofe@14105: val gi' = ObjectLogic.atomize_term sg (map_term_types berghofe@14105: (map_type_tfree (fn p as (s, _) => if_none (assoc (tvinsts, s)) berghofe@14105: (if_none default_type (TFree p)))) (subst_bounds (frees, strip gi))); berghofe@14105: in case test_term (Toplevel.theory_of st) size iterations gi' of berghofe@14105: None => writeln "No counterexamples found." berghofe@14105: | Some cex => writeln ("Counterexample found:\n" ^ berghofe@14105: Pretty.string_of (Pretty.chunks (map (fn (s, t) => berghofe@14105: Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, berghofe@14105: Sign.pretty_term sg t]) cex))) berghofe@14105: end; berghofe@14105: berghofe@14105: berghofe@12452: (**** Interface ****) berghofe@12452: berghofe@13731: val str = setmp print_mode [] Pretty.str; berghofe@13731: berghofe@11520: fun parse_mixfix rd s = berghofe@11520: (case Scan.finite Symbol.stopper (Scan.repeat berghofe@11520: ( $$ "_" >> K Arg berghofe@11520: || $$ "?" >> K Ignore berghofe@11520: || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length) berghofe@11520: || $$ "{" |-- $$ "*" |-- Scan.repeat1 berghofe@11520: ( $$ "'" |-- Scan.one Symbol.not_eof berghofe@11520: || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.not_eof)) --| berghofe@12452: $$ "*" --| $$ "}" >> (Quote o rd o implode) berghofe@11520: || Scan.repeat1 berghofe@11520: ( $$ "'" |-- Scan.one Symbol.not_eof berghofe@11520: || Scan.unless ($$ "_" || $$ "?" || $$ "/" || $$ "{" |-- $$ "*") berghofe@13731: (Scan.one Symbol.not_eof)) >> (Pretty o str o implode))) berghofe@11520: (Symbol.explode s) of berghofe@11520: (p, []) => p berghofe@11520: | _ => error ("Malformed annotation: " ^ quote s)); berghofe@11520: wenzelm@11546: structure P = OuterParse and K = OuterSyntax.Keyword; berghofe@11520: berghofe@11520: val assoc_typeP = berghofe@11520: OuterSyntax.command "types_code" wenzelm@11546: "associate types with target language types" K.thy_decl berghofe@11520: (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")") >> berghofe@12452: (fn xs => Toplevel.theory (fn thy => assoc_types berghofe@12452: (map (fn (name, mfx) => (name, parse_mixfix berghofe@12452: (typ_of o read_ctyp (sign_of thy)) mfx)) xs) thy))); berghofe@11520: berghofe@11520: val assoc_constP = berghofe@11520: OuterSyntax.command "consts_code" wenzelm@11546: "associate constants with target language code" K.thy_decl berghofe@11520: (Scan.repeat1 wenzelm@13003: (P.xname -- (Scan.option (P.$$$ "::" |-- P.typ)) --| berghofe@11520: P.$$$ "(" -- P.string --| P.$$$ ")") >> berghofe@11520: (fn xs => Toplevel.theory (fn thy => assoc_consts berghofe@11520: (map (fn ((name, optype), mfx) => (name, optype, parse_mixfix berghofe@11520: (term_of o read_cterm (sign_of thy) o rpair TypeInfer.logicT) mfx)) berghofe@11520: xs) thy))); berghofe@11520: berghofe@11520: val generate_codeP = wenzelm@11546: OuterSyntax.command "generate_code" "generates code for terms" K.thy_decl wenzelm@13003: (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- berghofe@13753: Scan.optional (P.$$$ "[" |-- P.enum "," P.xname --| P.$$$ "]") (!mode) -- wenzelm@13003: Scan.repeat1 (P.name --| P.$$$ "=" -- P.term) >> berghofe@13753: (fn ((opt_fname, mode'), xs) => Toplevel.theory (fn thy => berghofe@11520: ((case opt_fname of berghofe@11520: None => use_text Context.ml_output false berghofe@11520: | Some fname => File.write (Path.unpack fname)) berghofe@13753: (setmp mode mode' (generate_code thy) xs); thy)))); berghofe@11520: berghofe@14105: val params = berghofe@14105: [("size", P.nat >> (K o set_size)), berghofe@14105: ("iterations", P.nat >> (K o set_iterations)), berghofe@14105: ("default_type", P.typ >> set_default_type)]; berghofe@14105: berghofe@14105: val parse_test_params = P.short_ident :-- (fn s => berghofe@14105: P.$$$ "=" |-- if_none (assoc (params, s)) Scan.fail) >> snd; berghofe@14105: berghofe@14105: fun parse_tyinst xs = berghofe@14105: (P.type_ident --| P.$$$ "=" -- P.typ >> (fn (v, s) => fn sg => berghofe@14105: fn (x, ys) => (x, (v, typ_of (read_ctyp sg s)) :: ys))) xs; berghofe@14105: berghofe@14105: fun app [] x = x berghofe@14105: | app (f :: fs) x = app fs (f x); berghofe@14105: berghofe@14105: val test_paramsP = berghofe@14105: OuterSyntax.command "quickcheck_params" "set parameters for random testing" K.thy_decl berghofe@14105: (P.$$$ "[" |-- P.list1 parse_test_params --| P.$$$ "]" >> berghofe@14105: (fn fs => Toplevel.theory (fn thy => berghofe@14105: map_test_params (app (map (fn f => f (sign_of thy)) fs)) thy))); berghofe@14105: berghofe@14105: val testP = berghofe@14105: OuterSyntax.command "quickcheck" "try to find counterexample for subgoal" K.diag berghofe@14105: (Scan.option (P.$$$ "[" |-- P.list1 berghofe@14105: ( parse_test_params >> (fn f => fn sg => apfst (f sg)) berghofe@14105: || parse_tyinst) --| P.$$$ "]") -- Scan.optional P.nat 1 >> berghofe@14105: (fn (ps, g) => Toplevel.keep (fn st => berghofe@14105: test_goal (app (if_none (apsome berghofe@14105: (map (fn f => f (Toplevel.sign_of st))) ps) []) berghofe@14105: (get_test_params (Toplevel.theory_of st), [])) g st))); berghofe@14105: berghofe@14105: val parsers = [assoc_typeP, assoc_constP, generate_codeP, test_paramsP, testP]; berghofe@11520: berghofe@12452: val setup = berghofe@12452: [CodegenData.init, berghofe@12452: add_codegen "default" default_codegen, berghofe@12452: add_tycodegen "default" default_tycodegen, berghofe@12555: assoc_types [("fun", parse_mixfix (K dummyT) "(_ ->/ _)")], berghofe@12555: Attrib.add_attributes [("code", berghofe@12555: (code_attr, K Attrib.undef_local_attribute), berghofe@15261: "declare theorems for code generation")], berghofe@15261: add_attribute "unfold" (Scan.succeed unfold_attr)]; berghofe@11520: berghofe@11520: end; berghofe@11520: berghofe@11520: OuterSyntax.add_parsers Codegen.parsers;