Example #1
0
        public void TestStack()
        {
            stack = stack.Push(1);           //overwrite field!
            stack = stack.Push(2);           //overwrite field!
            Console.WriteLine(stack.Peek()); //2
            var biggerStack = stack.Push(3);

            Console.WriteLine(biggerStack.Peek()); //3
            Console.WriteLine(stack.Peek());       //2; now we have 2 stacks; but memory is shared
        }
Example #2
0
            private void SkipPastChanges()
            {
                var oldPosition = _oldTreeCursor.CurrentNodeOrToken.Position;

                while (!_changes.IsEmpty && oldPosition >= _changes.Peek().Span.End)
                {
                    var change = _changes.Peek();

                    _changes      = _changes.Pop();
                    _changeDelta += change.NewLength - change.Span.Length;
                }
            }
Example #3
0
        private void FinishInterpolatedString()
        {
            Assertion.Assert(!myInterpolatedStringStates.IsEmpty, "!myInterpolatedStringPreviousStates.IsEmpty");

            var interpolatedStringState = myInterpolatedStringStates.Peek();
            var prevContext             = interpolatedStringState.PreviousLexerContext;

            yy_lexical_state     = prevContext.LexerState;
            myBrackLevel         = prevContext.BrackLevel;
            myParenLevel         = prevContext.ParenLevel;
            myNestedCommentLevel = prevContext.NestedCommentLevel;

            myInterpolatedStringStates = myInterpolatedStringStates.Pop();
        }
        private bool TryGetSelectionSet(
            ImmutableStack <ISyntaxNode> path,
            out SelectionSetNode selectionSet)
        {
            SelectionSetNode             root    = null;
            ImmutableStack <ISyntaxNode> current = path;

            while (current.Any())
            {
                if (current.Peek() is SelectionSetNode set)
                {
                    root = set;
                    if (IsRelevantSelectionSet(current.Pop().Peek()))
                    {
                        selectionSet = set;
                        return(true);
                    }
                }

                current = current.Pop();
            }

            selectionSet = root;
            return(root != null);
        }
Example #5
0
        public ActionResult StackPop()
        {
            var i = ResultStack.Peek();

            ResultStack = ResultStack.Pop();
            return(i);
        }
        public ImmutableStack <T> Apply(ImmutableStack <T> stack)
        {
            var(b, stack2) = (stack.Peek(), stack.Pop());
            var(a, stack3) = (stack2.Peek(), stack2.Pop());

            return(stack3.Push(Apply(a, b)));
        }
Example #7
0
        public void CanPopFromEmptyIntStack()
        {
            var stack = new ImmutableStack <int>();

            Assert.Equal(0, stack.Peek());
            Assert.Same(stack, stack.Pop());
        }
Example #8
0
        public void CanPopFromEmptyStringStack()
        {
            var stack = new ImmutableStack <string>();

            Assert.Null(stack.Peek());
            Assert.Same(stack, stack.Pop());
        }
 public TaintedSourceInfo(ulong id, MethodUniqueSignature method, ImmutableStack <string> callStack)
 {
     Id                = id;
     Method            = method;
     ForwardCallStack  = callStack.Pop();
     BackwardCallStack = ImmutableStack <string> .Empty.Push(callStack.Peek());
 }
        private Tuple <State, bool> GetStateAfterStatement(StackEntry location, ImmutableStack <StackEntry> stack, ImmutableStack <Tuple <int, string> > finallyStack, State returnState)
        {
            JsStatement next;

            if (location.Index < location.Block.Statements.Count - 1)
            {
                next = location.Block.Statements[location.Index + 1];
            }
            else if (!stack.IsEmpty)
            {
                var tos = stack.Peek();
                next = tos.Block.Statements[tos.Index];
            }
            else
            {
                next = null;
            }

            if (next is JsLabelledStatement)
            {
                return(Tuple.Create(GetOrCreateStateForLabel((next as JsLabelledStatement).Label, finallyStack), false));
            }
            else if (next != null)
            {
                return(Tuple.Create(CreateNewStateValue(finallyStack), true));
            }
            else
            {
                return(Tuple.Create(returnState, false));
            }
        }
        public void DeserializeStack()
        {
            string json = @"[
  ""One"",
  ""II"",
  ""3""
]";

            ImmutableStack <string> data = JsonSerializer.Deserialize <ImmutableStack <string> >(json);

            Assert.False(data.IsEmpty);
            Assert.Equal("3", data.Peek());
            data = data.Pop();
            Assert.Equal("II", data.Peek());
            data = data.Pop();
            Assert.Equal("One", data.Peek());
        }
Example #12
0
        /// <summary>
        /// Returns the top of <see cref="CreationCallStack"/> if this location was created through an interprocedural method invocation, i.e. <see cref="CreationCallStack"/> is non-empty.
        /// Otherwise, returns <see cref="CreationOpt"/>.
        /// </summary>
        public IOperation GetTopOfCreationCallStackOrCreation()
        {
            if (CreationCallStack.IsEmpty)
            {
                return(CreationOpt);
            }

            return(CreationCallStack.Peek());
        }
Example #13
0
        internal ImmutableStack <RopeCacheEntry> FindNodeUsingCache(int index)
        {
            Debug.Assert(index >= 0 && index < this.Length);

            // thread safety: fetch stack into local variable
            ImmutableStack <RopeCacheEntry> stack    = lastUsedNodeStack;
            ImmutableStack <RopeCacheEntry> oldStack = stack;

            if (stack == null)
            {
                stack = ImmutableStack <RopeCacheEntry> .Empty.Push(new RopeCacheEntry(root, 0));
            }
            while (!stack.UnsafePeek().IsInside(index))
            {
                stack = stack.Pop();
            }
            while (true)
            {
                RopeCacheEntry entry = stack.UnsafePeek();
                // check if we've reached a leaf or function node
                if (entry.node.height == 0)
                {
                    if (entry.node.contents == null)
                    {
                        // this is a function node - go down into its subtree
                        entry = new RopeCacheEntry(entry.node.GetContentNode(), entry.nodeStartIndex);
                        // entry is now guaranteed NOT to be another function node
                    }
                    if (entry.node.contents != null)
                    {
                        // this is a node containing actual content, so we're done
                        break;
                    }
                }
                // go down towards leaves
                if (index - entry.nodeStartIndex >= entry.node.left.length)
                {
                    stack = stack.Push(new RopeCacheEntry(entry.node.right, entry.nodeStartIndex + entry.node.left.length));
                }
                else
                {
                    stack = stack.Push(new RopeCacheEntry(entry.node.left, entry.nodeStartIndex));
                }
            }

            // write back stack to volatile cache variable
            // (in multithreaded access, it doesn't matter which of the threads wins - it's just a cache)
            if (oldStack != stack)
            {
                // no need to write when we the cache variable didn't change
                lastUsedNodeStack = stack;
            }

            // this method guarantees that it finds a leaf node
            Debug.Assert(stack.Peek().node.contents != null);
            return(stack);
        }
Example #14
0
    public static ImmutableStack <T> Reverse <T>(this ImmutableStack <T> stack, ImmutableStack <T> initial) where T : notnull
    {
        ImmutableStack <T> r = initial;

        for (ImmutableStack <T> f = stack; !f.IsEmpty; f = f.Pop())
        {
            r = r.Push(f.Peek());
        }
        return(r);
    }
Example #15
0
        public void CanPopOffItem()
        {
            var stack = new ImmutableStack <string>();

            Assert.Null(stack.Peek());

            var fooStack = stack.Push("foo");

            Assert.Equal("foo", fooStack.Peek());

            Assert.Null(stack.Peek());

            var emptyStack = fooStack.Pop();

            Assert.Null(emptyStack.Peek());

            Assert.Equal("foo", fooStack.Peek());

            Assert.Null(stack.Peek());
        }
Example #16
0
 public static PositionedUnit PositionNewUnit(int width, ImmutableStack<Unit> nextUnits)
 {
     if (nextUnits.IsEmpty) return PositionedUnit.Null;
     var u = nextUnits.Peek();
     var topmostY = u.Displacements[0].Min(m => m.ToMap().Y);
     var pos = new PositionedUnit(u, 0, new Point(0, -topmostY));
     var leftMargin = pos.Members.Min(m => m.X);
     var rightMargin = width - 1 - pos.Members.Max(m => m.X);
     var newX = (rightMargin - leftMargin) / 2;
     return new PositionedUnit(u, 0, new Point(newX, -topmostY));
 }
        public void Peek_NotEmpty()
        {
            // arrange
            ImmutableStack <string> stack = ImmutableStack <string> .Empty.Push("Bottom").Push("Top");

            // act
            string result = stack.Peek();

            // assert
            Assert.Equal("Top", result);
        }
Example #18
0
        /// <summary>
        /// Closes the top screen on our stack, revealing the screen underneath
        /// </summary>
        /// <remarks>
        /// Won't close the top screen.
        /// </remarks>
        public WordTutorApplication CloseScreen()
        {
            if (_priorScreens.IsEmpty)
            {
                // Don't ever want to close the last screen
                return(this);
            }

            return(new WordTutorApplication(
                       this,
                       currentScreen: _priorScreens.Peek(),
                       priorScreens: _priorScreens.Pop()));
        }
        public void Peek_Empty()
        {
            // arrange
            ImmutableStack <string> stack = ImmutableStack <string> .Empty;

            // act
            Action validate = () => stack.Peek();

            // assert
            InvalidOperationException exception = Assert.Throws <InvalidOperationException>(validate);

            Assert.Equal(ExceptionMessages.ImmutableStackIsEmpty, exception.Message);
        }
Example #20
0
 /// <summary>
 /// Pops the stacked input handler (and all input handlers above it).
 /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
 /// does nothing.
 /// </summary>
 /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
 public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
 {
     if (stackedInputHandlers.Any(i => i == inputHandler))
     {
         ITextAreaInputHandler oldHandler;
         do
         {
             oldHandler           = stackedInputHandlers.Peek();
             stackedInputHandlers = stackedInputHandlers.Pop();
             oldHandler.Detach();
         } while (oldHandler != inputHandler);
     }
 }
Example #21
0
 protected override void VisitDirective(
     DirectiveNode directive,
     ImmutableStack <ISyntaxNode> path)
 {
     if (_directives.TryGetValue(directive.Name.Value, out DirectiveType d) &&
         TryLookupLocation(path.Peek(),
                           out Types.DirectiveLocation location) &&
         !d.Locations.Contains(location))
     {
         Errors.Add(new ValidationError(
                        "The specified directive is not valid the " +
                        "current location.", directive));
     }
 }
Example #22
0
        private static LoggerFileScope GetFileScope(ImmutableStack<string> parents)
        {
            if (!parents.IsEmpty)
            {
                var path = StringExtension.ToDisplayPath(parents.Peek());

                if (!string.IsNullOrEmpty(path))
                {
                    return new LoggerFileScope(path);
                }
            }

            return null;
        }
Example #23
0
        private static LoggerFileScope GetFileScope(ImmutableStack <string> parents)
        {
            if (!parents.IsEmpty)
            {
                var path = StringExtension.ToDisplayPath(parents.Peek());

                if (!string.IsNullOrEmpty(path))
                {
                    return(new LoggerFileScope(path));
                }
            }

            return(null);
        }
Example #24
0
        internal static bool Contains <T>(this ImmutableStack <T> stack, T value)
        {
            Requires.NotNull(stack, nameof(stack));

            while (!stack.IsEmpty)
            {
                if (EqualityComparer <T> .Default.Equals(value, stack.Peek()))
                {
                    return(true);
                }

                stack = stack.Pop();
            }

            return(false);
        }
Example #25
0
        ImmutableStack <int> IncrementPassword(ImmutableStack <int> password)
        {
            var chr  = password.Peek();
            var tail = password.Pop();

            if (chr == 25)
            {
                return(IncrementPassword(tail).Push(0));
            }
            else if (invalidChars.Contains(chr + 1))
            {
                return(tail.Push(chr + 2));
            }
            else
            {
                return(tail.Push(chr + 1));
            }
        }
Example #26
0
        internal string InternalMarkup(string src, ImmutableStack <string> parents)
        {
            LoggerFileScope fileScope = null;

            if (!parents.IsEmpty)
            {
                var path = parents.Peek().ToDisplayPath();
                if (!string.IsNullOrEmpty(path))
                {
                    fileScope = new LoggerFileScope(path);
                }
            }

            using (fileScope)
            {
                return(InternalMarkup(src, Context.SetFilePathStack(parents)));
            }
        }
Example #27
0
 ///<summary>A modified copy with more incremental rebuilding performed (in order to eventually discard garbage).</summary>
 private DropCollectStack <T> IterRebuild()
 {
     return
         // iteratively transfer from _itemsTraverser to _partialReversedItems
         (!_itemsTraverser.IsEmpty ? With(
              itemsTraverser: _itemsTraverser.Pop(),
              partialReversedItems: _partialReversedItems.Push(_itemsTraverser.Peek))
          // then iteratively transfer from _partialReversedItems to _partialRebuiltItems
       : !_partialReversedItems.IsEmpty ? With(
              partialReversedItems: _partialReversedItems.Pop(),
              partialRebuiltItems: _partialRebuiltItems.Push(_partialReversedItems.Peek()))
          // then, if there are new items, place them in _itemsTraverser for iterative transfer
       : _items.Count > _partialRebuiltItems.Count ? With(
              itemsTraverser: _items.Pop().KeepOnly(_items.Count - _partialRebuiltItems.Count - 1),
              partialReversedItems: _partialReversedItems.Push(_items.Peek))
          // if there were no new items, then we've finished rebuilding and can use the result
       : new DropCollectStack <T>(_partialRebuiltItems, _partialRebuiltItems));
 }
Example #28
0
File: Deck.cs Project: jps/Deck
        public (Option <Card> card, Option <Deck> deck) DrawCard()
        {
            if (_cardsInDeck.IsEmpty)
            {
                return(Option.None <Card>(), Option.None <Deck>());
            }

            var drawnCard       = _cardsInDeck.Peek().Some();
            var cardsInNextDeck = _cardsInDeck.Pop();

            if (cardsInNextDeck.IsEmpty)
            {
                return(drawnCard, Option.None <Deck>());
            }

            var nextDeck = new Deck(cardsInNextDeck.ToArray()).Some();

            return(drawnCard, nextDeck);
        }
Example #29
0
        public void When_handling_CreateActor_message_Then_the_LocalActorRef_is_pushed_to_stack_and_afterwards_removed()
        {
            var mailbox           = A.Fake <Mailbox>();
            var actorInstantiator = A.Fake <ActorInstantiator>();
            ImmutableStack <LocalActorRef> stackDuringActorCreation = null;

            A.CallTo(() => actorInstantiator.CreateNewActor()).Invokes(() =>
            {
                stackDuringActorCreation = ActorHelper.GetActorRefStack();
            }).ReturnsLazily(() => new TestActor());
            var actorRef = new LocalActorRef(new TestActorSystem(), actorInstantiator, new RootActorPath("test"), mailbox, A.Dummy <InternalActorRef>());

            actorRef.HandleSystemMessage(new SystemMessageEnvelope(actorRef, new CreateActor(), A.Fake <ActorRef>()));
            var stackAfterActorCreation = ActorHelper.GetActorRefStack();

            stackDuringActorCreation.IsEmpty.Should().BeFalse("The stack should contain one item");
            stackDuringActorCreation.Peek().Should().BeSameAs(actorRef, "The item on stack should be the LocalActorRef that creates the actor");
            stackDuringActorCreation.Count().Should().Be(1, "The stack should only contain one item.");
            (stackAfterActorCreation == null || stackAfterActorCreation.IsEmpty).Should().BeTrue("The stack should be empty after creation");
        }
Example #30
0
 private void MaybeAddGlobal(string name, HashSet <string> locals, ImmutableStack <JsDeclarationScope> functionStack)
 {
     if (!locals.Contains(name))
     {
         if (_reportGlobalsAsUsedInAllParentScopes)
         {
             foreach (var f in functionStack)
             {
                 _result[f].Add(name);
             }
         }
         else
         {
             if (!functionStack.IsEmpty)
             {
                 _result[functionStack.Peek()].Add(name);
             }
         }
     }
 }
        public override JsStatement VisitBreakStatement(JsBreakStatement statement, object data)
        {
            Tuple <string, State> state;

            if (statement.TargetLabel == null)
            {
                state = _breakStack.Peek();
            }
            else
            {
                state = _breakStack.SingleOrDefault(x => x != null && x.Item1 == statement.TargetLabel);
            }

            if (state != null)
            {
                return(new JsGotoStateStatement(state.Item2, _currentState));
            }
            else
            {
                return(statement);
            }
        }
Example #32
0
        public void CanPopOffMultipleItems()
        {
            var original = new ImmutableStack <string>();

            Assert.Null(original.Peek());
            Assert.Equal(0, original.Count);

            var stack = original.Push("foo").Push("bar");

            Assert.Equal(2, stack.Count);
            Assert.Equal("bar", stack.Peek());

            stack = stack.Pop();
            Assert.Equal("foo", stack.Peek());
            Assert.Equal(1, stack.Count);

            stack = stack.Pop();
            Assert.Null(stack.Peek());
            Assert.Equal(0, original.Count);

            Assert.Same(stack, original);
        }
        private Tuple<State, bool> GetStateAfterStatement(StackEntry location, ImmutableStack<StackEntry> stack, ImmutableStack<Tuple<int, string>> finallyStack, State returnState)
        {
            JsStatement next;
            if (location.Index < location.Block.Statements.Count - 1) {
                next = location.Block.Statements[location.Index + 1];
            }
            else if (!stack.IsEmpty) {
                var tos = stack.Peek();
                next = tos.Block.Statements[tos.Index];
            }
            else
                next = null;

            if (next is JsLabelledStatement) {
                return Tuple.Create(GetOrCreateStateForLabel((next as JsLabelledStatement).Label, finallyStack), false);
            }
            else if (next != null) {
                return Tuple.Create(CreateNewStateValue(finallyStack), true);
            }
            else {
                return Tuple.Create(returnState, false);
            }
        }
        private List<JsStatement> Handle(ImmutableStack<StackEntry> stack, ImmutableStack<Tuple<string, State>> breakStack, ImmutableStack<Tuple<string, State>> continueStack, State currentState, State returnState)
        {
            var currentBlock = new List<JsStatement>();
            while (!stack.IsEmpty) {
                var tos = stack.Peek();
                stack = stack.Pop();

                var stmt = tos.Block.Statements[tos.Index];
                var lbl = stmt as JsLabelledStatement;
                if (lbl != null) {
                    if (_processedStates.Contains(GetOrCreateStateForLabel(lbl.Label, currentState.FinallyStack))) {
                        // First statement in the new block
                        stmt = lbl.Statement;
                    }
                    else {
                        // A label that terminates the current block.
                        Enqueue(stack.Push(new StackEntry(tos.Block, tos.Index)), breakStack, continueStack, GetOrCreateStateForLabel(lbl.Label, currentState.FinallyStack), returnState);
                        if (currentBlock.Count == 0 || IsNextStatementReachable(currentBlock[currentBlock.Count - 1]))
                            currentBlock.Add(new JsGotoStateStatement(GetOrCreateStateForLabel(lbl.Label, currentState.FinallyStack), currentState));
                        return currentBlock;
                    }
                }

                if (stmt is JsYieldStatement) {
                    var ystmt = (JsYieldStatement)stmt;
                    if (ystmt.Value != null) {
                        if (!HandleYieldReturnStatement(ystmt, tos, stack, breakStack, continueStack, currentState, returnState, currentBlock))
                            return currentBlock;
                    }
                    else {
                        currentBlock.AddRange(new NestedJumpStatementRewriter(breakStack, continueStack, currentState, _exitState.Value).Process(stmt));
                        stack = PushFollowing(stack, tos);
                    }
                }
                else if (stmt is JsTryStatement) {
                    if (!HandleTryStatement((JsTryStatement)stmt, tos, stack, breakStack, continueStack, currentState, returnState, currentBlock))
                        return currentBlock;
                    stack = PushFollowing(stack, tos);
                }
                else if (FindInterestingConstructsVisitor.Analyze(stmt, InterestingConstruct.YieldReturn | InterestingConstruct.Label)) {
                    if (stmt is JsBlockStatement) {
                        stack = PushFollowing(stack, tos).Push(new StackEntry((JsBlockStatement)stmt, 0));
                    }
                    else {
                        if (stmt is JsIfStatement) {
                            if (!HandleIfStatement((JsIfStatement)stmt, tos, stack, breakStack, continueStack, currentState, returnState, currentBlock))
                                return currentBlock;
                        }
                        else if (stmt is JsDoWhileStatement) {
                            if (!HandleDoWhileStatement((JsDoWhileStatement)stmt, tos, stack, breakStack, continueStack, currentState, returnState, currentBlock))
                                return currentBlock;
                        }
                        else if (stmt is JsWhileStatement) {
                            if (!HandleWhileStatement((JsWhileStatement)stmt, tos, stack, breakStack, continueStack, currentState, returnState, currentBlock))
                                return currentBlock;
                        }
                        else if (stmt is JsForStatement) {
                            if (!HandleForStatement((JsForStatement)stmt, tos, stack, breakStack, continueStack, currentState, returnState, currentBlock))
                                return currentBlock;
                        }
                        else if (stmt is JsSwitchStatement) {
                            if (!HandleSwitchStatement((JsSwitchStatement)stmt, tos, stack, breakStack, continueStack, currentState, returnState, currentBlock))
                                return currentBlock;
                        }
                        else {
                            throw new NotSupportedException("Statement " + stmt + " cannot contain labels.");
                        }

                        stack = PushFollowing(stack, tos);
                    }
                }
                else {
                    currentBlock.AddRange(new NestedJumpStatementRewriter(breakStack, continueStack, currentState, _exitState.Value).Process(stmt));
                    stack = PushFollowing(stack, tos);
                }
            }
            if (currentBlock.Count == 0 || IsNextStatementReachable(currentBlock[currentBlock.Count - 1]))
                currentBlock.Add(new JsGotoStateStatement(returnState, currentState));

            return currentBlock;
        }
		List<InternalObject> CreateElements(ref ImmutableStack<InternalObject> inputObjects)
		{
			List<InternalObject> objects = new List<InternalObject>();
			while (!inputObjects.IsEmpty) {
				var obj = inputObjects.Peek();
				var tag = obj as InternalTag;
				if (tag != null && tag.IsStartTag)
					break;
				inputObjects = inputObjects.Pop();
				if (tag != null && tag.IsEndTag) {
					if (inputObjects.Peek() == StartTagPlaceholder) {
						objects.Add(tag.AddSyntaxError("Matching opening tag was not found"));
						inputObjects = inputObjects.Pop();
					} else {
						var childElements = CreateElements(ref inputObjects);
						var startTag = (InternalTag)inputObjects.Peek();
						inputObjects = inputObjects.Pop();
						childElements.Add(startTag);
						childElements.Reverse();
						if (tag != EndTagPlaceholder) {
							// add end tag
							if (startTag.Name != tag.Name) {
								childElements.Add(tag.AddSyntaxError("Expected '</" + startTag.Name + ">'. End tag must have same name as start tag."));
							} else {
								childElements.Add(tag);
							}
						}
						InternalElement e = new InternalElement(startTag);
						e.HasEndTag = (tag != EndTagPlaceholder);
						e.NestedObjects = new InternalObject[childElements.Count];
						int pos = 0;
						for (int i = 0; i < childElements.Count; i++) {
							e.NestedObjects[i] = childElements[i].SetStartRelativeToParent(pos);
							pos += e.NestedObjects[i].Length;
						}
						e.Length = pos;
						if (tag == EndTagPlaceholder) {
							e.SyntaxErrors = new [] { new InternalSyntaxError(pos, pos, "Missing '</" + startTag.Name + ">'") };
						}
						objects.Add(e);
					}
				} else {
					objects.Add(obj);
				}
			}
			return objects;
		}