Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / c_backend.ml @ 54ae8ac7

History | View | Annotate | Download (43.6 KB)

1
(* ----------------------------------------------------------------------------
2
 * SchedMCore - A MultiCore Scheduling Framework
3
 * Copyright (C) 2009-2013, ONERA, Toulouse, FRANCE - LIFL, Lille, FRANCE
4
 * Copyright (C) 2012-2013, INPT, Toulouse, FRANCE
5
 *
6
 * This file is part of Prelude
7
 *
8
 * Prelude is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public License
10
 * as published by the Free Software Foundation ; either version 2 of
11
 * the License, or (at your option) any later version.
12
 *
13
 * Prelude is distributed in the hope that it will be useful, but
14
 * WITHOUT ANY WARRANTY ; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with this program ; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21
 * USA
22
 *---------------------------------------------------------------------------- *)
23

    
24
(* This module is used for the lustre to C compiler *)
25

    
26
open Format
27
open LustreSpec
28
open Corelang
29
open Machine_code
30

    
31
(********************************************************************************************)
32
(*                     Basic      Printing functions                                        *)
33
(********************************************************************************************)
34

    
35
let print_version fmt =
36
  Format.fprintf fmt "/* @[<v>C code generated by %s@,SVN version number %s@,Code is %s compliant */@,@]@."
37
    (Filename.basename Sys.executable_name) Version.number (if !Options.ansi then "ANSI C90" else "C99")
38

    
39
(* Generation of a non-clashing name for the self memory variable (for step and reset functions) *)
40
let mk_self m =
41
  mk_new_name (m.mstep.step_inputs@m.mstep.step_outputs@m.mstep.step_locals@m.mmemory) "self"
42

    
43
(* Generation of a non-clashing name for the instance variable of static allocation macro *)
44
let mk_instance m =
45
  mk_new_name (m.mstep.step_inputs@m.mmemory) "inst"
46

    
47
(* Generation of a non-clashing name for the attribute variable of static allocation macro *)
48
let mk_attribute m =
49
  mk_new_name (m.mstep.step_inputs@m.mmemory) "attr"
50

    
51
let mk_call_var_decl loc id =
52
  { var_id = id;
53
    var_dec_type = mktyp Location.dummy_loc Tydec_any;
54
    var_dec_clock = mkclock Location.dummy_loc Ckdec_any;
55
    var_dec_const = false;
56
    var_type = Type_predef.type_arrow (Types.new_var ()) (Types.new_var ());
57
    var_clock = Clocks.new_var true;
58
    var_loc = loc }
59

    
60
(* counter for loop variable creation *)
61
let loop_cpt = ref (-1)
62

    
63
let reset_loop_counter () =
64
 loop_cpt := -1
65

    
66
let mk_loop_var m () =
67
  let vars = m.mstep.step_inputs@m.mstep.step_outputs@m.mstep.step_locals@m.mmemory in
68
  let rec aux () =
69
    incr loop_cpt;
70
    let s = Printf.sprintf "__%s_%d" "i" !loop_cpt in
71
    if List.exists (fun v -> v.var_id = s) vars then aux () else s
72
  in aux ()
73
(*
74
let addr_cpt = ref (-1)
75

    
76
let reset_addr_counter () =
77
 addr_cpt := -1
78

    
79
let mk_addr_var m var =
80
  let vars = m.mmemory in
81
  let rec aux () =
82
    incr addr_cpt;
83
    let s = Printf.sprintf "%s_%s_%d" var "addr" !addr_cpt in
84
    if List.exists (fun v -> v.var_id = s) vars then aux () else s
85
  in aux ()
86
*)
87
let pp_machine_memtype_name fmt id = fprintf fmt "struct %s_mem" id
88
let pp_machine_regtype_name fmt id = fprintf fmt "struct %s_reg" id
89
let pp_machine_alloc_name fmt id = fprintf fmt "%s_alloc" id
90
let pp_machine_static_declare_name fmt id = fprintf fmt "%s_DECLARE" id
91
let pp_machine_static_link_name fmt id = fprintf fmt "%s_LINK" id
92
let pp_machine_static_alloc_name fmt id = fprintf fmt "%s_ALLOC" id
93
let pp_machine_reset_name fmt id = fprintf fmt "%s_reset" id
94
let pp_machine_step_name fmt id = fprintf fmt "%s_step" id
95

    
96
let pp_c_dimension fmt d =
97
 fprintf fmt "%a" Dimension.pp_dimension d
98

    
99
let pp_c_type var fmt t =
100
  let rec aux t pp_suffix =
101
  match (Types.repr t).Types.tdesc with
102
  | Types.Tclock t'       -> aux t' pp_suffix
103
  | Types.Tbool           -> fprintf fmt "_Bool %s%a" var pp_suffix ()
104
  | Types.Treal           -> fprintf fmt "double %s%a" var pp_suffix ()
105
  | Types.Tint            -> fprintf fmt "int %s%a" var pp_suffix ()
106
  | Types.Tarray (d, t')  ->
107
    let pp_suffix' fmt () = fprintf fmt "%a[%a]" pp_suffix () pp_c_dimension d in
108
    aux t' pp_suffix'
109
  | Types.Tstatic (_, t') -> fprintf fmt "const "; aux t' pp_suffix
110
  | Types.Tconst ty       -> fprintf fmt "%s %s" ty var
111
  | Types.Tarrow (_, _)   -> fprintf fmt "void (*%s)()" var
112
  | _                     -> eprintf "internal error: pp_c_type %a@." Types.print_ty t; assert false
113
  in aux t (fun fmt () -> ())
114

    
115
let rec pp_c_initialize fmt t = 
116
  match (Types.repr t).Types.tdesc with
117
  | Types.Tint -> pp_print_string fmt "0"
118
  | Types.Tclock t' -> pp_c_initialize fmt t'
119
  | Types.Tbool -> pp_print_string fmt "0" 
120
  | Types.Treal -> pp_print_string fmt "0."
121
  | Types.Tarray (d, t') when Dimension.is_dimension_const d ->
122
    fprintf fmt "{%a}"
123
      (Utils.fprintf_list ~sep:"," (fun fmt _ -> pp_c_initialize fmt t'))
124
      (Utils.duplicate 0 (Dimension.size_const_dimension d))
125
  | _ -> assert false
126

    
127
(* Declaration of an input variable:
128
   - if its type is array/matrix/etc, then declare it as a mere pointer,
129
     in order to cope with unknown/parametric array dimensions, 
130
     as it is the case for generics
131
*)
132
let pp_c_decl_input_var fmt id =
133
  if !Options.ansi && Types.is_address_type id.var_type
134
  then pp_c_type (sprintf "(*%s)" id.var_id) fmt (Types.array_base_type id.var_type)
135
  else pp_c_type id.var_id fmt id.var_type
136

    
137
(* Declaration of an output variable:
138
   - if its type is scalar, then pass its address
139
   - if its type is array/matrix/struct/etc, then declare it as a mere pointer,
140
     in order to cope with unknown/parametric array dimensions, 
141
     as it is the case for generics
142
*)
143
let pp_c_decl_output_var fmt id =
144
  if (not !Options.ansi) && Types.is_address_type id.var_type
145
  then pp_c_type                  id.var_id  fmt id.var_type
146
  else pp_c_type (sprintf "(*%s)" id.var_id) fmt (Types.array_base_type id.var_type)
147

    
148
(* Declaration of a local/mem variable:
149
   - if it's an array/matrix/etc, its size(s) should be
150
     known in order to statically allocate memory, 
151
     so we print the full type
152
*)
153
let pp_c_decl_local_var fmt id =
154
  pp_c_type id.var_id fmt id.var_type
155

    
156
let pp_c_decl_array_mem self fmt id =
157
  fprintf fmt "%a = (%a) (%s->_reg.%s)"
158
    (pp_c_type (sprintf "(*%s)" id.var_id)) id.var_type
159
    (pp_c_type "(*)") id.var_type
160
    self
161
    id.var_id
162

    
163
(* Declaration of a struct variable:
164
   - if it's an array/matrix/etc, we declare it as a pointer
165
*)
166
let pp_c_decl_struct_var fmt id =
167
  if Types.is_array_type id.var_type
168
  then pp_c_type (sprintf "(*%s)" id.var_id) fmt (Types.array_base_type id.var_type)
169
  else pp_c_type                  id.var_id  fmt id.var_type
170

    
171
(* Access to the value of a variable:
172
   - if it's not a scalar output, then its name is enough
173
   - otherwise, dereference it (it has been declared as a pointer,
174
     despite its scalar Lustre type)
175
   - moreover, cast arrays variables into their original array type.
176
*)
177
let pp_c_var_read m fmt id =
178
  if Types.is_address_type id.var_type
179
  then
180
    fprintf fmt "%s" id.var_id
181
  else
182
    if List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_outputs (* id is output *)
183
    then fprintf fmt "*%s" id.var_id
184
    else fprintf fmt "%s" id.var_id
185

    
186
(* Addressable value of a variable, the one that is passed around in calls:
187
   - if it's not a scalar non-output, then its name is enough
188
   - otherwise, reference it (it must be passed as a pointer,
189
     despite its scalar Lustre type)
190
*)
191
let pp_c_var_write m fmt id =
192
  if Types.is_address_type id.var_type
193
  then
194
    fprintf fmt "%s" id.var_id
195
  else
196
    if List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_outputs (* id is output *)
197
    then
198
      fprintf fmt "%s" id.var_id
199
    else
200
      fprintf fmt "&%s" id.var_id
201

    
202
let pp_c_decl_instance_var fmt (name, (node, static)) = 
203
  fprintf fmt "%a *%s" pp_machine_memtype_name (node_name node) name
204

    
205
let pp_c_tag fmt t =
206
 pp_print_string fmt (if t = tag_true then "1" else if t = tag_false then "0" else t)
207

    
208
(* Prints a constant value *)
209
let rec pp_c_const fmt c =
210
  match c with
211
    | Const_int i     -> pp_print_int fmt i
212
    | Const_real r    -> pp_print_string fmt r
213
    | Const_float r   -> pp_print_float fmt r
214
    | Const_tag t     -> pp_c_tag fmt t
215
    | Const_array ca  -> fprintf fmt "{%a }" (Utils.fprintf_list ~sep:", " pp_c_const) ca
216
    | Const_struct fl -> fprintf fmt "{%a }" (Utils.fprintf_list ~sep:", " (fun fmt (f, c) -> pp_c_const fmt c)) fl
217

    
218
(* Prints a value expression [v], with internal function calls only.
219
   [pp_var] is a printer for variables (typically [pp_c_var_read]),
220
   but an offset suffix may be added for array variables
221
*)
222
let rec pp_c_val self pp_var fmt v =
223
  match v with
224
    | Cst c         -> pp_c_const fmt c
225
    | Array vl      -> fprintf fmt "{%a}" (Utils.fprintf_list ~sep:", " (pp_c_val self pp_var)) vl
226
    | Access (t, i) -> fprintf fmt "%a[%a]" (pp_c_val self pp_var) t (pp_c_val self pp_var) i
227
    | Power (v, n)  -> assert false
228
    | LocalVar v    -> pp_var fmt v
229
    | StateVar v    ->
230
      if Types.is_array_type v.var_type
231
      then fprintf fmt "*%a" pp_var v
232
      else fprintf fmt "%s->_reg.%a" self pp_var v
233
    | Fun (n, vl)   -> Basic_library.pp_c n (pp_c_val self pp_var) fmt vl
234

    
235
let pp_c_checks self fmt m =
236
  Utils.fprintf_list ~sep:"" (fun fmt (loc, check) -> fprintf fmt "@[<v>%a@,assert (%a);@]@," Location.pp_c_loc loc (pp_c_val self (pp_c_var_read m)) check) fmt m.mstep.step_checks
237

    
238

    
239
(********************************************************************************************)
240
(*                    Instruction Printing functions                                        *)
241
(********************************************************************************************)
242

    
243
(* Computes the depth to which multi-dimension array assignments should be expanded.
244
   It equals the maximum number of nested static array constructions accessible from root [v].
245
*)
246
let rec expansion_depth v =
247
 match v with
248
 | Cst (Const_array cl) -> 1 + List.fold_right (fun c -> max (expansion_depth (Cst c))) cl 0
249
 | Cst _
250
 | LocalVar _
251
 | StateVar _  -> 0
252
 | Fun (_, vl) -> List.fold_right (fun v -> max (expansion_depth v)) vl 0
253
 | Array vl    -> 1 + List.fold_right (fun v -> max (expansion_depth v)) vl 0
254
 | Access (v, i) -> max 0 (expansion_depth v - 1)
255
 | Power (v, n)  -> 0 (*1 + expansion_depth v*)
256

    
257
type loop_index = LVar of ident | LInt of int ref
258

    
259
(* Computes the list of nested loop variables together with their dimension bounds.
260
   - LInt r stands for loop expansion (no loop variable, but int loop index)
261
   - LVar v stands for loop variable v
262
*)
263
let rec mk_loop_variables m ty depth =
264
 match (Types.repr ty).Types.tdesc, depth with
265
 | Types.Tarray (d, ty'), 0       ->
266
   let v = mk_loop_var m () in
267
   (d, LVar v) :: mk_loop_variables m ty' 0
268
 | Types.Tarray (d, ty'), _       ->
269
   let r = ref (-1) in
270
   (d, LInt r) :: mk_loop_variables m ty' (depth - 1)
271
 | _                    , 0       -> []
272
 | _                              -> assert false
273

    
274
let reorder_loop_variables loop_vars =
275
  let (int_loops, var_loops) = List.partition (function (d, LInt _) -> true | _ -> false) loop_vars in
276
  var_loops @ int_loops
277

    
278
(* Prints a one loop variable suffix for arrays *)
279
let pp_loop_var fmt lv =
280
 match snd lv with
281
 | LVar v -> fprintf fmt "[%s]" v
282
 | LInt r -> fprintf fmt "[%d]" !r
283

    
284
(* Prints a suffix of loop variables for arrays *)
285
let pp_suffix fmt loop_vars =
286
 Utils.fprintf_list ~sep:"" pp_loop_var fmt loop_vars
287

    
288
(* Prints a [value] indexed by the suffix list [loop_vars] *)
289
let rec pp_value_suffix self loop_vars pp_value fmt value =
290
 match loop_vars, value with
291
 | (_, LInt r) :: q, Array vl     ->
292
   pp_value_suffix self q pp_value fmt (List.nth vl !r)
293
 | _           :: q, Power (v, n) ->
294
   pp_value_suffix self loop_vars pp_value fmt v
295
 | _               , Fun (n, vl)  ->
296
   Basic_library.pp_c n (pp_value_suffix self loop_vars pp_value) fmt vl
297
 | _               , _            ->
298
   let pp_var_suffix fmt v = fprintf fmt "%a%a" pp_value v pp_suffix loop_vars in
299
   pp_c_val self pp_var_suffix fmt value
300

    
301
(* type_directed assignment: array vs. statically sized type
302
   - [var_type]: type of variable to be assigned
303
   - [var_name]: name of variable to be assigned
304
   - [value]: assigned value
305
   - [pp_var]: printer for variables
306
*)
307
let pp_assign m self pp_var fmt var_type var_name value =
308
  let depth = expansion_depth value in
309
(*eprintf "pp_assign %a %a %d@." Types.print_ty var_type pp_val value depth;*)
310
  let loop_vars = mk_loop_variables m var_type depth in
311
  let reordered_loop_vars = reorder_loop_variables loop_vars in
312
  let rec aux fmt vars =
313
    match vars with
314
    | [] ->
315
      fprintf fmt "%a = %a;" (pp_value_suffix self loop_vars pp_var) var_name (pp_value_suffix self loop_vars pp_var) value
316
    | (d, LVar i) :: q ->
317
(*eprintf "pp_aux %a %s@." Dimension.pp_dimension d i;*)
318
      fprintf fmt "@[<v 2>{@,int %s;@,for(%s=0;%s<%a;%s++)@,%a @]@,}"
319
	i i i Dimension.pp_dimension d i
320
	aux q
321
    | (d, LInt r) :: q ->
322
(*eprintf "pp_aux %a %d@." Dimension.pp_dimension d (!r);*)
323
      let szl = Utils.enumerate (Dimension.size_const_dimension d) in
324
      fprintf fmt "@[<v 2>{@,%a@]@,}"
325
	(Utils.fprintf_list ~sep:"@," (fun fmt i -> r := i; aux fmt q)) szl
326
  in
327
  begin
328
    reset_loop_counter ();
329
    (*reset_addr_counter ();*)
330
    aux fmt reordered_loop_vars
331
  end
332

    
333
let pp_instance_call m self fmt i (inputs: value_t list) (outputs: var_decl list) =
334
 try (* stateful node instance *)
335
   let (n,_) = List.assoc i m.minstances in
336
   fprintf fmt "%a (%a%t%a%t%s->%s);"
337
     pp_machine_step_name (node_name n)
338
     (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) inputs
339
     (Utils.pp_final_char_if_non_empty ", " inputs) 
340
     (Utils.fprintf_list ~sep:", " (pp_c_var_write m)) outputs
341
     (Utils.pp_final_char_if_non_empty ", " outputs)
342
     self
343
     i
344
 with Not_found -> (* stateless node instance *)
345
   let (n,_) = List.assoc i m.mcalls in
346
   fprintf fmt "%a (%a%t%a);"
347
     pp_machine_step_name (node_name n)
348
     (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) inputs
349
     (Utils.pp_final_char_if_non_empty ", " inputs) 
350
     (Utils.fprintf_list ~sep:", " (pp_c_var_write m)) outputs 
351

    
352
let pp_machine_reset (m: machine_t) self fmt inst =
353
  let (node, static) = List.assoc inst m.minstances in
354
  fprintf fmt "%a(%a%t%s->%s);"
355
    pp_machine_reset_name (node_name node)
356
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
357
    (Utils.pp_final_char_if_non_empty ", " static)
358
    self inst
359

    
360
let has_c_prototype funname dependencies =
361
  let imported_node_opt = (* We select the last imported node with the name funname.
362
			       The order of evaluation of dependencies should be
363
			       compatible with overloading. (Not checked yet) *) 
364
      List.fold_left
365
	(fun res (_, _, decls) -> 
366
	  match res with
367
	  | Some _ -> res
368
	  | None -> 
369
	    let matched = fun t -> match t.top_decl_desc with 
370
	      | ImportedNode nd -> nd.nodei_id = funname 
371
	      | _ -> false
372
	    in
373
	    if List.exists matched decls then (
374
	      match (List.find matched decls).top_decl_desc with
375
	      | ImportedNode nd -> Some nd
376
	      | _ -> assert false
377
	    )
378
	    else
379
	      None
380
	) None dependencies in
381
    match imported_node_opt with
382
    | None -> false
383
    | Some nd -> (match nd.nodei_prototype with Some "C" -> true | _ -> false)
384

    
385
let rec pp_conditional dependencies (m: machine_t) self fmt c tl el =
386
  fprintf fmt "@[<v 2>if (%a) {%t%a@]@,@[<v 2>} else {%t%a@]@,}"
387
    (pp_c_val self (pp_c_var_read m)) c
388
    (Utils.pp_newline_if_non_empty tl)
389
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) tl
390
    (Utils.pp_newline_if_non_empty el)
391
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) el
392

    
393
and pp_machine_instr dependencies (m: machine_t) self fmt instr =
394
  match instr with 
395
  | MReset i ->
396
    pp_machine_reset m self fmt i
397
  | MLocalAssign (i,v) ->
398
    pp_assign
399
      m self (pp_c_var_read m) fmt
400
      i.var_type (LocalVar i) v
401
  | MStateAssign (i,v) ->
402
    pp_assign
403
      m self (pp_c_var_read m) fmt
404
      i.var_type (StateVar i) v
405
  | MStep ([i0], i, vl) when Basic_library.is_internal_fun i  ->
406
    pp_machine_instr dependencies m self fmt (MLocalAssign (i0, Fun (i, vl)))
407
  | MStep ([i0], i, vl) when has_c_prototype i dependencies -> 
408
    fprintf fmt "%a = %s(%a);" 
409
      (pp_c_val self (pp_c_var_read m)) (LocalVar i0) 
410
      i
411
      (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) vl
412
  | MStep (il, i, vl) ->
413
    pp_instance_call m self fmt i vl il
414
  | MBranch (g,hl) ->
415
    if hl <> [] && let t = fst (List.hd hl) in t = tag_true || t = tag_false
416
    then (* boolean case, needs special treatment in C because truth value is not unique *)
417
	 (* may disappear if we optimize code by replacing last branch test with default *)
418
      let tl = try List.assoc tag_true  hl with Not_found -> [] in
419
      let el = try List.assoc tag_false hl with Not_found -> [] in
420
      pp_conditional dependencies m self fmt g tl el
421
    else (* enum type case *)
422
      fprintf fmt "@[<v 2>switch(%a) {@,%a@,}@]"
423
	(pp_c_val self (pp_c_var_read m)) g
424
	(Utils.fprintf_list ~sep:"@," (pp_machine_branch dependencies m self)) hl
425

    
426
and pp_machine_branch dependencies m self fmt (t, h) =
427
  fprintf fmt "@[<v 2>case %a:@,%a@,break;@]" pp_c_tag t (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) h
428

    
429

    
430
(**************************************************************************)
431
(*     Printing spec for c *)
432

    
433
(**************************************************************************)
434

    
435

    
436
let pp_econst fmt c = 
437
  match c with
438
    | EConst_int i -> pp_print_int fmt i
439
    | EConst_real r -> pp_print_string fmt r
440
    | EConst_float r -> pp_print_float fmt r
441
    | EConst_bool b -> pp_print_bool fmt b
442
    | EConst_string s -> pp_print_string fmt ("\"" ^ s ^ "\"")
443

    
444
let rec pp_eexpr is_output fmt eexpr = 
445
  let pp_eexpr = pp_eexpr is_output in
446
  match eexpr.eexpr_desc with
447
    | EExpr_const c -> pp_econst fmt c
448
    | EExpr_ident id -> 
449
      if is_output id then pp_print_string fmt ("*" ^ id) else pp_print_string fmt id
450
    | EExpr_tuple el -> Utils.fprintf_list ~sep:"," pp_eexpr fmt el
451
    | EExpr_arrow (e1, e2) -> fprintf fmt "%a -> %a" pp_eexpr e1 pp_eexpr e2
452
    | EExpr_fby (e1, e2) -> fprintf fmt "%a fby %a" pp_eexpr e1 pp_eexpr e2
453
    (* | EExpr_concat (e1, e2) -> fprintf fmt "%a::%a" pp_eexpr e1 pp_eexpr e2 *)
454
    (* | EExpr_tail e -> fprintf fmt "tail %a" pp_eexpr e *)
455
    | EExpr_pre e -> fprintf fmt "pre %a" pp_eexpr e
456
    | EExpr_when (e, id) -> fprintf fmt "%a when %s" pp_eexpr e id
457
    | EExpr_merge (id, e1, e2) -> 
458
      fprintf fmt "merge (%s, %a, %a)" id pp_eexpr e1 pp_eexpr e2
459
    | EExpr_appl (id, e, r) -> pp_eapp is_output fmt id e r
460
    | EExpr_forall (vars, e) -> fprintf fmt "forall %a; %a" Printers.pp_node_args vars pp_eexpr e 
461
    | EExpr_exists (vars, e) -> fprintf fmt "exists %a; %a" Printers.pp_node_args vars pp_eexpr e 
462

    
463

    
464
    (* | EExpr_whennot _ *)
465
    (* | EExpr_uclock _ *)
466
    (* | EExpr_dclock _ *)
467
    (* | EExpr_phclock _ -> assert false *)
468
and pp_eapp is_output fmt id e r =
469
  let pp_eexpr = pp_eexpr is_output in
470
  match r with
471
  | None ->
472
    (match id, e.eexpr_desc with
473
    | "+", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a + %a)" pp_eexpr e1 pp_eexpr e2
474
    | "uminus", _ -> fprintf fmt "(- %a)" pp_eexpr e
475
    | "-", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a - %a)" pp_eexpr e1 pp_eexpr e2
476
    | "*", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a * %a)" pp_eexpr e1 pp_eexpr e2
477
    | "/", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a / %a)" pp_eexpr e1 pp_eexpr e2
478
    | "mod", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a mod %a)" pp_eexpr e1 pp_eexpr e2
479
    | "&&", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a && %a)" pp_eexpr e1 pp_eexpr e2
480
    | "||", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a || %a)" pp_eexpr e1 pp_eexpr e2
481
    | "xor", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a ^^ %a)" pp_eexpr e1 pp_eexpr e2
482
    | "impl", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a ==> %a)" pp_eexpr e1 pp_eexpr e2
483
    | "<", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a < %a)" pp_eexpr e1 pp_eexpr e2
484
    | "<=", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a <= %a)" pp_eexpr e1 pp_eexpr e2
485
    | ">", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a > %a)" pp_eexpr e1 pp_eexpr e2
486
    | ">=", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a >= %a)" pp_eexpr e1 pp_eexpr e2
487
    | "!=", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a != %a)" pp_eexpr e1 pp_eexpr e2
488
    | "=", EExpr_tuple([e1;e2]) -> fprintf fmt "(%a == %a)" pp_eexpr e1 pp_eexpr e2
489
    | "not", _ -> fprintf fmt "(! %a)" pp_eexpr e
490
    | "ite", EExpr_tuple([e1;e2;e3]) -> fprintf fmt "(if %a then %a else %a)" pp_eexpr e1 pp_eexpr e2 pp_eexpr e3
491
    | _ -> fprintf fmt "%s (%a)" id pp_eexpr e)
492
  | Some x -> fprintf fmt "%s (%a) every %s" id pp_eexpr e x 
493

    
494
let pp_ensures is_output fmt e =
495
  match e with
496
    | EnsuresExpr e -> fprintf fmt "ensures %a;@ " (pp_eexpr is_output) e
497
    | SpecObserverNode (name, args) -> fprintf fmt "observer %s (%a);@ " name (Utils.fprintf_list ~sep:", " (pp_eexpr is_output)) args
498

    
499
let pp_acsl_spec outputs fmt spec =
500
  let is_output = fun oid -> List.exists (fun v -> v.var_id = oid) outputs in
501
  let pp_eexpr = pp_eexpr is_output in
502
  fprintf fmt "@[<v 2>/*@@ ";
503
  Utils.fprintf_list ~sep:"" (fun fmt r -> fprintf fmt "requires %a;@ " pp_eexpr r) fmt spec.requires;
504
  Utils.fprintf_list ~sep:"" (pp_ensures is_output) fmt spec.ensures;
505
  fprintf fmt "@ ";
506
  (* fprintf fmt "assigns *self%t%a;@ "  *)
507
  (*   (fun fmt -> if List.length outputs > 0 then fprintf fmt ", ") *)
508
  (*   (fprintf_list ~sep:"," (fun fmt v -> fprintf fmt "*%s" v.var_id)) outputs; *)
509
  Utils.fprintf_list ~sep:"@ " (fun fmt (name, assumes, requires) -> 
510
    fprintf fmt "behavior %s:@[@ %a@ %a@]" 
511
      name
512
      (Utils.fprintf_list ~sep:"@ " (fun fmt r -> fprintf fmt "assumes %a;" pp_eexpr r)) assumes
513
      (Utils.fprintf_list ~sep:"@ " (pp_ensures is_output)) requires
514
  ) fmt spec.behaviors;
515
  fprintf fmt "@]@ */@.";
516
  ()
517

    
518
(********************************************************************************************)
519
(*                      Prototype Printing functions                                        *)
520
(********************************************************************************************)
521

    
522
let print_alloc_prototype fmt (name, static) =
523
  fprintf fmt "%a * %a (%a)"
524
    pp_machine_memtype_name name
525
    pp_machine_alloc_name name
526
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) static
527

    
528
let print_reset_prototype self fmt (name, static) =
529
  fprintf fmt "void %a (@[<v>%a%t%a *%s@])"
530
    pp_machine_reset_name name
531
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) static
532
    (Utils.pp_final_char_if_non_empty ",@," static) 
533
    pp_machine_memtype_name name
534
    self
535

    
536
let print_stateless_prototype fmt (name, inputs, outputs) =
537
  fprintf fmt "void %a (@[<v>@[%a%t@]@,@[%a@]@,@])"
538
    pp_machine_step_name name
539
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) inputs
540
    (Utils.pp_final_char_if_non_empty ",@ " inputs) 
541
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_output_var) outputs
542

    
543
let print_step_prototype self fmt (name, inputs, outputs) =
544
  fprintf fmt "void %a (@[<v>@[%a%t@]@,@[%a@]%t@[%a *%s@]@])"
545
    pp_machine_step_name name
546
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) inputs
547
    (Utils.pp_final_char_if_non_empty ",@ " inputs) 
548
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_output_var) outputs
549
    (Utils.pp_final_char_if_non_empty ",@," outputs) 
550
    pp_machine_memtype_name name
551
    self
552

    
553
(********************************************************************************************)
554
(*                         Header Printing functions                                        *)
555
(********************************************************************************************)
556

    
557

    
558
let print_import_standard fmt =
559
  fprintf fmt "#include \"%s/include/lustrec/arrow.h\"@.@." Version.prefix
560

    
561
let print_import_prototype fmt (s, _, _) =
562
  fprintf fmt "#include \"%s.h\"@," s
563
    
564
let pp_registers_struct fmt m =
565
  if m.mmemory <> []
566
  then
567
    fprintf fmt "@[%a {@[%a; @]}@] _reg; "
568
      pp_machine_regtype_name m.mname.node_id
569
      (Utils.fprintf_list ~sep:"; " pp_c_decl_struct_var) m.mmemory
570
  else
571
    ()
572

    
573
let print_machine_struct fmt m =
574
  if fst (get_stateless_status m) then
575
    begin
576
    end
577
  else
578
    begin
579
      (* Define struct *)
580
      fprintf fmt "@[%a {@[%a%a%t@]};@]@."
581
	pp_machine_memtype_name m.mname.node_id
582
	pp_registers_struct m
583
	(Utils.fprintf_list ~sep:"; " pp_c_decl_instance_var) m.minstances
584
	(Utils.pp_final_char_if_non_empty "; " m.minstances)
585
    end
586

    
587
let print_static_declare_instance attr fmt (i, (m, static)) =
588
  fprintf fmt "%a(%s, %a%t%s)"
589
    pp_machine_static_declare_name (node_name m)
590
    attr
591
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
592
    (Utils.pp_final_char_if_non_empty ", " static)
593
    i
594

    
595
let print_static_declare_macro fmt m =
596
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
597
  let inst = mk_instance m in
598
  let attr = mk_attribute m in
599
  fprintf fmt "@[<v 2>#define %a(%s, %a%t%s)\\@,%s %a %s;\\@,%a%t%a;@,@]"
600
    pp_machine_static_declare_name m.mname.node_id
601
    attr
602
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
603
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
604
    inst
605
    attr
606
    pp_machine_memtype_name m.mname.node_id
607
    inst
608
    (Utils.fprintf_list ~sep:";\\@," pp_c_decl_local_var) array_mem
609
    (Utils.pp_final_char_if_non_empty ";\\@," array_mem)
610
    (Utils.fprintf_list ~sep:";\\@,"
611
       (fun fmt (i',m') ->
612
	 let path = sprintf "inst ## _%s" i' in
613
	 fprintf fmt "%a"
614
	   (print_static_declare_instance attr) (path,m')
615
       )) m.minstances
616

    
617
      
618
let print_static_link_instance fmt (i, (m, _)) =
619
 fprintf fmt "%a(%s)" pp_machine_static_link_name (node_name m) i
620

    
621
let print_static_link_macro fmt m =
622
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
623
  fprintf fmt "@[<v>@[<v 2>#define %a(inst) do {\\@,%a%t%a;\\@]@,} while (0)@.@]"
624
    pp_machine_static_link_name m.mname.node_id
625
    (Utils.fprintf_list ~sep:";\\@,"
626
       (fun fmt v ->
627
	 fprintf fmt "inst.%s = &%s"
628
	   v.var_id
629
	   v.var_id
630
       )) array_mem
631
    (Utils.pp_final_char_if_non_empty ";\\@," array_mem)
632
    (Utils.fprintf_list ~sep:";\\@,"
633
       (fun fmt (i',m') ->
634
	 let path = sprintf "inst ## _%s" i' in
635
	 fprintf fmt "%a;\\@,inst.%s = &%s"
636
	   print_static_link_instance (path,m')
637
	   i'
638
	   path
639
       )) m.minstances
640
      
641
let print_static_alloc_macro fmt m =
642
  fprintf fmt "@[<v>@[<v 2>#define %a(attr,%a%tinst)\\@,%a(attr,%a%tinst);\\@,%a(inst);@]@,@]@."
643
    pp_machine_static_alloc_name m.mname.node_id
644
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
645
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
646
    pp_machine_static_declare_name m.mname.node_id
647
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
648
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
649
    pp_machine_static_link_name m.mname.node_id
650

    
651
let print_machine_decl fmt m =
652
  if fst (get_stateless_status m) then
653
    begin
654
      (* Print specification if any *)
655
      (match m.mspec with
656
      | None -> ()
657
      | Some spec -> 
658
	pp_acsl_spec m.mstep.step_outputs fmt spec
659
      );
660
      fprintf fmt "extern %a;@.@."
661
	print_stateless_prototype
662
	(m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
663
    end
664
  else
665
    begin
666
      (* Static allocation *)
667
      if !Options.static_mem
668
      then (
669
	fprintf fmt "%a@.%a@.%a@."
670
	  print_static_declare_macro m
671
	  print_static_link_macro m
672
	  print_static_alloc_macro m
673
      )
674
      else ( 
675
        (* Dynamic allocation *)
676
	fprintf fmt "extern %a;@.@."
677
	  print_alloc_prototype (m.mname.node_id, m.mstatic)
678
      );
679
      let self = mk_self m in
680
      fprintf fmt "extern %a;@.@."
681
	(print_reset_prototype self) (m.mname.node_id, m.mstatic);
682
      (* Print specification if any *)
683
      (match m.mspec with
684
      | None -> ()
685
      | Some spec -> 
686
	pp_acsl_spec m.mstep.step_outputs fmt spec
687
      );
688
      fprintf fmt "extern %a;@.@."
689
	(print_step_prototype self)
690
	(m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
691
    end
692

    
693

    
694
(********************************************************************************************)
695
(*                         C file Printing functions                                        *)
696
(********************************************************************************************)
697

    
698
let print_const_def fmt cdecl =
699
  fprintf fmt "%a = %a;@." (pp_c_type cdecl.const_id) cdecl.const_type pp_c_const cdecl.const_value 
700

    
701
let print_const_decl fmt cdecl =
702
  fprintf fmt "extern %a;@." (pp_c_type cdecl.const_id) cdecl.const_type
703

    
704
let print_alloc_instance fmt (i, (m, static)) =
705
  fprintf fmt "_alloc->%s = %a (%a);@,"
706
    i
707
    pp_machine_alloc_name (node_name m)
708
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
709

    
710
let print_alloc_array fmt vdecl =
711
  let base_type = Types.array_base_type vdecl.var_type in
712
  let size_types = Types.array_type_multi_dimension vdecl.var_type in
713
  let size_type = Dimension.multi_dimension_product vdecl.var_loc size_types in
714
  fprintf fmt "_alloc->%s = (%a*) malloc((%a)*sizeof(%a));@,assert(_alloc->%s);@,"
715
    vdecl.var_id
716
    (pp_c_type "") base_type
717
    Dimension.pp_dimension size_type
718
    (pp_c_type "") base_type
719
    vdecl.var_id
720

    
721
let print_alloc_code fmt m =
722
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
723
  fprintf fmt "%a *_alloc;@,_alloc = (%a *) malloc(sizeof(%a));@,assert(_alloc);@,%a%areturn _alloc;"
724
    pp_machine_memtype_name m.mname.node_id
725
    pp_machine_memtype_name m.mname.node_id
726
    pp_machine_memtype_name m.mname.node_id
727
    (Utils.fprintf_list ~sep:"" print_alloc_array) array_mem
728
    (Utils.fprintf_list ~sep:"" print_alloc_instance) m.minstances
729

    
730
let print_stateless_code dependencies fmt m =
731
  let self = "__ERROR__" in
732
  if not (!Options.ansi && is_generic_node { top_decl_desc = Node m.mname; top_decl_loc = Location.dummy_loc })
733
  then
734
    (* C99 code *)
735
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
736
      print_stateless_prototype (m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
737
      (* locals *)
738
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) m.mstep.step_locals
739
      (Utils.pp_final_char_if_non_empty ";@," m.mstep.step_locals)
740
      (* check assertions *)
741
      (pp_c_checks self) m
742
      (* instrs *)
743
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
744
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
745
      (fun fmt -> fprintf fmt "return;")
746
  else
747
    (* C90 code *)
748
    let (gen_locals, base_locals) = List.partition (fun v -> Types.is_generic_type v.var_type) m.mstep.step_locals in
749
    let gen_calls = List.map (fun e -> let (id, _, _) = call_of_expr e in mk_call_var_decl e.expr_loc id) m.mname.node_gencalls in
750
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
751
      print_stateless_prototype (m.mname.node_id, (m.mstep.step_inputs@gen_locals@gen_calls), m.mstep.step_outputs)
752
      (* locals *)
753
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) base_locals
754
      (Utils.pp_final_char_if_non_empty ";" base_locals)
755
      (* check assertions *)
756
      (pp_c_checks self) m
757
      (* instrs *)
758
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
759
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
760
      (fun fmt -> fprintf fmt "return;")
761

    
762
let print_reset_code dependencies fmt m self =
763
  fprintf fmt "@[<v 2>%a {@,%a%treturn;@]@,}@.@."
764
    (print_reset_prototype self) (m.mname.node_id, m.mstatic)
765
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.minit
766
    (Utils.pp_newline_if_non_empty m.minit)
767

    
768
let print_step_code dependencies fmt m self =
769
  if not (!Options.ansi && is_generic_node { top_decl_desc = Node m.mname; top_decl_loc = Location.dummy_loc })
770
  then
771
    (* C99 code *)
772
    let array_mems = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
773
    fprintf fmt "@[<v 2>%a {@,%a%t%a%t@,%a%a%t%t@]@,}@.@."
774
      (print_step_prototype self) (m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
775
      (* locals *)
776
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) m.mstep.step_locals
777
      (Utils.pp_final_char_if_non_empty ";@," m.mstep.step_locals)
778
      (* array mems *)
779
      (Utils.fprintf_list ~sep:";@," (pp_c_decl_array_mem self)) array_mems
780
      (Utils.pp_final_char_if_non_empty ";@," array_mems)
781
      (* check assertions *)
782
      (pp_c_checks self) m
783
      (* instrs *)
784
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
785
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
786
      (fun fmt -> fprintf fmt "return;")
787
  else
788
    (* C90 code *)
789
    let (gen_locals, base_locals) = List.partition (fun v -> Types.is_generic_type v.var_type) m.mstep.step_locals in
790
    let gen_calls = List.map (fun e -> let (id, _, _) = call_of_expr e in mk_call_var_decl e.expr_loc id) m.mname.node_gencalls in
791
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
792
      (print_step_prototype self) (m.mname.node_id, (m.mstep.step_inputs@gen_locals@gen_calls), m.mstep.step_outputs)
793
      (* locals *)
794
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) base_locals
795
      (Utils.pp_final_char_if_non_empty ";" base_locals)
796
      (* check assertions *)
797
      (pp_c_checks self) m
798
      (* instrs *)
799
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
800
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
801
      (fun fmt -> fprintf fmt "return;")
802

    
803
let print_machine dependencies fmt m =
804
  if fst (get_stateless_status m) then
805
    begin
806
      (* Step function *)
807
      print_stateless_code dependencies fmt m
808
    end
809
  else
810
    begin
811
      (* Alloc function, only if non static mode *)
812
      if (not !Options.static_mem) then  
813
	(
814
	  fprintf fmt "@[<v 2>%a {@,%a@]@,}@.@."
815
	    print_alloc_prototype (m.mname.node_id, m.mstatic)
816
	    print_alloc_code m;
817
	);
818
      let self = mk_self m in
819
      (* Reset function *)
820
      print_reset_code dependencies fmt m self;
821
      (* Step function *)
822
      print_step_code dependencies fmt m self
823
    end
824

    
825
(********************************************************************************************)
826
(*                         Main related functions                                           *)
827
(********************************************************************************************)
828

    
829
let print_get_input fmt v =
830
  match v.var_type.Types.tdesc with
831
    | Types.Tint -> fprintf fmt "_get_int(\"%s\")" v.var_id
832
    | Types.Tbool -> fprintf fmt "_get_bool(\"%s\")" v.var_id
833
    | Types.Treal -> fprintf fmt "_get_double(\"%s\")" v.var_id
834
    | _ -> assert false
835

    
836
let print_put_outputs fmt ol = 
837
  let po fmt o =
838
    match o.var_type.Types.tdesc with
839
    | Types.Tint -> fprintf fmt "_put_int(\"%s\", %s)" o.var_id o.var_id
840
    | Types.Tbool -> fprintf fmt "_put_bool(\"%s\", %s)" o.var_id o.var_id
841
    | Types.Treal -> fprintf fmt "_put_double(\"%s\", %s)" o.var_id o.var_id
842
    | _ -> assert false
843
  in
844
  List.iter (fprintf fmt "@ %a;" po) ol
845

    
846
let print_main_fun machines m fmt =
847
  let mname = m.mname.node_id in
848
  let main_mem =
849
    if (!Options.static_mem && !Options.main_node <> "")
850
    then "&main_mem"
851
    else "main_mem" in
852
  fprintf fmt "@[<v 2>int main (int argc, char *argv[]) {@ ";
853
  fprintf fmt "/* Declaration of inputs/outputs variables */@ ";
854
  List.iter 
855
    (fun v -> fprintf fmt "%a = %a;@ " (pp_c_type v.var_id) v.var_type pp_c_initialize v.var_type
856
    ) m.mstep.step_inputs;
857
  List.iter 
858
    (fun v -> fprintf fmt "%a = %a;@ " (pp_c_type v.var_id) v.var_type pp_c_initialize v.var_type
859
    ) m.mstep.step_outputs;
860
  fprintf fmt "@ /* Main memory allocation */@ ";
861
  if (!Options.static_mem && !Options.main_node <> "")
862
  then (fprintf fmt "%a(static,main_mem);@ " pp_machine_static_alloc_name mname)
863
  else (fprintf fmt "%a *main_mem = %a();@ " pp_machine_memtype_name mname pp_machine_alloc_name mname);
864
  fprintf fmt "@ /* Initialize the main memory */@ ";
865
  fprintf fmt "%a(%s);@ " pp_machine_reset_name mname main_mem;
866
  fprintf fmt "@ ISATTY = isatty(0);@ ";
867
  fprintf fmt "@ /* Infinite loop */@ ";
868
  fprintf fmt "@[<v 2>while(1){@ ";
869
  fprintf fmt  "fflush(stdout);@ ";
870
  List.iter 
871
    (fun v -> fprintf fmt "%s = %a;@ "
872
      v.var_id
873
      print_get_input v
874
    ) m.mstep.step_inputs;
875
  (match m.mstep.step_outputs with
876
    (* | [] -> ( *)
877
    (*   fprintf fmt "%a(%a%t%s);@ "  *)
878
    (* 	pp_machine_step_name mname *)
879
    (* 	(Utils.fprintf_list ~sep:", " (fun fmt v -> pp_print_string fmt v.var_id)) m.mstep.step_inputs *)
880
    (* 	(pp_final_char_if_non_empty ", " m.mstep.step_inputs) *)
881
    (* 	main_mem *)
882
    (* ) *)
883
    (* | [o] -> ( *)
884
    (*   fprintf fmt "%s = %a(%a%t%a, %s);%a" *)
885
    (* 	o.var_id *)
886
    (* 	pp_machine_step_name mname *)
887
    (* 	(Utils.fprintf_list ~sep:", " (fun fmt v -> pp_print_string fmt v.var_id)) m.mstep.step_inputs *)
888
    (* 	(pp_final_char_if_non_empty ", " m.mstep.step_inputs) *)
889
    (* 	(Utils.fprintf_list ~sep:", " (fun fmt v -> fprintf fmt "&%s" v.var_id)) m.mstep.step_outputs *)
890
    (* 	main_mem *)
891
    (* 	print_put_outputs [o]) *)
892
    | _ -> (
893
      fprintf fmt "%a(%a%t%a, %s);%a"
894
	pp_machine_step_name mname
895
	(Utils.fprintf_list ~sep:", " (fun fmt v -> pp_print_string fmt v.var_id)) m.mstep.step_inputs
896
	(Utils.pp_final_char_if_non_empty ", " m.mstep.step_inputs)
897
	(Utils.fprintf_list ~sep:", " (fun fmt v -> fprintf fmt "&%s" v.var_id)) m.mstep.step_outputs
898
	main_mem
899
	print_put_outputs m.mstep.step_outputs)
900
  );
901
  fprintf fmt "@]@ }@ ";
902
  fprintf fmt "return 1;";
903
  fprintf fmt "@]@ }@."       
904

    
905
let print_main_header fmt =
906
  fprintf fmt "#include <stdio.h>@.#include <unistd.h>@.#include \"%s/include/lustrec/io_frontend.h\"@." Version.prefix
907

    
908
let rec pp_c_struct_type_field filename cpt fmt (label, tdesc) =
909
  fprintf fmt "%a;" (pp_c_type_decl filename cpt label) tdesc
910
and pp_c_type_decl filename cpt var fmt tdecl =
911
  match tdecl with
912
  | Tydec_any           -> assert false
913
  | Tydec_int           -> fprintf fmt "int %s" var
914
  | Tydec_real          -> fprintf fmt "double %s" var
915
  | Tydec_float         -> fprintf fmt "float %s" var
916
  | Tydec_bool          -> fprintf fmt "_Bool %s" var
917
  | Tydec_clock ty      -> pp_c_type_decl filename cpt var fmt ty
918
  | Tydec_const c       -> fprintf fmt "%s %s" c var
919
  | Tydec_array (d, ty) -> fprintf fmt "%a[%a]" (pp_c_type_decl filename cpt var) ty pp_c_dimension d
920
  | Tydec_enum tl ->
921
    begin
922
      incr cpt;
923
      fprintf fmt "enum _enum_%s_%d { %a } %s" filename !cpt (Utils.fprintf_list ~sep:", " pp_print_string) tl var
924
    end
925
  | Tydec_struct fl ->
926
    begin
927
      incr cpt;
928
      fprintf fmt "struct _struct_%s_%d { %a } %s" filename !cpt (Utils.fprintf_list ~sep:" " (pp_c_struct_type_field filename cpt)) fl var
929
    end
930

    
931
let print_type_definitions fmt filename =
932
  let cpt_type = ref 0 in
933
  Hashtbl.iter (fun typ def ->
934
    match typ with
935
    | Tydec_const var ->
936
      fprintf fmt "typedef %a;@.@."
937
	(pp_c_type_decl filename cpt_type var) def
938
    | _        -> ()) type_table
939

    
940

    
941
let header_has_code header =
942
  List.exists 
943
    (fun top -> 
944
      match top.top_decl_desc with
945
      | Consts _ -> true 
946
      | ImportedNode nd -> nd.nodei_in_lib = None
947
      | _ -> false
948
    )
949
    header
950

    
951
let header_libs header =
952
  List.fold_left (fun accu top ->
953
    match top.top_decl_desc with
954
      | ImportedNode nd -> (match nd.nodei_in_lib with 
955
	| None -> accu 
956
	| Some lib -> Utils.list_union [lib] accu)
957
      | _ -> accu 
958
  ) [] header 
959
    
960
let print_makefile basename nodename dependencies fmt =
961
  let compiled_dependencies = 
962
    List.filter (fun (_, _, header) -> header_has_code header) dependencies
963
  in
964
  let lib_dependencies = 
965
    List.fold_left 
966
      (fun accu (_, _, header) -> Utils.list_union (header_libs header) accu) [] dependencies 
967
  in
968
  fprintf fmt "GCC=gcc@.";
969
  fprintf fmt "LUSTREC=%s@." Sys.executable_name;
970
  fprintf fmt "LUSTREC_BASE=%s@." (Filename.dirname (Filename.dirname Sys.executable_name));
971
  fprintf fmt "INC=${LUSTREC_BASE}/include/lustrec@.";
972
  fprintf fmt "@.";
973
  fprintf fmt "%s_%s:@." basename nodename;
974
  fprintf fmt "\t${GCC} -I${INC} -I. -c %s.c@." basename;    
975
  List.iter (fun s -> (* Format.eprintf "Adding dependency: %s@." s;  *)
976
    fprintf fmt "\t${GCC} -I${INC} -c %s@." s)
977
    (("${INC}/io_frontend.c"):: (* IO functions when a main function is computed *)
978
	(List.map 
979
	   (fun (s, local, _) -> 
980
	     (if local then s else Version.prefix ^ "/include/lustrec/" ^ s) ^ ".c")
981
	   compiled_dependencies));    
982
  fprintf fmt "\t${GCC} -o %s_%s io_frontend.o %a %s.o %a@." basename nodename 
983
    (Utils.fprintf_list ~sep:" " (fun fmt (s, _, _) -> Format.fprintf fmt "%s.o" s)) compiled_dependencies 
984
    basename
985
    (Utils.fprintf_list ~sep:" " (fun fmt lib -> fprintf fmt "-l%s" lib)) lib_dependencies
986
    ;
987
 fprintf fmt "@.";
988
 fprintf fmt "clean:@.";
989
 fprintf fmt "\t\\rm -f *.o %s_%s@." basename nodename
990

    
991

    
992

    
993

    
994
(********************************************************************************************)
995
(*                         Translation function                                             *)
996
(********************************************************************************************)
997

    
998
let translate_to_c header_fmt source_fmt makefile_fmt spec_fmt_opt basename prog machines dependencies =
999
  (* Generating H file *)
1000

    
1001
  (* Include once: start *)
1002
  let baseNAME = String.uppercase basename in
1003
  let baseNAME = Str.global_replace (Str.regexp "\\.\\|\\ ") "_" baseNAME in
1004
  (* Print the svn version number and the supported C standard (C90 or C99) *)
1005
  print_version header_fmt;
1006
  fprintf header_fmt "#ifndef _%s@.#define _%s@." baseNAME baseNAME;
1007
  pp_print_newline header_fmt ();
1008
  fprintf header_fmt "/* Imports standard library */@.";
1009
  (* imports standard library definitions (arrow) *)
1010
  print_import_standard header_fmt;
1011
  pp_print_newline header_fmt ();
1012
  fprintf header_fmt "/* Types definitions */@.";
1013
  (* Print the type definitions from the type table *)
1014
  print_type_definitions header_fmt basename;
1015
  pp_print_newline header_fmt ();
1016
  (* Print the global constant declarations. *)
1017
  fprintf header_fmt "/* Global constant (declarations, definitions are in C file) */@.";
1018
  List.iter (fun c -> print_const_decl header_fmt c) (get_consts prog);
1019
  pp_print_newline header_fmt ();
1020
  (* Print the struct declarations of all machines. *)
1021
  fprintf header_fmt "/* Struct declarations */@.";
1022
  List.iter (print_machine_struct header_fmt) machines;
1023
  pp_print_newline header_fmt ();
1024
  (* Print the prototypes of all machines *)
1025
  fprintf header_fmt "/* Nodes declarations */@.";
1026
  List.iter (print_machine_decl header_fmt) machines;
1027
  pp_print_newline header_fmt ();
1028
  (* Include once: end *)
1029
  fprintf header_fmt "#endif@.";
1030
  pp_print_newline header_fmt ();
1031

    
1032
  (* Generating C file *)
1033

    
1034
  (* If a main node is identified, generate a main function for it *)
1035
  let main_include, main_print, main_makefile =
1036
    match !Options.main_node with
1037
      | "" -> (fun _ -> ()), (fun _ -> ()), (fun _ -> ())
1038
      | main_node -> (
1039
	match Machine_code.get_machine_opt main_node machines with
1040
	| None -> eprintf "Unable to find a main node named %s@.@?" main_node; (fun _ -> ()), (fun _ -> ()), (fun _ -> ())
1041
	| Some m -> print_main_header, print_main_fun machines m, print_makefile basename !Options.main_node dependencies
1042
      )
1043
  in
1044
  main_include source_fmt;
1045
  fprintf source_fmt "#include <stdlib.h>@.#include <assert.h>@.#include \"%s\"@.@." (basename^".h");
1046
  (* Print the svn version number and the supported C standard (C90 or C99) *)
1047
  print_version source_fmt;
1048
  (* Print the prototype of imported nodes *)
1049
  fprintf source_fmt "/* Imported nodes declarations */@.";
1050
  fprintf source_fmt "@[<v>";
1051
  List.iter (print_import_prototype source_fmt) dependencies;
1052
  fprintf source_fmt "@]@.";
1053
  (* Print consts *)
1054
  fprintf source_fmt "/* Global constants (definitions) */@.";
1055
  List.iter (fun c -> print_const_def source_fmt c) (get_consts prog);
1056
  pp_print_newline source_fmt ();
1057
  (* Print nodes one by one (in the previous order) *)
1058
  List.iter (print_machine dependencies source_fmt) machines;
1059
  main_print source_fmt;
1060

    
1061
  (* Generating Makefile *)
1062
  main_makefile makefile_fmt
1063

    
1064
(* Local Variables: *)
1065
(* compile-command:"make -C .." *)
1066
(* End: *)