public void InputMustHaveMatchingNumberOfClosingChars()
        {
            const string     input  = "(()";
            IResult <string> result = BasicParser.EnclosedText('(', ')').TryParse(input);

            Assert.False(result.WasSuccessful);
        }
        public void SingleDepthEnclosedTextCanBeParsed()
        {
            const string input  = "(test)";
            string       result = BasicParser.EnclosedText('(', ')').Parse(input);

            Assert.Equal(input, result);
        }
        public void EmptyEnclosedTextCanBeParsed()
        {
            const string input  = "()";
            string       result = BasicParser.EnclosedText('(', ')').Parse(input);

            Assert.Equal(input, result);
        }
        public void InputMustStartWithOpenChar()
        {
            const string     input  = "fail(test)";
            IResult <string> result = BasicParser.EnclosedText('(', ')').TryParse(input);

            Assert.False(result.WasSuccessful);
        }
        public ParserProgram(string pattern)
        {
            Pattern      = pattern;
            Parser       = new FolderParser();
            RecipeParser = new RecipeParser();
            BasicParser  = new BasicParser();

            Provider = new ServiceProvider();
        }
Example #6
0
        public static void Main(string[] args)
        {
            //DateTime now = DateTime.Now;
            args = @"simulate -b 5 -n 1 -t rel -i ..\..\..\etc\$$year$$-runs.txt -j ..\..\..\etc\$$year$$-judgments.txt -e mout -p meta=..\..\..\etc\metadata.txt".Replace("$$year$$",args[0]).Split();

            if (args.Length > 0) {
                // Check CLI command name
                string commandName = args[0].ToLower();
                AbstractCommand command = null;
                switch (commandName) {
                    case "-h":
                        Allcea.PrintMainUsage(null);
                        Environment.Exit(0);
                        break;
                    case "estimate": command = new EstimateCommand(); break;
                    case "evaluate": command = new EvaluateCommand(); break;
                    case "next": command = new NextCommand(); break;
                    case "simulate": command = new SimulateCommand(); break;
                    case "features": command = new FeaturesCommand(); break;
                    default:
                        Console.Error.WriteLine("'" + commandName + "' is not a valid Allcea command. See '" + Allcea.CLI_NAME_AND_VERSION + " -h'.");
                        Environment.Exit(1);
                        break;
                }
                // Parse CLI options
                Options options = command.Options;
                // help? Cannot wait to parse CLI options because it will throw exception before
                if (options.HasOption("h") && args.Contains("-h")) {
                    Allcea.PrintUsage(null, commandName, options, command.OptionsFooter);
                } else {
                    try {
                        Parser parser = new BasicParser();
                        CommandLine cmd = parser.Parse(options, args.Skip(1).ToArray());
                        // If we have extra CLI options the Parse method doesn't throw exception. Handle here
                        if (cmd.Args == null || cmd.Args.Length != 0) {
                            throw new ParseException("Unused option(s): " + string.Join(",", cmd.Args));
                        }
                        // Run command
                        command.CheckOptions(cmd);
                        command.Run();
                    } catch (ParseException pe) {
                        Console.Error.WriteLine((pe.Message.EndsWith(".") ? pe.Message : pe.Message + ".")
                            + " See '" + Allcea.CLI_NAME_AND_VERSION + " " + commandName + " -h'.");
                        Environment.Exit(1);
                    } catch (Exception ex) {
                        Console.Error.WriteLine(ex.Message);
                        Environment.Exit(1);
                    }
                }
            } else {
                // No CLI options
                Allcea.PrintMainUsage(null);
                Environment.Exit(1);
            }
            //Console.Error.WriteLine(DateTime.Now.Subtract(now).TotalMilliseconds);
        }
Example #7
0
        public void Parse()
        {
            string      filePath    = Path.Combine(Directory.GetCurrentDirectory(), "samples/lexer2.st");
            Lexer       lexer       = new Lexer(new FileStream(filePath, FileMode.Open, FileAccess.Read));
            BasicParser basicParser = new BasicParser();

            while (lexer.Peek(0) != Token.EOF)
            {
                ASTNode astNode = basicParser.Parse(lexer);

                Console.WriteLine(astNode.ToString());
            }
        }
        public SortedDictionary <int, IStatement> Parse(Stream inputStream, TextWriter output, TextWriter error)
        {
            var input  = new AntlrInputStream(inputStream);
            var lexer  = new BasicLexer(input, output, error);
            var tokens = new CommonTokenStream(lexer);
            var parser = new BasicParser(tokens, output, error);
            var tree   = parser.program();

            var visitor = new ProgramVisitor();

            visitor.Visit(tree);

            var statements = visitor.Statements;

            return(statements);
        }
Example #9
0
        static void Main(string[] args)
        {
            var wapper = new ParamWrapper(args);
            var ins    = wapper.GetCommand("in").Select(p => p.IndexOf(":") >= 0 ? p : Path.Combine(Environment.CurrentDirectory, p)).ToList();
            var outs   = wapper.GetCommand("out").Select(p => p.IndexOf(":") >= 0 ? p : Path.Combine(Environment.CurrentDirectory, p)).ToList();

            if (ins.Count == 0)
            {
                ErrorAndExit("error: in empty");
            }
            if (outs.Count == 0)
            {
                ErrorAndExit("error: out empty");
            }

            try
            {
                var outPath = outs.First();
                BasicParser.Initialize();
                var assemblys = new List <AssemblyBuilder>();
                foreach (var @in in ins)
                {
                    Console.WriteLine("正在编译:{0}", @in);
                    using (var reader = new TokenReader(new StreamReader(File.OpenRead(@in), Encoding.UTF8)))
                    {
                        var lexer    = new Tokenizer(reader);
                        var assembly = BasicParser.Parse(lexer);
                        assembly.AddReference(typeof(Framework.Runtime.Serialization.Protobuf.IMessage).Namespace);

                        var sb = new StringBuilder();
                        assembly.BuildCode(sb);
                        var script = sb.ToString();
                        var name   = Path.GetFileNameWithoutExtension(@in);
                        var path   = Path.Combine(outPath, name + ".cs");
                        File.WriteAllText(path, script, Encoding.UTF8);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorAndExit(ex.ToString());
            }
        }
Example #10
0
        public void Counter()
        {
            string       filePath    = Path.Combine(Directory.GetCurrentDirectory(), "samples/closure.st");
            Lexer        lexer       = new Lexer(new FileStream(filePath, FileMode.Open, FileAccess.Read));
            BasicParser  basicParser = new BasicParser();
            IEnvironment environment = new Interpreter.Environment();

            while (lexer.Peek(0) != Token.EOF)
            {
                ASTNode astNode = basicParser.Parse(lexer);

                if (!(astNode is NullStatement))
                {
                    astNode.Lookup(environment.SymbolTable);

                    object result = astNode.Eval(environment);

                    Console.WriteLine(result);
                }
            }
        }
Example #11
0
 static void Translate(string filename)
 {
     try
     {
         Console.WriteLine("---=== " + filename + " ===---");
         string pyCode = "";
         using (StreamReader fileStream = new StreamReader(filename))
         {
             AntlrInputStream  inputStream       = new AntlrInputStream(fileStream);
             BasicLexer        basicLexer        = new BasicLexer(inputStream);
             CommonTokenStream commonTokenStream = new CommonTokenStream(basicLexer);
             BasicParser       basicParser       = new BasicParser(commonTokenStream);
             PyErrorListener   pyErrorListener   = new PyErrorListener();
             basicParser.AddErrorListener(pyErrorListener);
             var context = basicParser.program();
             if (pyErrorListener.ExceptionList.Count > 0)
             {
                 foreach (var msg in pyErrorListener.ExceptionList)
                 {
                     Console.WriteLine(msg);
                 }
             }
             else
             {
                 PyVisitor visitor = new PyVisitor();
                 pyCode = visitor.Visit(context);
                 File.WriteAllText(Path.ChangeExtension(filename, "py"), pyCode);
                 Console.WriteLine("Successfull translated");
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(filename + " Error: " + ex);
     }
 }
        private IEnumerable <RecipeInfo> RecipesFromFile(FileInfo f)
        {
            Log.Debug($"Parsing file: {f.Name}");

            return(BasicParser.ParseRecipes(f, File.ReadAllText(f.FullName)));
        }
        public void NestedEnclosedTextCanBeParsed(string input)
        {
            string result = BasicParser.EnclosedText('(', ')').Parse(input);

            Assert.Equal(input, result);
        }
Example #14
0
        public static void Main(string[] args)
        {
            //DateTime now = DateTime.Now;
            args = @"simulate -b 5 -n 1 -t rel -i ..\..\..\etc\$$year$$-runs.txt -j ..\..\..\etc\$$year$$-judgments.txt -e mout -p meta=..\..\..\etc\metadata.txt".Replace("$$year$$", args[0]).Split();

            if (args.Length > 0)
            {
                // Check CLI command name
                string          commandName = args[0].ToLower();
                AbstractCommand command     = null;
                switch (commandName)
                {
                case "-h":
                    Allcea.PrintMainUsage(null);
                    Environment.Exit(0);
                    break;

                case "estimate": command = new EstimateCommand(); break;

                case "evaluate": command = new EvaluateCommand(); break;

                case "next": command = new NextCommand(); break;

                case "simulate": command = new SimulateCommand(); break;

                case "features": command = new FeaturesCommand(); break;

                default:
                    Console.Error.WriteLine("'" + commandName + "' is not a valid Allcea command. See '" + Allcea.CLI_NAME_AND_VERSION + " -h'.");
                    Environment.Exit(1);
                    break;
                }
                // Parse CLI options
                Options options = command.Options;
                // help? Cannot wait to parse CLI options because it will throw exception before
                if (options.HasOption("h") && args.Contains("-h"))
                {
                    Allcea.PrintUsage(null, commandName, options, command.OptionsFooter);
                }
                else
                {
                    try {
                        Parser      parser = new BasicParser();
                        CommandLine cmd    = parser.Parse(options, args.Skip(1).ToArray());
                        // If we have extra CLI options the Parse method doesn't throw exception. Handle here
                        if (cmd.Args == null || cmd.Args.Length != 0)
                        {
                            throw new ParseException("Unused option(s): " + string.Join(",", cmd.Args));
                        }
                        // Run command
                        command.CheckOptions(cmd);
                        command.Run();
                    } catch (ParseException pe) {
                        Console.Error.WriteLine((pe.Message.EndsWith(".") ? pe.Message : pe.Message + ".")
                                                + " See '" + Allcea.CLI_NAME_AND_VERSION + " " + commandName + " -h'.");
                        Environment.Exit(1);
                    } catch (Exception ex) {
                        Console.Error.WriteLine(ex.Message);
                        Environment.Exit(1);
                    }
                }
            }
            else
            {
                // No CLI options
                Allcea.PrintMainUsage(null);
                Environment.Exit(1);
            }
            //Console.Error.WriteLine(DateTime.Now.Subtract(now).TotalMilliseconds);
        }
Example #15
0
            internal virtual Parser CreateParser()
            {
                Parser result = new BasicParser();

                return(result);
            }