Project

General

Profile

Download (25.1 KB) Statistics
| Branch: | Tag: | Revision:
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 LustreSpec
13
open Corelang
14
open Clocks
15
open Causality
16

    
17
exception NormalizationError
18

    
19
module OrdVarDecl:Map.OrderedType with type t=var_decl =
20
  struct type t = var_decl;; let compare = compare end
21

    
22
module ISet = Set.Make(OrdVarDecl)
23

    
24
let rec pp_val fmt v =
25
  match v.value_desc with
26
    | Cst c         -> Printers.pp_const fmt c 
27
    | LocalVar v    -> Format.pp_print_string fmt v.var_id
28
    | StateVar v    -> Format.pp_print_string fmt v.var_id
29
    | Array vl      -> Format.fprintf fmt "[%a]" (Utils.fprintf_list ~sep:", " pp_val)  vl
30
    | Access (t, i) -> Format.fprintf fmt "%a[%a]" pp_val t pp_val i
31
    | Power (v, n)  -> Format.fprintf fmt "(%a^%a)" pp_val v pp_val n
32
    | Fun (n, vl)   -> Format.fprintf fmt "%s (%a)" n (Utils.fprintf_list ~sep:", " pp_val)  vl
33

    
34
let rec pp_instr fmt i =
35
  match i with
36
    | MLocalAssign (i,v) -> Format.fprintf fmt "%s<-l- %a" i.var_id pp_val v
37
    | MStateAssign (i,v) -> Format.fprintf fmt "%s<-s- %a" i.var_id pp_val v
38
    | MReset i           -> Format.fprintf fmt "reset %s" i
39
    | MNoReset i         -> Format.fprintf fmt "noreset %s" i
40
    | MStep (il, i, vl)  ->
41
      Format.fprintf fmt "%a = %s (%a)"
42
	(Utils.fprintf_list ~sep:", " (fun fmt v -> Format.pp_print_string fmt v.var_id)) il
43
	i
44
	(Utils.fprintf_list ~sep:", " pp_val) vl
45
    | MBranch (g,hl)     ->
46
      Format.fprintf fmt "@[<v 2>case(%a) {@,%a@,}@]"
47
	pp_val g
48
	(Utils.fprintf_list ~sep:"@," pp_branch) hl
49
    | MComment s -> Format.pp_print_string fmt s
50

    
51
and pp_branch fmt (t, h) =
52
  Format.fprintf fmt "@[<v 2>%s:@,%a@]" t (Utils.fprintf_list ~sep:"@," pp_instr) h
53

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

    
57
type step_t = {
58
  step_checks: (Location.t * value_t) list;
59
  step_inputs: var_decl list;
60
  step_outputs: var_decl list;
61
  step_locals: var_decl list;
62
  step_instrs: instr_t list;
63
  step_asserts: value_t list;
64
}
65

    
66
type static_call = top_decl * (Dimension.dim_expr list)
67

    
68
type machine_t = {
69
  mname: node_desc;
70
  mmemory: var_decl list;
71
  mcalls: (ident * static_call) list; (* map from stateful/stateless instance to node, no internals *)
72
  minstances: (ident * static_call) list; (* sub-map of mcalls, from stateful instance to node *)
73
  minit: instr_t list;
74
  mstatic: var_decl list; (* static inputs only *)
75
  mconst: instr_t list; (* assignments of node constant locals *)
76
  mstep: step_t;
77
  mspec: node_annot option;
78
  mannot: expr_annot list;
79
}
80

    
81
let get_node_def id m =
82
  try
83
    let (decl, _) = List.assoc id m.minstances in
84
    Corelang.node_of_top decl
85
  with Not_found -> raise Not_found
86
    
87
let machine_vars m = m.mstep.step_inputs @ m.mstep.step_locals @ m.mstep.step_outputs @ m.mmemory
88

    
89
let pp_step fmt s =
90
  Format.fprintf fmt "@[<v>inputs : %a@ outputs: %a@ locals : %a@ checks : %a@ instrs : @[%a@]@ asserts : @[%a@]@]@ "
91
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_inputs
92
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_outputs
93
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_locals
94
    (Utils.fprintf_list ~sep:", " (fun fmt (_, c) -> pp_val fmt c)) s.step_checks
95
    (Utils.fprintf_list ~sep:"@ " pp_instr) s.step_instrs
96
    (Utils.fprintf_list ~sep:", " pp_val) s.step_asserts
97

    
98

    
99
let pp_static_call fmt (node, args) =
100
 Format.fprintf fmt "%s<%a>"
101
   (node_name node)
102
   (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) args
103

    
104
let pp_machine fmt m =
105
  Format.fprintf fmt
106
    "@[<v 2>machine %s@ mem      : %a@ instances: %a@ init     : %a@ const    : %a@ step     :@   @[<v 2>%a@]@ @  spec : @[%t@]@  annot : @[%a@]@]@ "
107
    m.mname.node_id
108
    (Utils.fprintf_list ~sep:", " Printers.pp_var) m.mmemory
109
    (Utils.fprintf_list ~sep:", " (fun fmt (o1, o2) -> Format.fprintf fmt "(%s, %a)" o1 pp_static_call o2)) m.minstances
110
    (Utils.fprintf_list ~sep:"@ " pp_instr) m.minit
111
    (Utils.fprintf_list ~sep:"@ " pp_instr) m.mconst
112
    pp_step m.mstep
113
    (fun fmt -> match m.mspec with | None -> () | Some spec -> Printers.pp_spec fmt spec)
114
    (Utils.fprintf_list ~sep:"@ " Printers.pp_expr_annot) m.mannot
115

    
116
let rec is_const_value v =
117
  match v.value_desc with
118
  | Cst _          -> true
119
  | Fun (id, args) -> Basic_library.is_value_internal_fun v && List.for_all is_const_value args
120
  | _              -> false
121

    
122
(* Returns the declared stateless status and the computed one. *)
123
let get_stateless_status m =
124
 (m.mname.node_dec_stateless, Utils.desome m.mname.node_stateless)
125

    
126
let is_input m id =
127
  List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_inputs
128

    
129
let is_output m id =
130
  List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_outputs
131

    
132
let is_memory m id =
133
  List.exists (fun o -> o.var_id = id.var_id) m.mmemory
134

    
135
let conditional c t e =
136
  MBranch(c, [ (tag_true, t); (tag_false, e) ])
137

    
138
let dummy_var_decl name typ =
139
  {
140
    var_id = name;
141
    var_orig = false;
142
    var_dec_type = dummy_type_dec;
143
    var_dec_clock = dummy_clock_dec;
144
    var_dec_const = false;
145
    var_dec_value = None;
146
    var_type =  typ;
147
    var_clock = Clocks.new_ck Clocks.Cvar true;
148
    var_loc = Location.dummy_loc
149
  }
150

    
151
let arrow_id = "_arrow"
152

    
153
let arrow_typ = Types.new_ty Types.Tunivar
154

    
155
let arrow_desc =
156
  {
157
    node_id = arrow_id;
158
    node_type = Type_predef.type_bin_poly_op;
159
    node_clock = Clock_predef.ck_bin_univ;
160
    node_inputs= [dummy_var_decl "_in1" arrow_typ; dummy_var_decl "_in2" arrow_typ];
161
    node_outputs= [dummy_var_decl "_out" arrow_typ];
162
    node_locals= [];
163
    node_gencalls = [];
164
    node_checks = [];
165
    node_asserts = [];
166
    node_stmts= [];
167
    node_dec_stateless = false;
168
    node_stateless = Some false;
169
    node_spec = None;
170
    node_annot = [];  }
171

    
172
let arrow_top_decl =
173
  {
174
    top_decl_desc = Node arrow_desc;
175
    top_decl_owner = !Options.include_dir;
176
    top_decl_itf = false;
177
    top_decl_loc = Location.dummy_loc
178
  }
179

    
180
let mk_val v t = { value_desc = v; 
181
		   value_type = t; 
182
		   value_annot = None }
183

    
184
let arrow_machine =
185
  let state = "_first" in
186
  let var_state = dummy_var_decl state (Types.new_ty Types.Tbool) in
187
  let var_input1 = List.nth arrow_desc.node_inputs 0 in
188
  let var_input2 = List.nth arrow_desc.node_inputs 1 in
189
  let var_output = List.nth arrow_desc.node_outputs 0 in
190
  let cst b = mk_val (Cst (const_of_bool b)) Type_predef.type_bool in
191
  let t_arg = Types.new_univar () in (* TODO Xavier: c'est bien la bonne def ? *)
192
  {
193
    mname = arrow_desc;
194
    mmemory = [var_state];
195
    mcalls = [];
196
    minstances = [];
197
    minit = [MStateAssign(var_state, cst true)];
198
    mstatic = [];
199
    mconst = [];
200
    mstep = {
201
      step_inputs = arrow_desc.node_inputs;
202
      step_outputs = arrow_desc.node_outputs;
203
      step_locals = [];
204
      step_checks = [];
205
      step_instrs = [conditional (mk_val (StateVar var_state) Type_predef.type_bool)
206
			         [MStateAssign(var_state, cst false);
207
                                  MLocalAssign(var_output, mk_val (LocalVar var_input1) t_arg)]
208
                                 [MLocalAssign(var_output, mk_val (LocalVar var_input2) t_arg)] ];
209
      step_asserts = [];
210
    };
211
    mspec = None;
212
    mannot = [];
213
  }
214

    
215
let empty_desc =
216
  {
217
    node_id = arrow_id;
218
    node_type = Types.bottom;
219
    node_clock = Clocks.bottom;
220
    node_inputs= [];
221
    node_outputs= [];
222
    node_locals= [];
223
    node_gencalls = [];
224
    node_checks = [];
225
    node_asserts = [];
226
    node_stmts= [];
227
    node_dec_stateless = true;
228
    node_stateless = Some true;
229
    node_spec = None;
230
    node_annot = [];  }
231

    
232
let empty_machine =
233
  {
234
    mname = empty_desc;
235
    mmemory = [];
236
    mcalls = [];
237
    minstances = [];
238
    minit = [];
239
    mstatic = [];
240
    mconst = [];
241
    mstep = {
242
      step_inputs = [];
243
      step_outputs = [];
244
      step_locals = [];
245
      step_checks = [];
246
      step_instrs = [];
247
      step_asserts = [];
248
    };
249
    mspec = None;
250
    mannot = [];
251
  }
252

    
253
let new_instance =
254
  let cpt = ref (-1) in
255
  fun caller callee tag ->
256
    begin
257
      let o =
258
	if Stateless.check_node callee then
259
	  node_name callee
260
	else
261
	  Printf.sprintf "ni_%d" (incr cpt; !cpt) in
262
      let o =
263
	if !Options.ansi && is_generic_node callee
264
	then Printf.sprintf "%s_inst_%d" o (Utils.position (fun e -> e.expr_tag = tag) caller.node_gencalls)
265
	else o in
266
      o
267
    end
268

    
269

    
270
(* translate_<foo> : node -> context -> <foo> -> machine code/expression *)
271
(* the context contains  m : state aka memory variables  *)
272
(*                      si : initialization instructions *)
273
(*                       j : node aka machine instances  *)
274
(*                       d : local variables             *)
275
(*                       s : step instructions           *)
276
let translate_ident node (m, si, j, d, s) id =
277
  try (* id is a node var *)
278
    let var_id = get_node_var id node in
279
    if ISet.exists (fun v -> v.var_id = id) m
280
    then mk_val (StateVar var_id) var_id.var_type
281
    else mk_val (LocalVar var_id) var_id.var_type
282
  with Not_found ->
283
    try (* id is a constant *)
284
      let vdecl = (Corelang.var_decl_of_const (const_of_top (Hashtbl.find Corelang.consts_table id))) in
285
      mk_val (LocalVar vdecl) vdecl.var_type
286
    with Not_found ->
287
      (* id is a tag *)
288
      (* DONE construire une liste des enum declarés et alors chercher dedans la liste
289
	 qui contient id *)
290
      try
291
        let typ = (typedef_of_top (Hashtbl.find Corelang.tag_table id)).tydef_id in
292
        mk_val (Cst (Const_tag id)) (Type_predef.type_const typ)
293
      with Not_found -> (Format.eprintf "internal error: Machine_code.translate_ident %s" id;
294
                         assert false)
295

    
296
let rec control_on_clock node ((m, si, j, d, s) as args) ck inst =
297
 match (Clocks.repr ck).cdesc with
298
 | Con    (ck1, cr, l) ->
299
   let id  = Clocks.const_of_carrier cr in
300
   control_on_clock node args ck1 (MBranch (translate_ident node args id,
301
					    [l, [inst]] ))
302
 | _                   -> inst
303

    
304
let rec join_branches hl1 hl2 =
305
 match hl1, hl2 with
306
 | []          , _            -> hl2
307
 | _           , []           -> hl1
308
 | (t1, h1)::q1, (t2, h2)::q2 ->
309
   if t1 < t2 then (t1, h1) :: join_branches q1 hl2 else
310
   if t1 > t2 then (t2, h2) :: join_branches hl1 q2
311
   else (t1, List.fold_right join_guards h1 h2) :: join_branches q1 q2
312

    
313
and join_guards inst1 insts2 =
314
 match inst1, insts2 with
315
 | _                   , []                               ->
316
   [inst1]
317
 | MBranch (x1, hl1), MBranch (x2, hl2) :: q when x1 = x2 ->
318
   MBranch (x1, join_branches (sort_handlers hl1) (sort_handlers hl2))
319
   :: q
320
 | _ -> inst1 :: insts2
321

    
322
let join_guards_list insts =
323
 List.fold_right join_guards insts []
324

    
325
(* specialize predefined (polymorphic) operators
326
   wrt their instances, so that the C semantics
327
   is preserved *)
328
let specialize_to_c expr =
329
 match expr.expr_desc with
330
 | Expr_appl (id, e, r) ->
331
   if List.exists (fun e -> Types.is_bool_type e.expr_type) (expr_list_of_expr e)
332
   then let id =
333
	  match id with
334
	  | "="  -> "equi"
335
	  | "!=" -> "xor"
336
	  | _    -> id in
337
	{ expr with expr_desc = Expr_appl (id, e, r) }
338
   else expr
339
 | _ -> expr
340

    
341
let specialize_op expr =
342
  match !Options.output with
343
  | "C" -> specialize_to_c expr
344
  | _   -> expr
345

    
346
let rec translate_expr node ((m, si, j, d, s) as args) expr =
347
  let expr = specialize_op expr in
348
  let value_desc = 
349
    match expr.expr_desc with
350
    | Expr_const v                     -> Cst v
351
    | Expr_ident x                     -> (translate_ident node args x).value_desc
352
    | Expr_array el                    -> Array (List.map (translate_expr node args) el)
353
    | Expr_access (t, i)               -> Access (translate_expr node args t, translate_expr node args (expr_of_dimension i))
354
    | Expr_power  (e, n)               -> Power  (translate_expr node args e, translate_expr node args (expr_of_dimension n))
355
    | Expr_tuple _
356
    | Expr_arrow _ 
357
    | Expr_fby _
358
    | Expr_pre _                       -> (Printers.pp_expr Format.err_formatter expr; Format.pp_print_flush Format.err_formatter (); raise NormalizationError)
359
    | Expr_when    (e1, _, _)          -> (translate_expr node args e1).value_desc
360
    | Expr_merge   (x, _)              -> raise NormalizationError
361
    | Expr_appl (id, e, _) when Basic_library.is_expr_internal_fun expr ->
362
      let nd = node_from_name id in
363
      Fun (node_name nd, List.map (translate_expr node args) (expr_list_of_expr e))
364
    | Expr_ite (g,t,e) -> (
365
      (* special treatment depending on the active backend. For horn backend, ite
366
	 are preserved in expression. While they are removed for C or Java
367
	 backends. *)
368
      match !Options.output with
369
      | "horn" -> 
370
	 Fun ("ite", [translate_expr node args g; translate_expr node args t; translate_expr node args e])
371
      | "C" | "java" | _ -> 
372
	 (Format.eprintf "Normalization error for backend %s: %a@."
373
	    !Options.output
374
	    Printers.pp_expr expr;
375
	  raise NormalizationError)
376
    )
377
    | _                   -> raise NormalizationError
378
  in
379
  mk_val value_desc expr.expr_type
380

    
381
let translate_guard node args expr =
382
  match expr.expr_desc with
383
  | Expr_ident x  -> translate_ident node args x
384
  | _ -> (Format.eprintf "internal error: translate_guard %s %a@." node.node_id Printers.pp_expr expr;assert false)
385

    
386
let rec translate_act node ((m, si, j, d, s) as args) (y, expr) =
387
  match expr.expr_desc with
388
  | Expr_ite   (c, t, e) -> let g = translate_guard node args c in
389
			    conditional g
390
                              [translate_act node args (y, t)]
391
                              [translate_act node args (y, e)]
392
  | Expr_merge (x, hl)   -> MBranch (translate_ident node args x,
393
                                     List.map (fun (t,  h) -> t, [translate_act node args (y, h)]) hl)
394
  | _                    -> MLocalAssign (y, translate_expr node args expr)
395

    
396
let reset_instance node args i r c =
397
  match r with
398
  | None        -> []
399
  | Some r      -> let g = translate_guard node args r in
400
                   [control_on_clock node args c (conditional g [MReset i] [MNoReset i])]
401

    
402
let translate_eq node ((m, si, j, d, s) as args) eq =
403
  (* Format.eprintf "translate_eq %a with clock %a@." Printers.pp_node_eq eq Clocks.print_ck eq.eq_rhs.expr_clock; *)
404
  match eq.eq_lhs, eq.eq_rhs.expr_desc with
405
  | [x], Expr_arrow (e1, e2)                     ->
406
    let var_x = get_node_var x node in
407
    let o = new_instance node arrow_top_decl eq.eq_rhs.expr_tag in
408
    let c1 = translate_expr node args e1 in
409
    let c2 = translate_expr node args e2 in
410
    (m,
411
     MReset o :: si,
412
     Utils.IMap.add o (arrow_top_decl, []) j,
413
     d,
414
     (control_on_clock node args eq.eq_rhs.expr_clock (MStep ([var_x], o, [c1;c2]))) :: s)
415
  | [x], Expr_pre e1 when ISet.mem (get_node_var x node) d     ->
416
    let var_x = get_node_var x node in
417
    (ISet.add var_x m,
418
     si,
419
     j,
420
     d,
421
     control_on_clock node args eq.eq_rhs.expr_clock (MStateAssign (var_x, translate_expr node args e1)) :: s)
422
  | [x], Expr_fby (e1, e2) when ISet.mem (get_node_var x node) d ->
423
    let var_x = get_node_var x node in
424
    (ISet.add var_x m,
425
     MStateAssign (var_x, translate_expr node args e1) :: si,
426
     j,
427
     d,
428
     control_on_clock node args eq.eq_rhs.expr_clock (MStateAssign (var_x, translate_expr node args e2)) :: s)
429

    
430
  | p  , Expr_appl (f, arg, r) when not (Basic_library.is_expr_internal_fun eq.eq_rhs) ->
431
    let var_p = List.map (fun v -> get_node_var v node) p in
432
    let el = expr_list_of_expr arg in
433
    let vl = List.map (translate_expr node args) el in
434
    let node_f = node_from_name f in
435
    let call_f =
436
      node_f,
437
      NodeDep.filter_static_inputs (node_inputs node_f) el in
438
    let o = new_instance node node_f eq.eq_rhs.expr_tag in
439
    let env_cks = List.fold_right (fun arg cks -> arg.expr_clock :: cks) el [eq.eq_rhs.expr_clock] in
440
    let call_ck = Clock_calculus.compute_root_clock (Clock_predef.ck_tuple env_cks) in
441
    (*Clocks.new_var true in
442
    Clock_calculus.unify_imported_clock (Some call_ck) eq.eq_rhs.expr_clock eq.eq_rhs.expr_loc;
443
    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;*)
444
    (m,
445
     (if Stateless.check_node node_f then si else MReset o :: si),
446
     Utils.IMap.add o call_f j,
447
     d,
448
     (if Stateless.check_node node_f
449
      then []
450
      else reset_instance node args o r call_ck) @
451
       (control_on_clock node args call_ck (MStep (var_p, o, vl))) :: s)
452
(*
453
   (* special treatment depending on the active backend. For horn backend, x = ite (g,t,e)
454
      are preserved. While they are replaced as if g then x = t else x = e in  C or Java
455
      backends. *)
456
  | [x], Expr_ite   (c, t, e)
457
    when (match !Options.output with | "horn" -> true | "C" | "java" | _ -> false)
458
      ->
459
    let var_x = get_node_var x node in
460
    (m,
461
     si,
462
     j,
463
     d,
464
     (control_on_clock node args eq.eq_rhs.expr_clock
465
	(MLocalAssign (var_x, translate_expr node args eq.eq_rhs))::s)
466
    )
467

    
468
*)
469
  | [x], _                                       -> (
470
    let var_x = get_node_var x node in
471
    (m, si, j, d,
472
     control_on_clock
473
       node
474
       args
475
       eq.eq_rhs.expr_clock
476
       (translate_act node args (var_x, eq.eq_rhs)) :: s
477
    )
478
  )
479
  | _                                            ->
480
    begin
481
      Format.eprintf "internal error: Machine_code.translate_eq %a@?" Printers.pp_node_eq eq;
482
      assert false
483
    end
484

    
485
let find_eq xl eqs =
486
  let rec aux accu eqs =
487
      match eqs with
488
	| [] ->
489
	  begin
490
	    Format.eprintf "Looking for variables %a in the following equations@.%a@."
491
	      (Utils.fprintf_list ~sep:" , " (fun fmt v -> Format.fprintf fmt "%s" v)) xl
492
	      Printers.pp_node_eqs eqs;
493
	    assert false
494
	  end
495
	| hd::tl ->
496
	  if List.exists (fun x -> List.mem x hd.eq_lhs) xl then hd, accu@tl else aux (hd::accu) tl
497
    in
498
    aux [] eqs
499

    
500
(* Sort the set of equations of node [nd] according
501
   to the computed schedule [sch]
502
*)
503
let sort_equations_from_schedule nd sch =
504
  (* Format.eprintf "%s schedule: %a@." *)
505
  (* 		 nd.node_id *)
506
  (* 		 (Utils.fprintf_list ~sep:" ; " Scheduling.pp_eq_schedule) sch; *)
507
  let split_eqs = Splitting.tuple_split_eq_list (get_node_eqs nd) in
508
  let eqs_rev, remainder =
509
    List.fold_left
510
      (fun (accu, node_eqs_remainder) vl ->
511
       if List.exists (fun eq -> List.exists (fun v -> List.mem v eq.eq_lhs) vl) accu
512
       then
513
	 (accu, node_eqs_remainder)
514
       else
515
	 let eq_v, remainder = find_eq vl node_eqs_remainder in
516
	 eq_v::accu, remainder
517
      )
518
      ([], split_eqs)
519
      sch
520
  in
521
  begin
522
    if List.length remainder > 0 then (
523
      Format.eprintf "Equations not used are@.%a@.Full equation set is:@.%a@.@?"
524
		     Printers.pp_node_eqs remainder
525
      		     Printers.pp_node_eqs (get_node_eqs nd);
526
      assert false);
527
    List.rev eqs_rev
528
  end
529

    
530
let constant_equations nd =
531
 List.fold_right (fun vdecl eqs ->
532
   if vdecl.var_dec_const
533
   then
534
     { eq_lhs = [vdecl.var_id];
535
       eq_rhs = Utils.desome vdecl.var_dec_value;
536
       eq_loc = vdecl.var_loc
537
     } :: eqs
538
   else eqs)
539
   nd.node_locals []
540

    
541
let translate_eqs node args eqs =
542
  List.fold_right (fun eq args -> translate_eq node args eq) eqs args;;
543

    
544
let translate_decl nd sch =
545
  (*Log.report ~level:1 (fun fmt -> Printers.pp_node fmt nd);*)
546

    
547
  let sorted_eqs = sort_equations_from_schedule nd sch in
548
  let constant_eqs = constant_equations nd in
549

    
550
  (* In case of non functional backend (eg. C), additional local variables have
551
     to be declared for each assert *)
552
  let new_locals, assert_instrs, nd_node_asserts =
553
    let exprl = List.map (fun assert_ -> assert_.assert_expr ) nd.node_asserts in
554
    if Corelang.functional_backend () then
555
      [], [], exprl  
556
    else (* Each assert(e) is associated to a fresh variable v and declared as
557
	    v=e; assert (v); *)
558
      let _, vars, eql, assertl =
559
	List.fold_left (fun (i, vars, eqlist, assertlist) expr ->
560
	  let loc = expr.expr_loc in
561
	  let var_id = nd.node_id ^ "_assert_" ^ string_of_int i in
562
	  let assert_var =
563
	    mkvar_decl
564
	      loc
565
	      ~orig:false (* fresh var *)
566
	      (var_id,
567
	       mktyp loc Tydec_bool,
568
	       mkclock loc Ckdec_any,
569
	       false, (* not a constant *)
570
	       None (* no default value *)
571
	      )
572
	  in
573
	  assert_var.var_type <- Types.new_ty (Types.Tbool); 
574
	  let eq = mkeq loc ([var_id], expr) in
575
	  (i+1, assert_var::vars, eq::eqlist, {expr with expr_desc = Expr_ident var_id}::assertlist)
576
	) (1, [], [], []) exprl
577
      in
578
      vars, eql, assertl
579
  in
580
  let locals_list = nd.node_locals @ new_locals in
581

    
582
  let nd = { nd with node_locals = locals_list } in
583
  let init_args = ISet.empty, [], Utils.IMap.empty, List.fold_right (fun l -> ISet.add l) locals_list ISet.empty, [] in
584
  (* memories, init instructions, node calls, local variables (including memories), step instrs *)
585
  let m0, init0, j0, locals0, s0 = translate_eqs nd init_args constant_eqs in
586
  assert (ISet.is_empty m0);
587
  assert (init0 = []);
588
  assert (Utils.IMap.is_empty j0);
589
  let m, init, j, locals, s = translate_eqs nd (m0, init0, j0, locals0, []) (sorted_eqs@assert_instrs) in
590
  let mmap = Utils.IMap.fold (fun i n res -> (i, n)::res) j [] in
591
  {
592
    mname = nd;
593
    mmemory = ISet.elements m;
594
    mcalls = mmap;
595
    minstances = List.filter (fun (_, (n,_)) -> not (Stateless.check_node n)) mmap;
596
    minit = init;
597
    mconst = s0;
598
    mstatic = List.filter (fun v -> v.var_dec_const) nd.node_inputs;
599
    mstep = {
600
      step_inputs = nd.node_inputs;
601
      step_outputs = nd.node_outputs;
602
      step_locals = ISet.elements (ISet.diff locals m);
603
      step_checks = List.map (fun d -> d.Dimension.dim_loc, translate_expr nd init_args (expr_of_dimension d)) nd.node_checks;
604
      step_instrs = (
605
	(* special treatment depending on the active backend. For horn backend,
606
	   common branches are not merged while they are in C or Java
607
	   backends. *)
608
	(*match !Options.output with
609
	| "horn" -> s
610
	  | "C" | "java" | _ ->*)
611
	if !Backends.join_guards then
612
	  join_guards_list s
613
	else
614
	  s
615
      );
616
      step_asserts = List.map (translate_expr nd init_args) nd_node_asserts;
617
    };
618
    mspec = nd.node_spec;
619
    mannot = nd.node_annot;
620
  }
621

    
622
(** takes the global declarations and the scheduling associated to each node *)
623
let translate_prog decls node_schs =
624
  let nodes = get_nodes decls in
625
  List.map
626
    (fun decl ->
627
     let node = node_of_top decl in
628
      let sch = (Utils.IMap.find node.node_id node_schs).Scheduling.schedule in
629
      translate_decl node sch
630
    ) nodes
631

    
632
let get_machine_opt name machines =
633
  List.fold_left
634
    (fun res m ->
635
      match res with
636
      | Some _ -> res
637
      | None -> if m.mname.node_id = name then Some m else None)
638
    None machines
639

    
640
let get_const_assign m id =
641
  try
642
    match (List.find (fun instr -> match instr with MLocalAssign (v, _) -> v == id | _ -> false) m.mconst) with
643
    | MLocalAssign (_, e) -> e
644
    | _                   -> assert false
645
  with Not_found -> assert false
646

    
647

    
648
let value_of_ident loc m id =
649
  (* is is a state var *)
650
  try
651
    let v = List.find (fun v -> v.var_id = id) m.mmemory
652
    in mk_val (StateVar v) v.var_type 
653
  with Not_found ->
654
    try (* id is a node var *)
655
      let v = get_node_var id m.mname
656
      in mk_val (LocalVar v) v.var_type
657
  with Not_found ->
658
    try (* id is a constant *)
659
      let c = Corelang.var_decl_of_const (const_of_top (Hashtbl.find Corelang.consts_table id))
660
      in mk_val (LocalVar c) c.var_type
661
    with Not_found ->
662
      (* id is a tag *)
663
      let t = Const_tag id
664
      in mk_val (Cst t) (Typing.type_const loc t)
665

    
666
(* type of internal fun used in dimension expression *)
667
let type_of_value_appl f args =
668
  if List.mem f Basic_library.arith_funs
669
  then (List.hd args).value_type
670
  else Type_predef.type_bool
671

    
672
let rec value_of_dimension m dim =
673
  match dim.Dimension.dim_desc with
674
  | Dimension.Dbool b         ->
675
     mk_val (Cst (Const_tag (if b then Corelang.tag_true else Corelang.tag_false))) Type_predef.type_bool
676
  | Dimension.Dint i          ->
677
     mk_val (Cst (Const_int i)) Type_predef.type_int
678
  | Dimension.Dident v        -> value_of_ident dim.Dimension.dim_loc m v
679
  | Dimension.Dappl (f, args) ->
680
     let vargs = List.map (value_of_dimension m) args
681
     in mk_val (Fun (f, vargs)) (type_of_value_appl f vargs) 
682
  | Dimension.Dite (i, t, e)  ->
683
     (match List.map (value_of_dimension m) [i; t; e] with
684
     | [vi; vt; ve] -> mk_val (Fun ("ite", [vi; vt; ve])) vt.value_type
685
     | _            -> assert false)
686
  | Dimension.Dlink dim'      -> value_of_dimension m dim'
687
  | _                         -> assert false
688

    
689
let rec dimension_of_value value =
690
  match value.value_desc with
691
  | Cst (Const_tag t) when t = Corelang.tag_true  -> Dimension.mkdim_bool  Location.dummy_loc true
692
  | Cst (Const_tag t) when t = Corelang.tag_false -> Dimension.mkdim_bool  Location.dummy_loc false
693
  | Cst (Const_int i)                             -> Dimension.mkdim_int   Location.dummy_loc i
694
  | LocalVar v                                    -> Dimension.mkdim_ident Location.dummy_loc v.var_id
695
  | Fun (f, args)                                 -> Dimension.mkdim_appl  Location.dummy_loc f (List.map dimension_of_value args)
696
  | _                                             -> assert false
697

    
698
(* Local Variables: *)
699
(* compile-command:"make -C .." *)
700
(* End: *)
(32-32/62)