Debian Codegraph @

src/Stringification/Java.v

raw
1 From Coq Require Import ZArith MSetPositive FMapPositive
2 String Ascii Bool List HexString.
3 From Crypto.Util Require Import
4 ListUtil
5 Strings.String Strings.Decimal Strings.Show
6 ZRange.Operations ZRange.Show
7 OptionList Bool.Equality.
8 Require Import Crypto.Util.Option.
9 (* Work around COQBUG(https://github.com/coq/coq/issues/12251) *)
10 Require Import Crypto.Util.ZRange.
11
12 From Crypto Require Import IR Stringification.Language AbstractInterpretation.ZRange.
13
14 Import ListNotations.
15
16 Local Open Scope string_scope.
17 Local Open Scope list_scope.
18 Local Open Scope zrange_scope.
19 Local Open Scope Z_scope.
20
21 Import IR.Compilers.ToString.
22 Import Stringification.Language.Compilers.
23 Import Stringification.Language.Compilers.Options.
24 Import Stringification.Language.Compilers.ToString.
25 Import Stringification.Language.Compilers.ToString.int.Notations.
26
27 Module Java.
28 Definition comment_block := List.map (fun line => "/* " ++ line ++ " */")%string.
29
30 (* Header imports and type defs *)
31 Definition header
32 {language_naming_conventions : language_naming_conventions_opt}
33 {documentation_options : documentation_options_opt}
34 {package_namev : package_name_opt}
35 {class_namev : class_name_opt}
36 {output_options : output_options_opt}
37 (machine_wordsize : Z) (internal_private : bool) (private : bool) (prefix : string) (infos : ToString.ident_infos)
38 (typedef_map : list typedef_info)
39 : list string
40 (* N.B. We don't do anything with private; we always export everything *)
41 := let bitwidths_used := ToString.bitwidths_used infos in
42 (* Java class names are in mixed case *)
43 ((["";
44 "package " ++ package_name prefix ++ ";";
45 "";
46 "public final class " ++ class_name prefix ++ " {";
47 (** Java doesn't have pointers, so we make them *)
48 "";
49 "static class Box<T> {";
50 " private T value;";
51 " public Box(T value) { this.value = value; }";
52 " public void set(T value) { this.value = value; }";
53 " public T get() { return this.value; }";
54 "}";
55 "";
56 ""]%string)).
57 Definition footer
58 {language_naming_conventions : language_naming_conventions_opt}
59 {documentation_options : documentation_options_opt}
60 {package_namev : package_name_opt}
61 {class_namev : class_name_opt}
62 (machine_wordsize : Z) (internal_private : bool) (private : bool) (prefix : string) (infos : ToString.ident_infos)
63 : list string
64 := ["}"]%string.
65
66 (* Supported integer bitwidths *)
67 Definition stdint_bitwidths : list Z := [32; 64].
68 Definition is_special_bitwidth (bw : Z) := negb (existsb (Z.eqb bw) stdint_bitwidths).
69
70
71 Definition int_type_to_string (use_class : bool) (prefix : string) (t : ToString.int.type) : string :=
72 let bw := ToString.int.bitwidth_of t in
73 if bw =? 1 (* we have some of these left over from carries guaranteed to be 0; we use int for them because that's the only thing that will typecheck. This is a bit of a kludge *)
74 then if use_class then "Integer" else "int"
75 else if bw =? 8 then if use_class then "Byte" else "byte"
76 else if bw =? 16 then if use_class then "Short" else "short"
77 else if bw =? 32 then if use_class then "Integer" else "int"
78 else if bw =? 64 then if use_class then "Long" else "long"
79 else (prefix
80 ++ (if ToString.int.is_unsigned t then "uint" else "int")
81 ++ Decimal.Z.to_string (ToString.int.bitwidth_of t))%string.
82
83 Definition primitive_type_to_string (use_class : bool) (prefix : string) (t : IR.type.primitive)
84 (r : option ToString.int.type) : string :=
85 match t with
86 | IR.type.Zptr => fun t => "Box<" ++ t true ++">"
87 | IR.type.Z => fun t => t use_class
88 end%string
89 (fun use_class
90 => match r with
91 | Some int_t => int_type_to_string use_class prefix int_t
92 | None => "ℤ" (* blackboard bold Z for unbounded integers (which don't actually exist, and thus will error) *)
93 end).
94
95 (* Integer literal to string *)
96 Definition int_literal_to_string (prefix : string) (t : IR.type.primitive) (v : BinInt.Z) : string :=
97 match t with
98 | IR.type.Z
99 => (HexString.of_Z v)
100 ++ if ToString.int.bitwidth_of (ToString.int.of_zrange_relaxed r[v ~> v]) >? 32
101 then "L"
102 else ""
103 | IR.type.Zptr => "error_literal_address_" ++ HexString.of_Z v
104 end%string.
105
106 Import IR.Notations.
107
108 Fixpoint arith_to_string
109 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)
110 (prefix : string)
111 {t} (e : IR.arith_expr t)
112 : string
113 := let special_name_ty name ty := ToString.format_special_function_name_ty internal_private prefix name ty in
114 let special_name name bw := ToString.format_special_function_name internal_private prefix name false(*unsigned*) bw in
115 match e with
116 (* integer literals *)
117 | (IR.literal v @@@ _) => int_literal_to_string prefix IR.type.Z v
118 (* array dereference *)
119 | (IR.List_nth n @@@ IR.Var _ v) => "(" ++ v ++ "[" ++ Decimal.Z.to_string (Z.of_nat n) ++ "])"
120 (* (de)referencing *)
121 | (IR.Dereference @@@ e) => "(" ++ arith_to_string internal_private prefix e ++ ").get()"
122 (* bitwise operations *)
123 | (IR.Z_shiftr offset @@@ e) =>
124 (* We assume that shift is always unsigned *)
125 "(" ++ arith_to_string internal_private prefix e ++ " >>> " ++ Decimal.Z.to_string offset ++ ")"
126 | (IR.Z_shiftl offset @@@ e) =>
127 "(" ++ arith_to_string internal_private prefix e ++ " << " ++ Decimal.Z.to_string offset ++ ")"
128 | (IR.Z_land @@@ (e1, e2)) =>
129 "(" ++ arith_to_string internal_private prefix e1 ++ " & " ++ arith_to_string internal_private prefix e2 ++ ")"
130 | (IR.Z_lor @@@ (e1, e2)) =>
131 "(" ++ arith_to_string internal_private prefix e1 ++ " | " ++ arith_to_string internal_private prefix e2 ++ ")"
132 | (IR.Z_lxor @@@ (e1, e2)) =>
133 "(" ++ arith_to_string internal_private prefix e1 ++ " ^ " ++ arith_to_string internal_private prefix e2 ++ ")"
134 | (IR.Z_lnot _ @@@ e) => "(~" ++ arith_to_string internal_private prefix e ++ ")"
135 (* arithmetic operations *)
136 | (IR.Z_add @@@ (x1, x2)) =>
137 "(" ++ arith_to_string internal_private prefix x1 ++ " + " ++ arith_to_string internal_private prefix x2 ++ ")"
138 | (IR.Z_mul @@@ (x1, x2)) =>
139 "(" ++ arith_to_string internal_private prefix x1 ++ " * " ++ arith_to_string internal_private prefix x2 ++ ")"
140 | (IR.Z_sub @@@ (x1, x2)) =>
141 "(" ++ arith_to_string internal_private prefix x1 ++ " - " ++ arith_to_string internal_private prefix x2 ++ ")"
142 | (IR.Z_bneg @@@ e) => "(!/* TODO: FIX ME */ " ++ arith_to_string internal_private prefix e ++ ")"
143 | (IR.Z_mul_split lg2s @@@ args) =>
144 special_name "mulx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
145 | (IR.Z_add_with_get_carry lg2s @@@ args) =>
146 special_name "addcarryx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
147 | (IR.Z_sub_with_get_borrow lg2s @@@ args) =>
148 special_name "subborrowx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
149 | (IR.Z_zselect ty @@@ args) =>
150 special_name_ty "cmovznz" (int.unsigned_counterpart_of ty) ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
151 | (IR.Z_value_barrier ty @@@ args) =>
152 special_name_ty "value_barrier" ty ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
153 | (IR.Z_static_cast int_t @@@ e) =>
154 "(" ++ primitive_type_to_string false prefix IR.type.Z (Some int_t) ++ ") Integer.toUnsignedLong(((Number) (" ++ arith_to_string internal_private prefix e ++ ")).intValue())"
155 | IR.Var _ v => v
156 | IR.Pair A B a b => arith_to_string internal_private prefix a ++ ", " ++ arith_to_string internal_private prefix b
157 | (IR.Addr @@@ IR.Var _ v) => "error_cannot_take_reference_in_Java_to_" ++ v
158 | (IR.Z_add_modulo @@@ (x1, x2, x3)) => "int _error = error_addmodulo"
159 | (IR.List_nth _ @@@ _)
160 | (IR.Addr @@@ _)
161 | (IR.Z_add @@@ _)
162 | (IR.Z_mul @@@ _)
163 | (IR.Z_sub @@@ _)
164 | (IR.Z_land @@@ _)
165 | (IR.Z_lor @@@ _)
166 | (IR.Z_lxor @@@ _)
167 | (IR.Z_add_modulo @@@ _) => "int _error = error_bad_arg"
168 | IR.TT => "error_tt"
169 end%string%Cexpr.
170
171 (** In Java, there is no munging of return arguments (they remain
172 passed by pointers), so all variables are live *)
173 Local Instance : IR.OfPHOAS.consider_retargs_live_opt := fun _ _ _ => true.
174 Local Instance : IR.OfPHOAS.rename_dead_opt := fun s => s.
175 (** No need to lift declarations to the top *)
176 Local Instance : IR.OfPHOAS.lift_declarations_opt := false.
177
178 Definition stmt_to_string
179 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)
180 (prefix : string)
181 (e : IR.stmt)
182 : string :=
183 match e with
184 | IR.Call val => arith_to_string internal_private prefix val ++ ";"
185 | IR.Assign true t sz name val =>
186 (* local non-mutable declaration with initialization *)
187 primitive_type_to_string false prefix t sz ++ " " ++ name ++ " = " ++ arith_to_string internal_private prefix val ++ ";"
188 | IR.Assign false _ sz name val =>
189 (* This corresponds to assignment to a non-pointer variable and should never ever
190 happen in our generated code. Fiat-crypto handles it but I
191 haven't found and instance of this to their generated code *)
192 (* code : name ++ " = " ++ arith_to_string internal_private prefix val ++ ";" *)
193 "error_trying_to_assign_value_to_non_mutable_variable;"
194 | IR.AssignZPtr name sz val =>
195 name ++ ".set(" ++ arith_to_string internal_private prefix val ++ ");"
196 | IR.DeclareVar t sz name =>
197 (* Local uninitialized declarations become mut declarations, and
198 are initialized to 0. *)
199 (* The assumptions here, based on fiat-crypto code generation
200 patterns, are that 1.) this variable will be an argument to a
201 call that will store its result in this variable. 2.) this will
202 have a non-pointer an integer type *)
203 primitive_type_to_string true prefix IR.type.Zptr sz ++ " " ++ name ++ " = new " ++ primitive_type_to_string true prefix IR.type.Zptr sz ++ "((" ++ primitive_type_to_string false prefix IR.type.Z sz ++ ")0);"
204 | IR.Comment lines _ =>
205 String.concat String.NewLine (comment_block (ToString.preprocess_comment_block lines))
206 | IR.AssignNth name n val =>
207 name ++ "[" ++ Decimal.Z.to_string (Z.of_nat n) ++ "] = " ++ arith_to_string internal_private prefix val ++ ";"
208 end.
209
210 Definition to_strings
211 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)
212 (prefix : string)
213 (e : IR.expr)
214 : list string :=
215 List.map (stmt_to_string internal_private prefix) e.
216
217 Import Rewriter.Language.Language.Compilers Crypto.Language.API.Compilers IR.OfPHOAS.
218 Local Notation tZ := (base.type.type_base base.type.Z).
219
220 Inductive Mode := In | Out.
221
222
223 (* This would have been nice, but coercions don't work *)
224 (* Module Base := Rewriter.Language.Language.Compilers.base. *)
225
226 Fixpoint to_base_arg_list (prefix : string) (mode : Mode) {t} : ToString.OfPHOAS.base_var_data t -> list string :=
227 match t return base_var_data t -> _ with
228 | tZ =>
229 let typ := match mode with In => IR.type.Z | Out => IR.type.Zptr end in
230 fun '(n, is_ptr, r, typedef) => [primitive_type_to_string false prefix typ r ++ " " ++ n]
231 | base.type.prod A B =>
232 fun '(va, vb) => (to_base_arg_list prefix mode va ++ to_base_arg_list prefix mode vb)%list
233 | base.type.list tZ =>
234 fun '(n, r, len, typedef) =>
235 match mode with
236 | In => (* arrays for inputs are immutable borrows *)
237 [("final " ++ primitive_type_to_string false prefix IR.type.Z r)
238 ++ "[] " (* ++ Decimal.Z.to_string (Z.of_nat len) ++ "] "*)
239 ++ n]
240 | Out => (* arrays for outputs are mutable borrows *)
241 [(primitive_type_to_string false prefix IR.type.Z r)
242 ++ "[] " (* ++ Decimal.Z.to_string (Z.of_nat len) ++ "] "*)
243 ++ n]
244 end
245 | base.type.list _ => fun _ => ["error_complex_list"]
246 | base.type.option _ => fun _ => ["error_option"]
247 | base.type.unit => fun _ => ["error_unit"]
248 | base.type.type_base t => fun _ => ["error_" ++ show t]%string
249 end%string.
250
251 Definition to_arg_list (prefix : string) (mode : Mode) {t} : var_data t -> list string :=
252 match t return var_data t -> _ with
253 | type.base t => to_base_arg_list prefix mode
254 | type.arrow _ _ => fun _ => ["error_arrow"]
255 end%string.
256
257 Fixpoint to_arg_list_for_each_lhs_of_arrow (prefix : string) {t} : type.for_each_lhs_of_arrow var_data t -> list string
258 := match t return type.for_each_lhs_of_arrow var_data t -> _ with
259 | type.base t => fun _ => nil
260 | type.arrow s d
261 => fun '(x, xs)
262 => to_arg_list prefix In x ++ @to_arg_list_for_each_lhs_of_arrow prefix d xs
263 end%list.
264
265 (** * Language-specific numeric conversions to be passed to the PHOAS -> IR translation *)
266
267 Definition Java_bin_op_natural_output
268 : IR.Z_binop -> ToString.int.type * ToString.int.type -> ToString.int.type
269 := fun idc '(t1, t2)
270 => ToString.int.union t1 t2.
271
272 (* Does the binary operation commute with (-- mod 2^bw)? *)
273 Definition bin_op_commutes_with_mod_pow2 (idc : IR.Z_binop)
274 := match idc with
275 | IR.Z_land
276 | IR.Z_lor
277 | IR.Z_lxor
278 | IR.Z_add
279 | IR.Z_mul
280 | IR.Z_sub
281 => true
282 end.
283
284 Definition Java_bin_op_casts
285 : IR.Z_binop -> option ToString.int.type -> ToString.int.type * ToString.int.type -> option ToString.int.type * (option ToString.int.type * option ToString.int.type)
286 := fun idc desired_type '(t1, t2)
287 => match desired_type with
288 | Some desired_type
289 => let ct := ToString.int.union t1 t2 in
290 if bin_op_commutes_with_mod_pow2 idc
291 then
292 (* these operations commute with mod, so we just pre-cast them *)
293 (None, (Some desired_type, Some desired_type))
294 else
295 let desired_type' := Some (ToString.int.union ct desired_type) in
296 (desired_type',
297 (get_Zcast_up_if_needed desired_type' (Some t1),
298 get_Zcast_up_if_needed desired_type' (Some t2)))
299 | None => (None, (None, None))
300 end.
301
302 Definition Java_un_op_casts
303 : IR.Z_unop -> option ToString.int.type -> ToString.int.type -> option ToString.int.type * option ToString.int.type
304 := fun idc desired_type t
305 => match idc with
306 | IR.Z_shiftr offset
307 => (** N.B. We must cast the expression up to a large
308 enough type to fit 2^offset (importantly, not just
309 2^offset-1), because C considers it to be undefined
310 behavior to shift >= width of the type. We should
311 probably figure out how to not generate these
312 things in the first place...
313
314 N.B. We must preserve signedness of the value being
315 shifted, because shift does not commute with
316 mod. *)
317 let t' := ToString.int.union_zrange r[0~>2^offset]%zrange t in
318 ((** We cast the result down to the specified type, if needed *)
319 get_Zcast_down_if_needed desired_type (Some t'),
320 (** We cast the argument up to a large enough type *)
321 get_Zcast_up_if_needed (Some t') (Some t))
322 | IR.Z_shiftl offset
323 => (** N.B. We must cast the expression up to a large
324 enough type to fit 2^offset (importantly, not just
325 2^offset-1), because C considers it to be undefined
326 behavior to shift >= width of the type. We should
327 probably figure out how to not generate these
328 things in the first place...
329
330 N.B. We make sure that we only left-shift unsigned
331 values, since shifting into the sign bit is
332 undefined behavior. *)
333 let rpre_out := match desired_type with
334 | Some rout => Some (ToString.int.union_zrange r[0~>2^offset] (ToString.int.unsigned_counterpart_of rout))
335 | None => Some (ToString.int.of_zrange_relaxed r[0~>2^offset]%zrange)
336 end in
337 ((** We cast the result down to the specified type, if needed *)
338 get_Zcast_down_if_needed desired_type rpre_out,
339 (** We cast the argument up to a large enough type *)
340 get_Zcast_up_if_needed rpre_out (Some t))
341 | IR.Z_lnot ty
342 => ((* if the result is too big, we cast it down; we
343 don't need to upcast it because it'll get
344 picked up by implicit casts if necessary *)
345 get_Zcast_down_if_needed desired_type (Some ty),
346 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)
347 Some ty)
348 | IR.Z_value_barrier ty
349 => ((* if the result is too big, we cast it down; we
350 don't need to upcast it because it'll get
351 picked up by implicit casts if necessary *)
352 get_Zcast_down_if_needed desired_type (Some ty),
353 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)
354 Some ty)
355 | IR.Z_bneg
356 => ((* bneg is !, i.e., takes the argument to 1 if its not zero, and to zero if it is zero; so we don't ever need to cast *)
357 None, None)
358 end.
359
360 Local Instance JavaLanguageCasts : LanguageCasts :=
361 {| bin_op_natural_output := Java_bin_op_natural_output
362 ; bin_op_casts := Java_bin_op_casts
363 ; un_op_casts := Java_un_op_casts
364 ; upcast_on_assignment := true
365 ; upcast_on_funcall := true
366 ; explicit_pointer_variables := true (* Java can't take the address of a variable, so we declare explicit pointer variables *)
367 |}.
368
369 Definition to_function_lines
370 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)
371 (internal : bool) (inline : bool) (prefix : string) (name : string)
372 {t}
373 (f : type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * IR.expr)
374 : list string :=
375 let '(args, rets, body) := f in
376 (((if internal then "" else "public ") ++ "static void " ++ name)
377 ++ "(" ++ String.concat ", " (to_arg_list prefix Out rets ++ to_arg_list_for_each_lhs_of_arrow prefix args) ++
378 ") {")%string :: (List.map (fun s => " " ++ s)%string (to_strings internal_private prefix body)) ++ ["}"%string]%list.
379
380 Definition javadoc_replace (s : string) : string
381 := String.replace "<" "&lt;" (String.replace ">" "&gt;" s).
382
383 Definition javadoc_format (ls : list string) : list string
384 := ["/**"%string]
385 ++ List.map (fun s => s ++ " <p>")%string ls
386 ++ [" */"%string].
387
388 Definition ToFunctionLines
389 {absint_opts : AbstractInterpretation.Options}
390 {relax_zrange : relax_zrange_opt}
391 {language_naming_conventions : language_naming_conventions_opt}
392 {documentation_options : documentation_options_opt}
393 {output_options : output_options_opt}
394 (machine_wordsize : Z)
395 (do_bounds_check : bool) (internal_private : bool) (internal : bool) (all_private : bool) (inline : bool) (prefix : string) (name : string)
396 {t}
397 (e : API.Expr t)
398 (comment : type.for_each_lhs_of_arrow var_data t -> var_data (type.base (type.final_codomain t)) -> list string)
399 (name_list : option (list string))
400 (inbounds : type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t)
401 (outbounds : Compilers.ZRange.type.base.option.interp (type.final_codomain t))
402 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
403 (outtypedefs : base_var_typedef_data (type.final_codomain t))
404 : (list string * ToString.ident_infos) + string :=
405 match ExprOfPHOAS do_bounds_check e name_list inbounds intypedefs outtypedefs with
406 | inl (indata, outdata, f) =>
407 inl ((javadoc_format
408 ((List.map (fun s => if (String.length s =? 0)%nat then " *" else (" * " ++ javadoc_replace s))%string (comment indata outdata))
409 ++ match input_bounds_to_string indata inbounds with
410 | nil => nil
411 | ls => [" * Input Bounds:"] ++ List.map (fun v => " * " ++ javadoc_replace v)%string ls
412 end
413 ++ match bound_to_string outdata outbounds with
414 | nil => nil
415 | ls => [" * Output Bounds:"] ++ List.map (fun v => " * " ++ javadoc_replace v)%string ls
416 end)
417 ++ to_function_lines internal_private internal inline prefix name (indata, outdata, f))%list%string,
418 IR.ident_infos.collect_all_infos f intypedefs outtypedefs)
419 | inr nil =>
420 inr ("Unknown internal error in converting " ++ name ++ " to Java")%string
421 | inr [err] =>
422 inr ("Error in converting " ++ name ++ " to Java:" ++ String.NewLine ++ err)%string
423 | inr errs =>
424 inr ("Errors in converting " ++ name ++ " to Java:" ++ String.NewLine ++ String.concat String.NewLine errs)%string
425 end.
426
427 Definition OutputJavaAPI : ToString.OutputLanguageAPI :=
428 {| ToString.comment_block := comment_block;
429 ToString.comment_file_header_block := comment_block;
430 ToString.ToFunctionLines := @ToFunctionLines;
431 ToString.header := @header;
432 ToString.footer := @footer;
433 ToString.strip_special_infos machine_wordsize infos := infos |}.
434
435 End Java.