cprinter.ml 21.1 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 35 36 37
    (* 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
    | Ecast of ty * expr
    | Ecall of expr * expr list
    | Econst of constant
38
    | Evar of ident
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
39 40 41
    | Esize_expr of expr
    | Esize_type of ty
    | Eindex of expr * expr (* Array access *)
42 43
    | 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
44 45 46
    | 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
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

  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 =
66
    | Dfun of ident * proto * body
67
    | Dinclude of ident
68
    | Dproto of ident * proto
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
69 70 71 72 73 74 75
    | Ddecl of names
    | Dtypedef of ty * ident

  and body = definition list * stmt

  type file = definition list

76 77 78 79
  exception NotAValue

  (* [assignify id] transforms a statement that computes a value into
     a statement that assigns that value to id *)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
80 81 82
  let rec assignify id s =
    match s with
    | Snop -> (*Format.printf "assign snop@."; Snop*) raise NotAValue (* ? *)
83 84 85 86 87 88 89 90 91
    | Sexpr e -> Sexpr (Ebinop (Bassign, Evar id, e))
    | Sblock (ds, s) -> Sblock (ds, assignify id s)
    | Sseq (s1, s2) -> Sseq (s1, assignify id s2)
    | Sif (c,t,e) -> Sif (c, assignify id t, assignify id e)
    | Swhile (c,s) -> Swhile (c, assignify id s) (* can this be a value ?*)
    | Sfor (e0,e1,e2,s) -> Sfor (e0,e1,e2, assignify id s)
    | Sbreak -> raise NotAValue
    | Sreturn _ -> raise NotAValue

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  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)
    | 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
107 108
    | Esyntax (s,t,ta,l,b) ->
      Esyntax (s,t,ta,List.map (fun (e,t) -> (propagate_in_expr id v e),t) l,b)
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    | 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")
144 145
    | Dtypedef _ -> raise (Unsupported "typedef inside function")
    | Dproto _ -> raise (Unsupported "prototype inside function")
146 147 148 149 150 151 152 153 154 155 156 157

  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)

158 159
  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
160 161 162 163 164 165 166 167 168 169 170 171 172

  let rec is_nop = function
    | Snop -> true
    | Sblock ([], s) -> is_nop s
    | Sseq (s1,s2) -> is_nop s1 && is_nop s2
    | _ -> false

  let one_stmt = function
    | Snop -> true
    | Sexpr _ -> true
    | Sblock _ -> true
    | _ -> false

173 174 175 176 177 178 179 180 181 182 183
end

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;
}

Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
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

  let rec print_ty ?(paren=false) fmt = function
    | Tvoid -> fprintf fmt "void"
    | Tsyntax (s, tl) ->
      syntax_arguments
        (if paren then ("("^s^")") else s)
        (print_ty ~paren:false) fmt tl
    | Tptr ty -> fprintf fmt "(%a)*" (print_ty ~paren:true) ty
    | 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
    | Enothing -> Format.printf "enothing"; ()
    | 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
    | 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

  let print_id_init fmt = function
    | 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
    | Snop -> Format.printf "snop"; ()
    | Sexpr e -> fprintf fmt "%a;" (print_expr ~paren:false) e;
266 267
    | Sblock ([] ,s) when (not braces || one_stmt s) ->
      (print_stmt ~braces:false) fmt s
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    | 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
    | Sif(c,t,e) when is_empty_block e ->
       fprintf fmt "if(%a)@\n%a" (print_expr ~paren:false) c
         (print_stmt ~braces:true) t
    | Sif (c,t,e) -> fprintf fmt "if(%a)@\n%a@\nelse@\n%a"
      (print_expr ~paren:false) c
      (print_stmt ~braces:true) t
      (print_stmt ~braces:true) e
    | Swhile (e,b) -> fprintf fmt "while (%a)@ %a"
      (print_expr ~paren:false) e (print_stmt ~braces:true) b
    | Sfor _ -> raise (Unprinted "for loops")
    | Sbreak -> fprintf fmt "break;"
    | Sreturn e -> fprintf fmt "return %a;" (print_expr ~paren:true) e

285 286
  and print_def fmt def =
    try match def with
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    | 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) ->
       fprintf fmt "%a @[<hov>%a@];@;"
	       (print_ty ~paren:false) ty
	       (print_list comma print_id_init) lie
    | Dinclude id ->
       fprintf fmt "#include<%a.h>@;" print_ident id
    | Dtypedef (ty,id) ->
       fprintf fmt "@[<hov>typedef@ %a@;%a;@]@;"
	       (print_ty ~paren:false) ty print_ident id
313
    with Unprinted s -> Format.printf "Missed a def because : %s@." s
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327

  and print_body fmt body =
    print_pair_delim nothing newline nothing
		     (print_list newline print_def)
		     (print_stmt ~braces:true)
		     fmt body

  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

328 329 330 331 332 333 334
module Translate = struct
  open Pdecl
  open Ity
  open Ty
  open Expr
  open Term
  open Printer
335
  open Pmodule
336

337
  let rec ty_of_ty info ty =
338 339 340 341
    match ty.ty_node with
    | Tyvar v ->
      begin match query_syntax info.syntax v.tv_name
        with
342
        | Some s -> C.Tsyntax (s, [])
343 344
        | None -> C.Tnamed (v.tv_name)
      end
345
    | Tyapp (ts, tl) ->
346 347
       begin match query_syntax info.syntax ts.ts_name
        with
348
        | Some s -> C.Tsyntax (s, List.map (ty_of_ty info) tl)
349
        | None -> C.Tnosyntax
350 351 352 353
       end

  let pv_name pv = pv.pv_vs.vs_name

354 355 356 357 358 359
  type syntax_env = { in_unguarded_loop : bool;
                      computes_return_value : bool;
                      breaks : Sid.t;
                      returns : Sid.t; }

  let rec expr info env (e:expr) : C.body =
360 361
    if e_ghost e then (Format.printf "translating ghost expr@."; C.([], Snop))
    else if is_e_void e then C.([], Snop)
362 363
    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)
364 365 366
    else match e.e_node with
    | Evar pv ->
       let e = C.Evar(pv_name pv) in
367
       C.([], if env.computes_return_value then Sreturn e else Sexpr e)
368 369
    | Econst (Number.ConstInt ic) ->
      let n = Number.compute_int ic in
370
      let e = C.(Econst (Cint (BigInt.to_string n))) in
371
      C.([], if env.computes_return_value then Sreturn e else Sexpr e)
372
    | Econst _ -> raise (Unsupported "real constants")
373
    | Eexec (ce, _cty) ->
374
      begin match ce.c_node with
375
      | Cfun e -> expr info env e
376
      | Capp (rs, pvsl) ->
377 378 379
         let e =  match query_syntax info.syntax rs.rs_name with
           | Some s ->
              let params =
380 381
		List.map (fun pv -> (C.Evar(pv_name pv),
                                     ty_of_ty info (ty_of_ity pv.pv_ity)))
382
			 pvsl in
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
383
              let rty = ty_of_ity e.e_ity in
384 385 386 387
              let rtyargs = match rty.ty_node with
		| Tyvar _ -> [||]
		| Tyapp (_,args) -> Array.of_list (List.map (ty_of_ty info) args)
              in
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
388 389
              C.Esyntax(s,ty_of_ty info rty, rtyargs, params,
                        Mid.mem rs.rs_name info.converter)
390 391 392 393
           | None ->
              let args = List.filter (fun pv -> not pv.pv_ghost) pvsl in
              C.(Ecall(Evar(rs.rs_name), List.map (fun pv -> Evar(pv_name pv)) args))
         in
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
394
	 C.([],
395 396
            if env.computes_return_value
              && not (ity_equal rs.rs_cty.cty_result ity_unit)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
397 398
            then Sreturn e
            else Sexpr e)
399
      | _ -> raise (Unsupported "Cpur/Cany") (*TODO clarify*)
400
      end
401
    | Eassign _ -> raise (Unsupported "mutable field assign")
402 403 404
    | Elet (ld,e) ->
      begin match ld with
      | LDvar (pv,le) ->
405
        Format.printf "let %s@." pv.pv_vs.vs_name.id_string;
406
        if pv.pv_ghost then expr info env e
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
407
        else if ity_equal pv.pv_ity ity_unit
408 409 410
        then let env' = {env with computes_return_value = false} in
             ([], C.Sseq (C.Sblock(expr info env' le),
		          C.Sblock(expr info env e)))
411 412 413 414
        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
415
            let ce = C.(Econst (Cint (BigInt.to_string n))) in
416 417
	    Format.printf "propagate constant %s for var %s@."
			  (BigInt.to_string n) (pv_name pv).id_string;
418
            C.propagate_in_block (pv_name pv) ce (expr info env e)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
419 420
          | Eexec ({c_node = Capp(rs,_); _},_)
              when Mid.mem rs.rs_name info.converter ->
421 422
            begin match expr info {env with computes_return_value = false} le
              with
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
423
            | [], C.Sexpr(se) ->
424
              C.propagate_in_block (pv_name pv) se (expr info env e)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
425 426
            | _ -> assert false
            end
427
          | _->
428
            let t = ty_of_ty info (ty_of_ity pv.pv_ity) in
429
            match expr info {env with computes_return_value = false} le with
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
430 431 432 433
            | [], C.Sexpr((C.Esyntax(_,_,_,_,b) as se))
                when b (* converter *) ->
              Format.printf "propagate converter for var %s@."
                (pv_name pv).id_string;
434
              C.propagate_in_block (pv_name pv) se (expr info env e)
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
435 436 437
            | d,s ->
              let initblock = d, C.assignify (pv_name pv) s in
              [ C.Ddecl (t, [pv_name pv, C.Enothing]) ],
438
              C.Sseq (C.Sblock initblock, C.Sblock (expr info env e))
439
        end
440
      | _ -> raise (Unsupported "LDsym/LDrec") (* TODO for rec at least*)
441
      end
442
    | Eif (cond, th, el) ->
443 444 445
       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
446 447 448 449 450 451 452 453
       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,
454 455
		C.Sseq (C.assignify cid cs,
                        C.Sif (C.Evar cid, C.Sblock t, C.Sblock e))
456 457
       (* TODO detect empty branches and replace with Snop, detect and/or*)
       end
458 459 460 461 462 463 464 465 466 467
    | Ewhile (c,_,_,b) ->
      Format.printf "while@.";
      let cd, cs = expr info {env with computes_return_value = false} c in
      let env' = { computes_return_value = false;
                   in_unguarded_loop = true;
                   returns = env.returns;
                   breaks =
                     if env.in_unguarded_loop
                     then Sid.empty else env.breaks } in
      let b = expr info  env' b in
468 469 470 471
      begin match cs with
      | C.Sexpr ce -> cd, C.Swhile (ce, C.Sblock b)
      | _ ->
        let cid = id_register (id_fresh "cond") in (* ? *)
472
        [C.Ddecl (C.Tsyntax ("int",[]), [cid, C.Enothing])],
473 474
        C.Sseq (C.Sblock (cd, C.assignify cid cs),
                C.Swhile (C.Evar cid, C.Sblock b))
475
      end
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    | Etry (b, exm) ->
      Format.printf "TRY@.";
      let is_while = match b.e_node with Ewhile _ -> true | _-> false in
      let breaks,returns = Mexn.fold
        (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)
          | [], _ when is_e_void r && is_while ->
            (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;
                   breaks = breaks;
                   returns = returns;
                 } in
      expr info env' b
    | Eraise (xs,_) when Sid.mem xs.xs_name env.breaks ->
      Format.printf "BREAK@.";
      ([], C.Sbreak)
    | Eraise (xs,r) when Sid.mem xs.xs_name env.returns ->
      Format.printf "RETURN@.";
      expr info {env with computes_return_value = true} r
    | Eraise _ -> raise (Unsupported "non break/return exception raised")
503
    | Efor _ -> raise (Unsupported "for loops")  (*TODO*)
504
    | Eassert _ -> [], C.Snop
505 506
    | Ecase _ -> raise (Unsupported "pattern matching")
    | Eghost _ | Epure _ | Eabsurd -> assert false
507 508 509 510

  let pdecl info (pd:Pdecl.pdecl) : C.definition list =
    match pd.pd_node with
    | PDlet (LDsym (rs, ce)) ->
511 512
      let fname = rs.rs_name in
      Format.printf "PDlet rsymbol %s@." fname.id_string;
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
      begin try
              if Mid.mem fname info.syntax
              then (Format.printf "has syntax@."; [])
              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
                | Cfun e ->
                  let rity = rs.rs_cty.cty_result in
                  let rtype =
                    if ity_equal rity ity_unit then C.Tvoid
                    else ty_of_ty info (ty_of_ity rity) in
                  let env = { computes_return_value = true;
                              in_unguarded_loop = false;
                              returns = Sid.empty;
                              breaks = Sid.empty; } in
                  [C.Dfun (fname, (rtype,params), expr info env e)]
                | _ -> raise (Unsupported
                                "Non-function with no syntax in toplevel let")
	        end
        with Unsupported s -> Format.printf "Unsupported : %s@." s; []
      end
539 540
    | PDtype [{itd_its = its}] ->
      let id = its.its_ts.ts_name in
541
      Format.printf "PDtype %s@." id.id_string;
542 543 544
      begin
        match its.its_ts.ts_def with
        | Some def -> [C.Dtypedef (ty_of_ty info def, id)]
545 546
        | None ->
          begin match query_syntax info.syntax id with
547
          | Some _ -> []
548 549 550
          | None ->
            raise (Unsupported "type declaration without syntax or alias")
          end
551 552
      end

553 554 555 556
    | _ -> [] (*TODO exn ? *)

  let munit info = function
    | Udecl pd -> pdecl info pd
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
557
    | Uuse _m -> (*[C.Dinclude m.mod_theory.Theory.th_name]*) []
558 559 560 561 562 563 564 565 566 567 568
    | 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
569
end
570
(*TODO simplifications : propagate constants, collapse blocks with only a statement and no def*)
571

572 573


574 575 576 577 578 579 580 581
let fg ?fname m =
  let n = m.Pmodule.mod_theory.Theory.th_name.Ident.id_string in
  match fname with
  | None -> n ^ ".c"
  | Some f -> f ^ "__" ^ n ^ ".c"

let pr args ?old fmt m =
  ignore(old);
582
  let ast = Translate.translate args m in
Raphaël Rieu-Helft's avatar
Raphaël Rieu-Helft committed
583
  try Print.print_file fmt args ast
584 585
  with Print.Unprinted s -> (Format.printf "Could not print: %s@." s;
		       Format.fprintf fmt "/* Dummy file */@.")
586 587

let () = Pdriver.register_printer "c" ~desc:"printer for C code" fg pr