Ejemplo n.º 1
0
        /// <summary>
        /// Determines whether the specified <paramref name="symbol"/> is part of any Durian module.
        /// </summary>
        /// <param name="symbol"><see cref="INamedTypeSymbol"/> to check if is part of any Durian module.</param>
        /// <param name="modules">Array of <see cref="DurianModule"/>s representing the modules the <paramref name="symbol"/> is part of.</param>
        /// <exception cref="ArgumentNullException"><paramref name="symbol"/> is <see langword="null"/>.</exception>
        public bool IsPartOfAnyModule(INamedTypeSymbol symbol, [NotNullWhen(true)] out DurianModule[]?modules)
        {
            if (symbol is null)
            {
                throw new ArgumentNullException(nameof(symbol));
            }

            if (!ValidateSymbol(symbol))
            {
                modules = null;
                return(false);
            }

            foreach (Entry e in _entries)
            {
                if (SymbolEqualityComparer.Default.Equals(e.Symbol, symbol))
                {
                    modules = ModuleConverter.ToEnums(e.Identity.Modules);
                    return(true);
                }
            }

            modules = null;
            return(false);
        }
Ejemplo n.º 2
0
        public void Build(Stream fs, Stream fspdb)
        {
            this.IsBuild = false;
            this.Error   = null;

            var log = new DefLogger();

            this.modIL = new ILModule(log);
            try
            {
                modIL.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                this.Error = err;
                return;
            }

            converterIL = new ModuleConverter(log);
            ConvOption option = new ConvOption();

            try
            {
                converterIL.Convert(modIL, option);
                finalAVM = converterIL.outModule.Build();
                IsBuild  = true;
            }
            catch (Exception err)
            {
                this.Error = err;
                log.Log("Convert IL->ASM Error:" + err.ToString());
                return;
            }
        }
Ejemplo n.º 3
0
        public async Task GetUserList()
        {
            try
            {
                string msg = "";

                UserManager     usrmngr = new UserManager();
                var             tusers  = usrmngr.GetUsers();
                ModuleConverter conv    = new ModuleConverter();
                BotGearServer   srv     = conv.IGuildToBotGearServer(Context.Guild);
                ServerManager   srvMngr = new ServerManager();
                if (tusers != null && srv != null)
                {
                    var users = await srvMngr.getServerMembersbyServerId(srv.Id);

                    if (users != null)
                    {
                        StringBuilder bld = new StringBuilder();
                        bld.AppendLine("Registered users with the bot in server : " + Context.Guild.Name);
                        foreach (var c in users)
                        {
                            bld.AppendFormat("\nId :{0}", c.Id);
                            bld.AppendFormat("\nUserName :{0}", c.Username);
                            bld.AppendFormat("\nBirthday  :{0}", c.Birthday);
                            bld.AppendFormat("\nCreated at :{0}", c.CreatedAt);
                            bld.AppendFormat("\nRegisted at: :{0}", c.RegisteredAt);
                            bld.AppendFormat("\nDiscriminator :{0}", c.Discriminator);
                            bld.AppendFormat("\nDiscriminator Value :{0}", c.DiscriminatorValue);

                            bld.AppendLine();
                        }
                        msg = bld.ToString();
                    }
                }
                else
                {
                    StringBuilder bld = new StringBuilder();
                    bld.AppendLine("Registered users with the bot in server : " + Context.Guild.Name);
                    bld.AppendLine("There are no users  ");
                    msg = bld.ToString();
                }


                var channel = await Context.User.GetOrCreateDMChannelAsync();

                if (channel != null)
                {
                    await channel.SendMessageAsync(msg);
                }


                //await ReplyAsync(msg);
            }
            catch (Exception ex)
            {
                CommonTools.ErrorReporting(ex);
            }
        }
Ejemplo n.º 4
0
        public void Build(Stream fs, Stream fspdb, bool optimizer)
        {
            this.IsBuild = false;
            this.Error   = null;

            var log = new DefLogger();

            this.modIL = new ILModule(log);
            try
            {
                modIL.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                this.Error = err;
                return;
            }

            converterIL = new ModuleConverter(log);
            ConvOption option = new ConvOption();

#if NDEBUG
            try
#endif
            {
                converterIL.Convert(modIL, option);
                finalNEF = converterIL.outModule.Build();
                if (optimizer)
                {
                    var   opbytes = NefOptimizeTool.Optimize(finalNEF);
                    float ratio   = (opbytes.Length * 100.0f) / (float)finalNEF.Length;
                    log.Log("optimization ratio = " + ratio + "%");
                    finalNEF = opbytes;
                }
                IsBuild = true;
            }
#if NDEBUG
            catch (Exception err)
            {
                this.Error = err;
                log.Log("Convert IL->ASM Error:" + err.ToString());
                return;
            }
#endif
            try
            {
                finialABI = vmtool.FuncExport.Export(converterIL.outModule, finalNEF);
            }
            catch
            {
            }
        }
Ejemplo n.º 5
0
        public static byte[] Convert(System.IO.Stream dllstream, Neo.Compiler.ILogger logger = null)
        {
            var module = new ILModule();

            module.LoadModule(dllstream, null);
            if (logger == null)
            {
                logger = new DefLogger();
            }
            var converter = new ModuleConverter(logger);
            //有异常的话在 convert 函数中会直接throw 出来
            var antmodule = converter.Convert(module);

            return(antmodule.Build());
        }
Ejemplo n.º 6
0
        public async Task <IHttpActionResult> GetModule(Guid id)
        {
            if (!(await Db.CertificateModules.FindAsync(id) is CertificateModule module))
            {
                return(NotFound());
            }

            // unvollständige Modulbeschreibungen werden gelten als nicht gefunden
            if (module.Subjects.Any(x => x.ContentModules.Any(y => y.TeachingBuildingBlock == null)))
            {
                return(NotFound());
            }

            var converter = new ModuleConverter(Db);
            var dto       = converter.ConvertCertificateModule(id);

            return(Ok(dto));
        }
Ejemplo n.º 7
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            //set console
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.JVM console app v" + Assembly.GetEntryAssembly().GetName().Version);
            if (args.Length == 0)
            {
                log.Log("need one param for .class filename.");
                return;
            }
            string filename = args[0];
            string onlyname = System.IO.Path.GetFileNameWithoutExtension(filename);
            //javaloader.ClassFile classFile = null;
            JavaModule module = new JavaModule();


            byte[] bytes = null;
            bool   bSucc = false;

            //convert and build
            try
            {
                var path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                path = System.IO.Path.GetDirectoryName(path);
                module.LoadJar(System.IO.Path.Combine(path, "org.neo.smartcontract.framework.jar"));
                module.LoadClass(filename);
                var conv = new ModuleConverter(log);

                AntsModule am = conv.Convert(module);
                bytes = am.Build();
                log.Log("convert succ");
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                System.IO.File.Delete(bytesname);
                System.IO.File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }


            if (bSucc)
            {
                log.Log("SUCC");
            }
        }
Ejemplo n.º 8
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            //set console
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL console app v" + Assembly.GetEntryAssembly().GetName().Version);

            if (args.Length == 0)
            {
                log.Log("need one param for DLL filename.");
                log.Log("Example:neon abc.dll");
                return;
            }

            string filename = args[0];
            string onlyname = Path.GetFileNameWithoutExtension(filename);
            string filepdb  = onlyname + ".pdb";
            var    path     = Path.GetDirectoryName(filename);

            if (!string.IsNullOrEmpty(path))
            {
                try
                {
                    Directory.SetCurrentDirectory(path);
                }
                catch
                {
                    log.Log("Could not find path: " + path);
                    Environment.Exit(-1);
                    return;
                }
            }

            ILModule mod = new ILModule(log);
            Stream   fs;
            Stream   fspdb = null;

            //open file
            try
            {
                fs = File.OpenRead(filename);

                if (File.Exists(filepdb))
                {
                    fspdb = File.OpenRead(filepdb);
                }
            }
            catch (Exception err)
            {
                log.Log("Open File Error:" + err.ToString());
                return;
            }
            //load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return;
            }
            byte[] bytes;
            bool   bSucc;
            string jsonstr = null;

            //convert and build
            try
            {
                var        conv   = new ModuleConverter(log);
                ConvOption option = new ConvOption();
                NeoModule  am     = conv.Convert(mod, option);
                bytes = am.Build();
                log.Log("convert succ");

                try
                {
                    var           outjson = vmtool.FuncExport.Export(am, bytes);
                    StringBuilder sb      = new StringBuilder();
                    outjson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                File.Delete(bytesname);
                File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }
            try
            {
                string abiname = onlyname + ".abi.json";

                File.Delete(abiname);
                File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return;
            }
            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }

            if (bSucc)
            {
                log.Log("SUCC");
            }
        }
Ejemplo n.º 9
0
        public static int Compile(Options options, ILogger log = null)
        {
            // Set console
            Console.OutputEncoding = Encoding.UTF8;
            log ??= new DefLogger();
            log.Log("Neo.Compiler.MSIL console app v" + Assembly.GetAssembly(typeof(Program)).GetName().Version);

            var fileInfo = new FileInfo(options.File);

            // Set current directory
            if (!fileInfo.Exists)
            {
                log.Log("Could not find file " + fileInfo.FullName);
                return(-1);
            }

            Stream fs;
            Stream fspdb;
            var    onlyname = Path.GetFileNameWithoutExtension(fileInfo.Name);
            var    path     = fileInfo.Directory.FullName;

            if (!string.IsNullOrEmpty(path))
            {
                try
                {
                    Directory.SetCurrentDirectory(path);
                }
                catch
                {
                    log.Log("Could not find path: " + path);
                    return(-1);
                }
            }

            switch (fileInfo.Extension.ToLowerInvariant())
            {
            case ".csproj":
            {
                // Compile csproj file

                log.Log("Compiling from csproj project");
                var output = Compiler.CompileCSProj(fileInfo.FullName);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".vbproj":
            {
                // Compile vbproj file

                log.Log("Compiling from vbproj project");
                var output = Compiler.CompileVBProj(fileInfo.FullName);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".cs":
            {
                // Compile C# files

                log.Log("Compiling from c# source");
                var output = Compiler.CompileCSFiles(new string[] { fileInfo.FullName }, new string[0]);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".vb":
            {
                // Compile VB files

                log.Log("Compiling from VB source");
                var output = Compiler.CompileVBFiles(new string[] { fileInfo.FullName }, new string[0]);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".dll":
            {
                string filepdb = onlyname + ".pdb";

                // Open file
                try
                {
                    fs = fileInfo.OpenRead();

                    if (File.Exists(filepdb))
                    {
                        fspdb = File.OpenRead(filepdb);
                    }
                    else
                    {
                        fspdb = null;
                    }
                }
                catch (Exception err)
                {
                    log.Log("Open File Error:" + err.ToString());
                    return(-1);
                }
                break;
            }

            default:
            {
                log.Log("File format not supported by neon: " + path);
                return(-1);
            }
            }

            ILModule mod = new ILModule(log);

            // Load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return(-1);
            }
            JObject abi;

            byte[]    bytes;
            int       bSucc    = 0;
            string    debugstr = null;
            NeoModule module;

            // Convert and build
            try
            {
                var        conv   = new ModuleConverter(log);
                ConvOption option = new ConvOption();
                module = conv.Convert(mod, option);
                bytes  = module.Build();
                log.Log("convert succ");
                Dictionary <int, int> addrConvTable = null;
                if (options.Optimize)
                {
                    HashSet <int> entryPoints = new HashSet <int>();
                    foreach (var func in module.mapMethods)
                    {
                        entryPoints.Add(func.Value.funcaddr);
                    }
                    var optimize = NefOptimizeTool.Optimize(bytes, entryPoints.ToArray(), out addrConvTable);
                    log.Log("optimization succ " + (((bytes.Length / (optimize.Length + 0.0)) * 100.0) - 100).ToString("0.00 '%'"));
                    bytes = optimize;
                }

                try
                {
                    abi = FuncExport.Export(module, bytes, addrConvTable);
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                    return(-1);
                }

                try
                {
                    var outjson = DebugExport.Export(module, bytes, addrConvTable);
                    debugstr = outjson.ToString(false);
                    log.Log("gen debug succ");
                }
                catch (Exception err)
                {
                    log.Log("gen debug Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return(-1);
            }

            // Write bytes

            try
            {
                string bytesname = onlyname + ".nef";
                var    nef       = new NefFile
                {
                    Compiler = "neon",
                    Version  = Version.Parse(((AssemblyFileVersionAttribute)Assembly.GetAssembly(typeof(Program))
                                              .GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version),
                    Script     = bytes,
                    ScriptHash = bytes.ToScriptHash()
                };
                nef.CheckSum = NefFile.ComputeChecksum(nef);

                File.Delete(bytesname);
                using (var stream = File.OpenWrite(bytesname))
                    using (var writer = new BinaryWriter(stream))
                    {
                        nef.Serialize(writer);
                    }
                log.Log("write:" + bytesname);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return(-1);
            }

            try
            {
                var    sbABI   = abi.ToString(false);
                string abiname = onlyname + ".abi.json";

                File.Delete(abiname);
                File.WriteAllText(abiname, sbABI.ToString());
                log.Log("write:" + abiname);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return(-1);
            }

            try
            {
                string debugname = onlyname + ".debug.json";
                string debugzip  = onlyname + ".nefdbgnfo";

                var tempName = Path.GetTempFileName();
                File.Delete(tempName);
                File.WriteAllText(tempName, debugstr);
                File.Delete(debugzip);
                using (var archive = ZipFile.Open(debugzip, ZipArchiveMode.Create))
                {
                    archive.CreateEntryFromFile(tempName, Path.GetFileName(debugname));
                }
                File.Delete(tempName);
                log.Log("write:" + debugzip);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write debug Error:" + err.ToString());
                return(-1);
            }

            try
            {
                string manifest    = onlyname + ".manifest.json";
                var    defManifest = FuncExport.GenerateManifest(abi, module);

                File.Delete(manifest);
                File.WriteAllText(manifest, defManifest);
                log.Log("write:" + manifest);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write manifest Error:" + err.ToString());
                return(-1);
            }

            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }

            if (bSucc == 4)
            {
                log.Log("SUCC");
                return(0);
            }

            return(-1);
        }
Ejemplo n.º 10
0
        public void Build(Stream fs, Stream fspdb, bool optimizer)
        {
            this.IsBuild      = false;
            this.Error        = null;
            this.UseOptimizer = optimizer;

            var log = new DefLogger();

            this.modIL = new ILModule(log);
            try
            {
                modIL.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                this.Error = err;
                return;
            }

            converterIL = new ModuleConverter(log);
            Dictionary <int, int> addrConvTable = null;
            ConvOption            option        = new ConvOption();

#if NDEBUG
            try
#endif
            {
                converterIL.Convert(modIL, option);
                finalNEFScript = converterIL.outModule.Build();
                if (optimizer)
                {
                    List <int> entryPoints = new List <int>();
                    foreach (var f in converterIL.outModule.mapMethods.Values)
                    {
                        if (!entryPoints.Contains(f.funcaddr))
                        {
                            entryPoints.Add(f.funcaddr);
                        }
                    }
                    var   opbytes = NefOptimizeTool.Optimize(finalNEFScript, entryPoints.ToArray(), out addrConvTable);
                    float ratio   = (opbytes.Length * 100.0f) / (float)finalNEFScript.Length;
                    log.Log("optimization ratio = " + ratio + "%");
                    finalNEFScript = opbytes;
                }
                IsBuild = true;
            }
#if NDEBUG
            catch (Exception err)
            {
                this.Error = err;
                log.Log("Convert IL->ASM Error:" + err.ToString());
                return;
            }
#endif
            try
            {
                finalABI = FuncExport.GenerateAbi(converterIL.outModule, addrConvTable);
            }
            catch (Exception err)
            {
                log.Log("Gen Abi Error:" + err.ToString());
                this.Error = err;
                return;
            }

            try
            {
                debugInfo = DebugExport.Export(converterIL.outModule, finalNEFScript, addrConvTable);
            }
            catch (Exception err)
            {
                log.Log("Gen debugInfo Error:" + err.ToString());
                this.Error = err;
                return;
            }

            try
            {
                finalManifest = FuncExport.GenerateManifest(finalABI, converterIL.outModule);
            }
            catch (Exception err)
            {
                log.Log("Gen Manifest Error:" + err.ToString());
                this.Error = err;
                return;
            }

            try
            {
                nefFile = new NefFile
                {
                    Compiler = "neon-" + Version.Parse(((AssemblyFileVersionAttribute)Assembly.GetAssembly(typeof(Program))
                                                        .GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version).ToString(),
                    Tokens = converterIL.methodTokens.ToArray(),
                    Script = finalNEFScript
                };
                nefFile.CheckSum = NefFile.ComputeChecksum(nefFile);
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }
        }
Ejemplo n.º 11
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            string outpath = "C:\\NeoCli\\SmartContracts";

            //set console
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL<Debug> console app v" + Assembly.GetEntryAssembly().GetName().Version);

            bool bCompatible = true;
            //bool bCompatible = false;
            string filename = null;

            for (var i = 0; i < args.Length; i++)
            {
                if (args[i][0] == '-')
                {
                    if (args[i] == "--uncompatible")
                    {
                        bCompatible = false;
                    }

                    //other option
                }
                else
                {
                    filename = args[i];
                }
            }

            if (filename == null)
            {
                log.Log("NEL Forked");
                log.Log("need one param for DLL filename.");
                log.Log("[--uncompatible] able nep8 function");
                log.Log("Example:neon abc.dll --uncompatible");
                return;
            }
            if (bCompatible)
            {
                log.Log("use --uncompatible able nep8");
            }
            string onlyname = System.IO.Path.GetFileNameWithoutExtension(filename);
            string filepdb  = onlyname + ".pdb";
            var    path     = Path.GetDirectoryName(filename);

            if (!string.IsNullOrEmpty(path))
            {
                try
                {
                    Directory.SetCurrentDirectory(path);
                }
                catch
                {
                    log.Log("Could not find path: " + path);
                    Environment.Exit(-1);
                }
            }

            ILModule mod = new ILModule();

            System.IO.Stream fs    = null;
            System.IO.Stream fspdb = null;

            //open file
            try
            {
                fs = System.IO.File.OpenRead(filename);

                if (System.IO.File.Exists(filepdb))
                {
                    fspdb = System.IO.File.OpenRead(filepdb);
                }
            }
            catch (Exception err)
            {
                log.Log("Open File Error:" + err.ToString());
                return;
            }
            //load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return;
            }
            byte[]    bytes   = null;
            bool      bSucc   = false;
            string    jsonstr = null;
            NeoModule neoM    = null;

            MyJson.JsonNode_Object abijson = null;
            //convert and build
            try
            {
                var        conv   = new ModuleConverter(log);
                ConvOption option = new ConvOption();
                option.useNep8 = !bCompatible;
                NeoModule am = conv.Convert(mod, option);
                neoM  = am;
                bytes = am.Build();
                log.Log("convert succ");


                try
                {
                    abijson = vmtool.FuncExport.Export(am, bytes);
                    StringBuilder sb = new StringBuilder();
                    abijson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                System.IO.File.Delete(bytesname);
                System.IO.File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }
            try
            {
                string abiname = onlyname + ".abi.json";

                System.IO.File.Delete(abiname);
                System.IO.File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return;
            }
            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }

            if (bSucc)
            {
                _DebugOutput.DebugOutput(outpath, neoM, bytes, abijson);
                log.Log("SUCC");
            }
        }
Ejemplo n.º 12
0
        public static int Compile(Options options)
        {
            // Set console
            Console.OutputEncoding = Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL console app v" + Assembly.GetEntryAssembly().GetName().Version);

            var fileInfo = new FileInfo(options.File);

            // Set current directory
            if (!fileInfo.Exists)
            {
                log.Log("Could not find file " + fileInfo.FullName);
                return(-1);
            }

            Stream fs;
            Stream fspdb;
            var    onlyname = Path.GetFileNameWithoutExtension(fileInfo.Name);
            var    path     = fileInfo.Directory.FullName;

            if (!string.IsNullOrEmpty(path))
            {
                try
                {
                    Directory.SetCurrentDirectory(path);
                }
                catch
                {
                    log.Log("Could not find path: " + path);
                    return(-1);
                }
            }

            switch (fileInfo.Extension.ToLowerInvariant())
            {
            case ".csproj":
            {
                // Compile csproj file

                log.Log("Compiling from csproj project");
                var output = Compiler.CompileCSProj(fileInfo.FullName);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".vbproj":
            {
                // Compile vbproj file

                log.Log("Compiling from vbproj project");
                var output = Compiler.CompileVBProj(fileInfo.FullName);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".cs":
            {
                // Compile C# files

                log.Log("Compiling from c# source");
                var output = Compiler.CompileCSFiles(new string[] { fileInfo.FullName }, new string[0]);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".vb":
            {
                // Compile VB files

                log.Log("Compiling from VB source");
                var output = Compiler.CompileVBFiles(new string[] { fileInfo.FullName }, new string[0]);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".dll":
            {
                string filepdb = onlyname + ".pdb";

                // Open file
                try
                {
                    fs = fileInfo.OpenRead();

                    if (File.Exists(filepdb))
                    {
                        fspdb = File.OpenRead(filepdb);
                    }
                    else
                    {
                        fspdb = null;
                    }
                }
                catch (Exception err)
                {
                    log.Log("Open File Error:" + err.ToString());
                    return(-1);
                }
                break;
            }

            default:
            {
                log.Log("File format not supported by neon: " + path);
                return(-1);
            }
            }

            ILModule mod = new ILModule(log);

            // Load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return(-1);
            }
            byte[]    bytes;
            int       bSucc   = 0;
            string    jsonstr = null;
            NeoModule module  = null;

            // Convert and build
            try
            {
                var        conv   = new ModuleConverter(log);
                ConvOption option = new ConvOption();
                module = conv.Convert(mod, option);
                bytes  = module.Build();
                log.Log("convert succ");
                Dictionary <int, int> addrConvTable = null;
                if (options.Optimize)
                {
                    module.ConvertFuncAddr();
                    List <int> entryPoints = new List <int>();

                    foreach (var func in module.mapMethods)
                    {
                        int srcaddr = func.Value.funcaddr;
                        if (entryPoints.Contains(srcaddr) == false)
                        {
                            entryPoints.Add(srcaddr);
                        }
                    }
                    var optimize = NefOptimizeTool.Optimize(bytes, entryPoints.ToArray(), out addrConvTable);
                    log.Log("optimization succ " + (((bytes.Length / (optimize.Length + 0.0)) * 100.0) - 100).ToString("0.00 '%'"));
                    bytes = optimize;
                }

                try
                {
                    var           outjson = vmtool.FuncExport.Export(module, bytes, addrConvTable);
                    StringBuilder sb      = new StringBuilder();
                    outjson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                    return(-1);
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return(-1);
            }

            // Write bytes

            try
            {
                string bytesname = onlyname + ".nef";
                var    nef       = new NefFile
                {
                    Compiler = "neon",
                    Version  = Version.Parse(((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly()
                                              .GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version),
                    Script     = bytes,
                    ScriptHash = bytes.ToScriptHash()
                };
                nef.CheckSum = NefFile.ComputeChecksum(nef);

                File.Delete(bytesname);
                using (var stream = File.OpenWrite(bytesname))
                    using (var writer = new BinaryWriter(stream))
                    {
                        nef.Serialize(writer);
                    }
                log.Log("write:" + bytesname);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return(-1);
            }

            try
            {
                string abiname = onlyname + ".abi.json";

                File.Delete(abiname);
                File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return(-1);
            }

            try
            {
                var features = module == null ? ContractFeatures.NoProperty : module.attributes
                               .Where(u => u.AttributeType.Name == "FeaturesAttribute")
                               .Select(u => (ContractFeatures)u.ConstructorArguments.FirstOrDefault().Value)
                               .FirstOrDefault();

                var extraAttributes = module == null ? new List <Mono.Collections.Generic.Collection <CustomAttributeArgument> >() : module.attributes.Where(u => u.AttributeType.Name == "ManifestExtraAttribute").Select(attribute => attribute.ConstructorArguments).ToList();

                var extra   = BuildExtraAttributes(extraAttributes);
                var storage = features.HasFlag(ContractFeatures.HasStorage).ToString().ToLowerInvariant();
                var payable = features.HasFlag(ContractFeatures.Payable).ToString().ToLowerInvariant();

                string manifest    = onlyname + ".manifest.json";
                string defManifest =
                    @"{""groups"":[],""features"":{""storage"":" + storage + @",""payable"":" + payable + @"},""abi"":" +
                    jsonstr +
                    @",""permissions"":[{""contract"":""*"",""methods"":""*""}],""trusts"":[],""safeMethods"":[],""extra"":" + extra + "}";

                File.Delete(manifest);
                File.WriteAllText(manifest, defManifest);
                log.Log("write:" + manifest);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write manifest Error:" + err.ToString());
                return(-1);
            }

            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }

            if (bSucc == 3)
            {
                log.Log("SUCC");
                return(0);
            }

            return(-1);
        }
Ejemplo n.º 13
0
        public void Build(Stream fs, Stream fspdb, bool optimizer)
        {
            this.IsBuild      = false;
            this.Error        = null;
            this.UseOptimizer = optimizer;

            var log = new DefLogger();

            this.modIL = new ILModule(log);
            try
            {
                modIL.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                this.Error = err;
                return;
            }

            converterIL = new ModuleConverter(log);
            Dictionary <int, int> addrConvTable = null;
            ConvOption            option        = new ConvOption();

#if NDEBUG
            try
#endif
            {
                converterIL.Convert(modIL, option);
                finalNEFScript = converterIL.outModule.Build();
                if (optimizer)
                {
                    List <int> entryPoints = new List <int>();
                    foreach (var f in converterIL.outModule.mapMethods.Values)
                    {
                        if (!entryPoints.Contains(f.funcaddr))
                        {
                            entryPoints.Add(f.funcaddr);
                        }
                    }
                    var   opbytes = NefOptimizeTool.Optimize(finalNEFScript, entryPoints.ToArray(), out addrConvTable);
                    float ratio   = (opbytes.Length * 100.0f) / (float)finalNEFScript.Length;
                    log.Log("optimization ratio = " + ratio + "%");
                    finalNEFScript = opbytes;
                }
                IsBuild = true;
            }
#if NDEBUG
            catch (Exception err)
            {
                this.Error = err;
                log.Log("Convert IL->ASM Error:" + err.ToString());
                return;
            }
#endif
            try
            {
                finalABI = FuncExport.GenerateAbi(converterIL.outModule, addrConvTable);
            }
            catch (Exception err)
            {
                log.Log("Gen Abi Error:" + err.ToString());
                this.Error = err;
                return;
            }

            try
            {
                debugInfo = DebugExport.Export(converterIL.outModule, finalNEFScript, addrConvTable);
            }
            catch (Exception err)
            {
                log.Log("Gen debugInfo Error:" + err.ToString());
                this.Error = err;
                return;
            }

            try
            {
                finalManifest = FuncExport.GenerateManifest(finalABI, converterIL.outModule);
            }
            catch (Exception err)
            {
                log.Log("Gen Manifest Error:" + err.ToString());
                this.Error = err;
                return;
            }
        }
Ejemplo n.º 14
0
        public bool compile(string filename, string filetext, out byte[] avmtext, out string abitext, out string maptext, out string hash)
        {
            var tree = CSharpSyntaxTree.ParseText(filetext);
            var comp = CSharpCompilation.Create("aaa.dll", new[] { tree },
                                                new[] { ref1, ref2, ref3, ref4 }, op);

            var fs     = new MemoryStream();
            var fspdb  = new MemoryStream();
            var result = comp.Emit(fs, fspdb);

            fs.Seek(0, SeekOrigin.Begin);
            fspdb.Seek(0, SeekOrigin.Begin);

            ILModule mod = new ILModule();

            mod.LoadModule(fs, fspdb);

            NeoModule am = null;

            byte[] bytes   = null;
            string jsonstr = null;
            string mapInfo = null;

            ConvOption option = new ConvOption()
            {
                useNep8 = false
            };
            var conv = new ModuleConverter(new DefLogger());

            am = conv.Convert(mod, option);
            // *.avm
            bytes   = am.Build();
            avmtext = bytes;

            // *.abi.json
            var outjson = vmtool.FuncExport.Export(am, bytes);

            jsonstr = outjson.ToString();
            abitext = jsonstr;
            hash    = outjson["hash"].ToString();

            // *.map.json
            Neo.Compiler.MyJson.JsonNode_Array arr = new Neo.Compiler.MyJson.JsonNode_Array();
            foreach (var m in am.mapMethods)
            {
                Neo.Compiler.MyJson.JsonNode_Object item = new Neo.Compiler.MyJson.JsonNode_Object();
                arr.Add(item);
                item.SetDictValue("name", m.Value.displayName);
                item.SetDictValue("addr", m.Value.funcaddr.ToString("X04"));
                Neo.Compiler.MyJson.JsonNode_Array infos = new Neo.Compiler.MyJson.JsonNode_Array();
                item.SetDictValue("map", infos);
                foreach (var c in m.Value.body_Codes)
                {
                    if (c.Value.debugcode != null)
                    {
                        var debugcode = c.Value.debugcode.ToLower();
                        //if (debugcode.Contains(".cs"))
                        {
                            infos.AddArrayValue(c.Value.addr.ToString("X04") + "-" + c.Value.debugline.ToString());
                        }
                    }
                }
            }
            mapInfo = arr.ToString();
            maptext = mapInfo;

            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }
            return(true);
        }
Ejemplo n.º 15
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            // Set console
            Console.OutputEncoding = Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL console app v" + Assembly.GetEntryAssembly().GetName().Version);

            // Check argmuents
            if (args.Length == 0)
            {
                log.Log("You need a parameter to specify the DLL or the file name of the project.");
                log.Log("Examples: ");
                log.Log("  neon mySmartContract.dll");
                log.Log("  neon mySmartContract.csproj");

                Environment.Exit(-1);
                return;
            }

            var fileInfo = new FileInfo(args[0]);

            // Set current directory
            if (!fileInfo.Exists)
            {
                log.Log("Could not find file " + fileInfo.FullName);
                Environment.Exit(-1);
                return;
            }

            Stream fs;
            Stream fspdb;
            var    onlyname = Path.GetFileNameWithoutExtension(fileInfo.Name);
            var    path     = fileInfo.Directory.FullName;

            if (!string.IsNullOrEmpty(path))
            {
                try
                {
                    Directory.SetCurrentDirectory(path);
                }
                catch
                {
                    log.Log("Could not find path: " + path);
                    Environment.Exit(-1);
                    return;
                }
            }

            switch (fileInfo.Extension.ToLowerInvariant())
            {
            case ".csproj":
            {
                // Compile csproj file

                log.Log("Compiling from csproj project");
                var output = Compiler.CompileCSProj(fileInfo.FullName);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".vbproj":
            {
                // Compile vbproj file

                log.Log("Compiling from vbproj project");
                var output = Compiler.CompileVBProj(fileInfo.FullName);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".cs":
            {
                // Compile C# files

                log.Log("Compiling from c# source");
                var output = Compiler.CompileCSFile(new string[] { fileInfo.FullName }, new string[0]);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".vb":
            {
                // Compile VB files

                log.Log("Compiling from VB source");
                var output = Compiler.CompileVBFile(new string[] { fileInfo.FullName }, new string[0]);
                fs    = new MemoryStream(output.Dll);
                fspdb = new MemoryStream(output.Pdb);
                break;
            }

            case ".dll":
            {
                string filepdb = onlyname + ".pdb";

                // Open file
                try
                {
                    fs = fileInfo.OpenRead();

                    if (File.Exists(filepdb))
                    {
                        fspdb = File.OpenRead(filepdb);
                    }
                    else
                    {
                        fspdb = null;
                    }
                }
                catch (Exception err)
                {
                    log.Log("Open File Error:" + err.ToString());
                    return;
                }
                break;
            }

            default:
            {
                log.Log("File format not supported by neon: " + path);
                Environment.Exit(-1);
                return;
            }
            }

            ILModule mod = new ILModule(log);

            // Load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return;
            }
            byte[]    bytes;
            int       bSucc   = 0;
            string    jsonstr = null;
            NeoModule module  = null;

            // Convert and build
            try
            {
                var        conv   = new ModuleConverter(log);
                ConvOption option = new ConvOption();
                module = conv.Convert(mod, option);
                bytes  = module.Build();
                log.Log("convert succ");

                try
                {
                    var           outjson = vmtool.FuncExport.Export(module, bytes);
                    StringBuilder sb      = new StringBuilder();
                    outjson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }

            // Write bytes

            try
            {
                string bytesname = onlyname + ".nef";
                var    nef       = new NefFile
                {
                    Compiler = "neon",
                    Version  = Version.Parse(((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly()
                                              .GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version),
                    Script     = bytes,
                    ScriptHash = bytes.ToScriptHash()
                };
                nef.CheckSum = NefFile.ComputeChecksum(nef);

                File.Delete(bytesname);
                using (var stream = File.OpenWrite(bytesname))
                    using (var writer = new BinaryWriter(stream))
                    {
                        nef.Serialize(writer);
                    }
                log.Log("write:" + bytesname);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }

            try
            {
                string abiname = onlyname + ".abi.json";

                File.Delete(abiname);
                File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return;
            }

            try
            {
                var features = module == null ? ContractFeatures.NoProperty : module.attributes
                               .Where(u => u.AttributeType.Name == "FeaturesAttribute")
                               .Select(u => (ContractFeatures)u.ConstructorArguments.FirstOrDefault().Value)
                               .FirstOrDefault();

                var storage = features.HasFlag(ContractFeatures.HasStorage).ToString().ToLowerInvariant();
                var payable = features.HasFlag(ContractFeatures.Payable).ToString().ToLowerInvariant();

                string manifest    = onlyname + ".manifest.json";
                string defManifest =
                    @"{""groups"":[],""features"":{""storage"":" + storage + @",""payable"":" + payable + @"},""abi"":" +
                    jsonstr +
                    @",""permissions"":[{""contract"":""*"",""methods"":""*""}],""trusts"":[],""safeMethods"":[]}";

                File.Delete(manifest);
                File.WriteAllText(manifest, defManifest);
                log.Log("write:" + manifest);
                bSucc++;
            }
            catch (Exception err)
            {
                log.Log("Write manifest Error:" + err.ToString());
                return;
            }

            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }

            if (bSucc == 3)
            {
                log.Log("SUCC");
            }
        }
Ejemplo n.º 16
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            //set console
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL(Debug) console app v" + Assembly.GetEntryAssembly().GetName().Version);
            if (args.Length == 0)
            {
                log.Log("need one param for DLL filename.");
                return;
            }
            string filename = args[0];
            string onlyname = System.IO.Path.GetFileNameWithoutExtension(filename);
            string filepdb  = onlyname + ".pdb";

            ILModule mod = new ILModule();

            System.IO.Stream fs    = null;
            System.IO.Stream fspdb = null;

            //open file
            try
            {
                fs = System.IO.File.OpenRead(filename);

                if (System.IO.File.Exists(filepdb))
                {
                    fspdb = System.IO.File.OpenRead(filepdb);
                }
            }
            catch (Exception err)
            {
                log.Log("Open File Error:" + err.ToString());
                return;
            }
            //load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return;
            }
            byte[] bytes   = null;
            bool   bSucc   = false;
            string jsonstr = null;
            //convert and build
            NeoModule neoM = null;

            MyJson.JsonNode_Object abijson = null;
            try
            {
                var conv = new ModuleConverter(log);

                NeoModule am = conv.Convert(mod);
                neoM  = am;
                bytes = am.Build();
                log.Log("convert succ");


                try
                {
                    abijson = vmtool.FuncExport.Export(am, bytes);
                    StringBuilder sb = new StringBuilder();
                    abijson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                System.IO.File.Delete(bytesname);
                System.IO.File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }
            try
            {
                string abiname = onlyname + ".abi.json";

                System.IO.File.Delete(abiname);
                System.IO.File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return;
            }
            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }
            if (bSucc)
            {
                _DebugOutput.DebugOutput(neoM, bytes, abijson);
                log.Log("SUCC");
            }
        }
Ejemplo n.º 17
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            //set console
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL console app v" + Assembly.GetEntryAssembly().GetName().Version + " [DEBUGGER SUPPORT]");
            if (args.Length == 0)
            {
                log.Log("need one param for DLL filename.");
                return;
            }
            string filename = args[0];
            string onlyname = System.IO.Path.GetFileNameWithoutExtension(filename);
            string filepdb  = filename.Replace(".dll", ".pdb");

            // fix necessary when debugging the compiler via VS
            var path = Path.GetDirectoryName(filename);

            if (!string.IsNullOrEmpty(path))
            {
                Directory.SetCurrentDirectory(path);
            }

            ILModule mod = new ILModule();

            System.IO.Stream fs    = null;
            System.IO.Stream fspdb = null;

            //open file
            try
            {
                fs = System.IO.File.OpenRead(filename);

                if (System.IO.File.Exists(filepdb))
                {
                    fspdb = System.IO.File.OpenRead(filepdb);
                }
            }
            catch (Exception err)
            {
                log.Log("Open File Error:" + err.ToString());
                return;
            }
            //load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return;
            }
            byte[] bytes = null;
            bool   bSucc = false;

            //convert and build
            try
            {
                var conv = new ModuleConverter(log);

                AntsModule am = conv.Convert(mod);
                bytes = am.Build(filename);
                log.Log("convert succ");
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                System.IO.File.Delete(bytesname);
                System.IO.File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }
            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }

            if (bSucc)
            {
                log.Log("SUCC");
            }
        }
Ejemplo n.º 18
0
        public void Build(Stream fs, Stream fspdb, bool optimizer)
        {
            this.IsBuild      = false;
            this.Error        = null;
            this.UseOptimizer = optimizer;

            var log = new DefLogger();

            this.modIL = new ILModule(log);
            try
            {
                modIL.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                this.Error = err;
                return;
            }

            converterIL = new ModuleConverter(log);
            Dictionary <int, int> addrConvTable = null;
            ConvOption            option        = new ConvOption();

#if NDEBUG
            try
#endif
            {
                converterIL.Convert(modIL, option);
                finalNEF = converterIL.outModule.Build();
                if (optimizer)
                {
                    var   opbytes = NefOptimizeTool.Optimize(finalNEF, out addrConvTable);
                    float ratio   = (opbytes.Length * 100.0f) / (float)finalNEF.Length;
                    log.Log("optimization ratio = " + ratio + "%");
                    finalNEF = opbytes;
                }
                IsBuild = true;
            }
#if NDEBUG
            catch (Exception err)
            {
                this.Error = err;
                log.Log("Convert IL->ASM Error:" + err.ToString());
                return;
            }
#endif
            try
            {
                finialABI = vmtool.FuncExport.Export(converterIL.outModule, finalNEF, addrConvTable);
            }
            catch (Exception e)
            {
                throw e;
            }

            try
            {
                var features = converterIL.outModule == null ? ContractFeatures.NoProperty : converterIL.outModule.attributes
                               .Where(u => u.AttributeType.Name == "FeaturesAttribute")
                               .Select(u => (ContractFeatures)u.ConstructorArguments.FirstOrDefault().Value)
                               .FirstOrDefault();

                var extraAttributes = converterIL.outModule == null ? new List <Mono.Collections.Generic.Collection <CustomAttributeArgument> >()
                    : converterIL.outModule.attributes.Where(u => u.AttributeType.Name == "ManifestExtraAttribute").Select(attribute => attribute.ConstructorArguments).ToList();
                var storage = features.HasFlag(ContractFeatures.HasStorage).ToString().ToLowerInvariant();
                var payable = features.HasFlag(ContractFeatures.Payable).ToString().ToLowerInvariant();

                finalManifest =
                    @"{""groups"":[],""features"":{""storage"":" + storage + @",""payable"":" + payable + @"},""abi"":" +
                    finialABI +
                    @",""permissions"":[{""contract"":""*"",""methods"":""*""}],""trusts"":[],""safeMethods"":[],""extra"":[]" + "}";
            }
            catch
            {
            }
        }
Ejemplo n.º 19
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static bool Execute(string filename, string filepdb, ILogger log)
        {
            string onlyname = System.IO.Path.GetFileNameWithoutExtension(filename);

            ILModule mod = new ILModule(log);

            System.IO.Stream fs    = null;
            System.IO.Stream fspdb = null;

            //open file
            try
            {
                fs = System.IO.File.OpenRead(filename);

                if (System.IO.File.Exists(filepdb))
                {
                    fspdb = System.IO.File.OpenRead(filepdb);
                }
            }
            catch (Exception err)
            {
                log.Log("Open File Error:" + err.ToString());
                return(false);
            }

            var exePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            var curPath = Directory.GetCurrentDirectory();

            Directory.SetCurrentDirectory(exePath);

            //load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return(false);
            }
            byte[] bytes       = null;
            bool   bSucc       = false;
            string jsonstr     = null;
            string debugmapstr = null;

            //convert and build
            try
            {
                var        conv   = new ModuleConverter(log);
                ConvOption option = new ConvOption();
                option.useNep8 = false;
                option.useSysCallInteropHash = false;
                NeoModule am = conv.Convert(mod, option);

                Directory.SetCurrentDirectory(curPath);

                bytes = am.Build();
                log.Log("convert succ");


                try
                {
                    var           outjson = FuncExport.Export(am, bytes);
                    StringBuilder sb      = new StringBuilder();
                    outjson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                }

                try
                {
                    var           outjson = DebugInfo.ExportDebugInfo(onlyname, am);
                    StringBuilder sb      = new StringBuilder();
                    outjson.ConvertToStringWithFormat(sb, 0);
                    debugmapstr = sb.ToString();
                    log.Log("gen debug map succ");
                }
                catch (Exception err)
                {
                    log.Log("gen debug map Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return(false);
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                System.IO.File.Delete(bytesname);
                System.IO.File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return(false);
            }
            try
            {
                string abiname = onlyname + ".abi.json";

                System.IO.File.Delete(abiname);
                System.IO.File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return(false);
            }
            try
            {
                string debugname = onlyname + ".debug.json";

                System.IO.File.Delete(debugname);
                System.IO.File.WriteAllText(debugname, debugmapstr);
                log.Log("write:" + debugname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return(false);
            }
            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }

            return(bSucc);
        }
Ejemplo n.º 20
0
        //Console.WriteLine("helo ha:"+args[0]); //普通输出
        //Console.WriteLine("<WARN> 这是一个严重的问题。");//警告输出,黄字
        //Console.WriteLine("<WARN|aaaa.cs(1)> 这是ee一个严重的问题。");//警告输出,带文件名行号
        //Console.WriteLine("<ERR> 这是一个严重的问题。");//错误输出,红字
        //Console.WriteLine("<ERR|aaaa.cs> 这是ee一个严重的问题。");//错误输出,带文件名
        //Console.WriteLine("SUCC");//输出这个表示编译成功
        //控制台输出约定了特别的语法
        public static void Main(string[] args)
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText("class A{public  int aaa(){return 3;}}");

            var op   = new CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary);
            var ref1 = MetadataReference.CreateFromFile("needlib\\mscorlib.dll");
            var comp = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("aaa.dll", new[] { tree },
                                                                              new[] { ref1 }, op);

            var fs     = new System.IO.MemoryStream();
            var fspdb  = new System.IO.MemoryStream();
            var result = comp.Emit(fs, fspdb);

            fs.Seek(0, System.IO.SeekOrigin.Begin);
            fspdb.Seek(0, System.IO.SeekOrigin.Begin);
            //set console
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var log = new DefLogger();

            log.Log("Neo.Compiler.MSIL(Debug) console app v" + Assembly.GetEntryAssembly().GetName().Version);
            if (args.Length == 0)
            {
                log.Log("need one param for DLL filename.");
                return;
            }
            string filename = args[0];
            string onlyname = System.IO.Path.GetFileNameWithoutExtension(filename);
            //string filepdb = onlyname + ".pdb";

            ILModule mod = new ILModule();

            //System.IO.Stream fs = null;
            //System.IO.Stream fspdb = null;

            //open file
            //try
            //{
            //    fs = System.IO.File.OpenRead(filename);

            //    if (System.IO.File.Exists(filepdb))
            //    {
            //        fspdb = System.IO.File.OpenRead(filepdb);
            //    }

            //}
            //catch (Exception err)
            //{
            //    log.Log("Open File Error:" + err.ToString());
            //    return;
            //}
            //load module
            try
            {
                mod.LoadModule(fs, fspdb);
            }
            catch (Exception err)
            {
                log.Log("LoadModule Error:" + err.ToString());
                return;
            }
            byte[] bytes   = null;
            bool   bSucc   = false;
            string jsonstr = null;
            //convert and build
            NeoModule neoM = null;

            MyJson.JsonNode_Object abijson = null;
            try
            {
                var conv = new ModuleConverter(log);

                NeoModule am = conv.Convert(mod);
                neoM  = am;
                bytes = am.Build();
                log.Log("convert succ");


                try
                {
                    abijson = vmtool.FuncExport.Export(am, bytes);
                    StringBuilder sb = new StringBuilder();
                    abijson.ConvertToStringWithFormat(sb, 0);
                    jsonstr = sb.ToString();
                    log.Log("gen abi succ");
                }
                catch (Exception err)
                {
                    log.Log("gen abi Error:" + err.ToString());
                }
            }
            catch (Exception err)
            {
                log.Log("Convert Error:" + err.ToString());
                return;
            }
            //write bytes
            try
            {
                string bytesname = onlyname + ".avm";

                System.IO.File.Delete(bytesname);
                System.IO.File.WriteAllBytes(bytesname, bytes);
                log.Log("write:" + bytesname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write Bytes Error:" + err.ToString());
                return;
            }
            try
            {
                string abiname = onlyname + ".abi.json";

                System.IO.File.Delete(abiname);
                System.IO.File.WriteAllText(abiname, jsonstr);
                log.Log("write:" + abiname);
                bSucc = true;
            }
            catch (Exception err)
            {
                log.Log("Write abi Error:" + err.ToString());
                return;
            }
            try
            {
                fs.Dispose();
                if (fspdb != null)
                {
                    fspdb.Dispose();
                }
            }
            catch
            {
            }
            if (bSucc)
            {
                _DebugOutput.DebugOutput(neoM, bytes, abijson);
                log.Log("SUCC");
            }
        }