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 }
public override CompilationOptions CreateCompilationOptions() { var project = (CSharpProject)ParentProject; var options = new CSharpCompilationOptions( OutputKind.ConsoleApplication, false, null, project.MainClass, "Script", null, OptimizationLevel.Debug, GenerateOverflowChecks, UnsafeCode, null, ParentConfiguration.SignAssembly ? ParentConfiguration.AssemblyKeyFile : null, ImmutableArray <byte> .Empty, null, Microsoft.CodeAnalysis.Platform.AnyCpu, ReportDiagnostic.Default, WarningLevel, null, false, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default, strongNameProvider: new DesktopStrongNameProvider() ); return(options.WithPlatform(GetPlatform()) .WithGeneralDiagnosticOption(TreatWarningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default) .WithOptimizationLevel(Optimize ? OptimizationLevel.Release : OptimizationLevel.Debug) .WithSpecificDiagnosticOptions(GetSuppressedWarnings().ToDictionary( suppress => suppress, _ => ReportDiagnostic.Suppress))); }
public void Platform_RoundTrip(Platform platform) { var original = CreateCompilation( "class C { static void Main() { } }", options: BaseCSharpCompilationOptions.WithPlatform(platform), sourceFileName: "test.cs"); VerifyRoundTrip(original); }
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); }
public static Compilation CreateLibraryCompilation(string assemblyName, bool enableOptimisations, MetadataReference[] references) { var options = new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, optimizationLevel: enableOptimisations ? OptimizationLevel.Release : OptimizationLevel.Debug, allowUnsafe: true); options = options.WithPlatform(Platform.X64); return(CSharpCompilation.Create(assemblyName, options: options, references: references)); }
public override CompilationOptions CreateCompilationOptions() { var project = (CSharpProject)ParentProject; var workspace = Ide.TypeSystem.TypeSystemService.GetWorkspace(project.ParentSolution); var metadataReferenceResolver = CreateMetadataReferenceResolver( workspace.Services.GetService <IMetadataService> (), project.BaseDirectory, ParentConfiguration.OutputDirectory ); var options = new CSharpCompilationOptions( OutputKind.ConsoleApplication, false, null, project.MainClass, "Script", null, OptimizationLevel.Debug, GenerateOverflowChecks, UnsafeCode, null, ParentConfiguration.SignAssembly ? ParentConfiguration.AssemblyKeyFile : null, ImmutableArray <byte> .Empty, null, Microsoft.CodeAnalysis.Platform.AnyCpu, ReportDiagnostic.Default, WarningLevel, null, false, metadataReferenceResolver: metadataReferenceResolver, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default, strongNameProvider: new DesktopStrongNameProvider() ); return(options.WithPlatform(GetPlatform()) .WithGeneralDiagnosticOption(TreatWarningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default) .WithOptimizationLevel(Optimize ? OptimizationLevel.Release : OptimizationLevel.Debug) .WithSpecificDiagnosticOptions(GetSpecificDiagnosticOptions())); }
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); } }
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()); } } }
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); }
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); }
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)); }
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(); */ }