예제 #1
0
            internal ImmutableArray <ModuleMetadata> GetAllModuleMetadata()
            {
                if (EmittedAssemblyData == null)
                {
                    throw new InvalidOperationException("You must call Emit before calling GetAllModuleMetadata.");
                }

                ImmutableArray <ModuleMetadata> modules = ImmutableArray.Create(ModuleMetadata.CreateFromImage(EmittedAssemblyData));

                if (allModuleData != null)
                {
                    var netModules = allModuleData.Where(m => m.Kind == OutputKind.NetModule);
                    if (netModules.Any())
                    {
                        modules = modules.Concat(
                            ImmutableArray.CreateRange <ModuleMetadata>(netModules.Select(m => ModuleMetadata.CreateFromImage(m.Image))));
                    }
                }

                return(modules);
            }
예제 #2
0
        public void CurrentCompilationVersionWildcards()
        {
            var source0 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]

class C
{
    static void M()
    {
        new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
    }

    static void F()
    {
    }
}");
            var source1 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]

class C
{
    static void M()
    {
        new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
        new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
    }

    static void F()
    {
    }
}");
            var source2 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]

class C
{
    static void M()
    {
        new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
        new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
    }

    static void F()
    {
        Console.WriteLine(1);
    }
}");
            var source3 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]

class C
{
    static void M()
    {
        new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
        new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
        new Action(<N:2>() => { Console.WriteLine(3); }</N:2>).Invoke();
        new Action(<N:3>() => { Console.WriteLine(4); }</N:3>).Invoke();
    }

    static void F()
    {
        Console.WriteLine(1);
    }
}");

            var options = ComSafeDebugDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2);

            var compilation0 = CreateCompilation(source0.Tree, options: options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 0)));
            var compilation1 = compilation0.WithSource(source1.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 10)));
            var compilation2 = compilation1.WithSource(source2.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 20)));
            var compilation3 = compilation2.WithSource(source3.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 30)));

            var v0      = CompileAndVerify(compilation0, verify: Verification.Passes);
            var md0     = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
            var reader0 = md0.MetadataReader;

            var m0 = compilation0.GetMember <MethodSymbol>("C.M");
            var m1 = compilation1.GetMember <MethodSymbol>("C.M");
            var m2 = compilation2.GetMember <MethodSymbol>("C.M");
            var m3 = compilation3.GetMember <MethodSymbol>("C.M");

            var f1 = compilation1.GetMember <MethodSymbol>("C.F");
            var f2 = compilation2.GetMember <MethodSymbol>("C.F");

            var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);

            // First update adds some new synthesized members (lambda related)
            var diff1 = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));

            diff1.VerifySynthesizedMembers(
                "C: {<>c}",
                "C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}");

            // Second update is to a method that doesn't produce any synthesized members
            var diff2 = compilation2.EmitDifference(
                diff1.NextGeneration,
                ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));

            diff2.VerifySynthesizedMembers(
                "C: {<>c}",
                "C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}");

            // Last update again adds some new synthesized members (lambdas).
            // Synthesized members added in the first update need to be mapped to the current compilation.
            // Their containing assembly version is different than the version of the previous assembly and
            // hence we need to account for wildcards when comparing the versions.
            var diff3 = compilation3.EmitDifference(
                diff2.NextGeneration,
                ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m2, m3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));

            diff3.VerifySynthesizedMembers(
                "C: {<>c}",
                "C.<>c: {<>9__0_0, <>9__0_1#1, <>9__0_2#3, <>9__0_3#3, <M>b__0_0, <M>b__0_1#1, <M>b__0_2#3, <M>b__0_3#3}");
        }
예제 #3
0
        private void CompileTimeAndRuntimeAssemblies(
            ImmutableArray <MetadataReference> compileReferences,
            ImmutableArray <MetadataReference> runtimeReferences,
            string storageAssemblyName)
        {
            var source =
                @"class C
{
    static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f)
    {
    }
}";
            var compilation0 = CreateStandardCompilation(source, compileReferences, TestOptions.DebugDll);

            WithRuntimeInstance(compilation0, runtimeReferences, runtime =>
            {
                var context = CreateMethodContext(runtime, "C.M");
                string error;
                var testData = new CompilationTestData();
                context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData);
                Assert.Null(error);
                testData.GetMethodData("<>x.<>m0").VerifyIL(
                    @"{
  // Code size       17 (0x11)
  .maxstack  2
  IL_0000:  ldarg.0
  IL_0001:  dup
  IL_0002:  brtrue.s   IL_0010
  IL_0004:  pop
  IL_0005:  ldarg.1
  IL_0006:  dup
  IL_0007:  brtrue.s   IL_0010
  IL_0009:  pop
  IL_000a:  ldarg.2
  IL_000b:  dup
  IL_000c:  brtrue.s   IL_0010
  IL_000e:  pop
  IL_000f:  ldarg.3
  IL_0010:  ret
}");
                testData   = new CompilationTestData();
                var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData);
                Assert.Null(error);
                var methodData = testData.GetMethodData("<>x.<>m0");
                methodData.VerifyIL(
                    @"{
  // Code size        2 (0x2)
  .maxstack  1
  IL_0000:  ldnull
  IL_0001:  ret
}");
                // Check return type is from runtime assembly.
                var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference();
                var compilation       = CSharpCompilation.Create(
                    assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
                    references: runtimeReferences.Concat(ImmutableArray.Create <MetadataReference>(assemblyReference)));
                var assembly = ImmutableArray.CreateRange(result.Assembly);
                using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly)))
                {
                    var reader          = metadata.MetadataReader;
                    var typeDef         = reader.GetTypeDef("<>x");
                    var methodHandle    = reader.GetMethodDefHandle(typeDef, "<>m0");
                    var module          = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule;
                    var metadataDecoder = new MetadataDecoder(module);
                    SignatureHeader signatureHeader;
                    BadImageFormatException metadataException;
                    var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException);
                    Assert.Equal(parameters.Length, 5);
                    var actualReturnType = parameters[0].Type;
                    Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error
                    var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder");
                    Assert.Equal(expectedReturnType, actualReturnType);
                    Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name);
                }
            });
        }
예제 #4
0
        void AddResourceToModule()
        {
            var sourceTree = SyntaxFactory.ParseSyntaxTree("");

            // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad.
            var c1 = CSharpCompilation.Create(
                Guid.NewGuid().ToString(),
                new[] { sourceTree },
                new[] { MscorlibRef },
                TestOptions.NetModule);

            var resourceFileName = "RoslynResourceFile.foo";
            var output           = new MemoryStream();

            const string r1Name = "some.dotted.NAME";
            const string r2Name = "another.DoTtEd.NAME";

            var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 };
            var resourceFileData    = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            var result = c1.Emit(output, manifestResources:
                                 new ResourceDescription[]
            {
                new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true),
                new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false)
            });

            Assert.False(result.Success);
            Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource));

            result = c1.Emit(output, manifestResources:
                             new ResourceDescription[]
            {
                new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false),
                new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true)
            });

            Assert.False(result.Success);
            Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource));

            result = c1.Emit(output, manifestResources:
                             new ResourceDescription[]
            {
                new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false)
            });

            Assert.False(result.Success);
            Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource));

            var c_mod1 = CSharpCompilation.Create(
                Guid.NewGuid().ToString(),
                new[] { sourceTree },
                new[] { MscorlibRef },
                TestOptions.NetModule);

            var output_mod1 = new MemoryStream();

            result = c_mod1.Emit(output_mod1, manifestResources:
                                 new ResourceDescription[]
            {
                new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true)
            });

            Assert.True(result.Success);
            var mod1     = ModuleMetadata.CreateFromImage(output_mod1.ToImmutable());
            var ref_mod1 = new MetadataImageReference(mod1);

            Assert.Equal(ManifestResourceAttributes.Public, mod1.Module.GetEmbeddedResourcesOrThrow()[0].Attributes);

            {
                var c2      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod1 }, TestOptions.Dll);
                var output2 = new MemoryStream();
                var result2 = c2.Emit(output2);

                Assert.True(result2.Success);
                var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output2.ToArray());

                assembly.ModuleResolve += (object sender, ResolveEventArgs e) =>
                {
                    if (e.Name.Equals(c_mod1.SourceModule.Name))
                    {
                        return(assembly.LoadModule(e.Name, output_mod1.ToArray()));
                    }

                    return(null);
                };

                string[] resourceNames = assembly.GetManifestResourceNames();
                Assert.Equal(1, resourceNames.Length);

                var rInfo = assembly.GetManifestResourceInfo(r1Name);
                Assert.Equal(System.Reflection.ResourceLocation.Embedded, rInfo.ResourceLocation);
                Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName);

                var rData  = assembly.GetManifestResourceStream(r1Name);
                var rBytes = new byte[rData.Length];
                rData.Read(rBytes, 0, (int)rData.Length);
                Assert.Equal(arrayOfEmbeddedData, rBytes);
            }

            var c_mod2 = CSharpCompilation.Create(
                Guid.NewGuid().ToString(),
                new[] { sourceTree },
                new[] { MscorlibRef },
                TestOptions.NetModule);

            var output_mod2 = new MemoryStream();

            result = c_mod2.Emit(output_mod2, manifestResources:
                                 new ResourceDescription[]
            {
                new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true),
                new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), true)
            });

            Assert.True(result.Success);
            var ref_mod2 = new MetadataImageReference(ModuleMetadata.CreateFromImage(output_mod2.ToImmutable()));

            {
                var c3      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod2 }, TestOptions.Dll);
                var output3 = new MemoryStream();
                var result3 = c3.Emit(output3);

                Assert.True(result3.Success);
                var assembly = Assembly.ReflectionOnlyLoad(output3.ToArray());

                assembly.ModuleResolve += (object sender, ResolveEventArgs e) =>
                {
                    if (e.Name.Equals(c_mod2.SourceModule.Name))
                    {
                        return(assembly.LoadModule(e.Name, output_mod2.ToArray()));
                    }

                    return(null);
                };

                string[] resourceNames = assembly.GetManifestResourceNames();
                Assert.Equal(2, resourceNames.Length);

                var rInfo = assembly.GetManifestResourceInfo(r1Name);
                Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName);

                var rData  = assembly.GetManifestResourceStream(r1Name);
                var rBytes = new byte[rData.Length];
                rData.Read(rBytes, 0, (int)rData.Length);
                Assert.Equal(arrayOfEmbeddedData, rBytes);

                rInfo = assembly.GetManifestResourceInfo(r2Name);
                Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName);

                rData  = assembly.GetManifestResourceStream(r2Name);
                rBytes = new byte[rData.Length];
                rData.Read(rBytes, 0, (int)rData.Length);
                Assert.Equal(resourceFileData, rBytes);
            }

            var c_mod3 = CSharpCompilation.Create(
                Guid.NewGuid().ToString(),
                new[] { sourceTree },
                new[] { MscorlibRef },
                TestOptions.NetModule);

            var output_mod3 = new MemoryStream();

            result = c_mod3.Emit(output_mod3, manifestResources:
                                 new ResourceDescription[]
            {
                new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false)
            });

            Assert.True(result.Success);
            var mod3     = ModuleMetadata.CreateFromImage(output_mod3.ToImmutable());
            var ref_mod3 = new MetadataImageReference(mod3);

            Assert.Equal(ManifestResourceAttributes.Private, mod3.Module.GetEmbeddedResourcesOrThrow()[0].Attributes);

            {
                var c4      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod3 }, TestOptions.Dll);
                var output4 = new MemoryStream();
                var result4 = c4.Emit(output4, manifestResources:
                                      new ResourceDescription[]
                {
                    new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), false)
                });

                Assert.True(result4.Success);
                var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output4.ToArray());

                assembly.ModuleResolve += (object sender, ResolveEventArgs e) =>
                {
                    if (e.Name.Equals(c_mod3.SourceModule.Name))
                    {
                        return(assembly.LoadModule(e.Name, output_mod3.ToArray()));
                    }

                    return(null);
                };

                string[] resourceNames = assembly.GetManifestResourceNames();
                Assert.Equal(2, resourceNames.Length);

                var rInfo = assembly.GetManifestResourceInfo(r1Name);
                Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation);

                var rData  = assembly.GetManifestResourceStream(r1Name);
                var rBytes = new byte[rData.Length];
                rData.Read(rBytes, 0, (int)rData.Length);
                Assert.Equal(arrayOfEmbeddedData, rBytes);

                rInfo = assembly.GetManifestResourceInfo(r2Name);
                Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName);

                rData  = assembly.GetManifestResourceStream(r2Name);
                rBytes = new byte[rData.Length];
                rData.Read(rBytes, 0, (int)rData.Length);
                Assert.Equal(resourceFileData, rBytes);
            }

            {
                var c5      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod1, ref_mod3 }, TestOptions.Dll);
                var output5 = new MemoryStream();
                var result5 = c5.Emit(output5);

                Assert.True(result5.Success);
                var assembly = Assembly.ReflectionOnlyLoad(output5.ToArray());

                assembly.ModuleResolve += (object sender, ResolveEventArgs e) =>
                {
                    if (e.Name.Equals(c_mod1.SourceModule.Name))
                    {
                        return(assembly.LoadModule(e.Name, output_mod1.ToArray()));
                    }
                    else if (e.Name.Equals(c_mod3.SourceModule.Name))
                    {
                        return(assembly.LoadModule(e.Name, output_mod3.ToArray()));
                    }

                    return(null);
                };

                string[] resourceNames = assembly.GetManifestResourceNames();
                Assert.Equal(2, resourceNames.Length);

                var rInfo = assembly.GetManifestResourceInfo(r1Name);
                Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName);

                var rData  = assembly.GetManifestResourceStream(r1Name);
                var rBytes = new byte[rData.Length];
                rData.Read(rBytes, 0, (int)rData.Length);
                Assert.Equal(arrayOfEmbeddedData, rBytes);

                rInfo = assembly.GetManifestResourceInfo(r2Name);
                Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation);
                Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName);

                rData  = assembly.GetManifestResourceStream(r2Name);
                rBytes = new byte[rData.Length];
                rData.Read(rBytes, 0, (int)rData.Length);
                Assert.Equal(resourceFileData, rBytes);
            }

            {
                var c6      = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.Dll);
                var output6 = new MemoryStream();
                var result6 = c6.Emit(output6);

                Assert.False(result6.Success);
                result6.Diagnostics.Verify(
                    // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly
                    Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME"));

                result6 = c6.Emit(output6, manifestResources:
                                  new ResourceDescription[]
                {
                    new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false)
                });

                Assert.False(result6.Success);
                result6.Diagnostics.Verify(
                    // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly
                    Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME"),
                    // error CS1508: Resource identifier 'another.DoTtEd.NAME' has already been used in this assembly
                    Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("another.DoTtEd.NAME"));

                c6 = CreateCompilationWithMscorlib(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.NetModule);

                result6 = c6.Emit(output6, manifestResources:
                                  new ResourceDescription[]
                {
                    new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false)
                });

                Assert.True(result6.Success);
            }
        }
        public void UpdateIterator_NoVariables()
        {
            var source0      = @"
using System.Collections.Generic;

class C
{
    static IEnumerable<int> F() 
    {
        yield return 1;
    }
}";
            var source1      = @"
using System.Collections.Generic;

class C
{
    static IEnumerable<int> F() 
    {
        yield return 2;
    }
}";
            var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
            var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);

            var v0 = CompileAndVerify(compilation0);

            using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
            {
                var method0 = compilation0.GetMember <MethodSymbol>("C.F");
                var method1 = compilation1.GetMember <MethodSymbol>("C.F");

                var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
                var diff1       = compilation1.EmitDifference(
                    generation0,
                    ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));

                // Verify delta metadata contains expected rows.
                using (var md1 = diff1.GetMetadata())
                {
                    // Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
                    // 3 methods were updated:
                    // - the kick-off method (might be changed if the method previously wasn't an iterator)
                    // - Finally method
                    // - MoveNext method
                    CheckEncLogDefinitions(md1.Reader,
                                           Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                           Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                           Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default));

                    diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
  // Code size       63 (0x3f)
  .maxstack  2
  .locals init (int V_0, //CS$524$0000
                bool V_1)
  IL_0000:  ldarg.0
  IL_0001:  ldfld      ""int C.<F>d__0.<>1__state""
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  brfalse.s  IL_0012
  IL_000a:  br.s       IL_000c
  IL_000c:  ldloc.0
  IL_000d:  ldc.i4.1
  IL_000e:  beq.s      IL_0014
  IL_0010:  br.s       IL_0016
  IL_0012:  br.s       IL_001a
  IL_0014:  br.s       IL_0034
  IL_0016:  ldc.i4.0
  IL_0017:  stloc.1
  IL_0018:  ldloc.1
  IL_0019:  ret
  IL_001a:  ldarg.0
  IL_001b:  ldc.i4.m1
  IL_001c:  stfld      ""int C.<F>d__0.<>1__state""
  IL_0021:  nop
  IL_0022:  ldarg.0
  IL_0023:  ldc.i4.2
  IL_0024:  stfld      ""int C.<F>d__0.<>2__current""
  IL_0029:  ldarg.0
  IL_002a:  ldc.i4.1
  IL_002b:  stfld      ""int C.<F>d__0.<>1__state""
  IL_0030:  ldc.i4.1
  IL_0031:  stloc.1
  IL_0032:  br.s       IL_0018
  IL_0034:  ldarg.0
  IL_0035:  ldc.i4.m1
  IL_0036:  stfld      ""int C.<F>d__0.<>1__state""
  IL_003b:  ldc.i4.0
  IL_003c:  stloc.1
  IL_003d:  br.s       IL_0018
}
");
                    v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
  // Code size       63 (0x3f)
  .maxstack  2
  .locals init (int V_0, //CS$524$0000
                bool V_1)
  IL_0000:  ldarg.0
  IL_0001:  ldfld      ""int C.<F>d__0.<>1__state""
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  brfalse.s  IL_0012
  IL_000a:  br.s       IL_000c
  IL_000c:  ldloc.0
  IL_000d:  ldc.i4.1
  IL_000e:  beq.s      IL_0014
  IL_0010:  br.s       IL_0016
  IL_0012:  br.s       IL_001a
  IL_0014:  br.s       IL_0034
  IL_0016:  ldc.i4.0
  IL_0017:  stloc.1
  IL_0018:  ldloc.1
  IL_0019:  ret
  IL_001a:  ldarg.0
  IL_001b:  ldc.i4.m1
  IL_001c:  stfld      ""int C.<F>d__0.<>1__state""
  IL_0021:  nop
  IL_0022:  ldarg.0
  IL_0023:  ldc.i4.1
  IL_0024:  stfld      ""int C.<F>d__0.<>2__current""
  IL_0029:  ldarg.0
  IL_002a:  ldc.i4.1
  IL_002b:  stfld      ""int C.<F>d__0.<>1__state""
  IL_0030:  ldc.i4.1
  IL_0031:  stloc.1
  IL_0032:  br.s       IL_0018
  IL_0034:  ldarg.0
  IL_0035:  ldc.i4.m1
  IL_0036:  stfld      ""int C.<F>d__0.<>1__state""
  IL_003b:  ldc.i4.0
  IL_003c:  stloc.1
  IL_003d:  br.s       IL_0018
}");
                }
            }
        }
예제 #6
0
        public unsafe void CreateFromImage()
        {
            Assert.Throws <ArgumentNullException>(() => ModuleMetadata.CreateFromImage(IntPtr.Zero, 0));
            Assert.Throws <ArgumentOutOfRangeException>(() => { fixed(byte *ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromImage((IntPtr)ptr, 0); });
            Assert.Throws <ArgumentOutOfRangeException>(() => { fixed(byte *ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromImage((IntPtr)ptr, -1); });

            Assert.Throws <ArgumentNullException>(() => ModuleMetadata.CreateFromImage(default(ImmutableArray <byte>)));
            Assert.Throws <ArgumentNullException>(() => ModuleMetadata.CreateFromImage(default(IEnumerable <byte>)));
            Assert.Throws <ArgumentNullException>(() => ModuleMetadata.CreateFromImage(default(byte[])));

            // It's not particularly important that this not throw. The parsing of the metadata is now lazy, and the result is that an exception
            // will be thrown when something tugs on the metadata later.
            ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Invalid.EmptyModuleTable);
        }
예제 #7
0
        public void UniqueSynthesizedNames2()
        {
            var source0 = @"
using System;

public class C
{    
    public static void Main() 
    {
    }
}";
            var source1 = @"
using System;

public class C
{
    public static void Main() 
    {
        new C().F();
    }

    public int F() 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }
}";
            var source2 = @"
using System;

public class C
{
    public static void Main() 
    {
        new C().F(1);
        new C().F();
    }

    public int F(int x) 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }

    public int F() 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }
}";

            var source3 = @"
using System;

public class C
{
    public static void Main() 
    {
    }

    public int F(int x) 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }

    public int F() 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }
}";

            var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
            var compilation1 = compilation0.WithSource(source1);
            var compilation2 = compilation1.WithSource(source2);
            var compilation3 = compilation2.WithSource(source3);

            var main0  = compilation0.GetMember <MethodSymbol>("C.Main");
            var main1  = compilation1.GetMember <MethodSymbol>("C.Main");
            var main2  = compilation2.GetMember <MethodSymbol>("C.Main");
            var main3  = compilation3.GetMember <MethodSymbol>("C.Main");
            var f1     = compilation1.GetMember <MethodSymbol>("C.F");
            var f_int2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");

            var v0  = CompileAndVerify(compilation0);
            var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);

            var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreatePdbInfoProvider().GetEncMethodDebugInfo);
            var diff1       = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(
                    new SemanticEdit(SemanticEditKind.Insert, null, f1),
                    new SemanticEdit(SemanticEditKind.Update, main0, main1, preserveLocalVariables: true)));

            diff1.VerifySynthesizedMembers(
                "C: {<F>b__1#1_1, <>c__DisplayClass1#1_0, <>c}",
                "C.<>c: {<>9__1#1_0, <F>b__1#1_0}",
                "C.<>c__DisplayClass1#1_0: {a, <F>b__2}");

            var diff2 = compilation2.EmitDifference(
                diff1.NextGeneration,
                ImmutableArray.Create(
                    new SemanticEdit(SemanticEditKind.Insert, null, f_int2),
                    new SemanticEdit(SemanticEditKind.Update, main1, main2, preserveLocalVariables: true)));

            diff2.VerifySynthesizedMembers(
                "C: {<F>b__1#2_1, <>c__DisplayClass1#2_0, <>c, <F>b__1#1_1, <>c__DisplayClass1#1_0}",
                "C.<>c: {<>9__1#2_0, <F>b__1#2_0, <>9__1#1_0, <F>b__1#1_0}",
                "C.<>c__DisplayClass1#1_0: {a, <F>b__2}",
                "C.<>c__DisplayClass1#2_0: {a, <F>b__2}");

            var diff3 = compilation3.EmitDifference(
                diff2.NextGeneration,
                ImmutableArray.Create(
                    new SemanticEdit(SemanticEditKind.Update, main2, main3, preserveLocalVariables: true)));

            diff3.VerifySynthesizedMembers(
                "C: {<F>b__1#2_1, <>c__DisplayClass1#2_0, <>c, <F>b__1#1_1, <>c__DisplayClass1#1_0}",
                "C.<>c: {<>9__1#2_0, <F>b__1#2_0, <>9__1#1_0, <F>b__1#1_0}",
                "C.<>c__DisplayClass1#1_0: {a, <F>b__2}",
                "C.<>c__DisplayClass1#2_0: {a, <F>b__2}");
        }
        public void AddAsyncMethod()
        {
            var source0      = @"
using System.Threading.Tasks;

class C
{
}";
            var source1      = @"
using System.Threading.Tasks;

class C
{
    static async Task<int> F() 
    {
        await Task.FromResult(10);
        return 20;
    }
}";
            var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
            var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);
            var v0           = CompileAndVerify(compilation0);

            var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), EmptyLocalsProvider);
            var diff1       = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Insert, null, compilation1.GetMember <MethodSymbol>("C.F"))));

            using (var md1 = diff1.GetMetadata())
            {
                var reader1 = md1.Reader;

                // Add state machine type and its members:
                // - Method '.ctor'
                // - Method 'MoveNext'
                // - Method 'SetStateMachine'
                // - Field '<>1__state'
                // - Field '<>t__builder'
                // - Field '<>u__$awaiter0'
                // Add method F()
                CheckEncLogDefinitions(reader1,
                                       Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                       Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                       Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
                                       Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                                       Row(1, TableIndex.Field, EditAndContinueOperation.Default),
                                       Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                                       Row(2, TableIndex.Field, EditAndContinueOperation.Default),
                                       Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                                       Row(3, TableIndex.Field, EditAndContinueOperation.Default),
                                       Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                                       Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                       Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                                       Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                       Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                                       Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                       Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                                       Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                       Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
                                       Row(1, TableIndex.Param, EditAndContinueOperation.Default),
                                       Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                       Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                       Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                       Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                       Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                                       Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                                       Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
                                       Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
            }
        }
        public void JoinAndGroupByClauses()
        {
            var source0      = MarkedSource(@"
using System.Linq;

class C
{
    void F()
    {
        var result = <N:0>from a in new[] { 1, 2, 3 }</N:0>
                     <N:1>join b in new[] { 5 } on a + 1 equals b - 1</N:1>
                     <N:2>group</N:2> new { a, b = a + 5 } by new { c = a + 4 } into d
                     <N:3>select d.Key</N:3>;
    }
}");
            var source1      = MarkedSource(@"
using System.Linq;

class C
{
    void F()
    {
        var result = <N:0>from a in new[] { 10, 20, 30 }</N:0>
                     <N:1>join b in new[] { 50 } on a + 10 equals b - 10</N:1>
                     <N:2>group</N:2> new { a, b = a + 50 } by new { c = a + 40 } into d
                     <N:3>select d.Key</N:3>;
    }
}");
            var compilation0 = CreateCompilationWithMscorlib(source0.Tree, new[] { SystemCoreRef }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
            var compilation1 = compilation0.WithSource(source1.Tree);

            var v0  = CompileAndVerify(compilation0);
            var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);

            var f0 = compilation0.GetMember <MethodSymbol>("C.F");
            var f1 = compilation1.GetMember <MethodSymbol>("C.F");

            var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreatePdbInfoProvider().GetEncMethodDebugInfo);

            var diff1 = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));

            // no new synthesized members generated (with #1 in names):
            diff1.VerifySynthesizedMembers(
                "C: {<>c}",
                "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <>9__0_4, <>9__0_5, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3, <F>b__0_4, <F>b__0_5}",
                "<>f__AnonymousType1<<c>j__TPar>: {Equals, GetHashCode, ToString}",
                "<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");

            var md1     = diff1.GetMetadata();
            var reader1 = md1.Reader;

            // Method updates for lambdas:
            CheckEncLogDefinitions(reader1,
                                   Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                   Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                   Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                   Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                   Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(16, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(17, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(21, TableIndex.MethodDef, EditAndContinueOperation.Default));
        }
예제 #10
0
        public void DependencyVersionWildcards_Metadata()
        {
            string srcLib = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.*"")]

public class D { }
";

            string src0 = @"
class C 
{ 
    public static int F(D a) { return 1; }
}
";
            string src1 = @"
class C 
{ 
    public static int F(D a) { return 2; }
}
";
            string src2 = @"
class C 
{ 
    public static int F(D a) { return 3; }
    public static int G(D a) { return 4; }
}
";
            var    lib0 = CreateStandardCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1001));
            lib0.VerifyDiagnostics();

            var lib1 = CreateStandardCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1002));
            lib1.VerifyDiagnostics();

            var lib2 = CreateStandardCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1003));
            lib2.VerifyDiagnostics();

            var compilation0 = CreateCompilation(src0, new[] { MscorlibRef, lib0.EmitToImageReference() }, assemblyName: "C", options: TestOptions.DebugDll);
            var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.EmitToImageReference() });
            var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.EmitToImageReference() });

            var v0 = CompileAndVerify(compilation0);
            var v1 = CompileAndVerify(compilation1);
            var v2 = CompileAndVerify(compilation2);

            var f0 = compilation0.GetMember <MethodSymbol>("C.F");
            var f1 = compilation1.GetMember <MethodSymbol>("C.F");
            var f2 = compilation2.GetMember <MethodSymbol>("C.F");
            var g2 = compilation2.GetMember <MethodSymbol>("C.G");

            var md0         = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
            var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);

            var diff1 = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, f0, f1)));

            diff1.EmitResult.Diagnostics.Verify(
                // error CS7038: Failed to emit module 'C'.
                Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C"));
        }
        public void ConstructorWithClosure1()
        {
            var source0      = MarkedSource(@"
using System;

class D { public D(Func<int> f) { } } 

class C : D
{
    <N:0>public C(int a, int b)</N:0>
      : base(<N:8>() => a</N:8>) 
    <N:1>{</N:1>
        int c = 0;

        Func<int> f1 = <N:2>() => a + 1</N:2>;        
        Func<int> f2 = <N:3>() => b + 2</N:3>;
        Func<int> f3 = <N:4>() => c + 3</N:4>;
        Func<int> f4 = <N:5>() => a + b + c</N:5>;
        Func<int> f5 = <N:6>() => a + c</N:6>;
        Func<int> f6 = <N:7>() => b + c</N:7>;
    }
}");
            var source1      = MarkedSource(@"
using System;

class D { public D(Func<int> f) { } } 

class C : D
{
    <N:0>public C(int a, int b)</N:0>
      : base(<N:8>() => a * 10</N:8>) 
    <N:1>{</N:1>
        int c = 0;

        Func<int> f1 = <N:2>() => a * 10 + 1</N:2>;        
        Func<int> f2 = <N:3>() => b * 10 + 2</N:3>;
        Func<int> f3 = <N:4>() => c * 10 + 3</N:4>;
        Func<int> f4 = <N:5>() => a * 10 + b + c</N:5>;
        Func<int> f5 = <N:6>() => a * 10 + c</N:6>;
        Func<int> f6 = <N:7>() => b * 10 + c</N:7>;
    }
}");
            var compilation0 = CreateCompilationWithMscorlib(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
            var compilation1 = compilation0.WithSource(source1.Tree);

            var v0  = CompileAndVerify(compilation0);
            var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);

            var ctor0 = compilation0.GetMember <NamedTypeSymbol>("C").InstanceConstructors.Single();
            var ctor1 = compilation1.GetMember <NamedTypeSymbol>("C").InstanceConstructors.Single();

            var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreatePdbInfoProvider().GetEncMethodDebugInfo);

            var diff1 = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));

            // no new synthesized members generated (with #1 in names):
            diff1.VerifySynthesizedMembers(
                "C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
                "C.<>c__DisplayClass0_0: {a, b, <.ctor>b__0, <.ctor>b__1, <.ctor>b__2}",
                "C.<>c__DisplayClass0_1: {c, CS$<>8__locals1, <.ctor>b__3, <.ctor>b__4, <.ctor>b__5, <.ctor>b__6}");

            var md1     = diff1.GetMetadata();
            var reader1 = md1.Reader;

            // Method updates
            CheckEncLogDefinitions(reader1,
                                   Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                   Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                   Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                   Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default));
        }
예제 #12
0
        public void AddReferences_Errors()
        {
            var moduleRef = ModuleMetadata
                            .CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00)
                            .GetReference();

            var options = ScriptOptions.Default.WithReferences(
                ImmutableArray <MetadataReference> .Empty
                );

            Assert.Throws <ArgumentNullException>(
                "references",
                () => options.AddReferences((MetadataReference[])null)
                );
            Assert.Throws <ArgumentNullException>(
                "references[0]",
                () => options.AddReferences(new MetadataReference[] { null })
                );

            Assert.Throws <ArgumentNullException>(
                "references",
                () => options.AddReferences((IEnumerable <MetadataReference>)null)
                );
            Assert.Throws <ArgumentNullException>(
                "references[0]",
                () =>
                options.AddReferences(
                    (IEnumerable <MetadataReference>) new MetadataReference[] { null }
                    )
                );

            Assert.Throws <ArgumentNullException>(
                "references",
                () => options.AddReferences((Assembly[])null)
                );
            Assert.Throws <ArgumentNullException>(
                "references[0]",
                () => options.AddReferences(new Assembly[] { null })
                );

            Assert.Throws <ArgumentNullException>(
                "references",
                () => options.AddReferences((IEnumerable <Assembly>)null)
                );
            Assert.Throws <ArgumentNullException>(
                "references[0]",
                () => options.AddReferences((IEnumerable <Assembly>) new Assembly[] { null })
                );

            Assert.Throws <ArgumentNullException>(
                "references",
                () => options.AddReferences((string[])null)
                );
            Assert.Throws <ArgumentNullException>(
                "references[0]",
                () => options.AddReferences(new string[] { null })
                );

            Assert.Throws <ArgumentNullException>(
                "references",
                () => options.AddReferences((IEnumerable <string>)null)
                );
            Assert.Throws <ArgumentNullException>(
                "references[0]",
                () => options.AddReferences((IEnumerable <string>) new string[] { null })
                );
        }
예제 #13
0
    public void TargetChanged1()
    {
        var source0      = @"
class C<T>
{
    static int Target0<G>() => 0;
    static int Target1<G>() => 1;

    System.Func<int> F() => Target0<T>;
}
";
        var source1      = @"
class C<T>
{
    static int Target0<G>() => 0;
    static int Target1<G>() => 1;

    System.Func<int> F() => Target1<T>;
}
";
        var compilation0 = CreateCompilation(source0);
        var compilation1 = compilation0.WithSource(source1);

        Assert.Equal(compilation0.LanguageVersion, compilation1.LanguageVersion);

        var f0 = compilation0.GetMember <MethodSymbol>("C.F");
        var f1 = compilation1.GetMember <MethodSymbol>("C.F");

        var v0 = CompileAndVerify(compilation0);

        using var moduleData0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
        var methodData0 = v0.TestData.GetMethodData("C<T>.F");

        var generation0 = EmitBaseline.CreateInitialBaseline(moduleData0, methodData0.EncDebugInfoProvider());
        var diff1       = compilation1.EmitDifference(
            generation0,
            ImmutableArray.Create(
                SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));

        diff1.EmitResult.Diagnostics.Verify();
        diff1.VerifyIL("C<T>.F", @"
{
  // Code size       28 (0x1c)
  .maxstack  2
  IL_0000:  ldsfld     ""System.Func<int> C<T>.<>O#1.<0>__Target1""
  IL_0005:  dup
  IL_0006:  brtrue.s   IL_001b
  IL_0008:  pop
  IL_0009:  ldnull
  IL_000a:  ldftn      ""int C<T>.Target1<T>()""
  IL_0010:  newobj     ""System.Func<int>..ctor(object, System.IntPtr)""
  IL_0015:  dup
  IL_0016:  stsfld     ""System.Func<int> C<T>.<>O#1.<0>__Target1""
  IL_001b:  ret
}
");

        var reader0 = moduleData0.MetadataReader;
        var reader1 = diff1.GetMetadata().Reader;

        CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "<>O");
        CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>O#1");
    }
예제 #14
0
        public void Declarations()
        {
            var source =
                @"class C
{
    static object F;
    static void M<T>(object x)
    {
        object y;
        if (x == null)
        {
            object z;
        }
    }
}";
            var compilation0 = CreateCompilationWithMscorlib(
                source,
                options: TestOptions.DebugDll,
                assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
            var runtime = CreateRuntimeInstance(compilation0);
            var context = CreateMethodContext(
                runtime,
                methodName: "C.M");
            ResultProperties resultProperties;
            string           error;
            ImmutableArray <AssemblyIdentity> missingAssemblyIdentities;
            var testData = new CompilationTestData();
            var result   = context.CompileExpression(
                InspectionContextFactory.Empty,
                "int z = 1, F = 2;",
                DkmEvaluationFlags.None,
                DiagnosticFormatter.Instance,
                out resultProperties,
                out error,
                out missingAssemblyIdentities,
                EnsureEnglishUICulture.PreferredOrNull,
                testData);

            Assert.Empty(missingAssemblyIdentities);
            Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
            testData.GetMethodData("<>x.<>m0<T>").VerifyIL(
                @"{
  // Code size       65 (0x41)
  .maxstack  2
  .locals init (object V_0, //y
                bool V_1,
                object V_2)
  IL_0000:  ldtoken    ""int""
  IL_0005:  call       ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
  IL_000a:  ldstr      ""z""
  IL_000f:  call       ""void <>x.<>CreateVariable(System.Type, string)""
  IL_0014:  ldstr      ""z""
  IL_0019:  call       ""int <>x.<>GetVariableAddress<int>(string)""
  IL_001e:  ldc.i4.1
  IL_001f:  stind.i4
  IL_0020:  ldtoken    ""int""
  IL_0025:  call       ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
  IL_002a:  ldstr      ""F""
  IL_002f:  call       ""void <>x.<>CreateVariable(System.Type, string)""
  IL_0034:  ldstr      ""F""
  IL_0039:  call       ""int <>x.<>GetVariableAddress<int>(string)""
  IL_003e:  ldc.i4.2
  IL_003f:  stind.i4
  IL_0040:  ret
}");
            var assembly = ImmutableArray.CreateRange(result.Assembly);

            assembly.VerifyIL("<>x.<>CreateVariable",
                              @"{
  // Code size        2 (0x2)
  .maxstack  8
  IL_0000:  ldnull
  IL_0001:  throw
}");
            assembly.VerifyIL("<>x.<>GetVariableAddress",
                              @"{
  // Code size        2 (0x2)
  .maxstack  8
  IL_0000:  ldnull
  IL_0001:  throw
}");
            // Verify <>CreateVariable is not generic and <>GetVariableAddress is.
            using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly)))
            {
                var reader  = metadata.MetadataReader;
                var typeDef = reader.GetTypeDef("<>x");
                reader.CheckTypeParameters(typeDef.GetGenericParameters());
                var methodDef = reader.GetMethodDef(typeDef, "<>CreateVariable");
                reader.CheckTypeParameters(methodDef.GetGenericParameters());
                var method = (MethodSymbol)testData.GetMethodData("<>x.<>CreateVariable").Method;
                Assert.Equal(method.CallingConvention, Cci.CallingConvention.Default);
                methodDef = reader.GetMethodDef(typeDef, "<>GetVariableAddress");
                reader.CheckTypeParameters(methodDef.GetGenericParameters(), "<>T");
                method = (MethodSymbol)testData.GetMethodData("<>x.<>GetVariableAddress<<>T>").Method;
                Assert.Equal(method.CallingConvention, Cci.CallingConvention.Generic);
            }
        }
예제 #15
0
        public void UniqueSynthesizedNames1()
        {
            var source0 = @"
using System;

public class C
{    
    public int F() 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }
}";
            var source1 = @"
using System;

public class C
{
    public int F(int x) 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }

    public int F() 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }
}";
            var source2 = @"
using System;

public class C
{
    public int F(int x) 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }

    public int F(byte x) 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }

    public int F() 
    { 
        var a = 1; 
        var f1 = new Func<int>(() => 1);
        var f2 = new Func<int>(() => F());
        var f3 = new Func<int>(() => a);
        return 2;
    }
}";

            var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
            var compilation1 = compilation0.WithSource(source1);
            var compilation2 = compilation1.WithSource(source2);

            var f_int1  = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
            var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(byte)");

            var v0  = CompileAndVerify(compilation0);
            var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);

            var reader0 = md0.MetadataReader;

            CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0", "<>c");
            CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", "<F>b__0_1", ".ctor", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
            CheckNames(reader0, reader0.GetFieldDefNames(), "a", "<>9", "<>9__0_0");

            var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreatePdbInfoProvider().GetEncMethodDebugInfo);
            var diff1       = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(
                    new SemanticEdit(SemanticEditKind.Insert, null, f_int1)));

            var reader1 = diff1.GetMetadata().Reader;

            CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0");
            CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), ".ctor", "F", "<F>b__0#1_1", ".ctor", "<F>b__2", "<F>b__0#1_0");
            CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "a", "<>9__0#1_0");

            diff1.VerifySynthesizedMembers(
                "C: {<F>b__0#1_1, <>c__DisplayClass0#1_0, <>c}",
                "C.<>c: {<>9__0#1_0, <F>b__0#1_0}",
                "C.<>c__DisplayClass0#1_0: {a, <F>b__2}");

            var diff2 = compilation2.EmitDifference(
                diff1.NextGeneration,
                ImmutableArray.Create(
                    new SemanticEdit(SemanticEditKind.Insert, null, f_byte2)));

            var reader2 = diff2.GetMetadata().Reader;

            CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0");
            CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), ".ctor", "F", "<F>b__1#2_1", ".ctor", "<F>b__2", "<F>b__1#2_0");
            CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "a", "<>9__1#2_0");
        }
        public void AddIteratorMethod()
        {
            var source0 =
                @"using System.Collections.Generic;
class C
{
    static IEnumerable<object> F()
    {
        yield return 0;
    }
    static void M()
    {
    }
}";
            var source1 =
                @"using System.Collections.Generic;
class C
{
    static IEnumerable<object> F()
    {
        yield return 0;
    }
    static IEnumerable<int> G()
    {
        yield return 1;
    }
    static void M()
    {
    }
}";
            var compilation0 = CreateCompilationWithMscorlib(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
            var compilation1 = CreateCompilationWithMscorlib(Parse(source1, "a.cs"), options: TestOptions.DebugDll);

            var bytes0      = compilation0.EmitToArray();
            var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
            var diff1       = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Insert, null, compilation1.GetMember <MethodSymbol>("C.G"))));

            using (var md1 = diff1.GetMetadata())
            {
                var reader1 = md1.Reader;

                CheckEncLog(reader1,
                            Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
                            Row(17, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(18, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(19, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(20, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(21, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(22, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(23, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(24, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(25, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(26, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(27, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(28, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(29, TableIndex.MemberRef, EditAndContinueOperation.Default),
                            Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(23, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(24, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(25, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(26, TableIndex.TypeRef, EditAndContinueOperation.Default),
                            Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
                            Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                            Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                            Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
                            Row(2, TableIndex.PropertyMap, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                            Row(4, TableIndex.Field, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                            Row(5, TableIndex.Field, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                            Row(6, TableIndex.Field, EditAndContinueOperation.Default),
                            Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(16, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(17, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                            Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
                            Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
                            Row(3, TableIndex.Property, EditAndContinueOperation.Default),
                            Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
                            Row(4, TableIndex.Property, EditAndContinueOperation.Default),
                            Row(13, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
                            Row(2, TableIndex.Param, EditAndContinueOperation.Default),
                            Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                            Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                            Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                            Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                            Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                            Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                            Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                            Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                            Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
                            Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
                            Row(8, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                            Row(9, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                            Row(10, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                            Row(11, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                            Row(12, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                            Row(13, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                            Row(14, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                            Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
                            Row(6, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
                            Row(7, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
                            Row(8, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
                            Row(9, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
                            Row(10, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
                CheckEncMap(reader1,
                            Handle(16, TableIndex.TypeRef),
                            Handle(17, TableIndex.TypeRef),
                            Handle(18, TableIndex.TypeRef),
                            Handle(19, TableIndex.TypeRef),
                            Handle(20, TableIndex.TypeRef),
                            Handle(21, TableIndex.TypeRef),
                            Handle(22, TableIndex.TypeRef),
                            Handle(23, TableIndex.TypeRef),
                            Handle(24, TableIndex.TypeRef),
                            Handle(25, TableIndex.TypeRef),
                            Handle(26, TableIndex.TypeRef),
                            Handle(4, TableIndex.TypeDef),
                            Handle(4, TableIndex.Field),
                            Handle(5, TableIndex.Field),
                            Handle(6, TableIndex.Field),
                            Handle(12, TableIndex.MethodDef),
                            Handle(13, TableIndex.MethodDef),
                            Handle(14, TableIndex.MethodDef),
                            Handle(15, TableIndex.MethodDef),
                            Handle(16, TableIndex.MethodDef),
                            Handle(17, TableIndex.MethodDef),
                            Handle(18, TableIndex.MethodDef),
                            Handle(19, TableIndex.MethodDef),
                            Handle(20, TableIndex.MethodDef),
                            Handle(2, TableIndex.Param),
                            Handle(6, TableIndex.InterfaceImpl),
                            Handle(7, TableIndex.InterfaceImpl),
                            Handle(8, TableIndex.InterfaceImpl),
                            Handle(9, TableIndex.InterfaceImpl),
                            Handle(10, TableIndex.InterfaceImpl),
                            Handle(17, TableIndex.MemberRef),
                            Handle(18, TableIndex.MemberRef),
                            Handle(19, TableIndex.MemberRef),
                            Handle(20, TableIndex.MemberRef),
                            Handle(21, TableIndex.MemberRef),
                            Handle(22, TableIndex.MemberRef),
                            Handle(23, TableIndex.MemberRef),
                            Handle(24, TableIndex.MemberRef),
                            Handle(25, TableIndex.MemberRef),
                            Handle(26, TableIndex.MemberRef),
                            Handle(27, TableIndex.MemberRef),
                            Handle(28, TableIndex.MemberRef),
                            Handle(29, TableIndex.MemberRef),
                            Handle(12, TableIndex.CustomAttribute),
                            Handle(13, TableIndex.CustomAttribute),
                            Handle(14, TableIndex.CustomAttribute),
                            Handle(15, TableIndex.CustomAttribute),
                            Handle(16, TableIndex.CustomAttribute),
                            Handle(17, TableIndex.CustomAttribute),
                            Handle(18, TableIndex.CustomAttribute),
                            Handle(19, TableIndex.CustomAttribute),
                            Handle(4, TableIndex.StandAloneSig),
                            Handle(5, TableIndex.StandAloneSig),
                            Handle(6, TableIndex.StandAloneSig),
                            Handle(2, TableIndex.PropertyMap),
                            Handle(3, TableIndex.Property),
                            Handle(4, TableIndex.Property),
                            Handle(3, TableIndex.MethodSemantics),
                            Handle(4, TableIndex.MethodSemantics),
                            Handle(8, TableIndex.MethodImpl),
                            Handle(9, TableIndex.MethodImpl),
                            Handle(10, TableIndex.MethodImpl),
                            Handle(11, TableIndex.MethodImpl),
                            Handle(12, TableIndex.MethodImpl),
                            Handle(13, TableIndex.MethodImpl),
                            Handle(14, TableIndex.MethodImpl),
                            Handle(3, TableIndex.TypeSpec),
                            Handle(4, TableIndex.TypeSpec),
                            Handle(2, TableIndex.AssemblyRef),
                            Handle(2, TableIndex.NestedClass));
            }

            string actualPdb1 = PdbToXmlConverter.DeltaPdbToXml(diff1.PdbDelta, Enumerable.Range(1, 100).Select(rid => 0x06000000U | (uint)rid));

            // TODO (tomat): bug in SymWriter.
            // The PDB is missing debug info for G method. The info is written to the PDB but the native SymWriter
            // seems to ignore it. If another method is added to the class all information is written.
            // This happens regardless of whether we emit just the delta or full PDB.

            string expectedPdb1 = @"
<symbols>
  <files>
    <file id=""1"" name=""a.cs"" language=""3f5162f8-07c6-11d3-9053-00c04fa302a1"" languageVendor=""994b45c4-e6e9-11d2-903f-00c04fa302a1"" documentType=""5a869d0b-6611-11d3-bd2a-0000f80849bd"" checkSumAlgorithmId=""ff1816ec-aa5e-4d10-87f7-6f4963833460"" checkSum=""6E, 19, 36, 2B, 9A, 28, AB, E3, A2, DA, EB, 51, C1, 37,  1, 10, B0, 4F, CA, 84, "" />
  </files>
  <methods>
    <method token=""0x600000f"">
      <customDebugInfo version=""4"" count=""1"">
        <using version=""4"" kind=""UsingInfo"" size=""12"" namespaceCount=""1"">
          <namespace usingCount=""1"" />
        </using>
      </customDebugInfo>
      <sequencepoints total=""5"">
        <entry il_offset=""0x0"" hidden=""true"" start_row=""16707566"" start_column=""0"" end_row=""16707566"" end_column=""0"" file_ref=""1"" />
        <entry il_offset=""0x21"" start_row=""9"" start_column=""5"" end_row=""9"" end_column=""6"" file_ref=""1"" />
        <entry il_offset=""0x22"" start_row=""10"" start_column=""9"" end_row=""10"" end_column=""24"" file_ref=""1"" />
        <entry il_offset=""0x34"" hidden=""true"" start_row=""16707566"" start_column=""0"" end_row=""16707566"" end_column=""0"" file_ref=""1"" />
        <entry il_offset=""0x3b"" start_row=""11"" start_column=""5"" end_row=""11"" end_column=""6"" file_ref=""1"" />
      </sequencepoints>
      <locals>
        <local name=""CS$524$0000"" il_index=""0"" il_start=""0x0"" il_end=""0x3f"" attributes=""0"" />
      </locals>
      <scope startOffset=""0x0"" endOffset=""0x3f"">
        <namespace name=""System.Collections.Generic"" />
        <local name=""CS$524$0000"" il_index=""0"" il_start=""0x0"" il_end=""0x3f"" attributes=""0"" />
      </scope>
    </method>
  </methods>
</symbols>";

            AssertXmlEqual(expectedPdb1, actualPdb1);
        }
예제 #17
0
        private static bool ReflectionEmitInternal(
            Compilation compilation,
            string expectedOutput,
            bool peImageRequested,
            out ImmutableArray <byte> peImage,
            bool refEmitSupported,
            bool fallback,
            bool collectEmittedAssembly,
            bool peVerify,
            TempRoot tempRoot)
        {
            peImage = default(ImmutableArray <byte>);

            var success = false;
            var compilationDependencies = new List <ModuleData>();
            var diagnostics             = new DiagnosticBag();

            HostedRuntimeEnvironment.EmitReferences(compilation, compilationDependencies, diagnostics);

            // allow warnings
            if (diagnostics.HasAnyErrors())
            {
                // this will throw if there are errors
                diagnostics.Verify();
            }

            bool doExecute = expectedOutput != null;

            string fileName;
            string fileNameExt;
            string fileDir;

            TempFile outputFile;
            AssemblyBuilderAccess access;

            if (peImageRequested)
            {
                access = doExecute ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Save;

                // Until HostedExecutionEnvironment supports ref emit, we need to generate a unique temp file.
                // Otherwise, the file will be held open the next time we Emit this same compilation (done in CompileAndVerify).
                outputFile = tempRoot.CreateFile("RefEmit_", ".dll");

                fileNameExt = Path.GetFileName(outputFile.Path);
                fileName    = Path.GetFileNameWithoutExtension(fileNameExt);
                fileDir     = Path.GetDirectoryName(outputFile.Path);
            }
            else
            {
                outputFile = null;

                fileName    = CommonTestBase.GetUniqueName();
                fileNameExt = fileName + ".dll";
                fileDir     = null;

                access = collectEmittedAssembly ? AssemblyBuilderAccess.RunAndCollect : AssemblyBuilderAccess.Run;
            }

            var             assemblyName = new AssemblyIdentity(fileName).ToAssemblyName();
            AssemblyBuilder abuilder     = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, access, fileDir);
            ModuleBuilder   mbuilder     = abuilder.DefineDynamicModule("Module", fileNameExt, emitSymbolInfo: false);

            using (var assemblyManager = new RuntimeAssemblyManager())
            {
                assemblyManager.AddModuleData(compilationDependencies);

                DiagnosticBag emitDiagnostics = DiagnosticBag.GetInstance();
                MethodInfo    entryPoint;

                byte[] compiledAssemblyImage;

                success = compilation.Emit(
                    moduleBuilder: mbuilder,
                    assemblyLoader: new AssemblyLoader(assemblyManager),
                    assemblySymbolMapper: null,
                    recoverOnError: !refEmitSupported && fallback,
                    diagnostics: emitDiagnostics,
                    cancellationToken: default(CancellationToken),
                    entryPoint: out entryPoint,
                    compiledAssemblyImage: out compiledAssemblyImage
                    );

                emitDiagnostics.Free();

                if (success && peImageRequested)
                {
                    if (fallback)
                    {
                        peImage = compiledAssemblyImage.AsImmutableOrNull();
                    }
                    else
                    {
                        abuilder.Save(fileNameExt);
                        peImage = CommonTestBase.ReadFromFile(outputFile.Path);
                    }
                }

                if (refEmitSupported)
                {
                    Assert.True(success, "Expected Ref.Emit success");
                    Assert.Null(compiledAssemblyImage);
                }
                else if (fallback)
                {
                    Assert.True(success, "Expected fallback to CCI");
                    Assert.NotNull(compiledAssemblyImage);
                }
                else
                {
                    Assert.False(success, "Expected emit failure but it succeeded");
                    Assert.Null(compiledAssemblyImage);
                }

                if (success)
                {
                    if (peVerify)
                    {
                        Assert.False(peImage.IsDefault);

                        // Saving AssemblyBuilder to disk changes its manifest module MVID.
                        Guid mvid;
                        using (var metadata = ModuleMetadata.CreateFromImage(peImage))
                        {
                            mvid = metadata.GetModuleVersionId();
                        }

                        assemblyManager.AddMainModuleMvid(mvid);
#if !(ARM)
                        Assert.Equal(String.Empty, CLRHelpers.PeVerify(peImage).Concat());
#endif
                    }

                    if (doExecute)
                    {
                        Assert.NotNull(entryPoint);
                        assemblyManager.AddMainModuleMvid(entryPoint.Module.ModuleVersionId);

                        Action main = GetEntryPointAction(entryPoint);
                        ConsoleOutput.AssertEqual(main, expectedOutput, "");
                    }
                }

                return(success);
            }
        }
        public void MethodToAsyncMethod()
        {
            var source0      = @"
using System.Threading.Tasks;

class C
{
    static Task<int> F() 
    {
        return Task.FromResult(1);
    }
}";
            var source1      = @"
using System.Threading.Tasks;

class C
{
    static async Task<int> F() 
    {
        return await Task.FromResult(1);
    }
}";
            var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
            var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);

            var v0 = CompileAndVerify(compilation0);

            using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
            {
                var method0 = compilation0.GetMember <MethodSymbol>("C.F");
                var method1 = compilation1.GetMember <MethodSymbol>("C.F");

                var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
                var diff1       = compilation1.EmitDifference(
                    generation0,
                    ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));

                using (var md1 = diff1.GetMetadata())
                {
                    CheckEncLogDefinitions(md1.Reader,
                                           Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                           Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                           Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
                                           Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                                           Row(1, TableIndex.Field, EditAndContinueOperation.Default),
                                           Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                                           Row(2, TableIndex.Field, EditAndContinueOperation.Default),
                                           Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                                           Row(3, TableIndex.Field, EditAndContinueOperation.Default),
                                           Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                                           Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                                           Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                                           Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
                                           Row(1, TableIndex.Param, EditAndContinueOperation.Default),
                                           Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                           Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                           Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                           Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                           Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                                           Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
                                           Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
                                           Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
                }
            }
        }
예제 #19
0
        public void ChangingCompilationDependencies()
        {
            string srcLib = @"
public class D { }
";

            string src0 = @"
class C 
{ 
    public static int F(D a) { return 1; }
}
";
            string src1 = @"
class C 
{ 
    public static int F(D a) { return 2; }
}
";
            string src2 = @"
class C 
{ 
    public static int F(D a) { return 3; }
}
";
            var    lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            lib0.VerifyDiagnostics();

            var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            lib1.VerifyDiagnostics();

            var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            lib2.VerifyDiagnostics();

            var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll);
            var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() });
            var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() });

            var v0 = CompileAndVerify(compilation0);
            var v1 = CompileAndVerify(compilation1);
            var v2 = CompileAndVerify(compilation2);

            var f0 = compilation0.GetMember <MethodSymbol>("C.F");
            var f1 = compilation1.GetMember <MethodSymbol>("C.F");
            var f2 = compilation2.GetMember <MethodSymbol>("C.F");

            var md0         = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
            var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);

            var diff1 = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));

            diff1.EmitResult.Diagnostics.Verify();

            var diff2 = compilation2.EmitDifference(
                diff1.NextGeneration,
                ImmutableArray.Create(
                    SemanticEdit.Create(SemanticEditKind.Update, f1, f2)));

            diff2.EmitResult.Diagnostics.Verify();
        }
        public void UpdateAsync_NoVariables()
        {
            var source0      = @"
using System.Threading.Tasks;

class C
{
    static async Task<int> F() 
    {
        await Task.FromResult(1);
        return 2;
    }
}";
            var source1      = @"
using System.Threading.Tasks;

class C
{
    static async Task<int> F() 
    {
        await Task.FromResult(10);
        return 20;
    }
}";
            var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
            var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);

            var v0 = CompileAndVerify(compilation0);

            using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
            {
                var method0 = compilation0.GetMember <MethodSymbol>("C.F");
                var method1 = compilation1.GetMember <MethodSymbol>("C.F");

                var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
                var diff1       = compilation1.EmitDifference(
                    generation0,
                    ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));

                using (var md1 = diff1.GetMetadata())
                {
                    // Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
                    // 2 methods were updated:
                    // - the kick-off method (might be changed if the method previously wasn't async)
                    // - MoveNext method
                    CheckEncLogDefinitions(md1.Reader,
                                           Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                           Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                                           Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
                                           Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
                                           Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));

                    diff1.VerifyIL("C.<F>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
  // Code size      171 (0xab)
  .maxstack  3
  .locals init (int V_0, //CS$524$0000
                int V_1, //CS$523$0001
                System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
                C.<F>d__1 V_3,
                System.Exception V_4)
  IL_0000:  ldarg.0
  IL_0001:  ldfld      ""int C.<F>d__1.<>1__state""
  IL_0006:  stloc.0
  .try
  {
    IL_0007:  ldloc.0
    IL_0008:  brfalse.s  IL_000c
    IL_000a:  br.s       IL_000e
    IL_000c:  br.s       IL_0049
    IL_000e:  nop
    IL_000f:  ldc.i4.s   10
    IL_0011:  call       ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)""
    IL_0016:  callvirt   ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
    IL_001b:  stloc.2
    IL_001c:  ldloca.s   V_2
    IL_001e:  call       ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
    IL_0023:  brtrue.s   IL_0065
    IL_0025:  ldarg.0
    IL_0026:  ldc.i4.0
    IL_0027:  dup
    IL_0028:  stloc.0
    IL_0029:  stfld      ""int C.<F>d__1.<>1__state""
    IL_002e:  ldarg.0
    IL_002f:  ldloc.2
    IL_0030:  stfld      ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
    IL_0035:  ldarg.0
    IL_0036:  stloc.3
    IL_0037:  ldarg.0
    IL_0038:  ldflda     ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
    IL_003d:  ldloca.s   V_2
    IL_003f:  ldloca.s   V_3
    IL_0041:  call       ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__1)""
    IL_0046:  nop
    IL_0047:  leave.s    IL_00aa
    IL_0049:  ldarg.0
    IL_004a:  ldfld      ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
    IL_004f:  stloc.2
    IL_0050:  ldarg.0
    IL_0051:  ldflda     ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
    IL_0056:  initobj    ""System.Runtime.CompilerServices.TaskAwaiter<int>""
    IL_005c:  ldarg.0
    IL_005d:  ldc.i4.m1
    IL_005e:  dup
    IL_005f:  stloc.0
    IL_0060:  stfld      ""int C.<F>d__1.<>1__state""
    IL_0065:  ldloca.s   V_2
    IL_0067:  call       ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
    IL_006c:  pop
    IL_006d:  ldloca.s   V_2
    IL_006f:  initobj    ""System.Runtime.CompilerServices.TaskAwaiter<int>""
    IL_0075:  ldc.i4.s   20
    IL_0077:  stloc.1
    IL_0078:  leave.s    IL_0095
  }
  catch System.Exception
  {
    IL_007a:  stloc.s    V_4
    IL_007c:  nop
    IL_007d:  ldarg.0
    IL_007e:  ldc.i4.s   -2
    IL_0080:  stfld      ""int C.<F>d__1.<>1__state""
    IL_0085:  ldarg.0
    IL_0086:  ldflda     ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
    IL_008b:  ldloc.s    V_4
    IL_008d:  call       ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
    IL_0092:  nop
    IL_0093:  leave.s    IL_00aa
  }
  IL_0095:  ldarg.0
  IL_0096:  ldc.i4.s   -2
  IL_0098:  stfld      ""int C.<F>d__1.<>1__state""
  IL_009d:  ldarg.0
  IL_009e:  ldflda     ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
  IL_00a3:  ldloc.1
  IL_00a4:  call       ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
  IL_00a9:  nop
  IL_00aa:  ret
}
");
                    v0.VerifyIL("C.<F>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
  // Code size      169 (0xa9)
  .maxstack  3
  .locals init (int V_0, //CS$524$0000
                int V_1, //CS$523$0001
                System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
                C.<F>d__1 V_3,
                System.Exception V_4)
  IL_0000:  ldarg.0
  IL_0001:  ldfld      ""int C.<F>d__1.<>1__state""
  IL_0006:  stloc.0
  .try
  {
    IL_0007:  ldloc.0
    IL_0008:  brfalse.s  IL_000c
    IL_000a:  br.s       IL_000e
    IL_000c:  br.s       IL_0048
    IL_000e:  nop
    IL_000f:  ldc.i4.1
    IL_0010:  call       ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)""
    IL_0015:  callvirt   ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
    IL_001a:  stloc.2
    IL_001b:  ldloca.s   V_2
    IL_001d:  call       ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
    IL_0022:  brtrue.s   IL_0064
    IL_0024:  ldarg.0
    IL_0025:  ldc.i4.0
    IL_0026:  dup
    IL_0027:  stloc.0
    IL_0028:  stfld      ""int C.<F>d__1.<>1__state""
    IL_002d:  ldarg.0
    IL_002e:  ldloc.2
    IL_002f:  stfld      ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
    IL_0034:  ldarg.0
    IL_0035:  stloc.3
    IL_0036:  ldarg.0
    IL_0037:  ldflda     ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
    IL_003c:  ldloca.s   V_2
    IL_003e:  ldloca.s   V_3
    IL_0040:  call       ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__1)""
    IL_0045:  nop
    IL_0046:  leave.s    IL_00a8
    IL_0048:  ldarg.0
    IL_0049:  ldfld      ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
    IL_004e:  stloc.2
    IL_004f:  ldarg.0
    IL_0050:  ldflda     ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
    IL_0055:  initobj    ""System.Runtime.CompilerServices.TaskAwaiter<int>""
    IL_005b:  ldarg.0
    IL_005c:  ldc.i4.m1
    IL_005d:  dup
    IL_005e:  stloc.0
    IL_005f:  stfld      ""int C.<F>d__1.<>1__state""
    IL_0064:  ldloca.s   V_2
    IL_0066:  call       ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
    IL_006b:  pop
    IL_006c:  ldloca.s   V_2
    IL_006e:  initobj    ""System.Runtime.CompilerServices.TaskAwaiter<int>""
    IL_0074:  ldc.i4.2
    IL_0075:  stloc.1
    IL_0076:  leave.s    IL_0093
  }
  catch System.Exception
  {
    IL_0078:  stloc.s    V_4
    IL_007a:  nop
    IL_007b:  ldarg.0
    IL_007c:  ldc.i4.s   -2
    IL_007e:  stfld      ""int C.<F>d__1.<>1__state""
    IL_0083:  ldarg.0
    IL_0084:  ldflda     ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
    IL_0089:  ldloc.s    V_4
    IL_008b:  call       ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
    IL_0090:  nop
    IL_0091:  leave.s    IL_00a8
  }
  IL_0093:  ldarg.0
  IL_0094:  ldc.i4.s   -2
  IL_0096:  stfld      ""int C.<F>d__1.<>1__state""
  IL_009b:  ldarg.0
  IL_009c:  ldflda     ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
  IL_00a1:  ldloc.1
  IL_00a2:  call       ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
  IL_00a7:  nop
  IL_00a8:  ret
}
");
                }
            }
        }
예제 #21
0
        private void TestDependencyVersionWildcards(string sourceVersion, Version version0, Version version1, Version version2)
        {
            string srcLib = $@"
[assembly: System.Reflection.AssemblyVersion(""{sourceVersion}"")]

public class D {{ }}
";

            string src0 = @"
class C 
{ 
    public static int F(D a) { return 1; }
}
";
            string src1 = @"
class C 
{ 
    public static int F(D a) { return 2; }
}
";
            string src2 = @"
class C 
{ 
    public static int F(D a) { return 3; }
    public static int G(D a) { return 4; }
}
";
            var    lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version0);
            lib0.VerifyDiagnostics();

            var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version1);
            lib1.VerifyDiagnostics();

            var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version2);

            lib2.VerifyDiagnostics();

            var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll);
            var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() });
            var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() });

            var v0 = CompileAndVerify(compilation0);
            var v1 = CompileAndVerify(compilation1);
            var v2 = CompileAndVerify(compilation2);

            var f0 = compilation0.GetMember <MethodSymbol>("C.F");
            var f1 = compilation1.GetMember <MethodSymbol>("C.F");
            var f2 = compilation2.GetMember <MethodSymbol>("C.F");
            var g2 = compilation2.GetMember <MethodSymbol>("C.G");

            var md0         = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
            var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);

            var diff1 = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));

            var diff2 = compilation2.EmitDifference(
                diff1.NextGeneration,
                ImmutableArray.Create(
                    SemanticEdit.Create(SemanticEditKind.Update, f1, f2),
                    SemanticEdit.Create(SemanticEditKind.Insert, null, g2)));

            var md1 = diff1.GetMetadata();
            var md2 = diff2.GetMetadata();

            var aggReader = new AggregatedMetadataReader(md0.MetadataReader, md1.Reader, md2.Reader);

            // all references to Lib should be to the baseline version:
            VerifyAssemblyReferences(aggReader, new[]
            {
                "mscorlib, 4.0.0.0",
                "Lib, " + lib0.Assembly.Identity.Version,
                "mscorlib, 4.0.0.0",
                "Lib, " + lib0.Assembly.Identity.Version,
                "mscorlib, 4.0.0.0",
                "Lib, " + lib0.Assembly.Identity.Version,
            });
        }
예제 #22
0
        public void ReadingFromMetadata()
        {
            // the image is missing a record in ClassLayout table
            using (var module = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Invalid.ClassLayout))
            {
                var reader = module.Module.GetMetadataReader();

                foreach (var typeHandle in reader.TypeDefinitions)
                {
                    var type = reader.GetTypeDefinition(typeHandle);
                    var name = reader.GetString(type.Name);

                    bool badLayout = false;
                    System.Reflection.Metadata.TypeLayout mdLayout;
                    try
                    {
                        mdLayout = type.GetLayout();
                    }
                    catch (BadImageFormatException)
                    {
                        badLayout = true;
                        mdLayout  = default(System.Reflection.Metadata.TypeLayout);
                    }

                    bool       hasClassLayout = !mdLayout.IsDefault;
                    TypeLayout layout         = module.Module.GetTypeLayout(typeHandle);
                    switch (name)
                    {
                    case "<Module>":
                        Assert.False(hasClassLayout);
                        Assert.Equal(default(TypeLayout), layout);
                        Assert.False(badLayout);
                        break;

                    case "S1":
                    case "S2":
                        // invalid size/pack value
                        Assert.False(hasClassLayout);
                        Assert.True(badLayout);
                        break;

                    case "S3":
                        Assert.True(hasClassLayout);
                        Assert.Equal(1, mdLayout.Size);
                        Assert.Equal(2, mdLayout.PackingSize);
                        Assert.Equal(new TypeLayout(LayoutKind.Sequential, size: 1, alignment: 2), layout);
                        Assert.False(badLayout);
                        break;

                    case "S4":
                        Assert.True(hasClassLayout);
                        Assert.Equal(unchecked ((int)0x12345678), mdLayout.Size);
                        Assert.Equal(0, mdLayout.PackingSize);
                        Assert.Equal(new TypeLayout(LayoutKind.Sequential, size: 0x12345678, alignment: 0), layout);
                        Assert.False(badLayout);
                        break;

                    case "S5":
                        // doesn't have layout
                        Assert.False(hasClassLayout);
                        Assert.Equal(new TypeLayout(LayoutKind.Sequential, size: 0, alignment: 0), layout);
                        Assert.False(badLayout);
                        break;

                    default:
                        throw TestExceptionUtilities.UnexpectedValue(name);
                    }
                }
            }
        }
예제 #23
0
        public void DependencyVersionWildcards_Metadata()
        {
            string srcLib = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.*"")]

public class D { }
";

            string src0 = @"
class C 
{ 
    public static int F(D a) { return 1; }
}
";
            string src1 = @"
class C 
{ 
    public static int F(D a) { return 2; }
}
";
            string src2 = @"
class C 
{ 
    public static int F(D a) { return 3; }
    public static int G(D a) { return 4; }
}
";
            var    lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1001));
            lib0.VerifyDiagnostics();

            var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1002));
            lib1.VerifyDiagnostics();

            var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);

            ((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1003));
            lib2.VerifyDiagnostics();

            var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.EmitToImageReference() }, assemblyName: "C", options: TestOptions.DebugDll);
            var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.EmitToImageReference() });
            var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.EmitToImageReference() });

            var v0 = CompileAndVerify(compilation0);
            var v1 = CompileAndVerify(compilation1);
            var v2 = CompileAndVerify(compilation2);

            var f0 = compilation0.GetMember <MethodSymbol>("C.F");
            var f1 = compilation1.GetMember <MethodSymbol>("C.F");
            var f2 = compilation2.GetMember <MethodSymbol>("C.F");
            var g2 = compilation2.GetMember <MethodSymbol>("C.G");

            var md0         = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
            var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);

            var diff1 = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));

            diff1.EmitResult.Diagnostics.Verify(
                // error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging:
                // 'Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null' changed version to '1.0.2000.1002'.
                Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C",
                                                                          string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging,
                                                                                        "Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null", "1.0.2000.1002")));
        }
예제 #24
0
        public void MethodExtents(DebugInformationFormat format)
        {
            var source0 = MarkedSource(
                WithWindowsLineBreaks(
                    @"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""1111111111111111111111111111111111111111""
using System;

public class C
{
    int A() => 1;                  
                                   
    void F()                       
    {                              
#line 10 ""C:\F\A.cs""               
        Console.WriteLine();
#line 20 ""C:\F\B.cs""
        Console.WriteLine();
#line default
    }

    int E() => 1;

    void G()
    {
        Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>;

        Action <N:5>H2</N:5> = <N:1>() =>
        {
            Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>;

        }</N:1>;
    }
}                              
"
                    ),
                fileName: @"C:\Enc1.cs"
                );

            var source1 = MarkedSource(
                WithWindowsLineBreaks(
                    @"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""2222222222222222222222222222222222222222""
using System;

public class C
{
    int A() => 1;                 
                              
    void F()                      
    {                             
#line 10 ""C:\F\A.cs""         
        Console.WriteLine();
#line 10 ""C:\F\C.cs""
        Console.WriteLine();
#line default
    }

    void G()
    {
        Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>;

        Action <N:5>H2</N:5> = <N:1>() =>
        {
            Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>;
            Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>;
        }</N:1>;
    }

    int E() => 1;
}
"
                    ),
                fileName: @"C:\Enc1.cs"
                );

            var source2 = MarkedSource(
                WithWindowsLineBreaks(
                    @"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""3333333333333333333333333333333333333333""
using System;

public class C
{
    int A() => 3;                 
                              
    void F()       
    {    
#line 10 ""C:\F\B.cs""
        Console.WriteLine();
#line 10 ""C:\F\E.cs""
        Console.WriteLine();
#line default
    }

    void G()
    {
        

        Action <N:5>H2</N:5> = <N:1>() =>
        {
            
            Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>;
        }</N:1>;
    }

    int E() => 1;  

    int B() => 4;
}
"
                    ),
                fileName: @"C:\Enc1.cs"
                );

            var compilation0 = CreateCompilation(
                source0.Tree,
                options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
                assemblyName: "EncMethodExtents"
                );
            var compilation1 = compilation0.WithSource(source1.Tree);
            var compilation2 = compilation1.WithSource(source2.Tree);

            compilation0.VerifyDiagnostics();
            compilation1.VerifyDiagnostics();
            compilation2.VerifyDiagnostics();

            var v0 = CompileAndVerify(
                compilation0,
                emitOptions: EmitOptions.Default.WithDebugInformationFormat(format)
                );
            var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);

            var f0 = compilation0.GetMember <MethodSymbol>("C.F");
            var f1 = compilation1.GetMember <MethodSymbol>("C.F");
            var f2 = compilation2.GetMember <MethodSymbol>("C.F");

            var g0 = compilation0.GetMember <MethodSymbol>("C.G");
            var g1 = compilation1.GetMember <MethodSymbol>("C.G");
            var g2 = compilation2.GetMember <MethodSymbol>("C.G");

            var a1 = compilation1.GetMember <MethodSymbol>("C.A");
            var a2 = compilation2.GetMember <MethodSymbol>("C.A");

            var b2 = compilation2.GetMember <MethodSymbol>("C.B");

            var generation0 = EmitBaseline.CreateInitialBaseline(
                md0,
                v0.CreateSymReader().GetEncMethodDebugInfo
                );

            var syntaxMap1 = GetSyntaxMapFromMarkers(source0, source1);
            var diff1      = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(
                    SemanticEdit.Create(
                        SemanticEditKind.Update,
                        f0,
                        f1,
                        syntaxMap1,
                        preserveLocalVariables: true
                        ),
                    SemanticEdit.Create(
                        SemanticEditKind.Update,
                        g0,
                        g1,
                        syntaxMap1,
                        preserveLocalVariables: true
                        )
                    )
                );

            diff1.VerifySynthesizedMembers(
                "C: {<>c}",
                "C.<>c: {<>9__3_0, <>9__3_2, <>9__3_3#1, <>9__3_1, <G>b__3_0, <G>b__3_1, <G>b__3_2, <G>b__3_3#1}"
                );

            var reader1 = diff1.GetMetadata().Reader;

            CheckEncLogDefinitions(
                reader1,
                Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
                Row(5, TableIndex.Field, EditAndContinueOperation.Default),
                Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default)
                );

            if (format == DebugInformationFormat.PortablePdb)
            {
                using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff1.PdbDelta);

                CheckEncMap(
                    pdbProvider.GetMetadataReader(),
                    Handle(2, TableIndex.MethodDebugInformation),
                    Handle(4, TableIndex.MethodDebugInformation),
                    Handle(8, TableIndex.MethodDebugInformation),
                    Handle(9, TableIndex.MethodDebugInformation),
                    Handle(10, TableIndex.MethodDebugInformation),
                    Handle(11, TableIndex.MethodDebugInformation)
                    );
            }

            diff1.VerifyPdb(
                Enumerable.Range(0x06000001, 20),
                @"
<symbols>
  <files>
    <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""0B-95-CB-78-00-AE-C7-34-45-D9-FB-31-E4-30-A4-0E-FC-EA-9E-95"" />
    <file id=""2"" name=""C:\F\A.cs"" language=""C#"" />
    <file id=""3"" name=""C:\F\C.cs"" language=""C#"" />
  </files>
  <methods>
    <method token=""0x6000002"">
      <customDebugInfo>
        <using>
          <namespace usingCount=""1"" />
        </using>
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
        <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" />
        <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" />
        <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0xe"">
        <namespace name=""System"" />
      </scope>
    </method>
    <method token=""0x6000004"">
      <customDebugInfo>
        <forward token=""0x6000002"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
        <entry offset=""0x1"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""54"" document=""1"" />
        <entry offset=""0x21"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" />
        <entry offset=""0x41"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x42"">
        <local name=""H1"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" />
        <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" />
      </scope>
    </method>
    <method token=""0x6000008"">
      <customDebugInfo>
        <forward token=""0x6000002"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""19"" startColumn=""46"" endLine=""19"" endColumn=""47"" document=""1"" />
      </sequencePoints>
    </method>
    <method token=""0x6000009"">
      <customDebugInfo>
        <forward token=""0x6000002"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
        <entry offset=""0x1"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""58"" document=""1"" />
        <entry offset=""0x21"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" />
        <entry offset=""0x41"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x42"">
        <local name=""H3"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" />
        <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" />
      </scope>
    </method>
    <method token=""0x600000a"">
      <customDebugInfo>
        <forward token=""0x6000002"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""23"" startColumn=""50"" endLine=""23"" endColumn=""51"" document=""1"" />
      </sequencePoints>
    </method>
    <method token=""0x600000b"">
      <customDebugInfo>
        <forward token=""0x6000002"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" />
      </sequencePoints>
    </method>
  </methods>
</symbols>
"
                );
            var syntaxMap2 = GetSyntaxMapFromMarkers(source1, source2);
            var diff2      = compilation2.EmitDifference(
                diff1.NextGeneration,
                ImmutableArray.Create(
                    SemanticEdit.Create(
                        SemanticEditKind.Update,
                        f1,
                        f2,
                        syntaxMap2,
                        preserveLocalVariables: true
                        ),
                    SemanticEdit.Create(
                        SemanticEditKind.Update,
                        g1,
                        g2,
                        syntaxMap2,
                        preserveLocalVariables: true
                        ),
                    SemanticEdit.Create(
                        SemanticEditKind.Update,
                        a1,
                        a2,
                        syntaxMap2,
                        preserveLocalVariables: true
                        ),
                    SemanticEdit.Create(SemanticEditKind.Insert, null, b2)
                    )
                );

            diff2.VerifySynthesizedMembers(
                "C: {<>c}",
                "C.<>c: {<>9__3_3#1, <>9__3_1, <G>b__3_1, <G>b__3_3#1, <>9__3_0, <>9__3_2, <G>b__3_0, <G>b__3_2}"
                );

            var reader2 = diff2.GetMetadata().Reader;

            CheckEncLogDefinitions(
                reader2,
                Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
                Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
                Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
                Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default)
                );

            if (format == DebugInformationFormat.PortablePdb)
            {
                using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff2.PdbDelta);

                CheckEncMap(
                    pdbProvider.GetMetadataReader(),
                    Handle(1, TableIndex.MethodDebugInformation),
                    Handle(2, TableIndex.MethodDebugInformation),
                    Handle(4, TableIndex.MethodDebugInformation),
                    Handle(9, TableIndex.MethodDebugInformation),
                    Handle(11, TableIndex.MethodDebugInformation),
                    Handle(12, TableIndex.MethodDebugInformation)
                    );
            }

            diff2.VerifyPdb(
                Enumerable.Range(0x06000001, 20),
                @"
<symbols>
  <files>
    <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""9C-B9-FF-18-0E-9F-A4-22-93-85-A8-5A-06-11-43-1E-64-3E-88-06"" />
    <file id=""2"" name=""C:\F\B.cs"" language=""C#"" />
    <file id=""3"" name=""C:\F\E.cs"" language=""C#"" />
  </files>
  <methods>
    <method token=""0x6000001"">
      <customDebugInfo>
        <using>
          <namespace usingCount=""1"" />
        </using>
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""6"" startColumn=""16"" endLine=""6"" endColumn=""17"" document=""1"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x2"">
        <namespace name=""System"" />
      </scope>
    </method>
    <method token=""0x6000002"">
      <customDebugInfo>
        <forward token=""0x6000001"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
        <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" />
        <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" />
        <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
      </sequencePoints>
    </method>
    <method token=""0x6000004"">
      <customDebugInfo>
        <forward token=""0x6000001"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
        <entry offset=""0x1"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" />
        <entry offset=""0x21"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x22"">
        <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
      </scope>
    </method>
    <method token=""0x6000009"">
      <customDebugInfo>
        <forward token=""0x6000001"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
        <entry offset=""0x1"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" />
        <entry offset=""0x21"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x22"">
        <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
      </scope>
    </method>
    <method token=""0x600000b"">
      <customDebugInfo>
        <forward token=""0x6000001"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" />
      </sequencePoints>
    </method>
    <method token=""0x600000c"">
      <customDebugInfo>
        <forward token=""0x6000001"" />
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""30"" startColumn=""16"" endLine=""30"" endColumn=""17"" document=""1"" />
      </sequencePoints>
    </method>
  </methods>
</symbols>
"
                );
        }
예제 #25
0
        public void DependencyVersionWildcardsCollisions()
        {
            string srcLib01 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.1"")]

public class D { }
";
            string srcLib02 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.2"")]

public class D { }
";

            string srcLib11 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.1.1"")]

public class D { }
";
            string srcLib12 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.1.2"")]

public class D { }
";

            string src0  = @"
extern alias L0;
extern alias L1;

class C 
{ 
    public static int F(L0::D a, L1::D b) => 1;
}
";
            string src1  = @"
extern alias L0;
extern alias L1;

class C 
{ 
    public static int F(L0::D a, L1::D b) => 2;
}
";
            var    lib01 = CreateCompilation(srcLib01, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
            var    ref01 = lib01.ToMetadataReference(ImmutableArray.Create("L0"));

            var lib02 = CreateCompilation(srcLib02, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
            var ref02 = lib02.ToMetadataReference(ImmutableArray.Create("L0"));

            var lib11 = CreateCompilation(srcLib11, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
            var ref11 = lib11.ToMetadataReference(ImmutableArray.Create("L1"));

            var lib12 = CreateCompilation(srcLib12, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
            var ref12 = lib12.ToMetadataReference(ImmutableArray.Create("L1"));

            var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, ref01, ref11 }, assemblyName: "C", options: TestOptions.DebugDll);
            var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, ref02, ref12 });

            var v0 = CompileAndVerify(compilation0);

            var f0 = compilation0.GetMember <MethodSymbol>("C.F");
            var f1 = compilation1.GetMember <MethodSymbol>("C.F");

            var md0         = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
            var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);

            var diff1 = compilation1.EmitDifference(
                generation0,
                ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));

            diff1.EmitResult.Diagnostics.Verify(
                // error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging:
                // 'Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null' changed version to '1.0.0.2'.
                Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C",
                                                                          string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging,
                                                                                        "Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "1.0.0.2")));
        }
예제 #26
0
 internal static MetadataReference GetILModuleReference(string ilSource, bool prependDefaultHeader = true)
 {
     EmitILToArray(ilSource, prependDefaultHeader, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes);
     return(ModuleMetadata.CreateFromImage(assemblyBytes).GetReference());
 }
예제 #27
0
        internal static void VerifyIL(
            this byte[] assembly,
            int methodToken,
            string qualifiedName,
            string expectedIL,
            [CallerLineNumber] int expectedValueSourceLine  = 0,
            [CallerFilePath] string expectedValueSourcePath = null
            )
        {
            var parts = qualifiedName.Split('.');

            if (parts.Length != 2)
            {
                throw new NotImplementedException();
            }

            using (var metadata = ModuleMetadata.CreateFromImage(assembly))
            {
                var module       = metadata.Module;
                var reader       = module.MetadataReader;
                var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken);
                var methodDef    = reader.GetMethodDefinition(methodHandle);
                var typeDef      = reader.GetTypeDefinition(methodDef.GetDeclaringType());
                Assert.True(reader.StringComparer.Equals(typeDef.Name, parts[0]));
                Assert.True(reader.StringComparer.Equals(methodDef.Name, parts[1]));
                var methodBody = module.GetMethodBodyOrThrow(methodHandle);

                var pooled  = PooledStringBuilder.GetInstance();
                var builder = pooled.Builder;

                if (!methodBody.LocalSignature.IsNil)
                {
                    var visualizer = new MetadataVisualizer(
                        reader,
                        new StringWriter(),
                        MetadataVisualizerOptions.NoHeapReferences
                        );
                    var signature = reader.GetStandaloneSignature(methodBody.LocalSignature);
                    builder.AppendFormat(
                        "Locals: {0}",
                        visualizer.StandaloneSignature(signature.Signature)
                        );
                    builder.AppendLine();
                }

                ILVisualizer.Default.DumpMethod(
                    builder,
                    methodBody.MaxStack,
                    methodBody.GetILContent(),
                    ImmutableArray.Create <ILVisualizer.LocalInfo>(),
                    ImmutableArray.Create <ILVisualizer.HandlerSpan>()
                    );

                var actualIL = pooled.ToStringAndFree();

                AssertEx.AssertEqualToleratingWhitespaceDifferences(
                    expectedIL,
                    actualIL,
                    escapeQuotes: true,
                    expectedValueSourcePath: expectedValueSourcePath,
                    expectedValueSourceLine: expectedValueSourceLine
                    );
            }
        }