Beispiel #1
0
        private static void TestGrammarParser()
        {
            string productionRule = "clauses : clause (COMMA [D] clause)*";
            var    ruleparser     = new RuleParser <TestGrammarToken>();
            var    builder        = new ParserBuilder <EbnfTokenGeneric, GrammarNode <TestGrammarToken> >();
            var    grammarParser  = builder.BuildParser(ruleparser, ParserType.LL_RECURSIVE_DESCENT, "rule").Result;
            var    result         = grammarParser.Parse(productionRule);

            //(grammarParser.Lexer as GenericLexer<TestGrammarToken>).ResetLexer();
            Console.WriteLine($"alors ? {string.Join('\n',result.Errors.Select(e => e.ErrorMessage))}");
            result = grammarParser.Parse(productionRule);
            Console.WriteLine($"alors ? {string.Join('\n',result.Errors.Select(e => e.ErrorMessage))}");
            ;

            Console.WriteLine("starting");
            ErroneousGrammar parserInstance = new ErroneousGrammar();

            Console.WriteLine("new instance");

            var builder2 = new ParserBuilder <TestGrammarToken, object>();

            Console.WriteLine("builder");

            var Parser = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "rule");

            Console.WriteLine($"built : {Parser.IsOk}");
        }
Beispiel #2
0
        public void TestIssue184()
        {
            StartingRule = $"{typeof(Issue184ParserOne).Name}_expressions";
            var parserInstance = new Issue184ParserOne();
            var builder        = new ParserBuilder <Issue184Token, double>();
            var issue184parser = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, StartingRule);

            Assert.True(issue184parser.IsOk);
            var c = issue184parser.Result.Parse(" 2 + 2");

            Assert.True(c.IsOk);
            Assert.Equal(4.0, c.Result);


            StartingRule = $"{typeof(Issue184Parser).Name}_expressions";
            var parserInstance2 = new Issue184Parser();
            var builder2        = new ParserBuilder <Issue184Token, double>();
            var issue184parser2 = builder.BuildParser(parserInstance2, ParserType.EBNF_LL_RECURSIVE_DESCENT, StartingRule);

            Assert.True(issue184parser2.IsOk);
            var c2 = issue184parser2.Result.Parse(" 2 + 2");

            Assert.True(c2.IsOk);
            Assert.Equal(4.0, c2.Result);

            c2 = issue184parser2.Result.Parse(" 2 + 2 / 2");
            Assert.True(c2.IsOk);
            Assert.Equal(2 + 2 / 2, c2.Result);

            c2 = issue184parser2.Result.Parse(" 2 - 2 * 2");
            Assert.True(c2.IsOk);
            Assert.Equal(2 - 2 * 2, c2.Result);
        }
Beispiel #3
0
    public SearchQueryParser(ILogger <SearchQueryParser> logger)
    {
        this.logger = logger;

        //Sly isn't designed with DI in mind, so... just hide it inside our own
        //dependency injection interface thing. Doesn't matter that we're directly instantiating it
        parserInstance = new QueryExpressionParser();

        var builder     = new ParserBuilder <QueryToken, string>();
        var buildResult = builder.BuildParser(parserInstance, ParserType.LL_RECURSIVE_DESCENT, "expr");

        if (buildResult.IsError)
        {
            var errors = buildResult.Errors?.Select(x => x.Message);
            if (errors == null || errors.Count() == 0)
            {
                errors = new List <string> {
                    "Unknown error"
                }
            }
            ;
            throw new InvalidOperationException("Couldn't construct parser: " + string.Join(",", errors));
        }
        parser = buildResult.Result;
    }
Beispiel #4
0
        protected ParsingResult CallParse(ParserBuilder parserBuilder, IEnumerable <string> args)
        {
            var parser        = parserBuilder.BuildParser();
            var parsingResult = parser.Parse(args, _scopedServiceProvider);

            return(parsingResult);
        }
Beispiel #5
0
        public void PreRunTest()
        {
            var parserInstance = new FormulaParser();
            var builder        = new ParserBuilder <FormulaToken, IFormula>();
            var parserResult   = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "formulae");

            Assert.True(parserResult.IsOk);
            var source = @"

aaa = bbb + 1
bbb = ccc + 2
ccc = 3 + 3 


";
            var t      = parserResult.Result.Parse(source);

            Assert.True(t.IsOk);

            var  form       = t.Result as Formulae;
            var  depbuilder = new Dependencies();
            bool isCyclic   = depbuilder.Build(t.Result as Formulae);

            Assert.False(isCyclic);
            var checker = new TypeChecker();

            checker.Type(form, depbuilder.DependenciesDictionary);
        }
Beispiel #6
0
        public static void TestScript()
        {
            var parserInstance = new ScriptParser();
            var builder        = new ParserBuilder <ScriptToken, object>();
            var parserBuild    = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "test");

            if (parserBuild.IsOk)
            {
                var    parser = parserBuild.Result;
                string ko1    = "|B|test2(a, b, c=100)|E|";
                string ko2    = "|B|plotshape(data, style=shapexcross)|E|";

                var r        = parser.Parse(ko1);
                var graphviz = new GraphVizEBNFSyntaxTreeVisitor <ScriptToken>();
                var root     = graphviz.VisitTree(r.SyntaxTree);
                var graph    = graphviz.Graph.Compile();
                r = parser.Parse(ko2);
            }
            else
            {
                foreach (var e in parserBuild.Errors)
                {
                    Console.WriteLine(e.Level + " - " + e.Message);
                }
            }
        }
        public JsonTests()
        {
            var jsonParser = new JSONParser();
            var builder    = new ParserBuilder <JsonToken, JSon>();

            Parser = builder.BuildParser(jsonParser, ParserType.LL_RECURSIVE_DESCENT, "root").Result;
        }
Beispiel #8
0
        private static Expression Parse(string query)
        {
            var parserInstance = new EarlyEosParser();
            var builder        = new ParserBuilder <EarlyEosToken, Expression>();

            var buildResult =
                builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "expression");

            if (buildResult.IsError)
            {
                throw new AggregateException(
                          buildResult.Errors
                          .Select(e => new Exception($"{e.Level} {e.Code} {e.Message}"))
                          );
            }
            var parser = buildResult.Result;

            var queryExpression = parser.Parse(query.Trim());

            var    graphviz = new GraphVizEBNFSyntaxTreeVisitor <EarlyEosToken>();
            var    root     = graphviz.VisitTree(queryExpression.SyntaxTree);
            string graph    = graphviz.Graph.Compile();

            ;

            if (queryExpression.IsError)
            {
                throw new AggregateException(
                          queryExpression.Errors
                          .Select(e => new Exception(e.ErrorMessage))
                          );
            }

            return(queryExpression.Result);
        }
        public void ParseWithValidArgs()
        {
            // Arrange
            var parserBuild            = new ParserBuilder();
            var parser                 = parserBuild.BuildParser();
            IEnumerable <string> args  = new[] { "delete", "-Source:custom value", "-np", "-ApiKey", "MyApiKey", "Custom argument value", "b" };
            var expectedReturnCode     = CommandResultCode.Ok;
            var expectedSource         = "custom value";
            var expectedApiKey         = "MyApiKey";
            var expectedNbOfArguments  = 2;
            var expectedArgumentsValue = new List <string> {
                "Custom argument value", "b"
            };

            // Act
            var actual = parser.Parse(args);

            // Assert
            Assert.True(actual.IsValid);
            Assert.Equal(expectedReturnCode, actual.ReturnCode);
            Assert.IsType <DeleteCommand>(actual.Command);
            Assert.Equal(expectedSource, ((DeleteCommand)actual.Command).Source);
            Assert.Equal(expectedApiKey, ((DeleteCommand)actual.Command).ApiKey);
            Assert.True(((DeleteCommand)actual.Command).NoPrompt);
            Assert.Null(((DeleteCommand)actual.Command).SourceProvider);
            Assert.Null(((DeleteCommand)actual.Command).Settings);
            Assert.Equal(expectedNbOfArguments, ((DeleteCommand)actual.Command).Arguments.Count);
            for (var i = 0; i < expectedNbOfArguments; i++)
            {
                Assert.Equal(expectedArgumentsValue[i], actual.Command.Arguments[i]);
            }
        }
Beispiel #10
0
 public static void testJSON()
 {
     try {
         var instance    = new EbnfJsonGenericParser();
         var builder     = new ParserBuilder <JsonTokenGeneric, JSon>();
         var buildResult = builder.BuildParser(instance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "root");
         // if (buildResult.IsOk)
         // {
         //     Console.WriteLine("parser built.");
         //     var parser = buildResult.Result;
         //     var content = File.ReadAllText("test.json");
         //     Console.WriteLine("test.json read.");
         //     var jsonResult = parser.Parse(content);
         //     Console.WriteLine("json parse done.");
         //     if (jsonResult.IsOk)
         //     {
         //         Console.WriteLine("YES !");
         //     }
         //     else
         //     {
         //         Console.WriteLine("Ooh no !");
         //     }
         //     Console.WriteLine("Done.");
         //
         // }
         // else
         // {
         //     buildResult.Errors.ForEach(e => Console.WriteLine(e.Message));
         // }
     }
     catch (Exception e) {
         Console.WriteLine($"ERROR {e.Message} : \n {e.StackTrace}");
     }
 }
Beispiel #11
0
        private static void testJSONLexer()
        {
            var builder = new ParserBuilder <JsonToken, JSon>();
            var parser  = builder.BuildParser(new JSONParser(), ParserType.EBNF_LL_RECURSIVE_DESCENT, "root");

            var source = "{ \"k\" : 1;\"k2\" : 1.1;\"k3\" : null;\"k4\" : false}";
            //source = File.ReadAllText("test.json");
            var lexer = new JSONLexer();
            var sw    = new Stopwatch();

            sw.Start();
            var lexresult = lexer.Tokenize(source);

            if (lexresult.IsOk)
            {
                var tokens = lexresult.Tokens;
                sw.Stop();
                Console.WriteLine($"hard coded lexer {tokens.Count()} tokens in {sw.ElapsedMilliseconds}ms");
                var sw2   = new Stopwatch();
                var start = DateTime.Now.Millisecond;
                sw2.Start();
                lexresult = parser.Result.Lexer.Tokenize(source);
                if (lexresult.IsOk)
                {
                    tokens = lexresult.Tokens;
                    sw2.Stop();
                    var end = DateTime.Now.Millisecond;
                    Console.WriteLine(
                        $"old lexer {tokens.Count()} tokens in {sw2.ElapsedMilliseconds}ms / {end - start}ms");
                }
            }
        }
Beispiel #12
0
        public void Setup()
        {
            Console.WriteLine(("SETUP"));
            Console.ReadLine();
            content = File.ReadAllText("test.json");
            Console.WriteLine("json read.");
            var jsonParser = new EbnfJsonGenericParser();
            var builder    = new ParserBuilder <JsonTokenGeneric, JSon>();

            var result = builder.BuildParser(jsonParser, ParserType.EBNF_LL_RECURSIVE_DESCENT, "root");

            Console.WriteLine("parser built.");
            if (result.IsError)
            {
                Console.WriteLine("ERROR");
                result.Errors.ForEach(e => Console.WriteLine(e));
            }
            else
            {
                Console.WriteLine("parser ok");
                BenchedParser = result.Result;
            }

            Console.WriteLine($"parser {BenchedParser}");
        }
        private static Expression Parse(string query)
        {
            var parserInstance = new IndexOutOfRangeParser();
            var builder        = new ParserBuilder <IndexOutOfRangeToken, Expression>();

            var buildResult =
                builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "expression");
            // if (buildResult.IsError)
            //     throw new AggregateException(
            //         buildResult.Errors
            //             .Select(e => new Exception($"{e.Level} {e.Code} {e.Message}"))
            //     );
            var parser = buildResult.Result;

            var queryExpression = parser.Parse(query.Trim());

            if (queryExpression.IsError)
            {
                throw new AggregateException(
                          queryExpression.Errors
                          .Select(e => new Exception(e.ErrorMessage))
                          );
            }

            return(queryExpression.Result);
        }
Beispiel #14
0
        private static void TestFactorial()
        {
            var whileParser = new WhileParser();
            var builder     = new ParserBuilder <WhileToken, WhileAST>();
            var Parser      = builder.BuildParser(whileParser, ParserType.EBNF_LL_RECURSIVE_DESCENT, "statement");

            ;

            var program = @"
(
    r:=1;
    i:=1;
    while i < 11 do 
    (";

            program += "\nprint \"r=\".r;\n";
            program += "r := r * i;\n";
            program += "print \"r=\".r;\n";
            program += "print \"i=\".i;\n";
            program += "i := i + 1 \n);\n";
            program += "return r)\n";
            var result      = Parser.Result.Parse(program);
            var interpreter = new Interpreter();
            var context     = interpreter.Interprete(result.Result);

            var compiler = new WhileCompiler();
            var code     = compiler.TranspileToCSharp(program);
            var f        = compiler.CompileToFunction(program);

            ;
        }
Beispiel #15
0
        public ExpressionTests()
        {
            ExpressionParser parserInstance = new ExpressionParser();
            ParserBuilder <ExpressionToken, int> builder = new ParserBuilder <ExpressionToken, int>();

            Parser = builder.BuildParser(parserInstance, ParserType.LL_RECURSIVE_DESCENT, "expression").Result;
        }
        public void ParseWithValidListArgs()
        {
            // Arrange
            var parserBuild = new ParserBuilder();
            var parser = parserBuild.BuildParser();
            IEnumerable<string> args = new[]
                {"IntTest", "-Strvalue:custom value", "-i", "42", "-il", "42", "Custom argument value", "-b"};
            var expectedReturnCode = CommandResultCode.Ok;
            var expectedStrValue = "custom value";
            var expectedNbOfArguments = 1;
            var expectedArgumentsValue = "Custom argument value";
            var expectedIntValue = 42;

            // Act
            var actual = parser.Parse(args);

            // Assert
            Assert.True(actual.IsValid);
            Assert.Equal(expectedReturnCode, actual.ReturnCode);
            Assert.IsType<IntTestCommand>(actual.Command);
            Assert.Equal(expectedStrValue, ((IntTestCommand) actual.Command).StrValue);
            Assert.Equal(expectedIntValue, ((IntTestCommand) actual.Command).IntValue);
            Assert.NotNull(((IntTestCommand) actual.Command).IntListValue);
            Assert.Equal(expectedNbOfArguments, ((IntTestCommand) actual.Command).Arguments.Count);
            Assert.Equal(expectedArgumentsValue, ((IntTestCommand) actual.Command).Arguments.Single());
            Assert.Equal(expectedNbOfArguments, ((IntTestCommand) actual.Command).IntListValue.Count);
            Assert.Equal(expectedIntValue, ((IntTestCommand) actual.Command).IntListValue.Single());
            Assert.True(((IntTestCommand) actual.Command).BoolValue);
        }
Beispiel #17
0
        public void TestIssue213()
        {
            var parserInstance = new DoNotIgnoreCommentsParser();
            var builder        = new ParserBuilder <DoNotIgnoreCommentsToken, DoNotIgnore>();
            var builtParser    = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "main");

            Assert.True(builtParser.IsOk);
            Assert.NotNull(builtParser.Result);
            var parser = builtParser.Result;

            var test = parser.Parse("a /*commented b*/b");

            Assert.True(test.IsOk);
            Assert.NotNull(test.Result);
            Assert.IsType <IdentifierList>(test.Result);
            var list = test.Result as IdentifierList;

            Assert.Equal(2, list.Ids.Count);
            Assert.False(list.Ids[0].IsCommented);
            Assert.Equal("a", list.Ids[0].Name);
            Assert.True(list.Ids[1].IsCommented);
            Assert.Equal("b", list.Ids[1].Name);
            Assert.Equal("commented b", list.Ids[1].Comment);
            ;
        }
Beispiel #18
0
        public void ParseWithValidListArgs()
        {
            // Arrange
            var parserBuild           = new ParserBuilder();
            var parser                = parserBuild.BuildParser();
            IEnumerable <string> args = new[]
            { "-Strvalue:custom value", "-i", "42", "-il", "42", "Custom argument value", "-b" };
            var expectedReturnCode     = CommandResultCode.Ok;
            var expectedStrValue       = "custom value";
            var expectedNbOfArguments  = 1;
            var expectedArgumentsValue = "Custom argument value";
            var expectedIntValue       = 42;

            // Act
            var actual = parser.Parse <IntTestCommand>(args);

            // Assert
            Assert.True(actual.IsValid);
            Assert.Equal(expectedReturnCode, actual.ReturnCode);
            Assert.IsType <IntTestCommand>(actual.Command);
            Assert.Equal(expectedStrValue, (actual.Command).StrValue);
            Assert.Equal(expectedIntValue, (actual.Command).IntValue);
            Assert.NotNull(actual.Command.IntListValue);
            Assert.Equal(expectedNbOfArguments, actual.Command.Arguments.Count);
            Assert.Equal(expectedArgumentsValue, actual.Command.Arguments.Single());
            Assert.Equal(expectedNbOfArguments, actual.Command.IntListValue.Count);
            Assert.Equal(expectedIntValue, actual.Command.IntListValue.Single());
            Assert.True(actual.Command.BoolValue);
        }
Beispiel #19
0
        public VariableExpressionTests()
        {
            var parserInstance = new VariableExpressionParser();
            var builder        = new ParserBuilder <ExpressionToken, Expression>();

            Parser = builder.BuildParser(parserInstance, ParserType.LL_RECURSIVE_DESCENT, "expression").Result;
        }
Beispiel #20
0
        public JsonGenericTests()
        {
            var jsonParser = new EbnfJsonGenericParser();
            var builder    = new ParserBuilder <JsonTokenGeneric, JSon>();

            Parser = builder.BuildParser(jsonParser, ParserType.EBNF_LL_RECURSIVE_DESCENT, "root").Result;
        }
        public void ParseWithValidArgs()
        {
            // Arrange
            var parserBuild = new ParserBuilder();
            var parser = parserBuild.BuildParser();
            IEnumerable<string> args = new[] { "delete", "-Source:custom value", "-np", "-ApiKey", "MyApiKey", "Custom argument value", "b" };
            var expectedReturnCode = CommandResultCode.Ok;
            var expectedSource = "custom value";
            var expectedApiKey = "MyApiKey";
            var expectedNbOfArguments = 2;
            var expectedArgumentsValue = new List<string> { "Custom argument value", "b" };

            // Act
            var actual = parser.Parse(args);

            // Assert
            Assert.True(actual.IsValid);
            Assert.Equal(expectedReturnCode, actual.ReturnCode);
            Assert.IsType<DeleteCommand>(actual.Command);
            Assert.Equal(expectedSource, ((DeleteCommand)actual.Command).Source);
            Assert.Equal(expectedApiKey, ((DeleteCommand)actual.Command).ApiKey);
            Assert.True(((DeleteCommand)actual.Command).NoPrompt);
            Assert.Null(((DeleteCommand)actual.Command).SourceProvider);
            Assert.Null(((DeleteCommand)actual.Command).Settings);
            Assert.Equal(expectedNbOfArguments, ((DeleteCommand)actual.Command).Arguments.Count);
            for (var i = 0; i < expectedNbOfArguments; i++)
            {
                Assert.Equal(expectedArgumentsValue[i], actual.Command.Arguments[i]);
            }
        }
        public void TestBug100()
        {
            var startingRule   = $"testNonTerm";
            var parserInstance = new Bugfix100Test();
            var builder        = new ParserBuilder <GroupTestToken, int>();
            var builtParser    = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, startingRule);

            Assert.False(builtParser.IsError);
            Assert.NotNull(builtParser.Result);
            var parser = builtParser.Result;

            Assert.NotNull(parser);
            var conf     = parser.Configuration;
            var expected = new List <GroupTestToken>()
            {
                GroupTestToken.A, GroupTestToken.COMMA
            };

            var nonTerm = conf.NonTerminals["testNonTerm"];

            Assert.NotNull(nonTerm);
            Assert.Equal(2, nonTerm.PossibleLeadingTokens.Count);
            Assert.True(nonTerm.PossibleLeadingTokens.ContainsAll(expected));

            var term = conf.NonTerminals["testTerm"];

            Assert.NotNull(term);
            Assert.Equal(2, nonTerm.PossibleLeadingTokens.Count);
            Assert.True(term.PossibleLeadingTokens.ContainsAll(expected));
        }
Beispiel #23
0
        private ILexer <ExpressionToken> GetExpressionLexer()
        {
            var exprParser = new ExpressionParser();
            var builder    = new ParserBuilder <ExpressionToken, int>();
            var parser     = builder.BuildParser(exprParser, ParserType.LL_RECURSIVE_DESCENT, "expression").Result;

            return(parser.Lexer);
        }
Beispiel #24
0
        private ILexer <JsonToken> GetJsonLexer()
        {
            var jsonParser = new JSONParser();
            var builder    = new ParserBuilder <JsonToken, JSon>();
            var parser     = builder.BuildParser(jsonParser, ParserType.LL_RECURSIVE_DESCENT, "root").Result;

            return(parser.Lexer);
        }
Beispiel #25
0
        public void BuildParserTest()
        {
            var parserInstance = new FormulaParser();
            var builder        = new ParserBuilder <FormulaToken, IFormula>();
            var parserResult   = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "formulae");

            Assert.True(parserResult.IsOk);
        }
Beispiel #26
0
        private void BuildParser()
        {
            StartingRule = $"{typeof(SimpleExpressionParser).Name}_expressions";
            var parserInstance = new SimpleExpressionParser();
            var builder        = new ParserBuilder <ExpressionToken, double>();

            Parser = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, StartingRule);
        }
        private BuildResult <Parser <TokenType, string> > BuildParser()
        {
            var parserInstance = new EBNFTests();
            var builder        = new ParserBuilder <TokenType, string>();
            var result         = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "R");

            return(result);
        }
Beispiel #28
0
        protected ParsingResult CallParseWithDefaultCommand <TCommand>(ParserBuilder parserBuilder, IEnumerable <string> args)
            where TCommand : class, ICommand
        {
            var parser        = parserBuilder.BuildParser();
            var parsingResult = parser.ParseWithDefaultCommand <TCommand>(args, _scopedServiceProvider);

            return(parsingResult);
        }
        public void TestBadVisitorTerminalArgument()
        {
            var instance = new BadTerminalArgParser();
            ParserBuilder <BadVisitorTokens, BadVisitor> builder = new ParserBuilder <BadVisitorTokens, BadVisitor>();
            var result = builder.BuildParser(instance, ParserType.LL_RECURSIVE_DESCENT, "badtermarg");

            Assert.True(result.IsError);
            Assert.Single(result.Errors);
            //"visitor BadReturn for rule badtermarg :  A B ; parameter a has incorrect type : expected sly.lexer.Token`1[ParserTests.BadVisitorTokens], found SubBadVisitor"
            Assert.Contains("parameter aArg has incorrect type", result.Errors.First().Message);

            result = builder.BuildParser(instance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "badtermarg");
            Assert.True(result.IsError);
            Assert.Single(result.Errors);
            //"visitor BadReturn for rule badtermarg :  A B ; parameter a has incorrect type : expected sly.lexer.Token`1[ParserTests.BadVisitorTokens], found SubBadVisitor"
            Assert.Contains("parameter aArg has incorrect type", result.Errors.First().Message);
        }
Beispiel #30
0
        private static BuildResult <Parser <ExpressionToken, double> > BuildParserExpression()
        {
            var StartingRule   = $"{typeof(SimpleExpressionParser).Name}_expressions";
            var parserInstance = new SimpleExpressionParser();
            var builder        = new ParserBuilder <ExpressionToken, double>();

            return(builder.BuildParser(parserInstance, ParserType.LL_RECURSIVE_DESCENT, StartingRule));
        }
Beispiel #31
0
        public WhileCompiler()
        {
            var parser  = new WhileParser();
            var builder = new ParserBuilder <WhileToken, WhileAST>();
            var whileParserBuildResult = builder.BuildParser(parser, ParserType.EBNF_LL_RECURSIVE_DESCENT, "statement");

            whileParser = whileParserBuildResult.Result;
        }
        public void TestBadVisitorReturn()
        {
            var instance = new BadVisitorReturnParser();
            ParserBuilder <BadVisitorTokens, BadVisitor> builder = new ParserBuilder <BadVisitorTokens, BadVisitor>();
            var result = builder.BuildParser(instance, ParserType.LL_RECURSIVE_DESCENT, "badreturn");

            Assert.True(result.IsError);
            Assert.Single(result.Errors);
            Assert.Contains("incorrect return type", result.Errors.First().Message);
            Assert.Contains("visitor BadReturn", result.Errors.First().Message);

            result = builder.BuildParser(instance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "badreturn");
            Assert.True(result.IsError);
            Assert.Single(result.Errors);
            Assert.Contains("incorrect return type", result.Errors.First().Message);
            Assert.Contains("visitor BadReturn", result.Errors.First().Message);
            ;
        }
        public void ParseWithInValidArgs()
        {
            // Arrange
            var parserBuild = new ParserBuilder();
            var parser = parserBuild.BuildParser();
            IEnumerable<string> args = new[] { "delete", "-Source:custom value", "-pn", "ApiKey", "MyApiKey", "Custom argument value", "b" };
            var expectedMessageException = @"There is no option 'pn' for the command 'Delete'.";

            // Act
            var actual = Assert.Throws<CommandLineParserException>(() => parser.Parse(args));

            // Assert
            Assert.Equal(expectedMessageException, actual.Message);
        }
        public void ParseWithBadCommandName()
        {
            // Arrange
            var parserBuild = new ParserBuilder();
            var parser = parserBuild.BuildParser();
            IEnumerable<string> args = new[] { "NotValid", "-option:true" };
            var expectedReturnCode = CommandResultCode.NoCommandFound;

            // Act
            var actual = parser.Parse(args);

            // Assert
            Assert.False(actual.IsValid);
            Assert.Equal(expectedReturnCode, actual.ReturnCode);
            Assert.Null(actual.Command);
        }
        public void ParseWithoutParameter()
        {
            // Arrange
            var parserBuild = new ParserBuilder();
            var parser = parserBuild.BuildParser();
            IEnumerable<string> args = null;
            var expectedReturnCode = CommandResultCode.NoArgs;

            // Act
            var actual = parser.Parse(args);

            // Assert
            Assert.False(actual.IsValid);
            Assert.Equal(expectedReturnCode, actual.ReturnCode);
            Assert.Null(actual.Command);
        }
        public void ParseWithInvalidArgs()
        {
            // Arrange
            var parserBuild = new ParserBuilder();
            var parser = parserBuild.BuildParser();
            IEnumerable<string> args = new[] {"-i", "42", "Custom argument value", "-b"};
            var expectedReturnCode = CommandResultCode.CommandParameterNotValid;
            var expectedNbOfArguments = 1;
            var expectedArgumentsValue = "Custom argument value";
            var expectedIntValue = 42;

            // Act
            var actual = parser.Parse<IntTestCommand>(args);

            // Assert
            Assert.False(actual.IsValid);
            Assert.Equal(expectedReturnCode, actual.ReturnCode);
            Assert.IsType<IntTestCommand>(actual.Command);
            Assert.Equal(expectedIntValue, actual.Command.IntValue);
            Assert.Null(actual.Command.IntListValue);
            Assert.Equal(expectedNbOfArguments, actual.Command.Arguments.Count);
            Assert.Equal(expectedArgumentsValue, actual.Command.Arguments.Single());
            Assert.True(actual.Command.BoolValue);
        }