Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / corelang.ml @ e8f55c25

History | View | Annotate | Download (47.9 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 Format
13
open Lustre_types
14
open Machine_code_types
15
(*open Dimension*)
16

    
17

    
18
exception Error of Location.t * Error.error_kind
19

    
20
module VDeclModule =
21
struct (* Node module *)
22
  type t = var_decl
23
  let compare v1 v2 = compare v1.var_id v2.var_id
24
end
25

    
26
module VMap = Map.Make(VDeclModule)
27

    
28
module VSet: sig
29
  include Set.S
30
  val pp: Format.formatter -> t -> unit
31
  val get: ident -> t -> elt
32
end with type elt = var_decl =
33
  struct
34
    include Set.Make(VDeclModule)
35
    let pp fmt s =
36
      Format.fprintf fmt "{@[%a}@]" (Utils.fprintf_list ~sep:",@ " Printers.pp_var) (elements s)
37
    (* Strangley the find_first function of Set.Make is incorrect (at
38
       the current time of writting this comment. Had to switch to
39
       lists *)
40
    let get id s = List.find (fun v -> v.var_id = id) (elements s)
41
  end
42
let dummy_type_dec = {ty_dec_desc=Tydec_any; ty_dec_loc=Location.dummy_loc}
43

    
44
let dummy_clock_dec = {ck_dec_desc=Ckdec_any; ck_dec_loc=Location.dummy_loc}
45

    
46

    
47

    
48
(************************************************************)
49
(* *)
50

    
51
let mktyp loc d =
52
  { ty_dec_desc = d; ty_dec_loc = loc }
53

    
54
let mkclock loc d =
55
  { ck_dec_desc = d; ck_dec_loc = loc }
56

    
57
let mkvar_decl loc ?(orig=false) (id, ty_dec, ck_dec, is_const, value, parentid) =
58
  assert (value = None || is_const);
59
  { var_id = id;
60
    var_orig = orig;
61
    var_dec_type = ty_dec;
62
    var_dec_clock = ck_dec;
63
    var_dec_const = is_const;
64
    var_dec_value = value;
65
    var_parent_nodeid = parentid;
66
    var_type = Types.new_var ();
67
    var_clock = Clocks.new_var true;
68
    var_loc = loc }
69

    
70
let dummy_var_decl name typ =
71
  {
72
    var_id = name;
73
    var_orig = false;
74
    var_dec_type = dummy_type_dec;
75
    var_dec_clock = dummy_clock_dec;
76
    var_dec_const = false;
77
    var_dec_value = None;
78
    var_parent_nodeid = None;
79
    var_type =  typ;
80
    var_clock = Clocks.new_ck Clocks.Cvar true;
81
    var_loc = Location.dummy_loc
82
  }
83

    
84
let mkexpr loc d =
85
  { expr_tag = Utils.new_tag ();
86
    expr_desc = d;
87
    expr_type = Types.new_var ();
88
    expr_clock = Clocks.new_var true;
89
    expr_delay = Delay.new_var ();
90
    expr_annot = None;
91
    expr_loc = loc }
92

    
93
let var_decl_of_const ?(parentid=None) c =
94
  { var_id = c.const_id;
95
    var_orig = true;
96
    var_dec_type = { ty_dec_loc = c.const_loc; ty_dec_desc = Tydec_any };
97
    var_dec_clock = { ck_dec_loc = c.const_loc; ck_dec_desc = Ckdec_any };
98
    var_dec_const = true;
99
    var_dec_value = None;
100
    var_parent_nodeid = parentid;
101
    var_type = c.const_type;
102
    var_clock = Clocks.new_var false;
103
    var_loc = c.const_loc }
104

    
105
let mk_new_name used id =
106
  let rec new_name name cpt =
107
    if used name
108
    then new_name (sprintf "_%s_%i" id cpt) (cpt+1)
109
    else name
110
  in new_name id 1
111

    
112
let mkeq loc (lhs, rhs) =
113
  { eq_lhs = lhs;
114
    eq_rhs = rhs;
115
    eq_loc = loc }
116

    
117
let mkassert loc expr =
118
  { assert_loc = loc;
119
    assert_expr = expr
120
  }
121

    
122
let mktop_decl loc own itf d =
123
  { top_decl_desc = d; top_decl_loc = loc; top_decl_owner = own; top_decl_itf = itf }
124

    
125
let mkpredef_call loc funname args =
126
  mkexpr loc (Expr_appl (funname, mkexpr loc (Expr_tuple args), None))
127

    
128
let is_clock_dec_type cty =
129
  match cty with
130
  | Tydec_clock _ -> true
131
  | _             -> false
132

    
133
let const_of_top top_decl =
134
  match top_decl.top_decl_desc with
135
  | Const c -> c
136
  | _ -> assert false
137

    
138
let node_of_top top_decl =
139
  match top_decl.top_decl_desc with
140
  | Node nd -> nd
141
  | _ -> raise Not_found
142

    
143
let imported_node_of_top top_decl =
144
  match top_decl.top_decl_desc with
145
  | ImportedNode ind -> ind
146
  | _ -> assert false
147

    
148
let typedef_of_top top_decl =
149
  match top_decl.top_decl_desc with
150
  | TypeDef tdef -> tdef
151
  | _ -> assert false
152

    
153
let dependency_of_top top_decl =
154
  match top_decl.top_decl_desc with
155
  | Open (local, dep) -> (local, dep)
156
  | _ -> assert false
157

    
158
let consts_of_enum_type top_decl =
159
  match top_decl.top_decl_desc with
160
  | TypeDef tdef ->
161
    (match tdef.tydef_desc with
162
    | Tydec_enum tags ->
163
       List.map
164
	 (fun tag ->
165
	   let cdecl = {
166
	     const_id = tag;
167
	     const_loc = top_decl.top_decl_loc;
168
	     const_value = Const_tag tag;
169
	     const_type = Type_predef.type_const tdef.tydef_id
170
	   } in
171
	   { top_decl with top_decl_desc = Const cdecl })
172
	 tags
173
     | _               -> [])
174
  | _ -> assert false
175

    
176
(************************************************************)
177
(*   Eexpr functions *)
178
(************************************************************)
179

    
180

    
181
let empty_contract =
182
  {
183
    consts = []; locals = []; stmts = []; assume = []; guarantees = []; modes = []; imports = []; spec_loc = Location.dummy_loc;
184
  }
185

    
186
(* For const declaration we do as for regular lustre node.
187
But for local flows we registered the variable and the lustre flow definition *)
188
let mk_contract_var id is_const type_opt expr loc =
189
  let typ = match type_opt with None -> mktyp loc Tydec_any | Some t -> t in
190
  if is_const then
191
  let v = mkvar_decl loc (id, typ, mkclock loc Ckdec_any, is_const, Some expr, None) in
192
  { empty_contract with consts = [v]; spec_loc = loc; }
193
  else
194
    let v = mkvar_decl loc (id, typ, mkclock loc Ckdec_any, is_const, None, None) in
195
    let eq = mkeq loc ([id], expr) in 
196
    { empty_contract with locals = [v]; stmts = [Eq eq]; spec_loc = loc; }
197
let eexpr_add_name eexpr name =
198
  {eexpr with eexpr_name = match name with "" -> None | _ -> Some name}
199
let mk_contract_guarantees ?(name="") eexpr =
200
  { empty_contract with guarantees = [eexpr_add_name eexpr name]; spec_loc = eexpr.eexpr_loc }
201

    
202
let mk_contract_assume ?(name="") eexpr =
203
  { empty_contract with assume = [eexpr_add_name eexpr name]; spec_loc = eexpr.eexpr_loc }
204

    
205
let mk_contract_mode id rl el loc =
206
  { empty_contract with modes = [{ mode_id = id; require = rl; ensure = el; mode_loc = loc; }]; spec_loc = loc }
207

    
208
let mk_contract_import id ins outs loc =
209
  { empty_contract with imports = [{import_nodeid = id; inputs = ins; outputs = outs; import_loc = loc; }]; spec_loc = loc }
210

    
211
    
212
let merge_contracts ann1 ann2 = (* keeping the first item loc *)
213
  { consts = ann1.consts @ ann2.consts;
214
    locals = ann1.locals @ ann2.locals;
215
    stmts = ann1.stmts @ ann2.stmts;
216
    assume = ann1.assume @ ann2.assume;
217
    guarantees = ann1.guarantees @ ann2.guarantees;
218
    modes = ann1.modes @ ann2.modes;
219
    imports = ann1.imports @ ann2.imports;
220
    spec_loc = ann1.spec_loc
221
  }
222

    
223
let mkeexpr loc expr =
224
  { eexpr_tag = Utils.new_tag ();
225
    eexpr_qfexpr = expr;
226
    eexpr_quantifiers = [];
227
    eexpr_name = None;
228
    eexpr_type = Types.new_var ();
229
    eexpr_clock = Clocks.new_var true;
230
    eexpr_loc = loc }
231

    
232
let extend_eexpr q e = { e with eexpr_quantifiers = q@e.eexpr_quantifiers }
233

    
234
(*
235
let mkepredef_call loc funname args =
236
  mkeexpr loc (EExpr_appl (funname, mkeexpr loc (EExpr_tuple args), None))
237

    
238
let mkepredef_unary_call loc funname arg =
239
  mkeexpr loc (EExpr_appl (funname, arg, None))
240
*)
241

    
242
let merge_expr_annot ann1 ann2 =
243
  match ann1, ann2 with
244
    | None, None -> assert false
245
    | Some _, None -> ann1
246
    | None, Some _ -> ann2
247
    | Some ann1, Some ann2 -> Some {
248
      annots = ann1.annots @ ann2.annots;
249
      annot_loc = ann1.annot_loc
250
    }
251

    
252
let update_expr_annot node_id e annot =
253
  List.iter (fun (key, _) -> 
254
    Annotations.add_expr_ann node_id e.expr_tag key
255
  ) annot.annots;
256
  e.expr_annot <- merge_expr_annot e.expr_annot (Some annot);
257
  e
258

    
259

    
260
let mkinstr ?lustre_expr ?lustre_eq i =
261
  {
262
    instr_desc = i;
263
    (* lustre_expr = lustre_expr; *)
264
    lustre_eq = lustre_eq;
265
  }
266

    
267
let get_instr_desc i = i.instr_desc
268
let update_instr_desc i id = { i with instr_desc = id }
269

    
270
(***********************************************************)
271
(* Fast access to nodes, by name *)
272
let (node_table : (ident, top_decl) Hashtbl.t) = Hashtbl.create 30
273
let consts_table = Hashtbl.create 30
274

    
275
let print_node_table fmt () =
276
  begin
277
    Format.fprintf fmt "{ /* node table */@.";
278
    Hashtbl.iter (fun id nd ->
279
      Format.fprintf fmt "%s |-> %a"
280
	id
281
	Printers.pp_short_decl nd
282
    ) node_table;
283
    Format.fprintf fmt "}@."
284
  end
285

    
286
let print_consts_table fmt () =
287
  begin
288
    Format.fprintf fmt "{ /* consts table */@.";
289
    Hashtbl.iter (fun id const ->
290
      Format.fprintf fmt "%s |-> %a"
291
	id
292
	Printers.pp_const_decl (const_of_top const)
293
    ) consts_table;
294
    Format.fprintf fmt "}@."
295
  end
296

    
297
let node_name td =
298
    match td.top_decl_desc with 
299
    | Node nd         -> nd.node_id
300
    | ImportedNode nd -> nd.nodei_id
301
    | _ -> assert false
302

    
303
let is_generic_node td =
304
  match td.top_decl_desc with 
305
  | Node nd         -> List.exists (fun v -> v.var_dec_const) nd.node_inputs
306
  | ImportedNode nd -> List.exists (fun v -> v.var_dec_const) nd.nodei_inputs
307
  | _ -> assert false
308

    
309
let node_inputs td =
310
  match td.top_decl_desc with 
311
  | Node nd         -> nd.node_inputs
312
  | ImportedNode nd -> nd.nodei_inputs
313
  | _ -> assert false
314

    
315
let node_from_name id =
316
      Hashtbl.find node_table id
317
  (* with Not_found -> (Format.eprintf "Unable to find any node named %s@ @?" id;
318
   *       	     assert false) *)
319

    
320
let update_node id top =
321
  Hashtbl.replace node_table id top
322

    
323
let is_imported_node td =
324
  match td.top_decl_desc with 
325
  | Node nd         -> false
326
  | ImportedNode nd -> true
327
  | _ -> assert false
328

    
329
let is_node_contract nd =
330
  match nd.node_spec with
331
  | Some (Contract _) -> true
332
  | _ -> false
333
  
334
let get_node_contract nd =
335
  match nd.node_spec with
336
  | Some (Contract c) -> c
337
  | _ -> assert false
338
  
339
let is_contract td =
340
  match td.top_decl_desc with 
341
  | Node nd -> is_node_contract nd
342
  | _ -> false
343

    
344
(* alias and type definition table *)
345

    
346
let mktop = mktop_decl Location.dummy_loc !Options.dest_dir false
347

    
348
let top_int_type = mktop (TypeDef {tydef_id = "int"; tydef_desc = Tydec_int})
349
let top_bool_type = mktop (TypeDef {tydef_id = "bool"; tydef_desc = Tydec_bool})
350
(* let top_float_type = mktop (TypeDef {tydef_id = "float"; tydef_desc = Tydec_float}) *)
351
let top_real_type = mktop (TypeDef {tydef_id = "real"; tydef_desc = Tydec_real})
352

    
353
let type_table =
354
  Utils.create_hashtable 20 [
355
    Tydec_int  , top_int_type;
356
    Tydec_bool , top_bool_type;
357
    (* Tydec_float, top_float_type; *)
358
    Tydec_real , top_real_type
359
  ]
360

    
361
let print_type_table fmt () =
362
  begin
363
    Format.fprintf fmt "{ /* type table */@.";
364
    Hashtbl.iter (fun tydec tdef ->
365
      Format.fprintf fmt "%a |-> %a"
366
	Printers.pp_var_type_dec_desc tydec
367
	Printers.pp_typedef (typedef_of_top tdef)
368
    ) type_table;
369
    Format.fprintf fmt "}@."
370
  end
371

    
372
let rec is_user_type typ =
373
  match typ with
374
  | Tydec_int | Tydec_bool | Tydec_real 
375
  (* | Tydec_float *) | Tydec_any | Tydec_const _ -> false
376
  | Tydec_clock typ' -> is_user_type typ'
377
  | _ -> true
378

    
379
let get_repr_type typ =
380
  let typ_def = (typedef_of_top (Hashtbl.find type_table typ)).tydef_desc in
381
  if is_user_type typ_def then typ else typ_def
382

    
383
let rec coretype_equal ty1 ty2 =
384
  let res =
385
  match ty1, ty2 with
386
  | Tydec_any           , _
387
  | _                   , Tydec_any             -> assert false
388
  | Tydec_const _       , Tydec_const _         -> get_repr_type ty1 = get_repr_type ty2
389
  | Tydec_const _       , _                     -> let ty1' = (typedef_of_top (Hashtbl.find type_table ty1)).tydef_desc
390
	       					   in (not (is_user_type ty1')) && coretype_equal ty1' ty2
391
  | _                   , Tydec_const _         -> coretype_equal ty2 ty1
392
  | Tydec_int           , Tydec_int
393
  | Tydec_real          , Tydec_real
394
  (* | Tydec_float         , Tydec_float *)
395
  | Tydec_bool          , Tydec_bool            -> true
396
  | Tydec_clock ty1     , Tydec_clock ty2       -> coretype_equal ty1 ty2
397
  | Tydec_array (d1,ty1), Tydec_array (d2, ty2) -> Dimension.is_eq_dimension d1 d2 && coretype_equal ty1 ty2
398
  | Tydec_enum tl1      , Tydec_enum tl2        -> List.sort compare tl1 = List.sort compare tl2
399
  | Tydec_struct fl1    , Tydec_struct fl2      ->
400
       List.length fl1 = List.length fl2
401
    && List.for_all2 (fun (f1, t1) (f2, t2) -> f1 = f2 && coretype_equal t1 t2)
402
      (List.sort (fun (f1,_) (f2,_) -> compare f1 f2) fl1)
403
      (List.sort (fun (f1,_) (f2,_) -> compare f1 f2) fl2)
404
  | _                                  -> false
405
  in ((*Format.eprintf "coretype_equal %a %a = %B@." Printers.pp_var_type_dec_desc ty1 Printers.pp_var_type_dec_desc ty2 res;*) res)
406

    
407
let tag_default = "default"
408

    
409
let const_is_bool c =
410
 match c with
411
 | Const_tag t -> t = tag_true || t = tag_false
412
 | _           -> false
413

    
414
(* Computes the negation of a boolean constant *)
415
let const_negation c =
416
  assert (const_is_bool c);
417
  match c with
418
  | Const_tag t when t = tag_true  -> Const_tag tag_false
419
  | _                              -> Const_tag tag_true
420

    
421
let const_or c1 c2 =
422
  assert (const_is_bool c1 && const_is_bool c2);
423
  match c1, c2 with
424
  | Const_tag t1, _            when t1 = tag_true -> c1
425
  | _           , Const_tag t2 when t2 = tag_true -> c2
426
  | _                                             -> Const_tag tag_false
427

    
428
let const_and c1 c2 =
429
  assert (const_is_bool c1 && const_is_bool c2);
430
  match c1, c2 with
431
  | Const_tag t1, _            when t1 = tag_false -> c1
432
  | _           , Const_tag t2 when t2 = tag_false -> c2
433
  | _                                              -> Const_tag tag_true
434

    
435
let const_xor c1 c2 =
436
  assert (const_is_bool c1 && const_is_bool c2);
437
   match c1, c2 with
438
  | Const_tag t1, Const_tag t2 when t1 <> t2  -> Const_tag tag_true
439
  | _                                         -> Const_tag tag_false
440

    
441
let const_impl c1 c2 =
442
  assert (const_is_bool c1 && const_is_bool c2);
443
  match c1, c2 with
444
  | Const_tag t1, _ when t1 = tag_false           -> Const_tag tag_true
445
  | _           , Const_tag t2 when t2 = tag_true -> Const_tag tag_true
446
  | _                                             -> Const_tag tag_false
447

    
448
(* To guarantee uniqueness of tags in enum types *)
449
let tag_table =
450
  Utils.create_hashtable 20 [
451
   tag_true, top_bool_type;
452
   tag_false, top_bool_type
453
  ]
454

    
455
(* To guarantee uniqueness of fields in struct types *)
456
let field_table =
457
  Utils.create_hashtable 20 [
458
  ]
459

    
460
let get_enum_type_tags cty =
461
(*Format.eprintf "get_enum_type_tags %a@." Printers.pp_var_type_dec_desc cty;*)
462
 match cty with
463
 | Tydec_bool    -> [tag_true; tag_false]
464
 | Tydec_const _ -> (match (typedef_of_top (Hashtbl.find type_table cty)).tydef_desc with
465
                     | Tydec_enum tl -> tl
466
                     | _             -> assert false)
467
 | _            -> assert false
468

    
469
let get_struct_type_fields cty =
470
 match cty with
471
 | Tydec_const _ -> (match (typedef_of_top (Hashtbl.find type_table cty)).tydef_desc with
472
                     | Tydec_struct fl -> fl
473
                     | _               -> assert false)
474
 | _            -> assert false
475

    
476
let const_of_bool b =
477
 Const_tag (if b then tag_true else tag_false)
478

    
479
(* let get_const c = snd (Hashtbl.find consts_table c) *)
480

    
481
let ident_of_expr expr =
482
 match expr.expr_desc with
483
 | Expr_ident id -> id
484
 | _             -> assert false
485

    
486
(* Generate a new ident expression from a declared variable *)
487
let expr_of_vdecl v =
488
  { expr_tag = Utils.new_tag ();
489
    expr_desc = Expr_ident v.var_id;
490
    expr_type = v.var_type;
491
    expr_clock = v.var_clock;
492
    expr_delay = Delay.new_var ();
493
    expr_annot = None;
494
    expr_loc = v.var_loc }
495

    
496
(* Caution, returns an untyped and unclocked expression *)
497
let expr_of_ident id loc =
498
  {expr_tag = Utils.new_tag ();
499
   expr_desc = Expr_ident id;
500
   expr_type = Types.new_var ();
501
   expr_clock = Clocks.new_var true;
502
   expr_delay = Delay.new_var ();
503
   expr_loc = loc;
504
   expr_annot = None}
505

    
506
let is_tuple_expr expr =
507
 match expr.expr_desc with
508
  | Expr_tuple _ -> true
509
  | _            -> false
510

    
511
let expr_list_of_expr expr =
512
  match expr.expr_desc with
513
  | Expr_tuple elist -> elist
514
  | _                -> [expr]
515

    
516
let expr_of_expr_list loc elist =
517
 match elist with
518
 | [t]  -> { t with expr_loc = loc }
519
 | t::_ ->
520
    let tlist = List.map (fun e -> e.expr_type) elist in
521
    let clist = List.map (fun e -> e.expr_clock) elist in
522
    { t with expr_desc = Expr_tuple elist;
523
	     expr_type = Type_predef.type_tuple tlist;
524
	     expr_clock = Clock_predef.ck_tuple clist;
525
	     expr_tag = Utils.new_tag ();
526
	     expr_loc = loc }
527
 | _    -> assert false
528

    
529
let call_of_expr expr =
530
 match expr.expr_desc with
531
 | Expr_appl (f, args, r) -> (f, expr_list_of_expr args, r)
532
 | _                      -> assert false
533

    
534
    
535
(* Conversion from dimension expr to standard expr, for the purpose of printing, typing, etc... *)
536
let rec expr_of_dimension dim =
537
  let open Dimension in
538
  match dim.dim_desc with
539
 | Dbool b        ->
540
     mkexpr dim.dim_loc (Expr_const (const_of_bool b))
541
 | Dint i         ->
542
     mkexpr dim.dim_loc (Expr_const (Const_int i))
543
 | Dident id      ->
544
     mkexpr dim.dim_loc (Expr_ident id)
545
 | Dite (c, t, e) ->
546
     mkexpr dim.dim_loc (Expr_ite (expr_of_dimension c, expr_of_dimension t, expr_of_dimension e))
547
 | Dappl (id, args) ->
548
     mkexpr dim.dim_loc (Expr_appl (id, expr_of_expr_list dim.dim_loc (List.map expr_of_dimension args), None))
549
 | Dlink dim'       -> expr_of_dimension dim'
550
 | Dvar
551
 | Dunivar          -> (Format.eprintf "internal error: Corelang.expr_of_dimension %a@." Dimension.pp_dimension dim;
552
			assert false)
553

    
554
let dimension_of_const loc const =
555
  let open Dimension in
556
 match const with
557
 | Const_int i                                    -> mkdim_int loc i
558
 | Const_tag t when t = tag_true || t = tag_false -> mkdim_bool loc (t = tag_true)
559
 | _                                              -> raise InvalidDimension
560

    
561
(* Conversion from standard expr to dimension expr, for the purpose of injecting static call arguments 
562
   into dimension expressions *)
563
let rec dimension_of_expr expr =
564
  let open Dimension in
565
  match expr.expr_desc with
566
  | Expr_const c  -> dimension_of_const expr.expr_loc c
567
  | Expr_ident id -> mkdim_ident expr.expr_loc id
568
  | Expr_appl (f, args, None) when Basic_library.is_expr_internal_fun expr ->
569
      let k = Types.get_static_value (Env.lookup_value Basic_library.type_env f) in
570
      if k = None then raise InvalidDimension;
571
      mkdim_appl expr.expr_loc f (List.map dimension_of_expr (expr_list_of_expr args))
572
  | Expr_ite (i, t, e)        ->
573
      mkdim_ite expr.expr_loc (dimension_of_expr i) (dimension_of_expr t) (dimension_of_expr e)
574
  | _ -> raise InvalidDimension (* not a simple dimension expression *)
575

    
576

    
577
let sort_handlers hl =
578
 List.sort (fun (t, _) (t', _) -> compare t t') hl
579

    
580
  
581
let rec is_eq_const c1 c2 =
582
  match c1, c2 with
583
  | Const_real r1, Const_real r2
584
    -> Real.eq r1 r1 
585
  | Const_struct lcl1, Const_struct lcl2
586
    -> List.length lcl1 = List.length lcl2
587
    && List.for_all2 (fun (l1, c1) (l2, c2) -> l1 = l2 && is_eq_const c1 c2) lcl1 lcl2
588
  | _  -> c1 = c2
589

    
590
let rec is_eq_expr e1 e2 = match e1.expr_desc, e2.expr_desc with
591
  | Expr_const c1, Expr_const c2 -> is_eq_const c1 c2
592
  | Expr_ident i1, Expr_ident i2 -> i1 = i2
593
  | Expr_array el1, Expr_array el2 
594
  | Expr_tuple el1, Expr_tuple el2 -> 
595
    List.length el1 = List.length el2 && List.for_all2 is_eq_expr el1 el2 
596
  | Expr_arrow (e1, e2), Expr_arrow (e1', e2') -> is_eq_expr e1 e1' && is_eq_expr e2 e2'
597
  | Expr_fby (e1,e2), Expr_fby (e1',e2') -> is_eq_expr e1 e1' && is_eq_expr e2 e2'
598
  | Expr_ite (i1, t1, e1), Expr_ite (i2, t2, e2) -> is_eq_expr i1 i2 && is_eq_expr t1 t2 && is_eq_expr e1 e2
599
  (* | Expr_concat (e1,e2), Expr_concat (e1',e2') -> is_eq_expr e1 e1' && is_eq_expr e2 e2' *)
600
  (* | Expr_tail e, Expr_tail e' -> is_eq_expr e e' *)
601
  | Expr_pre e, Expr_pre e' -> is_eq_expr e e'
602
  | Expr_when (e, i, l), Expr_when (e', i', l') -> l=l' && i=i' && is_eq_expr e e'
603
  | Expr_merge(i, hl), Expr_merge(i', hl') -> i=i' && List.for_all2 (fun (t, h) (t', h') -> t=t' && is_eq_expr h h') (sort_handlers hl) (sort_handlers hl')
604
  | Expr_appl (i, e, r), Expr_appl (i', e', r') -> i=i' && r=r' && is_eq_expr e e'
605
  | Expr_power (e1, i1), Expr_power (e2, i2)
606
  | Expr_access (e1, i1), Expr_access (e2, i2) -> is_eq_expr e1 e2 && is_eq_expr (expr_of_dimension i1) (expr_of_dimension i2)
607
  | _ -> false
608

    
609
let get_node_vars nd =
610
  nd.node_inputs @ nd.node_locals @ nd.node_outputs
611

    
612
let mk_new_node_name nd id =
613
  let used_vars = get_node_vars nd in
614
  let used v = List.exists (fun vdecl -> vdecl.var_id = v) used_vars in
615
  mk_new_name used id
616

    
617
let get_var id var_list =
618
  List.find (fun v -> v.var_id = id) var_list
619

    
620
let get_node_var id node =
621
  try
622
    get_var id (get_node_vars node)
623
  with Not_found -> begin
624
    (* Format.eprintf "Unable to find variable %s in node %s@.@?" id node.node_id; *)
625
    raise Not_found
626
  end
627

    
628

    
629
let get_node_eqs =
630
  let get_eqs stmts =
631
    List.fold_right
632
      (fun stmt (res_eq, res_aut) ->
633
	match stmt with
634
	| Eq eq -> eq :: res_eq, res_aut
635
	| Aut aut -> res_eq, aut::res_aut)
636
      stmts
637
      ([], []) in
638
  let table_eqs = Hashtbl.create 23 in
639
  (fun nd ->
640
    try
641
      let (old, res) = Hashtbl.find table_eqs nd.node_id
642
      in if old == nd.node_stmts then res else raise Not_found
643
    with Not_found -> 
644
      let res = get_eqs nd.node_stmts in
645
      begin
646
	Hashtbl.replace table_eqs nd.node_id (nd.node_stmts, res);
647
	res
648
      end)
649

    
650
let get_node_eq id node =
651
  let eqs, auts = get_node_eqs node in
652
  try
653
    List.find (fun eq -> List.mem id eq.eq_lhs) eqs
654
  with
655
    Not_found -> (* Shall be defined in automata auts *) raise Not_found
656
      
657
let get_nodes prog = 
658
  List.fold_left (
659
    fun nodes decl ->
660
      match decl.top_decl_desc with
661
	| Node _ -> decl::nodes
662
	| Const _ | ImportedNode _ | Include _ | Open _ | TypeDef _ -> nodes  
663
  ) [] prog
664

    
665
let get_imported_nodes prog = 
666
  List.fold_left (
667
    fun nodes decl ->
668
      match decl.top_decl_desc with
669
	| ImportedNode _ -> decl::nodes
670
	| Const _ | Node _ | Include _ | Open _ | TypeDef _-> nodes  
671
  ) [] prog
672

    
673
let get_consts prog = 
674
  List.fold_right (
675
    fun decl consts ->
676
      match decl.top_decl_desc with
677
	| Const _ -> decl::consts
678
	| Node _ | ImportedNode _ | Include _ | Open _ | TypeDef _ -> consts  
679
  ) prog []
680

    
681
let get_typedefs prog = 
682
  List.fold_right (
683
    fun decl types ->
684
      match decl.top_decl_desc with
685
	| TypeDef _ -> decl::types
686
	| Node _ | ImportedNode _ | Include _ | Open _ | Const _ -> types  
687
  ) prog []
688

    
689
let get_dependencies prog =
690
  List.fold_right (
691
    fun decl deps ->
692
      match decl.top_decl_desc with
693
	| Open _ -> decl::deps
694
	| Node _ | ImportedNode _ | TypeDef _ | Include _ | Const _ -> deps  
695
  ) prog []
696

    
697
let get_node_interface nd =
698
 {nodei_id = nd.node_id;
699
  nodei_type = nd.node_type;
700
  nodei_clock = nd.node_clock;
701
  nodei_inputs = nd.node_inputs;
702
  nodei_outputs = nd.node_outputs;
703
  nodei_stateless = nd.node_dec_stateless;
704
  nodei_spec = nd.node_spec;
705
  (* nodei_annot = nd.node_annot; *)
706
  nodei_prototype = None;
707
  nodei_in_lib = [];
708
 }
709

    
710
(************************************************************************)
711
(*        Renaming / Copying                                                      *)
712

    
713
let copy_var_decl vdecl =
714
  mkvar_decl
715
    vdecl.var_loc
716
    ~orig:vdecl.var_orig
717
    (
718
      vdecl.var_id,
719
      vdecl.var_dec_type,
720
      vdecl.var_dec_clock,
721
      vdecl.var_dec_const,
722
      vdecl.var_dec_value,
723
      vdecl.var_parent_nodeid
724
    )
725

    
726
let copy_const cdecl =
727
  { cdecl with const_type = Types.new_var () }
728

    
729
let copy_node nd =
730
  { nd with
731
    node_type     = Types.new_var ();
732
    node_clock    = Clocks.new_var true;
733
    node_inputs   = List.map copy_var_decl nd.node_inputs;
734
    node_outputs  = List.map copy_var_decl nd.node_outputs;
735
    node_locals   = List.map copy_var_decl nd.node_locals;
736
    node_gencalls = [];
737
    node_checks   = [];
738
    node_stateless = None;
739
  }
740

    
741
let copy_top top =
742
  match top.top_decl_desc with
743
  | Node nd -> { top with top_decl_desc = Node (copy_node nd)  }
744
  | Const c -> { top with top_decl_desc = Const (copy_const c) }
745
  | _       -> top
746

    
747
let copy_prog top_list =
748
  List.map copy_top top_list
749

    
750
  
751
let rec rename_static rename cty =
752
 match cty with
753
 | Tydec_array (d, cty') -> Tydec_array (Dimension.expr_replace_expr rename d, rename_static rename cty')
754
 | Tydec_clock cty       -> Tydec_clock (rename_static rename cty)
755
 | Tydec_struct fl       -> Tydec_struct (List.map (fun (f, cty) -> f, rename_static rename cty) fl)
756
 | _                      -> cty
757

    
758
let rec rename_carrier rename cck =
759
 match cck with
760
 | Ckdec_bool cl -> Ckdec_bool (List.map (fun (c, l) -> rename c, l) cl)
761
 | _             -> cck
762

    
763
 (*Format.eprintf "Types.rename_static %a = %a@." print_ty ty print_ty res; res*)
764

    
765
(* applies the renaming function [fvar] to all variables of expression [expr] *)
766
 (* let rec expr_replace_var fvar expr = *)
767
 (*  { expr with expr_desc = expr_desc_replace_var fvar expr.expr_desc } *)
768

    
769
 (* and expr_desc_replace_var fvar expr_desc = *)
770
 (*   match expr_desc with *)
771
 (*   | Expr_const _ -> expr_desc *)
772
 (*   | Expr_ident i -> Expr_ident (fvar i) *)
773
 (*   | Expr_array el -> Expr_array (List.map (expr_replace_var fvar) el) *)
774
 (*   | Expr_access (e1, d) -> Expr_access (expr_replace_var fvar e1, d) *)
775
 (*   | Expr_power (e1, d) -> Expr_power (expr_replace_var fvar e1, d) *)
776
 (*   | Expr_tuple el -> Expr_tuple (List.map (expr_replace_var fvar) el) *)
777
 (*   | Expr_ite (c, t, e) -> Expr_ite (expr_replace_var fvar c, expr_replace_var fvar t, expr_replace_var fvar e) *)
778
 (*   | Expr_arrow (e1, e2)-> Expr_arrow (expr_replace_var fvar e1, expr_replace_var fvar e2)  *)
779
 (*   | Expr_fby (e1, e2) -> Expr_fby (expr_replace_var fvar e1, expr_replace_var fvar e2) *)
780
 (*   | Expr_pre e' -> Expr_pre (expr_replace_var fvar e') *)
781
 (*   | Expr_when (e', i, l)-> Expr_when (expr_replace_var fvar e', fvar i, l) *)
782
 (*   | Expr_merge (i, hl) -> Expr_merge (fvar i, List.map (fun (t, h) -> (t, expr_replace_var fvar h)) hl) *)
783
 (*   | Expr_appl (i, e', i') -> Expr_appl (i, expr_replace_var fvar e', Utils.option_map (expr_replace_var fvar) i') *)
784

    
785

    
786

    
787
 let rec rename_expr  f_node f_var expr =
788
   { expr with expr_desc = rename_expr_desc f_node f_var expr.expr_desc }
789
 and rename_expr_desc f_node f_var expr_desc =
790
   let re = rename_expr  f_node f_var in
791
   match expr_desc with
792
   | Expr_const _ -> expr_desc
793
   | Expr_ident i -> Expr_ident (f_var i)
794
   | Expr_array el -> Expr_array (List.map re el)
795
   | Expr_access (e1, d) -> Expr_access (re e1, d)
796
   | Expr_power (e1, d) -> Expr_power (re e1, d)
797
   | Expr_tuple el -> Expr_tuple (List.map re el)
798
   | Expr_ite (c, t, e) -> Expr_ite (re c, re t, re e)
799
   | Expr_arrow (e1, e2)-> Expr_arrow (re e1, re e2) 
800
   | Expr_fby (e1, e2) -> Expr_fby (re e1, re e2)
801
   | Expr_pre e' -> Expr_pre (re e')
802
   | Expr_when (e', i, l)-> Expr_when (re e', f_var i, l)
803
   | Expr_merge (i, hl) -> 
804
     Expr_merge (f_var i, List.map (fun (t, h) -> (t, re h)) hl)
805
   | Expr_appl (i, e', i') -> 
806
     Expr_appl (f_node i, re e', Utils.option_map re i')
807
   
808
 let rename_var f_node f_var v = {
809
     (copy_var_decl v) with
810
     var_id = f_var v.var_id;
811
     var_type = v.var_type;
812
     var_clock = v.var_clock;
813
 } 
814

    
815
 let rename_vars f_node f_var = List.map (rename_var f_node f_var) 
816

    
817
 let rec rename_eq f_node f_var eq = { eq with
818
   eq_lhs = List.map f_var eq.eq_lhs; 
819
   eq_rhs = rename_expr f_node f_var eq.eq_rhs
820
 } 
821
 and rename_handler f_node f_var  h = {h with
822
   hand_state = f_var h.hand_state;
823
   hand_unless = List.map (
824
     fun (l,e,b,id) -> l, rename_expr f_node f_var e, b, f_var id
825
   ) h.hand_unless;
826
   hand_until = List.map (
827
     fun (l,e,b,id) -> l, rename_expr f_node f_var e, b, f_var id
828
   ) h.hand_until;
829
   hand_locals = rename_vars f_node f_var h.hand_locals;
830
   hand_stmts = rename_stmts f_node f_var h.hand_stmts;
831
   hand_annots = rename_annots f_node f_var h.hand_annots;
832
   
833
 } 
834
 and rename_aut f_node f_var  aut = { aut with
835
   aut_id = f_var aut.aut_id;
836
   aut_handlers = List.map (rename_handler f_node f_var) aut.aut_handlers;
837
 }
838
 and rename_stmts f_node f_var stmts = List.map (fun stmt -> match stmt with
839
   | Eq eq -> Eq (rename_eq f_node f_var eq)
840
   | Aut at -> Aut (rename_aut f_node f_var at))
841
   stmts
842
 and rename_annotl f_node f_var  annots = 
843
   List.map 
844
     (fun (key, value) -> key, rename_eexpr f_node f_var value) 
845
     annots
846
 and rename_annot f_node f_var annot =
847
   { annot with annots = rename_annotl f_node f_var annot.annots }
848
 and rename_annots f_node f_var annots =
849
   List.map (rename_annot f_node f_var) annots
850
and rename_eexpr f_node f_var ee =
851
   { ee with
852
     eexpr_tag = Utils.new_tag ();
853
     eexpr_qfexpr = rename_expr f_node f_var ee.eexpr_qfexpr;
854
     eexpr_quantifiers = List.map (fun (typ,vdecls) -> typ, rename_vars f_node f_var vdecls) ee.eexpr_quantifiers;
855
   }
856
and rename_mode f_node f_var m =
857
  let rename_ee = rename_eexpr f_node f_var in
858
  {
859
    m with
860
    require = List.map rename_ee m.require;
861
    ensure = List.map rename_ee m.ensure
862
  }
863
     
864
 let rename_import f_node f_var imp =
865
   let rename_expr = rename_expr f_node f_var in
866
   {
867
     imp with
868
     import_nodeid = f_node imp.import_nodeid;
869
     inputs = rename_expr imp.inputs;
870
     outputs =  rename_expr imp.outputs;
871
   }
872
   
873
 let rename_node f_node f_var nd =
874
   let f_var x = (* checking that this is actually a local variable *)
875
     if List.exists (fun v -> v.var_id = x) (get_node_vars nd) then
876
       f_var x
877
     else
878
       x
879
   in
880
   let rename_var = rename_var f_node f_var in
881
   let rename_vars = List.map rename_var in
882
   let rename_expr = rename_expr f_node f_var in
883
   let rename_eexpr = rename_eexpr f_node f_var in
884
   let rename_stmts = rename_stmts f_node f_var in
885
   let inputs = rename_vars nd.node_inputs in
886
   let outputs = rename_vars nd.node_outputs in
887
   let locals = rename_vars nd.node_locals in
888
   let gen_calls = List.map rename_expr nd.node_gencalls in
889
   let node_checks = List.map (Dimension.rename f_node f_var)  nd.node_checks in
890
   let node_asserts = List.map 
891
     (fun a -> 
892
       {a with assert_expr = 
893
	   let expr = a.assert_expr in
894
	   rename_expr expr})
895
     nd.node_asserts
896
   in
897
   let node_stmts = rename_stmts nd.node_stmts
898

    
899
     
900
   in
901
   let spec = 
902
     Utils.option_map 
903
       (fun s -> match s with
904
                   NodeSpec id -> NodeSpec (f_node id)
905
                 | Contract c -> Contract {
906
                     c with
907
                     consts = rename_vars c.consts;
908
                     locals = rename_vars c.locals;
909
                     stmts = rename_stmts c.stmts;
910
                     assume = List.map rename_eexpr c.assume;
911
                     guarantees = List.map rename_eexpr c.guarantees;
912
                     modes = List.map (rename_mode f_node f_var) c.modes;
913
                     imports = List.map (rename_import f_node f_var) c.imports;
914
                   }
915
       )
916
       nd.node_spec 
917
   in
918
   let annot = rename_annots f_node f_var nd.node_annot in
919
   {
920
     node_id = f_node nd.node_id;
921
     node_type = nd.node_type;
922
     node_clock = nd.node_clock;
923
     node_inputs = inputs;
924
     node_outputs = outputs;
925
     node_locals = locals;
926
     node_gencalls = gen_calls;
927
     node_checks = node_checks;
928
     node_asserts = node_asserts;
929
     node_stmts = node_stmts;
930
     node_dec_stateless = nd.node_dec_stateless;
931
     node_stateless = nd.node_stateless;
932
     node_spec = spec;
933
     node_annot = annot;
934
     node_iscontract = nd.node_iscontract;
935
   }
936

    
937

    
938
let rename_const f_const c =
939
  { c with const_id = f_const c.const_id }
940

    
941
let rename_typedef f_var t =
942
  match t.tydef_desc with
943
  | Tydec_enum tags -> { t with tydef_desc = Tydec_enum (List.map f_var tags) }
944
  | _               -> t
945

    
946
let rename_prog f_node f_var f_const prog =
947
  List.rev (
948
    List.fold_left (fun accu top ->
949
      (match top.top_decl_desc with
950
      | Node nd -> 
951
	 { top with top_decl_desc = Node (rename_node f_node f_var nd) }
952
      | Const c -> 
953
	 { top with top_decl_desc = Const (rename_const f_const c) }
954
      | TypeDef tdef ->
955
	 { top with top_decl_desc = TypeDef (rename_typedef f_var tdef) }
956
      | ImportedNode _
957
        | Include _ | Open _       -> top)
958
      ::accu
959
) [] prog
960
		   )
961

    
962
(* Applies the renaming function [fvar] to every rhs
963
   only when the corresponding lhs satisfies predicate [pvar] *)
964
 let eq_replace_rhs_var pvar fvar eq =
965
   let pvar l = List.exists pvar l in
966
   let rec replace lhs rhs =
967
     { rhs with expr_desc =
968
     match lhs with
969
     | []  -> assert false
970
     | [_] -> if pvar lhs then rename_expr_desc (fun x -> x) fvar rhs.expr_desc else rhs.expr_desc
971
     | _   ->
972
       (match rhs.expr_desc with
973
       | Expr_tuple tl ->
974
	 Expr_tuple (List.map2 (fun v e -> replace [v] e) lhs tl)
975
       | Expr_appl (f, arg, None) when Basic_library.is_expr_internal_fun rhs ->
976
	 let args = expr_list_of_expr arg in
977
	 Expr_appl (f, expr_of_expr_list arg.expr_loc (List.map (replace lhs) args), None)
978
       | Expr_array _
979
       | Expr_access _
980
       | Expr_power _
981
       | Expr_const _
982
       | Expr_ident _
983
       | Expr_appl _   ->
984
	 if pvar lhs
985
	 then rename_expr_desc (fun x -> x) fvar rhs.expr_desc
986
	 else rhs.expr_desc
987
       | Expr_ite (c, t, e)   -> Expr_ite (replace lhs c, replace lhs t, replace lhs e)
988
       | Expr_arrow (e1, e2)  -> Expr_arrow (replace lhs e1, replace lhs e2) 
989
       | Expr_fby (e1, e2)    -> Expr_fby (replace lhs e1, replace lhs e2)
990
       | Expr_pre e'          -> Expr_pre (replace lhs e')
991
       | Expr_when (e', i, l) -> let i' = if pvar lhs then fvar i else i
992
				 in Expr_when (replace lhs e', i', l)
993
       | Expr_merge (i, hl)   -> let i' = if pvar lhs then fvar i else i
994
				 in Expr_merge (i', List.map (fun (t, h) -> (t, replace lhs h)) hl)
995
       )
996
     }
997
   in { eq with eq_rhs = replace eq.eq_lhs eq.eq_rhs }
998

    
999
    
1000
(**********************************************************************)
1001
(* Pretty printers *)
1002

    
1003
let pp_decl_type fmt tdecl =
1004
  match tdecl.top_decl_desc with
1005
  | Node nd ->
1006
    fprintf fmt "%s: " nd.node_id;
1007
    Utils.reset_names ();
1008
    fprintf fmt "%a@ " Types.print_ty nd.node_type
1009
  | ImportedNode ind ->
1010
    fprintf fmt "%s: " ind.nodei_id;
1011
    Utils.reset_names ();
1012
    fprintf fmt "%a@ " Types.print_ty ind.nodei_type
1013
  | Const _ | Include _ | Open _ | TypeDef _ -> ()
1014

    
1015
let pp_prog_type fmt tdecl_list =
1016
  Utils.fprintf_list ~sep:"" pp_decl_type fmt tdecl_list
1017

    
1018
let pp_decl_clock fmt cdecl =
1019
  match cdecl.top_decl_desc with
1020
  | Node nd ->
1021
    fprintf fmt "%s: " nd.node_id;
1022
    Utils.reset_names ();
1023
    fprintf fmt "%a@ " Clocks.print_ck nd.node_clock
1024
  | ImportedNode ind ->
1025
    fprintf fmt "%s: " ind.nodei_id;
1026
    Utils.reset_names ();
1027
    fprintf fmt "%a@ " Clocks.print_ck ind.nodei_clock
1028
  | Const _ | Include _ | Open _ | TypeDef _ -> ()
1029

    
1030
let pp_prog_clock fmt prog =
1031
  Utils.fprintf_list ~sep:"" pp_decl_clock fmt prog
1032

    
1033

    
1034
(* filling node table with internal functions *)
1035
let vdecls_of_typ_ck cpt ty =
1036
  let loc = Location.dummy_loc in
1037
  List.map
1038
    (fun _ -> incr cpt;
1039
              let name = sprintf "_var_%d" !cpt in
1040
              mkvar_decl loc (name, mktyp loc Tydec_any, mkclock loc Ckdec_any, false, None, None))
1041
    (Types.type_list_of_type ty)
1042

    
1043
let mk_internal_node id =
1044
  let spec = None in
1045
  let ty = Env.lookup_value Basic_library.type_env id in
1046
  let ck = Env.lookup_value Basic_library.clock_env id in
1047
  let (tin, tout) = Types.split_arrow ty in
1048
  (*eprintf "internal fun %s: %d -> %d@." id (List.length (Types.type_list_of_type tin)) (List.length (Types.type_list_of_type tout));*)
1049
  let cpt = ref (-1) in
1050
  mktop
1051
    (ImportedNode
1052
       {nodei_id = id;
1053
	nodei_type = ty;
1054
	nodei_clock = ck;
1055
	nodei_inputs = vdecls_of_typ_ck cpt tin;
1056
	nodei_outputs = vdecls_of_typ_ck cpt tout;
1057
	nodei_stateless = Types.get_static_value ty <> None;
1058
	nodei_spec = spec;
1059
	(* nodei_annot = []; *)
1060
	nodei_prototype = None;
1061
       	nodei_in_lib = [];
1062
       })
1063

    
1064
let add_internal_funs () =
1065
  List.iter
1066
    (fun id -> let nd = mk_internal_node id in Hashtbl.add node_table id nd)
1067
    Basic_library.internal_funs
1068

    
1069

    
1070

    
1071
(* Replace any occurence of a var in vars_to_replace by its associated
1072
   expression in defs until e does not contain any such variables *)
1073
let rec substitute_expr vars_to_replace defs e =
1074
  let se = substitute_expr vars_to_replace defs in
1075
  { e with expr_desc = 
1076
      let ed = e.expr_desc in
1077
      match ed with
1078
      | Expr_const _ -> ed
1079
      | Expr_array el -> Expr_array (List.map se el)
1080
      | Expr_access (e1, d) -> Expr_access (se e1, d)
1081
      | Expr_power (e1, d) -> Expr_power (se e1, d)
1082
      | Expr_tuple el -> Expr_tuple (List.map se el)
1083
      | Expr_ite (c, t, e) -> Expr_ite (se c, se t, se e)
1084
      | Expr_arrow (e1, e2)-> Expr_arrow (se e1, se e2) 
1085
      | Expr_fby (e1, e2) -> Expr_fby (se e1, se e2)
1086
      | Expr_pre e' -> Expr_pre (se e')
1087
      | Expr_when (e', i, l)-> Expr_when (se e', i, l)
1088
      | Expr_merge (i, hl) -> Expr_merge (i, List.map (fun (t, h) -> (t, se h)) hl)
1089
      | Expr_appl (i, e', i') -> Expr_appl (i, se e', i')
1090
      | Expr_ident i -> 
1091
	if List.exists (fun v -> v.var_id = i) vars_to_replace then (
1092
	  let eq_i eq = eq.eq_lhs = [i] in
1093
	  if List.exists eq_i defs then
1094
	    let sub = List.find eq_i defs in
1095
	    let sub' = se sub.eq_rhs in
1096
	    sub'.expr_desc
1097
	  else 
1098
	    assert false
1099
	)
1100
	else
1101
	  ed
1102

    
1103
  }
1104
  
1105
 let rec expr_to_eexpr  expr =
1106
   { eexpr_tag = expr.expr_tag;
1107
     eexpr_qfexpr = expr;
1108
     eexpr_quantifiers = [];
1109
     eexpr_name = None;
1110
     eexpr_type = expr.expr_type;
1111
     eexpr_clock = expr.expr_clock;
1112
     eexpr_loc = expr.expr_loc;
1113
     (*eexpr_normalized = None*)
1114
   }
1115
 (* and expr_desc_to_eexpr_desc expr_desc = *)
1116
 (*   let conv = expr_to_eexpr in *)
1117
 (*   match expr_desc with *)
1118
 (*   | Expr_const c -> EExpr_const (match c with *)
1119
 (*     | Const_int x -> EConst_int x  *)
1120
 (*     | Const_real x -> EConst_real x  *)
1121
 (*     | Const_float x -> EConst_float x  *)
1122
 (*     | Const_tag x -> EConst_tag x  *)
1123
 (*     | _ -> assert false *)
1124

    
1125
 (*   ) *)
1126
 (*   | Expr_ident i -> EExpr_ident i *)
1127
 (*   | Expr_tuple el -> EExpr_tuple (List.map conv el) *)
1128

    
1129
 (*   | Expr_arrow (e1, e2)-> EExpr_arrow (conv e1, conv e2)  *)
1130
 (*   | Expr_fby (e1, e2) -> EExpr_fby (conv e1, conv e2) *)
1131
 (*   | Expr_pre e' -> EExpr_pre (conv e') *)
1132
 (*   | Expr_appl (i, e', i') ->  *)
1133
 (*     EExpr_appl  *)
1134
 (*       (i, conv e', match i' with None -> None | Some(id, _) -> Some id) *)
1135

    
1136
 (*   | Expr_when _ *)
1137
 (*   | Expr_merge _ -> assert false *)
1138
 (*   | Expr_array _  *)
1139
 (*   | Expr_access _  *)
1140
 (*   | Expr_power _  -> assert false *)
1141
 (*   | Expr_ite (c, t, e) -> assert false  *)
1142
 (*   | _ -> assert false *)
1143
      
1144
     
1145
let rec get_expr_calls nodes e =
1146
  let get_calls = get_expr_calls nodes in
1147
  match e.expr_desc with
1148
  | Expr_const _ 
1149
   | Expr_ident _ -> Utils.ISet.empty
1150
   | Expr_tuple el
1151
   | Expr_array el -> List.fold_left (fun accu e -> Utils.ISet.union accu (get_calls e)) Utils.ISet.empty el
1152
   | Expr_pre e1 
1153
   | Expr_when (e1, _, _) 
1154
   | Expr_access (e1, _) 
1155
   | Expr_power (e1, _) -> get_calls e1
1156
   | Expr_ite (c, t, e) -> Utils.ISet.union (Utils.ISet.union (get_calls c) (get_calls t)) (get_calls e) 
1157
   | Expr_arrow (e1, e2) 
1158
   | Expr_fby (e1, e2) -> Utils.ISet.union (get_calls e1) (get_calls e2)
1159
   | Expr_merge (_, hl) -> List.fold_left (fun accu (_, h) -> Utils.ISet.union accu (get_calls h)) Utils.ISet.empty  hl
1160
   | Expr_appl (i, e', i') -> 
1161
     if Basic_library.is_expr_internal_fun e then 
1162
       (get_calls e') 
1163
     else
1164
       let calls =  Utils.ISet.add i (get_calls e') in
1165
       let test = (fun n -> match n.top_decl_desc with Node nd -> nd.node_id = i | _ -> false) in
1166
       if List.exists test nodes then
1167
	 match (List.find test nodes).top_decl_desc with
1168
	 | Node nd -> Utils.ISet.union (get_node_calls nodes nd) calls
1169
	 | _ -> assert false
1170
       else 
1171
	 calls
1172

    
1173
and get_eq_calls nodes eq =
1174
  get_expr_calls nodes eq.eq_rhs
1175
and get_aut_handler_calls nodes h =
1176
  List.fold_left (fun accu stmt -> match stmt with
1177
  | Eq eq -> Utils.ISet.union (get_eq_calls nodes eq) accu
1178
  | Aut aut' ->  Utils.ISet.union (get_aut_calls nodes aut') accu
1179
  ) Utils.ISet.empty h.hand_stmts 
1180
and get_aut_calls nodes aut =
1181
  List.fold_left (fun accu h -> Utils.ISet.union (get_aut_handler_calls nodes h) accu)
1182
    Utils.ISet.empty aut.aut_handlers
1183
and get_node_calls nodes node =
1184
  let eqs, auts = get_node_eqs node in
1185
  let aut_calls =
1186
    List.fold_left
1187
      (fun accu aut -> Utils.ISet.union (get_aut_calls nodes aut) accu)
1188
      Utils.ISet.empty auts
1189
  in
1190
  List.fold_left
1191
    (fun accu eq -> Utils.ISet.union (get_eq_calls nodes eq) accu)
1192
    aut_calls eqs
1193

    
1194
let get_expr_vars e =
1195
  let rec get_expr_vars vars e =
1196
    get_expr_desc_vars vars e.expr_desc
1197
  and get_expr_desc_vars vars expr_desc =
1198
    (*Format.eprintf "get_expr_desc_vars expr=%a@." Printers.pp_expr (mkexpr Location.dummy_loc expr_desc);*)
1199
  match expr_desc with
1200
  | Expr_const _ -> vars
1201
  | Expr_ident x -> Utils.ISet.add x vars
1202
  | Expr_tuple el
1203
  | Expr_array el -> List.fold_left get_expr_vars vars el
1204
  | Expr_pre e1 -> get_expr_vars vars e1
1205
  | Expr_when (e1, c, _) -> get_expr_vars (Utils.ISet.add c vars) e1 
1206
  | Expr_access (e1, d) 
1207
  | Expr_power (e1, d)   -> List.fold_left get_expr_vars vars [e1; expr_of_dimension d]
1208
  | Expr_ite (c, t, e) -> List.fold_left get_expr_vars vars [c; t; e]
1209
  | Expr_arrow (e1, e2) 
1210
  | Expr_fby (e1, e2) -> List.fold_left get_expr_vars vars [e1; e2]
1211
  | Expr_merge (c, hl) -> List.fold_left (fun vars (_, h) -> get_expr_vars vars h) (Utils.ISet.add c vars) hl
1212
  | Expr_appl (_, arg, None)   -> get_expr_vars vars arg
1213
  | Expr_appl (_, arg, Some r) -> List.fold_left get_expr_vars vars [arg; r]
1214
  in
1215
  get_expr_vars Utils.ISet.empty e 
1216

    
1217
let rec expr_has_arrows e =
1218
  expr_desc_has_arrows e.expr_desc
1219
and expr_desc_has_arrows expr_desc =
1220
  match expr_desc with
1221
  | Expr_const _ 
1222
  | Expr_ident _ -> false
1223
  | Expr_tuple el
1224
  | Expr_array el -> List.exists expr_has_arrows el
1225
  | Expr_pre e1 
1226
  | Expr_when (e1, _, _) 
1227
  | Expr_access (e1, _) 
1228
  | Expr_power (e1, _) -> expr_has_arrows e1
1229
  | Expr_ite (c, t, e) -> List.exists expr_has_arrows [c; t; e]
1230
  | Expr_arrow (e1, e2) 
1231
  | Expr_fby (e1, e2) -> true
1232
  | Expr_merge (_, hl) -> List.exists (fun (_, h) -> expr_has_arrows h) hl
1233
  | Expr_appl (i, e', i') -> expr_has_arrows e'
1234

    
1235
and eq_has_arrows eq =
1236
  expr_has_arrows eq.eq_rhs
1237
and aut_has_arrows aut = List.exists (fun h -> List.exists (fun stmt -> match stmt with Eq eq -> eq_has_arrows eq | Aut aut' -> aut_has_arrows aut') h.hand_stmts ) aut.aut_handlers 
1238
and node_has_arrows node =
1239
  let eqs, auts = get_node_eqs node in
1240
  List.exists (fun eq -> eq_has_arrows eq) eqs || List.exists (fun aut -> aut_has_arrows aut) auts
1241

    
1242

    
1243

    
1244

    
1245

    
1246
let rec expr_contains_expr expr_tag expr  =
1247
  let search = expr_contains_expr expr_tag in
1248
  expr.expr_tag = expr_tag ||
1249
      (
1250
	match expr.expr_desc with
1251
	| Expr_const _ -> false
1252
	| Expr_array el -> List.exists search el
1253
	| Expr_access (e1, _) 
1254
	| Expr_power (e1, _) -> search e1
1255
	| Expr_tuple el -> List.exists search el
1256
	| Expr_ite (c, t, e) -> List.exists search [c;t;e]
1257
	| Expr_arrow (e1, e2)
1258
	| Expr_fby (e1, e2) -> List.exists search [e1; e2]
1259
	| Expr_pre e' 
1260
	| Expr_when (e', _, _) -> search e'
1261
	| Expr_merge (_, hl) -> List.exists (fun (_, h) -> search h) hl
1262
	| Expr_appl (_, e', None) -> search e' 
1263
	| Expr_appl (_, e', Some e'') -> List.exists search [e'; e''] 
1264
	| Expr_ident _ -> false
1265
      )
1266

    
1267

    
1268

    
1269
(* Generate a new local [node] variable *)
1270
let cpt_fresh = ref 0
1271

    
1272
let reset_cpt_fresh () =
1273
    cpt_fresh := 0
1274
    
1275
let mk_fresh_var (parentid, ctx_env) loc ty ck =
1276
  let rec aux () =
1277
  incr cpt_fresh;
1278
  let s = Printf.sprintf "__%s_%d" parentid !cpt_fresh in
1279
  if List.exists (fun v -> v.var_id = s) ctx_env then aux () else
1280
  {
1281
    var_id = s;
1282
    var_orig = false;
1283
    var_dec_type = dummy_type_dec;
1284
    var_dec_clock = dummy_clock_dec;
1285
    var_dec_const = false;
1286
    var_dec_value = None;
1287
    var_parent_nodeid = Some parentid;
1288
    var_type = ty;
1289
    var_clock = ck;
1290
    var_loc = loc
1291
  }
1292
  in aux ()
1293

    
1294

    
1295
let find_eq xl eqs =
1296
  let rec aux accu eqs =
1297
    match eqs with
1298
	| [] ->
1299
	  begin
1300
	    Format.eprintf "Looking for variables %a in the following equations@.%a@."
1301
	      (Utils.fprintf_list ~sep:" , " (fun fmt v -> Format.fprintf fmt "%s" v)) xl
1302
	      Printers.pp_node_eqs eqs;
1303
	    assert false
1304
	  end
1305
	| hd::tl ->
1306
	  if List.exists (fun x -> List.mem x hd.eq_lhs) xl then hd, accu@tl else aux (hd::accu) tl
1307
    in
1308
    aux [] eqs
1309

    
1310
       
1311
let get_node name prog =
1312
  let node_opt = List.fold_left
1313
    (fun res top -> 
1314
      match res, top.top_decl_desc with
1315
      | Some _, _ -> res
1316
      | None, Node nd -> 
1317
	(* Format.eprintf "Checking node %s = %s: %b@." nd.node_id name (nd.node_id = name); *)
1318
	if nd.node_id = name then Some nd else res
1319
      | _ -> None) 
1320
    None prog 
1321
  in
1322
  try 
1323
    Utils.desome node_opt
1324
  with Utils.DeSome -> raise Not_found
1325

    
1326
(* Pushing negations in expression. Subtitute operators whenever possible *)
1327
let rec push_negations ?(neg=false) e =
1328
  let res =
1329
    let pn = push_negations in
1330
    let map desc = mkexpr e.expr_loc desc in
1331
    match e.expr_desc with
1332
    | Expr_ite (g,t,e) ->
1333
       if neg then
1334
         map (Expr_ite(pn g, pn e, pn t))
1335
       else
1336
         map (Expr_ite(pn g, pn t, pn e)) 
1337
    | Expr_tuple t ->
1338
       map (Expr_tuple (List.map (pn ~neg) t))
1339
    | Expr_arrow (e1, e2) ->
1340
       map (Expr_arrow (pn ~neg e1, pn ~neg e2)) 
1341
    | Expr_fby (e1, e2) ->
1342
       map (Expr_fby (pn ~neg e1, pn ~neg e2))
1343
    | Expr_pre e ->
1344
       map (Expr_pre (pn ~neg e))
1345
    | Expr_appl (op, e', None) when op = "not" ->
1346
       if neg then
1347
         push_negations ~neg:false e'
1348
       else
1349
         push_negations ~neg:true e'
1350
    | Expr_appl (op, e', None) when List.mem op (Basic_library.bool_funs @ Basic_library.rel_funs) -> (
1351
      match op with
1352
      | "&&" -> map (Expr_appl((if neg then "||" else op), pn ~neg e', None))
1353
      | "||" -> map (Expr_appl((if neg then "&&" else op), pn ~neg e', None))
1354
      (* TODO xor/equi/impl *)
1355
      | "<" -> map (Expr_appl((if neg then ">=" else op), pn e', None))
1356
      | ">" -> map (Expr_appl((if neg then "<=" else op), pn e', None))
1357
      | "<=" -> map (Expr_appl((if neg then ">" else op), pn e', None))
1358
      | ">=" -> map (Expr_appl((if neg then "<" else op), pn e', None))
1359
      | "!=" -> map (Expr_appl((if neg then "=" else op), pn e', None))
1360
      | "=" -> map (Expr_appl((if neg then "!=" else op), pn e', None))
1361
             
1362
      | _ -> assert false                     
1363
    )
1364
    | Expr_const c -> if neg then map (Expr_const (const_negation c)) else e
1365
    | Expr_ident _ -> 
1366
       if neg then
1367
                         mkpredef_call e.expr_loc "not" [e]
1368
                       else
1369
                         e
1370
    | Expr_appl (op,_,_) -> 
1371
       if neg then
1372
         mkpredef_call e.expr_loc "not" [e]
1373
       else
1374
         e
1375
    | _ -> assert false (* no array, array access, power or merge/when *)
1376
  in
1377
  res
1378

    
1379
let rec add_pre_expr vars e =
1380
  let ap = add_pre_expr vars in
1381
  let desc =
1382
    match e.expr_desc with
1383
    | Expr_ite (g,t,e) ->
1384
       Expr_ite (ap g, ap t,ap e)
1385
    | Expr_tuple t ->
1386
       Expr_tuple (List.map ap t)
1387
    | Expr_arrow (e1, e2) ->
1388
       Expr_arrow (ap e1, ap e2) 
1389
    | Expr_fby (e1, e2) ->
1390
       Expr_fby (ap e1, ap e2)
1391
    | Expr_pre e ->
1392
       Expr_pre (ap e)
1393
    | Expr_appl (op, e, opt) ->
1394
       Expr_appl (op, ap e, opt)
1395
    | Expr_const _ -> e.expr_desc 
1396
    | Expr_ident id ->
1397
       if List.mem id vars then
1398
         Expr_pre e
1399
       else
1400
         e.expr_desc
1401
    | _ -> assert false (* no array, array access, power or merge/when yet *)
1402
  in
1403
  mkexpr e.expr_loc desc
1404

    
1405

    
1406
        
1407
let mk_eq l e1 e2 =
1408
  mkpredef_call l "=" [e1; e2]
1409

    
1410

    
1411
let rec partial_eval e =
1412
  let pa = partial_eval in
1413
  let edesc =
1414
    match e.expr_desc with
1415
    | Expr_const _ -> e.expr_desc 
1416
    | Expr_ident id -> e.expr_desc
1417
    | Expr_ite (g,t,e) -> (
1418
       let g, t, e = pa g, pa t, pa e in
1419
       match g.expr_desc with
1420
       | Expr_const (Const_tag tag) when (tag = tag_true) -> t.expr_desc
1421
       | Expr_const (Const_tag tag) when (tag = tag_false) -> e.expr_desc
1422
       | _ -> Expr_ite (g, t, e)
1423
    )
1424
    | Expr_tuple t ->
1425
       Expr_tuple (List.map pa t)
1426
    | Expr_arrow (e1, e2) ->
1427
       Expr_arrow (pa e1, pa e2) 
1428
    | Expr_fby (e1, e2) ->
1429
       Expr_fby (pa e1, pa e2)
1430
    | Expr_pre e ->
1431
       Expr_pre (pa e)
1432
    | Expr_appl (op, args, opt) ->
1433
       let args = pa args in
1434
       if Basic_library.is_expr_internal_fun e then
1435
         Basic_library.partial_eval op args opt
1436
       else
1437
         Expr_appl (op, pa e, opt)
1438
    | Expr_array el ->
1439
       Expr_array (List.map pa el)
1440
    | Expr_access (e, d) ->
1441
       Expr_access (pa e, d)
1442
    | Expr_power (e, d) ->
1443
       Expr_power (pa e, d)
1444
    | Expr_when (e, id, l) ->
1445
       Expr_when (pa e, id, l)
1446
    | Expr_merge (id, gl) -> 
1447
       Expr_merge(id, List.map (fun (l, e) -> l, pa e) gl)
1448
  in
1449
  { e with expr_desc = edesc }
1450

    
1451
    (* Local Variables: *)
1452
    (* compile-command:"make -C .." *)
1453
    (* End: *)