private static CSharpCompilation BuildCompilation(CompilerArguments compilerArguments) { CSharpCompilation compilation = CSharpCompilation.Create(compilerArguments.FileName) .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication)) .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); var netStandardAssembly = Assembly.Load(new AssemblyName("netstandard")); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(netStandardAssembly.Location)); AssemblyName[] netStandardAssemblies = netStandardAssembly.GetReferencedAssemblies(); foreach (var assembly in netStandardAssemblies) { string assemblyLocation = Assembly.Load(assembly).Location; compilation = compilation.AddReferences(MetadataReference.CreateFromFile(assemblyLocation)); } List <SyntaxTree> syntaxTrees = new List <SyntaxTree>(); foreach (var sourceCode in compilerArguments.Sources) { syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(sourceCode)); } compilation = compilation.AddSyntaxTrees(syntaxTrees); return(compilation); }
public void UpdateCompilationReplacesOriginalMetadataReference() { MetadataReference original = GetExampleMetadataReference1(); MetadataReference replaced = GetExampleMetadataReference2(); CSharpCompilation compilation = _compilation.AddReferences(original); Data.CompilationData data = new(compilation); data.UpdateCompilation(original, replaced); Assert.True(data.Compilation is not null && data.Compilation != compilation && data.Compilation.References.Contains(replaced) && !data.Compilation.References.Contains(original)); }
private static MetadataReference GetInMemoryAssemblyReferenceForCode([NotNull] string code, [NotNull][ItemNotNull] params MetadataReference[] references) { SyntaxTree tree = CSharpSyntaxTree.ParseText(code); CSharpCompilation compilation = CSharpCompilation.Create("TempAssembly", new[] { tree }) .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); PortableExecutableReference msCorLib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); compilation = compilation.AddReferences(msCorLib); compilation = compilation.AddReferences(references); return(compilation.ToMetadataReference()); }
private void Save() { if (Options.FullCompile) { var bindingsAssemblyPath = bindingCompiler.OutputFileName; var(builder, fields) = configuration.ServiceProvider.GetService <RefObjectSerializer>().CreateBuilder(configuration); bindingCompiler.AddSerializedObjects(ObjectsClassName, builder, fields); bindingCompiler.SaveAssembly(); Program2.WriteInfo($"Bindings saved to {bindingsAssemblyPath}."); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(Path.GetFullPath(bindingsAssemblyPath))); var compiledViewsFileName = Path.Combine(Options.OutputPath, Options.AssemblyName + "_Views" + ".dll"); var result = compilation.Emit(compiledViewsFileName); if (!result.Success) { throw new Exception("The compilation failed!"); } //TODO: merge emitted assemblies //var merger = new ILMerging.ILMerge() { // OutputFile = Path.Combine(Options.OutputPath, Options.AssemblyName + ".dll"), //}; //merger.SetInputAssemblies(new[] { compiledViewsFileName, bindingsAssemblyPath }); //merger.SetSearchDirectories(new[] { Path.GetDirectoryName(Options.WebSiteAssembly) }); //merger.Merge(); //File.Delete(compiledViewsFileName); //File.Delete(bindingsAssemblyPath); Program2.WriteInfo($"Compiled views saved to {compiledViewsFileName}."); } }
protected CSharpCompilation CreateCompilation(SyntaxTree syntaxTree) { CSharpCompilation compilation = CSharpCompilation.Create("ExamineSnippet"); HashSet <string> locations = new HashSet <string>(); locations.Add(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll"); foreach (SyntaxNode syntaxNode in syntaxTree.GetRoot().DescendantNodes().Where(d => d.Kind() == SyntaxKind.UsingDirective)) { string nodeContent = syntaxNode.ToString(); if (assemblyReferenceMappings.ContainsKey(nodeContent)) { foreach (Type type in assemblyReferenceMappings[nodeContent]) { if (!locations.Contains(type.Assembly.Location)) { locations.Add(type.Assembly.Location); } } } else { throw new Exception($"{nodeContent} not found in assembly mappings."); } } foreach (string location in locations) { compilation = compilation.AddReferences(MetadataReference.CreateFromFile(location)); } return(compilation.AddSyntaxTrees(syntaxTree)); }
public static CSharpCompilation AddReferenceFromType(this CSharpCompilation compilation, Type type) { var assembly = type.GetTypeInfo().Assembly.Location; Console.WriteLine("Adding Reference:" + assembly); return(compilation.AddReferences(MetadataReference.CreateFromFile(assembly, MetadataReferenceProperties.Assembly))); }
private Assembly Compile(string code) { CSharpCompilation compilation = CSharpCompilation.Create("assemblyName") .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddSyntaxTrees(CSharpSyntaxTree.ParseText(code)); var coreDir = Directory.GetParent(typeof(Enumerable).GetTypeInfo().Assembly.Location); compilation = compilation.AddReferences( MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(JsonConvert).Assembly.Location), MetadataReference.CreateFromFile(typeof(GeneratedCodeAttribute).Assembly.Location), MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Runtime.dll"), MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Dynamic.Runtime.dll"), MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.IO.dll"), MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Linq.dll"), MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.ObjectModel.dll"), MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Linq.Expressions.dll"), MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Runtime.Extensions.dll")); using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); if (!result.Success) { throw new Exception(String.Join(", ", result.Diagnostics .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error) .Select(d => d.Location.GetLineSpan().StartLinePosition + " - " + d.GetMessage())) + "\n" + code); } return(Assembly.Load(stream.GetBuffer())); } }
internal static IAssemblySymbol GetAssemblyFromSyntaxWithReferences(string syntax, IEnumerable <string> referencesSyntax, bool enableNullable = false, bool includeDefaultReferences = false, [CallerMemberName] string assemblyName = "") { CSharpCompilation compilation = CreateCSharpCompilationFromSyntax(syntax, assemblyName, enableNullable, includeDefaultReferences); CSharpCompilation compilationWithReferences = CreateCSharpCompilationFromSyntax(referencesSyntax, $"{assemblyName}_reference", enableNullable, includeDefaultReferences); compilation = compilation.AddReferences(compilationWithReferences.ToMetadataReference()); return(compilation.Assembly); }
public ScriptLoader(string generatedScriptOutput = null) { var suppressions = new Dictionary <string, ReportDiagnostic> { { "CS1998", ReportDiagnostic.Suppress } }; var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, specificDiagnosticOptions: suppressions, optimizationLevel: OptimizationLevel.Debug, platform: Platform.AnyCpu); var baseLibPath = Path.GetDirectoryName(typeof(object).Assembly.Location); var tpa = (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"); this.generatedScriptOutput = generatedScriptOutput; this.compilation = CSharpCompilation.Create(AssemblyName, options: compilationOptions) .AddReferences(MetadataReference.CreateFromFile(typeof(ScriptLoader).Assembly.Location)) .AddReferences(MetadataReference.CreateFromFile(Path.Combine(baseLibPath, "mscorlib.dll"))) .AddReferences(MetadataReference.CreateFromFile(Path.Combine(baseLibPath, "System.dll"))) .AddReferences(MetadataReference.CreateFromFile(Path.Combine(baseLibPath, "System.Core.dll"))); foreach (var asmPath in tpa.Split(';')) { this.compilation = this.compilation.AddReferences( MetadataReference.CreateFromFile(asmPath)); } foreach (var reference in typeof(ScriptLoader).Assembly.GetReferencedAssemblies()) { if (reference.CodeBase != null) { compilation = compilation.AddReferences(MetadataReference.CreateFromFile(reference.CodeBase)); } } var targetFrameworkUnit = SyntaxFactory.CompilationUnit() .AddAttributeLists( SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName( SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Runtime")), SyntaxFactory.IdentifierName("Versioning")), SyntaxFactory.IdentifierName("TargetFrameworkAttribute"))) .AddArgumentListArguments( SyntaxFactory.AttributeArgument(SyntaxUtil.LiteralExpression(".NETStandard,Version=v2.1")), SyntaxFactory.AttributeArgument(SyntaxUtil.LiteralExpression("")) .WithNameEquals(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName("FrameworkDisplayName")))))) .WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)))); this.compilation = this.compilation.AddSyntaxTrees(targetFrameworkUnit.SyntaxTree); }
public async ValueTask <CSharpCompilation> EnrichAsync(CSharpCompilation target, CancellationToken cancellationToken = default) { List <MetadataReference> references = await _referenceGenerators .ToAsyncEnumerable() .SelectMany(p => p.Generate(cancellationToken)) .ToListAsync(cancellationToken); return(target.AddReferences(references)); }
internal static IAssemblySymbol GetAssemblyFromSyntaxWithReferences(string syntax, IEnumerable <string> referencesSyntax, bool enableNullable = false, byte[] publicKey = null, [CallerMemberName] string assemblyName = "") { CSharpCompilation compilation = CreateCSharpCompilationFromSyntax(syntax, assemblyName, enableNullable, publicKey); CSharpCompilation compilationWithReferences = CreateCSharpCompilationFromSyntax(referencesSyntax, $"{assemblyName}_reference", enableNullable, publicKey); compilation = compilation.AddReferences(compilationWithReferences.ToMetadataReference()); Assert.Empty(compilation.GetDiagnostics()); return(compilation.Assembly); }
private static CSharpCompilation InstrumentProject(CSharpCompilation compiler, AssemblyMetadata interops, Workspace workspace) { compiler = compiler.AddReferences(interops.GetReference()); var oldToNew = compiler.SyntaxTrees.AsParallel().WithDegreeOfParallelism(8).Where(IsNotGeneratedCode).Select(t => InstrumentTree(t, workspace)); foreach (KeyValuePair <SyntaxTree, SyntaxTree> oldAndNew in oldToNew) { compiler = compiler.ReplaceSyntaxTree(oldAndNew.Key, oldAndNew.Value); Debug.Assert(oldAndNew.Value.GetText().ToString() != "{}"); } return(compiler); }
private static CSharpCompilation FixProject(IEnumerable <Document> documents, CSharpCompilation compiler, AssemblyMetadata interops) { compiler = compiler.AddReferences(interops.GetReference()); var oldToNew = documents.AsParallel().WithDegreeOfParallelism(8).Select(FixDocument); foreach (KeyValuePair <SyntaxTree, SyntaxTree> oldAndNew in oldToNew) { compiler = compiler.ReplaceSyntaxTree(oldAndNew.Key, oldAndNew.Value); Debug.Assert(oldAndNew.Value.GetText().ToString() != "{}"); } return(compiler); }
public async Task Success_When_ReferencesMainPackage() { CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation(); string dir = Path.GetDirectoryName(typeof(DependencyTests).Assembly.Location) !; string mainPath = Path.Combine(dir, "Durian.dll"); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(mainPath)); DependencyAnalyzer analyzer = new(); ImmutableArray <Diagnostic> diagnostics = await analyzer.RunAnalyzer(compilation); Assert.Empty(diagnostics); }
public async Task Error_When_ReferencesMainDurianPackageAndAnyDurianAnalyzerPackage() { CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation(); string dir = Path.GetDirectoryName(typeof(DependencyTests).Assembly.Location) !; string mainPath = Path.Combine(dir, "Durian.dll"); string analyzerPath = Path.Combine(dir, "Durian.Core.Analyzer.dll"); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(mainPath), MetadataReference.CreateFromFile(analyzerPath)); DependencyAnalyzer analyzer = new(); Assert.True(await analyzer.ProducesDiagnostic(compilation, DurianDiagnostics.DUR0007_DoNotReferencePackageIfManagerIsPresent)); }
private CSharpCompilation RefenenceUsingAssemblies(CSharpCompilation compilation) { var sysdllDirectory = Path.GetDirectoryName(typeof(object).Assembly.Location); //System.Collections var dllFiles = Directory.GetFiles(sysdllDirectory, "System.Collections*.dll").ToList(); //Directory.GetFiles(currentDirctory, "*.dll").ToList();//Directory.GetFiles(sysdllDirectory, "System*.dll").ToList(); dllFiles.AddRange(Directory.GetFiles(sysdllDirectory, "System.Collections*.dll")); dllFiles.AddRange(Directory.GetFiles(sysdllDirectory, "System.Data*.dll")); //dllFiles.AddRange(Directory.GetFiles(sysdllDirectory, "System.Net*.dll")); dllFiles.AddRange(Directory.GetFiles(sysdllDirectory, "System.Linq*.dll")); //dllFiles.AddRange(Directory.GetFiles(sysdllDirectory, "System.Text*.dll")); dllFiles.AddRange(Directory.GetFiles(sysdllDirectory, "System.Threading*.dll")); dllFiles.Add($"{sysdllDirectory}/System.IO.dll"); dllFiles.Add($"{sysdllDirectory}/netstandard.dll"); dllFiles.Add($"{sysdllDirectory}/System.Private.CoreLib.dll"); dllFiles.Add($"{sysdllDirectory}/System.Runtime.dll"); dllFiles.Add($"{sysdllDirectory}/System.ComponentModel.dll"); dllFiles.Add(typeof(Console).Assembly.Location); dllFiles.Add(Assembly.GetExecutingAssembly().Location); dllFiles.Add(typeof(CodeBuilder).Assembly.Location); foreach (var dllFile in _fixedAssemblyRefenceDlls) { compilation = compilation.AddReferences(MetadataReference.CreateFromFile(dllFile)); } foreach (var dllFile in dllFiles) { compilation = compilation.AddReferences(MetadataReference.CreateFromFile(dllFile)); } foreach (var dllFile in CodeAssembly.ShareDllFiles) { compilation = compilation.AddReferences(MetadataReference.CreateFromFile(dllFile)); } return(compilation); }
private MetadataReference CreateMetadataReferenceIfNeeded(string assembly) { // Roslyn doesn't support having two assemblies as references with the same identity and then getting the symbol for it. string fileName = Path.GetFileName(assembly); if (!_loadedAssemblies.TryGetValue(fileName, out MetadataReference reference)) { reference = MetadataReference.CreateFromFile(assembly); _loadedAssemblies.Add(fileName, reference); _cSharpCompilation = _cSharpCompilation.AddReferences(new MetadataReference[] { reference }); } return(reference); }
public async Task Warning_When_HasMultipleAnalyzerPackages_And_NoManager() { CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation(); string dir = Path.GetDirectoryName(typeof(DependencyTests).Assembly.Location) !; compilation = compilation.AddReferences( MetadataReference.CreateFromFile(Path.Combine(dir, "Durian.Core.Analyzer.dll")), MetadataReference.CreateFromFile(Path.Combine(dir, "Durian.InterfaceTargets.dll")) ); DependencyAnalyzer analyzer = new(); Assert.True(await analyzer.ProducesDiagnostic(compilation, DurianDiagnostics.DUR0008_MultipleAnalyzers)); }
public static CSharpCompilation AddCoreReference(this CSharpCompilation compilation) { var trustedPlatformAssemblies = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"); var libraries = ((String)trustedPlatformAssemblies).Split(Path.PathSeparator); foreach (var library in libraries) { Console.WriteLine("Adding Reference:" + library); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(library)); } return(compilation); }
private void Save() { if (Options.FullCompile) { var bindingsAssemblyPath = bindingCompiler.OutputFileName; bindingCompiler.SaveAssembly(); Program2.WriteInfo($"Bindings saved to {bindingsAssemblyPath}."); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(Path.GetFullPath(bindingsAssemblyPath))); var compiledViewsFileName = Path.Combine(Options.OutputPath, Options.AssemblyName + ".dll"); var result = compilation.Emit(compiledViewsFileName); if (!result.Success) { throw new Exception("The compilation failed!"); } Program2.WriteInfo($"Compiled views saved to {compiledViewsFileName}."); } }
private static CSharpCompilation AddGenericArgumentReferences(CSharpCompilation compilation, Type modelType) { Type[] genericArguments = modelType.GetGenericArguments(); foreach (var genericArgument in genericArguments) { var metadataReference = MetadataReference.CreateFromFile(genericArgument.Assembly.Location) as MetadataReference; if (compilation.References.All(mr => mr.Display != metadataReference.Display)) { compilation = compilation.AddReferences(metadataReference); } if (genericArgument.IsGenericType) { compilation = AddGenericArgumentReferences(compilation, genericArgument); } } return(compilation); }
private void Save() { if (Options.FullCompile) { var bindingsAssemblyPath = bindingCompiler.OutputFileName; bindingCompiler.SaveAssembly(); Program.WriteInfo("bindings saved to " + bindingsAssemblyPath); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(Path.GetFullPath(bindingsAssemblyPath))); var compiledViewsFileName = Path.Combine(Options.OutputPath, Options.AssemblyName + ".dll"); //Directory.CreateDirectory("outputCS"); //int i = 0; //foreach (var tree in compilation.SyntaxTrees) //{ // File.WriteAllText($"outputCS/file{i++}.cs", tree.GetRoot().NormalizeWhitespace().ToString()); //} var result = compilation.Emit(compiledViewsFileName); if (!result.Success) { throw new Exception("compilation failed"); } Program.WriteInfo("views saved to " + compiledViewsFileName); } }
/// <inheritdoc/> public byte[] Compile(string code, IEnumerable <KeyValuePair <string, string> > metadataPropertyKeys) { _ = code ?? throw new ArgumentNullException(nameof(code)); // Parse the code code = Parse(code, metadataPropertyKeys, _executionState); // Get the compilation CSharpParseOptions parseOptions = new CSharpParseOptions(); SourceText sourceText = SourceText.From(code, Encoding.UTF8); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceText, parseOptions, AssemblyName); CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithSpecificDiagnosticOptions(new Dictionary <string, ReportDiagnostic> { // ensure that specific warnings about assembly references are always suppressed // https://github.com/dotnet/roslyn/issues/5501 { "CS1701", ReportDiagnostic.Suppress }, { "CS1702", ReportDiagnostic.Suppress }, { "CS1705", ReportDiagnostic.Suppress }, // we don't care about unreachable code { "CS0162", ReportDiagnostic.Suppress }, }); // Get reference assemblies CompilationReferences references = new CompilationReferences(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { references.TryAddReference(assembly); } foreach (Assembly assembly in _executionState.ClassCatalog.GetAssemblies()) { references.TryAddReference(assembly); } references.TryAddReference(Assembly.GetEntryAssembly(), true); references.TryAddReference(Assembly.GetCallingAssembly(), true); references.TryAddReference(Assembly.GetExecutingAssembly(), true); // Create the compilation string assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); CSharpCompilation compilation = CSharpCompilation.Create(AssemblyName, new[] { syntaxTree }, references, compilationOptions); // For some reason, Roslyn really wants these added by filename // See http://stackoverflow.com/questions/23907305/roslyn-has-no-reference-to-system-runtime compilation = compilation.AddReferences( MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll"))); // Emit the assembly ILogger logger = _executionState.Services.GetRequiredService <ILogger <ScriptHelper> >(); using (MemoryStream ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); // Log warnings List <string> warningMessages = result.Diagnostics .Where(x => x.Severity == DiagnosticSeverity.Warning) .Select(GetCompilationErrorMessage) .ToList(); if (warningMessages.Count > 0) { logger.LogWarning( "{0} warnings compiling script:{1}{2}", warningMessages.Count, Environment.NewLine, string.Join(Environment.NewLine, warningMessages)); } // Log errors List <string> errorMessages = result.Diagnostics .Where(x => x.Severity == DiagnosticSeverity.Error) .Select(GetCompilationErrorMessage) .ToList(); if (errorMessages.Count > 0) { logger.LogError( "{0} errors compiling script:{1}{2}", errorMessages.Count, Environment.NewLine, string.Join(Environment.NewLine, errorMessages)); } // Throw for errors or not success if (!result.Success || errorMessages.Count > 0) { throw new ScriptCompilationException(errorMessages); } ms.Seek(0, SeekOrigin.Begin); return(ms.ToArray()); } }
// Internal for testing internal static string GenerateModuleConstructorMethods(Type moduleType, Dictionary <string, string> memberNames) { StringBuilder stringBuilder = new StringBuilder(); CSharpCompilation compilation = CSharpCompilation .Create("ScriptCtorMethodGen") .AddReferences(MetadataReference.CreateFromFile(moduleType.Assembly.Location)); foreach (AssemblyName referencedAssembly in moduleType.Assembly.GetReferencedAssemblies()) { try { compilation = compilation.AddReferences( MetadataReference.CreateFromFile(Assembly.Load(referencedAssembly).Location)); } catch (Exception) { // We don't care about problems loading referenced assemblies, just ignore them } } INamedTypeSymbol moduleSymbol = compilation.GetTypeByMetadataName(moduleType.FullName); bool foundInstanceConstructor = false; string moduleFullName = moduleSymbol.ToDisplayString(new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters)); string moduleName = moduleSymbol.ToDisplayString(new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters)); // Check to make sure we haven't already added a module with the same name string existingMemberName; if (memberNames.TryGetValue(moduleName, out existingMemberName)) { throw new Exception($"Could not add module {moduleFullName} because it was already defined in {existingMemberName}."); } memberNames.Add(moduleName, moduleFullName); foreach (IMethodSymbol ctorSymbol in moduleSymbol.InstanceConstructors .Where(x => x.DeclaredAccessibility == Accessibility.Public)) { foundInstanceConstructor = true; string ctorDisplayString = ctorSymbol.ToDisplayString(new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes)); string ctorCallDisplayString = ctorSymbol.ToDisplayString(new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut, memberOptions: SymbolDisplayMemberOptions.IncludeParameters)); stringBuilder.AppendFormat(@" {0} {1}{2} {{ return new {0}{3}; }}", moduleFullName, moduleName, ctorDisplayString.Substring(ctorDisplayString.IndexOf("(", StringComparison.Ordinal)), ctorCallDisplayString.Substring(ctorCallDisplayString.IndexOf("(", StringComparison.Ordinal))); } // Add a default constructor if we need to if (!foundInstanceConstructor) { stringBuilder.AppendFormat(@" {0} {1}() {{ return new {0}(); }}", moduleType.FullName, moduleType.Name); } return(stringBuilder.ToString()); }
public static Assembly Compile(string[] references, string name, params string[] codes) { string systemAsm = typeof(object).GetTypeInfo().Assembly.Location; string attributeAsm = typeof(System.Runtime.AssemblyTargetedPatchBandAttribute).GetTypeInfo().Assembly.Location; string vectorAsm = typeof(Vector3).GetTypeInfo().Assembly.Location; string consoleAsm = typeof(Console).GetTypeInfo().Assembly.Location; Encoding encoding = Encoding.UTF8; string assemblyName = Path.GetRandomFileName(); string symbolsName = Path.ChangeExtension(assemblyName, "pdb"); List <EmbeddedText> embeddedTexts = new List <EmbeddedText>(); List <SyntaxTree> encoded = new List <SyntaxTree>(); foreach (string code in codes) { string sourceCodePath = code.GetHashCode() + ".cs"; byte[] buffer = encoding.GetBytes(code); SourceText sourceText = SourceText.From(buffer, buffer.Length, encoding, canBeEmbedded: true); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText( sourceText, new CSharpParseOptions(), path: sourceCodePath); encoded.Add(CSharpSyntaxTree.Create(syntaxTree.GetRoot() as CSharpSyntaxNode, null, sourceCodePath, encoding)); embeddedTexts.Add(EmbeddedText.FromSource(sourceCodePath, sourceText)); } OptimizationLevel optimizationLevel = OptimizationLevel.Debug; #if !DEBUG optimizationLevel = OptimizationLevel.Release; #endif CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: encoded, references: new List <MetadataReference> { MetadataReference.CreateFromFile("ShaderLib.dll"), MetadataReference.CreateFromFile(systemAsm), MetadataReference.CreateFromFile(attributeAsm), MetadataReference.CreateFromFile(vectorAsm), MetadataReference.CreateFromFile(consoleAsm) }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithOptimizationLevel(optimizationLevel) .WithPlatform(Platform.AnyCpu) ); foreach (string item in references) { compilation = compilation.AddReferences(MetadataReference.CreateFromFile(item)); } using (MemoryStream assemblyStream = new MemoryStream()) using (MemoryStream symbolsStream = new MemoryStream()) { EmitOptions emitOptions = new EmitOptions( debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: symbolsName); EmitResult result = compilation.Emit( peStream: assemblyStream, pdbStream: symbolsStream, embeddedTexts: embeddedTexts, options: emitOptions); if (!result.Success) { foreach (Diagnostic item in result.Diagnostics) { if (item.Severity == DiagnosticSeverity.Error) { Console.WriteLine(item); } } return(null); } assemblyStream.Seek(0, SeekOrigin.Begin); symbolsStream?.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(assemblyStream, symbolsStream); return(assembly); } }
public List<T> Parse<T>(string codeFilePath, string methodName, int paramsCount) { string sCodeLocation = codeFilePath; string sCodeText = File.ReadAllText(sCodeLocation, Encoding.UTF8); FileInfo CSProjFile = null; #region Find project file. FileInfo codeFileInfo = new FileInfo(sCodeLocation); FileInfo[] projFileInfos = codeFileInfo.Directory.GetFiles("*.csproj", SearchOption.TopDirectoryOnly); projFileInfos = projFileInfos.Where((projFileInfo) => { if (Regex.IsMatch(projFileInfo.FullName, ".*[.]csproj$")) { return true; } return false; }).ToArray(); DirectoryInfo parentFolder = null; int iDeepth = 0; while (!projFileInfos.Any()) { iDeepth++; parentFolder = codeFileInfo.Directory.Parent; projFileInfos = codeFileInfo.Directory.GetFiles("*.csproj", SearchOption.TopDirectoryOnly); projFileInfos = projFileInfos.Where((projFileInfo) => { if (Regex.IsMatch(projFileInfo.FullName, ".*[.]csproj$")) { return true; } return false; }).ToArray(); if (iDeepth > 3 && codeFileInfo.Directory.GetFiles("*.sln", SearchOption.TopDirectoryOnly).Any()) { break; } } if (projFileInfos.Any()) { CSProjFile = projFileInfos[0]; } else { throw new FileNotFoundException(string.Format("Can't found the project configuration file. Code file {0}.", codeFilePath)); } #endregion #region Get all references references = new List<ReferenceInfo>(); XDocument xdocCSProj = XDocument.Load(CSProjFile.FullName); string sXmlns = xdocCSProj.Root.Attribute(XName.Get("xmlns")).Value; List<XElement> refNodes = xdocCSProj.Root.Descendants().Where((xe) => { if (xe.Name.LocalName == "Reference") { return true; } return false; }).ToList(); ReferenceInfo refInfo = null; foreach (XElement refNode in refNodes) { refInfo = new ReferenceInfo(); refInfo.IsProjectReference = false; refInfo.IsTeamCode = true; refInfo.Name = refNode.Attribute(XName.Get("Include")).Value; if (refNode.HasElements) { refInfo.AssemblyLocationForDebug = refNode.Element(XName.Get("HintPath", sXmlns)).Value; refInfo.AssemblyLocationForDebug = Path.Combine(CSProjFile.Directory.FullName, refInfo.AssemblyLocationForDebug); refInfo.AssemblyLocationForRelease = refNode.Element(XName.Get("HintPath", sXmlns)).Value; refInfo.AssemblyLocationForRelease = Path.Combine(CSProjFile.Directory.FullName, refInfo.AssemblyLocationForDebug); } if (refInfo.AssemblyLocationForDebug == null) { refInfo.AssemblyName = refInfo.Name; refInfo.AssemblyLocationForDebug = refInfo.Name; refInfo.AssemblyLocationForRelease = refInfo.Name; } if (!File.Exists(refInfo.Name)) { refInfo.IsTeamCode = false; } else { refInfo.LoadedAssembly = Assembly.LoadFile(refInfo.AssemblyLocationForRelease); } references.Add(refInfo); } refNodes = xdocCSProj.Root.Descendants().Where((xe) => { if (xe.Name.LocalName == "ProjectReference") { return true; } return false; }).ToList(); FileInfo refProjFileInfo = null; XDocument xdocRefProjFile = null; string sRefCSProjXmlns = string.Empty; XElement CSProjInfoNode = null; foreach (XElement refNode in refNodes) { refInfo = new ReferenceInfo(); refInfo.IsProjectReference = true; refInfo.IsTeamCode = true; refInfo.Name = refNode.Attribute(XName.Get("Include")).Value; refProjFileInfo = new FileInfo(Path.Combine(CSProjFile.Directory.FullName, refInfo.Name)); xdocRefProjFile = XDocument.Load(refProjFileInfo.FullName); sRefCSProjXmlns = xdocRefProjFile.Root.Attribute(XName.Get("xmlns")).Value; CSProjInfoNode = xdocRefProjFile.Root.Descendants(XName.Get("AssemblyName", sRefCSProjXmlns)).FirstOrDefault(); if (CSProjInfoNode != null) { refInfo.AssemblyName = CSProjInfoNode.Value; } CSProjInfoNode = xdocRefProjFile.Root.Descendants(XName.Get("Configuration", sRefCSProjXmlns)).FirstOrDefault(); if (CSProjInfoNode.Value == "Debug") { #region For Debug CSProjInfoNode = xdocRefProjFile.Root.Descendants(XName.Get("PropertyGroup", sRefCSProjXmlns)) .Where(xe => { try { if (xe.Attribute(XName.Get("Condition")).Value.Contains("Debug")) { return true; } } catch { } return false; }) .FirstOrDefault(); CSProjInfoNode = CSProjInfoNode != null ? CSProjInfoNode.Descendants(XName.Get("OutputPath", sRefCSProjXmlns)).FirstOrDefault() : null; if (CSProjInfoNode != null) { refInfo.AssemblyLocationForDebug = CSProjInfoNode.Value; refInfo.AssemblyLocationForDebug = Path.Combine(refProjFileInfo.Directory.FullName, refInfo.AssemblyLocationForDebug); if (!refInfo.AssemblyLocationForDebug.EndsWith(refInfo.AssemblyName + ".dll")) { refInfo.AssemblyLocationForDebug = Path.Combine(refInfo.AssemblyLocationForDebug, refInfo.AssemblyName + ".dll"); } } #endregion } else { #region For Release CSProjInfoNode = xdocRefProjFile.Root.Descendants(XName.Get("PropertyGroup", sRefCSProjXmlns)) .Where(xe => { try { if (xe.Attribute(XName.Get("Condition")).Value.Contains("Release")) { return true; } } catch { } return false; }) .FirstOrDefault(); CSProjInfoNode = CSProjInfoNode != null ? CSProjInfoNode.Descendants(XName.Get("OutputPath", sRefCSProjXmlns)).FirstOrDefault() : null; if (CSProjInfoNode != null) { refInfo.AssemblyLocationForRelease = CSProjInfoNode.Value; refInfo.AssemblyLocationForRelease = Path.Combine(refProjFileInfo.Directory.FullName, refInfo.AssemblyLocationForRelease); if (!refInfo.AssemblyLocationForRelease.EndsWith(refInfo.AssemblyName + ".dll")) { refInfo.AssemblyLocationForRelease = Path.Combine(refInfo.AssemblyLocationForRelease, refInfo.AssemblyName + ".dll"); } } #endregion } refInfo.Name = refNode.Element(XName.Get("Name", sXmlns)).Value; if (File.Exists(refInfo.Name)) { refInfo.IsTeamCode = false; } else { refInfo.LoadedAssembly = Assembly.LoadFile((refInfo.AssemblyLocationForDebug != null) ? refInfo.AssemblyLocationForDebug : refInfo.AssemblyLocationForRelease); } references.Add(refInfo); } #endregion CSharpCompilationOptions co = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); List<SyntaxTree> trees = new List<SyntaxTree>(); trees.Add(CSharpSyntaxTree.ParseText(sCodeText)); CSharpCompilation compilation = CSharpCompilation.Create(@"Roslyn_Output.dll" , options: co , syntaxTrees: trees); #region Add reference metadata to compiler. MetadataReference mr = null; foreach (ReferenceInfo RI in references) { if (File.Exists(RI.AssemblyLocationForDebug)) { if (string.IsNullOrEmpty(RI.AssemblyLocationForRelease)) { mr = MetadataReference.CreateFromFile(RI.AssemblyLocationForDebug, properties: MetadataReferenceProperties.Assembly); } else { mr = MetadataReference.CreateFromFile(RI.AssemblyLocationForDebug, properties: MetadataReferenceProperties.Assembly); } } RI.CurrentReferenceMetadata = mr; compilation = compilation.AddReferences(RI.CurrentReferenceMetadata); } #endregion #region create compilation unit and SemanticModel semanticModel = compilation.GetSemanticModel(trees[0]); CompilationUnitSyntax compilationUnit = trees[0].GetCompilationUnitRoot(); this.usings = compilationUnit.Usings; NamespaceDeclarationSyntax namespaceDeclaration = compilationUnit.Members .OfType<NamespaceDeclarationSyntax>().FirstOrDefault(); ClassDeclarationSyntax classDeclaration = namespaceDeclaration.Members .OfType<ClassDeclarationSyntax>().FirstOrDefault(); MethodDeclarationSyntax methodDeclaration = classDeclaration.Members .OfType<MethodDeclarationSyntax>() .Where(mds => string.Equals(mds.Identifier.ValueText, methodName) && mds.ParameterList.Parameters.Count >= paramsCount) .FirstOrDefault(); ParameterSyntax parameter = methodDeclaration.ParameterList.Parameters[0]; #endregion //(methodDeclaration.Body.Statements[1] as StatementSyntax); //MethodSymbol members = semanticModel.GetDeclaredSymbol(methodDeclaration); //// (line - column) information - start at 0. //string lcInfo = members.Locations[0].GetLineSpan(true).ToString(); //Symbol symbolAt44 = semanticModel.LookupSymbols(compilationUnit.DescendantTokens().ToArray()[44].FullSpan.End).FirstOrDefault(); List<InvocationExpressionSyntax> methodCalls = methodDeclaration.Body.DescendantNodes() .OfType<InvocationExpressionSyntax>().ToList(); string sMethodName = (methodCalls[3].Expression as MemberAccessExpressionSyntax).GetLastToken().ValueText; ExpressionSyntax es0 = methodDeclaration .FindToken((methodCalls[3] as InvocationExpressionSyntax).Expression.FullSpan.Start) .Parent as ExpressionSyntax; string varType0 = es0.Kind().ToString();// IdentifierName if (es0.Kind() == SyntaxKind.IdentifierName) { SyntaxToken[] callSeq = (methodCalls[3].Expression as MemberAccessExpressionSyntax).DescendantTokens() .Where(st => { if (st.Kind() == SyntaxKind.IdentifierToken) { return true; } return false; }).ToArray(); SymbolInfo symbolInfo0 = semanticModel.GetSymbolInfo(es0); Microsoft.CodeAnalysis.TypeInfo ti = semanticModel.GetTypeInfo(es0); string sVariableTypeName = ti.Type.Name; // first token type name. cpb1 Type tCPB = SearchTypeInAllAssemblies(sVariableTypeName); MemberInfo memberInfo = null; Type sNextType = null; int iSearchStart = 1; for (; iSearchStart < callSeq.Length; iSearchStart++) { memberInfo = tCPB.GetMembers() .Where(mi => { if (string.Equals(mi.Name, callSeq[iSearchStart].ValueText)) { return true; } return false; }) .FirstOrDefault(); if (memberInfo != null) { switch (memberInfo.MemberType) { case MemberTypes.Field: sNextType = (memberInfo as FieldInfo).FieldType; break; case MemberTypes.Property: sNextType = (memberInfo as PropertyInfo).PropertyType; break; case MemberTypes.Method: sNextType = (memberInfo as MethodInfo).ReturnType; break; } tCPB = sNextType; sNextType = null; } else { break; } } // Most possibility is extension method. if (memberInfo == null) { } MethodInfo target = memberInfo as MethodInfo; } foreach (ReferenceInfo RI in references.Where(e => e.LoadedAssembly != null)) { RI.LoadedAssembly = null; } return null; }
public static CSharpCompilation AddReferenceFromType(this CSharpCompilation compilation, Type type) { return(compilation.AddReferences( MetadataReference.CreateFromFile(type.GetTypeInfo().Assembly.Location))); }
public RoslynCompilationHelper AddReferences(params MetadataReference[] references) { _compilation = _compilation.AddReferences(references); return(this); }
private CompileResult BuildIncremental(CompileOptions options) { var result = new CompileResult(); _logger.Info("BuildIncremental"); _options = options; // update reference files var referenceChanges = _referenceFileList.Update(options.References); foreach (var file in referenceChanges.Added) { _logger.Info("+ {0}", file); var reference = CreateReference(file); _compilation = _compilation.AddReferences(reference); _referenceMap.Add(file, reference); } foreach (var file in referenceChanges.Changed) { _logger.Info("* {0}", file); var reference = CreateReference(file); _compilation = _compilation.RemoveReferences(_referenceMap[file]) .AddReferences(reference); _referenceMap[file] = reference; } foreach (var file in referenceChanges.Removed) { _logger.Info("- {0}", file); _compilation = _compilation.RemoveReferences(_referenceMap[file]); _referenceMap.Remove(file); } // update source files var sourceChanges = _sourceFileList.Update(options.Files); var parseOption = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Regular, options.Defines); foreach (var file in sourceChanges.Added) { _logger.Info("+ {0}", file); var syntaxTree = ParseSource(file, parseOption); _compilation = _compilation.AddSyntaxTrees(syntaxTree); _sourceMap.Add(file, syntaxTree); } foreach (var file in sourceChanges.Changed) { _logger.Info("* {0}", file); var syntaxTree = ParseSource(file, parseOption); _compilation = _compilation.RemoveSyntaxTrees(_sourceMap[file]) .AddSyntaxTrees(syntaxTree); _sourceMap[file] = syntaxTree; } foreach (var file in sourceChanges.Removed) { _logger.Info("- {0}", file); _compilation = _compilation.RemoveSyntaxTrees(_sourceMap[file]); _sourceMap.Remove(file); } // emit or reuse prebuilt output var reusePrebuilt = _outputDllStream != null && ( (_options.PrebuiltOutputReuse == PrebuiltOutputReuseType.WhenNoChange && sourceChanges.Empty && referenceChanges.Empty) || (_options.PrebuiltOutputReuse == PrebuiltOutputReuseType.WhenNoSourceChange && sourceChanges.Empty && referenceChanges.Added.Count == 0 && referenceChanges.Removed.Count == 0)); if (reusePrebuilt) { _logger.Info("Reuse prebuilt output"); // write dll var dllFile = Path.Combine(_options.WorkDirectory, _options.Output); using (var dllStream = new FileStream(dllFile, FileMode.Create)) { _outputDllStream.Seek(0L, SeekOrigin.Begin); _outputDllStream.CopyTo(dllStream); } // write pdb or mdb switch (_options.DebugSymbolFile) { case DebugSymbolFileType.Pdb: var pdbFile = Path.Combine(_options.WorkDirectory, Path.ChangeExtension(_options.Output, ".pdb")); using (var debugSymbolStream = new FileStream(pdbFile, FileMode.Create)) { _outputDebugSymbolStream.Seek(0L, SeekOrigin.Begin); _outputDebugSymbolStream.CopyTo(debugSymbolStream); } break; case DebugSymbolFileType.PdbToMdb: case DebugSymbolFileType.Mdb: var mdbFile = Path.Combine(_options.WorkDirectory, _options.Output + ".mdb"); using (var debugSymbolStream = new FileStream(mdbFile, FileMode.Create)) { _outputDebugSymbolStream.Seek(0L, SeekOrigin.Begin); _outputDebugSymbolStream.CopyTo(debugSymbolStream); } break; } result.Succeeded = true; } else { _logger.Info("Emit"); Emit(result); } return(result); }
private IView CompileAndInstance(string code, Assembly modelAssembly) { modelAssembly = modelAssembly ?? Assembly.GetEntryAssembly(); CSharpCompilation compilation = CSharpCompilation.Create("AppViewModel") .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddReferences(MetadataReference.CreateFromFile(modelAssembly.Location)) .AddReferences(MetadataReference.CreateFromFile(typeof(IView).Assembly.Location)); var netStandardAssembly = Assembly.Load(new AssemblyName("netstandard")); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(netStandardAssembly.Location)); var netStandardAssemblies = netStandardAssembly.GetReferencedAssemblies(); foreach (var assembly in netStandardAssemblies) { string assemblyLocation = Assembly.Load(assembly).Location; compilation = compilation.AddReferences(MetadataReference.CreateFromFile(assemblyLocation)); } SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(code); compilation = compilation.AddSyntaxTrees(syntaxTree); using (MemoryStream memoryStream = new MemoryStream()) { EmitResult emitResult = compilation.Emit(memoryStream); if (!emitResult.Success) { StringBuilder errors = new StringBuilder(); StringBuilder htmlErrorView = new StringBuilder(); htmlErrorView.AppendLine($"<h4>{emitResult.Diagnostics.Count()} errors:</h4>"); foreach (var error in emitResult.Diagnostics) { Console.WriteLine(error.GetMessage()); htmlErrorView.AppendLine($"<p>{error.GetMessage()}</p>"); } htmlErrorView.AppendLine($"<pre>{WebUtility.HtmlEncode(code)}</pre>"); return(new ErrorView(htmlErrorView.ToString())); } memoryStream.Seek(0, SeekOrigin.Begin); byte[] assemblyBytes = memoryStream.ToArray(); Assembly assembly = Assembly.Load(assemblyBytes); Type type = assembly.GetType("AppViewCodeNamespace.AppViewCode"); if (type == null) { Console.WriteLine("AppViewCodeNamespace.AppViewCode class was not found!"); throw new NullReferenceException("AppViewCodeNamespace.AppViewCode class was not found!"); } IView view = (IView)Activator.CreateInstance(type); if (view == null) { Console.WriteLine("AppViewCodeNamespace.AppViewCode class cannot be instanciated!"); throw new NullReferenceException("AppViewCodeNamespace.AppViewCode class cannot be instanciated!"); } return(view); } }