示例#1
0
        static string CreateAssembly(string name, string code, bool exe = false)
        {
            // Never return or hold the Assembly instance. This will cause
            // the assembly to be loaded into the current domain and this
            // interferes with the tests. The Domain can execute fine from a
            // path, so let's return that.
            CSharpCodeProvider provider   = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateExecutable = exe;
            var assemblyName     = name;
            var assemblyFullPath = Path.Combine(TestPath, assemblyName);

            parameters.OutputAssembly = assemblyFullPath;
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            var netstandard = "netstandard.dll";

            if (Type.GetType("Mono.Runtime") != null)
            {
                netstandard = "Facades/" + netstandard;
            }
            parameters.ReferencedAssemblies.Add(netstandard);
            parameters.ReferencedAssemblies.Add(PythonDllLocation);
            // Write code to file so it can debugged.
            var sourcePath = Path.Combine(TestPath, name + "_source.cs");

            using (var file = new StreamWriter(sourcePath))
            {
                file.Write(code);
            }
            CompilerResults results = provider.CompileAssemblyFromFile(parameters, sourcePath);

            if (results.NativeCompilerReturnValue != 0)
            {
                var stderr = System.Console.Error;
                stderr.WriteLine($"Error in {name} compiling:\n{code}");
                foreach (var error in results.Errors)
                {
                    stderr.WriteLine(error);
                }
                throw new ArgumentException("Error compiling code");
            }

            return(assemblyFullPath);
        }
示例#2
0
        protected override CompilerResults DoCompile()
        {
            var files =
                from doc in Documents
                where doc is CSDocument
                select doc.LocalPath;

            var assemblyLocation = GetFreshAssemblyLocation();
            var assemblyBaseDir  = Path.GetDirectoryName(assemblyLocation);

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

            var compilerParams = new CompilerParameters();

            compilerParams.WarningLevel            = 4;
            compilerParams.OutputAssembly          = assemblyLocation;
            compilerParams.GenerateExecutable      = false;
            compilerParams.GenerateInMemory        = false;
            compilerParams.IncludeDebugInformation = true;
            compilerParams.CompilerOptions        += "/unsafe ";

            switch (BuildConfiguration)
            {
            case BuildConfiguration.Release:
                compilerParams.CompilerOptions += "/optimize ";
                break;

            case BuildConfiguration.Debug:
                break;
            }

            foreach (var reference in References)
            {
                var location = reference.AssemblyLocation;
                if (Path.GetExtension(location) != ".dll")
                {
                    location = string.Format("{0}.dll", location);
                }

                compilerParams.ReferencedAssemblies.Add(location);
            }

            return(FProvider.CompileAssemblyFromFile(compilerParams, files.ToArray()));
        }
示例#3
0
        private IReflectionOptimizer Build(string code)
        {
            CodeDomProvider provider = new CSharpCodeProvider();
            CompilerResults res;

            if (FluorineConfiguration.Instance.OptimizerSettings.Debug)
            {
                string       file = Path.Combine(Path.GetTempPath(), _mappedClass.FullName.Replace('.', '_').Replace("+", "__")) + ".cs";
                StreamWriter sw   = File.CreateText(file);
                sw.Write(code);
                sw.Close();
                log.Debug(__Res.GetString(__Res.Optimizer_FileLocation, _mappedClass.FullName, file));

                _cp.TempFiles           = new TempFileCollection(Path.GetTempPath());
                _cp.TempFiles.KeepFiles = true;

#if !(NET_1_1)
                res = provider.CompileAssemblyFromFile(_cp, file);
#else
                ICodeCompiler compiler = provider.CreateCompiler();
                res = compiler.CompileAssemblyFromFile(_cp, file);
#endif
            }
            else
            {
#if !(NET_1_1)
                res = provider.CompileAssemblyFromSource(_cp, new string[] { code });
#else
                ICodeCompiler compiler = provider.CreateCompiler();
                res = compiler.CompileAssemblyFromSource(_cp, code);
#endif
            }

            if (res.Errors.HasErrors)
            {
                foreach (CompilerError e in res.Errors)
                {
                    log.Error(__Res.GetString(__Res.Compiler_Error, e.Line, e.Column, e.ErrorText));
                }
                throw new InvalidOperationException(res.Errors[0].ErrorText);
            }

            Assembly             assembly  = res.CompiledAssembly;
            System.Type[]        types     = assembly.GetTypes();
            IReflectionOptimizer optimizer = (IReflectionOptimizer)assembly.CreateInstance(types[0].FullName, false, BindingFlags.CreateInstance, null, null, null, null);
            return(optimizer);
        }
示例#4
0
        public void CompileArchive(string archiveFilename, bool run1stItem, string iconFilename)
        {
            CodeDomProvider    csc = new CSharpCodeProvider();
            CompilerParameters cp  = new CompilerParameters();

            cp.GenerateExecutable = true;
            cp.OutputAssembly     = archiveFilename;
            cp.CompilerOptions    = "/target:winexe";

            // Custom option to run a file after extraction
            if (run1stItem)
            {
                cp.CompilerOptions += " /define:RUN_1ST_ITEM";
            }
            if (!string.IsNullOrEmpty(iconFilename))
            {
                cp.CompilerOptions += " /win32icon:" + iconFilename;
            }
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Core.dll");
            cp.ReferencedAssemblies.Add("System.Xml.Linq.dll");
            cp.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
            cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            cp.ReferencedAssemblies.Add("System.Data.dll");
            cp.ReferencedAssemblies.Add("System.Deployment.dll");
            cp.ReferencedAssemblies.Add("System.Drawing.dll");
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cp.ReferencedAssemblies.Add("System.Xml.dll");

            // Add compressed files as resource
            cp.EmbeddedResources.AddRange(filenames.ToArray());

            // Compile standalone executable with input files embedded as resource
            CompilerResults cr = csc.CompileAssemblyFromFile(cp, sourceNames.ToArray());

            // yell if compilation error
            if (cr.Errors.Count > 0)
            {
                string msg = "Errors building " + cr.PathToAssembly;

                foreach (CompilerError ce in cr.Errors)
                {
                    msg += Environment.NewLine + ce.ToString();
                }
                throw new ApplicationException(msg);
            }
        }
示例#5
0
        string CompileTest(string testName)
        {
            string code = GetResource(testName);

            string md5 = ToHexadecimal(new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(code)));

            string path = Path.GetTempPath();

            path = Path.Combine(path, "SharpDevelop");
            path = Path.Combine(path, "DebuggerTestsX86");
            path = Path.Combine(path, testName + "." + md5);
            Directory.CreateDirectory(path);

            string codeFilename = Path.Combine(path, testName);
            string exeFilename  = Path.Combine(path, testName.Replace(".cs", ".exe"));

            if (File.Exists(exeFilename))
            {
                return(exeFilename);
            }

            StreamWriter file = new StreamWriter(codeFilename);

            file.Write(code);
            file.Close();

            CompilerParameters compParams = new CompilerParameters();

            compParams.GenerateExecutable      = true;
            compParams.GenerateInMemory        = false;
            compParams.TreatWarningsAsErrors   = false;
            compParams.IncludeDebugInformation = true;
            compParams.ReferencedAssemblies.Add("System.dll");
            compParams.OutputAssembly  = exeFilename;
            compParams.CompilerOptions = "/unsafe /platform:x86";
            compParams.ReferencedAssemblies.Add(typeof(TestFixtureAttribute).Assembly.Location);

            CSharpCodeProvider compiler = new CSharpCodeProvider();
            CompilerResults    result   = compiler.CompileAssemblyFromFile(compParams, codeFilename);

            if (result.Errors.Count > 0)
            {
                throw new System.Exception("There was an error(s) during compilation of test program:\n" + result.Errors[0].ToString());
            }

            return(exeFilename);
        }
示例#6
0
        private static Assembly CompileAssemblyFromFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new CustomScriptExecutionException(CustomScriptExecutionException.Reason.ScriptFileNotFound);
            }

            CodeDomProvider provider = new CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateInMemory = true;
            parameters.CompilerOptions  = "/optimize";

            parameters.ReferencedAssemblies.Add("mscorlib.dll");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("System.Xml.dll");
            parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");

            // Reference the AlarmWorkflow.Shared.dll as well.
            parameters.ReferencedAssemblies.Add(typeof(ExtendedObjectExpressionFormatter <>).Assembly.Location);
            // Also reference the assembly which contains the object to be formatted.
            parameters.ReferencedAssemblies.Add(typeof(TInput).Assembly.Location);

            Stopwatch       sw      = Stopwatch.StartNew();
            CompilerResults results = provider.CompileAssemblyFromFile(parameters, path);

            sw.Stop();
            Logger.Instance.LogFormat(LogType.Info, null, Properties.Resources.CustomScriptCompilationFinished, sw.ElapsedMilliseconds);

            if (results.Errors.Count > 0)
            {
                Logger.Instance.LogFormat(LogType.Warning, null, Properties.Resources.CustomScriptCompilationWithErrorsWarnings, results.Errors.Count, path);
                foreach (CompilerError item in results.Errors)
                {
                    Logger.Instance.LogFormat(LogType.Warning, null, "{0}", item);
                }

                if (results.Errors.HasErrors)
                {
                    throw new CustomScriptExecutionException(CustomScriptExecutionException.Reason.CompilationFailed);
                }
            }

            return(results.CompiledAssembly);
        }
示例#7
0
        /// <summary>
        /// 从文件编译
        /// </summary>
        /// <param name="files">要编译的代码文件集合</param>
        /// <param name="referenceAssemblyNames">引用程序集名称集合</param>
        /// <param name="outputAssembly">输出dll名称</param>
        /// <returns>返回异常信息</returns>
        public static string CompileFromFile(string[] files, string[] referenceAssemblyNames, string outputAssembly)
        {
            CSharpCodeProvider codeProvider       = new CSharpCodeProvider();
            CompilerParameters compilerParameters = new CompilerParameters(referenceAssemblyNames, outputAssembly);
            CompilerResults    complierResult     = codeProvider.CompileAssemblyFromFile(compilerParameters, files);

            if (complierResult.Errors.HasErrors)
            {
                StringBuilder message = new StringBuilder();
                foreach (CompilerError err in complierResult.Errors)
                {
                    message.AppendFormat("(FileName:{0},ErrLine:{1}): error {2}: {3}", err.FileName, err.Line, err.ErrorNumber, err.ErrorText);
                }
                return(message.ToString());
            }
            return(string.Empty);
        }
示例#8
0
        public static Boolean CompileSourceFiles(ruleSet[] rulesets, List <string> allSourceFiles,
                                                 out CompilerResults cr, string rulesDir, string execDir, string compiledparamRules)
        {
            cr = null;
            try
            {
                CSharpCodeProvider c = new CSharpCodeProvider();
                // c.CreateCompiler();
//                ICodeCompiler icc = c.CreateCompiler();
                CompilerParameters cp = new CompilerParameters();

                cp.ReferencedAssemblies.Add("system.dll");
                cp.ReferencedAssemblies.Add("system.xml.dll");
                cp.ReferencedAssemblies.Add("system.data.dll");
                cp.ReferencedAssemblies.Add("system.windows.forms.dll");
                cp.ReferencedAssemblies.Add(execDir + "GraphSynth.exe");
                cp.ReferencedAssemblies.Add(execDir + "Representation.dll");

                cp.CompilerOptions  = "/t:library";
                cp.GenerateInMemory = true;
                cp.OutputAssembly   = rulesDir + compiledparamRules;
                string[] allSourceFilesArray = allSourceFiles.ToArray();

                cr = c.CompileAssemblyFromFile(cp, allSourceFilesArray);

                //cr = icc.CompileAssemblyFromFileBatch(cp, allSourceFilesArray);
                if (cr.Errors.Count > 0)
                {
                    throw new Exception();
                }
                else
                {
                    return(true);
                }
            }
            catch
            {
                MessageBox.Show("Error Compiling C# recognize and apply source files.",
                                "Compilation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                foreach (CompilerError e in cr.Errors)
                {
                    SearchIO.output(e.ToString(), 1);
                }
                return(false);
            }
        }
示例#9
0
        public CompilerResults Compile(string filePath)
        {
            var parameters = new CompilerParameters
            {
                GenerateInMemory      = true,
                TreatWarningsAsErrors = false,
                GenerateExecutable    = true,
                CompilerOptions       = "/optimize"
            };

            var codeProvider    = new CSharpCodeProvider();
            var compilerResults = codeProvider.CompileAssemblyFromFile(parameters, new[] { filePath });

            compilerResults.PathToAssembly = @"C:\";

            return(compilerResults);
        }
示例#10
0
        public CompilationResult Compile(BuildFiles buildFiles)
        {
            using (var codeDomProvider = new CSharpCodeProvider())
            {
                var fileNames  = buildFiles.AllClasses.Select(c => c.FullPath).ToArray();
                var references = buildFiles.References
                                 .Select(reference => reference.FullPath)
                                 .ToArray();

                var options = new CompilerParameters();
                options.ReferencedAssemblies.AddRange(references);
                var result = codeDomProvider.CompileAssemblyFromFile(options, fileNames);

                var errors = result.Errors.Cast <CompilerError>().Select(error => error.ErrorText);
                return(new CompilationResult(errors, result.PathToAssembly));
            }
        }
        public CompilerResults Compile(CompilerParameters parameters, bool isFilePath, string Script)
        {
            bool            complete = false;
            bool            retried  = false;
            CompilerResults results;

            do
            {
                lock (YPcodeProvider)
                {
                    if (isFilePath)
                    {
                        results = YPcodeProvider.CompileAssemblyFromFile(
                            parameters, Script);
                    }
                    else
                    {
                        results = YPcodeProvider.CompileAssemblyFromSource(
                            parameters, Script);
                    }
                }
                // Deal with an occasional segv in the compiler.
                // Rarely, if ever, occurs twice in succession.
                // Line # == 0 and no file name are indications that
                // this is a native stack trace rather than a normal
                // error log.
                if (results.Errors.Count > 0)
                {
                    if (!retried && (results.Errors[0].FileName == null || results.Errors[0].FileName == String.Empty) &&
                        results.Errors[0].Line == 0)
                    {
                        // System.Console.WriteLine("retrying failed compilation");
                        retried = true;
                    }
                    else
                    {
                        complete = true;
                    }
                }
                else
                {
                    complete = true;
                }
            } while (!complete);
            return(results);
        }
示例#12
0
        public Assembly Generate(IAssemblySource assemblySource, CompilerParameters compilerParameters)
        {
            var stopwatch = Stopwatch.StartNew();

            compilerParameters.ReferencedAssemblies.AddRange(assemblySource.RegisteredReferences.ToArray());
            if (compilerParameters.WarningLevel == -1)
            {
                compilerParameters.WarningLevel = 4;
            }

            string          sourceFile = null;
            CompilerResults results;

            if (compilerParameters.GenerateInMemory)
            {
                using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
                    results = codeProvider.CompileAssemblyFromSource(compilerParameters, assemblySource.GeneratedCode);
            }
            else
            {
                sourceFile = Path.GetFullPath(Path.ChangeExtension(compilerParameters.OutputAssembly, ".cs"));
                File.WriteAllText(sourceFile, assemblySource.GeneratedCode, Encoding.UTF8);
                using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
                    results = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFile);
            }

            _performanceLogger.Write(stopwatch, "CSharpCodeProvider.CompileAssemblyFromSource");

            if (results.Errors.HasErrors)
            {
                throw new FrameworkException(ReportErrors(results, assemblySource.GeneratedCode, sourceFile));
            }

            try
            {
                results.CompiledAssembly.GetTypes();
            }
            catch (ReflectionTypeLoadException ex)
            {
                throw new FrameworkException(CsUtility.ReportTypeLoadException(ex, "Error while compiling " + compilerParameters.OutputAssembly + "."), ex);
            }

            ReportWarnings(results, sourceFile);

            return(results.CompiledAssembly);
        }
示例#13
0
        /// <summary>
        /// Compiles a C# script as a string or from a file. If "LoadAssemblies" is true, this call will try
        /// to manually load each assembly so that it is truly available on execution.
        /// </summary>
        public static Assembly Compile(string codeOrFile, bool isCodeOrFile, IEnumerable <string> referencedAssemblies, List <string> outputErrors, bool loadAssemblies)
        {
            try
            {
                if (loadAssemblies)
                {
                    foreach (var ra in referencedAssemblies)
                    {
                        try
                        {
                            Assembly.UnsafeLoadFrom(ra);
                        }
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
                        catch (Exception)
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
                        {
                        }
                    }
                }

                var csc = new CSharpCodeProvider(new Dictionary <string, string> {
                    { "CompilerVersion", "v4.0" }
                });
                var parameters = new CompilerParameters(referencedAssemblies.ToArray())
                {
                    GenerateInMemory = false,
                    //GenerateExecutable = false,
                    TempFiles = new TempFileCollection(Path.GetTempPath(), true),
                    IncludeDebugInformation = true,
                };
                var results = isCodeOrFile
                    ? csc.CompileAssemblyFromSource(parameters, codeOrFile)
                    : csc.CompileAssemblyFromFile(parameters, codeOrFile);
                results.Errors.Cast <CompilerError>().ToList().ForEach(error => outputErrors.Add(error.ToString()));
                if (results.Errors.Count > 0)
                {
                    return(null);
                }
                return(results.CompiledAssembly);
            }
            catch (Exception e)
            {
                outputErrors.Add(e.Message);
                return(null);
            }
        }
        private ILoggerBuilderExtension[] CompileAndEvaluateExtensions(ProjectItem projectItem, IEnumerable <ProjectItem> referenceItems)
        {
            LogMessage($"Compiling possible logger builder extension file {projectItem?.Include ?? "in referenced dlls"}");

            var extensions = new List <ILoggerBuilderExtension>();

            try
            {
                var parameters = new CompilerParameters();

                foreach (var referenceItem in referenceItems)
                {
                    parameters.ReferencedAssemblies.Add(referenceItem.Name);
                }

                //parameters.ReferencedAssemblies.Add("System.dll");
                parameters.GenerateExecutable = false;
                parameters.GenerateInMemory   = true;

                parameters.IncludeDebugInformation = false;
                var cSharpCodeProvider = new CSharpCodeProvider();
                //var cSharpCodeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

                var             items = projectItem != null ? new string[] { projectItem.Name } : new string[0];
                CompilerResults compilerResults;
                compilerResults = cSharpCodeProvider.CompileAssemblyFromFile(parameters, items);
                foreach (CompilerError compilerResultsError in compilerResults.Errors)
                {
                    LogMessage(compilerResultsError.ToString());
                }

                var types = compilerResults.CompiledAssembly.GetTypes();
                foreach (
                    var type in
                    types.Where(t => typeof(ILoggerBuilderExtension).IsAssignableFrom(t)))
                {
                    var extension = (ILoggerBuilderExtension)Activator.CreateInstance(type);
                    extensions.Add(extension);
                }
            }
            catch (Exception ex)
            {
                LogMessage($"Failed to compile/evaluate {projectItem.Include} - {ex.Message}\r\n{ex.StackTrace}");
            }
            return(extensions.ToArray());
        }
示例#15
0
        static void GetSpecializedTotalScore()
        {
            string             label    = Console.ReadLine();
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters para     = new CompilerParameters();

            para.ReferencedAssemblies.Add("System.dll");
            para.ReferencedAssemblies.Add("System.Core.dll");
            para.ReferencedAssemblies.Add("TaicaiLib.dll");
            para.GenerateInMemory   = true;
            para.GenerateExecutable = false;
            CompilerResults results = provider.CompileAssemblyFromFile(para, "total.cs");

            if (results.Errors.Count > 0)
            {
                Console.WriteLine("Code Errors:");
                foreach (CompilerError e in results.Errors)
                {
                    Console.WriteLine("{0} line {1}: {2}", e.IsWarning ? "Warning" : "Error", e.Line, e.ErrorText);
                }
                if (results.Errors.HasErrors)
                {
                    return;
                }
            }
            Assembly ass      = results.CompiledAssembly;
            object   theClass = ass.CreateInstance("Taicai" + label + ".TotalGenerator");

            if (theClass == null)
            {
                Console.WriteLine("Taicai{0}.TotalGenerator needed", label);
                return;
            }
            Type totalGenerator = theClass.GetType();
            var  spec           = userlist.Select(u => new
            {
                user  = u,
                total = (double)totalGenerator.InvokeMember("GetSpecializedTotalScore",
                                                            BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, new object[] { u })
            });

            foreach (var s in spec.OrderByDescending(x => x.total))
            {
                Console.WriteLine(new KeyValuePair <string, double>(s.user.Name, s.total));
            }
        }
示例#16
0
        /// <summary>
        /// Compile file
        /// </summary>
        /// <param name="filePath">CS file path</param>
        /// <returns></returns>
        static private Result <string> CompileCSFile(string filePath)
        {
            var result = new Result <string>(null, true);
            var file   = new FileInfo(filePath);

            if (!file.Exists)
            {
                result.Success = false;
                result.Messages.Add(MessageType.Error, "Input file \"{0}\" does not exist", filePath);
            }
            if (result.Success)
            {
                try
                {
                    var outputPath = Path.ChangeExtension(file.FullName, ".dll");
                    result.Entity = outputPath;
                    var csc = new CSharpCodeProvider(new Dictionary <string, string>()
                    {
                        { "CompilerVersion", "v3.5" }
                    });
                    var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.dll", "System.Xml.dll", "WindowsBase.dll", "System.Runtime.Serialization.dll" }, outputPath, true);
                    parameters.GenerateExecutable = false;
                    CompilerResults results = csc.CompileAssemblyFromFile(parameters, filePath);
                    if (results.Errors.HasErrors)
                    {
                        result.Success = false;
                        foreach (CompilerError error in results.Errors)
                        {
                            result.Messages.Add(MessageType.Error, error.ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Messages.Add(MessageType.Error, "Exception", ex.ToString());
                }
            }

            if (result.Messages.Count > 0)
            {
                Debug.WriteLine(result.Messages.ToString());
            }

            return(result);
        }
示例#17
0
        private CompilerResults CompileAssemblies(CompilerParameters parameters, List <string> sources)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerResults    results  = provider.CompileAssemblyFromFile(parameters, sources.ToArray());

            if (results.Errors.HasErrors)
            {
                foreach (var error in results.Errors)
                {
                    Console.WriteLine(error);
                }

                throw new LoadException("Unable to load project. Please make sure it is compilable.");
            }

            return(results);
        }
        protected bool Compile(string outFile, string[] sourceFiles, params string[] references)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters cp       = new CompilerParameters();

            cp.ReferencedAssemblies.AddRange(references);
            cp.GenerateExecutable = false;
            cp.OutputAssembly     = outFile;
            cp.GenerateInMemory   = false;
            //生成调试文件
            cp.IncludeDebugInformation = CompilerConfig.EnableDebug;
            try
            {
                CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFiles);
                if (cr.Errors.Count > 0)
                {
                    if (OnCompileFailed != null)
                    {
                        CompileException exp = new CompileException(sourceFiles, cr.PathToAssembly, cr.Errors);
                        OnCompileFailed(exp);
                    }
                }
                else
                {
                    if (OnCompileSuccess != null)
                    {
                        OnCompileSuccess(sourceFiles, outFile);
                    }
                }
                return(cr.Errors.Count == 0);
            }
            catch (Exception e) {
                if (OnCompileFailed != null)
                {
                    CompilerErrorCollection t = new CompilerErrorCollection();
                    t.Add(new CompilerError()
                    {
                        ErrorText = e.Message
                    });
                    CompileException exp = new CompileException(sourceFiles, outFile, t);
                    OnCompileFailed(exp);
                }
                return(false);
            }
        }
示例#19
0
        public static Dictionary<string, ReflectedScript> Compile(string[] files, string[] references, out string error) {
            // No Error Default
            error = null;

            // Compile
            CompilerParameters compParams = new CompilerParameters(references, null, false);
            compParams.CompilerOptions = "/optimize";
            compParams.GenerateExecutable = false;
            compParams.GenerateInMemory = true;
            compParams.TreatWarningsAsErrors = false;
#if DEBUG
            compParams.IncludeDebugInformation = true;
#endif
            CompilerResults cr = compiler.CompileAssemblyFromFile(compParams, files);

            // Check For Errors
            if(cr.Errors.Count > 0) {
                error = "";
                foreach(var e in cr.Errors)
                    error += e + "\n";
                return null;
            }

            // Dictionaries
            var res = new Dictionary<string, ReflectedScript>();

            // Loop Through All Visible Types
            Assembly a = cr.CompiledAssembly;
            Type[] types = a.GetExportedTypes();
            foreach(Type t in types) {
                ZXPProxy.Add(t);
                ZXParser.AddDynamicType(t.FullName, t);

                // We Don't Want Abstract Classes Or Interfaces
                if(t.IsAbstract || t.IsInterface) continue;


                // Check For The Superclass
                if(t.IsSubclassOf(typeof(ACScript))) {
                    var rs = new ReflectedScript(t);
                    res.Add(rs.TypeName, rs);
                }
            }
            return res;
        }
示例#20
0
        public static bool CompileCSharpCode(string fileName, List <string> neededAssemblies)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();

            // Build the parameters for source compilation.
            CompilerParameters cp = new CompilerParameters();

            if (neededAssemblies != null)
            {
                foreach (var item in neededAssemblies)
                {
                    cp.ReferencedAssemblies.Add(item);
                }
            }

            // Set the assembly file name to generate.
            cp.OutputAssembly = fileName + ".dll";

            // Save the assembly as a physical file.
            cp.GenerateInMemory = false;

            cp.GenerateExecutable = false;

            // Invoke compilation.
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, fileName + ".cs");

            if (cr.Errors.Count > 0)
            {
                // Display compilation errors.
                foreach (CompilerError ce in cr.Errors)
                {
                    MessageBox.Show(ce.ToString());
                }
            }

            // Return the results of compilation.
            if (cr.Errors.Count > 0)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
示例#21
0
    internal static void testCompileFiles(List<string> files)
    {
        if (files.Count == 0) return;
        Dictionary<string, string> options = new Dictionary<string, string>();
        options.Add("CompilerVersion", "v3.5");
        CodeDomProvider codeProvider = new CSharpCodeProvider(options);
        CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo("cs");
        CompilerParameters compilerParam = compilerInfo.CreateDefaultCompilerParameters();
        compilerParam.TreatWarningsAsErrors = false;
        compilerParam.IncludeDebugInformation = true;
        compilerParam.GenerateInMemory = true;
        foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
            try {
                compilerParam.ReferencedAssemblies.Add(assembly.Location);
            } catch {
            }
        }

        CompilerResults result = codeProvider.CompileAssemblyFromFile(compilerParam, files.ToArray());
        List<CompilerError> errors = new List<CompilerError>();
        foreach (CompilerError error in result.Errors) {
            errors.Add(error);
        }
        var criticalErrors = from err in errors where !err.IsWarning select err;
        if (criticalErrors.Count() > 0) {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(criticalErrors.Count() + Local.Text("Web.WAF.Edit.ExplorerCriticalCompileError"));
            sb.AppendLine("<ol>");
            foreach (CompilerError error in criticalErrors) {
                if (!error.IsWarning) {
                    sb.Append("<li>" + error.ErrorText + ":");
                    if (error.FileName.Length > WAFContext.PathFromRootToAppFolder.Length) {
                        sb.Append("<div style=\"color:gray\"> -> " + error.FileName.Substring(WAFContext.PathFromRootToAppFolder.Length) + "</div>");
                    } else {
                        sb.Append("<div style=\"color:gray\"> -> " + error.FileName + "</div>");
                    }
                    sb.Append("<div style=\"color:gray\"> -> Line " + error.Line + " Col " + error.Column + "</div>");
                    sb.Append("<br/><br/></li>");
                }
            }
            sb.AppendLine("</ol>");
            throw new Exception(sb.ToString());
        }
    }
示例#22
0
        /// <summary>
        /// Build project with includeing <paramref name="referencedAssemblies"/>.
        /// </summary>
        /// <param name="referencedAssemblies">Assemblies to include.</param>
        /// <param name="files">Files to build.</param>
        /// <returns>Compile result string.</returns>
        private static string Build(string[] referencedAssemblies, string[] dlls = default(string[]), params string[] files)
        {
            CSharpCodeProvider compiler   = new CSharpCodeProvider();
            CompilerParameters parameters = GetCompilerParameters(referencedAssemblies, dlls);
            TempFileCollection tfc        = new TempFileCollection(Assembly.GetEntryAssembly().Location, false);
            CompilerResults    cr         = new CompilerResults(tfc);

            files = ConcatFiles(files);
            if (files.Length == 0)//it means that we need to clear all files in the assembly (bc or modules is removed or if it's attribute to clear all files)
            {
                File.Delete(parameters.OutputAssembly);
                return("Assembly is clear.");
            }
            cr = compiler.CompileAssemblyFromFile(parameters, files);
            string compileResults = GetResultString(cr);

            return(compileResults);
        }
        /// <summary>
        /// Just compiles source code and returns compilation result
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static (CompilerResults CompilerResult, int CodeLine) Compile(string filePath)
        {
            CSharpCodeProvider cProv   = new CSharpCodeProvider();
            CompilerParameters cParams = new CompilerParameters();

            cParams.ReferencedAssemblies.Add("mscorlib.dll");
            cParams.ReferencedAssemblies.Add("System.dll");
            cParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cParams.ReferencedAssemblies.Add("System.Xml.dll");
            cParams.GenerateExecutable      = false;
            cParams.GenerateInMemory        = true;
            cParams.IncludeDebugInformation = true;

            var lines = File.ReadAllLines(filePath).ToList();
            var index = lines.FindIndex(line => line.Contains("public void UpdateText()"));

            return(cProv.CompileAssemblyFromFile(cParams, filePath), index + 2);
        }
示例#24
0
    static void loadFile(string fileName)
    {
        AppDomain domain = AppDomain.CurrentDomain;

        Assembly[] assemblies = domain.GetAssemblies();
        string[]   fileNames  = Directory.GetFiles(srcDir, "*.cs", SearchOption.AllDirectories);

        CSharpCodeProvider codeProvider = new CSharpCodeProvider();

        System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
        parameters.GenerateInMemory = true;

        /*
         * IEnumerable<Assembly> filteredAssemblies = assemblies
         * .Where(a => !a.IsDynamic && !String.IsNullOrEmpty(a.Location))
         * .Distinct();
         * foreach(Assembly assembly in filteredAssemblies) {
         * Debug.Log("adding assembly: " + assembly.FullName);
         * parameters.ReferencedAssemblies.Add(assembly.Location);
         * }
         */
        parameters.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(Noise)).Location);
        parameters.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(Mathf)).Location);
        Debug.Log("compiling files: " + string.Join(";", fileNames) + " " + fileNames.Length);
        CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, fileNames);

        Debug.Log("compiling finsihed");

        if (results.Errors.Count > 0)
        {
            string error = "";
            foreach (CompilerError CompErr in results.Errors)
            {
                error = "Line number " + CompErr.Line +
                        ", Error Number: " + CompErr.ErrorNumber +
                        ", '" + CompErr.ErrorText + ";" +
                        Environment.NewLine + Environment.NewLine;
            }
            Debug.LogError(error);
        }

        currentAssembly = results.CompiledAssembly;
        listener(results.CompiledAssembly);
    }
示例#25
0
                public IsolatedCompiler(CompilingParameters parameters_)
                {
                    parameters = parameters_;
                    CSharpCodeProvider   codeProvider   = new CSharpCodeProvider();
                    CompilerParameters   exeparams      = new CompilerParameters();
                    List <CompilerError> resourceErrors = new List <CompilerError>();

                    exeparams.GenerateExecutable = true;
                    var dir = Directory.CreateDirectory(parameters.filePath);

                    exeparams.OutputAssembly = Path.Combine(parameters.filePath, parameters.fileName);

                    var processes = Process.GetProcessesByName(parameters.fileName.Substring(0, parameters.fileName.Length - 4));

                    if (processes.Length > 0)
                    {
                        processes.First().Kill();
                    }

                    foreach (var dep in parameters.assemblyDeps)
                    {
                        File.Copy(Path.Combine(".", dep), Path.Combine(parameters.filePath, dep), true);
                        exeparams.ReferencedAssemblies.Add(dep);
                    }

                    CompilerResults results = codeProvider.CompileAssemblyFromFile(exeparams, parameters.files.ToArray());

                    foreach (var error in results.Errors)
                    {
                        Debug.WriteLine(error);
                    }
                    if (results.Errors.Count > 0)
                    {
                        var errstr = "";
                        foreach (var error in results.Errors)
                        {
                            errstr += error + "\n";
                        }
                        throw new Exception(String.Format("Compiler errors : \n{0}", errstr));
                    }
                    CopyContentFiles();
                    CopyDLLs(exeparams, results);
                    Task.Run(() => ZippingUp(exeparams, results));
                }
示例#26
0
 /// <summary>
 /// Compiles the specified collection of C# Source files and returns the generated assembly.
 /// </summary>
 /// <param name="scripts">A collection of C# Source files to compile.</param>
 /// <returns>The assembly generated by the compiler.</returns>
 /// <exception cref="ArgumentNullException">The scripts parameter is null.</exception>
 static Assembly CompileScripts(IEnumerable <string> scripts)
 {
     scripts.ThrowIfNull(nameof(scripts));
     using (var csProvider = new CSharpCodeProvider()) {
         var options = new CompilerParameters {
             GenerateExecutable = false,
             GenerateInMemory   = true
         };
         options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
         var result = csProvider.CompileAssemblyFromFile(options, scripts.ToArray());
         if (result.Errors.HasErrors)
         {
             Print("Compilation of scenario scripts failed: ", ConsoleColor.Red);
             foreach (CompilerError error in result.Errors)
             {
                 var s = string.Format("* {0}, Line {1}: {2}", Path.GetFileName(error.FileName),
                                       error.Line, error.ErrorText);
                 Print(s);
             }
             return(null);
         }
         if (result.Errors.HasWarnings)
         {
             Print("Compilation of scenario scripts generated warnings: ", ConsoleColor.Yellow);
             foreach (CompilerError error in result.Errors)
             {
                 if (!error.IsWarning)
                 {
                     continue;
                 }
                 var s = string.Format("* {0}, Line {1}: {2}", Path.GetFileName(error.FileName),
                                       error.Line, error.ErrorText);
                 Print(s);
             }
             Print("");
             Print("Continue execution? (Y/N)", ConsoleColor.Yellow);
             if (char.ToLower(ReadChar('Y', 'y', 'N', 'n')) == 'n')
             {
                 return(null);
             }
         }
         return(result.CompiledAssembly);
     }
 }
示例#27
0
        public static Assembly compile()
        {
            // Shellcode loader would make more sense here, just make sure your code is located within the default constructor.
            string _testClass = @"
                    
                using System;
                using System.Runtime.InteropServices;

 //                   public class TestClass
 //                   {
 //                       " + "[DllImport(\"User32.dll\", CharSet = CharSet.Unicode)]" +
                                //                       @"public static extern int MessageBox(IntPtr h, string m, string c, int t);
                                //                       public TestClass(){
                                //                           " + "MessageBox((IntPtr)0, \"Test .NET Assembly Constructor Called.\", \"Coolio\", 0);" +
                                //                       @"}
                                //                   }
                                //           ";

                                CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();

            parameters.ReferencedAssemblies.Add("System.dll");


//            CompilerResults results = provider.CompileAssemblyFromSource(parameters, _testClass);

            CompilerResults results = provider.CompileAssemblyFromFile(parameters, "payload.txt");

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}: {2}", error.ErrorNumber, error.ErrorText, error.Line));
                }

                throw new InvalidOperationException(sb.ToString());
            }

            Assembly _compiled = results.CompiledAssembly;

            return(_compiled);
        }
示例#28
0
        public static bool CompileAssemblyFromFiles(string outputPath, string outputAssemblyName, string[] files, CodeDomNamespace namesp)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();

            // Build the parameters for source compilation.
            CompilerParameters cp = new CompilerParameters();

            // Add an assembly reference.
            cp.ReferencedAssemblies.AddRange(namesp.GetAssemblyReferences());

            // Set the assembly file name to generate.
            cp.OutputAssembly = Path.Combine(outputPath, $"{outputAssemblyName}.dll");

            // Save the assembly as a physical file.
            cp.GenerateInMemory = false;

            // Invoke compilation.
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, files);

            if (cr.Errors.Count > 0)
            {
                // Display compilation errors.
                Console.WriteLine("Errors building {0} into {1}",
                                  cp.OutputAssembly, cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    Console.WriteLine("  {0}", ce.ToString());
                    Console.WriteLine();
                }
            }
            else
            {
                Console.WriteLine("Source {0} built into {1} successfully.",
                                  cp.OutputAssembly, cr.PathToAssembly);
            }

            // Return the results of compilation.
            if (cr.Errors.Count > 0)
            {
                return(false);
            }

            return(true);
        }
示例#29
0
        public static Assembly CreateFromCSFiles(string pathName, string appName, string dbAssebmly)
        {
            CSharpCodeProvider csCompiler = new CSharpCodeProvider();

            CompilerParameters compilerParams = new CompilerParameters();

            //compilerParams.GenerateInMemory = true;

            // here you must add all the references you need.
            // I don't know whether you know all of them, but you have to get them
            // someway, otherwise it can't work

            compilerParams.ReferencedAssemblies.Add("System.dll");
            //compilerParams.ReferencedAssemblies.Add("System.Collections.dll");
            compilerParams.ReferencedAssemblies.Add("System.Linq.dll");
            compilerParams.ReferencedAssemblies.Add("System.Web.dll");
            compilerParams.ReferencedAssemblies.Add("System.Data.dll");
            compilerParams.ReferencedAssemblies.Add("System.Data.Entity.dll");
            compilerParams.ReferencedAssemblies.Add("System.Data.Entity.Design.dll");
            compilerParams.ReferencedAssemblies.Add(typeof(System.Web.Mvc.ActionResult).Assembly.Location);
            compilerParams.ReferencedAssemblies.Add(typeof(System.Web.Optimization.Bundle).Assembly.Location);
            compilerParams.ReferencedAssemblies.Add(typeof(System.Data.Entity.DbContext).Assembly.Location);
            compilerParams.ReferencedAssemblies.Add(typeof(System.Linq.Enumerable).Assembly.Location);

            ArrayList files = filePaths(pathName);

            string[] csPaths = new string[files.Count];
            for (int i = 0; i < csPaths.Length; i++)
            {
                csPaths[i] = (string)files[i];
            }

            compilerParams.OutputAssembly = pathName + "\\bin\\" + appName + ".dll";
            CompilerResults result = csCompiler.CompileAssemblyFromFile(compilerParams, csPaths);

            if (result.Errors.HasErrors)
            {
                return(null);
            }

            File.Delete(pathName + "\\Global.asax.cs");

            return(result.CompiledAssembly);
        }
示例#30
0
        public CompilerResults CreateDLL(bool explicitFiles = false)
        {
            if (TestIfCannotOverwriteDll(FinalDllOutputPath))
            {
                Debug.LogError((object)("Cannot build DLL, existing DLL is not overwritable, locked. DLL: " + FinalDllOutputPath));
                return(null);
            }
            HashSet <string> allSourceDirectories = GetAllSourceDirectories();

            if (allSourceDirectories.Count == 0 && (sourceFilePaths == null || sourceFilePaths.Count == 0))
            {
                Debug.LogError((object)("Cannot build DLL, no source directories to compile for DLL:" + FinalDllOutputPath));
                return(null);
            }
            if (File.Exists(TempDllOutputPath))
            {
                FileUtil.DeleteFileOrDirectory(TempDllOutputPath);
            }
            if (!Directory.Exists(TempBuildDir))
            {
                Directory.CreateDirectory(TempBuildDir);
            }
            DeleteSuperflousExtensions(FinalDllOutputPath);
            CompilerParameters standardCompilerParameters = GetStandardCompilerParameters(TempDllOutputPath);

            AddDllDependenciesToReferencedAssemblies(standardCompilerParameters);
            Dictionary <string, string> dictionary = new Dictionary <string, string>();

            dictionary.Add("CompilerVersion", "v3.5");
            CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider(dictionary);
            CompilerResults    compilerResults    = (!explicitFiles) ? cSharpCodeProvider.CompileAssemblyFromFile(standardCompilerParameters, allSourceDirectories.ToArray()) : cSharpCodeProvider.CompileAssemblyFromFile(standardCompilerParameters, sourceFilePaths.ToArray());

            LogCompileResults(compilerResults);
            if (!compilerResults.Errors.HasErrors)
            {
                string directoryName = Path.GetDirectoryName(FinalDllOutputPath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                File.Copy(compilerResults.PathToAssembly, FinalDllOutputPath, overwrite: true);
            }
            return(compilerResults);
        }
示例#31
0
        public static CompilerResults CompileDirectories(DirectoryInfo[] directories, string assemblyFileName, string[] referenceAssemblies, bool executable)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CompilerParameters parameters   = GetCompilerParameters(assemblyFileName, referenceAssemblies, executable);

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

            foreach (DirectoryInfo directory in directories)
            {
                foreach (FileInfo fileInfo in directory.GetFiles("*.cs", SearchOption.AllDirectories))
                {
                    if (!fileNames.Contains(fileInfo.FullName))
                    {
                        fileNames.Add(fileInfo.FullName);
                    }
                }
            }
            return(codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray()));
        }
    static void ExtractAndCompile(string sourceFile) {
        string assemblyName = Path.ChangeExtension(sourceFile, ".dll");

        ExtractResource("RoundtripTests.TestData.source." + sourceFile, sourceFile);

        CompilerParameters parameters = new CompilerParameters();
        parameters.GenerateExecutable = Path.GetExtension(assemblyName) == ".exe";
        parameters.IncludeDebugInformation = true;
        parameters.OutputAssembly = assemblyName;

        string tempFile = Path.GetRandomFileName();
        File.Move(sourceFile, Path.Combine(Path.GetDirectoryName(sourceFile), tempFile));

        CompilerResults results;
        using (CodeDomProvider icc = new CSharpCodeProvider()) {
            results = icc.CompileAssemblyFromFile(parameters, tempFile);
        }

        File.Delete(tempFile);

        foreach (var s in results.Errors) {
            Debug.WriteLine(s);
        }

        Assert.Equal(0, results.Errors.Count);
        Assert.True(File.Exists(assemblyName), string.Format("Failed to compile {0} from {1}", assemblyName, sourceFile));
    }
    public override IEnumerator Execute(UTContext context)
    {
        var realIncludes = EvaluateAll (includes, context);
        var realExcludes = EvaluateAll (excludes, context);

        var theBaseDirectory = baseDirectory != null ? baseDirectory.EvaluateIn(context) : null;
        if (string.IsNullOrEmpty(theBaseDirectory)) {
            theBaseDirectory = Application.dataPath;
        }

        if (!Directory.Exists(theBaseDirectory)) {
            throw new UTFailBuildException("The base directory " + theBaseDirectory + " does not exist or is not a directory", this);
        }

        var fileList = UTFileUtils.CalculateFileset (theBaseDirectory, realIncludes, realExcludes, UTFileUtils.FileSelectionMode.Files);

        if (fileList.Length == 0) {
            throw new UTFailBuildException ("No files were selected for build. Please check includes and excludes.", this);
        }

        var realOutputFile = outputFile.EvaluateIn (context);
        if (!realOutputFile.EndsWith (".dll")) {
            if (UTPreferences.DebugMode) {
                Debug.LogWarning("The output file does not end with .dll. The built DLL will not be picked up by Unity.");
            }
        }

        UTFileUtils.EnsureParentFolderExists (realOutputFile);

        if (UTPreferences.DebugMode) {
            foreach (var file in fileList) {
                Debug.Log ("Compiling " + file);
            }
        } else {
            Debug.Log ("Compiling " + fileList.Length + " files.");
        }

        var compiler = new CSharpCodeProvider ();
        CompilerParameters parameters = new CompilerParameters ();
        var doIncludeEngineDll = true;
        if (includeEngineDll != null) { // can happen when we migrate older automation plans which didn't have this setting.
            doIncludeEngineDll = includeEngineDll.EvaluateIn(context);
        }
        if (doIncludeEngineDll) {
            parameters.ReferencedAssemblies.Add (UnityDll ());
        }
        if (includeEditorDll.EvaluateIn (context)) {
            parameters.ReferencedAssemblies.Add (UnitEditorDll ());
        }

        var realAssemblies = EvaluateAll (referencedAssemblies, context);
        foreach (var asm in realAssemblies) {
            parameters.ReferencedAssemblies.Add (asm);
        }

        parameters.GenerateExecutable = false;
        parameters.OutputAssembly = realOutputFile;

        var theSymbols = defineSymbols.EvaluateIn(context);
        if (!string.IsNullOrEmpty(theSymbols)) {
            parameters.CompilerOptions = "/define:"+theSymbols.Trim();
        }

        var theAdditionalOptions = additionalCompilerOptions.EvaluateIn(context);
        if (!string.IsNullOrEmpty(theAdditionalOptions)) {
            parameters.CompilerOptions += " " + theAdditionalOptions.Trim();
        }

        SetPath ();
        CompilerResults results = compiler.CompileAssemblyFromFile (parameters, fileList);

        if (UTPreferences.DebugMode) {
            var output = results.Output;
            foreach (var line in output) {
                Debug.Log (line);
            }
        }

        var errors = results.Errors;
        var hadErrors = false;
        foreach (CompilerError error in errors) {
            if (error.IsWarning) {
                Debug.LogWarning (error.ToString ());
            } else {
                hadErrors = true;
                Debug.LogError (error.ToString ()); // TODO link errors to file.
            }
        }
        if (hadErrors) {
            throw new UTFailBuildException ("There were compilation errors.", this);
        }
        Debug.Log ("Built " + realOutputFile + " from " + fileList.Length + " source file(s).");
        yield return "";
    }
示例#34
0
    public static unsafe int Main(string[] args)
    {
        string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        string pluginDirectory;
        if (baseDirectory.EndsWith("bin"))
        {
            // Windows
            pluginDirectory = Path.GetFullPath(Path.Combine(baseDirectory, "..\\lib\\plugins"));
        }
        else
        {
            // *nix
            pluginDirectory = Path.Combine(baseDirectory, "plugins");
        }

        List<string> codeFiles = new List<string>();
        List<CodeCompileUnit> codeSnippets = new List<CodeCompileUnit>();
        List<Assembly> references = new List<Assembly>();
        List<string> imports = new List<string>();
        StringBuilder compilerOptions = new StringBuilder();
        bool codeOnly = false;
        string codeFile = string.Empty;
        string assemblyFile = "out.dll";
        int warnLevel = 0;
        string smokeLib = null;
        string defaultNamespace = "Qyoto";
        string globalClass = "Global";
        string destination = string.Empty;
        string docs = string.Empty;

        List<Assembly> plugins = new List<Assembly>();

        foreach (string arg in args)
        {
            if (arg == "-help" || arg == "--help" || arg == "-h")
            {
                PrintHelp();
                return 0;
            }
            if (arg == "-verbose")
            {
                Debug.Listeners.Add(new ConsoleTraceListener(true));
                continue;
            }
            if (arg == "-code-only")
            {
                codeOnly = true;
                continue;
            }
            if (arg.StartsWith("-code-file:"))
            {
                codeFile = arg.Substring(11);
                continue;
            }
            if (arg.StartsWith("-out:"))
            {
                assemblyFile = arg.Substring(5);
                continue;
            }
            if (arg.StartsWith("-warn:"))
            {
                warnLevel = int.Parse(arg.Substring(6));
                continue;
            }
            if (arg.StartsWith("-r:"))
            {
                references.Add(Assembly.LoadFrom(arg.Substring(3)));
                continue;
            }
            if (arg.StartsWith("-reference:"))
            {
                references.Add(Assembly.LoadFrom(arg.Substring(11)));
                continue;
            }
            if (arg.StartsWith("-global-class:"))
            {
                globalClass = arg.Substring(14);
                continue;
            }
            if (arg.StartsWith("-namespace:"))
            {
                defaultNamespace = arg.Substring(11);
                continue;
            }
            if (arg.StartsWith("-dest:"))
            {
                destination = arg.Substring("-dest:".Length);
                continue;
            }
            if (arg.StartsWith("-import:"))
            {
                imports.AddRange(arg.Substring(8).Split(','));
                continue;
            }
            if (arg.StartsWith("-docs:"))
            {
                docs = arg.Substring("-docs:".Length);
                continue;
            }
            if (arg.StartsWith("-plugins:"))
            {
                foreach (string str in arg.Substring(9).Split(','))
                {
                    Assembly a;
                    try
                    {
                        a = Assembly.LoadFrom(str);
                    }
                    catch (FileNotFoundException)
                    {
                        a = Assembly.LoadFrom(Path.Combine(pluginDirectory, str));
                    }
                    plugins.Add(a);
                }
                continue;
            }
            if (arg.StartsWith("-"))
            {
                compilerOptions.Append(" /");
                compilerOptions.Append(arg.Substring(1));
                continue;
            }

            if (smokeLib == null)
            {
                smokeLib = arg;
                continue;
            }

            codeFiles.Add(arg);
            FileStream fs = new FileStream(arg, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            codeSnippets.Add(new CodeSnippetCompileUnit(sr.ReadToEnd()));
            sr.Close();
            fs.Close();
        }
        if (!string.IsNullOrEmpty(docs))
        {
            compilerOptions.Append(" /doc:" + Path.ChangeExtension(Path.GetFileName(assemblyFile), ".xml"));
        }

        compilerOptions.Append(" -debug");

        if (smokeLib == null)
        {
            PrintHelp();
            return 1;
        }

        Smoke* smoke = InitSmoke(smokeLib);
        if (smoke == (Smoke*) 0)
        {
            return SmokeLoadingFailure;
        }

        List<ICustomTranslator> customTranslators = (from plugin in plugins
                                                     from type in plugin.GetTypes()
                                                     from iface in type.GetInterfaces()
                                                     where iface == typeof(ICustomTranslator)
                                                     select (ICustomTranslator) Activator.CreateInstance(type)).ToList();

        GeneratorData data = new GeneratorData(smoke, defaultNamespace, imports, references, destination, docs);
        data.GlobalSpaceClassName = globalClass;
        Translator translator = new Translator(data, customTranslators);

        foreach (IHookProvider provider in from type in plugins.SelectMany(plugin => plugin.GetTypes())
                                           where type.GetInterfaces().Any(iface => iface == typeof(IHookProvider))
                                           select (IHookProvider) Activator.CreateInstance(type))
        {
            provider.Translator = translator;
            provider.Data = data;
            provider.RegisterHooks();
        }

        ClassesGenerator classgen = new ClassesGenerator(data, translator);
        Console.Error.WriteLine("Generating CodeCompileUnit...");
        classgen.Run();
        DestroySmoke((IntPtr) smoke);

        Dictionary<string, string> providerOptions = new Dictionary<string, string>();
        providerOptions.Add("CompilerVersion", "v4.0");
        CodeDomProvider csharp = new CSharpCodeProvider(providerOptions);
        if (codeFile != string.Empty)
        {
            FileStream fs = new FileStream(codeFile, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            Console.Error.WriteLine("Generating code...");
            CodeGeneratorOptions cgo = new CodeGeneratorOptions();
            csharp.GenerateCodeFromCompileUnit(data.CompileUnit, sw, cgo);
            sw.Close();
            fs.Close();
            codeFiles.Add(codeFile);
        }

        if (codeOnly)
        {
            if (codeFile == string.Empty)
            {
                Console.Error.WriteLine("Missing output filename. Use the -code-file:<file> option.");
                return MissingOptionError;
            }
            return NoError;
        }

        codeSnippets.Add(data.CompileUnit);

        Console.Error.WriteLine("Compiling assembly...");
        CompilerParameters cp = new CompilerParameters();
        cp.GenerateExecutable = false;
        cp.TreatWarningsAsErrors = false;
        cp.OutputAssembly = assemblyFile;
        cp.GenerateInMemory = false;
        cp.WarningLevel = warnLevel;
        cp.CompilerOptions = compilerOptions.ToString();
        cp.ReferencedAssemblies.Add(typeof(Regex).Assembly.Location);
        cp.ReferencedAssemblies.Add(typeof(ExtensionAttribute).Assembly.Location);
        foreach (Assembly assembly in references)
        {
            cp.ReferencedAssemblies.Add(assembly.Location);
        }
        CompilerResults cr;

        if(codeFile == null)
        {
            cr = csharp.CompileAssemblyFromDom(cp, codeSnippets.ToArray());
        }
        else
        {
            cr = csharp.CompileAssemblyFromFile(cp, codeFiles.ToArray());
        }

        bool errorsOccured = false;
        foreach (CompilerError error in cr.Errors)
        {
            if (!error.IsWarning)
                errorsOccured = true;
            Console.Error.WriteLine(error);
        }

        if (errorsOccured)
        {
            Console.Error.WriteLine("Errors occured. No assembly was generated.");
            return CompilationError;
        }
        Console.Error.WriteLine("Done.");
        return NoError;
    }