timedAutomaton.ml 46.9 KB
Newer Older
mcolange's avatar
mcolange committed
1
open Common
2
open Printf
mcolange's avatar
mcolange committed
3
open Dbm
mcolange's avatar
mcolange committed
4 5 6 7
open Uta

module type TIMED_AUTOMATON =
sig
mcolange's avatar
mcolange committed
8
  module MDbm : BIG_IDBM
9

mcolange's avatar
mcolange committed
10 11
  type timed_automaton
  type discrete_state
12
  type edge
mcolange's avatar
mcolange committed
13

14 15
  module DS : Hashtbl.HashedType with type t = discrete_state

16
  val clocks : timed_automaton -> VarContext.t
17
  val priority_compare : discrete_state -> discrete_state -> int
mcolange's avatar
mcolange committed
18
  val initial_extended_state : timed_automaton -> discrete_state * MDbm.Dbm.t
19 20
  val transitions_from : timed_automaton -> discrete_state ->
    (discrete_state * UDbm.Dbm.t * ((clock_t * int) list) * discrete_state) list
21
  val invariant_of_discrete_state : timed_automaton -> discrete_state -> UDbm.Dbm.t
mcolange's avatar
mcolange committed
22 23
  val is_urgent_or_committed : timed_automaton -> discrete_state -> bool
  val is_target : timed_automaton -> discrete_state -> bool
Maximilien Colange's avatar
Maximilien Colange committed
24
  val rate_of_state : timed_automaton -> discrete_state -> int
mcolange's avatar
mcolange committed
25
  val lu_bounds : timed_automaton -> discrete_state -> Udbml.Carray.t * Udbml.Carray.t
26
  val m_bounds : timed_automaton -> discrete_state -> Udbml.Carray.t
mcolange's avatar
mcolange committed
27
  val global_m_bounds : timed_automaton -> int array
mcolange's avatar
mcolange committed
28
  (** print functions *)
29 30 31
  val print_discrete_state  : out_channel -> timed_automaton -> discrete_state -> unit
  val print_timed_automaton : out_channel -> timed_automaton -> unit
  val print_extended_state : out_channel -> timed_automaton -> (discrete_state * MDbm.Dbm.t) -> unit
32 33
  val transition_to_string : timed_automaton ->
    (discrete_state * UDbm.Dbm.t * ((clock_t * int) list) * discrete_state) -> string
mcolange's avatar
mcolange committed
34
  val from_file : string -> string -> ?scale:int -> ?enlarge:int -> unit -> timed_automaton
mcolange's avatar
mcolange committed
35 36
end

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
module MBoundedAutomaton (TA : TIMED_AUTOMATON) =
struct
  include TA

  let bounding_transitions ta state=
    let n = VarContext.size (TA.clocks ta) in
    let m = TA.global_m_bounds ta in
    let rec build_list cl accu =
      if (cl = n) then accu
      else
        let guard = Dbm.UDbm.Dbm.create n in
        Dbm.UDbm.Dbm.set_init guard;
        Dbm.UDbm.Dbm.constrain guard (0, cl, (-m.(cl)-2, Udbml.Basic_types.DBM_WEAK));
        Dbm.UDbm.Dbm.constrain guard (cl, 0, (m.(cl)+2, Udbml.Basic_types.DBM_WEAK));
        assert(not(Dbm.UDbm.Dbm.is_empty guard));
        build_list (cl+1) ((state, guard, [(cl, m.(cl)+1)], state)::accu)
    in 
    build_list 1 []

  let transitions_from ta state =
    List.rev_append (TA.transitions_from ta state) (bounding_transitions ta state)

  let invariant_of_discrete_state ta state =
    let inv = TA.invariant_of_discrete_state ta state in
    let n = VarContext.size (TA.clocks ta) in
    let m = TA.global_m_bounds ta in
    for cl = 0 to n-1 do
      Dbm.UDbm.Dbm.constrain inv (cl, 0, (m.(cl) + 2, Udbml.Basic_types.DBM_WEAK))
    done;
    assert(not(Dbm.UDbm.Dbm.is_empty inv));
    inv
    
end

mcolange's avatar
mcolange committed
71 72 73 74 75 76 77 78
module type TIMED_GAME = 
sig
  include TIMED_AUTOMATON
  
  (* I am not convinced it is the better interface *)
  val is_controllable : timed_automaton -> edge -> bool
end

mcolange's avatar
mcolange committed
79
module GenericUAutomaton (BDbm : BIG_IDBM) =
mcolange's avatar
mcolange committed
80
struct
mcolange's avatar
mcolange committed
81
  module MDbm = BDbm
mcolange's avatar
mcolange committed
82
  module Dbm = BDbm.Dbm
83

84
  include Querybuilder
mcolange's avatar
mcolange committed
85

86 87
  (** Expression factory functions, to be registered as callbacks from C *)
  let cb_expression_constant i = Constant i
88

89 90 91
  let cb_expression_array varcont constcont clockcont tmp name sons =
    if ScopeVarContext.arraymem varcont (tmp, name) then
      let arrayid = ScopeVarContext.index_of_array varcont (tmp, name) in
92
      Array(arrayid, sons)
93 94
    else if (ScopeVarContext.arraymem varcont (None, name)) then
      let arrayid = ScopeVarContext.index_of_array varcont (None, name) in
95
      Array(arrayid, sons)
96 97
    else if (ScopeVarContext.arraymem constcont (tmp, name)) then
      let arrayid = ScopeVarContext.index_of_array constcont (tmp, name) in
98 99 100 101
      ConstArray(arrayid, sons)
    else if (ScopeVarContext.arraymem constcont (None, name)) then
      let arrayid = ScopeVarContext.index_of_array constcont (None, name) in
      ConstArray(arrayid, sons)
102 103 104 105 106 107
    else if (ScopeVarContext.arraymem clockcont (tmp, name)) then
      let arrayid = ScopeVarContext.index_of_array clockcont (tmp, name) in
      ClockArray(arrayid, sons)
    else if (ScopeVarContext.arraymem clockcont (None, name)) then
      let arrayid = ScopeVarContext.index_of_array clockcont (None, name) in
      ClockArray(arrayid, sons)
108 109
    else
      failwith (sprintf "Undefined array <%s>" name)
110
  
111
  let cb_expression_variable constcont const_values varcont tmp name =
112
    (* is it a local constant? *)
113 114
    if (ScopeVarContext.mem constcont (tmp, name)) then
      let varid = ScopeVarContext.index_of_var constcont (tmp, name) in
115 116
      Constant(Hashtbl.find const_values varid)
    (* is it a global constant? *)
117 118
    else if (ScopeVarContext.mem constcont (None, name)) then
      let varid = ScopeVarContext.index_of_var constcont (None, name) in
119 120
      Constant(Hashtbl.find const_values varid)
    (* is it a local variable? *)
121 122
    else if (ScopeVarContext.mem varcont (tmp, name)) then
      let varid = ScopeVarContext.index_of_var varcont (tmp, name) in
123 124
      Variable(varid)
    (* is it a global variable? *)
125 126
    else if (ScopeVarContext.mem varcont (None, name)) then
      let varid = ScopeVarContext.index_of_var varcont (None, name) in
127
      Variable(varid)
128
    else
129 130
      failwith (sprintf "Undefined variable <%s>" name)

131
  let cb_expression_clock clockcont tmp name =
132
    (* is it a local clock? *)
133 134
    if (ScopeVarContext.mem clockcont (tmp, name) ) then
      let varid = ScopeVarContext.index_of_var clockcont (tmp,name) in
135 136
      Clock(varid)
    (* is it a global clock? *)
137 138
    else if (ScopeVarContext.mem clockcont (None, name) ) then
      let varid = ScopeVarContext.index_of_var clockcont (None,name) in
139
      Clock(varid)
140
    else
141 142 143 144 145 146 147
      failwith (sprintf "Undefined clock <%s>" name)

  let cb_expression_sum a b = Sum (a,b)
  let cb_expression_product a b = Product (a,b)
  let cb_expression_substraction a b = Substraction (a,b)
  let cb_expression_division a b = Division (a,b)

mcolange's avatar
mcolange committed
148 149 150
  (** A guard is a conjunction of atomic guards *)
  type guard = atomic_guard list

151
  (** clocks and variables updates *)
152 153 154 155 156
  type lvalue =
      ClockRef of clock_t
    | ClockArrayRef of int * expression list 
    | VarRef of int 
    | ArrayRef of int * expression list
157
  type update = lvalue * expression
mcolange's avatar
mcolange committed
158

159 160 161 162
  type chanref =
      ChanId of int
    | ChanArray of int * expression list

163
  (* Channels are assumed to be global, so are handled by VarContext *)
164 165 166 167
  let cb_channel_simple chancont chanName =
    let aid = VarContext.index_of_var chancont chanName in
    ChanId(aid)

168
  let cb_channel_array chancont arrayName indices =
169 170
    let aid = VarContext.index_of_array chancont arrayName in
    ChanArray(aid, indices)
171

172
  type simplechan = 
173 174
      SendChan of chanref
    | RecvChan of chanref
175 176
  

mcolange's avatar
mcolange committed
177 178 179 180
  type edge = {
    edgeSource : int;
    edgeGuard : guard;
    edgeDiscGuard : guard;
181
    edgeUpdates : update list;
mcolange's avatar
mcolange committed
182
    edgeTarget : int;
183
    edgeSync : simplechan option;
184
    edgeProc : int; (* proc id *)
185 186
    edgeControllable : bool;
    edgeCost : Costs.edge_cost; (* the cost of this edge [default is 0] *)
mcolange's avatar
mcolange committed
187 188 189 190 191 192 193 194
  }
  and location = {
    locId : int;
    mutable locName : string;
    locCommitted : bool;
    locUrgent : bool;
    locInvar : guard;
    locEdges : edge list;
195
    locProc : int; (* proc id *)
196 197 198
    locRate : Costs.loc_rate;
      (* the cost rate of time elapsing in this location [default is None] *)
      (* the cost rate of an array of location is the sum of their cost rates *)
mcolange's avatar
mcolange committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  }
  and process = {
    procName : string;
    procId : int;
    procLocations : location array;
    procInitLoc : int;
  }
  type discrete_state = {
    stateLocs : location array;
    stateVars : int array;
  }

  type transition = InternalTrans of discrete_state * edge
                  | SyncTrans of discrete_state * edge * edge

214

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  let hash_discrete_state s =
    let tmp = Array.fold_right
      (fun x r -> r + x.locId + 0x9e3779b9 + (r lsl 6) + (r lsr 2))
      s.stateLocs 0
    in Array.fold_right
      (fun x r -> r + x + 0x9e3779b9 + (r lsl 6) + (r lsr 2))
      s.stateVars tmp

  let is_state_equal s t =
    let rec aux_loc a b n =
      if (n < 0) then true else
      if (a.(n).locId = b.(n).locId) then
        if (n > 0) then
          aux_loc a b (n-1)
        else true
      else false
    in
    let rec aux_var a b n =
      if (n < 0) then true else
      if (a.(n) = b.(n)) then
        if (n > 0) then
          aux_var a b (n-1)
        else true
      else false
    in
    (aux_loc s.stateLocs t.stateLocs (Array.length s.stateLocs - 1))
    &&
    (aux_var s.stateVars t.stateVars (Array.length s.stateVars - 1))

  module DS = struct
    type t = discrete_state
    let equal = is_state_equal
    let hash = hash_discrete_state
  end

  module DSHashtbl = Hashtbl.Make(DS)

252 253 254 255
  (* s1 < s2 iff s1.prio > s2.prio *)
  let priority_compare s1 s2 = 
    - compare s1.stateVars.(0) s2.stateVars.(0)

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
  (** A succinct version of the above to be used in hash tables *)
  type _succinct_transition = int array * guard

  module GuardHashtbl = Hashtbl.Make(
    struct
      type t = _succinct_transition

      let equal x y = x = y

      let hash (a,b) =
        Array.fold_right
          (fun x r -> r + x + 0x9e3779b9 + (r lsl 6) + (r lsr 2))
          a (Hashtbl.hash b)
    end
  )
mcolange's avatar
mcolange committed
271 272

  type timed_automaton = { 
273
    procs : process array; (* forall i: procs.(i).procId = i *)
274 275 276
    clocks : VarContext.t;
    vars : VarContext.t;
    constants : VarContext.t;
277
    constvalues : int array;
278
    channels : VarContext.t;
mcolange's avatar
mcolange committed
279
    init : discrete_state;
280
    query : query;
281 282
    lubounds_tbl : (int array * int array) DSHashtbl.t;
    lubounds_tbl_c : (Udbml.Carray.t * Udbml.Carray.t) DSHashtbl.t;
283
    mbounds_tbl_c : Udbml.Carray.t DSHashtbl.t;
284
    guards_tbl : UDbm.Dbm.t GuardHashtbl.t;
285
    invars_tbl : UDbm.Dbm.t DSHashtbl.t;
mcolange's avatar
mcolange committed
286
    global_mbounds : int array;
mcolange's avatar
mcolange committed
287 288 289 290 291 292 293 294
  }
  

  (********** PRINTING AUXILIARY FUNCTIONS **********)
  let rec string_of_exp ta e = 
    let string_of_exp = string_of_exp ta in
    (function
      | Constant c -> sprintf "%d" c 
295
      | Array(aid, indices) -> 
296 297 298
          List.fold_left (fun s x -> s ^ (string_of_exp x)) (VarContext.array_of_index ta.vars aid) indices
      | ConstArray(aid, indices) ->
          List.fold_left (fun s x -> s ^ (string_of_exp x)) (VarContext.array_of_index ta.constants aid) indices
mcolange's avatar
mcolange committed
299
      | Variable(id) -> VarContext.var_of_index ta.vars id
300
      | ConstVariable(id) -> VarContext.var_of_index ta.constants id
mcolange's avatar
mcolange committed
301
      | Clock(id) ->  VarContext.var_of_index ta.clocks id
302 303
      | ClockArray(aid,indices) ->
          let arrayName = VarContext.array_of_index ta.clocks aid in
304
          List.fold_left (fun s x -> s ^ "[" ^ (string_of_exp x) ^ "]") arrayName indices
mcolange's avatar
mcolange committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
      | Product(e1,e2) ->
        sprintf "%s * %s" (string_of_exp e1)
          (string_of_exp e2)
      | Sum(e1,e2) ->
        sprintf "(%s + %s)" (string_of_exp e1)
          (string_of_exp e2)
      | Division(e1,e2) ->
        sprintf "%s / %s" (string_of_exp e1)
          (string_of_exp e2)
      | Substraction(e1,e2) ->
        sprintf "(%s - %s)" (string_of_exp e1)
          (string_of_exp e2)
    ) e


  let string_of_atomic_guard ta = 
    let string_of_exp = string_of_exp ta in
    function
    |  GuardLeq(v,exp) ->
      sprintf "%s <= %s" (string_of_exp v)(string_of_exp exp)
    | GuardLess(v,exp) ->
      sprintf "%s < %s" (string_of_exp v)(string_of_exp exp)
    | GuardGeq(v,exp)->
      sprintf "%s >= %s" (string_of_exp v)(string_of_exp exp)
    | GuardGreater(v,exp)->
      sprintf "%s > %s" (string_of_exp v) (string_of_exp exp)
    | GuardEqual(v,exp)->
      sprintf "%s == %s" (string_of_exp v) (string_of_exp exp)
333 334
    | GuardNeq(v,exp)->
      sprintf "%s != %s" (string_of_exp v) (string_of_exp exp)
mcolange's avatar
mcolange committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349


  let xml_string_of_atomic_guard ta = 
    let string_of_exp = string_of_exp ta in       
    function
    |  GuardLeq(v,exp) ->
      sprintf "%s &lt;= %s" (string_of_exp v)(string_of_exp exp)
    | GuardLess(v,exp) ->
      sprintf "%s &lt; %s" (string_of_exp v)(string_of_exp exp)
    | GuardGeq(v,exp)->
      sprintf "%s &gt;= %s" (string_of_exp v)(string_of_exp exp)
    | GuardGreater(v,exp)->
      sprintf "%s &gt; %s" (string_of_exp v) (string_of_exp exp)
    | GuardEqual(v,exp)->
      sprintf "%s == %s" (string_of_exp v) (string_of_exp exp)
350 351
    | GuardNeq(v,exp)->
      sprintf "%s != %s" (string_of_exp v) (string_of_exp exp)
mcolange's avatar
mcolange committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373


  let rec string_of_guard ta = 
    function
    | [] -> ""
    | [x] -> string_of_atomic_guard ta x
    | x :: y :: l -> 
      ((string_of_atomic_guard ta x) ^ " && ")
      ^ (string_of_guard ta (y::l))


  let rec xml_string_of_guard ta =
    function
    | [] -> ""
    | [x] -> xml_string_of_atomic_guard ta x
    | x :: y :: l -> 
      ((xml_string_of_atomic_guard ta x) ^ " &amp;&amp; ")
      ^ (xml_string_of_guard ta (y::l))


  let string_of_updates ta ups = 
    let ups_str = 
374 375 376 377 378 379
      List.map (fun (var,exp) -> 
        let lhsname = match var with
          | ClockRef(c) -> VarContext.var_of_index ta.clocks c
          | VarRef(v) -> VarContext.var_of_index ta.vars v
        in
        sprintf "%s = %s" lhsname (string_of_exp ta exp)) ups in
mcolange's avatar
mcolange committed
380 381 382 383 384 385 386 387 388 389
    String.concat ", " ups_str

    
  let string_of_state ta state =
    let out = Buffer.create 50 in 
    Array.iter (fun loc -> Buffer.add_string out loc.locName;
                 Buffer.add_string out " ") state.stateLocs;
    if (Array.length state.stateVars > 0 ) then (
      Buffer.add_string out "\n";
      Array.iteri (fun i v ->
390
          let name = VarContext.var_of_index ta.vars i in
mcolange's avatar
mcolange committed
391 392 393 394 395 396 397
          Buffer.add_string out (sprintf "%s = %d, " name v)) state.stateVars;
    );
    (*    Buffer.add_string out "\n";*)
    Buffer.contents out

    
  let string_of_edge ta edge = 
398
    let proc = ta.procs.(edge.edgeProc) in
399 400 401 402 403
    let print_chanref = function
      | ChanId(c) -> string_of_int c
      | ChanArray(aid,indices) ->
          List.fold_left (fun s x -> sprintf "%s[%s]" s (string_of_exp ta x)) (string_of_int aid) indices
    in
mcolange's avatar
mcolange committed
404 405
    let sync = match edge.edgeSync with 
      |None -> ""
406 407
      |Some(SendChan(c)) -> (print_chanref c)^"!"
      |Some(RecvChan(c)) -> (print_chanref c)^"?"
mcolange's avatar
mcolange committed
408 409 410
    in
    let discguardstr = string_of_guard ta edge.edgeDiscGuard in
    let guardstr = string_of_guard ta edge.edgeGuard in
411
    sprintf "%s%s -> %s \tDiscGuard: %s \tGuard: %s \tUpdates:%s \tSync:%s" 
mcolange's avatar
mcolange committed
412 413 414 415 416
      (if (edge.edgeControllable) then "" else "[E]")
      (proc.procLocations.(edge.edgeSource).locName)
      (proc.procLocations.(edge.edgeTarget).locName)
      discguardstr
      guardstr
417
      (string_of_updates ta edge.edgeUpdates)
mcolange's avatar
mcolange committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
      sync

  
  let string_of_location ta loc =
    let out = Buffer.create 128 in
    let utter = Buffer.add_string out in
    utter (sprintf "Location %d: %s "loc.locId loc.locName);
    if (loc.locCommitted) then
      utter "committed ";
    utter (string_of_guard ta loc.locInvar);
    utter "\n";
    utter (sprintf "Has %d edges:\n" (List.length loc.locEdges));
    let edgestrlist = (List.map (string_of_edge ta) loc.locEdges) in
    utter (String.concat "\n" edgestrlist);
    utter "\n";
    Buffer.contents out


  let string_of_process ta proc = 
    let out = Buffer.create 1000 in
    let utter = Buffer.add_string out in
    utter (sprintf "Process(%d): %s\n"  proc.procId proc.procName);
    Array.iter (fun loc -> utter (string_of_location ta loc)) proc.procLocations;
    utter (sprintf "Initial location id: %d\n" proc.procInitLoc);
    Buffer.contents out


  let string_of_transition ta tr =
    let buf = Buffer.create 128 in
    let out = Buffer.add_string buf in
448
    let proc_name e = ta.procs.(e.edgeProc).procName in
mcolange's avatar
mcolange committed
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    match tr with 
      InternalTrans(state,e) ->
      out (sprintf "From global state: %s\n" (string_of_state ta state));
      out (string_of_edge ta e);
      Buffer.contents buf
    | SyncTrans(state,e1,e2) ->
      out (sprintf "Synchronized Transition btw Processes: %s - %s\n Source: %s\n" (proc_name e1) (proc_name e2)
             (string_of_state ta state));
      out "Sync:\n";
      out (string_of_edge ta e1);
      out "\n";
      out (string_of_edge ta e2);
      Buffer.contents buf


  (********** OTHER AUXILIARY FUNCTIONS **********)
    
Maximilien Colange's avatar
Maximilien Colange committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
  (* evaluate expression *)
  (* output is either Constant(_) or Clock(_)
   *)
  let rec eval_exp ta vars = function
    | Constant c -> Constant c
    | ConstVariable(id) ->
        if ( id < 0 || id >= Array.length ta.constvalues ) then
          failwith (sprintf "Const var index %d out of bounds (%d)" id (Array.length ta.constvalues));
        Constant ta.constvalues.(id)
    | Variable(id) -> 
        if ( id < 0 || id >= Array.length vars ) then
          failwith (sprintf "Var index %d out of bounds (%d)" id (Array.length vars));
        Constant vars.(id)
    | Clock(c) -> Clock(c)
    | ClockArray(arrayId, l) ->
        let indices = List.map (fun x -> eval_disc_exp ta vars x) l in
        let cellindex = VarContext.index_of_cell ta.clocks arrayId indices in
        Clock(cellindex)
    | Array(arrayId, l) -> 
        let indices = List.map (fun x -> eval_disc_exp ta vars x) l in
        let cellindex = VarContext.index_of_cell ta.vars arrayId indices in
        eval_exp ta vars (Variable cellindex)
    | ConstArray(arrayId, l) ->
        let indices = List.map (fun x -> eval_disc_exp ta vars x) l in
        let cellIndex = VarContext.index_of_cell ta.constants arrayId indices in
        eval_exp ta vars (ConstVariable cellIndex)
    | Product(e1,e2) -> Constant ((eval_disc_exp ta vars e1) * (eval_disc_exp ta vars e2))
    | Sum(e1,e2) -> Constant ((eval_disc_exp ta vars e1) + (eval_disc_exp ta vars e2))
    | Division(e1,e2) -> Constant ((eval_disc_exp ta vars e1) / (eval_disc_exp ta vars e2))
    | Substraction(e1,e2) -> Constant ((eval_disc_exp ta vars e1) - (eval_disc_exp ta vars e2))
  (* same as above, but fails if it encounters a clock *)
  and eval_disc_exp ta vars exp =
    match (eval_exp ta vars exp) with
      | Constant c -> c
      | _ -> failwith ("Unevaluable discrete expression" ^ (string_of_exp ta exp))
mcolange's avatar
mcolange committed
501 502
       
  let source_location_of_edge ta edge =
503
    ta.procs.(edge.edgeProc).procLocations.(edge.edgeSource)
mcolange's avatar
mcolange committed
504

Maximilien Colange's avatar
Maximilien Colange committed
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
  (* evaluate the discrete part of a guard
   * the result contains only clocks and constants (no clock array, no expression)
   *)
  let eval_ag ta state ag =
    let eval = eval_exp ta state.stateVars in
    match ag with
      | GuardLeq(a,b) -> GuardLeq(eval a, eval b)
      | GuardLess(a,b) -> GuardLess(eval a, eval b)
      | GuardEqual(a,b) -> GuardEqual(eval a, eval b)
      | GuardNeq(a,b) -> GuardNeq(eval a, eval b)
      | GuardGeq(a,b) -> GuardGeq(eval a, eval b)
      | GuardGreater(a,b) -> GuardGreater(eval a, eval b)

  (* completely evaluate a discrete guard to true or false.
   * fails if it encounters a clock *)
  let eval_disc_guard ta state =
    List.for_all (fun x ->
      match eval_ag ta state x with
        | GuardLeq(Constant(a),Constant(b)) -> a <= b
        | GuardLess(Constant(a),Constant(b)) -> a < b
        | GuardEqual(Constant(a),Constant(b)) -> a = b
        | GuardNeq(Constant(a),Constant(b)) -> a <> b
        | GuardGeq(Constant(a),Constant(b)) -> a >= b
        | GuardGreater(Constant(a),Constant(b)) -> a > b
        | _ -> failwith "Unevaluable discrete guard")
    
  (* Assumes the input guard has only Clock(_) comp Constant(_)
   * [i.e. no ClockArray and no other expression than Constant]
   *)
mcolange's avatar
mcolange committed
534 535
  let _guard_to_dbm ta state g =
    let nclocks = VarContext.size ta.clocks in
536 537
    let dbm = UDbm.Dbm.create nclocks in
    UDbm.Dbm.set_init dbm;
mcolange's avatar
mcolange committed
538
    let aux = function
Maximilien Colange's avatar
Maximilien Colange committed
539
      | GuardLeq(Clock(c), Constant(k)) ->
540
          UDbm.Dbm.constrain dbm (c, 0, (k, Udbml.Basic_types.DBM_WEAK))
Maximilien Colange's avatar
Maximilien Colange committed
541
      | GuardLess(Clock(c), Constant(k)) ->
542
        UDbm.Dbm.constrain dbm (c, 0, (k, Udbml.Basic_types.DBM_STRICT))
Maximilien Colange's avatar
Maximilien Colange committed
543
      | GuardGeq(Clock(c), Constant(k)) ->
544
        UDbm.Dbm.constrain dbm (0, c, (-k, Udbml.Basic_types.DBM_WEAK))
Maximilien Colange's avatar
Maximilien Colange committed
545
      | GuardGreater(Clock(c), Constant(k)) ->
546
        UDbm.Dbm.constrain dbm (0, c, (-k, Udbml.Basic_types.DBM_STRICT))
Maximilien Colange's avatar
Maximilien Colange committed
547
      | GuardEqual(Clock(c), Constant(k)) ->
548 549
        UDbm.Dbm.constrain dbm (0, c, (-k, Udbml.Basic_types.DBM_WEAK));
        UDbm.Dbm.constrain dbm (c, 0, (k, Udbml.Basic_types.DBM_WEAK))
mcolange's avatar
mcolange committed
550 551 552 553 554 555 556
      | _ as e -> failwith (sprintf "Bad Guard: %s" (string_of_guard ta [e]))
    in
    List.iter aux g;
    dbm


  let is_committed state =
557 558 559 560 561 562
    let rec aux ar n =
      if (ar.(n).locCommitted) then true
      else if (n > 0) then
        aux ar (n-1)
      else false
    in aux state.stateLocs (Array.length state.stateLocs - 1)
mcolange's avatar
mcolange committed
563 564 565 566 567 568

  
  let _copy_state state = 
    { stateVars = Array.copy state.stateVars;
      stateLocs = Array.copy state.stateLocs}

569 570
  (** Apply discrete update of edge to state, result written in state'
   *  Along the way, instantiate clock updates and return them *)
mcolange's avatar
mcolange committed
571
  let _apply_edge ta state edge state' =
572
    let result = ref [] in
573
    state'.stateLocs.(edge.edgeProc) <- ta.procs.(edge.edgeProc).procLocations.(edge.edgeTarget);
574 575 576
    List.iter (fun (lhs,e) ->
      match lhs with
        | VarRef(id) -> state'.stateVars.(id) <- eval_disc_exp ta state'.stateVars e
577 578 579
        | ClockRef(id) -> result := !result @ [(id, eval_disc_exp ta state'.stateVars e)]
        | ArrayRef(id,ilist) ->
            let indices = List.map (fun x -> eval_disc_exp ta state'.stateVars x) ilist in
580
            let cellId = VarContext.index_of_cell ta.vars id indices in
581 582 583 584 585
            state'.stateVars.(cellId) <- eval_disc_exp ta state'.stateVars e
        | ClockArrayRef(id,ilist) ->
            let indices = List.map (fun x -> eval_disc_exp ta state'.stateVars x) ilist in
            let cellId = VarContext.index_of_cell ta.clocks id indices in
            result := !result @ [(cellId, eval_disc_exp ta state'.stateVars e)])
586 587
    edge.edgeUpdates;
    !result
mcolange's avatar
mcolange committed
588 589 590 591 592 593 594 595 596


  (********** TIMED_AUTOMATON interface **********)
  let clocks ta = ta.clocks

  let initial_discrete_state ta = ta.init

  let invariant_of_discrete_state ta state =
    try
597
      DSHashtbl.find ta.invars_tbl state
mcolange's avatar
mcolange committed
598 599
    with Not_found ->
      let glob_inv =
Maximilien Colange's avatar
Maximilien Colange committed
600
        Array.fold_left (fun acc loc -> (List.map (eval_ag ta state) loc.locInvar) @ acc ) [] state.stateLocs in
mcolange's avatar
mcolange committed
601
      let inv = _guard_to_dbm ta state.stateVars glob_inv in
602
      DSHashtbl.add ta.invars_tbl state inv;
mcolange's avatar
mcolange committed
603 604 605
      inv
       | _ as e -> raise e

Maximilien Colange's avatar
Maximilien Colange committed
606
  let rate_of_state ta state =
607
    Costs.get_rate (Array.map (fun loc -> loc.locRate) state.stateLocs) (eval_disc_exp ta state.stateVars)
Maximilien Colange's avatar
Maximilien Colange committed
608

mcolange's avatar
mcolange committed
609 610 611
  let initial_extended_state ta =
    let dim = (VarContext.size (clocks ta)) in
    let z = Dbm.create dim in
612 613
    Dbm.set_zero z;
    (ta.init, z)
614 615 616 617 618
   
  let eval_chan ta state = function
    | ChanId(c) -> ChanId(c)
    | ChanArray(arrayId, l) ->
      let indices = List.map (fun x -> eval_disc_exp ta state.stateVars x) l in
619
      let cellindex = VarContext.index_of_cell ta.channels arrayId indices in
620 621
      ChanId (cellindex)

622
  let _transitions_from ta state = 
mcolange's avatar
mcolange committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636
    let committed = is_committed state in
    let transq = Queue.create () in
    (* Queue of synchronizing edges *)
    let rchan = Queue.create () in
    let schan = Queue.create () in
    let nproc = Array.length ta.procs in
    for i = 0 to nproc - 1 do
      let loc = state.stateLocs.(i) in
      let add_single = not committed || loc.locCommitted in
      List.iter
        (fun edge ->
          if (eval_disc_guard ta state edge.edgeDiscGuard) then
            (match edge.edgeSync with
              | Some (SendChan(c)) ->
637
                  Queue.add (eval_chan ta state c, edge) schan
mcolange's avatar
mcolange committed
638
              | Some (RecvChan(c)) ->
639
                  Queue.add (eval_chan ta state c, edge) rchan
mcolange's avatar
mcolange committed
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
              | None ->
                  if (add_single) then
                    Queue.add (InternalTrans (state, edge)) transq
            )
        ) loc.locEdges
    done;
    Queue.iter
      (fun (rname, redge) ->
        Queue.iter
          (fun (sname, sedge) ->
            (* Sync if same channels are used by different processes *)
            if (rname = sname && redge.edgeProc <> sedge.edgeProc) then (
              (* and if state not committed or one of the participating states is *)
              let sloc = source_location_of_edge ta sedge in
              let rloc = source_location_of_edge ta redge in
              if (not committed || sloc.locCommitted || rloc.locCommitted) then
                Queue.add (SyncTrans (state, redge, sedge)) transq
            )
          ) schan
      ) rchan;
    Queue.fold (fun l tr -> tr :: l) [] transq

662 663
  let guard_of_transition ta tr = 
    let to_succinct = function
Maximilien Colange's avatar
Maximilien Colange committed
664 665
      |InternalTrans(s,e) -> (s.stateVars,List.map (eval_ag ta s) e.edgeGuard)
      |SyncTrans(s,e1,e2) -> (s.stateVars,List.map (eval_ag ta s) (e1.edgeGuard @ e2.edgeGuard))
666 667 668 669 670 671 672 673 674 675
    in
    let (vars,succ_guard) as str = to_succinct tr in
    try 
      GuardHashtbl.find ta.guards_tbl str
    with Not_found ->
      let g = _guard_to_dbm ta vars succ_guard in
      GuardHashtbl.add ta.guards_tbl str g;
      g
      | _ as e -> raise e

Maximilien Colange's avatar
Maximilien Colange committed
676
  let _transition_fields ta = function
mcolange's avatar
mcolange committed
677 678
    | InternalTrans(state, e) ->
        let state' = _copy_state state in
679
        let resets = _apply_edge ta state e state' in
mcolange's avatar
mcolange committed
680
        (state,
Maximilien Colange's avatar
Maximilien Colange committed
681
         List.map (eval_ag ta state) e.edgeGuard,
682
         resets,
mcolange's avatar
mcolange committed
683 684 685
         state')
    | SyncTrans(state, e1, e2) ->
        let state' = _copy_state state in
686 687
        let resets1 = _apply_edge ta state e1 state' in
        let resets2 = _apply_edge ta state e2 state' in
Maximilien Colange's avatar
Maximilien Colange committed
688 689 690 691 692
        (state, List.map (eval_ag ta state) (e1.edgeGuard @ e2.edgeGuard), resets1 @ resets2, state')
  
  let transition_fields ta tr = 
    let (s,g,r,s') = _transition_fields ta tr in
    (s,_guard_to_dbm ta s.stateVars g,r,s')
mcolange's avatar
mcolange committed
693

694 695 696
  let transitions_from ta state =
    List.map (fun tr -> transition_fields ta tr) (_transitions_from ta state)

697 698 699 700 701 702 703 704 705 706
  let transition_to_string ta (source, dbm, ulist, target) =
    let res = List.find
      (fun trans ->
        let (_, d, u, t) = transition_fields ta trans in
        is_state_equal target t && ulist = u && UDbm.Dbm.equal dbm d)
      (_transitions_from ta source)
    in
    string_of_transition ta res


mcolange's avatar
mcolange committed
707
  let is_urgent_or_committed ta state =
708 709 710 711 712 713
    let rec aux ar n =
      if (ar.(n).locCommitted || ar.(n).locUrgent) then true
      else if (n > 0) then
        aux ar (n-1)
      else false
    in aux state.stateLocs (Array.length state.stateLocs - 1)
mcolange's avatar
mcolange committed
714 715

  let is_target ta state =
716 717 718 719 720 721
    let rec eval_query = function
      | EmptyQuery -> true
      | QueryAnd(l,r) -> (eval_query l) && (eval_query r)
      | QueryOr(l,r) -> (eval_query l) || (eval_query r)
      | Location(procId,locId) -> state.stateLocs.(procId).locId = locId
      | Atomic(ag) -> eval_disc_guard ta state [ag]
mcolange's avatar
mcolange committed
722
    in
723
    eval_query ta.query
mcolange's avatar
mcolange committed
724

mcolange's avatar
mcolange committed
725 726
  let lu_bounds ta state =
    try
727
      DSHashtbl.find ta.lubounds_tbl_c state
mcolange's avatar
mcolange committed
728 729
    with Not_found ->
      let nclocks = VarContext.size ta.clocks in
730 731 732 733
      let lower,upper = DSHashtbl.find ta.lubounds_tbl state in
      let lar,uar = (Udbml.Carray.to_c lower nclocks, Udbml.Carray.to_c upper nclocks) in
      DSHashtbl.add ta.lubounds_tbl_c state (lar,uar);
      (lar,uar)
mcolange's avatar
mcolange committed
734

735 736 737 738 739 740 741 742 743 744 745 746 747 748
  let m_bounds ta state =
    try
      DSHashtbl.find ta.mbounds_tbl_c state
    with Not_found ->
      let nclocks = VarContext.size ta.clocks in
      let lower,upper = DSHashtbl.find ta.lubounds_tbl state in
      let mbound = Array.make nclocks 0 in
      for cl = 0 to nclocks-1 do
        mbound.(cl) <- max lower.(cl) upper.(cl)
      done;
      let res = Udbml.Carray.to_c mbound nclocks in
      DSHashtbl.add ta.mbounds_tbl_c state res;
      res

mcolange's avatar
mcolange committed
749
  let global_m_bounds ta =
mcolange's avatar
mcolange committed
750 751 752
    if (ta.global_mbounds.(0) <> 0) then (
      let nclocks = VarContext.size (clocks ta) in
      ta.global_mbounds.(0) <- 0;
753 754 755 756 757 758 759 760
      DSHashtbl.iter (fun _ -> fun (lbound,ubound) ->
        for cl = 0 to nclocks-1 do
          ta.global_mbounds.(cl) <- max ta.global_mbounds.(cl) lbound.(cl);
          ta.global_mbounds.(cl) <- max ta.global_mbounds.(cl) ubound.(cl)
        done) ta.lubounds_tbl;
      Array.iteri (fun cl m ->
        if (m < 0) then
          printf "clock %d (of bound %d) is never read!?\n" cl m) ta.global_mbounds
mcolange's avatar
mcolange committed
761 762
    );
    ta.global_mbounds
mcolange's avatar
mcolange committed
763 764 765 766 767 768 769

  let global_m_invariant ta =
    let marray = global_m_bounds ta in
    let inv_guard = ref [] in
    for i = 0 to (Array.length marray)-1 do
      inv_guard := (GuardLeq (Clock i, Constant marray.(i))) :: !inv_guard
    done;
Maximilien Colange's avatar
Maximilien Colange committed
770
    (* no need to call eval_ag, the guard has only Clock and Constant *)
mcolange's avatar
mcolange committed
771 772
    _guard_to_dbm ta ta.init.stateVars !inv_guard
    
mcolange's avatar
mcolange committed
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
  (** print functions *)
  let print_discrete_state chan ta state =
    fprintf chan "%s\n" (string_of_state ta state)
  
  let print_transition chan ta trans = 
    fprintf chan "%s\n" (string_of_transition ta trans)

  let print_timed_automaton chan ta =
    fprintf chan "Timed automaton with %d clocks and %d processes\n"
      (VarContext.size ta.clocks) (Array.length ta.procs);
    Array.iter (fun proc -> fprintf chan "%s\n-----\n" (string_of_process ta proc)) ta.procs
 
  let print_extended_state chan ta (state,dbm) =
    fprintf chan "%s " (string_of_state ta state);
    fprintf chan "%s " (Dbm.to_string dbm)

  (********** LOADING FUNCTIONS **********)
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
  (* propagate the clocks given in input, and return a set of clocks still
   * worth to propagate
   *)
  let propagate lparent uparent lson uson updates clocks =
    let res = ref ClockSet.empty in
    (* for every element of clocks, check whether to propagate *)
    ClockSet.iter (fun cl ->
      (* a clock does not propagate past an update *)
      if (List.for_all (fun (i,_) -> i <> cl) updates) then
        begin
          (* a clock is worth propagating later on if it propagates here *)
          if (lparent.(cl) < lson.(cl)) then (
            lparent.(cl) <- lson.(cl);
            res := ClockSet.add cl !res
          );
          if (uparent.(cl) < uson.(cl)) then (
            uparent.(cl) <- uson.(cl);
            res := ClockSet.add cl !res
          )
        end) clocks;
    !res

  exception Early_stop

  (** To compute LU (and M) bounds, we first explore the whole discrete
   *  state space.
   *  At each discrete state s, each clock c is given the largest constant
   *  against which it is compared in s.
   *  Then, larger bounds propagate backwards, but not CROSS resets.
   *  The best way to do this (with the retropropagation) is a DFS of the
   *  discrete state space
   *)
  (* TODO by adapting the walk order, the M bounds could be computed on the fly,
   *      while the real state space is being discovered
   *)
  let build_lu ta =
mcolange's avatar
mcolange committed
826
    let nclocks = VarContext.size ta.clocks in
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
    let trace = Stack.create () in
    (* trace is a stack of discrete_state * (transition list) *)
    (* to get a list of transitions from a discrete state, use _transitions_from *)
    let init = initial_discrete_state ta in
    let init_edges = _transitions_from ta init in
    Stack.push (init, init_edges) trace;
    let ltmp, utmp = Array.make nclocks (-Dbm.infty), Array.make nclocks (-Dbm.infty) in
    DSHashtbl.add ta.lubounds_tbl init (ltmp,utmp);
    while (not (Stack.is_empty trace)) do
      let (current, edges) = Stack.top trace in
      match edges with
        | [] -> begin
            (* pop the stack *)
            let _ = Stack.pop trace in
            (* we are done with this state, retropropagation *)
            let son = ref current in
            let clocks = ref ClockSet.empty in
            for cl = 1 to nclocks-1 do clocks := ClockSet.add cl !clocks done;
            (* Do the bound retropropagation *)
            begin
            try
              Stack.iter (fun (parent, edge :: _) ->
                if (ClockSet.is_empty !clocks) then
                  raise Early_stop;
                let lson,uson = DSHashtbl.find ta.lubounds_tbl !son in
                let lparent,uparent = DSHashtbl.find ta.lubounds_tbl parent in
                let (_,_,updates,_) = _transition_fields ta edge in
                clocks := propagate lparent uparent lson uson updates !clocks;
                son := parent
              ) trace;
            with
              | Early_stop -> ()
            end;
            (* get the parent state, its first edge is the one between parent and current *)
            if (not (Stack.is_empty trace)) then (
              let (parent, _::l) = Stack.pop trace in
              (* repush the parent and its remaining edges *)
              Stack.push (parent, l) trace;
            )
        end
        | edge :: rest -> begin
          let (_,guard,updates,succ) = _transition_fields ta edge in
          let (current_lower,current_upper) = DSHashtbl.find ta.lubounds_tbl current in
870
          (* evaluate accesses to clock arrays, if any *)
Maximilien Colange's avatar
Maximilien Colange committed
871
          (* TODO refactor: the guard should already be evaluated by _transition_fields *)
872 873 874 875 876 877 878 879 880 881 882 883 884
          let evalClock = fun (ClockArray(i,ilist)) ->
            let indices = List.map (fun e -> eval_disc_exp ta current.stateVars e) ilist in
            let cid = VarContext.index_of_cell ta.clocks i indices in
            Clock(cid)
          in
          let guard_eval = List.map (function
            | GuardLeq(ClockArray(_,_) as ca,rhs) -> GuardLeq(evalClock ca,rhs)
            | GuardLess(ClockArray(_,_) as ca,rhs) -> GuardLess(evalClock ca,rhs)
            | GuardEqual(ClockArray(_,_) as ca,rhs) -> GuardEqual(evalClock ca,rhs)
            | GuardGeq(ClockArray(_,_) as ca,rhs) -> GuardGeq(evalClock ca,rhs)
            | GuardGreater(ClockArray(_,_) as ca,rhs) -> GuardGeq(evalClock ca,rhs)
            | _ as x -> x) guard
          in
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
          (* update the bounds of current thanks to current transition *)
          List.iter (function
            | GuardLeq(Clock(cl),e)
            | GuardLess(Clock(cl),e) ->
                let r = eval_disc_exp ta current.stateVars e in
                current_upper.(cl) <- max current_upper.(cl) r
            | GuardEqual(Clock(cl),e) ->
                let r = eval_disc_exp ta current.stateVars e in
                current_upper.(cl) <- max current_upper.(cl) r;
                current_lower.(cl) <- max current_lower.(cl) r
            | GuardGeq(Clock(cl),e)
            | GuardGreater(Clock(cl),e) ->
                let r = eval_disc_exp ta current.stateVars e in
                current_lower.(cl) <- max current_lower.(cl) r
            | _ -> failwith "cannot compute LU bounds, guard not in normal form")
900
          guard_eval;
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917

          (* now take care of the succ *)
          if (DSHashtbl.mem ta.lubounds_tbl succ) then
            (* if already discovered, push it on the stack with an empty list of
             * edges in order to have the correct retropropagation *)
            begin
              Stack.push (succ, []) trace
            end
          else
            (* if new, add it to the hashtable and push it on the stack *)
            begin
              let ltmp, utmp = Array.make nclocks (-Dbm.infty), Array.make nclocks (-Dbm.infty) in
              DSHashtbl.add ta.lubounds_tbl succ (ltmp,utmp);
              let succ_edges = _transitions_from ta succ in
              Stack.push (succ, succ_edges) trace
            end
        end
918 919 920 921 922 923
    done;
    DSHashtbl.iter (fun _ -> fun (lbound,ubound) ->
      for cl=0 to nclocks-1 do
        if (lbound.(cl) < 0) then lbound.(cl) <- 0;
        if (ubound.(cl) < 0) then ubound.(cl) <- 0
      done) ta.lubounds_tbl
924 925

  (** Constructs a timed_automaton from the C data structure produced by the
926 927 928 929 930 931 932 933 934
   *  library utap.
   *  TODO compared to previous version, this lacks:
     *  parameterization by guard_of_transition
     *  parameterization by invariant_of_discrete_state
     *  scaling
     *  enlarging
   *  This hinders the ability to instantiate to other kinds of automata,
   *  such as enlarged automata
   *)
935
  external utap_from_file : string -> string -> timed_automaton = "xta_from_xmlfile";;
936

937
  let build_ta_from_processes channels clockcont varcont var_init_values constcont constvalues procs =
938 939 940 941 942 943 944
    (* Fill in the edgeProc and locProc fields in all locations and edges *)
    Array.iter (fun proc -> 
        Array.iter (fun loc -> 
            loc.locName <- proc.procName ^ "." ^ loc.locName;
          ) proc.procLocations
      )
      procs;
945 946 947 948 949 950
    let procNames = Array.map (fun p -> p.procName) procs in
    (* Prefix all names with the scope process names *)
    let clocks = ScopeVarContext.to_vc clockcont procNames in
    let vars = ScopeVarContext.to_vc varcont procNames in
    let constants = ScopeVarContext.to_vc constcont procNames in

951 952 953 954 955 956
    (* build the array of const values *)
    let nconst = (Hashtbl.length constvalues) in
    let const_val = Array.make nconst 0 in
    for i = 0 to nconst-1 do
      const_val.(i) <- Hashtbl.find constvalues i;
    done;
957
    let nvars = (Hashtbl.length var_init_values) in
mcolange's avatar
mcolange committed
958
    let initLocs = Array.map (fun proc -> proc.procLocations.(proc.procInitLoc)) procs in
959
    let initVars = Array.make nvars 0 in
mcolange's avatar
mcolange committed
960 961 962
    for i = 0 to nvars-1 do
      initVars.(i) <- Hashtbl.find var_init_values i;
    done;
963 964 965 966 967
    (* Check that the special-meaning variable is at the correct index *)
    if (VarContext.index_of_var vars "preference" <> 0) then begin
      Printf.printf "preference has a wrong index, but this is not supposed to happen\n Aborting...\n";
      exit 1;
    end;
mcolange's avatar
mcolange committed
968 969 970 971
    let ta = {
      procs = procs;
      clocks = clocks;
      vars = vars;
972 973
      constants = constants;
      constvalues = const_val;
974
      channels = channels;
mcolange's avatar
mcolange committed
975
      init = {stateLocs = initLocs; stateVars = initVars};
976
      query = EmptyQuery;
977 978
      lubounds_tbl = DSHashtbl.create 1024;
      lubounds_tbl_c = DSHashtbl.create 1024;
979
      mbounds_tbl_c = DSHashtbl.create 1024;
980
      guards_tbl = GuardHashtbl.create 1024;
981
      invars_tbl = DSHashtbl.create 1024;
mcolange's avatar
mcolange committed
982
      global_mbounds = Array.make (VarContext.size clocks) (-Dbm.infty)
mcolange's avatar
mcolange committed
983
    }
984
    in
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001

    let cb_find_process procName =
      let res = ref (-1) in
      Array.iteri (fun i p -> if p.procName = procName then res := i) ta.procs;
      !res
    in
    Callback.register "cb_get_proc" cb_find_process;
    let cb_find_location procId locName =
      let proc = ta.procs.(procId) in
      let res = ref (-1) in
      Array.iteri (fun i l -> if l.locName = locName then res := i) proc.procLocations;
      !res
    in
    Callback.register "cb_get_loc" cb_find_location;

    Printf.printf "Input automaton parsed, computing LU bounds\n";
    flush stdout;
1002
    build_lu ta;
mcolange's avatar
mcolange committed
1003
    ta
1004
    
1005
  let make_ta tafile qfile =
1006 1007 1008
    (** Variable and clock contexts have initially keys of type (p,name)
     * where p is process option (None for global variables),
     * and name the name of the variable. *)
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    (* Clocks *)
    let clockcont = ScopeVarContext.create () in
    (* Variables, with initial values *)
    let varcont = ScopeVarContext.create () in
    let var_init_values = Hashtbl.create 16 in
    (* Constants, with initial values *)
    let constcont = ScopeVarContext.create () in
    let const_values = Hashtbl.create 16 in

    (* Register C callbacks to build expressions *)
1019 1020
    Callback.register "cb_expression_constant" cb_expression_constant;
    Callback.register "cb_expression_variable"
1021 1022
      (cb_expression_variable constcont const_values varcont);
    Callback.register "cb_expression_clock" (cb_expression_clock clockcont);
1023 1024 1025 1026
    Callback.register "cb_expression_sum" cb_expression_sum;
    Callback.register "cb_expression_product" cb_expression_product;
    Callback.register "cb_expression_substraction" cb_expression_substraction;
    Callback.register "cb_expression_division" cb_expression_division;
1027
    Callback.register "cb_expression_array"
1028
      (cb_expression_array varcont constcont clockcont);
1029

1030 1031 1032
    (* C callbacks for arrays of integers *)
    let cb_reg_array_name procref arrayName =
      ScopeVarContext.add_array varcont (procref, arrayName)
1033
    in
1034 1035 1036
    Callback.register "cb_register_array_name" cb_reg_array_name;
    let cb_reg_array_cell procref arrayName indices value =
      let cellId = ScopeVarContext.add_cell varcont (procref, arrayName) indices
1037
      in
1038
      Hashtbl.add var_init_values cellId value
1039
    in
1040
    Callback.register "cb_register_array_cell" cb_reg_array_cell;
1041

1042 1043 1044
    (* C callbacks for const arrays of integers *)
    let cb_reg_const_array_name procref arrayName =
      ScopeVarContext.add_array constcont (procref, arrayName)
1045
    in
1046 1047 1048
    Callback.register "cb_register_const_array_name" cb_reg_const_array_name;
    let cb_reg_const_array_cell procref arrayName indices value =
      let cellId = ScopeVarContext.add_cell constcont (procref, arrayName) indices
1049
      in
1050
      Hashtbl.add const_values cellId value
1051
    in
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    Callback.register "cb_register_const_array_cell" cb_reg_const_array_cell;

    (* C callbacks for arrays of clocks *)
    let cb_reg_clock_array procref arrayName =
      ScopeVarContext.add_array clockcont (procref, arrayName)
    in
    Callback.register "cb_register_clock_array_name" cb_reg_clock_array;
    let cb_reg_clock_array_cell procref arrayName indices =
      let _ = ScopeVarContext.add_cell clockcont (procref, arrayName) indices in ()
    in
    Callback.register "cb_register_clock_array_cell" cb_reg_clock_array_cell;
      
1064 1065 1066 1067 1068 1069 1070

    (* C callbacks for channels and arrays of channels *)
    (* Due to the very nature of channels, all channels and arrays of channels
     * should be global, which we assume here.
     * Thus, we directly use a VarContext, not a ScopeVarContext.
     *)
    let chans = VarContext.create () in
1071
    Callback.register "cb_channel_simple" (cb_channel_simple chans);
1072
    Callback.register "cb_channel_array" (cb_channel_array chans);
1073 1074
    (* first argument (reference to scope proc) kept for compatibility *)
    let cb_register_channel_array_name _ arrayName =
1075
      VarContext.add_array chans arrayName
1076 1077
    in
    Callback.register "cb_register_channel_array_name" cb_register_channel_array_name;
1078 1079
    let cb_register_channel_array_cell _ arrayName indices =
      let _ = VarContext.add_cell chans arrayName indices in ()
1080 1081 1082
    in
    Callback.register "cb_register_channel_array_cell" cb_register_channel_array_cell;

1083
    (* C callbacks for constants *)
1084
    let cb_register_constant tmp name value =
1085
      let varid = ScopeVarContext.add constcont (tmp, name) in
1086 1087 1088
      Hashtbl.add const_values varid value
    in
    Callback.register "cb_register_constant" cb_register_constant;
1089
    (* C callbacks for variables *)
1090
    let cb_register_variable tmp name value =
1091
      let varid = ScopeVarContext.add varcont (tmp, name) in
1092 1093 1094
      Hashtbl.add var_init_values varid value
    in
    Callback.register "cb_register_variable" cb_register_variable;
1095 1096 1097
    (* C callback for clocks *)
    let cb_register_clock tmp name =
      let _ = ScopeVarContext.add clockcont (tmp, name) in ()
1098 1099
    in
    Callback.register "cb_register_clock" cb_register_clock;
1100 1101 1102 1103 1104 1105
    (* C callbacks for channels *)
    (* first argument (reference to scope proc) kept for compatibility *)
    let cb_register_channel _ name =
      let _ = VarContext.add chans name in ()
    in
    Callback.register "cb_register_channel" cb_register_channel;
1106 1107 1108

    let rec evaluate_expression = function
      | Constant(c) -> c
1109 1110
      | Clock(_) | ClockArray(_,_) -> failwith "there should not be clocks in evaluated expressions"
      | Array(_,_) | ConstArray(_,_) -> failwith "there should not be array accesses in evaluated expressions"
1111
      | Variable(i) -> Hashtbl.find var_init_values i
1112
      | ConstVariable(i) -> Hashtbl.find const_values i
1113 1114 1115 1116 1117 1118 1119 1120 1121
      | Sum(a,b) -> (evaluate_expression a) + (evaluate_expression b)
      | Product(a,b) -> (evaluate_expression a) * (evaluate_expression b)
      | Substraction(a,b) -> (evaluate_expression a) - (evaluate_expression b)
      | Division(a,b) -> (evaluate_expression a) / (evaluate_expression b)
    in
    Callback.register "cb_evaluate_expr" evaluate_expression;
    (** Get discrete guard from mixed guard *)
    let filter_disc_guard g = 
      let rec filt_exp = function
1122
        | Clock(_) | ClockArray(_,_) -> false
1123 1124 1125 1126
        | Sum(x,y) -> (filt_exp x) && (filt_exp y)
        | Product(x,y) -> (filt_exp x) && (filt_exp y)
        | Substraction(x,y) -> (filt_exp x) && (filt_exp y)
        | Division(x,y) -> (filt_exp x) && (filt_exp y)
1127
        | Array(_, l) -> List.for_all (fun x -> filt_exp x) l
1128 1129 1130 1131 1132 1133 1134 1135
        | _ -> true
      in
      let filt_ag = function
        | GuardLess(x,y) -> (filt_exp x) && (filt_exp y)
        | GuardLeq(x,y) -> (filt_exp x) && (filt_exp y)
        | GuardGreater(x,y) -> (filt_exp x) && (filt_exp y)
        | GuardGeq(x,y) -> (filt_exp x) && (filt_exp y)
        | GuardEqual(x,y) -> (filt_exp x) && (filt_exp y)
1136
        | GuardNeq(x,y) -> (filt_exp x) && (filt_exp y)
1137 1138 1139 1140 1141 1142
      in
      List.filter filt_ag g
    in
    (** Get clock guard from mixed guard *)
    let filter_clock_guard g = 
      let rec filt_exp = function
1143
        | Clock(_) | ClockArray(_,_) -> true
1144 1145 1146 1147 1148 1149
        | Sum(x,y) -> (filt_exp x) || (filt_exp y)
        | Product(x,y) -> (filt_exp x) || (filt_exp y)
        | Substraction(x,y) -> (filt_exp x) || (filt_exp y)
        | Division(x,y) -> (filt_exp x) || (filt_exp y)
        | Array(_, l) -> List.exists (fun x -> filt_exp x) l
        | _ -> false
1150 1151
      in
      let filt_ag = function
1152 1153 1154 1155 1156 1157
        | GuardLess(x,y) -> (filt_exp x) || (filt_exp y)
        | GuardLeq(x,y) -> (filt_exp x) || (filt_exp y)
        | GuardGreater(x,y) -> (filt_exp x) || (filt_exp y)
        | GuardGeq(x,y) -> (filt_exp x) || (filt_exp y)
        | GuardEqual(x,y) -> (filt_exp x) || (filt_exp y)
        | GuardNeq(x,y) -> (filt_exp x) || (filt_exp y)
1158 1159 1160
      in
      List.filter filt_ag g
    in
1161 1162
    let cb_send_channel chan =
      Some(SendChan(chan))
1163
    in
1164 1165
    let cb_recv_channel chan =
      Some(RecvChan(chan))
1166 1167 1168 1169 1170 1171 1172 1173
    in
    Callback.register "cb_send_channel" cb_send_channel;
    Callback.register "cb_recv_channel" cb_recv_channel;
    let build_edge src dst extGuard extUpdate sync procId control =
      {
        edgeSource = src;
        edgeGuard = filter_clock_guard extGuard;
        edgeDiscGuard = filter_disc_guard extGuard;
1174 1175
        edgeUpdates = List.rev (List.map (function
          | (Clock(x),e) -> ClockRef(x),e
1176
          | (ClockArray(a,l),e) -> ClockArrayRef(a,l),e
1177
          | (Variable(x),e) -> VarRef(x),e
1178
          | (Array(a,l),e) -> ArrayRef(a,l),e
1179 1180
          | _ -> failwith "incorrect LHS for update")
        extUpdate);
1181 1182 1183 1184
        edgeTarget = dst;
        edgeSync = sync;
        edgeProc = procId;
        edgeControllable = control;
1185 1186
        (* TODO currently set to default *)
        edgeCost = Costs.edge_cost_def; 
1187 1188 1189
      }
    in
    Callback.register "cb_build_edge" build_edge;
1190
    let build_location id name committed urgent guard edges procId costRate =
1191 1192 1193 1194 1195 1196 1197 1198
      {
        locId = id;
        locName = name;
        locCommitted = committed;
        locUrgent = urgent;
        locInvar = guard;
        locEdges = edges;
        locProc = procId;
1199
        locRate = costRate;
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
      }
    in
    Callback.register "cb_build_location" build_location;
    let build_process name id locations init =
      {
        procName = name;
        procId = id;
        procLocations = locations;
        procInitLoc = init;
      }
    in
    Callback.register "cb_build_process" build_process;
1212
    let build_location_array n = Array.make n (build_location 0 "" false false [] [] 0 Costs.loc_rate_def) in
1213 1214 1215
    Callback.register "cb_build_location_array" build_location_array;
    let build_process_array n = Array.make n (build_process "" 0 (build_location_array 0) 0) in
    Callback.register "cb_build_process_array" build_process_array;
1216 1217
    let build_ta procs = build_ta_from_processes
      chans clockcont varcont var_init_values constcont const_values procs in
1218
    Callback.register "cb_build_ta" build_ta;
1219 1220
    let ta_set_query ta newquery = { ta with query = newquery; } in
    Callback.register "cb_set_query" ta_set_query;
1221
    utap_from_file tafile qfile
mcolange's avatar
mcolange committed
1222 1223

  let from_file tafile qfile ?scale:(scale=1) ?enlarge:(enlarge=0) () = 
1224
    let ta = make_ta tafile qfile in
mcolange's avatar
mcolange committed
1225 1226 1227 1228
    ta
  
end