Debian Codegraph @

src/Stringification/Zig.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
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 Zig.
28 Definition comment_module_header_block := List.map (fun line => "// " ++ line)%string.
29 Definition comment_block := List.map (fun line => "// " ++ line)%string.
30
31 (* Zig natively supports any integer size between 0 and 4096 bits.
32 So, we never need to define our own types. *)
33 Definition int_type_to_string_opt_typedef {skip_typedefs : skip_typedefs_opt} {language_naming_conventions : language_naming_conventions_opt} (typedef_private : bool) (prefix : string) (t : ToString.int.type) (typedef : option string) : string :=
34 match (if skip_typedefs then None else typedef) with
35 | None => (if int.is_unsigned t then "u" else "i") ++ Decimal.Z.to_string (ToString.int.bitwidth_of t)
36 | Some typedef => format_typedef_name prefix typedef_private typedef
37 end.
38 Definition int_type_to_string {language_naming_conventions : language_naming_conventions_opt} (t : ToString.int.type) : string :=
39 int_type_to_string_opt_typedef (skip_typedefs:=true) false "" t None.
40
41 Definition primitive_type_to_string_opt_typedef
42 {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt}
43 (all_private : bool)
44 (prefix : string) (t : IR.type.primitive)
45 (r : option ToString.int.type) (typedef : option string) : string :=
46 match t with
47 | IR.type.Zptr => "*"
48 | IR.type.Z => ""
49 end ++ match r with
50 | Some int_t => int_type_to_string_opt_typedef all_private prefix int_t typedef
51 | None => "ℤ" (* blackboard bold Z for unbounded integers (which don't actually exist, and thus will error) *)
52 end.
53 Definition primitive_type_to_string {language_naming_conventions : language_naming_conventions_opt} (t : IR.type.primitive)
54 (r : option ToString.int.type) : string :=
55 primitive_type_to_string_opt_typedef (skip_typedefs:=true) false "" t r None.
56
57 Definition primitive_array_type_to_string
58 {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt}
59 (all_private : bool)
60 (prefix : string) (t : IR.type.primitive)
61 (r : option ToString.int.type) (len : nat) (typedef : option string) : string :=
62 match (if skip_typedefs then None else typedef) with
63 | Some typedef => format_typedef_name prefix all_private typedef
64 | None => "[" ++ Decimal.Z.to_string (Z.of_nat len) ++ "]" ++
65 primitive_type_to_string t r
66 end.
67
68 Definition make_typedef
69 {language_naming_conventions : language_naming_conventions_opt}
70 {documentation_options : documentation_options_opt}
71 (prefix : string) (private : bool)
72 (typedef : typedef_info)
73 : list string
74 := let '(name, (ty, array_len), description) := name_and_type_and_describe_typedef prefix private typedef in
75 ((comment_block description)
76 ++ [(if private then "const " else "pub const ")
77 ++ name ++ " = " ++
78 let ty_string := match ty with
79 | Some ty => int_type_to_string ty
80 | None => "ℤ" (* blackboard bold Z for unbounded integers (which don't actually exist, and thus will error) *)
81 end in
82 match array_len with
83 | None (* just an integer *) => ty_string
84 | Some None (* unknown array length *) => "*" ++ ty_string
85 | Some (Some len) => "[" ++ Decimal.Z.to_string (Z.of_nat len) ++ "]" ++ ty_string
86 end
87 ++ ";"]%string)%list.
88
89 Definition header
90 {language_naming_conventions : language_naming_conventions_opt}
91 {documentation_options : documentation_options_opt}
92 {package_namev : package_name_opt}
93 {class_namev : class_name_opt}
94 {output_options : output_options_opt}
95 (machine_wordsize : Z) (internal_private : bool) (private : bool) (prefix : string) (infos : ToString.ident_infos)
96 (typedef_map : list typedef_info)
97 : list string
98 := (["";
99 "const std = @import(""std"");";
100 "const mode = @import(""builtin"").mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels";
101 "";
102 "inline fn cast(comptime DestType: type, target: anytype) DestType {";
103 " @setEvalBranchQuota(10000);";
104 " if (@typeInfo(@TypeOf(target)) == .int) {";
105 " const dest = @typeInfo(DestType).int;";
106 " const source = @typeInfo(@TypeOf(target)).int;";
107 " if (dest.bits < source.bits) {";
108 " const T = std.meta.Int(source.signedness, dest.bits);";
109 " return @bitCast(@as(T, @truncate(target)));";
110 " }";
111 " }";
112 " return target;";
113 "}"]
114 ++ (if skip_typedefs
115 then []
116 else List.flat_map
117 (fun td_name =>
118 match List.find (fun '(name, _, _, _) => (td_name =? name)%string) typedef_map with
119 | Some td_info => [""] ++ make_typedef prefix private td_info
120 | None => ["@compilerError(""Could not find typedef info for '" ++ td_name ++ "'"");"]%string
121 end%list)
122 (typedefs_used infos)))%list.
123
124 (* Integer literal to string *)
125 Definition int_literal_to_string (prefix : string) (t : IR.type.primitive) (v : BinInt.Z) : string :=
126 match t with
127 | IR.type.Z => HexString.of_Z v (* Zig can automatically figure out the size of integer literals *)
128 | IR.type.Zptr => "@compilerError(""literal address " ++ HexString.of_Z v ++ """);"
129 end.
130
131 Import IR.Notations.
132
133 Fixpoint arith_to_string
134 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)
135 (prefix : string) {t} (e : IR.arith_expr t) : string
136 := let special_name_ty name ty := ToString.format_special_function_name_ty internal_private prefix name ty in
137 let special_name name bw := ToString.format_special_function_name internal_private prefix name false(*unsigned*) bw in
138 match e with
139 (* integer literals *)
140 | (IR.literal v @@@ _) => int_literal_to_string prefix IR.type.Z v
141 (* array dereference *)
142 | (IR.List_nth n @@@ IR.Var _ v) => "(" ++ v ++ "[" ++ Decimal.Z.to_string (Z.of_nat n) ++ "])"
143 (* (de)referencing *)
144 | (IR.Addr @@@ IR.Var _ v) => "&" ++ v
145 | (IR.Dereference @@@ e) => "( " ++ arith_to_string internal_private prefix e ++ ".* )"
146 (* bitwise operations *)
147 | (IR.Z_shiftr offset @@@ e) =>
148 "(" ++ arith_to_string internal_private prefix e ++ " >> " ++ Decimal.Z.to_string offset ++ ")"
149 | (IR.Z_shiftl offset @@@ e) =>
150 "(" ++ arith_to_string internal_private prefix e ++ " << " ++ Decimal.Z.to_string offset ++ ")"
151 | (IR.Z_land @@@ (e1, e2)) =>
152 "(" ++ arith_to_string internal_private prefix e1 ++ " & " ++ arith_to_string internal_private prefix e2 ++ ")"
153 | (IR.Z_lor @@@ (e1, e2)) =>
154 "(" ++ arith_to_string internal_private prefix e1 ++ " | " ++ arith_to_string internal_private prefix e2 ++ ")"
155 | (IR.Z_lxor @@@ (e1, e2)) =>
156 "(" ++ arith_to_string internal_private prefix e1 ++ " ^ " ++ arith_to_string internal_private prefix e2 ++ ")"
157 | (IR.Z_lnot _ @@@ e) => "(~" ++ arith_to_string internal_private prefix e ++ ")"
158 (* arithmetic operations *)
159 | (IR.Z_add @@@ (x1, x2)) =>
160 "(" ++ arith_to_string internal_private prefix x1 ++ " + " ++ arith_to_string internal_private prefix x2 ++ ")"
161 | (IR.Z_mul @@@ (x1, x2)) =>
162 "(" ++ arith_to_string internal_private prefix x1 ++ " * " ++ arith_to_string internal_private prefix x2 ++ ")"
163 | (IR.Z_sub @@@ (x1, x2)) =>
164 "(" ++ arith_to_string internal_private prefix x1 ++ " - " ++ arith_to_string internal_private prefix x2 ++ ")"
165 | (IR.Z_bneg @@@ e) => "(~" ++ arith_to_string internal_private prefix e ++ ")"
166 | (IR.Z_mul_split lg2s @@@ args) =>
167 special_name "mulx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
168 | (IR.Z_add_with_get_carry lg2s @@@ args) =>
169 special_name "addcarryx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
170 | (IR.Z_sub_with_get_borrow lg2s @@@ args) =>
171 special_name "subborrowx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
172 | (IR.Z_zselect ty @@@ args) =>
173 special_name_ty "cmovznz" ty ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
174 | (IR.Z_value_barrier ty @@@ args) =>
175 special_name_ty "value_barrier" ty ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
176 | (IR.Z_static_cast int_t @@@ e) =>
177 "cast(" ++ primitive_type_to_string IR.type.Z (Some int_t) ++ ", " ++ arith_to_string internal_private prefix e ++ ")"
178 | IR.Var _ v => v
179 | IR.Pair A B a b => arith_to_string internal_private prefix a ++ ", " ++ arith_to_string internal_private prefix b
180 | (IR.Z_add_modulo @@@ (x1, x2, x3)) => "@compilerError(""addmodulo"");"
181 | (IR.List_nth _ @@@ _)
182 | (IR.Addr @@@ _)
183 | (IR.Z_add @@@ _)
184 | (IR.Z_mul @@@ _)
185 | (IR.Z_sub @@@ _)
186 | (IR.Z_land @@@ _)
187 | (IR.Z_lor @@@ _)
188 | (IR.Z_lxor @@@ _)
189 | (IR.Z_add_modulo @@@ _) => "@compilerError(""bad_arg"");"
190 | IR.TT => "@compilerError(""tt"");"
191 end%string%Cexpr.
192
193 Definition stmt_to_string
194 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)
195 (prefix : string) (e : IR.stmt) : string :=
196 match e with
197 | IR.Call val => arith_to_string internal_private prefix val ++ ";"
198 | IR.Assign true t sz name val =>
199 (* local non-mutable declaration with initialization *)
200 "const " ++ name ++ " = " ++ arith_to_string internal_private prefix val ++ ";"
201 | IR.Assign false _ sz name val =>
202 (* code : name ++ " = " ++ arith_to_string internal_private prefix val ++ ";" *)
203 "@compilerError(""trying to assign value to non-mutable variable"");"
204 | IR.AssignZPtr name sz val =>
205 name ++ ".* = " ++ arith_to_string internal_private prefix val ++ ";"
206 | IR.DeclareVar t sz name =>
207 "var " ++ name ++ ": " ++ primitive_type_to_string t sz ++ " = undefined;"
208 | IR.Comment lines _ =>
209 String.concat String.NewLine (comment_block (ToString.preprocess_comment_block lines))
210 | IR.AssignNth name n val =>
211 name ++ "[" ++ Decimal.Z.to_string (Z.of_nat n) ++ "] = " ++ arith_to_string internal_private prefix val ++ ";"
212 end.
213
214 Definition to_strings {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool) (prefix : string) (e : IR.expr) : 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 Fixpoint to_base_arg_list {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (internal_private : bool) (all_private : bool) (prefix : string) (mode : Mode) {t} : ToString.OfPHOAS.base_var_data t -> list string :=
223 match t return base_var_data t -> _ with
224 | tZ =>
225 let typ := match mode with In => IR.type.Z | Out => IR.type.Zptr end in
226 fun '(n, is_ptr, r, typedef) => [n ++ ": " ++ primitive_type_to_string_opt_typedef all_private prefix typ r typedef]
227 | base.type.prod A B =>
228 fun '(va, vb) => (to_base_arg_list internal_private all_private prefix mode va ++ to_base_arg_list internal_private all_private prefix mode vb)%list
229 | base.type.list tZ =>
230 fun '(n, r, len, typedef) =>
231 let modifier := match mode with
232 | In => (* arrays for inputs are immutable *) ""
233 | Out => (* arrays for outputs are mutable *) "*"
234 end in
235 [ n ++ ": " ++ modifier ++ primitive_array_type_to_string all_private prefix IR.type.Z r len typedef ]
236 | base.type.list _ => fun _ => ["@compilerError(""complex list"");"]
237 | base.type.option _ => fun _ => ["@compilerError(""option"");"]
238 | base.type.unit => fun _ => ["@compilerError(""unit"");"]
239 | base.type.type_base t => fun _ => ["@compilerError(""" ++ show t ++ """);"]%string
240 end%string.
241
242 Definition to_arg_list {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (internal_private : bool) (all_private : bool) (prefix : string) (mode : Mode) {t} : var_data t -> list string :=
243 match t return var_data t -> _ with
244 | type.base t => to_base_arg_list internal_private all_private prefix mode
245 | type.arrow _ _ => fun _ => ["@compilerError(""arrow"");"]
246 end%string.
247
248 Fixpoint to_arg_list_for_each_lhs_of_arrow {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (internal_private : bool) (all_private : bool) (prefix : string) {t} : type.for_each_lhs_of_arrow var_data t -> list string
249 := match t return type.for_each_lhs_of_arrow var_data t -> _ with
250 | type.base t => fun _ => nil
251 | type.arrow s d
252 => fun '(x, xs)
253 => to_arg_list internal_private all_private prefix In x ++ to_arg_list_for_each_lhs_of_arrow internal_private all_private prefix xs
254 end%list.
255
256 (** * Language-specific numeric conversions to be passed to the PHOAS -> IR translation *)
257
258 Definition Zig_bin_op_natural_output
259 : IR.Z_binop -> ToString.int.type * ToString.int.type -> ToString.int.type
260 := fun idc '(t1, t2)
261 => ToString.int.union t1 t2.
262
263 Definition Zig_bin_op_casts
264 : 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)
265 := fun idc desired_type '(t1, t2)
266 => match desired_type with
267 | Some desired_type
268 => let ct := ToString.int.union t1 t2 in
269 let desired_type' := Some (ToString.int.union ct desired_type) in
270 (Some desired_type,
271 (get_Zcast_up_if_needed desired_type' (Some t1),
272 get_Zcast_up_if_needed desired_type' (Some t2)))
273 | None => (None, (None, None))
274 end.
275
276 Definition Zig_un_op_casts
277 : IR.Z_unop -> option ToString.int.type -> ToString.int.type -> option ToString.int.type * option ToString.int.type
278 := fun idc desired_type t
279 => match idc with
280 | IR.Z_shiftr offset
281 =>
282 let t' := ToString.int.union_zrange r[0~>2^offset]%zrange t in
283 ((** We cast the result down to the specified type, if needed *)
284 get_Zcast_down_if_needed desired_type (Some t'),
285 (** We cast the argument up to a large enough type *)
286 get_Zcast_up_if_needed (Some t') (Some t))
287 | IR.Z_shiftl offset
288 =>
289 let rpre_out := match desired_type with
290 | Some rout => Some (ToString.int.union_zrange r[0~>2^offset] (ToString.int.unsigned_counterpart_of rout))
291 | None => Some (ToString.int.of_zrange_relaxed r[0~>2^offset]%zrange)
292 end in
293 ((** We cast the result down to the specified type, if needed *)
294 get_Zcast_down_if_needed desired_type rpre_out,
295 (** We cast the argument up to a large enough type *)
296 get_Zcast_up_if_needed rpre_out (Some t))
297 | IR.Z_lnot ty
298 => (
299 get_Zcast_down_if_needed desired_type (Some ty),
300 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)
301 Some ty)
302 | IR.Z_value_barrier ty
303 => (
304 get_Zcast_down_if_needed desired_type (Some ty),
305 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)
306 Some ty)
307 | IR.Z_bneg
308 => ((* 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 *)
309 None, None)
310 end.
311
312 Local Instance ZigLanguageCasts : LanguageCasts :=
313 {| bin_op_natural_output := Zig_bin_op_natural_output
314 ; bin_op_casts := Zig_bin_op_casts
315 ; un_op_casts := Zig_un_op_casts
316 ; upcast_on_assignment := true
317 ; upcast_on_funcall := true
318 ; explicit_pointer_variables := false
319 |}.
320
321 Definition to_function_lines {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (internal_private : bool) (private : bool) (all_private : bool) (inline : bool) (prefix : string) (name : string)
322 {t}
323 (f : type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * IR.expr)
324 : list string :=
325 let '(args, rets, body) := f in
326 ((if private || inline then "inline fn " else "pub fn ") ++ name ++
327 "(" ++ String.concat ", " (to_arg_list internal_private all_private prefix Out rets ++ to_arg_list_for_each_lhs_of_arrow internal_private all_private prefix args) ++
328 ") void {")%string :: ([" @setRuntimeSafety(mode == .Debug);"; ""]%string)%list ++ (List.map (fun s => " " ++ s)%string (to_strings internal_private prefix body)) ++ ["}"%string]%list.
329
330 (** In Zig, there is no munging of return arguments (they remain
331 passed by pointers), so all variables are live *)
332 Local Instance : consider_retargs_live_opt := fun _ _ _ => true.
333 Local Instance : rename_dead_opt := fun s => s.
334 (** No need to lift declarations to the top *)
335 Local Instance : lift_declarations_opt := false.
336
337 Definition ToFunctionLines
338 {absint_opts : AbstractInterpretation.Options}
339 {relax_zrange : relax_zrange_opt}
340 {language_naming_conventions : language_naming_conventions_opt}
341 {documentation_options : documentation_options_opt}
342 {output_options : output_options_opt}
343 (machine_wordsize : Z)
344 (do_bounds_check : bool) (internal_private : bool) (private : bool) (all_private : bool) (inline : bool) (prefix : string) (name : string)
345 {t}
346 (e : API.Expr t)
347 (comment : type.for_each_lhs_of_arrow var_data t -> var_data (type.base (type.final_codomain t)) -> list string)
348 (name_list : option (list string))
349 (inbounds : type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t)
350 (outbounds : Compilers.ZRange.type.base.option.interp (type.final_codomain t))
351 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
352 (outtypedefs : base_var_typedef_data (type.final_codomain t))
353 : (list string * ToString.ident_infos) + string :=
354 match ExprOfPHOAS do_bounds_check e name_list inbounds intypedefs outtypedefs with
355 | inl (indata, outdata, f) =>
356 inl (((List.map (fun s => if (String.length s =? 0)%nat then "///" else ("/// " ++ s))%string (comment indata outdata))
357 ++ match input_bounds_to_string indata inbounds with
358 | nil => nil
359 | ls => ["/// Input Bounds:"] ++ List.map (fun v => "/// " ++ v)%string ls
360 end
361 ++ match bound_to_string outdata outbounds with
362 | nil => nil
363 | ls => ["/// Output Bounds:"] ++ List.map (fun v => "/// " ++ v)%string ls
364 end
365 ++ to_function_lines internal_private private all_private inline prefix name (indata, outdata, f))%list%string,
366 IR.ident_infos.collect_all_infos f intypedefs outtypedefs)
367 | inr nil =>
368 inr ("Unknown internal error in converting " ++ name ++ " to Zig")%string
369 | inr [err] =>
370 inr ("Error in converting " ++ name ++ " to Zig:" ++ String.NewLine ++ err)%string
371 | inr errs =>
372 inr ("Errors in converting " ++ name ++ " to Zig:" ++ String.NewLine ++ String.concat String.NewLine errs)%string
373 end.
374
375 Definition OutputZigAPI : ToString.OutputLanguageAPI :=
376 {| ToString.comment_block := comment_block;
377 ToString.comment_file_header_block := comment_module_header_block;
378 ToString.ToFunctionLines := @ToFunctionLines;
379 ToString.header := @header;
380 ToString.footer := fun _ _ _ _ _ _ _ _ _ => [];
381 ToString.strip_special_infos machine_wordsize infos := infos |}.
382
383 End Zig.