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