src/Pure/codegen.ML
author wenzelm
Mon Jun 21 16:41:06 2004 +0200 (2004-06-21)
changeset 14990 582b655da757
parent 14981 e73f8140af78
child 15029 a4d0ed993050
permissions -rw-r--r--
pretty_abbr;
     1 (*  Title:      Pure/codegen.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4 
     5 Generic code generator.
     6 *)
     7 
     8 signature CODEGEN =
     9 sig
    10   val quiet_mode : bool ref
    11   val message : string -> unit
    12   val mode : string list ref
    13   val margin : int ref
    14 
    15   datatype 'a mixfix =
    16       Arg
    17     | Ignore
    18     | Pretty of Pretty.T
    19     | Quote of 'a;
    20 
    21   type 'a codegen
    22 
    23   val add_codegen: string -> term codegen -> theory -> theory
    24   val add_tycodegen: string -> typ codegen -> theory -> theory
    25   val add_attribute: string -> (Args.T list -> theory attribute * Args.T list) -> theory -> theory
    26   val print_codegens: theory -> unit
    27   val generate_code: theory -> (string * string) list -> string
    28   val generate_code_i: theory -> (string * term) list -> string
    29   val assoc_consts: (xstring * string option * term mixfix list) list -> theory -> theory
    30   val assoc_consts_i: (xstring * typ option * term mixfix list) list -> theory -> theory
    31   val assoc_types: (xstring * typ mixfix list) list -> theory -> theory
    32   val get_assoc_code: theory -> string -> typ -> term mixfix list option
    33   val get_assoc_type: theory -> string -> typ mixfix list option
    34   val invoke_codegen: theory -> string -> bool ->
    35     (exn option * string) Graph.T * term -> (exn option * string) Graph.T * Pretty.T
    36   val invoke_tycodegen: theory -> string -> bool ->
    37     (exn option * string) Graph.T * typ -> (exn option * string) Graph.T * Pretty.T
    38   val mk_id: string -> string
    39   val mk_const_id: Sign.sg -> string -> string
    40   val mk_type_id: Sign.sg -> string -> string
    41   val rename_term: term -> term
    42   val get_defn: theory -> string -> typ -> ((term list * term) * int option) option
    43   val is_instance: theory -> typ -> typ -> bool
    44   val parens: Pretty.T -> Pretty.T
    45   val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
    46   val eta_expand: term -> term list -> int -> term
    47   val strip_tname: string -> string
    48   val mk_type: bool -> typ -> Pretty.T
    49   val mk_term_of: Sign.sg -> bool -> typ -> Pretty.T
    50   val mk_gen: Sign.sg -> bool -> string list -> string -> typ -> Pretty.T
    51   val test_fn: (int -> (string * term) list option) ref
    52   val test_term: theory -> int -> int -> term -> (string * term) list option
    53   val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
    54   val parsers: OuterSyntax.parser list
    55   val setup: (theory -> theory) list
    56 end;
    57 
    58 structure Codegen : CODEGEN =
    59 struct
    60 
    61 val quiet_mode = ref true;
    62 fun message s = if !quiet_mode then () else writeln s;
    63 
    64 val mode = ref ([] : string list);
    65 
    66 val margin = ref 80;
    67 
    68 (**** Mixfix syntax ****)
    69 
    70 datatype 'a mixfix =
    71     Arg
    72   | Ignore
    73   | Pretty of Pretty.T
    74   | Quote of 'a;
    75 
    76 fun is_arg Arg = true
    77   | is_arg Ignore = true
    78   | is_arg _ = false;
    79 
    80 fun quotes_of [] = []
    81   | quotes_of (Quote q :: ms) = q :: quotes_of ms
    82   | quotes_of (_ :: ms) = quotes_of ms;
    83 
    84 fun args_of [] xs = ([], xs)
    85   | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
    86   | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
    87   | args_of (_ :: ms) xs = args_of ms xs;
    88 
    89 fun num_args x = length (filter is_arg x);
    90 
    91 
    92 (**** theory data ****)
    93 
    94 (* type of code generators *)
    95 
    96 type 'a codegen = theory -> (exn option * string) Graph.T ->
    97   string -> bool -> 'a -> ((exn option * string) Graph.T * Pretty.T) option;
    98 
    99 (* parameters for random testing *)
   100 
   101 type test_params =
   102   {size: int, iterations: int, default_type: typ option};
   103 
   104 fun merge_test_params
   105   {size = size1, iterations = iterations1, default_type = default_type1}
   106   {size = size2, iterations = iterations2, default_type = default_type2} =
   107   {size = Int.max (size1, size2),
   108    iterations = Int.max (iterations1, iterations2),
   109    default_type = case default_type1 of
   110        None => default_type2
   111      | _ => default_type1};
   112 
   113 val default_test_params : test_params =
   114   {size = 10, iterations = 100, default_type = None};
   115 
   116 fun set_size size ({iterations, default_type, ...} : test_params) =
   117   {size = size, iterations = iterations, default_type = default_type};
   118 
   119 fun set_iterations iterations ({size, default_type, ...} : test_params) =
   120   {size = size, iterations = iterations, default_type = default_type};
   121 
   122 fun set_default_type s sg ({size, iterations, ...} : test_params) =
   123   {size = size, iterations = iterations,
   124    default_type = Some (typ_of (read_ctyp sg s))};
   125 
   126 (* data kind 'Pure/codegen' *)
   127  
   128 structure CodegenArgs =
   129 struct
   130   val name = "Pure/codegen";
   131   type T =
   132     {codegens : (string * term codegen) list,
   133      tycodegens : (string * typ codegen) list,
   134      consts : ((string * typ) * term mixfix list) list,
   135      types : (string * typ mixfix list) list,
   136      attrs: (string * (Args.T list -> theory attribute * Args.T list)) list,
   137      test_params: test_params};
   138 
   139   val empty =
   140     {codegens = [], tycodegens = [], consts = [], types = [], attrs = [],
   141      test_params = default_test_params};
   142   val copy = I;
   143   val prep_ext = I;
   144 
   145   fun merge
   146     ({codegens = codegens1, tycodegens = tycodegens1,
   147       consts = consts1, types = types1, attrs = attrs1,
   148       test_params = test_params1},
   149      {codegens = codegens2, tycodegens = tycodegens2,
   150       consts = consts2, types = types2, attrs = attrs2,
   151       test_params = test_params2}) =
   152     {codegens = rev (merge_alists (rev codegens1) (rev codegens2)),
   153      tycodegens = rev (merge_alists (rev tycodegens1) (rev tycodegens2)),
   154      consts = merge_alists consts1 consts2,
   155      types = merge_alists types1 types2,
   156      attrs = merge_alists attrs1 attrs2,
   157      test_params = merge_test_params test_params1 test_params2};
   158 
   159   fun print sg ({codegens, tycodegens, ...} : T) =
   160     Pretty.writeln (Pretty.chunks
   161       [Pretty.strs ("term code generators:" :: map fst codegens),
   162        Pretty.strs ("type code generators:" :: map fst tycodegens)]);
   163 end;
   164 
   165 structure CodegenData = TheoryDataFun(CodegenArgs);
   166 val print_codegens = CodegenData.print;
   167 
   168 
   169 (**** access parameters for random testing ****)
   170 
   171 fun get_test_params thy = #test_params (CodegenData.get thy);
   172 
   173 fun map_test_params f thy =
   174   let val {codegens, tycodegens, consts, types, attrs, test_params} =
   175     CodegenData.get thy;
   176   in CodegenData.put {codegens = codegens, tycodegens = tycodegens,
   177     consts = consts, types = types, attrs = attrs,
   178     test_params = f test_params} thy
   179   end;
   180 
   181 
   182 (**** add new code generators to theory ****)
   183 
   184 fun add_codegen name f thy =
   185   let val {codegens, tycodegens, consts, types, attrs, test_params} =
   186     CodegenData.get thy
   187   in (case assoc (codegens, name) of
   188       None => CodegenData.put {codegens = (name, f) :: codegens,
   189         tycodegens = tycodegens, consts = consts, types = types,
   190         attrs = attrs, test_params = test_params} thy
   191     | Some _ => error ("Code generator " ^ name ^ " already declared"))
   192   end;
   193 
   194 fun add_tycodegen name f thy =
   195   let val {codegens, tycodegens, consts, types, attrs, test_params} =
   196     CodegenData.get thy
   197   in (case assoc (tycodegens, name) of
   198       None => CodegenData.put {tycodegens = (name, f) :: tycodegens,
   199         codegens = codegens, consts = consts, types = types,
   200         attrs = attrs, test_params = test_params} thy
   201     | Some _ => error ("Code generator " ^ name ^ " already declared"))
   202   end;
   203 
   204 
   205 (**** code attribute ****)
   206 
   207 fun add_attribute name att thy =
   208   let val {codegens, tycodegens, consts, types, attrs, test_params} =
   209     CodegenData.get thy
   210   in (case assoc (attrs, name) of
   211       None => CodegenData.put {tycodegens = tycodegens,
   212         codegens = codegens, consts = consts, types = types,
   213         attrs = (name, att) :: attrs, test_params = test_params} thy
   214     | Some _ => error ("Code attribute " ^ name ^ " already declared"))
   215   end;
   216 
   217 fun mk_parser (a, p) = (if a = "" then Scan.succeed "" else Args.$$$ a) |-- p;
   218 
   219 val code_attr =
   220   Attrib.syntax (Scan.depend (fn thy => foldr op || (map mk_parser
   221     (#attrs (CodegenData.get thy)), Scan.fail) >> pair thy));
   222 
   223 
   224 (**** associate constants with target language code ****)
   225 
   226 fun gen_assoc_consts prep_type xs thy = foldl (fn (thy, (s, tyopt, syn)) =>
   227   let
   228     val sg = sign_of thy;
   229     val {codegens, tycodegens, consts, types, attrs, test_params} =
   230       CodegenData.get thy;
   231     val cname = Sign.intern_const sg s;
   232   in
   233     (case Sign.const_type sg cname of
   234        Some T =>
   235          let val T' = (case tyopt of
   236                 None => T
   237               | Some ty =>
   238                   let val U = prep_type sg ty
   239                   in if Sign.typ_instance sg (U, T) then U
   240                     else error ("Illegal type constraint for constant " ^ cname)
   241                   end)
   242          in (case assoc (consts, (cname, T')) of
   243              None => CodegenData.put {codegens = codegens,
   244                tycodegens = tycodegens,
   245                consts = ((cname, T'), syn) :: consts,
   246                types = types, attrs = attrs, test_params = test_params} thy
   247            | Some _ => error ("Constant " ^ cname ^ " already associated with code"))
   248          end
   249      | _ => error ("Not a constant: " ^ s))
   250   end) (thy, xs);
   251 
   252 val assoc_consts_i = gen_assoc_consts (K I);
   253 val assoc_consts = gen_assoc_consts (fn sg => typ_of o read_ctyp sg);
   254 
   255 (**** associate types with target language types ****)
   256 
   257 fun assoc_types xs thy = foldl (fn (thy, (s, syn)) =>
   258   let
   259     val {codegens, tycodegens, consts, types, attrs, test_params} =
   260       CodegenData.get thy;
   261     val tc = Sign.intern_tycon (sign_of thy) s
   262   in
   263     (case assoc (types, tc) of
   264        None => CodegenData.put {codegens = codegens,
   265          tycodegens = tycodegens, consts = consts,
   266          types = (tc, syn) :: types, attrs = attrs,
   267          test_params = test_params} thy
   268      | Some _ => error ("Type " ^ tc ^ " already associated with code"))
   269   end) (thy, xs);
   270 
   271 fun get_assoc_type thy s = assoc (#types (CodegenData.get thy), s);
   272 
   273 
   274 (**** make valid ML identifiers ****)
   275 
   276 fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse
   277   Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x;
   278 
   279 fun dest_sym s = (case split_last (snd (take_prefix (equal "\\") (explode s))) of
   280     ("<" :: "^" :: xs, ">") => (true, implode xs)
   281   | ("<" :: xs, ">") => (false, implode xs)
   282   | _ => sys_error "dest_sym");
   283   
   284 fun mk_id s = if s = "" then "" else
   285   let
   286     fun check_str [] = []
   287       | check_str xs = (case take_prefix is_ascii_letdig xs of
   288           ([], " " :: zs) => check_str zs
   289         | ([], "_" :: zs) => check_str zs
   290         | ([], z :: zs) =>
   291           if size z = 1 then string_of_int (ord z) :: check_str zs
   292           else (case dest_sym z of
   293               (true, "isub") => check_str zs
   294             | (true, "isup") => "" :: check_str zs
   295             | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs)
   296         | (ys, zs) => implode ys :: check_str zs);
   297     val s' = space_implode "_"
   298       (flat (map (check_str o Symbol.explode) (NameSpace.unpack s)))
   299   in
   300     if Symbol.is_ascii_letter (hd (explode s')) then s' else "id_" ^ s'
   301   end;
   302 
   303 fun mk_const_id sg s =
   304   let val s' = mk_id (Sign.cond_extern sg Sign.constK s)
   305   in if s' mem ThmDatabase.ml_reserved then s' ^ "_const" else s' end;
   306 
   307 fun mk_type_id sg s =
   308   let val s' = mk_id (Sign.cond_extern sg Sign.typeK s)
   309   in if s' mem ThmDatabase.ml_reserved then s' ^ "_type" else s' end;
   310 
   311 fun rename_terms ts =
   312   let
   313     val names = foldr add_term_names
   314       (ts, map (fst o fst) (Drule.vars_of_terms ts));
   315     val reserved = names inter ThmDatabase.ml_reserved;
   316     val (illegal, alt_names) = split_list (mapfilter (fn s =>
   317       let val s' = mk_id s in if s = s' then None else Some (s, s') end) names)
   318     val ps = (reserved @ illegal) ~~
   319       variantlist (map (suffix "'") reserved @ alt_names, names);
   320 
   321     fun rename_id s = if_none (assoc (ps, s)) s;
   322 
   323     fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T)
   324       | rename (Free (a, T)) = Free (rename_id a, T)
   325       | rename (Abs (s, T, t)) = Abs (s, T, rename t)
   326       | rename (t $ u) = rename t $ rename u
   327       | rename t = t;
   328   in
   329     map rename ts
   330   end;
   331 
   332 val rename_term = hd o rename_terms o single;
   333 
   334 
   335 (**** retrieve definition of constant ****)
   336 
   337 fun is_instance thy T1 T2 =
   338   Sign.typ_instance (sign_of thy) (T1, Type.varifyT T2);
   339 
   340 fun get_assoc_code thy s T = apsome snd (find_first (fn ((s', T'), _) =>
   341   s = s' andalso is_instance thy T T') (#consts (CodegenData.get thy)));
   342 
   343 fun get_defn thy s T =
   344   let
   345     val axms = flat (map (Symtab.dest o #axioms o Theory.rep_theory)
   346       (thy :: Theory.ancestors_of thy));
   347     val defs = mapfilter (fn (_, t) =>
   348       (let
   349          val (lhs, rhs) = Logic.dest_equals t;
   350          val (c, args) = strip_comb lhs;
   351          val (s', T') = dest_Const c
   352        in if s=s' then Some (T', split_last (rename_terms (args @ [rhs])))
   353          else None end) handle TERM _ => None) axms;
   354     val i = find_index (is_instance thy T o fst) defs
   355   in
   356     if i>=0 then Some (snd (nth_elem (i, defs)),
   357       if length defs = 1 then None else Some i)
   358     else None
   359   end;
   360 
   361 
   362 (**** invoke suitable code generator for term / type ****)
   363 
   364 fun invoke_codegen thy dep brack (gr, t) = (case get_first
   365    (fn (_, f) => f thy gr dep brack t) (#codegens (CodegenData.get thy)) of
   366       None => error ("Unable to generate code for term:\n" ^
   367         Sign.string_of_term (sign_of thy) t ^ "\nrequired by:\n" ^
   368         commas (Graph.all_succs gr [dep]))
   369     | Some x => x);
   370 
   371 fun invoke_tycodegen thy dep brack (gr, T) = (case get_first
   372    (fn (_, f) => f thy gr dep brack T) (#tycodegens (CodegenData.get thy)) of
   373       None => error ("Unable to generate code for type:\n" ^
   374         Sign.string_of_typ (sign_of thy) T ^ "\nrequired by:\n" ^
   375         commas (Graph.all_succs gr [dep]))
   376     | Some x => x);
   377 
   378 
   379 (**** code generator for mixfix expressions ****)
   380 
   381 fun parens p = Pretty.block [Pretty.str "(", p, Pretty.str ")"];
   382 
   383 fun pretty_fn [] p = [p]
   384   | pretty_fn (x::xs) p = Pretty.str ("fn " ^ x ^ " =>") ::
   385       Pretty.brk 1 :: pretty_fn xs p;
   386 
   387 fun pretty_mixfix [] [] _ = []
   388   | pretty_mixfix (Arg :: ms) (p :: ps) qs = p :: pretty_mixfix ms ps qs
   389   | pretty_mixfix (Ignore :: ms) ps qs = pretty_mixfix ms ps qs
   390   | pretty_mixfix (Pretty p :: ms) ps qs = p :: pretty_mixfix ms ps qs
   391   | pretty_mixfix (Quote _ :: ms) ps (q :: qs) = q :: pretty_mixfix ms ps qs;
   392 
   393 
   394 (**** default code generators ****)
   395 
   396 fun eta_expand t ts i =
   397   let
   398     val (Ts, _) = strip_type (fastype_of t);
   399     val j = i - length ts
   400   in
   401     foldr (fn (T, t) => Abs ("x", T, t))
   402       (take (j, Ts), list_comb (t, ts @ map Bound (j-1 downto 0)))
   403   end;
   404 
   405 fun mk_app _ p [] = p
   406   | mk_app brack p ps = if brack then
   407        Pretty.block (Pretty.str "(" ::
   408          separate (Pretty.brk 1) (p :: ps) @ [Pretty.str ")"])
   409      else Pretty.block (separate (Pretty.brk 1) (p :: ps));
   410 
   411 fun new_names t xs = variantlist (map mk_id xs,
   412   map (fst o fst o dest_Var) (term_vars t) union
   413   add_term_names (t, ThmDatabase.ml_reserved));
   414 
   415 fun new_name t x = hd (new_names t [x]);
   416 
   417 fun default_codegen thy gr dep brack t =
   418   let
   419     val (u, ts) = strip_comb t;
   420     fun codegens brack = foldl_map (invoke_codegen thy dep brack)
   421   in (case u of
   422       Var ((s, i), T) =>
   423         let
   424           val (gr', ps) = codegens true (gr, ts);
   425           val (gr'', _) = invoke_tycodegen thy dep false (gr', T)
   426         in Some (gr'', mk_app brack (Pretty.str (s ^
   427            (if i=0 then "" else string_of_int i))) ps)
   428         end
   429 
   430     | Free (s, T) =>
   431         let
   432           val (gr', ps) = codegens true (gr, ts);
   433           val (gr'', _) = invoke_tycodegen thy dep false (gr', T)
   434         in Some (gr'', mk_app brack (Pretty.str s) ps) end
   435 
   436     | Const (s, T) =>
   437       (case get_assoc_code thy s T of
   438          Some ms =>
   439            let val i = num_args ms
   440            in if length ts < i then
   441                default_codegen thy gr dep brack (eta_expand u ts i)
   442              else
   443                let
   444                  val (ts1, ts2) = args_of ms ts;
   445                  val (gr1, ps1) = codegens false (gr, ts1);
   446                  val (gr2, ps2) = codegens true (gr1, ts2);
   447                  val (gr3, ps3) = codegens false (gr2, quotes_of ms);
   448                in
   449                  Some (gr3, mk_app brack (Pretty.block (pretty_mixfix ms ps1 ps3)) ps2)
   450                end
   451            end
   452        | None => (case get_defn thy s T of
   453            None => None
   454          | Some ((args, rhs), k) =>
   455              let
   456                val id = mk_const_id (sign_of thy) s ^ (case k of
   457                  None => "" | Some i => "_def" ^ string_of_int i);
   458                val (gr', ps) = codegens true (gr, ts);
   459              in
   460                Some (Graph.add_edge (id, dep) gr' handle Graph.UNDEF _ =>
   461                  let
   462                    val _ = message ("expanding definition of " ^ s);
   463                    val (Ts, _) = strip_type T;
   464                    val (args', rhs') =
   465                      if not (null args) orelse null Ts then (args, rhs) else
   466                        let val v = Free (new_name rhs "x", hd Ts)
   467                        in ([v], betapply (rhs, v)) end;
   468                    val (gr1, p) = invoke_codegen thy id false
   469                      (Graph.add_edge (id, dep)
   470                         (Graph.new_node (id, (None, "")) gr'), rhs');
   471                    val (gr2, xs) = codegens false (gr1, args');
   472                    val (gr3, ty) = invoke_tycodegen thy id false (gr2, T);
   473                  in Graph.map_node id (K (None, Pretty.string_of (Pretty.block
   474                    (separate (Pretty.brk 1) (if null args' then
   475                        [Pretty.str ("val " ^ id ^ " :"), ty]
   476                      else Pretty.str ("fun " ^ id) :: xs) @
   477                     [Pretty.str " =", Pretty.brk 1, p, Pretty.str ";"])) ^ "\n\n")) gr3
   478                  end, mk_app brack (Pretty.str id) ps)
   479              end))
   480 
   481     | Abs _ =>
   482       let
   483         val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   484         val t = strip_abs_body u
   485         val bs' = new_names t bs;
   486         val (gr1, ps) = codegens true (gr, ts);
   487         val (gr2, p) = invoke_codegen thy dep false
   488           (gr1, subst_bounds (map Free (rev (bs' ~~ Ts)), t));
   489       in
   490         Some (gr2, mk_app brack (Pretty.block (Pretty.str "(" :: pretty_fn bs' p @
   491           [Pretty.str ")"])) ps)
   492       end
   493 
   494     | _ => None)
   495   end;
   496 
   497 fun default_tycodegen thy gr dep brack (TVar ((s, i), _)) =
   498       Some (gr, Pretty.str (s ^ (if i = 0 then "" else string_of_int i)))
   499   | default_tycodegen thy gr dep brack (TFree (s, _)) = Some (gr, Pretty.str s)
   500   | default_tycodegen thy gr dep brack (Type (s, Ts)) =
   501       (case assoc (#types (CodegenData.get thy), s) of
   502          None => None
   503        | Some ms =>
   504            let
   505              val (gr', ps) = foldl_map
   506                (invoke_tycodegen thy dep false) (gr, fst (args_of ms Ts));
   507              val (gr'', qs) = foldl_map
   508                (invoke_tycodegen thy dep false) (gr', quotes_of ms)
   509            in Some (gr'', Pretty.block (pretty_mixfix ms ps qs)) end);
   510 
   511 
   512 fun output_code gr xs = implode (map (snd o Graph.get_node gr)
   513   (rev (Graph.all_preds gr xs)));
   514 
   515 fun gen_generate_code prep_term thy =
   516   setmp print_mode [] (Pretty.setmp_margin (!margin) (fn xs =>
   517   let
   518     val sg = sign_of thy;
   519     val gr = Graph.new_node ("<Top>", (None, "")) Graph.empty;
   520     val (gr', ps) = foldl_map (fn (gr, (s, t)) => apsnd (pair s)
   521       (invoke_codegen thy "<Top>" false (gr, t)))
   522         (gr, map (apsnd (prep_term sg)) xs)
   523     val code =
   524       "structure Generated =\nstruct\n\n" ^
   525       output_code gr' ["<Top>"] ^
   526       space_implode "\n\n" (map (fn (s', p) => Pretty.string_of (Pretty.block
   527         [Pretty.str ("val " ^ s' ^ " ="), Pretty.brk 1, p, Pretty.str ";"])) ps) ^
   528       "\n\nend;\n\nopen Generated;\n";
   529   in code end));
   530 
   531 val generate_code_i = gen_generate_code (K I);
   532 val generate_code = gen_generate_code
   533   (fn sg => term_of o read_cterm sg o rpair TypeInfer.logicT);
   534 
   535 
   536 (**** Reflection ****)
   537 
   538 val strip_tname = implode o tl o explode;
   539 
   540 fun pretty_list xs = Pretty.block (Pretty.str "[" ::
   541   flat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @
   542   [Pretty.str "]"]);
   543 
   544 fun mk_type p (TVar ((s, i), _)) = Pretty.str
   545       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
   546   | mk_type p (TFree (s, _)) = Pretty.str (strip_tname s ^ "T")
   547   | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   548       [Pretty.str "Type", Pretty.brk 1, Pretty.str ("(\"" ^ s ^ "\","),
   549        Pretty.brk 1, pretty_list (map (mk_type false) Ts), Pretty.str ")"]);
   550 
   551 fun mk_term_of sg p (TVar ((s, i), _)) = Pretty.str
   552       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
   553   | mk_term_of sg p (TFree (s, _)) = Pretty.str (strip_tname s ^ "F")
   554   | mk_term_of sg p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   555       (separate (Pretty.brk 1) (Pretty.str ("term_of_" ^ mk_type_id sg s) ::
   556         flat (map (fn T => [mk_term_of sg true T, mk_type true T]) Ts))));
   557 
   558 
   559 (**** Test data generators ****)
   560 
   561 fun mk_gen sg p xs a (TVar ((s, i), _)) = Pretty.str
   562       (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
   563   | mk_gen sg p xs a (TFree (s, _)) = Pretty.str (strip_tname s ^ "G")
   564   | mk_gen sg p xs a (Type (s, Ts)) = (if p then parens else I) (Pretty.block
   565       (separate (Pretty.brk 1) (Pretty.str ("gen_" ^ mk_type_id sg s ^
   566         (if s mem xs then "'" else "")) :: map (mk_gen sg true xs a) Ts @
   567         (if s mem xs then [Pretty.str a] else []))));
   568 
   569 val test_fn : (int -> (string * term) list option) ref = ref (fn _ => None);
   570 
   571 fun test_term thy sz i t =
   572   let
   573     val _ = assert (null (term_tvars t) andalso null (term_tfrees t))
   574       "Term to be tested contains type variables";
   575     val _ = assert (null (term_vars t))
   576       "Term to be tested contains schematic variables";
   577     val sg = sign_of thy;
   578     val frees = map dest_Free (term_frees t);
   579     val szname = variant (map fst frees) "i";
   580     val s = "structure TestTerm =\nstruct\n\n" ^
   581       setmp mode ["term_of", "test"] (generate_code_i thy)
   582         [("testf", list_abs_free (frees, t))] ^
   583       "\n" ^ Pretty.string_of
   584         (Pretty.block [Pretty.str "val () = Codegen.test_fn :=",
   585           Pretty.brk 1, Pretty.str ("(fn " ^ szname ^ " =>"), Pretty.brk 1,
   586           Pretty.blk (0, [Pretty.str "let", Pretty.brk 1,
   587             Pretty.blk (0, separate Pretty.fbrk (map (fn (s, T) =>
   588               Pretty.block [Pretty.str ("val " ^ mk_id s ^ " ="), Pretty.brk 1,
   589               mk_gen sg false [] "" T, Pretty.brk 1,
   590               Pretty.str (szname ^ ";")]) frees)),
   591             Pretty.brk 1, Pretty.str "in", Pretty.brk 1,
   592             Pretty.block [Pretty.str "if ",
   593               mk_app false (Pretty.str "testf") (map (Pretty.str o mk_id o fst) frees),
   594               Pretty.brk 1, Pretty.str "then Library.None",
   595               Pretty.brk 1, Pretty.str "else ",
   596               Pretty.block [Pretty.str "Library.Some ", Pretty.block (Pretty.str "[" ::
   597                 flat (separate [Pretty.str ",", Pretty.brk 1]
   598                   (map (fn (s, T) => [Pretty.block
   599                     [Pretty.str ("(" ^ Library.quote s ^ ","), Pretty.brk 1,
   600                      mk_app false (mk_term_of sg false T)
   601                        [Pretty.str (mk_id s)], Pretty.str ")"]]) frees)) @
   602                   [Pretty.str "]"])]],
   603             Pretty.brk 1, Pretty.str "end"]), Pretty.str ");"]) ^
   604       "\n\nend;\n";
   605     val _ = use_text Context.ml_output false s;
   606     fun iter f k = if k > i then None
   607       else (case (f () handle Match =>
   608           (warning "Exception Match raised in generated code"; None)) of
   609         None => iter f (k+1) | Some x => Some x);
   610     fun test k = if k > sz then None
   611       else (priority ("Test data size: " ^ string_of_int k);
   612         case iter (fn () => !test_fn k) 1 of
   613           None => test (k+1) | Some x => Some x);
   614   in test 0 end;
   615 
   616 fun test_goal ({size, iterations, default_type}, tvinsts) i st =
   617   let
   618     val sg = Toplevel.sign_of st;
   619     fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
   620       | strip t = t;
   621     val (gi, frees) = Logic.goal_params
   622       (prop_of (snd (snd (Proof.get_goal (Toplevel.proof_of st))))) i;
   623     val gi' = ObjectLogic.atomize_term sg (map_term_types
   624       (map_type_tfree (fn p as (s, _) => if_none (assoc (tvinsts, s))
   625         (if_none default_type (TFree p)))) (subst_bounds (frees, strip gi)));
   626   in case test_term (Toplevel.theory_of st) size iterations gi' of
   627       None => writeln "No counterexamples found."
   628     | Some cex => writeln ("Counterexample found:\n" ^
   629         Pretty.string_of (Pretty.chunks (map (fn (s, t) =>
   630           Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1,
   631             Sign.pretty_term sg t]) cex)))
   632   end;
   633 
   634 
   635 (**** Interface ****)
   636 
   637 val str = setmp print_mode [] Pretty.str;
   638 
   639 fun parse_mixfix rd s =
   640   (case Scan.finite Symbol.stopper (Scan.repeat
   641      (   $$ "_" >> K Arg
   642       || $$ "?" >> K Ignore
   643       || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
   644       || $$ "{" |-- $$ "*" |-- Scan.repeat1
   645            (   $$ "'" |-- Scan.one Symbol.not_eof
   646             || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.not_eof)) --|
   647          $$ "*" --| $$ "}" >> (Quote o rd o implode)
   648       || Scan.repeat1
   649            (   $$ "'" |-- Scan.one Symbol.not_eof
   650             || Scan.unless ($$ "_" || $$ "?" || $$ "/" || $$ "{" |-- $$ "*")
   651                  (Scan.one Symbol.not_eof)) >> (Pretty o str o implode)))
   652        (Symbol.explode s) of
   653      (p, []) => p
   654    | _ => error ("Malformed annotation: " ^ quote s));
   655 
   656 structure P = OuterParse and K = OuterSyntax.Keyword;
   657 
   658 val assoc_typeP =
   659   OuterSyntax.command "types_code"
   660   "associate types with target language types" K.thy_decl
   661     (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")") >>
   662      (fn xs => Toplevel.theory (fn thy => assoc_types
   663        (map (fn (name, mfx) => (name, parse_mixfix
   664          (typ_of o read_ctyp (sign_of thy)) mfx)) xs) thy)));
   665 
   666 val assoc_constP =
   667   OuterSyntax.command "consts_code"
   668   "associate constants with target language code" K.thy_decl
   669     (Scan.repeat1
   670        (P.xname -- (Scan.option (P.$$$ "::" |-- P.typ)) --|
   671         P.$$$ "(" -- P.string --| P.$$$ ")") >>
   672      (fn xs => Toplevel.theory (fn thy => assoc_consts
   673        (map (fn ((name, optype), mfx) => (name, optype, parse_mixfix
   674          (term_of o read_cterm (sign_of thy) o rpair TypeInfer.logicT) mfx))
   675            xs) thy)));
   676 
   677 val generate_codeP =
   678   OuterSyntax.command "generate_code" "generates code for terms" K.thy_decl
   679     (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") --
   680      Scan.optional (P.$$$ "[" |-- P.enum "," P.xname --| P.$$$ "]") (!mode) --
   681      Scan.repeat1 (P.name --| P.$$$ "=" -- P.term) >>
   682      (fn ((opt_fname, mode'), xs) => Toplevel.theory (fn thy =>
   683         ((case opt_fname of
   684             None => use_text Context.ml_output false
   685           | Some fname => File.write (Path.unpack fname))
   686               (setmp mode mode' (generate_code thy) xs); thy))));
   687 
   688 val params =
   689   [("size", P.nat >> (K o set_size)),
   690    ("iterations", P.nat >> (K o set_iterations)),
   691    ("default_type", P.typ >> set_default_type)];
   692 
   693 val parse_test_params = P.short_ident :-- (fn s =>
   694   P.$$$ "=" |-- if_none (assoc (params, s)) Scan.fail) >> snd;
   695 
   696 fun parse_tyinst xs =
   697   (P.type_ident --| P.$$$ "=" -- P.typ >> (fn (v, s) => fn sg =>
   698     fn (x, ys) => (x, (v, typ_of (read_ctyp sg s)) :: ys))) xs;
   699 
   700 fun app [] x = x
   701   | app (f :: fs) x = app fs (f x);
   702 
   703 val test_paramsP =
   704   OuterSyntax.command "quickcheck_params" "set parameters for random testing" K.thy_decl
   705     (P.$$$ "[" |-- P.list1 parse_test_params --| P.$$$ "]" >>
   706       (fn fs => Toplevel.theory (fn thy =>
   707          map_test_params (app (map (fn f => f (sign_of thy)) fs)) thy)));
   708 
   709 val testP =
   710   OuterSyntax.command "quickcheck" "try to find counterexample for subgoal" K.diag
   711   (Scan.option (P.$$$ "[" |-- P.list1
   712     (   parse_test_params >> (fn f => fn sg => apfst (f sg))
   713      || parse_tyinst) --| P.$$$ "]") -- Scan.optional P.nat 1 >>
   714     (fn (ps, g) => Toplevel.keep (fn st =>
   715       test_goal (app (if_none (apsome
   716           (map (fn f => f (Toplevel.sign_of st))) ps) [])
   717         (get_test_params (Toplevel.theory_of st), [])) g st)));
   718 
   719 val parsers = [assoc_typeP, assoc_constP, generate_codeP, test_paramsP, testP];
   720 
   721 val setup =
   722   [CodegenData.init,
   723    add_codegen "default" default_codegen,
   724    add_tycodegen "default" default_tycodegen,
   725    assoc_types [("fun", parse_mixfix (K dummyT) "(_ ->/ _)")],
   726    Attrib.add_attributes [("code",
   727      (code_attr, K Attrib.undef_local_attribute),
   728      "declare theorems for code generation")]];
   729 
   730 end;
   731 
   732 OuterSyntax.add_parsers Codegen.parsers;