src/Pure/codegen.ML
changeset 12452 68493b92e7a6
parent 12311 ce5f9e61c037
child 12490 d2a2c479b3cb
     1.1 --- a/src/Pure/codegen.ML	Mon Dec 10 15:37:03 2001 +0100
     1.2 +++ b/src/Pure/codegen.ML	Mon Dec 10 15:39:34 2001 +0100
     1.3 @@ -11,25 +11,28 @@
     1.4    val quiet_mode : bool ref
     1.5    val message : string -> unit
     1.6  
     1.7 -  datatype mixfix =
     1.8 +  datatype 'a mixfix =
     1.9        Arg
    1.10      | Ignore
    1.11      | Pretty of Pretty.T
    1.12 -    | Term of term;
    1.13 +    | Quote of 'a;
    1.14  
    1.15 -  val add_codegen: string ->
    1.16 -    (theory -> (exn option * string) Graph.T -> string -> bool -> term ->
    1.17 -    ((exn option * string) Graph.T * Pretty.T) option) -> theory -> theory
    1.18 +  type 'a codegen
    1.19 +
    1.20 +  val add_codegen: string -> term codegen -> theory -> theory
    1.21 +  val add_tycodegen: string -> typ codegen -> theory -> theory
    1.22    val print_codegens: theory -> unit
    1.23    val generate_code: theory -> (string * string) list -> string
    1.24    val generate_code_i: theory -> (string * term) list -> string
    1.25 -  val assoc_consts: (xstring * string option * mixfix list) list -> theory -> theory
    1.26 -  val assoc_consts_i: (xstring * typ option * mixfix list) list -> theory -> theory
    1.27 -  val assoc_types: (xstring * string) list -> theory -> theory
    1.28 -  val get_assoc_code: theory -> string -> typ -> mixfix list option
    1.29 -  val get_assoc_types: theory -> (string * string) list
    1.30 -  val invoke_codegen: theory -> (exn option * string) Graph.T ->
    1.31 -    string -> bool -> term -> (exn option * string) Graph.T * Pretty.T
    1.32 +  val assoc_consts: (xstring * string option * term mixfix list) list -> theory -> theory
    1.33 +  val assoc_consts_i: (xstring * typ option * term mixfix list) list -> theory -> theory
    1.34 +  val assoc_types: (xstring * typ mixfix list) list -> theory -> theory
    1.35 +  val get_assoc_code: theory -> string -> typ -> term mixfix list option
    1.36 +  val get_assoc_type: theory -> string -> typ mixfix list option
    1.37 +  val invoke_codegen: theory -> string -> bool ->
    1.38 +    (exn option * string) Graph.T * term -> (exn option * string) Graph.T * Pretty.T
    1.39 +  val invoke_tycodegen: theory -> string -> bool ->
    1.40 +    (exn option * string) Graph.T * typ -> (exn option * string) Graph.T * Pretty.T
    1.41    val mk_const_id: Sign.sg -> string -> string
    1.42    val mk_type_id: Sign.sg -> string -> string
    1.43    val rename_term: term -> term
    1.44 @@ -38,6 +41,7 @@
    1.45    val parens: Pretty.T -> Pretty.T
    1.46    val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
    1.47    val eta_expand: term -> term list -> int -> term
    1.48 +  val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
    1.49    val parsers: OuterSyntax.parser list
    1.50    val setup: (theory -> theory) list
    1.51  end;
    1.52 @@ -50,19 +54,24 @@
    1.53  
    1.54  (**** Mixfix syntax ****)
    1.55  
    1.56 -datatype mixfix =
    1.57 +datatype 'a mixfix =
    1.58      Arg
    1.59    | Ignore
    1.60    | Pretty of Pretty.T
    1.61 -  | Term of term;
    1.62 +  | Quote of 'a;
    1.63  
    1.64  fun is_arg Arg = true
    1.65    | is_arg Ignore = true
    1.66    | is_arg _ = false;
    1.67  
    1.68 -fun terms_of [] = []
    1.69 -  | terms_of (Term t :: ms) = t :: terms_of ms
    1.70 -  | terms_of (_ :: ms) = terms_of ms;
    1.71 +fun quotes_of [] = []
    1.72 +  | quotes_of (Quote q :: ms) = q :: quotes_of ms
    1.73 +  | quotes_of (_ :: ms) = quotes_of ms;
    1.74 +
    1.75 +fun args_of [] xs = ([], xs)
    1.76 +  | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
    1.77 +  | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
    1.78 +  | args_of (_ :: ms) xs = args_of ms xs;
    1.79  
    1.80  val num_args = length o filter is_arg;
    1.81  
    1.82 @@ -71,40 +80,54 @@
    1.83  
    1.84  (* data kind 'Pure/codegen' *)
    1.85  
    1.86 +type 'a codegen = theory -> (exn option * string) Graph.T ->
    1.87 +  string -> bool -> 'a -> ((exn option * string) Graph.T * Pretty.T) option;
    1.88 +
    1.89  structure CodegenArgs =
    1.90  struct
    1.91    val name = "Pure/codegen";
    1.92    type T =
    1.93 -    {codegens : (string * (theory -> (exn option * string) Graph.T -> string ->
    1.94 -       bool -> term -> ((exn option * string) Graph.T * Pretty.T) option)) list,
    1.95 -     consts : ((string * typ) * mixfix list) list,
    1.96 -     types : (string * string) list};
    1.97 +    {codegens : (string * term codegen) list,
    1.98 +     tycodegens : (string * typ codegen) list,
    1.99 +     consts : ((string * typ) * term mixfix list) list,
   1.100 +     types : (string * typ mixfix list) list};
   1.101  
   1.102 -  val empty = {codegens = [], consts = [], types = []};
   1.103 +  val empty = {codegens = [], tycodegens = [], consts = [], types = []};
   1.104    val copy = I;
   1.105    val prep_ext = I;
   1.106  
   1.107 -  fun merge ({codegens = codegens1, consts = consts1, types = types1},
   1.108 -             {codegens = codegens2, consts = consts2, types = types2}) =
   1.109 +  fun merge ({codegens = codegens1, tycodegens = tycodegens1, consts = consts1, types = types1},
   1.110 +             {codegens = codegens2, tycodegens = tycodegens2, consts = consts2, types = types2}) =
   1.111      {codegens = rev (merge_alists (rev codegens1) (rev codegens2)),
   1.112 +     tycodegens = rev (merge_alists (rev tycodegens1) (rev tycodegens2)),
   1.113       consts   = merge_alists consts1 consts2,
   1.114       types    = merge_alists types1 types2};
   1.115  
   1.116 -  fun print sg (cs:T) = Pretty.writeln
   1.117 -    (Pretty.strs ("code generators:" :: map fst (#codegens cs)));
   1.118 +  fun print sg ({codegens, tycodegens, ...} : T) =
   1.119 +    Pretty.writeln (Pretty.chunks
   1.120 +      [Pretty.strs ("term code generators:" :: map fst codegens),
   1.121 +       Pretty.strs ("type code generators:" :: map fst tycodegens)]);
   1.122  end;
   1.123  
   1.124  structure CodegenData = TheoryDataFun(CodegenArgs);
   1.125  val print_codegens = CodegenData.print;
   1.126  
   1.127  
   1.128 -(**** add new code generator to theory ****)
   1.129 +(**** add new code generators to theory ****)
   1.130  
   1.131  fun add_codegen name f thy =
   1.132 -  let val {codegens, consts, types} = CodegenData.get thy
   1.133 +  let val {codegens, tycodegens, consts, types} = CodegenData.get thy
   1.134    in (case assoc (codegens, name) of
   1.135 -      None => CodegenData.put {codegens = (name, f)::codegens,
   1.136 -        consts = consts, types = types} thy
   1.137 +      None => CodegenData.put {codegens = (name, f) :: codegens,
   1.138 +        tycodegens = tycodegens, consts = consts, types = types} thy
   1.139 +    | Some _ => error ("Code generator " ^ name ^ " already declared"))
   1.140 +  end;
   1.141 +
   1.142 +fun add_tycodegen name f thy =
   1.143 +  let val {codegens, tycodegens, consts, types} = CodegenData.get thy
   1.144 +  in (case assoc (tycodegens, name) of
   1.145 +      None => CodegenData.put {tycodegens = (name, f) :: tycodegens,
   1.146 +        codegens = codegens, consts = consts, types = types} thy
   1.147      | Some _ => error ("Code generator " ^ name ^ " already declared"))
   1.148    end;
   1.149  
   1.150 @@ -114,7 +137,7 @@
   1.151  fun gen_assoc_consts prep_type xs thy = foldl (fn (thy, (s, tyopt, syn)) =>
   1.152    let
   1.153      val sg = sign_of thy;
   1.154 -    val {codegens, consts, types} = CodegenData.get thy;
   1.155 +    val {codegens, tycodegens, consts, types} = CodegenData.get thy;
   1.156      val cname = Sign.intern_const sg s;
   1.157    in
   1.158      (case Sign.const_type sg cname of
   1.159 @@ -128,6 +151,7 @@
   1.160                    end)
   1.161           in (case assoc (consts, (cname, T')) of
   1.162               None => CodegenData.put {codegens = codegens,
   1.163 +               tycodegens = tycodegens,
   1.164                 consts = ((cname, T'), syn) :: consts, types = types} thy
   1.165             | Some _ => error ("Constant " ^ cname ^ " already associated with code"))
   1.166           end
   1.167 @@ -141,16 +165,17 @@
   1.168  
   1.169  fun assoc_types xs thy = foldl (fn (thy, (s, syn)) =>
   1.170    let
   1.171 -    val {codegens, consts, types} = CodegenData.get thy;
   1.172 +    val {codegens, tycodegens, consts, types} = CodegenData.get thy;
   1.173      val tc = Sign.intern_tycon (sign_of thy) s
   1.174    in
   1.175      (case assoc (types, tc) of
   1.176 -       None => CodegenData.put {codegens = codegens, consts = consts,
   1.177 +       None => CodegenData.put {codegens = codegens,
   1.178 +         tycodegens = tycodegens, consts = consts,
   1.179           types = (tc, syn) :: types} thy
   1.180       | Some _ => error ("Type " ^ tc ^ " already associated with code"))
   1.181    end) (thy, xs);
   1.182  
   1.183 -fun get_assoc_types thy = #types (CodegenData.get thy);
   1.184 +fun get_assoc_type thy s = assoc (#types (CodegenData.get thy), s);
   1.185  
   1.186  
   1.187  (**** retrieve definition of constant ****)
   1.188 @@ -214,14 +239,21 @@
   1.189    end;
   1.190  
   1.191  
   1.192 -(**** invoke suitable code generator for term t ****)
   1.193 +(**** invoke suitable code generator for term / type ****)
   1.194  
   1.195 -fun invoke_codegen thy gr dep brack t = (case get_first
   1.196 +fun invoke_codegen thy dep brack (gr, t) = (case get_first
   1.197     (fn (_, f) => f thy gr dep brack t) (#codegens (CodegenData.get thy)) of
   1.198        None => error ("Unable to generate code for term:\n" ^
   1.199          Sign.string_of_term (sign_of thy) t ^ "\nrequired by:\n" ^
   1.200          commas (Graph.all_succs gr [dep]))
   1.201 -    | Some x => x)
   1.202 +    | Some x => x);
   1.203 +
   1.204 +fun invoke_tycodegen thy dep brack (gr, T) = (case get_first
   1.205 +   (fn (_, f) => f thy gr dep brack T) (#tycodegens (CodegenData.get thy)) of
   1.206 +      None => error ("Unable to generate code for type:\n" ^
   1.207 +        Sign.string_of_typ (sign_of thy) T ^ "\nrequired by:\n" ^
   1.208 +        commas (Graph.all_succs gr [dep]))
   1.209 +    | Some x => x);
   1.210  
   1.211  
   1.212  (**** code generator for mixfix expressions ****)
   1.213 @@ -234,12 +266,12 @@
   1.214  
   1.215  fun pretty_mixfix [] [] _ = []
   1.216    | pretty_mixfix (Arg :: ms) (p :: ps) qs = p :: pretty_mixfix ms ps qs
   1.217 -  | pretty_mixfix (Ignore :: ms) (p :: ps) qs = pretty_mixfix ms ps qs
   1.218 +  | pretty_mixfix (Ignore :: ms) ps qs = pretty_mixfix ms ps qs
   1.219    | pretty_mixfix (Pretty p :: ms) ps qs = p :: pretty_mixfix ms ps qs
   1.220 -  | pretty_mixfix (Term _ :: ms) ps (q :: qs) = q :: pretty_mixfix ms ps qs;
   1.221 +  | pretty_mixfix (Quote _ :: ms) ps (q :: qs) = q :: pretty_mixfix ms ps qs;
   1.222  
   1.223  
   1.224 -(**** default code generator ****)
   1.225 +(**** default code generators ****)
   1.226  
   1.227  fun eta_expand t ts i =
   1.228    let
   1.229 @@ -265,18 +297,16 @@
   1.230  fun default_codegen thy gr dep brack t =
   1.231    let
   1.232      val (u, ts) = strip_comb t;
   1.233 -    fun mapcode brack' gr ts = foldl_map
   1.234 -      (fn (gr, t) => invoke_codegen thy gr dep brack' t) (gr, ts)
   1.235 -
   1.236 +    fun codegens brack = foldl_map (invoke_codegen thy dep brack)
   1.237    in (case u of
   1.238        Var ((s, i), _) =>
   1.239 -        let val (gr', ps) = mapcode true gr ts
   1.240 +        let val (gr', ps) = codegens true (gr, ts)
   1.241          in Some (gr', mk_app brack (Pretty.str (s ^
   1.242             (if i=0 then "" else string_of_int i))) ps)
   1.243          end
   1.244  
   1.245      | Free (s, _) =>
   1.246 -        let val (gr', ps) = mapcode true gr ts
   1.247 +        let val (gr', ps) = codegens true (gr, ts)
   1.248          in Some (gr', mk_app brack (Pretty.str s) ps) end
   1.249  
   1.250      | Const (s, T) =>
   1.251 @@ -287,11 +317,10 @@
   1.252                 default_codegen thy gr dep brack (eta_expand u ts i)
   1.253               else
   1.254                 let
   1.255 -                 val ts1 = take (i, ts);
   1.256 -                 val ts2 = drop (i, ts);
   1.257 -                 val (gr1, ps1) = mapcode false gr ts1;
   1.258 -                 val (gr2, ps2) = mapcode true gr1 ts2;
   1.259 -                 val (gr3, ps3) = mapcode false gr2 (terms_of ms);
   1.260 +                 val (ts1, ts2) = args_of ms ts;
   1.261 +                 val (gr1, ps1) = codegens false (gr, ts1);
   1.262 +                 val (gr2, ps2) = codegens true (gr1, ts2);
   1.263 +                 val (gr3, ps3) = codegens false (gr2, quotes_of ms);
   1.264                 in
   1.265                   Some (gr3, mk_app brack (Pretty.block (pretty_mixfix ms ps1 ps3)) ps2)
   1.266                 end
   1.267 @@ -302,7 +331,7 @@
   1.268               let
   1.269                 val id = mk_const_id (sign_of thy) s ^ (case k of
   1.270                   None => "" | Some i => "_def" ^ string_of_int i);
   1.271 -               val (gr', ps) = mapcode true gr ts;
   1.272 +               val (gr', ps) = codegens true (gr, ts);
   1.273               in
   1.274                 Some (Graph.add_edge (id, dep) gr' handle Graph.UNDEF _ =>
   1.275                   let
   1.276 @@ -312,9 +341,10 @@
   1.277                       if not (null args) orelse null Ts then (args, rhs) else
   1.278                         let val v = Free (new_name rhs "x", hd Ts)
   1.279                         in ([v], betapply (rhs, v)) end;
   1.280 -                   val (gr1, p) = invoke_codegen thy (Graph.add_edge (id, dep)
   1.281 -                     (Graph.new_node (id, (None, "")) gr')) id false rhs';
   1.282 -                   val (gr2, xs) = mapcode false gr1 args';
   1.283 +                   val (gr1, p) = invoke_codegen thy id false
   1.284 +                     (Graph.add_edge (id, dep)
   1.285 +                        (Graph.new_node (id, (None, "")) gr'), rhs');
   1.286 +                   val (gr2, xs) = codegens false (gr1, args');
   1.287                   in Graph.map_node id (K (None, Pretty.string_of (Pretty.block
   1.288                     (Pretty.str (if null args' then "val " else "fun ") ::
   1.289                      separate (Pretty.brk 1) (Pretty.str id :: xs) @
   1.290 @@ -327,9 +357,9 @@
   1.291          val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
   1.292          val t = strip_abs_body u
   1.293          val bs' = new_names t bs;
   1.294 -        val (gr1, ps) = mapcode true gr ts;
   1.295 -        val (gr2, p) = invoke_codegen thy gr1 dep false
   1.296 -          (subst_bounds (map Free (rev (bs' ~~ Ts)), t));
   1.297 +        val (gr1, ps) = codegens true (gr, ts);
   1.298 +        val (gr2, p) = invoke_codegen thy dep false
   1.299 +          (gr1, subst_bounds (map Free (rev (bs' ~~ Ts)), t));
   1.300        in
   1.301          Some (gr2, mk_app brack (Pretty.block (Pretty.str "(" :: pretty_fn bs' p @
   1.302            [Pretty.str ")"])) ps)
   1.303 @@ -338,6 +368,20 @@
   1.304      | _ => None)
   1.305    end;
   1.306  
   1.307 +fun default_tycodegen thy gr dep brack (TVar ((s, i), _)) =
   1.308 +      Some (gr, Pretty.str (s ^ (if i = 0 then "" else string_of_int i)))
   1.309 +  | default_tycodegen thy gr dep brack (TFree (s, _)) = Some (gr, Pretty.str s)
   1.310 +  | default_tycodegen thy gr dep brack (Type (s, Ts)) =
   1.311 +      (case assoc (#types (CodegenData.get thy), s) of
   1.312 +         None => None
   1.313 +       | Some ms =>
   1.314 +           let
   1.315 +             val (gr', ps) = foldl_map
   1.316 +               (invoke_tycodegen thy dep false) (gr, fst (args_of ms Ts));
   1.317 +             val (gr'', qs) = foldl_map
   1.318 +               (invoke_tycodegen thy dep false) (gr', quotes_of ms)
   1.319 +           in Some (gr'', Pretty.block (pretty_mixfix ms ps qs)) end);
   1.320 +
   1.321  
   1.322  fun output_code gr xs = implode (map (snd o Graph.get_node gr)
   1.323    (rev (Graph.all_preds gr xs)));
   1.324 @@ -347,7 +391,8 @@
   1.325      val sg = sign_of thy;
   1.326      val gr = Graph.new_node ("<Top>", (None, "")) Graph.empty;
   1.327      val (gr', ps) = foldl_map (fn (gr, (s, t)) => apsnd (pair s)
   1.328 -      (invoke_codegen thy gr "<Top>" false t)) (gr, map (apsnd (prep_term sg)) xs)
   1.329 +      (invoke_codegen thy "<Top>" false (gr, t)))
   1.330 +        (gr, map (apsnd (prep_term sg)) xs)
   1.331    in
   1.332      "structure Generated =\nstruct\n\n" ^
   1.333      output_code gr' ["<Top>"] ^
   1.334 @@ -360,6 +405,9 @@
   1.335  val generate_code = gen_generate_code
   1.336    (fn sg => term_of o read_cterm sg o rpair TypeInfer.logicT);
   1.337  
   1.338 +
   1.339 +(**** Interface ****)
   1.340 +
   1.341  fun parse_mixfix rd s =
   1.342    (case Scan.finite Symbol.stopper (Scan.repeat
   1.343       (   $$ "_" >> K Arg
   1.344 @@ -368,7 +416,7 @@
   1.345        || $$ "{" |-- $$ "*" |-- Scan.repeat1
   1.346             (   $$ "'" |-- Scan.one Symbol.not_eof
   1.347              || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.not_eof)) --|
   1.348 -         $$ "*" --| $$ "}" >> (Term o rd o implode)
   1.349 +         $$ "*" --| $$ "}" >> (Quote o rd o implode)
   1.350        || Scan.repeat1
   1.351             (   $$ "'" |-- Scan.one Symbol.not_eof
   1.352              || Scan.unless ($$ "_" || $$ "?" || $$ "/" || $$ "{" |-- $$ "*")
   1.353 @@ -383,7 +431,9 @@
   1.354    OuterSyntax.command "types_code"
   1.355    "associate types with target language types" K.thy_decl
   1.356      (Scan.repeat1 (P.xname --| P.$$$ "(" -- P.string --| P.$$$ ")") >>
   1.357 -     (Toplevel.theory o assoc_types));
   1.358 +     (fn xs => Toplevel.theory (fn thy => assoc_types
   1.359 +       (map (fn (name, mfx) => (name, parse_mixfix
   1.360 +         (typ_of o read_ctyp (sign_of thy)) mfx)) xs) thy)));
   1.361  
   1.362  val assoc_constP =
   1.363    OuterSyntax.command "consts_code"
   1.364 @@ -408,7 +458,11 @@
   1.365  
   1.366  val parsers = [assoc_typeP, assoc_constP, generate_codeP];
   1.367  
   1.368 -val setup = [CodegenData.init, add_codegen "default" default_codegen];
   1.369 +val setup =
   1.370 +  [CodegenData.init,
   1.371 +   add_codegen "default" default_codegen,
   1.372 +   add_tycodegen "default" default_tycodegen,
   1.373 +   assoc_types [("fun", parse_mixfix (K dummyT) "(_ ->/ _)")]];
   1.374  
   1.375  end;
   1.376