Cci.ITypeReference Cci.ISignature.GetType(Microsoft.CodeAnalysis.Emit.Context context)
 {
     CheckDefinitionInvariant();
     return(((PEModuleBuilder)context.Module).Translate(this.Type,
                                                        syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                        diagnostics: context.Diagnostics));
 }
示例#2
0
        public static void VisitReference(Microsoft.Cci.IReference reference, Microsoft.CodeAnalysis.Emit.Context context)
        {
            var typeReference = reference as Microsoft.Cci.ITypeReference;

            if (typeReference != null)
            {
                VisitTypeReference(typeReference, context);
                return;
            }

            var methodReference = reference as Microsoft.Cci.IMethodReference;

            if (methodReference != null)
            {
                VisitMethodReference(methodReference, context);
                return;
            }

            var fieldReference = reference as Microsoft.Cci.IFieldReference;

            if (fieldReference != null)
            {
                VisitFieldReference(fieldReference, context);
                return;
            }
        }
示例#3
0
        IEnumerable <Cci.ITypeReference> Cci.IGenericParameter.GetConstraints(Microsoft.CodeAnalysis.Emit.Context context)
        {
            var moduleBeingBuilt = (PEModuleBuilder)context.Module;
            var seenValueType    = false;

            foreach (var type in this.ConstraintTypesNoUseSiteDiagnostics)
            {
                switch (type.SpecialType)
                {
                case SpecialType.System_Object:
                    // Avoid emitting unnecessary object constraint.
                    continue;

                case SpecialType.System_ValueType:
                    seenValueType = true;
                    break;
                }
                yield return(moduleBeingBuilt.Translate(type,
                                                        syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                        diagnostics: context.Diagnostics));
            }
            if (this.HasValueTypeConstraint && !seenValueType)
            {
                // Add System.ValueType constraint to comply with Dev11 output
                yield return(moduleBeingBuilt.GetSpecialType(SpecialType.System_ValueType,
                                                             syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                             diagnostics: context.Diagnostics));
            }
        }
示例#4
0
        Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(Microsoft.CodeAnalysis.Emit.Context context)
        {
            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            Debug.Assert(((Cci.ITypeReference) this).AsNamespaceTypeReference != null);
            return(moduleBeingBuilt.Translate(this.ContainingModule, context.Diagnostics));
        }
        internal Cci.IMetadataConstant GetMetadataConstantValue(Microsoft.CodeAnalysis.Emit.Context context)
        {
            if (!HasMetadataConstantValue)
            {
                return(null);
            }

            ConstantValue constant = this.ExplicitDefaultConstantValue;
            TypeSymbol    type;

            if (constant.SpecialType != SpecialType.None)
            {
                // preserve the exact type of the constant for primitive types,
                // e.g. it should be Int16 for [DefaultParameterValue((short)1)]int x
                type = this.ContainingAssembly.GetSpecialType(constant.SpecialType);
            }
            else
            {
                // default(struct), enum
                type = this.Type;
            }

            return(((PEModuleBuilder)context.Module).CreateConstant(type, constant.Value,
                                                                    syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                                    diagnostics: context.Diagnostics));
        }
示例#6
0
        Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(Microsoft.CodeAnalysis.Emit.Context context)
        {
            var obj = ((PEModuleBuilder)context.Module).GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object,
                                                                       syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                                       diagnostics: context.Diagnostics);

            return(((Cci.INamespaceTypeReference)obj).GetUnit(context));
        }
示例#7
0
        Cci.ITypeReference Cci.ISignature.GetType(Microsoft.CodeAnalysis.Emit.Context context)
        {
            ByRefReturnErrorTypeSymbol byRefType = this.ReturnType as ByRefReturnErrorTypeSymbol;

            return(((PEModuleBuilder)context.Module).Translate(
                       (object)byRefType == null ? this.ReturnType : byRefType.ReferencedType,
                       syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                       diagnostics: context.Diagnostics));
        }
        public override IEnumerable <Microsoft.Cci.ICustomAttribute> GetAttributes(Microsoft.CodeAnalysis.Emit.Context context)
        {
            if (compilerGeneratedAttribute != null)
            {
                return(SpecializedCollections.SingletonEnumerable(this.compilerGeneratedAttribute));
            }

            return(SpecializedCollections.EmptyEnumerable <Microsoft.Cci.ICustomAttribute>());
        }
        private static MetadataTypeOf CreateType(TypedConstant argument, Microsoft.CodeAnalysis.Emit.Context context)
        {
            Debug.Assert(argument.Value != null);
            var moduleBeingBuilt = (PEModuleBuilder)context.Module;
            var syntaxNodeOpt    = (CSharpSyntaxNode)context.SyntaxNodeOpt;
            var diagnostics      = context.Diagnostics;

            return(new MetadataTypeOf(moduleBeingBuilt.Translate((TypeSymbol)argument.Value, syntaxNodeOpt, diagnostics),
                                      moduleBeingBuilt.Translate((TypeSymbol)argument.Type, syntaxNodeOpt, diagnostics)));
        }
示例#10
0
        protected override IEnumerable <Cci.ITypeReference> GetInterfaces(Microsoft.CodeAnalysis.Emit.Context context)
        {
            Debug.Assert((object)TypeManager.ModuleBeingBuilt == context.Module);

            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            foreach (NamedTypeSymbol @interface in UnderlyingNamedType.GetInterfacesToEmit())
            {
                yield return(moduleBeingBuilt.Translate(@interface, (CSharpSyntaxNode)context.SyntaxNodeOpt, context.Diagnostics));
            }
        }
示例#11
0
        Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode(Microsoft.CodeAnalysis.Emit.Context context)
        {
            Debug.Assert(this.IsDefinitionOrDistinct());

            if (this.IsDefinition)
            {
                return(this.PrimitiveTypeCode);
            }

            return(Cci.PrimitiveTypeCode.NotPrimitive);
        }
示例#12
0
        Cci.ITypeReference Cci.IPointerTypeReference.GetTargetType(Microsoft.CodeAnalysis.Emit.Context context)
        {
            var type = ((PEModuleBuilder)context.Module).Translate(this.PointedAtType, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt, diagnostics: context.Diagnostics);

            if (this.CustomModifiers.Length == 0)
            {
                return(type);
            }
            else
            {
                return(new Cci.ModifiedTypeReference(type, this.CustomModifiers));
            }
        }
示例#13
0
        private Cci.IMethodDefinition ResolvedMethodImpl(Microsoft.CodeAnalysis.Emit.Context context)
        {
            Debug.Assert(this.IsDefinitionOrDistinct());
            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            if (this.IsDefinition &&                                    // can't be generic instantiation
                this.ContainingModule == moduleBeingBuilt.SourceModule) // must be declared in the module we are building
            {
                return(this.PartialImplementation() ?? this);
            }

            return(null);
        }
        Microsoft.Cci.ITypeReference Microsoft.Cci.IFieldReference.GetType(Microsoft.CodeAnalysis.Emit.Context context)
        {
            var customModifiers = underlyingField.CustomModifiers;
            var type            = ((PEModuleBuilder)context.Module).Translate(underlyingField.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt, diagnostics: context.Diagnostics);

            if (customModifiers.Length == 0)
            {
                return(type);
            }
            else
            {
                return(new Microsoft.Cci.ModifiedTypeReference(type, customModifiers));
            }
        }
示例#15
0
        IEnumerable <Cci.ITypeReference> Cci.ITypeDefinition.Interfaces(Microsoft.CodeAnalysis.Emit.Context context)
        {
            Debug.Assert(((Cci.ITypeReference) this).AsTypeDefinition(context) != null);

            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            foreach (NamedTypeSymbol @interface in this.GetInterfacesToEmit())
            {
                yield return(moduleBeingBuilt.Translate(@interface,
                                                        syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                        diagnostics: context.Diagnostics,
                                                        fromImplements: true));
            }
        }
        Cci.IDefinition Cci.IReference.AsDefinition(Microsoft.CodeAnalysis.Emit.Context context)
        {
            Debug.Assert(this.IsDefinitionOrDistinct());

            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            if (this.IsDefinition &&
                this.ContainingModule == moduleBeingBuilt.SourceModule)
            {
                return(this);
            }

            return(null);
        }
示例#17
0
        /// <summary>
        /// Zero or more named arguments that specify values for fields and properties of the attribute.
        /// </summary>
        public ImmutableArray <Cci.IMetadataNamedArgument> GetNamedArguments(Microsoft.CodeAnalysis.Emit.Context context)
        {
            // Perform fixup
            Cci.ITypeReference stringType = context.Module.GetPlatformType(Cci.PlatformType.SystemString, context);

#if DEBUG
            // Must have exactly 1 named argument.
            var namedArgs = this.sourceAttribute.GetNamedArguments(context);
            Debug.Assert(namedArgs.Count() == 1);

            // Named argument must be 'File' property of string type
            var fileArg = namedArgs.First();
            Debug.Assert(fileArg.ArgumentName == FilePropertyName);
            Debug.Assert(context.Module.IsPlatformType(fileArg.Type, Cci.PlatformType.SystemString));

            // Named argument value must be a non-empty string
            Debug.Assert(fileArg.ArgumentValue is Cci.IMetadataConstant);
            var fileName = (string)((Cci.IMetadataConstant)fileArg.ArgumentValue).Value;
            Debug.Assert(!String.IsNullOrEmpty(fileName));

            // PermissionSetAttribute type must have a writable public string type property member 'Hex'
            Debug.Assert(((INamedTypeSymbol)this.sourceAttribute.GetType(context)).GetMembers(HexPropertyName).Any(
                             member => member.Kind == SymbolKind.Property && ((IPropertySymbol)member).Type.SpecialType == SpecialType.System_String));
#endif

            string hexFileContent;

            // Read the file contents at the resolved file path into a byte array.
            // May throw PermissionSetFileReadException, which is handled in Compilation.Emit.
            var resolver = context.ModuleBuilder.CommonCompilation.Options.XmlReferenceResolver;

            // If the resolver isn't available we won't get here since we had to use it to resolve the path.
            Debug.Assert(resolver != null);

            try
            {
                using (Stream stream = resolver.OpenReadChecked(resolvedPermissionSetFilePath))
                {
                    // Convert the byte array contents into a string in hexa-decimal format.
                    hexFileContent = ConvertToHex(stream);
                }
            }
            catch (IOException e)
            {
                throw new PermissionSetFileReadException(e.Message, resolvedPermissionSetFilePath);
            }

            // Synthesize a named attribute argument "Hex = hexFileContent".
            return(ImmutableArray.Create <Cci.IMetadataNamedArgument>(new HexPropertyMetadataNamedArgument(stringType, new MetadataConstant(stringType, hexFileContent))));
        }
        Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(Microsoft.CodeAnalysis.Emit.Context context)
        {
            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            Debug.Assert(this.IsDefinitionOrDistinct());

            if (!this.IsDefinition)
            {
                return(moduleBeingBuilt.Translate(this.ContainingType,
                                                  syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                  diagnostics: context.Diagnostics));
            }

            return(this.ContainingType);
        }
示例#19
0
        object Cci.IMarshallingInformation.GetCustomMarshaller(Microsoft.CodeAnalysis.Emit.Context context)
        {
            Debug.Assert(marshalType == Cci.Constants.UnmanagedType_CustomMarshaler);
            var typeSymbol = marshalTypeNameOrSymbol as ITypeSymbol;

            if (typeSymbol != null)
            {
                return(((CommonPEModuleBuilder)context.Module).Translate(typeSymbol, context.SyntaxNodeOpt, context.Diagnostics));
            }
            else
            {
                Debug.Assert(marshalTypeNameOrSymbol == null || marshalTypeNameOrSymbol is string);
                return(marshalTypeNameOrSymbol);
            }
        }
示例#20
0
        ImmutableArray <Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(Microsoft.CodeAnalysis.Emit.Context context)
        {
            Debug.Assert(this.IsDefinitionOrDistinct());

            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            if (this.IsDefinition && this.ContainingModule == moduleBeingBuilt.SourceModule)
            {
                return(StaticCast <Cci.IParameterTypeInformation> .From(this.EnumerateDefinitionParameters()));
            }
            else
            {
                return(moduleBeingBuilt.Translate(this.Parameters));
            }
        }
        Cci.ITypeReference Cci.IArrayTypeReference.GetElementType(Microsoft.CodeAnalysis.Emit.Context context)
        {
            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            var type = moduleBeingBuilt.Translate(this.ElementType, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt, diagnostics: context.Diagnostics);

            if (this.CustomModifiers.Length == 0)
            {
                return(type);
            }
            else
            {
                return(new Cci.ModifiedTypeReference(type, this.CustomModifiers));
            }
        }
示例#22
0
        Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(Microsoft.CodeAnalysis.Emit.Context context)
        {
            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            Debug.Assert(this.IsDefinitionOrDistinct());

            if ((object)this.ContainingType == null &&
                this.IsDefinition &&
                this.ContainingModule == moduleBeingBuilt.SourceModule)
            {
                return(this);
            }

            return(null);
        }
        internal Cci.IMetadataConstant GetMetadataConstantValue(Microsoft.CodeAnalysis.Emit.Context context)
        {
            // A constant field of type decimal is not treated as a compile time value in CLR,
            // so check if it is a metadata constant, not just a constant to exclude decimals.
            if (this.IsMetadataConstant)
            {
                // NOTE: We would like to be able to assert that the constant value of this field
                // is not bad (i.e. ConstantValue.Bad) if it is being consumed by CCI, but we can't
                // because this method is called by the ReferenceIndexer in the metadata-only case
                // (and we specifically don't want to prevent metadata-only emit because of a bad
                // constant).  If the constant value is bad, we'll end up exposing null to CCI.
                return(((PEModuleBuilder)context.Module).CreateConstant(this.Type, this.ConstantValue,
                                                                        syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                                        diagnostics: context.Diagnostics));
            }

            return(null);
        }
        ImmutableArray <Cci.IMetadataExpression> Cci.ICustomAttribute.GetArguments(Microsoft.CodeAnalysis.Emit.Context context)
        {
            var commonArgs = this.CommonConstructorArguments;

            if (commonArgs.IsEmpty)
            {
                return(ImmutableArray <Cci.IMetadataExpression> .Empty);
            }

            var builder = ArrayBuilder <Cci.IMetadataExpression> .GetInstance();

            foreach (var argument in commonArgs)
            {
                Debug.Assert(argument.Kind != TypedConstantKind.Error);
                builder.Add(CreateMetadataExpression(argument, context));
            }
            return(builder.ToImmutableAndFree());
        }
示例#25
0
        Cci.ITypeReference Cci.ITypeDefinition.GetBaseClass(Microsoft.CodeAnalysis.Emit.Context context)
        {
            PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;

            Debug.Assert(((Cci.ITypeReference) this).AsTypeDefinition(context) != null);
            NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics;

            if (this.TypeKind == TypeKind.Submission)
            {
                // although submission semantically doesn't have a base we need to emit one into metadata:
                Debug.Assert((object)baseType == null);
                baseType = this.ContainingAssembly.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object);
            }

            return(((object)baseType != null) ? moduleBeingBuilt.Translate(baseType,
                                                                           syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt,
                                                                           diagnostics: context.Diagnostics) : null);
        }
示例#26
0
        IEnumerable <Cci.INestedTypeDefinition> Cci.ITypeDefinition.GetNestedTypes(Microsoft.CodeAnalysis.Emit.Context context)
        {
            CheckDefinitionInvariant();

            foreach (NamedTypeSymbol type in this.GetTypeMembers()) // Ordered.
            {
                yield return(type);
            }

            IEnumerable <Cci.INestedTypeDefinition> generated = ((PEModuleBuilder)context.Module).GetCompilerGeneratedTypes(this);

            if (generated != null)
            {
                foreach (var t in generated)
                {
                    yield return(t);
                }
            }
        }
示例#27
0
        IEnumerable <Cci.IFieldDefinition> Cci.ITypeDefinition.GetFields(Microsoft.CodeAnalysis.Emit.Context context)
        {
            CheckDefinitionInvariant();

            foreach (var f in GetFieldsToEmit())
            {
                yield return(f);
            }

            IEnumerable <Cci.IFieldDefinition> generated = ((PEModuleBuilder)context.Module).GetCompilerGeneratedFields(this);

            if (generated != null)
            {
                foreach (var f in generated)
                {
                    yield return(f);
                }
            }
        }
示例#28
0
        public FullPeWriter(
            Microsoft.CodeAnalysis.Emit.Context context,
            CommonMessageProvider messageProvider,
            PdbWriter pdbWriter,
            bool allowMissingMethodBodies,
            bool foldIdenticalMethodBodies,
            CancellationToken cancellationToken) :
            base(context, messageProvider, pdbWriter, allowMissingMethodBodies, foldIdenticalMethodBodies, cancellationToken)
        {
            // EDMAURER make some intelligent guesses for the initial sizes of these things.
            int numMethods           = this.module.HintNumberOfMethodDefinitions;
            int numTypeDefsGuess     = numMethods / 6;
            int numFieldDefsGuess    = numTypeDefsGuess * 4;
            int numPropertyDefsGuess = numMethods / 4;

            this.typeDefs          = new DefinitionIndex <ITypeDefinition>(numTypeDefsGuess);
            this.eventDefs         = new DefinitionIndex <IEventDefinition>(0);
            this.fieldDefs         = new DefinitionIndex <IFieldDefinition>(numFieldDefsGuess);
            this.methodDefs        = new DefinitionIndex <IMethodDefinition>(numMethods);
            this.propertyDefs      = new DefinitionIndex <IPropertyDefinition>(numPropertyDefsGuess);
            this.parameterDefs     = new DefinitionIndex <IParameterDefinition>(numMethods);
            this.genericParameters = new DefinitionIndex <IGenericParameter>(0);

            this.fieldDefIndex      = new Dictionary <ITypeDefinition, uint>(numTypeDefsGuess);
            this.methodDefIndex     = new Dictionary <ITypeDefinition, uint>(numTypeDefsGuess);
            this.parameterListIndex = new Dictionary <IMethodDefinition, uint>(numMethods);

            this.assemblyRefIndex         = new HeapOrReferenceIndex <IAssemblyReference>(this, AssemblyReferenceComparer.Instance);
            this.moduleRefIndex           = new HeapOrReferenceIndex <string>(this);
            this.memberRefIndex           = new InstanceAndStructuralReferenceIndex <ITypeMemberReference>(this, new MemberRefComparer(this));
            this.methodSpecIndex          = new InstanceAndStructuralReferenceIndex <IGenericMethodInstanceReference>(this, new MethodSpecComparer(this));
            this.typeRefIndex             = new HeapOrReferenceIndex <ITypeReference>(this);
            this.typeSpecIndex            = new InstanceAndStructuralReferenceIndex <ITypeReference>(this, new TypeSpecComparer(this));
            this.standAloneSignatureIndex = new HeapOrReferenceIndex <uint>(this);

            // Add zero-th entry for indexed tables in full metadata. (For delta
            // metadata, the indexed tables will be concatenated with the full
            // metadata by the CLR, so the zero-th entries are not needed.)
            this.blobWriter.WriteByte(0);
            this.stringWriter.WriteByte(0);
            this.userStringWriter.WriteByte(0);
        }
示例#29
0
        IEnumerable <Cci.IPropertyDefinition> Cci.ITypeDefinition.GetProperties(Microsoft.CodeAnalysis.Emit.Context context)
        {
            CheckDefinitionInvariant();

            foreach (var property in this.GetPropertiesToEmit())
            {
                Debug.Assert((object)property != null);
                yield return(property);
            }

            IEnumerable <Cci.IPropertyDefinition> generated = ((PEModuleBuilder)context.Module).GetCompilerGeneratedProperties(this);

            if (generated != null)
            {
                foreach (var m in generated)
                {
                    yield return(m);
                }
            }
        }
示例#30
0
        IEnumerable <Cci.IAssemblyReference> Cci.IModule.GetAssemblyReferences(Microsoft.CodeAnalysis.Emit.Context context)
        {
            Cci.IAssemblyReference corLibrary = GetCorLibraryReferenceToEmit(context);

            // Only add Cor Library reference explicitly, PeWriter will add
            // other references implicitly on as needed basis.
            if (corLibrary != null)
            {
                yield return(corLibrary);
            }

            if (OutputKind != CodeAnalysis.OutputKind.NetModule)
            {
                // Explicitly add references from added modules
                foreach (var aRef in GetAssemblyReferencesFromAddedModules(context.Diagnostics))
                {
                    yield return(aRef);
                }
            }
        }
示例#31
0
        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, null, 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 Microsoft.CodeAnalysis.Emit.Context(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, emitOptions: EmitOptions.CCI, additionalRefs: new[] { SystemCoreRef }, sourceSymbolValidator: validator, symbolValidator: null);
        }
示例#32
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, null, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());

            var context = new Microsoft.CodeAnalysis.Emit.Context(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();
        }
示例#33
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, null, OutputKind.DynamicallyLinkedLibrary,
                    GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());

                var context = new Microsoft.CodeAnalysis.Emit.Context(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();
            }
        }
示例#34
0
 public MetadataVisitor(EmitContext context)
 {
     this.Context = context;
 }
        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 Microsoft.CodeAnalysis.Emit.Context(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();
        }
示例#36
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, null, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new Microsoft.CodeAnalysis.Emit.Context(module, null, new DiagnosticBag());
            var cciInterfaces = typeDef.Interfaces(context).Cast<NamedTypeSymbol>().AsImmutable();
            Assert.True(cciInterfaces.SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));
            context.Diagnostics.Verify();
        }
示例#37
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, null, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new Microsoft.CodeAnalysis.Emit.Context(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();
        }
示例#38
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, null, OutputKind.DynamicallyLinkedLibrary,
                GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new Microsoft.CodeAnalysis.Emit.Context(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();
        }
示例#39
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, null, OutputKind.DynamicallyLinkedLibrary,
               GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
            var context = new Microsoft.CodeAnalysis.Emit.Context(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();
        }