timedAutomaton.ml 41.1 KB
Newer Older
mcolange's avatar
mcolange committed
1
open Common
2
open Batteries.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 12 13
  type timed_automaton
  type discrete_state
  type transition

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

mcolange's avatar
mcolange committed
16
  val clocks : timed_automaton -> string VarContext.t
17
  val is_state_equal : discrete_state -> discrete_state -> bool
mcolange's avatar
mcolange committed
18 19
  val initial_discrete_state : timed_automaton -> discrete_state
  (* does it belong here? If so, so does type for extended_state... *)
mcolange's avatar
mcolange committed
20
  val initial_extended_state : timed_automaton -> discrete_state * MDbm.Dbm.t
21 22
  val transitions_from : timed_automaton -> discrete_state ->
    (discrete_state * UDbm.Dbm.t * ((clock_t * int) list) * discrete_state) list
mcolange's avatar
mcolange committed
23
  val transition_fields : timed_automaton -> transition ->
24
    (discrete_state * UDbm.Dbm.t * ((clock_t * int) list) * discrete_state)
25 26
  val guard_of_transition : timed_automaton -> transition -> UDbm.Dbm.t
  val invariant_of_discrete_state : timed_automaton -> discrete_state -> UDbm.Dbm.t
mcolange's avatar
mcolange committed
27 28
  val is_urgent_or_committed : timed_automaton -> discrete_state -> bool
  val is_target : timed_automaton -> discrete_state -> bool
mcolange's avatar
mcolange committed
29
  val lu_bounds : timed_automaton -> discrete_state -> Udbml.Carray.t * Udbml.Carray.t
mcolange's avatar
mcolange committed
30 31
  val global_m_bounds : timed_automaton -> int array
  val global_m_invariant : timed_automaton -> UDbm.Dbm.t
mcolange's avatar
mcolange committed
32 33 34 35
  (** print functions *)
  val print_discrete_state  : 'b BatIO.output -> timed_automaton -> discrete_state -> unit
  val print_transition : 'b BatIO.output -> timed_automaton -> transition -> unit
  val print_timed_automaton : 'b BatIO.output -> timed_automaton -> unit
mcolange's avatar
mcolange committed
36 37
  val print_extended_state : 'b BatIO.output -> timed_automaton -> (discrete_state * MDbm.Dbm.t) -> unit
  val from_file : string -> string -> ?scale:int -> ?enlarge:int -> unit -> timed_automaton
mcolange's avatar
mcolange committed
38 39
end

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 71 72 73
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
74 75 76 77 78 79 80 81
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
82
module GenericUAutomaton (BDbm : BIG_IDBM) =
mcolange's avatar
mcolange committed
83
struct
mcolange's avatar
mcolange committed
84
  module MDbm = BDbm
mcolange's avatar
mcolange committed
85
  module Dbm = BDbm.Dbm
86

mcolange's avatar
mcolange committed
87 88 89
  (** In contrast with Uta.expression used in the parser, the variables here are indexed
   *  by unique integer identifiers.
   *)
90
  include Querybuilder
mcolange's avatar
mcolange committed
91

92 93
  (** Expression factory functions, to be registered as callbacks from C *)
  let cb_expression_constant i = Constant i
94 95 96 97 98 99 100 101 102 103

  let cb_expression_array arraycont tmp name sons =
    if (VarContext.mem arraycont (Some tmp, name)) then
      let arrayid = VarContext.index_of_var arraycont (Some tmp, name) in
      Array(arrayid, sons)
    else if (VarContext.mem arraycont (None, name)) then
      let arrayid = VarContext.index_of_var arraycont (None, name) in
      Array(arrayid, sons)
    else
      failwith (sprintf "Undefined array <%s>" name)
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
  
  let cb_expression_variable constcont const_values varcont varref ref_variables tmp name =
    (* is it a local constant? *)
    if (VarContext.mem constcont (Some tmp, name)) then
      let varid = VarContext.index_of_var constcont (Some tmp, name) in
      Constant(Hashtbl.find const_values varid)
    (* is it a global constant? *)
    else if (VarContext.mem constcont (None, name)) then
      let varid = VarContext.index_of_var constcont (None, name) in
      Constant(Hashtbl.find const_values varid)
    (* is it a local variable? *)
    else if (VarContext.mem varcont (Some tmp, name)) then
      let varid = VarContext.index_of_var varcont (Some tmp, name) in
      Variable(varid)
    (* is it a global variable? *)
    else if (VarContext.mem varcont (None, name)) then
      let varid = VarContext.index_of_var varcont (None, name) in
      Variable(varid)
    (* is it a reference to a (global) variable (a template parameter)? *)
    else if (VarContext.mem varref (Some tmp, name)) then
      let refid = VarContext.index_of_var varref (Some tmp, name) in
      let refname = Hashtbl.find ref_variables refid in
      let varid = VarContext.index_of_var varcont (None, refname) in
      Variable(varid)
    else (
      eprintf "Printing final VarContext\n";
      VarContext.iter
        (fun (t,name) ind ->
          let scope = match t with
            | None -> "Global"
            | Some tmp -> sprintf "Local to process # %d" tmp
          in
          eprintf "\t%d <%s> : %s\n" ind name scope
        ) varcont;
      printf "%b\n" (VarContext.mem varcont (Some tmp, name));
      failwith (sprintf "Undefined variable <%s>" name)
    )

  let cb_expression_clock clockcont clockref ref_clocks tmp name =
    (* is it a local clock? *)
    if (VarContext.mem clockcont (Some tmp, name) ) then
      let varid = VarContext.index_of_var clockcont (Some tmp,name) in
      Clock(varid)
    (* is it a global clock? *)
    else if (VarContext.mem clockcont (None, name) ) then
      let varid = VarContext.index_of_var clockcont (None,name) in
      Clock(varid)
    (* is it a reference to a (global) clock (a template parameter)? *)
    else if (VarContext.mem clockref (Some tmp, name)) then
      let refid = VarContext.index_of_var clockref (Some tmp, name) in
      let refname = Hashtbl.find ref_clocks refid in
      let varid = VarContext.index_of_var clockcont (None, refname) in
      Clock(varid)
    else (
      eprintf "Printing final VarContext\n";
      VarContext.iter 
        (fun (t,name) ind ->
            let scope = match t with
              | None -> "Global"
              | Some tmp -> sprintf "Local to process # %d" tmp
            in
            eprintf "\t%d <%s> : %s\n" ind  name scope
        ) clockcont;
      printf "%b\n" (VarContext.mem clockcont (Some tmp, name));
      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
176 177 178 179 180 181
  (** A guard is a conjunction of atomic guards *)
  type guard = atomic_guard list

  (** clocks updates *)
  type update = (int * expression) list

182 183 184 185 186
  type simplechan = 
      SendChan of int
    | RecvChan of int
  

mcolange's avatar
mcolange committed
187 188 189 190
  type edge = {
    edgeSource : int;
    edgeGuard : guard;
    edgeDiscGuard : guard;
191
    edgeReset : (clock_t * int) list;
mcolange's avatar
mcolange committed
192 193
    edgeDiscUpdate : update;
    edgeTarget : int;
194
    edgeSync : simplechan option;
195
    edgeProc : int; (* proc id *)
mcolange's avatar
mcolange committed
196 197 198 199 200 201 202 203 204
    edgeControllable : bool
  }
  and location = {
    locId : int;
    mutable locName : string;
    locCommitted : bool;
    locUrgent : bool;
    locInvar : guard;
    locEdges : edge list;
205
    locProc : int; (* proc id *)
mcolange's avatar
mcolange committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
  }
  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

221 222 223 224 225 226

  module LocHashtbl = Hashtbl.Make(
    struct
      type t = location array

      let equal a1 a2 =
227 228 229 230 231 232
        let rec aux a b n =
          if (a.(n).locId = b.(n).locId) then
            if (n > 0) then aux a b (n-1)
            else true
          else false
        in aux a1 a2 (Array.length a1 - 1)
233 234

      let hash a =
mcolange's avatar
mcolange committed
235 236 237
        Array.fold_right
          (fun x r -> r + x.locId + 0x9e3779b9 + (r lsl 6) + (r lsr 2))
          a 0
238 239 240 241

    end
  )

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
  (** 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
257

258
  (* TODO add a VarContext for array names (and pretty printing) *)
mcolange's avatar
mcolange committed
259
  type timed_automaton = { 
260
    procs : process array; (* forall i: procs.(i).procId = i *)
261
    celltoindex : (int * int list, int) Hashtbl.t;
mcolange's avatar
mcolange committed
262 263 264
    clocks : string VarContext.t;
    vars : string VarContext.t;
    init : discrete_state;
265
    query : query;
mcolange's avatar
mcolange committed
266 267
    mutable lowerLU : int array array array;
    mutable upperLU : int array array array;
268
    guards_tbl : UDbm.Dbm.t GuardHashtbl.t;
269
    invars_tbl : UDbm.Dbm.t LocHashtbl.t;
mcolange's avatar
mcolange committed
270
    lubounds_tbl : (Udbml.Carray.t * Udbml.Carray.t) LocHashtbl.t;
mcolange's avatar
mcolange committed
271
    global_mbounds : int array;
mcolange's avatar
mcolange committed
272 273 274 275 276 277 278 279
  }
  

  (********** 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 
280 281
      | Array(aid, indices) -> 
          List.fold_left (fun s x -> sprintf "%s[%s]" s (string_of_exp x)) (string_of_int aid) indices
mcolange's avatar
mcolange committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
      | Variable(id) -> VarContext.var_of_index ta.vars id
      | Clock(id) ->  VarContext.var_of_index ta.clocks id
      | 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)
312 313
    | GuardNeq(v,exp)->
      sprintf "%s != %s" (string_of_exp v) (string_of_exp exp)
mcolange's avatar
mcolange committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328


  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)
329 330
    | GuardNeq(v,exp)->
      sprintf "%s != %s" (string_of_exp v) (string_of_exp exp)
mcolange's avatar
mcolange committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371


  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 = 
      List.map (fun (var,exp) -> sprintf "%s = %s" (VarContext.var_of_index ta.vars var) (string_of_exp ta exp)) ups in
    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 ->
          let name = VarContext.index2var ta.vars i in
          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 = 
372
    let proc = ta.procs.(edge.edgeProc) in
mcolange's avatar
mcolange committed
373 374
    let resetnames = 
      let out = Buffer.create 100 in
375 376 377
      List.iter 
        (fun (cl, _) -> 
           let name = VarContext.index2var ta.clocks cl in
mcolange's avatar
mcolange committed
378 379 380 381 382 383 384
           Buffer.add_string out name; 
           Buffer.add_string out " ") 
        edge.edgeReset;
      Buffer.contents out
    in
    let sync = match edge.edgeSync with 
      |None -> ""
385 386
      |Some(SendChan(c)) -> (string_of_int c)^"!"
      |Some(RecvChan(c)) -> (string_of_int c)^"?"
mcolange's avatar
mcolange committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    in
    let discguardstr = string_of_guard ta edge.edgeDiscGuard in
    let guardstr = string_of_guard ta edge.edgeGuard in
    sprintf "%s%s -> %s \tDiscGuard: %s \tDiscUpdate: %s \tGuard: %s \tResets:%s \tSync:%s" 
      (if (edge.edgeControllable) then "" else "[E]")
      (proc.procLocations.(edge.edgeSource).locName)
      (proc.procLocations.(edge.edgeTarget).locName)
      discguardstr
      (string_of_updates ta edge.edgeDiscUpdate)
      guardstr
      resetnames
      sync
  (*
    sprintf "Edge:\n Target: %s.%s\n\tDiscGuard: %s\n\tDiscUpdate: %s\n\tGuard: %s\n\tResets:%s\n\tSync:%s\n" 
            proc.procName
            (proc.procLocations.(edge.edgeTarget).locName)
            discguardstr
            (string_of_updates ta edge.edgeDiscUpdate)
            guardstr
            resetnames
            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
438
    let proc_name e = ta.procs.(e.edgeProc).procName in
mcolange's avatar
mcolange committed
439 440 441 442 443 444 445 446 447 448 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 **********)
    
  let rec eval_disc_exp ta vars exp =
    try
      let k = 
        (match exp with
         | Constant c -> c
         | Variable(id) -> 
           if ( id < 0 || id >= Array.length vars ) then
             failwith (sprintf "Var index %d out of bounds (%d)" id (Array.length vars));
           vars.(id)
         | Clock(id) ->raise Found
466 467 468 469
         | Array(arrayId, l) -> 
             let indices = List.map (fun x -> eval_disc_exp ta vars x) l in
             let cellindex = Hashtbl.find ta.celltoindex (arrayId, indices) in
             eval_disc_exp ta vars (Variable cellindex)
mcolange's avatar
mcolange committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
         | Product(e1,e2) -> (eval_disc_exp ta vars e1) * (eval_disc_exp ta vars e2)
         | Sum(e1,e2) -> (eval_disc_exp ta vars e1) + (eval_disc_exp ta vars e2)
         | Division(e1,e2) -> (eval_disc_exp ta vars e1) / (eval_disc_exp ta vars e2)
         | Substraction(e1,e2) -> (eval_disc_exp ta vars e1) - (eval_disc_exp ta vars e2)
        ) in
      (*
      eprintf "%s -----> %d\n" (string_of_exp ta exp) k;
       *)
      k
    with Found ->
      failwith ("Discrete expression contains clock: " ^ (string_of_exp ta exp)); 
       | e -> raise e

       
  let source_location_of_edge ta edge =
485
    ta.procs.(edge.edgeProc).procLocations.(edge.edgeSource)
mcolange's avatar
mcolange committed
486 487 488


  let eval_disc_guard ta state guard =
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    let rec aux_eval t v = function
      | [] -> true
      | GuardLeq(e1,e2) :: l ->
          if (    (eval_disc_exp t v e1)
              <=  (eval_disc_exp t v e2)) then
                aux_eval t v l
          else
            false
      | GuardLess(e1,e2) :: l ->
          if (    (eval_disc_exp t v e1)
              <   (eval_disc_exp t v e2)) then
                aux_eval t v l
          else
            false
      | GuardGeq(e1,e2) :: l ->
          if (    (eval_disc_exp t v e1)
              >=  (eval_disc_exp t v e2)) then
                aux_eval t v l
          else
            false
      | GuardGreater(e1,e2) :: l ->
          if (    (eval_disc_exp t v e1)
              >   (eval_disc_exp t v e2)) then
                aux_eval t v l
          else
            false
      | GuardEqual(e1,e2) :: l ->
          if (    (eval_disc_exp t v e1)
              =   (eval_disc_exp t v e2)) then
                aux_eval t v l
          else
            false
521 522 523 524 525 526
      | GuardNeq(e1,e2) :: l ->
          if (    (eval_disc_exp t v e1)
              <>  (eval_disc_exp t v e2)) then
                aux_eval t v l
          else
            false
527
    in aux_eval ta state.stateVars guard
mcolange's avatar
mcolange committed
528 529 530 531


  let _guard_to_dbm ta state g =
    let nclocks = VarContext.size ta.clocks in
532 533
    let dbm = UDbm.Dbm.create nclocks in
    UDbm.Dbm.set_init dbm;
mcolange's avatar
mcolange committed
534 535 536
    let aux = function
      | GuardLeq(Clock(c), e) ->
          let k = eval_disc_exp ta state e in
537
          UDbm.Dbm.constrain dbm (c, 0, (k, Udbml.Basic_types.DBM_WEAK))
mcolange's avatar
mcolange committed
538 539
      | GuardLess(Clock(c), e) ->
        let k = eval_disc_exp ta state e in
540
        UDbm.Dbm.constrain dbm (c, 0, (k, Udbml.Basic_types.DBM_STRICT))
mcolange's avatar
mcolange committed
541 542
      | GuardGeq(Clock(c), e) ->
        let k = eval_disc_exp ta state e in
543
        UDbm.Dbm.constrain dbm (0, c, (-k, Udbml.Basic_types.DBM_WEAK))
mcolange's avatar
mcolange committed
544 545
      | GuardGreater(Clock(c), e) ->
        let k = eval_disc_exp ta state e in
546
        UDbm.Dbm.constrain dbm (0, c, (-k, Udbml.Basic_types.DBM_STRICT))
mcolange's avatar
mcolange committed
547 548
      | GuardEqual(Clock(c), e) ->
        let k = eval_disc_exp ta state e in
549 550
        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
551 552 553 554 555 556 557
      | _ as e -> failwith (sprintf "Bad Guard: %s" (string_of_guard ta [e]))
    in
    List.iter aux g;
    dbm


  let is_committed state =
558 559 560 561 562 563
    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
564 565 566 567 568 569 570 571 572 573 574 575

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


  (** Apply discrete update of edge to state, result written in state' *)
  let _apply_edge ta state edge state' =
    let aux = fun (id,e) -> 
      state'.stateVars.(id) <- eval_disc_exp ta state.stateVars e
    in
576
    state'.stateLocs.(edge.edgeProc) <- ta.procs.(edge.edgeProc).procLocations.(edge.edgeTarget);
mcolange's avatar
mcolange committed
577 578 579 580 581 582 583
    List.iter aux edge.edgeDiscUpdate



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

584
  let hash_discrete_state s =
585 586 587 588 589 590
    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
591 592

  let is_state_equal s t =
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    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))
mcolange's avatar
mcolange committed
612

613 614 615 616 617 618
  module DS = struct
    type t = discrete_state
    let equal = is_state_equal
    let hash = hash_discrete_state
  end

mcolange's avatar
mcolange committed
619 620 621 622
  let initial_discrete_state ta = ta.init

  let invariant_of_discrete_state ta state =
    try
623
      LocHashtbl.find ta.invars_tbl state.stateLocs
mcolange's avatar
mcolange committed
624 625 626 627
    with Not_found ->
      let glob_inv =
        Array.fold_left (fun acc loc -> loc.locInvar @ acc ) [] state.stateLocs in
      let inv = _guard_to_dbm ta state.stateVars glob_inv in
628
      LocHashtbl.add ta.invars_tbl state.stateLocs inv;
mcolange's avatar
mcolange committed
629 630 631 632 633 634
      inv
       | _ as e -> raise e

  let initial_extended_state ta =
    let dim = (VarContext.size (clocks ta)) in
    let z = Dbm.create dim in
635 636
    Dbm.set_zero z;
    (ta.init, z)
mcolange's avatar
mcolange committed
637
    
638
  let _transitions_from ta state = 
mcolange's avatar
mcolange committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
    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)) ->
                  Queue.add (c, edge) schan
              | Some (RecvChan(c)) ->
                  Queue.add (c, edge) rchan
              | 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

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
  let guard_of_transition ta tr = 
    let to_succinct = function
      |InternalTrans(s,e) -> (s.stateVars,e.edgeGuard)
      |SyncTrans(s,e1,e2) -> (s.stateVars,List.rev_append e1.edgeGuard e2.edgeGuard)
    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

  let transition_fields ta tr = match tr with
mcolange's avatar
mcolange committed
693 694 695 696
    | InternalTrans(state, e) ->
        let state' = _copy_state state in
        _apply_edge ta state e state';
        (state,
697
         guard_of_transition ta tr,
mcolange's avatar
mcolange committed
698 699 700 701 702 703
         e.edgeReset,
         state')
    | SyncTrans(state, e1, e2) ->
        let state' = _copy_state state in
        _apply_edge ta state e1 state';       
        _apply_edge ta state e2 state';
704
        let g = guard_of_transition ta tr in
705
        (state, g, e1.edgeReset @ e2.edgeReset, state')
mcolange's avatar
mcolange committed
706

707 708 709
  let transitions_from ta state =
    List.map (fun tr -> transition_fields ta tr) (_transitions_from ta state)

mcolange's avatar
mcolange committed
710
  let is_urgent_or_committed ta state =
711 712 713 714 715 716
    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
717 718

  let is_target ta state =
719 720 721 722 723 724
    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
725
    in
726
    eval_query ta.query
mcolange's avatar
mcolange committed
727

mcolange's avatar
mcolange committed
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
  let lu_bounds ta state =
    try
      LocHashtbl.find ta.lubounds_tbl state.stateLocs
    with Not_found ->
      let mymax (x:int) (y:int) =
        if (x < y) then y else x
      in
      let nclocks = VarContext.size ta.clocks in
      let lbounds = Array.make nclocks (-Dbm.infty) in
      let ubounds = Array.make nclocks (-Dbm.infty) in
      lbounds.(0) <- 0;
      ubounds.(0) <- 0;
      let nprocs = Array.length state.stateLocs in
      for iproc = 0 to nprocs - 1 do
        let iloc = state.stateLocs.(iproc).locId in
        for cl = 0 to nclocks - 1 do
          lbounds.(cl) <- mymax lbounds.(cl) ta.lowerLU.(iproc).(iloc).(cl);
          ubounds.(cl) <- mymax ubounds.(cl) ta.upperLU.(iproc).(iloc).(cl);
        done;
mcolange's avatar
mcolange committed
747
      done;
mcolange's avatar
mcolange committed
748 749 750
      let (lar, uar) = (Udbml.Carray.to_c lbounds nclocks, Udbml.Carray.to_c ubounds nclocks) in
      LocHashtbl.add ta.lubounds_tbl state.stateLocs (lar, uar);
      (lar, uar)
mcolange's avatar
mcolange committed
751

mcolange's avatar
mcolange committed
752
  let global_m_bounds ta =
mcolange's avatar
mcolange committed
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    if (ta.global_mbounds.(0) <> 0) then (
      let nclocks = VarContext.size (clocks ta) in
      ta.global_mbounds.(0) <- 0;
      for cl = 0 to nclocks-1 do
        for i = 0 to (Array.length ta.lowerLU) - 1 do
          for j = 0 to (Array.length ta.lowerLU.(i)) - 1 do
            let mymax (x:int) (y:int) =
              if (x < y) then y else x
            in
            ta.global_mbounds.(cl) <- mymax ta.global_mbounds.(cl) ta.lowerLU.(i).(j).(cl);
            ta.global_mbounds.(cl) <- mymax ta.global_mbounds.(cl) ta.upperLU.(i).(j).(cl)
          done
        done;
      done
    );
    ta.global_mbounds
mcolange's avatar
mcolange committed
769 770 771 772 773 774 775 776 777

  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;
    _guard_to_dbm ta ta.init.stateVars !inv_guard
    
mcolange's avatar
mcolange committed
778 779 780 781 782 783 784 785 786 787 788 789 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 826 827 828 829 830 831 832 833 834 835 836
  (** 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 **********)
  
  (** This is pretty much a direct translation from LocalLUNormalizer class of Verifix.
      @return a pair (lower,upper) corresponding to L and U values, three-dimensional arrays indexed by  process, location, and clock
      *)
  let _make_lu_table ta = 
    let nclocks = VarContext.size ta.clocks in
    let maketable () = 
      Array.map (fun proc -> 
          Array.map (fun loc ->
              Array.init nclocks (fun c -> -Dbm.infty)
            ) proc.procLocations
        ) ta.procs
    in
    let upper = maketable () in
    let lower = maketable () in
    let process iproc iloc g = 
      let aux = function
        | GuardLeq(Clock(l),Constant(r)) ->
          upper.(iproc).(iloc).(l) <- max upper.(iproc).(iloc).(l) r
        | GuardLess(Clock(l),Constant(r)) ->
          upper.(iproc).(iloc).(l) <- max upper.(iproc).(iloc).(l) r
        | GuardEqual(Clock(l),Constant(r)) ->
          upper.(iproc).(iloc).(l) <- max upper.(iproc).(iloc).(l) r;
          lower.(iproc).(iloc).(l) <- max lower.(iproc).(iloc).(l) r
        | GuardGreater(Clock(l),Constant(r)) ->
          lower.(iproc).(iloc).(l) <- max lower.(iproc).(iloc).(l) r
        | GuardGeq(Clock(l),Constant(r)) ->
          lower.(iproc).(iloc).(l) <- max lower.(iproc).(iloc).(l) r
        | _ -> failwith "Cannot compute lu bounds: Guards not in normal form."
      in
      List.iter aux g
    in
    let close bounds iproc proc = 
      let stable = ref false in
      while (not !stable) do
        stable := true;
        Array.iter (fun loc -> 
            List.iter (fun edge ->
                let source = edge.edgeSource in
                let target = edge.edgeTarget in
                let sourceBnd = bounds.(iproc).(source) in
                let targetBnd = bounds.(iproc).(target) in
mcolange's avatar
mcolange committed
837
                for j = 1 to nclocks - 1 do
838
                  if (not (List.exists (fun (cl,_) -> j = cl) edge.edgeReset)) then (
mcolange's avatar
mcolange committed
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
                    if (targetBnd.(j) > sourceBnd.(j) ) then(
                      sourceBnd.(j) <- targetBnd.(j);
                      stable := false
                    )                                     
                  )
                done
              ) loc.locEdges
          ) proc.procLocations
      done;
    in
    Array.iteri (fun iproc proc -> 
        (* Initialize *)
        Array.iteri (fun iloc loc ->
            List.iter (fun edge ->
                process iproc iloc edge.edgeGuard) 
              loc.locEdges;
            process iproc iloc loc.locInvar
          ) proc.procLocations;
        (* Close *)
        close lower iproc proc;
        close upper iproc proc;
      ) ta.procs;
    (lower,upper)


864 865 866 867 868 869 870 871 872 873
  (** Constructs a timed_automaton from the C data structure produce by the
   *  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
   *)
874
  external utap_from_file : string -> string -> timed_automaton = "xta_from_xmlfile";;
875

876
  let build_ta_from_processes clockcont varcont var_init_values arraycells procs query =
877 878 879 880 881 882 883
    (* 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;
mcolange's avatar
mcolange committed
884 885 886 887 888 889 890 891 892 893 894
    (* Convert the (template,string) VarContext.t  to string VarContext.t
       by prepending the process names to variables and clocks. 
       We will just extract these elements from the hash tables, along with their indices,
       so as to reinsert them in the same order in the new VarContext.
       These contexts are only for pretty printing and have no role in simulation
    *)
    let get_vc_elements vc = 
      Hashtbl.fold 
        (fun (tmp,name) index acc ->
           let prefix = match tmp with
               None -> ""
895
             | Some procId -> procs.(procId).procName  ^ "."
mcolange's avatar
mcolange committed
896 897 898 899 900 901 902 903 904 905 906
           in
           let name = sprintf "%s%s" prefix name in
           (index,name) :: acc
        ) (VarContext.get_var2index vc) [] 
    in    
    let clist = List.sort compare (get_vc_elements clockcont) in
    let vlist = List.sort compare (get_vc_elements varcont) in
    let clocks = VarContext.create () in
    let vars = VarContext.create () in
    List.iter (fun (_,name) -> VarContext.add clocks name) clist;
    List.iter (fun (_,name) -> VarContext.add vars name) vlist;
907
    let nvars = (Hashtbl.length var_init_values) in
mcolange's avatar
mcolange committed
908
    let initLocs = Array.map (fun proc -> proc.procLocations.(proc.procInitLoc)) procs in
909
    let initVars = Array.make nvars 0 in
mcolange's avatar
mcolange committed
910 911 912 913 914
    for i = 0 to nvars-1 do
      initVars.(i) <- Hashtbl.find var_init_values i;
    done;
    let ta = {
      procs = procs;
915
      celltoindex = arraycells;
mcolange's avatar
mcolange committed
916 917 918
      clocks = clocks;
      vars = vars;
      init = {stateLocs = initLocs; stateVars = initVars};
919
      query = query;
mcolange's avatar
mcolange committed
920 921
      lowerLU = [||];
      upperLU = [||];
922
      guards_tbl = GuardHashtbl.create 1024;
mcolange's avatar
mcolange committed
923
      invars_tbl = LocHashtbl.create 1024;
mcolange's avatar
mcolange committed
924 925
      lubounds_tbl = LocHashtbl.create 1024;
      global_mbounds = Array.make (VarContext.size clocks) (-Dbm.infty)
mcolange's avatar
mcolange committed
926 927 928 929 930 931 932
    }
    in 
    let (lower,upper) = _make_lu_table ta in
    ta.lowerLU <- lower;
    ta.upperLU <- upper;
    ta

933
  let make_ta tafile qfile =
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
    (** 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. *)
    let varcont = VarContext.create () in
    let var_init_values = Hashtbl.create 10 in
    let const_values = Hashtbl.create 10 in
    let ref_clocks = Hashtbl.create 10 in
    let ref_variables = Hashtbl.create 10 in
    let clockcont = VarContext.create () in
    let constcont = VarContext.create () in
    let clockref = VarContext.create () in
    let varref = VarContext.create () in
    Callback.register "cb_expression_constant" cb_expression_constant;
    Callback.register "cb_expression_variable"
      (cb_expression_variable constcont const_values varcont varref ref_variables);
    Callback.register "cb_expression_clock"
      (cb_expression_clock clockcont clockref ref_clocks);
    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;

956
    let arraycont = VarContext.create () in
957
    Callback.register "cb_expression_array" (cb_expression_array arraycont);
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
    let arraycelltovar = Hashtbl.create 10 in
    let cb_register_global_array_name arrayName =
      VarContext.add arraycont (None, arrayName)
    in
    Callback.register "cb_register_global_array_name" cb_register_global_array_name;
    let cb_register_global_array_cell cellName value =
      VarContext.add varcont (None, cellName);
      let cellId = VarContext.index_of_var varcont (None, cellName) in
      Hashtbl.add var_init_values cellId value;
      let firstLSB = String.index cellName '[' in
      let arrayName = String.sub cellName 0 firstLSB in
      let last = ref (firstLSB+1) in
      let indexes = ref [] in
      let split pos = function
        | '[' -> last := pos+1
        | ']' -> 
            let substr = String.sub cellName !last (pos - !last) in
            indexes := (int_of_string substr) :: !indexes
        | _ -> ()
      in
      String.iteri split cellName;
      (* now `indexes` contains the indexes of the cell in the multidimensional array,
       * in reverse order *)
      let arrayId = VarContext.index_of_var arraycont (None, arrayName) in
      Hashtbl.add arraycelltovar (arrayId, List.rev !indexes) cellId
    in
    Callback.register "cb_register_global_array_cell" cb_register_global_array_cell;

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    let register_constant tmp name value =
      VarContext.add constcont (tmp, name);
      let varid = VarContext.index_of_var constcont (tmp, name) in
      Hashtbl.add const_values varid value
    in
    let cb_register_global_constant name value = register_constant None name value in
    let cb_register_constant tmp name value = register_constant (Some tmp) name value in
    Callback.register "cb_register_global_constant" cb_register_global_constant;
    Callback.register "cb_register_constant" cb_register_constant;
    let register_variable tmp name value =
      VarContext.add varcont (tmp, name);
      let varid = VarContext.index_of_var varcont (tmp, name) in
      Hashtbl.add var_init_values varid value
    in
    let cb_register_global_variable name value = register_variable None name value in
    let cb_register_variable tmp name value = register_variable (Some tmp) name value in
    Callback.register "cb_register_global_variable" cb_register_global_variable;
    Callback.register "cb_register_variable" cb_register_variable;
    let cb_register_global_clock name =
      VarContext.add clockcont (None, name)
    in
    Callback.register "cb_register_global_clock" cb_register_global_clock;
    let cb_register_clock name tmp =
      VarContext.add clockcont (Some tmp, name)
    in
    Callback.register "cb_register_clock" cb_register_clock;

    let rec evaluate_expression = function
      | Constant(c) -> c
      | Clock(_) -> failwith "there should not be clocks in evaluated expressions"
      | Variable(i) -> Hashtbl.find var_init_values i
      | 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
        | Clock(_) -> false
        | 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)
1031
        | Array(_, l) -> List.for_all (fun x -> filt_exp x) l
1032 1033 1034 1035 1036 1037 1038 1039
        | _ -> 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)
1040
        | GuardNeq(x,y) -> (filt_exp x) && (filt_exp y)
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
      in
      List.filter filt_ag g
    in
    (** Get clock guard from mixed guard *)
    let filter_clock_guard g = 
      let rec filt_exp = function
        | Variable(_) -> false
        | 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)
1052
        | Array(_, l) -> List.for_all (fun x -> filt_exp x) l
1053 1054 1055 1056 1057 1058 1059 1060
        | _ -> 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)
1061
        | GuardNeq(x,y) -> (filt_exp x) && (filt_exp y)
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
      in
      List.filter filt_ag g
    in
    (* Assign integer identifiers to channels. *)
    let chanids = Hashtbl.create 50 in
    let next_chan_id = ref 0 in
    let chan_to_id s =
      try Hashtbl.find chanids s 
      with Not_found -> (
        incr next_chan_id;
        Hashtbl.add chanids s !next_chan_id;
        !next_chan_id)
    in
    let cb_send_channel name =
      let chanid = chan_to_id name in
      Some(SendChan(chanid))
    in
    let cb_recv_channel name =
      let chanid = chan_to_id name in
      Some(RecvChan(chanid))
    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;
        edgeReset = List.map
          (fun (Clock(x),_) -> (x,0))
          (List.filter (function (Clock(_),_) -> true | _ -> false) extUpdate);
        edgeDiscUpdate = List.map
          (fun (Variable(x),e) -> (x,e))
          (List.filter (function (Variable(_),_) -> true | _ -> false) extUpdate);
        edgeTarget = dst;
        edgeSync = sync;
        edgeProc = procId;
        edgeControllable = control;
      }
    in
    Callback.register "cb_build_edge" build_edge;
    let build_location id name committed urgent guard edges procId =
      {
        locId = id;
        locName = name;
        locCommitted = committed;
        locUrgent = urgent;
        locInvar = guard;
        locEdges = edges;
        locProc = procId;
      }
    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;
    let build_location_array n = Array.make n (build_location 0 "" false false [] [] 0) in
    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;
1128
    let build_ta procs query = build_ta_from_processes clockcont varcont var_init_values arraycelltovar procs query in
1129
    Callback.register "cb_build_ta" build_ta;
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    let global_var_index varName =
      try
        VarContext.index_of_var varcont (None,varName)
      with
        | Not_found -> -1
    in
    Callback.register "cb_global_var_index" global_var_index;
    let local_var_index procId varName =
      try
        VarContext.index_of_var varcont (Some procId,varName)
      with
        | Not_found -> -1
    in
    Callback.register "cb_local_var_index" local_var_index;
    utap_from_file tafile qfile
mcolange's avatar
mcolange committed
1145 1146

  let from_file tafile qfile ?scale:(scale=1) ?enlarge:(enlarge=0) () = 
1147
    let ta = make_ta tafile qfile in
mcolange's avatar
mcolange committed
1148 1149 1150 1151
    ta
  
end