Example #1
0
 public int solution(int[] A, int[] B)
 {
     var ret = 0;
     var up = new System.Collections.Generic.Stack<int>();
     for (int i = A.Length - 1; i >= 0; i--)
     {
         if (B[i] == 1)
         {
             while (up.Count > 0)
             {
                 var fishSize = up.Peek();
                 if (A[i] > fishSize)
                     up.Pop(); // remove one from stack
                 else
                     break; // downFish was eaten, break circle
             }
             if (up.Count == 0)
                 ret++; // downFish ate all upFishes
         }
         else
         {
             up.Push(A[i]);
         }
     }
     while (up.Count > 0)
     {
         var fishSize = up.Pop();
         ret++;
     }
     return ret;
 }
Example #2
0
 public StatementVisitor(Statement entryPoint)
 {
     programStack = new System.Collections.Generic.Stack<System.Collections.Generic.Queue<Statement>>();
     programStack.Push(new System.Collections.Generic.Queue<Statement>());
     programStack.Peek ().Enqueue(entryPoint);
     TimeControl.OnStartCycle += OnStartCycle;
     TimeControl.OnTelegraph += OnTelegraph;
     TimeControl.OnStart += OnStartAction;
     TimeControl.OnStop += OnStopAction;
     TimeControl.OnEndCycle += OnEndCycle;
 }
Example #3
0
    //Evaluating RPN
    public static void evalu(string output)
    {
        int num1 = 0;
            int num2 = 0;
            System.Collections.Generic.Stack<int> myStack = new System.Collections.Generic.Stack<int>();
            foreach (char token in output)
            {
                if (Char.IsNumber(token) == true)
                {
                    myStack.Push(int.Parse(token.ToString()));
                }
                if (token == '+' || token == '-' || token == '*' || token == '/')
                {
                    if (token == '+')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 + num2);
                    }

                    if (token == '-')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num2 - num1);
                    }
                    if (token == '*')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 * num2);
                    }
                    if (token == '/')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 / num2);
                    }
                }
            }
        PrintValues(myStack, ' ');
    }
Example #4
0
        //revision:clear 12/2/2012
        public static bool validatePushPop(double[] pop)
        {
            int i = 0, length = pop.Length;
            bool[] positioned = new bool[1 + length];
            System.Collections.Generic.Stack<int> s = new System.Collections.Generic.Stack<int>();
            while (i < length)
            {
                if (s.Count == 0 || s.Peek() != pop[i])
                {
                    int n = 1; bool f = true;
                    while (n <= pop[i])
                    {
                        if (!positioned[n])
                        {
                            f = false;
                            s.Push(n);
                            positioned[n] = true;
                        }
                        n++;
                    }
                    if (f)
                    {
                        return false;
                    }
                }
                else if (s.Count != 0 && s.Peek() == pop[i])
                {
                    s.Pop();
                    i++;
                }
                else
                {
                    return false;
                }

            }

            return true;
        }
        public static void Main()
        {
            System.Collections.Generic.Stack<int> stack =
                new System.Collections.Generic.Stack<int>();
            int number;
            // ...

            // This code is conceptual, not the actual code.
            while(stack.Pop() != -1) //this is actually not the right logic, but the point is the while, not stack
            {
                number = stack.Peek();
                Console.WriteLine(number);
            }
        }
Example #6
0
            public int solution(int[] H)
            {
                var blockCount = 0;
                var stack = new System.Collections.Generic.Stack<Tuple<int, int>>();

                foreach (var h in H)
                {
                    var lastBlockBottom = 0;
                    var lastBlockTop = 0;
                    if (stack.Count != 0)
                    {
                        var lastBlock = stack.Peek();
                        lastBlockBottom = lastBlock.Item1;
                        lastBlockTop = lastBlock.Item2;
                    }
                    if (h > lastBlockTop)
                    {
                        stack.Push(new Tuple<int, int>(lastBlockTop, h));
                    }
                    else if (h < lastBlockTop)
                    {
                        stack.Pop();
                        blockCount++;

                        while (h < lastBlockBottom)
                        {
                            var lastBlock = stack.Pop();
                            blockCount++;
                            lastBlockBottom = lastBlock.Item1;
                        }
                        if (h > lastBlockBottom)
                        {
                            stack.Push(new Tuple<int, int>(lastBlockBottom, h));
                        }
                    }
                }

                return blockCount + stack.Count;
            }
Example #7
0
        private static int CalculateIndentation(string baseline, ITextSnapshotLine line, IEditorOptions options, IClassifier classifier, ITextView textView)
        {
            int indentation = GetIndentation(baseline, options.GetTabSize());
            int tabSize     = options.GetIndentSize();
            var tokens      = classifier.GetClassificationSpans(line.Extent);

            if (tokens.Count > 0 && !IsUnterminatedStringToken(tokens[tokens.Count - 1]))
            {
                int tokenIndex = tokens.Count - 1;

                while (tokenIndex >= 0 &&
                       (tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) ||
                        tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.WhiteSpace)))
                {
                    tokenIndex--;
                }

                if (tokenIndex < 0)
                {
                    return(indentation);
                }

                if (ReverseExpressionParser.IsExplicitLineJoin(tokens[tokenIndex]))
                {
                    // explicit line continuation, we indent 1 level for the continued line unless
                    // we're already indented because of multiple line continuation characters.

                    indentation = GetIndentation(line.GetText(), options.GetTabSize());
                    var joinedLine = tokens[tokenIndex].Span.Start.GetContainingLine();
                    if (joinedLine.LineNumber > 0)
                    {
                        var prevLineSpans = classifier.GetClassificationSpans(tokens[tokenIndex].Span.Snapshot.GetLineFromLineNumber(joinedLine.LineNumber - 1).Extent);
                        if (prevLineSpans.Count == 0 || !ReverseExpressionParser.IsExplicitLineJoin(prevLineSpans[prevLineSpans.Count - 1]))
                        {
                            indentation += tabSize;
                        }
                    }
                    else
                    {
                        indentation += tabSize;
                    }

                    return(indentation);
                }

                string sline    = tokens[tokenIndex].Span.GetText();
                var    lastChar = sline.Length == 0 ? '\0' : sline[sline.Length - 1];

                // use the expression parser to figure out if we're in a grouping...
                var spans = textView.BufferGraph.MapDownToFirstMatch(
                    tokens[tokenIndex].Span,
                    SpanTrackingMode.EdgePositive,
                    PythonContentTypePrediciate
                    );
                if (spans.Count == 0)
                {
                    return(indentation);
                }

                var revParser = new ReverseExpressionParser(
                    spans[0].Snapshot,
                    spans[0].Snapshot.TextBuffer,
                    spans[0].Snapshot.CreateTrackingSpan(
                        spans[0].Span,
                        SpanTrackingMode.EdgePositive
                        )
                    );

                var tokenStack = new System.Collections.Generic.Stack <ClassificationSpan>();
                tokenStack.Push(null);  // end with an implicit newline
                bool endAtNextNull = false;

                foreach (var token in revParser)
                {
                    tokenStack.Push(token);
                    if (token == null && endAtNextNull)
                    {
                        break;
                    }
                    else if (token != null &&
                             token.ClassificationType == revParser.Classifier.Provider.Keyword &&
                             PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText()))
                    {
                        endAtNextNull = true;
                    }
                }

                var indentStack = new System.Collections.Generic.Stack <LineInfo>();
                var current     = LineInfo.Empty;

                while (tokenStack.Count > 0)
                {
                    var token = tokenStack.Pop();
                    if (token == null)
                    {
                        current.NeedsUpdate = true;
                    }
                    else if (token.IsOpenGrouping())
                    {
                        indentStack.Push(current);
                        var start = token.Span.Start;
                        var line2 = start.GetContainingLine();
                        var next  = tokenStack.Count > 0 ? tokenStack.Peek() : null;
                        if (next != null && next.Span.End <= line2.End)
                        {
                            current = new LineInfo {
                                Indentation = start.Position - line2.Start.Position + 1
                            };
                        }
                        else
                        {
                            current = new LineInfo {
                                Indentation = GetIndentation(line2.GetText(), tabSize) + tabSize
                            };
                        }
                    }
                    else if (token.IsCloseGrouping())
                    {
                        if (indentStack.Count > 0)
                        {
                            current = indentStack.Pop();
                        }
                        else
                        {
                            current.NeedsUpdate = true;
                        }
                    }
                    else if (ReverseExpressionParser.IsExplicitLineJoin(token))
                    {
                        while (token != null && tokenStack.Count > 0)
                        {
                            token = tokenStack.Pop();
                        }
                    }
                    else if (current.NeedsUpdate == true)
                    {
                        var line2 = token.Span.Start.GetContainingLine();
                        current = new LineInfo {
                            Indentation = GetIndentation(line2.GetText(), tabSize)
                        };
                    }

                    if (token != null && ShouldDedentAfterKeyword(token))       // dedent after some statements
                    {
                        current.ShouldDedentAfter = true;
                    }

                    if (token != null && token.Span.GetText() == ":" &&         // indent after a colon
                        indentStack.Count == 0)                                 // except in a grouping
                    {
                        current.ShouldIndentAfter = true;
                        // If the colon isn't at the end of the line, cancel it out.
                        // If the following is a ShouldDedentAfterKeyword, only one dedent will occur.
                        current.ShouldDedentAfter = (tokenStack.Count != 0 && tokenStack.Peek() != null);
                    }
                }

                indentation = current.Indentation +
                              (current.ShouldIndentAfter ? tabSize : 0) -
                              (current.ShouldDedentAfter ? tabSize : 0);
            }

            // Map indentation back to the view's text buffer.
            int offset        = 0;
            var viewLineStart = textView.BufferGraph.MapUpToSnapshot(line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot);

            if (viewLineStart.HasValue)
            {
                offset = viewLineStart.Value.Position - viewLineStart.Value.GetContainingLine().Start.Position;
            }

            return(offset + indentation);
        }
Example #8
0
        protected override void HandleElementStart(ParserNode node)
        {
            HandleQuickTags(node, true);

            ParserNode next = node.NextNode;
            ParserNode prev = node.PrevNode;

            switch (node.Name)
            {
            case "p":
                if (node.Attributes["style"] != null || node.Attributes["class"] != null || _exitExtendedBlock)
                {
                    AddBlockTag(node, "p", true);
                }
                else
                {
                    AddOutput("", 2, true);
                }

                break;

            case "h1":
            case "h2":
            case "h3":
            case "h4":
            case "h5":
            case "h6":
            case "h7":
                AddBlockTag(node, node.Name, true);
                break;

            case "blockquote":
                AddBlockTag(node, "bq", true);
                break;

            case "a":
                AddOutput(" \"");
                AddOutput(GetStyleOrClassStr(CurrentNode));
                //text node will be aded next, then on the end tag,
                //we will output the href and all that.
                CurrentLink = CurrentNode;
                break;

            case "img":
                string src = node.Attributes["src"];
                if (src != null)
                {
                    AddOutput(string.Format(" !{0}{1}! ", GetStyleOrClassStr(CurrentNode), src));
                }
                break;

            case "br":
                AddOutput("\n");
                break;

            case "pre":

                //lookahead. If the next element is code,
                //dont print the pre. .
                if (next != null &&
                    next.NodeType == System.Xml.XmlNodeType.Element &&
                    next.Name == "code")
                {
                    break;
                }
                AddExtendedBlockTag(node, "pre", true);
                break;

            case "code":
                if (prev != null &&
                    prev.NodeType == System.Xml.XmlNodeType.Element &&
                    prev.Name == "pre")
                {
                    AddExtendedBlockTag(node, "bc", true);
                }
                break;


            //lists!
            case "ol":
                AddOutput("", _listDepth > 0 ? 1 : 2, true);
                _listDepth++;
                _inList.Push(ListType.Ordered);
                break;

            case "ul":
                AddOutput("", _listDepth > 0 ? 1 : 2, true);
                _listDepth++;
                _inList.Push(ListType.Unordered);
                break;

            case "li":

                //lookahead. If the next element is a nested list,
                //dont print the list indicator.
                if (next != null &&
                    next.NodeType == System.Xml.XmlNodeType.Element &&
                    (next.Name == "ul" || next.Name == "ol"))
                {
                    break;
                }

                if (_inList.Peek() == ListType.Ordered)
                {
                    AddOutput(RepeatStr("#", _listDepth) + " ", 1, true);
                }
                else
                {
                    AddOutput(RepeatStr("*", _listDepth) + " ", 1, true);
                }

                break;

            //TABLES
            case "table":
                AddOutput("", 2, true);
                _inTable = true;
                break;

            case "td":
            case "th":
                string pre     = "";
                string colspan = node.Attributes["colspan"];
                string rowspan = node.Attributes["rowspan"];

                if (node.Name == "th")
                {
                    pre += "_";
                }
                if (colspan != null && NUMRE.IsMatch(colspan))
                {
                    pre += "/" + colspan;
                }
                if (rowspan != null && NUMRE.IsMatch(rowspan))
                {
                    pre += "\\" + rowspan;
                }

                if (pre.Length > 0)
                {
                    pre += ". ";
                }

                AddOutput("|" + pre);
                break;


            default:
                break;
            }
        }
 public T Peek() => stack.Peek();
Example #10
0
        private static SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null) return null;

            // inject spaces after open paren and before close paren
            string[][] prPairs =
                {
                    new string[] { @"\(\(", "( (" },
                    new string[] { @"\)\)", ") )" },
                    new string[] { @"\((\S)", "( $1" },
                    new string[] { @"(\S)\)", "$1 )" },
                    new string[] { @"(\S)\(", "$1 (" },
                    new string[] { @"\)(\S)", ") $1" },
                    new string[] { @"([^ ]+)>([^ ]+)", "$1 > $2" },
                    new string[] { @"([^ ]+)<([^ ]+)", "$1 < $2" },
                    new string[] { @"([^ ]+)!=([^ ]+)", "$1 != $2" },
                    new string[] { @"([^ ]+)=([^ ]+)", "$1 = $2" },
                };
            for (int i = 0; i < prPairs.Length; i++)
            {
                Regex rgx = new Regex(prPairs[i][0]);
                s = rgx.Replace(s, prPairs[i][1]);
            }

            // shorthand for filename glob
            if (s.IndexOf(" ") == -1)
                s = "name = " + s;

            // split the expression into tokens
            string[] tokens = s.Trim().Split(' ', '\t');

            if (tokens.Length < 3) throw new ArgumentException(s);

            SelectionCriterion current = null;

            LogicalConjunction pendingConjunction = LogicalConjunction.NONE;

            ParseState state;
            var stateStack = new System.Collections.Generic.Stack<ParseState>();
            var critStack = new System.Collections.Generic.Stack<SelectionCriterion>();
            stateStack.Push(ParseState.Start);

            for (int i = 0; i < tokens.Length; i++)
            {
                string tok1 = tokens[i].ToLower();
                switch (tok1)
                {
                    case "and":
                    case "xor":
                    case "or":
                        state = stateStack.Peek();
                        if (state != ParseState.CriterionDone)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 3)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        pendingConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), tokens[i].ToUpper(), true);
                        current = new CompoundCriterion { Left = current, Right = null, Conjunction = pendingConjunction };
                        stateStack.Push(state);
                        stateStack.Push(ParseState.ConjunctionPending);
                        critStack.Push(current);
                        break;

                    case "(":
                        state = stateStack.Peek();
                        if (state != ParseState.Start && state != ParseState.ConjunctionPending && state != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 4)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Push(ParseState.OpenParen);
                        break;

                    case ")":
                        state = stateStack.Pop();
                        if (stateStack.Peek() != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Pop();
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "atime":
                    case "ctime":
                    case "mtime":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        DateTime t;
                        try
                        {
                            t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd-HH:mm:ss", null);
                        }
                        catch (FormatException)
                        {
                            try
                            {
                                t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd-HH:mm:ss", null);
                            }
                            catch (FormatException)
                            {
                                try
                                {
                                    t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd", null);
                                }
                                catch (FormatException)
                                {
                                    try
                                    {
                                        t = DateTime.ParseExact(tokens[i + 2], "MM/dd/yyyy", null);
                                    }
                                    catch (FormatException)
                                    {
                                        t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
                                    }
                                }
                            }
                        }
                        t= DateTime.SpecifyKind(t, DateTimeKind.Local).ToUniversalTime();
                        current = new TimeCriterion
                        {
                            Which = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i], true),
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]),
                            Time = t
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;


                    case "length":
                    case "size":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        Int64 sz = 0;
                        string v = tokens[i + 2];
                        if (v.ToUpper().EndsWith("K"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024;
                        else if (v.ToUpper().EndsWith("KB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024;
                        else if (v.ToUpper().EndsWith("M"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("MB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("G"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("GB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024 * 1024;
                        else sz = Int64.Parse(tokens[i + 2]);

                        current = new SizeCriterion
                        {
                            Size = sz,
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1])
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "filename":
                    case "name":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            string m = tokens[i + 2];
                            // handle single-quoted filespecs (used to include spaces in filename patterns)
                            if (m.StartsWith("'"))
                            {
                                int ix = i;
                                if (!m.EndsWith("'"))
                                {
                                    do
                                    {
                                        i++;
                                        if (tokens.Length <= i + 2)
                                            throw new ArgumentException(String.Join(" ", tokens, ix, tokens.Length - ix));
                                        m += " " + tokens[i + 2];
                                    } while (!tokens[i + 2].EndsWith("'"));
                                }
                                // trim off leading and trailing single quotes
                                m = m.Substring(1, m.Length - 2);
                            }

                            current = new NameCriterion
                            {
                                MatchingFileSpec = m,
                                Operator = c
                            };
                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

                    case "attrs":
                    case "attributes":
                    case "type":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            current = (tok1 == "type")
                                ? (SelectionCriterion) new TypeCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    }
                                : (SelectionCriterion) new AttributesCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    };

                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

                    case "":
                        // NOP
                        stateStack.Push(ParseState.Whitespace);
                        break;

                    default:
                        throw new ArgumentException("'" + tokens[i] + "'");
                }

                state = stateStack.Peek();
                if (state == ParseState.CriterionDone)
                {
                    stateStack.Pop();
                    if (stateStack.Peek() == ParseState.ConjunctionPending)
                    {
                        while (stateStack.Peek() == ParseState.ConjunctionPending)
                        {
                            var cc = critStack.Pop() as CompoundCriterion;
                            cc.Right = current;
                            current = cc; // mark the parent as current (walk up the tree)
                            stateStack.Pop();   // the conjunction is no longer pending

                            state = stateStack.Pop();
                            if (state != ParseState.CriterionDone)
                                throw new ArgumentException("??");
                        }
                    }
                    else stateStack.Push(ParseState.CriterionDone);  // not sure?
                }

                if (state == ParseState.Whitespace)
                    stateStack.Pop();
            }

            return current;
        }
        private static string InfixToRpn(string infix)
        {
            // Replace comma separator with white space for function-like use of operators.
            infix = infix.Replace(Interpreter.CommaSeparatorChar, Interpreter.WhiteSpaceChar);

            // Add operator markers.
            for (int index = 0; index < infix.Length; ++index)
            {
                if (infix[index] == Interpreter.VarPrefixChar)
                {
                    index = Interpreter.SkipString(infix, index + 2);
                }
                else if (Interpreter.IsAlpha(infix[index]))
                {
                    infix = infix.Insert(index, Interpreter.LongOpMark0Str);
                    index = Interpreter.SkipString(infix, index + 2);
                    infix = infix.Insert(index, Interpreter.LongOpMark1Str);
                }
                else if (Interpreter.IsSpecial(infix[index]))
                {
                    infix = infix.Insert(index, Interpreter.LongOpMark0Str);
                    index = Interpreter.SkipSpecial(infix, index + 2);
                    infix = infix.Insert(index, Interpreter.LongOpMark1Str);
                }
            }

            // Add blank spaces where needed.
            for (int index = 0; index < infix.Length; ++index)
            {
                if (Interpreter.operators.ContainsKey(infix[index].ToString()) || infix[index] == Interpreter.VarPrefixChar || infix[index] == Interpreter.OpMarkChar ||
                    infix[index] == Interpreter.OpenBracketChar || infix[index] == Interpreter.ClosingBracketChar)
                {
                    // Ignore variable. It would be a mess to find an operator in the middle of a variable name...
                    if (infix[index] == Interpreter.VarPrefixChar)
                    {
                        index = Interpreter.SkipString(infix, index + 2);
                        //continue;
                    }

                    if (index != 0 && infix[index - 1] != Interpreter.WhiteSpaceChar)
                    {
                        infix = infix.Insert(index, Interpreter.WhiteSpaceStr);
                    }

                    // Handle long operators.
                    int jndex = index;
                    if (infix[index] == Interpreter.OpMarkChar)
                    {
                        jndex = infix.IndexOf(Interpreter.OpMarkChar, index + 1);
                    }

                    if (jndex != infix.Length - 1 && infix[jndex + 1] != Interpreter.OpMarkChar)
                    {
                        infix = infix.Insert(jndex + 1, Interpreter.WhiteSpaceStr);
                    }

                    index = jndex;
                }
            }

            // Trim long op mark and white spaces.
            infix = System.Text.RegularExpressions.Regex.Replace(infix.Replace(Interpreter.OpMarkStr, string.Empty), @"\s+", " ");
            infix = infix.TrimStart(WhiteSpaceChar);
            infix = infix.TrimEnd(WhiteSpaceChar);

            string[] tokens = infix.Split(Interpreter.WhiteSpaceChar);
            System.Collections.Generic.List <string>  list  = new System.Collections.Generic.List <string>();  //TODO: static
            System.Collections.Generic.Stack <string> stack = new System.Collections.Generic.Stack <string>(); //TODO: static

            for (int tokenIndex = 0; tokenIndex < tokens.Length; ++tokenIndex)
            {
                string token = tokens[tokenIndex];

                if (string.IsNullOrEmpty(token) || token == Interpreter.WhiteSpaceStr)
                {
                    continue;
                }

                if (Interpreter.operators.ContainsKey(token))
                {
                    while (stack.Count > 0 && Interpreter.operators.ContainsKey(stack.Peek()))
                    {
                        if (ComparePrecedence(token, stack.Peek()) < 0)
                        {
                            list.Add(stack.Pop());
                            continue;
                        }

                        break;
                    }

                    stack.Push(token);
                }
                else if (token == Interpreter.OpenBracketStr)
                {
                    stack.Push(token);
                }
                else if (token == Interpreter.ClosingBracketStr)
                {
                    while (stack.Count > 0 && stack.Peek() != Interpreter.OpenBracketStr)
                    {
                        list.Add(stack.Pop());
                    }

                    stack.Pop();
                }
                else
                {
                    list.Add(token);
                }
            }

            while (stack.Count > 0)
            {
                list.Add(stack.Pop());
            }

            string rpn = string.Join(Interpreter.WhiteSpaceStr, list.ToArray());

            return(rpn);
        }
Example #12
0
        public string PrettyPrint(string input)
        {
            System.Text.StringBuilder output = new System.Text.StringBuilder(input.Length * 2);
            char c;

            for (int i = 0; i < input.Length; i++)
            {
                c = input[i];

                switch (c)
                {
                case '{':
                    if (!InString())
                    {
                        if (inVariableAssignment || (context.Count > 0 && context.Peek() != JsonContextType.Array))
                        {
                            output.Append(NewLine);
                            BuildIndents(context.Count, output);
                        }
                        output.Append(c);
                        context.Push(JsonContextType.Object);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '}':
                    if (!InString())
                    {
                        output.Append(NewLine);
                        context.Pop();
                        BuildIndents(context.Count, output);
                        output.Append(c);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '[':
                    output.Append(c);

                    if (!InString())
                    {
                        context.Push(JsonContextType.Array);
                    }

                    break;

                case ']':
                    if (!InString())
                    {
                        output.Append(c);
                        context.Pop();
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '=':
                    output.Append(c);
                    break;

                case ',':
                    output.Append(c);

                    if (!InString() && context.Peek() != JsonContextType.Array)
                    {
                        BuildIndents(context.Count, output);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                        inVariableAssignment = false;
                    }

                    break;

                case '\'':
                    if (!inDoubleString && prevChar != '\\')
                    {
                        inSingleString = !inSingleString;
                    }

                    output.Append(c);
                    break;

                case ':':
                    if (!InString())
                    {
                        inVariableAssignment = true;
                        output.Append(Space);
                        output.Append(c);
                        output.Append(Space);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '"':
                    if (!inSingleString && prevChar != '\\')
                    {
                        inDoubleString = !inDoubleString;
                    }

                    output.Append(c);
                    break;

                case ' ':
                    if (InString())
                    {
                        output.Append(c);
                    }
                    break;

                default:
                    output.Append(c);
                    break;
                }
                prevChar = c;
            }

            return(output.ToString());
        }
Example #13
0
        private static SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null)
            {
                return(null);
            }

            // shorthand for filename glob
            if (s.IndexOf(" ") == -1)
            {
                s = "name = " + s;
            }

            // inject spaces after open paren and before close paren
            string[] prPairs = { @"\((\S)", "( $1", @"(\S)\)", "$1 )", };
            for (int i = 0; i + 1 < prPairs.Length; i += 2)
            {
                Regex rgx = new Regex(prPairs[i]);
                s = rgx.Replace(s, prPairs[i + 1]);
            }

            // split the expression into tokens
            string[] tokens = s.Trim().Split(' ', '\t');

            if (tokens.Length < 3)
            {
                throw new ArgumentException(s);
            }

            SelectionCriterion current = null;

            LogicalConjunction pendingConjunction = LogicalConjunction.NONE;

            ParseState state;
            var        stateStack = new System.Collections.Generic.Stack <ParseState>();
            var        critStack  = new System.Collections.Generic.Stack <SelectionCriterion>();

            stateStack.Push(ParseState.Start);

            for (int i = 0; i < tokens.Length; i++)
            {
                switch (tokens[i].ToLower())
                {
                case "and":
                case "xor":
                case "or":
                    state = stateStack.Peek();
                    if (state != ParseState.CriterionDone)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    if (tokens.Length <= i + 3)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    pendingConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), tokens[i].ToUpper());
                    current            = new CompoundCriterion {
                        Left = current, Right = null, Conjunction = pendingConjunction
                    };
                    stateStack.Push(state);
                    stateStack.Push(ParseState.ConjunctionPending);
                    critStack.Push(current);
                    break;

                case "(":
                    state = stateStack.Peek();
                    if (state != ParseState.Start && state != ParseState.ConjunctionPending && state != ParseState.OpenParen)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    if (tokens.Length <= i + 4)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    stateStack.Push(ParseState.OpenParen);
                    break;

                case ")":
                    state = stateStack.Pop();
                    if (stateStack.Peek() != ParseState.OpenParen)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    stateStack.Pop();
                    stateStack.Push(ParseState.CriterionDone);
                    break;

                case "atime":
                case "ctime":
                case "mtime":
                    if (tokens.Length <= i + 2)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    DateTime t;
                    try
                    {
                        t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd-HH:mm:ss", null);
                    }
                    catch (FormatException)
                    {
                        t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
                    }
                    t       = DateTime.SpecifyKind(t, DateTimeKind.Local).ToUniversalTime();
                    current = new TimeCriterion
                    {
                        Which    = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i]),
                        Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]),
                        Time     = t
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                    break;


                case "length":
                case "size":
                    if (tokens.Length <= i + 2)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    Int64  sz = 0;
                    string v  = tokens[i + 2];
                    if (v.ToUpper().EndsWith("K"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024;
                    }
                    else if (v.ToUpper().EndsWith("KB"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024;
                    }
                    else if (v.ToUpper().EndsWith("M"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024;
                    }
                    else if (v.ToUpper().EndsWith("MB"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024;
                    }
                    else if (v.ToUpper().EndsWith("G"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024 * 1024;
                    }
                    else if (v.ToUpper().EndsWith("GB"))
                    {
                        sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024 * 1024;
                    }
                    else
                    {
                        sz = Int64.Parse(tokens[i + 2]);
                    }

                    current = new SizeCriterion
                    {
                        Size     = sz,
                        Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1])
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                    break;

                case "filename":
                case "name":
                {
                    if (tokens.Length <= i + 2)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    ComparisonOperator c =
                        (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                    if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    string m = tokens[i + 2];
                    // handle single-quoted filespecs (used to include spaces in filename patterns)
                    if (m.StartsWith("'"))
                    {
                        int ix = i;
                        if (!m.EndsWith("'"))
                        {
                            do
                            {
                                i++;
                                if (tokens.Length <= i + 2)
                                {
                                    throw new ArgumentException(String.Join(" ", tokens, ix, tokens.Length - ix));
                                }
                                m += " " + tokens[i + 2];
                            } while (!tokens[i + 2].EndsWith("'"));
                        }
                        // trim off leading and trailing single quotes
                        m = m.Substring(1, m.Length - 2);
                    }

                    current = new NameCriterion
                    {
                        MatchingFileSpec = m,
                        Operator         = c
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                }
                break;

                case "attributes":
                {
                    if (tokens.Length <= i + 2)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    ComparisonOperator c =
                        (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                    if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                    {
                        throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
                    }

                    current = new AttributesCriterion
                    {
                        AttributeString = tokens[i + 2],
                        Operator        = c
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                }
                break;

                case "":
                    // NOP
                    stateStack.Push(ParseState.Whitespace);
                    break;

                default:
                    throw new ArgumentException("'" + tokens[i] + "'");
                }

                state = stateStack.Peek();
                if (state == ParseState.CriterionDone)
                {
                    stateStack.Pop();
                    if (stateStack.Peek() == ParseState.ConjunctionPending)
                    {
                        while (stateStack.Peek() == ParseState.ConjunctionPending)
                        {
                            var cc = critStack.Pop() as CompoundCriterion;
                            cc.Right = current;
                            current  = cc;    // mark the parent as current (walk up the tree)
                            stateStack.Pop(); // the conjunction is no longer pending

                            state = stateStack.Pop();
                            if (state != ParseState.CriterionDone)
                            {
                                throw new ArgumentException("??");
                            }
                        }
                    }
                    else
                    {
                        stateStack.Push(ParseState.CriterionDone);   // not sure?
                    }
                }

                if (state == ParseState.Whitespace)
                {
                    stateStack.Pop();
                }
            }

            return(current);
        }
        public void PrettyPrint(System.Text.StringBuilder input, System.Text.StringBuilder output)
        {
            if (input == null)
            {
                throw new System.ArgumentNullException("input");
            }
            if (output == null)
            {
                throw new  System.ArgumentNullException("output");
            }

            int  inputLength = input.Length;
            char c;

            for (int i = 0; i < inputLength; i++)
            {
                c = input[i];

                switch (c)
                {
                case '{':
                    if (!InString())
                    {
                        if (inVariableAssignment || (context.Count > 0 && context.Peek() != JsonContextType.Array))
                        {
                            output.Append(NewLine);
                            BuildIndents(context.Count, output);
                        }
                        output.Append(c);
                        context.Push(JsonContextType.Object);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '}':
                    if (!InString())
                    {
                        output.Append(NewLine);
                        context.Pop();
                        BuildIndents(context.Count, output);
                        output.Append(c);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '[':
                    output.Append(c);

                    if (!InString())
                    {
                        context.Push(JsonContextType.Array);
                    }

                    break;

                case ']':
                    if (!InString())
                    {
                        output.Append(c);
                        context.Pop();
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '=':
                    output.Append(c);
                    break;

                case ',':
                    output.Append(c);

                    if (!InString() && context.Peek() != JsonContextType.Array)
                    {
                        BuildIndents(context.Count, output);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                        inVariableAssignment = false;
                    }

                    break;

                case '\'':
                    if (!inDoubleString && prevChar != '\\')
                    {
                        inSingleString = !inSingleString;
                    }

                    output.Append(c);
                    break;

                case ':':
                    if (!InString())
                    {
                        inVariableAssignment = true;
                        output.Append(Space);
                        output.Append(c);
                        output.Append(Space);
                    }
                    else
                    {
                        output.Append(c);
                    }

                    break;

                case '"':
                    if (!inSingleString && prevChar != '\\')
                    {
                        inDoubleString = !inDoubleString;
                    }

                    output.Append(c);
                    break;

                default:
                    output.Append(c);
                    break;
                }
                prevChar = c;
            }
        }
 private static long sr()
 {
     return((s.Count == 0)?0:s.Peek());
 }
Example #16
0
 protected void Store(params string[] member)
 {
     this._context.SetValue(stack.Peek(), 0, member);
 }
Example #17
0
        public static void Demo()
        {
            Console.WriteLine("Stack......");

            System.Collections.Generic.Stack <string> names = new System.Collections.Generic.Stack <string>();
            names.Push("Andrew");
            names.Push("Bobby");
            names.Push("Candy");
            names.Push("Dana");
            names.Push("Edith");

            Console.WriteLine("Default content of stack");

            foreach (string name in names)
            {
                Console.WriteLine(name);
            }

            Console.WriteLine("\nPopping '{0}'", names.Pop());
            Console.WriteLine("Peek at next item to display what will" + " be destacked: {0}", names.Peek());
            Console.WriteLine("Now, after peek, popping '{0}'", names.Pop());


            System.Collections.Generic.Stack <string> stack2 = new System.Collections.Generic.Stack <string>(names.ToArray());

            Console.WriteLine("\nContents of the first copy:");
            foreach (string name in stack2)
            {
                Console.WriteLine(name);
            }

            string[] array2 = new string[names.Count * 2];
            names.CopyTo(array2, names.Count);

            System.Collections.Generic.Stack <string> stack3 = new System.Collections.Generic.Stack <string>(array2);

            Console.WriteLine("\nContents of the second copy, with " + "duplicates and nulls:");
            foreach (string name in stack3)
            {
                Console.WriteLine(name);
            }

            Console.WriteLine("\nstack2.Contains(\"Dana\") = {0}", stack2.Contains("Dana"));

            Console.WriteLine("\nstack2.Clear()");
            stack2.Clear();
            Console.WriteLine("\nstack2.Count = {0}", stack2.Count);

            Console.WriteLine("End of Stack");
        }
Example #18
0
    public void compute_expression(string expr)
    {
        System.Collections.Generic.Stack<char> myStack = new System.Collections.Generic.Stack<char>();
        string output = "";
        // Rewriting the string into Reverse Polish Notation(RPN) format
        foreach(char token in expr)
        {
             //Read a token.
            //If the token is a number, then add it to the output queue.
            if (Char.IsNumber(token) == true)
            {
                output = output + ' ' +token;
            }
            if(token == '+' || token == '-')
            {
                if (myStack.Count() != 0)
                {
                        while(myStack.Peek() == '*' || myStack.Peek() == '/' || myStack.Peek() == '-')
                        {
                            if (myStack.Count() != 0)
                            {
                                output = output + ' ' + myStack.Peek();
                                myStack.Pop();
                            }
                            if (myStack.Count() == 0)
                            {
                                break;
                            }
                        }
                }
                myStack.Push(token);
            }
            if(token == '(')
            {
                myStack.Push(token);
            }

            if (token == ')')
            {
                if (myStack.Count() != 0)
                {
                    while (myStack.Peek() != '(')
                    {
                        if (myStack.Count() != 0)
                        {
                            output = output + ' ' + myStack.Peek();
                            myStack.Pop();
                        }
                    }
                myStack.Pop();
                }
            }
        }
           while(myStack.Count() != 0)
           {
               output = output + " " + myStack.Peek();
               myStack.Pop();
           }
        //Done RPN
           //Now we need to Evaluate the RPN
           evalu(output);
    }
Example #19
0
        public static void interateBinaryTreeEx(TreeAndGraph.BinaryTreeNode head, Order o)
        {
            TreeAndGraph.BinaryTreeNode btn = head;
            if (o == Order.Post)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                    = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();
                s.Push(btn);
                TreeAndGraph.BinaryTreeNode cur = null;
                TreeAndGraph.BinaryTreeNode pre = null;
                while (s.Count != 0)
                {
                    cur = s.Peek();
                    if ((cur.LeftNode == null && cur.RightNode == null) || (pre != null && (pre == cur.LeftNode || pre == cur.RightNode)))
                    {
                        System.Console.WriteLine("XPost:"+cur.Data);
                        s.Pop();
                        pre = cur;
                    }
                    else
                    {
                        if (cur.RightNode != null)
                        {
                            s.Push(cur.RightNode);
                        }
                        if (cur.LeftNode != null)
                        {
                            s.Push(cur.LeftNode);
                        }
                    }
                }
            }
            if (o == Order.Pre)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                    = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();

                while (btn != null || s.Count != 0)
                {
                    while (btn != null)
                    {
                        s.Push(btn);
                        System.Console.WriteLine("XPre:" + btn.Data);
                        btn = btn.LeftNode;
                    }
                    if (s.Count != 0)
                    {
                        btn = s.Pop().RightNode;
                    }
                }
            }
            if (o == Order.Mid)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                     = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();
                while (btn != null || s.Count != 0)
                {
                    while (btn != null)
                    {
                        s.Push(btn);
                        btn = btn.LeftNode;
                    }
                    if (s.Count != 0)
                    {
                        btn = s.Pop();
                        System.Console.WriteLine("XMid:" + btn.Data);
                        btn = btn.RightNode;
                    }

                }
            }
        }
Example #20
0
 public bool InScalarTypeContext()
 {
     return((_typeStack.Count > 0) && (_typeStack.Peek() is Schema.IScalarType));
 }
Example #21
0
        private static int CalculateIndentation(string baseline, ITextSnapshotLine line, IEditorOptions options, IClassifier classifier, ITextView textView) {
            int indentation = GetIndentation(baseline, options.GetTabSize());
            int tabSize = options.GetIndentSize();
            var tokens = classifier.GetClassificationSpans(line.Extent);
            if (tokens.Count > 0 && !IsUnterminatedStringToken(tokens[tokens.Count - 1])) {
                int tokenIndex = tokens.Count - 1;

                while (tokenIndex >= 0 &&
                    (tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) ||
                    tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.WhiteSpace))) {
                    tokenIndex--;
                }

                if (tokenIndex < 0) {
                    return indentation;
                }

                if (ReverseExpressionParser.IsExplicitLineJoin(tokens[tokenIndex])) {
                    // explicit line continuation, we indent 1 level for the continued line unless
                    // we're already indented because of multiple line continuation characters.

                    indentation = GetIndentation(line.GetText(), options.GetTabSize());
                    var joinedLine = tokens[tokenIndex].Span.Start.GetContainingLine();
                    if (joinedLine.LineNumber > 0) {
                        var prevLineSpans = classifier.GetClassificationSpans(tokens[tokenIndex].Span.Snapshot.GetLineFromLineNumber(joinedLine.LineNumber - 1).Extent);
                        if (prevLineSpans.Count == 0 || !ReverseExpressionParser.IsExplicitLineJoin(prevLineSpans[prevLineSpans.Count - 1])) {
                            indentation += tabSize;
                        }
                    } else {
                        indentation += tabSize;
                    }

                    return indentation;
                }

                string sline = tokens[tokenIndex].Span.GetText();
                var lastChar = sline.Length == 0 ? '\0' : sline[sline.Length - 1];

                // use the expression parser to figure out if we're in a grouping...
                var spans = textView.BufferGraph.MapDownToFirstMatch(
                    tokens[tokenIndex].Span,
                    SpanTrackingMode.EdgePositive,
                    PythonContentTypePrediciate
                );
                if (spans.Count == 0) {
                    return indentation;
                }
                
                var revParser = new ReverseExpressionParser(
                        spans[0].Snapshot,
                        spans[0].Snapshot.TextBuffer,
                        spans[0].Snapshot.CreateTrackingSpan(
                            spans[0].Span,
                            SpanTrackingMode.EdgePositive
                        )
                    );

                var tokenStack = new System.Collections.Generic.Stack<ClassificationSpan>();
                tokenStack.Push(null);  // end with an implicit newline
                bool endAtNextNull = false;

                foreach (var token in revParser) {
                    tokenStack.Push(token);
                    if (token == null && endAtNextNull) {
                        break;
                    } else if (token != null &&
                       token.ClassificationType == revParser.Classifier.Provider.Keyword &&
                       PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText())) {
                        endAtNextNull = true;
                    }
                }

                var indentStack = new System.Collections.Generic.Stack<LineInfo>();
                var current = LineInfo.Empty;

                while (tokenStack.Count > 0) {
                    var token = tokenStack.Pop();
                    if (token == null) {
                        current.NeedsUpdate = true;
                    } else if (token.IsOpenGrouping()) {
                        indentStack.Push(current);
                        var start = token.Span.Start;
                        var line2 = start.GetContainingLine();
                        var next = tokenStack.Count > 0 ? tokenStack.Peek() : null;
                        if (next != null && next.Span.End <= line2.End) {
                            current = new LineInfo {
                                Indentation = start.Position - line2.Start.Position + 1
                            };
                        } else {
                            current = new LineInfo {
                                Indentation = GetIndentation(line2.GetText(), tabSize) + tabSize
                            };
                        }
                    } else if (token.IsCloseGrouping()) {
                        if (indentStack.Count > 0) {
                            current = indentStack.Pop();
                        } else {
                            current.NeedsUpdate = true;
                        }
                    } else if (ReverseExpressionParser.IsExplicitLineJoin(token)) {
                        while (token != null && tokenStack.Count > 0) {
                            token = tokenStack.Pop();
                        }
                    } else if (current.NeedsUpdate == true) {
                        var line2 = token.Span.Start.GetContainingLine();
                        current = new LineInfo {
                            Indentation = GetIndentation(line2.GetText(), tabSize)
                        };
                    }

                    if (token != null && ShouldDedentAfterKeyword(token)) {     // dedent after some statements
                        current.ShouldDedentAfter = true;
                    }

                    if (token != null && token.Span.GetText() == ":" &&         // indent after a colon
                        indentStack.Count == 0) {                               // except in a grouping
                        current.ShouldIndentAfter = true;
                        // If the colon isn't at the end of the line, cancel it out.
                        // If the following is a ShouldDedentAfterKeyword, only one dedent will occur.
                        current.ShouldDedentAfter = (tokenStack.Count != 0 && tokenStack.Peek() != null);
                    }
                }

                indentation = current.Indentation +
                    (current.ShouldIndentAfter ? tabSize : 0) -
                    (current.ShouldDedentAfter ? tabSize : 0);
            }

            // Map indentation back to the view's text buffer.
            int offset = 0;
            var viewLineStart = textView.BufferGraph.MapUpToSnapshot(line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot);
            if (viewLineStart.HasValue) {
                offset = viewLineStart.Value.Position - viewLineStart.Value.GetContainingLine().Start.Position;
            }

            return offset + indentation;
        }
 public T Peek()
 {
     return(stack.Peek());
 }