private static CSharpCompilationOptions GetCompilationOptions(ICompilerOptions compilerOptions) { var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); string platformValue = compilerOptions.Platform; bool allowUnsafe = compilerOptions.AllowUnsafe ?? false; bool optimize = compilerOptions.Optimize ?? false; bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false; bool strongName = compilerOptions.StrongName ?? false; Platform platform; if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform)) { platform = Platform.AnyCpu; } return(options.WithAllowUnsafe(allowUnsafe) .WithPlatform(platform) .WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default) .WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug) .WithCryptoKeyFile(compilerOptions.KeyFile) .WithDelaySign(compilerOptions.DelaySign) .WithCryptoPublicKey(strongName ? StrongNameKey : ImmutableArray <byte> .Empty)); }
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 }
private static CSharpCompilationOptions GetCompilationOptions(JToken compilationOptions) { if (compilationOptions == null) { return(null); } var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithHighEntropyVirtualAddressSpace(true); bool allowUnsafe = GetValue <bool>(compilationOptions, "allowUnsafe"); string platformValue = GetValue <string>(compilationOptions, "platform"); bool warningsAsErrors = GetValue <bool>(compilationOptions, "warningsAsErrors"); Platform platform; if (!Enum.TryParse <Platform>(platformValue, out platform)) { platform = Platform.AnyCPU; } ReportWarning warningOption = warningsAsErrors ? ReportWarning.Error : ReportWarning.Default; return(options.WithAllowUnsafe(allowUnsafe) .WithPlatform(platform) .WithGeneralWarningOption(warningOption)); }
public static CSharpCompilationOptions CreateCompilationOptions(this ProjectFileInfo projectFileInfo) { var result = new CSharpCompilationOptions(projectFileInfo.OutputKind); result = result.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (projectFileInfo.AllowUnsafeCode) { result = result.WithAllowUnsafe(true); } result = result.WithSpecificDiagnosticOptions(CompilationOptionsHelper.GetDefaultSuppressedDiagnosticOptions(projectFileInfo.SuppressedDiagnosticIds)); if (projectFileInfo.SignAssembly && !string.IsNullOrEmpty(projectFileInfo.AssemblyOriginatorKeyFile)) { var keyFile = Path.Combine(projectFileInfo.Directory, projectFileInfo.AssemblyOriginatorKeyFile); result = result.WithStrongNameProvider(new DesktopStrongNameProvider()) .WithCryptoKeyFile(keyFile); } if (!string.IsNullOrWhiteSpace(projectFileInfo.DocumentationFile)) { result = result.WithXmlReferenceResolver(XmlFileResolver.Default); } return(result); }
private static CSharpCompilationOptions GetCompilationOptions(CompilerOptions compilerOptions) { var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); string platformValue = compilerOptions.Platform; bool allowUnsafe = compilerOptions.AllowUnsafe ?? false; bool optimize = compilerOptions.Optimize ?? false; bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false; Platform platform; if (!Enum.TryParse <Platform>(value: platformValue, ignoreCase: true, result: out platform)) { platform = Platform.AnyCpu; } ReportDiagnostic warningOption = warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default; return(options.WithAllowUnsafe(allowUnsafe) .WithPlatform(platform) .WithGeneralDiagnosticOption(warningOption) .WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug)); }
private static CSharpCompilationOptions GetCompilationOptions(ICompilerOptions compilerOptions, string projectDirectory) { var outputKind = compilerOptions.EmitEntryPoint.GetValueOrDefault() ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary; var options = new CSharpCompilationOptions(outputKind); string platformValue = compilerOptions.Platform; bool allowUnsafe = compilerOptions.AllowUnsafe ?? false; bool optimize = compilerOptions.Optimize ?? false; bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false; Platform platform; if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform)) { platform = Platform.AnyCpu; } options = options .WithAllowUnsafe(allowUnsafe) .WithPlatform(platform) .WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default) .WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug); return AddSigningOptions(options, compilerOptions, projectDirectory); }
private static CSharpCompilationOptions GetCompilationOptions(CommonCompilerOptions compilerOptions, string projectDirectory) { var outputKind = compilerOptions.EmitEntryPoint.GetValueOrDefault() ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary; var options = new CSharpCompilationOptions(outputKind); string platformValue = compilerOptions.Platform; bool allowUnsafe = compilerOptions.AllowUnsafe ?? false; bool optimize = compilerOptions.Optimize ?? false; bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false; Microsoft.CodeAnalysis.Platform platform; if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform)) { platform = Microsoft.CodeAnalysis.Platform.AnyCpu; } options = options .WithAllowUnsafe(allowUnsafe) .WithPlatform(platform) .WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default) .WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug); return(AddSigningOptions(options, compilerOptions, projectDirectory)); }
private CSharpCompilationOptions CreateCompilationOptions() { var csharpCommandLineArguments = _commandLineArgs.Value; // if RSP file was used, pick namespaces from there // otherwise use default set of namespaces var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: csharpCommandLineArguments != null ? csharpCommandLineArguments.CompilationOptions.Usings : DefaultNamespaces); foreach (var ns in compilationOptions.Usings) { _logger.LogDebug($"CSX global using statement: {ns}"); } if (csharpCommandLineArguments != null) { foreach (var error in csharpCommandLineArguments.Errors) { _logger.LogError($"CSX RSP parse error. {error.GetMessage()}"); } } var metadataReferenceResolver = CreateMetadataReferenceResolver(csharpCommandLineArguments?.ReferencePaths); var sourceResolver = CreateScriptSourceResolver(csharpCommandLineArguments?.SourcePaths); compilationOptions = compilationOptions .WithAllowUnsafe(true) .WithMetadataReferenceResolver(metadataReferenceResolver) .WithSourceReferenceResolver(sourceResolver) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default) .WithSpecificDiagnosticOptions(!_scriptOptions.IsNugetEnabled() ? CompilationOptionsHelper.GetDefaultSuppressedDiagnosticOptions() : CompilationOptionsHelper.GetDefaultSuppressedDiagnosticOptions(_scriptOptions.NullableDiagnostics)); // for .NET Core 3.0 dotnet-script use extra nullable diagnostics var topLevelBinderFlagsProperty = typeof(CSharpCompilationOptions).GetProperty(TopLevelBinderFlagsProperty, BindingFlags.Instance | BindingFlags.NonPublic); var binderFlagsType = typeof(CSharpCompilationOptions).GetTypeInfo().Assembly.GetType(BinderFlagsType); var ignoreCorLibraryDuplicatedTypesMember = binderFlagsType?.GetField(IgnoreCorLibraryDuplicatedTypesField, BindingFlags.Static | BindingFlags.Public); var ignoreCorLibraryDuplicatedTypesValue = ignoreCorLibraryDuplicatedTypesMember?.GetValue(null); if (ignoreCorLibraryDuplicatedTypesValue != null) { topLevelBinderFlagsProperty?.SetValue(compilationOptions, ignoreCorLibraryDuplicatedTypesValue); } // in scripts, the option to supersede lower versions is ALWAYS enabled // see: https://github.com/dotnet/roslyn/blob/version-2.6.0-beta3/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs#L199 var referencesSupersedeLowerVersionsProperty = typeof(CompilationOptions).GetProperty(ReferencesSupersedeLowerVersionsProperty, BindingFlags.Instance | BindingFlags.NonPublic); referencesSupersedeLowerVersionsProperty?.SetValue(compilationOptions, true); return(compilationOptions); }
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)..];
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); }
private static CSharpCompilationOptions CreateCompilationOptions(ProjectFileInfo projectFileInfo) { var result = new CSharpCompilationOptions(projectFileInfo.OutputKind); result = result.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (projectFileInfo.AllowUnsafeCode) { result = result.WithAllowUnsafe(true); } var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>(projectFileInfo.SuppressedDiagnosticIds.Count) { // Ensure that specific warnings about assembly references are always suppressed. { "CS1701", ReportDiagnostic.Suppress }, { "CS1702", ReportDiagnostic.Suppress }, { "CS1705", ReportDiagnostic.Suppress } }; if (projectFileInfo.SuppressedDiagnosticIds.Any()) { foreach (var id in projectFileInfo.SuppressedDiagnosticIds) { if (!specificDiagnosticOptions.ContainsKey(id)) { specificDiagnosticOptions.Add(id, ReportDiagnostic.Suppress); } } } result = result.WithSpecificDiagnosticOptions(specificDiagnosticOptions); if (projectFileInfo.SignAssembly && !string.IsNullOrEmpty(projectFileInfo.AssemblyOriginatorKeyFile)) { var keyFile = Path.Combine(projectFileInfo.Directory, projectFileInfo.AssemblyOriginatorKeyFile); result = result.WithStrongNameProvider(new DesktopStrongNameProvider()) .WithCryptoKeyFile(keyFile); } if (!string.IsNullOrWhiteSpace(projectFileInfo.DocumentationFile)) { result = result.WithXmlReferenceResolver(XmlFileResolver.Default); } return(result); }
public static CSharpCompilationOptions CreateCompilationOptions(this ProjectFileInfo projectFileInfo) { var compilationOptions = new CSharpCompilationOptions(projectFileInfo.OutputKind); compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default) .WithSpecificDiagnosticOptions(projectFileInfo.GetDiagnosticOptions()) .WithOverflowChecks(projectFileInfo.CheckForOverflowUnderflow); if (projectFileInfo.AllowUnsafeCode) { compilationOptions = compilationOptions.WithAllowUnsafe(true); } if (projectFileInfo.TreatWarningsAsErrors) { compilationOptions = compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Error); } if (projectFileInfo.NullableContextOptions != compilationOptions.NullableContextOptions) { compilationOptions = compilationOptions.WithNullableContextOptions(projectFileInfo.NullableContextOptions); } if (projectFileInfo.SignAssembly && !string.IsNullOrEmpty(projectFileInfo.AssemblyOriginatorKeyFile)) { var keyFile = Path.Combine(projectFileInfo.Directory, projectFileInfo.AssemblyOriginatorKeyFile); compilationOptions = compilationOptions.WithStrongNameProvider(new DesktopStrongNameProvider()) .WithCryptoKeyFile(keyFile); } if (!string.IsNullOrWhiteSpace(projectFileInfo.DocumentationFile)) { compilationOptions = compilationOptions.WithXmlReferenceResolver(XmlFileResolver.Default); } return(compilationOptions); }
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()); } } }
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(); */ }
public void Initalize(IConfiguration configuration) { _options = new MSBuildOptions(); OptionsServices.ReadProperties(_options, configuration); var solutionFilePath = _env.SolutionFilePath; if (string.IsNullOrEmpty(solutionFilePath)) { var solutions = Directory.GetFiles(_env.Path, "*.sln"); var result = SolutionPicker.ChooseSolution(_env.Path, solutions); if (result.Message != null) { _logger.LogInformation(result.Message); } if (result.Solution == null) { return; } solutionFilePath = result.Solution; } SolutionFile solutionFile = null; _context.SolutionPath = solutionFilePath; using (var stream = File.OpenRead(solutionFilePath)) { using (var reader = new StreamReader(stream)) { solutionFile = SolutionFile.Parse(reader); } } _logger.LogInformation($"Detecting projects in '{solutionFilePath}'."); foreach (var block in solutionFile.ProjectBlocks) { if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid)) { if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid) { _logger.LogWarning("Skipped unsupported project type '{0}'", block.ProjectPath); continue; } } if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid)) { continue; } var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar)))); _logger.LogInformation($"Loading project from '{projectFilePath}'."); var projectFileInfo = CreateProject(projectFilePath); if (projectFileInfo == null) { continue; } var compilationOptions = new CSharpCompilationOptions(projectFileInfo.OutputKind); #if DNX451 compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); #endif if (projectFileInfo.AllowUnsafe) { compilationOptions = compilationOptions.WithAllowUnsafe(true); } var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name), VersionStamp.Create(), projectFileInfo.Name, projectFileInfo.AssemblyName, LanguageNames.CSharp, projectFileInfo.ProjectFilePath, compilationOptions: compilationOptions); _workspace.AddProject(projectInfo); projectFileInfo.WorkspaceId = projectInfo.Id; _context.Projects[projectFileInfo.ProjectFilePath] = projectFileInfo; _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id; _watcher.Watch(projectFilePath, OnProjectChanged); } foreach (var projectFileInfo in _context.Projects.Values) { UpdateProject(projectFileInfo); } }
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 void Initalize(IConfiguration configuration) { _options = new MSBuildOptions(); OptionsServices.ReadProperties(_options, configuration); var solutionFilePath = _env.SolutionFilePath; if (string.IsNullOrEmpty(solutionFilePath)) { var solutions = Directory.GetFiles(_env.Path, "*.sln"); var result = SolutionPicker.ChooseSolution(_env.Path, solutions); if (result.Message != null) { _logger.LogInformation(result.Message); } if (result.Solution == null) { return; } solutionFilePath = result.Solution; } SolutionFile solutionFile = null; _context.SolutionPath = solutionFilePath; using (var stream = File.OpenRead(solutionFilePath)) { using (var reader = new StreamReader(stream)) { solutionFile = SolutionFile.Parse(reader); } } _logger.LogInformation($"Detecting projects in '{solutionFilePath}'."); foreach (var block in solutionFile.ProjectBlocks) { if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid)) { if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid) { _logger.LogWarning("Skipped unsupported project type '{0}'", block.ProjectPath); continue; } } if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid)) { continue; } var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar)))); _logger.LogInformation($"Loading project from '{projectFilePath}'."); var projectFileInfo = CreateProject(projectFilePath); if (projectFileInfo == null) { continue; } var compilationOptions = new CSharpCompilationOptions(projectFileInfo.OutputKind); #if DNX451 compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); #endif if (projectFileInfo.AllowUnsafe) { compilationOptions = compilationOptions.WithAllowUnsafe(true); } var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name), VersionStamp.Create(), projectFileInfo.Name, projectFileInfo.AssemblyName, LanguageNames.CSharp, projectFileInfo.ProjectFilePath, compilationOptions: compilationOptions); _workspace.AddProject(projectInfo); projectFileInfo.WorkspaceId = projectInfo.Id; _context.Projects[projectFileInfo.ProjectFilePath] = projectFileInfo; _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id; _watcher.Watch(projectFilePath, OnProjectChanged); } foreach (var projectFileInfo in _context.Projects.Values) { UpdateProject(projectFileInfo); } }
public void Initalize(IConfiguration configuration) { _options = new MSBuildOptions(); ConfigurationBinder.Bind(configuration, _options); if (_options.WaitForDebugger) { Console.WriteLine($"Attach to process {System.Diagnostics.Process.GetCurrentProcess().Id}"); while (!System.Diagnostics.Debugger.IsAttached) { System.Threading.Thread.Sleep(100); } } var solutionFilePath = _env.SolutionFilePath; if (string.IsNullOrEmpty(solutionFilePath)) { var solutions = Directory.GetFiles(_env.Path, "*.sln"); var result = SolutionPicker.ChooseSolution(_env.Path, solutions); if (result.Message != null) { _logger.LogInformation(result.Message); } if (result.Solution == null) { return; } solutionFilePath = result.Solution; } SolutionFile solutionFile = null; _context.SolutionPath = solutionFilePath; using (var stream = File.OpenRead(solutionFilePath)) { using (var reader = new StreamReader(stream)) { solutionFile = SolutionFile.Parse(reader); } } _logger.LogInformation($"Detecting projects in '{solutionFilePath}'."); foreach (var block in solutionFile.ProjectBlocks) { if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid)) { if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid) { _logger.LogWarning("Skipped unsupported project type '{0}'", block.ProjectPath); continue; } } if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid)) { continue; } var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar)))); _logger.LogInformation($"Loading project from '{projectFilePath}'."); var projectFileInfo = CreateProject(projectFilePath); if (projectFileInfo == null) { continue; } var compilationOptions = new CSharpCompilationOptions(projectFileInfo.OutputKind); compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (projectFileInfo.AllowUnsafe) { compilationOptions = compilationOptions.WithAllowUnsafe(true); } if (projectFileInfo.SignAssembly && !string.IsNullOrEmpty(projectFileInfo.AssemblyOriginatorKeyFile)) { var keyFile = Path.Combine(projectFileInfo.ProjectDirectory, projectFileInfo.AssemblyOriginatorKeyFile); compilationOptions = compilationOptions.WithStrongNameProvider(new DesktopStrongNameProvider()) .WithCryptoKeyFile(keyFile); } if (projectFileInfo.GenerateXmlDocumentation) { compilationOptions = compilationOptions.WithXmlReferenceResolver(XmlFileResolver.Default); } var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name), VersionStamp.Create(), projectFileInfo.Name, projectFileInfo.AssemblyName, LanguageNames.CSharp, projectFileInfo.ProjectFilePath, compilationOptions: compilationOptions); _workspace.AddProject(projectInfo); projectFileInfo.WorkspaceId = projectInfo.Id; _context.Projects[projectFileInfo.ProjectFilePath] = projectFileInfo; _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id; _watcher.Watch(projectFilePath, OnProjectChanged); } foreach (var projectFileInfo in _context.Projects.Values) { UpdateProject(projectFileInfo); } }
private static CSharpCompilationOptions GetCompilationOptions(ICompilerOptions compilerOptions) { var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); string platformValue = compilerOptions.Platform; bool allowUnsafe = compilerOptions.AllowUnsafe ?? false; bool optimize = compilerOptions.Optimize ?? false; bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false; Platform platform; if (!Enum.TryParse<Platform>(value: platformValue, ignoreCase: true, result: out platform)) { platform = Platform.AnyCpu; } ReportDiagnostic warningOption = warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default; return options.WithAllowUnsafe(allowUnsafe) .WithPlatform(platform) .WithGeneralDiagnosticOption(warningOption) .WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug); }
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)); }
private static CSharpCompilationOptions GetCompilationOptions(ICompilerOptions compilerOptions) { var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); string platformValue = compilerOptions.Platform; bool allowUnsafe = compilerOptions.AllowUnsafe ?? false; bool optimize = compilerOptions.Optimize ?? false; bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false; bool strongName = compilerOptions.StrongName ?? false; Platform platform; if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform)) { platform = Platform.AnyCpu; } return options.WithAllowUnsafe(allowUnsafe) .WithPlatform(platform) .WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default) .WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug) .WithCryptoKeyFile(compilerOptions.KeyFile) .WithDelaySign(compilerOptions.DelaySign) .WithCryptoPublicKey(strongName ? StrongNameKey : ImmutableArray<byte>.Empty); }
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); }