Exemplo n.º 1
0
        /// <summary>
        /// 直接运行于环境默认的上
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="self"></param>
        /// <returns></returns>
        public static T Run <T>(this T self) where T : IActionNode
        {
            NodeIterator it = NodeIterator.Allocate <NodeIterator>(self.env);

            it.Config(self);
            return(self);
        }
Exemplo n.º 2
0
        public void ShouldReturnTablesInCorrectOrder()
        {
            // Scenario: Make 2 customers, for each customer make two accounts and do one deposit and one withdraw for each account
            string[] requestedOrder = { "Customer", "Account", "Deposit", "Withdraw", "Account", "Deposit", "Withdraw",
                                        "Customer", "Account", "Deposit", "Withdraw", "Account", "Deposit", "Withdraw", };

            // 2 Customers
            ExecutionNode customer = ExecutionNode.CreateLevelOneNode(2, "Customer");

            customer.AddTable(new TableEntity("dbo", "Customer"));

            // Make 2 accounts
            var accounts = customer.AddChild(2, "Accounts");

            accounts.AddTable(new TableEntity("dbo", "Account"));

            // make one one Deposit and one WithDraw
            var accountTransactions = accounts.AddChild(1, "AccountTransactions");

            accountTransactions.AddTable(new TableEntity("dbo", "Deposit"));
            accountTransactions.AddTable(new TableEntity("dbo", "Withdraw"));


            NodeIterator it = new NodeIterator(customer);

            var actual =
                new List <TableEntity>(it.GetTablesRecursive().Select(x => x.Table));

            for (int i = 0; i < requestedOrder.Length; i++)
            {
                Console.WriteLine(actual[i].TableName);
                Assert.That(requestedOrder[i], Is.EqualTo(actual[i].TableName));
            }
        }
Exemplo n.º 3
0
        /// <summary>Gets the nearest focusable element below this.</summary>
        /// <returns>The nearest focusable element below. Null if there is none.</returns>
        public HtmlElement GetFocusableBelow()
        {
            // Has the element defined something specific?
            HtmlElement target = GetFocusableOverride("down");

            if (target != null)
            {
                // Yep, it did!
                return(target);
            }

            // Distance of the nearest element (set when nearest is first set):
            float nearestDistance = 0f;
            // The current nearest element:
            HtmlElement nearest = null;
            // Grab my computed style:
            ComputedStyle computed = Style.Computed;
            // Get hold of the iterator (so we can safely skip child elements):
            NodeIterator allElements = document.allNodes;

            // Grab my x position:
            float myX = computed.GetMidpointX();
            // Grab the midpoint of this element on Y:
            float myY = computed.GetMidpointY();


            // For each element in the dom that is focusable and below this..
            foreach (Node node in allElements)
            {
                HtmlElement element = node as HtmlElement;

                if (element == null)
                {
                    continue;
                }

                if (element != this && element.IsBelow(myY) && element.focusable)
                {
                    // We have an element below.

                    // Check if it is closer than the current result.
                    // If it is, it's the current result.

                    // Is it nearer?
                    float distance = element.DistanceFromFast(myX, myY);

                    // Is it the first we've found, or is it nearer?
                    if (nearest == null || distance < nearestDistance)
                    {
                        nearest         = element;
                        nearestDistance = distance;
                    }

                    // Make sure we don't now iterate its kids:
                    allElements.SkipChildren = true;
                }
            }

            return(nearest);
        }
Exemplo n.º 4
0
 public void ForEachNode(NodeIterator it)
 {
     for (int i = 0; i < NodeCount; i++)
     {
         it(i);
     }
 }
Exemplo n.º 5
0
        public void ShouldGetZeroTotalExpectedInsertedRowWhenThereIsNoTable()
        {
            ExecutionNode customer            = ExecutionNode.CreateLevelOneNode(2, "No tables");
            NodeIterator  it                  = new NodeIterator(customer);
            long          actualExpectedCount = it.GetExpectedInsertCount();

            Assert.That(actualExpectedCount, Is.EqualTo(0));
        }
Exemplo n.º 6
0
            public override bool Equals(object other)
            {
                NodeIterator iter = other as NodeIterator;

                if (iter == null)
                {
                    return(false);
                }
                return(object.ReferenceEquals(current, iter.current));
            }
Exemplo n.º 7
0
        public override object Execute(IContextProvider provider, object[] dataPool)
        {
            XPath2NodeIterator iter = XPath2NodeIterator.Create(this[0].Execute(provider, dataPool));

            for (int k = 1; k < Count; k++)
            {
                iter = new NodeIterator(CreateEnumerator(dataPool, this[k], iter));
            }
            return(iter);
        }
Exemplo n.º 8
0
            public override int Distance(Iterator <KeyValuePair <TKey, TValue> > iter)
            {
                NodeIterator nodeIter = iter as NodeIterator;

                if (nodeIter == null || !object.ReferenceEquals(nodeIter.Collection, this.Collection))
                {
                    throw new ArgumentException("Cannot determine distance of iterators belonging to different collections.");
                }

                var end = tree.end;

                int keyDiff;

                if (this == end || iter == end)
                {
                    keyDiff = (this == end && this != iter) ? 1 : 0;
                }
                else
                {
                    keyDiff = tree.keyComparer.Compare(current.Key, nodeIter.current.Key);
                }

                if (keyDiff <= 0)
                {
                    int diff = 0;
                    var rwd  = this.Clone();
                    for (; rwd != iter && rwd != end; rwd.Next())
                    {
                        --diff;
                    }

                    if (rwd == iter)
                    {
                        return(diff);
                    }
                }

                if (keyDiff >= 0)
                {
                    int diff = 0;
                    var fwd  = iter.Clone();
                    for (; fwd != this && fwd != end; fwd.Next())
                    {
                        ++diff;
                    }

                    if (fwd == this)
                    {
                        return(diff);
                    }
                }

                throw new Exception("Inconsistent state. Concurrency?");
            }
Exemplo n.º 9
0
    public IEnumerable <RelatedNode> GetStartNodesArriveToEnd(Int32 lengthPath)
    {
        var nodeIterator = new NodeIterator(this);

        while (nodeIterator.MoveNext())
        {
            if (nodeIterator.Current.CanMoveToEnd(lengthPath))
            {
                yield return(nodeIterator.Current);
            }
        }
    }
Exemplo n.º 10
0
        public void ShouldNotAllowNullInTheParameterForNodeIterator()
        {
            bool          thrown = false;
            ExecutionNode node   = null;

            try
            {
                NodeIterator it = new NodeIterator(node);
            }
            catch (ArgumentNullException)
            {
                thrown = true;
            }

            Assert.That(thrown, Is.True);
        }
Exemplo n.º 11
0
        public void ShouldBeAbleToRemoveSeveralTablesFromExecutionNode()
        {
            // 2 Customers
            ExecutionNode customer = ExecutionNode.CreateLevelOneNode(2, "Customer");

            customer.AddTable(_CustomerTable);
            customer.AddTable(_AccountTable);

            NodeIterator it = new NodeIterator(customer);

            Assert.That(it.GetExpectedInsertCount(), Is.EqualTo(4));
            AssertOrder(it.GetTablesRecursive().Select(x => x.Table), "Customer", "Accounts", "Customer", "Accounts");

            customer.RemoveTables(_AccountTable, _CustomerTable);

            Assert.That(it.GetExpectedInsertCount(), Is.EqualTo(0));
            // AssertOrder(it.GetTablesRecursive(), "Customer", "Customer");
        }
        public void testDecodingAmpersand()
        {
            string ENCODED_WORKSHOP_TITLE = "The Testing &amp; Refactoring Workshop";
            string DECODED_WORKSHOP_TITLE = "The Testing & Refactoring Workshop";

            StringBuilder decodedContent = new StringBuilder();
            Parser        parser         = Parser.createParser(ENCODED_WORKSHOP_TITLE);

            parser.setNodeDecoding(true);
            NodeIterator nodes = parser.element();

            while (nodes.hasMoreNodes())
            {
                decodedContent.Append(nodes.nextNode().toPlainTextString());
            }

            Assert.AreEqual(DECODED_WORKSHOP_TITLE, decodedContent.ToString(), "ampersand in string");
        }
        public void RunWorkFlow(string connectionString, DataConsumerPluginWrapper consumerWrapper, ExecutionResultBuilder builder, ExecutionTaskOptions options, ExecutionNode rootNode)
        {
            using (var consumer = consumerWrapper.CreateInstance())
                using (iterator = new NodeIterator(rootNode))
                {
                    consumer.ReportInsertionCallback = builder.Increment;
                    consumer.ReportErrorCallback     = builder.AddError;

                    ValueStore   valueStore = new ValueStore();
                    DataProducer producer   = new DataProducer(valueStore);

                    builder.Begin();

                    consumer.Init(connectionString, consumerWrapper.OptionsTemplate);
                    // hmm: Iterator should hold the Ienumerable and reset it when ever it starts over on a node?

                    consumer.Consume(producer.ProduceRows(iterator.GetTablesRecursive()), valueStore);
                }
        }
Exemplo n.º 14
0
        public void ShouldRestartNodeCounterWhenNodeIsRestarted()
        {
            // 2 Customers
            ExecutionNode customer = ExecutionNode.CreateLevelOneNode(2, "Customer");

            customer.AddTable(new TableEntity("dbo", "Customer"));

            // Make 2 accounts
            var accounts = customer.AddChild(2, "Accounts");

            accounts.AddTable(new TableEntity("dbo", "Account"));

            // make one one Deposit and one WithDraw
            var accountTransactions = accounts.AddChild(1, "AccountTransactions");

            accountTransactions.AddTable(new TableEntity("dbo", "Deposit"));
            accountTransactions.AddTable(new TableEntity("dbo", "Withdraw"));


            NodeIterator it = new NodeIterator(customer);

            var et         = it.GetTablesRecursive().ToList();
            int rowCounter = 0;

            et[rowCounter++].AssertNAndTable(1, "Customer");
            et[rowCounter++].AssertNAndTable(1, "Account");
            et[rowCounter++].AssertNAndTable(1, "Deposit");
            et[rowCounter++].AssertNAndTable(1, "Withdraw");
            // first customer, second account
            et[rowCounter++].AssertNAndTable(2, "Account");
            et[rowCounter++].AssertNAndTable(1, "Deposit");
            et[rowCounter++].AssertNAndTable(1, "Withdraw");

            // second customer
            et[rowCounter++].AssertNAndTable(2, "Customer");
            et[rowCounter++].AssertNAndTable(1, "Account");
            et[rowCounter++].AssertNAndTable(1, "Deposit");
            et[rowCounter++].AssertNAndTable(1, "Withdraw");
            et[rowCounter++].AssertNAndTable(2, "Account");
            et[rowCounter++].AssertNAndTable(1, "Deposit");
            et[rowCounter++].AssertNAndTable(1, "Withdraw");
        }
Exemplo n.º 15
0
    public Boolean CanMoveToEnd(Int32 lengthPath)
    {
        Int32 counter      = 0;
        var   nodeIterator = new NodeIterator(this);

        nodeIterator.AddActionOnMoveNext(() => counter--);
        while (nodeIterator.MoveNext())
        {
            if (counter == lengthPath)
            {
                if (nodeIterator.Current.IsEnd())
                {
                    return(true);
                }
                nodeIterator.MoveBack();
            }
            counter++;
        }
        return(counter == lengthPath);
    }
Exemplo n.º 16
0
        public void ShouldStopWhenAskedToBeCancled()
        {
            ExecutionNode node = ExecutionNode.CreateLevelOneNode(1000000);

            node.AddTable(new TableEntity("", ""));

            var tables = new List <ExecutionTable>();

            NodeIterator iterator = new NodeIterator(node);
            Action       a        = new Action(() =>
            {
                tables.AddRange(iterator.GetTablesRecursive());
            });

            a.BeginInvoke(null, null);
            Thread.Sleep(10);
            iterator.Cancel();
            Console.WriteLine(tables.Count);
            Assert.That(tables.Count, Is.LessThan(1000000));
            Assert.That(tables.Count, Is.GreaterThan(0));
        }
Exemplo n.º 17
0
        public void ShouldBeAbleToRemoveOneTableFromExecutionNode()
        {
            // 2 Customers
            ExecutionNode customer = ExecutionNode.CreateLevelOneNode(2, "Customer");

            customer.AddTable(_CustomerTable);

            // Make 2 accounts per customer
            ExecutionNode accounts = customer.AddChild(2, "Accounts");

            accounts.AddTable(_AccountTable);

            NodeIterator it = new NodeIterator(customer);

            Assert.That(it.GetExpectedInsertCount(), Is.EqualTo(6));
            AssertOrder(it.GetTablesRecursive().Select(x => x.Table), "Customer", "Accounts", "Accounts", "Customer", "Accounts", "Accounts");

            accounts.RemoveTable(_AccountTable);

            Assert.That(it.GetExpectedInsertCount(), Is.EqualTo(2));
            AssertOrder(it.GetTablesRecursive().Select(x => x.Table), "Customer", "Customer");
        }
Exemplo n.º 18
0
        public void shouldReturnOnlyTheNodeIfOnlyOne()
        {
            ExecutionNode node = ExecutionNode.CreateLevelOneNode(1);

            node.AddTable(new TableEntity("", ""));

            int          counter = 0;
            NodeIterator it      = new NodeIterator(node);

            Assert.That(node.Children.Count(), Is.EqualTo(0));

            HashSet <TableEntity> nodes = new HashSet <TableEntity>();

            foreach (var item in it.GetTablesRecursive())
            {
                nodes.Add(item.Table);
                counter++;
            }

            Assert.That(counter, Is.EqualTo(1));
            Assert.That(nodes.Count, Is.EqualTo(1));
        }
Exemplo n.º 19
0
 /// <summary>Handles the iteration of the children or qualfier</summary>
 /// <param name="iterator">an iterator</param>
 /// <returns>Returns if there are more elements available.</returns>
 private bool IterateChildrenMethod(IIterator iterator)
 {
     if (_enclosing._skipSiblings)
     {
         // setSkipSiblings(false);
         _enclosing._skipSiblings = false;
         _subIterator             = Enumerable.Empty <object>().Iterator();
     }
     // create sub iterator for every child,
     // if its the first child visited or the former child is finished
     if (!_subIterator.HasNext() && iterator.HasNext())
     {
         var child = (XmpNode)iterator.Next();
         _index++;
         _subIterator = new NodeIterator(_enclosing, child, _path, _index);
     }
     if (_subIterator.HasNext())
     {
         _returnProperty = (IXmpPropertyInfo)_subIterator.Next();
         return(true);
     }
     return(false);
 }
Exemplo n.º 20
0
        public void ShouldCountTheTotalExpectedInsertedRowsInOrderToPredictProgress()
        {
            // 2 Customers
            ExecutionNode customer = ExecutionNode.CreateLevelOneNode(2, "Customer");

            customer.AddTable(new TableEntity("dbo", "Customer"));

            // Make 2 accounts
            var accounts = customer.AddChild(2, "Accounts");

            accounts.AddTable(new TableEntity("dbo", "Account"));

            // make one one Deposit and one WithDraw
            var accountTransactions = accounts.AddChild(1, "AccountTransactions");

            accountTransactions.AddTable(new TableEntity("dbo", "Deposit"));
            accountTransactions.AddTable(new TableEntity("dbo", "Withdraw"));


            NodeIterator it = new NodeIterator(customer);
            long         actualExpectedCount = it.GetExpectedInsertCount();

            Assert.That(actualExpectedCount, Is.EqualTo(14));
        }
Exemplo n.º 21
0
        public void ShouldGetAllExecutionItems()
        {
            ExecutionNode node = ExecutionNode.CreateLevelOneNode(1);

            node.AddTable(new TableEntity("", ""));
            node.AddTable(new TableEntity("", ""));

            var child = node.AddChild(1);

            node.AddTable(new TableEntity("", ""));
            node.AddTable(new TableEntity("", ""));
            node.AddTable(new TableEntity("", ""));

            NodeIterator it      = new NodeIterator(node);
            int          counter = 0;

            foreach (var ei in it.GetTablesRecursive())
            {
                Console.WriteLine(ei);
                counter++;
            }

            Assert.That(counter, Is.EqualTo(5));
        }
 public NodeCanvas(AIGraph window) : base(window)
 {
     m_nodeIterator = new NodeIterator(this);
     AIGraph.onControllerChanged -= SetController;
     AIGraph.onControllerChanged += SetController;
 }
Exemplo n.º 23
0
 public override object Execute(IContextProvider provider, object[] args, MemoryPool pool)
 {
     if (Source == null)
         return EmptyIterator.Shared;
     XQueryNodeIterator iter = XQueryNodeIterator.Create(Source.Execute(provider, args, pool));
     for (int k = 0; k < m_filter.Length; k++)
         iter = new NodeIterator(CreateEnumerator(args, pool, m_filter[k], iter));
     return iter;
 }
Exemplo n.º 24
0
            // each call processes one element of pattern[]
            bool UnifyTailEx(int ip, int it, VarStack varStack)
            {
                ListPatternElem e            = (ListPatternElem)pattern[ip];
                Variable        rangeSpecVar = (Variable)e.RangeBindVar;
                NodeIterator    subtreeIterator;
                int             k;
                int             marker;
                ListTerm        RangeList = null;
                BaseTerm        tail      = null;
                int             minLen; // minimum required range length (number of range elements)
                int             maxLen; // maximum possible ...

                if (!DoLowerAndUpperboundChecks(ip, it, out minLen, out maxLen))
                {
                    return(false);
                }

                // scan the minimal number of range elements. Add them to the range list,
                // i.e. the last variable (if present) preceding the '{ , }'
                for (int i = 0; i < minLen; i++)
                {
                    if ((k = it + i) >= target.Count)
                    {
                        return(false);
                    }

                    AppendToRangeList(ref RangeList, rangeSpecVar, target[k], ref tail);
                }

                marker = varStack.Count; // register the point to which we must possibly undo unifications

                if (e.HasSearchTerm)
                {
                    // scan the elements up to the maximum range length, and the element immediately thereafter
                    for (int i = minLen; i <= maxLen; i++)
                    {
                        BaseTerm t = null;
                        k = it + i;

                        if (k == target.Count)
                        {
                            return(false);
                        }

                        bool negSearchSucceeded = true;         // iff none of the alternative term matches the target term

                        for (int j = 4; j < e.Args.Length; j++) // scan all AltSearchTerm alternatives (separated by '|')
                        {
                            BaseTerm      searchTerm    = e.AltSearchTerms[j];
                            DownRepFactor downRepFactor = null; // e.downRepFactor [j];
                            t = target[k];
                            AltLoopStatus status = AltLoopStatus.TryNextAlt;

                            if (downRepFactor == null)
                            {
                                status =
                                    TryOneAlternative(ip, varStack, e, k, marker, RangeList, i, t, ref negSearchSucceeded, searchTerm);

                                if (status == AltLoopStatus.MatchFound)
                                {
                                    return(true);
                                }
                            }
                            else // traverse the downRepFactor tree, which in principle may yield more than one match
                            {
                                subtreeIterator = new NodeIterator(t, searchTerm, downRepFactor.minLenTerm,
                                                                   downRepFactor.maxLenTerm, false, downRepFactor.bindVar, varStack);

                                foreach (BaseTerm match in subtreeIterator) // try -- if necessary -- each tree match with the current search term
                                {
                                    status =
                                        TryOneAlternative(ip, varStack, e, k, marker, RangeList, i, match, ref negSearchSucceeded, searchTerm);

                                    if (status == AltLoopStatus.MatchFound)
                                    {
                                        return(true);
                                    }

                                    if (status == AltLoopStatus.Break)
                                    {
                                        break;
                                    }
                                }
                            }

                            if (status == AltLoopStatus.Break)
                            {
                                break;
                            }
                        }

                        // at this point sufficient alternatives have been tried
                        if (e.IsNegSearch && negSearchSucceeded)                               // none of the terms matched => ok if binding succeeds
                        {
                            if (!TryBindingAltListVarToMatch(e.AltListBindVar, t, varStack) || // bind the AltListBindVar to the match
                                !TryBindingRangeRelatedVars(e, i, RangeList, varStack))        // bind the range to the range variables
                            {
                                return(false);                                                 // binding failed
                            }
                            if (ip == pattern.Length - 1)                                      // this was the last pattern element
                            {
                                if (k == target.Count - 1)                                     // both pattern and target exhausted
                                {
                                    return(true);
                                }
                            }
                            else if (UnifyTailEx(ip + 1, k + 1, varStack)) // now deal with the rest
                            {
                                return(true);
                            }
                        }
                        else if (i < maxLen) // append the rejected term to the range list and go try the next term
                        {
                            AppendToRangeList(ref RangeList, rangeSpecVar, t, ref tail);
                        }
                    }
                }
                else // a range without a subsequent search term (so followed by another range or end of pattern)
                {
                    for (int i = minLen; i <= maxLen; i++)
                    {
                        k = it + i;

                        if (k == target.Count)                                             // ok, target[k] does not exist, end of target hit
                        {
                            return(TryBindingRangeRelatedVars(e, i, RangeList, varStack)); // i is actual range length
                        }
                        // k is ok
                        if (i < maxLen)
                        {
                            AppendToRangeList(ref RangeList, rangeSpecVar, target[k], ref tail);
                        }

                        // now deal with the rest
                        if (TryBindingRangeRelatedVars(e, i, RangeList, varStack) &&
                            UnifyTailEx(ip + 1, k, varStack))
                        {
                            return(true);
                        }
                    }
                }

                // If we arrive here, no matching term was found in or immediately after the permitted range.
                // Therefore, undo any unifications made locally in this method and return with failure.
                if (marker != 0)
                {
                    BaseTerm.UnbindToMarker(varStack, marker);
                }

                return(false);
            }
Exemplo n.º 25
0
 public override DataIterator Clone()
 {
     return(new IteratorXPath(NodeIterator.Clone(), ConvertAsCharValue));
 }
Exemplo n.º 26
0
		private AxisIterator (AxisIterator other)
			: base (other)
		{
			iter = (NodeIterator) other.iter.Clone ();
			source = other.source;
		}
Exemplo n.º 27
0
		internal NodeIterator (NodeIterator other, bool cloneFlag)
			: base (other)
		{
			if (other.emptyInput)
				emptyInput = true;
			else
				node = other.node.Clone ();
		}
Exemplo n.º 28
0
 public override bool MoveNext()
 {
     return(NodeIterator.MoveNext());
 }
Exemplo n.º 29
0
		public AxisIterator (NodeIterator iter, AxisStepExpr source)
			: base (iter.Context)
		{
			this.iter = iter;
			this.source = source;
		}
Exemplo n.º 30
0
 private bool CompareXML(XQueryContext context, string sourceFile, XQueryNodeIterator iter)
 {
     IXPathNavigable doc = context.OpenDocument(sourceFile);
     XQueryNodeIterator src = new NodeIterator(new XPathItem[] { doc.CreateNavigator() });
     TreeComparer comparer = new TreeComparer();
     comparer.IgnoreWhitespace = true;
     return comparer.DeepEqual(src, new NodeIterator(DocumentIterator(context, iter)));
 }
Exemplo n.º 31
0
 public bool MoveNext()
 {
     return(NodeIterator.MoveNext());
 }
Exemplo n.º 32
0
 public XPathIterator Clone()
 {
     return(new XPathIterator(NodeIterator.Clone(), ConvertAsCharValue));
 }
      // each call processes one element of pattern[]
      bool UnifyTailEx (int ip, int it, VarStack varStack)
      {
        ListPatternElem e = (ListPatternElem)pattern [ip];
        Variable rangeSpecVar = (Variable)e.RangeBindVar;
        NodeIterator subtreeIterator;
        int k;
        int marker;
        ListTerm RangeList = null;
        BaseTerm tail = null;
        int minLen; // minimum required range length (number of range elements)
        int maxLen; // maximum possible ...

        if (!DoLowerAndUpperboundChecks (ip, it, out minLen, out maxLen)) return false;

        // scan the minimal number of range elements. Add them to the range last,
        // i.e. the last variable (if present) preceding the '{ , }'
        for (int i = 0; i < minLen; i++)
        {
          if ((k = it + i) >= target.Count)
            return false;

          AppendToRangeList (ref RangeList, rangeSpecVar, target [k], ref tail);
        }

        marker = varStack.Count; // register the point to which we must possibly undo unifications

        if (e.HasSearchTerm)
        {
          // scan the elements up to the maximum range length, and the element immediately thereafter
          for (int i = minLen; i <= maxLen; i++)
          {
            BaseTerm t = null;
            k = it + i;

            if (k == target.Count) return false;

            bool negSearchSucceeded = true; // iff none of the alternative term matches the target term

            for (int j = 4; j < e.Args.Length; j++) // scan all AltSearchTerm alternatives (separated by '|')
            {
              BaseTerm searchTerm = e.AltSearchTerms [j];
              DownRepFactor downRepFactor = null; // e.downRepFactor [j];
              t = target [k];
              AltLoopStatus status = AltLoopStatus.TryNextAlt;

              if (downRepFactor == null)
              {
                status =
                  TryOneAlternative (ip, varStack, e, k, marker, RangeList, i, t, ref negSearchSucceeded, searchTerm);

                if (status == AltLoopStatus.MatchFound) return true;
              }
              else // traverse the downRepFactor tree, which in principle may yield more than one match
              {
                subtreeIterator = new NodeIterator (t, searchTerm,
                  downRepFactor.minLenTerm, downRepFactor.maxLenTerm, downRepFactor.bindVar, varStack);

                foreach (BaseTerm match in subtreeIterator) // try -- if necessary -- each tree match with the current search term
                {
                  status =
                    TryOneAlternative (ip, varStack, e, k, marker, RangeList, i, match, ref negSearchSucceeded, searchTerm);

                  if (status == AltLoopStatus.MatchFound) return true;

                  if (status == AltLoopStatus.Break) break;
                }
              }

              if (status == AltLoopStatus.Break) break;
            }

            // at this point sufficient alternatives have been tried
            if (e.IsNegSearch && negSearchSucceeded) // none of the terms matched => ok if binding succeeds
            {
              if (!TryBindingAltListVarToMatch (e.AltListBindVar, t, varStack) || // bind the AltListBindVar to the match
                  !TryBindingRangeRelatedVars (e, i, RangeList, varStack))        // bind the range to the range variables
                return false; // binding failed

              if (ip == pattern.Length - 1) // this was the last pattern element
              {
                if (k == target.Count - 1) // both pattern and target exhausted
                  return true;
              }
              else if (UnifyTailEx (ip + 1, k + 1, varStack)) // now deal with the rest
                return true;
            }
            else if (i < maxLen) // append the rejected term to the range last and go try the next term
              AppendToRangeList (ref RangeList, rangeSpecVar, t, ref tail);
          }
        }
        else // a range without a subsequent search term (so followed by another range or end of pattern)
        {
          for (int i = minLen; i <= maxLen; i++)
          {
            k = it + i;

            if (k == target.Count) // ok, target[k] does not exist, end of target hit
              return TryBindingRangeRelatedVars (e, i, RangeList, varStack); // i is actual range length

            // k is ok
            if (i < maxLen)
              AppendToRangeList (ref RangeList, rangeSpecVar, target [k], ref tail);

            // now deal with the rest
            if (TryBindingRangeRelatedVars (e, i, RangeList, varStack) &&
                UnifyTailEx (ip + 1, k, varStack)) return true;
          }
        }

        // If we arrive here, no matching term was found in or immediately after the permitted range.
        // Therefore, undo any unifications made locally in this method and return with failure.
        if (marker != 0) BaseTerm.UnbindToMarker (varStack, marker);

        return false;
      }
Exemplo n.º 34
0
 private bool CompareFragment(XQueryContext context, string sourceFile, XQueryNodeIterator iter, XmlSpace space)
 {
     StringBuilder sb = new StringBuilder();
     sb.AppendLine("<?xml version='1.0'?>");
     sb.Append("<root>");
     TextReader textReader = new StreamReader(sourceFile, true);
     sb.Append(textReader.ReadToEnd());
     textReader.Close();
     sb.Append("</root>");
     XmlReaderSettings settings = context.GetSettings();
     XmlReader reader = XmlReader.Create(new StringReader(sb.ToString()), settings);
     XQueryDocument doc1 = new XQueryDocument(reader, space);
     doc1.Fill();
     context.AddDocument(doc1);
     XQueryDocument doc2 = context.CreateDocument();
     XQueryDocumentBuilder builder = new XQueryDocumentBuilder(doc2);
     builder.WriteStartDocument();
     builder.WriteStartElement("root", "");
     Core.WriteNode(context.Engine, builder, iter.Clone());
     builder.WriteEndElement();
     XQueryNodeIterator iter1 = new NodeIterator(new XPathItem[] { doc1.CreateNavigator() });
     XQueryNodeIterator iter2 = new NodeIterator(new XPathItem[] { doc2.CreateNavigator() });
     TreeComparer comparer = new TreeComparer();
     comparer.IgnoreWhitespace = true;
     bool res = comparer.DeepEqual(iter1, iter2);
     return res;
 }