Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / machine_code.ml @ 8446bf03

History | View | Annotate | Download (27.5 KB)

1
(********************************************************************)
2
(*                                                                  *)
3
(*  The LustreC compiler toolset   /  The LustreC Development Team  *)
4
(*  Copyright 2012 -    --   ONERA - CNRS - INPT                    *)
5
(*                                                                  *)
6
(*  LustreC is free software, distributed WITHOUT ANY WARRANTY      *)
7
(*  under the terms of the GNU Lesser General Public License        *)
8
(*  version 2.1.                                                    *)
9
(*                                                                  *)
10
(********************************************************************)
11

    
12
open Lustre_types
13
open Machine_code_types
14
open Corelang
15
open Clocks
16
open Causality
17

    
18
let print_statelocaltag = true
19
  
20
exception NormalizationError
21

    
22
module OrdVarDecl:Map.OrderedType with type t=var_decl =
23
  struct type t = var_decl;; let compare = compare end
24

    
25
module VSet = Set.Make(OrdVarDecl)
26

    
27
let rec pp_val fmt v =
28
  match v.value_desc with
29
    | Cst c         -> Printers.pp_const fmt c 
30
    | LocalVar v    ->
31
       if print_statelocaltag then
32
	 Format.fprintf fmt "%s(L)" v.var_id
33
       else
34
	 Format.pp_print_string fmt v.var_id
35
	   
36
    | StateVar v    ->
37
       if print_statelocaltag then
38
	 Format.fprintf fmt "%s(S)" v.var_id
39
       else
40
	 Format.pp_print_string fmt v.var_id
41
    | Array vl      -> Format.fprintf fmt "[%a]" (Utils.fprintf_list ~sep:", " pp_val)  vl
42
    | Access (t, i) -> Format.fprintf fmt "%a[%a]" pp_val t pp_val i
43
    | Power (v, n)  -> Format.fprintf fmt "(%a^%a)" pp_val v pp_val n
44
    | Fun (n, vl)   -> Format.fprintf fmt "%s (%a)" n (Utils.fprintf_list ~sep:", " pp_val)  vl
45

    
46
let rec pp_instr fmt i =
47
  let _ =
48
    match i.instr_desc with
49
    | MLocalAssign (i,v) -> Format.fprintf fmt "%s<-l- %a" i.var_id pp_val v
50
    | MStateAssign (i,v) -> Format.fprintf fmt "%s<-s- %a" i.var_id pp_val v
51
    | MReset i           -> Format.fprintf fmt "reset %s" i
52
    | MNoReset i         -> Format.fprintf fmt "noreset %s" i
53
    | MStep (il, i, vl)  ->
54
       Format.fprintf fmt "%a = %s (%a)"
55
	 (Utils.fprintf_list ~sep:", " (fun fmt v -> Format.pp_print_string fmt v.var_id)) il
56
	 i
57
	 (Utils.fprintf_list ~sep:", " pp_val) vl
58
    | MBranch (g,hl)     ->
59
       Format.fprintf fmt "@[<v 2>case(%a) {@,%a@,}@]"
60
	 pp_val g
61
	 (Utils.fprintf_list ~sep:"@," pp_branch) hl
62
    | MComment s -> Format.pp_print_string fmt s
63
       
64
  in
65
  (* Annotation *)
66
  (* let _ = *)
67
  (*   match i.lustre_expr with None -> () | Some e -> Format.fprintf fmt " -- original expr: %a" Printers.pp_expr e *)
68
  (* in *)
69
  let _ = 
70
    match i.lustre_eq with None -> () | Some eq -> Format.fprintf fmt " -- original eq: %a" Printers.pp_node_eq eq
71
  in
72
  ()
73
    
74
and pp_branch fmt (t, h) =
75
  Format.fprintf fmt "@[<v 2>%s:@,%a@]" t (Utils.fprintf_list ~sep:"@," pp_instr) h
76

    
77
and pp_instrs fmt il =
78
  Format.fprintf fmt "@[<v 2>%a@]" (Utils.fprintf_list ~sep:"@," pp_instr) il
79

    
80
type step_t = {
81
  step_checks: (Location.t * value_t) list;
82
  step_inputs: var_decl list;
83
  step_outputs: var_decl list;
84
  step_locals: var_decl list;
85
  step_instrs: instr_t list;
86
  step_asserts: value_t list;
87
}
88

    
89
type static_call = top_decl * (Dimension.dim_expr list)
90

    
91
type machine_t = {
92
  mname: node_desc;
93
  mmemory: var_decl list;
94
  mcalls: (ident * static_call) list; (* map from stateful/stateless instance to node, no internals *)
95
  minstances: (ident * static_call) list; (* sub-map of mcalls, from stateful instance to node *)
96
  minit: instr_t list;
97
  mstatic: var_decl list; (* static inputs only *)
98
  mconst: instr_t list; (* assignments of node constant locals *)
99
  mstep: step_t;
100
  mspec: node_annot option;
101
  mannot: expr_annot list;
102
}
103

    
104
(* merge log: get_node_def was in c0f8 *)
105
(* Returns the node/machine associated to id in m calls *)
106
let get_node_def id m =
107
  try
108
    let (decl, _) = List.assoc id m.mcalls in
109
    Corelang.node_of_top decl
110
  with Not_found -> ( 
111
    (* Format.eprintf "Unable to find node %s in list [%a]@.@?" *)
112
    (*   id *)
113
    (*   (Utils.fprintf_list ~sep:", " (fun fmt (n,_) -> Format.fprintf fmt "%s" n)) m.mcalls *)
114
    (* ; *)
115
    raise Not_found
116
  )
117
    
118
(* merge log: machine_vars was in 44686 *)
119
let machine_vars m = m.mstep.step_inputs @ m.mstep.step_locals @ m.mstep.step_outputs @ m.mmemory
120

    
121
let pp_step fmt s =
122
  Format.fprintf fmt "@[<v>inputs : %a@ outputs: %a@ locals : %a@ checks : %a@ instrs : @[%a@]@ asserts : @[%a@]@]@ "
123
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_inputs
124
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_outputs
125
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_locals
126
    (Utils.fprintf_list ~sep:", " (fun fmt (_, c) -> pp_val fmt c)) s.step_checks
127
    (Utils.fprintf_list ~sep:"@ " pp_instr) s.step_instrs
128
    (Utils.fprintf_list ~sep:", " pp_val) s.step_asserts
129

    
130

    
131
let pp_static_call fmt (node, args) =
132
 Format.fprintf fmt "%s<%a>"
133
   (node_name node)
134
   (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) args
135

    
136
let pp_machine fmt m =
137
  Format.fprintf fmt
138
    "@[<v 2>machine %s@ mem      : %a@ instances: %a@ init     : %a@ const    : %a@ step     :@   @[<v 2>%a@]@ @  spec : @[%t@]@  annot : @[%a@]@]@ "
139
    m.mname.node_id
140
    (Utils.fprintf_list ~sep:", " Printers.pp_var) m.mmemory
141
    (Utils.fprintf_list ~sep:", " (fun fmt (o1, o2) -> Format.fprintf fmt "(%s, %a)" o1 pp_static_call o2)) m.minstances
142
    (Utils.fprintf_list ~sep:"@ " pp_instr) m.minit
143
    (Utils.fprintf_list ~sep:"@ " pp_instr) m.mconst
144
    pp_step m.mstep
145
    (fun fmt -> match m.mspec with | None -> () | Some spec -> Printers.pp_spec fmt spec)
146
    (Utils.fprintf_list ~sep:"@ " Printers.pp_expr_annot) m.mannot
147

    
148
let pp_machines fmt ml =
149
  Format.fprintf fmt "@[<v 0>%a@]" (Utils.fprintf_list ~sep:"@," pp_machine) ml
150

    
151
  
152
let rec is_const_value v =
153
  match v.value_desc with
154
  | Cst _          -> true
155
  | Fun (id, args) -> Basic_library.is_value_internal_fun v && List.for_all is_const_value args
156
  | _              -> false
157

    
158
(* Returns the declared stateless status and the computed one. *)
159
let get_stateless_status m =
160
 (m.mname.node_dec_stateless, try Utils.desome m.mname.node_stateless with _ -> failwith ("stateless status of machine " ^ m.mname.node_id ^ " not computed"))
161

    
162
let is_input m id =
163
  List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_inputs
164

    
165
let is_output m id =
166
  List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_outputs
167

    
168
let is_memory m id =
169
  List.exists (fun o -> o.var_id = id.var_id) m.mmemory
170

    
171
let conditional ?lustre_eq c t e =
172
  mkinstr ?lustre_eq:lustre_eq  (MBranch(c, [ (tag_true, t); (tag_false, e) ]))
173

    
174
let dummy_var_decl name typ =
175
  {
176
    var_id = name;
177
    var_orig = false;
178
    var_dec_type = dummy_type_dec;
179
    var_dec_clock = dummy_clock_dec;
180
    var_dec_const = false;
181
    var_dec_value = None;
182
    var_parent_nodeid = None;
183
    var_type =  typ;
184
    var_clock = Clocks.new_ck Clocks.Cvar true;
185
    var_loc = Location.dummy_loc
186
  }
187

    
188
let arrow_id = "_arrow"
189

    
190
let arrow_typ = Types.new_ty Types.Tunivar
191

    
192
let arrow_desc =
193
  {
194
    node_id = arrow_id;
195
    node_type = Type_predef.type_bin_poly_op;
196
    node_clock = Clock_predef.ck_bin_univ;
197
    node_inputs= [dummy_var_decl "_in1" arrow_typ; dummy_var_decl "_in2" arrow_typ];
198
    node_outputs= [dummy_var_decl "_out" arrow_typ];
199
    node_locals= [];
200
    node_gencalls = [];
201
    node_checks = [];
202
    node_asserts = [];
203
    node_stmts= [];
204
    node_dec_stateless = false;
205
    node_stateless = Some false;
206
    node_spec = None;
207
    node_annot = [];  }
208

    
209
let arrow_top_decl =
210
  {
211
    top_decl_desc = Node arrow_desc;
212
    top_decl_owner = (Options_management.core_dependency "arrow");
213
    top_decl_itf = false;
214
    top_decl_loc = Location.dummy_loc
215
  }
216

    
217
let mk_val v t =
218
  { value_desc = v; 
219
    value_type = t; 
220
    value_annot = None }
221
    
222
let arrow_machine =
223
  let state = "_first" in
224
  let var_state = dummy_var_decl state Type_predef.type_bool(* (Types.new_ty Types.Tbool) *) in
225
  let var_input1 = List.nth arrow_desc.node_inputs 0 in
226
  let var_input2 = List.nth arrow_desc.node_inputs 1 in
227
  let var_output = List.nth arrow_desc.node_outputs 0 in
228
  let cst b = mk_val (Cst (const_of_bool b)) Type_predef.type_bool in
229
  let t_arg = Types.new_univar () in (* TODO Xavier: c'est bien la bonne def ? *)
230
  {
231
    mname = arrow_desc;
232
    mmemory = [var_state];
233
    mcalls = [];
234
    minstances = [];
235
    minit = [mkinstr (MStateAssign(var_state, cst true))];
236
    mstatic = [];
237
    mconst = [];
238
    mstep = {
239
      step_inputs = arrow_desc.node_inputs;
240
      step_outputs = arrow_desc.node_outputs;
241
      step_locals = [];
242
      step_checks = [];
243
      step_instrs = [conditional (mk_val (StateVar var_state) Type_predef.type_bool)
244
			(List.map mkinstr
245
			[MStateAssign(var_state, cst false);
246
			 MLocalAssign(var_output, mk_val (LocalVar var_input1) t_arg)])
247
                        (List.map mkinstr
248
			[MLocalAssign(var_output, mk_val (LocalVar var_input2) t_arg)]) ];
249
      step_asserts = [];
250
    };
251
    mspec = None;
252
    mannot = [];
253
  }
254

    
255
let empty_desc =
256
  {
257
    node_id = arrow_id;
258
    node_type = Types.bottom;
259
    node_clock = Clocks.bottom;
260
    node_inputs= [];
261
    node_outputs= [];
262
    node_locals= [];
263
    node_gencalls = [];
264
    node_checks = [];
265
    node_asserts = [];
266
    node_stmts= [];
267
    node_dec_stateless = true;
268
    node_stateless = Some true;
269
    node_spec = None;
270
    node_annot = [];  }
271

    
272
let empty_machine =
273
  {
274
    mname = empty_desc;
275
    mmemory = [];
276
    mcalls = [];
277
    minstances = [];
278
    minit = [];
279
    mstatic = [];
280
    mconst = [];
281
    mstep = {
282
      step_inputs = [];
283
      step_outputs = [];
284
      step_locals = [];
285
      step_checks = [];
286
      step_instrs = [];
287
      step_asserts = [];
288
    };
289
    mspec = None;
290
    mannot = [];
291
  }
292

    
293
let new_instance =
294
  let cpt = ref (-1) in
295
  fun caller callee tag ->
296
    begin
297
      let o =
298
	if Stateless.check_node callee then
299
	  node_name callee
300
	else
301
	  Printf.sprintf "ni_%d" (incr cpt; !cpt) in
302
      let o =
303
	if !Options.ansi && is_generic_node callee
304
	then Printf.sprintf "%s_inst_%d" o (Utils.position (fun e -> e.expr_tag = tag) caller.node_gencalls)
305
	else o in
306
      o
307
    end
308

    
309

    
310
(* translate_<foo> : node -> context -> <foo> -> machine code/expression *)
311
(* the context contains  m : state aka memory variables  *)
312
(*                      si : initialization instructions *)
313
(*                       j : node aka machine instances  *)
314
(*                       d : local variables             *)
315
(*                       s : step instructions           *)
316
let translate_ident node (m, si, j, d, s) id =
317
  (* Format.eprintf "trnaslating ident: %s@." id; *)
318
  try (* id is a node var *)
319
    let var_id = get_node_var id node in
320
    if VSet.exists (fun v -> v.var_id = id) m
321
    then (
322
      (* Format.eprintf "a STATE VAR@."; *)
323
      mk_val (StateVar var_id) var_id.var_type
324
    )
325
    else (
326
      (* Format.eprintf "a LOCAL VAR@."; *)
327
      mk_val (LocalVar var_id) var_id.var_type
328
    )
329
  with Not_found ->
330
    try (* id is a constant *)
331
      let vdecl = (Corelang.var_decl_of_const (const_of_top (Hashtbl.find Corelang.consts_table id))) in
332
      mk_val (LocalVar vdecl) vdecl.var_type
333
    with Not_found ->
334
      (* id is a tag *)
335
      (* DONE construire une liste des enum declarés et alors chercher dedans la liste
336
	 qui contient id *)
337
      try
338
        let typ = (typedef_of_top (Hashtbl.find Corelang.tag_table id)).tydef_id in
339
        mk_val (Cst (Const_tag id)) (Type_predef.type_const typ)
340
      with Not_found -> (Format.eprintf "internal error: Machine_code.translate_ident %s" id;
341
                         assert false)
342

    
343
let rec control_on_clock node ((m, si, j, d, s) as args) ck inst =
344
 match (Clocks.repr ck).cdesc with
345
 | Con    (ck1, cr, l) ->
346
   let id  = Clocks.const_of_carrier cr in
347
   control_on_clock node args ck1 (mkinstr
348
				     (* TODO il faudrait prendre le lustre
349
					associé à instr et rajouter print_ck_suffix
350
					ck) de clocks.ml *)
351
				     (MBranch (translate_ident node args id,
352
					       [l, [inst]] )))
353
 | _                   -> inst
354

    
355
let rec join_branches hl1 hl2 =
356
 match hl1, hl2 with
357
 | []          , _            -> hl2
358
 | _           , []           -> hl1
359
 | (t1, h1)::q1, (t2, h2)::q2 ->
360
   if t1 < t2 then (t1, h1) :: join_branches q1 hl2 else
361
   if t1 > t2 then (t2, h2) :: join_branches hl1 q2
362
   else (t1, List.fold_right join_guards h1 h2) :: join_branches q1 q2
363

    
364
and join_guards inst1 insts2 =
365
 match get_instr_desc inst1, List.map get_instr_desc insts2 with
366
 | _                   , []                               ->
367
   [inst1]
368
 | MBranch (x1, hl1), MBranch (x2, hl2) :: q when x1 = x2 ->
369
    mkinstr
370
      (* TODO on pourrait uniquement concatener les lustres de inst1 et hd(inst2) *)
371
      (MBranch (x1, join_branches (sort_handlers hl1) (sort_handlers hl2)))
372
   :: (List.tl insts2)
373
 | _ -> inst1 :: insts2
374

    
375
let join_guards_list insts =
376
 List.fold_right join_guards insts []
377

    
378
(* specialize predefined (polymorphic) operators
379
   wrt their instances, so that the C semantics
380
   is preserved *)
381
let specialize_to_c expr =
382
 match expr.expr_desc with
383
 | Expr_appl (id, e, r) ->
384
   if List.exists (fun e -> Types.is_bool_type e.expr_type) (expr_list_of_expr e)
385
   then let id =
386
	  match id with
387
	  | "="  -> "equi"
388
	  | "!=" -> "xor"
389
	  | _    -> id in
390
	{ expr with expr_desc = Expr_appl (id, e, r) }
391
   else expr
392
 | _ -> expr
393

    
394
let specialize_op expr =
395
  match !Options.output with
396
  | "C" -> specialize_to_c expr
397
  | _   -> expr
398

    
399
let rec translate_expr node ((m, si, j, d, s) as args) expr =
400
  let expr = specialize_op expr in
401
  let value_desc = 
402
    match expr.expr_desc with
403
    | Expr_const v                     -> Cst v
404
    | Expr_ident x                     -> (translate_ident node args x).value_desc
405
    | Expr_array el                    -> Array (List.map (translate_expr node args) el)
406
    | Expr_access (t, i)               -> Access (translate_expr node args t, translate_expr node args (expr_of_dimension i))
407
    | Expr_power  (e, n)               -> Power  (translate_expr node args e, translate_expr node args (expr_of_dimension n))
408
    | Expr_tuple _
409
    | Expr_arrow _ 
410
    | Expr_fby _
411
    | Expr_pre _                       -> (Printers.pp_expr Format.err_formatter expr; Format.pp_print_flush Format.err_formatter (); raise NormalizationError)
412
    | Expr_when    (e1, _, _)          -> (translate_expr node args e1).value_desc
413
    | Expr_merge   (x, _)              -> raise NormalizationError
414
    | Expr_appl (id, e, _) when Basic_library.is_expr_internal_fun expr ->
415
      let nd = node_from_name id in
416
      Fun (node_name nd, List.map (translate_expr node args) (expr_list_of_expr e))
417
    | Expr_ite (g,t,e) -> (
418
      (* special treatment depending on the active backend. For horn backend, ite
419
	 are preserved in expression. While they are removed for C or Java
420
	 backends. *)
421
      match !Options.output with
422
      | "horn" -> 
423
	 Fun ("ite", [translate_expr node args g; translate_expr node args t; translate_expr node args e])
424
      | "C" | "java" | _ -> 
425
	 (Format.eprintf "Normalization error for backend %s: %a@."
426
	    !Options.output
427
	    Printers.pp_expr expr;
428
	  raise NormalizationError)
429
    )
430
    | _                   -> raise NormalizationError
431
  in
432
  mk_val value_desc expr.expr_type
433

    
434
let translate_guard node args expr =
435
  match expr.expr_desc with
436
  | Expr_ident x  -> translate_ident node args x
437
  | _ -> (Format.eprintf "internal error: translate_guard %s %a@." node.node_id Printers.pp_expr expr;assert false)
438

    
439
let rec translate_act node ((m, si, j, d, s) as args) (y, expr) =
440
  let eq = Corelang.mkeq Location.dummy_loc ([y.var_id], expr) in
441
  match expr.expr_desc with
442
  | Expr_ite   (c, t, e) -> let g = translate_guard node args c in
443
			    conditional ?lustre_eq:(Some eq) g
444
                              [translate_act node args (y, t)]
445
                              [translate_act node args (y, e)]
446
  | Expr_merge (x, hl)   -> mkinstr ?lustre_eq:(Some eq) (MBranch (translate_ident node args x,
447
                                     List.map (fun (t,  h) -> t, [translate_act node args (y, h)]) hl))
448
  | _                    -> mkinstr ?lustre_eq:(Some eq)  (MLocalAssign (y, translate_expr node args expr))
449

    
450
let reset_instance node args i r c =
451
  match r with
452
  | None        -> []
453
  | Some r      -> let g = translate_guard node args r in
454
                   [control_on_clock node args c (conditional g [mkinstr (MReset i)] [mkinstr (MNoReset i)])]
455

    
456
let translate_eq node ((m, si, j, d, s) as args) eq =
457
  (* Format.eprintf "translate_eq %a with clock %a@." Printers.pp_node_eq eq Clocks.print_ck eq.eq_rhs.expr_clock;  *)
458
  match eq.eq_lhs, eq.eq_rhs.expr_desc with
459
  | [x], Expr_arrow (e1, e2)                     ->
460
     let var_x = get_node_var x node in
461
     let o = new_instance node arrow_top_decl eq.eq_rhs.expr_tag in
462
     let c1 = translate_expr node args e1 in
463
     let c2 = translate_expr node args e2 in
464
     (m,
465
      mkinstr (MReset o) :: si,
466
      Utils.IMap.add o (arrow_top_decl, []) j,
467
      d,
468
      (control_on_clock node args eq.eq_rhs.expr_clock (mkinstr ?lustre_eq:(Some eq) (MStep ([var_x], o, [c1;c2])))) :: s)
469
  | [x], Expr_pre e1 when VSet.mem (get_node_var x node) d     ->
470
     let var_x = get_node_var x node in
471
     (VSet.add var_x m,
472
      si,
473
      j,
474
      d,
475
      control_on_clock node args eq.eq_rhs.expr_clock (mkinstr ?lustre_eq:(Some eq) (MStateAssign (var_x, translate_expr node args e1))) :: s)
476
  | [x], Expr_fby (e1, e2) when VSet.mem (get_node_var x node) d ->
477
     let var_x = get_node_var x node in
478
     (VSet.add var_x m,
479
      mkinstr ?lustre_eq:(Some eq) (MStateAssign (var_x, translate_expr node args e1)) :: si,
480
      j,
481
      d,
482
      control_on_clock node args eq.eq_rhs.expr_clock (mkinstr ?lustre_eq:(Some eq) (MStateAssign (var_x, translate_expr node args e2))) :: s)
483

    
484
  | p  , Expr_appl (f, arg, r) when not (Basic_library.is_expr_internal_fun eq.eq_rhs) ->
485
     let var_p = List.map (fun v -> get_node_var v node) p in
486
     let el = expr_list_of_expr arg in
487
     let vl = List.map (translate_expr node args) el in
488
     let node_f = node_from_name f in
489
     let call_f =
490
       node_f,
491
       NodeDep.filter_static_inputs (node_inputs node_f) el in
492
     let o = new_instance node node_f eq.eq_rhs.expr_tag in
493
     let env_cks = List.fold_right (fun arg cks -> arg.expr_clock :: cks) el [eq.eq_rhs.expr_clock] in
494
     let call_ck = Clock_calculus.compute_root_clock (Clock_predef.ck_tuple env_cks) in
495
     (*Clocks.new_var true in
496
       Clock_calculus.unify_imported_clock (Some call_ck) eq.eq_rhs.expr_clock eq.eq_rhs.expr_loc;
497
       Format.eprintf "call %a: %a: %a@," Printers.pp_expr eq.eq_rhs Clocks.print_ck (Clock_predef.ck_tuple env_cks) Clocks.print_ck call_ck;*)
498
     (m,
499
      (if Stateless.check_node node_f then si else mkinstr (MReset o) :: si),
500
      Utils.IMap.add o call_f j,
501
      d,
502
      (if Stateless.check_node node_f
503
       then []
504
       else reset_instance node args o r call_ck) @
505
	(control_on_clock node args call_ck (mkinstr ?lustre_eq:(Some eq) (MStep (var_p, o, vl)))) :: s)
506
  (*
507
    (* special treatment depending on the active backend. For horn backend, x = ite (g,t,e)
508
    are preserved. While they are replaced as if g then x = t else x = e in  C or Java
509
    backends. *)
510
    | [x], Expr_ite   (c, t, e)
511
    when (match !Options.output with | "horn" -> true | "C" | "java" | _ -> false)
512
    ->
513
    let var_x = get_node_var x node in
514
    (m,
515
    si,
516
    j,
517
    d,
518
    (control_on_clock node args eq.eq_rhs.expr_clock
519
    (MLocalAssign (var_x, translate_expr node args eq.eq_rhs))::s)
520
    )
521

    
522
  *)
523
  | [x], _                                       -> (
524
    let var_x = get_node_var x node in
525
    (m, si, j, d,
526
     control_on_clock
527
       node
528
       args
529
       eq.eq_rhs.expr_clock
530
       (translate_act node args (var_x, eq.eq_rhs)) :: s
531
    )
532
  )
533
  | _                                            ->
534
     begin
535
       Format.eprintf "internal error: Machine_code.translate_eq %a@?" Printers.pp_node_eq eq;
536
       assert false
537
     end
538

    
539
let find_eq xl eqs =
540
  let rec aux accu eqs =
541
      match eqs with
542
	| [] ->
543
	  begin
544
	    Format.eprintf "Looking for variables %a in the following equations@.%a@."
545
	      (Utils.fprintf_list ~sep:" , " (fun fmt v -> Format.fprintf fmt "%s" v)) xl
546
	      Printers.pp_node_eqs eqs;
547
	    assert false
548
	  end
549
	| hd::tl ->
550
	  if List.exists (fun x -> List.mem x hd.eq_lhs) xl then hd, accu@tl else aux (hd::accu) tl
551
    in
552
    aux [] eqs
553

    
554
(* Sort the set of equations of node [nd] according
555
   to the computed schedule [sch]
556
*)
557
let sort_equations_from_schedule nd sch =
558
  (* Format.eprintf "%s schedule: %a@." *)
559
  (* 		 nd.node_id *)
560
  (* 		 (Utils.fprintf_list ~sep:" ; " Scheduling.pp_eq_schedule) sch; *)
561
  let eqs, auts = get_node_eqs nd in
562
  assert (auts = []); (* Automata should be expanded by now *)
563
  let split_eqs = Splitting.tuple_split_eq_list eqs in
564
  let eqs_rev, remainder =
565
    List.fold_left
566
      (fun (accu, node_eqs_remainder) vl ->
567
       if List.exists (fun eq -> List.exists (fun v -> List.mem v eq.eq_lhs) vl) accu
568
       then
569
	 (accu, node_eqs_remainder)
570
       else
571
	 let eq_v, remainder = find_eq vl node_eqs_remainder in
572
	 eq_v::accu, remainder
573
      )
574
      ([], split_eqs)
575
      sch
576
  in
577
  begin
578
    if List.length remainder > 0 then (
579
      let eqs, auts = get_node_eqs nd in
580
      assert (auts = []); (* Automata should be expanded by now *)
581
      Format.eprintf "Equations not used are@.%a@.Full equation set is:@.%a@.@?"
582
		     Printers.pp_node_eqs remainder
583
      		     Printers.pp_node_eqs eqs;
584
      assert false);
585
    List.rev eqs_rev
586
  end
587

    
588
let constant_equations nd =
589
 List.fold_right (fun vdecl eqs ->
590
   if vdecl.var_dec_const
591
   then
592
     { eq_lhs = [vdecl.var_id];
593
       eq_rhs = Utils.desome vdecl.var_dec_value;
594
       eq_loc = vdecl.var_loc
595
     } :: eqs
596
   else eqs)
597
   nd.node_locals []
598

    
599
let translate_eqs node args eqs =
600
  List.fold_right (fun eq args -> translate_eq node args eq) eqs args;;
601

    
602
let translate_decl nd sch =
603
  (*Log.report ~level:1 (fun fmt -> Printers.pp_node fmt nd);*)
604

    
605
  let sorted_eqs = sort_equations_from_schedule nd sch in
606
  let constant_eqs = constant_equations nd in
607

    
608
  (* In case of non functional backend (eg. C), additional local variables have
609
     to be declared for each assert *)
610
  let new_locals, assert_instrs, nd_node_asserts =
611
    let exprl = List.map (fun assert_ -> assert_.assert_expr ) nd.node_asserts in
612
    if Backends.is_functional () then
613
      [], [], exprl  
614
    else (* Each assert(e) is associated to a fresh variable v and declared as
615
	    v=e; assert (v); *)
616
      let _, vars, eql, assertl =
617
	List.fold_left (fun (i, vars, eqlist, assertlist) expr ->
618
	  let loc = expr.expr_loc in
619
	  let var_id = nd.node_id ^ "_assert_" ^ string_of_int i in
620
	  let assert_var =
621
	    mkvar_decl
622
	      loc
623
	      ~orig:false (* fresh var *)
624
	      (var_id,
625
	       mktyp loc Tydec_bool,
626
	       mkclock loc Ckdec_any,
627
	       false, (* not a constant *)
628
	       None, (* no default value *)
629
	       Some nd.node_id
630
	      )
631
	  in
632
	  assert_var.var_type <- Type_predef.type_bool (* Types.new_ty (Types.Tbool) *); 
633
	  let eq = mkeq loc ([var_id], expr) in
634
	  (i+1, assert_var::vars, eq::eqlist, {expr with expr_desc = Expr_ident var_id}::assertlist)
635
	) (1, [], [], []) exprl
636
      in
637
      vars, eql, assertl
638
  in
639
  let locals_list = nd.node_locals @ new_locals in
640

    
641
  let nd = { nd with node_locals = locals_list } in
642
  let init_args = VSet.empty, [], Utils.IMap.empty, List.fold_right (fun l -> VSet.add l) locals_list VSet.empty, [] in
643
  (* memories, init instructions, node calls, local variables (including memories), step instrs *)
644
  let m0, init0, j0, locals0, s0 = translate_eqs nd init_args constant_eqs in
645
  assert (VSet.is_empty m0);
646
  assert (init0 = []);
647
  assert (Utils.IMap.is_empty j0);
648
  let m, init, j, locals, s as context_with_asserts = translate_eqs nd (m0, init0, j0, locals0, []) (assert_instrs@sorted_eqs) in
649
  let mmap = Utils.IMap.fold (fun i n res -> (i, n)::res) j [] in
650
  {
651
    mname = nd;
652
    mmemory = VSet.elements m;
653
    mcalls = mmap;
654
    minstances = List.filter (fun (_, (n,_)) -> not (Stateless.check_node n)) mmap;
655
    minit = init;
656
    mconst = s0;
657
    mstatic = List.filter (fun v -> v.var_dec_const) nd.node_inputs;
658
    mstep = {
659
      step_inputs = nd.node_inputs;
660
      step_outputs = nd.node_outputs;
661
      step_locals = VSet.elements (VSet.diff locals m);
662
      step_checks = List.map (fun d -> d.Dimension.dim_loc, translate_expr nd init_args (expr_of_dimension d)) nd.node_checks;
663
      step_instrs = (
664
	(* special treatment depending on the active backend. For horn backend,
665
	   common branches are not merged while they are in C or Java
666
	   backends. *)
667
	(*match !Options.output with
668
	| "horn" -> s
669
	  | "C" | "java" | _ ->*)
670
	if !Backends.join_guards then
671
	  join_guards_list s
672
	else
673
	  s
674
      );
675
      step_asserts = List.map (translate_expr nd context_with_asserts) nd_node_asserts;
676
    };
677
    mspec = nd.node_spec;
678
    mannot = nd.node_annot;
679
  }
680

    
681
(** takes the global declarations and the scheduling associated to each node *)
682
let translate_prog decls node_schs =
683
  let nodes = get_nodes decls in
684
  List.map
685
    (fun decl ->
686
     let node = node_of_top decl in
687
      let sch = (Utils.IMap.find node.node_id node_schs).Scheduling.schedule in
688
      translate_decl node sch
689
    ) nodes
690

    
691
let get_machine_opt name machines =
692
  List.fold_left
693
    (fun res m ->
694
      match res with
695
      | Some _ -> res
696
      | None -> if m.mname.node_id = name then Some m else None)
697
    None machines
698

    
699
let get_const_assign m id =
700
  try
701
    match get_instr_desc (List.find
702
	     (fun instr -> match get_instr_desc instr with
703
	     | MLocalAssign (v, _) -> v == id
704
	     | _ -> false)
705
	     m.mconst
706
    ) with
707
    | MLocalAssign (_, e) -> e
708
    | _                   -> assert false
709
  with Not_found -> assert false
710

    
711

    
712
let value_of_ident loc m id =
713
  (* is is a state var *)
714
  try
715
    let v = List.find (fun v -> v.var_id = id) m.mmemory
716
    in mk_val (StateVar v) v.var_type 
717
  with Not_found ->
718
    try (* id is a node var *)
719
      let v = get_node_var id m.mname
720
      in mk_val (LocalVar v) v.var_type
721
  with Not_found ->
722
    try (* id is a constant *)
723
      let c = Corelang.var_decl_of_const (const_of_top (Hashtbl.find Corelang.consts_table id))
724
      in mk_val (LocalVar c) c.var_type
725
    with Not_found ->
726
      (* id is a tag *)
727
      let t = Const_tag id
728
      in mk_val (Cst t) (Typing.type_const loc t)
729

    
730
(* type of internal fun used in dimension expression *)
731
let type_of_value_appl f args =
732
  if List.mem f Basic_library.arith_funs
733
  then (List.hd args).value_type
734
  else Type_predef.type_bool
735

    
736
let rec value_of_dimension m dim =
737
  match dim.Dimension.dim_desc with
738
  | Dimension.Dbool b         ->
739
     mk_val (Cst (Const_tag (if b then Corelang.tag_true else Corelang.tag_false))) Type_predef.type_bool
740
  | Dimension.Dint i          ->
741
     mk_val (Cst (Const_int i)) Type_predef.type_int
742
  | Dimension.Dident v        -> value_of_ident dim.Dimension.dim_loc m v
743
  | Dimension.Dappl (f, args) ->
744
     let vargs = List.map (value_of_dimension m) args
745
     in mk_val (Fun (f, vargs)) (type_of_value_appl f vargs) 
746
  | Dimension.Dite (i, t, e)  ->
747
     (match List.map (value_of_dimension m) [i; t; e] with
748
     | [vi; vt; ve] -> mk_val (Fun ("ite", [vi; vt; ve])) vt.value_type
749
     | _            -> assert false)
750
  | Dimension.Dlink dim'      -> value_of_dimension m dim'
751
  | _                         -> assert false
752

    
753
let rec dimension_of_value value =
754
  match value.value_desc with
755
  | Cst (Const_tag t) when t = Corelang.tag_true  -> Dimension.mkdim_bool  Location.dummy_loc true
756
  | Cst (Const_tag t) when t = Corelang.tag_false -> Dimension.mkdim_bool  Location.dummy_loc false
757
  | Cst (Const_int i)                             -> Dimension.mkdim_int   Location.dummy_loc i
758
  | LocalVar v                                    -> Dimension.mkdim_ident Location.dummy_loc v.var_id
759
  | Fun (f, args)                                 -> Dimension.mkdim_appl  Location.dummy_loc f (List.map dimension_of_value args)
760
  | _                                             -> assert false
761

    
762
(* Local Variables: *)
763
(* compile-command:"make -C .." *)
764
(* End: *)