예제 #1
0
        public static (AstNode node, int numRead) Next(IEnumerable <ParseToken> tokens)
        {
            var originalTokens = tokens.ToList();
            var toParse        = originalTokens;

            var(lhs, skipCount) = NextValue(toParse);
            toParse             = toParse.Skip(skipCount).ToList();
            while (toParse.Any())
            {
                if (toParse[0].Type == ParseTokenType.Add || toParse[0].Type == ParseTokenType.Multiply)
                {
                    var type = toParse[0].Type;
                    toParse = toParse.Skip(1).ToList();
                    var rhs = NextValue(toParse);
                    if (type == ParseTokenType.Add)
                    {
                        lhs = new AstAdd(lhs, rhs.node);
                    }
                    else
                    {
                        lhs = new AstMultiply(lhs, rhs.node);
                    }

                    toParse = toParse.Skip(rhs.numRead).ToList();
                }
                else
                {
                    throw new Exception("Unexpected token type.");
                }
            }

            return(lhs, originalTokens.Count);
        }
예제 #2
0
        public static (AstNode node, int numRead) Next(IEnumerable <ParseToken> tokens)
        {
            var originalTokens = tokens.ToList();
            var toParse        = originalTokens;

            var(node, skipCount) = NextValue(toParse);
            toParse = toParse.Skip(skipCount).ToList();

            var valueList = new List <AstNode> {
                node
            };
            var operators = new List <ParseToken>();

            while (toParse.Any())
            {
                if (toParse[0].Type != ParseTokenType.Add && toParse[0].Type != ParseTokenType.Multiply)
                {
                    throw new Exception("Unexpected value.");
                }

                operators.Add(toParse[0]);
                toParse           = toParse.Skip(1).ToList();
                (node, skipCount) = NextValue(toParse);
                valueList.Add(node);
                toParse = toParse.Skip(skipCount).ToList();
            }

            foreach (var opToReplace in operators
                     .Select((op, idx) => (op.Type, idx))
                     .Reverse()
                     .Where(p => p.Type == ParseTokenType.Add)
                     .ToList())
            {
                var lhs = valueList[opToReplace.idx];
                var rhs = valueList[opToReplace.idx + 1];

                var newOp = new AstAdd(lhs, rhs);
                operators.RemoveAt(opToReplace.idx);
                valueList.RemoveAt(opToReplace.idx + 1);
                valueList[opToReplace.idx] = newOp;
            }

            var firstValue = valueList.First();

            return(valueList.Skip(1).Aggregate(firstValue, (lhs, rhs) => new AstMultiply(lhs, rhs)), originalTokens.Count);
        }