cprinter.ml 44.5 KB
Newer Older
Andrei Paskevich's avatar
Andrei Paskevich committed
1 2 3
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
Guillaume Melquiond's avatar
Guillaume Melquiond committed
4
(*  Copyright 2010-2018   --   Inria - CNRS - Paris-Sud University  *)
Andrei Paskevich's avatar
Andrei Paskevich committed
5 6 7 8 9 10 11
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
(*                                                                  *)
(********************************************************************)

12
open Ident
13

14 15
exception Unsupported of string

16
module C = struct
17

18 19 20
  type struct_def = string * (string * ty) list

  and ty =
21
    | Tvoid
22
    | Tsyntax of string * ty list
23 24
    | Tptr of ty
    | Tarray of ty * expr
25
    | Tstruct of struct_def
26 27
    | Tunion of ident * (ident * ty) list
    | Tnamed of ident (* alias from typedef *)
28
    | Tnosyntax (* types that do not have a syntax, can't be printed *)
29 30 31 32 33 34 35 36 37 38 39
    (* enum, const could be added *)

  (* int x=2, *y ... *)
  and names = ty * (ident * expr) list

  (* names with a single declaration *)
  and name = ty * ident * expr

  (* return type, parameter list. Variadic functions not handled. *)
  and proto = ty * (ty * ident) list

40 41
  and binop = Band | Bor | Beq | Bne | Bassign | Blt | Ble | Bgt | Bge
  (* += and co. maybe to add *)
42

43
  and unop = Unot | Ustar | Uaddr | Upreincr | Upostincr | Upredecr | Upostdecr
44 45 46 47 48

  and expr =
    | Enothing
    | Eunop of unop * expr
    | Ebinop of binop * expr * expr
49
    | Equestion of expr * expr * expr (* c ? t : e *)
50 51 52
    | Ecast of ty * expr
    | Ecall of expr * expr list
    | Econst of constant
53
    | Evar of ident
54 55
    | Elikely of expr (* __builtin_expect(e,1) *)
    | Eunlikely of expr (* __builtin_expect(e,0) *)
56 57 58
    | Esize_expr of expr
    | Esize_type of ty
    | Eindex of expr * expr (* Array access *)
59 60
    | Edot of expr * string (* Field access with dot *)
    | Earrow of expr * string (* Pointer access with arrow *)
61 62 63
    | Esyntax of string * ty * (ty array) * (expr*ty) list * bool
  (* template, type and type arguments of result, typed arguments,
     is/is not converter*)
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

  and constant =
    | Cint of string
    | Cfloat of string
    | Cchar of string
    | Cstring of string

  type stmt =
    | Snop
    | Sexpr of expr
    | Sblock of body
    | Sseq of stmt * stmt
    | Sif of expr * stmt * stmt
    | Swhile of expr * stmt
    | Sfor of expr * expr * expr * stmt
    | Sbreak
    | Sreturn of expr

82
  and include_kind = Sys | Proj (* include <...> vs. include "..." *)
83
  and definition =
84
    | Dfun of ident * proto * body
85
    | Dinclude of ident * include_kind
86
    | Dproto of ident * proto
87
    | Ddecl of names
88
    | Dstruct of struct_def
89
    | Dstruct_decl of string
90 91 92 93 94 95
    | Dtypedef of ty * ident

  and body = definition list * stmt

  type file = definition list

96 97
  exception NotAValue

98 99 100 101 102 103
  let rec is_nop = function
    | Snop -> true
    | Sblock ([], s) -> is_nop s
    | Sseq (s1,s2) -> is_nop s1 && is_nop s2
    | _ -> false

104 105 106 107 108 109 110 111
  let is_true = function
    | Sexpr(Econst(Cint "1")) -> true
    | _ -> false

  let is_false = function
    | Sexpr(Econst(Cint "0")) -> true
    | _ -> false

112 113 114 115 116 117
  let rec one_stmt = function
    | Snop -> true
    | Sexpr _ -> true
    | Sblock (d,s) -> d = [] && one_stmt s
    | _ -> false

Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
118 119 120
  (** [assignify v] transforms a statement that computes a value into
     a statement that assigns that value to v *)
  let rec assignify v = function
121
    | Snop -> raise NotAValue
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
122 123 124 125 126 127 128
    | Sexpr e -> Sexpr (Ebinop (Bassign, v, e))
    | Sblock (ds, s) -> Sblock (ds, assignify v s)
    | Sseq (s1, s2) when not (is_nop s2) -> Sseq (s1, assignify v s2)
    | Sseq (s1,_) -> assignify v s1
    | Sif (c,t,e) -> Sif (c, assignify v t, assignify v e)
    | Swhile (c,s) -> Swhile (c, assignify v s) (* can this be a value ?*)
    | Sfor (e0,e1,e2,s) -> Sfor (e0,e1,e2, assignify v s)
129 130 131
    | Sbreak -> raise NotAValue
    | Sreturn _ -> raise NotAValue

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

  (** [get_last_expr] extracts the expression computed by the given statement.
     This is needed when loop conditions are more complex than a simple expression. *)
  let rec get_last_expr = function
    | Snop -> raise NotAValue
    | Sexpr e -> Snop, e
    | Sblock (ds,s) ->
      let s',e = get_last_expr s in
      Sblock(ds,s'), e
    | Sseq (s1,s2) when not (is_nop s2) ->
      let s', e = get_last_expr s2 in
      Sseq(s1,s'), e
    | Sseq (s1,_) -> get_last_expr s1
    | Sif (c,Sexpr t,Sexpr e) -> Snop, Equestion(c,t,e)
    | Sif _ -> raise (Unsupported "while (complex if)")
    | Swhile (_c,_s) -> raise (Unsupported "while (while) {}")
    | Sfor _ -> raise (Unsupported "while (for)")
    | Sbreak -> raise NotAValue
    | Sreturn _ -> raise NotAValue

  (** [propagate_in_expr id v] and the associated functions replace
      all instances of [id] by [v] in an
      expression/statement/definition/block. It is used for constant
      propagation to reduce the number of variables. *)
156 157 158 159 160 161 162
  let rec propagate_in_expr id (v:expr) = function
    | Evar i when Ident.id_equal i id -> v
    | Evar i -> Evar i
    | Eunop (u,e) -> Eunop (u, propagate_in_expr id v e)
    | Ebinop (b,e1,e2) -> Ebinop (b,
                                  propagate_in_expr id v e1,
                                  propagate_in_expr id v e2)
163 164 165
    | Equestion (c,t,e) -> Equestion(propagate_in_expr id v c,
                                     propagate_in_expr id v t,
                                     propagate_in_expr id v e)
166 167 168 169 170 171 172 173
    | Ecast (ty,e) -> Ecast (ty, propagate_in_expr id v e)
    | Ecall (e, l) -> Ecall (propagate_in_expr id v e,
                             List.map (propagate_in_expr id v) l)
    | Esize_expr e -> Esize_expr (propagate_in_expr id v e)
    | Eindex (e1,e2) -> Eindex (propagate_in_expr id v e1,
                                propagate_in_expr id v e2)
    | Edot (e,i) -> Edot (propagate_in_expr id v e, i)
    | Earrow (e,i) -> Earrow (propagate_in_expr id v e, i)
174 175
    | Esyntax (s,t,ta,l,b) ->
      Esyntax (s,t,ta,List.map (fun (e,t) -> (propagate_in_expr id v e),t) l,b)
176 177
    | Enothing -> Enothing
    | Econst c -> Econst c
178 179
    | Elikely e -> Elikely (propagate_in_expr id v e)
    | Eunlikely e -> Eunlikely (propagate_in_expr id v e)
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
    | Esize_type ty -> Esize_type ty

  let rec propagate_in_stmt id v = function
    | Sexpr e -> Sexpr (propagate_in_expr id v e)
    | Sblock b -> Sblock(propagate_in_block id v b)
    | Sseq (s1,s2) -> Sseq (propagate_in_stmt id v s1,
                            propagate_in_stmt id v s2)
    | Sif (e,s1,s2) -> Sif (propagate_in_expr id v e,
                            propagate_in_stmt id v s1,
                            propagate_in_stmt id v s2)
    | Swhile (e, s) -> Swhile (propagate_in_expr id v e,
                               propagate_in_stmt id v s)
    | Sfor (e1,e2,e3,s) -> Sfor (propagate_in_expr id v e1,
                                 propagate_in_expr id v e2,
                                 propagate_in_expr id v e3,
                                 propagate_in_stmt id v s)
    | Sreturn e -> Sreturn (propagate_in_expr id v e)
    | Snop -> Snop
    | Sbreak -> Sbreak

  and propagate_in_def id v d =
    let rec aux = function
      | [] -> [], true
      | (i,e)::t ->
        if Ident.id_equal i id then (i,e)::t, false
        else let t,b = aux t in ((i,propagate_in_expr id v e)::t), b
    in
    match d with
    | Ddecl (ty,l) ->
      let l,b = aux l in
      Ddecl (ty, l), b
211
    | Dinclude (i,k) -> Dinclude (i,k), true
212
    | Dstruct _ -> raise (Unsupported "struct declaration inside function")
213
    | Dfun _ -> raise (Unsupported "nested function")
214
    | Dtypedef _ | Dproto _ | Dstruct_decl _ -> assert false
215 216 217 218 219 220 221 222 223 224 225 226

  and propagate_in_block id v (dl, s) =
    let dl, b = List.fold_left
      (fun (dl, acc) d ->
        if acc
        then
          let d, b = propagate_in_def id v d in
          (d::dl, b)
        else (d::dl, false))
      ([],true) dl in
    (List.rev dl, if b then propagate_in_stmt id v s else s)

227 228
  let is_empty_block s = s = Sblock([], Snop)
  let block_of_expr e = [], Sexpr e
229

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
(** [flatten_defs d s] appends all definitions in the statement [s] to d. *)
  (* TODO check ident unicity ? *)
  let rec flatten_defs d = function
    | Sseq (s1,s2) ->
      let d, s1' = flatten_defs d s1 in
      let d, s2' = flatten_defs d s2 in
      d, Sseq(s1',s2')
    | Sblock (d',s) ->
      let d',s' = flatten_defs d' s in
      d@d', s'
    | Sif (c,t,e) ->
      let d, t' = flatten_defs d t in
      let d, e' = flatten_defs d e in
      d,Sif(c,t',e')
    | Swhile (c,s) ->
      let d, s' = flatten_defs d s in
      d, Swhile (c, s')
    | Sfor (e1,e2,e3,s) ->
      let d, s' = flatten_defs d s in
      d, Sfor(e1,e2,e3,s')
    | s -> d,s

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

  let rec group_defs_by_type l =
    (* heuristic to reduce the number of lines of defs*)
    let rec group_types t1 t2 =
      match t1, t2 with
      | Tsyntax (s1, l1), Tsyntax (s2, l2) ->
        List.length l1 = List.length l2
        && List.for_all2 group_types l1 l2
        && (s1 = s2)
        && (not (String.contains s1 '*'))
      | Tsyntax _, _ | _, Tsyntax _ -> false
      | t1, t2 -> t1 = t2
    in
    match l with
    | [] | [_] -> l
    | Ddecl (ty1, el1) :: Ddecl (ty2, el2) :: l'
        when group_types ty1 ty2
          -> group_defs_by_type (Ddecl(ty1, el1@el2)::l')
    | Ddecl (ty1, el1) :: Ddecl (ty2, el2) :: Ddecl (ty3, el3) :: l'
        when group_types ty1 ty3
          -> group_defs_by_type (Ddecl (ty1, el1@el3) :: Ddecl (ty2, el2) :: l')
    | Ddecl (ty1, el1) :: Ddecl (ty2, el2) :: Ddecl (ty3, el3) :: l'
        when group_types ty2 ty3
          -> group_defs_by_type (Ddecl (ty1, el1) :: Ddecl (ty2, el2@el3) :: l')
    | Ddecl (ty1, el1) :: l' ->
      Ddecl (ty1, el1) :: group_defs_by_type l'
    | _ -> l

280 281 282 283 284 285 286 287 288
  let rec elim_empty_blocks = function
    | Sblock ([], s) -> elim_empty_blocks s
    | Sblock (d,s) -> Sblock (d, elim_empty_blocks s)
    | Sseq (s1,s2) -> Sseq (elim_empty_blocks s1, elim_empty_blocks s2)
    | Sif (c,t,e) -> Sif(c, elim_empty_blocks t, elim_empty_blocks e)
    | Swhile (c,s) -> Swhile(c, elim_empty_blocks s)
    | Sfor(e1,e2,e3,s) -> Sfor(e1,e2,e3,elim_empty_blocks s)
    | s -> s

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
  let rec elim_nop = function
    | Sseq (s1,s2) ->
      let s1 = elim_nop s1 in
      let s2 = elim_nop s2 in
      begin match s1,s2 with
      | Snop, Snop -> Snop
      | Snop, s | s, Snop -> s
      | _ -> Sseq(s1,s2)
      end
    | Sblock (d,s) ->
      let s = elim_nop s in
      begin match d, s with
      | [], Snop -> Snop
      | _ -> Sblock(d,s)
      end
    | Sif (c,t,e) -> Sif(c, elim_nop t, elim_nop e)
    | Swhile (c,s) -> Swhile (c, elim_nop s)
    | Sfor(e1,e2,e3,s) -> Sfor(e1,e2,e3,elim_nop s)
    | s -> s

  let rec add_to_last_call params = function
    | Sblock (d,s) -> Sblock (d, add_to_last_call params s)
    | Sseq (s1,s2) when not (is_nop s2) ->
      Sseq (s1, add_to_last_call params s2)
    | Sseq (s1,_) -> add_to_last_call params s1
    | Sexpr (Ecall(fname, args)) ->
      Sexpr (Ecall(fname, params@args)) (*change name to ensure no renaming ?*)
    | Sreturn (Ecall (fname, args)) ->
      Sreturn (Ecall(fname, params@args))
    | _ -> raise (Unsupported "tuple pattern matching with too complex def")
319

Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
320 321 322 323 324 325
  let rec stmt_of_list (l: stmt list) : stmt =
    match l with
    | [] -> Snop
    | [s] -> s
    | h::t -> Sseq (h, stmt_of_list t)

326 327 328 329
  let is_expr = function
    | Sexpr _ -> true
    | _ -> false

330
  let rec simplify_expr (d,s) : expr =
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
331
    match (d,s) with
332
    | [], Sblock([],s) -> simplify_expr ([],s)
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
333
    | [], Sexpr e -> e
334 335
    | [], Sif(c,t,e) ->
       Equestion (c, simplify_expr([],t), simplify_expr([],e))
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
    | _ -> raise (Invalid_argument "simplify_expr")

  let rec simplify_cond (cd, cs) =
    match cd,elim_empty_blocks(elim_nop cs) with
    | [], Sexpr c -> ([], Sexpr c)
    | ([], Sif (c', t', e') as b) ->
       let _,t' = simplify_cond ([], t') in
       let _,e' = simplify_cond ([], e') in
       if is_false e' && is_expr t'(* c' && t' *)
       then
         let t' = simplify_expr ([],t') in
         [], Sexpr(Ebinop(Band, c', t'))
       else if is_true e' && is_expr t' (* !c' || t' *)
       then
         let t' = simplify_expr ([],t') in
         [], Sexpr(Ebinop(Bor,Eunop(Unot,c'),t'))
       else if is_true t' && is_expr e' (* c' || e' *)
       then
         let e' = simplify_expr ([],e') in
         [], Sexpr(Ebinop(Bor,c',e'))
       else if is_false t' && is_expr e' (* !c' && e' *)
       then
         let e' = simplify_expr ([],e') in
         [], Sexpr(Ebinop(Band,Eunop(Unot,c'),e'))
       else b
    | d,s -> d, s

363 364 365 366 367 368 369 370 371 372 373 374 375 376

(* Operator precedence, needed to compute which parentheses can be removed *)

  let prec_unop = function
    | Unot | Ustar | Uaddr | Upreincr | Upredecr -> 2
    | Upostincr  | Upostdecr -> 1

  let prec_binop = function
    | Band -> 11
    | Bor -> 11 (* really 12, but this avoids Wparentheses *)
    | Beq | Bne -> 7
    | Bassign -> 14
    | Blt | Ble | Bgt | Bge -> 6

377
end
378

379 380 381 382
type info = Pdriver.printer_args = private {
  env         : Env.env;
  prelude     : Printer.prelude;
  thprelude   : Printer.prelude_map;
383
  thinterface : Printer.interface_map;
384 385 386
  blacklist   : Printer.blacklist;
  syntax      : Printer.syntax_map;
  converter   : Printer.syntax_map;
387
  literal     : Printer.syntax_map; (*TODO handle literals*)
388 389
}

390 391 392
let debug_c_extraction = Debug.register_info_flag
                           ~desc:"C extraction"
                           "c_extraction"
393

394 395 396 397 398 399 400 401 402 403 404 405 406 407
module Print = struct

  open C
  open Format
  open Printer
  open Pp

  exception Unprinted of string

  let c_keywords = ["auto"; "break"; "case"; "char"; "const"; "continue"; "default"; "do"; "double"; "else"; "enum"; "extern"; "float"; "for"; "goto"; "if"; "int"; "long"; "register"; "return"; "short"; "signed"; "sizeof"; "static"; "struct"; "switch"; "typedef"; "union"; "unsigned"; "void"; "volatile"; "while" ]

  let () = assert (List.length c_keywords = 32)

  let sanitizer = sanitizer char_to_lalpha char_to_alnumus
408
  let sanitizer s = Strings.lowercase (sanitizer s)
409 410
  let local_printer = create_ident_printer c_keywords ~sanitizer
  let global_printer = create_ident_printer c_keywords ~sanitizer
411

412 413 414 415
  let print_local_ident fmt id = fprintf fmt "%s" (id_unique local_printer id)
  let print_global_ident fmt id = fprintf fmt "%s" (id_unique global_printer id)

  let clear_local_printer () = Ident.forget_all local_printer
416 417 418

  let protect_on x s = if x then "(" ^^ s ^^ ")" else s

419 420 421 422 423 424 425
  let extract_stars ty =
    let rec aux acc = function
      | Tptr t -> aux (acc+1) t
      | t -> (acc, t)
    in
  aux 0 ty

426 427 428 429
  let rec print_ty ?(paren=false) fmt = function
    | Tvoid -> fprintf fmt "void"
    | Tsyntax (s, tl) ->
      syntax_arguments
430
	s
431
        (print_ty ~paren:false) fmt tl
432
    | Tptr ty -> fprintf fmt "%a *" (print_ty ~paren:true) ty
433
    (* should be handled in extract_stars *)
434 435
    | Tarray (ty, expr) ->
      fprintf fmt (protect_on paren "%a[%a]")
436
        (print_ty ~paren:true) ty (print_expr ~prec:1) expr
437
    | Tstruct (s,_) -> fprintf fmt "struct %s" s
438
    | Tunion _ -> raise (Unprinted "unions")
439
    | Tnamed id -> print_global_ident fmt id
440 441 442 443 444 445
    | Tnosyntax -> raise (Unprinted "type without syntax")

  and print_unop fmt = function
    | Unot -> fprintf fmt "!"
    | Ustar -> fprintf fmt "*"
    | Uaddr -> fprintf fmt "&"
446 447 448 449 450 451
    | Upreincr | Upostincr -> fprintf fmt "++"
    | Upredecr | Upostdecr -> fprintf fmt "--"

  and unop_postfix = function
    | Upostincr | Upostdecr -> true
    | _ -> false
452 453 454 455 456 457 458

  and print_binop fmt = function
    | Band -> fprintf fmt "&&"
    | Bor -> fprintf fmt "||"
    | Beq -> fprintf fmt "=="
    | Bne -> fprintf fmt "!="
    | Bassign -> fprintf fmt "="
459 460 461 462
    | Blt -> fprintf fmt "<"
    | Ble -> fprintf fmt "<="
    | Bgt -> fprintf fmt ">"
    | Bge -> fprintf fmt ">="
463

464
  and print_expr ~prec fmt = function
465
    | Enothing -> Debug.dprintf debug_c_extraction "enothing"; ()
466
    | Eunop(u,e) ->
467
       let p = prec_unop u in
468
       if unop_postfix u
469 470 471 472
       then fprintf fmt (protect_on (prec <= p) "%a%a")
              (print_expr ~prec:p) e print_unop u
       else fprintf fmt (protect_on (prec <= p) "%a%a")
              print_unop u (print_expr ~prec:p) e
473
    | Ebinop(b,e1,e2) ->
474 475 476
       let p = prec_binop b in
       fprintf fmt (protect_on (prec <= p) "%a %a %a")
        (print_expr ~prec:p) e1 print_binop b (print_expr ~prec:p) e2
477
    | Equestion(c,t,e) ->
478 479 480 481
      fprintf fmt (protect_on (prec <= 13) "%a ? %a : %a")
        (print_expr ~prec:13) c
        (print_expr ~prec:13) t
        (print_expr ~prec:13) e
482
    | Ecast(ty, e) ->
483 484 485 486 487 488 489 490 491
      fprintf fmt (protect_on (prec <= 2) "(%a)%a")
        (print_ty ~paren:false) ty (print_expr ~prec:2) e
    | Ecall (Esyntax (s, _, _, [], _), l) ->
       (* function defined in the prelude *)
       fprintf fmt (protect_on (prec <= 1) "%s(%a)")
         s (print_list comma (print_expr ~prec:15)) l
    | Ecall (e,l) ->
       fprintf fmt (protect_on (prec <= 1) "%a(%a)")
         (print_expr ~prec:1) e (print_list comma (print_expr ~prec:15)) l
492
    | Econst c -> print_const fmt c
493
    | Evar id -> print_local_ident fmt id
494 495 496 497 498 499
    | Elikely e -> fprintf fmt
                     (protect_on (prec <= 1) "__builtin_expect(%a,1)")
                     (print_expr ~prec:15) e
    | Eunlikely e -> fprintf fmt
                       (protect_on (prec <= 1) "__builtin_expect(%a,0)")
                       (print_expr ~prec:15) e
500
    | Esize_expr e ->
501
       fprintf fmt (protect_on (prec <= 2) "sizeof(%a)") (print_expr ~prec:15) e
502
    | Esize_type ty ->
503 504 505 506 507 508 509 510 511 512 513 514
       fprintf fmt (protect_on (prec <= 2) "sizeof(%a)")
         (print_ty ~paren:false) ty
    | Edot (e,s) ->
       fprintf fmt (protect_on (prec <= 1) "%a.%s")
         (print_expr ~prec:1) e s
    | Eindex _  | Earrow _ -> raise (Unprinted "struct/union access")
    | Esyntax (s, t, args, lte, c) ->
       (* no way to know precedence, so full parentheses*)
       gen_syntax_arguments_typed snd (fun _ -> args)
         (if prec <= 13 && not c then ("("^s^")") else s)
         (fun fmt (e,_t) -> print_expr ~prec:1 fmt e)
         (print_ty ~paren:false) (C.Enothing,t) fmt lte
515 516 517 518

  and print_const  fmt = function
    | Cint s | Cfloat s | Cchar s | Cstring s -> fprintf fmt "%s" s

519 520 521 522 523
  let print_id_init ~stars fmt ie =
    (if stars > 0
    then fprintf fmt "%s " (String.make stars '*')
    else ());
    match ie with
524 525
    | id, Enothing -> print_local_ident fmt id
    | id,e -> fprintf fmt "%a = %a"
526 527 528
                print_local_ident id (print_expr ~prec:(prec_binop Bassign)) e

  let print_expr_no_paren fmt expr = print_expr ~prec:max_int fmt expr
529 530

  let rec print_stmt ~braces fmt = function
531
    | Snop -> Debug.dprintf debug_c_extraction "snop"; ()
532
    | Sexpr e -> fprintf fmt "%a;" print_expr_no_paren e;
533
    | Sblock ([] ,s) when not braces ->
534
      (print_stmt ~braces:false) fmt s
535 536 537 538
    | Sblock b -> fprintf fmt "@[<hov>{@\n  @[<hov>%a@]@\n}@]" print_body b
    | Sseq (s1,s2) -> fprintf fmt "%a@\n%a"
      (print_stmt ~braces:false) s1
      (print_stmt ~braces:false) s2
539
    | Sif(c,t,e) when is_nop e ->
540
       fprintf fmt "if(%a)@\n%a" print_expr_no_paren c
541
         (print_stmt ~braces:true) (Sblock([],t))
542
    | Sif (c,t,e) -> fprintf fmt "if(%a)@\n%a@\nelse@\n%a"
543
      print_expr_no_paren c
544 545 546
      (print_stmt ~braces:true) (Sblock([],t))
      (print_stmt ~braces:true) (Sblock([],e))
    | Swhile (e,b) -> fprintf fmt "while (%a)@;<1 2>%a"
547
      print_expr_no_paren e (print_stmt ~braces:true) (Sblock([],b))
548 549
    | Sfor (einit, etest, eincr, s) ->
       fprintf fmt "for (%a; %a; %a)@;<1 2>%a"
550 551 552
         print_expr_no_paren einit
         print_expr_no_paren etest
         print_expr_no_paren eincr
553
         (print_stmt ~braces:true) (Sblock([],s))
554
    | Sbreak -> fprintf fmt "break;"
555
    | Sreturn Enothing -> fprintf fmt "return;"
556
    | Sreturn e -> fprintf fmt "return %a;" print_expr_no_paren e
557

558 559
  and print_def fmt def =
    try match def with
560 561 562
      | Dfun (id,(rt,args),body) ->
         let s = sprintf "%a %a(@[%a@])@ @[<hov>{@;<1 2>@[<hov>%a@]@\n}@\n@]"
                   (print_ty ~paren:false) rt
563
                   print_global_ident id
564 565
                   (print_list comma
		      (print_pair_delim nothing space nothing
566
			 (print_ty ~paren:false) print_local_ident))
567 568 569 570 571 572 573
	           args
                   print_body body in
         (* print into string first to print nothing in case of exception *)
         fprintf fmt "%s" s
      | Dproto (id, (rt, args)) ->
         let s = sprintf "%a %a(@[%a@]);@;"
                   (print_ty ~paren:false) rt
574
                   print_global_ident id
575 576
                   (print_list comma
                      (print_pair_delim nothing space nothing
577
		         (print_ty ~paren:false) print_local_ident))
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
	           args in
         fprintf fmt "%s" s
      | Ddecl (ty, lie) ->
         let nb, ty = extract_stars ty in
         assert (nb=0);
         let s = sprintf "%a @[<hov>%a@];"
	           (print_ty ~paren:false) ty
	           (print_list comma (print_id_init ~stars:nb)) lie in
         fprintf fmt "%s" s
      | Dstruct (s, lf) ->
         let s = sprintf "struct %s@ @[<hov>{@;<1 2>@[<hov>%a@]@\n};@\n@]"
                   s
                   (print_list newline
                      (fun fmt (s,ty) -> fprintf fmt "%a %s;"
                                           (print_ty ~paren:false) ty s))
                   lf in
         fprintf fmt "%s" s
      | Dstruct_decl s ->
         fprintf fmt "struct %s;@;" s
      | Dinclude (id, Sys) ->
         fprintf fmt "#include <%s.h>@;"  (sanitizer id.id_string)
      | Dinclude (id, Proj) ->
         fprintf fmt "#include \"%s.h\"@;" (sanitizer id.id_string)
      | Dtypedef (ty,id) ->
         let s = sprintf "@[<hov>typedef@ %a@;%a;@]"
603
	           (print_ty ~paren:false) ty print_global_ident id in
604
         fprintf fmt "%s" s
605 606
    with Unprinted s ->
      Debug.dprintf debug_c_extraction "Missed a def because : %s@." s
607

608 609 610
  and print_body fmt (def, s) =
    if def = []
    then print_stmt ~braces:true fmt s
611 612 613 614
    else
      print_pair_delim nothing newline nothing
        (print_list newline print_def)
        (print_stmt ~braces:true)
615
        fmt (def,s)
616

617 618 619 620
  let print_global_def fmt def =
    clear_local_printer ();
    print_def fmt def

621 622 623
  let print_file fmt info ast =
    Mid.iter (fun _ sl -> List.iter (fprintf fmt "%s\n") sl) info.thprelude;
    newline fmt ();
624
    fprintf fmt "@[<v>%a@]@." (print_list newline print_global_def) ast
625 626

end
627

Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
628 629 630 631 632 633 634
module MLToC = struct

  open Ity
  open Ty
  open Expr
  open Term
  open Printer
635
  open Mltree
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  open C

  let rec ty_of_mlty info = function
    | Tvar tv ->
      begin match query_syntax info.syntax tv.tv_name
        with
        | Some s -> C.Tsyntax (s, [])
        | None -> C.Tnamed (tv.tv_name)
      end
    | Tapp (id, tl) ->
       begin match query_syntax info.syntax id
        with
        | Some s -> C.Tsyntax (s, List.map (ty_of_mlty info) tl)
        | None -> C.Tnosyntax
       end
651
    | Ttuple [] -> C.Tvoid
652
    | Ttuple _ -> raise (Unsupported "tuple parameters")
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
653 654 655 656 657 658 659 660 661 662 663 664 665

  let rec ty_of_ty info ty = (*FIXME try to use only ML tys*)
    match ty.ty_node with
    | Tyvar v ->
      begin match query_syntax info.syntax v.tv_name
        with
        | Some s -> C.Tsyntax (s, [])
        | None -> C.Tnamed (v.tv_name)
      end
    | Tyapp (ts, tl) ->
       begin match query_syntax info.syntax ts.ts_name
        with
        | Some s -> C.Tsyntax (s, List.map (ty_of_ty info) tl)
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
666 667 668
        | None -> if is_ts_tuple ts && tl = []
                  then C.Tvoid
                  else C.Tnosyntax
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
669 670 671 672 673 674 675 676 677 678
       end

  let ity_of_expr e = match e.e_ity with
    | I i -> i
    | _ -> assert false

  let pv_name pv = pv.pv_vs.vs_name

  type syntax_env = { in_unguarded_loop : bool;
                      computes_return_value : bool;
679 680
                      current_function : rsymbol;
		      breaks : Sid.t;
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
                      returns : Sid.t; }


  let is_true e = match e.e_node with
    | Eapp (s, []) -> rs_equal s rs_true
    | _ -> false

  let is_false e = match e.e_node with
    | Eapp (s, []) -> rs_equal s rs_false
    | _ -> false

  let is_unit = function
    | I i -> ity_equal i Ity.ity_unit
    | C _ -> false

  let return_or_expr env (e:C.expr) =
    if env.computes_return_value
    then Sreturn e
    else Sexpr e

701

Andrei Paskevich's avatar
Andrei Paskevich committed
702 703
  let likely = create_attribute "ex:likely"
  let unlikely = create_attribute "ex:unlikely"
704

Andrei Paskevich's avatar
Andrei Paskevich committed
705 706 707
  let handle_likely attrs (e:C.expr) =
    let lkl = Sattr.mem likely attrs in
    let ulk = Sattr.mem unlikely attrs in
708 709 710 711 712 713 714 715 716
    if lkl
    then (if ulk then e else Elikely e)
    else (if ulk then Eunlikely e else e)

  let reverse_likely = function
    | Elikely e -> Eunlikely e
    | Eunlikely e -> Elikely e
    | e -> e

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
  let field i = "__field_"^(string_of_int i)

  let struct_of_rs info rs =
    let rty = ty_of_ity rs.rs_cty.cty_result in
    match rty.ty_node with
    | Tyapp (ts, lt) ->
       assert (is_ts_tuple ts);
       let rec fields fr tys =
         match tys with
         | [] -> []
         | ty::l -> (field fr, ty_of_ty info ty)::(fields (fr+1) l) in
       let fields = fields 0 lt in
       let s = match query_syntax info.syntax rs.rs_name with
         | Some s -> s
         | None -> rs.rs_name.id_string in
       let name = Pp.sprintf "__%s_result" s in
       (name, fields)
    | _ -> assert false

  let struct_of_rs info = Wrs.memoize 17 (fun rs -> struct_of_rs info rs)

738
  let rec expr info env (e:Mltree.expr) : C.body =
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
739 740 741 742 743 744 745 746
    assert (not e.e_effect.eff_ghost);
    match e.e_node with
    | Eblock [] ->
       if env.computes_return_value
       then C.([], Sreturn(Enothing))
       else C.([], Snop)
    | Eblock [_] -> assert false
    | Eblock l ->
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
747
       let env_f = { env with computes_return_value = false } in
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
748 749 750 751 752
       let rec aux = function
         | [] ->
            if env.computes_return_value
            then C.([], Sreturn(Enothing))
            else C.([], Snop)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
753 754
         | [s] -> ([], C.Sblock (expr info env s))
         | h::t -> ([], C.Sseq (C.Sblock (expr info env_f h),
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
755 756 757 758 759 760 761
                                C.Sblock (aux t)))
       in
       aux l
    | Eapp (rs, []) when rs_equal rs rs_true ->
       ([],return_or_expr env (C.Econst (Cint "1")))
    | Eapp (rs, []) when rs_equal rs rs_false ->
       ([],return_or_expr env (C.Econst (Cint "0")))
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
762
    | Mltree.Evar pv ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
763 764
       let e = C.Evar (pv_name pv) in
       ([], return_or_expr env e)
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
765
    | Mltree.Econst ic ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
766
      let n = Number.compute_int_constant ic in
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
767 768 769
      let e = C.(Econst (Cint (BigInt.to_string n))) in
      ([], return_or_expr env e)
    | Eapp (rs, el) ->
770
       Debug.dprintf debug_c_extraction "call to %s@." rs.rs_name.id_string;
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
771
       if is_rs_tuple rs && env.computes_return_value
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
       then begin
	 let args =
           List.filter
             (fun e ->
               assert (not e.e_effect.eff_ghost);
               match e.e_ity with
               | I i when ity_equal i Ity.ity_unit -> false
               | _ -> true)
	     el
         in (*FIXME still needed with masks? *)
         let env_f = { env with computes_return_value = false } in
         let id_struct = id_register (id_fresh "result") in
         let e_struct = C.Evar id_struct in
         let d_struct = C.(Ddecl(Tstruct
                                   (struct_of_rs info env.current_function),
                                 [id_struct, Enothing])) in
         let assign i (d,s) =
           C.Sblock (d,assignify C.(Edot (e_struct, field i)) s) in
         let rec assigns args i =
           match args with
           | [] -> Snop
           | e::t ->
              let b = expr info env_f e in
              C.Sseq(assign i b, assigns t (i+1)) in
	 C.([d_struct], Sseq(assigns args 0, Sreturn(e_struct)))
	 end
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
798
       else
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
	 let e' =
           match
             (query_syntax info.syntax rs.rs_name,
              query_syntax info.converter rs.rs_name) with
           | _, Some s
             | Some s, _ ->
              begin
                try
                  let _ =
                    Str.search_forward
                      (Str.regexp "[%]\\([tv]?\\)[0-9]+") s 0 in
                  let env_f =
                    { env with computes_return_value = false } in
                  let params =
		    List.map
                      (fun e ->
                        (simplify_expr (expr info env_f e),
                         ty_of_ty info (ty_of_ity (ity_of_expr e))))
		      el in
		  let rty = ty_of_ity (match e.e_ity with
                                       | C _ -> assert false
                                       | I i -> i) in
		  let rtyargs = match rty.ty_node with
		    | Tyvar _ -> [||]
		    | Tyapp (_,args) ->
                       Array.of_list (List.map (ty_of_ty info) args)
		  in
		  C.Esyntax(s,ty_of_ty info rty, rtyargs, params,
                            Mid.mem rs.rs_name info.converter)
                with Not_found ->
		  let args =
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
830 831 832 833 834 835
                    List.filter
                      (fun e ->
                        assert (not e.e_effect.eff_ghost);
                        match e.e_ity with
                        | I i when ity_equal i Ity.ity_unit -> false
                        | _ -> true)
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
		      el
                  in
                  if args=[]
                  then C.(Esyntax(s, Tnosyntax, [||], [], true)) (*constant*)
                  else
                    (*function defined in the prelude *)
                    let env_f =
                      { env with computes_return_value = false } in
		    C.(Ecall(Esyntax(s, Tnosyntax, [||], [], true),
			     List.map
                               (fun e ->
                                 simplify_expr (expr info env_f e))
                               el))
              end
           | _ ->
              let args =
                List.filter
                  (fun e ->
                    assert (not e.e_effect.eff_ghost);
                    match e.e_ity with
                    | I i when ity_equal i Ity.ity_unit -> false
                    | _ -> true)
		  el in
              let env_f =
                { env with computes_return_value = false } in
	      C.(Ecall(Evar(rs.rs_name), List.map
                                           (fun e ->
                                             simplify_expr (expr info env_f e))
                                           args))
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
865
         in
866 867 868 869 870 871 872 873 874 875
	 C.([],
            if env.computes_return_value
	    then
              begin match e.e_ity with
              | I ity when ity_equal ity Ity.ity_unit ->
                 Sseq(Sexpr e', Sreturn Enothing)
              | I _ -> Sreturn e'
              | _ -> assert false
              end
            else Sexpr e')
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
876 877 878 879 880
    | Elet (ld,e) ->
       begin match ld with
       | Lvar (pv,le) -> (* not a block *)
          begin
          match le.e_node with
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
881
          | Mltree.Econst ic ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
882
            let n = Number.compute_int_constant ic in
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
883
            let ce = C.(Econst (Cint (BigInt.to_string n))) in
884
	    Debug.dprintf debug_c_extraction "propagate constant %s for var %s@."
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898
			  (BigInt.to_string n) (pv_name pv).id_string;
            C.propagate_in_block (pv_name pv) ce (expr info env e)
          | Eapp (rs,_) when Mid.mem rs.rs_name info.converter ->
            begin match expr info {env with computes_return_value = false} le
              with
            | [], C.Sexpr(se) ->
              C.propagate_in_block (pv_name pv) se (expr info env e)
            | _ -> assert false
            end
          | _->
            let t = ty_of_ty info (ty_of_ity pv.pv_ity) in
            match expr info {env with computes_return_value = false} le with
            | [], C.Sexpr((C.Esyntax(_,_,_,_,b) as se))
                when b (* converter *) ->
899
              Debug.dprintf debug_c_extraction "propagate converter for var %s@."
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
900 901 902 903 904 905 906 907 908
                (pv_name pv).id_string;
              C.propagate_in_block (pv_name pv) se (expr info env e)
            | d,s ->
              let initblock = d, C.assignify (Evar (pv_name pv)) s in
              [ C.Ddecl (t, [pv_name pv, C.Enothing]) ],
              C.Sseq (C.Sblock initblock, C.Sblock (expr info env e))
          end
      | Lsym _ -> raise (Unsupported "LDsym")
      | Lrec _ -> raise (Unsupported "LDrec") (* TODO for rec at least*)
909
      | Lany _ -> raise (Unsupported "Lany")
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
910 911
       end
    | Eif (cond, th, el) ->
912
       let cd,cs = expr info {env with computes_return_value = false} cond in
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
913 914
       let t = expr info env th in
       let e = expr info env el in
915
       begin match simplify_cond (cd, cs) with
916
       | [], C.Sexpr c ->
Andrei Paskevich's avatar
Andrei Paskevich committed
917
          let c = handle_likely cond.e_attrs c in
918 919 920 921 922 923 924
          if is_false th && is_true el
	  then C.([], Sexpr(Eunop(Unot, c)))
	  else [], C.Sif(c,C.Sblock t, C.Sblock e)
       | cdef, cs ->
	  let cid = id_register (id_fresh "cond") in (* ? *)
	  C.Ddecl (C.Tsyntax ("int",[]), [cid, C.Enothing])::cdef,
	  C.Sseq (C.assignify (Evar cid) cs,
Andrei Paskevich's avatar
Andrei Paskevich committed
925
                  C.Sif ((handle_likely cond.e_attrs (C.Evar cid)),
926
                         C.Sblock t, C.Sblock e))
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
927 928
       end
    | Ewhile (c,b) ->
929
       Debug.dprintf debug_c_extraction "while@.";
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
930 931 932 933 934 935 936
      let cd, cs = expr info {env with computes_return_value = false} c in
      (* this is needed so that the extracted expression has all
         needed variables in its scope *)
      let cd, cs = C.flatten_defs cd cs in
      let cd = C.group_defs_by_type cd in
      let env' = { computes_return_value = false;
                   in_unguarded_loop = true;
937 938
		   returns = env.returns;
                   current_function = env.current_function;
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
939 940 941 942
                   breaks =
                     if env.in_unguarded_loop
                     then Sid.empty else env.breaks } in
      let b = expr info  env' b in
943
      begin match (C.simplify_cond (cd,cs)) with
Andrei Paskevich's avatar
Andrei Paskevich committed
944
      | cd, C.Sexpr ce -> cd, C.Swhile (handle_likely c.e_attrs ce, C.Sblock b)
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
945 946
      | _ ->
        begin match C.get_last_expr cs with
Andrei Paskevich's avatar
Andrei Paskevich committed
947
        | C.Snop, e -> cd, C.(Swhile(handle_likely c.e_attrs e, C.Sblock b))
948
        | s,e ->
Andrei Paskevich's avatar
Andrei Paskevich committed
949
           let brc = reverse_likely (handle_likely c.e_attrs (Eunop(Unot,e))) in
950 951 952 953
           cd, C.(Swhile(Econst (Cint "1"),
                         Sseq(s,
                              Sseq(Sif(brc, Sbreak, Snop),
                                   C.Sblock b))))
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
954 955
        end
      end
956
    | Ematch (b, [], (_::_ as xl)) ->
957
      Debug.dprintf debug_c_extraction "TRY@.";
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
958 959 960 961 962
      let is_while = match b.e_node with Ewhile _ -> true | _-> false in
      let breaks, returns = List.fold_left
        (fun (bs,rs) (xs, pvsl, r) ->
          let id = xs.xs_name in
          match pvsl, r.e_node with
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
963
          | [pv], Mltree.Evar pv'
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
964
            when pv_equal pv pv' && env.computes_return_value ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
965 966 967 968 969 970 971 972
            (bs, Sid.add id rs)
          | [], (Eblock []) when is_unit r.e_ity && is_while ->
            (Sid.add id bs, rs)
          |_ -> raise (Unsupported "non break/return exception in try"))
        (Sid.empty, env.returns) xl
      in
      let env' = { computes_return_value = env.computes_return_value;
                   in_unguarded_loop = false;
973 974
                   current_function = env.current_function;
		   breaks = breaks;
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
975 976 977 978
                   returns = returns;
                 } in
      expr info env' b
    | Eraise (xs,_) when Sid.mem xs.xs_name env.breaks ->
979
      Debug.dprintf debug_c_extraction "BREAK@.";
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
980 981
      ([], C.Sbreak)
    | Eraise (xs, Some r) when Sid.mem xs.xs_name env.returns ->
982
      Debug.dprintf debug_c_extraction "RETURN@.";
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
983
      expr info {env with computes_return_value = true} r
984 985
    | Eraise (xs, None) when Sid.mem xs.xs_name env.returns ->
       assert false (* nothing to pass to return *)
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
986
    | Eraise _ -> raise (Unsupported "non break/return exception raised")
987 988 989 990 991 992 993 994 995
    | Efor (i, sb, dir, eb, body) ->
       begin match i.pv_vs.vs_ty.ty_node with
       | Tyapp ({ ts_def = Range _ },_) ->
          let ty = ty_of_ty info i.pv_vs.vs_ty in
          let di = C.Ddecl(ty, [i.pv_vs.vs_name, Enothing]) in
          let ei = C.Evar (i.pv_vs.vs_name) in
          let init_e = C.Ebinop (Bassign, ei, C.Evar (sb.pv_vs.vs_name)) in
          let incr_op = match dir with To -> C.Upostincr | DownTo -> C.Upostdecr in
          let incr_e = C.Eunop (incr_op, ei) in
996 997 998 999 1000 1001 1002
          let init_test_op = match dir with | To -> C.Blt | DownTo -> C.Bgt in
          let init_test = C.Sif (C.Ebinop(init_test_op,
                                          C.Evar (eb.pv_vs.vs_name),
                                          C.Evar (sb.pv_vs.vs_name)),
                                 Sbreak, Snop) in
          let end_test = C.Sif (C.Ebinop (C.Beq, ei, C.Evar eb.pv_vs.vs_name),
                                Sbreak, Snop) in
1003 1004 1005 1006 1007 1008
          let env' = { env with computes_return_value = false;
                                in_unguarded_loop = true;
                                breaks =
                                  if env.in_unguarded_loop
                                  then Sid.empty else env.breaks } in
          let bd, bs = expr info env' body in
1009 1010
          let bs = C.Sseq(init_test, C.Sseq (bs, end_test)) in
          [di], C.Sfor(init_e, Enothing, incr_e, C.Sblock (bd,bs))
1011 1012
       |  _ -> raise (Unsupported "for loops")
       end
1013
    | Ematch (({e_node = Eapp(rs,_)} as e1), [Ptuple rets,e2], [])
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1014
         when List.for_all
1015
                (function | Pwild (*ghost*) | Pvar _ -> true |_-> false)
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1016 1017
                rets
      ->
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
       let id_struct = id_register (id_fresh "struct_res") in
       let e_struct = C.Evar id_struct in
       let d_struct = C.Ddecl(C.Tstruct (struct_of_rs info rs),
                              [id_struct, C.Enothing]) in
       let defs =
         List.fold_right
           (fun p acc ->
             match p with
             | Pvar vs -> C.Ddecl(ty_of_ty info vs.vs_ty,
                                  [vs.vs_name, C.Enothing])::acc
1028
             | Pwild -> acc
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
             | _ -> assert false )
        rets [d_struct] in
       let d,s = expr info {env with computes_return_value = false} e1 in
       let s = assignify e_struct s in
       let assign vs i =
         assignify (C.Evar vs) C.(Sexpr (Edot (e_struct, field i))) in
       let rec assigns rets i =
         match rets with
         | [] -> C.Snop
         | Pvar vs :: t -> C.Sseq ((assign vs.vs_name i), (assigns t (i+1)))
1039
         | Pwild :: t -> assigns t (i+1) (* ghost variable, skip *)
1040 1041 1042 1043
         | _ -> assert false in
       let assigns = assigns rets 0 in
       let b = expr info env e2 in
       d@defs, C.(Sseq(Sseq(s,assigns), Sblock b))
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1044 1045
    | Ematch _ -> raise (Unsupported "pattern matching")
    | Eabsurd -> assert false
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    | Eassign ([pv, ({rs_field = Some _} as rs), v]) ->
       let t =
         match (query_syntax info.syntax rs.rs_name,
                      query_syntax info.converter rs.rs_name) with
         | _, Some s | Some s, _ ->
            let _ =
              try
                Str.search_forward
                  (Str.regexp "[%]\\([tv]?\\)[0-9]+") s 0
              with Not_found -> raise (Unsupported "assign field format")  in
            let params = [ C.Evar pv.pv_vs.vs_name,
                           ty_of_ty info (ty_of_ity pv.pv_ity) ] in
            let rty = ty_of_ity rs.rs_cty.cty_result in
            let rtyargs = match rty.ty_node with
	      | Tyvar _ -> [||]
	      | Tyapp (_,args) ->
                 Array.of_list (List.map (ty_of_ty info) args)
	    in
            C.Esyntax(s,ty_of_ty info rty, rtyargs, params,
                      Mid.mem rs.rs_name info.converter)
         | None, None -> raise (Unsupported ("assign not in driver")) in
       [], C.(Sexpr(Ebinop(Bassign, t, C.Evar v.pv_vs.vs_name)))
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1068
    | Eassign _ -> raise (Unsupported "assign")
1069
    | Ehole | Eany _ -> assert false
1070
    | Eexn (_,_,e) -> expr info env e
1071 1072 1073 1074 1075
    | Eignore e ->
       [], C.Sseq(C.Sblock(expr info {env with computes_return_value = false} e),
              if env.computes_return_value
              then C.Sreturn(Enothing)
              else C.Snop)
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1076 1077
    | Efun _ -> raise (Unsupported "higher order")

1078
  let translate_decl (info:info) (d:decl) ~header : C.definition list =
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    let translate_fun rs vl e =
      Debug.dprintf debug_c_extraction "print %s@." rs.rs_name.id_string;
      if rs_ghost rs
      then begin Debug.dprintf debug_c_extraction "is ghost@."; [] end
      else
        let params =
          List.map (fun (id, ty, _gh) -> (ty_of_mlty info ty, id))
            (List.filter (fun (_,_, gh) -> not gh) vl) in
        let params = List.filter (fun (ty, _) -> ty <> C.Tvoid) params in
	let env = { computes_return_value = true;
		    in_unguarded_loop = false;
                    current_function = rs;
		    returns = Sid.empty;
		    breaks = Sid.empty; } in
	let rity = rs.rs_cty.cty_result in
	let is_simple_tuple ity =
	  let arity_zero = function
	    | Ityapp(_,a,r) -> a = [] && r = []
	    | Ityreg { reg_args = a; reg_regs = r } ->
               a = [] && r = []
	    | Ityvar _ -> true
	  in
	  (match ity.ity_node with
	   | Ityapp ({its_ts = s},_,_)
             | Ityreg { reg_its = {its_ts = s}; }
	     -> is_ts_tuple s
	   | _ -> false)
	  && (ity_fold
                (fun acc ity ->
                  acc && arity_zero ity.ity_node) true ity)
	in
	(* FIXME is it necessary to have arity 0 in regions ?*)
	let rtype = ty_of_ty info (ty_of_ity rity) in
        let rtype,sdecls =
          if rtype=C.Tnosyntax && is_simple_tuple rity
          then
            let st = struct_of_rs info rs in
            C.Tstruct st, [C.Dstruct st]
          else rtype, [] in
1118 1119 1120 1121 1122 1123 1124 1125 1126
        if header
        then sdecls@[C.Dproto (rs.rs_name, (rtype, params))]
        else
	  let d,s = expr info env e in
	  let d,s = C.flatten_defs d s in
          let d = C.group_defs_by_type d in
	  let s = C.elim_nop s in
	  let s = C.elim_empty_blocks s in
	  sdecls@[C.Dfun (rs.rs_name, (rtype,params), (d,s))] in
1127 1128
    try
      begin match d with
1129
      | Dlet (Lsym(rs, _, vl, e)) -> translate_fun rs vl e
1130 1131 1132 1133
      | Dtype [{its_name=id; its_def=idef}] ->
         Debug.dprintf debug_c_extraction "PDtype %s@." id.id_string;
         begin
           match idef with
1134
           | Some (Dalias _ty) -> [] (*[C.Dtypedef (ty_of_mlty info ty, id)] *)
1135 1136 1137 1138 1139
           | Some _ -> raise (Unsupported "Ddata/Drecord@.")
           | None ->
              begin match query_syntax info.syntax id with
              | Some _ -> []
              | None ->
1140 1141 1142
                 raise (Unsupported
                          ("type declaration without syntax or alias: "
                           ^id.id_string))
1143
              end
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1144
         end
1145 1146 1147 1148
      | Dlet (Lrec rl) ->
         let translate_rdef rd =
           translate_fun rd.rec_sym rd.rec_args rd.rec_exp in
         let defs = List.flatten (List.map translate_rdef rl) in
1149 1150 1151 1152 1153 1154 1155
         if header then defs
         else
           let proto_of_fun = function
             | C.Dfun (id, pr, _) -> [C.Dproto (id, pr)]
             | _ -> [] in
           let protos = List.flatten (List.map proto_of_fun defs) in
           protos@defs
1156 1157
      | _ -> [] (*TODO exn ? *) end
    with Unsupported s ->
1158
      Debug.dprintf debug_c_extraction "Unsupported : %s@." s; []
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1159

1160
  let translate_decl (info:info) (d:Mltree.decl) ~header : C.definition list =
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1161
    let decide_print id = query_syntax info.syntax id = None in
1162 1163
    let names = Mltree.get_decl_name d in
    match List.filter decide_print names with
1164
    | [] -> []
1165
    | _ -> translate_decl info d ~header
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1166 1167 1168 1169

end


1170
let name_gen suffix ?fname m =
1171
  let n = m.Pmodule.mod_theory.Theory.th_name.Ident.id_string in
1172
  let n = Print.sanitizer n in
1173 1174 1175
  let r = match fname with
    | None -> n ^ suffix
    | Some f -> f ^ "__" ^ n ^ suffix in
1176
  Strings.lowercase r
1177 1178 1179 1180

let file_gen = name_gen ".c"
let header_gen = name_gen ".h"

1181 1182
let print_header_decl args fmt d =
  let cds = MLToC.translate_decl args d ~header:true in
1183
  List.iter (Format.fprintf fmt "%a@." Print.print_global_def) cds
1184 1185 1186 1187

let print_header_decl =
  let memo = Hashtbl.create 16 in
  fun args ?old ?fname ~flat m fmt d ->
1188 1189 1190 1191
  ignore old;
  ignore fname;
  ignore flat;
  ignore m;
1192 1193 1194 1195
  if not (Hashtbl.mem memo d)
  then begin
    Hashtbl.add memo d ();
    print_header_decl args fmt d end
1196

1197
let print_prelude args ?old ?fname ~flat deps fmt pm =
1198 1199 1200
  ignore old;
  ignore fname;
  ignore flat;
1201
  ignore pm;
1202
  ignore args;
1203
  let add_include id =
1204
    Format.fprintf fmt "%a@." Print.print_global_def C.(Dinclude (id,Proj)) in
1205 1206 1207 1208 1209
  List.iter
    (fun m ->
      let id = m.Pmodule.mod_theory.Theory.th_name in
      add_include id)
    (List.rev deps)
1210

1211 1212 1213
let print_decl args fmt d =
  let cds = MLToC.translate_decl args d ~header:false in
  let print_def d =
1214
    Format.fprintf fmt "%a@." Print.print_global_def d in
1215 1216 1217 1218 1219
  List.iter print_def cds

let print_decl =
  let memo = Hashtbl.create 16 in
  fun args ?old ?fname ~flat m fmt d ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1220 1221
  ignore old;
  ignore fname;
1222
  ignore flat;
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1223
  ignore m;
1224 1225 1226 1227
  if not (Hashtbl.mem memo d)
  then begin
    Hashtbl.add memo d ();
    print_decl args fmt d end
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1228

1229 1230 1231 1232 1233 1234 1235 1236
let c_printer = Pdriver.{
      desc            = "printer for C code";
      file_gen        = file_gen;
      decl_printer    = print_decl;
      interf_gen      = Some header_gen;
      interf_printer  = Some print_header_decl;
      prelude_printer = print_prelude }

Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1237
let () =
1238
  Pdriver.register_printer "c" c_printer
1239 1240 1241 1242 1243 1244

(*
Local Variables:
compile-command: "unset LANG; make -C ../.."
End:
*)