Esempio n. 1
0
        static void Main(string[] args)
        {
            bool argloaded = false;
            bool receiveo  = false;

            string outputfile = null;

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

            string projpath = string.Empty;

            foreach (var arg in args)
            {
                //Console.WriteLine(arg);
                if (arg.StartsWith("-load-config+=") && arg.EndsWith(".xml"))
                {
                    string configpath = arg.Substring(14);

                    projpath = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(configpath)));

                    System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(configpath);
                    //***读取源代码类路径***

                    var srcpath = document.Descendants("source-path").First().Descendants("path-element").Select((o) => o.Value).ToArray();

                    foreach (var p in srcpath)
                    {
                        if (!p.Replace('\\', '/').EndsWith("FlashDevelop/Library/AS3/classes")

                            //&&
                            //!p.Replace('\\', '/').EndsWith("/as3_commapi/api")
                            //&&
                            //!p.Replace('\\', '/').EndsWith("/as3_commapi/sharpapi")
                            //&&
                            //!p.Replace('\\', '/').EndsWith("/as3_unityapi")
                            )
                        {
                            srcpathList.Add(System.IO.Path.GetFullPath(p));
                            Console.WriteLine("Add Source Path:" + System.IO.Path.GetFullPath(p));
                        }
                    }



                    argloaded = true;
                }
                else if (arg == "-o")
                {
                    receiveo = true;
                }
                else if (receiveo)
                {
                    receiveo   = false;
                    outputfile = arg;
                }
            }


            if (!argloaded)
            {
                Console.Error.WriteLine("Configuration file not found");

                Environment.Exit(1);

                return;
            }

            string libcswc;

            if (outputfile == null)
            {
                Console.Error.WriteLine("No output file configured");
                Environment.Exit(1);

                return;
            }

            libcswc =
                projpath + "/lib/as3unitylib.cswc";

            if (!System.IO.File.Exists(libcswc))
            {
                Console.Error.WriteLine("No as3unitylib.cswc found.Execute LinkCodeGenCLI.exe to generate the API and generate 'as3unitylib.cswc' to the following locations:" + libcswc);

                Environment.Exit(1);
            }
            HashSet <string> inlibclass = new HashSet <string>();

            {
                byte[] bin     = System.IO.File.ReadAllBytes(libcswc);
                var    library = ASBinCode.CSWC.loadFromBytes(bin);
                foreach (var item in library.classes)
                {
                    if (item.instanceClass == null)
                    {
                        if (string.IsNullOrEmpty(item.package))
                        {
                            inlibclass.Add(item.name + ".as");
                        }
                        else
                        {
                            inlibclass.Add((item.package.Replace('.', '/') + "/" + item.name + ".as"));
                        }
                    }
                }
            }



            ASTool.Grammar grammar     = ASCompiler.Grammar.getGrammar();
            string[]       files       = null;
            List <string>  loadedfiles = new List <string>();
            Dictionary <string, string> srcFileProjFile = new Dictionary <string, string>();

            foreach (var path_ in srcpathList)
            {
                string path = path_;
                path = path.Replace('\\', '/');
                string[] ps = path.Split('/');

                if (System.IO.Directory.Exists(path))
                {
                    files = System.IO.Directory.GetFiles(path, "*.as", System.IO.SearchOption.AllDirectories);

                    foreach (var item in files)
                    {
                        string projfile = item.Replace("\\", "/").Replace(path.Replace("\\", "/"), "");
                        if (projfile.StartsWith("/"))
                        {
                            projfile = projfile.Substring(1);
                        }

                        if (!inlibclass.Contains(projfile))
                        {
                            loadedfiles.Add(item);
                            srcFileProjFile.Add(item, projfile);

                            Console.WriteLine("load file: " + projfile);
                        }
                    }
                }
                else
                {
                    Console.Error.WriteLine("源码路径 " + path + " 没有找到.");

                    Environment.Exit(1);
                    return;
                }
            }


            Dictionary <string, string> fileFullPath = new Dictionary <string, string>();

            foreach (var item in srcFileProjFile)
            {
                if (!fileFullPath.ContainsKey(item.Value))
                {
                    fileFullPath.Add(item.Value, item.Key);
                }
                else
                {
                    Console.Error.WriteLine(item.Key + ":" + 1 + ":Error: " + "Duplicate compilation of file with same name");
                    Environment.Exit(1);

                    return;
                }
            }


            files = loadedfiles.ToArray();

            var proj   = new ASTool.AS3.AS3Proj();
            var srcout = new ASTool.ConSrcOut();

            for (int i = 0; i < files.Length; i++)
            {
                grammar.hasError = false;
                string teststring = System.IO.File.ReadAllText(files[i]);
                if (string.IsNullOrEmpty(teststring))
                {
                    continue;
                }

                var tree = grammar.ParseTree(teststring, ASTool.AS3LexKeywords.LEXKEYWORDS,
                                             ASTool.AS3LexKeywords.LEXSKIPBLANKWORDS,
                                             srcFileProjFile[files[i]],
                                             files[i].Replace('\\', '/')

                                             );

                //System.IO.File.WriteAllText("d:\\" + System.IO.Path.GetFileName(files[i]), tree.GetTreeString());

                if (grammar.hasError)
                {
                    //Console.WriteLine(files[i]);
                    //Console.WriteLine("解析语法树失败!");

                    Environment.Exit(1);

                    return;
                }
                var analyser = new ASTool.AS3FileGrammarAnalyser(proj, srcFileProjFile[files[i]]);
                if (!analyser.Analyse(tree))                 //生成项目的语法树
                {
                    Console.WriteLine(analyser.err.ToString());
                    //Console.WriteLine("语义分析失败!");

                    Environment.Exit(1);

                    return;
                }
            }

            ASCompiler.compiler.Builder builder = new ASCompiler.compiler.Builder();

            builder.LoadLibrary(System.IO.File.ReadAllBytes(libcswc));

            builder.options.CheckNativeFunctionSignature = false;
            builder.options.isConsoleOut = false;
            builder.Build(proj, null);

            if (builder.buildErrors.Count == 0)
            {
                ASBinCode.CSWC swc = builder.getBuildOutSWC();
                byte[]         bin = swc.toBytes();

                //string as3libfile = @"F:\AS3Hotfix_Unity\AS3Hotfix_U56\Assets\StreamingAssets\hotfix.cswc";

                System.IO.File.WriteAllBytes(
                    //as3libfile
                    outputfile
                    ,
                    bin);

                Console.WriteLine("Write to File" +
                                  //as3libfile
                                  outputfile
                                  + " total" + bin.Length + "bytes");


                return;
            }
            else
            {
                foreach (var err in builder.buildErrors)
                {
                    //Console.Error.WriteLine("file :" + err.srcFile);
                    //Console.Error.WriteLine("line :" + (err.line+1) + " ptr :" + (err.ptr+1));
                    //Console.Error.WriteLine(err.errorMsg);
                    Console.Error.WriteLine(fileFullPath[err.srcFile] + ":" + (err.line + 1) + ":Error: " + err.errorMsg);
                    //input = input.Replace(vbCrLf, vbLf)
                    //input = input.Replace(vbCr, vbLf)
                    //Dim lines = input.Split(vbLf)
                    Console.Error.WriteLine();
                }



                Environment.Exit(1);

                return;
            }
        }
        static void Main(string[] args)
        {
            bool dirseted = false;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].StartsWith("config="))
                {
                    string tempconfig = args[i].Substring(7);
                    if (System.IO.File.Exists(tempconfig))
                    {
                        AppConfig.Change(System.IO.Path.GetFullPath(tempconfig));
                        System.Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(tempconfig));
                        dirseted = true;
                    }
                    else
                    {
                        Console.WriteLine("The specified config file does not exist:" + System.IO.Path.GetFullPath(tempconfig));
                        Environment.Exit(1);
                        return;
                    }
                }
            }
            if (!dirseted)
            {
                System.Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            }

            System.Configuration.AppSettingsReader appSettingsReader = new System.Configuration.AppSettingsReader();

            string outputcode               = (string)appSettingsReader.GetValue("combiedcodefile", typeof(string));
            string as3apipath               = (string)appSettingsReader.GetValue("as3apipath", typeof(string));
            string csharpcodepath           = (string)appSettingsReader.GetValue("csharpcodepath", typeof(string));
            string csharpcodenamespace      = (string)appSettingsReader.GetValue("csharpcodenamespace", typeof(string));
            string regfunctioncodenamespace = (string)appSettingsReader.GetValue("regfunctioncodenamespace", typeof(string));
            string regfunctioncode          = (string)appSettingsReader.GetValue("regfunctioncodefile", typeof(string));

            bool makemscorelib = (bool)appSettingsReader.GetValue("makemscorlib", typeof(bool));



            LinkCodeGen.Generator generator = new LinkCodeGen.Generator();

            {
                var           skipcreatortypes = (StringListSection)System.Configuration.ConfigurationManager.GetSection("skipcreatortypes");
                List <string> configs          = new List <string>();
                foreach (AssemblyElement ele in skipcreatortypes.Types)
                {
                    configs.Add(ele.StringValue);
                }
                generator.AddSkipCreateTypes(configs);
            }

            {
                var           notcreatenamespace = (StringListSection)System.Configuration.ConfigurationManager.GetSection("notcreatenamespace");
                List <string> configs            = new List <string>();
                foreach (AssemblyElement ele in notcreatenamespace.Types)
                {
                    configs.Add(ele.StringValue);
                }
                generator.AddNotCreateNameSpace(configs);


                generator.AddNotCreateNameSpace(new string[] {
                    "ASBinCode", "ASRuntime", csharpcodenamespace, regfunctioncodenamespace
                });
            }

            {
                var           notcreatetypes = (StringListSection)System.Configuration.ConfigurationManager.GetSection("notcreatetypes");
                List <string> configs        = new List <string>();
                foreach (AssemblyElement ele in notcreatetypes.Types)
                {
                    configs.Add(ele.StringValue);
                }
                generator.AddNotCreateTypes(configs);
            }
            {
                var           notcreatemembers = (StringListSection)System.Configuration.ConfigurationManager.GetSection("notcreatemembers");
                List <string> configs          = new List <string>();
                foreach (AssemblyElement ele in notcreatemembers.Types)
                {
                    configs.Add(ele.StringValue);
                }
                generator.AddNotCreateMember(configs);
            }



            string[] files = null;
            Dictionary <string, string> srcFileProjFile = new Dictionary <string, string>();

            string sdkpath = (string)appSettingsReader.GetValue("sdkpath", typeof(string));

            if (sdkpath == "auto")
            {
                sdkpath = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
                Console.WriteLine("The SDK path is set to Automatic.");
            }


            if (System.IO.Directory.Exists(sdkpath))
            {
                if (System.IO.File.Exists(sdkpath + "/air-sdk-description.xml")
                    &&
                    System.IO.Directory.Exists(sdkpath + "/as3_commapi/sharpapi/")
                    )
                {
                    string sharpapi = System.IO.Path.GetFullPath(sdkpath + "/as3_commapi/sharpapi/");

                    var linkapi = System.IO.Directory.GetFiles(sharpapi, "*.as", System.IO.SearchOption.AllDirectories);

                    foreach (var item in linkapi)
                    {
                        string projfile = item.Replace("\\", "/").Replace(sharpapi.Replace("\\", "/"), "");
                        if (projfile.StartsWith("/"))
                        {
                            projfile = projfile.Substring(1);
                        }
                        srcFileProjFile.Add(item, projfile);
                    }

                    files = new string[linkapi.Length];
                    linkapi.CopyTo(files, 0);
                }
                else
                {
                    Console.WriteLine("Invalid SDK folder");
                    Console.WriteLine("Please specify the ASRuntimeSDK path");
                    Environment.Exit(1);
                    return;
                }
            }
            else
            {
                Console.WriteLine("SDK folder not found");
                Console.WriteLine("Please specify the ASRuntimeSDK path");
                Environment.Exit(1);
                return;
            }

            SDKPATH = sdkpath;

            outputcode      = replacePathVariable(outputcode);
            as3apipath      = replacePathVariable(as3apipath);
            csharpcodepath  = replacePathVariable(csharpcodepath);
            regfunctioncode = replacePathVariable(regfunctioncode);

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

            //****加载dll***
            List <Type> types = new List <Type>();

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ReflectionOnlyAssemblyResolve;
            if (makemscorelib)
            {
                //加入基础类型
                types.AddRange(typeof(object).Assembly.GetExportedTypes());
            }
            {
                var buildassemblys = (AssemblyListSection)System.Configuration.ConfigurationManager.GetSection("buildassemblys");
                foreach (AssemblyDefineElement asm in buildassemblys.Assemblys)
                {
                    string assembly = asm.StringValue;
                    string fullpath = System.IO.Path.GetFullPath(assembly);

                    m_rootAssembly = System.IO.Path.GetDirectoryName(fullpath);

                    try
                    {
                        if (!System.IO.File.Exists(fullpath))
                        {
                            notexistdlls.Add(fullpath);
                            continue;
                        }

                        var dll = System.Reflection.Assembly.ReflectionOnlyLoadFrom(fullpath);
                        if (!dictionaryAssemblyLoadPath.ContainsKey(dll.FullName))
                        {
                            dictionaryAssemblyLoadPath.Add(dll.FullName, fullpath);
                        }
                        List <string> definetypes = new List <string>();

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

                        foreach (AssemblyTypeElement type in asm.Types)
                        {
                            if (type.DefineType == "type")
                            {
                                definetypes.Add(type.StringValue);
                            }
                            else if (type.DefineType == "namespace")
                            {
                                definenamespaces.Add(type.StringValue);
                            }
                            else
                            {
                                Console.WriteLine("Export Type Configuration Error。'definetype' can only be 'type' or 'namespace'");

                                Environment.Exit(1);
                                return;
                            }
                        }

                        foreach (var type in dll.GetExportedTypes())
                        {
                            if (definetypes.Count == 0 && definenamespaces.Count == 0
                                //||
                                //definetypes.Contains(type.FullName)
                                )
                            {
                                types.Add(type);
                            }
                            else
                            {
                                if (definetypes.Contains(type.FullName))
                                {
                                    types.Add(type);
                                }
                                else if (definenamespaces.Contains(type.Namespace))
                                {
                                    types.Add(type);
                                }
                            }
                        }
                    }
                    catch (System.IO.FileLoadException e)
                    {
                        Console.WriteLine(e.ToString());

                        Console.WriteLine(System.IO.Path.GetFileName(fullpath) + "Load failed");
                        Environment.Exit(1);
                        return;
                    }
                    catch (System.BadImageFormatException e)
                    {
                        Console.WriteLine(e.ToString());

                        Console.WriteLine("A DLL that cannot be parsed may have been loaded.Please go to Unity's installation directory find the '/Editor/Data/Managed' Directory loading UnityEngine.dll, '/Editor/Data/UnityExtensions/Unity/GUISystem/' loading UnityEngine.UI.dll。");


                        //Console.WriteLine(System.IO.Path.GetFileName(fullpath) + "读取失败");
                        Environment.Exit(1);
                    }
                    catch (System.Reflection.ReflectionTypeLoadException e)
                    {
                        Console.WriteLine(e.ToString());
                        foreach (var l in e.LoaderExceptions)
                        {
                            Console.WriteLine(l.ToString());
                        }

                        //Console.WriteLine(System.IO.Path.GetFileName(fullpath) + "读取失败");
                        Environment.Exit(1);
                        return;
                    }
                    catch (FileNotFoundException e)
                    {
                        Console.WriteLine(e.ToString());
                        //Console.WriteLine(System.IO.Path.GetFileName(fullpath) + "读取失败");
                        Environment.Exit(1);
                        return;
                    }
                    catch (System.Security.SecurityException e)
                    {
                        Console.WriteLine(e.ToString());
                        //Console.WriteLine(System.IO.Path.GetFileName(fullpath) + "读取失败");
                        Environment.Exit(1);
                        return;
                    }
                }
            }


            generator.AddTypes(types);

            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(outputcode))))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(outputcode)));
            }
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(regfunctioncode))))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(regfunctioncode)));
            }
            using (System.IO.FileStream fs = new System.IO.FileStream(outputcode, System.IO.FileMode.Create))
            {
                string regcode;
                generator.MakeCode(fs, as3apipath, csharpcodepath, csharpcodenamespace, regfunctioncodenamespace, System.IO.Path.GetDirectoryName(regfunctioncode), out regcode);
                System.IO.File.WriteAllText(regfunctioncode, regcode);
            }

            Console.WriteLine("====");

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("now compiling");



            //编译刚生成的as3api.
            {
                string apidir = as3apipath;
                if (System.IO.Directory.Exists(apidir))
                {
                    var linkapi = System.IO.Directory.GetFiles(apidir, "*.as", System.IO.SearchOption.AllDirectories);

                    foreach (var item in linkapi)
                    {
                        string projfile = item.Replace("\\", "/").Replace(apidir.Replace("\\", "/"), "");
                        if (projfile.StartsWith("/"))
                        {
                            projfile = projfile.Substring(1);
                        }
                        srcFileProjFile.Add(item, projfile);
                    }

                    string[] n = new string[files.Length + linkapi.Length];
                    linkapi.CopyTo(n, 0);
                    files.CopyTo(n, linkapi.Length);
                    files = n;
                }
            }
            //***加入其他lib****
            {
                var           includelibcode = (StringListSection)System.Configuration.ConfigurationManager.GetSection("includelibcode");
                List <string> configs        = new List <string>();
                foreach (AssemblyElement ele in includelibcode.Types)
                {
                    configs.Add(replacePathVariable(ele.StringValue));
                }
                foreach (var apidir in configs)
                {
                    if (System.IO.Directory.Exists(apidir))
                    {
                        var linkapi = System.IO.Directory.GetFiles(apidir, "*.as", System.IO.SearchOption.AllDirectories);

                        foreach (var item in linkapi)
                        {
                            string projfile = item.Replace("\\", "/").Replace(apidir.Replace("\\", "/"), "");
                            if (projfile.StartsWith("/"))
                            {
                                projfile = projfile.Substring(1);
                            }
                            srcFileProjFile.Add(item, projfile);
                        }

                        string[] n = new string[files.Length + linkapi.Length];
                        linkapi.CopyTo(n, 0);
                        files.CopyTo(n, linkapi.Length);
                        files = n;
                    }
                }
            }



            //****开始编译lib*****
            ASTool.Grammar grammar = ASCompiler.Grammar.getGrammar();
            var            proj    = new ASTool.AS3.AS3Proj();
            var            srcout  = new ASTool.ConSrcOut();

            for (int i = 0; i < files.Length; i++)
            {
                grammar.hasError = false;
                var teststring = System.IO.File.ReadAllText(files[i]);
                if (string.IsNullOrEmpty(teststring))
                {
                    continue;
                }
                var tree = grammar.ParseTree(teststring, ASTool.AS3LexKeywords.LEXKEYWORDS,
                                             ASTool.AS3LexKeywords.LEXSKIPBLANKWORDS, srcFileProjFile[files[i]]);

                if (grammar.hasError)
                {
                    Console.WriteLine(files[i]);
                    Console.WriteLine("Parse Syntax tree failed!");

                    Environment.Exit(1);
                    return;
                }

                var analyser = new ASTool.AS3FileGrammarAnalyser(proj, srcFileProjFile[files[i]]);
                if (!analyser.Analyse(tree))                 //生成项目的语法树
                {
                    Console.WriteLine(analyser.err.ToString());
                    Console.WriteLine("Semantic analysis failed!");
                    Environment.Exit(1);
                    return;
                }
            }

            ASCompiler.compiler.Builder builder = new ASCompiler.compiler.Builder();

            builder.options.CheckNativeFunctionSignature = false;
            builder.Build(proj, null);

            if (builder.buildErrors.Count == 0)
            {
                ASBinCode.CSWC swc = builder.getBuildOutSWC();
                byte[]         bin = swc.toBytes();

                string as3libfile = (string)appSettingsReader.GetValue("as3libfile", typeof(string));
                System.IO.File.WriteAllBytes(as3libfile, bin);

                //ASBinCode.CSWC.loadFromBytes(bin);

                if (notexistdlls.Count > 0)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("The following DLL file is not found, please check");

                    foreach (var item in notexistdlls)
                    {
                        Console.WriteLine("\t" + item);
                    }
                }

                Console.ResetColor();
                Console.WriteLine("The work is done. Press any key to finish。");
                Console.ReadLine();
            }
            else
            {
                Environment.Exit(1);
            }
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            ASTool.Grammar grammar = ASCompiler.Grammar.getGrammar();

            string teststring =
                @"package{
                    [Doc] //this is document class
                    class Main
                    {}
                }
                var a=1;
                var b=2;
                trace( a,'+',b,'=', a + b);
                ";


            var proj   = new ASTool.AS3.AS3Proj();
            var srcout = new ASTool.ConSrcOut();


            //build AST
            grammar.hasError = false;
            var tree = grammar.ParseTree(teststring, ASTool.AS3LexKeywords.LEXKEYWORDS,
                                         ASTool.AS3LexKeywords.LEXSKIPBLANKWORDS);

            if (grammar.hasError)
            {
                Console.WriteLine("解析语法树失败!");
                Console.ReadLine();
                return;
            }

            var analyser = new ASTool.AS3FileGrammarAnalyser(proj, "Main.cs");

            if (!analyser.Analyse(tree)) //生成项目的语法树
            {
                Console.WriteLine(analyser.err.ToString());
                Console.WriteLine("语义分析失败!");
                Console.ReadLine();
                return;
            }

            //build bytecode
            ASCompiler.compiler.Builder builder = new ASCompiler.compiler.Builder();

            builder.options.CheckNativeFunctionSignature = false;
            builder.Build(proj, null);

            if (builder.buildErrors.Count == 0)
            {
                ASBinCode.CSWC swc = builder.getBuildOutSWC();

                //save bytecode
                byte[] bin = swc.toBytes();
                swc = ASBinCode.CSWC.loadFromBytes(bin);

                if (swc.blocks.Count > 0)
                {
                    ASRuntime.Player player = new ASRuntime.Player();
                    //load bytecode
                    player.loadCode(swc);


                    Console.WriteLine();
                    Console.WriteLine("========");

                    player.run(null);
                }
                Console.ReadLine();
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            //{
            //	ASRuntime.Player player = new ASRuntime.Player();

            //	byte[] bytecode = System.IO.File.ReadAllBytes("../Debug/as3unitylib.cswc");
            //	ASBinCode.CSWC swc2 = ASBinCode.CSWC.loadFromBytes(bytecode);
            //	ASRuntime.nativefuncs.BuildInFunctionLoader.loadBuildInFunctions(swc2);
            //	(new extFunctions()).registrationFunction(swc2);

            //	player.loadCode(swc2);

            //	player.run(null);
            //	return;
            //}



            //ASCompiler.compiler.Builder bu = new ASCompiler.compiler.Builder();
            //byte[] b = bu.BuildLibBin();
            //System.IO.File.WriteAllBytes("astoolglobal.swc", b);
            ASTool.Grammar grammar = ASCompiler.Grammar.getGrammar();

            //string teststring = "package{}var a:String = \"first\";var b:String = \"First\"; var c=a==b;";
            string teststring = "package{}";//System.IO.File.ReadAllText("../../testScript/AS3Testproj/src/Main.as");

            string[] files = null;

            Dictionary <string, string> srcFileProjFile = new Dictionary <string, string>();

            if (args.Length > 0)
            {
                string path = args[0]; //path = @"F:\ASTool\ASCTest\bin\Release\tests\2_managed_array\";
                //path = @"F:\ASTool\ASCTest\testScript\AS3Testproj\src\";
                //path = @"E:\Manju-pc\as3protobuf\AS3ProtoBuf\src";
                path = @"E:\Manju-pc\as3protobuf\AS3ProtoBuf\protobuflib";
                //path = @"../..\testScript\AS3Testproj\amd";
                //path = @"../..\testScript\AS3Testproj\src";



                if (path.EndsWith(".as"))
                {
                    path = System.IO.Path.GetDirectoryName(path);
                }

                if (string.IsNullOrEmpty(path))
                {
                    path = ".\\";
                }

                //path = "";
                //files =new string[] { "E:/Manju-pc/as3protobuf/AS3ProtoBuf/src/com/netease/protobuf/Message.as" };

                path = path.Replace('\\', '/');
                string[] ps = path.Split('/');
                if (ps.Length == 2 && string.IsNullOrEmpty(ps[1]) && ps[0].IndexOf(System.IO.Path.VolumeSeparatorChar) > 0)
                {
                    Console.WriteLine("无法在根目录下搜索.请将as源代码放到一个文件夹内");
                    return;
                }
                else if (System.IO.Directory.Exists(path))
                {
                    //Console.WriteLine(path);
                    //teststring = System.IO.File.ReadAllText(args[0]);
                    files = System.IO.Directory.GetFiles(path, "*.as", System.IO.SearchOption.AllDirectories);

                    foreach (var item in files)
                    {
                        string projfile = item.Replace("\\", "/").Replace(path.Replace("\\", "/"), "");
                        if (projfile.StartsWith("/"))
                        {
                            projfile = projfile.Substring(1);
                        }
                        srcFileProjFile.Add(item, projfile);
                    }
                }
            }
            else
            {
                Console.Write("输入as文件所在路径");
                return;
            }

            if (files == null)
            {
                Console.Write("输入as文件所在路径");
                return;
            }


            //*********加入API*****
            //{
            //	string apidir = @"../../..\LinkCodeGenCLI\bin\Debug\as3api";
            //	if (System.IO.Directory.Exists(apidir))
            //	{
            //		var linkapi = System.IO.Directory.GetFiles(apidir, "*.as", System.IO.SearchOption.AllDirectories);

            //		foreach (var item in linkapi)
            //		{
            //			string projfile = item.Replace("\\", "/").Replace(apidir.Replace("\\", "/"), "");
            //			if (projfile.StartsWith("/"))
            //				projfile = projfile.Substring(1);
            //			srcFileProjFile.Add(item, projfile);
            //		}

            //		string[] n = new string[files.Length + linkapi.Length];
            //		linkapi.CopyTo(n, 0);
            //		files.CopyTo(n, linkapi.Length);
            //		files = n;
            //	}
            //}
            //{
            //	string apidir = @"..\..\..\as3_commapi\sharpapi";
            //	if (System.IO.Directory.Exists(apidir))
            //	{
            //		var linkapi = System.IO.Directory.GetFiles(apidir, "*.as", System.IO.SearchOption.AllDirectories);

            //		foreach (var item in linkapi)
            //		{
            //			string projfile = item.Replace("\\", "/").Replace(apidir.Replace("\\", "/"), "");
            //			if (projfile.StartsWith("/"))
            //				projfile = projfile.Substring(1);
            //			srcFileProjFile.Add(item, projfile);
            //		}

            //		string[] n = new string[files.Length + linkapi.Length];
            //		linkapi.CopyTo(n, 0);
            //		files.CopyTo(n, linkapi.Length);
            //		files = n;
            //	}
            //}
            //*********************

            //*********加入ProtoBuf API*****
            //string apidir = @"E:\Manju-pc\as3protobuf\AS3ProtoBuf\protobuflib";
            //if (System.IO.Directory.Exists(apidir))
            //{
            //	var linkapi = System.IO.Directory.GetFiles(apidir, "*.as", System.IO.SearchOption.AllDirectories);
            //	foreach (var item in linkapi)
            //	{
            //		string projfile = item.Replace("\\", "/").Replace(apidir.Replace("\\", "/"), "");
            //		if (projfile.StartsWith("/"))
            //			projfile = projfile.Substring(1);
            //		srcFileProjFile.Add(item, projfile);
            //	}


            //	string[] n = new string[files.Length + linkapi.Length];
            //	linkapi.CopyTo(n, 0);
            //	files.CopyTo(n, linkapi.Length);
            //	files = n;
            //}
            //*********************

            var proj   = new ASTool.AS3.AS3Proj();
            var srcout = new ASTool.ConSrcOut();

            for (int i = 0; i < files.Length; i++)
            {
                grammar.hasError = false;
                teststring       = System.IO.File.ReadAllText(files[i]);
                if (string.IsNullOrEmpty(teststring))
                {
                    continue;
                }



                var tree = grammar.ParseTree(teststring, ASTool.AS3LexKeywords.LEXKEYWORDS,
                                             ASTool.AS3LexKeywords.LEXSKIPBLANKWORDS, srcFileProjFile[files[i]]);

                //System.IO.File.WriteAllText("d:\\" + System.IO.Path.GetFileName(files[i]), tree.GetTreeString());

                if (grammar.hasError)
                {
                    Console.WriteLine(files[i]);
                    Console.WriteLine("解析语法树失败!");
                    Console.ReadLine();
                    return;
                }



                var analyser = new ASTool.AS3FileGrammarAnalyser(proj, srcFileProjFile[files[i]]);
                if (!analyser.Analyse(tree))  //生成项目的语法树
                {
                    Console.WriteLine(analyser.err.ToString());
                    Console.WriteLine("语义分析失败!");
                    Console.ReadLine();
                    return;
                }
#if DEBUG
                //Console.Clear();
#endif
            }

#if DEBUG
            Console.WriteLine();
            Console.WriteLine("====语法树翻译====");

            //runtimeCompiler rtLoader = new runtimeCompiler();
            foreach (var p in proj.SrcFiles)
            {
                p.Write(0, srcout);
            }
#endif
            //Console.Read();
            //return;
            ASCompiler.compiler.Builder builder = new ASCompiler.compiler.Builder();
            //builder.LoadLibrary( System.IO.File.ReadAllBytes("as3protobuf.swc") );

            //builder.LoadLibrary(System.IO.File.ReadAllBytes("F:/ASTool/LinkCodeGenCLI/bin/Debug/as3unitylib.cswc"));

            //builder.LoadLibrary(System.IO.File.ReadAllBytes("astoolglobal.swc"));
            //builder.Build(proj, new ASBinCode.INativeFunctionRegister[] { new extFunctions() } );

            builder.options.CheckNativeFunctionSignature = false;
            builder.Build(proj, null);

            if (builder.buildErrors.Count == 0)
            {
                ASBinCode.CSWC swc = builder.getBuildOutSWC();

                byte[] bin = swc.toBytes();



                swc = ASBinCode.CSWC.loadFromBytes(bin);
                ASRuntime.nativefuncs.BuildInFunctionLoader.loadBuildInFunctions(swc);
                (new extFunctions()).registrationAllFunction(swc);

                //System.IO.File.WriteAllBytes("astoolglobal.swc", swc.toBytes());
                System.IO.File.WriteAllBytes("as3protobuf.swc", swc.toBytes());
                //System.IO.File.WriteAllBytes("as3test.cswc", swc.toBytes());
                //System.IO.File.WriteAllBytes("as3unitylib.cswc", swc.toBytes());

                if (swc != null)
                {
#if DEBUG
                    for (int i = 0; i < swc.blocks.Count; i++)
                    {
                        var block = swc.blocks[i];
                        if (block != null && block.name.EndsWith("::Main"))                        // "CRC32::update"))
                        {
                            Console.WriteLine();
                            Console.WriteLine("====操作指令 block " + block.name + " " + block.id + "====");
                            Console.WriteLine();
                            Console.WriteLine("total registers:" + block.totalStackSlots);
                            Console.WriteLine(block.GetInstruction());
                        }
                    }
#endif

                    if (swc.blocks.Count > 0)
                    {
                        ASRuntime.Player player = new ASRuntime.Player();
                        player.loadCode(swc);

                        //byte[] bytecode = System.IO.File.ReadAllBytes("as3test.cswc");
                        //ASBinCode.CSWC swc2 = ASBinCode.CSWC.loadFromBytes(bytecode);
                        //ASRuntime.nativefuncs.BuildInFunctionLoader.loadBuildInFunctions(swc2);

                        //player.loadCode(swc2);



                        //var d = player.createInstance("SProtoSpace.group_area_info");
                        //uint len = (uint)player.getMemberValue(d, "groupids.length");
                        //player.setMemberValue(d, "groupids.length", 3);
                        //player.setMemberValue(d, "areaGroupName", null);

                        //for (int i = 0; i < 3; i++)
                        //{
                        //	player.setMemberValue(d, "groupids", i + 5, i);
                        //}

                        ////var d = player.createInstance("SProtoSpace.role_base_info");
                        //ASRuntime.flash.utils.ByteArray array;
                        //var byteArray = player.createByteArrayObject(out array);
                        ////player.setMemberValue(d, "groupName", "账号你二大爷");



                        //var r = player.invokeMethod(d, "writeTo", byteArray);
                        //var d2 = player.createInstance("SProtoSpace.group_area_info");

                        //player.setMemberValue(byteArray, "position", 0);
                        //var k = player.invokeMethod(d2, "mergeFrom", byteArray);
                        //var m = player.getMemberValue(d2, "groupids.length");

                        //var ts = player.invokeMethod(byteArray, "toString");

                        //var messageUnion = player.getMemberValue("SProtoSpace.base_msg_id", "name_check_ack_id");

                        //try
                        //{
                        //	player.setMemberValue("SProtoSpace.base_msg_id", "name_check_ack_id", 5);
                        //}
                        //catch (ASBinCode.ASRunTimeException e)
                        //{
                        //	Console.WriteLine(e.ToString());
                        //}

                        //var s = player.invokeMethod("Test", "TTT", 3, 4);

                        //***zip***
                        //ASRuntime.flash.utils.ByteArray array;
                        //var byteArray = player.createByteArrayObject(out array);

                        //var bytes = System.IO.File.ReadAllBytes(@"F:/code/Protobuf-as3-ILRuntime-master.zip");
                        //////var bytes = System.IO.File.ReadAllBytes(@"F:/3STOOGES.zip");
                        //array.writeBytes(bytes, 0, bytes.Length);
                        //array.position = 0;

                        //player.invokeMethod("Main", "showzip", byteArray);
                        ////var by = player.invokeMethod("Main", "saveZip", byteArray);
                        ////System.IO.File.WriteAllBytes("e:/kkk.zip", array.ToArray());


                        Console.WriteLine();
                        Console.WriteLine("====程序输出====");

                        player.run(null);
                    }
                    Console.WriteLine();
                }
            }

#if DEBUG
            Console.WriteLine("按任意键结束");
            Console.ReadLine();
#endif
        }
        static void Main(string[] args)
        {
            //-- 分析命令行参数
            var options = new Options();
            var parser  = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (!parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-1)))
            {
                //-- 执行导出操作
                return;
            }


            string outputcsfile = options.OutPutCSFile;            //@"../../../../HotFixProto/proto.cs";

            string outputswcfile = options.OutPutCSWC;             //@"../../../../AS3ProtoBuf_Unity/Assets/StreamingAssets/proto.cswc";

            ASTool.Grammar grammar = ASCompiler.Grammar.getGrammar();

            string teststring = "package{}";

            Dictionary <string, string> srcFiles = new Dictionary <string, string>();

            string[] protofiles = null;


            {
                string path = options.ProtoAS3;

                if (path.EndsWith(".as"))
                {
                    path = System.IO.Path.GetDirectoryName(path);
                }

                if (string.IsNullOrEmpty(path))
                {
                    path = ".\\";
                }

                string[] ps = path.Split(System.IO.Path.DirectorySeparatorChar);
                if (ps.Length == 2 && string.IsNullOrEmpty(ps[1]) && ps[0].IndexOf(System.IO.Path.VolumeSeparatorChar) > 0)
                {
                    Console.WriteLine("无法在根目录下搜索.请将as源代码放到一个文件夹内");
                    return;
                }
                else if (System.IO.Directory.Exists(path))
                {
                    //Console.WriteLine(path);
                    //teststring = System.IO.File.ReadAllText(args[0]);
                    //files = System.IO.Directory.GetFiles(path, "*.as", System.IO.SearchOption.AllDirectories);

                    AddSrcFiles(path, srcFiles);
                    protofiles = new string[srcFiles.Count];
                    srcFiles.Keys.CopyTo(protofiles, 0);                     //(string[])files.Clone();
                }
            }


            if (srcFiles.Count == 0)
            {
                Console.Write("输入as文件所在路径");
                return;
            }

            //*********加入ProtoBuf API*****
            //string apidir = @"../../../../as3protobuflib";
            //if (System.IO.Directory.Exists(apidir))
            //{
            //	AddSrcFiles(apidir, srcFiles);
            //}
            //*********************

            var proj   = new ASTool.AS3.AS3Proj();
            var srcout = new ASTool.ConSrcOut();

            foreach (var src in srcFiles)
            {
                grammar.hasError = false;
                teststring       = System.IO.File.ReadAllText(src.Key);
                if (string.IsNullOrEmpty(teststring))
                {
                    continue;
                }

                teststring = teststring.Replace("override com.netease.protobuf.used_by_generated_code final function", "override protected final function");

                var tree = grammar.ParseTree(teststring, ASTool.AS3LexKeywords.LEXKEYWORDS,
                                             ASTool.AS3LexKeywords.LEXSKIPBLANKWORDS, src.Value);

                if (grammar.hasError)
                {
                    Console.WriteLine(src.Key);
                    Console.WriteLine("解析语法树失败!");
                    Console.ReadLine();
                    return;
                }



                var analyser = new ASTool.AS3FileGrammarAnalyser(proj, src.Value);
                if (!analyser.Analyse(tree))                 //生成项目的语法树
                {
                    Console.WriteLine(analyser.err.ToString());
                    Console.WriteLine("语义分析失败!");
                    Console.ReadLine();
                    return;
                }
#if DEBUG
                //Console.Clear();
#endif
            }

#if DEBUG
            Console.WriteLine();
            Console.WriteLine("====语法树翻译====");

            //runtimeCompiler rtLoader = new runtimeCompiler();
            foreach (var p in proj.SrcFiles)
            {
                p.Write(0, srcout);
            }
#endif
            //Console.Read();
            //return;
            ASCompiler.compiler.Builder builder = new ASCompiler.compiler.Builder();
            builder.LoadLibrary(System.IO.File.ReadAllBytes("as3protobuf.swc"));
            //builder.LoadLibrary( System.IO.File.ReadAllBytes("astoolglobal.swc"));

            builder.Build(proj, null);


            if (builder.buildErrors.Count == 0)
            {
                ASBinCode.CSWC swc = builder.getBuildOutSWC();
                //System.IO.File.WriteAllBytes("astoolglobal.swc", swc.toBytes());
                //System.IO.File.WriteAllBytes("as3protobuf.swc", swc.toBytes());
                System.IO.File.WriteAllBytes(outputswcfile, swc.toBytes());

                if (swc != null)
                {
                    ASRuntime.Player player = new ASRuntime.Player();
                    player.loadCode(swc);

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine("using System;");

                    foreach (var cls in swc.classes)
                    {
                        if (cls.staticClass != null)
                        {
                            //判断是否在编译路径中
                            string fullname = cls.package + (string.IsNullOrEmpty(cls.package)?"":  ".") + cls.name + ".as";
                            foreach (var f in protofiles)
                            {
                                string ff = f.Replace("\\", ".").Replace("/", ".");
                                if (ff.EndsWith(fullname))
                                {
                                    CodeGen codeGen = new CodeGen(cls, swc, player);

                                    string cs = codeGen.GetCode();

                                    Console.Write(cs);
                                    stringBuilder.AppendLine(cs);

                                    break;
                                }
                            }
                        }
                    }

                    System.IO.File.WriteAllText(outputcsfile, stringBuilder.ToString());
                }
            }
        }