public void CreateFromImage() { var r = MetadataReference.CreateFromImage(ProprietaryTestResources.NetFX.v4_0_30319.mscorlib); Assert.Null(r.FilePath); Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display); Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind); Assert.False(r.Properties.EmbedInteropTypes); Assert.True(r.Properties.Aliases.IsEmpty); }
public void AddMetadataReference(AssemblyReference asm) => WithCompilation(c => { /* * Logger.LogInformation( * "Adding reference to '{AssemblyLocation}' for client '{Client}'", * Path.GetFileName(asm.AssemblyLocation), _client.Client); */ return(c.AddReferences(MetadataReference.CreateFromImage(asm.PeBytes))); });
public void UnsuccessfulSourceGeneration() { // Compile the referenced assembly first. Compilation campaignCompilation = CompilationHelper.CreateCampaignSummaryViewModelCompilation(); Compilation eventCompilation = CompilationHelper.CreateActiveOrUpcomingEventCompilation(); // Emit the image of the referenced assembly. byte[] campaignImage = CompilationHelper.CreateAssemblyImage(campaignCompilation); byte[] eventImage = CompilationHelper.CreateAssemblyImage(eventCompilation); // Main source for current compilation. string source = @" using System.Collections.Generic; using System.Text.Json.Serialization; using ReferencedAssembly; [assembly: JsonSerializable(typeof(JsonSourceGenerator.IndexViewModel)] namespace JsonSourceGenerator { public class IndexViewModel { public ISet<ActiveOrUpcomingEvent> ActiveOrUpcomingEvents { get; set; } public CampaignSummaryViewModel FeaturedCampaign { get; set; } public bool IsNewAccount { get; set; } public bool HasFeaturedCampaign => FeaturedCampaign != null; } }"; MetadataReference[] additionalReferences = { MetadataReference.CreateFromImage(campaignImage), MetadataReference.CreateFromImage(eventImage), }; Compilation compilation = CompilationHelper.CreateCompilation(source, additionalReferences); JsonSourceGenerator generator = new JsonSourceGenerator(); CompilationHelper.RunGenerators(compilation, out var generatorDiags, generator); // Expected success info logs. string[] expectedInfoDiagnostics = new string[] { "Generated serialization metadata for type JsonSourceGeneration.IndexViewModel", "Generated serialization metadata for type System.Boolean", "Generated serialization metadata for type ReferencedAssembly.CampaignSummaryViewModel" }; // Expected warning logs. string[] expectedWarningDiagnostics = new string[] { "Did not generate serialization metadata for type System.Collections.Generic.ISet<ReferencedAssembly.ActiveOrUpcomingEvent>" }; CompilationHelper.CheckDiagnosticMessages(generatorDiags, DiagnosticSeverity.Info, expectedInfoDiagnostics); CompilationHelper.CheckDiagnosticMessages(generatorDiags, DiagnosticSeverity.Warning, expectedWarningDiagnostics); CompilationHelper.CheckDiagnosticMessages(generatorDiags, DiagnosticSeverity.Error, new string[] { }); }
public static MetadataReference CompileToMetadata(string source, string assemblyName = null, IEnumerable <MetadataReference> references = null, bool verify = true) { if (references == null) { references = new[] { TestBase.MscorlibRef }; } var compilation = CreateCompilationWithMscorlib(source, assemblyName, references); var verifier = Instance.CompileAndVerify(compilation, emitOptions: EmitOptions.CCI, verify: verify); return(MetadataReference.CreateFromImage(verifier.EmittedAssemblyData)); }
/// <summary> /// Initializes a new instance of the <see cref="Documentation"/> class. /// </summary> /// <param name="assemblies">The assembly images to be part of the compilation.</param> internal Documentation(IEnumerable <ImmutableArray <byte> > assemblies) { var compilation = CSharpCompilation.Create(null); foreach (var assembly in assemblies) { compilation = compilation.AddReferences(MetadataReference.CreateFromImage(assembly, MetadataReferenceProperties.Assembly)); } this.Compilation = compilation; }
public void TypeSymbolFromReflectionType() { var c = CSharpCompilation.Create("TypeSymbolFromReflectionType", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree("class C { }") }, references: new[] { MscorlibRef, MetadataReference.CreateFromImage(File.ReadAllBytes( CorLightup.Desktop.GetAssemblyLocation(typeof(TypeTests).GetTypeInfo().Assembly))) }); var intSym = c.Assembly.GetTypeByReflectionType(typeof(int), includeReferences: true); Assert.NotNull(intSym); Assert.Equal(SpecialType.System_Int32, intSym.SpecialType); var strcmpSym = c.Assembly.GetTypeByReflectionType(typeof(StringComparison), includeReferences: true); Assert.NotNull(strcmpSym); Assert.Equal("System.StringComparison", strcmpSym.ToDisplayString()); var arraySym = c.Assembly.GetTypeByReflectionType(typeof(List <int>[][, , ]), includeReferences: true); Assert.NotNull(arraySym); Assert.Equal("System.Collections.Generic.List<int>[][*,*,*]", arraySym.ToDisplayString()); var ptrSym = c.Assembly.GetTypeByReflectionType(typeof(char).MakePointerType().MakePointerType(), includeReferences: true); Assert.NotNull(ptrSym); Assert.Equal("char**", ptrSym.ToDisplayString()); string testType1 = typeof(C <,>).DeclaringType.FullName; var nestedSym1 = c.Assembly.GetTypeByReflectionType(typeof(C <int, bool> .D.E <double, float> .F <byte>), includeReferences: true); Assert.Equal(testType1 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym1.ToDisplayString()); // Not supported atm: //string testType2 = typeof(C<,>).DeclaringType.FullName; //var nestedSym2 = c.Assembly.GetTypeByReflectionType(typeof(C<,>.D.E<,>.F<>), includeReferences: true); //Assert.Equal(testType2 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym2.ToDisplayString()); // Process is defined in System, which isn't referenced: var err = c.Assembly.GetTypeByReflectionType(typeof(C <Process, bool> .D.E <double, float> .F <byte>), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(C <int, bool> .D.E <double, Process> .F <byte>), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(Process[]), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(SyntaxKind).MakePointerType(), includeReferences: true); Assert.Null(err); }
public void AccessorWithImportedGenericType() { var comp0 = CreateCompilation( @" public class MC<T> { } public delegate void MD<T>(T t); " ); var compref = new CSharpCompilationReference(comp0); var comp1 = CreateCompilation( @" using System; public class G<T> { public MC<T> Prop { set { } } public int this[MC<T> p] { get { return 0;} } public event MD<T> E { add { } remove { } } } ", references: new MetadataReference[] { compref }, assemblyName: "ACCImpGen" ); var mtdata = comp1.EmitToArray(options: new EmitOptions(metadataOnly: true)); var mtref = MetadataReference.CreateFromImage(mtdata); var comp2 = CreateCompilation( @"", references: new MetadataReference[] { mtref }, assemblyName: "META" ); var tsym = comp2 .GetReferencedAssemblySymbol(mtref) .GlobalNamespace.GetMember <NamedTypeSymbol>("G"); Assert.NotNull(tsym); var mems = tsym.GetMembers().Where(s => s.Kind == SymbolKind.Method); // 4 accessors + ctor Assert.Equal(5, mems.Count()); foreach (MethodSymbol m in mems) { if (m.MethodKind == MethodKind.Constructor) { continue; } Assert.NotNull(m.AssociatedSymbol); Assert.NotEqual(MethodKind.Ordinary, m.MethodKind); } }
public void TestMultipleDefinitions() { // Adding a dependency to an assembly that has internal definitions of public types // should not result in a collision and break generation. // Verify usage of the extension GetBestTypeByMetadataName(this Compilation) instead of Compilation.GetTypeByMetadataName(). var referencedSource = @" namespace System.Text.Json.Serialization { internal class JsonSerializerContext { } internal class JsonSerializableAttribute { } internal class JsonSourceGenerationOptionsAttribute { } }"; // Compile the referenced assembly first. Compilation referencedCompilation = CompilationHelper.CreateCompilation(referencedSource); // Obtain the image of the referenced assembly. byte[] referencedImage = CompilationHelper.CreateAssemblyImage(referencedCompilation); // Generate the code string source = @" using System.Text.Json.Serialization; namespace HelloWorld { [JsonSerializable(typeof(HelloWorld.MyType))] internal partial class JsonContext : JsonSerializerContext { } public class MyType { public int MyInt { get; set; } } }"; MetadataReference[] additionalReferences = { MetadataReference.CreateFromImage(referencedImage) }; Compilation compilation = CompilationHelper.CreateCompilation(source, additionalReferences); JsonSourceGenerator generator = new JsonSourceGenerator(); Compilation newCompilation = CompilationHelper.RunGenerators( compilation, out ImmutableArray <Diagnostic> generatorDiags, generator); // Make sure compilation was successful. Assert.Empty(generatorDiags.Where(diag => diag.Severity.Equals(DiagnosticSeverity.Error))); Assert.Empty(newCompilation.GetDiagnostics().Where(diag => diag.Severity.Equals(DiagnosticSeverity.Error))); // Should find the generated type. Dictionary <string, Type> types = generator.GetSerializableTypes(); Assert.Equal(1, types.Count); Assert.Equal("HelloWorld.MyType", types.Keys.First()); }
public EmitResult Generate(IDictionary <string, MetadataReference> existingReferences) { Compilation = CSharpCompilation.Create( assemblyName: AssemblyName, options: Worker.OriginalCompilation.Options, references: Worker.OriginalCompilation.References); foreach (var other in Requires.Keys) { if (other.EmitResult != null && !other.EmitResult.Success) { // Skip this reference if it hasn't beed emitted continue; } // If we're already referencing this assembly then skip it if (existingReferences.ContainsKey(other.AssemblyName)) { continue; } Compilation = Compilation.AddReferences(other.RealOrShallowReference()); } foreach (var syntaxReference in TypeSymbol.DeclaringSyntaxReferences) { var node = syntaxReference.GetSyntax(); var tree = syntaxReference.SyntaxTree; var root = tree.GetRoot(); var nodesToRemove = GetNodesToRemove(root, node).ToArray(); // what it looks like when removed var newRoot = root.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepDirectives); var newTree = SyntaxFactory.SyntaxTree(newRoot, options: tree.Options, path: tree.FilePath, encoding: Encoding.UTF8); // update compilation with code removed Compilation = Compilation.AddSyntaxTrees(newTree); } var outputStream = new MemoryStream(); EmitResult = Compilation.Emit(outputStream); if (!EmitResult.Success) { return(EmitResult); } OutputBytes = outputStream.ToArray(); Reference = MetadataReference.CreateFromImage(OutputBytes); return(EmitResult); }
public void OverloadResolutionWithStaticType() { var vbSource = @" Imports System Namespace Microsoft.VisualBasic.CompilerServices <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)> Public NotInheritable Class StandardModuleAttribute Inherits System.Attribute Public Sub New() MyBase.New() End Sub End Class End Namespace Public Module M Sub Foo(x as Action(Of String)) End Sub Sub Foo(x as Action(Of GC)) End Sub End Module "; var vbProject = VisualBasic.VisualBasicCompilation.Create( "VBProject", references: new[] { MscorlibRef }, syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) }); var csSource = @" class Program { static void Main() { M.Foo(x => { }); } } "; var metadataStream = new MemoryStream(); var emitResult = vbProject.Emit(metadataStream, options: new EmitOptions(metadataOnly: true)); Assert.True(emitResult.Success); var csProject = CreateCompilationWithMscorlib( Parse(csSource), new[] { MetadataReference.CreateFromImage(metadataStream.ToImmutable()) }); Assert.Equal(0, csProject.GetDiagnostics().Count()); }
public static MetadataReference CreateMetadataReference(this CompilerMetadataReference mdRef, IRoslynDocumentationProviderFactory docFactory) { var docProvider = docFactory.TryCreate(mdRef.Filename); if (mdRef.IsAssemblyReference) { return(MetadataReference.CreateFromImage(mdRef.Data, MetadataReferenceProperties.Assembly, docProvider, mdRef.Filename)); } var moduleMetadata = ModuleMetadata.CreateFromImage(mdRef.Data); return(moduleMetadata.GetReference(docProvider, mdRef.Filename)); }
public void ExternAliasDoesntFailNonSourceBinds() { // Ensure that adding an alias doesn't interfere with resolution among metadata references. The alias only affects source usage // of the types defined in the aliased assembly. var src = @" namespace NS { public class Baz { public int M() { return 1; } } } "; var comp = CreateStandardCompilation(src, assemblyName: "Baz.dll", options: TestOptions.ReleaseDll); var outputMetadata = AssemblyMetadata.CreateFromImage(comp.EmitToArray()); var goo1 = outputMetadata.GetReference(); var goo1Alias = outputMetadata.GetReference(aliases: ImmutableArray.Create("Baz")); src = @" namespace NS { public class Bar : Baz { public int M2() { return 2; } } } "; comp = CreateStandardCompilation(src, assemblyName: "Bar.dll", options: TestOptions.ReleaseDll); comp = comp.AddReferences(goo1); var goo2 = MetadataReference.CreateFromImage(comp.EmitToArray()); src = @" class Maine { public static void Main() { NS.Bar d = null; } } "; comp = CreateStandardCompilation(src); comp = comp.AddReferences(goo2, goo1Alias); comp.VerifyDiagnostics( // (6,20): warning CS0219: The variable 'd' is assigned but its value is never used // NS.Bar d = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d") ); }
public void InvalidNestedArity() { // .class public C`2<T1,T2> // .class nested public D<S1> var mdRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.InvalidGenericType.AsImmutableOrNull()); string source = "class X : C<int, int>.D { }"; CreateCompilationWithMscorlib(source, new[] { mdRef }).VerifyDiagnostics( // (2,11): error CS0648: 'C<T1, T2>.D' is a type not supported by the language // class X : C<int, int>.D { } Diagnostic(ErrorCode.ERR_BogusType, "C<int, int>.D").WithArguments("C<T1, T2>.D") ); }
/// <summary> /// Compiles <paramref name="code"/> and creates script. /// </summary> /// <param name="options">Compilation options.</param> /// <param name="code">Code to be compiled.</param> /// <param name="builder">Assembly builder.</param> /// <param name="previousSubmissions">Enumeration of scripts that were evaluated within current context. New submission may reference them.</param> /// <returns>New script reepresenting the compiled code.</returns> public static Script Create(Context.ScriptOptions options, string code, PhpCompilationFactory builder, IEnumerable <Script> previousSubmissions) { var tree = PhpSyntaxTree.ParseCode(code, new PhpParseOptions(kind: options.IsSubmission ? SourceCodeKind.Script : SourceCodeKind.Regular), PhpParseOptions.Default, options.Location.Path); var diagnostics = tree.Diagnostics; if (!HasErrors(diagnostics)) { // unique in-memory assembly name var name = builder.GetNewSubmissionName(); // list of scripts that were eval'ed in the context already, // our compilation may depend on them var dependingSubmissions = previousSubmissions.Where(s => !s.Image.IsDefaultOrEmpty); // create the compilation object // TODO: add conditionally declared types into the compilation tables var compilation = (PhpCompilation)builder.CoreCompilation .WithAssemblyName(name.Name) .AddSyntaxTrees(tree) .AddReferences(dependingSubmissions.Select(s => MetadataReference.CreateFromImage(s.Image))); if (options.EmitDebugInformation) { compilation = compilation.WithPhpOptions(compilation.Options.WithOptimizationLevel(OptimizationLevel.Debug).WithDebugPlusMode(true)); } diagnostics = compilation.GetDeclarationDiagnostics(); if (!HasErrors(diagnostics)) { var peStream = new MemoryStream(); var pdbStream = options.EmitDebugInformation ? new MemoryStream() : null; var result = compilation.Emit(peStream, pdbStream); if (result.Success) { return(new Script(name, peStream, pdbStream, builder, previousSubmissions)); } else { diagnostics = result.Diagnostics; } } } // return(CreateInvalid(diagnostics)); }
/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <param name="externalCode">The source codes for new memory compilation. The goal of the external code is to simulate the behaviour of the extenal assembly without source code.</param> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp, string[] externalCode = null) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var workspace = new AdhocWorkspace(); workspace.Options = workspace.Options.WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, true) .WithChangedOption(FormattingOptions.SmartIndent, LanguageNames.CSharp, FormattingOptions.IndentStyle.Smart) .WithChangedOption(FormattingOptions.TabSize, LanguageNames.CSharp, 4) .WithChangedOption(FormattingOptions.IndentationSize, LanguageNames.CSharp, 4); var solution = workspace.CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .AddMetadataReference(projectId, CorlibReference) .AddMetadataReference(projectId, SystemCoreReference) .AddMetadataReference(projectId, CSharpSymbolsReference) .AddMetadataReference(projectId, CodeAnalysisReference) .AddMetadataReference(projectId, PXDataReference) .AddMetadataReference(projectId, FluentBqlReference) .AddMetadataReference(projectId, PXCommonReference) .AddMetadataReference(projectId, PXObjectsReference); if (externalCode != null && externalCode.Length > 0) { IEnumerable <byte> dynamicAssembly = BuildAssemblyFromSources(externalCode); MetadataReference dynamicReference = MetadataReference.CreateFromImage(dynamicAssembly); solution = solution.AddMetadataReference(projectId, dynamicReference); } var project = solution.GetProject(projectId); var parseOptions = project.ParseOptions.WithFeatures( project.ParseOptions.Features.Union(new[] { new KeyValuePair <string, string>("IOperation", "true") })); solution = solution.WithProjectParseOptions(projectId, parseOptions); int count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count + "." + fileExt; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return(solution.GetProject(projectId)); }
public void RecordDerivedFromRecordInExternalAssembly() { // Compile the referenced assembly first. Compilation referencedCompilation = CompilationHelper.CreateReferencedSimpleLibRecordCompilation(); // Emit the image of the referenced assembly. byte[] referencedImage = CompilationHelper.CreateAssemblyImage(referencedCompilation); string source = @" using System.Text.Json.Serialization; using ReferencedAssembly; namespace HelloWorld { [JsonSerializable(typeof(AppRecord))] internal partial class JsonContext : JsonSerializerContext { } internal record AppRecord : LibRecord { public string ExtraData { get; set; } } }"; MetadataReference[] additionalReferences = { MetadataReference.CreateFromImage(referencedImage) }; Compilation compilation = CompilationHelper.CreateCompilation(source, additionalReferences); JsonSourceGenerator generator = new JsonSourceGenerator(); Compilation newCompilation = CompilationHelper.RunGenerators(compilation, out ImmutableArray <Diagnostic> generatorDiags, generator); // Make sure compilation was successful. CheckCompilationDiagnosticsErrors(generatorDiags); CheckCompilationDiagnosticsErrors(newCompilation.GetDiagnostics()); Dictionary <string, Type> types = generator.GetSerializableTypes(); Assert.Equal(1, types.Count); Type recordType = types["HelloWorld.AppRecord"]; Assert.Equal("HelloWorld.AppRecord", recordType.FullName); string[] expectedFieldsNames = { "Country", "PhoneNumber" }; string[] expectedPropertyNames = { "Address1", "Address2", "City", "ExtraData", "Id", "Name", "PostalCode", "State" }; CheckFieldsPropertiesMethods(recordType, expectedFieldsNames, expectedPropertyNames, inspectBaseTypes: true); Assert.Equal(1, recordType.GetConstructors().Length); }
public void PresentCorLib() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[] { TestReferences.NetStandard30.SystemRuntimeRef }); MetadataOrSourceAssemblySymbol msCorLibRef = (MetadataOrSourceAssemblySymbol)assemblies[0]; for (int i = 1; i <= (int)SpecialType.Count; i++) { var t = msCorLibRef.GetSpecialType((SpecialType)i); Assert.Equal((SpecialType)i, t.SpecialType); Assert.Same(msCorLibRef, t.ContainingAssembly); } Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes); assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { MetadataReference.CreateFromImage(TestResources.NetFX.netstandard30.System_Runtime.AsImmutableOrNull()) }); msCorLibRef = (MetadataOrSourceAssemblySymbol)assemblies[0]; Assert.True(msCorLibRef.KeepLookingForDeclaredSpecialTypes); Queue <NamespaceSymbol> namespaces = new Queue <NamespaceSymbol>(); namespaces.Enqueue(msCorLibRef.Modules[0].GlobalNamespace); int count = 0; while (namespaces.Count > 0) { foreach (var m in namespaces.Dequeue().GetMembers()) { NamespaceSymbol ns = m as NamespaceSymbol; if (ns != null) { namespaces.Enqueue(ns); } else if (((NamedTypeSymbol)m).SpecialType != SpecialType.None) { count++; } if (count >= (int)SpecialType.Count) { Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes); } } } Assert.Equal(count, (int)SpecialType.Count); Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes); }
internal Engine(RealPlugin rp) { var pi = typeof(RealPlugin).Assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic); byte[] b = (byte[])pi.Invoke(typeof(RealPlugin).Assembly, null); var mref = MetadataReference.CreateFromImage(b); sop = ScriptOptions.Default.AddReferences(mref).AddReferences(new string[] { "System.Text.RegularExpressions", }).AddImports(new string[] { "System", "System.Text", "System.IO", "System.Text.RegularExpressions", "System.Collections.Generic", "Triggernometry.VariableTypes" }); }
public MetadataReferenceFeatureProvider(DynamicAssemblyCollection dynamicAssemblies) { _metadataReferences = AppDomain.CurrentDomain.GetAssemblies() .Where(x => !x.IsDynamic && !string.IsNullOrEmpty(x.Location)) .Select(x => MetadataReference.CreateFromFile(x.Location)) .Concat((dynamicAssemblies ?? Enumerable.Empty <byte[]>()) .Select(x => (MetadataReference)MetadataReference.CreateFromImage(x))) .Concat(new MetadataReference[] { // Razor/MVC assemblies that might not be loaded yet MetadataReference.CreateFromFile(typeof(IHtmlContent).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.CSharp")).Location) }) .ToList(); }
internal static MetadataReference CreateReflectionEmitAssembly(Action <ModuleBuilder> create) { using (var file = new DisposableFile(extension: ".dll")) { var name = Path.GetFileName(file.Path); var appDomain = AppDomain.CurrentDomain; var assembly = appDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Save, Path.GetDirectoryName(file.Path)); var module = assembly.DefineDynamicModule(CommonTestBase.GetUniqueName(), name); create(module); assembly.Save(name); var image = CommonTestBase.ReadFromFile(file.Path); return(MetadataReference.CreateFromImage(image)); } }
internal static PortableExecutableReference BuildPortableExecutableReference(this AssemblyReference assemblyReference, byte[] image) { if (assemblyReference == null) { return(null); } MetadataReferenceProperties properties = new MetadataReferenceProperties( assemblyReference.IsModule ? MetadataImageKind.Module : MetadataImageKind.Assembly, assemblyReference.Aliases == null ? default(ImmutableArray <string>) : assemblyReference.Aliases.ToImmutableArray(), assemblyReference.EmbedInteropTypes); PortableExecutableReference reference = MetadataReference.CreateFromImage(image.ToImmutableArray(), properties); return(reference); }
public void SuccessfulSourceGeneration() { // Compile the referenced assembly first. Compilation campaignCompilation = CompilationHelper.CreateCampaignSummaryViewModelCompilation(); Compilation eventCompilation = CompilationHelper.CreateActiveOrUpcomingEventCompilation(); // Emit the image of the referenced assembly. byte[] campaignImage = CompilationHelper.CreateAssemblyImage(campaignCompilation); byte[] eventImage = CompilationHelper.CreateAssemblyImage(eventCompilation); // Main source for current compilation. string source = @" using System.Collections.Generic; using System.Text.Json.Serialization; using ReferencedAssembly; namespace JsonSourceGenerator { [JsonSerializable(typeof(JsonSourceGenerator.IndexViewModel)] public partial class JsonContext : JsonSerializerContext { } public class IndexViewModel { public List<ActiveOrUpcomingEvent> ActiveOrUpcomingEvents { get; set; } public CampaignSummaryViewModel FeaturedCampaign { get; set; } public bool IsNewAccount { get; set; } public bool HasFeaturedCampaign => FeaturedCampaign != null; } }"; MetadataReference[] additionalReferences = { MetadataReference.CreateFromImage(campaignImage), MetadataReference.CreateFromImage(eventImage), }; Compilation compilation = CompilationHelper.CreateCompilation(source, additionalReferences); JsonSourceGenerator generator = new JsonSourceGenerator(); CompilationHelper.RunGenerators(compilation, out var generatorDiags, generator); CompilationHelper.CheckDiagnosticMessages(DiagnosticSeverity.Info, generatorDiags, Array.Empty <(Location, string)>()); CompilationHelper.CheckDiagnosticMessages(DiagnosticSeverity.Warning, generatorDiags, Array.Empty <(Location, string)>()); CompilationHelper.CheckDiagnosticMessages(DiagnosticSeverity.Error, generatorDiags, Array.Empty <(Location, string)>()); }
public bool TryGetMetadataReference(string assemblyName, [NotNullWhen(true)] out MetadataReference?reference) { reference = null; if (TryGetAssemblyPath(assemblyName, out var path)) { reference = MetadataReference.CreateFromFile(path); } if (reference == null && TryGetAssemblyBytes(assemblyName, out var stream)) { reference = MetadataReference.CreateFromImage(stream); } return(reference != null); }
public void AddReference_Dependencies_DllExe() { var dir = Temp.CreateDirectory(); var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }"); var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(dll.Image)); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); }
public void CollectionDictionarySourceGeneration() { // Compile the referenced assembly first. Compilation referencedCompilation = CompilationHelper.CreateReferencedHighLowTempsCompilation(); // Emit the image of the referenced assembly. byte[] referencedImage = CompilationHelper.CreateAssemblyImage(referencedCompilation); string source = @" using System; using System.Collections; using System.Collections.Generic; using System.Text.Json.Serialization; using ReferencedAssembly; namespace HelloWorld { [JsonSerializable(typeof(HelloWorld.WeatherForecastWithPOCOs))] internal partial class JsonContext : JsonSerializerContext { } public class WeatherForecastWithPOCOs { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string Summary { get; set; } public string SummaryField; public List<DateTimeOffset> DatesAvailable { get; set; } public Dictionary<string, HighLowTemps> TemperatureRanges { get; set; } public string[] SummaryWords { get; set; } } }"; MetadataReference[] additionalReferences = { MetadataReference.CreateFromImage(referencedImage) }; Compilation compilation = CompilationHelper.CreateCompilation(source, additionalReferences); JsonSourceGenerator generator = new JsonSourceGenerator(); Compilation newCompilation = CompilationHelper.RunGenerators(compilation, out var generatorDiags, generator); // Make sure compilation was successful. CheckCompilationDiagnosticsErrors(generatorDiags); CheckCompilationDiagnosticsErrors(newCompilation.GetDiagnostics()); }
internal void MultipleTypeDefinitions() { // Adding a dependency to an assembly that has internal definitions of public types // should not result in a collision and break generation. // Verify usage of the extension GetBestTypeByMetadataName(this Compilation) instead of Compilation.GetTypeByMetadataName(). var referencedSource = @" namespace Microsoft.Extensions.Logging { internal class LoggerMessageAttribute { } } namespace Microsoft.Extensions.Logging { internal interface ILogger { } internal enum LogLevel { } }"; // Compile the referenced assembly first. Compilation referencedCompilation = CompilationHelper.CreateCompilation(referencedSource); // Obtain the image of the referenced assembly. byte[] referencedImage = CompilationHelper.CreateAssemblyImage(referencedCompilation); // Generate the code string source = @" namespace Test { using Microsoft.Extensions.Logging; partial class C { [LoggerMessage(EventId = 1, Level = LogLevel.Debug, Message = ""M1"")] static partial void M1(ILogger logger); } }"; MetadataReference[] additionalReferences = { MetadataReference.CreateFromImage(referencedImage) }; Compilation compilation = CompilationHelper.CreateCompilation(source, additionalReferences); LoggerMessageGenerator generator = new LoggerMessageGenerator(); (ImmutableArray <Diagnostic> diagnostics, ImmutableArray <GeneratedSourceResult> generatedSources) = RoslynTestUtils.RunGenerator(compilation, generator); // Make sure compilation was successful. Assert.Empty(diagnostics); Assert.Equal(1, generatedSources.Length); Assert.Equal(21, generatedSources[0].SourceText.Lines.Count); }
public void ConstructedErrorTypes() { var source1 = @"public class A<T> { public class B<U> { } }"; var compilation1 = CreateStandardCompilation(source1, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A41"); compilation1.VerifyDiagnostics(); var reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Binding types in source, no missing types. var source2 = @"class C1<T, U> : A<T>.B<U> { } class C2<T, U> : A<T>.B<U> { } class C3<T> : A<T>.B<object> { } class C4<T> : A<object>.B<T> { } class C5 : A<object>.B<int> { } class C6 : A<string>.B<object> { } class C7 : A<string>.B<object> { }"; var compilation2 = CreateStandardCompilation(source2, references: new[] { reference1 }, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A42"); compilation2.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation2, missingTypes: false, fromSource: true); var reference2 = MetadataReference.CreateFromImage(compilation2.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Loading types from metadata, no missing types. var source3 = @""; var compilation3 = CreateStandardCompilation(source3, references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation3, missingTypes: false, fromSource: false); // Binding types in source, missing types, resulting inExtendedErrorTypeSymbols. var compilation4 = CreateStandardCompilation(source2); CompareConstructedErrorTypes(compilation4, missingTypes: true, fromSource: true); // Loading types from metadata, missing types, resulting in ErrorTypeSymbols. var source5 = @""; var compilation5 = CreateStandardCompilation(source5, references: new[] { reference2 }); CompareConstructedErrorTypes(compilation5, missingTypes: true, fromSource: false); }
public void CreateFrom_Errors() { Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromImage(null)); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromImage(default(ImmutableArray <byte>))); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromFile(null)); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromFile(null, default(MetadataReferenceProperties))); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromStream(null)); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromAssemblyInternal(null)); Assert.Throws <ArgumentException>(() => MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly, new MetadataReferenceProperties(MetadataImageKind.Module))); var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName { Name = "Goo" }, System.Reflection.Emit.AssemblyBuilderAccess.Run); Assert.Throws <NotSupportedException>(() => MetadataReference.CreateFromAssemblyInternal(dynamicAssembly)); }
public void OverloadResolutionWithStaticTypeError() { var vbSource = @" Imports System Namespace Microsoft.VisualBasic.CompilerServices <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)> Public NotInheritable Class StandardModuleAttribute Inherits System.Attribute Public Sub New() MyBase.New() End Sub End Class End Namespace Public Module M Public Dim F As Action(Of GC) End Module "; var vbProject = VisualBasic.VisualBasicCompilation.Create( "VBProject", references: new[] { MscorlibRef }, syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) }); var csSource = @" class Program { static void Main() { M.F = x=>{}; } } "; var vbMetadata = vbProject.EmitToArray(options: new EmitOptions(metadataOnly: true)); var csProject = CreateCompilationWithMscorlib(Parse(csSource), new[] { MetadataReference.CreateFromImage(vbMetadata) }); var diagnostics = csProject.GetDiagnostics().Select(DumpDiagnostic); Assert.Equal(1, diagnostics.Count()); Assert.Equal("'x' error CS0721: 'GC': static types cannot be used as parameters", diagnostics.First()); }
/// <summary> /// Compiles the given source fragment to a single module assembly, and returns it's image. /// </summary> /// <param name="source">The source fragment to compile, or null for empty assembly.</param> /// <param name="assemblyName">The assembly name to compile.</param> /// <param name="assemblies">References to other assemblies. Note that a reference to an assembly containing <c>System.Object</c> is always added.</param> /// <exception cref="EmitException">Thrown when assembly emitting fails.</exception> /// <returns>The compiled assembly as an immutable byte array.</returns> protected static ImmutableArray <byte> CompileAssembly(string?source = null, string assemblyName = "TestAssembly", params ImmutableArray <byte>[] assemblies) { var references = from a in assemblies select MetadataReference.CreateFromImage(a, MetadataReferenceProperties.Assembly); var compilation = CreateCompilation(source, assemblyName).AddReferences(references).AddReferences(BaseMetadata); using var str = new MemoryStream(); var result = compilation.Emit(str); if (!result.Success) { throw new EmitException($"Unable to compile assembly {assemblyName}.", result.Diagnostics); } return(ImmutableArray.Create(str.GetBuffer(), 0, (int)str.Length)); }