grew_rule.ml 29.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
(* ================================================================================ *)
pj2m's avatar
pj2m committed
18 19
module Instance = struct
  type t = {
20
      graph: G_graph.t;
pj2m's avatar
pj2m committed
21 22 23 24 25
      commands: Command.h list;
      rules: string list;
      big_step: Grew_types.big_step option; 
    }

26
  let empty = {graph = G_graph.empty; rules=[]; commands=[]; big_step=None;}
pj2m's avatar
pj2m committed
27 28 29 30

  let from_graph g = {empty with graph = g} 

  let build gr_ast = 
31
    let graph = G_graph.build gr_ast.Ast.nodes gr_ast.Ast.edges in
32
    { empty with graph = graph }
pj2m's avatar
pj2m committed
33

bguillaum's avatar
bguillaum committed
34 35 36
  let of_conll ?loc lines = 
      (match loc with None -> "None" | Some (f,l) -> Printf.sprintf "(%s,%d)" f l);
    { empty with graph = G_graph.of_conll ?loc lines }
bguillaum's avatar
bguillaum committed
37

pj2m's avatar
pj2m committed
38 39 40 41 42 43 44 45 46
  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

47
  (* comparison is done on the list of commands *)
pj2m's avatar
pj2m committed
48 49 50
  (* 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
51 52
IFDEF DEP2PICT THEN
  let save_dep_png ?main_feat base t = 
53
    ignore (Dep2pict.fromDepStringToPng (G_graph.to_dep ?main_feat t.graph) (base^".png"))
pj2m's avatar
pj2m committed
54
ENDIF
55
end (* module Instance *)
pj2m's avatar
pj2m committed
56 57

module Instance_set = Set.Make (Instance)
58
(* ================================================================================ *)
pj2m's avatar
pj2m committed
59 60 61 62 63




module Rule = struct 
bguillaum's avatar
bguillaum committed
64
  (* the [pid] type is used for pattern identifier *)
65
  type pid = Pid.t
bguillaum's avatar
bguillaum committed
66 67
   
  (* the [gid] type is used for graph identifier *)
pj2m's avatar
pj2m committed
68
  type gid = int
69

bguillaum's avatar
bguillaum committed
70
  (* the rewriting depth is bounded to stop rewriting when the system is not terminating *) 
71
  let max_depth = ref 500
pj2m's avatar
pj2m committed
72 73

  type const = 
74 75
    | No_out of pid * P_edge.t 
    | No_in of pid * P_edge.t
76
    | Feature_eq of pid * string * pid * string
77
    | Filter of pid * P_fs.t (* used when a without impose a fs on a node defined by the match pattern *)
pj2m's avatar
pj2m committed
78 79

  let build_constraint ?locals table = function 
80 81 82 83
    | (Ast.Start (node_name, labels), loc) -> No_out (Id.build ~loc node_name table, P_edge.make ?locals labels)
    | (Ast.No_out node_name, loc) -> No_out (Id.build ~loc node_name table, P_edge.all)
    | (Ast.End (node_name, labels),loc) -> No_in (Id.build ~loc node_name table, P_edge.make ?locals labels)
    | (Ast.No_in node_name, loc) -> No_in (Id.build ~loc node_name table, P_edge.all)
84 85
    | (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)
bguillaum's avatar
bguillaum committed
86 87 88 89 90
          
  type pattern = {
      graph: P_graph.t;
      constraints: const list;
    }
pj2m's avatar
pj2m committed
91

92 93
  let build_pos_pattern ?pat_vars ?(locals=[||]) pattern_ast =
    let (graph,table,filter_nodes) = P_graph.build ?pat_vars ~locals pattern_ast.Ast.pat_nodes pattern_ast.Ast.pat_edges in
pj2m's avatar
pj2m committed
94 95 96
    (
     {
      graph = graph;
97 98 99
      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
100 101 102 103
    }, 
     table
    )

bguillaum's avatar
bguillaum committed
104 105


106
      (* the neg part *)
pj2m's avatar
pj2m committed
107 108 109 110
  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
111 112 113 114
    | (Ast.Start (node_name, labels),loc) -> No_out (id_build loc node_name, P_edge.make ?locals labels)
    | (Ast.No_out node_name, loc) -> No_out (id_build loc node_name, P_edge.all)
    | (Ast.End (node_name, labels),loc) -> No_in (id_build loc node_name, P_edge.make ?locals labels)
    | (Ast.No_in node_name, loc) -> No_in (id_build loc node_name, P_edge.all)
115 116
    | (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
117

118
  let build_neg_pattern ?(locals=[||]) pos_table pattern_ast =
pj2m's avatar
pj2m committed
119
    let (extension, neg_table) =
120
      P_graph.build_extension ~locals pos_table pattern_ast.Ast.pat_nodes pattern_ast.Ast.pat_edges in
pj2m's avatar
pj2m committed
121

122
    let filters = Pid_map.fold (fun id node acc -> Filter (id, P_node.get_fs node) :: acc) extension.P_graph.old_map [] in
pj2m's avatar
pj2m committed
123 124

    {
125
     graph = extension.P_graph.ext_map;
pj2m's avatar
pj2m committed
126 127 128
     constraints = filters @ List.map (build_neg_constraint ~locals pos_table neg_table) pattern_ast.Ast.pat_const ;
   }

129
  let get_edge_ids pattern =
130
    Pid_map.fold
131 132
      (fun _ node acc -> 
        Massoc.fold_left
133 134 135
          (fun acc2 _ edge -> match P_edge.get_id edge with None -> acc2 | Some id -> id::acc2)
          acc (P_node.get_next node)
      ) pattern.graph []
136
      
pj2m's avatar
pj2m committed
137 138 139 140 141
  type t = {
      name: string;
      pos: pattern;
      neg: pattern list;
      commands: Command.t list;
142
      param: Lex_par.t option;
bguillaum's avatar
bguillaum committed
143
      loc: Loc.t;
pj2m's avatar
pj2m committed
144 145
    }

bguillaum's avatar
bguillaum committed
146 147
  let get_name t = t.name

148
  let get_loc t = t.loc
pj2m's avatar
pj2m committed
149

bguillaum's avatar
bguillaum committed
150 151
  let to_dep t = P_graph.to_dep t.pos.graph

152 153
  let is_filter t = t.commands = []

bguillaum's avatar
bguillaum committed
154
  let build_commands ?param ?(locals=[||]) pos pos_table ast_commands =
155 156 157 158 159 160
    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)) = 
bguillaum's avatar
bguillaum committed
161
            Command.build ?param (kni,kei) pos_table locals ast_command in
162 163 164
          command :: (loop (new_kni,new_kei) tail) in
    loop (known_node_ids, known_edge_ids) ast_commands

bguillaum's avatar
bguillaum committed
165 166 167 168 169 170 171 172 173 174 175 176
  let parse_vars loc vars =
    let rec parse_cmd_vars = function
      | [] -> []
      | x::t when x.[0] = '@' -> x :: parse_cmd_vars t
      | x::t -> Error.bug ~loc "Illegal feature definition '%s' in the lexical rule" x in
    let rec parse_pat_vars = function
      | [] -> ([],[])
      | x::t when x.[0] = '@' -> ([],parse_cmd_vars (x::t))
      | x::t when x.[0] = '$' -> let (pv,cv) = parse_pat_vars t in (x::pv, cv)
      | x::t -> Error.bug ~loc "Illegal feature definition '%s' in the lexical rule" x in
    parse_pat_vars vars
    
177
  let build ?(locals=[||]) dir rule_ast = 
bguillaum's avatar
bguillaum committed
178 179 180 181 182 183 184 185

    let (param, pat_vars, cmd_vars) = 
      match rule_ast.Ast.param with
      | None -> (None,[],[])
      | Some (file,vars) ->
          let (pat_vars, cmd_vars) = parse_vars rule_ast.Ast.rule_loc vars in
          let nb_pv = List.length pat_vars in
          let nb_cv = List.length cmd_vars in
186
          let param = Lex_par.load ~loc:rule_ast.Ast.rule_loc dir nb_pv nb_cv file in
187
          (Some param, pat_vars, cmd_vars) in
188

189
    let (pos,pos_table) = build_pos_pattern ~pat_vars ~locals rule_ast.Ast.pos_pattern in
pj2m's avatar
pj2m committed
190 191

    {
bguillaum's avatar
bguillaum committed
192
     name = rule_ast.Ast.rule_id;
pj2m's avatar
pj2m committed
193
     pos = pos;
194
     neg = List.map (fun p -> build_neg_pattern ~locals pos_table p) rule_ast.Ast.neg_patterns;
bguillaum's avatar
bguillaum committed
195
     commands = build_commands ~param:(pat_vars,cmd_vars) ~locals pos pos_table rule_ast.Ast.commands;
196
     loc = rule_ast.Ast.rule_loc;
bguillaum's avatar
bguillaum committed
197
     param = param; 
198
   };
bguillaum's avatar
bguillaum committed
199
      
pj2m's avatar
pj2m committed
200
  type matching = {
bguillaum's avatar
bguillaum committed
201
      n_match: gid Pid_map.t;                   (* partial fct: pattern nodes |--> graph nodes *)
pj2m's avatar
pj2m committed
202 203
      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 *)
204
      m_param: Lex_par.t option;
pj2m's avatar
pj2m committed
205
    }
206

bguillaum's avatar
bguillaum committed
207
  let empty_matching param = { n_match = Pid_map.empty; e_match = []; a_match = []; m_param = param;}
208

pj2m's avatar
pj2m committed
209 210
  let e_comp (e1,_) (e2,_) = compare e1 e2

bguillaum's avatar
bguillaum committed
211
  let e_match_add ?pos edge_id matching =
pj2m's avatar
pj2m committed
212 213
    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
214
    | None -> Error.bug "The edge identifier '%s' is binded twice in the same pattern" (fst edge_id)
215
          
pj2m's avatar
pj2m committed
216 217 218
  let a_match_add edge matching = {matching with a_match = edge::matching.a_match }

  let up_deco matching = 
219
    { Deco.nodes = Pid_map.fold (fun _ gid acc -> gid::acc) matching.n_match [];
pj2m's avatar
pj2m committed
220 221 222
      Deco.edges = List.fold_left (fun acc (_,edge) -> edge::acc) matching.a_match matching.e_match;
    }

bguillaum's avatar
bguillaum committed
223
  let find cnode ?loc (matching, created_nodes) =
pj2m's avatar
pj2m committed
224 225
    match cnode with
    | Command.Pid pid -> 
226
        (try Pid_map.find pid matching.n_match
227
        with Not_found -> Error.bug ?loc "Inconsistent matching pid '%d' not found" pid)
pj2m's avatar
pj2m committed
228
    | Command.New name -> 
229 230 231
        try List.assoc name created_nodes 
        with Not_found -> Error.run ?loc "Identifier '%s' not found" name
            
pj2m's avatar
pj2m committed
232 233 234 235 236

  let down_deco (matching,created_nodes) commands =
    {
     Deco.nodes = List.fold_left
       (fun acc -> function
237
         | (Command.UPDATE_FEAT (tar_cn,_,_),loc)
238 239 240
         | (Command.SHIFT_EDGE (_,tar_cn),loc) -> 
             (find tar_cn (matching, created_nodes)) :: acc
         | _ -> acc
pj2m's avatar
pj2m committed
241 242 243
       ) [] commands;
     Deco.edges = List.fold_left
       (fun acc -> function 
244
         | (Command.ADD_EDGE (src_cn,tar_cn,edge),loc) ->  
245
             (find src_cn (matching, created_nodes), edge, find tar_cn (matching, created_nodes)) :: acc
246
         | _ -> acc
pj2m's avatar
pj2m committed
247 248 249 250 251 252 253 254
       ) [] commands
   }

  exception Fail
(* ================================================================================ *)
  type partial = {
      sub: matching; 
      unmatched_nodes: pid list;
255
      unmatched_edges: (pid * P_edge.t * pid) list;
pj2m's avatar
pj2m committed
256 257 258
      already_matched_gids: gid list; (* to ensure injectivity *)
      check: const list (* constraints to verify at the end of the matching *)
    }    
259 260 261 262 263
        
        (* 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
264

bguillaum's avatar
bguillaum committed
265
  let init param pattern =
266
    let roots = P_graph.roots pattern.graph in
pj2m's avatar
pj2m committed
267

268
    let node_list = Pid_map.fold (fun pid _ acc -> pid::acc) pattern.graph [] in
pj2m's avatar
pj2m committed
269 270 271 272

    (* put all roots in the front of the list to speed up the algo *)
    let sorted_node_list = 
      List.sort
273 274 275 276 277
        (fun n1 n2 -> match (List.mem n1 roots, List.mem n2 roots) with
        | true, false -> -1
        | false, true -> 1
        | _ -> 0) node_list in
    
bguillaum's avatar
bguillaum committed
278
    { sub = empty_matching param;
pj2m's avatar
pj2m committed
279 280 281 282 283 284
      unmatched_nodes = sorted_node_list;
      unmatched_edges = [];
      already_matched_gids = [];
      check = pattern.constraints;
    }

285 286 287 288 289 290 291 292 293 294
(* Ocaml < 3.12 doesn't have exists function for maps! *)
  exception True
  let gid_map_exists fct map =
    try 
      Gid_map.iter (fun k v -> if fct k v then raise True) map;
      false
    with True -> true
(* Ocaml < 3.12 doesn't have exists function for maps! *)


pj2m's avatar
pj2m committed
295 296
  let fullfill graph matching = function 
    | No_out (pid,edge) -> 
297 298
        let gid = Pid_map.find pid matching.n_match in
        G_graph.edge_out graph gid edge
pj2m's avatar
pj2m committed
299
    | No_in (pid,edge) -> 
300
        let gid = Pid_map.find pid matching.n_match in
301
        gid_map_exists (* should be Gid_map.exists with ocaml 3.12 *)
302
          (fun _ node ->
303 304
            List.exists (fun e -> P_edge.compatible edge e) (Massoc.assoc gid (G_node.get_next node))
          ) graph.G_graph.map
305
    | Feature_eq (pid1, feat_name1, pid2, feat_name2) ->
306 307
        let gnode1 = Gid_map.find (Pid_map.find pid1 matching.n_match) graph.G_graph.map in
        let gnode2 = Gid_map.find (Pid_map.find pid2 matching.n_match) graph.G_graph.map in
308 309
        (match (G_fs.get_atom feat_name1 (G_node.get_fs gnode1),
                G_fs.get_atom feat_name2 (G_node.get_fs gnode2)
310
               ) with
bguillaum's avatar
bguillaum committed
311 312
        | Some fv1, Some fv2 when fv1 = fv2 -> true
        | _ -> false)
pj2m's avatar
pj2m committed
313
    | Filter (pid, fs) ->
314 315
        let gid = Pid_map.find pid matching.n_match in
        let gnode = Gid_map.find gid graph.G_graph.map in
316
        P_fs.filter fs (G_node.get_fs gnode)
pj2m's avatar
pj2m committed
317

bguillaum's avatar
bguillaum committed
318
  (* returns all extension of the partial input matching *)
319
  let rec extend_matching (positive,neg) (graph:G_graph.t) (partial:partial) =
pj2m's avatar
pj2m committed
320 321
    match (partial.unmatched_edges, partial.unmatched_nodes) with
    | [], [] -> 
322 323 324
        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
325
    | (src_pid, p_edge, tar_pid)::tail_ue, _ ->
326 327 328
        begin
          try (* is the tar already found in the matching ? *)
            let new_partials = 
329 330 331 332
              let src_gid = Pid_map.find src_pid partial.sub.n_match in
              let tar_gid = Pid_map.find tar_pid partial.sub.n_match in
              let src_gnode = G_graph.find src_gid graph in
              let g_edges = Massoc.assoc tar_gid (G_node.get_next src_gnode) in
333
              
334 335
              match P_edge.match_list p_edge g_edges with
              | P_edge.Fail -> (* no good edge in graph for this pattern edge -> stop here *)
336
                  []
337
              | P_edge.Ok label -> (* at least an edge in the graph fits the p_edge "constraint" -> go on *)
338
                  [ {partial with unmatched_edges = tail_ue; sub = a_match_add (src_gid,label,tar_gid) partial.sub} ] 
339
              | P_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) *)
340 341 342 343 344 345 346
                  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 *)
347 348
              let src_gid = Pid_map.find src_pid partial.sub.n_match in
              let src_gnode = G_graph.find src_gid graph in
349 350
              Massoc.fold_left 
                (fun acc gid_next g_edge ->
351 352
                  match P_edge.match_ p_edge g_edge with
                  | P_edge.Fail -> (* g_edge does not fit, no new candidate *)
353
                      acc
354
                  | P_edge.Ok label -> (* g_edge fits with the same matching *)
355
                      (gid_next, a_match_add (src_gid, label, gid_next) partial.sub) :: acc 
356
                  | P_edge.Binds (id,[label]) -> (* g_edge fits with an extended matching *)
357
                      (gid_next, e_match_add (id, (src_gid, label, gid_next)) partial.sub) :: acc
358 359
                  | _ -> Error.bug "P_edge.match_ must return exactly one label"
                ) [] (G_node.get_next src_gnode) in
360 361 362 363 364 365
            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
366
    | [], pid :: _ -> 
367
        Gid_map.fold          
368 369
          (fun gid _ acc ->
            (extend_matching_from (positive,neg) graph pid gid partial) @ acc
370
          ) graph.G_graph.map []
371
          
372
  and extend_matching_from (positive,neg) (graph:G_graph.t) pid gid partial =
pj2m's avatar
pj2m committed
373 374 375 376
    if List.mem gid partial.already_matched_gids
    then [] (* the required association pid -> gid is not injective *)
    else
      let p_node = 
377
        if pid >= 0 
378 379 380
        then try P_graph.find pid positive with Not_found -> failwith "POS"
        else try P_graph.find pid neg with Not_found -> failwith "NEG" in
      let g_node = try G_graph.find gid graph with Not_found -> failwith "INS" in
bguillaum's avatar
bguillaum committed
381 382
      
      try
383 384 385

        let new_param = P_node.match_ ?param: partial.sub.m_param p_node g_node in

386 387 388 389
        (* 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
390
            ) partial.unmatched_edges (P_node.get_next p_node) in
bguillaum's avatar
bguillaum committed
391 392 393 394 395 396 397 398
        
        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 = Pid_map.add pid gid partial.sub.n_match; m_param = new_param};
          } in
399
        extend_matching (positive,neg) graph new_partial
400
      with P_fs.Fail -> []
pj2m's avatar
pj2m committed
401 402

(* the exception below is added to handle unification failure in merge!! *)
403
  exception Command_execution_fail
pj2m's avatar
pj2m committed
404 405

(** [apply_command instance matching created_nodes command] returns [(new_instance, new_created_nodes)] *)
406 407 408 409 410 411 412 413
  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
414
          match G_graph.add_edge instance.Instance.graph src_gid edge tar_gid with
415 416 417 418 419 420 421 422 423
          | 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 -> 
424
              Error.run "ADD_EDGE: the edge '%s' already exists %s" (G_edge.to_string edge) (Loc.to_string loc)
425 426 427 428 429 430 431
        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 
432
          Instance.graph = G_graph.del_edge loc instance.Instance.graph src_gid edge tar_gid; 
433 434 435 436 437 438
          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 ->
439
        let (src_gid,edge,tar_gid) = 
440 441 442 443
          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
        (
         {instance with 
444
          Instance.graph = G_graph.del_edge ~edge_ident loc instance.Instance.graph src_gid edge tar_gid; 
445 446 447 448 449 450 451 452 453
          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 
454
          Instance.graph = G_graph.del_node instance.Instance.graph node_gid;
455 456 457 458 459 460 461 462
          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
463
        (match G_graph.merge_node loc instance.Instance.graph src_gid tar_gid with
464 465 466 467 468 469 470 471 472 473 474
        | 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
        )
          
475
    | Command.UPDATE_FEAT (tar_cn,tar_feat_name, item_list) ->
bguillaum's avatar
bguillaum committed
476
        let tar_gid = node_find tar_cn in
477 478
        let rule_items = List.map
            (function
479 480
              | Command.Feat (cnode, feat_name) -> G_graph.Feat (node_find cnode, feat_name)
              | Command.String s -> G_graph.String s
bguillaum's avatar
bguillaum committed
481 482 483 484 485 486
              | Command.Param_out index -> 
                  (match matching.m_param with
                  | None -> Error.bug "Cannot apply a UPDATE_FEAT command without parameter"
                  | Some param -> G_graph.String (Lex_par.get_command_value index param))
              | Command.Param_in index -> 
                  (match matching.m_param with
487
                  | None -> Error.bug "Cannot apply a UPDATE_FEAT command without parameter"
bguillaum's avatar
bguillaum committed
488
                  | Some param -> G_graph.String (Lex_par.get_param_value index param))
489
            ) item_list in
490

491
        let (new_graph, new_feature_value) = 
492
          G_graph.update_feat ~loc instance.Instance.graph tar_gid tar_feat_name rule_items in
bguillaum's avatar
bguillaum committed
493
        (
494 495 496 497
         {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
498 499 500
            instance.Instance.commands
        },
         created_nodes
501
        )
502 503 504 505 506

    | Command.DEL_FEAT (tar_cn,feat_name) ->
        let tar_gid = node_find tar_cn in
        (
         {instance with 
507
          Instance.graph = G_graph.del_feat instance.Instance.graph tar_gid feat_name;
508 509 510 511 512 513
          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) ->
514 515
        let base_gid = Pid_map.find base_pid matching.n_match in
        let (new_gid,new_graph) = G_graph.add_neighbour loc instance.Instance.graph base_gid edge in
516 517 518 519 520 521 522 523
        (
         {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
        )

524 525 526 527 528
    | 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 
529
          Instance.graph = G_graph.shift_in loc instance.Instance.graph src_gid tar_gid; 
530 531 532 533 534 535 536 537 538 539
          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 
540
          Instance.graph = G_graph.shift_out loc instance.Instance.graph src_gid tar_gid; 
541 542 543 544 545
          commands = List_.sort_insert (Command.H_SHIFT_OUT (src_gid,tar_gid)) instance.Instance.commands
        },
         created_nodes
        )

bguillaum's avatar
bguillaum committed
546
    | Command.SHIFT_EDGE (src_cn,tar_cn) ->
547 548 549 550
        let src_gid = node_find src_cn in
        let tar_gid = node_find tar_cn in
        (
         {instance with 
551
          Instance.graph = G_graph.shift_edges loc instance.Instance.graph src_gid tar_gid; 
552 553 554 555
          commands = List_.sort_insert (Command.H_SHIFT_EDGE (src_gid,tar_gid)) instance.Instance.commands
        },
         created_nodes
        )
pj2m's avatar
pj2m committed
556 557 558 559

(** [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
 *)
560
  let apply_rule instance matching rule = 
pj2m's avatar
pj2m committed
561

bguillaum's avatar
bguillaum committed
562 563 564
    (* Timeout check *)
    (try Timeout.check () with Timeout.Stop -> Error.run "Time out");

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    (* 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
580

581 582 583 584 585 586
    {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
587 588 589

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

590 591
  let update_partial pos_graph without (sub, already_matched_gids) = 
    let neg_graph = without.graph in
592
    let unmatched_nodes = Pid_map.fold (fun pid _ acc -> if pid < 0 then pid::acc else acc) neg_graph [] in
593
    let unmatched_edges = 
594
      Pid_map.fold 
595 596 597 598 599 600
        (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)
601 602
              acc (P_node.get_next node)
        ) neg_graph [] in
603 604 605 606 607 608 609 610
    {
     sub = sub;
     unmatched_nodes = unmatched_nodes;
     unmatched_edges = unmatched_edges;
     already_matched_gids = already_matched_gids;
     check = without.constraints;
   }
      
pj2m's avatar
pj2m committed
611

612 613 614 615
  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
616 617 618


(** [one_step instance rules] computes the list of one-step reduct with rules *)
619 620 621 622 623 624 625 626
  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 
627
            (pos_graph,P_graph.empty) 
628
            instance.Instance.graph 
bguillaum's avatar
bguillaum committed
629
            (init rule.param rule.pos) in
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

        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
648 649

(** [conf_one_step instance rules] computes one Some (one-step reduct) with rules, None if no rule apply *)
650 651 652 653 654 655 656 657
  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 
658
            (pos_graph,P_graph.empty) 
659
            instance.Instance.graph 
bguillaum's avatar
bguillaum committed
660
            (init rule.param rule.pos) in
661 662 663 664 665 666 667 668 669 670 671 672 673 674
        
        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
675 676 677


(** filter nfs being equal *)
678 679
  let rec filter_equal_nfs nfs =
    Instance_set.fold (fun nf acc ->
680
      if Instance_set.exists (fun e -> G_graph.equals e.Instance.graph nf.Instance.graph) acc
681 682 683 684
      then (printf "two normal equal normal forms"; acc)
      else Instance_set.add nf acc)
      nfs Instance_set.empty
      
pj2m's avatar
pj2m committed
685 686
(** normalize [t] according to the [rules]
 * [t] is a raw graph
687
 * Info about the commands applied on [t] are kept
pj2m's avatar
pj2m committed
688 689
 *)

690
  (* type: Instance.t -> t list -> Instance_set.t *)
pj2m's avatar
pj2m committed
691 692 693
  let normalize_instance instance rules =
    let rec loop to_do nf = 
      if to_do = Instance_set.empty
694 695 696 697 698 699 700 701 702 703 704 705
      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
706 707
    let nfs = loop (Instance_set.singleton instance) Instance_set.empty in 
    filter_equal_nfs nfs
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
      
  (* [filter_instance instance filters] return a boolean:
     - true iff the instance does NOT match any pattern in [filters] *)
  let filter_instance filters instance =
    let rec loop = function
      | [] -> true (* no more filter to check *)
      | filter::filter_tail ->
          let pos_graph = filter.pos.graph in
          
          (* get the list of partial matching for positive part of the pattern *)
          let matching_list = 
            extend_matching 
              (pos_graph,P_graph.empty) 
              instance.Instance.graph 
              (init filter.param filter.pos) in
          
          if List.exists
              (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
                  ) filter.neg
              ) matching_list
          then (* one of the matching can be extended *) false
          else loop filter_tail in
    loop filters


pj2m's avatar
pj2m committed
738

739 740 741 742 743 744 745
  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 *)

746
  let normalize ?(confluent=false) rules filters instance =
bguillaum's avatar
bguillaum committed
747
    Timeout.start ();
748 749 750
    if confluent
    then
      let output = conf_normalize instance rules in
751
      if filter_instance filters output 
752 753 754 755
      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 
756
      let (good_set, bad_set) = Instance_set.partition (filter_instance filters) output_set in
757
      (good_set, bad_set)
758

bguillaum's avatar
bguillaum committed
759
end (* module Rule *)