Esempio n. 1
0
        protected virtual NPath CompileCSharpAssemblyWithRoslyn(CompilerOptions options)
        {
            var languageVersion    = LanguageVersion.Default;
            var compilationOptions = new CSharpCompilationOptions(
                outputKind: options.OutputPath.FileName.EndsWith(".exe") ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary,
                assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default
                );
            // Default debug info format for the current platform.
            DebugInformationFormat debugType = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb;
            bool emitPdb = false;

            if (options.AdditionalArguments != null)
            {
                foreach (var option in options.AdditionalArguments)
                {
                    switch (option)
                    {
                    case "/unsafe":
                        compilationOptions = compilationOptions.WithAllowUnsafe(true);
                        break;

                    case "/optimize+":
                        compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
                        break;

                    case "/optimize-":
                        compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Debug);
                        break;

                    case "/debug:full":
                    case "/debug:pdbonly":
                        // Use platform's default debug info. This behavior is the same as csc.
                        emitPdb = true;
                        break;

                    case "/debug:portable":
                        emitPdb   = true;
                        debugType = DebugInformationFormat.PortablePdb;
                        break;

                    case "/debug:embedded":
                        emitPdb   = true;
                        debugType = DebugInformationFormat.Embedded;
                        break;

                    case "/langversion:7.3":
                        languageVersion = LanguageVersion.CSharp7_3;
                        break;

                    default:
                        var splitIndex = option.IndexOf(":");
                        if (splitIndex != -1 && option[..splitIndex] == "/main")
                        {
                            var mainTypeName = option[(splitIndex + 1)..];
Esempio n. 2
0
        static byte[] GetILDLL(string srccode, bool Optimization = false)
        {
            byte[] dll = null;
            byte[] pdb = null;
            var    ast = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(srccode);
            var    op  = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            if (Optimization)
            {
                op = op.WithOptimizationLevel(OptimizationLevel.Release);
            }
            var comp = CSharpCompilation.Create("aaa.dll", new[] { ast }, new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
            }, op);

            using (var streamDll = new MemoryStream())
            {
                using (var streamPdb = new MemoryStream())
                {
                    var result = comp.Emit(streamDll, streamPdb);
                    if (!result.Success)
                    {
                        foreach (var d in result.Diagnostics)
                        {
                            Console.WriteLine(d.ToString());
                        }
                        throw new Exception("build error.");
                    }
                    dll = streamDll.ToArray();
                    pdb = streamPdb.ToArray();
                    return(dll);
                }
            }
        }
Esempio n. 3
0
    public void _TestCompilationOptions()
    {
        var tree = CSharpSyntaxTree.ParseText(@"
        using System;using Xunit;
        public class MyClass
        {
            public static void Main()
            {
                //DebugLogger.Instance.WriteLine(""Hello World!"");
                //DebugLogger.Instance.ReadLine();
            }   
        }");

        //We first have to choose what kind of output we're creating: DLL, .exe etc.
        var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

        options = options.WithAllowUnsafe(true);                                //Allow unsafe code;
        options = options.WithOptimizationLevel(OptimizationLevel.Release);     //Set optimization level
        options = options.WithPlatform(Platform.X64);                           //Set platform

        var mscorlib    = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
        var compilation = CSharpCompilation.Create("MyCompilation",
                                                   syntaxTrees: new[] { tree },
                                                   references: new[] { mscorlib },
                                                   options: options);     //Pass options to compilation
    }
Esempio n. 4
0
        public async Task <ScriptsCompileResult> Build(GameProject gameProject, FileInfo mainScript, bool releaseMode)
        {
            string scriptsPath = mainScript.DirectoryName;


            _compilationOptions =
                _compilationOptions.WithSourceReferenceResolver(
                    new SourceFileResolver(ImmutableArray <string> .Empty, scriptsPath));


            if (releaseMode)
            {
                _compilationOptions = _compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
            }

            if (!releaseMode && mainScript.LastWriteTime < _lastBuildTime)
            {
                return(new ScriptsCompileResult());
            }

            string scriptCode = File.ReadAllText(mainScript.FullName);

            ScriptsCompileResult result = await Task.Run(() => GenerateGameAssembly(scriptCode));

            if (result.Errors == null)
            {
                _lastBuildTime = DateTime.Now;
            }

            return(result);
        }
Esempio n. 5
0
        private static Assembly CreateAssembly(string sourceCode, bool debug)
        {
            lineOffset   = CalculateLineOffset(sourceCode);
            exceptionMsg = null;
            errors       = null;

            string assemblyName = Path.GetRandomFileName();
            IEnumerable <SyntaxTree> syntaxTree = new[] { CSharpSyntaxTree.ParseText(sourceCode, options: debug ? parseOptions.WithPreprocessorSymbols("DEBUG") : parseOptions) };

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName, syntaxTree, references,
                compilationOptions.WithOptimizationLevel(debug ? OptimizationLevel.Debug : OptimizationLevel.Release));

            using (MemoryStream ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                errors = result.Diagnostics.Where(ErrorFilter);

                if (!result.Success)
                {
                    return(null);
                }

                AssemblyLoadContext loadContext = new AssemblyLoadContext(null, true);
                ms.Seek(0, SeekOrigin.Begin);
                Assembly assembly = loadContext.LoadFromStream(ms);
                return(assembly);
            }
        }
Esempio n. 6
0
        private EmitResult CompileAndBuild(string outputFileName, string sourceCode, BuildConfiguration buildConfiguration)
        {
            var referenceBasePath   = $@"c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\{buildConfiguration.TargetFramework}\";
            var template            = File.ReadAllText(@"C:\Workspace\Sharpbench\src\BenchmarkHost\EntryPoint.cs");
            var generatedSourceCode = template.Replace("/*CODE_PLACEHOLDER*/", sourceCode);
            var syntaxTree          = CSharpSyntaxTree.ParseText(generatedSourceCode);

            var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

            if (buildConfiguration.Optimization == Optimization.Debug)
            {
                options.WithOptimizationLevel(OptimizationLevel.Debug);
            }
            else if (buildConfiguration.Optimization == Optimization.Release)
            {
                options.WithOptimizationLevel(OptimizationLevel.Release);
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(buildConfiguration.Optimization));
            }

            if (buildConfiguration.Platform == Platform.X86)
            {
                options.WithPlatform(Microsoft.CodeAnalysis.Platform.X86);
            }
            else if (buildConfiguration.Platform == Platform.X64)
            {
                options.WithPlatform(Microsoft.CodeAnalysis.Platform.X64);
            }

            var references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(Path.Combine(referenceBasePath, "mscorlib.dll")),
                MetadataReference.CreateFromFile(Path.Combine(referenceBasePath, "System.dll")),
                MetadataReference.CreateFromFile(Path.Combine(referenceBasePath, "System.Xml.dll")),
            };
            var compilation = CSharpCompilation.Create("GeneratedAssembly", new[] { syntaxTree }, options: options, references: references);
            var emitResult  = compilation.Emit(outputFileName);

            return(emitResult);
        }
        private static void ConfigureRazor(RazorViewEngineOptions razorOptions,
                                           IApplicationEnvironment applicationEnvironment,
                                           IHostingEnvironment hostingEnvironment)
        {
            razorOptions.FileProviders.Add(new PhysicalFileProvider(applicationEnvironment.ApplicationBasePath));

            var parseOptions       = new CSharpParseOptions(LanguageVersion.CSharp6);
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            if (hostingEnvironment.IsDevelopment())
            {
                razorOptions.ParseOptions       = parseOptions.WithPreprocessorSymbols("DEBUG");
                razorOptions.CompilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Debug);
            }
            else
            {
                razorOptions.ParseOptions       = parseOptions.WithPreprocessorSymbols("RELEASE");
                razorOptions.CompilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
            }
        }
Esempio n. 8
0
    protected virtual CSharpCompilationOptions GetCompilationOptions()
    {
        var csharpCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

        // Disable 1702 until roslyn turns this off by default
        csharpCompilationOptions = csharpCompilationOptions.WithSpecificDiagnosticOptions(
            new Dictionary <string, ReportDiagnostic>
        {
            { "CS1701", ReportDiagnostic.Suppress },       // Binding redirects
            { "CS1702", ReportDiagnostic.Suppress },
            { "CS1705", ReportDiagnostic.Suppress }
        });

        return(csharpCompilationOptions.WithOptimizationLevel(OptimizationLevel.Release));
    }
Esempio n. 9
0
        private static CSharpCompilationOptions GetCompilationOptions(
            IWebHostEnvironment hostingEnvironment,
            DependencyContextCompilationOptions dependencyContextOptions)
        {
            var csharpCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            // Disable 1702 until roslyn turns this off by default
            csharpCompilationOptions = csharpCompilationOptions.WithSpecificDiagnosticOptions(
                new Dictionary <string, ReportDiagnostic>
            {
                { "CS1701", ReportDiagnostic.Suppress },   // Binding redirects
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress }
            });

            if (dependencyContextOptions.AllowUnsafe.HasValue)
            {
                csharpCompilationOptions = csharpCompilationOptions.WithAllowUnsafe(
                    dependencyContextOptions.AllowUnsafe.Value);
            }

            OptimizationLevel optimizationLevel;

            if (dependencyContextOptions.Optimize.HasValue)
            {
                optimizationLevel = dependencyContextOptions.Optimize.Value ?
                                    OptimizationLevel.Release :
                                    OptimizationLevel.Debug;
            }
            else
            {
                optimizationLevel = hostingEnvironment.IsDevelopment() ?
                                    OptimizationLevel.Debug :
                                    OptimizationLevel.Release;
            }
            csharpCompilationOptions = csharpCompilationOptions.WithOptimizationLevel(optimizationLevel);

            if (dependencyContextOptions.WarningsAsErrors.HasValue)
            {
                var reportDiagnostic = dependencyContextOptions.WarningsAsErrors.Value ?
                                       ReportDiagnostic.Error :
                                       ReportDiagnostic.Default;
                csharpCompilationOptions = csharpCompilationOptions.WithGeneralDiagnosticOption(reportDiagnostic);
            }

            return(csharpCompilationOptions);
        }
Esempio n. 10
0
        public void EmittingConsoleApplication()
        {
            var text = "Hello Roslyn!";
            var tree = CSharpSyntaxTree.ParseText($@"
using System;
using System.Diagnostics;

public class MyClass
{{
    public static void Main()
    {{
        Console.WriteLine(""{text}"");
    }}   
}}");

            var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

            options = options.WithOptimizationLevel(OptimizationLevel.Release);     //Set optimization level
            options = options.WithPlatform(Platform.X86);                           //Set platform


            var mscorlib    = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var compilation = CSharpCompilation.Create("MyCompilation",
                                                       syntaxTrees: new[] { tree }, references: new[] { mscorlib }, options: options);

            //Emit to stream
            using (var ms = new MemoryStream())
            {
                var emitResult = compilation.Emit(ms);

                //Load into currently running assembly. Normally we'd probably
                //want to do this in an AppDomain
                var ourAssembly = Assembly.Load(ms.ToArray());
                var type        = ourAssembly.GetType("MyClass");

                //Invokes our main method and writes "Hello World" :)
                type.InvokeMember("Main", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, null);
            }
        }
Esempio n. 11
0
        private static void CompileToCSharp(SyntaxTree tree)
        {
            var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var ethSharp = MetadataReference.CreateFromFile(typeof(UInt256).Assembly.Location);

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            options = options.WithAllowUnsafe(true);                                //Allow unsafe code;
            options = options.WithOptimizationLevel(OptimizationLevel.Release);     //Set optimization level
            options = options.WithPlatform(Platform.X64);
            var compilation = CSharpCompilation.Create("MyCompilation",
                                                       syntaxTrees: new[] { tree }, references: new[] { mscorlib, ethSharp },
                                                       options: options);
            var emitResult = compilation.Emit("output.dll", "output.pdb");

            //If our compilation failed, we can discover exactly why.
            if (!emitResult.Success)
            {
                foreach (var diagnostic in emitResult.Diagnostics)
                {
                    Console.WriteLine(diagnostic.ToString());
                }
            }
        }
Esempio n. 12
0
        public HostBuildData Create(HostBuildOptions options)
        {
            var parseOptions = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6, documentationMode: DocumentationMode.Parse);
            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.ConsoleApplication,
                xmlReferenceResolver: new XmlFileResolver(options.ProjectDirectory),
                sourceReferenceResolver: new SourceFileResolver(ImmutableArray<string>.Empty, options.ProjectDirectory),
                metadataReferenceResolver: new AssemblyReferenceResolver(
                    new MetadataFileReferenceResolver(ImmutableArray<string>.Empty, options.ProjectDirectory),
                    MetadataFileReferenceProvider.Default),
                strongNameProvider: new DesktopStrongNameProvider(ImmutableArray.Create(options.ProjectDirectory, options.OutputDirectory)),
                assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default);
            var warnings = new List<KeyValuePair<string, ReportDiagnostic>>(options.Warnings);

            if (options.OutputKind.HasValue)
            {
                var kind = options.OutputKind.Value;
                compilationOptions = compilationOptions.WithOutputKind(kind);
                if (compilationOptions.Platform == Platform.AnyCpu32BitPreferred &&
                    (kind == OutputKind.DynamicallyLinkedLibrary || kind == OutputKind.NetModule || kind == OutputKind.WindowsRuntimeMetadata))
                {
                    compilationOptions = compilationOptions.WithPlatform(Platform.AnyCpu);
                }
            }

            if (!string.IsNullOrEmpty(options.DefineConstants))
            {
                IEnumerable<Diagnostic> diagnostics;
                parseOptions = parseOptions.WithPreprocessorSymbols(CSharpCommandLineParser.ParseConditionalCompilationSymbols(options.DefineConstants, out diagnostics));
            }

            if (options.DocumentationFile != null)
            {
                parseOptions = parseOptions.WithDocumentationMode(!string.IsNullOrEmpty(options.DocumentationFile) ? DocumentationMode.Diagnose : DocumentationMode.Parse);
            }

            if (options.LanguageVersion != null)
            {
                var languageVersion = CompilationOptionsConversion.GetLanguageVersion(options.LanguageVersion);
                if (languageVersion.HasValue)
                {
                    parseOptions = parseOptions.WithLanguageVersion(languageVersion.Value);
                }
            }

            if (!string.IsNullOrEmpty(options.PlatformWith32BitPreference))
            {
                Platform platform;
                if (Enum.TryParse<Platform>(options.PlatformWith32BitPreference, true, out platform))
                {
                    if (platform == Platform.AnyCpu &&
                        compilationOptions.OutputKind != OutputKind.DynamicallyLinkedLibrary &&
                        compilationOptions.OutputKind != OutputKind.NetModule &&
                        compilationOptions.OutputKind != OutputKind.WindowsRuntimeMetadata)
                    {
                        platform = Platform.AnyCpu32BitPreferred;
                    }

                    compilationOptions = compilationOptions.WithPlatform(platform);
                }
            }

            if (options.AllowUnsafeBlocks.HasValue)
            {
                compilationOptions = compilationOptions.WithAllowUnsafe(options.AllowUnsafeBlocks.Value);
            }

            if (options.CheckForOverflowUnderflow.HasValue)
            {
                compilationOptions = compilationOptions.WithOverflowChecks(options.CheckForOverflowUnderflow.Value);
            }

            if (options.DelaySign != null)
            {
                bool delaySignExplicitlySet = options.DelaySign.Item1;
                bool delaySign = options.DelaySign.Item2;
                compilationOptions = compilationOptions.WithDelaySign(delaySignExplicitlySet ? delaySign : (bool?)null);
            }

            if (!string.IsNullOrEmpty(options.ApplicationConfiguration))
            {
                var appConfigPath = FileUtilities.ResolveRelativePath(options.ApplicationConfiguration, options.ProjectDirectory);
                try
                {
                    using (var appConfigStream = PortableShim.FileStream.Create(appConfigPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read))
                    {
                        compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream));
                    }
                }
                catch (Exception)
                {
                }
            }

            if (!string.IsNullOrEmpty(options.KeyContainer))
            {
                compilationOptions = compilationOptions.WithCryptoKeyContainer(options.KeyContainer);
            }

            if (!string.IsNullOrEmpty(options.KeyFile))
            {
                var fullPath = FileUtilities.ResolveRelativePath(options.KeyFile, options.ProjectDirectory);
                compilationOptions = compilationOptions.WithCryptoKeyFile(fullPath);
            }

            if (!string.IsNullOrEmpty(options.MainEntryPoint))
            {
                compilationOptions = compilationOptions.WithMainTypeName(options.MainEntryPoint);
            }

            if (!string.IsNullOrEmpty(options.ModuleAssemblyName))
            {
                compilationOptions = compilationOptions.WithModuleName(options.ModuleAssemblyName);
            }

            if (options.Optimize.HasValue)
            {
                compilationOptions = compilationOptions.WithOptimizationLevel(options.Optimize.Value ? OptimizationLevel.Release : OptimizationLevel.Debug);
            }

            if (!string.IsNullOrEmpty(options.Platform))
            {
                Platform plat;
                if (Enum.TryParse<Platform>(options.Platform, ignoreCase: true, result: out plat))
                {
                    compilationOptions = compilationOptions.WithPlatform(plat);
                }
            }

            // Get options from the ruleset file, if any.
            if (!string.IsNullOrEmpty(options.RuleSetFile))
            {
                var fullPath = FileUtilities.ResolveRelativePath(options.RuleSetFile, options.ProjectDirectory);

                Dictionary<string, ReportDiagnostic> specificDiagnosticOptions;
                var generalDiagnosticOption = RuleSet.GetDiagnosticOptionsFromRulesetFile(fullPath, out specificDiagnosticOptions);
                compilationOptions = compilationOptions.WithGeneralDiagnosticOption(generalDiagnosticOption);
                warnings.AddRange(specificDiagnosticOptions);
            }

            if (options.WarningsAsErrors.HasValue)
            {
                compilationOptions = compilationOptions.WithGeneralDiagnosticOption(options.WarningsAsErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default);
            }

            if (options.WarningLevel.HasValue)
            {
                compilationOptions = compilationOptions.WithWarningLevel(options.WarningLevel.Value);
            }

            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(warnings);
            return new HostBuildData(
                parseOptions,
                compilationOptions);
        }
        public override async Task <CodeCompilerResult> CompileFile(
            CodeCompilerArguments arguments,
            TextWriter log,
            CancellationToken token)
        {
            var references = new List <MetadataReference> ();

            foreach (var assemblyReference in AssemblyResolver.GetResolvedReferences(runtime, arguments.AssemblyReferences))
            {
                references.Add(MetadataReference.CreateFromFile(assemblyReference));
                try {
                    Assembly.LoadFrom(assemblyReference);
                } catch (Exception) { }
            }

            var syntaxTrees = new List <SyntaxTree> ();

            foreach (var sourceFile in arguments.SourceFiles)
            {
                using var stream = File.OpenRead(sourceFile);
                var sourceText = SourceText.From(stream, Encoding.UTF8, canBeEmbedded: true);
                syntaxTrees.Add(CSharpSyntaxTree.ParseText(sourceText, path: sourceFile));
            }

            var compilationoptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            if (arguments.Debug)
            {
                compilationoptions = compilationoptions.WithOptimizationLevel(OptimizationLevel.Debug);
            }

            var compilation = CSharpCompilation.Create(
                "GeneratedTextTransformation",
                syntaxTrees,
                references,
                compilationoptions
                );

            EmitOptions         emitOptions   = null;
            List <EmbeddedText> embeddedTexts = null;
            string pdbPath = null;

            if (arguments.Debug)
            {
                pdbPath       = Path.ChangeExtension(arguments.OutputPath, "pdb");
                embeddedTexts = syntaxTrees.Where(st => !string.IsNullOrEmpty(st.FilePath)).Select(st => EmbeddedText.FromSource(st.FilePath, st.GetText())).ToList();
                emitOptions   = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: pdbPath);
            }

            EmitResult result;

            using var fs = File.OpenWrite(arguments.OutputPath);
            {
                if (pdbPath != null)
                {
                    using var pdb = File.OpenWrite(pdbPath);
                    result        = compilation.Emit(fs, pdbStream: pdb, options: emitOptions, embeddedTexts: embeddedTexts);
                }
                else
                {
                    result = compilation.Emit(fs, options: emitOptions, embeddedTexts: embeddedTexts);
                }
            }

            if (result.Success)
            {
                return(new CodeCompilerResult {
                    Output = new List <string> (),
                    Success = true,
                    Errors = new List <CodeCompilerError> ()
                });
            }

            var failures = result.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error);
            var errors   = failures.Select(x => {
                var location          = x.Location.GetMappedLineSpan();
                var startLinePosition = location.StartLinePosition;
                var endLinePosition   = location.EndLinePosition;
                return(new CodeCompilerError {
                    Message = x.GetMessage(),
                    Column = startLinePosition.Character,
                    Line = startLinePosition.Line,
                    EndLine = endLinePosition.Line,
                    EndColumn = endLinePosition.Character,
                    IsError = x.Severity == DiagnosticSeverity.Error,
                    Origin = location.Path
                });
            }).ToList();

            return(new CodeCompilerResult {
                Success = false,
                Output = new List <string> (),
                Errors = errors
            });
        }
Esempio n. 14
0
        private static (string outputFile, CSharpCompilationOptions compilationOptions, CSharpParseOptions parseOptions) ParseArguments(IEnumerable <string> args)
        {
            var arguments = new Dictionary <string, string>();

            var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

            compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
            string outputFile = "";

            var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>()
            {
                // Ensure that specific warnings about assembly references are always suppressed.
                { "CS1701", ReportDiagnostic.Suppress },
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress }
            };

            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions);

            var parseOptions = new CSharpParseOptions();

            foreach (var arg in args)
            {
                var argParts = arg.Split(':');

                var argument = argParts[0].Replace("+", "").Replace("/", "");
                var value    = "";

                if (argParts.Count() > 1)
                {
                    value = argParts[1];
                }

                switch (argument)
                {
                case "target":
                    compilationOptions = compilationOptions.WithOutputKind(ParseTarget(value));
                    break;

                case "unsafe":
                    compilationOptions = compilationOptions.WithAllowUnsafe(true);
                    break;

                case "nowarn":
                    var warnings = value.Split(',');

                    if (warnings.Count() > 0)
                    {
                        compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(warnings.Select(s => new KeyValuePair <string, ReportDiagnostic>(!s.StartsWith("CS") ? $"CS{s}" : s, ReportDiagnostic.Suppress)));
                    }
                    break;

                case "define":
                    var defines = value.Split(';');

                    if (defines.Count() > 0)
                    {
                        parseOptions = parseOptions.WithPreprocessorSymbols(defines);
                    }
                    break;

                case "optimize":
                    compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
                    break;

                case "platform":
                    compilationOptions = compilationOptions.WithPlatform(ParsePlatform(value));
                    break;

                case "out":
                    outputFile = value;
                    break;
                }
            }

            return(outputFile, compilationOptions, parseOptions);
        }
Esempio n. 15
0
        private static IActionResult Roslyn(string code, string responseMessage)
        {
            //Based on Josh Varty and Damir code
            var tree = CSharpSyntaxTree.ParseText(@"
            using System;

            namespace ConsoleApp1
            {
                public class Program
                {
                    static void Main(string[] args)
                    {
                        Console.WriteLine(""" + code + @""");
                        //Console.ReadLine();
                    }
                }
            }
            ");

            var assemblyPath = Path.ChangeExtension("output", "exe");

            File.WriteAllText(
                Path.ChangeExtension(assemblyPath, "runtimeconfig.json"),
                GenerateRuntimeConfig()
                );

            var dotNetCoreDir = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            var mscorlib      = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var console       = MetadataReference.CreateFromFile(typeof(Console).GetTypeInfo().Assembly.Location);
            var myruntime     = MetadataReference.CreateFromFile(Path.Combine(dotNetCoreDir, "System.Runtime.dll"));

            //We first have to choose what kind of output we're creating: DLL, .exe etc.
            var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

            options = options.WithAllowUnsafe(true);                              //Allow unsafe code;
            options = options.WithOptimizationLevel(OptimizationLevel.Debug);     //Set optimization level
            options = options.WithPlatform(Platform.X64);                         //Set platform

            var compilation = CSharpCompilation.Create("MyCompilation",
                                                       syntaxTrees: new[] { tree },
                                                       references: new[] { mscorlib, console, myruntime },
                                                       options: options);

            //Emitting to file is available through an extension method in the Microsoft.CodeAnalysis namespace
            var emitResult = compilation.Emit(assemblyPath);

            Process process = new Process();

            process.StartInfo.FileName  = "dotnet";
            process.StartInfo.Arguments = assemblyPath; // Note the /c command (*)
            //process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.Start();
            //* Read the output (or the error)
            string output = process.StandardOutput.ReadToEnd();
            //Console.WriteLine(output);
            string err = process.StandardError.ReadToEnd();

            //Console.WriteLine(err);
            process.WaitForExit();

            return(new OkObjectResult(output + err));
        }
Esempio n. 16
0
        protected virtual NPath CompileCSharpAssemblyWithRoslyn(CompilerOptions options)
        {
            var languageVersion    = LanguageVersion.Default;
            var compilationOptions = new CSharpCompilationOptions(
                outputKind: options.OutputPath.FileName.EndsWith(".exe") ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary,
                assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default
                );
            // Default debug info format for the current platform.
            DebugInformationFormat debugType = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb;
            bool emitPdb = false;

            if (options.AdditionalArguments != null)
            {
                foreach (var option in options.AdditionalArguments)
                {
                    switch (option)
                    {
                    case "/unsafe":
                        compilationOptions = compilationOptions.WithAllowUnsafe(true);
                        break;

                    case "/optimize+":
                        compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
                        break;

                    case "/debug:full":
                    case "/debug:pdbonly":
                        // Use platform's default debug info. This behavior is the same as csc.
                        emitPdb = true;
                        break;

                    case "/debug:portable":
                        emitPdb   = true;
                        debugType = DebugInformationFormat.PortablePdb;
                        break;

                    case "/debug:embedded":
                        emitPdb   = true;
                        debugType = DebugInformationFormat.Embedded;
                        break;

                    case "/langversion:7.3":
                        languageVersion = LanguageVersion.CSharp7_3;
                        break;
                    }
                }
            }
            var parseOptions = new CSharpParseOptions(preprocessorSymbols: options.Defines, languageVersion: languageVersion);
            var emitOptions  = new EmitOptions(debugInformationFormat: debugType);
            var pdbPath      = (!emitPdb || debugType == DebugInformationFormat.Embedded) ? null : options.OutputPath.ChangeExtension(".pdb").ToString();

            var syntaxTrees = options.SourceFiles.Select(p =>
                                                         CSharpSyntaxTree.ParseText(
                                                             text: p.ReadAllText(),
                                                             options: parseOptions
                                                             )
                                                         );

            var compilation = CSharpCompilation.Create(
                assemblyName: options.OutputPath.FileNameWithoutExtension,
                syntaxTrees: syntaxTrees,
                references: options.References.Select(r => MetadataReference.CreateFromFile(r)),
                options: compilationOptions
                );

            var manifestResources = options.Resources.Select(r => {
                var fullPath = r.ToString();
                return(new ResourceDescription(
                           resourceName: Path.GetFileName(fullPath),
                           dataProvider: () => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
                           isPublic: true
                           ));
            });

            EmitResult result;

            using (var outputStream = File.Create(options.OutputPath.ToString()))
                using (var pdbStream = (pdbPath == null ? null : File.Create(pdbPath))) {
                    result = compilation.Emit(
                        peStream: outputStream,
                        pdbStream: pdbStream,
                        manifestResources: manifestResources,
                        options: emitOptions
                        );
                }

            var errors = new StringBuilder();

            if (result.Success)
            {
                return(options.OutputPath);
            }

            foreach (var diagnostic in result.Diagnostics)
            {
                errors.AppendLine(diagnostic.ToString());
            }
            throw new Exception("Roslyn compilation errors: " + errors);
        }
Esempio n. 17
0
        internal RoslynGenerate()
        {
            var tree = CSharpSyntaxTree.ParseText(@"
            using System;

            namespace ConsoleApp1
            {
                public class Program
                {
                    static void Main(string[] args)
                    {
                        //Console.WriteLine("");
                        //Console.ReadLine();
                    }
                }
            }
            ");

            ParameterExpression value = Expression.Parameter(typeof(int), "value");

            // Creating an expression to hold a local variable.
            ParameterExpression result = Expression.Parameter(typeof(int), "result");

            // Creating a label to jump to from a loop.
            LabelTarget label = Expression.Label(typeof(int));

            // Creating a method body.
            BlockExpression block = Expression.Block(
                // Adding a local variable.
                new[] { result },
                // Assigning a constant to a local variable: result = 1
                Expression.Assign(result, Expression.Constant(1)),
                // Adding a loop.
                Expression.Loop(
                    // Adding a conditional block into the loop.
                    Expression.IfThenElse(
                        // Condition: value > 1
                        Expression.GreaterThan(value, Expression.Constant(1)),
                        // If true: result *= value --
                        Expression.MultiplyAssign(result,
                                                  Expression.PostDecrementAssign(value)),
                        // If false, exit the loop and go to the label.
                        Expression.Break(label, result)
                        ),
                    // Label to jump to.
                    label
                    )
                );

            var dotNetCoreDir = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            var mscorlib      = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var console       = MetadataReference.CreateFromFile(typeof(Console).GetTypeInfo().Assembly.Location);
            var myruntime     = MetadataReference.CreateFromFile(Path.Combine(dotNetCoreDir, "System.Runtime.dll"));

            var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

            options = options.WithAllowUnsafe(true);
            options = options.WithOptimizationLevel(OptimizationLevel.Debug);
            options = options.WithPlatform(Platform.X64);

            var compilation = CSharpCompilation.Create("MyCompilation",
                                                       syntaxTrees: new[] { tree },
                                                       references: new[] { mscorlib, console, myruntime },
                                                       options: options);

            /*
             * CallSiteBinder binder = new DynamicMetaObjectBinder();
             *
             * ConstantExpression[] arguments = new[] { Expression.Constant(5), Expression.Constant(2) };
             * DynamicExpression exp = Expression.Dynamic(
             *  binder,
             *  typeof(object),
             *  arguments);
             *
             * var compiled = Expression.Lambda<Func<object>>(exp).Compile();
             * var result = compiled();
             */
        }
Esempio n. 18
0
        private CompilerResults CompileWithRoslyn(List <string> filenames, List <string> sources, ICollection <Assembly> referencedAssemblies)
        {
#if ROSLYN
            CompilerResults          cr;
            CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            EmitOptions emitOptions          = new EmitOptions();
            if (includeDebugInformation)
            {
                // Embedded option doesn't seem to work
                // Explanation of options: https://github.com/dotnet/designs/blob/master/accepted/diagnostics/debugging-with-symbols-and-sources.md
                emitOptions = emitOptions.WithDebugInformationFormat(DebugInformationFormat.PortablePdb);
            }
            else
            {
                emitOptions = emitOptions.WithDebugInformationFormat(DebugInformationFormat.Embedded);
            }
            if (optimizeCode)
            {
                options = options.WithOptimizationLevel(OptimizationLevel.Release);
            }

            // If running on the Mono VM, disable all warnings in the generated
            // code because these are treated as errors by the Mono compiler.
            if (runningOnMono)
            {
                options = options.WithWarningLevel(0);
            }

            List <MetadataReference> references = new List <MetadataReference>();
            foreach (Assembly assembly in referencedAssemblies)
            {
                try
                {
                    references.Add(MetadataReference.CreateFromFile(assembly.Location));
                }
                catch (NotSupportedException)
                {
                    // do nothing - this assembly does not have a location e.g. it is in memory
                }
                catch (Exception e)
                {
                    Console.WriteLine("Warning, could not add location for assembly: " + assembly);
                    Console.WriteLine(e);
                }
            }
            // we must only add references to assemblies that are actually referenced by the code -- not all the assemblies in memory during model compilation (that could be a much larger set)

            SyntaxTree[] trees;
            if (!writeSourceFiles)
            {
                // Note: Without source files, the debugger cannot step into generated code, even if a pdb is generated.
                // Theoretically, it should be possible to embed the source into the pdb.
                trees = sources.Select(s => CSharpSyntaxTree.ParseText(s, encoding: Encoding.UTF8)).ToArray();
            }
            else
            {
                trees = filenames.Select(fn => CSharpSyntaxTree.ParseText(File.ReadAllText(fn), null, fn, Encoding.UTF8)).ToArray();
            }

            string targetAssemblyPath = "";
            string pdbPath            = "";
            string targetAssemblyName;
            if (!generateInMemory)
            {
                targetAssemblyPath = Path.ChangeExtension(filenames[0], ".dll");
                try
                {
                    if (File.Exists(targetAssemblyPath))
                    {
                        File.Delete(targetAssemblyPath);
                    }
                }
                catch
                {
                    for (int i = 0; ; i++)
                    {
                        targetAssemblyPath = Path.ChangeExtension(Path.ChangeExtension(filenames[0], null) + DateTime.Now.Millisecond, ".dll");
                        try
                        {
                            if (File.Exists(targetAssemblyPath))
                            {
                                File.Delete(targetAssemblyPath);
                            }
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
                targetAssemblyName = Path.GetFileNameWithoutExtension(targetAssemblyPath);
                pdbPath            = Path.ChangeExtension(targetAssemblyPath, ".pdb");
                emitOptions        = emitOptions.WithPdbFilePath(pdbPath);
            }
            else
            {
                targetAssemblyName = Guid.NewGuid().ToString(); // Empty names are not allowed
            }

            Compilation compilation    = CSharpCompilation.Create(targetAssemblyName, trees, references, options);
            Assembly    resultAssembly = null;
            EmitResult  result;
            using (Stream assemblyStream = generateInMemory ? (Stream) new MemoryStream() : File.Create(targetAssemblyPath))
            {
                using (Stream pdbStream = generateInMemory ? (Stream) new MemoryStream() : File.Create(pdbPath))
                {
                    if (emitOptions.DebugInformationFormat == DebugInformationFormat.Embedded)
                    {
                        result = compilation.Emit(assemblyStream, options: emitOptions);
                    }
                    else
                    {
                        result = compilation.Emit(assemblyStream, pdbStream, options: emitOptions);
                    }
                    if (result.Success)
                    {
                        // TODO: allow compiled assemblies to be unloaded
                        assemblyStream.Seek(0, SeekOrigin.Begin);
                        var asmBin = new BinaryReader(assemblyStream).ReadBytes((int)assemblyStream.Length);
                        if (emitOptions.DebugInformationFormat == DebugInformationFormat.Embedded)
                        {
                            resultAssembly = Assembly.Load(asmBin);
                        }
                        else
                        {
                            pdbStream.Seek(0, SeekOrigin.Begin);
                            var pdbBin = new BinaryReader(pdbStream).ReadBytes((int)pdbStream.Length);
                            resultAssembly = Assembly.Load(asmBin, pdbBin);
                        }
                    }
                }
            }
            cr = new CompilerResults(resultAssembly, result.Success, result.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => d.ToString()).ToList());
            return(cr);
#else
            throw new NotSupportedException("This assembly was compiled without Roslyn support.  To use Roslyn, recompile with the ROSLYN compiler flag.");
#endif
        }