Add backward moves in the syntax of the automaton.
[SXSI/xpathcomp.git] / src / runtime.ml
1 INCLUDE "debug.ml"
2 INCLUDE "utils.ml"
3
4 open Format
5 open Ata
6 module type S = sig
7   type result_set
8   val top_down_run : Ata.t -> Tree.t -> Tree.node -> result_set
9   val bottom_up_run : Ata.t -> Tree.t -> Compile.text_query * string -> result_set
10 end
11
12 module Make (U : ResJIT.S) : S with type result_set = U.NS.t =
13   struct
14
15     type result_set = U.NS.t;;
16
17     let eval_form auto s1 s2 f =
18       let rec loop f =
19         match Formula.expr f with
20           | Formula.False | Formula.True | Formula.Pred _ -> f, []
21           | Formula.Atom(`Left, b, q) ->
22               Formula.of_bool (b == (StateSet.mem q s1)),
23               if b && StateSet.mem q auto.topdown_marking_states then [ResJIT.LEFT q] else []
24           | Formula.Atom (`Right, b, q) ->
25               Formula.of_bool(b == (StateSet.mem q s2)),
26               if b && StateSet.mem q auto.topdown_marking_states then [ResJIT.RIGHT q] else []
27           | Formula.Atom (`Epsilon, _, _) -> assert false
28
29           | Formula.Or(f1, f2) ->
30               let b1, i1 = loop f1 in
31               let b2, i2 = loop f2 in
32               Formula.or_pred b1 b2, i1 @ i2
33           | Formula.And(f1, f2) ->
34               let b1, i1 = loop f1 in
35               let b2, i2 = loop f2 in
36               Formula.and_pred b1 b2, i1 @ i2
37       in
38       loop f
39
40
41     let eval_trans auto s1 s2 trans =
42       Translist.fold
43         (fun t ((a_st, a_op, a_todo) as acc)->
44            let q, _, m, f = Transition.node t in
45            let form, ops = eval_form auto s1 s2 f in
46            match Formula.expr form with
47              | Formula.True ->
48                StateSet.add q a_st,
49                (q, (if m then (ResJIT.SELF() :: ops) else ops)):: a_op,
50                a_todo
51              | Formula.False -> acc
52              | Formula.Pred p -> a_st, a_op,
53                (p.Tree.Predicate.node, q, [(q,(if m then (ResJIT.SELF() :: ops) else ops))]) :: a_todo
54              | _ -> assert false
55         ) trans (StateSet.empty, [], [])
56
57
58
59     module L3JIT =
60       struct
61
62         type opcode = (t -> t -> t -> Tree.t -> Tree.node -> StateSet.t * t)
63
64         type t = opcode Cache.t Cache.t Cache.t
65
66         let dummy _ _ _ _ _ = failwith "Uninitialized L3JIT"
67
68         let create () = Cache.Lvl3.create 1024 dummy
69
70         let stats fmt d =
71           let d = Cache.Lvl3.to_array d in
72           let len = Array.fold_left
73             (fun acc a ->
74                Array.fold_left (fun acc2 a2 -> Array.length a2 + acc2) acc a) 0 d
75           in
76
77           let lvl1 =
78             Array.fold_left
79               (fun acc a -> if Array.length a == 0 then acc else acc+1) 0 d in
80           let lvl2 = Array.fold_left
81             (fun acc a ->
82                Array.fold_left (fun acc2 a2 -> if Array.length a2 == 0 then acc2 else acc2+1)
83                  acc a) 0 d
84           in
85           let lvl3 = Array.fold_left
86             (fun acc a ->
87                Array.fold_left (fun acc2 a2 ->
88                                   Array.fold_left
89                                     (fun acc3 a3 -> if a3 == dummy then acc3 else acc3+1) acc2 a2)
90                  acc a) 0 d
91       in
92         fprintf fmt "L3JIT Statistics:
93 \t%i entries
94 \t%i used L1 lines
95 \t%i used L2 lines
96 \t%i used L3 lines
97 \ttable size: %ikb\n"
98           len lvl1 lvl2 lvl3 (Ocaml.size_kb d)
99
100         let find t tlist s1 s2 =
101           Cache.Lvl3.find t
102             (Uid.to_int tlist.Translist.Node.id)
103             (Uid.to_int s1.StateSet.Node.id)
104             (Uid.to_int s2.StateSet.Node.id)
105
106         let add t tlist s1 s2 v =
107           Cache.Lvl3.add t
108             (Uid.to_int tlist.Translist.Node.id)
109             (Uid.to_int s1.StateSet.Node.id)
110             (Uid.to_int s2.StateSet.Node.id)
111             v
112
113         let compile auto trl s1 s2 =
114           let orig_s1, orig_s2 =
115             Translist.fold (fun t (a1, a2) ->
116                           let _, _, _, f = Transition.node t in
117                           let (_, _, fs1), (_, _, fs2) = Formula.st f in
118                             (StateSet.union s1 fs1, StateSet.union s2 fs2)
119                        ) trl (StateSet.empty, StateSet.empty)
120           in
121           let ns1 = StateSet.inter s1 orig_s1
122           and ns2 = StateSet.inter s2 orig_s2 in
123           let res, ops, todo = eval_trans auto ns1 ns2 trl in
124           let code, not_marking = ResJIT.compile ops in
125           let todo_code, todo_notmarking =
126             List.fold_left (fun (l, b) (p, q, o) -> let c, b' = ResJIT.compile o in
127                                          (p, q, c)::l, b && b')
128               ([], not_marking) todo
129           in
130           let opcode = res, code, todo_notmarking, todo_code in
131           opcode
132
133         let gen_code auto tlist s1 s2 =
134           let res, code, not_marking, todo_code = compile auto tlist s1 s2 in
135           let f =
136             if todo_code == [] then
137               if not_marking then begin fun empty_slot sl1 sl2 _ node ->
138                 let slot1_empty = sl1 == empty_slot
139                 and slot2_empty = sl2 == empty_slot in
140                 if slot1_empty && slot2_empty then res,sl2
141                 else
142                   let sl =
143                     if slot2_empty then
144                       if slot1_empty then
145                         Array.copy empty_slot
146                       else sl1
147                     else sl2
148                   in
149                   U.exec sl sl1 sl2 node code;
150                   res, sl
151               end
152               else (* marking *) begin fun empty_slot sl1 sl2 _ node ->
153                 let sl =
154                   if sl2 == empty_slot  then
155                     if sl1 == empty_slot then
156                       Array.copy empty_slot
157                     else sl1
158                   else sl2
159                 in
160                 U.exec sl sl1 sl2 node code;
161                 res, sl
162               end
163               else (* todo != [] *)
164               begin fun empty_slot sl1 sl2 tree node ->
165                 let sl =
166                   if sl2 == empty_slot  then
167                     if sl1 == empty_slot then
168                       Array.copy empty_slot
169                     else sl1
170                   else sl2
171                 in
172                 U.exec sl sl1 sl2 node code;
173                 List.fold_left
174                   (fun ares (p, q, code) ->
175                     if !p tree node then begin
176                       if code != ResJIT.Nil then U.exec sl sl1 sl2 node code;
177                       StateSet.add q ares
178                     end
179                     else ares) res todo_code, sl
180
181               end
182           in
183           f
184
185         let cache_apply cache auto tlist s1 s2 =
186           let f = gen_code auto tlist s1 s2 in
187           add cache tlist s1 s2 f; f
188       end
189
190 DEFINE LOOP (t, states, ctx) = (
191   let _t = (t) in
192   if _t == Tree.nil then nil_res
193   else
194     let tag = Tree.tag tree _t in
195       l2jit_dispatch
196         _t tag (states) (ctx) (L2JIT.find cache2 tag (states))
197 )
198
199 DEFINE LOOP_TAG (t, states, tag, ctx) = (
200   let _t = (t) in (* to avoid duplicating expression t *)
201   if _t == Tree.nil then nil_res
202   else
203     l2jit_dispatch
204       _t (tag) (states) (ctx) (L2JIT.find cache2 (tag) (states)))
205
206     let top_down_run auto tree root states ctx =
207       let res_len = (StateSet.max_elt auto.states) + 1 in
208       let empty_slot = Array.create res_len U.NS.empty in
209       let nil_res = auto.bottom_states, empty_slot in
210       let cache3 = L3JIT.create () in
211
212       let l3jit_dispatch trl s1 s2 t sl1 sl2 =
213         let f = L3JIT.find cache3 trl s1 s2 in
214         if f == L3JIT.dummy then (L3JIT.cache_apply cache3 auto trl s1 s2) empty_slot sl1 sl2 tree t
215         else f empty_slot sl1 sl2 tree t
216
217       in
218       let cache2 = L2JIT.create () in
219
220       let () = D_TRACE_(at_exit (fun () -> L2JIT.stats Format.err_formatter cache2)) in
221
222       let rec l2jit_dispatch t tag states ctx opcode =
223         match opcode with
224           | L2JIT.RETURN () -> nil_res
225           | L2JIT.CACHE () ->
226               let opcode = L2JIT.compile cache2 auto tree tag states in
227                 l2jit_dispatch t tag states ctx opcode
228
229           | L2JIT.LEFT (tr_list, instr) ->
230               let res1, slot1 =
231                 l2jit_dispatch_instr t tag states (Tree.closing tree t) instr true
232               in
233                 l3jit_dispatch tr_list res1 auto.bottom_states t slot1 empty_slot
234
235           | L2JIT.RIGHT (tr_list, instr) ->
236             let res2, slot2 = l2jit_dispatch_instr t tag states ctx instr false in
237               l3jit_dispatch tr_list auto.bottom_states res2 t empty_slot slot2
238
239           | L2JIT.BOTH (tr_list, instr1, instr2) ->
240               let res1, slot1 =
241                 l2jit_dispatch_instr t tag states (Tree.closing tree t) instr1 true
242               in
243               let res2, slot2 = l2jit_dispatch_instr t tag states ctx instr2 false in
244                 l3jit_dispatch tr_list res1 res2 t slot1 slot2
245
246     and l2jit_dispatch_instr t tag states ctx instr _left =
247       match instr with
248         | L2JIT.NOP () -> nil_res
249         | L2JIT.FIRST_CHILD s -> LOOP ((Tree.first_child tree t), s, ctx)
250         | L2JIT.NEXT_SIBLING s -> LOOP ((Tree.next_sibling tree t), s, ctx)
251
252         | L2JIT.FIRST_ELEMENT s -> LOOP ((Tree.first_element tree t), s, ctx)
253         | L2JIT.NEXT_ELEMENT s -> LOOP ((Tree.next_element tree t), s, ctx)
254
255         | L2JIT.TAGGED_DESCENDANT (s, tag) ->
256             LOOP_TAG ((Tree.tagged_descendant tree t tag), s, tag, ctx)
257
258         | L2JIT.TAGGED_FOLLOWING (s, tag) ->
259             LOOP_TAG((Tree.tagged_following_before tree t tag ctx), s, tag, ctx)
260
261         | L2JIT.SELECT_DESCENDANT (s, _, us) ->
262             LOOP((Tree.select_descendant tree t us), s, ctx)
263
264         | L2JIT.SELECT_FOLLOWING (s, pt, us) ->
265             LOOP ((Tree.select_following_before tree t us ctx), s, ctx)
266
267         | L2JIT.TAGGED_CHILD (s, tag) ->
268             LOOP_TAG((Tree.tagged_child tree t tag), s, tag, ctx)
269
270         | L2JIT.TAGGED_FOLLOWING_SIBLING (s, tag) ->
271             LOOP_TAG((Tree.tagged_following_sibling tree t tag), s, tag, ctx)
272
273         | L2JIT.SELECT_CHILD (s, _, us) ->
274             LOOP ((Tree.select_child tree t us), s, ctx)
275
276         | L2JIT.SELECT_FOLLOWING_SIBLING (s, _, us) ->
277             LOOP ((Tree.select_following_sibling tree t us), s, ctx)
278
279         | L2JIT.TAGGED_SUBTREE(s, tag) ->
280
281           let count = U.NS.subtree_tags tree t tag in
282                 if count != U.NS.empty then
283                   let r = Array.copy empty_slot in
284                     r.(auto.last) <- count;
285                     s,r
286                 else
287                   s,empty_slot
288
289         | L2JIT.ELEMENT_SUBTREE(s) ->
290
291               let count = U.NS.subtree_elements tree t in
292                 if count != U.NS.empty then
293                   let r = Array.copy empty_slot in
294                     r.(auto.last) <- count;
295                     s,r
296                 else
297                   s,empty_slot
298
299     in
300       LOOP (root, states, ctx)
301
302     let full_top_down_run auto states tree root =
303       (*Ata.init (); *)
304       top_down_run auto tree root states (Tree.closing tree root)
305
306     let top_down_run auto tree root =
307       (*Ata.init (); *)
308       let res, slot = full_top_down_run auto auto.init tree root in
309       slot.(StateSet.min_elt auto.topdown_marking_states)
310
311
312     (*** Bottom-up evaluation function **)
313
314     let ns_print fmt t =
315       Format.fprintf fmt "{ ";
316       U.NS.iter begin fun node ->
317         Format.fprintf fmt "%a " Node.print node;
318       end t;
319       Format.fprintf fmt "}"
320
321     let slot_print fmt t =
322       Array.iteri begin fun state ns ->
323         Format.eprintf "%a -> %a\n" State.print state ns_print ns;
324       end t
325
326
327     let eval_trans auto tree parent res1 res2 = assert false
328
329
330     let bottom_up_run auto tree (query, pat) =
331       let leaves = Array.to_list (Tree.full_text_query query tree pat) in
332       let states = auto.states in
333       let res_len = (StateSet.max_elt states) + 1 in
334       let empty_slot = Array.create res_len U.NS.empty in
335       let nil_res = auto.bottom_states, empty_slot in
336       let cache = Cache.Lvl3.create 1024 L3JIT.dummy in
337       let rec loop_leaves l acc =
338         match l with
339             [] -> acc
340           | node :: ll ->
341             let res, lll = bottom_up_next node ll Tree.nil in
342             if (lll <> []) then Printf.eprintf "Leftover elements\n%!";
343             res
344
345       and bottom_up_next node rest stop =
346         let fs = Tree.first_child tree node in
347         let res1 =
348           if fs == Tree.nil then nil_res
349           else full_top_down_run auto states tree fs
350         in
351         move_up node res1 true rest stop
352
353       and move_up node res is_left rest stop =
354         if node == stop then res, rest
355         else
356           let prev_sibling = Tree.prev_sibling tree node in
357           let is_left' = prev_sibling == Tree.nil in
358           let real_parent = Tree.parent tree node in
359           let parent =
360             if is_left' then real_parent else max (Tree.first_child tree real_parent) stop
361           in
362           (* let parent = if is_left' then Tree.parent tree node else prev_sibling in *)
363           let (s1, sl1), (s2, sl2), rest' =
364             if is_left then match rest with
365                 [] -> res, nil_res, rest
366               | next :: rest' ->
367                 if Tree.is_right_descendant tree node next
368                 then
369                   let res2, rest' = bottom_up_next next rest' node in
370                   res, res2, rest'
371                 else res, nil_res, rest
372             else
373               nil_res, res, rest
374           in
375           let tag = Tree.tag tree node in
376           let id1 = Uid.to_int s1.StateSet.Node.id in
377           let id2 = Uid.to_int s2.StateSet.Node.id in
378           let code =
379             let code = Cache.Lvl3.find cache tag id1 id2 in
380             if code == L3JIT.dummy then
381               let trl =
382                 StateSet.fold
383                   (fun q acc ->
384                     List.fold_left (fun acc' (labels, tr) ->
385                       if labels == TagSet.any || TagSet.mem tag labels
386                       then Translist.cons tr acc' else acc')
387                       acc
388                       (Hashtbl.find auto.trans q)
389                   )
390                   states
391                   Translist.nil
392               in
393               let code = L3JIT.gen_code auto trl s1 s2 in
394               Cache.Lvl3.add cache tag id1 id2 code; code
395             else code
396           in
397           let res' = code empty_slot sl1 sl2 tree node in
398           move_up parent res' is_left' rest' stop
399       in
400       let _, slot = loop_leaves leaves (nil_res) in
401       slot.(StateSet.min_elt auto.topdown_marking_states)
402
403
404   end
405