Source

ocaml-cstruct-codegen / lib / cstruct_codegen.ml

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
type ftype_int =
  { getter : string
  ; setter : string
  ; sz : int
  ; ocamltype : string
  ; printer : string
  }
;

type ftype_enum =
  { enum_repr : ftype_int
  ; enum_name : string
  ; enum_elts : list (string * string)  (* like ("Myenum", "123L") *)
  }
;

type ftype =
  [ Fint of ftype_int
  | Fenum of ftype_enum
  ]
;


value enum_module fe = String.capitalize fe.enum_name
;

value enum_ocamltype fe = (enum_module fe) ^ ".t"
;

value ocamltype ftype =
  match ftype with
  [ Fint fi -> fi.ocamltype
  | Fenum fe -> enum_ocamltype fe
  ]
;

value printer ftype =
  match ftype with
  [ Fint fi -> fi.printer
  | Fenum fe -> (enum_module fe) ^ ".to_string"
  ]
;

(*
value field_of_num fld =
  match fld.ftype with
  [ Fint _ -> fld.fname
  | Fenum fe -> fe.enum_name ^ "_of_num"
  ]
;

value num_of_field fld =
  match fld.ftype with
  [ Fint _ -> fld.fname
  | Fenum fe -> "num_of_" ^ fe.enum_name
  ]
;
*)


type cfielddef = { fname : string ; ftype : ftype }
;

type cstructdef = (string * list cfielddef)
;

value cstructs = Queue.create ()
;

value cstruct name fields = Queue.push (name, fields) cstructs
;

value accessors_module = "ExtUnix.Specific.BA.LittleEndian"
;

value printers =
  [ ("int", "string_of_int")
  ; ("int32", "Int32.to_string")
  ; ("int64", "Int64.to_string")
  ]
;

value fld sz fn mlty =
  let fty = Fint
    { getter = accessors_module ^ ".unsafe_get_" ^ fn
    ; setter = accessors_module ^ ".unsafe_set_" ^ fn
    ; sz = sz
    ; ocamltype = mlty
    ; printer =
        try
          List.assoc mlty printers
        with
        [ Not_found ->
            failwith ("can't find printer for OCaml type " ^ mlty)
        ]
    }
  in
    fun n ->
      { fname = n
      ; ftype = fty
      }
;

(*                   bytes
                     |  getter-setter
                     |  |        ocaml type
                     |  |        |            *)
value int8_t   = fld 1  "int8"   "int"
  and uint8_t  = fld 1  "uint8"  "int"
  and int16_t  = fld 2  "int16"  "int"
  and uint16_t = fld 2  "uint16" "int"
  and int31_t  = fld 4  "int31"  "int"
  and int32_t  = fld 4  "int32"  "int32"
  and int64_t  = fld 8  "int64"  "int64"
;


(************************************************************)


value generate_always_queue = Queue.create ()
;


module Enum
 =
  struct

    type enum_type 'a =
      { et_ftype_int : ftype_int
      ; et_to_literal : 'a -> string
      ; et_first_val : 'a
      ; et_next_val : 'a -> 'a
      }
    ;

    value et_int fi =
      { et_ftype_int = fi
      ; et_to_literal = string_of_int
      ; et_first_val = 0
      ; et_next_val = succ
      }
    ;

    value et_int32 fi =
      { et_ftype_int = fi
      ; et_to_literal = fun x -> (Int32.to_string x) ^ "l"
      ; et_first_val = 0l
      ; et_next_val = Int32.add 1l
      }
    ;

    value et_int64 fi =
      { et_ftype_int = fi
      ; et_to_literal = fun x -> (Int64.to_string x) ^ "L"
      ; et_first_val = 0L
      ; et_next_val = Int64.add 1L
      }
    ;

    value of_cfield
     : (string -> cfielddef) -> (ftype_int -> enum_type 'a) -> enum_type 'a
     = fun cf et ->
         match (cf "").ftype with
         [ Fenum _ -> assert False
         | Fint fi -> et fi
         ]
    ;

    value int8_t   : enum_type int   = of_cfield int8_t   et_int  ;
    value uint8_t  : enum_type int   = of_cfield uint8_t  et_int  ;
    value int16_t  : enum_type int   = of_cfield int16_t  et_int  ;
    value uint16_t : enum_type int   = of_cfield uint16_t et_int  ;
    value int31_t  : enum_type int   = of_cfield int31_t  et_int  ;
    value int32_t  : enum_type int32 = of_cfield int32_t  et_int32;
    value int64_t  : enum_type int64 = of_cfield int64_t  et_int64;



    type enum_elt 'a =
      { ee_name : string
      ; ee_opt_val : option 'a
      }
    ;

    value elt ?v name = { ee_name = String.capitalize name ; ee_opt_val = v }
    ;

    value enum
      ?(generate_always=False)
      name (enumtype : enum_type 'a) (elts : list (enum_elt 'a))
     : string -> cfielddef
     =
      let fe =
        { enum_repr = enumtype.et_ftype_int
        ; enum_name = String.uncapitalize name
        ; enum_elts =
            let cur = ref enumtype.et_first_val in
            List.map
              (fun elt ->
                 let v =
                   match elt.ee_opt_val with
                   [ Some v ->
                       ( cur.val := enumtype.et_next_val v
                       ; v
                       )
                   | None ->
                       let c = cur.val in
                       let () = cur.val := enumtype.et_next_val cur.val in
                       c
                   ]
                 in
                 (String.capitalize elt.ee_name, enumtype.et_to_literal v)
              )
              elts
        }
      in
      let () =
        if generate_always
        then Queue.push fe generate_always_queue
        else ()
      in
      let ftype = Fenum fe
      in
        fun fieldname -> { fname = fieldname ; ftype = ftype }
    ;

  end
;


(************************************************************)

open Printf
;

value module_ name sig_ struct_ =
  sprintf "\
 module %s\n\
\ :\n\
\  sig\n%s\
\  end\n\
\ =\n\
\  struct\n%s\
\  end\n\n"
    (String.capitalize name) sig_ struct_
;


value list_iteri f l =
  loop l 0
  where rec loop l i =
    match l with
    [ [] -> ()
    | [h :: t] -> (f i h; loop t (i+1))
    ]
;


value string_of_cstructdef (csname, csfields) =
  let sig__ = ref ""
  and str__ = ref "" in
  let add strref fmt =
    Printf.ksprintf
      (fun str ->
         strref.val :=
             strref.val
           ^ (if str = "" then "" else "    ")
           ^ str
           ^ "\n"
      )
      fmt
  in
  let str_ fmt = add str__ fmt
  and sig_ fmt = add sig__ fmt in
  let rec ident base =
    if List.exists (fun f -> base = f.fname) csfields
    then ident (base ^ "'")
    else base
  in
  let ident_t = ident "t" in
  let cur_ofs = ref 0 in
  let ba_type =
    "(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t"
  and ba_create = "Bigarray.Array1.create Bigarray.char Bigarray.c_layout" in
  ( sig_ ""
  ; sig_ "(* Abstract data type to represent values of C-like structure '%s' *)"
      csname
  ; sig_ "type t"
  ; str_ "type t = %s" ba_type
  ; sig_ ""
  ; sig_ "(* size of structure [t] in bytes *)"
  ; sig_ "val sizeof : int"
  ; sig_ ""
  ; sig_ "(* Creates a value of type [t] on bigarray of size [sizeof]."
  ; sig_ "   one can modify bigarray, and these modifications will"
  ; sig_ "   affect fields of created value (they will be visible with"
  ; sig_ "   get_<field> or [dump])."
  ; sig_ "   Raises [Failure] on size mismatch. *)"
  ; sig_ "val of_bigarray : %s -> t" ba_type

  ; sig_ ""
  ; sig_ "(* [bigarray_of s] returns bigarray containing all fields of [s]"
  ; sig_ "   in C-like layout. *)"
  ; sig_ "val bigarray_of : t -> %s" ba_type
  ; str_ "let bigarray_of t = t"

  ; sig_ ""
  ; sig_ "(* [create ()] creates an uninitialized structure of type [t]."
  ; sig_ "   It can be useful when:"
  ; sig_ "   - one wants to set all fields manually with setters"
  ; sig_ "     (however consider [make] function below, it gives guarantees"
  ; sig_ "     that every field is initialized)"
  ; sig_ "   - one wants to modify structure's bigarray (returned by"
  ; sig_ "     [bigarray_of]): fill it from file, socket etc. *)"
  ; sig_ "val create : unit -> t"

  ; sig_ ""
  ; sig_ "(* getters and setters: *)"
  ; str_ ""

  ; let for_field { fname = fname ; ftype = ftype_gen } =
      let gen_get_set ~ftype ~fname =
        let getter = "get_" ^ fname
        and setter = "set_" ^ fname in
        ( sig_
            "val %s : t -> %s"
            getter ftype.ocamltype
        ; sig_
            "val %s : t -> %s -> unit"
            setter ftype.ocamltype
        ; str_
            "let %s t = %s t %i"
            getter ftype.getter cur_ofs.val
        ; str_
            "let %s t v = %s t %i v"
            setter ftype.setter cur_ofs.val
        ; cur_ofs.val := cur_ofs.val + ftype.sz
        )
      in
      match ftype_gen with
      [ Fint ftype ->
          gen_get_set ~ftype ~fname
      | Fenum fe ->
          ( gen_get_set ~ftype:fe.enum_repr ~fname:(fname ^ "_num")

          ; sig_ "val get_%s_exn : t -> %s"
              fname (enum_ocamltype fe)
          ; str_ "let get_%s_exn t = %s.of_num_exn (get_%s_num t)"
              fname (enum_module fe) fname

          ; sig_ "val get_%s_res : t -> [ `Ok of %s | `Error of %s ]"
              fname (enum_ocamltype fe) fe.enum_repr.ocamltype
          ; str_ "let get_%s_res t = %s.of_num_res (get_%s_num t)"
              fname (enum_module fe) fname

          ; sig_ "val set_%s : t -> %s -> unit"
              fname (enum_ocamltype fe)
          ; str_ "let set_%s t v = set_%s_num t (%s.num_of v)"
              fname fname (enum_module fe)
          )
      ]
    in
      List.iter for_field csfields

  ; str_ "let sizeof = %i" cur_ofs.val

  ; str_ ""
  ; str_ "let of_bigarray t ="
  ; str_ "  if Bigarray.Array1.dim t <> sizeof"
  ; str_ "  then failwith \"%s.of_bigarray: size doesn't match\""
                  (String.capitalize csname)
  ; str_ "  else t"

  ; str_ ""
  ; str_ "let create () = %s sizeof" ba_create

  ; sig_ ""
  ; sig_ "(* makes a value of type [t] and initializes it with"
  ; sig_ "   field values passed as labelled arguments. *)"
  ; sig_ "val make : %st"
      (String.concat ""
         (List.map
            (fun fld ->
               fld.fname ^ ":" ^ (ocamltype fld.ftype) ^ " -> "
            )
            csfields
         )
      )
  ; str_ ""
  ; str_ "let make %s ="
      (String.concat " " (List.map (fun f -> "~" ^ f.fname) csfields))
  ; str_ "  let %s = %s sizeof in" ident_t ba_create
  ; str_ "  ("
  ; List.iter
     (fun f -> str_ "    set_%s %s %s;" f.fname ident_t f.fname
     )
     csfields
  ; str_ "    %s" ident_t
  ; str_ "  )"

  ; sig_ ""
  ; sig_ "(* dumps a value of type [t] to string, result looks like"
  ; sig_ "   \"{ a=1 ; b=3456 ; c=Myenumelement }\" *)"
  ; sig_ "val dump : t -> string"
  ; str_ ""
  ; str_ "let dump t ="
  ; str_ "  let b = Buffer.create 50 in"
  ; str_ "  ("
  ; list_iteri
     (fun i f ->
        ( str_ "    Buffer.add_string b %S;"
            ((if i = 0 then "{ " else " ; ") ^ f.fname ^ "=")
        ; str_ "    Buffer.add_string b (%s);"
            (match f.ftype with
             [ Fint _ ->
                 Printf.sprintf "%s (get_%s t)" (printer f.ftype) f.fname
             | Fenum fe ->
                 Printf.sprintf
                   "try %s.to_string (get_%s_exn t) with Enum (_, v) -> v"
                   (enum_module fe) f.fname
             ]
            )
        )
     )
     csfields
  ; str_ "    Buffer.add_string b %S;" " }"
  ; str_ "    Buffer.contents b"
  ; str_ "  )"

  ; module_ csname sig__.val str__.val
  )
;

value codegen_cstruct outch (cs : cstructdef) =
  output_string outch (string_of_cstructdef cs)
;

value enum_exn_written = ref False
;
value write_enum_exn outch =
  if enum_exn_written.val
  then ()
  else
    ( output_string outch "\
(* exception [Enum (\"myenum\", \"badvalue\")] is raised when \"badvalue\"\n\
\   is not convertible to value enum type \"myenum\".\n\
\   \"badvalue\" is a string to cover cases \"123\", \"123l\" and \"123L\".\n\
\ *)\n\
exception Enum of (string * string)\n\n"
    ; enum_exn_written.val := True
    )
;

value codegen_enum outch fe =
  let () = write_enum_exn outch in
  let str_ fmt = Printf.ksprintf
    (fun s -> output_string outch
       ((if s = "" then "" else "    " ^ s) ^ "\n")
    ) fmt
  in
  ( output_string outch ("module " ^ (enum_module fe) ^ "\n\
\ =\n\
\  struct\n\n")

  ; str_ "type t ="
  ; List.iter
      (fun (elt_name, _elt_lit) ->
         str_ "  | %s" elt_name
      )
      fe.enum_elts
  ; str_ ""

  ; str_ "let of_num_exn = function"
  ; List.iter
      (fun (elt_name, elt_lit) ->
         str_ "  | %s -> %s"
           elt_lit elt_name
      )
      fe.enum_elts
  ; str_ "  | v -> raise (Enum (%S, %s v))"
      fe.enum_name fe.enum_repr.printer
  ; str_ ""

  ; List.iter
      (fun (elt_name, _elt_lit) ->
         str_ "let ok_%s = `Ok %s"
           elt_name elt_name
      )
      fe.enum_elts
  ; str_ ""

  ; str_ "let of_num_res = function"
  ; List.iter
      (fun (elt_name, elt_lit) ->
         str_ "  | %s -> ok_%s"
           elt_lit elt_name
      )
      fe.enum_elts
  ; str_ "  | v -> `Error v"
  ; str_ ""

  ; str_ "let num_of = function"
  ; List.iter
      (fun (elt_name, elt_lit) ->
         str_ "  | %s -> %s"
           elt_name elt_lit
      )
      fe.enum_elts
  ; str_ ""

  ; str_ "let to_string = function"
  ; List.iter
      (fun (elt_name, _elt_lit) ->
         str_ "  | %s -> %S"
           elt_name elt_name
      )
      fe.enum_elts
  ; str_ ""

  ; output_string outch "\
\  end\n\n"
  )
;


value codegen_enums outch =
  let generated = Hashtbl.create 7 in
  let maybe_gen fe =
    if not (Hashtbl.mem generated fe.enum_name)
    then
      ( codegen_enum outch fe
      ; Hashtbl.add generated fe.enum_name ()
      )
    else
      ()
  in
  let () = Queue.iter maybe_gen generate_always_queue in
  Queue.iter
    (fun (_csname, csfields) ->
       List.iter
         (fun fld ->
            match fld.ftype with
            [ Fint _ -> ()
            | Fenum fe -> maybe_gen fe
            ]
         )
         csfields
    )
    cstructs
;


value codegen filename =
  let outch = open_out filename in
  let () = codegen_enums outch in
  let () = Queue.iter (codegen_cstruct outch) cstructs in
  close_out outch
;