示例#1
0
        private void checkBtn_Click(object sender, RoutedEventArgs e)
        {
            GlobalScope        global = new GlobalScope();
            ANTLRStringStream  stream = new ANTLRStringStream(FileContent, m_fileName);
            KermitLexer        lexer  = new KermitLexer(stream);
            TokenRewriteStream tokens = new TokenRewriteStream(lexer);
            KermitParser       parser = new KermitParser(tokens, global);

            parser.TreeAdaptor = new KermitAdaptor();
            parser.StopOnError = false;

            List <string> errors = new List <string>();

            AstParserRuleReturnScope <KermitAST, CommonToken> ret;

            try
            {
                ret = parser.program();
            }
            catch (PartialStatement)
            {
                errors.Add("Partial statement");
            }

            if (parser.NumberOfSyntaxErrors != 0)
            {
                errors.Add($"{parser.NumberOfSyntaxErrors} syntax error(s)");
            }

            MessageBox.Show(this, string.Join("\n", errors.Concat(parser.ErrorList.Select(x => x.Message))));
        }
示例#2
0
        /// <summary>
        /// Execute the input stream
        /// </summary>
        /// <param name="input">Input stream to be executed</param>
        public void InterpretAntlrStream(ANTLRStringStream input)
        {
            KermitLexer        lexer  = new KermitLexer(input);
            TokenRewriteStream tokens = new TokenRewriteStream(lexer);

            _parser.TokenStream = tokens;

            AstParserRuleReturnScope <KermitAST, CommonToken> ret;

            try
            {
                ret = _parser.program();
                CommitableScope g = GlobalScope as CommitableScope;
                g?.CommitScope();
            }
            catch (Exception e) when(e is ParserException || e is PartialStatement)
            {
                CommitableScope g = GlobalScope as CommitableScope;

                g?.RevertScope();
                throw;
            }

            if (_parser.NumberOfSyntaxErrors == 0)
            {
                _root = ret.Tree;

                try
                {
                    Block(_root);
                    CommitableScope g = GlobalScope as CommitableScope;
                    g?.CommitScope();
                }
                catch (InterpreterException e)
                {
                    if (e.CallStack != null)
                    {
                        Listener.Error("CallStack:");
                        foreach (string call in e.CallStack)
                        {
                            Listener.Error(" - " + call);
                        }
                    }
                    Listener.Error(e);
                    Stack.Clear(); // Clear the function stack after an error
                }
            }
            else // We shouldn't reach this condition never
            {
                //throw new InterpreterException($"{_parser.NumberOfSyntaxErrors} syntax errors");
                Listener.Error($"{_parser.NumberOfSyntaxErrors} syntax errors");
            }
        }
示例#3
0
 public static void Main(string[] args)
 {
     if (args.Length > 0)
     {
         string inputFileName = args[0];
         if (!Path.IsPathRooted(inputFileName))
         {
             inputFileName = Path.Combine(Environment.CurrentDirectory, inputFileName);
         }
         ICharStream  input  = new ANTLRFileStream(inputFileName);
         TLexer       lex    = new TLexer(input);
         ITokenStream tokens = new TokenRewriteStream(lex);
         TParser      parser = new TParser(tokens);
         parser.program();
         Console.Out.WriteLine(tokens);
     }
     else
     {
         Console.Error.WriteLine("Usage: tweak <input-file>");
     }
 }
示例#4
0
        public static void Loop2()
        {
            bool         exit   = false;
            string       input  = "";
            KermitParser parser = new KermitParser(null);

            //parser.TreeAdaptor = new KermitAdaptor();
            while (!exit)
            {
                if (input == string.Empty)
                {
                    Console.Write("> ");
                }
                else
                {
                    Console.Write(".. ");
                }
                input += Console.ReadLine() + "\n";
                ANTLRStringStream  stream = new ANTLRStringStream(input);
                KermitLexer        lexer  = new KermitLexer(stream);
                TokenRewriteStream tokens = new TokenRewriteStream(lexer);
                parser.TokenStream = tokens;
                try
                {
                    AstParserRuleReturnScope <KermitAST, CommonToken> result = parser.program();
                    var tree             = (CommonTree)result.Tree;
                    DotTreeGenerator gen = new DotTreeGenerator();
                    Console.WriteLine("{0}", gen.ToDot(tree));
                    input = "";

                    //Console.WriteLine(globalScope.ToString());
                }
                catch (PartialStatement)
                {
                }
                catch (ParserException e)
                {
                }
            }
        }
示例#5
0
 public DeleteOp(int from, int to, TokenRewriteStream parent)
     : base(from, to, null, parent)
     {
     }
示例#6
0
 public ReplaceOp(int from, int to, object text, TokenRewriteStream parent)
     : base(from, text, parent)
     {
     lastIndex = to;
     }
示例#7
0
 public InsertBeforeOp(int index, object text, TokenRewriteStream parent)
     : base(index, text, parent)
     {
     }
示例#8
0
 protected internal RewriteOperation(int index, object text, TokenRewriteStream parent)
     {
     this.index = index;
     this.text = text;
     this.parent = parent;
     }
示例#9
0
文件: TParser.cs 项目: dfneto/comdd
    // throws RecognitionException [1]
    // $ANTLR start program
    // T.g:26:1: program : ( method )+ ;
    public void program()
    {
        TParser.method_return method1 = null;

            tokens = (TokenRewriteStream)input;
            IToken start = input.LT(1);

        try
        {
            // T.g:31:5: ( ( method )+ )
            // T.g:31:9: ( method )+
            {
                // T.g:31:9: ( method )+
                int cnt1 = 0;
                do
                {
                    int alt1 = 2;
                    int LA1_0 = input.LA(1);

                    if ( (LA1_0 == 7) )
                    {
                        alt1 = 1;
                    }

                    switch (alt1)
                    {
                        case 1 :
                            // T.g:31:9: method
                            {
                                PushFollow(FOLLOW_method_in_program46);
                                method1 = method();
                                state.followingStackPointer--;

                            }
                            break;

                        default:
                            if ( cnt1 >= 1 ) goto loop1;
                                EarlyExitException eee =
                                    new EarlyExitException(1, input);
                                throw eee;
                    }
                    cnt1++;
                } while (true);

                loop1:
                    ;	// Stops C# compiler whinging that label 'loop1' has no statements

                        tokens.InsertBefore(start,"public class Wrapper {\n");
                        // note the reference to the last token matched for method:
                        tokens.InsertAfter(((method1 != null) ? ((IToken)method1.stop) : null), "\n}\n");

            }

        }
        catch (RecognitionException re)
        {
            ReportError(re);
            Recover(input,re);
        }
        finally
        {
        }
        return ;
    }
示例#10
0
文件: Program.cs 项目: jbakst/xas
        static void Main(string[] args)
        {
            List <string> names       = new List <string>();
            int           _errorCount = 0;

            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

            var options            = new Options();
            ICommandLineParser clp = new CommandLineParser(new CommandLineParserSettings(true, Console.Error));

            if (!clp.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }
#if !ANTLR
#if REV4
            Parser4 p = new Parser4();
#else
            Parser3 p = new Parser3();
#endif

            p.OutputPath = options.OutputDir;
#endif
            Console.WriteLine("Initializing...");

            TemplateGroupFile loader = new TemplateGroupFile(path, null);
            loader.Load();
//            TemplateGroupString templates = loader.Compile() ;//"cpp2");//, typeof(TemplateLexer), null);
//            templates.Listener = new ErrorListener();

            if (options.Recurse)
            {
                string rootpath = options.InputFile;
                if (!rootpath.EndsWith("\\"))
                {
                    rootpath += @"\";
                }

                Console.WriteLine("Processing...");

                AS3TParser parser;

                string[] files = Directory.GetFiles(options.InputFile, "*.as", SearchOption.AllDirectories);
                foreach (string f in files)
                {
#if ANTLR
                    AS3TLexer lex = new AS3TLexer(new ANTLRFileStream(f));
                    //CommonTokenStream tokens = new CommonTokenStream(lex);
                    TokenRewriteStream tokens = new TokenRewriteStream(lex);

                    //CommonTokenStream tokens = new CommonTokenStream(lex);

                    parser = new AS3TParser(tokens);
                    parser.TemplateGroup = templates;
                    parser.OutputPath    = options.OutputDir;

                    try
                    {
                        parser.program();
                        if (options.VerboseLevel > 2)
                        {
                            Console.WriteLine("calling generateSource {0}", parser.Classname);
                        }
                        generateSource(options, tokens, parser.Classname);
                        if (options.VerboseLevel > 2)
                        {
                            Console.WriteLine("calling generateHeader {0}", parser.Classname);
                        }
                        generateHeader(options, tokens, parser.Classname, parser.Basetype, parser.SymTable);
                        parser.Reset();
                    }
                    catch (NoViableAltException e)
                    {
                        Console.WriteLine("{0} {1}", e.Line, e.Message);
                        _errorCount += 1;
                    }
                    catch (RewriteEmptyStreamException e)
                    {
                        if (options.VerboseLevel > 2)
                        {
                            Console.WriteLine(e.Message);
                        }

                        _errorCount += 1;
                    }
                    catch (ArgumentException e)
                    {
                        Console.WriteLine("{0} {1}", e.Source, e.Message);
                        _errorCount += 1;
                    }
                    catch (NullReferenceException e)
                    {
                        Console.WriteLine("{0} {1}", e.Source, e.Message);
                        _errorCount += 1;
                    }
#else
                    Console.WriteLine("{0}", f);
                    p.Parse(f);
#endif
                }

                Console.WriteLine("xas done. {0} file(s) processed, {1} Error(s)", files.Length, _errorCount);
#if DEBUG
                Console.ReadKey();
#endif
            }

            else
            {
#if ANTLR
                AS3TLexer          lex    = new AS3TLexer(new ANTLRFileStream(options.InputFile));
                TokenRewriteStream tokens = new TokenRewriteStream(lex);

                AS3TParser parser = new AS3TParser(tokens);
                parser.TemplateGroup = templates;
                parser.OutputPath    = options.OutputDir;

                //parser.TemplateGroup = templates.
                try
                {
                    parser.program();
                    generateSource(options, tokens, parser.Classname);
                    generateHeader(options, tokens, parser.Classname, parser.Basetype, parser.SymTable);
                    parser.Reset();
                }
                catch (NoViableAltException e)
                {
                    if (options.VerboseLevel > 2)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                catch (RewriteEmptyStreamException e)
                {
                    if (options.VerboseLevel > 2)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                catch (ArgumentException e)
                {
                    if (options.VerboseLevel > 2)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                catch (NullReferenceException e)
                {
                    if (options.VerboseLevel > 2)
                    {
                        Console.WriteLine(e.Message);
                    }
                }

                Console.WriteLine("xas done. {0} file(s) processed, {1} Error(s)", 1, _errorCount);

#if DEBUG
                Console.ReadKey();
#endif
#else
                p.Parse(options.InputFile);
#endif
            }
        }
示例#11
0
文件: Program.cs 项目: jbakst/xas
        private static void generateHeader(Options options, TokenRewriteStream tokens, string className, string baseName, SymbolTable symtab)
        {
            if (options.VerboseLevel > 2)
            {
                Console.WriteLine("generateHeader()");
            }
            string path = options.OutputDir + @"\";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            StreamWriter sw = new StreamWriter(path + className + ".h", false);

            sw.WriteLine("/* Autogenerated by xas on {0} */", DateTime.Now);

            sw.WriteLine("#if !defined({0})", className.ToUpper());
            sw.WriteLine("#define {0}\n", className.ToUpper());

            if (null != baseName && baseName.Length > 0)
            {
                sw.WriteLine("class {0} : public {1} {2}", className, baseName, "{");
            }
            else
            {
                sw.WriteLine("class {0} {1}", className, "{");
            }

            sw.Flush();
//            parser.gen(headerFile);

            sw.WriteLine("\n// instance variables");

            sw.WriteLine("public:\n");
            foreach (Symbol s in symtab)
            {
                switch (s.Kind)
                {
                case Symbol.VARIABLE:
                    if (s.Scope == Symbol.PUBLIC)
                    {
                        string storage = "";
                        switch (s.Storage)
                        {
                        case Symbol.STATIC:
                            storage = "static";
                            break;
                        }
                        sw.WriteLine("\t{0} {1} {2};", storage, s.ReturnType, s.Name);
                    }
                    break;

                default:
                    break;
                }
            }

            sw.WriteLine("protected:\n");
            foreach (Symbol s in symtab)
            {
                switch (s.Kind)
                {
                case Symbol.VARIABLE:
                    if (s.Scope == Symbol.PROTECTED && s.Storage != Symbol.STATIC)
                    {
                        sw.WriteLine("\t{0} {1};", s.ReturnType, s.Name);
                    }
                    break;

                default:
                    break;
                }
            }

            sw.WriteLine("private:\n");
            foreach (Symbol s in symtab)
            {
                switch (s.Kind)
                {
                case Symbol.VARIABLE:
                    if (s.Scope == Symbol.PRIVATE && s.Storage != Symbol.STATIC)
                    {
                        sw.WriteLine("\t{0} {1};", s.ReturnType, s.Name);
                    }
                    break;

                default:
                    break;
                }
            }

            sw.WriteLine("\n// methods");
            sw.WriteLine("public:\n");

            foreach (Symbol s in symtab)
            {
                switch (s.Kind)
                {
                case Symbol.FUNCTION:
                    if (s.Scope == Symbol.PUBLIC)
                    {
                        string prefix = "";
                        switch (s.Accessor)
                        {
                        case Symbol.SETTER:
                            prefix = "set_";
                            break;

                        case Symbol.GETTER:
                            prefix = "get_";
                            break;
                        }
                        if (s.Name == className)
                        {
                            sw.WriteLine("\t{0} {1}{2}{3};", s.ReturnType, prefix, s.Name, s.ArgList);
                            sw.WriteLine("\tvirtual ~{0}();\n", className);
                        }
                        else
                        {
                            sw.WriteLine("\t{0} {1}{2}{3};", s.ReturnType, prefix, s.Name, s.ArgList);
                        }
                    }
                    break;

                default:
                    break;
                }
            }

            sw.WriteLine("protected:\n");
            foreach (Symbol s in symtab)
            {
                switch (s.Kind)
                {
                case Symbol.FUNCTION:
                    if (s.Scope == Symbol.PROTECTED)
                    {
                        string prefix = "";
                        switch (s.Accessor)
                        {
                        case Symbol.SETTER:
                            prefix = "set_";
                            break;

                        case Symbol.GETTER:
                            prefix = "get_";
                            break;
                        }
                        sw.WriteLine("\t{0} {1}{2}{3};", s.ReturnType, prefix, s.Name, s.ArgList);
                    }
                    break;

                default:
                    break;
                }
            }

            sw.WriteLine("private:\n");
            foreach (Symbol s in symtab)
            {
                switch (s.Kind)
                {
                case Symbol.FUNCTION:
                    if (s.Scope == Symbol.PRIVATE)
                    {
                        string prefix = "";
                        switch (s.Accessor)
                        {
                        case Symbol.SETTER:
                            prefix = "set_";
                            break;

                        case Symbol.GETTER:
                            prefix = "get_";
                            break;
                        }
                        sw.WriteLine("\t{0} {1}{2}{3};", s.ReturnType, prefix, s.Name, s.ArgList);
                    }
                    break;

                default:
                    break;
                }
            }

            sw.WriteLine("{0}\n", "};");
            sw.WriteLine("\n#endif // {0}", className.ToUpper());

            sw.Close();
            if (options.VerboseLevel > 2)
            {
                Console.WriteLine("generateHeader()--");
            }
        }
示例#12
0
文件: Program.cs 项目: jbakst/xas
        private static void generateSource(Options options, TokenRewriteStream tokens, string className)
        {
            if (options.VerboseLevel > 2)
            {
                Console.WriteLine("generateSource()");
            }
            string path = options.OutputDir + @"\";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            StreamWriter sourceFile = new StreamWriter(path + className + ".cpp", false);


            sourceFile.WriteLine("/* Autogenerated by xas on {0} */", DateTime.Now);

            sourceFile.WriteLine("#include <cstddef>");
            sourceFile.WriteLine("#include <cstdio>");
            sourceFile.WriteLine("#include <cstdlib>");
            sourceFile.WriteLine("#include <cstring>");

            sourceFile.WriteLine("\n#include \"{0}.h\"", className);

            //Console.WriteLine(tokens.ToString("program"));

            try
            {
                sourceFile.WriteLine(tokens.ToString());
            }
            catch (NoViableAltException e)
            {
                if (options.VerboseLevel > 2)
                {
                    Console.WriteLine(e.Message);
                }
            }
            catch (InvalidCastException e)
            {
                if (options.VerboseLevel > 2)
                {
                    Console.WriteLine(e.Message);
                }
            }
            catch (ArgumentException e)
            {
                if (options.VerboseLevel > 2)
                {
                    Console.WriteLine(e.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected {0}", e.Message);
            }

            sourceFile.Close();
            if (options.VerboseLevel > 2)
            {
                Console.WriteLine("generateSource()--");
            }
        }
示例#13
0
    TokenRewriteStream tokens; // avoid typecasts all over



    // $ANTLR start program
    // T.g:26:1: program : ( method )+ ;
    public void program() // throws RecognitionException [1]
    {
        TParser.method_return method1 = null;



        tokens = (TokenRewriteStream)input;
        IToken start = input.LT(1);

        try
        {
            // T.g:31:5: ( ( method )+ )
            // T.g:31:9: ( method )+
            {
                // T.g:31:9: ( method )+
                int cnt1 = 0;
                do
                {
                    int alt1  = 2;
                    int LA1_0 = input.LA(1);

                    if ((LA1_0 == 7))
                    {
                        alt1 = 1;
                    }


                    switch (alt1)
                    {
                    case 1:
                        // T.g:31:9: method
                    {
                        PushFollow(FOLLOW_method_in_program46);
                        method1 = method();
                        state.followingStackPointer--;
                    }
                    break;

                    default:
                        if (cnt1 >= 1)
                        {
                            goto loop1;
                        }
                        EarlyExitException eee =
                            new EarlyExitException(1, input);
                        throw eee;
                    }
                    cnt1++;
                } while (true);

loop1:
                ;               // Stops C# compiler whinging that label 'loop1' has no statements


                tokens.InsertBefore(start, "public class Wrapper {\n");
                // note the reference to the last token matched for method:
                tokens.InsertAfter(((method1 != null) ? ((IToken)method1.stop) : null), "\n}\n");
            }
        }
        catch (RecognitionException re)
        {
            ReportError(re);
            Recover(input, re);
        }
        finally
        {
        }
        return;
    }