Debian Codegraph @

src/CLI.v

raw
1 From Coq Require Import QArith.
2 From Coq Require Import ZArith.
3 From Coq Require Import Ascii.
4 From Coq Require Import List.
5 From Coq Require Import String.
6 From Coq Require Import HexString.
7 Require Crypto.Util.Strings.String.
8 Require Import Crypto.Assembly.Syntax.
9 Require Import Crypto.Assembly.Parse.
10 Require Import Crypto.Assembly.Symbolic.
11 Require Import Crypto.Assembly.Equivalence.
12 Require Import Crypto.Util.Strings.Decimal.
13 Require Import Crypto.Util.Strings.ParseArithmetic.
14 Require Import Crypto.Util.Strings.ParseArithmeticToTaps.
15 Require Import Crypto.Util.Strings.Parse.Common.
16 Require Import Crypto.Util.Strings.NamingConventions.
17 Require Import Crypto.Util.Option.
18 Require Import Crypto.Util.OptionList.
19 Require Import Crypto.Util.Strings.Show.
20 Require Import Crypto.Util.Strings.Show.Enum.
21 Require Import Crypto.Util.Strings.Sorting.
22 Require Import Crypto.Util.Strings.ParseFlagOptions.
23 Require Import Crypto.Util.DebugMonad.
24 Require Import Crypto.Util.Listable.
25 Require Crypto.PushButtonSynthesis.SaturatedSolinas.
26 Require Crypto.PushButtonSynthesis.UnsaturatedSolinas.
27 Require Crypto.PushButtonSynthesis.WordByWordMontgomery.
28 Require Crypto.PushButtonSynthesis.BaseConversion.
29 Require Crypto.PushButtonSynthesis.DettmanMultiplication.
30 Require Crypto.PushButtonSynthesis.SolinasReduction.
31 Require Import Crypto.UnsaturatedSolinasHeuristics.
32 Require Import Crypto.Stringification.Language.
33 Require Import Crypto.Stringification.C.
34 Require Import Crypto.BoundsPipeline.
35 Require Import Crypto.Stringification.Rust.
36 Require Import Crypto.Stringification.Go.
37 Require Import Crypto.Stringification.Java.
38 Require Import Crypto.Stringification.JSON.
39 Require Import Crypto.Stringification.Zig.
40 Require Crypto.Util.Arg.
41 Import ListNotations. Local Open Scope Z_scope. Local Open Scope string_scope.
42
43 Import
44 Stringification.Language.Compilers
45 Stringification.C.Compilers.
46
47 Module ForExtraction.
48 Variant SynthesisKind : Set :=
49 | word_by_word_montgomery
50 | unsaturated_solinas
51 | saturated_solinas
52 | dettman_multiplication
53 | solinas_reduction
54 | base_conversion
55 .
56
57 Derive SynthesisKind_Listable SuchThat (@FinitelyListable SynthesisKind SynthesisKind_Listable) As SynthesisKind_FinitelyListable.
58 Proof. prove_ListableDerive. Qed.
59 Global Existing Instances SynthesisKind_Listable SynthesisKind_FinitelyListable.
60
61 Global Instance show_SynthesisKind : Show SynthesisKind.
62 Proof. prove_Show_enum (). Defined.
63 Global Instance show_lvl_SynthesisKind : ShowLevel SynthesisKind := show_SynthesisKind.
64
65 Definition parse_SynthesisKind_list : list (string * SynthesisKind)
66 := Eval vm_compute in
67 List.map
68 (fun r => (String.replace "_" "-" (show r), r))
69 (list_all SynthesisKind).
70
71 Definition parse_SynthesisKind_act : ParserAction SynthesisKind
72 := parse_strs parse_SynthesisKind_list.
73
74 Definition parse_string_and {T} (parse_T : string -> option T) (s : string) : option (string * T)
75 := option_map (@pair _ _ s) (parse_T s).
76 Definition parse_Z (s : string) : option Z := parseZ_arith_strict s.
77 Definition parse_N (s : string) : option N := parseN_arith_strict s.
78 Definition parse_nat (s : string) : option nat := parsenat_arith_strict s.
79 Definition parse_Q (s : string) : option Q := parseQ_arith_strict s.
80 Definition parse_bool (s : string) : option bool
81 := if string_dec s "true"
82 then Some true
83 else if string_dec s "false"
84 then Some false
85 else None.
86 Definition parse_list_Z (s : string) : option (list Z)
87 := (ls <- finalize (parse_list ParseArithmetic.parse_Qexpr) s;
88 ls <-- List.map ParseArithmetic.eval_Qexpr_strict ls;
89 ls <-- List.map ParseArithmetic.Q_to_Z_strict ls;
90 Some ls).
91
92 Definition parse_SynthesisKind (s : string) : option SynthesisKind
93 := finalize parse_SynthesisKind_act s.
94
95 Definition parse_list_REG (s : string) : option (list REG)
96 := finalize (parse_comma_list parse_REG) s.
97
98 Definition parse_list_rewrite_pass (s : string) : option (list rewrite_pass)
99 := finalize (parse_comma_list parse_rewrite_pass) s.
100
101 Definition parse_comma_list_Z (s : string) : option (list Z)
102 := (ls <- finalize (parse_comma_list ParseArithmetic.parse_Qexpr) s;
103 ls <-- List.map ParseArithmetic.eval_Qexpr_strict ls;
104 ls <-- List.map ParseArithmetic.Q_to_Z_strict ls;
105 Some ls).
106
107 Definition parse_callee_saved_registers (s : string) : option assembly_callee_saved_registers_opt
108 := finalize parse_assembly_callee_saved_registers_opt s.
109
110 Definition parse_n (n : string) : option MaybeLimbCount
111 := match parse_nat n with
112 | Some n => Some (NumLimbs n)
113 | None
114 => let idx1 := String.length "(auto" in
115 let autov := substring 0 idx1 n in
116 let numv := substring idx1 (String.length n) n in
117 let numv := substring 0 (String.length numv - 1) numv in
118 let lastch := substring (String.length n - 1) 1 n in
119 if ((lastch =? ")") && (autov =? "(auto"))%string%bool
120 then let numv := if (numv =? "")%string
121 then Some 0%nat
122 else parse_nat numv in
123 option_map Auto numv
124 else None
125 end.
126
127 Definition parse_sc (s : string) : option (Z * list (Z * Z))
128 := parseZ_arith_to_taps s.
129
130 Definition parse_machine_wordsize (s : string) : option Z
131 := parse_Z s.
132 Definition parse_m (s : string) : option Z
133 := parse_Z s.
134
135 Definition parse_case_convention (s : string) : option capitalization_data
136 := parse_capitalization_data_strict s.
137 Definition valid_case_conventions : string
138 := Eval compute in
139 String.concat
140 ", "
141 (List.flat_map
142 (fun '(_, ls)
143 => match ls with
144 | [] => []
145 | [n] => [n]
146 | n :: ns
147 => [n ++ " (alternatively: " ++ String.concat ", " ns ++ ")"]
148 end%string)
149 parse_capitalization_data_pre_list).
150
151 Definition parse_src_n : string -> option nat := parse_nat.
152 Definition parse_limbwidth : string -> option Q := parse_Q.
153 Definition parse_max (s : string) : option (option Z)
154 := option_map (@Some _) (parse_Z s).
155 Definition parse_bounds_multiplier (s : option string) : string * option (option Q)
156 := let s := Option.value s "" in
157 (s,
158 if string_dec s ""
159 then Some None
160 else option_map (@Some _) (parse_Q s)).
161 Definition parse_dirbounds_multiplier (dir : string) (s : option string + list string) : string * (option Q + list string)
162 := match s with
163 | inl s
164 => let '(s, q) := parse_bounds_multiplier s in
165 (s,
166 match q with
167 | Some q => inl q
168 | None => inr ["Could not parse '" ++ s ++ "' as a ℚ for --" ++ dir ++ "bounds-multiplier"]%string
169 end)
170 | inr opts
171 => ("", inr ["Argument --" ++ dir ++ "bounds-multiplier can only be passed once; passed multiple times with values: " ++ String.concat ", " opts])
172 end.
173
174 Definition parse_bounds_list (s : option string) : string * option (option (list Z))
175 := match s with
176 | None => ("", Some None)
177 | Some s
178 => (s,
179 option_map (@Some _) (parse_list_Z s))
180 end.
181
182 Definition parse_dirbounds (dir : string) (s : option string + list string) (use_bitwidth : bool) : string * (BaseConversion.bounds + list string)
183 := match s with
184 | inl s
185 => let '(s, ls) := parse_bounds_list s in
186 (s,
187 match ls, use_bitwidth with
188 | Some (Some ls), false => inl (BaseConversion.exactly ls)
189 | Some None, false => inl BaseConversion.use_prime
190 | Some None, true => inl BaseConversion.use_bitwidth
191 | _, _
192 => let err1 := match ls, use_bitwidth with
193 | Some _, true => ["Cannot pass both --use-bitwidth-" ++ dir ++ " and --" ++ dir ++ "bounds=" ++ s]%string
194 | _, _ => []
195 end in
196 let err2 := match ls with
197 | None => ["Could not parse " ++ dir ++ "bounds (" ++ s ++ ")"]%string
198 | _ => []
199 end in
200 inr (err1 ++ err2)%list
201 end)
202 | inr opts
203 => ("",
204 inr ((["Argument --" ++ dir ++ "bounds can only be passed once; passed multiple times with values: " ++ String.concat ", " opts]%string)
205 ++ if use_bitwidth
206 then ["Cannot pass both --use-bitwidth-" ++ dir ++ " and --" ++ dir ++ "bounds"]%string
207 else [])%list)
208 end.
209
210 Definition show_c : Show (list (Z * Z))
211 := @show_list _ (@show_prod _ _ PowersOfTwo.show_Z Decimal.show_Z).
212
213 Local Open Scope string_scope.
214
215 (** TODO: Write a better quoter and maybe move this elsewhere *)
216 (** https://mywiki.wooledge.org/BashGuide/SpecialCharacters *)
217 (** We also quote the "/" character so that we don't change quoting behavior based on Windows vs Linux paths *)
218 Definition quote (s : string) : string
219 := if List.existsb (fun ch => List.existsb (fun badch => badch =? ch)%char
220 [" "; "$"; "'"; """"; "\"; "#"; "="; "!"; ">"; "<"; "|"; ";"; "{"; "}"; "("; ")"; "["; "]"; "*"; "?"; "~"; "&"; "`"; "/"]%char)
221 (String.list_ascii_of_string s)
222 || (String.length s =? 0)%nat
223 then "'" ++ String.replace "'" "'""'""'" s ++ "'"
224 else s.
225
226 Definition known_debug_options_with_spec : list (string * string)
227 := [("on-success", "In addition to printing the debug information when synthesis fails, also print it when synthesis succeeds.")
228 ; ("rewriting", "Print the AST before and after each rewriting pass.")
229 ].
230 Definition known_debug_options : list string
231 := Eval compute in List.map fst known_debug_options_with_spec.
232 Definition special_debug_options : list (string * flag_option_kind)
233 := [("all", all)
234 ].
235 (** This string gets parsed as the initial argument to --debug, to be updated by subsequent arguments *)
236 Definition default_debug : string := "rewriting".
237
238 Definition known_asm_rewriting_pass_flags : list string
239 := Eval compute in StringSort.sort (List.map show (list_all Assembly.Symbolic.RewritePass.rewrite_pass)).
240 Definition known_asm_rewriting_pass_flags_with_spec : list (string * string)
241 := Eval compute in
242 Option.invert_Some
243 (Option.List.lift
244 (List.map
245 (fun s => p <- finalize parse_rewrite_pass s; Some (s, Assembly.Symbolic.Rewrite.describe_pass p:string))%option
246 known_asm_rewriting_pass_flags)).
247 Definition special_asm_rewriting_pass_flags : list (string * flag_option_kind)
248 := [("all", all)
249 ].
250 (** This string gets parsed as the initial argument to --asm-rewriting-passes, to be updated by subsequent arguments *)
251 Definition default_asm_rewriting_passes : string := "all".
252
253 Definition default_asm_rewriting_pipeline : string
254 := Eval compute in String.concat "," (List.map show default_rewrite_pass_order).
255
256 Definition CollectErrors
257 {machine_wordsize : machine_wordsize_opt}
258 {output_language_api : ToString.OutputLanguageAPI}
259 (res : list (synthesis_output_kind * string * Pipeline.M (list string)))
260 : Pipeline.DebugM (((* normal *) list (list string)) * ((* asm output *) list (list string))) + (* error *) list (Pipeline.DebugM (list string))
261 := (let header := hd "" (List.map (@snd _ _) (List.map (@fst _ _) res)) in
262 let res :=
263 List.fold_right
264 (fun '(kind, name, res) rest
265 => match Debug.eval_result res, rest with
266 | ErrorT.Error err, rest
267 => let in_name := ("In " ++ name ++ ":") in
268 let cur :=
269 match show_lines err with
270 | [serr] => [in_name ++ " " ++ serr]
271 | serr => in_name::serr
272 end in
273 let rest := match rest with inl _ => nil | inr rest => rest end in
274 inr ((Debug.with_debug_info res (Debug.ret cur)) :: rest)
275 | ErrorT.Success v, inr ls => inr ls
276 | ErrorT.Success v, inl ls
277 => inl (Debug.copy_debug_info res;;
278 ls <- ls;
279 Debug.ret
280 (match kind, ls with
281 | normal_output , (ls_normal, ls_asm)
282 => (v :: ls_normal, ls_asm)
283 | assembly_output, (ls_normal, ls_asm)
284 => (ls_normal, v :: ls_asm)
285 end))
286 end)
287 (inl (Debug.ret (nil, nil)))
288 res in
289 match res with
290 | inl ls => inl ls
291 | inr err => inr (Debug.ret [header]::err)
292 end)%debugM.
293
294 Class supported_languagesT := supported_languages : list (string * ToString.OutputLanguageAPI).
295
296 (** N.B. The order matters, as the first element of the supported
297 languages list is used as the default. *)
298 Definition default_supported_languages : supported_languagesT
299 := [("C", ToString.OutputCAPI)
300 ; ("Rust", Rust.OutputRustAPI)
301 ; ("Go", Go.OutputGoAPI)
302 ; ("Java", Java.OutputJavaAPI)
303 ; ("JSON", JSON.OutputJSONAPI)
304 ; ("Zig", Zig.OutputZigAPI)].
305
306 Local Notation anon_argT := (string * Arg.spec * Arg.doc)%type (only parsing).
307 Local Notation named_argT := (list Arg.key * Arg.spec * Arg.doc)%type (only parsing).
308
309 Definition describe_flag_options (kind:string) (all_descr:string) (special_options : list (string * flag_option_kind)) (known_options_with_spec : list (string * string)) : list string
310 := let len := List.fold_right Nat.max 0%nat (List.map String.length (List.map fst known_options_with_spec ++ List.map fst special_options)) in
311 let fill s := (s ++ String.repeat " " (len - String.length s))%string in
312 ((["Valid " ++ kind ++ " flags:"]%string)
313 ++ (List.flat_map
314 (fun '(opt, k)
315 => match k with
316 | all => ["- " ++ fill opt ++ String.Tab ++ all_descr]
317 | alias _ => []
318 end)%string
319 special_options)
320 ++ (List.map
321 (fun '(opt, descr) => "- " ++ fill opt ++ String.Tab ++ descr)%string
322 known_options_with_spec)
323 ++ (List.flat_map
324 (fun '(opt, k)
325 => match k with
326 | all => []
327 | alias ls => ["- " ++ fill opt ++ String.Tab ++ "an alias for " ++ String.concat "," ls]
328 end)%string
329 special_options)).
330
331 Definition synthesis_kind_spec : anon_argT
332 := ("synthesis_kind",
333 Arg.CustomSymbol parse_SynthesisKind_list,
334 ["The algorithm for field arithmetic. Further options depend on the choice of algorithm, and can be viewed by passing -h after this argument. Note that no options other than -h are permitted before this argument."]).
335 Definition curve_description_spec : anon_argT
336 := ("curve_description",
337 Arg.String,
338 ["A string which will be prefixed to every function name generated"]).
339 Definition lang_default {supported_languages : supported_languagesT}
340 := List.hd ("C", ToString.OutputCAPI) supported_languages.
341 Definition lang_spec {supported_languages : supported_languagesT} : named_argT
342 := let supported_language_names := List.map (@fst _ _) supported_languages in
343 ([Arg.long_key "lang"],
344 Arg.CustomSymbol supported_languages,
345 ["The output language code should be emitted in. Defaults to " ++ List.hd "C" supported_language_names ++ " if no language is given. Case-sensitive."]).
346 Definition no_prefix_fiat_spec : named_argT
347 := ([Arg.long_key "no-prefix-fiat"], Arg.Unit, ["Don't prefix functions with fiat_"]).
348 Definition package_name_spec : named_argT
349 := ([Arg.long_key "package-name"], Arg.String, ["The name of the package, for languages that support it."]).
350 Definition class_name_spec : named_argT
351 := ([Arg.long_key "class-name"], Arg.String, ["The name of the class, for languages that support it."]).
352 Definition private_function_case_spec : named_argT
353 := ([Arg.long_key "private-function-case"],
354 Arg.Custom (parse_string_and parse_case_convention) "CONVENTION",
355 ["The case convention for non-exported function names. Default is to not adjust case, resulting in, roughly, snake_case."
356 ; "Valid options are: " ++ valid_case_conventions ++ "."]).
357 Definition public_function_case_spec : named_argT
358 := ([Arg.long_key "public-function-case"],
359 Arg.Custom (parse_string_and parse_case_convention) "CONVENTION",
360 ["The case convention for exported function names. Default is to not adjust case, resulting in, roughly, snake_case."
361 ; "Valid options are: " ++ valid_case_conventions ++ "."]).
362 Definition private_type_case_spec : named_argT
363 := ([Arg.long_key "private-type-case"],
364 Arg.Custom (parse_string_and parse_case_convention) "CONVENTION",
365 ["The case convention for non-exported type names. Default is to not adjust case, resulting in, roughly, snake_case."
366 ; "Valid options are: " ++ valid_case_conventions ++ "."]).
367 Definition public_type_case_spec : named_argT
368 := ([Arg.long_key "public-type-case"],
369 Arg.Custom (parse_string_and parse_case_convention) "CONVENTION",
370 ["The case convention for exported type names. Default is to not adjust case, resulting in, roughly, snake_case."
371 ; "Valid options are: " ++ valid_case_conventions ++ "."]).
372 Definition class_case_spec : named_argT
373 := ([Arg.long_key "class-case"],
374 Arg.Custom (parse_string_and parse_case_convention) "CONVENTION",
375 ["The case convention for the default class name. Only meaningful when the class name is inferred from curve_description, rather than given explicitly with --class-name."
376 ; "Valid options are: " ++ valid_case_conventions ++ "."]).
377 Definition package_case_spec : named_argT
378 := ([Arg.long_key "package-case"],
379 Arg.Custom (parse_string_and parse_case_convention) "CONVENTION",
380 ["The case convention for the default package name. Only meaningful when the package name is inferred from curve_description, rather than given explicitly with --package-name."
381 ; "Valid options are: " ++ valid_case_conventions ++ "."]).
382 Definition static_spec : named_argT
383 := ([Arg.long_key "static"], Arg.Unit, ["Declare the functions as static, i.e., local to the file."]).
384 Definition internal_static_spec : named_argT
385 := ([Arg.long_key "internal-static"], Arg.Unit, ["Declare internal functions as static, i.e., local to the file."]).
386 Definition inline_spec : named_argT
387 := ([Arg.long_key "inline"], Arg.Unit, ["Declare all functions as inline."]).
388 Definition inline_internal_spec : named_argT
389 := ([Arg.long_key "inline-internal"], Arg.Unit, ["Declare internal functions as inline."]).
390 Definition only_signed_spec : named_argT
391 := ([Arg.long_key "only-signed"], Arg.Unit, ["Only allow signed integer types."]).
392 Definition no_select_spec : named_argT
393 := ([Arg.long_key "no-select"], Arg.Unit, ["Use expressions that don't require cmov."]).
394 Definition no_wide_int_spec : named_argT
395 := ([Arg.long_key "no-wide-int"], Arg.Unit, ["Don't use integers wider than the bitwidth."]).
396 Definition widen_carry_to_bytes_spec : named_argT
397 := ([Arg.long_key "widen-carry-to-bytes"], Arg.Unit, ["Always widen carry bit integer types the byte type, or to the full bitwidth if --widen-bytes is also passed."]).
398 Definition widen_carry_spec : named_argT
399 := ([Arg.long_key "widen-carry"], Arg.Unit, ["Widen carry bit integer types to either the byte type, or to the full bitwidth if --widen-bytes is also passed."]).
400 Definition widen_bytes_spec : named_argT
401 := ([Arg.long_key "widen-bytes"], Arg.Unit, ["Widen byte types to the full bitwidth."]).
402 Definition split_multiret_spec : named_argT
403 := ([Arg.long_key "split-multiret"], Arg.Unit, ["Don't allow instructions to return two results. This should always be set for bedrock2."]).
404 Definition value_barrier_spec : named_argT
405 := ([Arg.long_key "use-value-barrier"], Arg.Unit, ["Guard some expressions with an assembly barrier to prevent compilers from generating non-constant-time code for cmovznz."]).
406 Definition no_primitives_spec : named_argT
407 := ([Arg.long_key "no-primitives"], Arg.Unit, ["Suppress the generation of the bodies of primitive operations such as addcarryx, subborrowx, cmovznz, mulx, etc."]).
408 Definition no_field_element_typedefs_spec : named_argT
409 := ([Arg.long_key "no-field-element-typedefs"], Arg.Unit, ["Do not use type aliases for field elements based on bounds, Montgomery-domain vs not Montgomery-domain, etc."]).
410 Definition emit_all_casts_spec : named_argT
411 := ([Arg.long_key "emit-all-casts"], Arg.Unit, ["Rather than performing language-specific cast-adjustment, just emit all casts that are present in the intermediate representation, annotating all constructions."]).
412 Definition relax_primitive_carry_to_bitwidth_spec : named_argT
413 := ([Arg.long_key "relax-primitive-carry-to-bitwidth"],
414 Arg.Custom (parse_string_and parse_comma_list_Z) "ℤ,ℤ,…",
415 ["For any (comma-separated) bitwidths passed to this argument, use bitwidth-sized bounds rather than tighter bounds for the carry return value of primitives such as addcarryx and subborrowx."]).
416 Definition cmovznz_by_mul_spec : named_argT
417 := ([Arg.long_key "cmovznz-by-mul"], Arg.Unit, ["Use an alternative implementation of cmovznz using multiplication rather than bitwise-and with -1."]).
418 Definition shiftr_avoid_uint1_spec : named_argT
419 := ([Arg.long_key "shiftr-avoid-uint1"], Arg.Unit, ["Avoid uint1 types at the output of (>>) operations."]).
420 Definition tight_bounds_multiplier_default := default_tight_upperbound_fraction.
421 Definition tight_bounds_multiplier_spec : named_argT
422 := ([Arg.long_key "tight-bounds-mul-by"],
423 Arg.Custom (parse_string_and parse_Q) "ℚ",
424 ["The (improper) fraction by which the (tight) bounds of each limb are scaled"]).
425 Definition n_spec : anon_argT
426 := ("n",
427 Arg.Custom (parse_string_and parse_n) "an ℕ or the literal '(auto)' or '(autoN)' for a non-negative number N",
428 ["The number of limbs, or the literal '(auto)' or '(autoN)' for a non-negative number N, to automatically guess the number of limbs"]).
429 Definition n_nat_spec : anon_argT
430 := ("n",
431 Arg.Custom (parse_string_and parse_nat) "ℕ",
432 ["The number of limbs"]).
433 Definition last_limb_width_spec : anon_argT
434 := ("last_limb_width",
435 Arg.Custom (parse_string_and parse_nat) "ℕ",
436 ["The desired width of the last (most significant) limb"]).
437 Definition last_reduction_spec : anon_argT
438 := ("last_reduction",
439 Arg.Custom (parse_string_and parse_nat) "ℕ",
440 ["The limb that the final modular reduction lands in. Should be between 1 and limbs - 3, inclusive. Larger values correspond to a faster algorithm but looser bounds on the output."]).
441 Definition sc_spec : anon_argT
442 := ("s-c",
443 Arg.Custom (parse_string_and parse_sc) "an integer expression",
444 ["The prime, which must be expressed as a difference of a power of two and a small field element (e.g., '2^255 - 19', '2^448 - 2^224 - 1')"]).
445 Definition m_spec : anon_argT
446 := ("m",
447 Arg.Custom (parse_string_and parse_m) "an integer expression",
448 ["The prime (e.g., '2^434 - (2^216*3^137 - 1)')"]).
449 Definition machine_wordsize_spec : anon_argT
450 := ("machine_wordsize",
451 Arg.Custom (parse_string_and parse_machine_wordsize) "an integer",
452 ["The machine bitwidth (e.g., 32 or 64)"]).
453 Definition src_n_spec : anon_argT
454 := ("src_n",
455 Arg.Custom (parse_string_and parse_src_n) "ℕ",
456 ["The number of limbs in the input"]).
457 Definition src_limbwidth_spec : anon_argT
458 := ("src_limbwidth",
459 Arg.Custom (parse_string_and parse_limbwidth) "ℕ",
460 ["The limbwidth of the input field element"]).
461 Definition dst_limbwidth_spec : anon_argT
462 := ("dst_limbwidth",
463 Arg.Custom (parse_string_and parse_limbwidth) "ℕ",
464 ["The limbwidth of the field element to be returned"]).
465 Definition use_bitwidth_in_spec : named_argT
466 := ([Arg.long_key "use-bitwidth-in"],
467 Arg.Unit,
468 ["Instead of using an upper bound of s-1 on the input, use the maximum number that can be properly represented with the given base"]).
469 Definition use_bitwidth_out_spec : named_argT
470 := ([Arg.long_key "use-bitwidth-out"],
471 Arg.Unit,
472 ["Instead of using an upper bound of s-1 on the output, use the maximum number that can be properly represented with the given base"]).
473 Definition default_inbounds_multiplier := 1.
474 Definition inbounds_multiplier_spec : named_argT
475 := ([Arg.long_key "inbounds-multiplier"],
476 Arg.String,
477 ["The (improper) fraction by which the bounds of each input limb are scaled (default: " ++ show default_inbounds_multiplier ++ ")"]).
478 Definition default_outbounds_multiplier := 1.
479 Definition outbounds_multiplier_spec : named_argT
480 := ([Arg.long_key "outbounds-multiplier"],
481 Arg.String,
482 ["The (improper) fraction by which the bounds of each output limb are scaled (default: " ++ show default_outbounds_multiplier ++ ")"]).
483 Definition inbounds_spec : named_argT
484 := ([Arg.long_key "inbounds"],
485 Arg.String,
486 ["A semicolon-separated, square-bracked-surrounded list of integer expressions describing the input bounds. Incompatible with --use-bitwidth-in."]).
487 Definition outbounds_spec : named_argT
488 := ([Arg.long_key "outbounds"],
489 Arg.String,
490 ["A semicolon-separated, square-bracked-surrounded list of integer expressions describing the output bounds. Incompatible with --use-bitwidth-out."]).
491 Definition function_to_synthesize_spec (valid_names : string) : anon_argT
492 := ("function_to_synthesize",
493 Arg.String,
494 ["A space-separated list of functions that should be synthesized. If no functions are given, all functions are synthesized."
495 ; "Valid options are " ++ valid_names ++ "."]).
496 Definition hint_file_spec : named_argT
497 := ([Arg.long_key "hints-file"],
498 Arg.String,
499 ["An assembly file to be read for hinting the synthesis process. Use - for stdin. To check multiple files against the same synthesized operation(s), pass this argument multiple times."]).
500 Definition output_file_spec : named_argT
501 := ([Arg.long_key "output"; Arg.short_key "o"],
502 Arg.String,
503 ["The name of the file to write output to. Use - for stdout. (default: -)"]).
504 Definition asm_output_spec : named_argT
505 := ([Arg.long_key "output-asm"],
506 Arg.String,
507 ["The name of the file to write generated assembly to. Use - for stdout. (default: -)"]).
508 Definition asm_label_exact_match_spec : named_argT
509 := ([Arg.long_key "asm-label-exact-match"],
510 Arg.Unit,
511 ["Assembly labels must exactly match the requested function names, rather than permitting arbitrary prefixes and suffixes. Only relevant when --hints-file is specified."]).
512 Definition asm_reg_spec : named_argT
513 := ([Arg.long_key "asm-reg"],
514 Arg.Custom (parse_string_and parse_list_REG) "REG",
515 ["A comma-separated list of registers to use for calling conventions. Only relevant when --hints-file is specified."
516 ; "Defaults to the System V AMD64 ABI of " ++ String.concat "," (List.map show default_assembly_calling_registers) ++ ". Note that registers are first used for outputs and then inputs."]).
517 Definition asm_callee_saved_registers_spec : named_argT
518 := ([Arg.long_key "asm-callee-saved-registers"],
519 Arg.Custom (parse_string_and parse_callee_saved_registers) "REG",
520 ["Either '" ++ show System_V_AMD64 ++ "' (indicating " ++ String.concat "," (List.map show system_v_amd64_assembly_callee_saved_registers) ++ "), '" ++ show Microsoft_x64 ++ "' (indicating " ++ String.concat "," (List.map show microsoft_x64_assembly_callee_saved_registers) ++ "), or a comma-separated list of registers which are callee-saved / non-volatile. Only relevant when --hints-file is specified."
521 ; "Defaults to " ++ show default_assembly_callee_saved_registers ++ "."]).
522 Definition asm_node_reveal_depth_spec : named_argT
523 := ([Arg.long_key "asm-node-reveal-depth"],
524 Arg.Custom (parse_string_and parse_nat) "ℕ",
525 ["The depth of nodes to reveal in the assembly equivalence checker. Only relevant when --hints-file is specified. In most situations, this should not have to be changed. Defaults to " ++ show default_node_reveal_depth ++ "."]).
526 Definition asm_stack_size_spec : named_argT
527 := ([Arg.long_key "asm-stack-size"],
528 Arg.Custom (parse_string_and parse_N) "ℕ",
529 ["The number of bytes of stack. Only relevant when --hints-file is specified. Defaults to the conventional size of the red zone (" ++ show (system_v_amd64_assembly_stack_red_zone:N) ++ " for --asm-callee-saved-registers " ++ show System_V_AMD64 ++ ", or " ++ show (microsoft_x64_assembly_stack_red_zone:N) ++ " for --asm-callee-saved-registers " ++ show Microsoft_x64 ++ ", or " ++ show (@assembly_stack_red_zone (explicit_registers []):N) ++ " for an explicit list of registers given to --asm-callee-saved-registers) plus the maximum statically knowable increase to `rsp` (via `push`, `pop`, `sub`, `add`, and `lea` instructions) the code."]).
530 Definition no_error_on_unused_asm_functions_spec : named_argT
531 := ([Arg.long_key "no-error-on-unused-asm-functions"],
532 Arg.Unit,
533 ["Don't error if there are global labels in the hints-file which are not requested functions."]).
534 Definition asm_input_first_spec : named_argT
535 := ([Arg.long_key "asm-input-first"],
536 Arg.Unit,
537 ["By default, output pointers are assumed to come before input arguments in the C code the assembly hints are based on. This flag reverses that convention."]).
538 Definition asm_reg_rtl_spec : named_argT
539 := ([Arg.long_key "asm-reg-rtl"],
540 Arg.Unit,
541 ["By default, registers are assumed to be assigned to function arguments from left to right in the hints file. This flag reverses that convention to be right-to-left. Note that this flag interacts with --asm-input-first, which determines whether the output pointers are to the left or to the right of the input arguments."]).
542 Definition asm_error_on_unique_names_mismatch_spec : named_argT
543 := ([Arg.long_key "asm-error-on-unique-name-mismatch"],
544 Arg.Unit,
545 ["By default, when there's only one assembly function in a --hints-file and only one function requested to be synthesized, the name of the assembly function is ignored. Passing this flag disables this behavior, raising an error if the names mismatch regardless of whether there are multiple functions or just one."]).
546 Definition asm_rewriting_pipeline_spec : named_argT
547 := ([Arg.long_key "asm-rewriting-pipeline"],
548 Arg.Custom (parse_string_and parse_list_rewrite_pass) "REWRITE_PASS",
549 ["Specifies the order and multiplicity of rewriting passes used in the assembly equivalence checker. Default: " ++ default_asm_rewriting_pipeline]).
550 Definition asm_rewriting_passes_spec : named_argT
551 := ([Arg.long_key "asm-rewriting-passes"],
552 Arg.String,
553 ["A comma-separated list of rewriting passes to enable. Prefix with - to disable a pass. This list only impacts passes listed in --asm-rewriting-pipeline. Default : " ++ (if default_asm_rewriting_passes =? "" then "(none)" else default_asm_rewriting_passes)]%string ++ describe_flag_options "rewriting pass" "Enable all rewriting passes" special_asm_rewriting_pass_flags known_asm_rewriting_pass_flags_with_spec)%list.
554 Definition asm_debug_symex_asm_first_spec : named_argT
555 := ([Arg.long_key "debug-asm-symex-first"],
556 Arg.Unit,
557 ["Debug option: If true, the assembly equivalence checker will symex the assembly first, even though this may be more inefficient. This may be useful for having a more concise description of errors in assembly symbolic execution."]).
558 Definition doc_text_before_function_name_spec : named_argT
559 := ([Arg.long_key "doc-text-before-function-name"],
560 Arg.String,
561 ["Documentation Option: A custom string to insert before the function name in each docstring. Default: " ++ default_text_before_function_name]).
562 Definition doc_text_before_type_name_spec : named_argT
563 := ([Arg.long_key "doc-text-before-type-name"],
564 Arg.String,
565 ["Documentation Option: A custom string to insert before the type name in each docstring. Default: " ++ default_text_before_type_name]).
566 Definition doc_newline_before_package_declaration_spec : named_argT
567 := ([Arg.long_key "doc-newline-before-package-declaration"],
568 Arg.Unit,
569 ["Documentation Option: For languages that emit package declarations, add an extra newline before the declaration. Primarily useful to detach the header from the Go package."]).
570 Definition doc_newline_in_typedef_bounds_spec : named_argT
571 := ([Arg.long_key "doc-newline-in-typedef-bounds"],
572 Arg.Unit,
573 ["Documentation Option: When emitting the documentation comment for typedefs, insert a newline between ""Bounds:"" and the bounds rather than a space."]).
574 Definition doc_prepend_header_raw_spec : named_argT
575 := ([Arg.long_key "doc-prepend-header-raw"],
576 Arg.String,
577 ["Documentation Option: Prepend a line before the documentation header at the top of the file. This argument can be passed multiple times to insert multiple lines."]).
578 Definition doc_prepend_header_spec : named_argT
579 := ([Arg.long_key "doc-prepend-header"],
580 Arg.String,
581 ["Documentation Option: Prepend a line at the beginning of the documentation header at the top of the file. This argument can be passed multiple times to insert multiple lines. Lines will be automatically commented."]).
582 Definition debug_spec : named_argT
583 := ([Arg.long_key "debug"; Arg.short_key "d"],
584 Arg.String,
585 (["A comma-separated list of debug options to turn on. Use - to disable an option. Default debug options: " ++ (if default_debug =? "" then "(none)" else default_debug)]%string ++ describe_flag_options "debug" "Turn all debugging on" special_debug_options known_debug_options_with_spec))%list.
586
587 Definition collapse_list_default {A} (default : A) (ls : list A)
588 := List.hd default (List.rev ls).
589
590 Definition join_errors {A B} (x : A + list string) (y : B + list string) : (A * B) + list string
591 := match x, y with
592 | inr errs1, inr errs2 => inr (errs1 ++ errs2)%list
593 | inr err, inl _ | inl _, inr err => inr err
594 | inl x, inl y => inl (x, y)
595 end.
596
597 (** We define a class for holding the various options we might pass to [Synthesize] *)
598 (** We split up the ones we can directly parse and the ones we have to process *)
599 Class ParsedSynthesizeOptions :=
600 {
601 (** Is the code static / private *)
602 #[global] static :: static_opt
603 (** Is the internal code static / private *)
604 ; #[global] internal_static :: internal_static_opt
605 (** Is the code inlined *)
606 ; #[global] inline :: inline_opt
607 (** Is the internal code inlined *)
608 ; #[global] inline_internal :: inline_internal_opt
609 (** Should we only use signed integers *)
610 ; #[global] only_signed :: only_signed_opt
611 (** Should we emit expressions requiring cmov *)
612 ; #[global] no_select :: no_select_opt
613 (** Should we emit primitive operations *)
614 ; #[global] emit_primitives :: emit_primitives_opt
615 (** Various output options including: *)
616 (** Should we skip emitting typedefs for field elements *)
617 (** Should we relax the bounds on the return carry type of sbb/adc operations? *)
618 ; #[global] output_options :: output_options_opt
619 (** Should we use the alternate implementation of cmovznz *)
620 ; #[global] use_mul_for_cmovznz :: use_mul_for_cmovznz_opt
621 (** Various abstract interpretation options *)
622 (** Should we avoid uint1 at the output of shiftr *)
623 ; #[global] abstract_interpretation_options :: AbstractInterpretation.Options
624 (** Should we split apart oversized operations? *)
625 ; #[global] should_split_mul :: should_split_mul_opt
626 (** Should we split apart multi-return operations? *)
627 ; #[global] should_split_multiret :: should_split_multiret_opt
628 (** Should we remove use of value_barrier? *)
629 ; #[global] unfold_value_barrier :: unfold_value_barrier_opt
630 (** Should we widen the carry to the full bitwidth? *)
631 ; #[global] widen_carry :: widen_carry_opt
632 (** Should we widen the byte type to the full bitwidth? *)
633 ; #[global] widen_bytes :: widen_bytes_opt
634 (** Should we ignore function-name mismatch errors when there's only one assembly function and only one actual function requested? *)
635 ; #[global] ignore_unique_asm_names :: ignore_unique_asm_names_opt
636 (** What method should we use for rewriting? *)
637 ; #[global] low_level_rewriter_method :: low_level_rewriter_method_opt
638 := default_low_level_rewriter_method
639 (** What's the bitwidth? *)
640 ; #[global] machine_wordsize :: machine_wordsize_opt
641 (** What's the package name *)
642 ; #[global] internal_package_name :: package_name_opt
643 (** What's the class name *)
644 ; #[global] internal_class_name :: class_name_opt
645 (** What's are the naming conventions to use? *)
646 ; #[global] language_naming_conventions :: language_naming_conventions_opt
647 (** Documentation options *)
648 ; #[global] documentation_options :: documentation_options_opt
649 (** assembly equivalence checker options *)
650 ; #[global] equivalence_checker_options :: equivalence_checker_options_opt
651 (** error if there are un-requested assembly functions *)
652 ; #[global] error_on_unused_assembly_functions :: error_on_unused_assembly_functions_opt
653 (** don't prepend fiat to prefix *)
654 ; no_prefix_fiat : bool
655 (** Extra lines before the documentation header *)
656 ; before_header_lines : list string
657 (** Extra lines at the beginning of the documentation header *)
658 ; extra_early_header_lines : list string
659 (** Debug rewriting *)
660 ; #[global] debug_rewriting :: debug_rewriting_opt
661 (** Print debug info on success too *)
662 ; debug_on_success : bool
663 }.
664 Class SynthesizeOptions :=
665 {
666 #[global] parsed_synthesize_options :: ParsedSynthesizeOptions
667 (** Lines of assembly hints *)
668 ; #[global] assembly_hints_lines :: assembly_hints_lines_opt
669 }.
670
671 (** We define a class for holding the various options about file interaction that we don't pass to [Synthesize] *)
672 Class IODriverOptions :=
673 {
674 (** The name of the file holding assembly hints *)
675 hint_file_names : list string
676 (** The name of the file to output to *)
677 ; output_file_name : string
678 (** The name of the file to output assembly to *)
679 ; asm_output_file_name : string
680 }.
681
682 Fixpoint with_read_concat_asm_files_cps
683 {A}
684 (with_read_file : string (* fname *) -> (list string -> A) -> A)
685 (hint_file_names : list string)
686 : (assembly_hints_lines_opt -> A) -> A
687 := match hint_file_names with
688 | nil => fun k => k []
689 | fname :: fnames
690 => fun k
691 => with_read_file
692 fname
693 (fun lines
694 => with_read_concat_asm_files_cps
695 with_read_file
696 fnames
697 (fun rest => k ((fname, lines) :: rest)))
698 end.
699
700 Definition common_optional_options {supported_languages : supported_languagesT}
701 := [lang_spec
702 ; package_name_spec
703 ; class_name_spec
704 ; package_case_spec
705 ; class_case_spec
706 ; private_function_case_spec
707 ; public_function_case_spec
708 ; private_type_case_spec
709 ; public_type_case_spec
710 ; no_prefix_fiat_spec
711 ; static_spec
712 ; internal_static_spec
713 ; inline_spec
714 ; inline_internal_spec
715 ; no_wide_int_spec
716 ; widen_carry_spec
717 ; widen_bytes_spec
718 ; no_select_spec
719 ; split_multiret_spec
720 ; value_barrier_spec
721 ; no_primitives_spec
722 ; no_field_element_typedefs_spec
723 ; emit_all_casts_spec
724 ; relax_primitive_carry_to_bitwidth_spec
725 ; cmovznz_by_mul_spec
726 ; shiftr_avoid_uint1_spec
727 ; only_signed_spec
728 ; hint_file_spec
729 ; output_file_spec
730 ; asm_output_spec
731 ; asm_label_exact_match_spec
732 ; asm_reg_spec
733 ; asm_callee_saved_registers_spec
734 ; asm_stack_size_spec
735 ; no_error_on_unused_asm_functions_spec
736 ; asm_input_first_spec
737 ; asm_reg_rtl_spec
738 ; asm_error_on_unique_names_mismatch_spec
739 ; asm_rewriting_pipeline_spec
740 ; asm_rewriting_passes_spec
741 ; asm_node_reveal_depth_spec
742 ; asm_debug_symex_asm_first_spec
743 ; doc_text_before_function_name_spec
744 ; doc_text_before_type_name_spec
745 ; doc_newline_before_package_declaration_spec
746 ; doc_newline_in_typedef_bounds_spec
747 ; doc_prepend_header_raw_spec
748 ; doc_prepend_header_spec
749 ; debug_spec
750 ].
751
752 (* We follow the standard convention of giving precedence to the final option passed *)
753 Definition choose_one_of_many {A} (args : list A) : option A
754 := List.nth_error (List.rev args) 0.
755
756 Definition parse_common_optional_options
757 {supported_languages : supported_languagesT}
758 {machine_wordsizev : machine_wordsize_opt}
759 (data : Arg.keyed_spec_list_data common_optional_options)
760 : (IODriverOptions * ParsedSynthesizeOptions * ToString.OutputLanguageAPI) + list string
761 := let '(langv
762 , package_namev
763 , class_namev
764 , package_casev
765 , class_casev
766 , private_function_casev
767 , public_function_casev
768 , private_type_casev
769 , public_type_casev
770 , no_prefix_fiatv
771 , staticv
772 , internal_staticv
773 , inlinev
774 , inline_internalv
775 , no_wide_intv
776 , widen_carryv
777 , widen_bytesv
778 , no_selectv
779 , split_multiretv
780 , value_barrierv
781 , no_primitivesv
782 , no_field_element_typedefsv
783 , emit_all_castsv
784 , relax_primitive_carry_to_bitwidthv
785 , cmovznz_by_mulv
786 , shiftr_avoid_uint1v
787 , only_signedv
788 , hint_file_namesv
789 , output_file_namev
790 , asm_output_file_namev
791 , asm_label_exact_matchv
792 , asm_regv
793 , asm_callee_saved_registersv
794 , asm_stack_sizev
795 , no_error_on_unused_asm_functionsv
796 , asm_input_firstv
797 , asm_reg_rtlv
798 , asm_error_on_unique_names_mismatchv
799 , asm_rewriting_pipelinev
800 , asm_rewriting_passesv
801 , asm_node_reveal_depthv
802 , asm_debug_symex_asm_firstv
803 , doc_text_before_function_namev
804 , doc_text_before_type_namev
805 , doc_newline_before_package_declarationv
806 , doc_newline_in_typedef_boundsv
807 , doc_prepend_header_rawv
808 , doc_prepend_headerv
809 , debugv
810 ) := data in
811 let flag_to_bool x := bool_of_full_flag_status x false in
812 let to_bool ls := (0 <? List.length ls)%nat in
813 let to_string_list ls := List.map (@snd _ _) ls in
814 let to_N_list ls := List.map (@snd _ _) (List.map (@snd _ _) ls) in
815 let to_nat_list ls := List.map (@snd _ _) (List.map (@snd _ _) ls) in
816 let to_Z_flat_list ls := List.flat_map (@snd _ _) (List.map (@snd _ _) ls) in
817 let to_reg_list ls := match List.map (@snd _ _) (List.map (@snd _ _) ls) with
818 | nil => None
819 | ls => Some (List.concat ls)
820 end in
821 let to_rewriting_pipeline_list ls
822 := match List.map (@snd _ _) (List.map (@snd _ _) ls) with
823 | nil => default_rewrite_pass_order
824 | ls => List.concat ls
825 end in
826 let to_assembly_callee_saved_registers_opt ls := choose_one_of_many (List.map (fun '(_, (_, v)) => v) ls) in
827 let to_assembly_callee_saved_registers_default ls default := Option.value (to_assembly_callee_saved_registers_opt ls) default in
828 let to_N_opt ls := choose_one_of_many (to_N_list ls) in
829 let to_N_default ls default := Option.value (to_N_opt ls) default in
830 let to_nat_opt ls := choose_one_of_many (to_nat_list ls) in
831 let to_nat_default ls default := Option.value (to_nat_opt ls) default in
832 let to_string_opt ls := choose_one_of_many (to_string_list ls) in
833 let to_string_default ls default := Option.value (to_string_opt ls) default in
834 let to_capitalization_data_opt ls := choose_one_of_many (List.map (fun '(_, (_, v)) => v) ls) in
835 let to_capitalization_convention_opt ls
836 := option_map (fun d => {| capitalization_convention_data := d ; only_lower_first_letters := true |})
837 (to_capitalization_data_opt ls) in
838 let '(_, unknown_debug_options, (debug_on_successv, debug_rewritingv)) := parse_flag_opts special_debug_options known_debug_options (default_debug :: List.map snd debugv) in
839 let default_asm_rewriting_pass_status := true (* default status of non-explicit passes; it doesn't actually matter because we're going to control the default with default_asm_rewriting_passes *) in
840 let '(unknown_asm_rewriting_passes, asm_rewriting_pass_filterv) := parse_flag_opts_to_bool_filter default_asm_rewriting_pass_status special_asm_rewriting_pass_flags known_asm_rewriting_pass_flags (default_asm_rewriting_passes :: List.map snd asm_rewriting_passesv) in
841 let res
842 := ({|
843 hint_file_names := to_string_list hint_file_namesv
844 ; output_file_name := to_string_default output_file_namev "-"
845 ; asm_output_file_name := to_string_default asm_output_file_namev "-"
846 |},
847 {| static := to_bool staticv
848 ; internal_static := to_bool internal_staticv
849 ; inline := to_bool inlinev
850 ; inline_internal := to_bool inline_internalv
851 ; internal_class_name := to_string_opt class_namev
852 ; internal_package_name := to_string_opt package_namev
853 ; language_naming_conventions
854 := {| public_function_naming_convention := to_capitalization_convention_opt public_function_casev
855 ; private_function_naming_convention := to_capitalization_convention_opt private_function_casev
856 ; public_type_naming_convention := to_capitalization_convention_opt public_type_casev
857 ; private_type_naming_convention := to_capitalization_convention_opt private_type_casev
858 ; variable_naming_convention := None
859 ; package_naming_convention := to_capitalization_convention_opt package_casev
860 ; class_naming_convention := to_capitalization_convention_opt class_casev
861 |}
862 ; no_prefix_fiat := to_bool no_prefix_fiatv
863 ; widen_carry := to_bool widen_carryv
864 ; widen_bytes := to_bool widen_bytesv
865 ; no_select := to_bool no_selectv
866 ; only_signed := to_bool only_signedv
867 ; should_split_mul := to_bool no_wide_intv
868 ; should_split_multiret := to_bool split_multiretv
869 ; unfold_value_barrier := negb (to_bool value_barrierv)
870 ; use_mul_for_cmovznz := to_bool cmovznz_by_mulv
871 ; abstract_interpretation_options :=
872 {| AbstractInterpretation.shiftr_avoid_uint1 := to_bool shiftr_avoid_uint1v
873 |}
874 ; emit_primitives := negb (to_bool no_primitivesv)
875 ; output_options :=
876 {| skip_typedefs_ := to_bool no_field_element_typedefsv
877 ; relax_adc_sbb_return_carry_to_bitwidth_ := to_Z_flat_list relax_primitive_carry_to_bitwidthv
878 ; language_specific_cast_adjustment_ := negb (to_bool emit_all_castsv)
879 |}
880 ; equivalence_checker_options :=
881 {| assembly_conventions_ :=
882 {| assembly_calling_registers_ := to_reg_list asm_regv
883 ; assembly_callee_saved_registers_ := to_assembly_callee_saved_registers_default asm_callee_saved_registersv default_assembly_callee_saved_registers
884 ; assembly_stack_size_ := to_N_opt asm_stack_sizev
885 ; assembly_output_first_ := negb (to_bool asm_input_firstv)
886 ; assembly_argument_registers_left_to_right_ := negb (to_bool asm_reg_rtlv)
887 ; assembly_labels_fuzzy_suffixes_ := negb (to_bool asm_label_exact_matchv)
888 ; assembly_labels_fuzzy_prefixes_ := negb (to_bool asm_label_exact_matchv)
889 |}
890 ; symbolic_options_ :=
891 {| asm_rewriting_pipeline := to_rewriting_pipeline_list asm_rewriting_pipelinev
892 ; asm_rewriting_pass_filter := fun p => asm_rewriting_pass_filterv (show_rewrite_pass p)
893 ; asm_debug_symex_asm_first := to_bool asm_debug_symex_asm_firstv
894 ; asm_node_reveal_depth := to_nat_default asm_node_reveal_depthv default_node_reveal_depth
895 |}
896 |}
897 ; ignore_unique_asm_names := negb (to_bool asm_error_on_unique_names_mismatchv)
898 ; error_on_unused_assembly_functions := negb (to_bool no_error_on_unused_asm_functionsv)
899 ; documentation_options
900 := {| text_before_function_name_opt := to_string_opt doc_text_before_function_namev
901 ; text_before_type_name_opt := to_string_opt doc_text_before_type_namev
902 ; newline_before_package_declaration := to_bool doc_newline_before_package_declarationv
903 ; newline_in_typedef_bounds := to_bool doc_newline_in_typedef_boundsv
904 |}
905 ; before_header_lines := to_string_list doc_prepend_header_rawv
906 ; extra_early_header_lines := to_string_list doc_prepend_headerv
907 ; debug_rewriting := flag_to_bool debug_rewritingv
908 ; debug_on_success := flag_to_bool debug_on_successv
909 |},
910 snd (List.hd lang_default langv)) in
911 let unknown_errs descr sing_suffix plural_suffix arg unknown_opts
912 := match unknown_opts with
913 | [] => []
914 | _ :: _ => ["Unrecognized " ++ descr ++ (if (1 <? List.length unknown_opts)%nat then plural_suffix else sing_suffix) ++ " (from " ++ arg ++ "): " ++ String.concat ", " (List.map fst unknown_opts)]
915 end in
916 let lang_errs
917 := match langv with
918 | [] | [_] => []
919 | _ :: _ :: _ => ["Only one language specification with --lang is allowed; multiple languages were requested: " ++ String.concat ", " (List.map (@fst _ _) langv)]
920 end in
921 match lang_errs
922 ++ unknown_errs "debug flag" "" "s" "--debug" unknown_debug_options
923 ++ unknown_errs "assembly rewriting pass" "" "es" "--asm-rewriting-passes" unknown_asm_rewriting_passes
924 with
925 | [] => inl res
926 | errs => inr errs
927 end%list.
928
929 (** We define a class for the various operations that are specific to a pipeline *)
930 Class PipelineAPI :=
931 {
932 (** The spec of curve-specific command line arguments *)
933 spec : Arg.arg_spec;
934 (** Type of arguments parsed from the command line *)
935 ParsedArgsT : Type;
936 (** Type of (unparsed) arguments remembered from the command line *)
937 StringArgsT : Type;
938 ArgsT := (StringArgsT * ParsedArgsT)%type;
939
940 (** Takes in args parsed via the spec and post-parses
941 curve-specific arguments, returning either [inl value] or
942 [inr errors] *)
943 parse_args : forall {synthesize_opts : SynthesizeOptions}, Arg.arg_spec_results spec -> ArgsT + list string;
944
945 (** Renders a header at the top displaying the command line
946 arguments. Will be wrapped in a comment block *)
947 show_lines_args : ArgsT -> list string;
948
949 (** The Synthesize function from the pipeline *)
950 (** N.B. [comment_header] will be passed in *without* wrapping
951 it in a comment block first *)
952 Synthesize : forall
953 {output_language_api : ToString.OutputLanguageAPI}
954 {synthesize_opts : SynthesizeOptions}
955 (args : ParsedArgsT) (comment_header : list string) (function_name_prefix : string),
956 list (synthesis_output_kind * string * Pipeline.M (list string))
957 }.
958
959 (** API for performing IO *)
960 Class IODriverAPI {A} :=
961 {
962 error : list string -> A
963 ; ret : unit -> A
964 ; with_read_stdin : (list string -> A) -> A
965 ; write_stdout_then : list string (* lines, to be joined with "" *) -> (unit -> A) -> A
966 ; write_stderr_then : list string (* lines, to be joined with "" *) -> (unit -> A) -> A
967 ; with_read_file : string (* fname *) -> (list string -> A) -> A
968 ; write_file_then : string (* fname *) -> list string (* lines, to be joined with "" *) -> (unit -> A) -> A
969 }.
970 Global Arguments IODriverAPI : clear implicits.
971
972 Module Export Notations.
973 Bind Scope list_scope with supported_languagesT.
974 End Notations.
975
976 Module Parameterized.
977 Section __.
978 Context {api : PipelineAPI}.
979
980 Definition PipelineLines
981 {output_language_api : ToString.OutputLanguageAPI}
982 {synthesize_opts : SynthesizeOptions}
983 (invocation : string)
984 (curve_description : string)
985 (str_machine_wordsize : string)
986 (args : ArgsT)
987 : list (synthesis_output_kind * string * Pipeline.M (list string))
988 := let prefix := ((if no_prefix_fiat then "" else "fiat_")
989 ++ (if (curve_description =? "") then "" else (curve_description ++ "_")))%string in
990 let header :=
991 ((extra_early_header_lines
992 ++ ["Autogenerated: " ++ invocation
993 ; match (curve_description =? ""), internal_package_name, internal_class_name with
994 | false, _, _
995 | _, (None | Some ""), (None | Some "")
996 => "curve description: " ++ curve_description
997 | _, Some pkg, _
998 => "curve description (via package name): " ++ pkg
999 | _, _, Some cls
1000 => "curve description (via class name): " ++ cls
1001 end
1002 ; "machine_wordsize = " ++ show (machine_wordsize:Z) ++ " (from """ ++ str_machine_wordsize ++ """)"]%string)
1003 ++ show_lines_args args)%list in
1004 Synthesize (snd args) header prefix.
1005
1006 Local Notation debug_to_lines v
1007 := (List.flat_map (fun f => String.NewLine :: f tt) (Debug.get_debug_info v)).
1008
1009 Definition ProcessedLines
1010 {output_language_api : ToString.OutputLanguageAPI}
1011 {synthesize_opts : SynthesizeOptions}
1012 (invocation : string)
1013 (curve_description : string)
1014 (str_machine_wordsize : string)
1015 (args : ArgsT)
1016 : Pipeline.DebugM ((* normal *) list string * (* asm *) list string) + list string
1017 := match CollectErrors (PipelineLines invocation curve_description str_machine_wordsize args) with
1018 | inl ls
1019 => let '(ls_normal, ls_asm) := Debug.eval_result ls in
1020 let before_header := List.map (fun s => s ++ String.NewLine) before_header_lines in
1021 let postprocess_lines ls
1022 := String.strip_trailing_newlines
1023 (List.flat_map (fun s => ((List.map (fun s => s ++ String.NewLine) (List.map String.strip_trailing_spaces s))%string)
1024 ++ [String.NewLine])
1025 ls)%list in
1026 inl
1027 (Debug.copy_debug_info ls;;
1028 Debug.ret (before_header ++ postprocess_lines ls_normal, postprocess_lines ls_asm)%list)
1029 | inr nil => inr nil
1030 | inr (l :: ls)
1031 => let flatten_debug_info (ls : DebugM (list string))
1032 := let dbg := debug_to_lines ls in
1033 let ls := Debug.eval_result ls in
1034 (dbg ++ ls)%list in
1035 inr ((flatten_debug_info l)
1036 ++ (List.flat_map
1037 (fun e => String.NewLine :: flatten_debug_info e)
1038 ls))%list
1039 end%debugM.
1040
1041 Definition Pipeline
1042 {A}
1043 {output_language_api : ToString.OutputLanguageAPI}
1044 {synthesize_opts : SynthesizeOptions}
1045 (invocation : string)
1046 (curve_description : string)
1047 (str_machine_wordsize : string)
1048 (args : ArgsT)
1049 (success : list string (* stderr *) * list string (* normal lines *) * list string (* asm lines *) -> A)
1050 (error : list string -> A)
1051 : A
1052 := match ProcessedLines invocation curve_description str_machine_wordsize args with
1053 | inl s => let stderr := if debug_on_success
1054 then debug_to_lines s
1055 else [] in
1056 let '(normal_ls, asm_ls) := Debug.eval_result s in
1057 success (stderr, normal_ls, asm_ls)
1058 | inr s => error s
1059 end.
1060
1061 Definition PipelineMain
1062 {prog_name_count : Arg.prog_name_countT}
1063 {supported_languages : supported_languagesT}
1064 {A}
1065 {io_driver : IODriverAPI A}
1066 (argv : list string)
1067 : A
1068 := let with_read_file fname
1069 := if (fname =? "-")%string then with_read_stdin else with_read_file fname in
1070 let write_file_then fname
1071 := if (fname =? "-")%string then write_stdout_then else write_file_then fname in
1072 let invocation := String.concat " " (List.map quote argv) in
1073 let full_spec
1074 := {| Arg.named_args := common_optional_options ++ spec.(Arg.named_args)
1075 ; Arg.anon_args := curve_description_spec :: machine_wordsize_spec :: spec.(Arg.anon_args)
1076 ; Arg.anon_opt_args := spec.(Arg.anon_opt_args)
1077 ; Arg.anon_opt_repeated_arg := spec.(Arg.anon_opt_repeated_arg) |} in
1078 match Arg.parse_argv argv full_spec with
1079 | ErrorT.Success (named_data, anon_data, anon_opt_data, anon_opt_repeated_data)
1080 => let '(common_named_data, named_data) := Arg.split_type_of_list' (ls1:=List.map _ common_optional_options) named_data in
1081 let '((curve_description, (str_machine_wordsize, machine_wordsize)), anon_data) := Arg.split_type_of_list' (ls1:=[_;_]) anon_data in
1082 let machine_wordsize : machine_wordsize_opt := machine_wordsize in
1083 match parse_common_optional_options common_named_data with
1084 | inl (io_driver_opts, opts, output_language_api)
1085 => with_read_concat_asm_files_cps
1086 with_read_file
1087 hint_file_names
1088 (fun assembly_hints_linesv
1089 => let success :=
1090 fun '(stderr, normal_lines, asm_lines)
1091 => write_stderr_then
1092 stderr
1093 (fun 'tt
1094 => write_file_then
1095 output_file_name
1096 normal_lines
1097 (fun 'tt
1098 => match asm_lines, assembly_hints_linesv with
1099 | nil, [] => ret tt
1100 | _, _ => write_file_then
1101 asm_output_file_name
1102 asm_lines
1103 ret
1104 end)) in
1105 let opts := {|
1106 parsed_synthesize_options := opts
1107 ; assembly_hints_lines := assembly_hints_linesv
1108 |} in
1109 match parse_args (named_data, anon_data, anon_opt_data, anon_opt_repeated_data) with
1110 | inl args
1111 => Pipeline invocation curve_description str_machine_wordsize args success error
1112 | inr errs => error errs
1113 end)
1114 | inr errs => error errs
1115 end
1116 | ErrorT.Error err
1117 => let display := Arg.show_list_parse_error full_spec err in
1118 if Arg.is_real_error err
1119 then error display
1120 else (* just a requested help/usage message *)
1121 write_stdout_then
1122 (List.map (fun s => s ++ String.NewLine)%string display)
1123 ret
1124 end.
1125 End __.
1126 End Parameterized.
1127
1128 Module UnsaturatedSolinas.
1129 Local Instance api : PipelineAPI
1130 := {
1131 spec :=
1132 {| Arg.named_args := [tight_bounds_multiplier_spec]
1133 ; Arg.anon_args := [n_spec; sc_spec]
1134 ; Arg.anon_opt_args := []
1135 ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec UnsaturatedSolinas.valid_names) |};
1136
1137 parse_args opts args
1138 := let '(tight_bounds_multiplier, ((str_n, n), (str_sc, (s, c))), tt, requests) := args in
1139 let show_requests := match requests with nil => "(all)" | _ => String.concat ", " requests end in
1140 let '(str_tight_bounds_multiplier, tight_bounds_multiplier) := collapse_list_default ("", tight_bounds_multiplier_default) (List.map (@snd _ _) tight_bounds_multiplier) in
1141 let tight_bounds_multiplier : tight_upperbound_fraction_opt := tight_bounds_multiplier in
1142 match get_num_limbs s c machine_wordsize n, n with
1143 | None, NumLimbs n => inr ["Internal error: get_num_limbs (on (" ++ PowersOfTwo.show_Z s ++ ", " ++ show_c c ++ ", " ++ show (machine_wordsize:Z) ++ ", " ++ show n ++ ")) returned None even though the argument was NumLimbs"]
1144 | None, Auto idx => inr ["Invalid index " ++ show idx ++ " when guessing the number of limbs for s-c = " ++ PowersOfTwo.show_Z s ++ " - " ++ show_c c ++ "; valid indices must index into the list " ++ show (get_possible_limbs s c machine_wordsize) ++ "."]
1145 | Some n, _
1146 => inl
1147 ((str_n, str_sc, str_tight_bounds_multiplier, show_requests),
1148 (n, s, c, tight_bounds_multiplier, requests))
1149 end;
1150
1151 show_lines_args :=
1152 fun '((str_n, str_sc, str_tight_bounds_multiplier, show_requests),
1153 (n, s, c, tight_bounds_multiplier, requests))
1154 => ["requested operations: " ++ show_requests;
1155 "n = " ++ show n ++ " (from """ ++ str_n ++ """)";
1156 "s-c = " ++ PowersOfTwo.show_Z s ++ " - " ++ show_c c ++ " (from """ ++ str_sc ++ """)";
1157 "tight_bounds_multiplier = " ++ show (tight_bounds_multiplier:Q) ++ " (from """ ++ str_tight_bounds_multiplier ++ """)"]%string;
1158
1159 Synthesize
1160 := fun _ opts '(n, s, c, tight_bounds_multiplier, requests) comment_header prefix
1161 => UnsaturatedSolinas.Synthesize n s c machine_wordsize comment_header prefix requests;
1162 }.
1163
1164 Definition PipelineMain
1165 {prog_name_count : Arg.prog_name_countT}
1166 {supported_languages : supported_languagesT}
1167 {A}
1168 {io_driver : IODriverAPI A}
1169 (argv : list string)
1170 : A
1171 := Parameterized.PipelineMain argv.
1172 End UnsaturatedSolinas.
1173
1174 Module WordByWordMontgomery.
1175 Local Instance api : PipelineAPI
1176 := {
1177 spec :=
1178 {| Arg.named_args := []
1179 ; Arg.anon_args := [m_spec]
1180 ; Arg.anon_opt_args := []
1181 ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec WordByWordMontgomery.valid_names) |};
1182
1183 parse_args opts args
1184 := let '(tt, (str_m, m), tt, requests) := args in
1185 let show_requests := match requests with nil => "(all)" | _ => String.concat ", " requests end in
1186 inl ((str_m, show_requests),
1187 (m, requests));
1188
1189 show_lines_args :=
1190 fun '((str_m, show_requests),
1191 (m, requests))
1192 => ["requested operations: " ++ show_requests;
1193 "m = " ++ Hex.show_Z m ++ " (from """ ++ str_m ++ """)";
1194 " ";
1195 "NOTE: In addition to the bounds specified above each function, all";
1196 " functions synthesized for this Montgomery arithmetic require the";
1197 " input to be strictly less than the prime modulus (m), and also ";
1198 " require the input to be in the unique saturated representation. ";
1199 " All functions also ensure that these two properties are true of ";
1200 " return values. "];
1201
1202 Synthesize
1203 := fun _ opts '(m, requests) comment_header prefix
1204 => WordByWordMontgomery.Synthesize m machine_wordsize comment_header prefix requests
1205 }.
1206
1207 Definition PipelineMain
1208 {prog_name_count : Arg.prog_name_countT}
1209 {supported_languages : supported_languagesT}
1210 {A}
1211 {io_driver : IODriverAPI A}
1212 (argv : list string)
1213 : A
1214 := Parameterized.PipelineMain argv.
1215 End WordByWordMontgomery.
1216
1217 Module SaturatedSolinas.
1218 Local Instance api : PipelineAPI
1219 := {
1220 spec :=
1221 {| Arg.named_args := []
1222 ; Arg.anon_args := [sc_spec]
1223 ; Arg.anon_opt_args := []
1224 ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec SaturatedSolinas.valid_names) |};
1225
1226 parse_args opts args
1227 := let '(tt, (str_sc, (s, c)), tt, requests) := args in
1228 let show_requests := match requests with nil => "(all)" | _ => String.concat ", " requests end in
1229 inl ((str_sc, show_requests),
1230 (s, c, requests));
1231
1232 show_lines_args :=
1233 fun '((str_sc, show_requests),
1234 (s, c, requests))
1235 => ["requested operations: " ++ show_requests;
1236 "s-c = " ++ PowersOfTwo.show_Z s ++ " - " ++ show_c c ++ " (from """ ++ str_sc ++ """)"];
1237
1238 Synthesize
1239 := fun _ opts '(s, c, requests) comment_header prefix
1240 => SaturatedSolinas.Synthesize s c machine_wordsize comment_header prefix requests
1241 }.
1242
1243 Definition PipelineMain
1244 {prog_name_count : Arg.prog_name_countT}
1245 {supported_languages : supported_languagesT}
1246 {A}
1247 {io_driver : IODriverAPI A}
1248 (argv : list string)
1249 : A
1250 := Parameterized.PipelineMain argv.
1251 End SaturatedSolinas.
1252
1253 Module DettmanMultiplication.
1254 Local Instance api : PipelineAPI
1255 := {
1256 spec :=
1257 {| Arg.named_args := [inbounds_multiplier_spec]
1258 ; Arg.anon_args := [n_nat_spec; last_limb_width_spec; last_reduction_spec; sc_spec]
1259 ; Arg.anon_opt_args := []
1260 ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec DettmanMultiplication.valid_names) |};
1261
1262 parse_args opts args
1263 := let '(inbounds_multiplier, ((str_n, n), (str_last_limb_width, last_limb_width), (str_last_reduction, last_reduction), (str_sc, (s, c))), tt, requests) := args in
1264 let show_requests := match requests with nil => "(all)" | _ => String.concat ", " requests end in
1265 let to_string_opt ls := choose_one_of_many (List.map (@snd _ _) ls) in
1266 let inbounds_multiplier := to_string_opt inbounds_multiplier in
1267 let '(str_inbounds_multiplier, inbounds_multiplier) := parse_dirbounds_multiplier "in" (inl inbounds_multiplier) in
1268 match inbounds_multiplier with
1269 | inr errs => inr errs
1270 | inl inbounds_multiplier
1271 => inl ((str_n, str_last_limb_width, str_last_reduction, str_sc, str_inbounds_multiplier, show_requests),
1272 (n, last_limb_width, last_reduction, s, c, inbounds_multiplier, requests))
1273 end;
1274
1275 show_lines_args :=
1276 fun '((str_n, str_last_limb_width, str_last_reduction, str_sc, str_inbounds_multiplier, show_requests),
1277 (n, last_limb_width, last_reduction, s, c, inbounds_multiplier, requests))
1278 => ["requested operations: " ++ show_requests;
1279 "n = " ++ show n ++ " (from """ ++ str_n ++ """)";
1280 "last_limb_width = " ++ show last_limb_width ++ " (from """ ++ str_last_limb_width ++ """)";
1281 "last_reduction = " ++ show last_reduction ++ " (from """ ++ str_last_reduction ++ """)";
1282 "s-c = " ++ PowersOfTwo.show_Z s ++ " - " ++ show_c c ++ " (from """ ++ str_sc ++ """)";
1283 "inbounds_multiplier: " ++ show inbounds_multiplier ++ " (from """ ++ str_inbounds_multiplier ++ """)"];
1284
1285 Synthesize
1286 := fun _ opts '(n, last_limb_width, last_reduction, s, c, inbounds_multiplier, requests) comment_header prefix
1287 => DettmanMultiplication.Synthesize machine_wordsize s c n last_limb_width last_reduction inbounds_multiplier comment_header prefix requests
1288 }.
1289
1290 Definition PipelineMain
1291 {prog_name_count : Arg.prog_name_countT}
1292 {supported_languages : supported_languagesT}
1293 {A}
1294 {io_driver : IODriverAPI A}
1295 (argv : list string)
1296 : A
1297 := Parameterized.PipelineMain argv.
1298 End DettmanMultiplication.
1299
1300 Module SolinasReduction.
1301 Local Instance api : PipelineAPI
1302 := {
1303 spec :=
1304 {| Arg.named_args := []
1305 ; Arg.anon_args := [sc_spec]
1306 ; Arg.anon_opt_args := []
1307 ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec SolinasReduction.valid_names) |};
1308
1309 parse_args opts args
1310 := let '(tt, (str_sc, (s, c)), tt, requests) := args in
1311 let show_requests := match requests with nil => "(all)" | _ => String.concat ", " requests end in
1312 inl ((str_sc, show_requests),
1313 (s, c, requests));
1314
1315 show_lines_args :=
1316 fun '((str_sc, show_requests),
1317 (s, c, requests))
1318 => ["requested operations: " ++ show_requests;
1319 "s-c = " ++ PowersOfTwo.show_Z s ++ " - " ++ show_c c ++ " (from """ ++ str_sc ++ """)"];
1320
1321 Synthesize
1322 := fun _ opts '(s, c, requests) comment_header prefix
1323 => SolinasReduction.Synthesize s c machine_wordsize comment_header prefix requests
1324 }.
1325
1326 Definition PipelineMain
1327 {prog_name_count : Arg.prog_name_countT}
1328 {supported_languages : supported_languagesT}
1329 {A}
1330 {io_driver : IODriverAPI A}
1331 (argv : list string)
1332 : A
1333 := Parameterized.PipelineMain argv.
1334 End SolinasReduction.
1335
1336 Module BaseConversion.
1337 Local Instance api : PipelineAPI
1338 := {
1339 spec :=
1340 {| Arg.named_args := [inbounds_multiplier_spec; outbounds_multiplier_spec; inbounds_spec; outbounds_spec; use_bitwidth_in_spec; use_bitwidth_out_spec]
1341 ; Arg.anon_args := [src_n_spec; sc_spec; src_limbwidth_spec; dst_limbwidth_spec]
1342 ; Arg.anon_opt_args := []
1343 ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec BaseConversion.valid_names) |};
1344
1345 parse_args opts args
1346 := let '((inbounds_multiplier, outbounds_multiplier, inbounds, outbounds, use_bitwidth_in, use_bitwidth_out),
1347 ((str_src_n, src_n), (str_sc, (s, c)), (str_src_limbwidth, src_limbwidth), (str_dst_limbwidth, dst_limbwidth)),
1348 tt,
1349 requests) := args in
1350 let show_requests := match requests with nil => "(all)" | _ => String.concat ", " requests end in
1351 let to_bool ls := (0 <? List.length ls)%nat in
1352 let to_string_opt ls := choose_one_of_many (List.map (@snd _ _) ls) in
1353 let inbounds_multiplier := to_string_opt inbounds_multiplier in
1354 let outbounds_multiplier := to_string_opt outbounds_multiplier in
1355 let inbounds := to_string_opt inbounds in
1356 let outbounds := to_string_opt outbounds in
1357 let use_bitwidth_in := to_bool use_bitwidth_in in
1358 let use_bitwidth_out := to_bool use_bitwidth_out in
1359 let '(str_inbounds_multiplier, inbounds_multiplier) := parse_dirbounds_multiplier "in" (inl inbounds_multiplier) in
1360 let '(str_outbounds_multiplier, outbounds_multiplier) := parse_dirbounds_multiplier "out" (inl outbounds_multiplier) in
1361 let '(str_inbounds, inbounds) := parse_dirbounds "in" (inl inbounds) use_bitwidth_in in
1362 let '(str_outbounds, outbounds) := parse_dirbounds "out" (inl outbounds) use_bitwidth_out in
1363 match join_errors
1364 (join_errors
1365 inbounds_multiplier
1366 outbounds_multiplier)
1367 (join_errors
1368 inbounds
1369 outbounds)
1370 with
1371 | inr errs => inr errs
1372 | inl ((inbounds_multiplier, outbounds_multiplier), (inbounds, outbounds))
1373 => inl ((str_src_n, str_sc, str_src_limbwidth, str_dst_limbwidth, str_inbounds_multiplier, str_outbounds_multiplier, use_bitwidth_in, use_bitwidth_out, str_inbounds, str_outbounds, show_requests),
1374 (src_n, s, c, src_limbwidth, dst_limbwidth, inbounds_multiplier, outbounds_multiplier, inbounds, outbounds, requests))
1375 end;
1376
1377 show_lines_args :=
1378 fun '((str_src_n, str_sc, str_src_limbwidth, str_dst_limbwidth, str_inbounds_multiplier, str_outbounds_multiplier, use_bitwidth_in, use_bitwidth_out, str_inbounds, str_outbounds, show_requests),
1379 (src_n, s, c, src_limbwidth, dst_limbwidth, inbounds_multiplier, outbounds_multiplier, inbounds, outbounds, requests))
1380 => ["requested operations: " ++ show_requests;
1381 "src_n = " ++ show src_n ++ " (from """ ++ str_src_n ++ """)";
1382 "s-c = " ++ PowersOfTwo.show_Z s ++ " - " ++ show_c c ++ " (from """ ++ str_sc ++ """)";
1383 "src_limbwidth = " ++ show src_limbwidth ++ " (from """ ++ str_src_limbwidth ++ """)";
1384 "dst_limbwidth = " ++ show dst_limbwidth ++ " (from """ ++ str_dst_limbwidth ++ """)";
1385 "inbounds_multiplier = " ++ show inbounds_multiplier ++ " (from """ ++ str_inbounds_multiplier ++ """)";
1386 "outbounds_multiplier = " ++ show outbounds_multiplier ++ " (from """ ++ str_outbounds_multiplier ++ """)";
1387 "inbounds = " ++ show inbounds ++ " (from """ ++ str_inbounds ++ """ and use_bithwidth_in = " ++ show use_bitwidth_in ++ ")";
1388 "outbounds = " ++ show outbounds ++ " (from """ ++ str_outbounds ++ """ and use_bithwidth_out = " ++ show use_bitwidth_out ++ ")"];
1389
1390 Synthesize
1391 := fun _ opts '(src_n, s, c, src_limbwidth, dst_limbwidth, inbounds_multiplier, outbounds_multiplier, inbounds, outbounds, requests) comment_header prefix
1392 => BaseConversion.Synthesize s c src_n src_limbwidth dst_limbwidth machine_wordsize inbounds_multiplier outbounds_multiplier inbounds outbounds comment_header prefix requests
1393 }.
1394
1395 Definition PipelineMain
1396 {prog_name_count : Arg.prog_name_countT}
1397 {supported_languages : supported_languagesT}
1398 {A}
1399 {io_driver : IODriverAPI A}
1400 (argv : list string)
1401 : A
1402 := Parameterized.PipelineMain argv.
1403 End BaseConversion.
1404
1405 (** The combined binary that delegates *)
1406 Module FiatCrypto.
1407 Definition PipelineMain
1408 {supported_languages : supported_languagesT}
1409 {A}
1410 {io_driver : IODriverAPI A}
1411 (argv : list string)
1412 : A
1413 := let spec
1414 := {| Arg.named_args := []
1415 ; Arg.anon_args := [synthesis_kind_spec]
1416 ; Arg.anon_opt_args := []
1417 ; Arg.anon_opt_repeated_arg := None |} in
1418 match Arg.parse_argv (List.firstn 2 argv) spec with
1419 | ErrorT.Success (tt as _named_data, anon_data, tt as _anon_opt_data, tt as _anon_opt_repeated_data)
1420 => let synthesis_kind := anon_data in
1421 let prog_name_count : Arg.prog_name_countT := 2%nat in
1422 match synthesis_kind with
1423 | word_by_word_montgomery
1424 => WordByWordMontgomery.PipelineMain (prog_name_count:=prog_name_count) argv
1425 | unsaturated_solinas
1426 => UnsaturatedSolinas.PipelineMain (prog_name_count:=prog_name_count) argv
1427 | saturated_solinas
1428 => SaturatedSolinas.PipelineMain (prog_name_count:=prog_name_count) argv
1429 | dettman_multiplication
1430 => DettmanMultiplication.PipelineMain (prog_name_count:=prog_name_count) argv
1431 | solinas_reduction
1432 => SolinasReduction.PipelineMain (prog_name_count:=prog_name_count) argv
1433 | base_conversion
1434 => BaseConversion.PipelineMain (prog_name_count:=prog_name_count) argv
1435 end
1436 | ErrorT.Error err
1437 => let display := Arg.show_list_parse_error spec err in
1438 if Arg.is_real_error err
1439 then error display
1440 else (* just a requested help/usage message *)
1441 write_stdout_then
1442 (List.map (fun s => s ++ String.NewLine)%string display)
1443 ret
1444 end.
1445 End FiatCrypto.
1446 End ForExtraction.