xia_1.4.0_b16bb5ce/src/mckae-xml-xpath-xia_worker.adb

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
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
620
621
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
-------------------------------------------------------------------------------
--                                                                           --
--            XPATH IN ADA Copyright (C) 2003, McKae Technologies            --
--     XPATH IN ADA Copyright (C) 2021, Simon Wright <simon@pushface.org>    --
--                                                                           --
--  XPath in  Ada (XIA) is  free software;  you can redistribute  it and/or  --
--  modify it under terms of the GNU General Public License as published by  --
--  the Free Software Foundation; either version 3, or (at your option) any  --
--  later version.  GNAT is distributed in the hope that it will be useful,  --
--  but  WITHOUT  ANY  WARRANTY;  without  even  the  implied  warranty  of  --
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                     --
--                                                                           --
--  As  a special  exception under  Section  7 of  GPL version  3, you  are  --
--  granted  additional permissions  described in  the GCC  Runtime Library  --
--  Exception, version 3.1, as published by the Free Software Foundation.    --
--                                                                           --
--  You should have received a copy of the GNU General Public License and a  --
--  copy of the GCC Runtime Library  Exception along with this program; see  --
--  the  files  COPYING3 and  COPYING.RUNTIME  respectively.   If not,  see  --
--  <http://www.gnu.org/licenses/>.                                          --
--                                                                           --
--  XIA is maintained at https://github.com/simonjwright/xia                 --
--                                                                           --
-------------------------------------------------------------------------------

with Ada.Containers.Ordered_Maps;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;

with Dom.Core.Append_Node;
with Dom.Core.Nodes;

with Mckae.Xml.Xpath.Locations;
with Mckae.Xml.Xpath.Node_Sets;
with Mckae.XML.XPath.Predicates;
with Mckae.XML.XPath.Predicates.Evaluation;
with McKae.XML.XPath.Query_Handling;

with Xpath_Model;
with Xpath_Parser;

with Ada.Text_IO;

package body Mckae.XML.XPath.XIA_Worker is

   use Ada.Strings;
   use Ada.Strings.Fixed;
   use Ada.Strings.Unbounded;
   use Dom.Core;
   use Dom.Core.Nodes;
   use Mckae.Xml.Xpath.Locations;

   -------------------------------------------------------------------
   --  Local specs

   --  This is used to obtain the set of matching nodes in document
   --  order.
   package Sortable_Matching_Tree
   is new Ada.Containers.Ordered_Maps (Key_Type     => Unbounded_String,
                                       Element_Type => DOM.Core.Node);

   -------------------------------------------------------------------

   procedure Get_Index_And_List (Of_Node : in     Node;
                                 Index   :    out Natural;
                                 List    :    out Node_List);

   --  Search for a '|' in the string, which signifies the separator
   --  between queries being unioned together.  However, beware such
   --  vertical bars embedded in strings and predicates.
   function Query_Separator_Index(S : String) return Natural;

   --  Apply the Step's Predicates to Matchings, removing any entries
   --  that don't pass.
   procedure Predicate_Filtration (Matchings     : in out Node_Sets.Set;
                                   Location_Step : in     Location_Steps);

   function Is_Node_Match (N  : Node; Ls : Location_Steps) return Boolean;

   --  Apply Location_Step to N, appending any resulting nodes to
   --  Matchings.
   --  Attr_Parent is a workround for an XML/Ada feature: the parent of
   --  an attribute node isn't available.
   procedure Do_Matching (N             : in     Node;
                          Location_Step : in     Location_Steps;
                          Matchings     : in out Node_Sets.Set;
                          Attr_Parent   : in     Node := null);

   --  If Include_Self is True, process N; in any case, process all
   --  the descendats of N, and their descendants, all the way down.
   procedure Descendant_Traversal (N             : in     Node;
                                   Deferred_Step : in     Location_Steps;
                                   Location_Step : in     Location_Steps;
                                   Matchings     : in out Node_Sets.Set;
                                   Include_Self  : in     Boolean := True);

   --  Process the rest of the nodes in this list and their
   --  descendants, then go to the parent and process all its
   --  subsequent nodes
   procedure Following_Traversal (N             : in     Node;
                                  Deferred_Step : in     Location_Steps;
                                  Location_Step : in     Location_Steps;
                                  Matchings     : in out Node_Sets.Set);

   --  Process the previous of the nodes in this list and their
   --  descendants, then go to the parent and process all its
   --  preceding nodes
   procedure Preceding_Traversal (N             : in     Node;
                                  Deferred_Step : in     Location_Steps;
                                  Location_Step : in     Location_Steps;
                                  Matchings     : in out Node_Sets.Set);

   --  Decide whether to pursue the descendant or self axis, the
   --  following axis, or the preceding axis.
   procedure Deferred_Traversal
     (Location_Step : in     Location_Steps;
      Match         : in     Node_Sets.Current_Matchings;
      Matchings     : in out Node_Sets.Set);

   --  ? XXX
   procedure Do_Final_Traversal (N             : in     Node;
                                 Location_Step : in     Location_Steps;
                                 Matchings     : in out Node_Sets.Set;
                                 Include_Self  : in     Boolean := True);

   --  Apply the Step to each node in Matchings, then overwrite Matchings
   --  with the new set.
   procedure Extract_Nodes (Location_Step : in     Location_Steps;
                            Matchings     : in out Node_Sets.Set);

   --  Split XPath into Location_Steps, then apply each successively to
   --  Matchings, overwriting Matchings with the resultant set.
   procedure Evaluate_Location_Path (XPath     : in     String;
                                     Matchings : in out Node_Sets.Set);

   --  Use the node's position in the DOM to make a unique sort key.
   --  The 5th node will have key          000000000000000005
   --  Its 3rd child will have key         000000000000000005000003
   --  That node's 1st child will have key 000000000000000005000003000001
   --  etc.
   --  (the first 5 zeros correspond to the root node)
   function Create_Node_Key (For_Node : Node) return Unbounded_String;

   --  Do an in-order traversal of M to get the nodes back in document
   --  order, and output them to Nodes..
   procedure Output_Nodes (M     : in     Sortable_Matching_Tree.Map;
                           Nodes :    out Node_List);

   --  Iterate through the set of Matchings, sorting them into
   --  document order and returning them as a Node_List.
   procedure Finalize_Matchings (Matchings   : in     Node_Sets.Set;
                                 Xpath_Nodes :    out Node_List);

   -------------------------------------------------------------------

   procedure Get_Index_And_List (Of_Node : in     Node;
                                 Index   :    out Natural;
                                 List    :    out Node_List) is
      P : Node := Parent_Node(Of_Node);

   begin
      Index := 0;
      if P /= null then
         List := Child_Nodes(P);
         for I in 1 .. Length(List) loop
            Index := I - 1;
            exit when Of_Node = Item(List, Index);
         end loop;
      end if;
   end Get_Index_And_List;

   -------------------------------------------------------------------

   function Query_Separator_Index(S : String) return Natural is

      --  Search for a '|' in the string, which signifies the separator
      --  between queries being unioned together.  However, beware
      --  such vertical bars embedded in strings and predicates.

      End_Quote   : Character := '"';
      End_Predicate : constant Character := ']';
      Quoting     : Boolean := False;
      Predicating : Boolean := False;

   begin
      for I in S'Range loop
         if Quoting then
            -- Ignore everything other than the match close quote character
            Quoting := S(I) /= End_Quote;
         elsif Predicating then
            -- Ignore everything until the predicate's end bracket
            Predicating := S(I) /= End_Predicate;
            if S(I) = ''' then
               End_Quote := ''';
               Quoting := True;
            elsif S(I) = '"' then
               End_Quote := '"';
               Quoting := True;
            end if;
         else
            -- Could be anything, check to see if it's special.  If
            --  not signaling the start of a quote or predicate, just
            --  keep on going.
            if S(I) = ''' then
               End_Quote := ''';
               Quoting := True;
            elsif S(I) = '"' then
               End_Quote := '"';
               Quoting := True;
            elsif S(I) = '[' then
               Predicating := True;
            elsif S(I) = '|' then
               return I;
            end if;
         end if;
      end loop;
      return 0;
   end Query_Separator_Index;

   -------------------------------------------------------------------

   procedure Predicate_Filtration (Matchings     : in out Node_Sets.Set;
                                   Location_Step : in     Location_Steps) is
   begin
      Predicates.Evaluation.Evaluate_Predicate
        (Matchings, Location_Step.Location_Predicates, Location_Step.Axis);
   exception
      when Predicates.Malformed_Predicate =>
         raise Malformed_Xpath;
   end Predicate_Filtration;

   -------------------------------------------------------------------

   function Is_Node_Match (N  : Node;
                           Ls : Location_Steps)
                          return Boolean is

      use type Predicates.Predicate_List;

      NT    : Node_Test_Specification := Ls.Node_Test;
      Match : Boolean := False;

   begin
      case NT.Node_Test is
         when Node_Node_Test =>
            -- Matches anything
            Match := True;

         when NCName_Node_Test =>
            Match := (((N.Node_Type = Element_Node) or (N.Node_Type = Attribute_Node))
                       and (NT.Name = "*"))
                      or (NT.Name = Node_Name(N));

         when QName_Node_Test =>
            Match := ((NT.Prefix = "*") and ((NT.Name = "*") or (NT.Name = Prefix(N))))
              or
              ((NT.Name = "*") and ((NT.Prefix = "*") or (NT.Prefix = Local_Name(N))))
              or
              ((NT.Prefix = Prefix(N)) and (NT.Name = Local_Name(N)));

         when Text_Node_Test =>
            Match := N.Node_Type = Text_Node;

         when Comment_Node_Test =>
            Match := N.Node_Type = Comment_Node;

         when Processing_Instruction_Node_Test =>
            Match := (N.Node_Type = Processing_Instruction_Node)
              and NT.Name = Node_Value(N);

         when Expression_Node_Test =>
            Match := True;

         when No_Node_Test =>
            pragma Assert (False);
            null;

      end case;

      return Match;
   end Is_Node_Match;

   -------------------------------------------------------------------

   procedure Do_Matching (N             : in     Node;
                          Location_Step : in     Location_Steps;
                          Matchings     : in out Node_Sets.Set;
                          Attr_Parent   : in     Node := null) is

      Ancestor : Node;
      Child    : Node;
      Children : Node_List;
      N_Index  : Natural;
      Attr     : Node;
      Attrs    : Named_Node_Map;

      use Node_Sets;

      -- This function masks the DOM.Core.Parent_Node function so as
      --  to work around its bug when it comes to returning the parent
      --  of attribute nodes
      function Parent_Node(N : in Node) return Node is
      begin
         if Attr_Parent = null then
            -- No attribute parent node was provided, so the node was
            --  not an attribute
            return DOM.Core.Nodes.Parent_Node(N);
         else
            return Attr_Parent;
         end if;
      end Parent_Node;

   begin

      -- The first set of axes is for those for which an immediate
      --  determination of node matching is made.
      case Location_Step.Axis is
         when Child_Axis =>
            -- Check to see if any of the children match
            Children := Child_Nodes(N);
            for I in 1 .. Length(Children) loop
               Child := Item(Children, I - 1);
               if Is_Node_Match(Child, Location_Step) then
                  Matchings.Append ((Self_Axis, Child));
               end if;
            end loop;

         when Following_Sibling_Axis =>
            Get_Index_And_List(N, N_Index, Children);
            for I in N_Index + 1 .. Length(Children) - 1 loop
               Child := Item(Children, I);
               if Is_Node_Match(Child, Location_Step) then
                  Matchings.Append ((Self_Axis, Child));
               end if;
            end loop;

         when Preceding_Sibling_Axis =>
            Get_Index_And_List(N, N_Index, Children);
            for I in 0 .. N_Index - 1 loop
               Child := Item(Children, I);
               if Is_Node_Match(Child, Location_Step) then
                  Matchings.Append ((Self_Axis, Child));
               end if;
            end loop;

         when Self_Axis | Parent_Axis =>
            -- Get the starting node for the upwards traversal
            if Location_Step.Axis = Parent_Axis then
               Ancestor := Parent_Node(N);

            else
               Ancestor := N;
            end if;

            -- Check the node for a match
            if (Ancestor /= null)
              and then Is_Node_Match(Ancestor, Location_Step) then
               Matchings.Append ((Self_Axis, Ancestor));
            end if;

         when Ancestor_Axis | Ancestor_Or_Self_Axis =>
            -- Get the starting node for the upwards traversal
            if Location_Step.Axis = Ancestor_Axis then
               Ancestor := Parent_Node(N);
            else
               Ancestor := N;  -- I am my mother :-)
            end if;

            -- Any matches in the ancestor chain?
            loop
               exit when Ancestor = null;
               if Is_Node_Match(Ancestor, Location_Step) then
                  Matchings.Insert ((Self_Axis, Ancestor));
               end if;
               Ancestor := Parent_Node(Ancestor);
            end loop;

         when Attribute_Axis =>
            Attrs := Attributes(N);
            for I in 1 .. Length(Attrs) loop
               Attr := Item(Attrs, I - 1);
               if Is_Node_Match(Attr, Location_Step) then
                  Matchings.Append ((Attribute_Axis,
                                     Attr,
                                     Owner_Node => N,
                                     Attr_Index => I));
               end if;
            end loop;

            -- The tests for the remaining axes is deferred
            --  until they can be done in conjunction with the
            --  next path step

         when Branched_Axes =>
            if not Location_Step.Output_Step then
               declare
                  Deferred_Match : Node_Sets.Current_Matchings(Location_Step.Axis);
               begin
                  Deferred_Match.Matching_Node := N;
                  Deferred_Match.Branch_Step := Location_Step;
                  Matchings.Append (Deferred_Match);
               end;
            else
               Do_Final_Traversal(N, Location_Step, Matchings,
                                  Location_Step.Axis = Descendant_Or_Self_Axis);
            end if;

         when Namespace_Axis =>
            pragma Assert(False);
            null;  -- TBD
      end case;
   end Do_Matching;

   -------------------------------------------------------------------

   procedure Descendant_Traversal (N             : in     Node;
                                   Deferred_Step : in     Location_Steps;
                                   Location_Step : in     Location_Steps;
                                   Matchings     : in out Node_Sets.Set;
                                   Include_Self  : in     Boolean := True) is
      Children : Node_List;
      Child    : Node;

   begin
      -- This node matches the original traversal-requiring match, now
      --  check the next location step
      if Include_Self and Is_Node_Match(N, Deferred_Step) then
         Do_Matching(N, Location_Step, Matchings);
      end if;

      -- Process the child nodes
      Children := Child_Nodes(N);
      for I in 1 .. Length(Children) loop
         Child := Item(Children, I - 1);
         Descendant_Traversal(Child, Deferred_Step, Location_Step, Matchings);
      end loop;
   end Descendant_Traversal;

   -------------------------------------------------------------------

   procedure Following_Traversal (N             : in     Node;
                                  Deferred_Step : in     Location_Steps;
                                  Location_Step : in     Location_Steps;
                                  Matchings     : in out Node_Sets.Set) is

      --  Process the rest of the nodes in this list and their
      --  descendants, then go to the parent and process all its
      --  subsequent nodes

      This_List : Node_List;
      N_Index   : Natural;

   begin
      if N /= null then
         Get_Index_And_List(N, N_Index, This_List);

         -- Process the following siblings and all descendants
         for I in N_Index + 1 .. Length(This_List) - 1 loop
            Descendant_Traversal(Item(This_List, I), Deferred_Step, Location_Step, Matchings);
         end loop;

         -- Now go to the parent
         Following_Traversal(Parent_Node(N), Deferred_Step, Location_Step, Matchings);
      end if;
   end Following_Traversal;

   -------------------------------------------------------------------

   procedure Preceding_Traversal (N             : in     Node;
                                  Deferred_Step : in     Location_Steps;
                                  Location_Step : in     Location_Steps;
                                  Matchings     : in out Node_Sets.Set) is
      --  Process the previous of the nodes in this list and their
      --  descendants, then go to the parent and process all its
      --  preceding nodes

      This_List : Node_List;
      N_Index   : Natural;

   begin
      if N /= null then
         Get_Index_And_List(N, N_Index, This_List);

         -- Process the preceding siblings and all descendants
         for I in 0 .. N_Index - 1 loop
            Descendant_Traversal(Item(This_List, I), Deferred_Step, Location_Step, Matchings);
         end loop;

         -- Now go to the parent
         Preceding_Traversal(Parent_Node(N), Deferred_Step, Location_Step, Matchings);
      end if;
   end Preceding_Traversal;

   -------------------------------------------------------------------

   procedure Deferred_Traversal
     (Location_Step : in     Location_Steps;
      Match         : in     Node_Sets.Current_Matchings;
      Matchings     : in out Node_Sets.Set) is
   begin
      case Match.Branch_Step.Axis is
         when Descendant_Or_Self_Axis |
           Descendant_Axis =>
            Descendant_Traversal(Match.Matching_Node,
                                 Match.Branch_Step,
                                 Location_Step,
                                 Matchings,
                                 Match.Branch_Step.Axis = Descendant_Or_Self_Axis);

         when Following_Axis =>
            Following_Traversal(Match.Matching_Node,
                                Match.Branch_Step,
                                Location_Step,
                                Matchings);

         when Preceding_Axis =>
            Preceding_Traversal(Match.Matching_Node,
                                Match.Branch_Step,
                                Location_Step,
                                Matchings);

         when others =>
            pragma Assert(False);
            null;
      end case;
   end Deferred_Traversal;

   -------------------------------------------------------------------

   procedure Do_Final_Traversal (N             : in     Node;
                                 Location_Step : in     Location_Steps;
                                 Matchings     : in out Node_Sets.Set;
                                 Include_Self  : in     Boolean := True) is
      Children : Node_List;
      Child    : Node;
      Siblings : Node_List;
      N_Index  : Natural;

      Mod_Step : Location_Steps := Location_Step;

   begin
      case Location_Step.Axis is
         when Descendant_Or_Self_Axis |
           Descendant_Axis =>
            -- This node matches the original traversal-requiring match, now
            --  check the next location step
            if Include_Self and Is_Node_Match(N, Location_Step) then
               Matchings.Append ((Self_Axis, N));
            end if;

            -- Process the child nodes
            Children := Child_Nodes(N);
            for I in 1 .. Length(Children) loop
               Child := Item(Children, I - 1);
               Do_Final_Traversal(Child, Location_Step, Matchings);
            end loop;

         when Following_Axis =>
            if N /= null then
               Get_Index_And_List(N, N_Index, Siblings);
               Mod_Step.Axis := Descendant_Axis;

               -- Process the following siblings and all descendants
               for I in N_Index + 1 .. Length(Siblings) - 1 loop
                  Child := Item(Siblings, I);
                  Do_Final_Traversal(Child, Mod_Step, Matchings);
               end loop;

               Do_Final_Traversal(Parent_Node(N), Location_Step, Matchings, Include_Self => False);
            end if;

         when Preceding_Axis =>
            if N /= null then
               Get_Index_And_List(N, N_Index, Siblings);
               Mod_Step.Axis := Descendant_Axis;

               -- Process the preceding siblings and all descendants
               for I in 0 .. N_Index - 1 loop
                  Child := Item(Siblings, I);
                  Do_Final_Traversal(Child, Mod_Step, Matchings);
               end loop;

               Do_Final_Traversal(Parent_Node(N), Location_Step, Matchings, Include_Self => False);
            end if;

         when others =>
            pragma Assert(False);
            null;
      end case;
   end Do_Final_Traversal;

   -------------------------------------------------------------------

   procedure Extract_Nodes (Location_Step : in     Location_Steps;
                            Matchings     : in out Node_Sets.Set) is

      Match         : Node_Sets.Current_Matchings;
      New_Matchings : Node_Sets.Set;
      Cursor        : Node_Sets.Cursor := Matchings.First;

      use type Node_Sets.Cursor;
      use type Predicates.Predicate_List;

   begin
      if Location_Step.Node_Test.Node_Test = Expression_Node_Test
      then
         --  Check the predicate criteria for all the input nodes together
         if Location_Step.Location_Predicates /= Predicates.Null_Predicate
         then
            Predicate_Filtration (Matchings, Location_Step);
         end if;
      else
         --  Iterate through the current set of matchings, evaluating each
         --  against the path step
         Input_Nodes_Loop :
         while Cursor /= Node_Sets.No_Element loop
            One_Node :
            declare
               Step_Matchings : Node_Sets.Set;
            begin
               Match := Node_Sets.Element (Cursor);

               -- Check whether this is a direct node check, or a
               -- deferred traversal
               if Match.Axis = Self_Axis then
                  Do_Matching (Match.Matching_Node,
                               Location_Step,
                               Step_Matchings);

               elsif Match.Axis = Attribute_Axis then
                  -- This is a workaround for an XML/Ada bug wherein
                  --  invoking Parent_Node() on an attribute node returns
                  --  null instead of its parent.
                  Do_Matching (Match.Matching_Node,
                               Location_Step,
                               Step_Matchings,
                               Match.Owner_Node);

               else
                  -- A deferred traversal
                  Deferred_Traversal (Location_Step, Match, Step_Matchings);
               end if;

               -- Now check the predicate criteria for the nodes selected for
               -- this input node by this location path
               if Location_Step.Location_Predicates /= Predicates.Null_Predicate
               then
                  Predicate_Filtration (Step_Matchings, Location_Step);
               end if;

               --  incorporate survivors in the result
               New_Matchings.Union (Step_Matchings);

            end One_Node;

            Node_Sets.Next (Cursor);
         end loop Input_Nodes_Loop;

         Matchings := New_Matchings;
      end if;
   exception
      when Xpath_Parser.Syntax_Error =>
         raise Malformed_XPath;
   end Extract_Nodes;

   -------------------------------------------------------------------

   procedure Evaluate_Location_Path (XPath     : in     String;
                                     Matchings : in out Node_Sets.Set)
   is
      Query : String := Trim (XPath, Both);

      Location_Steps : Location_Paths;
   begin
      -- Split up the location path into discrete steps
      Location_Steps := Query_Handling.Pathify (Query);

      pragma Debug
        (Ada.Text_IO.Put_Line (Image (Location_Steps)));

      for P of Location_Steps.Path loop

         Extract_Nodes (P, Matchings);

         exit when Matchings.Is_Empty;
      end loop;

      Free (Location_Steps);
   exception
      when Query_Handling.Malformed_Query =>
         raise Malformed_XPath;
   end Evaluate_Location_Path;

   -------------------------------------------------------------------

   function Create_Node_Key (For_Node : Node) return Unbounded_String
   is

      This_List  : Node_List;
      Index      : Natural;
      Parent     : Node;

      Result : Unbounded_String;

   begin
      Get_Index_And_List(For_Node, Index, This_List);

      Parent := Parent_Node (For_Node);
      if Parent /= null then
         Result := Create_Node_Key (For_Node => Parent);
      end if;

      declare
         Zeroed_Index : constant Natural := Index + 1000000;
         Index_Img : constant String := Natural'Image(Zeroed_Index);
      begin
         Append (Result, Index_Img(3 .. Index_Img'Last));
      end;
      return Result;
   end Create_Node_Key;

   -------------------------------------------------------------------

   procedure Output_Nodes (M     : in     Sortable_Matching_Tree.Map;
                           Nodes :    out Node_List)
   is
      procedure Output_Node (Position : in Sortable_Matching_Tree.Cursor)
      is
      begin
         Dom.Core.Append_Node (Nodes,
                               Sortable_Matching_Tree.Element (Position));
      end Output_Node;
   begin
      M.Iterate (Process => Output_Node'Access);
   end Output_Nodes;

   -------------------------------------------------------------------

   procedure Finalize_Matchings (Matchings   : in     Node_Sets.Set;
                                 Xpath_Nodes :    out Node_List) is

      Sorting_Tree   : Sortable_Matching_Tree.Map;

      Cursor        : Node_Sets.Cursor := Matchings.First;

      Current       : Node_Sets.Current_Matchings;
      Node_Key      : Unbounded_String;

      Sorted_Results  : Node_List;

      use type Node_Sets.Cursor;
   begin
      -- Perform a tree insertion sort of all the nodes
      while Cursor /= Node_Sets.No_Element loop

         -- Get the matching info for the node
         Current := Node_Sets.Element (Cursor);

         pragma Assert((Current.Axis = Self_Axis)
                       or (Current.Axis = Attribute_Axis));

         if Current.Axis = Attribute_Axis then
            --  Most nodes are simply a node on the DOM tree;
            --  attribute nodes are "special" for some reason, so we
            --  have to go get their owner element specifically.
            --
            --  XXX this may still be an XML/Ada bug; in XML/Ada 1.0,
            --  Attrs.Owner_Element(Current.Matching_Node) didn't
            --  work.
            --
            --  Make the key for the parent ...
            Node_Key := Create_Node_Key (Current.Owner_Node);
            --  ... and append the key for the attribute.
            declare
               Zeroed_Index : constant Natural := Current.Attr_Index + 1000000;
               Index_Img : constant String := Natural'Image(Zeroed_Index);
            begin
               Append (Node_Key, Index_Img(3 .. Index_Img'Last));
            end;
         else
            Node_Key := Create_Node_Key (Current.Matching_Node);
         end if;

         Sorting_Tree.Insert (Node_Key, Current.Matching_Node);

         Node_Sets.Next (Cursor);
      end loop;

      --  All the nodes are now inserted, do an in-order traversal to
      --  get the nodes back in document order, and output them.
      Output_Nodes(Sorting_Tree, XPath_Nodes);
   end Finalize_Matchings;

   -------------------------------------------------------------------

   function XPath_Query
     (N     : Node;
      XPath : String) return Node_List
   is
      Starting_Node : Node := N;
      Xpath_Nodes   : Node_List;

      Start : Natural := 1;
      Split : Natural := 1;
      Query : String := Trim (XPath, Both);

      Matchings : Node_Sets.Set;
      Total_Matchings : Node_Sets.Set;

   begin
      pragma Debug
        (Ada.Text_IO.Put_Line ("q: " & XPath));
      loop

         Matchings.Clear;

         -- The given node is either a document node or an element node
         --  within a document.
         Starting_Node := N;

         if Query (Start) = '/' then
            Starting_Node := Owner_Document(N);
         end if;

         if Starting_Node = null then
            raise Inappropriate_Node;
         end if;

         Matchings.Append ((Self_Axis, Starting_Node));

         --  Process this as a concatenation of queries, i.e.,
         --  different queries separated by '|'.  Watch out for '|'s
         --  embedded in predicates!
         Split := Query_Separator_Index (Query (Start .. Query'Last));

         if Split = 0 then
            Evaluate_Location_Path (Query (Start .. Query'Last), Matchings);
         else
            Evaluate_Location_Path (Query (Start .. Split - 1), Matchings);
         end if;

         -- Merge the distinct sets
         Total_Matchings.Union (Matchings);

         exit when Split = 0;

         Start := Split + 1;
      end loop;

      --  Iterate through the set of matchings, sorting them into
      --  document order and returning them as a Node_List.
      Finalize_Matchings (Total_Matchings, Xpath_Nodes);

      return Xpath_Nodes;
   end XPath_Query;

   -------------------------------------------------------------------

end Mckae.XML.XPath.XIA_Worker;