Debian Codegraph @

src/Stringification/Rust.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 zrange_scope.
17 Local Open Scope Z_scope.
18
19 Import IR.Compilers.ToString.
20 Import Stringification.Language.Compilers.
21 Import Stringification.Language.Compilers.Options.
22 Import Stringification.Language.Compilers.ToString.
23 Import Stringification.Language.Compilers.ToString.int.Notations.
24
25 Module Rust.
26 Definition comment_module_header_block := List.map (fun line => "//! " ++ line)%string.
27 Definition comment_block := List.map (fun line => "/** " ++ line ++ " */")%string.
28
29
30 (* Supported integer bitwidths *)
31 Definition stdint_bitwidths : list Z := [8; 16; 32; 64; 128].
32 Definition is_special_bitwidth (bw : Z) := negb (existsb (Z.eqb bw) stdint_bitwidths).
33
34
35 Definition int_type_to_string_opt_typedef {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (private : bool) (all_private : bool) (prefix : string) (t : ToString.int.type) (typedef : option string) : string :=
36 int.to_string_gen_opt_typedef stdint_bitwidths "u" "i" "" "" private all_private prefix t typedef.
37 Definition int_type_to_string {language_naming_conventions : language_naming_conventions_opt} (private : bool) (prefix : string) (t : ToString.int.type) : string :=
38 int_type_to_string_opt_typedef (skip_typedefs:=true) private private prefix t None.
39
40 Definition make_typedef
41 {language_naming_conventions : language_naming_conventions_opt}
42 {documentation_options : documentation_options_opt}
43 (prefix : string) (internal_private : bool) (private : bool)
44 (typedef : typedef_info)
45 : list string
46 := let '(name, (ty, array_len), description) := name_and_type_and_describe_typedef prefix private typedef in
47 ((comment_block description)
48 ++ [
49 let ty_string := match ty with
50 | Some ty => int_type_to_string internal_private prefix ty
51 | None => "ℤ" (* blackboard bold Z for unbounded integers (which don't actually exist, and thus will error) *)
52 end in
53 let visibility := (if private then "" else "pub ") in
54 match array_len with
55 | None (* just an integer *) => visibility ++ "type " ++ name ++ " = " ++ ty_string ++ ";"
56 | Some None (* unknown array length *) => visibility ++ "type " ++ name ++ " = *mut " ++ ty_string ++ ";"
57 | Some (Some len) => "#[derive(Clone, Copy)]" ++ String.NewLine
58 ++ visibility ++ "struct " ++ name ++ "(pub [" ++ ty_string ++ "; " ++ Decimal.Z.to_string (Z.of_nat len) ++ "]);" ++ String.NewLine ++ String.NewLine
59 ++ "impl core::ops::Index<usize> for " ++ name ++ " {" ++ String.NewLine
60 ++ " type Output = " ++ ty_string ++ ";" ++ String.NewLine
61 ++ " #[inline]" ++ String.NewLine
62 ++ " fn index(&self, index: usize) -> &Self::Output {" ++ String.NewLine
63 ++ " &self.0[index]" ++ String.NewLine
64 ++ " }" ++ String.NewLine
65 ++ "}" ++ String.NewLine ++ String.NewLine
66 ++ "impl core::ops::IndexMut<usize> for " ++ name ++ " {" ++ String.NewLine
67 ++ " #[inline]" ++ String.NewLine
68 ++ " fn index_mut(&mut self, index: usize) -> &mut Self::Output {" ++ String.NewLine
69 ++ " &mut self.0[index]" ++ String.NewLine
70 ++ " }" ++ String.NewLine
71 ++ "}" ++ String.NewLine ++ String.NewLine
72 ++ "impl<'a> IndexConst<&'a " ++ name ++ "> {" ++ String.NewLine
73 ++ " #[allow(unused)]" ++ String.NewLine
74 ++ " #[inline(always)]" ++ String.NewLine
75 ++ " const fn index(self, i: usize) -> &'a " ++ ty_string ++ " {" ++ String.NewLine
76 ++ " &self.0.0[i]" ++ String.NewLine
77 ++ " }" ++ String.NewLine
78 ++ "}" ++ String.NewLine ++ String.NewLine
79 ++ "impl<'a, 'b> IndexConst<&'a mut &'b mut " ++ name ++ "> {" ++ String.NewLine
80 ++ " #[allow(unused)]" ++ String.NewLine
81 ++ " #[inline(always)]" ++ String.NewLine
82 ++ " const fn index_mut(self, i: usize) -> &'a mut " ++ ty_string ++ " {" ++ String.NewLine
83 ++ " &mut self.0.0[i]" ++ String.NewLine
84 ++ " }" ++ String.NewLine
85 ++ "}"
86 end
87 ]%string)%list.
88
89 (* Header imports and type defs *)
90 Definition header
91 {language_naming_conventions : language_naming_conventions_opt}
92 {documentation_options : documentation_options_opt}
93 {package_namev : package_name_opt}
94 {class_namev : class_name_opt}
95 {output_options : output_options_opt}
96 (machine_wordsize : Z) (internal_private : bool) (private : bool) (prefix : string) (infos : ToString.ident_infos)
97 (typedef_map : list typedef_info)
98 : list string
99 := let bitwidths_used := ToString.bitwidths_used infos in
100 let type_prefix := (if internal_private then "type " else "pub type ")%string in
101 (["";
102 "#![allow(unused_parens)]";
103 "#![allow(non_camel_case_types)]";
104 "";
105 "/// Since `Index` and `IndexMut` aren't callable in `const` contexts yet, this helper type helps unify";
106 "/// arrays and user-defined array-wrapper types into a single type which can be indexed in `const`";
107 "/// contexts. Once `const trait`s are stabilized this type can go away";
108 "struct IndexConst<T: ?Sized>(T);";
109 "";
110 "impl<'a, T, const N: usize> IndexConst<&'a [T; N]> {";
111 " #[inline(always)]";
112 " #[allow(unused)]";
113 " const fn index(self, i: usize) -> &'a T {";
114 " &self.0[i]";
115 " }";
116 "}";
117 "impl<'a, 'b, T, const N: usize> IndexConst<&'a mut &'b mut [T; N]> {";
118 " #[inline(always)]";
119 " #[allow(unused)]";
120 " const fn index_mut(self, i: usize) -> &'a mut T {";
121 " &mut self.0[i]";
122 " }";
123 "}";
124 ""]%string
125 ++ (List.flat_map
126 (fun bw
127 => let type_suffix (b : bool) := (int.of_bitwidth b bw) in
128 let typedef_name (b : bool) := int_type_to_string internal_private prefix (type_suffix b) in
129 let type_comment (name : string) := String.concat String.NewLine (comment_block [( name ++ " represents values of " ++ show bw ++ " bits, stored in one byte.")%string]) in
130 (if IntSet.mem (type_suffix false) bitwidths_used || IntSet.mem (type_suffix true) bitwidths_used
131 then [type_comment (typedef_name false) ++ String.NewLine ++ type_prefix ++ (typedef_name false) ++ " = u8;"; (* C: typedef unsigned char prefix_uint1 *)
132 type_comment (typedef_name true ) ++ String.NewLine ++ type_prefix ++ (typedef_name true) ++ " = i8;"]%string (* C: typedef signed char prefix_int1 *)
133 else []))
134 [1; 2])
135 ++ (if skip_typedefs
136 then []
137 else List.flat_map
138 (fun td_name =>
139 match List.find (fun '(name, _, _, _) => (td_name =? name)%string) typedef_map with
140 | Some td_info => [""] ++ make_typedef prefix internal_private private td_info
141 | None => ["#error ""Could not find typedef info for '" ++ td_name ++ "'"";"]%string
142 end%list)
143 (typedefs_used infos))
144 ++ [""])%list%string.
145
146 (* Instead of "macros for minimum-width integer constants" we tried to
147 use numeric casts in Rust. It turns out that it wasn't needed and Rust
148 will figure out the types of the litterals, so disabling this for
149 now *)
150 Definition cast_literal (prefix : string) (t : ToString.int.type) : option string :=
151 if Z.ltb (ToString.int.bitwidth_of t) 8
152 then None
153 else None.
154
155
156 (* Zoe: In fiat-crypto C functions are void and as such, they receive
157 pointers to the result as argumnets. The C code before calling a
158 function, declares uninitializedinteger pointers and passes them as
159 arguments. In Rust to do that, we declare an initialized (to 0)
160 mutable, and pass a mutable reference to the callee.
161
162 In the longer term, we should examine whether we should use
163 non-void functions in Rust and just return the result *)
164
165 Definition primitive_type_to_string_opt_typedef
166 {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt}
167 (private : bool) (all_private : bool)
168 (prefix : string) (t : IR.type.primitive)
169 (r : option ToString.int.type) (typedef : option string) : string :=
170 match t with
171 | IR.type.Zptr => "&mut "
172 | IR.type.Z => ""
173 end ++ match r with
174 | Some int_t => int_type_to_string_opt_typedef private all_private prefix int_t typedef
175 | None => "ℤ" (* blackboard bold Z for unbounded integers (which don't actually exist, and thus will error) *)
176 end.
177 Definition primitive_type_to_string {language_naming_conventions : language_naming_conventions_opt} (private : bool) (prefix : string) (t : IR.type.primitive)
178 (r : option ToString.int.type) : string :=
179 primitive_type_to_string_opt_typedef (skip_typedefs:=true) private private prefix t r None.
180 Definition primitive_array_type_to_string
181 {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt}
182 (internal_private : bool) (all_private : bool)
183 (prefix : string) (t : IR.type.primitive)
184 (r : option ToString.int.type) (len : nat) (typedef : option string) : string :=
185 match (if skip_typedefs then None else typedef) with
186 | Some typedef => format_typedef_name prefix all_private typedef
187 | None => "[" ++ primitive_type_to_string internal_private prefix t r ++ "; " ++ Decimal.Z.to_string (Z.of_nat len) ++ "]"
188 end.
189
190 (* Integer literal to string *)
191 Definition int_literal_to_string (prefix : string) (t : IR.type.primitive) (v : BinInt.Z) : string :=
192 match t, cast_literal prefix (ToString.int.of_zrange_relaxed r[v ~> v]) with
193 | IR.type.Z, Some cast => "(" ++ HexString.of_Z v ++ cast ++ ")"
194 | IR.type.Z, None => (* just print hex value, no cast *) HexString.of_Z v
195 | IR.type.Zptr, _ => "#error ""literal address " ++ HexString.of_Z v ++ """;"
196 end.
197
198 Import IR.Notations.
199
200 Fixpoint arith_to_string
201 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)
202 (prefix : string) {t} (e : IR.arith_expr t) : string
203 := let special_name_ty name ty := ToString.format_special_function_name_ty internal_private prefix name ty in
204 let special_name name bw := ToString.format_special_function_name internal_private prefix name false(*unsigned*) bw in
205 match e with
206 (* integer literals *)
207 | (IR.literal v @@@ _) => int_literal_to_string prefix IR.type.Z v
208 (* array dereference *)
209 | (IR.List_nth n @@@ IR.Var _ v) => "(*IndexConst(" ++ v ++ ").index(" ++ Decimal.Z.to_string (Z.of_nat n) ++ "))"
210 (* (de)referencing *)
211 | (IR.Addr @@@ IR.Var _ v) => "&mut " ++ v (* borrow a mutable ref to v *)
212 | (IR.Dereference @@@ e) => "( *" ++ arith_to_string internal_private prefix e ++ " )"
213 (* bitwise operations *)
214 | (IR.Z_shiftr offset @@@ e) =>
215 "(" ++ arith_to_string internal_private prefix e ++ " >> " ++ Decimal.Z.to_string offset ++ ")"
216 | (IR.Z_shiftl offset @@@ e) =>
217 "(" ++ arith_to_string internal_private prefix e ++ " << " ++ Decimal.Z.to_string offset ++ ")"
218 | (IR.Z_land @@@ (e1, e2)) =>
219 "(" ++ arith_to_string internal_private prefix e1 ++ " & " ++ arith_to_string internal_private prefix e2 ++ ")"
220 | (IR.Z_lor @@@ (e1, e2)) =>
221 "(" ++ arith_to_string internal_private prefix e1 ++ " | " ++ arith_to_string internal_private prefix e2 ++ ")"
222 | (IR.Z_lxor @@@ (e1, e2)) =>
223 "(" ++ arith_to_string internal_private prefix e1 ++ " ^ " ++ arith_to_string internal_private prefix e2 ++ ")"
224 | (IR.Z_lnot _ @@@ e) => "(!" ++ arith_to_string internal_private prefix e ++ ")"
225 (* arithmetic operations *)
226 | (IR.Z_add @@@ (x1, x2)) =>
227 "(" ++ arith_to_string internal_private prefix x1 ++ " + " ++ arith_to_string internal_private prefix x2 ++ ")"
228 | (IR.Z_mul @@@ (x1, x2)) =>
229 "(" ++ arith_to_string internal_private prefix x1 ++ " * " ++ arith_to_string internal_private prefix x2 ++ ")"
230 | (IR.Z_sub @@@ (x1, x2)) =>
231 "(" ++ arith_to_string internal_private prefix x1 ++ " - " ++ arith_to_string internal_private prefix x2 ++ ")"
232 | (IR.Z_bneg @@@ e) => "(!" ++ arith_to_string internal_private prefix e ++ ")" (* logical negation. XXX this has different semantics for numbers <>
233 0 or 1 than it did before *)
234 | (IR.Z_mul_split lg2s @@@ args) =>
235 special_name "mulx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
236 | (IR.Z_add_with_get_carry lg2s @@@ args) =>
237 special_name "addcarryx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
238 | (IR.Z_sub_with_get_borrow lg2s @@@ args) =>
239 special_name "subborrowx" lg2s ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
240 | (IR.Z_zselect ty @@@ args) =>
241 special_name_ty "cmovznz" ty ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
242 | (IR.Z_value_barrier ty @@@ args) =>
243 special_name_ty "value_barrier" ty ++ "(" ++ arith_to_string internal_private prefix args ++ ")"
244 | (IR.Z_static_cast int_t @@@ e) =>
245 "(" ++ arith_to_string internal_private prefix e ++ " as " ++ primitive_type_to_string internal_private prefix IR.type.Z (Some int_t) ++ ")"
246 | IR.Var _ v => v
247 | IR.Pair A B a b => arith_to_string internal_private prefix a ++ ", " ++ arith_to_string internal_private prefix b
248 | (IR.Z_add_modulo @@@ (x1, x2, x3)) => "#error addmodulo;"
249 | (IR.List_nth _ @@@ _)
250 | (IR.Addr @@@ _)
251 | (IR.Z_add @@@ _)
252 | (IR.Z_mul @@@ _)
253 | (IR.Z_sub @@@ _)
254 | (IR.Z_land @@@ _)
255 | (IR.Z_lor @@@ _)
256 | (IR.Z_lxor @@@ _)
257 | (IR.Z_add_modulo @@@ _) => "#error bad_arg;"
258 | IR.TT => "#error tt;"
259 end%string%Cexpr.
260
261 Definition stmt_to_string
262 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)
263 (prefix : string) (e : IR.stmt) : string :=
264 match e with
265 | IR.Call val => arith_to_string internal_private prefix val ++ ";"
266 | IR.Assign true t sz name val =>
267 (* local non-mutable declaration with initialization *)
268 "let " ++ name ++ ": " ++ primitive_type_to_string internal_private prefix t sz ++ " = " ++ arith_to_string internal_private prefix val ++ ";"
269 | IR.Assign false _ sz name val =>
270 (* This corresponds to assignment to a non-pointer variable and should never ever
271 happen in our generated code. Fiat-crypto handles it but I
272 haven't found and instance of this to their generated code *)
273 (* code : name ++ " = " ++ arith_to_string internal_private prefix val ++ ";" *)
274 "#error trying to assign value to non-mutable variable;"
275 | IR.AssignZPtr name sz val =>
276 "*" ++ name ++ " = " ++ arith_to_string internal_private prefix val ++ ";"
277 | IR.DeclareVar t sz name =>
278 (* Local uninitialized declarations become mut declarations, and
279 are initialized to 0. *)
280 (* The assumptions here, based on fiat-crypto code generation
281 patterns, are that 1.) this variable will be an argument to a
282 call that will store its result in this variable. 2.) this will
283 have a non-pointer an integer type *)
284 "let mut " ++ name ++ ": " ++ primitive_type_to_string internal_private prefix t sz ++ " = 0;"
285 | IR.Comment lines _ =>
286 String.concat String.NewLine (comment_block (ToString.preprocess_comment_block lines))
287 | IR.AssignNth name n val =>
288 "*IndexConst(&mut " ++ name ++ ").index_mut(" ++ Decimal.Z.to_string (Z.of_nat n) ++ ") = " ++ arith_to_string internal_private prefix val ++ ";"
289 end.
290
291 Definition to_strings {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool) (prefix : string) (e : IR.expr) : list string :=
292 List.map (stmt_to_string internal_private prefix) e.
293
294 Import Rewriter.Language.Language.Compilers Crypto.Language.API.Compilers IR.OfPHOAS.
295 Local Notation tZ := (base.type.type_base base.type.Z).
296
297 Inductive Mode := In | Out.
298
299
300 (* This would have been nice, but coercions don't work *)
301 (* Module Base := Rewriter.Language.Language.Compilers.base. *)
302
303 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 :=
304 match t return base_var_data t -> _ with
305 | tZ =>
306 let typ := match mode with In => IR.type.Z | Out => IR.type.Zptr end in
307 fun '(n, is_ptr, r, typedef) => [n ++ ": " ++ primitive_type_to_string_opt_typedef internal_private all_private prefix typ r typedef]
308 | base.type.prod A B =>
309 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
310 | base.type.list tZ =>
311 fun '(n, r, len, typedef) =>
312 let (modifier1, modifier2) := match mode with
313 | In => (* arrays for inputs are immutable *) ("", "&")
314 | Out => (* arrays for outputs are mutable *) ("mut ", "&mut ")
315 end in
316 [modifier1 ++ n ++ ": " ++ modifier2 ++ primitive_array_type_to_string internal_private all_private prefix IR.type.Z r len typedef]
317 | base.type.list _ => fun _ => ["#error ""complex list"";"]
318 | base.type.option _ => fun _ => ["#error option;"]
319 | base.type.unit => fun _ => ["#error unit;"]
320 | base.type.type_base t => fun _ => ["#error " ++ show t ++ ";"]%string
321 end%string.
322
323 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 :=
324 match t return var_data t -> _ with
325 | type.base t => to_base_arg_list internal_private all_private prefix mode
326 | type.arrow _ _ => fun _ => ["#error arrow;"]
327 end%string.
328
329 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
330 := match t return type.for_each_lhs_of_arrow var_data t -> _ with
331 | type.base t => fun _ => nil
332 | type.arrow s d
333 => fun '(x, xs)
334 => to_arg_list internal_private all_private prefix In x ++ to_arg_list_for_each_lhs_of_arrow internal_private all_private prefix xs
335 end%list.
336
337 (** * Language-specific numeric conversions to be passed to the PHOAS -> IR translation *)
338
339 Definition Rust_bin_op_natural_output
340 : IR.Z_binop -> ToString.int.type * ToString.int.type -> ToString.int.type
341 := fun idc '(t1, t2)
342 => ToString.int.union t1 t2.
343
344 Definition Rust_bin_op_casts
345 : 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)
346 := fun idc desired_type '(t1, t2)
347 => match desired_type with
348 | Some desired_type
349 => let ct := ToString.int.union t1 t2 in
350 let desired_type' := Some (ToString.int.union ct desired_type) in
351 (Some desired_type,
352 (get_Zcast_up_if_needed desired_type' (Some t1),
353 get_Zcast_up_if_needed desired_type' (Some t2)))
354 | None => (None, (None, None))
355 end.
356
357 Definition Rust_un_op_casts
358 : IR.Z_unop -> option ToString.int.type -> ToString.int.type -> option ToString.int.type * option ToString.int.type
359 := fun idc desired_type t
360 => match idc with
361 | IR.Z_shiftr offset
362 => (** N.B. We must cast the expression up to a large
363 enough type to fit 2^offset (importantly, not just
364 2^offset-1), because C considers it to be undefined
365 behavior to shift >= width of the type. We should
366 probably figure out how to not generate these
367 things in the first place...
368
369 N.B. We must preserve signedness of the value being
370 shifted, because shift does not commute with
371 mod. *)
372 let t' := ToString.int.union_zrange r[0~>2^offset]%zrange t in
373 ((** We cast the result down to the specified type, if needed *)
374 get_Zcast_down_if_needed desired_type (Some t'),
375 (** We cast the argument up to a large enough type *)
376 get_Zcast_up_if_needed (Some t') (Some t))
377 | IR.Z_shiftl offset
378 => (** N.B. We must cast the expression up to a large
379 enough type to fit 2^offset (importantly, not just
380 2^offset-1), because C considers it to be undefined
381 behavior to shift >= width of the type. We should
382 probably figure out how to not generate these
383 things in the first place...
384
385 N.B. We make sure that we only left-shift unsigned
386 values, since shifting into the sign bit is
387 undefined behavior. *)
388 let rpre_out := match desired_type with
389 | Some rout => Some (ToString.int.union_zrange r[0~>2^offset] (ToString.int.unsigned_counterpart_of rout))
390 | None => Some (ToString.int.of_zrange_relaxed r[0~>2^offset]%zrange)
391 end in
392 ((** We cast the result down to the specified type, if needed *)
393 get_Zcast_down_if_needed desired_type rpre_out,
394 (** We cast the argument up to a large enough type *)
395 get_Zcast_up_if_needed rpre_out (Some t))
396 | IR.Z_lnot ty
397 => ((* if the result is too big, we cast it down; we
398 don't need to upcast it because it'll get
399 picked up by implicit casts if necessary *)
400 get_Zcast_down_if_needed desired_type (Some ty),
401 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)
402 Some ty)
403 | IR.Z_value_barrier ty
404 => ((* if the result is too big, we cast it down; we
405 don't need to upcast it because it'll get
406 picked up by implicit casts if necessary *)
407 get_Zcast_down_if_needed desired_type (Some ty),
408 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)
409 Some ty)
410 | IR.Z_bneg
411 => ((* 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 *)
412 None, None)
413 end.
414
415 Local Instance RustLanguageCasts : LanguageCasts :=
416 {| bin_op_natural_output := Rust_bin_op_natural_output
417 ; bin_op_casts := Rust_bin_op_casts
418 ; un_op_casts := Rust_un_op_casts
419 ; upcast_on_assignment := true
420 ; upcast_on_funcall := true
421 ; explicit_pointer_variables := false
422 |}.
423
424 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)
425 {t}
426 (f : type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * IR.expr)
427 : list string :=
428 let '(args, rets, body) := f in
429 ((if inline then "#[inline]" ++ String.NewLine else "") ++ (if private then "const fn " else "pub const fn ") ++ name ++
430 "(" ++ 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) ++
431 ") {")%string :: (List.map (fun s => " " ++ s)%string (to_strings internal_private prefix body)) ++ ["}"%string]%list.
432
433 (** In Rust, there is no munging of return arguments (they remain
434 passed by pointers), so all variables are live *)
435 Local Instance : consider_retargs_live_opt := fun _ _ _ => true.
436 Local Instance : rename_dead_opt := fun s => s.
437 (** No need to lift declarations to the top *)
438 Local Instance : lift_declarations_opt := false.
439
440 Definition ToFunctionLines
441 {absint_opts : AbstractInterpretation.Options}
442 {relax_zrange : relax_zrange_opt}
443 {language_naming_conventions : language_naming_conventions_opt}
444 {documentation_options : documentation_options_opt}
445 {output_options : output_options_opt}
446 (machine_wordsize : Z)
447 (do_bounds_check : bool) (internal_private : bool) (private : bool) (all_private : bool) (inline : bool) (prefix : string) (name : string)
448 {t}
449 (e : API.Expr t)
450 (comment : type.for_each_lhs_of_arrow var_data t -> var_data (type.base (type.final_codomain t)) -> list string)
451 (name_list : option (list string))
452 (inbounds : type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t)
453 (outbounds : Compilers.ZRange.type.base.option.interp (type.final_codomain t))
454 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
455 (outtypedefs : base_var_typedef_data (type.final_codomain t))
456 : (list string * ToString.ident_infos) + string :=
457 match ExprOfPHOAS do_bounds_check e name_list inbounds intypedefs outtypedefs with
458 | inl (indata, outdata, f) =>
459 inl (((List.map (fun s => if (String.length s =? 0)%nat then "///" else ("/// " ++ s))%string (comment indata outdata))
460 ++ match input_bounds_to_string indata inbounds with
461 | nil => nil
462 | ls => ["/// Input Bounds:"] ++ List.map (fun v => "/// " ++ v)%string ls
463 end
464 ++ match bound_to_string outdata outbounds with
465 | nil => nil
466 | ls => ["/// Output Bounds:"] ++ List.map (fun v => "/// " ++ v)%string ls
467 end
468 ++ to_function_lines internal_private private all_private inline prefix name (indata, outdata, f))%list%string,
469 IR.ident_infos.collect_all_infos f intypedefs outtypedefs)
470 | inr nil =>
471 inr ("Unknown internal error in converting " ++ name ++ " to Rust")%string
472 | inr [err] =>
473 inr ("Error in converting " ++ name ++ " to Rust:" ++ String.NewLine ++ err)%string
474 | inr errs =>
475 inr ("Errors in converting " ++ name ++ " to Rust:" ++ String.NewLine ++ String.concat String.NewLine errs)%string
476 end.
477
478 Definition OutputRustAPI : ToString.OutputLanguageAPI :=
479 {| ToString.comment_block := comment_block;
480 ToString.comment_file_header_block := comment_module_header_block;
481 ToString.ToFunctionLines := @ToFunctionLines;
482 ToString.header := @header;
483 ToString.footer := fun _ _ _ _ _ _ _ _ _ => [];
484 (** No special handling for any functions *)
485 ToString.strip_special_infos machine_wordsize infos := infos |}.
486
487 End Rust.