コード例 #1
0
        public void NotYetLoadedWinMds_MultipleParts()
        {
            var source =
                @"class C
{
    static void M(Windows.UI.Colors c)
    {
    }
}";
            var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll);
            var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI");

            Assert.True(runtimeAssemblies.Any());
            var context = CreateMethodContextWithReferences(comp, "C.M", ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies));

            const string expectedError = "error CS0234: The type or namespace name 'Xaml' does not exist in the namespace 'Windows.UI' (are you missing an assembly reference?)";
            var          expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI.Xaml", contentType: System.Reflection.AssemblyContentType.WindowsRuntime);

            ResultProperties resultProperties;
            string           actualError;
            ImmutableArray <AssemblyIdentity> actualMissingAssemblyIdentities;

            context.CompileExpression(
                InspectionContextFactory.Empty,
                "typeof([email protected])",
                DkmEvaluationFlags.None,
                DiagnosticFormatter.Instance,
                out resultProperties,
                out actualError,
                out actualMissingAssemblyIdentities,
                EnsureEnglishUICulture.PreferredOrNull,
                testData: null);
            Assert.Equal(expectedError, actualError);
            Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
        }
コード例 #2
0
        internal static EvaluationContext CreateMethodContext(
            RuntimeInstance runtime,
            string methodName,
            int atLineNumber = -1)
        {
            ImmutableArray <MetadataBlock> blocks;
            Guid moduleVersionId;
            ISymUnmanagedReader symReader;
            int methodToken;
            int localSignatureToken;

            GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);

            int ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber);

            return(EvaluationContext.CreateMethodContext(
                       default(CSharpMetadataContext),
                       blocks,
                       symReader,
                       moduleVersionId,
                       methodToken: methodToken,
                       methodVersion: 1,
                       ilOffset: ilOffset,
                       localSignatureToken: localSignatureToken));
        }
コード例 #3
0
 internal static void VerifyLocal(
     CompilationTestData testData,
     string typeName,
     LocalAndMethod localAndMethod,
     string expectedMethodName,
     string expectedLocalName,
     DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None,
     string expectedILOpt = null,
     bool expectedGeneric = false,
     [CallerFilePath] string expectedValueSourcePath = null,
     [CallerLineNumber] int expectedValueSourceLine  = 0)
 {
     ExpressionCompilerTestHelpers.VerifyLocal <MethodSymbol>(
         testData,
         typeName,
         localAndMethod,
         expectedMethodName,
         expectedLocalName,
         expectedFlags,
         VerifyTypeParameters,
         expectedILOpt,
         expectedGeneric,
         expectedValueSourcePath,
         expectedValueSourceLine);
 }
コード例 #4
0
        public void BadPdb_DotInAlias()
        {
            var source  = @"
public class C
{
    public static void Main()
    {
    }
}
";
            var comp    = CreateCompilation(source);
            var peImage = comp.EmitToArray();

            var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports(
                peImage,
                "Main",
                "USystem",                                                                                                                  // Valid.
                "AMy.Alias TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped.
                "ASI USystem.IO");                                                                                                          // Valid.

            var module      = ModuleInstance.Create(peImage, symReader);
            var runtime     = CreateRuntimeInstance(module, new[] { MscorlibRef });
            var evalContext = CreateMethodContext(runtime, "C.Main");
            var compContext = evalContext.CreateCompilationContext(); // Used to throw.
            var imports     = compContext.NamespaceBinder.ImportChain.Single();

            Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString());
            Assert.Equal("SI", imports.UsingAliases.Keys.Single());
            Assert.Equal(0, imports.ExternAliases.Length);
        }
コード例 #5
0
ファイル: MissingAssemblyTests.cs プロジェクト: belav/roslyn
        public void CompileWithRetrySameErrorReported()
        {
            var source =
                @" 
class C 
{ 
    void M() 
    { 
    } 
}";
            var comp = CreateCompilation(source);

            WithRuntimeInstance(
                comp,
                runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");

                var missingModule   = runtime.Modules.First();
                var missingIdentity = missingModule
                                      .GetMetadataReader()
                                      .ReadAssemblyIdentityOrThrow();

                var numRetries = 0;
                string errorMessage;
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
                    runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
                    context,
                    (_, diagnostics) =>
                {
                    numRetries++;
                    Assert.InRange(numRetries, 0, 2);         // We don't want to loop forever...
                    diagnostics.Add(
                        new CSDiagnostic(
                            new CSDiagnosticInfo(
                                ErrorCode.ERR_NoTypeDef,
                                "MissingType",
                                missingIdentity
                                ),
                            Location.None
                            )
                        );
                    return(null);
                },
                    (AssemblyIdentity assemblyIdentity, out uint uSize) =>
                {
                    uSize = (uint)missingModule.MetadataLength;
                    return(missingModule.MetadataAddress);
                },
                    out errorMessage
                    );

                Assert.Equal(2, numRetries);     // Ensure that we actually retried and that we bailed out on the second retry if the same identity was seen in the diagnostics.
                Assert.Equal(
                    $"error CS0012: {string.Format(CSharpResources.ERR_NoTypeDef, "MissingType", missingIdentity)}",
                    errorMessage
                    );
            }
                );
        }
コード例 #6
0
        public void OtherFrameworkAssembly()
        {
            var source =
                @"class C
{
    static void M(Windows.UI.Xaml.FrameworkElement f)
    {
    }
}";
            var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll);

            WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")), runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                string error;
                ResultProperties resultProperties;
                ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;
                var testData = new CompilationTestData();
                var result   = context.CompileExpression(
                    "f.RenderSize",
                    DkmEvaluationFlags.TreatAsExpression,
                    NoAliases,
                    DebuggerDiagnosticFormatter.Instance,
                    out resultProperties,
                    out error,
                    out missingAssemblyIdentities,
                    EnsureEnglishUICulture.PreferredOrNull,
                    testData);
                var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity();
                Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single());
            });
        }
コード例 #7
0
        public void OldStyleNonCapturingLambda()
        {
            var ilSource = @"
.class public auto ansi beforefieldinit C
       extends [mscorlib]System.Object
{
  .method public hidebysig instance void 
          M() cil managed
  {
    ldnull
    throw
  }

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    ldarg.0
    call       instance void [mscorlib]System.Object::.ctor()
    ret
  }

  .method private hidebysig static int32 
          '<M>b__0'() cil managed
  {
    ldnull
    throw
  }
} // end of class C
";
            var module   = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource);
            var runtime  = CreateRuntimeInstance(module, new[] { MscorlibRef });
            var context  = CreateMethodContext(runtime, "C.<M>b__0");

            VerifyNoThis(context);
        }
コード例 #8
0
        public void BadPdb_DotInAlias()
        {
            var source = @"
public class C
{
    public static void Main()
    {
    }
}
";
            var comp   = CreateCompilationWithMscorlib(source);

            byte[] exeBytes;
            byte[] unusedPdbBytes;
            ImmutableArray <MetadataReference> references;
            var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);

            Assert.True(result);

            var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports(
                exeBytes,
                "Main",
                "USystem",                                                                                                                  // Valid.
                "AMy.Alias TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped.
                "ASI USystem.IO");                                                                                                          // Valid.

            var runtime     = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
            var evalContext = CreateMethodContext(runtime, "C.Main");
            var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); // Used to throw.
            var imports     = compContext.NamespaceBinder.ImportChain.Single();

            Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString());
            Assert.Equal("SI", imports.UsingAliases.Keys.Single());
            Assert.Equal(0, imports.ExternAliases.Length);
        }
コード例 #9
0
        public void Win8RuntimeAssemblies_ExternAlias()
        {
            var source =
                @"extern alias X;
class C
{
    static void M(X::Windows.Storage.StorageFolder f)
    {
    }
}";
            var compilation0 = CreateEmptyCompilation(
                source,
                options: TestOptions.DebugDll,
                assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
                references: WinRtRefs.Select(
                    r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r
                    )
                );

            var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds(
                "Windows.Storage"
                );

            Assert.True(runtimeAssemblies.Length >= 1);

            // no reference to Windows.winmd
            WithRuntimeInstance(
                compilation0,
                new[] { MscorlibRef }.Concat(runtimeAssemblies),
                runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                string error;
                var testData = new CompilationTestData();
                context.CompileExpression(
                    "X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified",
                    out error,
                    testData
                    );
                Assert.Null(error);
                testData
                .GetMethodData("<>x.<>m0")
                .VerifyIL(
                    @"{
  // Code size        2 (0x2)
  .maxstack  1
  IL_0000:  ldc.i4.0
  IL_0001:  ret
}"
                    );
            }
                );
        }
コード例 #10
0
ファイル: WinMdTests.cs プロジェクト: tinaschrepfer/roslyn
        public void AssemblyQualifiedName()
        {
            var source =
                @"class C
{
    static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
    {
    }
}";
            var runtime = CreateRuntime(
                source,
                ImmutableArray.CreateRange(WinRtRefs),
                ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")));
            var context = CreateMethodContext(runtime, "C.M");
            ResultProperties resultProperties;
            string           error;
            var testData = new CompilationTestData();
            ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;

            context.CompileExpression(
                InspectionContextFactory.Empty.
                Add("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime").
                Add("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
                "(object)s.Attributes ?? d.UniversalTime",
                DkmEvaluationFlags.TreatAsExpression,
                DiagnosticFormatter.Instance,
                out resultProperties,
                out error,
                out missingAssemblyIdentities,
                EnsureEnglishUICulture.PreferredOrNull,
                testData);
            Assert.Empty(missingAssemblyIdentities);
            testData.GetMethodData("<>x.<>m0").VerifyIL(
                @"{
  // Code size       55 (0x37)
  .maxstack  2
  IL_0000:  ldstr      ""s""
  IL_0005:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
  IL_000a:  castclass  ""Windows.Storage.StorageFolder""
  IL_000f:  callvirt   ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
  IL_0014:  box        ""Windows.Storage.FileAttributes""
  IL_0019:  dup
  IL_001a:  brtrue.s   IL_0036
  IL_001c:  pop
  IL_001d:  ldstr      ""d""
  IL_0022:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
  IL_0027:  unbox.any  ""Windows.Foundation.DateTime""
  IL_002c:  ldfld      ""long Windows.Foundation.DateTime.UniversalTime""
  IL_0031:  box        ""long""
  IL_0036:  ret
}");
        }
コード例 #11
0
ファイル: MissingAssemblyTests.cs プロジェクト: belav/roslyn
        public void NotYetLoadedWinMds()
        {
            var source =
                @"class C
{
    static void M(Windows.Storage.StorageFolder f)
    {
    }
}";
            var comp = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll);
            var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds(
                "Windows.Storage"
                );

            Assert.True(runtimeAssemblies.Any());

            WithRuntimeInstance(
                comp,
                new[] { MscorlibRef }.Concat(runtimeAssemblies),
                runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");

                const string expectedError =
                    "error CS0234: The type or namespace name 'UI' does not exist in the namespace 'Windows' (are you missing an assembly reference?)";
                var expectedMissingAssemblyIdentity = new AssemblyIdentity(
                    "Windows.UI",
                    contentType: System.Reflection.AssemblyContentType.WindowsRuntime
                    );

                ResultProperties resultProperties;
                string actualError;
                ImmutableArray <AssemblyIdentity> actualMissingAssemblyIdentities;
                context.CompileExpression(
                    "typeof(@Windows.UI.Colors)",
                    DkmEvaluationFlags.None,
                    NoAliases,
                    DebuggerDiagnosticFormatter.Instance,
                    out resultProperties,
                    out actualError,
                    out actualMissingAssemblyIdentities,
                    EnsureEnglishUICulture.PreferredOrNull,
                    testData: null
                    );
                Assert.Equal(expectedError, actualError);
                Assert.Equal(
                    expectedMissingAssemblyIdentity,
                    actualMissingAssemblyIdentities.Single()
                    );
            }
                );
        }
コード例 #12
0
        public void WinMdAssemblyReferenceRequiresRedirect()
        {
            var source =
                @"class C : Windows.UI.Xaml.Controls.UserControl
{
    static void M(C c)
    {
    }
}";
            var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll);

            WithRuntimeInstance(
                compilation,
                new[] { MscorlibRef }.Concat(
                    ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")
                    ),
                runtime =>
            {
                string errorMessage;
                var testData = new CompilationTestData();
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
                    runtime.Modules.SelectAsArray(m => m.MetadataBlock),
                    "c.Dispatcher",
                    ImmutableArray <Alias> .Empty,
                    (metadataBlocks, _) =>
                {
                    return(CreateMethodContext(runtime, "C.M"));
                },
                    (AssemblyIdentity assembly, out uint size) =>
                {
                    // Compilation should succeed without retry if we redirect assembly refs correctly.
                    // Throwing so that we don't loop forever (as we did before fix)...
                    throw ExceptionUtilities.Unreachable;
                },
                    out errorMessage,
                    out testData
                    );
                Assert.Null(errorMessage);
                testData
                .GetMethodData("<>x.<>m0")
                .VerifyIL(
                    @"{
  // Code size        7 (0x7)
  .maxstack  1
  IL_0000:  ldarg.0
  IL_0001:  callvirt   ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get""
  IL_0006:  ret
}"
                    );
            }
                );
        }
コード例 #13
0
        internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature)
        {
            string[] parameterTypeNames;
            var      methodOrTypeName = ExpressionCompilerTestHelpers.GetMethodOrTypeSignatureParts(signature, out parameterTypeNames);

            var candidates   = compilation.GetMembers(methodOrTypeName);
            var methodOrType = (parameterTypeNames == null) ?
                               candidates.FirstOrDefault() :
                               candidates.FirstOrDefault(c => parameterTypeNames.SequenceEqual(((MethodSymbol)c).Parameters.Select(p => p.Type.Name)));

            Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'.");
            return(methodOrType);
        }
コード例 #14
0
        public void Win8RuntimeAssemblies()
        {
            var source =
                @"class C
{
    static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
    {
    }
}";
            var compilation0 = CreateEmptyCompilation(
                source,
                options: TestOptions.DebugDll,
                assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
                references: WinRtRefs
                );

            var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds(
                "Windows.Storage",
                "Windows.Foundation.Collections"
                );

            Assert.True(runtimeAssemblies.Length >= 2);

            // no reference to Windows.winmd
            WithRuntimeInstance(
                compilation0,
                new[] { MscorlibRef }.Concat(runtimeAssemblies),
                runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                string error;
                var testData = new CompilationTestData();
                context.CompileExpression("(p == null) ? f : null", out error, testData);
                Assert.Null(error);
                testData
                .GetMethodData("<>x.<>m0")
                .VerifyIL(
                    @"{
  // Code size        7 (0x7)
  .maxstack  1
  IL_0000:  ldarg.1
  IL_0001:  brfalse.s  IL_0005
  IL_0003:  ldnull
  IL_0004:  ret
  IL_0005:  ldarg.0
  IL_0006:  ret
}"
                    );
            }
                );
        }
コード例 #15
0
        public void OtherFrameworkAssembly()
        {
            var source =
                @"class C
{
    static void M(Windows.UI.Xaml.FrameworkElement f)
    {
    }
}";
            var runtime = CreateRuntime(
                source,
                ImmutableArray.CreateRange(WinRtRefs),
                ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")));
            var context = CreateMethodContext(runtime, "C.M");
            ResultProperties resultProperties;
            string           error;
            var testData = new CompilationTestData();
            ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;

            context.CompileExpression(
                InspectionContextFactory.Empty,
                "f.RenderSize",
                DkmEvaluationFlags.TreatAsExpression,
                DiagnosticFormatter.Instance,
                out resultProperties,
                out error,
                out missingAssemblyIdentities,
                EnsureEnglishUICulture.PreferredOrNull,
                testData);
            Assert.Empty(missingAssemblyIdentities);
            testData.GetMethodData("<>x.<>m0").VerifyIL(
                @"{
  // Code size       55 (0x37)
  .maxstack  2
  IL_0000:  ldstr      ""s""
  IL_0005:  call       ""object <>x.<>GetObjectByAlias(string)""
  IL_000a:  castclass  ""Windows.Storage.StorageFolder""
  IL_000f:  callvirt   ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
  IL_0014:  box        ""Windows.Storage.FileAttributes""
  IL_0019:  dup
  IL_001a:  brtrue.s   IL_0036
  IL_001c:  pop
  IL_001d:  ldstr      ""d""
  IL_0022:  call       ""object <>x.<>GetObjectByAlias(string)""
  IL_0027:  unbox.any  ""Windows.Foundation.DateTime""
  IL_002c:  ldfld      ""long Windows.Foundation.DateTime.UniversalTime""
  IL_0031:  box        ""long""
  IL_0036:  ret
}");
        }
コード例 #16
0
        [ConditionalFact(typeof(OSVersionWin8), typeof(IsRelease))] // https://github.com/dotnet/roslyn/issues/25702
        public void AssemblyQualifiedName()
        {
            var source =
                @"class C
{
    static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
    {
    }
}";
            var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll);

            WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")), runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");

                var aliases = ImmutableArray.Create(
                    VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
                    VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"));

                string error;
                var testData = new CompilationTestData();
                context.CompileExpression(
                    "(object)s.Attributes ?? d.UniversalTime",
                    DkmEvaluationFlags.TreatAsExpression,
                    aliases,
                    out error,
                    testData);
                testData.GetMethodData("<>x.<>m0").VerifyIL(
                    @"{
  // Code size       55 (0x37)
  .maxstack  2
  IL_0000:  ldstr      ""s""
  IL_0005:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
  IL_000a:  castclass  ""Windows.Storage.StorageFolder""
  IL_000f:  callvirt   ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
  IL_0014:  box        ""Windows.Storage.FileAttributes""
  IL_0019:  dup
  IL_001a:  brtrue.s   IL_0036
  IL_001c:  pop
  IL_001d:  ldstr      ""d""
  IL_0022:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
  IL_0027:  unbox.any  ""Windows.Foundation.DateTime""
  IL_002c:  ldfld      ""long Windows.Foundation.DateTime.UniversalTime""
  IL_0031:  box        ""long""
  IL_0036:  ret
}");
            });
        }
コード例 #17
0
        public void SucceedOnRetry()
        {
            var source = @" 
class C 
{ 
    void M() 
    { 
    } 
}";
            var comp   = CreateStandardCompilation(source);

            WithRuntimeInstance(comp, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");

                var missingModule   = runtime.Modules.First();
                var missingIdentity = missingModule.GetMetadataReader().ReadAssemblyIdentityOrThrow();

                var shouldSucceed = false;
                string errorMessage;
                var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
                    runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
                    context,
                    (_, diagnostics) =>
                {
                    if (shouldSucceed)
                    {
                        return(TestCompileResult.Instance);
                    }
                    else
                    {
                        shouldSucceed = true;
                        diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None));
                        return(null);
                    }
                },
                    (AssemblyIdentity assemblyIdentity, out uint uSize) =>
                {
                    uSize = (uint)missingModule.MetadataLength;
                    return(missingModule.MetadataAddress);
                },
                    out errorMessage);

                Assert.Same(TestCompileResult.Instance, compileResult);
                Assert.Null(errorMessage);
            });
        }
コード例 #18
0
ファイル: WinMdTests.cs プロジェクト: tinaschrepfer/roslyn
        public void Win8RuntimeAssemblies()
        {
            var source =
                @"class C
{
    static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
    {
    }
}";
            var compilation0 = CreateCompilationWithMscorlib(
                source,
                options: TestOptions.DebugDll,
                assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
                references: WinRtRefs);
            var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections");

            Assert.True(runtimeAssemblies.Length >= 2);
            byte[] exeBytes;
            byte[] pdbBytes;
            ImmutableArray <MetadataReference> references;

            compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
            var runtime = CreateRuntimeInstance(
                ExpressionCompilerUtilities.GenerateUniqueName(),
                ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
                exeBytes,
                new SymReader(pdbBytes));
            var context = CreateMethodContext(runtime, "C.M");
            ResultProperties resultProperties;
            string           error;
            var testData = new CompilationTestData();

            context.CompileExpression("(p == null) ? f : null", out resultProperties, out error, testData);
            Assert.Null(error);
            testData.GetMethodData("<>x.<>m0").VerifyIL(
                @"{
  // Code size        7 (0x7)
  .maxstack  1
  IL_0000:  ldarg.1
  IL_0001:  brfalse.s  IL_0005
  IL_0003:  ldnull
  IL_0004:  ret
  IL_0005:  ldarg.0
  IL_0006:  ret
}");
        }
コード例 #19
0
        private static void TupleContextNoSystemRuntime(string source, string methodName, string expression, string expectedIL,
                                                        LanguageVersion languageVersion = LanguageVersion.CSharp7)
        {
            var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular.WithLanguageVersion(languageVersion),
                                                       references: new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);

            using (var systemRuntime = SystemRuntimeFacadeRef.ToModuleInstance())
            {
                WithRuntimeInstance(comp, new[] { MscorlibRef, ValueTupleRef }, runtime =>
                {
                    ImmutableArray <MetadataBlock> blocks;
                    Guid moduleVersionId;
                    ISymUnmanagedReader symReader;
                    int methodToken;
                    int localSignatureToken;
                    GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
                    string errorMessage;
                    CompilationTestData testData;
                    int retryCount    = 0;
                    var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
                        runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
                        expression,
                        ImmutableArray <Alias> .Empty,
                        (b, u) => EvaluationContext.CreateMethodContext(
                            b.ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies),
                            symReader,
                            moduleVersionId,
                            methodToken,
                            methodVersion: 1,
                            ilOffset: 0,
                            localSignatureToken: localSignatureToken),
                        (AssemblyIdentity assemblyIdentity, out uint uSize) =>
                    {
                        retryCount++;
                        Assert.Equal("System.Runtime", assemblyIdentity.Name);
                        var block = systemRuntime.MetadataBlock;
                        uSize     = (uint)block.Size;
                        return(block.Pointer);
                    },
                        errorMessage: out errorMessage,
                        testData: out testData);
                    Assert.Equal(1, retryCount);
                    testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL);
                });
            }
        }
コード例 #20
0
        public void AccessType()
        {
            var ilSource = @"
.class public auto ansi beforefieldinit C
       extends [mscorlib]System.Object
{
  .field private int32 Private
  .field family int32 Protected
  .field assembly int32 Internal
  .field public int32 Public
  .field famorassem int32 ProtectedInternal
  .field famandassem int32 ProtectedAndInternal

  .method public hidebysig instance void 
          Test() cil managed
  {
    ret
  }

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    ldarg.0
    call       instance void [mscorlib]System.Object::.ctor()
    ret
  } // end of method C::.ctor

} // end of class C
";
            var module   = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource);
            var runtime  = CreateRuntimeInstance(module, new[] { MscorlibRef });
            var context  = CreateMethodContext(runtime, methodName: "C.Test");

            Assert.Equal(DkmEvaluationResultAccessType.Private, GetResultProperties(context, "Private").AccessType);
            Assert.Equal(DkmEvaluationResultAccessType.Protected, GetResultProperties(context, "Protected").AccessType);
            Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "Internal").AccessType);
            Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "Public").AccessType);

            // As in dev12.
            Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedInternal").AccessType);
            Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedAndInternal").AccessType);

            Assert.Equal(DkmEvaluationResultAccessType.None, GetResultProperties(context, "null").AccessType);
        }
コード例 #21
0
ファイル: WinMdTests.cs プロジェクト: tinaschrepfer/roslyn
        public void Win8RuntimeAssemblies_ExternAlias()
        {
            var source =
                @"extern alias X;
class C
{
    static void M(X::Windows.Storage.StorageFolder f)
    {
    }
}";
            var compilation0 = CreateCompilationWithMscorlib(
                source,
                options: TestOptions.DebugDll,
                assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
                references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r));
            var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage");

            Assert.True(runtimeAssemblies.Length >= 1);
            byte[] exeBytes;
            byte[] pdbBytes;
            ImmutableArray <MetadataReference> references;

            compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
            var runtime = CreateRuntimeInstance(
                ExpressionCompilerUtilities.GenerateUniqueName(),
                ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
                exeBytes,
                new SymReader(pdbBytes));
            var context = CreateMethodContext(runtime, "C.M");
            ResultProperties resultProperties;
            string           error;
            var testData = new CompilationTestData();

            context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out resultProperties, out error, testData);
            Assert.Null(error);
            testData.GetMethodData("<>x.<>m0").VerifyIL(
                @"{
  // Code size        2 (0x2)
  .maxstack  1
  IL_0000:  ldc.i4.0
  IL_0001:  ret
}");
        }
コード例 #22
0
ファイル: WinMdTests.cs プロジェクト: tsasioglu/roslyn
        public void OtherFrameworkAssembly()
        {
            var source =
                @"class C
{
    static void M(Windows.UI.Xaml.FrameworkElement f)
    {
    }
}";
            var runtime = CreateRuntime(
                source,
                ImmutableArray.CreateRange(WinRtRefs),
                ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")));
            var    context = CreateMethodContext(runtime, "C.M");
            string error;
            var    testData = new CompilationTestData();

            context.CompileExpression(
                "f.RenderSize",
                DkmEvaluationFlags.TreatAsExpression,
                NoAliases,
                out error,
                testData);
            testData.GetMethodData("<>x.<>m0").VerifyIL(
                @"{
  // Code size       55 (0x37)
  .maxstack  2
  IL_0000:  ldstr      ""s""
  IL_0005:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
  IL_000a:  castclass  ""Windows.Storage.StorageFolder""
  IL_000f:  callvirt   ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
  IL_0014:  box        ""Windows.Storage.FileAttributes""
  IL_0019:  dup
  IL_001a:  brtrue.s   IL_0036
  IL_001c:  pop
  IL_001d:  ldstr      ""d""
  IL_0022:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
  IL_0027:  unbox.any  ""Windows.Foundation.DateTime""
  IL_002c:  ldfld      ""long Windows.Foundation.DateTime.UniversalTime""
  IL_0031:  box        ""long""
  IL_0036:  ret
}");
        }
コード例 #23
0
        public void TryDifferentLinqLibraryOnRetry()
        {
            var source = @"
using System.Linq;
class C 
{ 
    void M(string[] args) 
    {
    } 
}
class UseLinq
{
    bool b = Enumerable.Any<int>(null);
}";

            var compilation = CreateCompilation(source, new[] { MscorlibRef, SystemCoreRef });

            WithRuntimeInstance(compilation, new[] { MscorlibRef }, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");

                var systemCore     = SystemCoreRef.ToModuleInstance();
                var fakeSystemLinq = CreateCompilationWithMscorlib45("", assemblyName: "System.Linq").
                                     EmitToImageReference().ToModuleInstance();

                string errorMessage;
                CompilationTestData testData;
                int retryCount    = 0;
                var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
                    runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
                    "args.Where(a => a.Length > 0)",
                    ImmutableArray <Alias> .Empty,
                    (_1, _2) => context, // ignore new blocks and just keep using the same failed context...
                    (AssemblyIdentity assemblyIdentity, out uint uSize) =>
                {
                    retryCount++;
                    MetadataBlock block;
                    switch (retryCount)
                    {
                    case 1:
                        Assert.Equal(EvaluationContextBase.SystemLinqIdentity, assemblyIdentity);
                        block = fakeSystemLinq.MetadataBlock;
                        break;

                    case 2:
                        Assert.Equal(EvaluationContextBase.SystemCoreIdentity, assemblyIdentity);
                        block = systemCore.MetadataBlock;
                        break;

                    default:
                        throw ExceptionUtilities.Unreachable;
                    }
                    uSize = (uint)block.Size;
                    return(block.Pointer);
                },
                    errorMessage: out errorMessage,
                    testData: out testData);

                Assert.Equal(2, retryCount);
            });
        }
コード例 #24
0
        public void IntrinsicMethods()
        {
            var sourceA =
                @"public class A { }";
            var sourceB =
                @"public class A { }
public class B
{
    static void M(A a)
    {
    }
}";
            var compilationA = CreateCompilationWithMscorlibAndSystemCore(sourceA, options: TestOptions.DebugDll);
            var moduleA      = compilationA.ToModuleInstance();

            var compilationB = CreateCompilationWithMscorlibAndSystemCore(sourceB, options: TestOptions.DebugDll, references: new[] { moduleA.GetReference() });
            var moduleB      = compilationB.ToModuleInstance();

            var runtime = CreateRuntimeInstance(new[]
            {
                MscorlibRef.ToModuleInstance(),
                SystemCoreRef.ToModuleInstance(),
                moduleA,
                moduleB,
                ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()
            });

            ImmutableArray <MetadataBlock> blocks;
            Guid moduleVersionId;
            ISymUnmanagedReader symReader;
            int methodToken;
            int localSignatureToken;

            GetContextState(runtime, "B.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);

            var aliases = ImmutableArray.Create(
                ExceptionAlias(typeof(ArgumentException)),
                ReturnValueAlias(2, typeof(string)),
                ObjectIdAlias(1, typeof(object)));

            int attempts = 0;

            EvaluationContextBase contextFactory(ImmutableArray <MetadataBlock> b, bool u)
            {
                attempts++;
                return(EvaluationContext.CreateMethodContext(
                           ToCompilation(b, u, moduleVersionId),
                           symReader,
                           moduleVersionId,
                           methodToken,
                           methodVersion: 1,
                           ilOffset: 0,
                           localSignatureToken: localSignatureToken));
            }

            string errorMessage;
            CompilationTestData testData;

            ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
                blocks,
                "(object)new A() ?? $exception ?? $1 ?? $ReturnValue2",
                aliases,
                contextFactory,
                getMetaDataBytesPtr: null,
                errorMessage: out errorMessage,
                testData: out testData);

            Assert.Null(errorMessage);
            Assert.Equal(2, attempts);
            var methodData = testData.GetMethodData("<>x.<>m0");

            methodData.VerifyIL(
                @"{
// Code size       49 (0x31)
.maxstack  2
IL_0000:  newobj     ""A..ctor()""
IL_0005:  dup
IL_0006:  brtrue.s   IL_0030
IL_0008:  pop
IL_0009:  call       ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()""
IL_000e:  castclass  ""System.ArgumentException""
IL_0013:  dup
IL_0014:  brtrue.s   IL_0030
IL_0016:  pop
IL_0017:  ldstr      ""$1""
IL_001c:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0021:  dup
IL_0022:  brtrue.s   IL_0030
IL_0024:  pop
IL_0025:  ldc.i4.2
IL_0026:  call       ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)""
IL_002b:  castclass  ""string""
IL_0030:  ret
}");
        }
コード例 #25
0
        public void MissingMscorlib()
        {
            var sourceA =
                @"public class A
{
}
class B
{
}
class C
{
}";
            var sourceB =
                @"public class B : A
{
}";
            var moduleA = CreateCompilation(
                sourceA,
                references: new[] { SystemRuntimePP7Ref },
                options: TestOptions.DebugDll).ToModuleInstance();

            var moduleB = CreateCompilation(
                sourceB,
                references: new[] { SystemRuntimePP7Ref, moduleA.GetReference() },
                options: TestOptions.DebugDll).ToModuleInstance();

            // Include an empty assembly to verify that not all assemblies
            // with no references are treated as mscorlib.
            var referenceC = AssemblyMetadata.CreateFromImage(CommonResources.Empty).GetReference();

            // At runtime System.Runtime.dll contract assembly is replaced
            // by mscorlib.dll and System.Runtime.dll facade assemblies.
            var runtime = CreateRuntimeInstance(new[]
            {
                MscorlibFacadeRef.ToModuleInstance(),
                SystemRuntimeFacadeRef.ToModuleInstance(),
                moduleA,
                moduleB,
                referenceC.ToModuleInstance()
            });

            ImmutableArray <MetadataBlock> blocks;
            Guid moduleVersionId;
            ISymUnmanagedReader symReader;
            int typeToken;
            int localSignatureToken;

            GetContextState(runtime, "C", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
            string errorMessage;
            CompilationTestData testData;
            int attempts = 0;

            EvaluationContextBase contextFactory(ImmutableArray <MetadataBlock> b, bool u)
            {
                attempts++;
                return(EvaluationContext.CreateTypeContext(
                           ToCompilation(b, u, moduleVersionId),
                           moduleVersionId,
                           typeToken));
            }

            // Compile: [DebuggerDisplay("{new B()}")]
            const string expr = "new B()";

            ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, expr, ImmutableArray <Alias> .Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
            Assert.Null(errorMessage);
            Assert.Equal(2, attempts);
            var methodData = testData.GetMethodData("<>x.<>m0");

            methodData.VerifyIL(
                @"{
// Code size        6 (0x6)
.maxstack  1
IL_0000:  newobj     ""B..ctor()""
IL_0005:  ret
}");
        }
コード例 #26
0
        public void MissingMscorlib()
        {
            var sourceA =
                @"public class A
{
}
class B
{
}
class C
{
}";
            var sourceB =
                @"public class B : A
{
}";
            var assemblyNameA = ExpressionCompilerUtilities.GenerateUniqueName();
            var compilationA  = CreateCompilation(
                sourceA,
                references: new MetadataReference[] { SystemRuntimePP7Ref },
                options: TestOptions.DebugDll,
                assemblyName: assemblyNameA);

            byte[] exeBytesA;
            byte[] pdbBytesA;
            ImmutableArray <MetadataReference> referencesA;

            compilationA.EmitAndGetReferences(out exeBytesA, out pdbBytesA, out referencesA);
            var referenceA = AssemblyMetadata.CreateFromImage(exeBytesA).GetReference(display: assemblyNameA);
            var identityA  = referenceA.GetAssemblyIdentity();
            var moduleA    = referenceA.ToModuleInstance(exeBytesA, new SymReader(pdbBytesA));

            var assemblyNameB = ExpressionCompilerUtilities.GenerateUniqueName();
            var compilationB  = CreateCompilation(
                sourceB,
                references: new MetadataReference[] { SystemRuntimePP7Ref, referenceA },
                options: TestOptions.DebugDll,
                assemblyName: assemblyNameB);

            byte[] exeBytesB;
            byte[] pdbBytesB;
            ImmutableArray <MetadataReference> referencesB;

            compilationB.EmitAndGetReferences(out exeBytesB, out pdbBytesB, out referencesB);
            var referenceB = AssemblyMetadata.CreateFromImage(exeBytesB).GetReference(display: assemblyNameB);
            var moduleB    = referenceB.ToModuleInstance(exeBytesB, new SymReader(pdbBytesB));

            // At runtime System.Runtime.dll contract assembly is replaced
            // by mscorlib.dll and System.Runtime.dll facade assemblies.
            var moduleBuilder = ArrayBuilder <ModuleInstance> .GetInstance();

            moduleBuilder.Add(MscorlibFacadeRef.ToModuleInstance(null, null));
            moduleBuilder.Add(SystemRuntimeFacadeRef.ToModuleInstance(null, null));
            moduleBuilder.Add(moduleA);
            moduleBuilder.Add(moduleB);
            var modules = moduleBuilder.ToImmutableAndFree();

            using (var runtime = new RuntimeInstance(modules))
            {
                ImmutableArray <MetadataBlock> blocks;
                Guid moduleVersionId;
                ISymUnmanagedReader symReader;
                int typeToken;
                int localSignatureToken;
                GetContextState(runtime, "C", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
                string errorMessage;
                CompilationTestData testData;
                int attempts = 0;
                ExpressionCompiler.CreateContextDelegate contextFactory = (b, u) =>
                {
                    attempts++;
                    return(EvaluationContext.CreateTypeContext(
                               ToCompilation(b, u, moduleVersionId),
                               moduleVersionId,
                               typeToken));
                };

                // Compile: [DebuggerDisplay("{new B()}")]
                const string expr = "new B()";
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, expr, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
                Assert.Null(errorMessage);
                Assert.Equal(2, attempts);
                var methodData = testData.GetMethodData("<>x.<>m0");
                methodData.VerifyIL(
                    @"{
  // Code size        6 (0x6)
  .maxstack  1
  IL_0000:  newobj     ""B..ctor()""
  IL_0005:  ret
}");
            }
        }
コード例 #27
0
        public void DuplicateTypesAndMethodsDifferentAssemblies()
        {
            var sourceA =
                @"using N;
namespace N
{
    class C1 { }
    public static class E
    {
        public static A F(this A o) { return o; }
    }
}
class C2 { }
public class A
{
    public static void M()
    {
        var x = new A();
        var y = x.F();
    }
}";
            var sourceB =
                @"using N;
namespace N
{
    class C1 { }
    public static class E
    {
        public static int F(this A o) { return 2; }
    }
}
class C2 { }
public class B
{
    static void M()
    {
        var x = new A();
    }
}";
            var assemblyNameA = ExpressionCompilerUtilities.GenerateUniqueName();
            var compilationA  = CreateCompilationWithMscorlibAndSystemCore(sourceA, options: TestOptions.DebugDll, assemblyName: assemblyNameA);

            byte[] exeBytesA;
            byte[] pdbBytesA;
            ImmutableArray <MetadataReference> referencesA;

            compilationA.EmitAndGetReferences(out exeBytesA, out pdbBytesA, out referencesA);
            var referenceA = AssemblyMetadata.CreateFromImage(exeBytesA).GetReference(display: assemblyNameA);
            var identityA  = referenceA.GetAssemblyIdentity();
            var moduleA    = referenceA.ToModuleInstance(exeBytesA, new SymReader(pdbBytesA));

            var assemblyNameB = ExpressionCompilerUtilities.GenerateUniqueName();
            var compilationB  = CreateCompilationWithMscorlibAndSystemCore(sourceB, options: TestOptions.DebugDll, assemblyName: assemblyNameB, references: new[] { referenceA });

            byte[] exeBytesB;
            byte[] pdbBytesB;
            ImmutableArray <MetadataReference> referencesB;

            compilationB.EmitAndGetReferences(out exeBytesB, out pdbBytesB, out referencesB);
            var referenceB = AssemblyMetadata.CreateFromImage(exeBytesB).GetReference(display: assemblyNameB);
            var moduleB    = referenceB.ToModuleInstance(exeBytesB, new SymReader(pdbBytesB));

            var moduleBuilder = ArrayBuilder <ModuleInstance> .GetInstance();

            moduleBuilder.AddRange(referencesA.Select(r => r.ToModuleInstance(null, null)));
            moduleBuilder.Add(moduleA);
            moduleBuilder.Add(moduleB);
            var modules = moduleBuilder.ToImmutableAndFree();

            using (var runtime = new RuntimeInstance(modules))
            {
                ImmutableArray <MetadataBlock> blocks;
                Guid moduleVersionId;
                ISymUnmanagedReader symReader;
                int typeToken;
                int methodToken;
                int localSignatureToken;
                GetContextState(runtime, "B", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
                string errorMessage;
                CompilationTestData testData;
                var contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken);

                // Duplicate type in namespace, at type scope.
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new N.C1()", contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
                Assert.True(errorMessage.StartsWith("error CS0433: The type 'C1' exists in both "));

                GetContextState(runtime, "B.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
                contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken);

                // Duplicate type in namespace, at method scope.
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C1()", contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
                Assert.True(errorMessage.StartsWith("error CS0433: The type 'C1' exists in both "));

                // Duplicate type in global namespace, at method scope.
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C2()", contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
                Assert.True(errorMessage.StartsWith("error CS0433: The type 'C2' exists in both "));

                // Duplicate extension method, at method scope.
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
                Assert.Equal(errorMessage, "(1,3): error CS0121: The call is ambiguous between the following methods or properties: 'N.E.F(A)' and 'N.E.F(A)'");

                // Same tests as above but in library that does not directly reference duplicates.
                GetContextState(runtime, "A", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
                contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken);

                // Duplicate type in namespace, at type scope.
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new N.C1()", contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
                Assert.Null(errorMessage);
                var methodData = testData.GetMethodData("<>x.<>m0");
                methodData.VerifyIL(
                    @"{
  // Code size        6 (0x6)
  .maxstack  1
  IL_0000:  newobj     ""N.C1..ctor()""
  IL_0005:  ret
}");
                Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName());

                GetContextState(runtime, "A.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
                contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken);

                // Duplicate type in global namespace, at method scope.
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C2()", contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
                Assert.Null(errorMessage);
                methodData = testData.GetMethodData("<>x.<>m0");
                methodData.VerifyIL(
                    @"{
  // Code size        6 (0x6)
  .maxstack  1
  .locals init (A V_0, //x
                A V_1) //y
  IL_0000:  newobj     ""C2..ctor()""
  IL_0005:  ret
}");
                Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName());

                // Duplicate extension method, at method scope.
                ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
                Assert.Null(errorMessage);
                methodData = testData.GetMethodData("<>x.<>m0");
                methodData.VerifyIL(
                    @"{
  // Code size        7 (0x7)
  .maxstack  1
  .locals init (A V_0, //x
                A V_1) //y
  IL_0000:  ldloc.0
  IL_0001:  call       ""A N.E.F(A)""
  IL_0006:  ret
}");
                Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName());
            }
        }
コード例 #28
0
        public void AssemblyDuplicateReferences()
        {
            var sourceA =
                @"public class A
{
}";
            var sourceB =
                @"public class B
{
    public A F = new A();
}";
            var sourceC =
                @"class C
{
    private B F = new B();
    static void M()
    {
    }
}";
            // Assembly A, multiple versions, strong name.
            var assemblyNameA  = ExpressionCompilerUtilities.GenerateUniqueName();
            var publicKeyA     = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD });
            var compilationAS1 = CreateCompilation(
                new AssemblyIdentity(assemblyNameA, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true),
                new[] { sourceA },
                references: new[] { MscorlibRef },
                options: TestOptions.DebugDll.WithDelaySign(true));
            var referenceAS1   = compilationAS1.EmitToImageReference();
            var identityAS1    = referenceAS1.GetAssemblyIdentity();
            var compilationAS2 = CreateCompilation(
                new AssemblyIdentity(assemblyNameA, new Version(2, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true),
                new[] { sourceA },
                references: new[] { MscorlibRef },
                options: TestOptions.DebugDll.WithDelaySign(true));
            var referenceAS2 = compilationAS2.EmitToImageReference();
            var identityAS2  = referenceAS2.GetAssemblyIdentity();

            // Assembly B, multiple versions, not strong name.
            var assemblyNameB  = ExpressionCompilerUtilities.GenerateUniqueName();
            var compilationBN1 = CreateCompilation(
                new AssemblyIdentity(assemblyNameB, new Version(1, 1, 1, 1)),
                new[] { sourceB },
                references: new[] { MscorlibRef, referenceAS1 },
                options: TestOptions.DebugDll);
            var referenceBN1   = compilationBN1.EmitToImageReference();
            var identityBN1    = referenceBN1.GetAssemblyIdentity();
            var compilationBN2 = CreateCompilation(
                new AssemblyIdentity(assemblyNameB, new Version(2, 2, 2, 1)),
                new[] { sourceB },
                references: new[] { MscorlibRef, referenceAS1 },
                options: TestOptions.DebugDll);
            var referenceBN2 = compilationBN2.EmitToImageReference();
            var identityBN2  = referenceBN2.GetAssemblyIdentity();

            // Assembly B, multiple versions, strong name.
            var publicKeyB     = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x53, 0x52, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD });
            var compilationBS1 = CreateCompilation(
                new AssemblyIdentity(assemblyNameB, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyB, hasPublicKey: true),
                new[] { sourceB },
                references: new[] { MscorlibRef, referenceAS1 },
                options: TestOptions.DebugDll.WithDelaySign(true));
            var referenceBS1   = compilationBS1.EmitToImageReference();
            var identityBS1    = referenceBS1.GetAssemblyIdentity();
            var compilationBS2 = CreateCompilation(
                new AssemblyIdentity(assemblyNameB, new Version(2, 2, 2, 1), cultureName: "", publicKeyOrToken: publicKeyB, hasPublicKey: true),
                new[] { sourceB },
                references: new[] { MscorlibRef, referenceAS2 },
                options: TestOptions.DebugDll.WithDelaySign(true));
            var referenceBS2 = compilationBS2.EmitToImageReference();
            var identityBS2  = referenceBS2.GetAssemblyIdentity();

            var mscorlibIdentity    = MscorlibRef.GetAssemblyIdentity();
            var mscorlib20Identity  = MscorlibRef_v20.GetAssemblyIdentity();
            var systemRefIdentity   = SystemRef.GetAssemblyIdentity();
            var systemRef20Identity = SystemRef_v20.GetAssemblyIdentity();

            // No duplicates.
            VerifyAssemblyReferences(
                referenceBN1,
                ImmutableArray.Create(MscorlibRef, referenceAS1, referenceBN1),
                ImmutableArray.Create(mscorlibIdentity, identityAS1, identityBN1));
            // No duplicates, extra references.
            VerifyAssemblyReferences(
                referenceAS1,
                ImmutableArray.Create(MscorlibRef, referenceBN1, referenceAS1, referenceBS2),
                ImmutableArray.Create(mscorlibIdentity, identityAS1));
            // Strong-named, non-strong-named, and framework duplicates, same version (no aliases).
            VerifyAssemblyReferences(
                referenceBN2,
                ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef, referenceBN2, referenceBN2, referenceAS1, referenceAS1),
                ImmutableArray.Create(mscorlibIdentity, identityAS1, identityBN2));
            // Strong-named, non-strong-named, and framework duplicates, different versions.
            VerifyAssemblyReferences(
                referenceBN1,
                ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef_v20, referenceAS2, referenceBN2, referenceBN1, referenceAS2, referenceAS1, referenceBN1),
                ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBN2));
            VerifyAssemblyReferences(
                referenceBN2,
                ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef_v20, referenceAS2, referenceBN2, referenceBN1, referenceAS2, referenceAS1, referenceBN1),
                ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBN2));
            // Strong-named, different versions.
            VerifyAssemblyReferences(
                referenceBS1,
                ImmutableArray.Create(MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceAS2, referenceAS1, referenceBS1),
                ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBS2));
            VerifyAssemblyReferences(
                referenceBS2,
                ImmutableArray.Create(MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceAS2, referenceAS1, referenceBS1),
                ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBS2));

            // Assembly C, multiple versions, not strong name.
            var assemblyNameC  = ExpressionCompilerUtilities.GenerateUniqueName();
            var compilationCN1 = CreateCompilation(
                new AssemblyIdentity(assemblyNameC, new Version(1, 1, 1, 1)),
                new[] { sourceC },
                references: new[] { MscorlibRef, referenceBS1 },
                options: TestOptions.DebugDll);

            byte[] exeBytesC1;
            byte[] pdbBytesC1;
            ImmutableArray <MetadataReference> references;

            compilationCN1.EmitAndGetReferences(out exeBytesC1, out pdbBytesC1, out references);
            var compilationCN2 = CreateCompilation(
                new AssemblyIdentity(assemblyNameC, new Version(2, 1, 1, 1)),
                new[] { sourceC },
                references: new[] { MscorlibRef, referenceBS2 },
                options: TestOptions.DebugDll);

            byte[] exeBytesC2;
            byte[] pdbBytesC2;
            compilationCN1.EmitAndGetReferences(out exeBytesC2, out pdbBytesC2, out references);

            // Duplicate assemblies, target module referencing BS1.
            using (var runtime = CreateRuntimeInstance(
                       assemblyNameC,
                       ImmutableArray.Create(MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceBS2),
                       exeBytesC1,
                       new SymReader(pdbBytesC1)))
            {
                ImmutableArray <MetadataBlock> typeBlocks;
                ImmutableArray <MetadataBlock> methodBlocks;
                Guid moduleVersionId;
                ISymUnmanagedReader symReader;
                int typeToken;
                int methodToken;
                int localSignatureToken;
                GetContextState(runtime, "C", out typeBlocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
                GetContextState(runtime, "C.M", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
                int ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader);

                // Compile expression with type context with all modules.
                var context = EvaluationContext.CreateTypeContext(
                    default(CSharpMetadataContext),
                    typeBlocks,
                    moduleVersionId,
                    typeToken);
                string error;
                // A is ambiguous.
                var testData = new CompilationTestData();
                context.CompileExpression("new A()", out error, testData);
                Assert.True(error.StartsWith("error CS0433: The type 'A' exists in both "));
                testData = new CompilationTestData();
                // B is ambiguous.
                context.CompileExpression("new B()", out error, testData);
                Assert.True(error.StartsWith("error CS0433: The type 'B' exists in both "));
                var previous = new CSharpMetadataContext(typeBlocks, context);

                // Compile expression with type context with referenced modules only.
                context = EvaluationContext.CreateTypeContext(
                    typeBlocks.ToCompilationReferencedModulesOnly(moduleVersionId),
                    moduleVersionId,
                    typeToken);
                // A is unrecognized since there were no direct references to AS1 or AS2.
                testData = new CompilationTestData();
                context.CompileExpression("new A()", out error, testData);
                Assert.Equal(error, "error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)");
                testData = new CompilationTestData();
                // B should be resolved to BS2.
                context.CompileExpression("new B()", out error, testData);
                var methodData = testData.GetMethodData("<>x.<>m0");
                methodData.VerifyIL(
                    @"{
  // Code size        6 (0x6)
  .maxstack  1
  IL_0000:  newobj     ""B..ctor()""
  IL_0005:  ret
}");
                Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityBS2.GetDisplayName());
                // B.F should result in missing assembly AS2 since there were no direct references to AS2.
                ResultProperties resultProperties;
                ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;
                testData = new CompilationTestData();
                context.CompileExpression(
                    InspectionContextFactory.Empty,
                    "(new B()).F",
                    DkmEvaluationFlags.None,
                    DiagnosticFormatter.Instance,
                    out resultProperties,
                    out error,
                    out missingAssemblyIdentities,
                    EnsureEnglishUICulture.PreferredOrNull,
                    testData);
                AssertEx.Equal(missingAssemblyIdentities, ImmutableArray.Create(identityAS2));

                // Compile expression with method context with all modules.
                context = EvaluationContext.CreateMethodContext(
                    previous,
                    methodBlocks,
                    symReader,
                    moduleVersionId,
                    methodToken: methodToken,
                    methodVersion: 1,
                    ilOffset: ilOffset,
                    localSignatureToken: localSignatureToken);
                Assert.Equal(previous.Compilation, context.Compilation); // re-use type context compilation
                testData = new CompilationTestData();
                // A is ambiguous.
                testData = new CompilationTestData();
                context.CompileExpression("new A()", out error, testData);
                Assert.True(error.StartsWith("error CS0433: The type 'A' exists in both "));
                testData = new CompilationTestData();
                // B is ambiguous.
                context.CompileExpression("new B()", out error, testData);
                Assert.True(error.StartsWith("error CS0433: The type 'B' exists in both "));

                // Compile expression with method context with referenced modules only.
                context = EvaluationContext.CreateMethodContext(
                    methodBlocks.ToCompilationReferencedModulesOnly(moduleVersionId),
                    symReader,
                    moduleVersionId,
                    methodToken: methodToken,
                    methodVersion: 1,
                    ilOffset: ilOffset,
                    localSignatureToken: localSignatureToken);
                // A is unrecognized since there were no direct references to AS1 or AS2.
                testData = new CompilationTestData();
                context.CompileExpression("new A()", out error, testData);
                Assert.Equal(error, "error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)");
                testData = new CompilationTestData();
                // B should be resolved to BS2.
                context.CompileExpression("new B()", out error, testData);
                methodData = testData.GetMethodData("<>x.<>m0");
                methodData.VerifyIL(
                    @"{
  // Code size        6 (0x6)
  .maxstack  1
  IL_0000:  newobj     ""B..ctor()""
  IL_0005:  ret
}");
                Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityBS2.GetDisplayName());
                // B.F should result in missing assembly AS2 since there were no direct references to AS2.
                testData = new CompilationTestData();
                context.CompileExpression(
                    InspectionContextFactory.Empty,
                    "(new B()).F",
                    DkmEvaluationFlags.None,
                    DiagnosticFormatter.Instance,
                    out resultProperties,
                    out error,
                    out missingAssemblyIdentities,
                    EnsureEnglishUICulture.PreferredOrNull,
                    testData);
                AssertEx.Equal(missingAssemblyIdentities, ImmutableArray.Create(identityAS2));
            }
        }
コード例 #29
0
        public void CorLibWithAssemblyReferences_Pdb()
        {
            string sourceLib =
                @"namespace Namespace
{
    public class Private { }
}";
            var compLib = CreateStandardCompilation(sourceLib, assemblyName: "System.Private.Library");

            compLib.VerifyDiagnostics();
            var refLib = compLib.EmitToImageReference(aliases: ImmutableArray.Create("A"));

            string sourceCorLib =
                @"extern alias A;
#pragma warning disable 8019
using N = A::Namespace;
namespace System
{
    public class Object
    {
        public void F()
        {
        }
    }
#pragma warning disable 0436
    public class Void : Object { }
#pragma warning restore 0436
}";
            // Create a custom corlib with a reference to compilation
            // above and a reference to the actual mscorlib.
            var compCorLib = CreateCompilation(sourceCorLib, assemblyName: CorLibAssemblyName, references: new[] { MscorlibRef, refLib });

            compCorLib.VerifyDiagnostics();
            var objectType = compCorLib.SourceAssembly.GlobalNamespace.GetMember <NamedTypeSymbol>("System.Object");

            Assert.NotNull(objectType.BaseType);

            var pdbPath = Temp.CreateDirectory().Path;
            ImmutableArray <byte> peBytes;
            ImmutableArray <byte> pdbBytes;

            ExpressionCompilerTestHelpers.EmitCorLibWithAssemblyReferences(
                compCorLib,
                pdbPath,
                (moduleBuilder, emitOptions) => new PEAssemblyBuilderWithAdditionalReferences(moduleBuilder, emitOptions, objectType),
                out peBytes,
                out pdbBytes);
            var symReader = SymReaderFactory.CreateReader(pdbBytes);

            using (var reader = new PEReader(peBytes))
            {
                var metadata       = reader.GetMetadata();
                var module         = metadata.ToModuleMetadata(ignoreAssemblyRefs: true);
                var metadataReader = metadata.ToMetadataReader();
                var moduleInstance = ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow(), symReader);

                // Verify the module declares System.Object.
                Assert.True(metadataReader.DeclaresTheObjectClass());
                // Verify the PEModule has no assembly references.
                Assert.Equal(0, module.Module.ReferencedAssemblies.Length);
                // Verify the underlying metadata has the expected assembly references.
                var actualReferences = metadataReader.AssemblyReferences.Select(r => metadataReader.GetString(metadataReader.GetAssemblyReference(r).Name)).ToImmutableArray();
                AssertEx.Equal(new[] { "mscorlib", "System.Private.Library" }, actualReferences);

                using (var runtime = RuntimeInstance.Create(new[] { moduleInstance }))
                {
                    string error;
                    var    context  = CreateMethodContext(runtime, "System.Object.F");
                    var    testData = new CompilationTestData();
                    // Invalid import: "using N = A::Namespace;".
                    context.CompileExpression(
                        "new N.Private()",
                        out error,
                        testData);
                    Assert.Equal("error CS0246: The type or namespace name 'N' could not be found (are you missing a using directive or an assembly reference?)", error);
                }
            }
        }
コード例 #30
0
        public void CorLibWithAssemblyReferences()
        {
            string sourceLib =
                @"public class Private1
{
}
public class Private2
{
}";
            var compLib = CreateStandardCompilation(sourceLib, assemblyName: "System.Private.Library");

            compLib.VerifyDiagnostics();
            var refLib = compLib.EmitToImageReference();

            string sourceCorLib =
                @"using System.Runtime.CompilerServices;
[assembly: TypeForwardedTo(typeof(Private2))]
namespace System
{
    public class Object
    {
        public Private1 F() => null;
    }
#pragma warning disable 0436
    public class Void : Object { }
#pragma warning restore 0436
}";
            // Create a custom corlib with a reference to compilation
            // above and a reference to the actual mscorlib.
            var compCorLib = CreateCompilation(sourceCorLib, assemblyName: CorLibAssemblyName, references: new[] { MscorlibRef, refLib });

            compCorLib.VerifyDiagnostics();
            var objectType = compCorLib.SourceAssembly.GlobalNamespace.GetMember <NamedTypeSymbol>("System.Object");

            Assert.NotNull(objectType.BaseType);

            ImmutableArray <byte> peBytes;
            ImmutableArray <byte> pdbBytes;

            ExpressionCompilerTestHelpers.EmitCorLibWithAssemblyReferences(
                compCorLib,
                null,
                (moduleBuilder, emitOptions) => new PEAssemblyBuilderWithAdditionalReferences(moduleBuilder, emitOptions, objectType),
                out peBytes,
                out pdbBytes);

            using (var reader = new PEReader(peBytes))
            {
                var metadata       = reader.GetMetadata();
                var module         = metadata.ToModuleMetadata(ignoreAssemblyRefs: true);
                var metadataReader = metadata.ToMetadataReader();
                var moduleInstance = ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow());

                // Verify the module declares System.Object.
                Assert.True(metadataReader.DeclaresTheObjectClass());
                // Verify the PEModule has no assembly references.
                Assert.Equal(0, module.Module.ReferencedAssemblies.Length);
                // Verify the underlying metadata has the expected assembly references.
                var actualReferences = metadataReader.AssemblyReferences.Select(r => metadataReader.GetString(metadataReader.GetAssemblyReference(r).Name)).ToImmutableArray();
                AssertEx.Equal(new[] { "mscorlib", "System.Private.Library" }, actualReferences);

                var source =
                    @"class C
{
    static void M()
    {
    }
}";
                var comp = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { refLib, AssemblyMetadata.Create(module).GetReference() });
                comp.VerifyDiagnostics();

                using (var runtime = RuntimeInstance.Create(new[] { comp.ToModuleInstance(), moduleInstance }))
                {
                    string error;
                    var    context = CreateMethodContext(runtime, "C.M");

                    // Valid expression.
                    var testData = new CompilationTestData();
                    context.CompileExpression(
                        "new object()",
                        out error,
                        testData);
                    Assert.Null(error);
                    testData.GetMethodData("<>x.<>m0").VerifyIL(
                        @"{
  // Code size        6 (0x6)
  .maxstack  1
  IL_0000:  newobj     ""object..ctor()""
  IL_0005:  ret
}");

                    // Invalid expression: System.Int32 is not defined in corlib above.
                    testData = new CompilationTestData();
                    context.CompileExpression(
                        "1",
                        out error,
                        testData);
                    Assert.Equal("error CS0518: Predefined type 'System.Int32' is not defined or imported", error);

                    // Invalid expression: type in method signature from missing referenced assembly.
                    testData = new CompilationTestData();
                    context.CompileExpression(
                        "(new object()).F()",
                        out error,
                        testData);
                    Assert.Equal("error CS0570: 'object.F()' is not supported by the language", error);

                    // Invalid expression: type forwarded to missing referenced assembly.
                    testData = new CompilationTestData();
                    context.CompileExpression(
                        "new Private2()",
                        out error,
                        testData);
                    Assert.Equal("error CS0246: The type or namespace name 'Private2' could not be found (are you missing a using directive or an assembly reference?)", error);
                }
            }
        }