public void SameExternAliasInMultipleTreesValid() { var comp1 = CreateCompilationWithMscorlib("public class C { }", assemblyName: "A1"); var ref1 = new MetadataImageReference(CompileAndVerify(comp1).EmittedAssemblyData, aliases: ImmutableArray.Create("X")); var comp2 = CreateCompilationWithMscorlib("public class D { }", assemblyName: "A2"); var ref2 = new MetadataImageReference(CompileAndVerify(comp2).EmittedAssemblyData, aliases: ImmutableArray.Create("X")); const int numFiles = 20; var comp3 = CreateCompilationWithMscorlib(Enumerable.Range(1, numFiles).Select(x => "extern alias X;"), new[] { ref1, ref2 }, assemblyName: "A3.dll"); var targets = comp3.SyntaxTrees.AsParallel().Select(tree => { var model = comp3.GetSemanticModel(tree); var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType <ExternAliasDirectiveSyntax>().Single(); var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax); return((NamespaceSymbol)aliasSymbol.Target); }).ToArray(); //force evaluation var firstTarget = targets.First(); Assert.NotNull(firstTarget); Assert.IsType <MergedNamespaceSymbol>(firstTarget); firstTarget.GetMember <NamedTypeSymbol>("C"); firstTarget.GetMember <NamedTypeSymbol>("D"); Assert.True(targets.All(target => ReferenceEquals(firstTarget, target))); }
public void MetadataReference_Display() { MetadataReference r; r = new MetadataImageReference(AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1)); Assert.Equal("<in-memory assembly>".NeedsLocalization(), r.Display); r = new MetadataImageReference(ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1)); Assert.Equal("<in-memory module>".NeedsLocalization(), r.Display); r = new MetadataImageReference(ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1), fullPath: @"c:\blah"); Assert.Equal(@"c:\blah", r.Display); r = new MetadataImageReference(ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1), display: @"dddd"); Assert.Equal(@"dddd", r.Display); r = new MetadataImageReference(ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1), fullPath: @"c:\blah", display: @"dddd"); Assert.Equal(@"dddd", r.Display); r = new MetadataFileReference(@"c:\some path"); Assert.Equal(@"c:\some path", r.Display); r = CS.CSharpCompilation.Create("compilation name").ToMetadataReference(); Assert.Equal(@"compilation name", r.Display); r = VisualBasic.VisualBasicCompilation.Create("compilation name").ToMetadataReference(); Assert.Equal(@"compilation name", r.Display); }
internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null) { // The mechanism of this test is: we build the bound tree for the code passed in and then extract // from it the nodes that describe the method symbols. We then compare the description of // the symbols given to the comment that follows the call. var mscorlibRef = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30316_17626.mscorlib.AsImmutableOrNull(), display: "mscorlib"); var references = new[] { mscorlibRef }.Concat(additionalRefs ?? SpecializedCollections.EmptyArray <MetadataReference>()); var compilation = CreateCompilation(source, references, TestOptions.Dll.WithAllowUnsafe(true)); var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, diagnostics); var tree = BoundTreeDumperNodeProducer.MakeTree(block); var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value) .Where(x => x.Text == "method" && x.Value != null) .Select(x => x.Value) .ToArray()); // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray(); var expected = string.Join("\n", source .Split(new[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries) .Where(x => x.Contains("//-")) .Select(x => x.Substring(x.IndexOf("//-") + 3)) .ToArray()); AssertEx.Equal(expected, results); }
public CompilationVerifier CompileWithCustomILSource(string cSharpSource, string ilSource, Action <CSharpCompilation> compilationVerifier = null, bool importInternals = true, EmitOptions emitOptions = EmitOptions.All, string expectedOutput = null) { var compilationOptions = importInternals ? ((expectedOutput != null) ? TestOptions.ExeAlwaysImportInternals : TestOptions.DllAlwaysImportInternals) : ((expectedOutput != null) ? TestOptions.Exe : TestOptions.Dll); if (ilSource == null) { var c = CreateCompilationWithMscorlib(cSharpSource, compOptions: compilationOptions); return(CompileAndVerify(c, emitOptions: emitOptions, expectedOutput: expectedOutput)); } MetadataReference reference = null; using (var tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource)) { reference = new MetadataImageReference(ReadFromFile(tempAssembly.Path)); } var compilation = CreateCompilationWithMscorlib(cSharpSource, new[] { reference }, compilationOptions); if (compilationVerifier != null) { compilationVerifier(compilation); } return(CompileAndVerify(compilation, emitOptions: emitOptions, expectedOutput: expectedOutput)); }
internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null) { // The mechanism of this test is: we build the bound tree for the code passed in and then extract // from it the nodes that describe the method symbols. We then compare the description of // the symbols given to the comment that follows the call. var mscorlibRef = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30316_17626.mscorlib.AsImmutableOrNull(), display: "mscorlib"); var references = new[] { mscorlibRef }.Concat(additionalRefs ?? SpecializedCollections.EmptyArray<MetadataReference>()); var compilation = CreateCompilation(source, references, TestOptions.ReleaseDll); var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), diagnostics); var tree = BoundTreeDumperNodeProducer.MakeTree(block); var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value) .Where(x => x.Text == "method" && x.Value != null) .Select(x => x.Value) .ToArray()); // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray(); var expected = string.Join("\n", source .Split(new[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries) .Where(x => x.Contains("//-")) .Select(x => x.Substring(x.IndexOf("//-") + 3)) .ToArray()); AssertEx.Equal(expected, results); }
public void CanBeReferencedByName() { var vbText = @" Public Interface I Property P(x As Integer) End Interface "; var vbcomp = VisualBasicCompilation.Create( "Test", new[] { VisualBasicSyntaxTree.ParseText(vbText) }, new[] { MscorlibRef_v4_0_30316_17626 }, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var metaDataArray = vbcomp.EmitToArray(); var ref1 = new MetadataImageReference(metaDataArray, embedInteropTypes: true); var text = @"class C : I {}"; var tree = Parse(text); var comp = CreateCompilation(new [] { tree }, new [] { ref1 }); var t = comp.GetTypeByMetadataName("I"); Assert.Empty(t.GetMembersUnordered().Where(x => x.Kind == SymbolKind.Method && !x.CanBeReferencedByName)); Assert.False(t.GetMembersUnordered().Where(x => x.Kind == SymbolKind.Property).First().CanBeReferencedByName); //there's only one. }
public void Test_007B() { // Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IReadOnlyList<S>. var testSrc = @" using System.Collections.Generic; namespace Test { public class Program { public static void Main() { int[] array = new int[] {1, 2, 3}; object obj = array; IEnumerable<int> ro1 = array; IReadOnlyList<int> ro2 = (IReadOnlyList<int>)obj; IReadOnlyList<int> ro3 = (IReadOnlyList<int>)array; IReadOnlyList<int> ro4 = obj as IReadOnlyList<int>; System.Console.WriteLine(ro4 != null ? 1 : 2); } } } "; // The version of mscorlib checked in to the test resources in v4_0_30316 does not have // the IReadOnlyList<T> and IReadOnlyCollection<T> interfaces. Use the one in v4_0_30316_17626. var mscorlib17626 = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30316_17626.mscorlib.AsImmutableOrNull(), display: "mscorlib"); CompileAndVerify(testSrc, new MetadataReference[] { mscorlib17626 }, expectedOutput: "1"); }
public void MetadataImageReference_Module_WithXxx() { var doc = new TestDocumentationProvider(); var module = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1); var r = new MetadataImageReference(module, fullPath: @"c:\temp", display: "hello", documentation: doc); Assert.Same(doc, r.DocumentationProvider); Assert.Same(doc, r.DocumentationProvider); Assert.NotNull(r.GetMetadata()); Assert.Equal(false, r.Properties.EmbedInteropTypes); Assert.Equal(MetadataImageKind.Module, r.Properties.Kind); Assert.True(r.Properties.Aliases.IsDefault); Assert.Equal(@"c:\temp", r.FullPath); var r1 = r.WithAliases(default(ImmutableArray <string>)); Assert.Same(r, r1); var r2 = r.WithEmbedInteropTypes(false); Assert.Same(r, r2); var r3 = r.WithDocumentationProvider(doc); Assert.Same(r, r3); Assert.Throws <ArgumentException>(() => r.WithAliases(new[] { "bar" })); Assert.Throws <ArgumentException>(() => r.WithEmbedInteropTypes(true)); }
public void MetadataImageReference_Module_WithXxx() { var doc = new TestDocumentationProvider(); var module = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1); var r = new MetadataImageReference(module, filePath: @"c:\temp", display: "hello", documentation: doc); Assert.Same(doc, r.DocumentationProvider); Assert.Same(doc, r.DocumentationProvider); Assert.NotNull(r.GetMetadata()); Assert.Equal(false, r.Properties.EmbedInteropTypes); Assert.Equal(MetadataImageKind.Module, r.Properties.Kind); Assert.True(r.Properties.Aliases.IsDefault); Assert.Equal(@"c:\temp", r.FilePath); var r1 = r.WithAliases(default(ImmutableArray<string>)); Assert.Same(r, r1); var r2 = r.WithEmbedInteropTypes(false); Assert.Same(r, r2); var r3 = r.WithDocumentationProvider(doc); Assert.Same(r, r3); Assert.Throws<ArgumentException>(() => r.WithAliases(new[] { "bar" })); Assert.Throws<ArgumentException>(() => r.WithEmbedInteropTypes(true)); }
private void AddAsseblyReference(List <MetadataImageReference> assemblies, HashSet <AssemblyIdentity> added, AssemblyIdentity assemblyIdentity) { if (added.Contains(assemblyIdentity)) { return; } var resolvedFilePath = this.ResolveReferencePath(assemblyIdentity); if (resolvedFilePath == null) { return; } var metadata = AssemblyMetadata.CreateFromImageStream(new FileStream(resolvedFilePath, FileMode.Open, FileAccess.Read)); if (added.Add(metadata.Assembly.Identity)) { var metadataImageReference = new MetadataImageReference(new FileStream(resolvedFilePath, FileMode.Open, FileAccess.Read)); assemblies.Add(metadataImageReference); this.LoadAssemblySymbol(metadata, true); // process nested foreach (var refAssemblyIdentity in metadata.Assembly.AssemblyReferences) { this.AddAsseblyReference(assemblies, added, refAssemblyIdentity); } } }
public void NoDecimalConversion() { var source1 = @"namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Int32 { } public struct Decimal { } }"; var compilation1 = CreateCompilation(source1, assemblyName: GetUniqueName()); var reference1 = new MetadataImageReference(compilation1.EmitToStream()); var source2 = @"class C { static int M(decimal d) { return (int)d; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); // Should report "CS0656: Missing compiler required member 'System.Decimal.op_Explicit_ToInt32'". // Instead, we report no errors and assert during emit. compilation2.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation2); }
public void DumpWinMDPrefixing() { var winmd = new MetadataImageReference(TestResources.WinRt.WinMDPrefixing.AsImmutableOrNull()); var actual = Dump(winmd, new[] { WindowsRef }); var expected = Encoding.UTF8.GetString(TestResources.WinRt.WinMDPrefixing_dump); AssertDumpsEqual(expected, actual); }
public void MetadataImageReference_Assembly_WithXxx() { var doc = new TestDocumentationProvider(); var assembly = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1); var r = new MetadataImageReference( assembly, documentation: doc, aliases: ImmutableArray.Create("a"), embedInteropTypes: true, fullPath: @"c:\temp", display: "hello"); Assert.Same(doc, r.DocumentationProvider); Assert.Same(doc, r.DocumentationProvider); Assert.NotNull(r.GetMetadata()); Assert.Equal(true, r.Properties.EmbedInteropTypes); Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind); AssertEx.Equal(new[] { "a" }, r.Properties.Aliases); Assert.Equal(@"c:\temp", r.FullPath); var r2 = r.WithEmbedInteropTypes(true); Assert.Equal(r, r2); var r3 = r.WithAliases(ImmutableArray.Create("b", "c")); Assert.Same(r.DocumentationProvider, r3.DocumentationProvider); Assert.Same(r.GetMetadata(), r3.GetMetadata()); Assert.Equal(r.Properties.EmbedInteropTypes, r3.Properties.EmbedInteropTypes); Assert.Equal(r.Properties.Kind, r3.Properties.Kind); AssertEx.Equal(new[] { "b", "c" }, r3.Properties.Aliases); Assert.Equal(r.FullPath, r3.FullPath); var r4 = r.WithEmbedInteropTypes(false); Assert.Same(r.DocumentationProvider, r4.DocumentationProvider); Assert.Same(r.GetMetadata(), r4.GetMetadata()); Assert.Equal(false, r4.Properties.EmbedInteropTypes); Assert.Equal(r.Properties.Kind, r4.Properties.Kind); AssertEx.Equal(r.Properties.Aliases, r4.Properties.Aliases); Assert.Equal(r.FullPath, r4.FullPath); Assert.Throws <ArgumentNullException>(() => r.WithDocumentationProvider(null)); Assert.Same(r, r.WithDocumentationProvider(r.DocumentationProvider)); var doc2 = new TestDocumentationProvider(); var r5 = r.WithDocumentationProvider(doc2); Assert.Same(doc2, r5.DocumentationProvider); Assert.Same(r.GetMetadata(), r5.GetMetadata()); Assert.Equal(r.Properties.EmbedInteropTypes, r5.Properties.EmbedInteropTypes); Assert.Equal(r.Properties.Kind, r5.Properties.Kind); AssertEx.Equal(r.Properties.Aliases, r5.Properties.Aliases); Assert.Equal(r.FullPath, r5.FullPath); }
public void MetadataImageReferenceFromStream() { MetadataImageReference r; r = new MetadataImageReference(new MemoryStream(TestResources.SymbolsTests.General.C1, writable: false)); Assert.Equal("<in-memory assembly>".NeedsLocalization(), r.Display); Assert.Equal("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", ((AssemblyMetadata)r.GetMetadata()).Assembly.Identity.GetDisplayName()); }
public void WellKnownTypesAndAliases() { var lib = @" namespace System.Threading.Tasks { public class Task { public int Status; } } "; var source = @" extern alias myTask; using System.Threading; using System.Threading.Tasks; class App { async void AM() { } } "; var libComp = CreateCompilationWithMscorlib45(lib, assemblyName: "lib"); var libRef = new MetadataImageReference(libComp.EmitToArray(), aliases: ImmutableArray.Create("myTask")); var comp = CreateCompilationWithMscorlib45(source, new[] { libRef }); // NOTE: As in dev11, we don't consider myTask::System.Threading.Tasks.Task to be // ambiguous with global::System.Threading.Tasks.Task (prefer global). comp.VerifyDiagnostics( // (7,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void AM() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "AM"), // (3,1): info CS8019: Unnecessary using directive. // using System.Threading; Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Threading;"), // (4,1): info CS8019: Unnecessary using directive. // using System.Threading.Tasks; Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System.Threading.Tasks;"), // (2,1): info CS8020: Unused extern alias. // extern alias myTask; Diagnostic(ErrorCode.INF_UnusedExternAlias, "extern alias myTask;")); var taskType = comp.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task); Assert.Equal(TypeKind.Class, taskType.TypeKind); Assert.Equal("System.Threading.Tasks.Task", taskType.ToTestDisplayString()); // When we look in a single assembly, we don't consider referenced assemblies. Assert.Null(comp.Assembly.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)); Assert.Null(comp.Assembly.GetTypeByMetadataName("System.Threading.Tasks.Task")); Assert.Equal(taskType, comp.Assembly.CorLibrary.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)); Assert.Equal(taskType, comp.Assembly.CorLibrary.GetTypeByMetadataName("System.Threading.Tasks.Task")); }
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); } OutputStream = new MemoryStream(); EmitResult = Compilation.Emit(OutputStream); if (!EmitResult.Success) { return(EmitResult); } OutputStream.Position = 0; Reference = new MetadataImageReference(OutputStream); OutputStream.Position = 0; return(EmitResult); }
public void MissingCompareExchange() { var source1 = @"namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Boolean { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public struct IntPtr { private IntPtr m_value; IntPtr Use(IntPtr b) { m_value = b; return m_value; } } } "; var compilation1 = CreateCompilation(source1, assemblyName: GetUniqueName()); var reference1 = new MetadataImageReference(compilation1.EmitToStream()); var source2 = @" public delegate void E1(); class C { public event E1 e; public static void Main() { var v = new C(); v.e += Main; } } "; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (7,21): warning CS0067: The event 'C.e' is never used // public event E1 e; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("C.e") ); compilation2.Emit(new System.IO.MemoryStream()).Diagnostics.Verify( // (12,28): error CS0656: Missing compiler required member 'System.Threading.Interlocked.CompareExchange' // public static event E1 e; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e").WithArguments("System.Threading.Interlocked", "CompareExchange"), // (12,28): error CS0656: Missing compiler required member 'System.Threading.Interlocked.CompareExchange' // public static event E1 e; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e").WithArguments("System.Threading.Interlocked", "CompareExchange"), // (12,28): warning CS0067: The event 'C.e' is never used // public static event E1 e; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("C.e")); }
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 = CreateCompilationWithMscorlib(src, assemblyName: "Baz.dll", compOptions: TestOptions.Dll); var outputBytes = comp.EmitToArray(); var foo1 = new MetadataImageReference(outputBytes); var foo1Alias = new MetadataImageReference(outputBytes, aliases: ImmutableArray.Create("Baz")); src = @" namespace NS { public class Bar : Baz { public int M2() { return 2; } } } "; comp = CreateCompilationWithMscorlib(src, assemblyName: "Bar.dll", compOptions: TestOptions.Dll); comp = comp.AddReferences(foo1); var foo2 = new MetadataImageReference(comp.EmitToArray()); src = @" class Maine { public static void Main() { NS.Bar d = null; } } "; comp = CreateCompilationWithMscorlib(src); comp = comp.AddReferences(foo2, foo1Alias); 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 = new MetadataImageReference(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") ); }
public void Equivalence() { var comparer = CommonReferenceManager <CS.CSharpCompilation, IAssemblySymbol> .MetadataReferenceEqualityComparer.Instance; var f1 = MscorlibRef; var f2 = SystemCoreRef; var i1 = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30319.mscorlib.AsImmutableOrNull(), display: "i1"); var i2 = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30319.mscorlib.AsImmutableOrNull(), display: "i2"); var m1a = new MyReference(@"c:\a\foo.dll", display: "m1a"); Assert.Equal("m1a", ((PortableExecutableReference )m1a).Display); var m1b = new MyReference(@"c:\b\..\a\foo.dll", display: "m1b"); Assert.Equal("m1b", ((PortableExecutableReference)m1b).Display); var m2 = new MyReference(@"c:\b\foo.dll", display: "m2"); Assert.Equal("m2", ((PortableExecutableReference)m2).Display); var m3 = new MyReference(null, display: "m3"); var m4 = new MyReference(null, display: "m4"); var c1a = CS.CSharpCompilation.Create("foo").ToMetadataReference(); var c1b = c1a.Compilation.ToMetadataReference(); var c2 = CS.CSharpCompilation.Create("foo").ToMetadataReference(); var all = new MetadataReference[] { f1, f2, i1, i2, m1a, m1b, m2, c1a, c1b, c2 }; foreach (var r in all) { foreach (var s in all) { var eq = comparer.Equals(r, s); if (ReferenceEquals(r, s) || ReferenceEquals(r, c1a) && ReferenceEquals(s, c1b) || ReferenceEquals(s, c1a) && ReferenceEquals(r, c1b) || ReferenceEquals(r, m1a) && ReferenceEquals(s, m1b) || ReferenceEquals(s, m1a) && ReferenceEquals(r, m1b)) { Assert.True(eq, string.Format("expected '{0}' == '{1}'", r.Display, s.Display)); } else { Assert.False(eq, string.Format("expected '{0}' != '{1}'", r.Display, s.Display)); } } } }
public void MetadataImageReference_Assembly_Path() { var assembly = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1); // no path specified var mmr1 = new MetadataImageReference(assembly); Assert.Null(mmr1.FullPath); // path specified const string path = @"c:\some path that doesn't need to exist"; var r = new MetadataImageReference(assembly, fullPath: path); Assert.Equal(path, r.FullPath); }
public void ConstructedErrorTypes() { var source1 = @"public class A<T> { public class B<U> { } }"; var compilation1 = CreateCompilationWithMscorlib(source1, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A41"); compilation1.VerifyDiagnostics(); var reference1 = new MetadataImageReference(compilation1.EmitToArray(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 = CreateCompilationWithMscorlib(source2, references: new[] { reference1 }, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A42"); compilation2.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation2, missingTypes: false, fromSource: true); var reference2 = new MetadataImageReference(compilation2.EmitToArray(true)); // Loading types from metadata, no missing types. var source3 = @""; var compilation3 = CreateCompilationWithMscorlib(source3, references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation3, missingTypes: false, fromSource: false); // Binding types in source, missing types, resulting inExtendedErrorTypeSymbols. var compilation4 = CreateCompilationWithMscorlib(source2); CompareConstructedErrorTypes(compilation4, missingTypes: true, fromSource: true); // Loading types from metadata, missing types, resulting in ErrorTypeSymbols. var source5 = @""; var compilation5 = CreateCompilationWithMscorlib(source5, references: new[] { reference2 }); CompareConstructedErrorTypes(compilation5, missingTypes: true, fromSource: false); }
public void VersionUnification_SymbolNotUsed() { var v1 = new MetadataImageReference(TestResources.SymbolsTests.General.C1); var v2 = new MetadataImageReference(TestResources.SymbolsTests.General.C2); var refV1 = CreateCompilationWithMscorlib("public class D : C { }", new[] { v1 }); var refV2 = CreateCompilationWithMscorlib("public class D : C { }", new[] { v2 }); // reference asks for a lower version than available: var testRefV1 = CreateCompilationWithMscorlib("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }); // reference asks for a higher version than available: var testRefV2 = CreateCompilationWithMscorlib("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }); testRefV1.VerifyDiagnostics(); testRefV2.VerifyDiagnostics(); }
private MetadataReference GenerateShallowReference() { ShallowCompilation = CSharpCompilation.Create( assemblyName: AssemblyName, options: Worker.OriginalCompilation.Options, references: Worker.OriginalCompilation.References); foreach (var other in Requires) { if (other.Value == AssemblyNeutralWorker.OrderingState.StrengthKind.DeepUsage) { ShallowCompilation = ShallowCompilation.AddReferences(other.Key.RealOrShallowReference()); } } foreach (var syntaxReference in TypeSymbol.DeclaringSyntaxReferences) { var node = syntaxReference.GetSyntax(); var tree = syntaxReference.SyntaxTree; var root = tree.GetRoot(); var nodesToRemove = GetNodesToRemove(root, node); foreach (var member in TypeSymbol.GetMembers()) { foreach (var memberSyntaxReference in member.DeclaringSyntaxReferences) { if (memberSyntaxReference.SyntaxTree == tree) { nodesToRemove = nodesToRemove.Concat(new[] { memberSyntaxReference.GetSyntax() }); } } } var newRoot = root.RemoveNodes(nodesToRemove.ToArray(), SyntaxRemoveOptions.KeepDirectives); var newTree = SyntaxFactory.SyntaxTree(newRoot, options: tree.Options, path: tree.FilePath, encoding: Encoding.UTF8); ShallowCompilation = ShallowCompilation.AddSyntaxTrees(newTree); } ShallowOutputStream = new MemoryStream(); ShallowEmitResult = ShallowCompilation.Emit(ShallowOutputStream); ShallowOutputStream.Position = 0; ShallowReference = new MetadataImageReference(ShallowOutputStream); ShallowOutputStream.Position = 0; return(ShallowReference); }
public void DocCommentProvider() { var docProvider = new TestDocumentationProvider(); var corlib = new MetadataImageReference( ProprietaryTestResources.NetFX.v4_0_30319.mscorlib.AsImmutableOrNull(), display: "corlib", documentation: docProvider); var comp = CS.CSharpCompilation.Create("foo", syntaxTrees: new[] { CS.SyntaxFactory.ParseSyntaxTree("class C : System.Collections.ArrayList { }") }, references: new[] { corlib }); var c = (ITypeSymbol)comp.GlobalNamespace.GetMembers("C").Single(); var list = c.BaseType; var summary = list.GetDocumentationCommentXml(); Assert.Equal("<member name='T:System.Collections.ArrayList'><summary>T:System.Collections.ArrayList</summary></member>", summary); }
public void VersionUnification_SymbolUsed() { // Identity: C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9 var v1 = new MetadataImageReference(TestResources.SymbolsTests.General.C1, display: "C, V1"); // Identity: C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9 var v2 = new MetadataImageReference(TestResources.SymbolsTests.General.C2, display: "C, V2"); var refV1 = CreateCompilationWithMscorlib("public class D : C { }", new[] { v1 }, assemblyName: "refV1"); var refV2 = CreateCompilationWithMscorlib("public class D : C { }", new[] { v2 }, assemblyName: "refV2"); // reference asks for a lower version than available: var testRefV1 = CreateCompilationWithMscorlib("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }, assemblyName: "testRefV1"); // reference asks for a higher version than available: var testRefV2 = CreateCompilationWithMscorlib("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }, assemblyName: "testRefV2"); // TODO (tomat): we should display paths rather than names "refV1" and "C" testRefV1.VerifyDiagnostics( // warning CS1701: // Assuming assembly reference 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' // used by 'refV1' matches identity 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' of 'C', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "D").WithArguments( "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "refV1", "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "C")); // TODO (tomat): we should display paths rather than names "refV2" and "C" testRefV2.VerifyDiagnostics( // error CS1705: Assembly 'refV2' with identity 'refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // uses 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' which has a higher version than referenced assembly // 'C' with identity 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion, "D").WithArguments( "refV2", "refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "C", "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9")); }
public void SpecialTypesAndAliases() { var source = @"public class C { }"; var aliasedCorlib = new MetadataImageReference(ProprietaryTestResources.NetFX.v4_0_30319.mscorlib, aliases: ImmutableArray.Create("Foo")); var comp = CreateCompilation(source, new [] { aliasedCorlib }); // NOTE: this doesn't compile in dev11 - it reports that it cannot find System.Object. // However, we've already changed how special type lookup works, so this is not a major issue. comp.VerifyDiagnostics(); var objectType = comp.GetSpecialType(SpecialType.System_Object); Assert.Equal(TypeKind.Class, objectType.TypeKind); Assert.Equal("System.Object", objectType.ToTestDisplayString()); Assert.Equal(objectType, comp.Assembly.GetSpecialType(SpecialType.System_Object)); Assert.Equal(objectType, comp.Assembly.CorLibrary.GetSpecialType(SpecialType.System_Object)); }
public void InaccessibleReturnType() { var sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""B"")] internal class A { } "; var compilationA = CreateCompilationWithMscorlib(sourceA, assemblyName: "A"); var compilationVerifier = CompileAndVerify(compilationA, emitOptions: EmitOptions.CCI); var referenceA = new MetadataImageReference(compilationVerifier.EmittedAssemblyData); // Dev11 compiler doesn't allow this code, Roslyn does. var sourceB = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""C"")] public class B { internal A M() { return null; } } "; var compilationB = CreateCompilationWithMscorlib(sourceB, assemblyName: "B", references: new[] { referenceA }); compilationVerifier = CompileAndVerify(compilationB, emitOptions: EmitOptions.CCI); var referenceB = new MetadataImageReference(compilationVerifier.EmittedAssemblyData); var sourceC = @" class C { static void M(B b) { b.M(); } } "; var compilationC = CreateCompilationWithMscorlib(sourceC, assemblyName: "C", references: new[] { referenceA, referenceB }); compilationC.VerifyDiagnostics( // (5,9): error CS0122: 'B.M()' is inaccessible due to its protection level // b.M(); Diagnostic(ErrorCode.ERR_BadAccess, "b.M").WithArguments("B.M()")); }
public void AccessorWithImportedGenericType() { var comp0 = CreateCompilationWithMscorlib(@" public class MC<T> { } public delegate void MD<T>(T t); "); var compref = new CSharpCompilationReference(comp0); var comp1 = CreateCompilationWithMscorlib(@" 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(true); var mtref = new MetadataImageReference(mtdata); var comp2 = CreateCompilationWithMscorlib(@"", 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 InternalOverriddenMember() { var source1 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""B"")] public abstract class A { internal abstract void M(); internal abstract object P { get; } }"; var compilation1 = CreateCompilationWithMscorlib(source1, assemblyName: "A"); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1, emitOptions: EmitOptions.CCI); var reference1 = new MetadataImageReference(compilationVerifier.EmittedAssemblyData); var source2 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""C"")] public abstract class B : A { internal override abstract void M(); internal override abstract object P { get; } }"; var compilation2 = CreateCompilationWithMscorlib(source2, assemblyName: "B", references: new[] { reference1 }); compilation2.VerifyDiagnostics(); compilationVerifier = CompileAndVerify(compilation2, emitOptions: EmitOptions.CCI); var reference2 = new MetadataImageReference(compilationVerifier.EmittedAssemblyData); var source3 = @"class C { static object M(B b) { b.M(); return b.P; } }"; var compilation3 = CreateCompilationWithMscorlib(source3, assemblyName: "C", references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); }
public void MissingReturnType() { var comp1 = CreateCompilationWithMscorlib(@"public class C { }", assemblyName: "C"); var C = new MetadataImageReference(comp1.EmitToArray()); var comp2 = CreateCompilationWithMscorlib(@"public class B { public static C GetC() { return new C(); } }", assemblyName: "B", references: new[] { C }); var B = new MetadataImageReference(comp2.EmitToArray()); var comp3 = CreateCompilationWithMscorlib(@"public class A { public static void Main() { object o = B.GetC(); } }", assemblyName: "A", references: new[] { B }); comp3.VerifyDiagnostics( // (1,57): error CS0012: The type 'C' is defined in an assembly that is not referenced. // You must add a reference to assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef, "B.GetC").WithArguments("C", "C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); }
public void InvalidAttributeArgs1() { string csSource = @" class D { void M(C c) { var f1 = c.F1; var f2 = c.F2; var f3 = c.F3; var f4 = c.F4; var f5 = c.F5; var f6 = c.F6; var m1 = c.M1(); var m2 = c.M2(); var p1 = c.P1; var p2 = c.P2; } } "; var dll = new MetadataImageReference(TestResources.MetadataTests.Invalid.InvalidDynamicAttributeArgs.AsImmutableOrNull()); var c = CreateCompilationWithMscorlib(csSource, new[] { dll }); c.VerifyDiagnostics( // (7,20): error CS0570: 'C.F1' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("C.F1"), // (7,20): error CS0570: 'C.F2' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("C.F2"), // (8,18): error CS0570: 'C.M1()' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("C.M1()"), // (9,18): error CS0570: 'C.M2()' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "M2").WithArguments("C.M2()"), // (10,20): error CS0570: 'C.P1' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "P1").WithArguments("C.P1"), // (11,20): error CS0570: 'C.P2' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "P2").WithArguments("C.P2")); }
public void HostObjectInInMemoryAssembly() { var lib = CreateCSharpCompilation("public class C { public int X = 1, Y = 2; }", new[] { TestReferences.NetFx.v4_0_30319.mscorlib }, "HostLib"); var libImage = lib.EmitToArray(); var libRef = MetadataImageReference.CreateFromImage(libImage); var libAssembly = Assembly.Load(libImage.ToArray()); var globalsType = libAssembly.GetType("C"); var globals = Activator.CreateInstance(globalsType); using (var loader = new InteractiveAssemblyLoader()) { loader.RegisterDependency(libAssembly); var script = CSharpScript.Create <int>( "X+Y", ScriptOptions.Default.WithReferences(libRef), globalsType: globalsType, assemblyLoader: loader); int result = script.RunAsync(globals).Result.ReturnValue; Assert.Equal(3, result); } }
public void Error_ExternAliasIdentifierIsGlobalKeyword() { var src = @" namespace NS { public class Baz { public int M() { return 1; } } } "; var comp = CreateCompilationWithMscorlib(src, compOptions: TestOptions.Dll); var foo1Alias = new MetadataImageReference(comp.EmitToArray(), aliases: ImmutableArray.Create("global")); src = @" extern alias global; class Maine { public static void Main() { } } "; comp = CreateCompilationWithMscorlib(src); comp = comp.AddReferences(foo1Alias); comp.VerifyDiagnostics( // (2,14): error CS1681: You cannot redefine the global extern alias // extern alias global; Diagnostic(ErrorCode.ERR_GlobalExternAlias, "global"), // (2,1): info CS8020: Unused extern alias. // extern alias global; Diagnostic(ErrorCode.INF_UnusedExternAlias, "extern alias global;")); }
public void InvalidFunc_Arity() { var systemCoreRef = CreateCompilationWithMscorlib(SystemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); var funcRef = new MetadataImageReference(TestResources.MetadataTests.Invalid.InvalidFuncDelegateName.AsImmutableOrNull()); string source = @" class C { dynamic F(dynamic d) { return d(1,2,3,4,5,6,7,8,9,10); // Func`13 } } "; // the delegate is generated, no error is reported var c = CompileAndVerify(source, new[] { systemCoreRef, csrtRef, funcRef }); Assert.Equal(1, ((CSharpCompilation)c.Compilation).GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMember<NamedTypeSymbol>("Func`13").Arity); }
public void GetIndex_IndexerWithByRefParam() { var ilRef = new MetadataImageReference(TestResources.MetadataTests.Interop.IndexerWithByRefParam.AsImmutableOrNull()); string source = @" class C { B b; dynamic d; object M() { return b[d]; } } "; CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, ilRef }, expectedOptimizedIL: @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<M>o__SiteContainer0.<>p__Site1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<M>o__SiteContainer0.<>p__Site1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<M>o__SiteContainer0.<>p__Site1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<M>o__SiteContainer0.<>p__Site1"" IL_004a: ldarg.0 IL_004b: ldfld ""B C.b"" IL_0050: ldarg.0 IL_0051: ldfld ""dynamic C.d"" IL_0056: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_005b: ret } "); }
public void GenericType1() { string source = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public class LocalTypes2 { public void Test2(S1 x, S2<int> y) { } } [CompilerGenerated, TypeIdentifier(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""S1"")] public struct S1 { public int F1; } [CompilerGenerated, TypeIdentifier(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""S2`1"")] public struct S2<T> { public int F1; } [ComEventInterface(typeof(S1), typeof(S2<>))] interface AttrTest1 { } "; var localTypes2 = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Dll, assemblyName: "LocalTypes2"); //CompileAndVerify(localTypes2); var localTypes2Image = new MetadataImageReference(localTypes2.EmitToArray()); string piaSource = @" using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [assembly: ImportedFromTypeLib(""Pia1.dll"")] public struct S1 { public int F1; } public struct S2<T> { public int F1; } "; var pia = CreateCompilationWithMscorlib(piaSource, compOptions: TestOptions.Dll, assemblyName: "Pia"); CompileAndVerify(pia); var piaImage = new MetadataImageReference(pia.EmitToArray()); var compilation = CreateCompilationWithMscorlib("", compOptions: TestOptions.Dll, references: new MetadataReference[] {new CSharpCompilationReference(localTypes2), new CSharpCompilationReference(pia)}); NamedTypeSymbol lt = compilation.GetTypeByMetadataName("LocalTypes2"); var test2 = lt.GetMember<MethodSymbol>("Test2"); Assert.Equal("Pia", test2.Parameters[0].Type.ContainingAssembly.Name); Assert.IsType<UnsupportedMetadataTypeSymbol>(test2.Parameters[1].Type); NamedTypeSymbol attrTest1 = compilation.GetTypeByMetadataName("AttrTest1"); var args = attrTest1.GetAttributes()[0].CommonConstructorArguments; Assert.Equal("Pia", ((TypeSymbol)args[0].Value).ContainingAssembly.Name); Assert.IsType<UnsupportedMetadataTypeSymbol>(args[1].Value); compilation = CreateCompilationWithMscorlib("", compOptions: TestOptions.Dll, references: new MetadataReference[] {localTypes2Image, new CSharpCompilationReference(pia)}); lt = compilation.GetTypeByMetadataName("LocalTypes2"); test2 = lt.GetMember<MethodSymbol>("Test2"); Assert.Equal("Pia", test2.Parameters[0].Type.ContainingAssembly.Name); Assert.IsType<UnsupportedMetadataTypeSymbol>(test2.Parameters[1].Type); attrTest1 = compilation.GetTypeByMetadataName("AttrTest1"); args = attrTest1.GetAttributes()[0].CommonConstructorArguments; Assert.Equal("Pia", ((TypeSymbol)args[0].Value).ContainingAssembly.Name); Assert.IsType<UnsupportedMetadataTypeSymbol>(args[1].Value); compilation = CreateCompilationWithMscorlib("", compOptions: TestOptions.Dll, references: new MetadataReference[] {new CSharpCompilationReference(localTypes2), piaImage}); lt = compilation.GetTypeByMetadataName("LocalTypes2"); test2 = lt.GetMember<MethodSymbol>("Test2"); Assert.Equal("Pia", test2.Parameters[0].Type.ContainingAssembly.Name); Assert.IsType<UnsupportedMetadataTypeSymbol>(test2.Parameters[1].Type); attrTest1 = compilation.GetTypeByMetadataName("AttrTest1"); args = attrTest1.GetAttributes()[0].CommonConstructorArguments; Assert.Equal("Pia", ((TypeSymbol)args[0].Value).ContainingAssembly.Name); Assert.IsType<UnsupportedMetadataTypeSymbol>(args[1].Value); compilation = CreateCompilationWithMscorlib("", compOptions: TestOptions.Dll, references: new MetadataReference[] {localTypes2Image, piaImage}); lt = compilation.GetTypeByMetadataName("LocalTypes2"); test2 = lt.GetMember<MethodSymbol>("Test2"); Assert.Equal("Pia", test2.Parameters[0].Type.ContainingAssembly.Name); Assert.IsType<UnsupportedMetadataTypeSymbol>(test2.Parameters[1].Type); attrTest1 = compilation.GetTypeByMetadataName("AttrTest1"); args = attrTest1.GetAttributes()[0].CommonConstructorArguments; Assert.Equal("Pia", ((TypeSymbol)args[0].Value).ContainingAssembly.Name); Assert.IsType<UnsupportedMetadataTypeSymbol>(args[1].Value); }
public void TypeForwarderInAModule() { string forwardedTypes = @" public class CF1 {}"; var forwardedTypesCompilation = CreateCompilationWithMscorlib(forwardedTypes, compOptions: TestOptions.Dll, assemblyName: "ForwarderTargetAssembly"); string mod = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF1))] "; var modCompilation = CreateCompilationWithMscorlib(mod, references: new[] { new CSharpCompilationReference(forwardedTypesCompilation) }, compOptions: TestOptions.NetModule); var modRef1 = modCompilation.EmitToImageReference(); string app = @" public class Test { } "; var appCompilation = CreateCompilationWithMscorlib(app, references: new[] { modRef1, new CSharpCompilationReference(forwardedTypesCompilation) }, compOptions: TestOptions.Dll); var module = (PEModuleSymbol)appCompilation.Assembly.Modules[1]; var metadata = module.Module; var peReader = metadata.GetMetadataReader(); Assert.Equal(1, peReader.GetTableRowCount(TableIndex.ExportedType)); ValidateExportedTypeRow(peReader.GetExportedTypes().First(), peReader, "CF1"); Handle token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. // Exported types in .Net module cause PEVerify to fail. CompileAndVerify(appCompilation, emitOptions: EmitOptions.RefEmitBug, verify: false, symbolValidator: m => { var peReader1 = ((PEModuleSymbol)m).Module.GetMetadataReader(); Assert.Equal(1, peReader1.GetTableRowCount(TableIndex.ExportedType)); ValidateExportedTypeRow(peReader1.GetExportedTypes().First(), peReader1, "CF1"); // Attributes should not actually be emitted. Assert.Equal(0, m.ContainingAssembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count()); }).VerifyDiagnostics(); var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern Microsoft.VisualBasic { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: .ver 10:0:0:0 } .assembly extern ForwarderTargetAssembly { .ver 0:0:0:0 } .module mod.netmodule // MVID: {EFC6E215-2156-4ACE-A787-67C58990AEB5} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0002 // WINDOWS_GUI .corflags 0x00000001 // ILONLY // Image base: 0x00980000 .custom ([mscorlib]System.Runtime.CompilerServices.AssemblyAttributesGoHereM) instance void [mscorlib]System.Runtime.CompilerServices.TypeForwardedToAttribute::.ctor(class [mscorlib]System.Type) = {type(class 'CF1, ForwarderTargetAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null')} "; var ilBytes = default(ImmutableArray<Byte>); using (var reference = SharedCompilationUtils.IlasmTempAssembly(ilSource, appendDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var modRef2 = new MetadataImageReference(ModuleMetadata.CreateFromImage(ilBytes)); appCompilation = CreateCompilationWithMscorlib(app, references: new MetadataReference [] { modRef2, new CSharpCompilationReference(forwardedTypesCompilation) }, compOptions: TestOptions.Dll); module = (PEModuleSymbol)appCompilation.Assembly.Modules[1]; metadata = module.Module; peReader = metadata.GetMetadataReader(); Assert.Equal(0, peReader.GetTableRowCount(TableIndex.ExportedType)); token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. Assert.Equal(1, peReader.CustomAttributes.Count); CompileAndVerify(appCompilation, emitOptions: EmitOptions.RefEmitBug, symbolValidator: m => { var peReader1 = ((PEModuleSymbol)m).Module.GetMetadataReader(); Assert.Equal(0, peReader1.GetTableRowCount(TableIndex.ExportedType)); // Attributes should not actually be emitted. Assert.Equal(0, m.ContainingAssembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count()); }).VerifyDiagnostics(); appCompilation = CreateCompilationWithMscorlib(app, references: new[] { modRef1, new CSharpCompilationReference(forwardedTypesCompilation) }, compOptions: TestOptions.NetModule); var appModule = ModuleMetadata.CreateFromImage(appCompilation.EmitToArray()).Module; peReader = appModule.GetMetadataReader(); Assert.Equal(0, peReader.GetTableRowCount(TableIndex.ExportedType)); token = appModule.GetTypeRef(appModule.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. appCompilation = CreateCompilationWithMscorlib(app, references: new[] { modRef1 }, compOptions: TestOptions.Dll); appCompilation.GetDeclarationDiagnostics().Verify( // error CS0012: The type 'CF1' is defined in an assembly that is not referenced. You must add a reference to assembly 'Test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("CF1", "ForwarderTargetAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); }
public void UseTypeInNetModule() { var module1Ref = new MetadataImageReference( ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1), display: "netModule1.netmodule"); var text = @"class Test { Class1 a = null; }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var comp = CreateCompilationWithMscorlib(text, references: new[] { module1Ref }); var globalNS = comp.SourceModule.GlobalNamespace; var classTest = globalNS.GetTypeMembers("Test").First(); var varA = classTest.GetMembers("a").First() as FieldSymbol; Assert.Equal(SymbolKind.Field, varA.Kind); Assert.Equal(TypeKind.Class, varA.Type.TypeKind); Assert.Equal(SymbolKind.NamedType, varA.Type.Kind); }
public void ExternAlias() { var source = @" extern alias X; class Test { static void Main() { X::C c = null; } } "; var comp1 = CreateCompilationWithMscorlib("public class C { }"); var ref1 = new MetadataImageReference(CompileAndVerify(comp1).EmittedAssemblyData, aliases: ImmutableArray.Create("X")); var comp2 = CreateCompilationWithMscorlib(source, new[] { ref1 }); var tree = comp2.SyntaxTrees.Single(); var model = comp2.GetSemanticModel(tree); var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Single(); // Compilation.GetExternAliasTarget defines this behavior: the target is a merged namespace // with the same name as the alias, contained in the global namespace of the compilation. var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax); var aliasTarget = (NamespaceSymbol)aliasSymbol.Target; Assert.Equal(NamespaceKind.Module, aliasTarget.Extent.Kind); Assert.Equal("", aliasTarget.Name); Assert.True(aliasTarget.IsGlobalNamespace); Assert.Null(aliasTarget.ContainingNamespace); Assert.Equal(0, comp2.GlobalNamespace.GetMembers("X").Length); //Doesn't contain the alias target namespace as a child. var aliasQualifiedSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AliasQualifiedNameSyntax>().Single(); Assert.Equal(aliasSymbol, model.GetAliasInfo(aliasQualifiedSyntax.Alias)); comp2.VerifyDiagnostics( // (8,14): warning CS0219: The variable 'c' is assigned but its value is never used // X::C c = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c")); }
public void NoSynthesizedInterfaceImplementation() { var xSource = @" public class X {} "; var xImage = CreateCompilationWithMscorlib(xSource, assemblyName: "X").EmitToArray(); var xRef = new MetadataImageReference(xImage, display: "X"); var libSource = @" public interface I { void Foo(X a); } public class C { public virtual void Foo(X a) { } } "; var lib = CreateCompilationWithMscorlib(libSource, new[] { xRef }, assemblyName: "Lib"); var mainSource = @" class B : C, I { } "; var main = CreateCompilationWithMscorlib(mainSource, new[] { new CSharpCompilationReference(lib) }, assemblyName: "Main"); main.VerifyEmitDiagnostics(); }
public void NameCollisionWithAddedModule_02() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module mod_1_1.netmodule // MVID: {98479031-F5D1-443D-AF73-CF21159C1BCF} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D30000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ns.c1<T> { } .class interface public abstract auto ansi c2<T> { } .class interface public abstract auto ansi ns.C3<T> { } .class interface public abstract auto ansi C4<T> { } .class interface public abstract auto ansi NS1.c5<T> { } "; ImmutableArray<Byte> ilBytes; using (var reference = SharedCompilationUtils.IlasmTempAssembly(ilSource, appendDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef1 = new MetadataImageReference(ModuleMetadata.CreateFromImage(ilBytes)); var mod2Source = @" namespace ns { public interface c1 {} public interface c3 {} } public interface c2 {} public interface c4 {} namespace ns1 { public interface c5 {} } "; var moduleRef2 = CreateCompilationWithMscorlib(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "mod_1_2").EmitToImageReference(); var compilation = CreateCompilationWithMscorlib("", new List<MetadataReference>() { moduleRef1, moduleRef2 }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8005: Type 'c2' exported from module 'mod_1_2.netmodule' conflicts with type 'c2<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("c2", "mod_1_2.netmodule", "c2<T>", "mod_1_1.netmodule"), // error CS8005: Type 'ns.c1' exported from module 'mod_1_2.netmodule' conflicts with type 'ns.c1<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("ns.c1", "mod_1_2.netmodule", "ns.c1<T>", "mod_1_1.netmodule") ); }
public void AccessorWithImportedGenericType() { var comp0 = CreateCompilationWithMscorlib(@" public class MC<T> { } public delegate void MD<T>(T t); "); var compref = new CSharpCompilationReference(comp0); var comp1 = CreateCompilationWithMscorlib(@" 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(true); var mtref = new MetadataImageReference(mtdata); var comp2 = CreateCompilationWithMscorlib(@"", 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 TestObsoleteAttributeInMetadata() { var peSource = @" using System; [Obsolete] public class TestClass1 {} [Obsolete(""TestClass2 is obsolete"")] public class TestClass2 {} [Obsolete(""Do not use TestClass3"", true)] public class TestClass3 {} [Obsolete(""TestClass4 is obsolete"", false)] public class TestClass4 {} public class TestClass { [Obsolete(""Do not use TestMethod"")] public void TestMethod() {} [Obsolete(""Do not use Prop1"", false)] public int Prop1 { get; set; } [Obsolete(""Do not use field1"", true)] public TestClass field1; [Obsolete(""Do not use event"", true)] public Action event1; } "; var peReference = new MetadataImageReference(CreateCompilationWithMscorlib(peSource).EmitToStream()); var source = @" public class Test { public static void foo1(TestClass1 c) {} public static void foo2(TestClass2 c) {} public static void foo3(TestClass3 c) {} public static void foo4(TestClass4 c) {} public static void Main() { TestClass c = new TestClass(); c.TestMethod(); var i = c.Prop1; c = c.field1; c.event1(); c.event1 += () => {}; } } "; CreateCompilationWithMscorlib(source, new[] { peReference }).VerifyDiagnostics( // (4,29): warning CS0612: 'TestClass1' is obsolete // public static void foo1(TestClass1 c) {} Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "TestClass1").WithArguments("TestClass1"), // (5,29): warning CS0618: 'TestClass2' is obsolete: 'TestClass2 is obsolete' // public static void foo2(TestClass2 c) {} Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "TestClass2").WithArguments("TestClass2", "TestClass2 is obsolete"), // (6,29): error CS0619: 'TestClass3' is obsolete: 'Do not use TestClass3' // public static void foo3(TestClass3 c) {} Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "TestClass3").WithArguments("TestClass3", "Do not use TestClass3"), // (7,29): warning CS0618: 'TestClass4' is obsolete: 'TestClass4 is obsolete' // public static void foo4(TestClass4 c) {} Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "TestClass4").WithArguments("TestClass4", "TestClass4 is obsolete"), // (12,9): warning CS0618: 'TestClass.TestMethod()' is obsolete: 'Do not use TestMethod' // c.TestMethod(); Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "c.TestMethod()").WithArguments("TestClass.TestMethod()", "Do not use TestMethod"), // (13,17): warning CS0618: 'TestClass.Prop1' is obsolete: 'Do not use Prop1' // var i = c.Prop1; Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "c.Prop1").WithArguments("TestClass.Prop1", "Do not use Prop1"), // (14,13): error CS0619: 'TestClass.field1' is obsolete: 'Do not use field1' // c = c.field1; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "c.field1").WithArguments("TestClass.field1", "Do not use field1"), // (15,9): error CS0619: 'TestClass.event1' is obsolete: 'Do not use event' // c.event1(); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "c.event1").WithArguments("TestClass.event1", "Do not use event"), // (16,9): error CS0619: 'TestClass.event1' is obsolete: 'Do not use event' // c.event1 += () => {}; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "c.event1").WithArguments("TestClass.event1", "Do not use event")); }
public void MemberSignature_LongFormType() { string source = @" public class D { public static void Main() { string s = C.RT(); double d = C.VT(); } } "; var longFormRef = new MetadataImageReference(TestResources.MetadataTests.Invalid.LongTypeFormInSignature.AsImmutableOrNull()); var c = CreateCompilationWithMscorlib(source, new[] { longFormRef }); c.VerifyDiagnostics( // (6,20): error CS0570: 'C.RT()' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "RT").WithArguments("C.RT()"), // (7,20): error CS0570: 'C.VT()' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "VT").WithArguments("C.VT()")); }
public void MultiDimArray() { var r = new MetadataImageReference(TestResources.SymbolsTests.Methods.CSMethods.AsImmutableOrNull()); var source = @" class Program { static void Main() { MultiDimArrays.Foo(null); } } "; CompileAndVerify(source, new[] { r }, emitOptions: EmitOptions.RefEmitBug); }
void EmitNetModuleWithReferencedNetModule() { string source1 = @"public class A {}"; string source2 = @"public class B: A {}"; var comp = CreateCompilationWithMscorlib(source1, compOptions: TestOptions.NetModule); var metadataRef = new MetadataImageReference(ModuleMetadata.CreateFromImageStream(comp.EmitToStream())); CompileAndVerify(source2, additionalRefs: new[] { metadataRef }, options: TestOptions.NetModule, emitOptions: EmitOptions.RefEmitBug, verify: false); }
public void EmitMetadataOnly_SynthesizedExplicitImplementations() { var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll; var libAssemblyName = "SynthesizedMethodMetadata"; var exeAssemblyName = "CallSynthesizedMethod"; // Setup: CppBase2 has methods that implement CppInterface1, but it doesn't declare // that it implements the interface. Class1 does declare that it implements the // interface, but it's empty so it counts on CppBase2 to provide the implementations. // Since CppBase2 is not in the current source module, bridge methods are inserted // into Class1 to implement the interface methods by delegating to CppBase2. var libText = @" public class Class1 : CppCli.CppBase2, CppCli.CppInterface1 { } "; var libComp = CreateCompilationWithMscorlib( text: libText, references: new MetadataReference[] { ilAssemblyReference }, compOptions: TestOptions.Dll, assemblyName: libAssemblyName); Assert.False(libComp.GetDiagnostics().Any()); EmitResult emitResult; byte[] dllImage; using (var output = new MemoryStream()) { emitResult = libComp.EmitMetadataOnly(output); dllImage = output.ToArray(); } Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); Assert.True(dllImage.Length > 0, "no metadata emitted"); // NOTE: this DLL won't PEVerify because there are no method bodies. var class1 = libComp.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("Class1"); // We would prefer to check that the module used by Compiler.Emit does the right thing, // but we don't have access to that object, so we'll create our own and manipulate it // in the same way. var module = new PEAssemblyBuilder((SourceAssemblySymbol)class1.ContainingAssembly, null, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); Compiler.CompileSynthesizedMethodMetadata(libComp, module, default(CancellationToken)); var class1TypeDef = (Cci.ITypeDefinition)class1; var symbolSynthesized = class1.GetSynthesizedExplicitImplementations(CancellationToken.None); var context = new Microsoft.CodeAnalysis.Emit.Context(module, null, new DiagnosticBag()); var cciExplicit = class1TypeDef.GetExplicitImplementationOverrides(context); var cciMethods = class1TypeDef.GetMethods(context).Where(m => ((MethodSymbol)m).MethodKind != MethodKind.Constructor); context.Diagnostics.Verify(); var symbolsSynthesizedCount = symbolSynthesized.Length; Assert.True(symbolsSynthesizedCount > 0, "Expected more than 0 synthesized method symbols."); Assert.Equal(symbolsSynthesizedCount, cciExplicit.Count()); Assert.Equal(symbolsSynthesizedCount, cciMethods.Count()); var libAssemblyReference = new MetadataImageReference(dllImage.AsImmutableOrNull()); var exeText = @" class Class2 { public static void Main() { CppCli.CppInterface1 c = new Class1(); c.Method1(1); c.Method2(2); } } "; var exeComp = CreateCompilationWithMscorlib( text: exeText, references: new MetadataReference[] { ilAssemblyReference, libAssemblyReference }, assemblyName: exeAssemblyName); Assert.False(exeComp.GetDiagnostics().Any()); using (var output = new MemoryStream()) { emitResult = exeComp.Emit(output); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); output.Flush(); Assert.True(output.Length > 0, "no metadata emitted"); } // NOTE: there's no point in trying to run the EXE since it depends on a DLL with no method bodies. }
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 = CreateCompilationWithMscorlib(src, assemblyName: "Baz.dll", options: TestOptions.ReleaseDll); var outputBytes = comp.EmitToArray(); var foo1 = new MetadataImageReference(outputBytes); var foo1Alias = new MetadataImageReference(outputBytes, aliases: ImmutableArray.Create("Baz")); src = @" namespace NS { public class Bar : Baz { public int M2() { return 2; } } } "; comp = CreateCompilationWithMscorlib(src, assemblyName: "Bar.dll", options: TestOptions.ReleaseDll); comp = comp.AddReferences(foo1); var foo2 = new MetadataImageReference(comp.EmitToArray()); src = @" class Maine { public static void Main() { NS.Bar d = null; } } "; comp = CreateCompilationWithMscorlib(src); comp = comp.AddReferences(foo2, foo1Alias); 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 Bug602893() { var source1 = @"namespace NA { internal static class A { public static void F(this object o) { } } }"; var compilation1 = CreateCompilationWithMscorlibAndSystemCore(source1, assemblyName: "A"); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1, emitOptions: EmitOptions.CCI); var reference1 = new MetadataImageReference(compilationVerifier.EmittedAssemblyData); var source2 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""C"")] namespace NB { internal static class B { public static void F(this object o) { } } }"; var compilation2 = CreateCompilationWithMscorlibAndSystemCore(source2, assemblyName: "B"); compilation2.VerifyDiagnostics(); compilationVerifier = CompileAndVerify(compilation2, emitOptions: EmitOptions.CCI); var reference2 = new MetadataImageReference(compilationVerifier.EmittedAssemblyData); var source3 = @"using NB; namespace NA.NC { class C { static void Main() { new object().F(); } } }"; var compilation3 = CreateCompilationWithMscorlib(source3, assemblyName: "C", references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); }
public void Error_ExternAliasIdentifierIsGlobalKeyword() { var src = @" namespace NS { public class Baz { public int M() { return 1; } } } "; var comp = CreateCompilationWithMscorlib(src, options: TestOptions.ReleaseDll); var foo1Alias = new MetadataImageReference(comp.EmitToArray(), aliases: ImmutableArray.Create("global")); src = @" extern alias global; class Maine { public static void Main() { } } "; comp = CreateCompilationWithMscorlib(src); comp = comp.AddReferences(foo1Alias); comp.VerifyDiagnostics( // (2,14): error CS1681: You cannot redefine the global extern alias // extern alias global; Diagnostic(ErrorCode.ERR_GlobalExternAlias, "global"), // (2,1): info CS8020: Unused extern alias. // extern alias global; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias global;")); }
public void SameExternAliasInMultipleTreesValid() { var comp1 = CreateCompilationWithMscorlib("public class C { }", assemblyName: "A1"); var ref1 = new MetadataImageReference(CompileAndVerify(comp1).EmittedAssemblyData, aliases: ImmutableArray.Create("X")); var comp2 = CreateCompilationWithMscorlib("public class D { }", assemblyName: "A2"); var ref2 = new MetadataImageReference(CompileAndVerify(comp2).EmittedAssemblyData, aliases: ImmutableArray.Create("X")); const int numFiles = 20; var comp3 = CreateCompilationWithMscorlib(Enumerable.Range(1, numFiles).Select(x => "extern alias X;"), new[] { ref1, ref2 }, assemblyName: "A3.dll"); var targets = comp3.SyntaxTrees.AsParallel().Select(tree => { var model = comp3.GetSemanticModel(tree); var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Single(); var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax); return (NamespaceSymbol)aliasSymbol.Target; }).ToArray(); //force evaluation var firstTarget = targets.First(); Assert.NotNull(firstTarget); Assert.IsType<MergedNamespaceSymbol>(firstTarget); firstTarget.GetMember<NamedTypeSymbol>("C"); firstTarget.GetMember<NamedTypeSymbol>("D"); Assert.True(targets.All(target => ReferenceEquals(firstTarget, target))); }
public void MissingStringLengthForEach() { var source1 = @"namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Boolean { } public class String : System.Collections.IEnumerable { public System.Collections.IEnumerator GetEnumerator() { return null; } } public interface IDisposable { void Dispose(); } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); } }"; var compilation1 = CreateCompilation(source1, assemblyName: GetUniqueName()); var reference1 = new MetadataImageReference(compilation1.EmitToStream()); var source2 = @"class C { static void M(string s) { foreach (var c in s) { // comment } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics(); compilation2.Emit(new System.IO.MemoryStream()).Diagnostics.Verify( // (5,9): error CS0656: Missing compiler required member 'System.String.get_Length' // foreach (var c in s) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var c in s) { // comment }").WithArguments("System.String", "get_Length"), // (5,9): error CS0656: Missing compiler required member 'System.String.get_Chars' // foreach (var c in s) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"foreach (var c in s) { // comment }").WithArguments("System.String", "get_Chars") ); }
public void NameCollisionWithAddedModule_01() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module ITest20Mod.netmodule // MVID: {53AFCDC2-985A-43AE-928E-89B4A4017344} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00EC0000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ITest20<T> { } // end of class ITest20 "; ImmutableArray<Byte> ilBytes; using (var reference = SharedCompilationUtils.IlasmTempAssembly(ilSource, appendDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef = new MetadataImageReference(ModuleMetadata.CreateFromImage(ilBytes)); var source = @" interface ITest20 {} "; var compilation = CreateCompilationWithMscorlib(source, new List<MetadataReference>() { moduleRef }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8004: Type 'ITest20<T>' exported from module 'ITest20Mod.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("ITest20<T>", "ITest20Mod.netmodule") ); }
public void EmitForwarder_ModuleInReferencedAssembly() { string moduleA = @"public class Foo{ public static string A = ""Original""; }"; var bitsA = CreateCompilationWithMscorlib(moduleA, compOptions: TestOptions.Dll, assemblyName: "asm2").EmitToArray(); var refA = new MetadataImageReference(bitsA); string moduleB = @"using System; class Program2222 { static void Main(string[] args) { Console.WriteLine(Foo.A); } }"; var bitsB = CreateCompilationWithMscorlib(moduleB, new[] { refA }, TestOptions.Exe, assemblyName: "test").EmitToArray(); string module0 = @"public class Foo{ public static string A = ""Substituted""; }"; var bits0 = CreateCompilationWithMscorlib(module0, compOptions: TestOptions.NetModule, assemblyName: "asm0").EmitToArray(); var ref0 = new MetadataImageReference(ModuleMetadata.CreateFromImage(bits0)); string module1 = "using System;"; var bits1 = CreateCompilationWithMscorlib(module1, new[] { ref0 }, compOptions: TestOptions.Dll, assemblyName: "asm1").EmitToArray(); var ref1 = new MetadataImageReference(AssemblyMetadata.Create(ModuleMetadata.CreateFromImage(bits1), ModuleMetadata.CreateFromImage(bits0))); string module2 = @"using System; [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Foo))]"; var bits2 = CreateCompilationWithMscorlib(module2, new[] { ref1 }, compOptions: TestOptions.Dll, assemblyName: "asm2").EmitToArray(); // runtime check: var folder = Temp.CreateDirectory(); var folderA = folder.CreateDirectory("A"); var folderB = folder.CreateDirectory("B"); folderA.CreateFile("asm2.dll").WriteAllBytes(bitsA); var asmB = folderA.CreateFile("test.exe").WriteAllBytes(bitsB); var result = RunAndGetOutput(asmB.Path); Assert.Equal("Original", result.Trim()); folderB.CreateFile("asm0.netmodule").WriteAllBytes(bits0); var asm1 = folderB.CreateFile("asm1.dll").WriteAllBytes(bits1); var asm2 = folderB.CreateFile("asm2.dll").WriteAllBytes(bits2); var asmB2 = folderB.CreateFile("test.exe").WriteAllBytes(bitsB); result = RunAndGetOutput(asmB2.Path); Assert.Equal("Substituted", result.Trim()); }
private void CheckForwarderEmit2(string source0, string source1, string source2, params string[] forwardedTypeFullNames) { var folder = Temp.CreateDirectory(); var comp0 = CreateCompilationWithMscorlib(source0, compOptions: TestOptions.NetModule, assemblyName: "asm0"); var asm0 = ModuleMetadata.CreateFromImage(CompileAndVerify(comp0, emitOptions: EmitOptions.RefEmitBug, verify: false).EmittedAssemblyData); var ref0 = new MetadataImageReference(asm0); var comp1 = CreateCompilationWithMscorlib(source1, new[] { ref0 }, compOptions: TestOptions.Dll, assemblyName: "asm1"); var asm1 = ModuleMetadata.CreateFromImage(CompileAndVerify(comp1, emitOptions: EmitOptions.RefEmitBug).EmittedAssemblyData); var assembly1 = AssemblyMetadata.Create(asm1, asm0); var ref1 = new MetadataImageReference(assembly1); var comp2 = CreateCompilationWithMscorlib(source2, new[] { ref1 }, compOptions: TestOptions.Dll, assemblyName: "asm2"); Action<ModuleSymbol> metadataValidator = module => { var assembly = module.ContainingAssembly; // Attributes should not actually be emitted. Assert.Equal(0, assembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count()); var topLevelTypes = new HashSet<string>(); foreach (var fullName in forwardedTypeFullNames) { var plus = fullName.IndexOf('+'); if (plus != -1) { topLevelTypes.Add(fullName.Substring(0, plus)); } else { topLevelTypes.Add(fullName); } } foreach (var fullName in topLevelTypes) { var type = assembly.ResolveForwardedType(fullName); Assert.NotNull(type); Assert.NotEqual(TypeKind.Error, type.TypeKind); Assert.Equal("asm1", type.ContainingAssembly.Name); } }; var verifier2 = CompileAndVerify(comp2, emitOptions: EmitOptions.RefEmitBug, symbolValidator: metadataValidator); var asm2 = folder.CreateFile("asm2.dll"); asm2.WriteAllBytes(verifier2.EmittedAssemblyData); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(verifier2.EmittedAssemblyData)) { var peReader = metadata.Module.GetMetadataReader(); Assert.Equal(forwardedTypeFullNames.Length, peReader.GetTableRowCount(TableIndex.ExportedType)); int i = 0; foreach (var exportedType in peReader.GetExportedTypes()) { ValidateExportedTypeRow(exportedType, peReader, forwardedTypeFullNames[i]); i++; } } }