Esempio n. 1
0
        internal static BoundStatement ParseAndBindMethodBody(string program, bool lower, string typeName = DefaultTypeName, string methodName = DefaultMethodName)
        {
            var compilation = CreateCompilationWithMscorlib(program);
            var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single();
            var diagnostics = DiagnosticBag.GetInstance();
            try
            {
                // Provide an Emit.Module so that the lowering passes will be run
                var module = new PEAssemblyBuilder(
                    (SourceAssemblySymbol)compilation.Assembly,
                    EmitOptions.Default,
                    OutputKind.ConsoleApplication,
                    GetDefaultModulePropertiesForSerialization(),
                    Enumerable.Empty<ResourceDescription>(),
                    assemblySymbolMapper: null);

                TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, compilation, module);

                var block = MethodCompiler.BindMethodBody(method, compilationState, diagnostics);
                if ((block == null) || !lower)
                {
                    return block;
                }

                StateMachineTypeSymbol stateMachineTypeOpt;
                VariableSlotAllocator lazyVariableSlotAllocator = null;
                var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance();
                var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance();

                var body = MethodCompiler.LowerBodyOrInitializer(
                    method: method,
                    methodOrdinal: 0,
                    body: block,
                    previousSubmissionFields: null,
                    compilationState: compilationState,
                    diagnostics: diagnostics,
                    lazyVariableSlotAllocator: ref lazyVariableSlotAllocator,
                    lambdaDebugInfoBuilder: lambdaDebugInfoBuilder,
                    closureDebugInfoBuilder: closureDebugInfoBuilder,
                    stateMachineTypeOpt: out stateMachineTypeOpt);

                lambdaDebugInfoBuilder.Free();
                closureDebugInfoBuilder.Free();

                return body;
            }
            finally
            {
                diagnostics.Free();
            }
        }
Esempio n. 2
0
        internal static BoundBlock ParseAndBindMethodBody(string program, string typeName = DefaultTypeName, string methodName = DefaultMethodName)
        {
            var compilation = CreateCompilationWithMscorlib(program);
            var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single();

            // Provide an Emit.Module so that the lowering passes will be run
            var module = new PEAssemblyBuilder(
                (SourceAssemblySymbol)compilation.Assembly,
                emitOptions: EmitOptions.Default,
                outputKind: OutputKind.ConsoleApplication,
                serializationProperties: GetDefaultModulePropertiesForSerialization(),
                manifestResources: Enumerable.Empty<ResourceDescription>());

            TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, compilation, module);

            var diagnostics = DiagnosticBag.GetInstance();
            var block = MethodCompiler.BindMethodBody(method, compilationState, diagnostics);
            diagnostics.Free();
            return block;
        }
Esempio n. 3
0
        internal static BoundStatement ParseAndBindMethodBody(string program, bool lower, string typeName = DefaultTypeName, string methodName = DefaultMethodName)
        {
            var compilation = CreateCompilationWithMscorlib(program);
            var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single();
            var diagnostics = DiagnosticBag.GetInstance();
            try
            {
                var block = Compiler.BindMethodBody(method, diagnostics);
                if ((block == null) || !lower)
                {
                    return block;
                }

                // Provide an Emit.Module so that the lowering passes will be run
                var module = new PEAssemblyBuilder(
                    (SourceAssemblySymbol)compilation.Assembly,
                    null,
                    OutputKind.ConsoleApplication,
                    GetDefaultModulePropertiesForSerialization(),
                    Enumerable.Empty<ResourceDescription>(),
                    assemblySymbolMapper: null);

                TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, module);

                var body = Compiler.LowerStatement(
                    generateDebugInfo: true,
                    method: method,
                    body: block,
                    previousSubmissionFields: null,
                    compilationState: compilationState,
                    diagnostics: diagnostics);

                return body;
            }
            finally
            {
                diagnostics.Free();
            }
        }
        internal static void VerifyParamArrayAttribute(ParameterSymbol parameter, SourceModuleSymbol module, bool expected = true, OutputKind outputKind = OutputKind.ConsoleApplication)
        {
            Assert.Equal(expected, parameter.IsParams);

            var emitModule = new PEAssemblyBuilder(module.ContainingSourceAssembly, null, outputKind, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var paramArrayAttributeCtor = (MethodSymbol)emitModule.Compilation.GetWellKnownTypeMember(WellKnownMember.System_ParamArrayAttribute__ctor);
            bool found = false;

            var context = new EmitContext(emitModule, null, new DiagnosticBag());

            foreach (Microsoft.Cci.ICustomAttribute attr in parameter.GetSynthesizedAttributes())
            {
                if (paramArrayAttributeCtor == (MethodSymbol)attr.Constructor(context))
                {
                    Assert.False(found, "Multiple ParamArrayAttribute");
                    found = true;
                }
            }

            Assert.Equal(expected, found);
            context.Diagnostics.Verify();
        }
Esempio n. 5
0
        public void EmitMetadataOnly_SynthesizedExplicitImplementations()
        {
            var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;

            var libAssemblyName = "SynthesizedMethodMetadata";
            var exeAssemblyName = "CallSynthesizedMethod";

            // Setup: CppBase2 has methods that implement CppInterface1, but it doesn't declare
            // that it implements the interface.  Class1 does declare that it implements the
            // interface, but it's empty so it counts on CppBase2 to provide the implementations.
            // Since CppBase2 is not in the current source module, bridge methods are inserted
            // into Class1 to implement the interface methods by delegating to CppBase2.
            var libText = @"
public class Class1 : CppCli.CppBase2, CppCli.CppInterface1
{
}
";

            var libComp = CreateCompilationWithMscorlib(
                text: libText,
                references: new MetadataReference[] { ilAssemblyReference },
                compOptions: TestOptions.Dll,
                assemblyName: libAssemblyName);

            Assert.False(libComp.GetDiagnostics().Any());

            EmitResult emitResult;
            byte[] dllImage;
            using (var output = new MemoryStream())
            {
                emitResult = libComp.EmitMetadataOnly(output);
                dllImage = output.ToArray();
            }

            Assert.True(emitResult.Success);
            emitResult.Diagnostics.Verify();
            Assert.True(dllImage.Length > 0, "no metadata emitted");

            // NOTE: this DLL won't PEVerify because there are no method bodies.

            var class1 = libComp.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("Class1");

            // We would prefer to check that the module used by Compiler.Emit does the right thing,
            // but we don't have access to that object, so we'll create our own and manipulate it
            // in the same way.
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)class1.ContainingAssembly, null,
                OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            Compiler.CompileSynthesizedMethodMetadata(libComp, module, default(CancellationToken));

            var class1TypeDef = (Cci.ITypeDefinition)class1;

            var symbolSynthesized = class1.GetSynthesizedExplicitImplementations(CancellationToken.None);
            var context = new Microsoft.CodeAnalysis.Emit.Context(module, null, new DiagnosticBag());
            var cciExplicit = class1TypeDef.GetExplicitImplementationOverrides(context);
            var cciMethods = class1TypeDef.GetMethods(context).Where(m => ((MethodSymbol)m).MethodKind != MethodKind.Constructor);

            context.Diagnostics.Verify();
            var symbolsSynthesizedCount = symbolSynthesized.Length;
            Assert.True(symbolsSynthesizedCount > 0, "Expected more than 0 synthesized method symbols.");
            Assert.Equal(symbolsSynthesizedCount, cciExplicit.Count());
            Assert.Equal(symbolsSynthesizedCount, cciMethods.Count());

            var libAssemblyReference = new MetadataImageReference(dllImage.AsImmutableOrNull());

            var exeText = @"
class Class2
{
    public static void Main()
    {
        CppCli.CppInterface1 c = new Class1();
        c.Method1(1);
        c.Method2(2);
    }
}  
";

            var exeComp = CreateCompilationWithMscorlib(
                text: exeText,
                references: new MetadataReference[] { ilAssemblyReference, libAssemblyReference },
                assemblyName: exeAssemblyName);

            Assert.False(exeComp.GetDiagnostics().Any());

            using (var output = new MemoryStream())
            {
                emitResult = exeComp.Emit(output);

                Assert.True(emitResult.Success);
                emitResult.Diagnostics.Verify();
                output.Flush();
                Assert.True(output.Length > 0, "no metadata emitted");
            }

            // NOTE: there's no point in trying to run the EXE since it depends on a DLL with no method bodies.
        }
        public void IgnoreOtherDiagnosticsCompilingSynthesizedMethods()
        {
            var source =
@"class C
{
    static object F = new object(); // generate .cctor
    static System.Action M()
    {
        return () => { }; // generate lambda
    }
}";
            var compilation = CreateCompilationWithMscorlib(source, options: TestOptions.ReleaseDll.WithConcurrentBuild(false));
            var options = compilation.Options;
            var diagnostics = DiagnosticBag.GetInstance();

            var assembly = (SourceAssemblySymbol)compilation.Assembly;
            var module = new PEAssemblyBuilder(
                assembly,
                EmitOptions.Default,
                options.OutputKind,
                GetDefaultModulePropertiesForSerialization(),
                new ResourceDescription[0]);

            var methodBodyCompiler = new MethodCompiler(
                compilation: compilation,
                moduleBeingBuiltOpt: module,
                emittingPdb: false,
                hasDeclarationErrors: false,
                diagnostics: diagnostics,
                filterOpt: null,
                cancellationToken: CancellationToken.None);

            // Add diagnostic to MethodBodyCompiler bag, as if
            // code gen for an earlier method had generated an error.
            diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_IntDivByZero), NoLocation.Singleton));

            // Compile all methods for type including synthesized methods.
            var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
            methodBodyCompiler.Visit(type);

            Assert.Equal(1, diagnostics.AsEnumerable().Count());
            diagnostics.Free();
        }
Esempio n. 7
0
        public void MethodAccessorMethodOverriding()
        {
            var text = @"
public class A
{
    public virtual int get_P() { return 0; }
}

public class B : A
{
    public virtual int P { get; set; }
}

public class C : B
{
    public override int get_P() { return 0; }
}
";
            var comp = CreateCompilationWithMscorlib(text);
            comp.VerifyDiagnostics();

            var globalNamespace = comp.GlobalNamespace;

            var classA = globalNamespace.GetMember<NamedTypeSymbol>("A");
            var classB = globalNamespace.GetMember<NamedTypeSymbol>("B");
            var classC = globalNamespace.GetMember<NamedTypeSymbol>("C");

            var methodA = classA.GetMember<MethodSymbol>("get_P");
            var methodB = classB.GetMember<PropertySymbol>("P").GetMethod;
            var methodC = classC.GetMember<MethodSymbol>("get_P");

            var typeDefC = (Cci.ITypeDefinition)classC;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)classC.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverride = typeDefC.GetExplicitImplementationOverrides(context).Single();
            Assert.Equal(classC, explicitOverride.ContainingType);
            Assert.Equal(methodC, explicitOverride.ImplementingMethod);
            Assert.Equal(methodA, explicitOverride.ImplementedMethod);
            context.Diagnostics.Verify();
        }
Esempio n. 8
0
        public void ExplicitInterfaceImplementationGeneric()
        {
            string text = @"
namespace Namespace
{
    interface I<T>
    {
        void Method(T t);
    }
}

class IC : Namespace.I<int>
{
    void Namespace.I<int>.Method(int i) { }
}
";

            var comp = CreateCompilationWithMscorlib(Parse(text));

            var globalNamespace = comp.GlobalNamespace;
            var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("Namespace").Single();

            var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("I", 1).Single();
            Assert.Equal(TypeKind.Interface, @interface.TypeKind);

            var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();

            var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IC").Single();
            Assert.Equal(TypeKind.Class, @class.TypeKind);

            var substitutedInterface = @class.Interfaces.Single();
            Assert.Equal(@interface, substitutedInterface.ConstructedFrom);

            var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Single();

            var classMethod = (MethodSymbol)@class.GetMembers("Namespace.I<System.Int32>.Method").Single();
            Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);

            var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
            Assert.Equal(substitutedInterface, explicitImpl.ContainingType);
            Assert.Equal(substitutedInterfaceMethod.OriginalDefinition, explicitImpl.OriginalDefinition);

            var typeDef = (Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
            Assert.Equal(@class, explicitOverride.ContainingType);
            Assert.Equal(classMethod, explicitOverride.ImplementingMethod);

            var explicitOverrideImplementedMethod = explicitOverride.ImplementedMethod;
            Assert.Equal(substitutedInterface, explicitOverrideImplementedMethod.GetContainingType(context));
            Assert.Equal(substitutedInterfaceMethod.Name, explicitOverrideImplementedMethod.Name);
            Assert.Equal(substitutedInterfaceMethod.Arity, explicitOverrideImplementedMethod.GenericParameterCount);
            context.Diagnostics.Verify();
        }
Esempio n. 9
0
        public void ExplicitInterfaceImplementationRef()
        {
            string text = @"
interface I
{
    ref int Method(ref int i);
}

class C : I
{
    ref int I.Method(ref int i) { return ref i; }
}
";

            var comp = CreateCompilationWithMscorlib45(text);

            var globalNamespace = comp.GlobalNamespace;

            var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single();
            Assert.Equal(TypeKind.Interface, @interface.TypeKind);

            var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single();
            Assert.Equal(RefKind.Ref, interfaceMethod.RefKind);

            var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single();
            Assert.Equal(TypeKind.Class, @class.TypeKind);
            Assert.True(@class.Interfaces.Contains(@interface));

            var classMethod = (MethodSymbol)@class.GetMembers("I.Method").Single();
            Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);
            Assert.Equal(RefKind.Ref, classMethod.RefKind);

            var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
            Assert.Equal(interfaceMethod, explicitImpl);

            var typeDef = (Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
            Assert.Equal(@class, explicitOverride.ContainingType);
            Assert.Equal(classMethod, explicitOverride.ImplementingMethod);
            Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod);
            context.Diagnostics.Verify();
        }
Esempio n. 10
0
        public void ExplicitInterfaceImplementationCorLib()
        {
            string text = @"
class F : System.IFormattable
{
    string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider)
    {
        return null;
    }
}
";

            var comp = CreateCompilationWithMscorlib(Parse(text));

            var globalNamespace = comp.GlobalNamespace;
            var systemNamespace = (NamespaceSymbol)globalNamespace.GetMembers("System").Single();

            var @interface = (NamedTypeSymbol)systemNamespace.GetTypeMembers("IFormattable").Single();
            Assert.Equal(TypeKind.Interface, @interface.TypeKind);

            var interfaceMethod = (MethodSymbol)@interface.GetMembers("ToString").Single();

            var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("F").Single();
            Assert.Equal(TypeKind.Class, @class.TypeKind);
            Assert.True(@class.Interfaces.Contains(@interface));

            var classMethod = (MethodSymbol)@class.GetMembers("System.IFormattable.ToString").Single();
            Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind);

            var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single();
            Assert.Equal(interfaceMethod, explicitImpl);

            var typeDef = (Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
               GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverride = typeDef.GetExplicitImplementationOverrides(context).Single();
            Assert.Equal(@class, explicitOverride.ContainingType);
            Assert.Equal(classMethod, explicitOverride.ImplementingMethod);
            Assert.Equal(interfaceMethod, explicitOverride.ImplementedMethod);
            context.Diagnostics.Verify();
        }
        public void ExtensionMethod_ValidateExtensionAttribute()
        {
            var source =
@"using System;
internal static class C
{
    internal static void M1(this object o) { }
    private static void Main(string[] args) { }
}
";
            Action<ModuleSymbol> validator = module =>
            {
                var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");

                // Extension method.
                var method = type.GetMember<MethodSymbol>("M1");
                Assert.True(method.IsExtensionMethod);
                var parameter = method.Parameters[0];
                Assert.Equal(parameter.Type.SpecialType, SpecialType.System_Object);

                // Validate Extension attribute.
                var sourceModule = (SourceModuleSymbol)module;
                var emitModule = new PEAssemblyBuilder(sourceModule.ContainingSourceAssembly, EmitOptions.Default, OutputKind.ConsoleApplication, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
                var attrs = method.GetSynthesizedAttributes();
                Assert.Equal(1, attrs.Length);
                var attr = (Microsoft.Cci.ICustomAttribute)attrs.First();

                var extensionAttrCtor = (MethodSymbol)emitModule.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor);
                Assert.NotNull(extensionAttrCtor);
                var context = new EmitContext(emitModule, null, new DiagnosticBag());
                Assert.Equal(extensionAttrCtor, attr.Constructor(context));
                Assert.NotNull(extensionAttrCtor.ContainingType);
                Assert.Equal(extensionAttrCtor.ContainingType, attr.GetType(context));
                context.Diagnostics.Verify();
            };
            CompileAndVerify(source, additionalRefs: new[] { SystemCoreRef }, sourceSymbolValidator: validator, symbolValidator: null);
        }
Esempio n. 12
0
        private static void CheckPropertyExplicitImplementation(NamedTypeSymbol @class, PropertySymbol classProperty, PropertySymbol interfaceProperty)
        {
            var interfacePropertyGetter = interfaceProperty.GetMethod;
            Assert.NotNull(interfacePropertyGetter);
            var interfacePropertySetter = interfaceProperty.SetMethod;
            Assert.NotNull(interfacePropertySetter);

            Assert.Equal(interfaceProperty, classProperty.ExplicitInterfaceImplementations.Single());

            var classPropertyGetter = classProperty.GetMethod;
            Assert.NotNull(classPropertyGetter);
            var classPropertySetter = classProperty.SetMethod;
            Assert.NotNull(classPropertySetter);

            Assert.Equal(interfacePropertyGetter, classPropertyGetter.ExplicitInterfaceImplementations.Single());
            Assert.Equal(interfacePropertySetter, classPropertySetter.ExplicitInterfaceImplementations.Single());

            var typeDef = (Microsoft.Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());

            var context = new EmitContext(module, null, new DiagnosticBag());
            var explicitOverrides = typeDef.GetExplicitImplementationOverrides(context);
            Assert.Equal(2, explicitOverrides.Count());
            Assert.True(explicitOverrides.All(@override => ReferenceEquals(@class, @override.ContainingType)));

            // We're not actually asserting that the overrides are in this order - set comparison just seems like overkill for two elements
            var getterOverride = explicitOverrides.First();
            Assert.Equal(classPropertyGetter, getterOverride.ImplementingMethod);
            Assert.Equal(interfacePropertyGetter.ContainingType, getterOverride.ImplementedMethod.GetContainingType(context));
            Assert.Equal(interfacePropertyGetter.Name, getterOverride.ImplementedMethod.Name);

            var setterOverride = explicitOverrides.Last();
            Assert.Equal(classPropertySetter, setterOverride.ImplementingMethod);
            Assert.Equal(interfacePropertySetter.ContainingType, setterOverride.ImplementedMethod.GetContainingType(context));
            Assert.Equal(interfacePropertySetter.Name, setterOverride.ImplementedMethod.Name);
            context.Diagnostics.Verify();
        }
Esempio n. 13
0
        private void CheckEnumType(NamedTypeSymbol type, Accessibility declaredAccessibility, SpecialType underlyingType)
        {
            Assert.Equal(type.BaseType.SpecialType, SpecialType.System_Enum);
            Assert.Equal(type.EnumUnderlyingType.SpecialType, underlyingType);
            Assert.Equal(type.DeclaredAccessibility, declaredAccessibility);
            Assert.True(type.IsSealed);

            // value__ field should not be exposed from type, even though it is public,
            // since we want to prevent source from accessing the field directly.
            var field = type.GetMembers(WellKnownMemberNames.EnumBackingFieldName).SingleOrDefault() as FieldSymbol;
            Assert.Null(field);

            var sourceType = type as SourceNamedTypeSymbol;
            if (sourceType != null)
            {
                field = sourceType.EnumValueField;
                Assert.NotNull(field);
                Assert.Equal(field.Name, WellKnownMemberNames.EnumBackingFieldName);
                Assert.False(field.IsStatic);
                Assert.False(field.IsConst);
                Assert.False(field.IsReadOnly);
                Assert.Equal(field.DeclaredAccessibility, Accessibility.Public); // Dev10: value__ is public
                Assert.Equal(field.Type, type.EnumUnderlyingType);

                var module = new PEAssemblyBuilder((SourceAssemblySymbol)sourceType.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                    GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());

                var context = new EmitContext(module, null, new DiagnosticBag());

                var typeDefinition = (Microsoft.Cci.ITypeDefinition)type;
                var fieldDefinition = typeDefinition.GetFields(context).First();
                Assert.Same(fieldDefinition, field); // Dev10: value__ field is the first field.
                Assert.True(fieldDefinition.IsSpecialName);
                Assert.True(fieldDefinition.IsRuntimeSpecial);
                context.Diagnostics.Verify();
            }
        }
Esempio n. 14
0
        public void AssemblyRefs_DuplicateRows()
        {
            var compilation = CreateCompilationWithMscorlib(
                "class C : C1 { }; class D { }",
                new[] { TestReferences.SymbolsTests.Methods.CSMethods });

            PEAssemblyBuilder assembly = new PEAssemblyBuilder(
                (SourceAssemblySymbol)compilation.Assembly,
                EmitOptions.Default,
                compilation.Options.OutputKind,
                GetDefaultModulePropertiesForSerialization(),
                Enumerable.Empty<ResourceDescription>(),
                // map all references to a single name:
                assembylSymbol => new AssemblyIdentity("foo")
            );

            // Don't attempt to emit if there were any syntax, declaration, semantic, or emitted errors previously.
            DiagnosticBag diagnostics = new DiagnosticBag();

            MethodCompiler.CompileMethodBodies(
                compilation: compilation,
                moduleBeingBuiltOpt: assembly,
                generateDebugInfo: false,
                hasDeclarationErrors: false,
                diagnostics: diagnostics,
                filterOpt: null,
                cancellationToken: default(CancellationToken));

            diagnostics.Verify();
            var context = new EmitContext(assembly, null, new DiagnosticBag());
            ImmutableArray<byte> image;
            using (var stream = new MemoryStream())
            {
                Cci.PeWriter.WritePeToStream(
                    context,
                    compilation.MessageProvider,
                    stream,
                    nativePdbWriterOpt: null,
                    allowMissingMethodBodies: false,
                    deterministic: false,
                    cancellationToken: CancellationToken.None);

                image = stream.ToImmutable();
            }
            context.Diagnostics.Verify();

            // check that there are no duplicate rows in AssemblyRef table:
            PEAssembly emittedAssembly = AssemblyMetadata.CreateFromImage(image).GetAssembly();
            var emittedReferences = emittedAssembly.Modules[0].ReferencedAssemblies;
            Assert.Equal(1, emittedReferences.Length);
            Assert.Equal("foo", emittedReferences[0].Name);
        }
Esempio n. 15
0
        public void BaseInterfacesInMetadata()
        {
            var text = @"
interface I1 { }
interface I2 : I1 { }
class C : I2 { }
";
            var comp = CreateCompilationWithMscorlib(text);
            var global = comp.GlobalNamespace;

            var baseInterface = global.GetMember<NamedTypeSymbol>("I1");
            var derivedInterface = global.GetMember<NamedTypeSymbol>("I2");
            var @class = global.GetMember<NamedTypeSymbol>("C");

            var bothInterfaces = ImmutableArray.Create<NamedTypeSymbol>(baseInterface, derivedInterface);

            Assert.Equal(baseInterface, derivedInterface.AllInterfaces.Single());
            Assert.Equal(derivedInterface, @class.Interfaces.Single());
            Assert.True(@class.AllInterfaces.SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));

            var typeDef = (Cci.ITypeDefinition)@class;
            var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new EmitContext(module, null, new DiagnosticBag());
            var cciInterfaces = typeDef.Interfaces(context).Cast<NamedTypeSymbol>().AsImmutable();
            Assert.True(cciInterfaces.SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));
            context.Diagnostics.Verify();
        }
        internal CommonPEModuleBuilder CreateModuleBuilder(
            string outputName,
            IEnumerable<ResourceDescription> manifestResources,
            Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper,
            CancellationToken cancellationToken,
            CompilationTestData testData,
            DiagnosticBag diagnostics,
            bool metadataOnly,
            ImmutableArray<NamedTypeSymbol> additionalTypes)
        {
            // Do not waste a slot in the submission chain for submissions that contain no executable code
            // (they may only contain #r directives, usings, etc.)
            if (IsSubmission && !HasCodeToEmit())
            {
                return null;
            }

            string runtimeMDVersion = GetRuntimeMetadataVersion(diagnostics);
            if (runtimeMDVersion == null)
            {
                return null;
            }

            var moduleProps = ConstructModuleSerializationProperties(runtimeMDVersion);

            if (manifestResources == null)
            {
                manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>();
            }

            PEModuleBuilder moduleBeingBuilt;
            if (options.OutputKind.IsNetModule())
            {
                Debug.Assert(additionalTypes.IsEmpty);

                moduleBeingBuilt = new PENetModuleBuilder(
                    (SourceModuleSymbol)SourceModule,
                    outputName,
                    moduleProps,
                    manifestResources,
                    metadataOnly);
            }
            else
            {
                var kind = options.OutputKind.IsValid() ? options.OutputKind : OutputKind.DynamicallyLinkedLibrary;
                moduleBeingBuilt = new PEAssemblyBuilder(
                    SourceAssembly,
                    outputName,
                    kind,
                    moduleProps,
                    manifestResources,
                    assemblySymbolMapper,
                    additionalTypes,
                    metadataOnly);
            }

            // testData is only passed when running tests.
            if (testData != null)
            {
                moduleBeingBuilt.SetMethodTestData(testData.Methods);
                testData.Module = moduleBeingBuilt;
            }

            return moduleBeingBuilt;
        }
Esempio n. 17
0
        internal CommonPEModuleBuilder CreateModuleBuilder(
            string outputName,
            IEnumerable<ResourceDescription> manifestResources,
            Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper,
            ImmutableArray<NamedTypeSymbol> additionalTypes,
            CancellationToken cancellationToken,
            CompilationTestData testData,
            DiagnosticBag diagnostics,
            ref bool hasDeclarationErrors,
            bool metadataOnly)
        {
            // The diagnostics should include syntax and declaration errors also. We insert these before calling Emitter.Emit, so that the emitter
            // does not attempt to emit if there are declaration errors (but we do insert all errors from method body binding...)
            if (!FilterAndAppendDiagnostics(
                diagnostics,
                GetDiagnostics(CompilationStage.Declare, true, cancellationToken),
                this.options))
            {
                hasDeclarationErrors = true;
            }

            // Do not waste a slot in the submission chain for submissions that contain no executable code
            // (they may only contain #r directives, usings, etc.)
            if (IsSubmission && !HasCodeToEmit())
            {
                return null;
            }

            string runtimeMDVersion = GetRuntimeMetadataVersion(diagnostics);
            if (runtimeMDVersion == null)
            {
                return null;
            }

            var moduleProps = ConstructModuleSerializationProperties(runtimeMDVersion);

            if (manifestResources == null)
            {
                manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>();
            }

            PEModuleBuilder moduleBeingBuilt;
            if (options.OutputKind.IsNetModule())
            {
                Debug.Assert(additionalTypes.IsEmpty);

                moduleBeingBuilt = new PENetModuleBuilder(
                    (SourceModuleSymbol)SourceModule,
                    outputName,
                    moduleProps,
                    manifestResources,
                    metadataOnly);
            }
            else
            {
                var kind = options.OutputKind.IsValid() ? options.OutputKind : OutputKind.DynamicallyLinkedLibrary;
                moduleBeingBuilt = new PEAssemblyBuilder(
                    SourceAssembly,
                    outputName,
                    kind,
                    moduleProps,
                    manifestResources,
                    assemblySymbolMapper,
                    additionalTypes,
                    metadataOnly);
            }

            // testData is only passed when running tests.
            if (testData != null)
            {
                moduleBeingBuilt.SetMethodTestData(testData.Methods);
                testData.Module = moduleBeingBuilt;
            }

            return moduleBeingBuilt;
        }