Exemplo n.º 1
0
        public void BuildSetOptions_Build_ReturnsParser()
        {
            var parser = new ParserBuilder <TestTypeParent>().SetOptions(new MessageParserOptions()).Build <byte>();

            Assert.NotNull(parser);
            Assert.IsType <TypedMessageParser <TestTypeParent> >(parser);
        }
Exemplo n.º 2
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);
                }
            }
        }
Exemplo n.º 3
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);

            ;
        }
Exemplo n.º 4
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;
    }
Exemplo n.º 5
0
 /// <summary>
 /// Invokes configuration.
 /// </summary>
 /// <param name="parserBuilder">Parser builder.</param>
 /// <param name="configureAction">Configuration action.</param>
 internal static ParserBuilder <TOptions, TValue> Configure(ParserBuilder <TOptions, TValue> parserBuilder,
                                                            Action <MultiValueArgumentConfiguration <TOptions, TValue> > configureAction)
 {
     Check.NotNull(configureAction, nameof(configureAction));
     configureAction(new MultiValueArgumentConfiguration <TOptions, TValue>(parserBuilder));
     return(parserBuilder);
 }
Exemplo n.º 6
0
        public JsonTests()
        {
            var jsonParser = new JSONParser();
            var builder    = new ParserBuilder <JsonToken, JSon>();

            Parser = builder.BuildParser(jsonParser, ParserType.LL_RECURSIVE_DESCENT, "root").Result;
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            string path = ConfigurationManager.AppSettings.Get("filepath-in");
            Text   text;

            using (FileReader file = new FileReader(path))
            {
                Parser parser = ParserBuilder.GetParser();
                text = parser.Parse(file.Reader);
            }

            path = ConfigurationManager.AppSettings.Get("filepath-out");
            using (FileWriter file = new FileWriter(path))
            {
                text.Serialize(file.Writer);
            }

            //var words = TextManager.GetWordsInQuestions(text, 3);

            /*foreach (var word in words)
             * {
             *  Console.WriteLine(word.GetString());
             * }*/

            /*TextManager.PasteSubstring(text, StringParser.Parse("(: i love you :)"), 7, 3);
             * foreach (var sentence in text)
             * {
             *  Console.WriteLine(sentence.ToString());
             * }*/

            /*foreach (var sentence in TextManager.DeleteWords(text, 3))
             * {
             *  Console.WriteLine(sentence.ToString());
             * }*/
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
0
        public void GivenAFilePathWhenUsingTheBuilderThen()
        {
            using (FileStream stream = new FileStream(".\\MOCK_DATA.csv", FileMode.Open, FileAccess.Read, FileShare.None, 4096))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    int expecedRecordsCount = 800001; //One less than the source file because we are zero based.
                    int actualRecordCount   = 0;

                    foreach (var item in ParserBuilder.Create(reader, ParserSettings.CSV))
                    {
                        ++actualRecordCount;
                        using (IEnumerator <string> fields = item.GetEnumerator())
                        {
                            while (fields.MoveNext())
                            {
                                ;
                            }
                        }
                    }

                    Assert.AreEqual(expecedRecordsCount, actualRecordCount);
                }
            }
        }
        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]);
            }
        }
Exemplo n.º 11
0
        public JsonGenericTests()
        {
            var jsonParser = new EbnfJsonGenericParser();
            var builder    = new ParserBuilder <JsonTokenGeneric, JSon>();

            Parser = builder.BuildParser(jsonParser, ParserType.EBNF_LL_RECURSIVE_DESCENT, "root").Result;
        }
Exemplo n.º 12
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}");
     }
 }
Exemplo n.º 13
0
        public void BuildSetSubPropertySetter_Build_ReturnsParser()
        {
            var parser = new ParserBuilder <TestTypeParent>().SetSubPropertySetter(Mock.Of <ISubPropertySetterFactory>()).Build <byte>();

            Assert.NotNull(parser);
            Assert.IsType <TypedMessageParser <TestTypeParent> >(parser);
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
        public void BuildSetValidators_Build_ReturnsParser()
        {
            var parser = new ParserBuilder <TestTypeParent>().SetValidators(Mock.Of <IValidator>()).Build <byte>();

            Assert.NotNull(parser);
            Assert.IsType <TypedMessageParser <TestTypeParent> >(parser);
        }
Exemplo n.º 16
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);
            ;
        }
Exemplo n.º 17
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;
        }
Exemplo n.º 18
0
        public ParserForm()
        {
            InitializeComponent();

            parsers = ParserBuilder.GetParsers();
            ltbResults.DisplayMember = "DisplayInfo";
        }
Exemplo n.º 19
0
        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));
        }
Exemplo n.º 20
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");
                }
            }
        }
Exemplo n.º 21
0
        public static IParser Integer(
            bool allowLeadingZero = false,
            bool allowNegative    = true,
            string name           = "Integer")
        {
            var parser = allowLeadingZero
                ? ParserBuilder.OneOrMore(ParserBuilder.Class("0-9"))
                : ParserBuilder.Choice(
                ParserBuilder.T("0"),
                ParserBuilder.Sequence(
                    ParserBuilder.Class("1-9"),
                    ParserBuilder.ZeroOrMore(ParserBuilder.Class("0-9"))
                    )
                );

            if (allowNegative)
            {
                parser = ParserBuilder.Sequence(
                    ParserBuilder.Optional(ParserBuilder.T("-")),
                    parser
                    );
            }

            return(AddName(parser, name));
        }
Exemplo n.º 22
0
        public VariableExpressionTests()
        {
            var parserInstance = new VariableExpressionParser();
            var builder        = new ParserBuilder <ExpressionToken, Expression>();

            Parser = builder.BuildParser(parserInstance, ParserType.LL_RECURSIVE_DESCENT, "expression").Result;
        }
        public void TestNonLalr1()
        {
            //S->aEa | bEb | aFb | bFa
            //E->e
            //F->e

            var s      = new NonTerminal("S");
            var e      = new NonTerminal("E");
            var f      = new NonTerminal("F");
            var a      = new Token("a");
            var b      = new Token("b");
            var eToken = new Token("e");

            var rules = new[]
            {
                new Rule(Start, s),
                new Rule(s, a, e, a),
                new Rule(s, b, e, b),
                new Rule(s, a, f, b),
                new Rule(s, b, f, a),
                new Rule(e, eToken),
                new Rule(f, eToken),
            };
            var nodes  = ParserBuilder.CreateParser(rules);
            var parser = new ParserNodeParser(nodes, Start, this.output.WriteLine);

            var listener = new TreeListener();

            parser.Parse(new[] { a, eToken, a }, listener);

            this.output.WriteLine(listener.Root.Flatten().ToString());
            listener.Root.Flatten().ToString()
            .ShouldEqual("Start(S(a, E(e), a))");
        }
Exemplo n.º 24
0
        public static IParser Decimal(
            bool allowLeadingZero        = false,
            bool allowNegative           = true,
            bool allowIntegerOnly        = true,
            bool allowEmptyDecimalDigits = false, // Ex: 12. instead of 12.0
            string name = "Decimal")
        {
            var intPart = Integer(
                allowLeadingZero,
                allowNegative,
                null);

            var decimalDigitsPart = allowEmptyDecimalDigits
                ? ParserBuilder.ZeroOrMore(ParserBuilder.Class("0-9"))
                : ParserBuilder.OneOrMore(ParserBuilder.Class("0-9"));

            var decimalPart = ParserBuilder.Sequence(
                ParserBuilder.T("."),
                decimalDigitsPart);

            if (allowIntegerOnly)
            {
                decimalPart = ParserBuilder.Optional(decimalPart);
            }

            var parser = ParserBuilder.Sequence(
                intPart,
                decimalPart);

            return(AddName(parser, name));
        }
Exemplo n.º 25
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}");
        }
        public void TestTrueGenericsAmbiguity()
        {
            var name                      = new NonTerminal("Name");
            var argList                   = new NonTerminal("List<Exp>");
            var genericParameters         = new NonTerminal("Gen");
            var optionalGenericParameters = new NonTerminal("Opt<Gen>");
            var cmp = new NonTerminal("Cmp");

            var rules = new[]
            {
                new Rule(Start, Exp),

                new Rule(Exp, ID),
                new Rule(Exp, OPEN_PAREN, Exp, CLOSE_PAREN),
                new Rule(Exp, ID, cmp, Exp),
                new Rule(Exp, name, OPEN_PAREN, argList, CLOSE_PAREN),

                new Rule(cmp, LT),
                new Rule(cmp, GT),

                new Rule(argList, Exp),
                new Rule(argList, Exp, COMMA, argList),

                new Rule(name, ID, optionalGenericParameters),

                new Rule(optionalGenericParameters),
                new Rule(optionalGenericParameters, genericParameters),

                new Rule(genericParameters, LT, ID, GT)
            };

            // currently this fails due to duplicate prefixes
            var ex = Assert.Throws <NotSupportedException>(() => ParserBuilder.CreateParser(rules));

            this.output.WriteLine(ex.Message);

            var nodes = ParserBuilder.CreateParser(
                rules,
                new Dictionary <IReadOnlyList <Symbol>, Rule>
            {
                {
                    // id<id>(id could be call(id<id>, id) or compare(id, compare(id, id))
                    new[] { ID, LT, ID, GT, OPEN_PAREN, ID },
                    rules.Single(r => r.Symbols.SequenceEqual(new Symbol[] { name, OPEN_PAREN, argList, CLOSE_PAREN }))
                },
                {
                    // id<id>(( could be call(id<id>, (...)) or compare(id, compare(id, (...)))
                    new[] { ID, LT, ID, GT, OPEN_PAREN, OPEN_PAREN },
                    rules.Single(r => r.Symbols.SequenceEqual(new Symbol[] { name, OPEN_PAREN, argList, CLOSE_PAREN }))
                },
            }
                );
            var parser   = new ParserNodeParser(nodes, Start, this.output.WriteLine);
            var listener = new TreeListener();

            // compares: id < id > (id) vs. call: id<id>(id) => our resolution says call
            parser.Parse(new[] { ID, LT, ID, GT, OPEN_PAREN, ID, CLOSE_PAREN }, listener);
            this.output.WriteLine(listener.Root.Flatten().ToString());
            listener.Root.Flatten().ToString().ShouldEqual("Start(Exp(Name(ID, Opt<Gen>(Gen(<, ID, >))), (, List<Exp>(Exp(ID)), )))");
        }
        public void TestAliases()
        {
            var binop = new NonTerminal("Binop");
            var rules = new[]
            {
                new Rule(Start, Exp),

                new Rule(Exp, ID),
                new Rule(Exp, MINUS, Exp),
                new Rule(Exp, binop),

                new Rule(binop, Exp, TIMES, Exp),
                new Rule(binop, Exp, MINUS, Exp),
            };

            var rewritten = LeftRecursionRewriter.Rewrite(rules, rightAssociativeRules: ImmutableHashSet.Create(rules[1]));

            this.output.WriteLine(ToString(rewritten));

            var nodes    = ParserBuilder.CreateParser(rewritten.Keys);
            var listener = new TreeListener(rewritten);
            var parser   = new ParserNodeParser(nodes, Start);

            parser.Parse(new[] { ID, TIMES, MINUS, ID, MINUS, ID }, listener);
            this.output.WriteLine(ToGroupedTokenString(listener.Root));
            ToGroupedTokenString(listener.Root)
            .ShouldEqual("(ID * (- ID)) - ID");
        }
Exemplo n.º 28
0
        public async Task ParseMultipleMessages()
        {
            // Construct the pipe
            var pipe = new Pipe();

            // Create a message parser that can parser bytes into Order
            var messageParser = new ParserBuilder <Order>().Build <byte>(new MessageParserOptions()
            {
                ThrowIfInvalidMessage = false
            });

            // Create the piped parser, providing the pipe and an IMessageParser
            var parser = new PipeParser <Order>(pipe.Reader, messageParser, SupportedFixVersion.Fix44);

            // We subscribe to the observable to print the parsed messages
            parser.Subscribe(
                order => Console.WriteLine($"Order {order.Symbol} - Px {order.Price}, Qty {order.Quantity}"),
                ex => Console.WriteLine($"Error: {ex.Message}"));

            // We create sample messages and write them into the pipe asnyc
            var inputTask = Task.Run(() => CreateSimulatedInput(pipe));

            // Start observing and await until all messages observed
            await parser.ListenAsync();

            // Should be completed by now
            await inputTask;
        }
        public void ParserWithNoConverterThrows()
        {
            var parserBuilder = new ParserBuilder <object, NotConvertible>();

            ((IComponentSink <IMapper <object, NotConvertible> >)parserBuilder).Sink(new Mock <IMapper <object, NotConvertible> >().Object);
            Should.Throw <ConfigurationException>(() => parserBuilder.PositionArgument(0));
        }
        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);
        }
        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]);
            }
        }
Exemplo n.º 32
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}");
        }
        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);
        }