Exemplo n.º 1
0
 public void ValidateIndentation()
 {
     if ((Indent.Length % _indentSize) != 0)
     {
         SyntaxException.Throw(this, "Illegal Indentation: Only {0} space character(s) allowed as indentation", _indentSize);
     }
 }
 public ParserResult(TokenInfo token, bool isSuccessed, LambdaExpression expr, SyntaxException error = null)
 {
     IsSuccessed = isSuccessed;
     Expression = expr;
     Token = token;
     Error = error;
 }
Exemplo n.º 3
0
        public void TestVariableNotTerminatedFromInvalidVariableName(string variableName)
        {
            var             template = Template.Parse("{{ " + variableName + " }}");
            SyntaxException ex       = Assert.Throws <SyntaxException>(() => template.Render(new RenderParameters(System.Globalization.CultureInfo.InvariantCulture)
            {
                LocalVariables           = Hash.FromAnonymousObject(new { x = "" }),
                ErrorsOutputMode         = ErrorsOutputMode.Rethrow,
                SyntaxCompatibilityLevel = SyntaxCompatibility.DotLiquid22
            }));

            Assert.AreEqual(
                expected: string.Format(Liquid.ResourceManager.GetString("VariableNotTerminatedException"), variableName),
                actual: ex.Message);

            template = Template.Parse("{{ x[" + variableName + "] }}");
            ex       = Assert.Throws <SyntaxException>(() => template.Render(new RenderParameters(System.Globalization.CultureInfo.InvariantCulture)
            {
                LocalVariables           = Hash.FromAnonymousObject(new { x = new { x = "" } }),
                ErrorsOutputMode         = ErrorsOutputMode.Rethrow,
                SyntaxCompatibilityLevel = SyntaxCompatibility.DotLiquid22
            }));
            Assert.AreEqual(
                expected: string.Format(Liquid.ResourceManager.GetString("VariableNotTerminatedException"), variableName),
                actual: ex.Message);
        }
Exemplo n.º 4
0
        public override BlockClosingAction Render(ViewSourceReader viewSourceReader, TemplateOptions options, TemplateClassBuilder builder)
        {
            var currentInputLine = viewSourceReader.CurrentInputLine;
            var content          = currentInputLine.NormalizedText.Trim().ToLowerInvariant();

            if (string.IsNullOrEmpty(content))
            {
                builder.AppendOutput(@"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">");
            }
            else if (string.Equals(content, "1.1"))
            {
                builder.AppendOutput(@"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.1//EN"" ""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"">");
            }
            else if (string.Equals(content, "strict"))
            {
                builder.AppendOutput(@"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">");
            }
            else if (string.Equals(content, "frameset"))
            {
                builder.AppendOutput(@"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Frameset//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"">");
            }
            else if (string.Equals(content, "html"))
            {
                builder.AppendOutput(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd"">");
            }
            else if (string.Equals(content, "html strict"))
            {
                builder.AppendOutput(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http://www.w3.org/TR/html4/strict.dtd"">");
            }
            else if (string.Equals(content, "html frameset"))
            {
                builder.AppendOutput(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Frameset//EN"" ""http://www.w3.org/TR/html4/frameset.dtd"">");
            }
            else
            {
                var parts = content.Split(' ');

                if (string.Equals(parts[0], "xml"))
                {
                    var encoding = "utf-8";

                    if (parts.Length == 2)
                    {
                        encoding = parts[1];
                    }

                    var invariant = Utility.FormatInvariant(@"<?xml version=""1.0"" encoding=""{0}"" ?>", encoding);
                    builder.AppendOutput(invariant);
                }
                else
                {
                    SyntaxException.Throw(currentInputLine, ErrorParsingTag, currentInputLine);
                }
            }

            builder.AppendOutputLine();

            return(EmptyClosingAction);
        }
        public void TestIfMaxConditions()
        {
            SyntaxException se = Assert.Throws <SyntaxException>(() => Helper.AssertTemplateResultAsync("", "{% if 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 and 1 %}too many conditions{% endif %}").GetAwaiter().GetResult());

            StringAssert.Contains("'if'", se.Message);
            StringAssert.Contains("tag", se.Message);
            StringAssert.Contains("500", se.Message);
        }
Exemplo n.º 6
0
        public void Constructor_WhenSpecifiedInner_ShouldAssignToInnerExceptionProperty(Type exception)
        {
            var inner = (exception != null) ? (Exception)Activator.CreateInstance(exception) : null;

            var subject = new SyntaxException(null, inner);

            subject.InnerException.Should().Be(inner);
        }
Exemplo n.º 7
0
 public static GraphQLRequestException DefaultHttpRequestParser_SyntaxError(
     SyntaxException ex) =>
 new GraphQLRequestException(
     ErrorBuilder.New()
     .SetMessage(ex.Message)
     .AddLocation(ex.Line, ex.Column)
     .SetCode(ErrorCodes.Server.SyntaxError)
     .Build());
Exemplo n.º 8
0
        public override BlockClosingAction Render(ViewSourceReader viewSourceReader, TemplateOptions options, TemplateClassBuilder builder)
        {
            var currentInputLine = viewSourceReader.CurrentInputLine;
            var match            = _commentRegex.Match(currentInputLine.NormalizedText);

            if (!match.Success)
            {
                SyntaxException.Throw(currentInputLine, ErrorParsingTag, currentInputLine);
            }

            var ieBlock = match.Groups[1].Value;
            var content = match.Groups[2].Value;

            var openingTag = new StringBuilder(currentInputLine.Indent);

            openingTag.Append("<!--");
            var closingTag = new StringBuilder("-->");

            if (!string.IsNullOrEmpty(ieBlock))
            {
                openingTag.AppendFormat("{0}>", ieBlock);
                closingTag.Insert(0, "<![endif]");
            }

            if (string.IsNullOrEmpty(content))
            {
                builder.AppendOutput(openingTag.ToString());
                builder.AppendOutputLine();
                closingTag.Insert(0, currentInputLine.Indent);
            }
            else
            {
                if (content.Length > 50)
                {
                    builder.AppendOutput(openingTag.ToString());
                    builder.AppendOutputLine();

                    builder.AppendOutput(viewSourceReader.NextIndent);

                    builder.AppendOutput(content);

                    builder.AppendOutputLine();
                }
                else
                {
                    builder.AppendOutput(openingTag.ToString());
                    builder.AppendOutput(content);
                    closingTag.Insert(0, ' ');
                }
            }

            return(() =>
            {
                builder.AppendOutput(closingTag.ToString());
                builder.AppendOutputLine();
            });
        }
Exemplo n.º 9
0
        public void TestSyntaxErrorWithTokenPosition()
        {
            var pos = new TokenPosition("", 10, 10);
            var e   = new SyntaxException(pos, "msg");

            Assert.Equal("msg", e.Message);
            Assert.Null(e.Token);
            Assert.Equal(pos, e.Position);
        }
Exemplo n.º 10
0
        public void TestSyntaxErrorWithToken()
        {
            var pos   = new TokenPosition("", 10, 10);
            var token = new Token(TokenKind.NoneLiteral, "none", pos);
            var e     = new SyntaxException(token, "msg");

            Assert.Equal("msg", e.Message);
            Assert.Equal(token, e.Token);
            Assert.Equal(pos, e.Position);
        }
Exemplo n.º 11
0
        public void Constructor_WhenSpecifiedMessage_ShouldAssignToMessageProperty()
        {
            var message = "abc";

            var subject1 = new SyntaxException(message);
            var subject2 = new SyntaxException(message, new Exception());

            subject1.Message.Should().Be(message);
            subject2.Message.Should().Be(message);
        }
Exemplo n.º 12
0
        public static DataphorFault ExceptionToFault(DataphorException exception)
        {
            DataphorFault fault = new DataphorFault();

            fault.ExceptionClassName = exception.GetType().Name;
            fault.Code          = exception.Code;
            fault.Severity      = exception.Severity;
            fault.Message       = exception.Message;
            fault.Details       = exception.Details;
            fault.ServerContext = exception.ServerContext;
            if (exception.InnerException != null)
            {
                fault.InnerFault = ExceptionToFault(exception.InnerException);
            }

                        #if !SILVERLIGHT
            // Under Silverlight, a ConnectionException will come back as a DataphorException
            // The statement is still present in the Details.
            ConnectionException connectionException = exception as ConnectionException;
            if (connectionException != null)
            {
                fault.Statement = connectionException.Statement;
            }
                        #endif

            SyntaxException syntaxException = exception as SyntaxException;
            if (syntaxException != null)
            {
                fault.Locator   = syntaxException.Locator;
                fault.Line      = syntaxException.Line;
                fault.LinePos   = syntaxException.LinePos;
                fault.Token     = syntaxException.Token;
                fault.TokenType = syntaxException.TokenType;
            }

            CompilerException compilerException = exception as CompilerException;
            if (compilerException != null)
            {
                fault.Locator    = compilerException.Locator;
                fault.Line       = compilerException.Line;
                fault.LinePos    = compilerException.LinePos;
                fault.ErrorLevel = compilerException.ErrorLevel;
            }

            RuntimeException runtimeException = exception as RuntimeException;
            if (runtimeException != null)
            {
                fault.Locator = runtimeException.Locator;
                fault.Line    = runtimeException.Line;
                fault.LinePos = runtimeException.LinePos;
                fault.Context = runtimeException.Context;
            }

            return(fault);
        }
 public static IError Generator_SyntaxException(SyntaxException syntaxException, string file) =>
 ErrorBuilder.New()
 .SetCode(SyntaxError)
 .SetExtension(FileExtensionKey, file)
 .SetMessage(Throwhelper_Generator_SyntaxError)
 .SetException(syntaxException)
 .SetExtension(TitleExtensionKey, "A graphql file contains a syntax error")
 .AddLocation(new HotChocolate.Location(
                  syntaxException.Line,
                  syntaxException.Column))
 .Build();
Exemplo n.º 14
0
        /// <summary>
        /// Handles an unknown tag.
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="markup"></param>
        /// <param name="tokens"></param>
        public virtual void UnknownTag(string tag, string markup, List <string> tokens)
        {
            SyntaxException exception = tag switch
            {
                "else" => new SyntaxException(Liquid.ResourceManager.GetString("BlockTagNoElseException"), this.BlockName),
                "end" => new SyntaxException(Liquid.ResourceManager.GetString("BlockTagNoEndException"), this.BlockName, this.BlockDelimiter),
                _ => new SyntaxException(Liquid.ResourceManager.GetString("BlockUnknownTagException"), tag),
            };

            throw exception;
        }
Exemplo n.º 15
0
        public void Constructor_WithNullMessage_ShouldGenerateMessageProperty()
        {
            var subject = new SyntaxException(null);

            subject.Message.Should().NotBeNull();
        }
Exemplo n.º 16
0
        public override BlockClosingAction Render(ViewSourceReader viewSourceReader, TemplateOptions options, TemplateClassBuilder builder)
        {
            var currentInputLine = viewSourceReader.CurrentInputLine;
            var input            = PreprocessLine(currentInputLine);
            var match            = _tagRegex.Match(input);

            if (!match.Success)
            {
                SyntaxException.Throw(currentInputLine, ErrorParsingTag, currentInputLine);
            }

            var groups  = match.Groups;
            var tagName = groups[1].Value.Replace("\\", string.Empty);

            var isWhitespaceSensitive = _whitespaceSensitiveTags.Contains(tagName);
            var openingTag            = string.Format("{0}<{1}", currentInputLine.Indent, tagName);
            var closingTag            = string.Format("</{0}>", tagName);

            builder.AppendOutput(openingTag);

            ParseAndRenderAttributes(builder, match);

            var action = groups[6].Value.Trim();

            if (string.Equals("/", action) || options.IsAutoClosingTag(tagName))
            {
                builder.AppendOutput(" />");
                builder.AppendOutputLine();
                return(EmptyClosingAction);
            }

            var content = groups[7].Value.Trim();

            if (string.IsNullOrEmpty(content))
            {
                builder.AppendOutput(">");
                builder.AppendOutputLine();
                closingTag = currentInputLine.Indent + closingTag;
            }
            else
            {
                if ((content.Length > 50) || ("=" == action) || ("&=" == action) || ("!=" == action))
                {
                    builder.AppendOutput(">");

                    if (!isWhitespaceSensitive)
                    {
                        builder.AppendOutputLine();
                        builder.AppendOutput(viewSourceReader.NextIndent);
                    }

                    if (string.Equals("=", action))
                    {
                        builder.AppendCode(content, options.EncodeHtml);
                    }
                    else if (string.Equals("&=", action))
                    {
                        builder.AppendCode(content, true);
                    }
                    else if (string.Equals("!=", action))
                    {
                        builder.AppendCode(content, false);
                    }
                    else
                    {
                        AppendText(content, builder, options);
                    }

                    if (!isWhitespaceSensitive)
                    {
                        builder.AppendOutputLine();
                        closingTag = currentInputLine.Indent + closingTag;
                    }
                }
                else
                {
                    builder.AppendOutput(">");
                    AppendText(content, builder, options);
                    if ((currentInputLine.IndentCount + 1) == viewSourceReader.NextInputLine.IndentCount)
                    {
                        builder.AppendOutputLine();
                        closingTag = currentInputLine.Indent + closingTag;
                    }
                }
            }

            return(() =>
            {
                builder.AppendOutput(closingTag);
                builder.AppendOutputLine();
            });
        }
Exemplo n.º 17
0
        public SyntaxNode Parse(Queue <LexicalElement> input, HashSet <Item> startPoint, Type acceptNode, List <ParserConfiguration> history = null, List <SyntaxException> exceptions = null, AbstractVisitor visitor = null)
        {
            Stack <SyntaxNode>    nodeStack  = new Stack <SyntaxNode>();
            Stack <AnalyzerState> stateStack = new Stack <AnalyzerState>();

            stateStack.Push(Slr1Table.States[startPoint]);
            if (visitor == null)
            {
                visitor = PassthroughVisitor.Instance;
            }
            while (true)
            {
                try {
                    if (input.Count == 0)
                    {
                        if (nodeStack.Count > 0 && nodeStack.Peek().GetType() == acceptNode)
                        {
                            history?.Add(new ParserConfiguration(nodeStack, stateStack, input, null));
                            break;
                        }
                        var reducibleRules = new List <ProductionRule>(from item in stateStack.Peek().ItemSet
                                                                       where item.Cursor == item.ProductionRule.Length
                                                                       select item.ProductionRule);
                        if (reducibleRules.Count != 1)
                        {
                            var l = FindRightMostTerminal(nodeStack.Peek());
                            throw new SyntaxException($"Multiple or No Reducible Rule, last token \"{l.StringValue}\" at {l.LineNumber}:[{l.StartIndex}, {l.EndIndex}). Expected {String.Join(", ", from pred in stateStack.Peek().Action.Keys select pred.Name)}");
                        }

                        var reducibleRule = reducibleRules[0];
                        history?.Add(new ParserConfiguration(nodeStack, stateStack, input, new ReduceOperation()
                        {
                            ReduceBy = reducibleRule
                        }));
                        var argNodes = new SyntaxNode[reducibleRule.Length];
                        for (int i = argNodes.Length - 1; i >= 0; --i)
                        {
                            stateStack.Pop();
                            argNodes[i] = nodeStack.Pop();
                        }
                        nodeStack.Push(visitor.Visit(reducibleRule.Produce(argNodes)));
                        stateStack.Push(stateStack.Peek().GotoTable[reducibleRule.Key]);
                    }
                    else
                    {
                        var  cur     = input.Peek();
                        bool matched = false;
                        foreach (var action in stateStack.Peek().Action)
                        {
                            if (action.Key.Predicate(cur))
                            {
                                matched = true;
                                var operation = action.Value;
                                switch (operation)
                                {
                                case ShiftOperation so:
                                    history?.Add(new ParserConfiguration(nodeStack, stateStack, input, so));
                                    input.Dequeue();
                                    nodeStack.Push(new TerminalNode(cur));
                                    stateStack.Push(so.NextState);

                                    break;

                                case ReduceOperation ro:
                                    var reducibleRule = ro.ReduceBy;
                                    history?.Add(new ParserConfiguration(nodeStack, stateStack, input, ro));
                                    var argNodes = new SyntaxNode[reducibleRule.Length];
                                    for (int i = argNodes.Length - 1; i >= 0; --i)
                                    {
                                        stateStack.Pop();
                                        argNodes[i] = nodeStack.Pop();
                                    }
                                    nodeStack.Push(visitor.Visit(reducibleRule.Produce(argNodes)));
                                    stateStack.Push(stateStack.Peek().GotoTable[reducibleRule.Key]);

                                    break;

                                default:
                                    throw new SyntaxException("Internal Error: Unknown Operation");
                                }
                            }
                        }
                        if (!matched)
                        {
                            throw new SyntaxException($"Unknown Token \"{cur.StringValue}\" at {cur.LineNumber}:[{cur.StartIndex}, {cur.EndIndex}), no matching operation. Expected {String.Join(", ", from pred in stateStack.Peek().Action.Keys select pred.Name)}");
                        }
                    }
                } catch (SyntaxException e) {
                    exceptions?.Add(e);
                    var ero = new ErrorRecoveryOperation();
                    history?.Add(new ParserConfiguration(nodeStack, stateStack, input, ero));
                    if (input.Count == 0)
                    {
                        var ex = new SyntaxException("Error Recovery Failed: Unable to Reduce");
                        ero.Success = false;
                        exceptions.Add(ex);
                        throw ex;
                    }
                    List <object> intersection = new List <object>();
                    intersection.AddRange(Slr1Table.AllowedErrorRecoveryKey.Keys.Intersect(stateStack.Peek().GotoTable.Keys));
                    while (intersection.Count == 0 && stateStack.Count > 0)
                    {
                        stateStack.Pop();
                        nodeStack.Pop();
                        intersection.AddRange(Slr1Table.AllowedErrorRecoveryKey.Keys.Intersect(stateStack.Peek().GotoTable.Keys));
                    }

                    if (intersection.Count == 0)
                    {
                        var ex = new SyntaxException("Error Recovery Failed: No Recoverable State");
                        ero.Success = false;
                        exceptions.Add(ex);
                        throw ex;
                    }

                    var  nextKey = intersection.First();
                    bool matched = false;
                    while (!matched && input.Count > 0)
                    {
                        foreach (var follow in Slr1Table.FollowSets[nextKey])
                        {
                            if (follow is TerminalPredicate tp && tp.Predicate(input.Peek()))
                            {
                                matched = true;
                                break;
                            }

                            input.Dequeue();
                        }
                    }

                    if (!matched)
                    {
                        var ex = new SyntaxException("Error Recovery Failed: No Followable Input");
                        ero.Success = false;
                        exceptions.Add(ex);
                        throw ex;
                    }
                    var nextState = stateStack.Peek().GotoTable[nextKey];
                    var nextNode  = Slr1Table.AllowedErrorRecoveryKey[nextKey]();
                    stateStack.Push(nextState);
                    nodeStack.Push(visitor.Visit(nextNode));
                    ero.Success = true;
                }
            }
            return(nodeStack.Pop());
        }
Exemplo n.º 18
0
 internal ValidationException(SyntaxException ex)
     : base(ex.Details, ex)
 {
 }
Exemplo n.º 19
0
 public ParserResult(bool isSuccessed, SyntaxException error)
 {
     IsSuccessed = isSuccessed;
     Error = error;
 }
        /// <summary>
        /// вычисляет выражение, записанное в RPN(обратная польская запись)
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public string RPNToAnswer(string expression)
        {
            var        text = ExpressionToRPN(expression, out var tokensList);
            var        tokens = tokensList.ToArray();
            var        stack = new Stack <Token>();
            Token      leftOp, rightOp;
            Polynomial result;

            for (int i = 0; i < tokens.Length; i++)
            {
                switch (tokens[i].Type)
                {
                case TokenType.Polynomial:
                    stack.Push(tokens[i]);
                    break;

                case TokenType.Variable:
                    if (PolyVars.ContainsKey(tokens[i].Value.ToString()))
                    {
                        stack.Push(new Token(TokenType.Polynomial, PolyVars[tokens[i].Value].ToString()));
                    }
                    else
                    {
                        stack.Push(tokens[i]);
                    }
                    break;

                case TokenType.Function:
                    if (Function.GetFunctions()[tokens[i].Value].Type == FunctionType.Unary)
                    {
                        try
                        {
                            leftOp = stack.Pop();
                        }
                        catch (System.InvalidOperationException)
                        {
                            SyntaxException syntaxException = new SyntaxException("Не удалось определить функцию");
                            leftOp = new Token(TokenType.Exeption, syntaxException.Message);
                        }
                        result = Function.GetFunctions()[tokens[i].Value].UFunction
                                 (
                            new Polynomial(PolynomialParser.Parse(leftOp.Value))
                                 );
                        stack.Push(new Token(TokenType.Polynomial, result.ToString()));
                    }
                    else
                    {
                        try
                        {
                            rightOp = stack.Pop();
                            leftOp  = stack.Pop();
                        }
                        catch (System.InvalidOperationException)
                        {
                            SyntaxException syntaxException = new SyntaxException("Не удалось применить функцию к операнду(ам)");
                            rightOp = new Token(TokenType.Exeption, syntaxException.Message);
                            leftOp  = new Token(TokenType.Exeption, syntaxException.Message);
                        }
                        result = Function.GetFunctions()[tokens[i].Value].BiFunction
                                 (
                            new Polynomial(PolynomialParser.Parse(leftOp.Value)),
                            new Polynomial(PolynomialParser.Parse(rightOp.Value))
                                 );
                        stack.Push(new Token(TokenType.Polynomial, result.ToString()));
                    }
                    break;

                case TokenType.Operator:
                    try
                    {
                        rightOp = stack.Pop();
                        //leftOp = stack.Pop();
                    }
                    catch (System.InvalidOperationException)
                    {
                        SyntaxException syntaxException = new SyntaxException("Не удалось применить оператор к операнду(ам)");
                        rightOp = new Token(TokenType.Polynomial, "0");
                        //leftOp  = new Token(TokenType.Exeption, syntaxException.Message);
                    }
                    try
                    {
                        //rightOp = stack.Pop();
                        leftOp = stack.Pop();
                    }
                    catch (System.InvalidOperationException)
                    {
                        SyntaxException syntaxException = new SyntaxException("Не удалось применить оператор к операнду(ам)");
                        //rightOp = new Token(TokenType.Exeption, syntaxException.Message);
                        leftOp = new Token(TokenType.Polynomial, "0");
                    }
                    if (Operator.GetOperators()[tokens[i].Value].Type == OperatorType.Binary)
                    {
                        try
                        {
                            result = Operator.GetOperators()[tokens[i].Value].biOperator
                                     (
                                new Polynomial(PolynomialParser.Parse(leftOp.Value)),
                                new Polynomial(PolynomialParser.Parse(rightOp.Value))
                                     );
                            stack.Push(new Token(TokenType.Polynomial, result.ToString()));
                        }
                        catch (InvalidPolynomialStringException exception)
                        {
                            stack.Push(new Token(TokenType.Exeption, exception.Message));
                        }
                    }
                    else    //TODO подумать как детальнее реализовать взаимодействие с логическими операциями
                    {
                        result = Convert.ToDouble(Operator.GetOperators()[tokens[i].Value].biBoolOperator
                                                  (
                                                      new Polynomial(PolynomialParser.Parse(leftOp.Value)),
                                                      new Polynomial(PolynomialParser.Parse(rightOp.Value))
                                                  ));
                        stack.Push(new Token(TokenType.Polynomial, result.ToString()));
                    }
                    break;

                default:
                    throw new Exception("Wrong token");
                }
            }
            try
            {
                text = stack.Pop().Value;
            }
            catch (System.InvalidOperationException)
            {
                text = "";
            }
            return(text);
        }