Exemple #1
0
 private static INode GetTree(string str)
 {
     var parser = new SimpleParser<Arithmetic, double>(double.Parse,
         t => t.IsGenericType && t.IsSubclassOf(typeof(BinaryOp)));
     var tree = parser.Parse(str);
     return tree;
 }
        /// <summary>
        /// Parse a line with space separators.
        /// </summary>
        /// <param name="line">The line to parse.</param>
        /// <returns>The list of items from the line.</returns>
        private static List<String> ParseSpaceSep(String line)
        {
            var result = new List<String>();
            var parse = new SimpleParser(line);

            while (!parse.EOL())
            {
                result.Add(parse.Peek() == '\"' ? parse.ReadQuotedString() : parse.ReadToWhiteSpace());
                parse.EatWhiteSpace();
            }

            return result;
        }
Exemple #3
0
        public static void Main(string[] args)
        {
            if (args.Length > 0)
            {

                ICharStream input = new ANTLRFileStream(args[0]);
                SimpleLexer lex = new SimpleLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lex);
                SimpleParser parser = new SimpleParser(tokens);
                parser.program();
            }
            else
                Console.Error.WriteLine("Usage: island <input-file>");
        }
        private static string MatchEval(Match m, object data, bool htmlEncode)
        {
            var parser = new SimpleParser(m.Groups[1].Value)
                {
                    GlobalType = data.GetType(),
                    StaticTypes = new[] { typeof(Path) },
                };
            var valueExecutor = parser.Read<TemplateParser.ValueBuilder, TemplateParser.INode>();
            var type = valueExecutor.Compile(parser.GlobalType);
            var value = valueExecutor.Execute(data);
            var result = value.ToString();
            if (htmlEncode)
                result = HttpUtility.HtmlEncode(result);

            return result;
        }
Exemple #5
0
        /// <summary>
        /// Parse a value.
        /// </summary>
        ///
        /// <param name="parser">The parser to use.</param>
        /// <returns>The newly parsed value.</returns>
        private static String ParseValue(SimpleParser parser)
        {
            bool quoted = false;
            var  str    = new StringBuilder();

            parser.EatWhiteSpace();

            if (parser.Peek() == '\"')
            {
                quoted = true;
                parser.Advance();
            }

            while (!parser.EOL())
            {
                if (parser.Peek() == '\"')
                {
                    if (quoted)
                    {
                        parser.Advance();
                        if (parser.Peek() == '\"')
                        {
                            str.Append(parser.ReadChar());
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        str.Append(parser.ReadChar());
                    }
                }
                else if (!quoted &&
                         (parser.IsWhiteSpace() || (parser.Peek() == ',')))
                {
                    break;
                }
                else
                {
                    str.Append(parser.ReadChar());
                }
            }
            return(str.ToString());
        }
Exemple #6
0
        public static CommonTree Parse(string formula)
        {
            var m     = new MemoryStream(Encoding.UTF8.GetBytes(formula));
            var input = new ANTLRInputStream(m);

            // Create lexer
            var lexer  = new SimpleLexer(input);
            var tokens = new CommonTokenStream(lexer);

            // Create parser and start evaluating from start rule
            var parser = new SimpleParser(tokens);
            var tree   = parser.start();

            var root = (CommonTree)tree.Tree;

            return(root);
        }
        public ParsedOutputConverter()
        {
            var simpleParser = new SimpleParser();
            var attackParser = new AttackParser();
            var narrsParser  = new NarrsParser();

            Store.TcpReceive.SubscribeAsync(async(message) => {
                var lines = ControlCharacterEncoder.EncodeAndSplit(message);


                var parsedWithStatusSeparate        = new StatusParser().Parse(lines);
                var parsedWithStatusAndRoomSeparate = RoomParser.Parse(parsedWithStatusSeparate);

                foreach (var output in parsedWithStatusAndRoomSeparate)
                {
                    if (output.Type != ParsedOutputType.Raw)
                    {
                        continue;
                    }

                    output.LineMetadata = new LineMetadata[output.Lines.Length];

                    int i = 0;
                    foreach (var line in output.Lines)
                    {
                        // todo: is having a separate lineMetadata array the way to go? it minimizes copies a little bit but it's ugly and also in some ways doesnt
                        output.LineMetadata[i] = new LineMetadata();
                        var result             = simpleParser.Parse(line);
                        if (result != LineMetadataType.None)
                        {
                            output.LineMetadata[i].Type = result;
                        }
                        else if (attackParser.Matches(line))
                        {
                            output.LineMetadata[i].Type = LineMetadataType.Attack;
                        }
                        else if (narrsParser.Matches(line))
                        {
                            output.LineMetadata[i].Type = LineMetadataType.Communication;
                        }
                        i++;
                    }
                }
                await Store.ParsedOutput.SendAsync(parsedWithStatusAndRoomSeparate);
            });
        }
            public void NextIs()
            {
                var parser = new SimpleParser("<asdf/>");

                Assert.IsFalse(parser.NextIs("asdf"));
                Assert.IsTrue(parser.NextIs('<'));
                Assert.AreEqual(0, parser.Position);
                Assert.IsTrue(parser.NextIs("<asdf/>"));
                Assert.AreEqual(0, parser.Position);
                Assert.IsTrue(parser.NextIs('<'));
                parser.ReadUntil('/');
                parser.Unskip(1);
                Assert.IsTrue(parser.NextIs('/'));
                Assert.IsFalse(parser.NextIs("asdf"));
                Assert.IsTrue(parser.NextIs('/'));
                Assert.IsTrue(parser.NextIs("/>"));
                Assert.IsTrue(parser.NextIs('/'));
            }
        private static string MatchEval(Match m, object data, bool htmlEncode)
        {
            var parser = new SimpleParser(m.Groups[1].Value)
            {
                GlobalType = data.GetType()
            };
            var valueExecutor = parser.Read <TemplateParser.ValueBuilder, TemplateParser.INode>();
            var type          = valueExecutor.Compile(parser.GlobalType);
            var value         = valueExecutor.Execute(data);
            var result        = value.ToString();

            if (htmlEncode)
            {
                result = HttpUtility.HtmlEncode(result);
            }

            return(result);
        }
Exemple #10
0
        private TableSchema ParseCreateTable(string sql)
        {
            var parser = new SimpleParser(sql);

            var tableSchema = new TableSchema();

            tableSchema.Columns = new List <ColumnSchema>();

            parser.SkipOverString("create table");
            tableSchema.TableName = parser.TakeWord();
            parser.SkipOverString("(");
            while (!parser.AtEnd() && !parser.Is(')'))
            {
                var column = new ColumnSchema();
                tableSchema.Columns.Add(column);

                column.ColumnName = parser.TakeWord();
                column.DataType   = parser.TakeWord();

                var attributes = parser.TakeToAny(new[] { ',', ')' }).ToUpper();
                if (attributes.Contains("PRIMARY KEY"))
                {
                    column.Attributes = column.Attributes | ColumnAttributes.Primary;
                }
                if (attributes.Contains("NOT NULL"))
                {
                    column.Attributes = column.Attributes | ColumnAttributes.NotNull;
                }
                if (attributes.Contains("UNIQUE"))
                {
                    column.Attributes = column.Attributes | ColumnAttributes.Unique;
                }
                if (attributes.Contains("AUTOINCREMENT"))
                {
                    column.Attributes = column.Attributes | ColumnAttributes.AutoIncrement;
                }
                if (string.Equals(column.DataType, "TEXT", StringComparison.OrdinalIgnoreCase) && !attributes.Contains("COLLATE NOCASE"))
                {
                    column.Attributes = column.Attributes | ColumnAttributes.CaseSensitive;
                }
            }

            return(tableSchema);
        }
        public static void TestReturnsZeroWhenEmptyString()
        {
            //use reflection to get the current method's name
            string testName = MethodBase.GetCurrentMethod().Name;

            try
            {
                SimpleParser p      = new SimpleParser();
                int          result = p.ParseAndSum("1");
                if (result != 0)
                {
                    TestUtil.ShowProblem(testName, "Parse and sum should have returned 0 on an empty string");
                }
            }
            catch (Exception e)
            {
                TestUtil.ShowProblem(testName, e.ToString());
            }
        }
Exemple #12
0
 public static void TestReturnsZeroWhenEmptyString()
 {
     try
     {
         SimpleParser p      = new SimpleParser();
         int          result = p.ParseAndSum(string.Empty);
         if (result != 0)
         {
             Console.WriteLine(
                 @"***SimpleParserTests.TestReturnsZeroWhenEmptyString: 
                 -------
                 Parse and sum should have returned 0 on an empty string");
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Exemple #13
0
        public static void TestReturnsZeroWhenEmptyString()
        {
            // 현재 메서드의 이름을 얻기위해 리플렉션 API사용.
            string testName = MethodBase.GetCurrentMethod().Name;

            try
            {
                SimpleParser p      = new SimpleParser();
                int          result = p.ParseAndSum(string.Empty);
                if (result != 0)
                {
                    Console.WriteLine(@"SimplePArserTests.TestReturnsZeroWhenEmptyString: ParseAndSum은 빈 문자열에 대해 0을 반환해야한다.");
                }
            }
            catch (Exception e)
            {
                TestUtil.ShowProblem(testName, e.ToString());
            }
        }
        public HardwareEmulator(string port)
        {
            _port = new SerialPort(port, baudRate: 115200, parity: Parity.None, dataBits: 8, stopBits: StopBits.One);
            _port.ReceivedBytesThreshold = 14;
            _port.DataReceived          += PortOnDataReceived;

            try
            {
                if (!_port.IsOpen)
                {
                    _port.Open();
                }
                _port.DiscardInBuffer();
                _port.DiscardOutBuffer();
            }
            catch { }

            _parser           = new SimpleParser();
            _parser.Received += (sender, s) => Received?.Invoke(sender, s);
        }
Exemple #15
0
        private IndexSchema ParseCreateIndex(string sql)
        {
            var parser      = new SimpleParser(sql);
            var indexSchema = new IndexSchema();

            indexSchema.Attributes = IndexAttributes.CaseSensitive;

            parser.SkipOverString("CREATE");
            if (parser.TakeWord().ToUpper() == "UNIQUE")
            {
                indexSchema.Attributes = indexSchema.Attributes | IndexAttributes.Unique;
                parser.SkipOverString("INDEX");
            }

            indexSchema.IndexName = parser.TakeWord();
            if (indexSchema.IndexName.ToUpper() == "IF")
            {
                parser.SkipOverString("EXISTS");
                indexSchema.IndexName = parser.TakeWord();
            }
            parser.SkipOverString("ON");
            parser.TakeWord(); // table name
            parser.SkipOverString("(");

            var columnNames = new List <string>();

            while (!parser.AtEnd() && !parser.Is(')'))
            {
                columnNames.Add(parser.TakeWord());
                parser.SkipAny(' ');
                var columnOptions = parser.TakeToAny(',', ')').ToUpper();
                if (columnOptions.Contains("COLLATE NOCASE"))
                {
                    indexSchema.Attributes = indexSchema.Attributes & ~IndexAttributes.CaseSensitive;
                }
                parser.Skip(1);
            }
            indexSchema.ColumnNames = columnNames.ToArray();

            return(indexSchema);
        }
Exemple #16
0
        static void ParseAddressesHelper(List <string> addresses, SimpleParser p, bool ipv6, List <string> rejectedAddresses)
        {
            string address;

            while (true)
            {
                address = p.TrySeekAndExtract("", ipv6 ? IPv6Prefix : IPv4Prefix, IpSuffix).Trim();
                if (address == "")
                {
                    return;
                }
                if (IsValidIpOrSubnet(address, ipv6))
                {
                    addresses.Add(address);
                }
                else
                {
                    rejectedAddresses.Add(address);
                }
            }
        }
Exemple #17
0
        public void SplitFace_ShouldWorkForComplicatedFile()
        {
            // Arrange
            var path = "D:\\Git\\PolygonMesh\\PolygonMesh.Library.Tests\\Resources\\torus.obj";
            var vecs = SimpleParser.Parse(path, out var faces);
            var mesh = Mesh.Core.Mesh.CreateFromPositions(vecs, faces);

            // Act
            var initialFaces    = mesh.FaceCount;
            var initialVertices = mesh.VertexCount;

            for (int i = 0; i < initialFaces; i++)
            {
                mesh.SplitFace(i);
            }

            // Assert
            Assert.AreEqual(initialVertices, mesh.VertexCount);
            Assert.AreEqual(initialFaces * 2, mesh.FaceCount);
            SimpleExporter.Export("D:\\Git\\PolygonMesh\\PolygonMesh.Library.Tests\\Resources\\test.obj", mesh);
        }
Exemple #18
0
        public static Command Parse(string[] args, IList <ICommandMapper> commands, Func <Type, Command> commandTypeResolver = null)
        {
            var resolver = commandTypeResolver ?? DefaultResolver;

            var parser = new SimpleParser(args, true);
            var cmd    = parser.Arguments[0].ToLower();
            var mapper = commands.FirstOrDefault(commandMapper => commandMapper.CommandName.ToLower() == cmd);

            if (mapper == null)
            {
                throw new ArgumentException($"No CommandMapper found for command: '{cmd}'.", nameof(args));
            }
            var commandType = mapper.CommandType;

            var command = resolver(commandType);

            mapper.MapArguments(parser.Arguments, command);
            parser.SetOptionAndFlagValues(command);
            Validator.ValidateObject(command, new ValidationContext(command));
            return(command);
        }
Exemple #19
0
        static void Main(string[] args)
        {
            // TODO: Show usage
            var clap    = new SimpleParser(args);
            var inputs  = clap.Arguments;
            var options = GetOptions(clap);

            options = CheckOptions(inputs, options);

            Console.WriteLine("Plaiting...");
            ShowOptions(options, inputs);

            var bitmaps = ReadImages(inputs);


            var output = Plait(bitmaps, options);

            bitmaps.Dispose();

            SaveImage(output, options.OutputFilename);
        }
Exemple #20
0
        private static bool ParseArgs(string[] args, SimpleParser parser)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("");
                Console.WriteLine("Usage:");
                Console.WriteLine("--path:      Specifies path to a Unity generated Log file, which will be the file to parse.");
                Console.WriteLine("--output:    Specifies path to where the CSV containing the categorized entries should be written to.");
                Console.WriteLine("");
                Console.WriteLine(@"Sample command line: dotnet SimpleLogParser.dll --path C:\Projects\Game01\Editor.log --output C:\Projects\Game01\CategorizedLog.csv");
                Console.WriteLine("");
                return(false);
            }

            for (int i = 0; i < args.Length; ++i)
            {
                if (args[i] == "--path")
                {
                    parser.EditorLogPath = args[i + 1];
                }
                else if (args[i] == "--output")
                {
                    parser.OutputPath = args[i + 1];
                }
            }

            if (parser.EditorLogPath == null)
            {
                Console.WriteLine("Error: Path to log file must be specified. Please use --path followed by the path to the file.");
                return(false);
            }

            if (parser.OutputPath == null)
            {
                Console.WriteLine("Error: Path to where categorized CSV file should be written to was not specified. Please add --output followed by the path to where this file should be written.");
                return(false);
            }

            return(true);
        }
Exemple #21
0
        // Here's where we do the real work...
        public static void  ParseJavaFile(string f)
        {
            try
            {
                // Create a scanner that reads from the input stream passed to us
                SimpleLexer       lexer  = new SimpleLexer(new ANTLRFileStream(f));
                CommonTokenStream tokens = new CommonTokenStream();
                tokens.TokenSource = lexer;

                // Create a parser that reads from the scanner
                SimpleParser parser = new SimpleParser(tokens);

                // start parsing at the file rule
                parser.file();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("[ERROR}");
                Console.Error.WriteLine("parser exception: " + e);
                Console.Error.WriteLine(e.StackTrace);                 // so we can get stack trace
            }
        }
        public void TestMatchStringEquals()
        {
            const string expressionJson  = @"
[""equals"",
    [""field"", ""name""],
    [""value"",""Daphne Sutton""]
]";
            var          expressionBytes = Encoding.UTF8.GetBytes(expressionJson);

            var parser     = new SimpleParser();
            var expression = parser.ParseJsonExpression(expressionBytes);

            var matcher = new SlowMatcher(new[] { expression });

            var ids = new[] { "5b47eb0936ff92a567a0307e" };

            foreach (var entry in _peopleData.Where(x => ids.Contains(x.Key)))
            {
                var data = Encoding.UTF8.GetBytes(entry.Value);
                Assert.True(matcher.Match(data));
            }
        }
        public void TestMatcherNumericEquals()
        {
            const string expressionJson  = @"
[""equals"",
    [""field"",""age""],
    [""value"",25]
]";
            var          expressionBytes = Encoding.UTF8.GetBytes(expressionJson);

            var parser     = new SimpleParser();
            var expression = parser.ParseJsonExpression(expressionBytes);

            var matcher = new SlowMatcher(new[] { expression });

            var ids = new[] { "5b47eb091f57571d3c3b1aa1" };

            foreach (var entry in _peopleData.Where(x => ids.Contains(x.Key)))
            {
                var data = Encoding.UTF8.GetBytes(entry.Value);
                Assert.True(matcher.Match(data));
            }
        }
        public void TestMatcherFloatEquals()
        {
            const string expressionJson  = @"
[""equals"",
    [""field"",""latitude""],
    [""value"",-40.262556]
]";
            var          expressionBytes = Encoding.UTF8.GetBytes(expressionJson);

            var parser     = new SimpleParser();
            var expression = parser.ParseJsonExpression(expressionBytes);

            var matcher = new SlowMatcher(new[] { expression });

            var ids = new[] { "5b47eb096b1d911c0b9492fb" };

            foreach (var entry in _peopleData.Where(x => ids.Contains(x.Key)))
            {
                var data = Encoding.UTF8.GetBytes(entry.Value);
                Assert.True(matcher.Match(data));
            }
        }
        public static void TestReturnsZeroWhenEmptyString()
        {
            string testName = MethodBase.GetCurrentMethod().Name;

            try
            {
                SimpleParser p      = new SimpleParser();
                int          result = p.ParseAndSum(string.Empty);
                if (result != 0)
                {
                    TestUtility.ShowProblem(testName, "FAILED: Parse and sum should have returned 0 on an empty string");
                }
                else
                {
                    TestUtility.ShowProblem(testName, "PASSED");
                }
            }
            catch (Exception e)
            {
                TestUtility.ShowProblem(testName, string.Format("FAILED: {0}", e.ToString()));
            }
        }
        public void TestMatcherDisparateTypeEquals()
        {
            const string expressionJson  = @"
[""equals"",
    [""field"", ""sometimesValue""],
    [""value"", ""thisShouldBeABoolean""]
]";
            var          expressionBytes = Encoding.UTF8.GetBytes(expressionJson);

            var parser     = new SimpleParser();
            var expression = parser.ParseJsonExpression(expressionBytes);

            var matcher = new SlowMatcher(new[] { expression });

            var ids = new[] { "5b47eb0936ff92a567a0307e", "5b47eb096b1d911c0b9492fb" };

            foreach (var entry in _peopleData.Where(x => ids.Contains(x.Key)))
            {
                var data = Encoding.UTF8.GetBytes(entry.Value);
                Assert.True(matcher.Match(data));
            }
        }
        public void TestMatcherMissingStringEquals()
        {
            const string expressionJson  = @"
[""equals"",
    [""field"", ""someValueWhichNeverExists""],
    [""value"", ""hello""]
]";
            var          expressionBytes = Encoding.UTF8.GetBytes(expressionJson);

            var parser     = new SimpleParser();
            var expression = parser.ParseJsonExpression(expressionBytes);

            var matcher = new SlowMatcher(new[] { expression });

            var ids = new string[] { };

            foreach (var entry in _peopleData.Where(x => ids.Contains(x.Key)))
            {
                var data = Encoding.UTF8.GetBytes(entry.Value);
                Assert.True(matcher.Match(data));
            }
        }
Exemple #28
0
        // Here's where we do the real work...
        public static void ParseJavaFile(string f)
        {
            try
            {
                // Create a scanner that reads from the input stream passed to us
                SimpleLexer lexer = new SimpleLexer(new ANTLRFileStream(f));
                CommonTokenStream tokens = new CommonTokenStream();
                tokens.TokenSource = lexer;

                // Create a parser that reads from the scanner
                SimpleParser parser = new SimpleParser(tokens);

                // start parsing at the file rule
                parser.file();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("[ERROR}");
                Console.Error.WriteLine("parser exception: " + e);
                Console.Error.WriteLine(e.StackTrace); // so we can get stack trace
            }
        }
            public void ReadUntil()
            {
                Assert.AreEqual("", new SimpleParser("abcabc").ReadUntil('a'));
                Assert.AreEqual("a", new SimpleParser("abcabc").ReadUntil('b'));
                Assert.AreEqual("ab", new SimpleParser("abcabc").ReadUntil('c'));
                Assert.AreEqual("abcabc", new SimpleParser("abcabc").ReadUntil('d'));
                Assert.AreEqual("", new SimpleParser("").ReadUntil('d'));
                var p = new SimpleParser("abc.def ghi");

                Assert.AreEqual('\0', p.LastChar);
                Assert.AreEqual('a', p.NextChar.Value);
                Assert.AreEqual("abc", p.ReadUntil('.', ' '));
                Assert.AreEqual('.', p.LastChar);
                Assert.AreEqual('d', p.NextChar.Value);
                Assert.AreEqual("def", p.ReadUntil('.', ' '));
                Assert.AreEqual(' ', p.LastChar);
                Assert.IsTrue(p.HasNext);
                Assert.AreEqual("ghi", p.ReadUntil());
                Assert.AreEqual('i', p.LastChar);
                Assert.IsNull(p.NextChar);
                Assert.IsFalse(p.HasNext);
            }
Exemple #30
0
        public void TestBuilding()
        {
            var x = Parser.ParseString("(node {attr (node 3.14) attr2 (node [\"6\" \"7\"])} [true false null])");
            var s = SimpleParser.Build(x);
            var n = s as Node;

            AssertNode(n, "node", 2, 3);

            var attr     = n.Attributes["attr"];
            var attrNode = attr as Node;

            AssertNode(attrNode, "node", 0, 1);
            AssertNumberLiteral(attrNode.Children[0] as NumberLiteral, 3, 14);

            var attr2     = n.Attributes["attr2"];
            var attr2Node = attr2 as Node;

            AssertNode(attr2Node, "node", 0, 2);
            AssertStringLiteral(attr2Node.Children[0] as StringLiteral, "6");
            AssertStringLiteral(attr2Node.Children[1] as StringLiteral, "7");

            AssertBooleanLiteral(n.Children[0] as BooleanLiteral, true);
            AssertBooleanLiteral(n.Children[1] as BooleanLiteral, false);
            Assert.AreEqual(n.Children[2].GetType(), typeof(NullLiteral));

            // a few other cases

            var fn = TestHelper.MakeTempFile("(node (node {a 1 b 2}))");

            s = SimpleParser.Parse(fn);
            TestHelper.DeleteTempFile(fn);
            n = s as Node;
            AssertNode(n, "node", 0, 1);

            n = n.Children[0] as Node;
            AssertNode(n, "node", 2, 0);
            AssertNumberLiteral(n.Attributes["a"] as NumberLiteral, 1, 0);
        }
        private Node <string> CallParse()
        {
            if (txtInput.Text.Length == 0)
            {
                AddTextLineToOutput("No input specified", Color.Red);
                return(null);
            }

            var parser = new SimpleParser(lexer);

            try
            {
                parser.Parse(txtInput.Text);
                RenderTree(parser.SyntaxTree);
                AddTextLineToOutput("Parsing succeeded", Color.DarkGreen);
                return(parser.SyntaxTree);
            }
            catch (ParserException ex)
            {
                AddTextLineToOutput(ex.Message, Color.Red);
                return(null);
            }
        }
        public static void TestReturnsNumberWhenStringContainsOneNumber()
        {
            string testName = MethodBase.GetCurrentMethod().Name;

            try
            {
                SimpleParser p       = new SimpleParser();
                string       numbers = "324";
                int          result  = p.ParseAndSum(numbers);
                if (result == Convert.ToInt32(numbers))
                {
                    TestUtility.ShowProblem(testName, "PASSED");
                }
                else
                {
                    TestUtility.ShowProblem(testName, "FAILED: Parse and sum should have returned a single number.");
                }
            }
            catch (Exception e)
            {
                TestUtility.ShowProblem(testName, string.Format("FAILED: {0}", e.ToString()));
            }
        }
        public static void TestReturnsSumWhenStringContainsMoreThanOneNumber()
        {
            string testName = MethodBase.GetCurrentMethod().Name;

            try
            {
                SimpleParser p       = new SimpleParser();
                string       numbers = "5,10,15,20,25,30,40";
                int          result  = p.ParseAndSum(numbers);
                if (result == 145)
                {
                    TestUtility.ShowProblem(testName, "PASSED");
                }
                else
                {
                    TestUtility.ShowProblem(testName, "FAILED: Parse and sum should have returned the correct summation");
                }
            }
            catch (Exception e)
            {
                TestUtility.ShowProblem(testName, string.Format("FAILED: {0}", e.ToString()));
            }
        }
Exemple #34
0
        /// <summary>
        /// Create the behaviors.
        /// </summary>
        /// <param name="types">The behavior types.</param>
        /// <param name="simulation">The simulation.</param>
        /// <param name="entities">The circuit entities.</param>
        public override void CreateBehaviors(Type[] types, Simulation simulation, EntityCollection entities)
        {
            // Get the expression
            var expression = ParameterSets.Get <BaseParameters>().Expression;

            // We first want to create the behaviors of sources for which we will use the current branches
            var parser = new SimpleParser();

            // Get our own parameter
            var bp = simulation.EntityParameters[Name].Get <BaseParameters>();

            // We want to avoid throwing exceptions on variables, functions or spice properties, we just want to find the
            // voltage sources our component depends on
            parser.VariableFound      += (sender, e) => e.Result = 0.0;
            parser.FunctionFound      += (sender, e) => e.Result = 0.0;
            parser.SpicePropertyFound += (sender, e) =>
            {
                if (bp.SpicePropertyComparer.Equals(e.Property.Identifier, "I"))
                {
                    // Get the component name
                    var source = e.Property[0];
                    if (bp.Instance != null)
                    {
                        source = bp.Instance.GenerateIdentifier(source);
                    }

                    // Make sure its behaviors are created before ours
                    entities[source].CreateBehaviors(types, simulation, entities);
                }
                e.Apply(() => 0.0);
            };
            parser.Parse(expression);

            // Now we can continue with out own behavior creation
            base.CreateBehaviors(types, simulation, entities);
        }
Exemple #35
0
        public static void TestReturnsZeroWhenEmptyString()
        {
            //wykorzystanie API refleksji frameworka .NET
            // do uzyskania bieżącej nazwy metody
            // można by ją zakodować na sztywno,
            //ale posługiwanie się refleksjami jest użyteczną techniką, którą warto znać
            string testName = MethodBase.GetCurrentMethod().Name;

            try
            {
                SimpleParser p      = new SimpleParser();
                int          result = p.ParseAndSum("1");
                if (result != 0)
                {
                    // Wywołanie metody pomocniczej
                    TestUtil.ShowProblem(testName,
                                         "Metoda ParseAndSum powinna zwrócić 0 w przypadku przekazania pustego ciągu znaków");
                }
            }
            catch (Exception e)
            {
                TestUtil.ShowProblem(testName, e.ToString());
            }
        }
            /// <summary>
            /// Reads the code trying to extract the AST from it.
            /// </summary>
            /// <param name="parser">The parser object used to read the code.</param>
            /// <param name="prevData">Previously parsed result. This is used to chain results together.</param>
            /// <returns>Returns an object that results from parsing the code.</returns>
            public override object Read(SimpleParser parser, object prevData)
            {
                var prevExecutor = (INode)prevData;

                parser.SkipSpaces();

                if (prevExecutor == null)
                {
                    var name = this.ReadName(parser);

                    // this is a direct method call in the root
                    var call = ReadMethodCall(parser, null, name);
                    if (call != null)
                        return call;

                    // this is a global property
                    if (!string.IsNullOrWhiteSpace(name))
                        return new PropertyGet { Name = name, Element = null };

                    // this is an array construct
                    if (parser.ReadChar('{'))
                    {
                        var values = parser.ReadList<ValueBuilder, INode>(ReadListSeparator);
                        if (values.Count > 0)
                        {
                            parser.SkipSpaces();
                            if (!parser.ReadChar('}'))
                                return new Exception("Unterminated array construct.");

                            return new ArrayConstruct { Values = values };
                        }
                    }

                    // this is a precedence operator
                    if (parser.ReadChar('('))
                    {
                        var value = parser.Read<ValueBuilder, INode>();
                        if (value == null)
                            return new Exception("Syntax error.");

                        parser.SkipSpaces();
                        if (!parser.ReadChar(')'))
                            return new Exception("Unterminated precedence construct.");

                        return value;
                    }

                    // this is a number literal
                    var number = parser.ReadWhileCharOrEof(char.IsNumber);
                    if (number.Length > 0)
                        return new NumberLiteral { Data = number };

                    // this is a string literal
                    if (parser.ReadChar('"'))
                    {
                        var strBuilder = new StringBuilder();
                        while (true)
                        {
                            strBuilder.Append(parser.ReadWhileCharOrEof(ch => ch != '\\' && ch != '"'));

                            if (parser.Eof)
                                return new InvalidOperationException("String literal not terminated.");

                            if (parser.ReadChar('\\'))
                            {
                                if (parser.ReadChar('0')) strBuilder.Append('\0');
                                else if (parser.ReadChar('n')) strBuilder.Append('\n');
                                else if (parser.ReadChar('r')) strBuilder.Append('\r');
                                else if (parser.ReadChar('\\')) strBuilder.Append('\\');
                                else if (parser.ReadChar('"')) strBuilder.Append('"');
                                else
                                    return new InvalidOperationException("Escape sequence not recognized.");
                            }

                            if (parser.ReadChar('"'))
                                break;
                        }

                        return new StringLiteral { Data = strBuilder.ToString() };
                    }
                }
                else
                {
                    if (parser.ReadChar('.'))
                    {
                        var name = this.ReadName(parser);

                        // this is a direct method call in the previous element
                        var call = ReadMethodCall(parser, prevExecutor, name);
                        if (call != null)
                            return call;

                        if (!string.IsNullOrWhiteSpace(name))
                            return new PropertyGet { Name = name, Element = prevExecutor };
                    }

                    // indexer property
                    if (parser.ReadChar('['))
                    {
                        var indexValues = parser.ReadList<ValueBuilder, INode>(ReadListSeparator);

                        if (indexValues.Count == 0)
                            return new Exception("Index is missing.");

                        parser.SkipSpaces();
                        if (!parser.ReadChar(']'))
                            return new Exception("Unterminated indexer.");

                        return new IndexerGet { Element = prevExecutor, Indexes = indexValues };
                    }

                    // this only happens when calling a delegate
                    // direct method calls never fall here
                    if (parser.ReadChar('('))
                    {
                        var paramValues = parser.ReadList<ValueBuilder, INode>(ReadListSeparator);

                        parser.SkipSpaces();
                        if (parser.ReadChar(')'))
                            return new Call { Element = prevExecutor, Name = "Invoke", Parameters = paramValues };
                    }

                    if (parser.ReadChar('?'))
                    {
                        var trueValue = parser.Read<ValueBuilder, INode>();
                        parser.SkipSpaces();
                        if (!parser.ReadChar(':'))
                            throw new Exception("Missing ':' for ternary operator a?b:c.");
                        parser.SkipSpaces();
                        var falseValue = parser.Read<ValueBuilder, INode>();

                        return new TernaryInlineIf { Condition = prevExecutor, TrueValue = trueValue, FalseValue = falseValue };
                    }

                    var binOp = parser.ReadAnyStringAlternative("==", "!=", ">", "<", ">=", "<=", "&&", "||");
                    if (binOp != null)
                    {
                        var valueB = parser.Read<ValueBuilder, INode>();

                        return new BinaryBoolOps { ValueA = prevExecutor, ValueB = valueB, Operator = binOp };
                    }
                }

                return null;
            }
 private static bool ReadListSeparator(SimpleParser parser)
 {
     parser.SkipSpaces();
     return parser.ReadChar(',');
 }
            private static object ReadMethodCall(SimpleParser parser, object prevData, string name)
            {
                using (var la = parser.LookAround())
                {
                    parser.SkipSpaces();
                    if (parser.ReadChar('('))
                    {
                        var prevExecutor = (INode)prevData;
                        var type = prevData == null ? parser.GlobalType : prevExecutor.Compile(parser.GlobalType);
                        var isMethodGroup = type.GetMethods().Any(m => m.Name == name);
                        if (isMethodGroup)
                        {
                            var paramValues = parser.ReadList<ValueBuilder, INode>(ReadListSeparator);
                            if (paramValues.Count == 1 && paramValues[0] == null)
                                paramValues.Clear();

                            parser.SkipSpaces();
                            if (parser.ReadChar(')'))
                            {
                                la.Success();
                                return new Call { Element = prevExecutor, Name = name, Parameters = paramValues };
                            }
                        }
                    }

                    return null;
                }
            }
            private string ReadName(SimpleParser parser)
            {
                using (var la = parser.LookAround())
                {
                    if (!parser.ReadChar('_')
                        && !parser.ReadChar(UnicodeCategory.LowercaseLetter)
                        && !parser.ReadChar(UnicodeCategory.UppercaseLetter))
                        return null;

                    parser.ReadWhileCharOrEof(IsIdentifierChar);

                    la.Success();

                    return la.Text;
                }
            }