Debian Codegraph @

src/Stringification/Language.v

raw
1 From Coq Require Import ZArith.
2 From Coq Require Import MSetPositive.
3 From Coq Require Import FMapPositive.
4 From Coq Require Import Lia.
5 From Coq Require Import String.
6 From Coq Require Import Ascii.
7 From Coq Require Import Bool.
8 From Coq Require Import Orders.
9 From Coq Require Import OrdersEx.
10 From Coq Require Import MSetInterface.
11 From Coq Require Import MSetPositive.
12 From Coq Require Import HexString.
13 Require Import Crypto.Util.ListUtil Coq.Lists.List.
14 Require Import Crypto.Util.Sigma.
15 Require Import Crypto.Util.Prod.
16 Require Crypto.Util.Strings.String.
17 Require Import Crypto.Util.Structures.Equalities.Sum.
18 Require Import Crypto.Util.Structures.Equalities.Iso.
19 Require Import Crypto.Util.Structures.Orders.Sum.
20 Require Import Crypto.Util.Structures.Orders.Iso.
21 Require Import Crypto.Util.MSets.MSetIso.
22 Require Import Crypto.Util.MSets.MSetSum.
23 Require Import Crypto.Util.Strings.Decimal.
24 Require Import Crypto.Util.Strings.Show.
25 Require Import Crypto.Util.Strings.NamingConventions.
26 Require Import Crypto.Util.ZRange.
27 Require Import Crypto.Util.ZRange.Operations.
28 Require Import Crypto.Util.ZRange.Show.
29 Require Import Crypto.Util.Option.
30 Require Import Crypto.Util.OptionList.
31 Require Import Crypto.Util.MSets.MSetPositive.Show.
32 Require Import Crypto.Util.MSets.Show.
33 Require Import Crypto.Util.Level.
34 Require Import Rewriter.Language.Language.
35 Require Import Crypto.Language.API.
36 Require Import Crypto.AbstractInterpretation.ZRange.
37 Require Import Crypto.Util.Sum.
38 Require Import Crypto.Util.Bool.Equality.
39 Require Import Crypto.Util.Notations.
40 Import Coq.Lists.List ListNotations. Local Open Scope zrange_scope. Local Open Scope Z_scope.
41
42 Module Compilers.
43 Local Set Boolean Equality Schemes.
44 Local Set Decidable Equality Schemes.
45 Export Language.Language.Compilers.
46 Export Language.API.Compilers.
47 Export AbstractInterpretation.ZRange.Compilers.
48 Import invert_expr.
49 Import Compilers.API.
50
51 Local Notation tZ := (base.type.type_base base.type.Z).
52
53 Module Export Options.
54 Module PHOAS.
55 (** Print casts in PHOAS? *)
56 Class with_casts := with_castsv : bool.
57 #[global] Typeclasses Opaque with_casts.
58
59 (** Print all casts in PHOAS? *)
60 Class with_all_casts := with_all_castsv : bool.
61 #[global] Typeclasses Opaque with_all_casts.
62
63 Definition default_with_casts : with_casts := true.
64 Definition default_with_all_casts : with_all_casts := false.
65 End PHOAS.
66 #[global] Typeclasses Opaque PHOAS.with_casts PHOAS.with_all_casts.
67 #[global] Existing Instances PHOAS.default_with_casts PHOAS.default_with_all_casts.
68
69 (** How to relax zranges *)
70 Class relax_zrange_opt := relax_zrange : zrange -> zrange.
71 #[global]
72 Typeclasses Opaque relax_zrange_opt.
73 (** What's the package name? *)
74 Class package_name_opt := internal_package_name : option string.
75 #[global]
76 Typeclasses Opaque package_name_opt.
77 (** What's the class name? *)
78 Class class_name_opt := internal_class_name : option string.
79 #[global]
80 Typeclasses Opaque class_name_opt.
81 (** Should we emit typedefs or not? *)
82 Class skip_typedefs_opt := skip_typedefs : bool.
83 #[global]
84 Typeclasses Opaque skip_typedefs_opt.
85 (** Which adc/sbb bitwidth-split-carries should be relaxed to bitwidth *)
86 Class relax_adc_sbb_return_carry_to_bitwidth_opt := relax_adc_sbb_return_carry_to_bitwidth : list Z.
87 #[global]
88 Typeclasses Opaque relax_adc_sbb_return_carry_to_bitwidth_opt.
89 (** Do language-specific cast adjustment *)
90 Class language_specific_cast_adjustment_opt := language_specific_cast_adjustment : bool.
91 #[global]
92 Typeclasses Opaque language_specific_cast_adjustment_opt.
93 Class language_naming_conventions_opt :=
94 { public_function_naming_convention : option capitalization_convention
95 ; private_function_naming_convention : option capitalization_convention
96 ; public_type_naming_convention : option capitalization_convention
97 ; private_type_naming_convention : option capitalization_convention
98 ; variable_naming_convention : option capitalization_convention
99 ; package_naming_convention : option capitalization_convention
100 ; class_naming_convention : option capitalization_convention
101 }.
102 Definition default_language_naming_conventions : language_naming_conventions_opt
103 := {| public_function_naming_convention := None
104 ; private_function_naming_convention := None
105 ; public_type_naming_convention := None
106 ; private_type_naming_convention := None
107 ; variable_naming_convention := None
108 ; package_naming_convention := None
109 ; class_naming_convention := None
110 |}.
111
112 Definition convert_to_naming_convention (convention : option capitalization_convention) (s : string) : string
113 := match convention with
114 | Some convention => convert_case snake_case convention s
115 | None => s
116 end.
117 Definition package_name {pkg_name : package_name_opt} {language_naming_conventions : language_naming_conventions_opt} (prefix : string) : string
118 := match pkg_name with
119 | Some name => name
120 | None => convert_to_naming_convention
121 package_naming_convention
122 (if String.endswith "_" prefix then substring 0 (String.length prefix - 1) prefix else prefix)
123 end.
124 Definition class_name {cls_name : class_name_opt} {language_naming_conventions : language_naming_conventions_opt} (prefix : string) : string
125 := match cls_name with
126 | Some name => name
127 | None => convert_to_naming_convention
128 class_naming_convention
129 (if String.endswith "_" prefix then substring 0 (String.length prefix - 1) prefix else prefix)
130 end.
131
132 Definition default_text_before_function_name : string := "The function ".
133 Definition default_text_before_type_name : string := "The type ".
134
135 Class documentation_options_opt :=
136 {
137 (** Text to insert before the function name *)
138 text_before_function_name_opt : option string;
139 text_before_function_name : string := Option.value text_before_function_name_opt default_text_before_function_name;
140 (** Text to insert before the type name *)
141 text_before_type_name_opt : option string;
142 text_before_type_name : string := Option.value text_before_type_name_opt default_text_before_type_name;
143 (** Stick an extra newline before the package declaration *)
144 newline_before_package_declaration : bool;
145 (** Stick a newline between the "Bounds:" and the bounds of typedefs *)
146 newline_in_typedef_bounds : bool;
147 }.
148
149 Definition default_documentation_options : documentation_options_opt
150 := {| text_before_function_name_opt := None
151 ; text_before_type_name_opt := None
152 ; newline_before_package_declaration := false
153 ; newline_in_typedef_bounds := false
154 |}.
155
156 Class output_options_opt :=
157 { #[global] skip_typedefs_ :: skip_typedefs_opt
158 ; #[global] relax_adc_sbb_return_carry_to_bitwidth_ :: relax_adc_sbb_return_carry_to_bitwidth_opt
159 ; #[global] language_specific_cast_adjustment_ :: language_specific_cast_adjustment_opt
160 }.
161
162 Definition default_output_options : output_options_opt
163 := {| skip_typedefs_ := true
164 ; relax_adc_sbb_return_carry_to_bitwidth_ := []
165 ; language_specific_cast_adjustment_ := true
166 |}.
167 End Options.
168
169 Module ToString.
170 Local Open Scope string_scope.
171 Local Open Scope Z_scope.
172
173 Module Import ZRange.
174 Module Export type.
175 Module Export base.
176 Fixpoint show_lvl_interp {t} : ShowLevel (ZRange.type.base.interp t)
177 := match t return ShowLevel (ZRange.type.base.interp t) with
178 | base.type.unit => @show_lvl unit _
179 | base.type.type_base base.type.Z => @show_lvl zrange _
180 | base.type.type_base base.type.positive => @show_lvl positive _
181 | base.type.type_base base.type.bool => @show_lvl bool _
182 | base.type.type_base base.type.nat => @show_lvl nat _
183 | base.type.type_base base.type.zrange => @show_lvl zrange _
184 | base.type.type_base base.type.string => @show_lvl string _
185 | base.type.prod A B => @show_lvl (ZRange.type.base.interp A * ZRange.type.base.interp B) _
186 | base.type.list A => @show_lvl (list (ZRange.type.base.interp A)) _
187 | base.type.option A => @show_lvl (option (ZRange.type.base.interp A)) _
188 end%string.
189 Global Existing Instance show_lvl_interp.
190 Global Instance show_interp {t} : Show (ZRange.type.base.interp t) := show_lvl_interp.
191 Module Export option.
192 Fixpoint show_lvl_interp {t} : ShowLevel (ZRange.type.base.option.interp t)
193 := match t return ShowLevel (ZRange.type.base.option.interp t) with
194 | base.type.unit => @show_lvl unit _
195 | base.type.type_base _ as t => @show_lvl (option (ZRange.type.base.interp t)) _
196 | base.type.prod A B => @show_lvl (ZRange.type.base.option.interp A * ZRange.type.base.option.interp B) _
197 | base.type.list A => @show_lvl (option (list (ZRange.type.base.option.interp A))) _
198 | base.type.option A => @show_lvl (option (option (ZRange.type.base.option.interp A))) _
199 end.
200 Global Existing Instance show_lvl_interp.
201 Global Instance show_interp {t} : Show (ZRange.type.base.option.interp t) := show_lvl_interp.
202 End option.
203 End base.
204
205 Module option.
206 Global Instance show_lvl_interp {t} : ShowLevel (ZRange.type.option.interp t)
207 := match t return ShowLevel (ZRange.type.option.interp t) with
208 | type.base t => @show_lvl (ZRange.type.base.option.interp t) _
209 | type.arrow s d => fun _ _ => "λ"
210 end.
211 Global Instance show_interp {t} : Show (ZRange.type.option.interp t) := show_lvl_interp.
212 End option.
213 End type.
214 End ZRange.
215
216 Module PHOAS.
217 Module type.
218 Module base.
219 Global Instance show_base : Show base.type.base
220 := fun t => match t with
221 | base.type.Z => "ℤ"
222 | base.type.positive => "ℤ⁺"
223 | base.type.bool => "𝔹"
224 | base.type.nat => "ℕ"
225 | base.type.zrange => "zrange"
226 | base.type.string => "string"
227 end.
228 Global Instance show_lvl_base : ShowLevel base.type.base := show_base.
229 Global Instance show_lvl_type : ShowLevel base.type
230 := fix show_lvl_type (t : base.type) : Level.Level -> string
231 := match t with
232 | base.type.unit => fun _ => "()"
233 | base.type.type_base t => show_lvl t
234 | base.type.prod A B => show_lvl_binop
235 mul_assoc mul_lvl
236 (show_lvl_type A) " * " (show_lvl_type B)
237 | base.type.list A => fun _ => "[" ++ show_lvl_type A term_lvl ++ "]"
238 | base.type.option A
239 => show_lvl_app
240 (fun 'tt => "option") (show_lvl_type A)
241 end.
242 Global Instance show_type : Show base.type := show_lvl_type.
243 Global Instance show_lvl_base_interp {t} : ShowLevel (base.base_interp t)
244 := match t with
245 | base.type.Z => @show_lvl Z _
246 | base.type.bool => @show_lvl bool _
247 | base.type.positive => @show_lvl positive _
248 | base.type.nat => @show_lvl nat _
249 | base.type.zrange => @show_lvl zrange _
250 | base.type.string => @show_lvl string _
251 end.
252 Global Instance show_base_interp {t} : Show (base.base_interp t) := show_lvl_base_interp.
253 Fixpoint show_lvl_interp {t} : ShowLevel (base.interp t)
254 := match t with
255 | base.type.unit => @show_lvl unit _
256 | base.type.type_base t => @show_lvl (base.base_interp t) _
257 | base.type.prod A B => @show_lvl (base.interp A * base.interp B) _
258 | base.type.list A => @show_lvl (list (base.interp A)) _
259 | base.type.option A => @show_lvl (option (base.interp A)) _
260 end.
261 Global Existing Instance show_lvl_interp.
262 Global Instance show_interp {t} : Show (base.interp t) := show_lvl_interp.
263 Global Instance show_lvl : ShowLevel base.type := show_lvl_type.
264 Global Instance show : Show base.type := show_type.
265 End base.
266 Fixpoint show_lvl_for_each_lhs_of_arrow {base_type} {f : type.type base_type -> Type} {show_f : forall t, ShowLevel (f t)} {t : type.type base_type} {struct t} : ShowLevel (type.for_each_lhs_of_arrow f t)
267 := match t return ShowLevel (type.for_each_lhs_of_arrow f t) with
268 | type.base t => @show_lvl unit _
269 | type.arrow s d
270 => Option.value
271 (match d with
272 | type.base _ => Some (fun '(x, _) => @show_lvl (f s) _ x)
273 | type.arrow _ _ => None
274 end)
275 (@show_lvl (f s * type.for_each_lhs_of_arrow f d) _)
276 end.
277 Global Existing Instance show_lvl_for_each_lhs_of_arrow.
278 Definition show_for_each_lhs_of_arrow {base_type} {f : type.type base_type -> Type} {show_f : forall t, Show (f t)} {t : type.type base_type} : Show (type.for_each_lhs_of_arrow f t)
279 := let _ := fun t => @ShowLevel_of_Show (f t) in
280 show_lvl_for_each_lhs_of_arrow.
281
282 Global Instance show_lvl_type : forall {base_type} {S : ShowLevel base_type}, ShowLevel (type.type base_type)
283 := fix show_lvl_type {base_type} {S : ShowLevel base_type} (t : type.type base_type) : Level.Level -> string
284 := match t with
285 | type.base t => show_lvl t
286 | type.arrow s d
287 => show_lvl_binop impl_assoc impl_lvl (show_lvl_type s) " → " (show_lvl_type d)
288 end.
289 Global Instance show_lvl {base_type} {S : ShowLevel base_type} : ShowLevel (type.type base_type) := show_lvl_type.
290 Global Instance show_type {base_type} {S : Show base_type} : Show (type.type base_type)
291 := let _ := @ShowLevel_of_Show base_type in
292 show_lvl_type.
293 Global Instance show {base_type} {S : Show base_type} : Show (type.type base_type) := show_type.
294 End type.
295
296 Definition bitwidth_to_string (v : Z) : string
297 := (if v =? 2^Z.log2 v then "2^" ++ Decimal.Z.to_string (Z.log2 v) else HexString.of_Z v).
298 Definition show_range_or_ctype : Show zrange
299 := fun v
300 => if (v.(lower) =? 0) && (v.(upper) =? 2^(Z.log2 (v.(upper) + 1)) - 1)
301 then ("uint" ++ Decimal.Z.to_string (Z.log2 (v.(upper) + 1)) ++ "_t")%string
302 else let lg2 := 1 + Z.log2 (-v.(lower)) in
303 if (v.(lower) =? -2^(lg2-1)) && (v.(upper) =? 2^(lg2-1)-1)
304 then ("int" ++ Decimal.Z.to_string lg2 ++ "_t")%string
305 else show v.
306 Definition show_lvl_compact_Z : ShowLevel Z
307 := fun v
308 => let is_neg := v <? 0 in
309 (if is_neg then show_lvl_unop opp_lvl "-" else show_lvl)
310 (let v := Z.abs v in
311 if v <=? 2^8
312 then Decimal.show_lvl_Z v
313 else if v =? 2^(Z.log2 v)
314 then show_lvl_binop pow_assoc pow_lvl 2 "^" (Decimal.show_lvl_Z (Z.log2 v))
315 else if v =? 2^(Z.log2_up v) - 1
316 then show_lvl_binop
317 sub_assoc sub_lvl
318 (show_lvl_binop pow_assoc pow_lvl 2 "^" (Decimal.show_lvl_Z (Z.log2_up v))) "-" 1
319 else Hex.show_lvl_Z v).
320 Definition show_compact_Z : Show Z := show_lvl_compact_Z.
321
322 Fixpoint make_castb {t} : ZRange.type.base.option.interp t -> option string
323 := match t return ZRange.type.base.option.interp t -> option string with
324 | base.type.type_base base.type.Z => option_map show_range_or_ctype
325 | base.type.prod A B
326 => fun '(r1, r2)
327 => match @make_castb A r1, @make_castb B r2 with
328 | Some c1, Some c2 => Some (c1 ++ ", " ++ c2)
329 | None, Some c => Some ("??, " ++ c)
330 | Some c, None => Some (c ++ ", ??")
331 | None, None => None
332 end
333 | base.type.list A
334 => fun r
335 => match r with
336 | None => None
337 | Some nil => Some "void[0]"
338 | Some ((r :: rs) as ls)
339 => let n := show (List.length ls) in
340 let c1 := @make_castb A r in
341 let all_same := List.forallb (ZRange.type.base.option.interp_beq r) rs in
342 Some
343 (match all_same, c1 with
344 | true, Some c1 => c1
345 | _, _ => "??"
346 end
347 ++ "[" ++ n ++ "]")
348 end
349 | base.type.unit
350 | base.type.type_base _
351 | base.type.option _
352 => fun _ => None
353 end.
354
355 Definition make_cast {t} : ZRange.type.option.interp t -> option string
356 := match t with
357 | type.base t => @make_castb t
358 | type.arrow _ _ => fun _ => None
359 end.
360
361 Definition maybe_wrap_cast (with_cast : bool) {t} (xr : (Level.Level -> string) * ZRange.type.option.interp t) (lvl : Level.Level) : string
362 := match with_cast, make_cast (snd xr) with
363 | true, Some c => "(" ++ c ++ ")" ++ fst xr (Level.next app_lvl)
364 | _, _ => fst xr lvl
365 end.
366
367 Section without_prod.
368 Local Remove Hints show_lvl_prod : typeclass_instances.
369 Definition show_application (with_casts : bool) {t : type} (f : Level.Level -> string) (args : type.for_each_lhs_of_arrow (fun t => (Level.Level -> string) * ZRange.type.option.interp t)%type t)
370 : Level.Level -> string
371 := match t return type.for_each_lhs_of_arrow (fun t => (Level.Level -> string) * ZRange.type.option.interp t)%type t -> Level.Level -> string with
372 | type.base _ => fun 'tt lvl => f lvl
373 | type.arrow s d
374 => fun xs lvl
375 => let _ : forall t, Show ((Level.Level -> string) * ZRange.type.option.interp t)%type
376 := (fun t x => maybe_wrap_cast with_casts x app_lvl) in
377 let _ : forall t, ShowLevel ((Level.Level -> string) * ZRange.type.option.interp t)%type
378 := fun t => ShowLevel_of_Show in
379 maybe_wrap_parens (Level.ltb lvl (Level.prev app_lvl)) (f (Level.prev app_lvl) ++ show_lvl xs (-∞))
380 end args.
381 End without_prod.
382
383 Module ident.
384 Global Instance show_lvl_ident {t} : ShowLevel (ident.ident t)
385 := fun idc
386 => match idc with
387 | ident.Literal base.type.Z v => show_lvl_compact_Z v
388 | ident.Literal _t v => show_lvl v
389 | ident.value_barrier => neg_wrap_parens "value_barrier"
390 | ident.comment _ => neg_wrap_parens "comment"
391 | ident.comment_no_keep _ => neg_wrap_parens "comment_no_keep"
392 | ident.tt => fun _ => "()"
393 | ident.Nat_succ => neg_wrap_parens "Nat.succ"
394 | ident.Nat_pred => neg_wrap_parens "Nat.pred"
395 | ident.Nat_max => neg_wrap_parens "Nat.max"
396 | ident.Nat_mul => neg_wrap_parens "Nat.mul"
397 | ident.Nat_add => neg_wrap_parens "Nat.add"
398 | ident.Nat_sub => neg_wrap_parens "Nat.sub"
399 | ident.Nat_eqb => neg_wrap_parens "Nat.eqb"
400 | ident.Pos_mul => neg_wrap_parens "Pos.mul"
401 | ident.Pos_add => neg_wrap_parens "Pos.add"
402 | ident.nil t => neg_wrap_parens "[]"
403 | ident.cons t => fun _ => "(::)"
404 | ident.pair A B => fun _ => "(,)"
405 | ident.fst A B => neg_wrap_parens "fst"
406 | ident.snd A B => neg_wrap_parens "snd"
407 | ident.prod_rect A B T => neg_wrap_parens "prod_rect"
408 | ident.bool_rect T => neg_wrap_parens "bool_rect"
409 | ident.bool_rect_nodep T => neg_wrap_parens "bool_rect_nodep"
410 | ident.nat_rect P => neg_wrap_parens "nat_rect"
411 | ident.eager_nat_rect P => neg_wrap_parens "eager_nat_rect"
412 | ident.nat_rect_arrow P Q => neg_wrap_parens "nat_rect(→)"
413 | ident.eager_nat_rect_arrow P Q => neg_wrap_parens "eager_nat_rect(→)"
414 | @ident.nat_rect_fbb_b A B C => neg_wrap_parens "nat_rect_fbb_b"
415 | @ident.nat_rect_fbb_b_b A B C D => neg_wrap_parens "nat_rect_fbb_b_b"
416 | @ident.list_rect_fbb_b T A B C => neg_wrap_parens "list_rect_fbb_b"
417 | @ident.list_rect_fbb_b_b T A B C D => neg_wrap_parens "list_rect_fbb_b_b"
418 | @ident.list_rect_fbb_b_b_b T A B C D E => neg_wrap_parens "list_rect_fbb_b_b"
419 | @ident.list_rect_fbb_b_b_b_b T A B C D E F => neg_wrap_parens "list_rect_fbb_b_b"
420 | @ident.list_rect_fbb_b_b_b_b_b T A B C D E F G => neg_wrap_parens "list_rect_fbb_b_b"
421 | ident.list_rect A P => neg_wrap_parens "list_rect"
422 | ident.eager_list_rect A P => neg_wrap_parens "eager_list_rect"
423 | ident.list_rect_arrow A P Q => neg_wrap_parens "list_rect(→)"
424 | ident.eager_list_rect_arrow A P Q => neg_wrap_parens "eager_list_rect(→)"
425 | ident.list_case A P => neg_wrap_parens "list_case"
426 | ident.List_length T => neg_wrap_parens "length"
427 | ident.List_seq => neg_wrap_parens "seq"
428 | ident.List_repeat A => neg_wrap_parens "repeat"
429 | ident.List_firstn A => neg_wrap_parens "firstn"
430 | ident.List_skipn A => neg_wrap_parens "skipn"
431 | ident.List_combine A B => neg_wrap_parens "combine"
432 | ident.List_map A B => neg_wrap_parens "map"
433 | ident.List_app A => fun _ => "(++)"
434 | ident.List_rev A => neg_wrap_parens "rev"
435 | ident.List_flat_map A B => neg_wrap_parens "flat_map"
436 | ident.List_partition A => neg_wrap_parens "partition"
437 | ident.List_filter A => neg_wrap_parens "filter"
438 | ident.List_fold_right A B => neg_wrap_parens "fold_right"
439 | ident.List_update_nth T => neg_wrap_parens "update_nth"
440 | ident.List_nth_default T => neg_wrap_parens "nth"
441 | ident.eager_List_nth_default T => neg_wrap_parens "eager_nth"
442 | ident.Some _ => neg_wrap_parens "Some"
443 | ident.None _ => neg_wrap_parens "None"
444 | ident.option_rect _ _ => neg_wrap_parens "option_rect"
445 | ident.Z_add => fun _ => "(+)"
446 | ident.Z_mul => fun _ => "( * )"
447 | ident.Z_pow => fun _ => "(^)"
448 | ident.Z_sub => fun _ => "(-)"
449 | ident.Z_opp => fun _ => "-"
450 | ident.Z_div => fun _ => "(/)"
451 | ident.Z_modulo => fun _ => "(mod)"
452 | ident.Z_eqb => fun _ => "(=)"
453 | ident.Z_leb => fun _ => "(≤)"
454 | ident.Z_ltb => fun _ => "(<)"
455 | ident.Z_geb => fun _ => "(≥)"
456 | ident.Z_gtb => fun _ => "(>)"
457 | ident.Z_min => neg_wrap_parens "min"
458 | ident.Z_max => neg_wrap_parens "max"
459 | ident.Z_abs => neg_wrap_parens "abs"
460 | ident.Z_log2 => neg_wrap_parens "log₂"
461 | ident.Z_log2_up => neg_wrap_parens "⌈log₂⌉"
462 | ident.Z_of_nat => fun _ => "(ℕ→ℤ)"
463 | ident.Z_to_nat => fun _ => "(ℤ→ℕ)"
464 | ident.Z_pos => fun _ => "(ℤ⁺→ℤ)"
465 | ident.Z_to_pos => fun _ => "(ℤ→ℤ⁺)"
466 | ident.Z_shiftr => fun _ => "(>>)"
467 | ident.Z_shiftl => fun _ => "(<<)"
468 | ident.Z_land => fun _ => "(&)"
469 | ident.Z_lor => fun _ => "(|)"
470 | ident.Z_lnot_modulo => neg_wrap_parens "~"
471 | ident.Z_lxor => neg_wrap_parens "⊕"
472 | ident.Z_bneg => neg_wrap_parens "!"
473 | ident.Z_mul_split => neg_wrap_parens "Z.mul_split"
474 | ident.Z_mul_high => neg_wrap_parens "Z.mul_high"
475 | ident.Z_add_get_carry => neg_wrap_parens "Z.add_get_carry"
476 | ident.Z_add_with_carry => neg_wrap_parens "Z.add_with_carry"
477 | ident.Z_add_with_get_carry => neg_wrap_parens "Z.add_with_get_carry"
478 | ident.Z_sub_get_borrow => neg_wrap_parens "Z.sub_get_borrow"
479 | ident.Z_sub_with_get_borrow => neg_wrap_parens "Z.sub_with_get_borrow"
480 | ident.Z_ltz => neg_wrap_parens "Z.ltz"
481 | ident.Z_zselect => neg_wrap_parens "Z.zselect"
482 | ident.Z_add_modulo => neg_wrap_parens "Z.add_modulo"
483 | ident.Z_truncating_shiftl => neg_wrap_parens "Z.truncating_shiftl"
484 | ident.Z_rshi => neg_wrap_parens "Z.rshi"
485 | ident.Z_cc_m => neg_wrap_parens "Z.cc_m"
486 | ident.Z_combine_at_bitwidth => neg_wrap_parens "Z.combine_at_bitwidth"
487 | ident.Z_cast => neg_wrap_parens "Z.cast"
488 | ident.Z_cast2 => neg_wrap_parens "Z.cast2"
489 | ident.Build_zrange => neg_wrap_parens "Build_zrange"
490 | ident.zrange_rect _ => neg_wrap_parens "zrange_rect"
491 | ident.fancy_add => neg_wrap_parens "fancy.add"
492 | ident.fancy_addc => neg_wrap_parens "fancy.addc"
493 | ident.fancy_sub => neg_wrap_parens "fancy.sub"
494 | ident.fancy_subb => neg_wrap_parens "fancy.subb"
495 | ident.fancy_mulll => neg_wrap_parens "fancy.mulll"
496 | ident.fancy_mullh => neg_wrap_parens "fancy.mullh"
497 | ident.fancy_mulhl => neg_wrap_parens "fancy.mulhl"
498 | ident.fancy_mulhh => neg_wrap_parens "fancy.mulhh"
499 | ident.fancy_rshi => neg_wrap_parens "fancy.rshi"
500 | ident.fancy_selc => neg_wrap_parens "fancy.selc"
501 | ident.fancy_selm => neg_wrap_parens "fancy.selm"
502 | ident.fancy_sell => neg_wrap_parens "fancy.sell"
503 | ident.fancy_addm => neg_wrap_parens "fancy.addm"
504 end.
505 Global Instance show_ident {t} : Show (ident.ident t) := show_lvl_ident.
506
507 (** N.B. Even though we are nominally printing Gallina
508 identifiers here, we parenthesize bitwise operators much
509 more frequently. See, e.g.,
510 https://github.com/mit-plv/fiat-crypto/pull/792#issuecomment-627647069,
511 where Andres makes the point that in C, [+] binds more
512 tightly than [<<]. *)
513
514 Definition conservative_binop_precedence_table : list (string * (Associativity * Level))
515 := [("*ℕ", (mul_assoc, mul_lvl))
516 ; ("+ℕ", (add_assoc, add_lvl))
517 ; ("-ℕ", (sub_assoc, sub_lvl))
518 ; ("=ℕ", (NoAssoc, Level.level 70))
519 ; ("*ℤ⁺", (mul_assoc, mul_lvl))
520 ; ("+ℤ⁺", (add_assoc, add_lvl))
521 ; ("::", (RightAssoc, Level.level 60))
522 ; ("++", (FullyAssoc, Level.level 60))
523 ; ("*", (mul_assoc, mul_lvl))
524 ; ("/", (div_assoc, div_lvl))
525 ; ("+", (add_assoc, add_lvl))
526 ; ("-", (sub_assoc, sub_lvl))
527 ; ("^", (pow_assoc, pow_lvl))
528 ; ("⊕", (LeftAssoc, Level.level 50))
529 ; ("mod", (LeftAssoc, Level.level 40))
530 ; ("=", (NoAssoc, Level.level 70))
531 ; ("<", (NoAssoc, Level.level 70))
532 ; ("≤", (NoAssoc, Level.level 70))
533 ; (">", (NoAssoc, Level.level 70))
534 ; ("≥", (NoAssoc, Level.level 70))
535 ; (">>", (ExplicitAssoc 35 35, Level.level 55))
536 ; ("<<", (ExplicitAssoc 35 35, Level.level 55))
537 ; ("&", (ExplicitAssoc 35 35, Level.level 55))
538 ; ("|", (ExplicitAssoc 35 35, Level.level 55))
539 ; (", ", (pair_assoc, pair_lvl))
540 ].
541 Definition conservative_preop_precedence_table : list (string * (Associativity * Level))
542 := [("-", (RightAssoc, opp_lvl))
543 ; ("!", (RightAssoc, Level.level 75))
544 ].
545 Definition conservative_postop_precedence_table : list (string * (Associativity * Level))
546 := [(".+1", (LeftAssoc, app_lvl))
547 ; (".-1", (LeftAssoc, app_lvl))
548 ; ("₁", (LeftAssoc, Level.level 0))
549 ; ("₂", (LeftAssoc, Level.level 0))
550 ].
551
552 Inductive Not_found := not_found.
553
554 Class with_space_opt := with_space : bool.
555 Global Instance with_space_default : with_space_opt | 1000 := true.
556
557 Definition lookup_lvl (table : list (string * (Associativity * Level))) (op : string)
558 := match List.find (fun '(op', _) => String.eqb op op') table as x return if x then Level else Not_found with
559 | Some (_, (assoc, lvl)) => lvl
560 | None => not_found
561 end.
562 Definition lookup_assoc (table : list (string * (Associativity * Level))) (op : string)
563 := match List.find (fun '(op', _) => String.eqb op op') table as x return if x then Associativity else Not_found with
564 | Some (_, (assoc, lvl)) => assoc
565 | None => not_found
566 end.
567 Definition lookup_show_lvl_binop {with_space : bool} (table : list (string * (Associativity * Level))) (binop : string)
568 := match List.find (fun '(binop', _) => String.eqb binop binop') table as x return if x then (Level -> string) -> (Level -> string) -> (Level -> string) else Not_found with
569 | Some (_, (binop_assoc, binop_lvl)) => fun x y => show_lvl_binop binop_assoc binop_lvl x (if with_space then " " ++ binop ++ " " else binop) y
570 | None => not_found
571 end.
572 Definition lookup_show_lvl_preop (table : list (string * (Associativity * Level))) (preop : string)
573 := match List.find (fun '(op', _) => String.eqb preop op') table as x return if x then (Level -> string) -> (Level -> string) else Not_found with
574 | Some (op, (op_assoc, op_lvl)) => fun x => show_lvl_preop_assoc op_assoc op_lvl op x
575 | None => not_found
576 end.
577 Definition lookup_show_lvl_postop (table : list (string * (Associativity * Level))) (postop : string)
578 := match List.find (fun '(op', _) => String.eqb postop op') table as x return if x then (Level -> string) -> (Level -> string) else Not_found with
579 | Some (op, (op_assoc, op_lvl)) => fun x => show_lvl_postop_assoc op_assoc op_lvl x op
580 | None => not_found
581 end.
582 (** We give the ident type [a -> b] to force patterns like [|
583 ident.Nat_mul as idc => ident_to_binop_string idc] to bind
584 [ident.Nat_mul] rather than the discriminee *)
585 Definition ident_to_op_string {a b} (idc : ident.ident (a -> b)) : string
586 := match idc with
587 | ident.Nat_mul => "*ℕ"
588 | ident.Nat_add => "+ℕ"
589 | ident.Nat_sub => "-ℕ"
590 | ident.Nat_eqb => "=ℕ"
591 | ident.Pos_mul => "*ℤ⁺"
592 | ident.Pos_add => "+ℤ⁺"
593 | ident.cons _ => "::"
594 | ident.List_app _ => "++"
595 | ident.Z_mul => "*"
596 | ident.Z_add => "+"
597 | ident.Z_sub => "-"
598 | ident.Z_pow => "^"
599 | ident.Z_lxor => "⊕"
600 | ident.Z_div => "/"
601 | ident.Z_modulo => "mod"
602 | ident.Z_eqb => "="
603 | ident.Z_ltb => "<"
604 | ident.Z_leb => "≤"
605 | ident.Z_gtb => ">"
606 | ident.Z_geb => "≥"
607 | ident.Z_shiftr => ">>"
608 | ident.Z_shiftl => "<<"
609 | ident.Z_land => "&"
610 | ident.Z_lor => "|"
611 | ident.pair _ _ => ", "
612 | ident.Nat_succ => ".+1"
613 | ident.Nat_pred => ".-1"
614 | ident.fst _ _ => "₁"
615 | ident.snd _ _ => "₂"
616 | ident.Z_opp => "-"
617 | ident.Z_bneg => "!"
618 | _ => ""
619 end.
620
621 Local Notation show_lvl_binop_no_space idc := (lookup_show_lvl_binop (with_space:=false) conservative_binop_precedence_table (ident_to_op_string idc)).
622 Local Notation show_lvl_binop idc := (lookup_show_lvl_binop (with_space:=true) conservative_binop_precedence_table (ident_to_op_string idc)).
623 Local Notation show_lvl_preop idc := (lookup_show_lvl_preop conservative_preop_precedence_table (ident_to_op_string idc)).
624 Local Notation show_lvl_postop idc := (lookup_show_lvl_postop conservative_postop_precedence_table (ident_to_op_string idc)).
625
626 Definition show_ident_lvl (with_casts : bool) (with_all_casts : bool) {t} (idc : ident.ident t)
627 : type.for_each_lhs_of_arrow (fun t => (Level.Level -> string) * ZRange.type.option.interp t)%type t -> (Level.Level -> string) * ZRange.type.base.option.interp (type.final_codomain t)
628 := let with_casts := (with_casts && negb with_all_casts)%bool in
629 match idc in ident.ident t return type.for_each_lhs_of_arrow (fun t => (Level.Level -> string) * ZRange.type.option.interp t)%type t -> (Level.Level -> string) * ZRange.type.base.option.interp (type.final_codomain t) with
630 | ident.Literal base.type.Z v => fun 'tt => (show_lvl_compact_Z v, ZRange.type.base.option.None)
631 | ident.Literal t v => fun 'tt => (show_lvl v, ZRange.type.base.option.Some (t:=t) v)
632 | ident.tt => fun _ => (fun _ => "()", tt)
633 | ident.Nat_max as idc
634 => fun '((x, xr), ((y, yr), tt)) => (show_lvl_app2 (show_lvl_ident idc) x y, ZRange.type.base.option.None)
635 | ident.Nat_succ as idc
636 | ident.Nat_pred as idc
637 => fun '((x, xr), tt) => (show_lvl_postop idc x, ZRange.type.base.option.None)
638 | ident.Z_opp as idc
639 | ident.Z_bneg as idc
640 => fun '((x, xr), tt) => (show_lvl_preop idc x, ZRange.type.base.option.None)
641 | ident.Nat_mul as idc
642 | ident.Nat_add as idc
643 | ident.Nat_sub as idc
644 | ident.Nat_eqb as idc
645 | ident.Pos_mul as idc
646 | ident.Pos_add as idc
647 | ident.cons _ as idc
648 | ident.List_app _ as idc
649 | ident.Z_mul as idc
650 | ident.Z_add as idc
651 | ident.Z_sub as idc
652 | ident.Z_pow as idc
653 | ident.Z_lxor as idc
654 | ident.Z_div as idc
655 | ident.Z_modulo as idc
656 | ident.Z_shiftr as idc
657 | ident.Z_shiftl as idc
658 | ident.Z_land as idc
659 | ident.Z_lor as idc
660 => fun '((x, xr), ((y, yr), tt)) => (show_lvl_binop idc x y, ZRange.type.base.option.None)
661 | ident.Z_eqb as idc
662 | ident.Z_ltb as idc
663 | ident.Z_leb as idc
664 | ident.Z_gtb as idc
665 | ident.Z_geb as idc
666 => fun '(x, (y, tt)) => (show_lvl_binop idc (maybe_wrap_cast with_casts x) (maybe_wrap_cast with_casts y), ZRange.type.base.option.None)
667 | ident.pair _ _ as idc => fun '((x, xr), ((y, yr), tt)) => (show_lvl_binop_no_space idc x y, (xr, yr))
668 | ident.fst _ _ as idc
669 => fun '((x, xr), tt) => (show_lvl_postop idc x, fst xr)
670 | ident.snd _ _ as idc
671 => fun '((x, xr), tt) => (show_lvl_postop idc x, snd xr)
672 | ident.None _ => fun 'tt => (neg_wrap_parens "None", ZRange.type.base.option.None)
673 | ident.nil t => fun 'tt => (neg_wrap_parens "[]", ZRange.type.base.option.None)
674 | ident.prod_rect A B T => fun '((f, fr), ((p, pr), tt)) => (neg_wrap_parens ("match " ++ show_lvl p term_lvl ++ " with " ++ show_lvl f term_lvl ++ " end"), ZRange.type.base.option.None)
675 | ident.bool_rect _
676 | ident.bool_rect_nodep _
677 => fun '(t, (f, ((b, br), tt))) => (fun lvl => maybe_wrap_parens (Level.ltb lvl term_lvl) ("if " ++ show_lvl b term_lvl ++ " then " ++ maybe_wrap_cast with_casts t term_lvl ++ " else " ++ maybe_wrap_cast with_casts f term_lvl), ZRange.type.base.option.None)
678 | ident.eager_List_nth_default _
679 => fun '((d, dr), ((ls, lsr), ((i, ir), tt))) => (fun lvl => maybe_wrap_parens (Level.ltb lvl app_lvl) (show_lvl ls app_lvl ++ "[[" ++ show_lvl i term_lvl ++ "]]"), ZRange.type.base.option.None)
680 | ident.List_nth_default _
681 => fun '((d, dr), ((ls, lsr), ((i, ir), tt))) => (fun lvl => maybe_wrap_parens (Level.ltb lvl app_lvl) (show_lvl ls app_lvl ++ "[" ++ show_lvl i term_lvl ++ "]"), ZRange.type.base.option.None)
682 | ident.Z_lnot_modulo => fun '((x, xr), ((m, mr), tt)) => (fun lvl => maybe_wrap_parens (Level.ltb lvl 75) ("~" ++ show_lvl x 75 ++ (if with_casts then " (mod " ++ show_lvl m term_lvl ++ ")" else "")), ZRange.type.base.option.None)
683 | ident.Z_cast as idc
684 | ident.Z_cast2 as idc
685 => fun '((srange, range), ((x, xr), tt))
686 => let t := (fun t (idc : ident.ident (_ -> t -> _)) => t) _ idc in
687 (* if we don't do the above, we pick up the wrong type in maybe_wrap_cast below *)
688 (if with_all_casts && Option.is_None (ZRange.type.base.option.lift_Some range)
689 then (fun _ => "(" ++ srange term_lvl ++ ")" ++ x 0)
690 else maybe_wrap_cast (t:=t) with_all_casts (x, range),
691 range)
692 | ident.Build_zrange
693 => fun '((x, xr), ((y, yr), tt))
694 => (neg_wrap_parens ("r[" ++ show_lvl x 60 ++ " ~> " ++ show_lvl y term_lvl),
695 match ZRange.ident.option.to_literal xr, ZRange.ident.option.to_literal yr with
696 | Some l, Some h => Some r[l ~> h]
697 | _, _ => (*ZRange.type.base.option.*)None
698 end)
699 | ident.comment _ as idc
700 | ident.comment_no_keep _ as idc
701 | ident.value_barrier as idc
702 | ident.Some _ as idc
703 | ident.nat_rect _ as idc
704 | ident.eager_nat_rect _ as idc
705 | ident.eager_nat_rect_arrow _ _ as idc
706 | ident.nat_rect_arrow _ _ as idc
707 | @ident.nat_rect_fbb_b _ _ _ as idc
708 | @ident.nat_rect_fbb_b_b _ _ _ _ as idc
709 | @ident.list_rect_fbb_b _ _ _ _ as idc
710 | @ident.list_rect_fbb_b_b _ _ _ _ _ as idc
711 | @ident.list_rect_fbb_b_b_b _ _ _ _ _ _ as idc
712 | @ident.list_rect_fbb_b_b_b_b _ _ _ _ _ _ _ as idc
713 | @ident.list_rect_fbb_b_b_b_b_b _ _ _ _ _ _ _ _ as idc
714 | ident.option_rect _ _ as idc
715 | ident.list_rect _ _ as idc
716 | ident.eager_list_rect _ _ as idc
717 | ident.list_rect_arrow _ _ _ as idc
718 | ident.eager_list_rect_arrow _ _ _ as idc
719 | ident.list_case _ _ as idc
720 | ident.List_length _ as idc
721 | ident.List_seq as idc
722 | ident.List_repeat _ as idc
723 | ident.List_firstn _ as idc
724 | ident.List_skipn _ as idc
725 | ident.List_combine _ _ as idc
726 | ident.List_map _ _ as idc
727 | ident.List_rev _ as idc
728 | ident.List_flat_map _ _ as idc
729 | ident.List_partition _ as idc
730 | ident.List_filter _ as idc
731 | ident.List_fold_right _ _ as idc
732 | ident.List_update_nth _ as idc
733 | ident.Z_log2 as idc
734 | ident.Z_log2_up as idc
735 | ident.Z_of_nat as idc
736 | ident.Z_to_nat as idc
737 | ident.Z_pos as idc
738 | ident.Z_to_pos as idc
739 | ident.Z_min as idc
740 | ident.Z_max as idc
741 | ident.Z_abs as idc
742 | ident.Z_mul_split as idc
743 | ident.Z_mul_high as idc
744 | ident.Z_add_get_carry as idc
745 | ident.Z_add_with_carry as idc
746 | ident.Z_add_with_get_carry as idc
747 | ident.Z_sub_get_borrow as idc
748 | ident.Z_sub_with_get_borrow as idc
749 | ident.Z_ltz as idc
750 | ident.Z_zselect as idc
751 | ident.Z_add_modulo as idc
752 | ident.Z_truncating_shiftl as idc
753 | ident.Z_rshi as idc
754 | ident.Z_cc_m as idc
755 | ident.Z_combine_at_bitwidth as idc
756 | ident.zrange_rect _ as idc
757 | ident.fancy_add as idc
758 | ident.fancy_addc as idc
759 | ident.fancy_sub as idc
760 | ident.fancy_subb as idc
761 | ident.fancy_mulll as idc
762 | ident.fancy_mullh as idc
763 | ident.fancy_mulhl as idc
764 | ident.fancy_mulhh as idc
765 | ident.fancy_rshi as idc
766 | ident.fancy_selc as idc
767 | ident.fancy_selm as idc
768 | ident.fancy_sell as idc
769 | ident.fancy_addm as idc
770 => fun args => (show_application with_casts (fun _ => show idc) args, ZRange.type.base.option.None)
771 end.
772 End ident.
773
774 Module expr.
775 Local Notation show_ident := ident.show_ident.
776 Local Notation show_ident_lvl := ident.show_ident_lvl.
777 Fixpoint get_eta_cps_args {A} (t : type) (idx : positive) {struct t}
778 : (type.for_each_lhs_of_arrow (fun y => (Level -> string) * ZRange.type.option.interp y)%type t -> positive -> A) -> list string * A
779 := match t with
780 | type.arrow s d
781 => fun k
782 => let n := "x" ++ Decimal.Pos.to_string idx in
783 let '(args, show_f) := @get_eta_cps_args A d (Pos.succ idx) (fun arglist => k (((fun _ => n), ZRange.type.option.None), arglist)) in
784 (n :: args, show_f)
785 | type.base _
786 => fun k => (nil, k tt idx)
787 end.
788 Section helper.
789 Context {var}
790 (of_string : forall t, string -> option (var t))
791 (k : forall t, @API.expr var t -> type.for_each_lhs_of_arrow (fun t => (Level -> string) * ZRange.type.option.interp t)%type t -> positive -> (positive * (Level -> list string)) * ZRange.type.base.option.interp (type.final_codomain t)).
792 Definition show_eta_abs_aux
793 (aux : forall t (idx : positive) (e : @API.expr var t),
794 (positive * (list string * (Level -> list string))) * ZRange.type.base.option.interp (type.final_codomain t))
795 s d (idx : positive) (f : var s -> @API.expr var d)
796 : (positive * (list string * (Level -> list string))) * ZRange.type.base.option.interp (type.final_codomain d)
797 := let n := match s with
798 | type.base base.type.unit => "()_" ++ Decimal.Pos.to_string idx
799 | _ => "x" ++ Decimal.Pos.to_string idx
800 end in
801 match of_string s n with
802 | Some n'
803 => let '(_, (args, show_f), r) := aux d (Pos.succ idx) (f n') in
804 (idx,
805 (n :: args, show_f),
806 r)
807 | None
808 => (idx,
809 ([n], (fun _ => ["λ_(" ++ show s ++ ")"])),
810 ZRange.type.base.option.None)
811 end.
812 Fixpoint show_eta_abs_cps' {t} (idx : positive) (e : @API.expr var t)
813 : (positive * (list string * (Level -> list string))) * ZRange.type.base.option.interp (type.final_codomain t)
814 := match e in expr.expr t return (unit -> _ * ZRange.type.base.option.interp (type.final_codomain t)) -> _ * ZRange.type.base.option.interp (type.final_codomain t) with
815 | expr.Abs s d f
816 => fun _
817 => show_eta_abs_aux (@show_eta_abs_cps') s d idx f
818 | _
819 => fun default
820 => default tt
821 end (fun _
822 => let '(args, (idx, show_f, r)) := get_eta_cps_args _ idx (@k _ e) in
823 ((idx, (args, show_f)), r)).
824 Definition show_eta_abs_cps (with_casts : bool) {s d} (idx : positive) (f : var s -> @API.expr var d) (extraargs : type.for_each_lhs_of_arrow (fun t => (Level -> string) * ZRange.type.option.interp t)%type (s -> d))
825 : (positive * (Level -> list string)) * ZRange.type.base.option.interp (type.final_codomain d)
826 := let '(idx, (args, show_f), r) := show_eta_abs_aux (@show_eta_abs_cps') s d idx f in
827 let argstr := String.concat " " args in
828 (idx,
829 fun lvl
830 => match show_f lvl with
831 | nil => [show_application with_casts (fun _ => "(λ " ++ argstr ++ ", (* NOTHING‽ *))") extraargs (Level.prev app_lvl)]%string
832 | show_f::nil
833 => [show_application with_casts (fun _ => "(λ " ++ argstr ++ ", " ++ show_f ++ ")") extraargs (Level.prev app_lvl)]%string
834 | show_f
835 => ["(λ " ++ argstr ++ ","]%string ++ (List.map (fun v => String " " (String " " v)) show_f) ++ [")" ++ show_application with_casts (fun _ => "") extraargs (Level.prev app_lvl)]%string
836 end%list,
837 r).
838 Definition show_eta_cps {t} (idx : positive) (e : @API.expr var t)
839 : (positive * (Level -> list string)) * ZRange.type.option.interp t
840 := let '(idx, (args, show_f), r) := @show_eta_abs_cps' t idx e in
841 let argstr := String.concat " " args in
842 (idx,
843 (fun lvl
844 => match args, show_f lvl with
845 | nil, show_f => show_f
846 | _, nil => ["(λ " ++ argstr ++ ", (* NOTHING‽ *))"]%string
847 | _, show_f::nil
848 => ["(λ " ++ argstr ++ ", " ++ show_f ++ ")"]%string
849 | _, show_f
850 => ["(λ " ++ argstr ++ ","]%string ++ (List.map (fun v => String " " (String " " v)) show_f) ++ [")"]
851 end%list),
852 match t return ZRange.type.base.option.interp (type.final_codomain t) -> ZRange.type.option.interp t with
853 | type.base _ => fun r => r
854 | type.arrow _ _ => fun _ => ZRange.type.option.None
855 end r).
856 End helper.
857
858 Fixpoint show_expr_lines_gen (with_casts : bool) (with_all_casts : bool) {var} (to_string : forall t, var t -> string) (of_string : forall t, string -> option (var t)) {t} (e : @API.expr var t) (args : type.for_each_lhs_of_arrow (fun t => (Level -> string) * ZRange.type.option.interp t)%type t) (idx : positive) {struct e} : (positive * (Level -> list string)) * ZRange.type.base.option.interp (type.final_codomain t)
859 := let show_expr_lines_gen := @show_expr_lines_gen with_casts with_all_casts var to_string of_string in
860 match e in expr.expr t return type.for_each_lhs_of_arrow (fun t => (Level -> string) * ZRange.type.option.interp t)%type t -> (positive * (Level -> list string)) * ZRange.type.base.option.interp (type.final_codomain t) with
861 | expr.Ident t idc
862 => fun args => let '(v, r) := @show_ident_lvl with_casts with_all_casts t idc args in
863 (idx, fun lvl => [v lvl], r)
864 | expr.Var t v
865 => fun args => (idx, fun lvl => [show_application with_casts (fun _ => to_string _ v) args lvl], ZRange.type.base.option.None)
866 | expr.Abs s d f
867 => fun args
868 => show_eta_abs_cps of_string (fun t e args idx => let '(idx, v, r) := @show_expr_lines_gen t e args idx in (idx, fun _ => v term_lvl, r)) with_casts idx f args
869 | expr.App s d f x
870 => fun args
871 => let '(idx', x', xr) := show_eta_cps of_string (fun t e args idx => @show_expr_lines_gen t e args idx) idx x in
872 @show_expr_lines_gen
873 _ f
874 (((fun lvl => String.concat String.NewLine (x' lvl)), xr),
875 args)
876 idx
877 | expr.LetIn A (type.base B) x f
878 => fun 'tt
879 => let n := "x" ++ Decimal.Pos.to_string idx in
880 let '(_, show_x, xr) := show_eta_cps of_string (fun t e args idx => @show_expr_lines_gen t e args idx) idx x in
881 let '(idx, show_f, fr)
882 := match of_string A n with
883 | Some n' => show_eta_cps of_string (fun t e args idx => @show_expr_lines_gen t e args idx) (Pos.succ idx) (f n')
884 | None => (idx, (fun _ => ["_"]), ZRange.type.option.None)
885 end in
886 let '(ty_str, comment_ty_str, space_comment_ty_str)
887 := match make_cast xr with
888 | Some c => let ty_str := " : " ++ c in
889 let comment_ty_str := "(*" ++ ty_str ++ " *)" in
890 (ty_str, comment_ty_str, " " ++ comment_ty_str)
891 | None => ("", "", "")
892 end in
893 let expr_let_line := "let " ++ n ++ " := " in
894 (idx,
895 (fun lvl
896 => match show_x term_lvl with
897 | nil => [expr_let_line ++ "(* NOTHING‽ *)" ++ space_comment_ty_str ++ " in"]%string ++ show_f term_lvl
898 | show_x::nil => [expr_let_line ++ show_x ++ "" ++ space_comment_ty_str ++ " in"]%string ++ show_f term_lvl
899 | show_x::rest
900 => ([expr_let_line ++ show_x]%string)
901 ++ (List.map (fun l => String.string_of_list_ascii (List.repeat " "%char (String.length expr_let_line)) ++ l)%string
902 rest)
903 ++ (if ty_str =? "" then ["(*" ++ ty_str ++ " *)"] else [])%string
904 ++ ["in"]
905 ++ show_f term_lvl
906 end%list),
907 fr)
908 | expr.LetIn A B x f
909 => fun args
910 => let n := "x" ++ Decimal.Pos.to_string idx in
911 let '(_, show_x, xr) := show_eta_cps of_string (fun t e args idx => @show_expr_lines_gen t e args idx) idx x in
912 let '(idx, show_f, fr)
913 := match of_string A n with
914 | Some n' => show_eta_cps of_string (fun t e args idx => @show_expr_lines_gen t e args idx) (Pos.succ idx) (f n')
915 | None => (idx, (fun _ => ["_"]), ZRange.type.option.None)
916 end in
917 let '(ty_str, comment_ty_str, space_comment_ty_str)
918 := match make_cast xr with
919 | Some c => let ty_str := " : " ++ c in
920 let comment_ty_str := "(*" ++ ty_str ++ " *)" in
921 (ty_str, comment_ty_str, " " ++ comment_ty_str)
922 | None => ("", "", "")
923 end in
924 let expr_let_line := "let " ++ n ++ " := " in
925 (idx,
926 (fun lvl
927 => (["("]
928 ++ (map
929 (String " ")
930 match show_x term_lvl with
931 | nil => [expr_let_line ++ "(* NOTHING‽ *)" ++ space_comment_ty_str ++ " in"]%string ++ show_f term_lvl
932 | show_x::nil => [expr_let_line ++ show_x ++ "" ++ space_comment_ty_str ++ " in"]%string ++ show_f term_lvl
933 | show_x::rest
934 => ([expr_let_line ++ show_x]%string)
935 ++ (List.map (fun l => String.string_of_list_ascii (List.repeat " "%char (String.length expr_let_line)) ++ l)%string
936 rest)
937 ++ (if ty_str =? "" then ["(*" ++ ty_str ++ " *)"] else [])%string
938 ++ ["in"]
939 ++ show_f term_lvl
940 end%list)
941 ++ [")"; show_application with_casts (fun _ => "") args (Level.prev app_lvl)])%list),
942 ZRange.type.base.option.None)
943 end args.
944 Definition show_expr_lines (with_casts : bool) (with_all_casts : bool) {t} (e : @API.expr (fun _ => string) t) (args : type.for_each_lhs_of_arrow (fun t => (Level -> string) * ZRange.type.option.interp t)%type t) (idx : positive) : (positive * (Level -> list string)) * ZRange.type.base.option.interp (type.final_codomain t)
945 := @show_expr_lines_gen with_casts with_all_casts (fun _ => string) (fun _ x => x) (fun _ x => Some x) t e args idx.
946 Definition show_lvl_var_expr : forall {var t}, ShowLevel (@API.expr var t)
947 := fix show_lvl_var_expr {var t} (e : @API.expr var t) : Level -> string
948 := match e with
949 | expr.Ident t idc => show_lvl idc
950 | expr.Var t v => neg_wrap_parens ("VAR_" ++ show_lvl t 0)
951 | expr.Abs s d f => neg_wrap_parens ("λ_" ++ show_lvl t 0)
952 | expr.App s d f x => show_lvl_binop LeftAssoc app_lvl (show_lvl_var_expr f) " @ " (show_lvl_var_expr x)
953 | expr.LetIn A B x f
954 => fun lvl => maybe_wrap_parens (Level.ltb lvl term_lvl) ("expr_let _ := " ++ show_lvl_var_expr x term_lvl ++ " in _")
955 end%string.
956 Definition show_var_expr {var t} : Show (@API.expr var t) := show_lvl_var_expr.
957 Definition partially_show_expr {var t} : Show (@API.expr var t) := show_var_expr.
958 Section Show_gen.
959 Context {with_casts : PHOAS.with_casts}
960 {with_all_casts : PHOAS.with_all_casts}
961 {var : API.type -> Type}
962 (to_string : forall t, var t -> string)
963 (of_string : forall t, string -> option (var t)).
964
965 Definition show_lines_expr_gen {t} : ShowLines (@API.expr var t)
966 := fun e => let '(_, v, _) := show_eta_cps of_string (fun t e args idx => @show_expr_lines_gen with_casts with_all_casts var to_string of_string t e args idx) 1%positive e in v (Level.prev term_lvl).
967 Definition show_expr_gen {t} : Show (@API.expr var t)
968 := fun e => String.concat String.NewLine (show_lines_expr_gen e).
969 End Show_gen.
970 Global Instance show_lines_expr {with_casts : PHOAS.with_casts} {with_all_casts : PHOAS.with_all_casts} {t} : ShowLines (@API.expr (fun _ => string) t)
971 := @show_lines_expr_gen with_casts with_all_casts (fun _ => string) (fun _ x => x) (fun _ x => Some x) t.
972 Global Instance show_lines_Expr {with_casts : PHOAS.with_casts} {with_all_casts : PHOAS.with_all_casts} {t} : ShowLines (@API.Expr t)
973 := fun e => show_lines (e _).
974 Global Instance show_expr {with_casts : PHOAS.with_casts} {with_all_casts : PHOAS.with_all_casts} {t} : Show (@API.expr (fun _ => string) t)
975 := fun e => String.concat String.NewLine (show_lines e).
976 Global Instance show_Expr {with_casts : PHOAS.with_casts} {with_all_casts : PHOAS.with_all_casts} {t} : Show (@API.Expr t)
977 := fun e => show (e _).
978 End expr.
979 End PHOAS.
980
981 Definition LinesToString (lines : list string)
982 : string
983 := String.concat String.NewLine lines.
984
985 Definition format_typedef_name
986 {language_naming_conventions : language_naming_conventions_opt}
987 (prefix : string)
988 (private : bool)
989 (name : string)
990 : string
991 := convert_to_naming_convention (if private then private_type_naming_convention else public_type_naming_convention) (prefix ++ name).
992
993 Module int.
994 Inductive type := signed (lgbitwidth : nat) | unsigned (lgbitwidth : nat).
995
996 Definition lgbitwidth_of (t : type) : nat
997 := match t with
998 | signed lgbitwidth => lgbitwidth
999 | unsigned lgbitwidth => lgbitwidth
1000 end.
1001 Definition of_lgbitwidth (is_signed : bool) (lgbitwidth : nat) : type
1002 := if is_signed then signed lgbitwidth else unsigned lgbitwidth.
1003 Definition bitwidth_of (t : type) : Z := 2^Z.of_nat (lgbitwidth_of t).
1004 Definition of_bitwidth (is_signed : bool) (bitwidth : Z) : type
1005 := of_lgbitwidth is_signed (Z.to_nat (Z.log2 bitwidth)).
1006 Definition of_bitwidth_up (is_signed : bool) (bitwidth : Z) : type
1007 := of_lgbitwidth is_signed (Z.to_nat (Z.log2_up bitwidth)).
1008 Definition is_signed (t : type) : bool := match t with signed _ => true | unsigned _ => false end.
1009 Definition is_unsigned (t : type) : bool := negb (is_signed t).
1010 Definition to_zrange (t : type) : zrange
1011 := let bw := bitwidth_of t in
1012 if is_signed t
1013 then r[-2^(bw-1) ~> 2^(bw-1) - 1]
1014 else r[0 ~> 2^bw - 1].
1015 Definition is_tighter_than (t1 t2 : type)
1016 := ZRange.is_tighter_than_bool (to_zrange t1) (to_zrange t2).
1017 Definition of_zrange_relaxed (r : zrange) : type
1018 := let lg2 := Z.log2_up ((upper r - lower r) + 1) in
1019 let lg2u := Z.log2_up (upper r + 1) in
1020 let lg2l := (if (lower r <? 0) then 1 + Z.log2_up (-lower r) else 0) in
1021 let lg2 := Z.max lg2 (Z.max lg2u lg2l) in
1022 let lg2lg2u := Z.log2_up lg2 in
1023 if (0 <=? lower r)
1024 then unsigned (Z.to_nat lg2lg2u)
1025 else signed (Z.to_nat lg2lg2u).
1026 Definition of_zrange (r : zrange) : option type
1027 := let t := of_zrange_relaxed r in
1028 let r' := to_zrange t in
1029 if (r' =? r)%zrange
1030 then Some t
1031 else None.
1032 Definition unsigned_counterpart_of (t : type) : type
1033 := unsigned (lgbitwidth_of t).
1034 Definition signed_counterpart_of (t : type) : type
1035 := signed (lgbitwidth_of t).
1036
1037 Lemma bitwidth_of_pos v : 0 < bitwidth_of v.
1038 Proof. cbv [bitwidth_of]; apply Z.pow_pos_nonneg; lia. Qed.
1039
1040 Lemma of_lgbitwidth_of v : of_lgbitwidth (is_signed v) (lgbitwidth_of v) = v.
1041 Proof. case v; reflexivity. Qed.
1042
1043 Lemma lgbitwidth_of_lgbitwidth b v : lgbitwidth_of (of_lgbitwidth b v) = v.
1044 Proof. case b; reflexivity. Qed.
1045
1046 Lemma is_signed_of_lgbitwidth b v : is_signed (of_lgbitwidth b v) = b.
1047 Proof. case b; reflexivity. Qed.
1048
1049 Lemma of_bitwidth_of v : of_bitwidth (is_signed v) (bitwidth_of v) = v.
1050 Proof.
1051 cbv [of_bitwidth bitwidth_of].
1052 rewrite Z.log2_pow2, Nat2Z.id by lia.
1053 apply of_lgbitwidth_of.
1054 Qed.
1055
1056 Lemma of_bitwidth_up_of v : of_bitwidth_up (is_signed v) (bitwidth_of v) = v.
1057 Proof.
1058 cbv [of_bitwidth_up bitwidth_of].
1059 rewrite Z.log2_up_pow2, Nat2Z.id by lia.
1060 apply of_lgbitwidth_of.
1061 Qed.
1062
1063 Lemma is_signed_of_bitwidth b v : is_signed (of_bitwidth b v) = b.
1064 Proof. apply is_signed_of_lgbitwidth. Qed.
1065
1066 Lemma is_signed_of_bitwidth_up b v : is_signed (of_bitwidth_up b v) = b.
1067 Proof. apply is_signed_of_lgbitwidth. Qed.
1068
1069 Global Instance show_lvl_type : ShowLevel type
1070 := fun t => neg_wrap_parens ((if is_unsigned t then "u" else "") ++ "int" ++ Decimal.Z.to_string (bitwidth_of t)).
1071 Global Instance show_type : Show type := show_lvl_type.
1072
1073 Definition to_string_gen
1074 {language_naming_conventions : language_naming_conventions_opt}
1075 (standard_bitwidths : list Z)
1076 (unsigned_s signed_s : string)
1077 (standard_postfix special_postfix : string)
1078 (private : bool) (prefix : string)
1079 (t : type)
1080 : string
1081 := let is_standard := existsb (Z.eqb (bitwidth_of t)) standard_bitwidths in
1082 (if is_standard
1083 then (fun s => s)
1084 else (fun s => convert_to_naming_convention
1085 (if private then private_type_naming_convention else public_type_naming_convention)
1086 (prefix ++ s)))
1087 ((if is_unsigned t then unsigned_s else signed_s)
1088 ++ Decimal.Z.to_string (ToString.int.bitwidth_of t)
1089 ++ (if is_standard then standard_postfix else special_postfix)).
1090
1091 Definition to_string_gen_opt_typedef
1092 {language_naming_conventions : language_naming_conventions_opt}
1093 {skip_typedefs : skip_typedefs_opt}
1094 (standard_bitwidths : list Z)
1095 (unsigned_s signed_s : string)
1096 (standard_postfix special_postfix : string)
1097 (private : bool) (typedef_private : bool) (prefix : string)
1098 (t : type)
1099 (typedef : option string)
1100 : string
1101 := match (if skip_typedefs then None else typedef) with
1102 | Some typedef => format_typedef_name prefix typedef_private typedef
1103 | None => to_string_gen standard_bitwidths unsigned_s signed_s standard_postfix special_postfix private prefix t
1104 end.
1105
1106 Definition union (t1 t2 : type) : type := of_zrange_relaxed (ZRange.union (to_zrange t1) (to_zrange t2)).
1107
1108 Definition union_zrange (r : zrange) (t : type) : type
1109 := of_zrange_relaxed (ZRange.union r (to_zrange t)).
1110
1111 Fixpoint base_interp (t : base.type) : Set
1112 := match t with
1113 | base.type.type_base base.type.Z => type
1114 | base.type.type_base _
1115 | base.type.unit
1116 => unit
1117 | base.type.prod A B => base_interp A * base_interp B
1118 | base.type.list A => list (base_interp A)
1119 | base.type.option A => option (base_interp A)
1120 end%type.
1121
1122 Module base_interp.
1123 Fixpoint of_zrange_relaxed {t : base.type} : ZRange.type.base.interp t -> base_interp t
1124 := match t with
1125 | base.type.type_base base.type.Z => int.of_zrange_relaxed
1126 | base.type.type_base _
1127 | base.type.unit
1128 => fun _ => tt
1129 | base.type.prod A B => fun '(a, b) => (@of_zrange_relaxed A a, @of_zrange_relaxed B b)
1130 | base.type.list A => List.map (@of_zrange_relaxed A)
1131 | base.type.option A => option_map (@of_zrange_relaxed A)
1132 end.
1133
1134 Fixpoint to_union {t : base.type} : base_interp t -> option type
1135 := match t with
1136 | base.type.type_base base.type.Z => fun r => Some r
1137 | base.type.type_base _
1138 | base.type.unit
1139 => fun 'tt => None
1140 | base.type.prod A B => fun '(a, b) => (a <- @to_union A a; b <- @to_union B b; Some (union a b))
1141 | base.type.list A
1142 => fun ls
1143 => (ls <-- List.map (@to_union A) ls;
1144 match ls with
1145 | nil => None
1146 | cons x xs => Some (List.fold_right union x xs)
1147 end)
1148 | base.type.option A => fun x => (x <- option_map (@to_union A) x; x)
1149 end%option.
1150 End base_interp.
1151
1152 Module option.
1153 Fixpoint interp (t : base.type) : Set
1154 := match t with
1155 | base.type.type_base base.type.Z => option type
1156 | base.type.type_base _
1157 | base.type.unit
1158 => unit
1159 | base.type.prod A B => interp A * interp B
1160 | base.type.list A => option (list (interp A))
1161 | base.type.option A => option (option (interp A))
1162 end%type.
1163
1164 Module interp.
1165 Fixpoint to_zrange {t : base.type} : interp t -> ZRange.type.base.option.interp t
1166 := match t with
1167 | base.type.type_base base.type.Z => option_map int.to_zrange
1168 | base.type.type_base _
1169 => fun 'tt => None
1170 | base.type.unit
1171 => fun 'tt => tt
1172 | base.type.prod A B => fun '(a, b) => (@to_zrange A a, @to_zrange B b)
1173 | base.type.list A => option_map (List.map (@to_zrange A))
1174 | base.type.option A => option_map (option_map (@to_zrange A))
1175 end.
1176 Fixpoint of_zrange_relaxed {t : base.type} : ZRange.type.base.option.interp t -> interp t
1177 := match t with
1178 | base.type.type_base base.type.Z => option_map int.of_zrange_relaxed
1179 | base.type.type_base _
1180 | base.type.unit
1181 => fun _ => tt
1182 | base.type.prod A B => fun '(a, b) => (@of_zrange_relaxed A a, @of_zrange_relaxed B b)
1183 | base.type.list A => option_map (List.map (@of_zrange_relaxed A))
1184 | base.type.option A => option_map (option_map (@of_zrange_relaxed A))
1185 end.
1186 Fixpoint to_union {t : base.type} : interp t -> option type
1187 := match t return interp t -> option type with
1188 | base.type.type_base base.type.Z => fun r => r
1189 | base.type.type_base _
1190 | base.type.unit
1191 => fun 'tt => None
1192 | base.type.prod A B => fun '(a, b) => (a <- @to_union A a; b <- @to_union B b; Some (union a b))
1193 | base.type.list A
1194 => fun ls
1195 => (ls <- ls;
1196 ls <-- List.map (@to_union A) ls;
1197 match ls with
1198 | nil => None
1199 | cons x xs => Some (List.fold_right union x xs)
1200 end)
1201 | base.type.option A => fun x => (x <- x; x <- option_map (@to_union A) x; x)
1202 end%option.
1203 End interp.
1204 Fixpoint None {t} : interp t
1205 := match t with
1206 | base.type.type_base base.type.Z => Datatypes.None
1207 | base.type.type_base _
1208 | base.type.unit
1209 => tt
1210 | base.type.prod A B => (@None A, @None B)
1211 | base.type.list A => Datatypes.None
1212 | base.type.option A => Datatypes.None
1213 end.
1214 Fixpoint Some {t} : base_interp t -> interp t
1215 := match t with
1216 | base.type.type_base base.type.Z => Datatypes.Some
1217 | base.type.type_base _
1218 | base.type.unit
1219 => fun tt => tt
1220 | base.type.prod A B => fun '(a, b) => (@Some A a, @Some B b)
1221 | base.type.list A => fun ls => Datatypes.Some (List.map (@Some A) ls)
1222 | base.type.option A => fun ls => Datatypes.Some (Option.map (@Some A) ls)
1223 end.
1224 End option.
1225
1226 Module Export Notations.
1227 Notation _Bool := (unsigned 0).
1228 Notation uint8 := (unsigned 3).
1229 Notation int8 := (signed 3).
1230 Notation uint16 := (unsigned 4).
1231 Notation int16 := (signed 4).
1232 Notation uint32 := (unsigned 5).
1233 Notation int32 := (signed 5).
1234 Notation uint64 := (unsigned 6).
1235 Notation int64 := (signed 6).
1236 Notation uint128 := (unsigned 7).
1237 Notation int128 := (signed 7).
1238 End Notations.
1239 End int.
1240 Import int.Notations.
1241
1242 Example of_zrange_int32 : int.of_zrange_relaxed r[-2^31 ~> 2^31-1] = int32 := eq_refl.
1243 Example of_zrange_int64 : int.of_zrange_relaxed r[-2^31-1 ~> 2^31-1] = int64 := eq_refl.
1244 Example of_zrange_int64' : int.of_zrange_relaxed r[-2^31 ~> 2^31] = int64 := eq_refl.
1245 Example of_zrange_uint32 : int.of_zrange_relaxed r[0 ~> 2^32-1] = uint32 := eq_refl.
1246 Example of_zrange_uint64 : int.of_zrange_relaxed r[0 ~> 2^32] = uint64 := eq_refl.
1247
1248 Module SumPositiveSet := SumSets PositiveSet PositiveSet.
1249
1250 Module IntAsDecidableType <: IsoDecidableType SumPositiveSet.E.
1251 Definition t := int.type.
1252 Definition eq : t -> t -> Prop := eq.
1253 Definition eq_equiv : Equivalence eq := _.
1254 Definition eq_dec := int.type_eq_dec.
1255 Definition to_ (v : t) : positive + positive
1256 := (if int.is_signed v then inl else inr)
1257 (Pos.of_succ_nat (int.lgbitwidth_of v)).
1258 Definition of_ (v : positive + positive) : t
1259 := let is_signed := match v with inl _ => true | inr _ => false end in
1260 let lgbitwidth := match v with inl v => v | inr v => v end in
1261 int.of_lgbitwidth is_signed (Nat.pred (Pos.to_nat lgbitwidth)).
1262 Lemma of_to v : of_ (to_ v) = v.
1263 Proof.
1264 destruct v; cbv [of_ to_]; cbn;
1265 now rewrite SuccNat2Pos.pred_id.
1266 Qed.
1267 Lemma to_of v : SumPositiveSet.E.eq (to_ (of_ v)) v.
1268 Proof.
1269 destruct v; cbv [of_ to_ SumPositiveSet.E.eq sumwise];
1270 rewrite int.lgbitwidth_of_lgbitwidth, int.is_signed_of_lgbitwidth;
1271 f_equal;
1272 lia.
1273 Qed.
1274 Global Instance Proper_to_ : Proper (eq ==> SumPositiveSet.E.eq) to_.
1275 Proof. cbv [eq]; intros ???; subst; reflexivity. Qed.
1276 Global Instance Proper_of_ : Proper (SumPositiveSet.E.eq ==> eq) of_.
1277 Proof. cbv [eq SumPositiveSet.E.eq sumwise]; intros [?|?] [?|?] ?; subst; tauto. Qed.
1278 End IntAsDecidableType.
1279
1280 Module IntSet <: WSets := IsoWSets SumPositiveSet IntAsDecidableType.
1281 Module Import IntSetShow := ShowWSets IntSet.
1282 Global Instance show_IntSet : Show IntSet.t := _.
1283 Global Instance show_lines_IntSet : ShowLines IntSet.t := _.
1284
1285 Notation typedef_info := (string (* name *) * (string -> string) (* description *) * option int.type * { t : base.type & ZRange.type.base.option.interp t } (* bounds *))%type.
1286
1287 (* Work around COQBUG(https://github.com/coq/coq/issues/11942) *)
1288 Local Unset Decidable Equality Schemes.
1289 Record ident_infos :=
1290 { bitwidths_used : IntSet.t;
1291 addcarryx_lg_splits : PositiveSet.t;
1292 mulx_lg_splits : PositiveSet.t;
1293 cmovznz_bitwidths : IntSet.t;
1294 value_barrier_bitwidths : IntSet.t;
1295 typedefs_used : list string (* typedef name *);
1296 }.
1297 Local Set Decidable Equality Schemes.
1298 Global Instance show_lines_ident_infos : ShowLines ident_infos
1299 := fun v
1300 => ["{| bitwidths_used := " ++ show (bitwidths_used v)
1301 ; " ; addcarryx_lg_splits := " ++ show (addcarryx_lg_splits v)
1302 ; " ; mulx_lg_splits := " ++ show (mulx_lg_splits v)
1303 ; " ; cmovznz_bitwidths := " ++ show (cmovznz_bitwidths v)
1304 ; " ; value_barrier_bitwidths := " ++ show (value_barrier_bitwidths v)
1305 ; " ; typedefs_used := " ++ show (typedefs_used v) ++ " |}"].
1306 Global Instance show_ident_infos : Show ident_infos
1307 := fun v => String.concat "" (show_lines v).
1308 Global Instance show_lvl_ident_infos : ShowLevel ident_infos
1309 := fun v => neg_wrap_parens (show_ident_infos v).
1310 Local Notation typedef_beq := String.eqb (only parsing).
1311 Local Notation typedefs_diff x y := (List.filter (fun v => negb (existsb (typedef_beq v) y)) x).
1312 Definition ident_infos_equal (x y : ident_infos) : bool
1313 := let (x0, x1, x2, x3, x4, x5) := x in
1314 let (y0, y1, y2, y3, y4, y5) := y in
1315 List.fold_right
1316 andb true
1317 [IntSet.equal x0 y0
1318 ; PositiveSet.equal x1 y1
1319 ; PositiveSet.equal x2 y2
1320 ; IntSet.equal x3 y3
1321 ; IntSet.equal x4 y4
1322 ; list_beq _ typedef_beq x5 y5 ].
1323 Definition ident_info_empty : ident_infos
1324 := Build_ident_infos IntSet.empty PositiveSet.empty PositiveSet.empty IntSet.empty IntSet.empty [].
1325 Definition ident_info_diff (x y : ident_infos) : ident_infos
1326 := let (x0, x1, x2, x3, x4, x5) := x in
1327 let (y0, y1, y2, y3, y4, y5) := y in
1328 Build_ident_infos
1329 (IntSet.diff x0 y0)
1330 (PositiveSet.diff x1 y1)
1331 (PositiveSet.diff x2 y2)
1332 (IntSet.diff x3 y3)
1333 (IntSet.diff x4 y4)
1334 (typedefs_diff x5 y5).
1335 Definition ident_info_diff_except_bitwidths (x y : ident_infos) : ident_infos
1336 := let (x0, x1, x2, x3, x4, x5) := x in
1337 let (y0, y1, y2, y3, y4, y5) := y in
1338 Build_ident_infos
1339 x0
1340 (PositiveSet.diff x1 y1)
1341 (PositiveSet.diff x2 y2)
1342 (IntSet.diff x3 y3)
1343 (IntSet.diff x4 y4)
1344 (typedefs_diff x5 y5).
1345 Definition ident_info_union (x y : ident_infos) : ident_infos
1346 := let (x0, x1, x2, x3, x4, x5) := x in
1347 let (y0, y1, y2, y3, y4, y5) := y in
1348 Build_ident_infos
1349 (IntSet.union x0 y0)
1350 (PositiveSet.union x1 y1)
1351 (PositiveSet.union x2 y2)
1352 (IntSet.union x3 y3)
1353 (IntSet.union x4 y4)
1354 (x5 ++ typedefs_diff y5 x5).
1355 Definition ident_info_of_bitwidths_used (v : IntSet.t) : ident_infos
1356 := {| bitwidths_used := v;
1357 addcarryx_lg_splits := PositiveSet.empty;
1358 mulx_lg_splits := PositiveSet.empty;
1359 cmovznz_bitwidths := IntSet.empty;
1360 value_barrier_bitwidths := IntSet.empty;
1361 typedefs_used := [] |}.
1362 Definition ident_info_of_addcarryx (v : PositiveSet.t) : ident_infos
1363 := {| bitwidths_used := IntSet.empty;
1364 addcarryx_lg_splits := v;
1365 mulx_lg_splits := PositiveSet.empty;
1366 cmovznz_bitwidths := IntSet.empty;
1367 value_barrier_bitwidths := IntSet.empty;
1368 typedefs_used := [] |}.
1369 Definition ident_info_of_mulx (v : PositiveSet.t) : ident_infos
1370 := {| bitwidths_used := IntSet.empty;
1371 addcarryx_lg_splits := PositiveSet.empty;
1372 mulx_lg_splits := v;
1373 cmovznz_bitwidths := IntSet.empty;
1374 value_barrier_bitwidths := IntSet.empty;
1375 typedefs_used := [] |}.
1376 Definition ident_info_of_cmovznz (v : IntSet.t) : ident_infos
1377 := {| bitwidths_used := IntSet.empty;
1378 addcarryx_lg_splits := PositiveSet.empty;
1379 mulx_lg_splits := PositiveSet.empty;
1380 cmovznz_bitwidths := v;
1381 value_barrier_bitwidths := IntSet.empty;
1382 typedefs_used := [] |}.
1383 Definition ident_info_of_value_barrier (v : IntSet.t) : ident_infos
1384 := {| bitwidths_used := IntSet.empty;
1385 addcarryx_lg_splits := PositiveSet.empty;
1386 mulx_lg_splits := PositiveSet.empty;
1387 cmovznz_bitwidths := IntSet.empty;
1388 value_barrier_bitwidths := v;
1389 typedefs_used := [] |}.
1390 Definition ident_info_of_typedefs (v : list _) : ident_infos
1391 := {| bitwidths_used := IntSet.empty;
1392 addcarryx_lg_splits := PositiveSet.empty;
1393 mulx_lg_splits := PositiveSet.empty;
1394 cmovznz_bitwidths := IntSet.empty;
1395 value_barrier_bitwidths := IntSet.empty;
1396 typedefs_used := v |}.
1397 Definition ident_info_with_bitwidths_used (i : ident_infos) (v : IntSet.t) : ident_infos
1398 := {| bitwidths_used := v;
1399 addcarryx_lg_splits := addcarryx_lg_splits i;
1400 mulx_lg_splits := mulx_lg_splits i;
1401 cmovznz_bitwidths := cmovznz_bitwidths i;
1402 value_barrier_bitwidths := value_barrier_bitwidths i;
1403 typedefs_used := typedefs_used i |}.
1404 Definition ident_info_with_addcarryx (i : ident_infos) (v : PositiveSet.t) : ident_infos
1405 := {| bitwidths_used := bitwidths_used i;
1406 addcarryx_lg_splits := v;
1407 mulx_lg_splits := mulx_lg_splits i;
1408 cmovznz_bitwidths := cmovznz_bitwidths i;
1409 value_barrier_bitwidths := value_barrier_bitwidths i;
1410 typedefs_used := typedefs_used i |}.
1411 Definition ident_info_with_mulx (i : ident_infos) (v : PositiveSet.t) : ident_infos
1412 := {| bitwidths_used := bitwidths_used i;
1413 addcarryx_lg_splits := addcarryx_lg_splits i;
1414 mulx_lg_splits := v;
1415 cmovznz_bitwidths := cmovznz_bitwidths i;
1416 value_barrier_bitwidths := value_barrier_bitwidths i;
1417 typedefs_used := typedefs_used i |}.
1418 Definition ident_info_with_cmovznz (i : ident_infos) (v : IntSet.t) : ident_infos
1419 := {| bitwidths_used := bitwidths_used i;
1420 addcarryx_lg_splits := addcarryx_lg_splits i;
1421 mulx_lg_splits := mulx_lg_splits i;
1422 cmovznz_bitwidths := v;
1423 value_barrier_bitwidths := value_barrier_bitwidths i;
1424 typedefs_used := typedefs_used i |}.
1425 Definition ident_info_with_value_barrier (i : ident_infos) (v : IntSet.t) : ident_infos
1426 := {| bitwidths_used := bitwidths_used i;
1427 addcarryx_lg_splits := addcarryx_lg_splits i;
1428 mulx_lg_splits := mulx_lg_splits i;
1429 cmovznz_bitwidths := cmovznz_bitwidths i;
1430 value_barrier_bitwidths := v;
1431 typedefs_used := typedefs_used i |}.
1432 Definition ident_info_with_typedefs (i : ident_infos) (v : list _) : ident_infos
1433 := {| bitwidths_used := bitwidths_used i;
1434 addcarryx_lg_splits := addcarryx_lg_splits i;
1435 mulx_lg_splits := mulx_lg_splits i;
1436 cmovznz_bitwidths := cmovznz_bitwidths i;
1437 value_barrier_bitwidths := value_barrier_bitwidths i;
1438 typedefs_used := v |}.
1439
1440 Module Import OfPHOAS.
1441 Fixpoint base_var_data (t : base.type) : Set
1442 := match t with
1443 | base.type.unit
1444 => unit
1445 | base.type.type_base base.type.Z => string * bool (* is pointer *) * option int.type * option string (* typedef alias *)
1446 | base.type.prod A B => base_var_data A * base_var_data B
1447 | base.type.list A => string * option int.type * nat * option string (* typedef alias *)
1448 | base.type.type_base _
1449 | base.type.option _
1450 => Empty_set
1451 end.
1452 Definition var_data (t : API.type) : Set
1453 := match t with
1454 | type.base t => base_var_data t
1455 | type.arrow s d => Empty_set
1456 end.
1457
1458 Fixpoint base_var_typedef_data (t : base.type) : Set
1459 := match t with
1460 | base.type.unit
1461 => unit
1462 | base.type.type_base base.type.Z => option string
1463 | base.type.prod A B => base_var_typedef_data A * base_var_typedef_data B
1464 | base.type.list A => option string
1465 | base.type.type_base _
1466 | base.type.option _
1467 => unit
1468 end.
1469 Fixpoint base_var_typedef_data_None {t : base.type} : base_var_typedef_data t
1470 := match t with
1471 | base.type.unit
1472 => tt
1473 | base.type.type_base base.type.Z => None
1474 | base.type.prod A B => (base_var_typedef_data_None, base_var_typedef_data_None)
1475 | base.type.list A => None
1476 | base.type.type_base _
1477 | base.type.option _
1478 => tt
1479 end.
1480
1481 Definition var_typedef_data (t : API.type) : Set
1482 := match t with
1483 | type.base t => base_var_typedef_data t
1484 | type.arrow s d => unit
1485 end.
1486
1487 Definition var_typedef_data_None {t : API.type} : var_typedef_data t
1488 := match t with
1489 | type.base t => base_var_typedef_data_None
1490 | type.arrow _ _ => tt
1491 end.
1492
1493 Fixpoint base_var_names (t : base.type) : Set
1494 := match t with
1495 | base.type.unit
1496 => unit
1497 | base.type.type_base base.type.Z => string
1498 | base.type.prod A B => base_var_names A * base_var_names B
1499 | base.type.list A => string
1500 | base.type.type_base _
1501 | base.type.option _
1502 => Empty_set
1503 end.
1504 Definition var_names (t : API.type) : Set
1505 := match t with
1506 | type.base t => base_var_names t
1507 | type.arrow s d => Empty_set
1508 end.
1509
1510 Fixpoint names_list_of_base_var_names {t} : base_var_names t -> list string
1511 := match t return base_var_names t -> list string with
1512 | base.type.unit
1513 => fun _ => []
1514 | base.type.type_base base.type.Z
1515 | base.type.list _
1516 => fun n => [n]
1517 | base.type.prod A B
1518 => fun x : base_var_names A * base_var_names B
1519 => @names_list_of_base_var_names A (fst x) ++ @names_list_of_base_var_names B (snd x)
1520 | base.type.type_base _
1521 | base.type.option _
1522 => fun absurd : Empty_set => match absurd with end
1523 end%list.
1524
1525 Definition names_list_of_var_names {t} : var_names t -> list string
1526 := match t with
1527 | type.base t => @names_list_of_base_var_names t
1528 | type.arrow _ _ => fun absurd : Empty_set => match absurd with end
1529 end.
1530
1531 Fixpoint names_of_base_var_data {t} : base_var_data t -> base_var_names t
1532 := match t return base_var_data t -> base_var_names t with
1533 | base.type.type_base base.type.Z => fun '(n, is_ptr, _, _) => n
1534 | base.type.prod A B
1535 => fun xy => (@names_of_base_var_data A (fst xy), @names_of_base_var_data B (snd xy))
1536 | base.type.list A => fun x => fst (fst (fst x))
1537 | base.type.unit
1538 | base.type.type_base _
1539 | base.type.option _
1540 => fun x => x
1541 end.
1542 Definition names_of_var_data {t} : var_data t -> var_names t
1543 := match t with
1544 | type.base t => names_of_base_var_data
1545 | type.arrow _ _ => fun x => x
1546 end.
1547
1548 Definition names_list_of_base_var_data {t} (v : base_var_data t) : list string
1549 := names_list_of_base_var_names (names_of_base_var_data v).
1550
1551 Definition names_list_of_var_data {t} (v : var_data t) : list string
1552 := names_list_of_var_names (names_of_var_data v).
1553
1554 Fixpoint flatten_names_list_of_input_data {t : type} : type.for_each_lhs_of_arrow (fun _ => list string) t -> list string
1555 := match t return type.for_each_lhs_of_arrow _ t -> _ with
1556 | type.base _ => fun 'tt => nil
1557 | type.arrow s d
1558 => fun '(sl, v) => sl ++ @flatten_names_list_of_input_data d v
1559 end%list.
1560
1561 Definition names_list_of_input_var_names {t} (v : type.for_each_lhs_of_arrow var_names t) : list string
1562 := flatten_names_list_of_input_data (type.map_for_each_lhs_of_arrow (@names_list_of_var_names) v).
1563
1564 Definition names_list_of_input_var_data {t} (v : type.for_each_lhs_of_arrow var_data t) : list string
1565 := names_list_of_input_var_names (type.map_for_each_lhs_of_arrow (@names_of_var_data) v).
1566
1567 Fixpoint base_var_data_of_names {t} : base_var_names t -> base_var_data t
1568 := match t return base_var_names t -> base_var_data t with
1569 | base.type.type_base base.type.Z => fun n => (n, false, None, None)
1570 | base.type.prod A B
1571 => fun xy => (@base_var_data_of_names A (fst xy), @base_var_data_of_names B (snd xy))
1572 | base.type.list A => fun n => (n, None, 0%nat, None)
1573 | base.type.unit
1574 | base.type.type_base _
1575 | base.type.option _
1576 => fun x => x
1577 end.
1578 Definition var_data_of_names {t} : var_names t -> var_data t
1579 := match t with
1580 | type.base t => base_var_data_of_names
1581 | type.arrow _ _ => fun x => x
1582 end.
1583
1584 Fixpoint bound_to_string {skip_typedefs : skip_typedefs_opt} {t : base.type}
1585 : var_data (type.base t) -> ZRange.type.base.option.interp t -> list string
1586 := match t return var_data (type.base t) -> ZRange.type.base.option.interp t -> list string with
1587 | base.type.list _
1588 | tZ
1589 => fun '(name, _, _, td) arg
1590 => if skip_typedefs || Option.is_None td
1591 then [(name ++ ": ")
1592 ++ match ZRange.type.base.option.lift_Some arg with
1593 | Some arg => show arg
1594 | None => show arg
1595 end]%string
1596 else []
1597 | base.type.prod A B
1598 => fun '(va, vb) '(a, b)
1599 => @bound_to_string skip_typedefs A va a ++ @bound_to_string skip_typedefs B vb b
1600 | base.type.unit
1601 => fun 'tt _ => nil
1602 | base.type.option _
1603 | base.type.type_base _
1604 => fun absurd : Empty_set => match absurd with end
1605 end%list.
1606
1607 Fixpoint input_bounds_to_string {skip_typedefs : skip_typedefs_opt} {t} : type.for_each_lhs_of_arrow var_data t -> type.for_each_lhs_of_arrow ZRange.type.option.interp t -> list string
1608 := match t return type.for_each_lhs_of_arrow var_data t -> type.for_each_lhs_of_arrow ZRange.type.option.interp t -> list string with
1609 | type.base t => fun _ _ => nil
1610 | type.arrow (type.base s) d
1611 => fun '(v, vs) '(arg, args)
1612 => (bound_to_string v arg)
1613 ++ @input_bounds_to_string skip_typedefs d vs args
1614 | type.arrow s d
1615 => fun '(absurd, _) => match absurd : Empty_set with end
1616 end%list.
1617 End OfPHOAS.
1618
1619 Definition format_special_function_name
1620 {language_naming_conventions : language_naming_conventions_opt}
1621 (internal_private : bool)
1622 (prefix : string)
1623 (name : string)
1624 (is_signed : bool)
1625 (bw : Z)
1626 : string
1627 := convert_to_naming_convention
1628 (if internal_private then private_function_naming_convention else public_function_naming_convention)
1629 (prefix ++ name ++ "_" ++ (if negb is_signed then "u" else "") ++ Decimal.Z.to_string bw).
1630
1631 Definition name_of_typedef
1632 {language_naming_conventions : language_naming_conventions_opt}
1633 (prefix : string)
1634 (private : bool)
1635 : typedef_info -> string
1636 := fun '(name, description, ty, existT t bounds)
1637 => format_typedef_name prefix private name.
1638
1639 Definition describe_typedef
1640 {language_naming_conventions : language_naming_conventions_opt}
1641 {documentation_options : documentation_options_opt}
1642 (prefix : string)
1643 (private : bool)
1644 (typedef : typedef_info)
1645 : list string
1646 := let name := name_of_typedef prefix private typedef in
1647 let '(_, description, ty, existT t bounds) := typedef in
1648 (([description name]%string)
1649 ++ (if ZRange.type.base.option.is_informative bounds
1650 then let bounds := match ZRange.type.base.option.lift_Some bounds with
1651 | Some bounds => show bounds
1652 | None => show bounds
1653 end in
1654 if newline_in_typedef_bounds
1655 then ["Bounds:"; " " ++ bounds]%string
1656 else ["Bounds: " ++ bounds]%string
1657 else []))%list.
1658
1659
1660 (** None means not array; Some None means array of unknown length; Some Some means array of known length *)
1661 Definition array_length_of_typedef
1662 : typedef_info -> option (option nat)
1663 := fun '(_, _, _, existT t bounds)
1664 => match t return ZRange.type.base.option.interp t -> option (option nat) with
1665 | base.type.list _ => fun bounds => Some (option_map (@List.length _) bounds)
1666 | _ => fun _ => None
1667 end bounds.
1668
1669 (** For the second part of the returned type, None means not
1670 array; Some None means array of unknown length; Some Some
1671 means array of known length *)
1672 Definition name_and_type_and_describe_typedef
1673 {language_naming_conventions : language_naming_conventions_opt}
1674 {documentation_options : documentation_options_opt}
1675 (prefix : string)
1676 (private : bool)
1677 (typedef : typedef_info)
1678 : string * (option int.type * option (option nat)) * list string
1679 := let name := name_of_typedef prefix private typedef in
1680 let description := describe_typedef prefix private typedef in
1681 let len := array_length_of_typedef typedef in
1682 let '(_, _, ty, _) := typedef in
1683 (name, (ty, len), description).
1684
1685 Definition format_special_function_name_ty
1686 {language_naming_conventions : language_naming_conventions_opt}
1687 (internal_private : bool)
1688 (prefix : string)
1689 (name : string)
1690 (t : int.type)
1691 : string
1692 := format_special_function_name internal_private prefix name (int.is_signed t) (int.bitwidth_of t).
1693
1694 Definition normalize_newlines (lines : list string)
1695 := String.split String.NewLine (String.concat String.NewLine lines).
1696
1697 Definition preprocess_comment_block (lines : list string) := normalize_newlines lines.
1698
1699 (** prepends [prefix] to the first line of [lines] (after
1700 processing it to adjust for newlines), and indents the rest of
1701 the lines appropriately *)
1702 Definition prefix_and_indent (prefix : string) (lines : list string)
1703 := let lines := normalize_newlines lines in
1704 match lines with
1705 | [] => [prefix]
1706 | val :: vals
1707 => let indent := String.repeat " " (String.length prefix) in
1708 (prefix ++ val)
1709 :: List.map (fun v => indent ++ v) vals
1710 end.
1711
1712 Class OutputLanguageAPI :=
1713 {
1714 (** [String.concat NewLine (comment_block lines)] should the
1715 the block-commented form of [String.concat NewLine lines].
1716 NewLines internal to elements in the list are allowed to
1717 be ignored / can be assumed to not be present. Callers
1718 who want to ensure correct commenting on unknown blocks of
1719 text should instead run [comment_block
1720 (preprocess_comment_block lines)]. *)
1721 comment_block : list string -> list string;
1722
1723 (** [String.concat NewLine (comment_file_header_block lines)]
1724 should the the block-commented form of [String.concat
1725 NewLine lines] which can be used for the header at the top
1726 of the file. NewLines internal to elements in the list
1727 are allowed to be ignored / can be assumed to not be
1728 present. Callers who want to ensure correct commenting on
1729 unknown blocks of text should instead run
1730 [comment_file_header_block (preprocess_comment_block
1731 lines)]. *)
1732 comment_file_header_block : list string -> list string;
1733
1734 (** Converts a PHOAS AST to lines of code * info on which
1735 primitive functions are called, or else an error string *)
1736 ToFunctionLines
1737 : forall {absint_opts : AbstractInterpretation.Options}
1738 {relax_zrange : relax_zrange_opt}
1739 {language_naming_conventions : language_naming_conventions_opt}
1740 {documentation_options : documentation_options_opt}
1741 {output_options : output_options_opt}
1742 (machine_wordsize : Z)
1743 (do_bounds_check : bool) (internal_private : bool) (private : bool) (all_private : bool) (inline : bool) (prefix : string) (name : string)
1744 {t}
1745 (e : @API.Expr t)
1746 (comment : type.for_each_lhs_of_arrow var_data t -> var_data (type.final_codomain t) -> list string)
1747 (name_list : option (list string))
1748 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1749 (outbounds : ZRange.type.base.option.interp (type.final_codomain t))
1750 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1751 (outtypedefs : base_var_typedef_data (type.final_codomain t)),
1752 (list string * ident_infos) + string;
1753
1754 (** Generates a header of any needed typedefs, etc based on the idents used and the curve-specific prefix *)
1755 header
1756 : forall {language_naming_conventions : language_naming_conventions_opt}
1757 {documentation_options : documentation_options_opt}
1758 {package_name : package_name_opt}
1759 {class_name : class_name_opt}
1760 {output_options : output_options_opt}
1761 (machine_wordsize : Z) (internal_private : bool) (private : bool) (prefix : string) (ident_info : ident_infos)
1762 (typedef_map : list typedef_info),
1763 list string;
1764
1765 (** The footer on the file, if any *)
1766 footer
1767 : forall {language_naming_conventions : language_naming_conventions_opt}
1768 {documentation_options : documentation_options_opt}
1769 {package_name : package_name_opt}
1770 {class_name : class_name_opt}
1771 (machine_wordsize : Z) (internal_private : bool) (private : bool) (prefix : string) (ident_info : ident_infos),
1772 list string;
1773
1774 (** Filters [ident_infos] to strip out primitive functions
1775 that we don't want to request (because they have special
1776 language handling) *)
1777 strip_special_infos
1778 : forall (machine_wordsize : Z),
1779 ident_infos -> ident_infos;
1780 }.
1781 End ToString.
1782 End Compilers.