Debian Codegraph @

src/Stringification/JSON.v

raw
1 From Coq Require Import ZArith MSetPositive FMapPositive
2 String Ascii Bool List HexString.
3 From Crypto.Util Require Import
4 ListUtil
5 Strings.String Strings.Decimal Strings.Show
6 ZRange.Operations ZRange.Show
7 OptionList Bool.Equality.
8 Require Import Crypto.Util.Option.
9 (* Work around COQBUG(https://github.com/coq/coq/issues/12251) *)
10 Require Import Crypto.Util.ZRange.
11
12 From Crypto Require Import IR Stringification.Language AbstractInterpretation.ZRange.
13
14 Import ListNotations.
15
16 Local Open Scope string_scope.
17 Local Open Scope list_scope.
18 Local Open Scope zrange_scope.
19 Local Open Scope Z_scope.
20
21 Import IR.Compilers.ToString.
22 Import Stringification.Language.Compilers.
23 Import Stringification.Language.Compilers.Options.
24 Import Stringification.Language.Compilers.ToString.
25 Import Stringification.Language.Compilers.ToString.int.Notations.
26
27 Module JSON.
28 Definition indent (indent : string) : list string -> list string
29 := List.map (fun s => indent ++ s)%string.
30
31 Definition int_bitwidth_to_string (signed : bool) (bitwidth : Z) : string :=
32 ((if signed then "i" else "u")
33 ++ Decimal.Z.to_string bitwidth)%string.
34
35 Definition int_type_to_string (t : ToString.int.type) : string :=
36 int_bitwidth_to_string (ToString.int.is_signed t) (ToString.int.bitwidth_of t).
37
38 Definition primitive_type_to_string (t : IR.type.primitive)
39 (r : option ToString.int.type) : string :=
40 match t with
41 | IR.type.Zptr => "*"
42 | IR.type.Z => ""
43 end ++ match r with
44 | Some int_t => int_type_to_string int_t
45 | None => "(auto)"
46 end.
47
48 Definition int_literal_to_string (t : IR.type.primitive) (v : BinInt.Z) : string :=
49 match t with
50 | IR.type.Z => HexString.of_Z v
51 | IR.type.Zptr => "#error ""literal address " ++ HexString.of_Z v ++ """;"
52 end.
53
54 Import IR.Notations.
55
56 Record op_data :=
57 { datatype : string ; name : list string ; operation : string ; parameters : list (string * string) ; arguments : list (list string) }.
58
59 Definition comma_concat (ls : list (list string)) : list string
60 := let ret := List.flat_map (fun s => match s with
61 | [] => []
62 | _ => s ++ [","]
63 end) ls in
64 (* drop the final , *)
65 List.firstn (List.length ret - 1) ret.
66
67 Definition op_data_to_JSON (v : op_data) : list string
68 := (["{"
69 ; " ""datatype"": """ ++ v.(datatype) ++ ""","
70 ; " ""name"": [" ++ String.concat ", " (List.map (fun n => """" ++ n ++ """")%string v.(name)) ++ "],"
71 ; " ""operation"": """ ++ v.(operation) ++ ""","
72 ]%string)
73 ++ match v.(parameters) with
74 | [] => []
75 | _ =>
76 [" ""parameters"": {" ++ String.concat ", " (List.map (fun '(n, val) => """" ++ n ++ """: " ++ val)%string v.(parameters)) ++ "},"]%string
77 end
78 ++ [" ""arguments"": ["]
79 ++ (indent " " (comma_concat v.(arguments)))
80 ++ [" ]"
81 ; "}"].
82
83 Fixpoint arith_to_string (outargs : list string)
84 {t} (sz : option ToString.int.type)
85 (e : IR.arith_expr t)
86 : list (list string)
87 := let handle_op sz op params outargs inargs
88 := [op_data_to_JSON
89 {| datatype := match sz with None => "(auto)" | Some ty => int_type_to_string ty end
90 ; name := outargs
91 ; operation := op
92 ; parameters := params
93 ; arguments := inargs |}] in
94 let handle_op_size lg2s op outargs inargs
95 := handle_op sz op [("size", Decimal.show_Z lg2s)] outargs inargs in
96 let handle_op1 op {t} inargs
97 := handle_op sz op [] outargs (@arith_to_string [] t sz inargs) in
98 let wrap_value res
99 := match outargs with
100 | [] => res
101 | _ => handle_op sz "=" [] outargs res
102 end in
103 match e with
104 (* integer literals *)
105 | (IR.literal v @@@ _)
106 => wrap_value [ ["""" ++ int_literal_to_string IR.type.Z v ++ """"] ]
107 (* array dereference *)
108 | (IR.List_nth n @@@ IR.Var _ v)
109 => wrap_value [ ["""" ++ v ++ "[" ++ Decimal.Z.to_string (Z.of_nat n) ++ "]"""] ]
110 (* (de)referencing *)
111 | (IR.Addr @@@ IR.Var _ v)
112 => wrap_value [ ["""&" ++ v ++ """"] ]
113 | (IR.Dereference @@@ IR.Var _ v)
114 => wrap_value [ ["""*" ++ v ++ """"] ]
115 | (IR.Dereference @@@ e)
116 => handle_op sz "dereference" [] [] (arith_to_string [] sz e)
117 (* bitwise operations *)
118 | (IR.Z_shiftr offset @@@ e)
119 => handle_op sz ">>" [] outargs
120 ((arith_to_string [] sz e)
121 ++ [ ["""" ++ Decimal.Z.to_string offset ++ """"]%string ])%list
122 | (IR.Z_shiftl offset @@@ e)
123 => handle_op sz "<<" [] outargs
124 ((arith_to_string [] sz e)
125 ++ [ ["""" ++ Decimal.Z.to_string offset ++ """"]%string ])%list
126 | (IR.Z_land @@@ args)
127 => handle_op1 "&" args
128 | (IR.Z_lor @@@ args)
129 => handle_op1 "|" args
130 | (IR.Z_lxor @@@ args)
131 => handle_op1 "^" args
132 | (IR.Z_lnot _ @@@ args)
133 => handle_op1 "~" args
134 (* arithmetic operations *)
135 | (IR.Z_add @@@ args)
136 => handle_op1 "+" args
137 | (IR.Z_mul @@@ args)
138 => handle_op1 "*" args
139 | (IR.Z_sub @@@ args)
140 => handle_op1 "-" args
141 | (IR.Z_bneg @@@ args)
142 => handle_op1 "!" args
143 | (IR.Z_mul_split lg2s @@@ ((IR.Addr @@@ IR.Var _ x1, IR.Addr @@@ IR.Var _ x2), args))
144 => let sz' := Some (int.of_bitwidth_up false lg2s) in
145 wrap_value (handle_op_size lg2s "mulx" [x1; x2] (arith_to_string [] sz' args))
146 | (IR.Z_add_with_get_carry lg2s @@@ ((IR.Addr @@@ IR.Var _ x1, IR.Addr @@@ IR.Var _ x2), args))
147 => let sz' := Some (int.of_bitwidth_up false lg2s) in
148 wrap_value (handle_op_size lg2s "addcarryx" [x1; x2] (arith_to_string [] sz' args))
149 | (IR.Z_sub_with_get_borrow lg2s @@@ ((IR.Addr @@@ IR.Var _ x1, IR.Addr @@@ IR.Var _ x2), args))
150 => let sz' := Some (int.of_bitwidth_up false lg2s) in
151 wrap_value (handle_op_size lg2s "subborrowx" [x1; x2] (arith_to_string [] sz' args))
152 | (IR.Z_value_barrier ty @@@ args) => arith_to_string outargs sz args
153 | (IR.Z_zselect ty @@@ (IR.Addr @@@ IR.Var _ v, args))
154 => wrap_value (handle_op (Some ty) "cmovznz" [] [v] (arith_to_string [] (Some ty) args))
155 | (IR.Z_static_cast int_t @@@ args)
156 => handle_op (Some int_t) "static_cast" [] outargs (arith_to_string [] (Some int_t) args)
157 | IR.Var _ v
158 => wrap_value [ [ """" ++ v ++ """" ] ]
159 | IR.Pair A B a b
160 => wrap_value (arith_to_string [] sz a ++ arith_to_string [] sz b)%list
161 | (IR.Z_add_modulo @@@ _)
162 => wrap_value [ [ "#error addmodulo" ] ]
163 | (IR.List_nth _ @@@ _)
164 | (IR.Addr @@@ _)
165 | (IR.Z_mul_split _ @@@ _)
166 | (IR.Z_add_with_get_carry _ @@@ _)
167 | (IR.Z_sub_with_get_borrow _ @@@ _)
168 | (IR.Z_zselect _ @@@ _)
169 => wrap_value [ [ "#error bad_arg" ] ]
170 | IR.TT => wrap_value [ [ "#error tt" ] ]
171 end%string%Cexpr.
172
173 Definition stmt_to_string (e : IR.stmt) : list string
174 := List.concat
175 match e with
176 | IR.Call val
177 => arith_to_string [] None val
178 | IR.Assign _ _ sz name val
179 => arith_to_string [name] sz val
180 | IR.AssignZPtr name sz val
181 => arith_to_string [name] sz val
182 | IR.AssignNth name n val
183 => let name := (name ++ "[" ++ Decimal.Z.to_string (Z.of_nat n) ++ "]")%string in
184 arith_to_string [name] None val
185 | IR.DeclareVar _ _ _
186 | IR.Comment _ _
187 => []
188 end.
189
190 Definition to_strings (e : IR.expr) : list string :=
191 comma_concat (List.map stmt_to_string e).
192
193
194 Import Rewriter.Language.Language.Compilers Crypto.Language.API.Compilers IR.OfPHOAS.
195
196 Local Notation tZ := (base.type.type_base base.type.Z).
197 Local Notation None_object := "null" (only parsing).
198 Local Notation quote_string s := ("""" ++ s ++ """")%string (only parsing).
199
200 Fixpoint to_base_arg_list {t} : base_var_data t -> Compilers.ZRange.type.base.option.interp t -> list (string * string * (string * string))
201 := let show_Z s := quote_string (Hex.show_Z s) in
202 let opt_to_json T f (b : option T) :=
203 match b with
204 | None => (None_object, None_object)
205 | Some v => f v
206 end in
207 let zrange_to_json b :=
208 (show_Z b.(lower), show_Z b.(upper)) in
209 let opt_zrange_to_json b :=
210 opt_to_json _ zrange_to_json b in
211 let opt_zrange_list_to_json ls :=
212 let ls := List.map opt_zrange_to_json ls in
213 ("[" ++ String.concat ", " (List.map (@fst _ _) ls) ++ "]",
214 "[" ++ String.concat ", " (List.map (@snd _ _) ls) ++ "]")%string in
215 let opt_opt_zrange_list_to_json ls :=
216 opt_to_json _ opt_zrange_list_to_json ls in
217 match t return base_var_data t -> Compilers.ZRange.type.base.option.interp t -> _ with
218 | tZ
219 => fun '(n, is_ptr, r, typedef) b
220 => [(primitive_type_to_string IR.type.Z r, n, opt_zrange_to_json b)]
221 | base.type.prod A B
222 => fun '(va, vb) '(ba, bb) => (@to_base_arg_list A va ba ++ @to_base_arg_list B vb bb)%list
223 | base.type.list tZ
224 => fun '(n, r, len, typedef) b
225 => [(primitive_type_to_string IR.type.Z r ++ "[" ++ Decimal.Z.to_string (Z.of_nat len) ++ "]", n,
226 opt_opt_zrange_list_to_json b)]
227 | base.type.list _ => fun _ _ => [("#error ""complex list""", "", (None_object, None_object))]
228 | base.type.option _ => fun _ _ => [("#error option", "", (None_object, None_object))]
229 | base.type.unit => fun _ _ => [("#error unit", "", (None_object, None_object))]
230 | base.type.type_base t => fun _ _ => [("#error " ++ show t, "", (None_object, None_object))]
231 end%string.
232
233 Definition to_arg_list {t} : var_data t -> Compilers.ZRange.type.option.interp t -> list (string * string * (string * string)) :=
234 match t return var_data t -> Compilers.ZRange.type.option.interp t -> _ with
235 | type.base t => to_base_arg_list
236 | type.arrow _ _ => fun _ _ => [("#error arrow", "", (None_object, None_object))]
237 end%string.
238
239 Fixpoint to_arg_list_for_each_lhs_of_arrow {t} : type.for_each_lhs_of_arrow var_data t -> type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t -> list (string * string * (string * string))
240 := match t return type.for_each_lhs_of_arrow _ t -> type.for_each_lhs_of_arrow _ t -> _ with
241 | type.base t => fun _ _ => nil
242 | type.arrow s d
243 => fun '(x, xs) '(b, bs)
244 => to_arg_list x b ++ @to_arg_list_for_each_lhs_of_arrow d xs bs
245 end%list.
246
247 (** * Language-specific numeric conversions to be passed to the PHOAS -> IR translation *)
248
249 Definition JSON_bin_op_natural_output
250 : IR.Z_binop -> ToString.int.type * ToString.int.type -> ToString.int.type
251 := fun idc '(t1, t2)
252 => ToString.int.union t1 t2.
253
254 (* Does the binary operation commute with (-- mod 2^bw)? *)
255 Definition bin_op_commutes_with_mod_pow2 (idc : IR.Z_binop)
256 := match idc with
257 | IR.Z_land
258 | IR.Z_lor
259 | IR.Z_lxor
260 | IR.Z_add
261 | IR.Z_mul
262 | IR.Z_sub
263 => true
264 end.
265
266 Definition JSON_bin_op_casts
267 : IR.Z_binop -> option ToString.int.type -> ToString.int.type * ToString.int.type -> option ToString.int.type * (option ToString.int.type * option ToString.int.type)
268 := fun idc desired_type '(t1, t2)
269 => match desired_type with
270 | Some desired_type
271 => let ct := ToString.int.union t1 t2 in
272 if bin_op_commutes_with_mod_pow2 idc
273 then
274 (* these operations commute with mod, so we just pre-cast them *)
275 (None, (Some desired_type, Some desired_type))
276 else
277 let desired_type' := Some (ToString.int.union ct desired_type) in
278 (desired_type',
279 (get_Zcast_up_if_needed desired_type' (Some t1),
280 get_Zcast_up_if_needed desired_type' (Some t2)))
281 | None => (None, (None, None))
282 end.
283
284 Definition JSON_un_op_casts
285 : IR.Z_unop -> option ToString.int.type -> ToString.int.type -> option ToString.int.type * option ToString.int.type
286 := fun idc desired_type t
287 => match idc with
288 | IR.Z_shiftr offset
289 => (** N.B. We must cast the expression up to a large
290 enough type to fit 2^offset (importantly, not just
291 2^offset-1), because C considers it to be undefined
292 behavior to shift >= width of the type. We should
293 probably figure out how to not generate these
294 things in the first place...
295
296 N.B. We must preserve signedness of the value being
297 shifted, because shift does not commute with
298 mod. *)
299 let t' := ToString.int.union_zrange r[0~>2^offset]%zrange t in
300 ((** We cast the result down to the specified type, if needed *)
301 get_Zcast_down_if_needed desired_type (Some t'),
302 (** We cast the argument up to a large enough type *)
303 get_Zcast_up_if_needed (Some t') (Some t))
304 | IR.Z_shiftl offset
305 => (** N.B. We must cast the expression up to a large
306 enough type to fit 2^offset (importantly, not just
307 2^offset-1), because C considers it to be undefined
308 behavior to shift >= width of the type. We should
309 probably figure out how to not generate these
310 things in the first place...
311
312 N.B. We make sure that we only left-shift unsigned
313 values, since shifting into the sign bit is
314 undefined behavior. *)
315 let rpre_out := match desired_type with
316 | Some rout => Some (ToString.int.union_zrange r[0~>2^offset] (ToString.int.unsigned_counterpart_of rout))
317 | None => Some (ToString.int.of_zrange_relaxed r[0~>2^offset]%zrange)
318 end in
319 ((** We cast the result down to the specified type, if needed *)
320 get_Zcast_down_if_needed desired_type rpre_out,
321 (** We cast the argument up to a large enough type *)
322 get_Zcast_up_if_needed rpre_out (Some t))
323 | IR.Z_lnot ty
324 => ((* if the result is too big, we cast it down; we
325 don't need to upcast it because it'll get
326 picked up by implicit casts if necessary *)
327 get_Zcast_down_if_needed desired_type (Some ty),
328 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)
329 Some ty)
330 | IR.Z_value_barrier ty
331 => ((* if the result is too big, we cast it down; we
332 don't need to upcast it because it'll get
333 picked up by implicit casts if necessary *)
334 get_Zcast_down_if_needed desired_type (Some ty),
335 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles *)
336 Some ty)
337 | IR.Z_bneg
338 => ((* bneg is !, i.e., takes the argument to 1 if its not zero, and to zero if it is zero; so we don't ever need to cast *)
339 None, None)
340 end.
341
342 Local Instance JSONLanguageCasts : LanguageCasts :=
343 {| bin_op_natural_output := JSON_bin_op_natural_output
344 ; bin_op_casts := JSON_bin_op_casts
345 ; un_op_casts := JSON_un_op_casts
346 ; upcast_on_assignment := true
347 ; upcast_on_funcall := true
348 ; explicit_pointer_variables := false
349 |}.
350
351 Definition to_function_lines (static : bool) (inline : bool) (name : string)
352 {t}
353 (inbounds : type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t)
354 (outbounds : Compilers.ZRange.type.base.option.interp (type.final_codomain t))
355 (f : type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * IR.expr)
356 : list string :=
357 let '(args, rets, body) := f in
358 let args_list_to_string ls
359 := ("["
360 ++ (String.concat
361 ", "
362 (List.map
363 (fun '(typ, name, (lbound, ubound)) => "{""datatype"": """ ++ typ ++ """, ""name"": """ ++ name ++ """, ""lbound"": " ++ lbound ++ ", ""ubound"": " ++ ubound ++ "}")
364 ls))
365 ++ "]")%string in
366 ["{"]
367 ++ (["""operation"": """ ++ name ++ ""","
368 ; """arguments"": " ++ args_list_to_string (to_arg_list_for_each_lhs_of_arrow args inbounds) ++ ","
369 ; """returns"": " ++ args_list_to_string (to_arg_list rets outbounds) ++ ","
370 ; """body"": ["]%string)
371 ++ to_strings body
372 ++ ["]"
373 ; "}"].
374
375 (** We will treat all dead variables as _ *)
376 Local Instance : consider_retargs_live_opt := fun _ _ _ => false.
377 Local Instance : rename_dead_opt := fun s => "_".
378 (** No need to lift declarations to the top *)
379 Local Instance : lift_declarations_opt := false.
380
381 Definition ToFunctionLines
382 {absint_opts : AbstractInterpretation.Options}
383 {relax_zrange : relax_zrange_opt}
384 {language_naming_conventions : language_naming_conventions_opt}
385 {documentation_options : documentation_options_opt}
386 {output_options : output_options_opt}
387 (machine_wordsize : Z)
388 (do_bounds_check : bool) (internal_static : bool) (static : bool) (all_static : bool) (inline : bool) (prefix : string) (name : string)
389 {t}
390 (e : API.Expr t)
391 (comment : type.for_each_lhs_of_arrow var_data t -> var_data (type.base (type.final_codomain t)) -> list string)
392 (name_list : option (list string))
393 (inbounds : type.for_each_lhs_of_arrow Compilers.ZRange.type.option.interp t)
394 (outbounds : Compilers.ZRange.type.base.option.interp (type.final_codomain t))
395 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
396 (outtypedefs : base_var_typedef_data (type.final_codomain t))
397 : (list string * ToString.ident_infos) + string :=
398 match ExprOfPHOAS do_bounds_check e name_list inbounds intypedefs outtypedefs with
399 | inl (indata, outdata, f) =>
400 inl (to_function_lines
401 static inline name
402 inbounds
403 outbounds
404 (indata, outdata, f),
405 IR.ident_infos.collect_all_infos f intypedefs outtypedefs)
406 | inr nil =>
407 inr ("Unknown internal error in converting " ++ name ++ " to JSON")%string
408 | inr [err] =>
409 inr ("Error in converting " ++ name ++ " to JSON:" ++ String.NewLine ++ err)%string
410 | inr errs =>
411 inr ("Errors in converting " ++ name ++ " to JSON:" ++ String.NewLine ++ String.concat String.NewLine errs)%string
412 end.
413
414 Definition OutputJSONAPI : ToString.OutputLanguageAPI :=
415 {| ToString.comment_block _ := [];
416 ToString.comment_file_header_block _ := [];
417 ToString.ToFunctionLines := @ToFunctionLines;
418 ToString.header := fun _ _ _ _ _ _ _ _ _ _ _ => [];
419 ToString.footer := fun _ _ _ _ _ _ _ _ _ => [];
420 (** No special handling for any functions *)
421 ToString.strip_special_infos machine_wordsize infos := infos |}.
422
423 End JSON.