public void Ctor_Errors()
        {
            Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.CreateFromImage(default(ImmutableArray <byte>)));

            IEnumerable <byte> enumerableImage = null;

            Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.CreateFromImage(enumerableImage));

            byte[] arrayImage = null;
            Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.CreateFromImage(arrayImage));

            Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.Create((ModuleMetadata)null));
            Assert.Throws <ArgumentException>(() => AssemblyMetadata.Create(default(ImmutableArray <ModuleMetadata>)));
            Assert.Throws <ArgumentException>(() => AssemblyMetadata.Create(ImmutableArray.Create <ModuleMetadata>()));

            var m1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.MultiModuleDll);
            var m2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod2);
            var m3 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod3);

            Assert.Throws <ArgumentException>(() => AssemblyMetadata.Create(m1, m2.Copy(), m3));
            Assert.Throws <ArgumentException>(() => AssemblyMetadata.Create(new List <ModuleMetadata>(new ModuleMetadata[] { m1.Copy(), m2.Copy(), m3.Copy() })));
            Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.Create(ImmutableArray.Create(m1, m2, null)));
            Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.Create(ImmutableArray.Create((ModuleMetadata)null)));

            Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.CreateFromFile((string)null));
        }
예제 #2
0
        public void TestTypetoDocumentNavigationMethodWithNoBody()
        {
            string sourceA = @"
using System;

public partial  class C
{
#line hidden
    public void F1() {}  
#line default

    public void F2() {}
    public void F3() {}  

}
";

            string sourceB = @"
using System;

public partial class C
{
   
    
}
";

            var c1 = CreateCompilation(new[]
            {
                SyntaxFactory.ParseSyntaxTree(sourceA, path: "X.cs", encoding: Encoding.UTF8),
                SyntaxFactory.ParseSyntaxTree(sourceB, path: "Z.cs", encoding: Encoding.UTF8)
            }, options: TestOptions.DebugDll);

            var pdbStream = new MemoryStream();
            var peImage   = c1.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream);

            pdbStream.Position = 0;


            string source2           = @"
using System;

public class Program
{
    public static void Main() { }   
}
";
            var    assemblyMetadata  = AssemblyMetadata.CreateFromImage(peImage);
            var    metadataReference = assemblyMetadata.GetReference();
            var    c2     = CreateCompilation(new[] { source2 }, new[] { metadataReference }, options: TestOptions.DebugDll);
            var    typeC  = c2.GetTypeByMetadataName("C");
            Symbol symbol = typeC.GetMethod("F1");

            using var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream);
            var pdbReader = provider.GetMetadataReader();
            var docList   = FindSourceDocuments(symbol, pdbReader);

            Assert.Equal(0x30000001, MetadataTokens.GetToken(docList[0]));
            Assert.Equal(0x30000002, MetadataTokens.GetToken(docList[1]));
        }
예제 #3
0
        public void Keywords()
        {
            var source =
                @"namespace @namespace
{
    struct @struct
    {
    }
}
class async
{
    (async @var, @namespace.@struct @class) F;
}";
            var assembly0    = GenerateTupleAssembly();
            var reference0   = AssemblyMetadata.CreateFromImage(assembly0).GetReference();
            var compilation1 = CSharpTestBaseBase.CreateCompilationWithMscorlib(source, references: new[] { reference0 });
            var assembly1    = compilation1.EmitToArray();
            var runtime      = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(ReflectionUtilities.Load(assembly0), ReflectionUtilities.Load(assembly1)));

            using (runtime.Load())
            {
                var type       = runtime.GetType("async");
                var value      = type.Instantiate();
                var evalResult = FormatResult("o", value);
                Verify(evalResult,
                       EvalResult("o", "{async}", "async", "o", DkmEvaluationResultFlags.Expandable));
                var children = GetChildren(evalResult);
                Verify(children,
                       EvalResult("F", "(null, {namespace.struct})", "(async, namespace.struct)", "o.F", DkmEvaluationResultFlags.Expandable));
            }
        }
예제 #4
0
        internal static void CheckAttribute(IEnumerable <byte> assembly, IMethodSymbol method, AttributeDescription description, bool expected)
        {
            var module = AssemblyMetadata.CreateFromImage(assembly).GetModules().Single().Module;

            var typeName   = method.ContainingType.Name;
            var typeHandle = module.MetadataReader.TypeDefinitions
                             .Single(handle => module.GetTypeDefNameOrThrow(handle) == typeName);

            var methodName   = method.Name;
            var methodHandle = module
                               .GetMethodsOfTypeOrThrow(typeHandle)
                               .Single(handle => module.GetMethodDefNameOrThrow(handle) == methodName);

            var returnParamHandle = module.GetParametersOfMethodOrThrow(methodHandle).FirstOrDefault();

            if (returnParamHandle.IsNil)
            {
                Assert.False(expected);
            }
            else
            {
                var attributes = module
                                 .GetCustomAttributesOrThrow(returnParamHandle)
                                 .Where(handle => module.GetTargetAttributeSignatureIndex(handle, description) != -1);

                if (expected)
                {
                    Assert.Equal(1, attributes.Count());
                }
                else
                {
                    Assert.Empty(attributes);
                }
            }
        }
        public void CanResolveTypeFromReference()
        {
            var pluginNamespace = "TestPlugins";
            var pluginClass     = "MyPlugin";
            var pluginAssembly  = "MyPlugins";
            var pluginWorkspace = TestWorkspaceFactory.GetWorkspace(null, pluginNamespace, pluginClass, pluginAssembly);
            var pluginBinary    = TestWorkspaceFactory.BuildAndGetPe(pluginWorkspace);

            string pluginPath = $"Z:\\plugins\\{pluginAssembly}.dll";

            var reference = AssemblyMetadata.CreateFromImage(pluginBinary).GetReference(filePath: pluginPath, display: $"{pluginAssembly}.dll");

            var workspace = TestWorkspaceFactory.GetWorkspace(new[] { reference });

            var pathMock = new Mock <IPath>(MockBehavior.Strict);

            pathMock.Setup(p => p.GetFileName(It.IsAny <string>())).Returns <string>(v => Path.GetFileName(v));
            var fileMock = new Mock <IFile>(MockBehavior.Strict);

            fileMock.Setup(f => f.ReadAllBytes(It.Is <string>(v => v == pluginPath))).Returns(pluginBinary);
            var fileSystemMock = new Mock <IFileSystem>(MockBehavior.Strict);

            fileSystemMock.Setup(p => p.Path).Returns(pathMock.Object);
            fileSystemMock.Setup(p => p.File).Returns(fileMock.Object);

            var subject = new ProjectReferenceTypeLoader(new WorkspaceManager(workspace), fileSystemMock.Object, AssemblyLoadContext.Default);

            Action action = () => { subject.LoadType($"{pluginNamespace}.{pluginClass}, {pluginAssembly}"); };

            //// Temporary thing. I hope.
            action.Should().Throw <FileNotFoundException>();
        }
예제 #6
0
        public void Display()
        {
            MetadataReference r;

            r = MetadataReference.CreateFromImage(TestResources.General.C1);
            Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);

            r = ModuleMetadata.CreateFromImage(TestResources.General.C1).GetReference();
            Assert.Equal(CodeAnalysisResources.InMemoryModule, r.Display);

            r = MetadataReference.CreateFromImage(TestResources.General.C1, filePath: @"c:\blah");
            Assert.Equal(@"c:\blah", r.Display);

            r = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(display: @"dddd");
            Assert.Equal(@"dddd", r.Display);

            r = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\blah", display: @"dddd");
            Assert.Equal(@"dddd", 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);
        }
예제 #7
0
        public void DebuggerDisplayAttribute()
        {
            var source =
                @"using System.Diagnostics;
[DebuggerDisplay(""F={F}"")]
class A
{
    internal object F;
}
class B
{
    (A, A) F = (new A() { F = 1 }, new A() { F = 2 });
}";
            var assembly0    = GenerateTupleAssembly();
            var reference0   = AssemblyMetadata.CreateFromImage(assembly0).GetReference();
            var compilation1 = CSharpTestBaseBase.CreateCompilationWithMscorlib(source, references: new[] { reference0 });
            var assembly1    = compilation1.EmitToArray();
            var runtime      = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(ReflectionUtilities.Load(assembly0), ReflectionUtilities.Load(assembly1)));

            using (runtime.Load())
            {
                var type       = runtime.GetType("B");
                var value      = type.Instantiate();
                var evalResult = FormatResult("o", value);
                var children   = GetChildren(evalResult);
                Verify(children,
                       EvalResult("F", "({A}, {A})", "(A, A)", "o.F", DkmEvaluationResultFlags.Expandable));
                children = GetChildren(children[0]);
                Verify(children,
                       EvalResult("Item1", "F=1", "A", "o.F.Item1", DkmEvaluationResultFlags.Expandable),
                       EvalResult("Item2", "F=2", "A", "o.F.Item2", DkmEvaluationResultFlags.Expandable));
            }
        }
예제 #8
0
        /// <summary>
        /// Gets a MetadataReference to a project's output assembly.
        /// </summary>
        private async Task <MetadataReference> GetProjectMetadata(string projectFilePath, ImmutableArray <string> aliases, IDictionary <string, string> globalProperties, CancellationToken cancellationToken)
        {
            try
            {
                // use loader service to determine output file for project if possible
                var outputFilePath = await ProjectFileLoader.GetOutputFilePathAsync(projectFilePath, globalProperties, cancellationToken).ConfigureAwait(false);

                if (outputFilePath != null && File.Exists(outputFilePath))
                {
                    var docProvider = this.GetDocumentationProvider(outputFilePath);

                    if (Workspace.TestHookStandaloneProjectsDoNotHoldReferences)
                    {
                        return(new MetadataImageReference(
                                   AssemblyMetadata.CreateFromImage(ImmutableArray.Create(File.ReadAllBytes(outputFilePath))),
                                   documentation: docProvider,
                                   aliases: aliases,
                                   display: outputFilePath));
                    }
                    else
                    {
                        return(new MetadataFileReference(outputFilePath, new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases), docProvider));
                    }
                }
            }
            catch (System.IO.IOException exception)
            {
                this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.FileAccessFailure, exception.Message, this.GetOrCreateProjectId(projectFilePath)));
            }

            return(null);
        }
예제 #9
0
        public void NamesAndDynamic()
        {
            var source =
                @"class C
{
    (dynamic A, (int B, dynamic C)[] D, dynamic E, (int F, dynamic G, int H, int I, int J, int K, int L, int M, int N) O) F =
        (1, new (int, dynamic)[] { (2, 3) }, (4, 5), (6, 7, 8, 9, 10, 11, 12, 13, 14));
}";
            var assembly0    = GenerateTupleAssembly();
            var reference0   = AssemblyMetadata.CreateFromImage(assembly0).GetReference();
            var compilation1 = CSharpTestBaseBase.CreateCompilationWithMscorlib45AndCSruntime(source, additionalRefs: new[] { reference0 });
            var assembly1    = compilation1.EmitToArray();
            var runtime      = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(ReflectionUtilities.Load(assembly0), ReflectionUtilities.Load(assembly1)));

            using (runtime.Load())
            {
                var type       = runtime.GetType("C");
                var value      = type.Instantiate();
                var evalResult = FormatResult("o", value);
                var children   = GetChildren(evalResult);
                Verify(children,
                       EvalResult(
                           "F",
                           "(1, {(int, object)[1]}, (4, 5), (6, 7, 8, 9, 10, 11, 12, 13, 14))",
                           "(dynamic A, (int B, dynamic C)[] D, dynamic E, (int F, dynamic G, int H, int I, int J, int K, int L, int M, int N) O) {(object, (int, object)[], object, (int, object, int, int, int, int, int, int, int))}",
                           "o.F",
                           DkmEvaluationResultFlags.Expandable));
            }
        }
예제 #10
0
        public void Names_LongTuple()
        {
            var source =
                @"class C
{
    ((int A, (int B, int C) D, int E, int F, int G, int H, int I, int J) K, (int L, int M, int N) O) F =
        ((1, (2, 3), 4, 5, 6, 7, 8, 9), (10, 11, 12));
}";
            var assembly0    = GenerateTupleAssembly();
            var reference0   = AssemblyMetadata.CreateFromImage(assembly0).GetReference();
            var compilation1 = CSharpTestBaseBase.CreateCompilationWithMscorlib45AndCSruntime(source, additionalRefs: new[] { reference0 });
            var assembly1    = compilation1.EmitToArray();
            var runtime      = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(ReflectionUtilities.Load(assembly0), ReflectionUtilities.Load(assembly1)));

            using (runtime.Load())
            {
                var type       = runtime.GetType("C");
                var value      = type.Instantiate();
                var evalResult = FormatResult("o", value);
                var children   = GetChildren(evalResult);
                Verify(children,
                       EvalResult(
                           "F",
                           "((1, (2, 3), 4, 5, 6, 7, 8, 9), (10, 11, 12))",
                           "((int A, (int B, int C) D, int E, int F, int G, int H, int I, int J) K, (int L, int M, int N) O)",
                           "o.F",
                           DkmEvaluationResultFlags.Expandable));
            }
        }
예제 #11
0
        public void Dynamic()
        {
            var source =
                @"class C
{
    (dynamic, (object, dynamic)) F = (1, (2, 3));
    (object, object, object, object, object, object, dynamic[], dynamic[]) G = (1, 2, 3, 4, 5, 6, new object[] { 7 }, new object[] { 8 });
}";
            var assembly0    = GenerateTupleAssembly();
            var reference0   = AssemblyMetadata.CreateFromImage(assembly0).GetReference();
            var compilation1 = CSharpTestBaseBase.CreateCompilationWithMscorlib45AndCSruntime(source, additionalRefs: new[] { reference0 });
            var assembly1    = compilation1.EmitToArray();
            var runtime      = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(ReflectionUtilities.Load(assembly0), ReflectionUtilities.Load(assembly1)));

            using (runtime.Load())
            {
                var type       = runtime.GetType("C");
                var value      = type.Instantiate();
                var evalResult = FormatResult("o", value);
                var children   = GetChildren(evalResult);
                Verify(children,
                       EvalResult(
                           "F",
                           "(1, (2, 3))",
                           "(dynamic, (object, dynamic)) {(object, (object, object))}",
                           "o.F",
                           DkmEvaluationResultFlags.Expandable),
                       EvalResult(
                           "G",
                           "(1, 2, 3, 4, 5, 6, {object[1]}, {object[1]})",
                           "(object, object, object, object, object, object, dynamic[], dynamic[]) {(object, object, object, object, object, object, object[], object[])}",
                           "o.G",
                           DkmEvaluationResultFlags.Expandable));
            }
        }
예제 #12
0
        public void DocCommentProvider()
        {
            var docProvider = new TestDocumentationProvider();
            var corlib      = AssemblyMetadata
                              .CreateFromImage(ResourcesNet451.mscorlib)
                              .GetReference(display: "corlib", documentation: docProvider);

            var comp = (Compilation)CS.CSharpCompilation.Create(
                "goo",
                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
                );
        }
예제 #13
0
 public void Win10OnWin10()
 {
     CompileTimeAndRuntimeAssemblies(
         ImmutableArray.Create(
             MscorlibRef,
             AssemblyMetadata
             .CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData))
             .GetReference(),
             AssemblyMetadata
             .CreateFromImage(
                 ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)
                 )
             .GetReference(),
             AssemblyMetadata
             .CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA))
             .GetReference(),
             AssemblyMetadata
             .CreateFromImage(TestResources.ExpressionCompiler.LibraryB)
             .GetReference()
             ),
         ImmutableArray.Create(
             MscorlibRef,
             AssemblyMetadata
             .CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.Windows))
             .GetReference(),
             AssemblyMetadata
             .CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA))
             .GetReference(),
             AssemblyMetadata
             .CreateFromImage(TestResources.ExpressionCompiler.LibraryB)
             .GetReference()
             ),
         "Windows"
         );
 }
예제 #14
0
        public void WinMdAssemblyQualifiedType()
        {
            var source =
                @"using System;

[MyAttribute(typeof(C1))]
public class C
{
    public static void Main(string[] args)
    {
    }
}

public class MyAttribute : System.Attribute
{
    public MyAttribute(System.Type type)
    {
    }
}
";

            CompileAndVerify(
                source,
                WinRtRefs.Concat(new[] { AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1).GetReference() }),
                symbolValidator: m =>
            {
                var module          = (PEModuleSymbol)m;
                var c               = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMember("C");
                var attributeHandle = module.Module.MetadataReader.GetCustomAttributes(c.Handle).Single();
                string value;
                module.Module.TryExtractStringValueFromAttribute(attributeHandle, out value);

                Assert.Equal("C1, W, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", value);
            });
        }
예제 #15
0
        public void CompilationChain_SystemObject_NotEquals()
        {
            // As in VS/ETA, make a new list of references for each submission.

            var options = new CSharpParseOptions(kind: SourceCodeKind.Interactive, documentationMode: DocumentationMode.None);
            var corLib  = AssemblyMetadata.CreateFromImage(TestResources.NetFX.v4_0_30319.mscorlib);

            var s1 = CSharpCompilation.CreateSubmission("s1.dll",
                                                        syntaxTree: SyntaxFactory.ParseSyntaxTree("struct S { }", options),
                                                        references: new[] { corLib.GetReference(documentation: new TestDocumentationProviderNoEquals()) },
                                                        returnType: typeof(object));

            s1.VerifyDiagnostics();

            var s2 = CSharpCompilation.CreateSubmission("s2.dll",
                                                        syntaxTree: SyntaxFactory.ParseSyntaxTree("System.Collections.IEnumerable Iterator() { yield return new S(); }", options),
                                                        previousSubmission: s1,
                                                        references: new[] { corLib.GetReference(documentation: new TestDocumentationProviderNoEquals()) },
                                                        returnType: typeof(object));

            Assert.NotEqual(s1.GetSpecialType(SpecialType.System_Object), s2.GetSpecialType(SpecialType.System_Object));

            s2.VerifyDiagnostics(
                // (1,58): error CS0029: Cannot implicitly convert type 'S' to 'object'
                // System.Collections.IEnumerable Iterator() { yield return new S(); }
                Diagnostic(ErrorCode.ERR_NoImplicitConv, "new S()").WithArguments("S", "object"));
        }
        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);
        }
예제 #17
0
        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 = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.NetFX.v4_0_30316_17626.mscorlib).GetReference(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);
        }
예제 #18
0
 public void IncorrectCustomAssemblyTableSize_TooManyMethodSpecs()
 {
     Assert.Throws <BadImageFormatException>(() =>
     {
         AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.Invalid.IncorrectCustomAssemblyTableSize_TooManyMethodSpecs);
     });
 }
예제 #19
0
        public void Display()
        {
            MetadataReference r;

            r = MetadataReference.CreateFromImage(TestResources.SymbolsTests.General.C1);
            Assert.Equal("<in-memory assembly>", r.Display);

            r = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1).GetReference();
            Assert.Equal("<in-memory module>", r.Display);

            r = MetadataReference.CreateFromImage(TestResources.SymbolsTests.General.C1, filePath: @"c:\blah");
            Assert.Equal(@"c:\blah", r.Display);

            r = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1).GetReference(display: @"dddd");
            Assert.Equal(@"dddd", r.Display);

            r = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.General.C1).GetReference(filePath: @"c:\blah", display: @"dddd");
            Assert.Equal(@"dddd", 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);
        }
예제 #20
0
        /// <summary>
        /// Gets a MetadataReference to a project's output assembly.
        /// </summary>
        private async Task <MetadataReference> GetProjectMetadata(string projectFilePath, ImmutableArray <string> aliases, IDictionary <string, string> globalProperties, CancellationToken cancellationToken)
        {
            // use loader service to determine output file for project if possible
            var outputFilePath = await ProjectFileLoader.GetOutputFilePathAsync(projectFilePath, globalProperties, cancellationToken).ConfigureAwait(false);

            if (outputFilePath != null && File.Exists(outputFilePath))
            {
                if (Workspace.TestHookStandaloneProjectsDoNotHoldReferences)
                {
                    var documentationService = this.Services.GetService <IDocumentationProviderService>();
                    var docProvider          = documentationService.GetDocumentationProvider(outputFilePath);
                    var metadata             = AssemblyMetadata.CreateFromImage(File.ReadAllBytes(outputFilePath));

                    return(metadata.GetReference(
                               documentation: docProvider,
                               aliases: aliases,
                               display: outputFilePath));
                }
                else
                {
                    var metadataService = this.Services.GetService <IMetadataService>();
                    return(metadataService.GetReference(outputFilePath, new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases)));
                }
            }

            return(null);
        }
예제 #21
0
        public void ContainsNoPiaLocalTypes()
        {
            using (
                AssemblyMetadata piaMetadata = AssemblyMetadata.CreateFromImage(
                    TestResources.SymbolsTests.NoPia.Pia1
                    ),
                metadata1 = AssemblyMetadata.CreateFromImage(
                    TestResources.SymbolsTests.NoPia.LocalTypes1
                    ),
                metadata2 = AssemblyMetadata.CreateFromImage(
                    TestResources.SymbolsTests.NoPia.LocalTypes2
                    )
                )
            {
                var pia1        = piaMetadata.GetAssembly().Modules[0];
                var localTypes1 = metadata1.GetAssembly().Modules[0];
                var localTypes2 = metadata2.GetAssembly().Modules[0];

                Assert.False(pia1.ContainsNoPiaLocalTypes());
                Assert.False(pia1.ContainsNoPiaLocalTypes());

                Assert.True(localTypes1.ContainsNoPiaLocalTypes());
                Assert.True(localTypes1.ContainsNoPiaLocalTypes());

                Assert.True(localTypes2.ContainsNoPiaLocalTypes());
                Assert.True(localTypes2.ContainsNoPiaLocalTypes());
            }
        }
예제 #22
0
        internal static MetadataReference CompileIL(string ilSource, bool appendDefaultHeader = true, bool embedInteropTypes = false)
        {
            ImmutableArray <byte> assemblyBytes;
            ImmutableArray <byte> pdbBytes;

            EmitILToArray(ilSource, appendDefaultHeader, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
            return(AssemblyMetadata.CreateFromImage(assemblyBytes).GetReference(embedInteropTypes: embedInteropTypes));
        }
예제 #23
0
 public void CreateFromBytes()
 {
     using (var a = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.MultiModuleDll))
     {
         // even though the image refers to other modules only the manifest module is loaded:
         Assert.Equal(1, a.GetModules().Length);
         Assert.Equal("MultiModule.dll", a.GetModules()[0].Name);
     }
 }
        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);
        }
예제 #25
0
        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 = CreateCompilation(
                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 = CreateCompilation(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 = CreateCompilation(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")
                );
        }
예제 #26
0
        public static Workspace GetWorkspaceWithReference(string referredAssemblyPath, string referredNs, string referredClass, string referredAssemblyName)
        {
            var referredWorkspace = GetWorkspace(null, referredNs, referredClass, referredAssemblyName);

            byte[] referredPe = BuildAndGetPe(referredWorkspace);

            var reference = AssemblyMetadata.CreateFromImage(referredPe).GetReference(filePath: referredAssemblyPath, display: $"{referredAssemblyName}.dll");

            return(GetWorkspace(new MetadataReference[] { reference }));
        }
예제 #27
0
        public void Assembly_WithXxx()
        {
            var doc      = new TestDocumentationProvider();
            var assembly = AssemblyMetadata.CreateFromImage(TestResources.General.C1);

            var r = assembly.GetReference(
                documentation: doc,
                aliases: ImmutableArray.Create("a"),
                embedInteropTypes: true,
                filePath: @"c:\temp",
                display: "hello");

            Assert.Same(doc, r.DocumentationProvider);
            Assert.Same(doc, r.DocumentationProvider);
            Assert.NotNull(r.GetMetadataNoCopy());
            Assert.True(r.Properties.EmbedInteropTypes);
            Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
            AssertEx.Equal(new[] { "a" }, r.Properties.Aliases);
            Assert.Equal(@"c:\temp", r.FilePath);

            var r2 = r.WithEmbedInteropTypes(true);

            Assert.Equal(r, r2);
            Assert.Equal(@"c:\temp", r2.FilePath);

            var r3 = r.WithAliases(ImmutableArray.Create("b", "c"));

            Assert.Same(r.DocumentationProvider, r3.DocumentationProvider);
            Assert.Same(r.GetMetadataNoCopy(), r3.GetMetadataNoCopy());
            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.FilePath, r3.FilePath);

            var r4 = r.WithEmbedInteropTypes(false);

            Assert.Same(r.DocumentationProvider, r4.DocumentationProvider);
            Assert.Same(r.GetMetadataNoCopy(), r4.GetMetadataNoCopy());
            Assert.False(r4.Properties.EmbedInteropTypes);
            Assert.Equal(r.Properties.Kind, r4.Properties.Kind);
            AssertEx.Equal(r.Properties.Aliases, r4.Properties.Aliases);
            Assert.Equal(r.FilePath, r4.FilePath);

            var r5 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module));

            Assert.Equal(MetadataImageKind.Module, r5.Properties.Kind);
            Assert.True(r5.Properties.Aliases.IsEmpty);
            Assert.False(r5.Properties.EmbedInteropTypes);

            var r6 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("x"), embedInteropTypes: true));

            Assert.Equal(MetadataImageKind.Assembly, r6.Properties.Kind);
            AssertEx.Equal(new[] { "x" }, r6.Properties.Aliases);
            Assert.True(r6.Properties.EmbedInteropTypes);
        }
예제 #28
0
        public void LongTuple()
        {
            var source =
                @"class C
{
    (short, short, short, short, short, short, short, short, short, short, short, short, short, short, short, short, short) _17 =
        (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17);
}";
            var assembly0    = GenerateTupleAssembly();
            var reference0   = AssemblyMetadata.CreateFromImage(assembly0).GetReference();
            var compilation1 = CSharpTestBaseBase.CreateCompilationWithMscorlib(source, references: new[] { reference0 });
            var assembly1    = compilation1.EmitToArray();
            var runtime      = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(ReflectionUtilities.Load(assembly0), ReflectionUtilities.Load(assembly1)));

            using (runtime.Load())
            {
                var inspectionContext = CreateDkmInspectionContext(radix: 16);
                var type       = runtime.GetType("C");
                var value      = type.Instantiate();
                var evalResult = FormatResult("o", value, inspectionContext: inspectionContext);
                Verify(evalResult,
                       EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
                var children = GetChildren(evalResult, inspectionContext);
                Verify(children,
                       EvalResult(
                           "_17",
                           "(0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011)",
                           "(short, short, short, short, short, short, short, short, short, short, short, short, short, short, short, short, short)",
                           "o._17",
                           DkmEvaluationResultFlags.Expandable));
                children = GetChildren(children[0], inspectionContext);
                Assert.Equal(8, children.Length); // Should be 18. https://github.com/dotnet/roslyn/issues/13421
                var child = children[children.Length - 1];
                Verify(child,
                       EvalResult(
                           "Rest",
                           "(0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011)",
                           "(short, short, short, short, short, short, short, short, short, short)",
                           "o._17.Rest",
                           DkmEvaluationResultFlags.Expandable));
                children = GetChildren(child, inspectionContext);
                Assert.Equal(8, children.Length); // Should be 11. https://github.com/dotnet/roslyn/issues/13421
                child = children[children.Length - 1];
                Verify(child,
                       EvalResult(
                           "Rest",
                           "(0x000f, 0x0010, 0x0011)",
                           "(short, short, short)",
                           "o._17.Rest.Rest",
                           DkmEvaluationResultFlags.Expandable));
            }
        }
예제 #29
0
 public static ModuleInstance Create(
     ImmutableArray <byte> assemblyImage,
     ISymUnmanagedReader symReader,
     bool includeLocalSignatures = true
     )
 {
     // create a new instance of metadata, the resulting object takes an ownership:
     return(Create(
                AssemblyMetadata.CreateFromImage(assemblyImage),
                symReader,
                includeLocalSignatures
                ));
 }
예제 #30
0
        public static MetadataReference EmitToImageReference(this Compilation comp, bool embedInteropTypes = false, ImmutableArray <string> aliases = default(ImmutableArray <string>), DiagnosticDescription[] expectedWarnings = null)
        {
            var image = comp.EmitToArray(expectedWarnings: expectedWarnings);

            if (comp.Options.OutputKind == OutputKind.NetModule)
            {
                return(ModuleMetadata.CreateFromImage(image).GetReference(display: comp.MakeSourceModuleName()));
            }
            else
            {
                return(AssemblyMetadata.CreateFromImage(image).GetReference(aliases: aliases, embedInteropTypes: embedInteropTypes, display: comp.MakeSourceAssemblySimpleName()));
            }
        }