Welcome to mirror list, hosted at ThFree Co, Russian Federation.

QueryMatcher.cs « Dispatcher « ServiceModel « System « System.ServiceModel « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d34430b8733dc0ad20fd023e56c7e49ab6e2c7cf (plain)
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Runtime;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Diagnostics;
    using System.Xml;
    using System.Xml.XPath;
    using System.Xml.Xsl;

    internal enum QueryCompilerFlags
    {
        None = 0x00000000,
        InverseQuery = 0x00000001
    }

    internal struct FilterResult
    {
        QueryProcessor processor;
        bool result;

        internal FilterResult(QueryProcessor processor)
        {
            this.processor = processor;
            this.result = this.processor.Result;
        }

        internal FilterResult(bool result)
        {
            this.processor = null;
            this.result = result;
        }

#if NO
        internal ICollection<MessageFilter> Matches
        {
            get
            {
                return this.processor.ResultSet;
            }            
        }
#endif
        internal QueryProcessor Processor
        {
            get
            {
                return this.processor;
            }
        }

        internal bool Result
        {
            get
            {
                return this.result;
            }
        }

        internal MessageFilter GetSingleMatch()
        {
            Collection<MessageFilter> matches = processor.MatchList;
            MessageFilter match;
            switch (matches.Count)
            {
                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, matches));

                case 0:
                    match = null;
                    break;

                case 1:
                    match = matches[0];
                    break;
            }

            return match;
        }
    }

    // XPathResult.GetResultAsString and XPathResult.GetResultAsBoolean,
    // drive knowledge of TResult into the engine.
    internal class QueryResult<TResult> : IEnumerable<KeyValuePair<MessageQuery, TResult>>
    {
        bool evalBody;
        QueryMatcher matcher;
        Message message;

        internal QueryResult(QueryMatcher matcher, Message message, bool evalBody)
        {
            this.matcher = matcher;
            this.message = message;
            this.evalBody = evalBody;
        }

        public TResult GetSingleResult()
        {
            QueryProcessor processor = this.matcher.CreateProcessor();
            XPathResult result;

            try
            {
                processor.Eval(this.matcher.RootOpcode, this.message, this.evalBody);
            }
            catch (XPathNavigatorException e)
            {
                throw TraceUtility.ThrowHelperError(e.Process(this.matcher.RootOpcode), this.message);
            }
            catch (NavigatorInvalidBodyAccessException e)
            {
                throw TraceUtility.ThrowHelperError(e.Process(this.matcher.RootOpcode), this.message);
            }
            finally
            {
                if (this.evalBody)
                {
                    this.message.Close();
                }

                result = processor.QueryResult;
                this.matcher.ReleaseProcessor(processor);
            }

            if (typeof(TResult) == typeof(XPathResult) || typeof(TResult) == typeof(object))
            {
                return (TResult)(object)result;
            }
            else if (typeof(TResult) == typeof(string))
            {
                return (TResult)(object)result.GetResultAsString();
            }
            else if (typeof(TResult) == typeof(bool))
            {
                return (TResult)(object)result.GetResultAsBoolean();
            }
            else
            {
                throw Fx.AssertAndThrowFatal("unsupported type");
            }
        }

        public IEnumerator<KeyValuePair<MessageQuery, TResult>> GetEnumerator()
        {
            QueryProcessor processor = this.matcher.CreateProcessor();
            Collection<KeyValuePair<MessageQuery, XPathResult>> results =
                new Collection<KeyValuePair<MessageQuery, XPathResult>>();
            processor.ResultSet = results;

            try
            {
                processor.Eval(this.matcher.RootOpcode, this.message, this.evalBody);

                if (typeof(TResult) == typeof(XPathResult))
                {
                    return (IEnumerator<KeyValuePair<MessageQuery, TResult>>)(object)results.GetEnumerator();
                }
                else if (typeof(TResult) == typeof(string) ||
                    typeof(TResult) == typeof(bool) ||
                    typeof(TResult) == typeof(object))
                {
                    Collection<KeyValuePair<MessageQuery, TResult>> typedResults =
                        new Collection<KeyValuePair<MessageQuery, TResult>>();

                    foreach (var result in results)
                    {
                        if (typeof(TResult) == typeof(string))
                        {
                            typedResults.Add(
                                new KeyValuePair<MessageQuery, TResult>(
                                    result.Key, (TResult)(object)result.Value.GetResultAsString()));
                        }
                        else if (typeof(TResult) == typeof(bool))
                        {
                            typedResults.Add(
                                new KeyValuePair<MessageQuery, TResult>(
                                    result.Key, (TResult)(object)result.Value.GetResultAsBoolean()));
                        }
                        else
                        {
                            typedResults.Add(new KeyValuePair<MessageQuery, TResult>(
                                result.Key, (TResult)(object)result.Value));
                        }
                    }

                    return (IEnumerator<KeyValuePair<MessageQuery, TResult>>)typedResults.GetEnumerator();
                }
                else
                {
                    throw Fx.AssertAndThrowFatal("unsupported type");
                }
            }
            catch (XPathNavigatorException e)
            {
                throw TraceUtility.ThrowHelperError(e.Process(this.matcher.RootOpcode), this.message);
            }
            catch (NavigatorInvalidBodyAccessException e)
            {
                throw TraceUtility.ThrowHelperError(e.Process(this.matcher.RootOpcode), this.message);
            }
            finally
            {
                if (this.evalBody)
                {
                    this.message.Close();
                }

                this.matcher.ReleaseProcessor(processor);
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }

    /// <summary>
    /// 
    /// </summary>
    internal abstract class QueryMatcher
    {
        static IFunctionLibrary[] defaultFunctionLibs;  // The set of function libraries that our XPath compiler will link to
        static XPathNavigator fxCompiler;       // fx compiler

        protected int maxNodes;     // Maximum # of nodes that we will process while performing any individual match
        protected Opcode query;     // root opcode - this is where query evaluation starts
        protected int subExprVars;  // the number of subexpr node sequences the processing context must hold

        // Processor Pool
        protected WeakReference processorPool;

        internal class QueryProcessorPool
        {
            QueryProcessor processor;

            internal QueryProcessorPool()
            {
            }

            internal QueryProcessor Pop()
            {
                QueryProcessor p = this.processor;
                if (null != p)
                {
                    this.processor = (QueryProcessor)p.next;
                    p.next = null;
                    return p;
                }
                return null;
            }

            internal void Push(QueryProcessor p)
            {
                p.next = this.processor;
                this.processor = p;
            }
        }

        static QueryMatcher()
        {
            QueryMatcher.defaultFunctionLibs = new IFunctionLibrary[] { new XPathFunctionLibrary() };

            // For some incomprehensible reason, the Framework XPath compiler requires an instance of an XPath navigator
            // to compile an xpath. This compiler uses a dummy xml document to create a navigator
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<a/>");
            QueryMatcher.fxCompiler = doc.CreateNavigator();
        }

        internal QueryMatcher()
        {
            this.maxNodes = int.MaxValue;
            this.query = null;
            this.processorPool = new WeakReference(null);
            this.subExprVars = 0;
        }
#if NO       
        internal QueryMatcher(QueryMatcher matcher)
        {
            this.processorPool = new WeakReference(null); 
            this.maxNodes = matcher.maxNodes;
            this.query = matcher.query;
            this.subExprVars = matcher.subExprVars;
        }
#endif
        internal bool IsCompiled
        {
            get
            {
                return (null != this.query);
            }
        }

        internal int NodeQuota
        {
            get
            {
                return this.maxNodes;
            }
            set
            {
                Fx.Assert(value > 0, "");
                this.maxNodes = value;
            }
        }

        internal Opcode RootOpcode
        {
            get
            {
                return this.query;
            }
        }

        internal int SubExprVarCount
        {
            get
            {
                return this.subExprVars;
            }
        }

        /// <summary>
        /// Compile the given filter to run on an external (fx) xpath engine
        /// </summary>
        internal static OpcodeBlock CompileForExternalEngine(string expression, XmlNamespaceManager namespaces, object item, bool match)
        {
            // Compile...            
            XPathExpression xpathExpr = QueryMatcher.fxCompiler.Compile(expression);

            // Fx will bind prefixes and functions here.
            if (namespaces != null)
            {
                // There's a bug in System.Xml.XPath.  If we pass an XsltContext to SetContext it won't throw if there's
                // an undefined prefix.
                if (namespaces is XsltContext)
                {
                    // Lex the xpath to find all prefixes used
                    XPathLexer lexer = new XPathLexer(expression, false);
                    while (lexer.MoveNext())
                    {
                        string prefix = lexer.Token.Prefix;

                        if (prefix.Length > 0 && namespaces.LookupNamespace(prefix) == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XsltException(SR.GetString(SR.FilterUndefinedPrefix, prefix)));
                        }
                    }
                }

                xpathExpr.SetContext(namespaces);
            }

            //
            // FORCE the function to COMPILE - they won't bind namespaces unless we check the return type
            //
            if (XPathResultType.Error == xpathExpr.ReturnType)
            {
                // This should never be reached.  The above property should throw if there's an error
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XPathException(SR.GetString(SR.FilterCouldNotCompile, expression)));
            }

            OpcodeBlock codeBlock = new OpcodeBlock();
            SingleFxEngineResultOpcode op;

            if (!match)
            {
                op = new QuerySingleFxEngineResultOpcode();
            }
            else
            {
                op = new MatchSingleFxEngineResultOpcode();
            }

            op.XPath = xpathExpr;
            op.Item = item;

            codeBlock.Append(op);
            return codeBlock;
        }

        /// <summary>
        /// Compile the given filter for evaluation using the internal engine. 
        /// </summary>
        /// <param name="flags">Caller customizes optimizations via the flags parameter</param>
        /// <param name="returnType">Every xpath expression has a return type</param>
        /// <returns>The opcode block we execute to evaluate</returns>
        internal static OpcodeBlock CompileForInternalEngine(XPathMessageFilter filter, QueryCompilerFlags flags, IFunctionLibrary[] functionLibs, out ValueDataType returnType)
        {
            return QueryMatcher.CompileForInternalEngine(filter.XPath.Trim(), filter.namespaces, flags, functionLibs, out returnType);
        }

        internal static OpcodeBlock CompileForInternalEngine(string xpath, XmlNamespaceManager nsManager, QueryCompilerFlags flags, IFunctionLibrary[] functionLibs, out ValueDataType returnType)
        {
            OpcodeBlock codeBlock;

            returnType = ValueDataType.None;
            if (0 == xpath.Length)
            {
                // 0 length XPaths always match
                codeBlock = new OpcodeBlock();
                codeBlock.Append(new PushBooleanOpcode(true)); // Always match by pushing true on the eval stack
            }
            else
            {
                // Try to parse the xpath. Bind to default function libraries
                // The parser returns an expression tree
                XPathParser parser = new XPathParser(xpath, nsManager, functionLibs);
                XPathExpr parseTree = parser.Parse();

                if (null == parseTree)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryCompileException(QueryCompileError.CouldNotParseExpression));
                }

                returnType = parseTree.ReturnType;

                // Compile the expression tree
                XPathCompiler compiler = new XPathCompiler(flags);

                codeBlock = compiler.Compile(parseTree);
            }

            return codeBlock;
        }

        internal static OpcodeBlock CompileForInternalEngine(string xpath, XmlNamespaceManager ns, QueryCompilerFlags flags, out ValueDataType returnType)
        {
            return QueryMatcher.CompileForInternalEngine(xpath, ns, flags, QueryMatcher.defaultFunctionLibs, out returnType);
        }

        internal SeekableXPathNavigator CreateMessageNavigator(Message message, bool matchBody)
        {
            SeekableXPathNavigator nav = message.GetNavigator(matchBody, this.maxNodes);

            // Position the navigator at the root element
            // This allows a caller to run relative XPaths on message
            nav.MoveToRoot();
            return nav;
        }

        /// <summary>
        /// Checks the context pool for a generic navigator first. If none is available, creates a new one
        /// </summary>
        internal SeekableXPathNavigator CreateSeekableNavigator(XPathNavigator navigator)
        {
            return new GenericSeekableNavigator(navigator);
        }

        internal SeekableXPathNavigator CreateSafeNavigator(SeekableXPathNavigator navigator)
        {
            INodeCounter counter = navigator as INodeCounter;
            if (counter != null)
            {
                counter.CounterMarker = this.maxNodes;
                counter.MaxCounter = this.maxNodes;
            }
            else
            {
                navigator = new SafeSeekableNavigator(navigator, this.maxNodes);
            }
            return navigator;
        }

        /// <summary>
        /// Checks the context pool for a processor first. If none is available, creates a new one
        /// </summary>
        internal QueryProcessor CreateProcessor()
        {
            QueryProcessor p = null;

            lock (this.processorPool)
            {
                QueryProcessorPool pool = this.processorPool.Target as QueryProcessorPool;
                if (null != pool)
                {
                    p = pool.Pop();
                }
            }

            if (null != p)
            {
                p.ClearProcessor();
            }
            else
            {
                p = new QueryProcessor(this);
            }

            p.AddRef();
            return p;
        }

        internal FilterResult Match(MessageBuffer messageBuffer, ICollection<MessageFilter> matches)
        {
            Message message = messageBuffer.CreateMessage();
            FilterResult result;
            try
            {
                result = this.Match(message, true, matches);
            }
            finally
            {
                message.Close();
            }

            return result;
        }

        internal FilterResult Match(Message message, bool matchBody, ICollection<MessageFilter> matches)
        {
            QueryProcessor processor = this.CreateProcessor();
            processor.MatchSet = matches;
            processor.EnsureFilterCollection();
            try
            {
                processor.Eval(this.query, message, matchBody);
            }
            catch (XPathNavigatorException e)
            {
                throw TraceUtility.ThrowHelperError(e.Process(this.query), message);
            }
            catch (NavigatorInvalidBodyAccessException e)
            {
                throw TraceUtility.ThrowHelperError(e.Process(this.query), message);
            }

            return new FilterResult(processor);
        }

        internal QueryResult<TResult> Evaluate<TResult>(MessageBuffer messageBuffer)
        {
            Message message = messageBuffer.CreateMessage();
            return this.Evaluate<TResult>(message, true);
        }

        internal QueryResult<TResult> Evaluate<TResult>(Message message, bool matchBody)
        {
            return new QueryResult<TResult>(this, message, matchBody);
        }

        /// <summary>
        /// Execute matches over the given seekable navigator. If the navigator is not safe, wrap it with one that is
        /// </summary>
        internal FilterResult Match(SeekableXPathNavigator navigator, ICollection<MessageFilter> matches)
        {
            // If the matcher places restrictions on the # of nodes we will inspect, and the navigator passed does
            // not do any nodecounting itself, we must make that navigator safe by wrapping it
            if (this.maxNodes < int.MaxValue)
            {
                navigator = this.CreateSafeNavigator(navigator);
            }

            QueryProcessor processor = this.CreateProcessor();
            processor.MatchSet = matches;
            processor.EnsureFilterCollection();
            try
            {
                processor.Eval(this.query, navigator);
            }
            catch (XPathNavigatorException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(this.query));
            }
            catch (NavigatorInvalidBodyAccessException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(this.query));
            }

            return new FilterResult(processor);
        }

        /// <summary>
        /// Execute matches over the given navigator by wrapping it with a Seekable Navigator
        /// </summary>
        internal FilterResult Match(XPathNavigator navigator, ICollection<MessageFilter> matches)
        {
            SeekableXPathNavigator nav = this.CreateSeekableNavigator(navigator);
            return this.Match(nav, matches);
        }

        /// <summary>
        /// Release the given processor and place it back in the context pool
        /// </summary>
        internal void ReleaseProcessor(QueryProcessor processor)
        {
            if (!processor.ReleaseRef())
            {
                return;
            }

            lock (this.processorPool)
            {
                QueryProcessorPool pool = this.processorPool.Target as QueryProcessorPool;
                if (null == pool)
                {
                    pool = new QueryProcessorPool();
                    this.processorPool.Target = pool;
                }
                pool.Push(processor);
            }
        }

        internal void ReleaseResult(FilterResult result)
        {
            if (null != result.Processor)
            {
                result.Processor.MatchSet = null;
                this.ReleaseProcessor(result.Processor);
            }
        }

        /// <summary>
        /// Trim all pool
        /// </summary>
        internal virtual void Trim()
        {
            if (this.query != null)
            {
                this.query.Trim();
            }
        }
    }

    internal enum XPathFilterFlags
    {
        None = 0x00,
        AlwaysMatch = 0x01,     // filter always matches
        IsFxFilter = 0x02,      // filter is matched using the framework engine
    }

    /// <summary>
    /// A matcher used to evalute single XPath expressions
    /// </summary>    
    internal class XPathQueryMatcher : QueryMatcher
    {
        XPathFilterFlags flags;
        bool match;
        static PushBooleanOpcode matchAlwaysFilter; // used for compiling xpaths that always match - i.e. xpath.Length == 0
        static OpcodeBlock rootFilter;        // used for compiling "/"

        static XPathQueryMatcher()
        {
            XPathQueryMatcher.matchAlwaysFilter = new PushBooleanOpcode(true); //dummy

            ValueDataType returnType;
            XPathQueryMatcher.rootFilter = QueryMatcher.CompileForInternalEngine("/", null, QueryCompilerFlags.None, out returnType);
            XPathQueryMatcher.rootFilter.Append(new MatchResultOpcode());
        }

        internal XPathQueryMatcher(bool match)
            : base()
        {
            this.flags = XPathFilterFlags.None;
            this.match = match;
        }
#if NO        
        internal XPathFilterMatcher(XPathFilterMatcher matcher)
            : base(matcher)
        {
            this.flags = matcher.flags;
        }
#endif
        internal bool IsAlwaysMatch
        {
            get
            {
                return (0 != (this.flags & XPathFilterFlags.AlwaysMatch));
            }
        }

        internal bool IsFxFilter
        {
            get
            {
                return (0 != (this.flags & XPathFilterFlags.IsFxFilter));
            }
        }

        /// <summary>
        /// If the xpath is an empty string, there is nothing to compile and the filter always matches
        /// If not, try to compile the filter for execution within the filter engine's own query processor
        /// If that query processor cannot accept the filter (it doesn't fall within the class of xpaths it can handle),
        /// then revert to the fall-back solution - the slower Fx engine
        /// </summary>
        internal void Compile(string expression, XmlNamespaceManager namespaces)
        {
            if (null == this.query)
            {
                // Try to compile for the internal engine first
                try
                {
                    this.CompileForInternal(expression, namespaces);
                }
                catch (QueryCompileException)
                {
                }
                if (null == this.query)
                {
                    // Try for an external engine that might work..
                    this.CompileForExternal(expression, namespaces);
                }
            }
        }

        /// <summary>
        /// Compile this xpath to run on an external (fx) xpath engine
        /// </summary>
        internal void CompileForExternal(string xpath, XmlNamespaceManager names)
        {
            Opcode op = QueryMatcher.CompileForExternalEngine(xpath, names, null, this.match).First;
            this.query = op;
            this.flags |= XPathFilterFlags.IsFxFilter;
        }

        /// <summary>
        /// Compile for the internal engine with default flags
        /// By defalt, we compile an xpath to run stand alone, with standard optimizations
        /// </summary>
        internal void CompileForInternal(string xpath, XmlNamespaceManager names)
        {
            this.query = null;
            xpath = xpath.Trim();

            if (0 == xpath.Length)
            {
                // Empty xpaths always match. Same for xpaths that refer to the root only
                // We will evaluate such filters with minimal overhead. However, we
                // don't want a null value for this.query, so we stick a dummy value in there
                this.query = XPathQueryMatcher.matchAlwaysFilter;
                this.flags |= (XPathFilterFlags.AlwaysMatch);
            }
            else if (1 == xpath.Length && '/' == xpath[0])
            {
                this.query = XPathQueryMatcher.rootFilter.First;
                this.flags |= (XPathFilterFlags.AlwaysMatch);
            }
            else
            {
                ValueDataType returnType;
                OpcodeBlock codeBlock = QueryMatcher.CompileForInternalEngine(xpath, names, QueryCompilerFlags.None, out returnType);
                // Inject a final opcode that will place the query result on the query context
                // This query is now ready for execution STAND ALONE
                if (this.match)
                {
                    codeBlock.Append(new MatchResultOpcode());
                }
                else
                {
                    codeBlock.Append(new QueryResultOpcode());
                }

                this.query = codeBlock.First;
            }

            this.flags &= ~XPathFilterFlags.IsFxFilter;
        }

        internal FilterResult Match(MessageBuffer messageBuffer)
        {
            Message message = messageBuffer.CreateMessage();
            FilterResult result;

            try
            {
                result = this.Match(message, true);
            }
            finally
            {
                message.Close();
            }
            return result;
        }

        internal FilterResult Match(Message message, bool matchBody)
        {
            if (this.IsAlwaysMatch)
            {
                // No need to do any expensive query evaluation if we know that the query will always match
                return new FilterResult(true);
            }

            return base.Match(message, matchBody, null);
        }

        internal FilterResult Match(SeekableXPathNavigator navigator)
        {
            if (this.IsAlwaysMatch)
            {
                // No need to do any expensive query evaluation if we know that the query will always match
                return new FilterResult(true);
            }

            // Is it a filter that we will evaluate using the framework engine?
            // We can evaluate that without having to allocate a query processor
            if (this.IsFxFilter)
            {
                return new FilterResult(this.MatchFx(navigator));
            }

            return base.Match(navigator, null);
        }

        internal FilterResult Match(XPathNavigator navigator)
        {
            Fx.Assert(null != this.query, "");
            if (this.IsAlwaysMatch)
            {
                return new FilterResult(true);
            }
            // Is it a filter that we will evaluate using the framework engine?
            // We can evaluate that without having to allocate a query processor
            if (this.IsFxFilter)
            {
                return new FilterResult(this.MatchFx(navigator));
            }

            return base.Match(navigator, null);
        }

        /// <summary>
        /// Evaluates the filter over infosets surfaced via the given navigator by using the Fx engine
        /// We assume that the filter was pre-compiled using the framework engine
        /// </summary>
        internal bool MatchFx(XPathNavigator navigator)
        {
            INodeCounter counter = navigator as INodeCounter;
            if (counter == null)
            {
                navigator = new SafeSeekableNavigator(new GenericSeekableNavigator(navigator), this.NodeQuota);
            }
            else
            {
                counter.CounterMarker = this.NodeQuota;
                counter.MaxCounter = this.NodeQuota;
            }
            Fx.Assert(null != this.query && OpcodeID.MatchSingleFx == this.query.ID, "");
            try
            {
                return ((MatchSingleFxEngineResultOpcode)this.query).Match(navigator);
            }
            catch (XPathNavigatorException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(this.query));
            }
            catch (NavigatorInvalidBodyAccessException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(this.query));
            }
        }
    }

    internal class InverseQueryMatcher : QueryMatcher
    {
        SubExprEliminator elim;
        Dictionary<object, Opcode> lastLookup;
        bool match;

        internal InverseQueryMatcher(bool match)
            : base()
        {
            this.elim = new SubExprEliminator();
            this.lastLookup = new Dictionary<object, Opcode>();
            this.match = match;
        }

        internal void Add(string expression, XmlNamespaceManager names, object item, bool forceExternal)
        {
            Fx.Assert(null != item, "");

            // Compile the new filter

            bool compiled = false;
            OpcodeBlock codeBlock = new OpcodeBlock();

            codeBlock.Append(new NoOpOpcode(OpcodeID.QueryTree));
            if (!forceExternal)
            {
                try
                {
                    ValueDataType returnType = ValueDataType.None;

                    // Try to compile and merge the compiled query into the query tree
                    codeBlock.Append(QueryMatcher.CompileForInternalEngine(expression, names, QueryCompilerFlags.InverseQuery, out returnType));

                    MultipleResultOpcode opcode;

                    if (!this.match)
                    {
                        opcode = new QueryMultipleResultOpcode();
                    }
                    else
                    {
                        opcode = new MatchMultipleResultOpcode();
                    }

                    opcode.AddItem(item);
                    codeBlock.Append(opcode);
                    compiled = true;

                    // Perform SubExpression Elimination
                    codeBlock = new OpcodeBlock(this.elim.Add(item, codeBlock.First));
                    this.subExprVars = this.elim.VariableCount;
                }
                catch (QueryCompileException)
                {
                    // If the filter couldn't be compiled, we drop down to the framework engine
                }
            }

            if (!compiled)
            {
                codeBlock.Append(QueryMatcher.CompileForExternalEngine(expression, names, item, this.match));
            }

            // Merge the compiled query into the query tree
            QueryTreeBuilder builder = new QueryTreeBuilder();
            this.query = builder.Build(this.query, codeBlock);
            // To de-merge this filter from the tree, we'll have to walk backwards up the tree... so we
            // have to remember the last opcode that is executed on behalf of this filter
            this.lastLookup[item] = builder.LastOpcode;
        }

        internal void Clear()
        {
            foreach (object item in this.lastLookup.Keys)
            {
                this.Remove(this.lastLookup[item], item);
                this.elim.Remove(item);
            }
            this.subExprVars = this.elim.VariableCount;
            this.lastLookup.Clear();
        }

        internal void Remove(object item)
        {
            Fx.Assert(this.lastLookup.ContainsKey(item), "");

            this.Remove(this.lastLookup[item], item);
            this.lastLookup.Remove(item);

            // Remove filter from subexpr eliminator
            this.elim.Remove(item);
            this.subExprVars = this.elim.VariableCount;
        }

        void Remove(Opcode opcode, object item)
        {
            MultipleResultOpcode multiOpcode = opcode as MultipleResultOpcode;

            if (multiOpcode != null)
            {
                multiOpcode.RemoveItem(item);
            }
            else
            {
                opcode.Remove();
            }
        }

        internal override void Trim()
        {
            base.Trim();
            elim.Trim();
        }
    }
}