cprinter.ml 47.2 KB
Newer Older
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
1
open Ident
2

3 4
exception Unsupported of string

Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
5
module C = struct
6

Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
7 8
  type ty =
    | Tvoid
9
    | Tsyntax of string * ty list
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
10 11 12 13 14
    | Tptr of ty
    | Tarray of ty * expr
    | Tstruct of ident * (ident * ty) list
    | Tunion of ident * (ident * ty) list
    | Tnamed of ident (* alias from typedef *)
15
    | Tnosyntax (* types that do not have a syntax, can't be printed *)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
    (* 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

  and binop = Band | Bor | Beq | Bne | Bassign (* += and co. maybe to add *)

  and unop = Unot | Ustar | Uaddr (* (pre|post)(incr|decr) maybe to add *)

  and expr =
    | Enothing
    | Eunop of unop * expr
    | Ebinop of binop * expr * expr
35
    | Equestion of expr * expr * expr (* c ? t : e *)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
36 37 38
    | Ecast of ty * expr
    | Ecall of expr * expr list
    | Econst of constant
39
    | Evar of ident
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
40 41 42
    | Esize_expr of expr
    | Esize_type of ty
    | Eindex of expr * expr (* Array access *)
43 44
    | Edot of expr * ident (* Field access with dot *)
    | Earrow of expr * ident (* Pointer access with arrow *)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
45 46 47
    | Esyntax of string * ty * (ty array) * (expr*ty) list * bool
  (* template, type and type arguments of result, typed arguments,
     is/is not converter*)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

  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

  and definition =
67
    | Dfun of ident * proto * body
68
    | Dinclude of ident
69
    | Dproto of ident * proto
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
70 71 72 73 74 75 76
    | Ddecl of names
    | Dtypedef of ty * ident

  and body = definition list * stmt

  type file = definition list

77 78
  exception NotAValue

79 80 81 82 83 84 85 86 87 88 89 90
  let rec is_nop = function
    | Snop -> true
    | Sblock ([], s) -> is_nop s
    | Sseq (s1,s2) -> is_nop s1 && is_nop s2
    | _ -> false

  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
91 92 93
  (** [assignify v] transforms a statement that computes a value into
     a statement that assigns that value to v *)
  let rec assignify v = function
94
    | Snop -> raise NotAValue
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
95 96 97 98 99 100 101
    | 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)
102 103 104
    | Sbreak -> raise NotAValue
    | Sreturn _ -> raise NotAValue

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

  (** [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. *)
129 130 131 132 133 134 135
  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)
136 137 138
    | Equestion (c,t,e) -> Equestion(propagate_in_expr id v c,
                                     propagate_in_expr id v t,
                                     propagate_in_expr id v e)
139 140 141 142 143 144 145 146
    | 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)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
147 148
    | Esyntax (s,t,ta,l,b) ->
      Esyntax (s,t,ta,List.map (fun (e,t) -> (propagate_in_expr id v e),t) l,b)
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
    | Enothing -> Enothing
    | Econst c -> Econst c
    | 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
    | Dinclude i -> Dinclude i, true
    | Dfun _ -> raise (Unsupported "nested function")
184 185
    | Dtypedef _ -> raise (Unsupported "typedef inside function")
    | Dproto _ -> raise (Unsupported "prototype inside function")
186 187 188 189 190 191 192 193 194 195 196 197

  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)

198 199
  let is_empty_block s = s = Sblock([], Snop)
  let block_of_expr e = [], Sexpr e
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
200

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
(** [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

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

  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

251 252 253 254 255 256 257 258 259
  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

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
  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")
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
290

Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
291 292 293 294 295 296 297 298 299 300 301 302 303
  let rec stmt_of_list (l: stmt list) : stmt =
    match l with
    | [] -> Snop
    | [s] -> s
    | h::t -> Sseq (h, stmt_of_list t)

  let simplify_expr (d,s) : expr =
    match (d,s) with
    | [], Sexpr e -> e
 (*   | [], Sreturn e -> assert false
    | [], Snop -> assert false
    | [], Sblock _ -> assert false *)
    | _ -> assert false
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
304
end
305

306 307 308 309 310 311 312 313 314
type info = Pdriver.printer_args = private {
  env         : Env.env;
  prelude     : Printer.prelude;
  thprelude   : Printer.prelude_map;
  blacklist   : Printer.blacklist;
  syntax      : Printer.syntax_map;
  converter   : Printer.syntax_map;
}

315 316
let debug = false

Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
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
  let printer = create_ident_printer c_keywords ~sanitizer

  let print_ident fmt id = fprintf fmt "%s" (id_unique printer id)

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

337 338 339 340 341 342 343
  let extract_stars ty =
    let rec aux acc = function
      | Tptr t -> aux (acc+1) t
      | t -> (acc, t)
    in
  aux 0 ty

Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
344 345 346 347
  let rec print_ty ?(paren=false) fmt = function
    | Tvoid -> fprintf fmt "void"
    | Tsyntax (s, tl) ->
      syntax_arguments
348
	s
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
349
        (print_ty ~paren:false) fmt tl
350
    | Tptr ty -> fprintf fmt "%a *" (print_ty ~paren:true) ty
351
    (* should be handled in extract_stars *)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    | Tarray (ty, expr) ->
      fprintf fmt (protect_on paren "%a[%a]")
        (print_ty ~paren:true) ty (print_expr ~paren:false) expr
    | Tstruct _ -> raise (Unprinted "structs")
    | Tunion _ -> raise (Unprinted "unions")
    | Tnamed id -> print_ident fmt id
    | Tnosyntax -> raise (Unprinted "type without syntax")

  and print_unop fmt = function
    | Unot -> fprintf fmt "!"
    | Ustar -> fprintf fmt "*"
    | Uaddr -> fprintf fmt "&"

  and print_binop fmt = function
    | Band -> fprintf fmt "&&"
    | Bor -> fprintf fmt "||"
    | Beq -> fprintf fmt "=="
    | Bne -> fprintf fmt "!="
    | Bassign -> fprintf fmt "="

  and print_expr ~paren fmt = function
373
    | Enothing -> if debug then Format.printf "enothing"; ()
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
374 375 376 377 378
    | Eunop(u,e) -> fprintf fmt (protect_on paren "%a %a")
      print_unop u (print_expr ~paren:true) e
    | Ebinop(b,e1,e2) ->
      fprintf fmt (protect_on paren "%a %a %a")
        (print_expr ~paren:true) e1 print_binop b (print_expr ~paren:true) e2
379 380 381 382 383
    | Equestion(c,t,e) ->
      fprintf fmt (protect_on paren "%a ? %a : %a")
        (print_expr ~paren:true) c
        (print_expr ~paren:true) t
        (print_expr ~paren:true) e
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    | Ecast(ty, e) ->
      fprintf fmt (protect_on paren "(%a)%a")
        (print_ty ~paren:false) ty (print_expr ~paren:true) e
    | Ecall (e,l) -> fprintf fmt (protect_on paren "%a(%a)")
      (print_expr ~paren:true) e (print_list comma (print_expr ~paren:false)) l
    | Econst c -> print_const fmt c
    | Evar id -> print_ident fmt id
    | Esize_expr e ->
      fprintf fmt (protect_on paren "sizeof(%a)") (print_expr ~paren:false) e
    | Esize_type ty ->
      fprintf fmt (protect_on paren "sizeof(%a)") (print_ty ~paren:false) ty
    | Eindex _ | Edot _ | Earrow _ -> raise (Unprinted "struct/array access")
    | Esyntax (s, t, args, lte,_) ->
      gen_syntax_arguments_typed snd (fun _ -> args)
        (if paren then ("("^s^")") else s)
        (fun fmt (e,_t) -> print_expr ~paren:false fmt e)
        (print_ty ~paren:false) (C.Enothing,t) fmt lte

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

405 406 407 408 409
  let print_id_init ~stars fmt ie =
    (if stars > 0
    then fprintf fmt "%s " (String.make stars '*')
    else ());
    match ie with
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
410 411 412 413
    | id, Enothing -> print_ident fmt id
    | id,e -> fprintf fmt "%a = %a" print_ident id (print_expr ~paren:false) e

  let rec print_stmt ~braces fmt = function
414
    | Snop -> if debug then Format.printf "snop"; ()
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
415
    | Sexpr e -> fprintf fmt "%a;" (print_expr ~paren:false) e;
416
    | Sblock ([] ,s) when (not braces || (one_stmt s && not (is_nop s))) ->
417
      (print_stmt ~braces:false) fmt s
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
418 419 420 421
    | 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
422
    | Sif(c,t,e) when is_nop e ->
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
423
       fprintf fmt "if(%a)@\n%a" (print_expr ~paren:false) c
424
         (print_stmt ~braces:true) (Sblock([],t))
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
425 426
    | Sif (c,t,e) -> fprintf fmt "if(%a)@\n%a@\nelse@\n%a"
      (print_expr ~paren:false) c
427 428 429 430
      (print_stmt ~braces:true) (Sblock([],t))
      (print_stmt ~braces:true) (Sblock([],e))
    | Swhile (e,b) -> fprintf fmt "while (%a)@;<1 2>%a"
      (print_expr ~paren:false) e (print_stmt ~braces:true) (Sblock([],b))
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
431 432
    | Sfor _ -> raise (Unprinted "for loops")
    | Sbreak -> fprintf fmt "break;"
433
    | Sreturn Enothing -> fprintf fmt "return;"
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
434 435
    | Sreturn e -> fprintf fmt "return %a;" (print_expr ~paren:true) e

436 437
  and print_def fmt def =
    try match def with
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    | Dfun (id,(rt,args),body) ->
       fprintf fmt "%a %a(@[%a@])@ @[<hov>{@;<1 2>@[<hov>%a@]@\n}@\n@]"
               (print_ty ~paren:false) rt
               print_ident id
               (print_list comma
			   (print_pair_delim nothing space nothing
					     (print_ty ~paren:false) print_ident))
	       args
               print_body body
    | Dproto (id, (rt, args)) ->
      fprintf fmt "%a %a(@[%a@]);@;"
        (print_ty ~paren:false) rt
        print_ident id
        (print_list comma
           (print_pair_delim nothing space nothing
			     (print_ty ~paren:false) print_ident))
	args
    | Ddecl (ty, lie) ->
456 457 458 459 460
      let nb, ty = extract_stars ty in
      assert (nb=0);
      fprintf fmt "%a @[<hov>%a@];"
	(print_ty ~paren:false) ty
	(print_list comma (print_id_init ~stars:nb)) lie
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
461 462 463
    | Dinclude id ->
       fprintf fmt "#include<%a.h>@;" print_ident id
    | Dtypedef (ty,id) ->
464
       fprintf fmt "@[<hov>typedef@ %a@;%a;@]"
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
465
	       (print_ty ~paren:false) ty print_ident id
466
    with Unprinted s -> Format.printf "Missed a def because : %s@." s
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
467

468 469 470
  and print_body fmt (def, s) =
    if def = []
    then print_stmt ~braces:true fmt s
471 472 473 474
    else
      print_pair_delim nothing newline nothing
        (print_list newline print_def)
        (print_stmt ~braces:true)
475
        fmt (def,s)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
476 477 478 479 480 481 482

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

end
483
(*
484 485 486 487 488 489 490
module Translate = struct
  open Pdecl
  open Ity
  open Ty
  open Expr
  open Term
  open Printer
491
  open Pmodule
492

493
  let rec ty_of_ty info ty =
494 495 496 497
    match ty.ty_node with
    | Tyvar v ->
      begin match query_syntax info.syntax v.tv_name
        with
498
        | Some s -> C.Tsyntax (s, [])
499 500
        | None -> C.Tnamed (v.tv_name)
      end
501
    | Tyapp (ts, tl) ->
502 503
       begin match query_syntax info.syntax ts.ts_name
        with
504
        | Some s -> C.Tsyntax (s, List.map (ty_of_ty info) tl)
505
        | None -> C.Tnosyntax
506 507 508 509
       end

  let pv_name pv = pv.pv_vs.vs_name

510 511
  type syntax_env = { in_unguarded_loop : bool;
                      computes_return_value : bool;
512
		      returns_tuple: bool * ident list;
513 514 515 516
                      breaks : Sid.t;
                      returns : Sid.t; }

  let rec expr info env (e:expr) : C.body =
517 518
    if e_ghost e 
    then (if debug then Format.printf "translating ghost expr@."; C.([], Snop))
519 520 521 522
    else if is_e_void e then
      if env.computes_return_value
      then C.([], Sreturn(Enothing))
      else C.([], Snop)
523 524
    else if is_e_true e then expr info env (e_nat_const 1)
    else if is_e_false e then expr info env (e_nat_const 0)
525 526 527
    else match e.e_node with
    | Evar pv ->
       let e = C.Evar(pv_name pv) in
528
       C.([], if env.computes_return_value then Sreturn e else Sexpr e)
529 530
    | Econst (Number.ConstInt ic) ->
      let n = Number.compute_int ic in
531
      let e = C.(Econst (Cint (BigInt.to_string n))) in
532
      C.([], if env.computes_return_value then Sreturn e else Sexpr e)
533
    | Econst _ -> raise (Unsupported "real constants")
534
    | Eexec (ce, _cty) ->
535
      begin match ce.c_node with
536
      | Cfun e -> expr info env e
537
      | Capp (rs, pvsl) ->
538 539 540 541
	 if is_rs_tuple rs && env.computes_return_value
	 then begin
	     match env.returns_tuple with
	     | true, rl ->
542 543 544 545 546 547
		let args =
                  List.filter
                    (fun pv -> not (pv.pv_ghost
				    || ity_equal pv.pv_ity ity_unit))
		    pvsl
                in
548 549
		assert (List.length rl = List.length args);
		C.([],
550
		   List.fold_right2 (fun res arg acc ->
551 552 553 554 555 556 557
				     Sseq(Sexpr(Ebinop(Bassign,
						       Eunop(Ustar,Evar(res)),
						       Evar(pv_name arg))),
					 acc))
				    rl args (Sreturn(Enothing)))
	     | _ -> assert false
	   end
558
	 else
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
559 560 561 562 563 564
	   let e =
             match
               (query_syntax info.syntax rs.rs_name,
                query_syntax info.converter rs.rs_name) with
               | _, Some s
               | Some s, _ ->
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
                 begin
                   try
                     let _ = Str.search_forward
                       (Str.regexp "[%]\\([tv]?\\)[0-9]+") s 0 in
                     let params =
		       List.map (fun pv -> (C.Evar(pv_name pv),
                                            ty_of_ty info (ty_of_ity pv.pv_ity)))
		         pvsl in
		     let rty = ty_of_ity e.e_ity 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 = List.filter
		       (fun pv -> not (pv.pv_ghost
				       || ity_equal pv.pv_ity ity_unit))
		       pvsl in
                     if pvsl=[]
                     then C.(Esyntax(s, Tnosyntax, [||], [], true)) (*constant*)
                     else
                     (*function defined in the prelude *)
		     C.(Ecall(Esyntax(s, Tnosyntax, [||], [], true),
			      List.map (fun pv -> Evar(pv_name pv)) args))
                 end
               | _ ->
                 let args = List.filter
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
595 596 597 598 599
		   (fun pv -> not (pv.pv_ghost
				   || ity_equal pv.pv_ity ity_unit))
		   pvsl in
		 C.(Ecall(Evar(rs.rs_name),
			  List.map (fun pv -> Evar(pv_name pv)) args))
600
         in
601 602
	   C.([],
              if env.computes_return_value
603 604 605 606
	      then
                if (ity_equal rs.rs_cty.cty_result ity_unit)
                then Sseq(Sexpr e, Sreturn Enothing)
                else Sreturn e
607
              else Sexpr e)
608
      | _ -> raise (Unsupported "Cpur/Cany") (*TODO clarify*)
609
      end
610
    | Eassign _ -> raise (Unsupported "mutable field assign")
611 612 613
    | Elet (ld,e) ->
      begin match ld with
      | LDvar (pv,le) ->
614
        (*if debug then Format.printf "let %s@." pv.pv_vs.vs_name.id_string;*)
615 616 617
        if pv.pv_ghost
        (*TODO check it's actually unused *)
        then expr info env e
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
618
        else if ity_equal pv.pv_ity ity_unit
619
             || pv.pv_vs.vs_name.id_string = "_"
620 621 622
        then let env' = {env with computes_return_value = false} in
             ([], C.Sseq (C.Sblock(expr info env' le),
		          C.Sblock(expr info env e)))
623 624 625 626
        else begin
          match le.e_node with
          | Econst (Number.ConstInt ic) ->
            let n = Number.compute_int ic in
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
627
            let ce = C.(Econst (Cint (BigInt.to_string n))) in
628
	    if debug then Format.printf "propagate constant %s for var %s@."
629
			  (BigInt.to_string n) (pv_name pv).id_string;
630
            C.propagate_in_block (pv_name pv) ce (expr info env e)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
631 632
          | Eexec ({c_node = Capp(rs,_); _},_)
              when Mid.mem rs.rs_name info.converter ->
633 634
            begin match expr info {env with computes_return_value = false} le
              with
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
635
            | [], C.Sexpr(se) ->
636
              C.propagate_in_block (pv_name pv) se (expr info env e)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
637 638
            | _ -> assert false
            end
639
          | _->
640
            let t = ty_of_ty info (ty_of_ity pv.pv_ity) in
641
            match expr info {env with computes_return_value = false} le with
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
642 643
            | [], C.Sexpr((C.Esyntax(_,_,_,_,b) as se))
                when b (* converter *) ->
644
              if debug then Format.printf "propagate converter for var %s@."
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
645
                (pv_name pv).id_string;
646
              C.propagate_in_block (pv_name pv) se (expr info env e)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
647
            | d,s ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
648
              let initblock = d, C.assignify (C.Evar (pv_name pv)) s in
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
649
              [ C.Ddecl (t, [pv_name pv, C.Enothing]) ],
650
              C.Sseq (C.Sblock initblock, C.Sblock (expr info env e))
651
        end
652 653
      | LDsym _ -> raise (Unsupported "LDsym")
      | LDrec _ -> raise (Unsupported "LDrec") (* TODO for rec at least*)
654
      end
655
    | Eif (cond, th, el) ->
656 657 658
       let c = expr info {env with computes_return_value = false} cond in
       let t = expr info env th in
       let e = expr info env el in
659 660 661 662 663 664 665 666
       begin match c with
	     | [], C.Sexpr c ->
		if is_e_false th && is_e_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,
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
667
		C.Sseq (C.assignify (C.Evar cid) cs,
668
                        C.Sif (C.Evar cid, C.Sblock t, C.Sblock e))
669 670
       (* TODO detect empty branches and replace with Snop, detect and/or*)
       end
671
    | Ewhile (c,_,_,b) ->
672
      if debug then Format.printf "while@.";
673
      let cd, cs = expr info {env with computes_return_value = false} c in
674 675 676
      (* this is needed so that the extracted expression has all
         needed variables in its scope *)
      let cd, cs = C.flatten_defs cd cs in
677
      let cd = C.group_defs_by_type cd in
678 679
      let env' = { computes_return_value = false;
                   in_unguarded_loop = true;
680
		   returns_tuple = env.returns_tuple;
681 682 683 684 685
                   returns = env.returns;
                   breaks =
                     if env.in_unguarded_loop
                     then Sid.empty else env.breaks } in
      let b = expr info  env' b in
686 687 688
      begin match cs with
      | C.Sexpr ce -> cd, C.Swhile (ce, C.Sblock b)
      | _ ->
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
689 690 691
        begin match C.get_last_expr cs with
        | C.Snop, e -> cd, C.(Swhile(e, C.Sblock b))
        | s,e -> cd, C.(Swhile(Econst (Cint "1"),
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
692
                     Sseq(s,
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
693 694 695
                          Sseq(Sif(Eunop(Unot, e), Sbreak, Snop),
                               C.Sblock b))))
        end
696
      end
697
    | Etry (b, exm) ->
698
      if debug then Format.printf "TRY@.";
699
      let is_while = match b.e_node with Ewhile _ -> true | _-> false in
700
      let breaks,returns = Mxs.fold
701 702 703 704 705
        (fun xs (pvsl,r) (bs,rs) ->
          let id = xs.xs_name in
          match pvsl, r.e_node with
          | [pv], Evar pv' when pv_equal pv pv' && env.computes_return_value ->
            (bs, Sid.add id rs)
706
          | [], _ when is_e_void r && is_while (*FIXME*) ->
707 708 709 710 711 712
            (Sid.add id bs, rs)
          |_ -> raise (Unsupported "non break/return exception in try"))
        exm (Sid.empty, env.returns)
      in
      let env' = { computes_return_value = env.computes_return_value;
                   in_unguarded_loop = false;
713
		   returns_tuple = env.returns_tuple;
714 715 716 717 718
                   breaks = breaks;
                   returns = returns;
                 } in
      expr info env' b
    | Eraise (xs,_) when Sid.mem xs.xs_name env.breaks ->
719
      if debug then Format.printf "BREAK@.";
720 721
      ([], C.Sbreak)
    | Eraise (xs,r) when Sid.mem xs.xs_name env.returns ->
722
      if debug then Format.printf "RETURN@.";
723 724
      expr info {env with computes_return_value = true} r
    | Eraise _ -> raise (Unsupported "non break/return exception raised")
725
    | Efor _ -> raise (Unsupported "for loops")  (*TODO*)
726
    | Eassert _ -> [], C.Snop
727 728 729 730 731 732 733
      (* let (a,b) = f(...) in *)
    | Ecase (e1,[{pp_pat = {pat_node = Papp(ls,rets)}}, e2])
        when is_fs_tuple ls
          && List.for_all (fun p ->
            match p.pat_node with Pvar _ -> true |_-> false)
            rets
          ->
734 735 736 737
      let rets, defs = List.fold_right
        (fun p (r, d)-> match p.pat_node with
        | Pvar vs -> (C.(Eunop(Uaddr,Evar(vs.vs_name)))::r,
		     C.Ddecl(ty_of_ty info vs.vs_ty, [vs.vs_name, C.Enothing])::d)
738
        | _ -> assert false )
739
        rets ([], []) in
740
      let d,s = expr info {env with computes_return_value = false} e1 in
741
      let s' = C.add_to_last_call rets s in
742
      let b = expr info env e2 in
743
      d@defs, C.(Sseq(s', Sblock b))
744 745
    | Ecase _ -> raise (Unsupported "pattern matching")
    | Eghost _ | Epure _ | Eabsurd -> assert false
746 747 748 749

  let pdecl info (pd:Pdecl.pdecl) : C.definition list =
    match pd.pd_node with
    | PDlet (LDsym (rs, ce)) ->
750
      let fname = rs.rs_name in
751
      if debug then Format.printf "PDlet rsymbol %s@." fname.id_string;
752
      if rs_ghost rs
753
      then begin if debug then Format.printf "is ghost@."; [] end
754
      else
755 756
      begin try
              if Mid.mem fname info.syntax
757
              then (if debug then Format.printf "has syntax@."; [])
758 759 760 761 762 763 764 765
              else
                let params = List.map
		  (fun pv -> ty_of_ty info pv.pv_vs.vs_ty, pv_name pv)
		  (List.filter
		     (fun pv -> not pv.pv_ghost
                       && not (ity_equal pv.pv_ity ity_unit))
		     rs.rs_cty.cty_args) in
                begin match ce.c_node with
766 767 768 769 770 771 772
                      | Cfun e ->
			 let env = { computes_return_value = true;
				     in_unguarded_loop = false;
				     returns_tuple = false, [];
				     returns = Sid.empty;
				     breaks = Sid.empty; } in
			 let rity = rs.rs_cty.cty_result in
773
			 let is_simple_tuple ity =
774 775
			   let arity_zero = function
			     | Ityapp(_,a,r) -> a = [] && r = []
776 777
			     | Ityreg { reg_args = a; reg_regs = r } ->
                               a = [] && r = []
778 779 780
			     | Ityvar _ -> true
			   in
			   (match ity.ity_node with
781 782 783
			    | Ityapp ({its_ts = s},_,_)
                            | Ityreg { reg_its = {its_ts = s}; }
			      -> is_ts_tuple s
784
			    | _ -> false)
785 786 787
			   && (ity_fold
                                 (fun acc ity ->
                                   acc && arity_zero ity.ity_node) true ity)
788 789 790 791 792 793 794 795 796 797 798
			 in
			 (* FIXME is it necessary to have arity 0 in regions ?*)
			 let rtype =
			   if ity_equal rity ity_unit
			   then C.Tvoid
			   else ty_of_ty info (ty_of_ity rity) in
			 let env, rtype, params = match rtype with
			   | C.Tnosyntax when is_simple_tuple rity ->
			      (* instead of returning a tuple, return
			      void and assign the result to addresses
			      passed as parameters *)
799
			      let returns =
800
				let f ity b acc =
801
				  if b.its_visible
802
				  then (C.Tptr(ty_of_ty info (ty_of_ity ity)),
803 804 805 806
					id_register (id_fresh "result"))::acc
				  else acc
				in
				match rity.ity_node with
807
				| Ityapp(s, tl,_)
808
				| Ityreg { reg_its = s; reg_args = tl } ->
809
				   List.fold_right2 f tl s.its_arg_flg []
810 811 812 813 814
				| Ityvar _ -> assert false
			      in
			      {env with returns_tuple = true, List.map snd returns},
			      C.Tvoid,
			      returns@params
815
			   | _ -> env, rtype, params
816 817
			 in
			 let d,s = expr info env e in
818 819 820
                         (*TODO check if we want this flatten*)
			 let d,s = C.flatten_defs d s in
                         let d = C.group_defs_by_type d in
821 822 823
			 let s = C.elim_nop s in
			 let s = C.elim_empty_blocks s in
			 [C.Dfun (fname, (rtype,params), (d,s))]
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
824 825 826
                      | _ ->
                         raise
                           (Unsupported
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
827
                              "Non-function with no syntax in toplevel let")
828 829 830
	        end
        with Unsupported s -> Format.printf "Unsupported : %s@." s; []
      end
831 832
    | PDtype [{itd_its = its}] ->
      let id = its.its_ts.ts_name in
833
      if debug then Format.printf "PDtype %s@." id.id_string;
834 835
      begin
        match its.its_ts.ts_def with
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
836 837 838
        | Alias def -> [C.Dtypedef (ty_of_ty info def, id)]
        | Range _ | Float _ -> raise (Unsupported "range types")
        | NoDef ->
839
          begin match query_syntax info.syntax id with
840
          | Some _ -> []
841 842 843
          | None ->
            raise (Unsupported "type declaration without syntax or alias")
          end
844 845
      end

846 847 848 849
    | _ -> [] (*TODO exn ? *)

  let munit info = function
    | Udecl pd -> pdecl info pd
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
850
    | Uuse _m -> (*[C.Dinclude m.mod_theory.Theory.th_name]*) []
851 852 853 854 855 856 857 858 859 860 861
    | Uclone _ -> raise (Unsupported "clone")
    | Umeta _ -> raise (Unsupported "meta")
    | Uscope _ -> []

  let translate (info:info) (m:pmodule) : C.file =
    Format.printf "Translating module %s@."
      m.mod_theory.Theory.th_name.id_string;
    try List.flatten (List.map (munit info) m.mod_units)
    with
    | Unsupported s ->
      Format.printf "Failed because of unsupported construct: %s@." s; []
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
862
end
863
*)
864
(*TODO simplifications : propagate constants, collapse blocks with only a statement and no def*)
865

Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
866 867 868 869 870 871 872 873 874
module MLToC = struct

  open Pdecl
  open Ity
  open Ty
  open Expr
  open Term
  open Printer
  open Pmodule
875
  open Mltree
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
  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
    | Ttuple _ -> raise (Unsupported "type tuple")

  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)
        | None -> C.Tnosyntax
       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;
		      returns_tuple: bool * ident list;
                      breaks : Sid.t;
                      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

938
  let rec expr info env (e:Mltree.expr) : C.body =
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
939 940 941 942 943 944 945 946
    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
947
       let env_f = { env with computes_return_value = false } in
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
948 949 950 951 952
       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
953 954
         | [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
955 956 957 958 959 960 961
                                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")))
962
    | Evar pv ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
963 964
       let e = C.Evar (pv_name pv) in
       ([], return_or_expr env e)
965
    | Econst ic ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
      let n = Number.compute_int ic in
      let e = C.(Econst (Cint (BigInt.to_string n))) in
      ([], return_or_expr env e)
    | Eapp (rs, el) ->
       if is_rs_tuple rs && env.computes_return_value
	 then begin
	     match env.returns_tuple with
	     | true, rl ->
		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
		assert (List.length rl = List.length args);
                let env_f = { env with computes_return_value=false } in
		C.([],
		   List.fold_right2
                     (fun res arg acc ->
                       let d,s = expr info env_f arg in
                       let s = assignify (Eunop(Ustar,Evar(res))) s in
		       Sseq(Sblock(d,s),
			    acc))
		     rl args (Sreturn(Enothing)))
	     | _ -> assert false
	   end
       else
	   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 =
                       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
                     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))
         in
	   C.([],
              if env.computes_return_value
	      then
                if (ity_equal rs.rs_cty.cty_result Ity.ity_unit)
                then Sseq(Sexpr e, Sreturn Enothing)
                else Sreturn e
              else Sexpr e)
    | Elet (ld,e) ->
       begin match ld with
       | Lvar (pv,le) -> (* not a block *)
          begin
          match le.e_node with
1075
          | Econst ic ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1076 1077
            let n = Number.compute_int ic in
            let ce = C.(Econst (Cint (BigInt.to_string n))) in
1078
	    if debug then Format.printf "propagate constant %s for var %s@."
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
			  (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 *) ->
1093
              if debug then Format.printf "propagate converter for var %s@."
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
                (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*)
       end
    | Eif (cond, th, el) ->
       let c = expr info {env with computes_return_value = false} cond in
       let t = expr info env th in
       let e = expr info env el in
       begin match c with
	     | [], C.Sexpr c ->
		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,
                        C.Sif (C.Evar cid, C.Sblock t, C.Sblock e))
       (* TODO detect empty branches and replace with Snop, detect and/or*)
       end
    | Ewhile (c,b) ->
1121
       if debug then Format.printf "while@.";
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
      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;
		   returns_tuple = env.returns_tuple;
                   returns = env.returns;
                   breaks =
                     if env.in_unguarded_loop
                     then Sid.empty else env.breaks } in
      let b = expr info  env' b in
      begin match cs with
      | C.Sexpr ce -> cd, C.Swhile (ce, C.Sblock b)
      | _ ->
        begin match C.get_last_expr cs with
        | C.Snop, e -> cd, C.(Swhile(e, C.Sblock b))
        | s,e -> cd, C.(Swhile(Econst (Cint "1"),
                     Sseq(s,
                          Sseq(Sif(Eunop(Unot, e), Sbreak, Snop),
                               C.Sblock b))))
        end
      end
    | Etry (b,xl) ->
1147
      if debug then Format.printf "TRY@.";
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1148 1149 1150 1151 1152
      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
1153
          | [pv], Evar pv'
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
1154
            when pv_equal pv pv' && env.computes_return_value ->
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
            (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;
		   returns_tuple = env.returns_tuple;
                   breaks = breaks;
                   returns = returns;
                 } in
      expr info env' b
    | Eraise (xs,_) when Sid.mem xs.xs_name env.breaks ->
1169
      if debug then Format.printf "BREAK@.";
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1170 1171
      ([], C.Sbreak)
    | Eraise (xs, Some r) when Sid.mem xs.xs_name env.returns ->
1172
      if debug then Format.printf "RETURN@.";
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
      expr info {env with computes_return_value = true} r
    | Eraise (xs, None) -> assert false (* nothing to pass to return *)
    | Eraise _ -> raise (Unsupported "non break/return exception raised")
    | Efor _ -> raise (Unsupported "for loops")  (*TODO*)
    | Ematch (e1, [Ptuple rets,e2])
         when List.for_all
                (function Pvar _ -> true |_-> false)
                rets
      ->
      let rets, defs = List.fold_right
        (fun p (r, d)-> match p with
        | Pvar vs -> (C.(Eunop(Uaddr,Evar vs.vs_name))::r,
		        C.Ddecl(ty_of_ty info vs.vs_ty,
                                [vs.vs_name, C.Enothing])::d)
        | _ -> assert false )
        rets ([], []) in
      let d,s = expr info {env with computes_return_value = false} e1 in
      let s' = C.add_to_last_call rets s in
      let b = expr info env e2 in
      d@defs, C.(Sseq(s', Sblock b))
    | Ematch _ -> raise (Unsupported "pattern matching")
    | Eabsurd -> assert false
    | Eassign _ -> raise (Unsupported "assign")
1196
    | Ehole -> assert false
1197
    | Eexn _ -> raise (Unsupported "exception")
1198 1199 1200 1201 1202
    | 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
1203 1204 1205 1206 1207 1208 1209
    | Efun _ -> raise (Unsupported "higher order")

  let translate_decl (info:info) (d:decl) : C.definition option
    =
    match d with
    | Dlet (Lsym(rs, ty, vl, e)) ->
       if rs_ghost rs
1210
       then begin if debug then Format.printf "is ghost@."; None end
Raphael Rieu-Helft's avatar
Raphael Rieu-Helft committed
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
       else
         begin try
           let params =
             List.map (fun (id, ty, _gh) -> (ty_of_mlty info ty, id))
                      (List.filter (fun (id, ty, gh) -> not gh) vl) in
	   let env = { computes_return_value = true;
		       in_unguarded_loop = false;
		       returns_tuple = false, [];
		       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 =
	     if ity_equal rity Ity.ity_unit
	     then C.Tvoid
	     else ty_of_ty info (ty_of_ity rity) in
	   let env, rtype, params = match rtype with
	     | C.Tnosyntax when is_simple_tuple rity ->
		(* instead of returning a tuple, return
			      void and assign the result to addresses
			      passed as parameters *)
		let returns =
		  let f ity b acc =
		    if b.its_visible
		    then (C.Tptr(ty_of_ty info (ty_of_ity ity)),
			  id_register (id_fresh "result"))::acc
		    else acc
		  in
		  match rity.ity_node with
		  | Ityapp(s, tl,_)
		    | Ityreg { reg_its = s; reg_args = tl } ->
		     List.fold_right2 f tl s.its_arg_flg []
		  | Ityvar _ -> assert false
		in
		{env with returns_tuple = true, List.map snd returns},
		C.Tvoid,
		returns@params
	     | _ -> env, rtype, params
	   in
	   let d,s = expr info env e in
           (*TODO check if we want this flatten*)
	   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
	   Some
             (C.Dfun (rs.rs_name, (rtype,params), (d,s)))
           with  Unsupported s ->
             Format.printf "Unsupported : %s@." s; None
         end
    | Dtype [{its_name=id; its_def=idef}] ->
1278
      if debug then Format.printf "PDtype %s@." id.id_string;