private static void Method7() { var work = MSBuildWorkspace.Create(); var solution = work.OpenSolutionAsync(@"..\..\..\RoslynPlayGround.sln").Result; var project = solution.Projects.FirstOrDefault(p => p.Name == "CodeGenerationWithRoslyn"); if (project == null) { throw new Exception("Could not find the CodeGenerationWithRoslyn Project"); } // Provide compilation options var options = new CS.CSharpCompilationOptions( Microsoft.CodeAnalysis.OutputKind.ConsoleApplication, optimizationLevel: Microsoft.CodeAnalysis.OptimizationLevel.Release, platform: Microsoft.CodeAnalysis.Platform.X64); project = project.WithCompilationOptions(options); var compilation = project.GetCompilationAsync().Result; // Do something with the compilation var memory = new MemoryStream(); var results = compilation.Emit(memory); if (!results.Success) { foreach (var item in results.Diagnostics) { if (item.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error) { Console.WriteLine(item.GetMessage()); } } } var assembly = Assembly.Load(memory.ToArray()); var types = assembly.GetTypes(); var greetingRules = types.FirstOrDefault(t => t.Name == "GreetingRules"); if (greetingRules == null) { throw new Exception("Could not find the type, GreetingRules"); } foreach (var method in greetingRules.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public)) { Console.WriteLine(method.Name); } }
private static Compilation CreateCompilationFromAssembly(IEnumerable <string> assemblyPaths) { try { List <string> paths = assemblyPaths.ToList(); //TODO: "mscorlib" should be ignored while extracting metadata from .NET Core/.NET Framework paths.Add(typeof(object).Assembly.Location); List <PortableExecutableReference> assemblies = (from path in paths select MetadataReference.CreateFromFile(path)).ToList(); CS.CSharpCompilationOptions options = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); return(CS.CSharpCompilation.Create("EmptyProjectWithAssembly", new SyntaxTree[] { }, assemblies, options)); } catch (Exception e) { Logger.Log(LogLevel.Warning, $"Error generating compilation from assemblies {string.Join(Environment.NewLine, assemblyPaths)}: {e.Message}. Ignored."); return(null); } }
// TODO: implement resources https://stackoverflow.com/a/26853131/2350244 private static CS.CSharpCompilation CreateCSharpCompilation( IEnumerable <string> sourceFiles, string assemblyName, IEnumerable <string> references, IEnumerable <string> defines, out List <string> messages ) { // parse the source files var parseOpts = CS.CSharpParseOptions.Default .WithLanguageVersion(MaxCSharpLanguageVersion) .WithPreprocessorSymbols(defines); // and build syntax tree List <SyntaxTree> syntaxTrees = new List <SyntaxTree>(); foreach (var sourceFile in sourceFiles) { syntaxTrees.Add( CS.CSharpSyntaxTree.ParseText( text: File.ReadAllText(sourceFile), options: parseOpts, path: sourceFile, encoding: Encoding.UTF8 ) ); } // collect references var refs = new List <string>(); // add mscorelib refs.Add(typeof(object).Assembly.Location); foreach (var refFile in references) { refs.Add(refFile); } messages = new List <string>(); messages.Add($"Define: {string.Join(";", defines)}"); var mdataRefs = new List <MetadataReference>(); foreach (var refPath in refs) { messages.Add($"Reference: {refPath}"); mdataRefs.Add( AssemblyMetadata.CreateFromFile(refPath).GetReference() ); } // compile options var compileOpts = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithOverflowChecks(true) .WithPlatform(Platform.X64) .WithOptimizationLevel(OptimizationLevel.Release); // create compilation job return(CS.CSharpCompilation.Create( assemblyName: assemblyName, syntaxTrees: syntaxTrees, references: mdataRefs, options: compileOpts )); }
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)); }