grew_rule.ml 27.8 KB
Newer Older
pj2m's avatar
pj2m committed
1 2 3
open Log
open Printf 

bguillaum's avatar
bguillaum committed
4 5
open Grew_utils
open Grew_ast
pj2m's avatar
pj2m committed
6
open Grew_edge
bguillaum's avatar
bguillaum committed
7
open Grew_fs
pj2m's avatar
pj2m committed
8
open Grew_node
bguillaum's avatar
bguillaum committed
9 10
open Grew_command
open Grew_graph
pj2m's avatar
pj2m committed
11

pj2m's avatar
pj2m committed
12
IFDEF DEP2PICT THEN
pj2m's avatar
pj2m committed
13
open Dep2pict
pj2m's avatar
pj2m committed
14
ENDIF
pj2m's avatar
pj2m committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29


module Instance = struct
  type t = {
      graph: Graph.t;
      commands: Command.h list;
      rules: string list;
      big_step: Grew_types.big_step option; 
    }

  let empty = {graph = Graph.empty; rules=[]; commands=[]; big_step=None;}

  let from_graph g = {empty with graph = g} 

  let build gr_ast = 
30 31
    let (graph,_,_) = Graph.build gr_ast.Ast.nodes gr_ast.Ast.edges in
    { empty with graph = graph }
pj2m's avatar
pj2m committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45

  let rev_steps t = 
    { t with big_step = match t.big_step with
    | None -> None
    | Some bs -> Some {bs with Grew_types.small_step = List.rev bs.Grew_types.small_step }
    }

  let clear t = {empty with graph = t.graph } (* FIXME: normalization of node ids ??? *)
  let get_graph t = t.graph

  (* comparition is done on the list of commands *)
  (* only graph rewrited from the same init graph can be "compared" *)
  let compare t1 t2 = Pervasives.compare t1.commands t2.commands

pj2m's avatar
pj2m committed
46 47
IFDEF DEP2PICT THEN
  let save_dep_png ?main_feat base t = 
48
    ignore (Dep2pict.fromDepStringToPng (Graph.to_dep ?main_feat t.graph) (base^".png"))
pj2m's avatar
pj2m committed
49 50
ENDIF

pj2m's avatar
pj2m committed
51 52 53 54 55 56 57 58 59 60 61
end

module Instance_set = Set.Make (Instance)





module Rule = struct 
  type pid = int
  type gid = int
62

63
  let max_depth = ref 500
pj2m's avatar
pj2m committed
64 65 66
  exception Bound_reached

  type const = 
67 68 69 70
    | No_out of pid * Edge.t 
    | No_in of pid * Edge.t
    | Feature_eq of pid * string * pid * string
    | Filter of pid * Feature_structure.t (* used when a without impose a fs on a node defined by the match pattern *)
pj2m's avatar
pj2m committed
71 72 73

  let build_constraint ?locals table = function 
    | (Ast.Start (node_name, labels), loc) -> No_out (Id.build ~loc node_name table, Edge.make ?locals labels)
bguillaum's avatar
bguillaum committed
74
    | (Ast.No_out node_name, loc) -> No_out (Id.build ~loc node_name table, Edge.all)
pj2m's avatar
pj2m committed
75
    | (Ast.End (node_name, labels),loc) -> No_in (Id.build ~loc node_name table, Edge.make ?locals labels)
bguillaum's avatar
bguillaum committed
76
    | (Ast.No_in node_name, loc) -> No_in (Id.build ~loc node_name table, Edge.all)
77 78
    | (Ast.Feature_eq ((node_name1, feat_name1), (node_name2, feat_name2)), loc) -> 
        Feature_eq (Id.build ~loc node_name1 table, feat_name1, Id.build ~loc node_name2 table, feat_name2)
pj2m's avatar
pj2m committed
79 80 81

  type pattern = 
      { graph: Graph.t;
82
        constraints: const list;
pj2m's avatar
pj2m committed
83 84 85
      }

  let build_pos_pattern ?domain ?(locals=[||]) pattern_ast =
86
    let (graph,table,filter_nodes) = Graph.build ?domain ~locals pattern_ast.Ast.pat_nodes pattern_ast.Ast.pat_edges in
pj2m's avatar
pj2m committed
87 88 89
    (
     {
      graph = graph;
90 91 92
      constraints = 
      List.map (build_constraint ~locals table) pattern_ast.Ast.pat_const 
      @ (List.map (fun (pid, fs) -> Filter (pid, fs)) filter_nodes);
pj2m's avatar
pj2m committed
93 94 95 96
    }, 
     table
    )

97
      (* the neg part *)
pj2m's avatar
pj2m committed
98 99 100 101 102
  let build_neg_constraint ?locals pos_table neg_table const =
    let id_build loc string_id = 
      match Id.build_opt string_id pos_table with Some i -> i | None -> -1-(Id.build ~loc string_id neg_table) in
    match const with
    | (Ast.Start (node_name, labels),loc) -> No_out (id_build loc node_name, Edge.make ?locals labels)
bguillaum's avatar
bguillaum committed
103
    | (Ast.No_out node_name, loc) -> No_out (id_build loc node_name, Edge.all)
pj2m's avatar
pj2m committed
104
    | (Ast.End (node_name, labels),loc) -> No_in (id_build loc node_name, Edge.make ?locals labels)
bguillaum's avatar
bguillaum committed
105
    | (Ast.No_in node_name, loc) -> No_in (id_build loc node_name, Edge.all)
106 107
    | (Ast.Feature_eq ((node_name1, feat_name1), (node_name2, feat_name2)), loc) -> 
        Feature_eq (id_build loc node_name1, feat_name1, id_build loc node_name2, feat_name2)
pj2m's avatar
pj2m committed
108 109 110 111 112 113 114 115 116 117 118 119 120

  let build_neg_pattern ?domain ?(locals=[||]) pos_table pattern_ast =
    let (extension, neg_table) =
      Graph.build_extention ?domain ~locals pos_table pattern_ast.Ast.pat_nodes pattern_ast.Ast.pat_edges in

    let filters = IntMap.fold (fun id node acc -> Filter (id, node.Node.fs) :: acc) extension.Graph.old_map [] in

    (* (\* DEBUG *\) Printf.printf "-----> |filters| = %d\n%!" (List.length filters); *)
    {
     graph = {Graph.map = extension.Graph.ext_map; lub=0 };
     constraints = filters @ List.map (build_neg_constraint ~locals pos_table neg_table) pattern_ast.Ast.pat_const ;
   }

121 122 123 124 125 126 127 128
  let get_edge_ids pattern =
    IntMap.fold
      (fun _ node acc -> 
        Massoc.fold_left
          (fun acc2 _ edge -> match Edge.get_id edge with None -> acc2 | Some id -> id::acc2)
          acc node.Node.next
      ) pattern.graph.Graph.map []
      
pj2m's avatar
pj2m committed
129 130 131 132 133
  type t = {
      name: string;
      pos: pattern;
      neg: pattern list;
      commands: Command.t list;
134
      loc: Loc.t;
pj2m's avatar
pj2m committed
135 136
    }

bguillaum's avatar
bguillaum committed
137 138
  let get_name t = t.name

139
  let get_loc t = t.loc
pj2m's avatar
pj2m committed
140

141 142 143 144 145 146 147 148 149 150 151 152
  let build_commands ?domain ?(locals=[||]) pos pos_table ast_commands =
    let known_node_ids = Array.to_list pos_table in
    let known_edge_ids = get_edge_ids pos in
    let rec loop (kni,kei) = function
      | [] -> []
      | ast_command :: tail ->
          let (command, (new_kni, new_kei)) = 
            Command.build ?domain (kni,kei) pos_table locals ast_command in
          command :: (loop (new_kni,new_kei) tail) in
    loop (known_node_ids, known_edge_ids) ast_commands

  let build ?domain ?(locals=[||]) rule_ast = 
pj2m's avatar
pj2m committed
153 154 155 156 157 158
    let (pos,pos_table) = build_pos_pattern ?domain ~locals rule_ast.Ast.pos_pattern in

    {
     name = rule_ast.Ast.rule_id ;
     pos = pos;
     neg = List.map (fun p -> build_neg_pattern ?domain ~locals pos_table p) rule_ast.Ast.neg_patterns;
159 160
     commands = build_commands ?domain ~locals pos pos_table rule_ast.Ast.commands;
     loc = rule_ast.Ast.rule_loc;
pj2m's avatar
pj2m committed
161 162 163
   }

  type matching = {
164
      n_match: gid IntMap.t;                    (* partial fct: pattern nodes |--> graph nodes *)
pj2m's avatar
pj2m committed
165 166 167
      e_match: (string*(gid*Label.t*gid)) list; (* edge matching: edge ident  |--> (src,label,tar) *)
      a_match: (gid*Label.t*gid) list;          (* anonymous edge mached *)
    }
168

pj2m's avatar
pj2m committed
169
  let empty_matching = { n_match = IntMap.empty; e_match = []; a_match = [];}
170

pj2m's avatar
pj2m committed
171
  let singleton_matching i j =  { empty_matching with n_match = IntMap.add i j IntMap.empty }
172

pj2m's avatar
pj2m committed
173 174 175 176 177 178 179 180
  let e_comp (e1,_) (e2,_) = compare e1 e2
      
  let union match1 match2 = {
    n_match = IntMap.union_if match1.n_match match2.n_match; 
    e_match = List_.sort_disjoint_union ~compare:e_comp match1.e_match match2.e_match;
    a_match = match1.a_match @ match2.a_match;
  }

bguillaum's avatar
bguillaum committed
181
  let e_match_add ?pos edge_id matching =
pj2m's avatar
pj2m committed
182 183
    match List_.usort_insert ~compare:e_comp edge_id matching.e_match with
    | Some new_e_match -> { matching with e_match = new_e_match }
bguillaum's avatar
bguillaum committed
184
    | None -> Error.bug "The edge identifier '%s' is binded twice in the same pattern" (fst edge_id)
185
          
pj2m's avatar
pj2m committed
186 187 188 189 190 191 192
  let a_match_add edge matching = {matching with a_match = edge::matching.a_match }

  let up_deco matching = 
    { Deco.nodes = IntMap.fold (fun _ gid acc -> gid::acc) matching.n_match [];
      Deco.edges = List.fold_left (fun acc (_,edge) -> edge::acc) matching.a_match matching.e_match;
    }

bguillaum's avatar
bguillaum committed
193
  let find cnode ?loc (matching, created_nodes) =
pj2m's avatar
pj2m committed
194 195
    match cnode with
    | Command.Pid pid -> 
196 197
        (try IntMap.find pid matching.n_match
        with Not_found -> Error.bug ?loc "Inconsistent matching pid '%d' not found" pid)
pj2m's avatar
pj2m committed
198
    | Command.New name -> 
199 200 201
        try List.assoc name created_nodes 
        with Not_found -> Error.run ?loc "Identifier '%s' not found" name
            
pj2m's avatar
pj2m committed
202 203 204 205 206

  let down_deco (matching,created_nodes) commands =
    {
     Deco.nodes = List.fold_left
       (fun acc -> function
207
         | (Command.UPDATE_FEAT (tar_cn,_,_),loc)
208 209 210
         | (Command.SHIFT_EDGE (_,tar_cn),loc) -> 
             (find tar_cn (matching, created_nodes)) :: acc
         | _ -> acc
pj2m's avatar
pj2m committed
211 212 213
       ) [] commands;
     Deco.edges = List.fold_left
       (fun acc -> function 
214 215 216
         | (Command.ADD_EDGE (src_cn,tar_cn,edge),loc) ->  
             (find src_cn (matching, created_nodes), Edge.as_label edge, find tar_cn (matching, created_nodes)) :: acc
         | _ -> acc
pj2m's avatar
pj2m committed
217 218 219 220 221 222 223 224 225 226 227 228
       ) [] commands
   }

  exception Fail
(* ================================================================================ *)
  type partial = {
      sub: matching; 
      unmatched_nodes: pid list;
      unmatched_edges: (pid * Edge.t * pid) list;
      already_matched_gids: gid list; (* to ensure injectivity *)
      check: const list (* constraints to verify at the end of the matching *)
    }    
229 230 231 232 233
        
        (* PREREQUISITES: 
           - all partial matching have the same domain 
           - the domain of the pattern P is the disjoint union of domain([sub]) and [unmatched_nodes]
         *)
pj2m's avatar
pj2m committed
234 235 236 237 238 239 240 241 242

  let init pattern =
    let roots = Graph.roots pattern.graph in

    let node_list = IntMap.fold (fun pid _ acc -> pid::acc) pattern.graph.Graph.map [] in

    (* put all roots in the front of the list to speed up the algo *)
    let sorted_node_list = 
      List.sort
243 244 245 246 247
        (fun n1 n2 -> match (List.mem n1 roots, List.mem n2 roots) with
        | true, false -> -1
        | false, true -> 1
        | _ -> 0) node_list in
    
pj2m's avatar
pj2m committed
248 249 250 251 252 253 254 255 256
    { sub = empty_matching;
      unmatched_nodes = sorted_node_list;
      unmatched_edges = [];
      already_matched_gids = [];
      check = pattern.constraints;
    }

  let fullfill graph matching = function 
    | No_out (pid,edge) -> 
257 258
        let gid = IntMap.find pid matching.n_match in
        Graph.edge_out graph gid edge
pj2m's avatar
pj2m committed
259
    | No_in (pid,edge) -> 
260 261 262 263 264
        let gid = IntMap.find pid matching.n_match in
        IntMap.exists
          (fun _ node ->
            List.exists (fun e -> Edge.compatible edge e) (Massoc.assoc gid node.Node.next)
          ) graph.Graph.map
265 266 267
    | Feature_eq (pid1, feat_name1, pid2, feat_name2) ->
        let gnode1 = IntMap.find (IntMap.find pid1 matching.n_match) graph.Graph.map in
        let gnode2 = IntMap.find (IntMap.find pid2 matching.n_match) graph.Graph.map in
bguillaum's avatar
bguillaum committed
268 269 270 271
        (match (Feature_structure.get feat_name1 gnode1.Node.fs,
               Feature_structure.get feat_name2 gnode2.Node.fs) with
        | Some fv1, Some fv2 when fv1 = fv2 -> true
        | _ -> false)
pj2m's avatar
pj2m committed
272
    | Filter (pid, fs) ->
273 274 275
        let gid = IntMap.find pid matching.n_match in
        let gnode = IntMap.find gid graph.Graph.map in
        Feature_structure.filter fs gnode.Node.fs
pj2m's avatar
pj2m committed
276

bguillaum's avatar
bguillaum committed
277
  (* returns all extension of the partial input matching *)
bguillaum's avatar
bguillaum committed
278
  let rec extend_matching (positive,neg) (graph:Graph.t) (partial:partial) =
pj2m's avatar
pj2m committed
279 280
    match (partial.unmatched_edges, partial.unmatched_nodes) with
    | [], [] -> 
281 282 283 284
        (* (\* DEBUG *\) Printf.printf "==<1>==\n%!"; *)
        if List.for_all (fun const -> fullfill graph partial.sub const) partial.check 
        then [partial.sub, partial.already_matched_gids]
        else []
pj2m's avatar
pj2m committed
285
    | (src_pid, p_edge, tar_pid)::tail_ue, _ ->
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 312 313 314 315 316 317 318 319 320 321 322 323 324 325
        begin
          try (* is the tar already found in the matching ? *)
            let new_partials = 
              let src_gid = IntMap.find src_pid partial.sub.n_match in
              let tar_gid = IntMap.find tar_pid partial.sub.n_match in
              let src_gnode = Graph.find src_gid graph in
              let g_edges = Massoc.assoc tar_gid src_gnode.Node.next in
              
              match Edge.match_list p_edge g_edges with
              | Edge.Fail -> (* no good edge in graph for this pattern edge -> stop here *)
                  []
              | Edge.Ok label -> (* at least an edge in the graph fits the p_edge "constraint" -> go on *)
                  [ {partial with unmatched_edges = tail_ue; sub = a_match_add (src_gid,label,tar_gid) partial.sub} ] 
              | Edge.Binds (id,labels) -> (* n edges in the graph match the identified p_edge -> make copies of the [k] matchings (and returns n*k matchings) *)
                  List.map 
                    (fun label ->
                      {partial with sub = e_match_add (id,(src_gid,label,tar_gid)) partial.sub; unmatched_edges = tail_ue }
                    ) labels 
            in List_.flat_map (extend_matching (positive,neg) graph) new_partials
          with Not_found -> (* p_edge goes to an unmatched node *)
            let candidates = (* candidates (of type (gid, matching)) for m(tar_pid) = gid) with new partial matching m *)
              let src_gid = IntMap.find src_pid partial.sub.n_match in
              let src_gnode = Graph.find src_gid graph in
              Massoc.fold_left 
                (fun acc gid_next g_edge ->
                  match Edge.match_ p_edge g_edge with
                  | Edge.Fail -> (* g_edge does not fit, no new candidate *)
                      acc
                  | Edge.Ok label -> (* g_edge fits with the same matching *)
                      (gid_next, a_match_add (src_gid, label, gid_next) partial.sub) :: acc 
                  | Edge.Binds (id,[label]) -> (* g_edge fits with an extended matching *)
                      (gid_next, e_match_add (id, (src_gid, label, gid_next)) partial.sub) :: acc
                  | _ -> Error.bug "Edge.match_ must return exactly one label"
                ) [] src_gnode.Node.next in
            List_.flat_map
              (fun (gid_next, matching) -> 
                extend_matching_from (positive,neg) graph tar_pid gid_next
                  {partial with sub=matching; unmatched_edges = tail_ue}
              ) candidates
        end
pj2m's avatar
pj2m committed
326
    | [], pid :: _ -> 
327 328 329 330 331
        IntMap.fold          
          (fun gid _ acc ->
            (extend_matching_from (positive,neg) graph pid gid partial) @ acc
          ) graph.Graph.map []
          
bguillaum's avatar
bguillaum committed
332
  and extend_matching_from (positive,neg) (graph:Graph.t) pid gid partial =
pj2m's avatar
pj2m committed
333 334 335 336
    if List.mem gid partial.already_matched_gids
    then [] (* the required association pid -> gid is not injective *)
    else
      let p_node = 
337 338 339
        if pid >= 0 
        then try Graph.find pid positive with Not_found -> failwith "POS"
        else try Graph.find pid neg with Not_found -> failwith "NEG" in
pj2m's avatar
pj2m committed
340 341 342 343
      let g_node = try Graph.find gid graph with Not_found -> failwith "INS" in
      if not (Node.is_a p_node g_node) 
      then [] (* the nodes don't match *) 
      else 
344 345 346 347 348
        (* add all out-edges from pid in pattern *)
        let new_unmatched_edges = 
          Massoc.fold_left
            (fun acc pid_next p_edge -> (pid, p_edge, pid_next) :: acc
            ) partial.unmatched_edges p_node.Node.next in
pj2m's avatar
pj2m committed
349

350 351 352 353 354 355 356
        let new_partial = { partial with
                            unmatched_nodes = (try List_.rm pid partial.unmatched_nodes with Not_found -> failwith "List_.rm"); 
                            unmatched_edges = new_unmatched_edges;
                            already_matched_gids = gid :: partial.already_matched_gids;
                            sub = {partial.sub with n_match = IntMap.add pid gid partial.sub.n_match};
                          } in
        extend_matching (positive,neg) graph new_partial
pj2m's avatar
pj2m committed
357 358 359 360



(* the exception below is added to handle unification failure in merge!! *)
361
  exception Command_execution_fail
pj2m's avatar
pj2m committed
362 363

(** [apply_command instance matching created_nodes command] returns [(new_instance, new_created_nodes)] *)
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  let apply_command (command,loc) instance matching created_nodes =
    let node_find cnode = find ~loc cnode (matching, created_nodes) in

    match command with
    | Command.ADD_EDGE (src_cn,tar_cn,edge) -> 
        let src_gid = node_find src_cn in
        let tar_gid = node_find tar_cn in
        begin
          match Graph.add_edge instance.Instance.graph src_gid edge tar_gid with
          | Some new_graph -> 
              (
               {instance with 
                Instance.graph = new_graph; 
                commands = List_.sort_insert (Command.H_ADD_EDGE (src_gid,tar_gid,edge)) instance.Instance.commands
              },
               created_nodes
              )
          | None -> 
              Error.run "ADD_EDGE: the edge '%s' already exists %s" (Edge.to_string edge) (Loc.to_string loc)
        end

    | Command.DEL_EDGE_EXPL (src_cn,tar_cn,edge) -> 
        let src_gid = node_find src_cn in
        let tar_gid = node_find tar_cn in
        (
         {instance with 
          Instance.graph = Graph.del_edge loc instance.Instance.graph src_gid edge tar_gid; 
          commands = List_.sort_insert (Command.H_DEL_EDGE_EXPL (src_gid,tar_gid,edge)) instance.Instance.commands
        },
         created_nodes
        )

    | Command.DEL_EDGE_NAME edge_ident ->
        let (src_gid,label,tar_gid) = 
          try List.assoc edge_ident matching.e_match 
          with Not_found -> Error.bug "The edge identifier '%s' is undefined %s" edge_ident (Loc.to_string loc) in
        let edge = Edge.of_label label in
        (
         {instance with 
403
          Instance.graph = Graph.del_edge ~edge_ident loc instance.Instance.graph src_gid edge tar_gid; 
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
          commands = List_.sort_insert (Command.H_DEL_EDGE_EXPL (src_gid,tar_gid,edge)) instance.Instance.commands
        },
         created_nodes
        )    

    | Command.DEL_NODE node_cn -> 
        let node_gid = node_find node_cn in
        (
         {instance with 
          Instance.graph = Graph.del_node instance.Instance.graph node_gid;
          commands = List_.sort_insert (Command.H_DEL_NODE node_gid) instance.Instance.commands
        },
         created_nodes
        )

    | Command.MERGE_NODE (src_cn, tar_cn) ->
        let src_gid = node_find src_cn in
        let tar_gid = node_find tar_cn in
        (match Graph.merge_node loc instance.Instance.graph src_gid tar_gid with
        | Some new_graph -> 
            (
             {instance with 
              Instance.graph = new_graph;
              commands = List_.sort_insert (Command.H_MERGE_NODE (src_gid,tar_gid)) instance.Instance.commands
            },
             created_nodes
            )
        | None -> raise Command_execution_fail
        )
          
434
    | Command.UPDATE_FEAT (tar_cn,tar_feat_name, item_list) ->
bguillaum's avatar
bguillaum committed
435
        let tar_gid = node_find tar_cn in
436 437 438 439 440 441 442
        let rule_items = List.map
            (function
              | Command.Feat (cnode, feat_name) -> Graph.Feat (node_find cnode, feat_name)
              | Command.String s -> Graph.String s
            ) item_list in
        let (new_graph, new_feature_value) = 
          Graph.update_feat instance.Instance.graph tar_gid tar_feat_name rule_items in
bguillaum's avatar
bguillaum committed
443
        (
444 445 446 447
         {instance with
          Instance.graph = new_graph;
          commands = List_.sort_insert
            (Command.H_UPDATE_FEAT (tar_gid,tar_feat_name,new_feature_value))
bguillaum's avatar
bguillaum committed
448 449 450
            instance.Instance.commands
        },
         created_nodes
451
        )
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

    | Command.DEL_FEAT (tar_cn,feat_name) ->
        let tar_gid = node_find tar_cn in
        (
         {instance with 
          Instance.graph = Graph.del_feat instance.Instance.graph tar_gid feat_name;
          commands = List_.sort_insert (Command.H_DEL_FEAT (tar_gid,feat_name)) instance.Instance.commands
        },
         created_nodes
        )     

    | Command.NEW_NEIGHBOUR (created_name,edge,base_pid) ->
        let base_gid = IntMap.find base_pid matching.n_match in
        let (new_gid,new_graph) = Graph.add_neighbour loc instance.Instance.graph base_gid edge in
        (
         {instance with 
          Instance.graph = new_graph;
          commands = List_.sort_insert (Command.H_NEW_NEIGHBOUR (created_name,edge,new_gid)) instance.Instance.commands
        },
         (created_name,new_gid) :: created_nodes
        )

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
    | Command.SHIFT_IN (src_cn,tar_cn) ->
        let src_gid = node_find src_cn in
        let tar_gid = node_find tar_cn in
        (
         {instance with 
          Instance.graph = Graph.shift_in loc instance.Instance.graph src_gid tar_gid; 
          commands = List_.sort_insert (Command.H_SHIFT_IN (src_gid,tar_gid)) instance.Instance.commands
        },
         created_nodes
        )

    | Command.SHIFT_OUT (src_cn,tar_cn) ->
        let src_gid = node_find src_cn in
        let tar_gid = node_find tar_cn in
        (
         {instance with 
          Instance.graph = Graph.shift_out loc instance.Instance.graph src_gid tar_gid; 
          commands = List_.sort_insert (Command.H_SHIFT_OUT (src_gid,tar_gid)) instance.Instance.commands
        },
         created_nodes
        )

bguillaum's avatar
bguillaum committed
496
    | Command.SHIFT_EDGE (src_cn,tar_cn) ->
497 498 499 500 501 502 503 504 505
        let src_gid = node_find src_cn in
        let tar_gid = node_find tar_cn in
        (
         {instance with 
          Instance.graph = Graph.shift_edges loc instance.Instance.graph src_gid tar_gid; 
          commands = List_.sort_insert (Command.H_SHIFT_EDGE (src_gid,tar_gid)) instance.Instance.commands
        },
         created_nodes
        )
pj2m's avatar
pj2m committed
506 507 508 509 510 511 512


(* (\* DEBUG *\)let cpt = ref 0 *)

(** [apply_rule instance matching rule] returns a new instance after the application of the rule 
    [Command_execution_fail] is raised if some merge unification fails
 *)
513
  let apply_rule instance matching rule = 
pj2m's avatar
pj2m committed
514

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    (* limit the rewriting depth to avoid looping rewriting *)
    begin
      if List.length instance.Instance.rules >= !max_depth 
      then Error.run "Bound reached (when applying rule %s)" rule.name
    end;
    
    let (new_instance, created_nodes) =
      List.fold_left 
        (fun (instance, created_nodes) command ->
          apply_command command instance matching created_nodes
        ) 
        (instance, []) 
        rule.commands in

    let rule_app = {Grew_types.rule_name = rule.name; up = up_deco matching; down = down_deco (matching,created_nodes) rule.commands } in
pj2m's avatar
pj2m committed
530

531 532 533
    (* (\* DEBUG *\) let up_dot = Graph.to_dot ~deco:rule_app.Grew_types.up instance.Instance.graph in *)
    (* (\* DEBUG *\) let _ = File.write up_dot (Printf.sprintf "dot_%d_a.dot" !cpt) in *)
    (* (\* DEBUG *\) let _ = Sys.command (Printf.sprintf "dot -Tpng -o dot_%d_a.png dot_%d_a.dot" !cpt !cpt) in *)
pj2m's avatar
pj2m committed
534

535 536 537
    (* (\* DEBUG *\) let up_dep = Graph.to_dep ~deco:rule_app.Grew_types.up instance.Instance.graph in *)
    (* (\* DEBUG *\) let _ = File.write up_dep (Printf.sprintf "dep_%d_a.dep" !cpt) in *)
    (* (\* DEBUG *\) let _ = Sys.command (Printf.sprintf "dep2pict -png -o dep_%d_a.png -dep dep_%d_a.dep" !cpt !cpt) in *)
pj2m's avatar
pj2m committed
538

539 540 541
    (* (\* DEBUG *\) let down_dot = Graph.to_dot ~deco:rule_app.Grew_types.down new_instance.Instance.graph in *)
    (* (\* DEBUG *\) let _ = File.write down_dot (Printf.sprintf "dot_%d_b.dot" !cpt) in *)
    (* (\* DEBUG *\) let _ = Sys.command (Printf.sprintf "dot -Tpng -o dot_%d_b.png dot_%d_b.dot" !cpt !cpt) in *)
pj2m's avatar
pj2m committed
542

543 544 545
    (* (\* DEBUG *\) let down_dep = Graph.to_dep ~deco:rule_app.Grew_types.down new_instance.Instance.graph in *)
    (* (\* DEBUG *\) let _ = File.write down_dep (Printf.sprintf "dep_%d_b.dep" !cpt) in *)
    (* (\* DEBUG *\) let _ = Sys.command (Printf.sprintf "dep2pict -png -o dep_%d_b.png -dep dep_%d_b.dep" !cpt !cpt) in *)
pj2m's avatar
pj2m committed
546

547
    (* (\* DEBUG *\) incr cpt; *)
pj2m's avatar
pj2m committed
548

549 550 551 552 553 554
    {new_instance with 
     Instance.rules = rule.name :: new_instance.Instance.rules;
     big_step = match new_instance.Instance.big_step with
     | None -> Some { Grew_types.first = rule_app; small_step = [] }
     | Some bs -> Some { bs with Grew_types.small_step = (instance.Instance.graph, rule_app) :: bs.Grew_types.small_step }
   } 
pj2m's avatar
pj2m committed
555 556 557

(*-----------------------------*)

558 559 560 561 562 563 564 565 566 567 568 569 570
  let update_partial pos_graph without (sub, already_matched_gids) = 
    let neg_graph = without.graph in
    let unmatched_nodes = IntMap.fold (fun pid _ acc -> if pid < 0 then pid::acc else acc) neg_graph.Graph.map [] in
    let unmatched_edges = 
      IntMap.fold 
        (fun pid node acc -> 
          if pid < 0 
          then acc
          else 
            Massoc.fold_left 
              (fun acc2 pid_next p_edge -> (pid, p_edge, pid_next) :: acc2)
              acc node.Node.next
        ) neg_graph.Graph.map [] in
pj2m's avatar
pj2m committed
571 572 573 574

(* Printf.printf "XXX -> unmatched_nodes: %d\n" (List.length unmatched_nodes); *)
(* Printf.printf "XXX -> unmatched_edges: %d\n" (List.length unmatched_edges); *)

575 576 577 578 579 580 581 582
    {
     sub = sub;
     unmatched_nodes = unmatched_nodes;
     unmatched_edges = unmatched_edges;
     already_matched_gids = already_matched_gids;
     check = without.constraints;
   }
      
pj2m's avatar
pj2m committed
583

584 585 586 587
  let fulfill (pos_graph,neg_graph) graph new_partial_matching  =
    match extend_matching (pos_graph, neg_graph) graph new_partial_matching with
    | [] -> true (* the without pattern in not found -> OK *)
    | x -> false 
pj2m's avatar
pj2m committed
588 589 590


(** [one_step instance rules] computes the list of one-step reduct with rules *)
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
  let one_step instance rules =
    List.fold_left 
      (fun acc rule -> 
        let pos_graph = rule.pos.graph in

        (* get the list of partial matching for positive part of the pattern *)
        let matching_list = 
          extend_matching 
            (pos_graph,Graph.empty) 
            instance.Instance.graph 
            (init rule.pos) in

        let filtered_matching_list =
          List.filter
            (fun (sub, already_matched_gids) ->
              List.for_all 
                (fun without -> 
                  let neg_graph = without.graph in
                  let new_partial_matching = update_partial pos_graph without (sub, already_matched_gids) in
                  fulfill (pos_graph,neg_graph) instance.Instance.graph new_partial_matching
                ) rule.neg
            ) matching_list in
        
        List.fold_left 
          (fun acc1 (matching,_) -> 
            try (apply_rule instance matching rule) :: acc1 
            with Command_execution_fail -> Printf.printf "******\n%!"; acc1
          ) acc filtered_matching_list
      ) [] rules 
pj2m's avatar
pj2m committed
620 621

(** [conf_one_step instance rules] computes one Some (one-step reduct) with rules, None if no rule apply *)
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
  let rec conf_one_step (instance : Instance.t) = function
    | [] -> None
    | rule::rule_tail ->
        let pos_graph = rule.pos.graph in

        (* get the list of partial matching for positive part of the pattern *)
        let matching_list = 
          extend_matching 
            (pos_graph,Graph.empty) 
            instance.Instance.graph 
            (init rule.pos) in
        
        try 
          let (first_matching_where_all_witout_are_fulfilled,_) =
            List.find
              (fun (sub, already_matched_gids) ->
                List.for_all 
                  (fun without -> 
                    let neg_graph = without.graph in
                    let new_partial_matching = update_partial pos_graph without (sub, already_matched_gids) in
                    fulfill (pos_graph,neg_graph) instance.Instance.graph new_partial_matching
                  ) rule.neg
              ) matching_list in
          Some (apply_rule instance first_matching_where_all_witout_are_fulfilled rule)
        with Not_found -> (* try another rule *) conf_one_step instance rule_tail
pj2m's avatar
pj2m committed
647 648 649


(** filter nfs being equal *)
650 651 652 653 654 655 656
  let rec filter_equal_nfs nfs =
    Instance_set.fold (fun nf acc ->
      if Instance_set.exists (fun e -> Graph.equals e.Instance.graph nf.Instance.graph) acc
      then (printf "two normal equal normal forms"; acc)
      else Instance_set.add nf acc)
      nfs Instance_set.empty
      
pj2m's avatar
pj2m committed
657 658 659 660 661
(** normalize [t] according to the [rules]
 * [t] is a raw graph
 * info about the commands applied on [t] are kept
 *)

662
      (* type: Instance.t -> t list -> Instance_set.t *)
pj2m's avatar
pj2m committed
663 664 665
  let normalize_instance instance rules =
    let rec loop to_do nf = 
      if to_do = Instance_set.empty
666 667 668 669 670 671 672 673 674 675 676 677
      then nf
      else
        let (new_to_do,new_nf) =  
          Instance_set.fold 
            (fun v (to_do1,nf1) ->
              let step_of_v = one_step v rules in
              if step_of_v = [] (* nothing came out of v*)
              then (to_do1,Instance_set.add (Instance.rev_steps v) nf1)
              else (List.fold_left (fun acc v1 -> Instance_set.add v1 acc) to_do1 step_of_v,nf1)
            )
            to_do (Instance_set.empty,nf) in
        loop new_to_do new_nf in
pj2m's avatar
pj2m committed
678 679 680
    let nfs = loop (Instance_set.singleton instance) Instance_set.empty in 
    filter_equal_nfs nfs

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
  let rec conf_normalize instance rules =
    match conf_one_step instance rules with
    | Some new_instance -> conf_normalize new_instance rules
    | None -> Instance.rev_steps instance

          (* type: t list -> (Instance_set.elt -> bool) -> Instance.t -> Instance_set.t * Instance_set.t *)

  let normalize ?(confluent=false) rules filter instance =
    if confluent
    then
      let output = conf_normalize instance rules in
      if filter output 
      then (Instance_set.singleton output, Instance_set.empty)
      else (Instance_set.empty, Instance_set.singleton output)
    else
      let output_set = normalize_instance instance rules in 
      let (good_set, bad_set) = Instance_set.partition filter output_set in
      (good_set, bad_set)
pj2m's avatar
pj2m committed
699
end