Пример #1
0
        /// <param name="sourceType">Type that already has custom modifiers.</param>
        /// <param name="destinationType">Same as <paramref name="sourceType"/>, but without custom modifiers.  May differ in object/dynamic.</param>
        /// <param name="refKind"><see cref="RefKind"/> of the parameter of which this is the type (or <see cref="RefKind.None"/> for a return type.</param>
        /// <param name="containingAssembly">The assembly containing the signature referring to the destination type.</param>
        /// <returns><paramref name="destinationType"/> with custom modifiers copied from <paramref name="sourceType"/>.</returns>
        internal static TypeSymbol CopyTypeCustomModifiers(TypeSymbol sourceType, TypeSymbol destinationType, RefKind refKind, AssemblySymbol containingAssembly)
        {
            Debug.Assert(sourceType.Equals(destinationType, ignoreCustomModifiersAndArraySizesAndLowerBounds: true, ignoreDynamic: true));

            if (sourceType.ContainsTuple())
            {
                // TODO(https://github.com/dotnet/roslyn/issues/12389):
                // Need to save/restore tupleness as well
                if (sourceType.IsTupleType)
                {
                    Debug.Assert(destinationType.IsTupleType);
                    return destinationType;
                }

                ImmutableArray<bool> flags = CSharpCompilation.DynamicTransformsEncoder.EncodeWithoutCustomModifierFlags(destinationType, refKind);
                TypeSymbol resultType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(sourceType, containingAssembly, refKind, flags);

                Debug.Assert(resultType.Equals(sourceType, ignoreCustomModifiersAndArraySizesAndLowerBounds: false, ignoreDynamic: true)); // Same custom modifiers as source type.
                return resultType;
            }
            else
            {
                // NOTE: overrides can differ by object/dynamic.  If they do, we'll need to tweak newType before
                // we can use it in place of this.Type.  We do so by computing the dynamic transform flags that
                // code gen uses and then passing them to the dynamic type decoder that metadata reading uses.
                ImmutableArray<bool> flags = CSharpCompilation.DynamicTransformsEncoder.EncodeWithoutCustomModifierFlags(destinationType, refKind);
                TypeSymbol resultType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(sourceType, containingAssembly, refKind, flags);

                Debug.Assert(resultType.Equals(sourceType, ignoreCustomModifiersAndArraySizesAndLowerBounds: false, ignoreDynamic: true)); // Same custom modifiers as source type.
                Debug.Assert(resultType.Equals(destinationType, ignoreCustomModifiersAndArraySizesAndLowerBounds: true, ignoreDynamic: false)); // Same object/dynamic as destination type.
                return resultType;
            }
        }
Пример #2
0
        /// <summary>
        /// Determine the effective base type, effective interface set, and set of type
        /// parameters (excluding cycles) from the type parameter constraints. Conflicts
        /// within the constraints and constraint types are returned as diagnostics.
        /// 'inherited' should be true if the type parameters are from an overridden
        /// generic method. In those cases, additional constraint checks are applied.
        /// </summary>
        public static TypeParameterBounds ResolveBounds(
            this TypeParameterSymbol typeParameter,
            AssemblySymbol corLibrary,
            ConsList<TypeParameterSymbol> inProgress,
            ImmutableArray<TypeSymbol> constraintTypes,
            bool inherited,
            CSharpCompilation currentCompilation,
            DiagnosticBag diagnostics)
        {
            var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance();
            ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null;
            var bounds = typeParameter.ResolveBounds(corLibrary, inProgress, constraintTypes, inherited, currentCompilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder);

            if (useSiteDiagnosticsBuilder != null)
            {
                diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder);
            }

            foreach (var pair in diagnosticsBuilder)
            {
                diagnostics.Add(new CSDiagnostic(pair.DiagnosticInfo, pair.TypeParameter.Locations[0]));
            }

            diagnosticsBuilder.Free();
            return bounds;
        }
        /// <summary>
        /// A helper method for AssemblyManager to set the system assembly, which provides primitive 
        /// types like Object, String, etc., think mscorlib.dll. 
        /// </summary>
        /// <param name="corLibrary"></param>
        internal void SetCorLibrary(
            AssemblySymbol corLibrary)
        {
            Contract.ThrowIfNull(referencedAssemblies);
            Contract.ThrowIfNull(referencedAssemblySymbols);

            if (corLibrary != null && !ReferenceEquals(corLibrary, this.ContainingAssembly))
            {
                bool corLibraryIsOk = false;

                foreach (var asm in referencedAssemblySymbols)
                {
                    if (object.ReferenceEquals(asm, corLibrary))
                    {
                        corLibraryIsOk = true;
                        break;
                    }
                }

                Contract.ThrowIfFalse(corLibraryIsOk);
            }

            System.Diagnostics.Debug.Assert(coreLibrary == null);
            coreLibrary = corLibrary;
        }
Пример #4
0
        /// <param name="sourceType">Type that already has custom modifiers.</param>
        /// <param name="destinationType">Same as <paramref name="sourceType"/>, but without custom modifiers.  May differ in object/dynamic.</param>
        /// <param name="refKind"><see cref="RefKind"/> of the parameter of which this is the type (or <see cref="RefKind.None"/> for a return type.</param>
        /// <param name="containingAssembly">The assembly containing the signature referring to the destination type.</param>
        /// <returns><paramref name="destinationType"/> with custom modifiers copied from <paramref name="sourceType"/>.</returns>
        internal static TypeSymbol CopyTypeCustomModifiers(TypeSymbol sourceType, TypeSymbol destinationType, RefKind refKind, AssemblySymbol containingAssembly)
        {
            Debug.Assert(sourceType.Equals(destinationType, TypeCompareKind.AllIgnoreOptions));

            // NOTE: overrides can differ by object/dynamic.  If they do, we'll need to tweak newType before
            // we can use it in place of this.Type.  We do so by computing the dynamic transform flags that
            // code gen uses and then passing them to the dynamic type decoder that metadata reading uses.
            ImmutableArray<bool> flags = CSharpCompilation.DynamicTransformsEncoder.EncodeWithoutCustomModifierFlags(destinationType, refKind);
            TypeSymbol typeWithDynamic = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(sourceType, containingAssembly, refKind, flags);

            TypeSymbol resultType;
            if (destinationType.ContainsTuple() && !sourceType.Equals(destinationType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamic))
            {
                // We also preserve tuple names, if present and different
                ImmutableArray<string> names = CSharpCompilation.TupleNamesEncoder.Encode(destinationType);
                resultType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeWithDynamic, containingAssembly, names);
            }
            else
            {
                resultType = typeWithDynamic;
            }

            Debug.Assert(resultType.Equals(sourceType, TypeCompareKind.IgnoreDynamicAndTupleNames)); // Same custom modifiers as source type.
            Debug.Assert(resultType.Equals(destinationType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); // Same object/dynamic and tuple names as destination type.
            return resultType;
        }
        private static TypeSymbol TransformTypeInternal(
            TypeSymbol metadataType,
            AssemblySymbol containingAssembly,
            int targetSymbolCustomModifierCount,
            RefKind targetSymbolRefKind,
            ImmutableArray<bool> dynamicTransformFlags,
            bool haveCustomModifierFlags)
        {
            Debug.Assert((object)metadataType != null);
            Debug.Assert((object)containingAssembly != null);
            Debug.Assert(!dynamicTransformFlags.IsDefault);

            if (dynamicTransformFlags.Length == 0)
            {
                return new UnsupportedMetadataTypeSymbol();
            }

            var decoder = new DynamicTypeDecoder(dynamicTransformFlags, haveCustomModifierFlags, containingAssembly);

            // Native compiler encodes bools (always false) for custom modifiers and parameter ref-kinds, if ref-kind is ref or out.
            if (decoder.HandleCustomModifiers(targetSymbolCustomModifierCount) && decoder.HandleParameterRefKind(targetSymbolRefKind))
            {
                TypeSymbol transformedType = decoder.TransformType(metadataType);

                if ((object)transformedType != null && decoder.index == dynamicTransformFlags.Length)
                {
                    return transformedType;
                }
            }

            // We ignore the dynamic transformation and return unchanged metadataType to match Dev11 behavior.
            return metadataType;
        }
Пример #6
0
 /// <summary>
 /// Checks if 'symbol' is accessible from within assembly 'within'.  
 /// </summary>
 public static bool IsSymbolAccessible(
     Symbol symbol,
     AssemblySymbol within,
     ref HashSet<DiagnosticInfo> useSiteDiagnostics)
 {
     bool failedThroughTypeCheck;
     return IsSymbolAccessibleCore(symbol, within, null, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteDiagnostics);
 }
        public UnifiedAssembly(AssemblySymbol targetAssembly, AssemblyIdentity originalReference)
        {
            Debug.Assert(originalReference != null);
            Debug.Assert(targetAssembly != null);

            this.OriginalReference = originalReference;
            this.TargetAssembly = targetAssembly;
        }
        /// <summary>
        /// A helper method for AssemblyManager to set assembly identities for assemblies 
        /// referenced by this module and corresponding AssemblySymbols.
        /// </summary>
        /// <param name="names"></param>
        /// <param name="symbols"></param>
        internal override void SetReferences(
            System.Reflection.AssemblyName[] names,
            AssemblySymbol[] symbols)
        {
            base.SetReferences(names, symbols);

            System.Diagnostics.Debug.Assert(coreLibrary == null);
            coreLibrary = null;
        }
 internal static TypeSymbol TransformTypeWithoutCustomModifierFlags(
     TypeSymbol type,
     AssemblySymbol containingAssembly,
     RefKind targetSymbolRefKind,
     ImmutableArray<bool> dynamicTransformFlags)
 {
     Debug.Assert(containingAssembly is SourceAssemblySymbol); // Doesn't happen during decoding.
     return TransformTypeInternal(type, containingAssembly, 0, targetSymbolRefKind, dynamicTransformFlags, haveCustomModifierFlags: false);
 }
        public MissingModuleSymbol(AssemblySymbol assembly, int ordinal)
        {
            Debug.Assert((object)assembly != null);
            Debug.Assert(ordinal >= -1);

            this.assembly = assembly;
            this.ordinal = ordinal;
            globalNamespace = new MissingNamespaceSymbol(this);
        }
 public NoPiaAmbiguousCanonicalTypeSymbol(
     AssemblySymbol embeddingAssembly,
     NamedTypeSymbol firstCandidate,
     NamedTypeSymbol secondCandidate)
 {
     _embeddingAssembly = embeddingAssembly;
     _firstCandidate = firstCandidate;
     _secondCandidate = secondCandidate;
 }
        private DynamicTypeDecoder(ImmutableArray<bool> dynamicTransformFlags, bool haveCustomModifierFlags, AssemblySymbol containingAssembly)
        {
            Debug.Assert(!dynamicTransformFlags.IsEmpty);
            Debug.Assert((object)containingAssembly != null);

            this.dynamicTransformFlags = dynamicTransformFlags;
            this.containingAssembly = containingAssembly;
            this.haveCustomModifierFlags = haveCustomModifierFlags;
            this.index = 0;
        }
Пример #13
0
        private DynamicTypeDecoder(ImmutableArray<bool> dynamicTransformFlags, bool haveCustomModifierFlags, bool checkLength, AssemblySymbol containingAssembly)
        {
            Debug.Assert(!dynamicTransformFlags.IsEmpty);
            Debug.Assert((object)containingAssembly != null);

            _dynamicTransformFlags = dynamicTransformFlags;
            _containingAssembly = containingAssembly;
            _haveCustomModifierFlags = haveCustomModifierFlags;
            _checkLength = checkLength;
            _index = 0;
        }
 public NoPiaMissingCanonicalTypeSymbol(
     AssemblySymbol embeddingAssembly,
     string fullTypeName,
     string guid,
     string scope,
     string identifier)
 {
     this.embeddingAssembly = embeddingAssembly;
     this.fullTypeName = fullTypeName;
     this.guid = guid;
     this.scope = scope;
     this.identifier = identifier;
 }
 public NoPiaMissingCanonicalTypeSymbol(
     AssemblySymbol embeddingAssembly,
     string fullTypeName,
     string guid,
     string scope,
     string identifier)
 {
     _embeddingAssembly = embeddingAssembly;
     _fullTypeName = fullTypeName;
     _guid = guid;
     _scope = scope;
     _identifier = identifier;
 }
Пример #16
0
        internal static LocalSymbol Create(
            TypeNameDecoder<PEModuleSymbol, TypeSymbol> typeNameDecoder,
            MethodSymbol containingMethod,
            AssemblySymbol sourceAssembly,
            Alias alias)
        {
            var typeName = alias.Type;
            Debug.Assert(typeName.Length > 0);

            var type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName);
            Debug.Assert((object)type != null);

            var dynamicFlagsInfo = alias.CustomTypeInfo.ToDynamicFlagsCustomTypeInfo();
            if (dynamicFlagsInfo.Any())
            {
                var flagsBuilder = ArrayBuilder<bool>.GetInstance();
                dynamicFlagsInfo.CopyTo(flagsBuilder);
                var dynamicType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(
                    type,
                    sourceAssembly,
                    RefKind.None,
                    flagsBuilder.ToImmutableAndFree(),
                    checkLength: false);
                Debug.Assert(dynamicType != null);
                Debug.Assert(dynamicType != type);
                type = dynamicType;
            }

            var name = alias.FullName;
            var displayName = alias.Name;
            switch (alias.Kind)
            {
                case DkmClrAliasKind.Exception:
                    return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName);
                case DkmClrAliasKind.StowedException:
                    return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName);
                case DkmClrAliasKind.ReturnValue:
                    {
                        int index;
                        PseudoVariableUtilities.TryParseReturnValueIndex(name, out index);
                        Debug.Assert(index >= 0);
                        return new ReturnValueLocalSymbol(containingMethod, name, displayName, type, index);
                    }
                case DkmClrAliasKind.ObjectId:
                    return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: false);
                case DkmClrAliasKind.Variable:
                    return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: true);
                default:
                    throw ExceptionUtilities.UnexpectedValue(alias.Kind);
            }
        }
Пример #17
0
        private void TestBaseTypeResolutionHelper1(AssemblySymbol assembly)
        {
            var module0 = assembly.Modules[0];

            var sys = module0.GlobalNamespace.GetMembers("System");
            var collections = ((NamespaceSymbol)sys[0]).GetMembers("Collections");
            var generic = ((NamespaceSymbol)collections[0]).GetMembers("Generic");
            var dictionary = ((NamespaceSymbol)generic[0]).GetMembers("Dictionary");
            var @base = ((NamedTypeSymbol)dictionary[0]).BaseType;

            AssertBaseType(@base, "System.Object");
            Assert.Null(@base.BaseType);

            var concurrent = ((NamespaceSymbol)collections[0]).GetMembers("Concurrent");

            var orderablePartitioners = ((NamespaceSymbol)concurrent[0]).GetMembers("OrderablePartitioner");
            NamedTypeSymbol orderablePartitioner = null;

            foreach (var p in orderablePartitioners)
            {
                var t = p as NamedTypeSymbol;

                if (t != null && t.Arity == 1)
                {
                    orderablePartitioner = t;
                    break;
                }
            }

            @base = orderablePartitioner.BaseType;

            AssertBaseType(@base, "System.Collections.Concurrent.Partitioner<TSource>");
            Assert.Same(((NamedTypeSymbol)@base).TypeArguments[0], orderablePartitioner.TypeParameters[0]);

            var partitioners = ((NamespaceSymbol)concurrent[0]).GetMembers("Partitioner");
            NamedTypeSymbol partitioner = null;

            foreach (var p in partitioners)
            {
                var t = p as NamedTypeSymbol;

                if (t != null && t.Arity == 0)
                {
                    partitioner = t;
                    break;
                }
            }

            Assert.NotNull(partitioner);
        }
Пример #18
0
        internal static LocalSymbol Create(
            TypeNameDecoder<PEModuleSymbol, TypeSymbol> typeNameDecoder,
            MethodSymbol containingMethod,
            AssemblySymbol sourceAssembly,
            Alias alias)
        {
            var typeName = alias.Type;
            Debug.Assert(typeName.Length > 0);

            var type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName);
            Debug.Assert((object)type != null);

            ReadOnlyCollection<byte> dynamicFlags;
            ReadOnlyCollection<string> tupleElementNames;
            CustomTypeInfo.Decode(alias.CustomTypeInfoId, alias.CustomTypeInfo, out dynamicFlags, out tupleElementNames);

            if (dynamicFlags != null)
            {
                type = DecodeDynamicTypes(type, sourceAssembly, dynamicFlags);
            }

            if (tupleElementNames != null)
            {
                type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, sourceAssembly, tupleElementNames.AsImmutable());
            }

            var name = alias.FullName;
            var displayName = alias.Name;
            switch (alias.Kind)
            {
                case DkmClrAliasKind.Exception:
                    return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName);
                case DkmClrAliasKind.StowedException:
                    return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName);
                case DkmClrAliasKind.ReturnValue:
                    {
                        int index;
                        PseudoVariableUtilities.TryParseReturnValueIndex(name, out index);
                        Debug.Assert(index >= 0);
                        return new ReturnValueLocalSymbol(containingMethod, name, displayName, type, index);
                    }
                case DkmClrAliasKind.ObjectId:
                    return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: false);
                case DkmClrAliasKind.Variable:
                    return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: true);
                default:
                    throw ExceptionUtilities.UnexpectedValue(alias.Kind);
            }
        }
Пример #19
0
        private void TestTypeForwarderHelper(AssemblySymbol[] assemblies)
        {
            var module1 = (PEModuleSymbol)assemblies[0].Modules[0];
            var module2 = (PEModuleSymbol)assemblies[1].Modules[0];

            var assembly2 = (MetadataOrSourceAssemblySymbol)assemblies[1];
            var assembly3 = (MetadataOrSourceAssemblySymbol)assemblies[2];

            var derived1 = module1.GlobalNamespace.GetTypeMembers("Derived").Single();
            var base1 = derived1.BaseType;
            BaseTypeResolution.AssertBaseType(base1, "Base");

            var derived4 = module1.GlobalNamespace.GetTypeMembers("GenericDerived").Single();
            var base4 = derived4.BaseType;
            BaseTypeResolution.AssertBaseType(base4, "GenericBase<K>");

            var derived6 = module1.GlobalNamespace.GetTypeMembers("GenericDerived1").Single();
            var base6 = derived6.BaseType;
            BaseTypeResolution.AssertBaseType(base6, "GenericBase<K>.NestedGenericBase<L>");

            Assert.Equal(assembly3, base1.ContainingAssembly);
            Assert.Equal(assembly3, base4.ContainingAssembly);
            Assert.Equal(assembly3, base6.ContainingAssembly);

            Assert.Equal(base1, module1.TypeRefHandleToTypeMap[(TypeReferenceHandle)module1.Module.GetBaseTypeOfTypeOrThrow(((PENamedTypeSymbol)derived1).Handle)]);
            Assert.True(module1.TypeRefHandleToTypeMap.Values.Contains((TypeSymbol)base4.OriginalDefinition));
            Assert.True(module1.TypeRefHandleToTypeMap.Values.Contains((TypeSymbol)base6.OriginalDefinition));

            Assert.Equal(base1, assembly2.CachedTypeByEmittedName(base1.ToTestDisplayString()));
            Assert.Equal(base4.OriginalDefinition, assembly2.CachedTypeByEmittedName("GenericBase`1"));
            Assert.Equal(2, assembly2.EmittedNameToTypeMapCount);

            Assert.Equal(base1, assembly3.CachedTypeByEmittedName(base1.ToTestDisplayString()));
            Assert.Equal(base4.OriginalDefinition, assembly3.CachedTypeByEmittedName("GenericBase`1"));
            Assert.Equal(2, assembly3.EmittedNameToTypeMapCount);

            var derived2 = module2.GlobalNamespace.GetTypeMembers("Derived").Single();
            var base2 = derived2.BaseType;
            BaseTypeResolution.AssertBaseType(base2, "Base");
            Assert.Same(base2, base1);

            var derived3 = module2.GlobalNamespace.GetTypeMembers("GenericDerived").Single();
            var base3 = derived3.BaseType;
            BaseTypeResolution.AssertBaseType(base3, "GenericBase<S>");

            var derived5 = module2.GlobalNamespace.GetTypeMembers("GenericDerived1").Single();
            var base5 = derived5.BaseType;
            BaseTypeResolution.AssertBaseType(base5, "GenericBase<S1>.NestedGenericBase<S2>");
        }
Пример #20
0
 internal static TypeSymbol TransformTypeWithoutCustomModifierFlags(
     TypeSymbol type,
     AssemblySymbol containingAssembly,
     RefKind targetSymbolRefKind,
     ImmutableArray<bool> dynamicTransformFlags,
     bool checkLength = true)
 {
     return TransformTypeInternal(
         type,
         containingAssembly,
         0,
         targetSymbolRefKind,
         dynamicTransformFlags,
         haveCustomModifierFlags: false,
         checkLength: checkLength);
 }
Пример #21
0
        /// <summary>
        /// Checks if 'symbol' is accessible from within assembly 'within'.  
        /// </summary>
        public static bool IsSymbolAccessible(
            Symbol symbol,
            AssemblySymbol within)
        {
            if ((object)symbol == null)
            {
                throw new ArgumentNullException(nameof(symbol));
            }

            if ((object)within == null)
            {
                throw new ArgumentNullException(nameof(within));
            }

            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
            return AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteDiagnostics);
        }
Пример #22
0
        /// <param name="sourceType">Type that already has custom modifiers.</param>
        /// <param name="destinationType">Same as <paramref name="sourceType"/>, but without custom modifiers.  May differ in object/dynamic.</param>
        /// <param name="refKind"><see cref="RefKind"/> of the parameter of which this is the type (or <see cref="RefKind.None"/> for a return type.</param>
        /// <param name="containingAssembly">The assembly containing the signature referring to the destination type.</param>
        /// <returns><paramref name="destinationType"/> with custom modifiers copied from <paramref name="sourceType"/>.</returns>
        internal static TypeSymbol CopyTypeCustomModifiers(TypeSymbol sourceType, TypeSymbol destinationType, RefKind refKind, AssemblySymbol containingAssembly)
        {
            Debug.Assert(sourceType.Equals(destinationType, ignoreCustomModifiers: true, ignoreDynamic: true));

            // NOTE: overrides can differ by object/dynamic.  If they do, we'll need to tweak newType before
            // we can use it in place of this.Type.  We do so by computing the dynamic transform flags that
            // code gen uses and then passing them to the dynamic type decoder that metadata reading uses.

            const int customModifierCount = 0;// Ignore custom modifiers, since we're not done copying them.
            ImmutableArray<bool> flags = CSharpCompilation.DynamicTransformsEncoder.Encode(destinationType, customModifierCount, refKind);
            TypeSymbol resultType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(sourceType, containingAssembly, refKind, flags);

            Debug.Assert(resultType.Equals(sourceType, ignoreCustomModifiers: false, ignoreDynamic: true)); // Same custom modifiers as source type.
            Debug.Assert(resultType.Equals(destinationType, ignoreCustomModifiers: true, ignoreDynamic: false)); // Same object/dynamic as destination type.

            return resultType;
        }
        internal Microsoft.Cci.IAssemblyReference Translate(AssemblySymbol assembly)
        {
            if (ReferenceEquals(sourceModule.ContainingAssembly, assembly))
            {
                return (Microsoft.Cci.IAssemblyReference)this;
            }

            object reference;

            if (SymbolsMap.TryGetValue(assembly, out reference))
            {
                return (Microsoft.Cci.IAssemblyReference)reference;
            }

            AssemblyReference asmRef = new AssemblyReference(assembly);

            SymbolsMap.Add(assembly, asmRef);
            SymbolsMap.Add(assembly.Modules[0], asmRef);

            return asmRef;
        }
Пример #24
0
        private void CommonTestInitialization()
        {
            _assembly = MetadataTestHelpers.GetSymbolsForReferences(
                TestReferences.SymbolsTests.Metadata.DynamicAttributeLib,
                TestReferences.NetFx.v4_0_30319.mscorlib)[0];

            _base0Class = _assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>("Base0");
            _base1Class = _assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>("Base1");
            _base2Class = _assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>("Base2");
            _derivedClass = _assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
            _outerClass = _assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>("Outer");
            _innerClass = _outerClass.GetTypeMember("Inner");
            _innerInnerClass = _innerClass.GetTypeMember("InnerInner");
            _outer2Class = _assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>("Outer2");
            _inner2Class = _outer2Class.GetTypeMember("Inner2");
            _innerInner2Class = _inner2Class.GetTypeMember("InnerInner2");
            _outer3Class = _assembly.Modules[0].GlobalNamespace.GetMember<NamedTypeSymbol>("Outer3");
            _inner3Class = _outer3Class.GetTypeMember("Inner3");

            _objectType = _assembly.CorLibrary.GetSpecialType(SpecialType.System_Object);
            _intType = _assembly.CorLibrary.GetSpecialType(SpecialType.System_Int32);
        }
Пример #25
0
        private DynamicTypeDecoder(ImmutableArray <bool> dynamicTransformFlags, bool haveCustomModifierFlags, AssemblySymbol containingAssembly)
        {
            Debug.Assert(!dynamicTransformFlags.IsEmpty);
            Debug.Assert((object)containingAssembly != null);

            this.dynamicTransformFlags   = dynamicTransformFlags;
            this.containingAssembly      = containingAssembly;
            this.haveCustomModifierFlags = haveCustomModifierFlags;
            this.index = 0;
        }
 public virtual void VisitAssembly(AssemblySymbol symbol)
 {
     DefaultVisit(symbol);
 }
Пример #27
0
        internal static LocalSymbol Create(
            TypeNameDecoder <PEModuleSymbol, TypeSymbol> typeNameDecoder,
            MethodSymbol containingMethod,
            AssemblySymbol sourceAssembly,
            Alias alias)
        {
            var typeName = alias.Type;

            Debug.Assert(typeName.Length > 0);

            var type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName);

            Debug.Assert((object)type != null);

            var dynamicFlagsInfo = alias.CustomTypeInfo.ToDynamicFlagsCustomTypeInfo();

            if (dynamicFlagsInfo.Any())
            {
                var flagsBuilder = ArrayBuilder <bool> .GetInstance();

                dynamicFlagsInfo.CopyTo(flagsBuilder);
                var dynamicType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(
                    type,
                    sourceAssembly,
                    RefKind.None,
                    flagsBuilder.ToImmutableAndFree(),
                    checkLength: false);
                Debug.Assert(dynamicType != null);
                Debug.Assert(dynamicType != type);
                type = dynamicType;
            }

            var name        = alias.FullName;
            var displayName = alias.Name;

            switch (alias.Kind)
            {
            case DkmClrAliasKind.Exception:
                return(new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName));

            case DkmClrAliasKind.StowedException:
                return(new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName));

            case DkmClrAliasKind.ReturnValue:
            {
                int index;
                PseudoVariableUtilities.TryParseReturnValueIndex(name, out index);
                Debug.Assert(index >= 0);
                return(new ReturnValueLocalSymbol(containingMethod, name, displayName, type, index));
            }

            case DkmClrAliasKind.ObjectId:
                return(new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: false));

            case DkmClrAliasKind.Variable:
                return(new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: true));

            default:
                throw ExceptionUtilities.UnexpectedValue(alias.Kind);
            }
        }
Пример #28
0
        public void AccessCheckApi1()
        {
            CSharpCompilation c              = CreateCompilation(@"
using System.Collections.Generic;
class A
{
    static private int priv;
    static public int pub;
    protected int prot;
    static private Goo unknowntype;
    
    private class K {}

    private K[] karray;
    private A[] aarray;
    private IEnumerable<K> kenum;
    private IEnumerable<A> aenum;
}

class B
{}

class ADerived: A
{}

class ADerived2: A
{}
");
            NamespaceSymbol   globalNS       = c.GlobalNamespace;
            AssemblySymbol    sourceAssem    = c.SourceModule.ContainingAssembly;
            AssemblySymbol    mscorlibAssem  = c.GetReferencedAssemblySymbol(c.ExternalReferences[0]);
            NamedTypeSymbol   classA         = globalNS.GetMembers("A").Single() as NamedTypeSymbol;
            NamedTypeSymbol   classADerived  = globalNS.GetMembers("ADerived").Single() as NamedTypeSymbol;
            NamedTypeSymbol   classADerived2 = globalNS.GetMembers("ADerived2").Single() as NamedTypeSymbol;
            NamedTypeSymbol   classB         = globalNS.GetMembers("B").Single() as NamedTypeSymbol;
            NamedTypeSymbol   classK         = classA.GetMembers("K").Single() as NamedTypeSymbol;
            FieldSymbol       privField      = classA.GetMembers("priv").Single() as FieldSymbol;
            FieldSymbol       pubField       = classA.GetMembers("pub").Single() as FieldSymbol;
            FieldSymbol       protField      = classA.GetMembers("prot").Single() as FieldSymbol;
            TypeSymbol        karrayType     = (classA.GetMembers("karray").Single() as FieldSymbol).Type;
            TypeSymbol        aarrayType     = (classA.GetMembers("aarray").Single() as FieldSymbol).Type;
            TypeSymbol        kenumType      = (classA.GetMembers("kenum").Single() as FieldSymbol).Type;
            TypeSymbol        aenumType      = (classA.GetMembers("aenum").Single() as FieldSymbol).Type;
            TypeSymbol        unknownType    = (classA.GetMembers("unknowntype").Single() as FieldSymbol).Type;
            var semanticModel = c.GetSemanticModel(c.SyntaxTrees[0]);

            Assert.True(Symbol.IsSymbolAccessible(classA, classB));
            Assert.True(Symbol.IsSymbolAccessible(pubField, classB));
            Assert.False(Symbol.IsSymbolAccessible(privField, classB));
            Assert.False(Symbol.IsSymbolAccessible(karrayType, classB));
            Assert.True(Symbol.IsSymbolAccessible(aarrayType, classB));
            Assert.False(Symbol.IsSymbolAccessible(kenumType, classB));
            Assert.True(Symbol.IsSymbolAccessible(aenumType, classB));
            Assert.True(Symbol.IsSymbolAccessible(unknownType, classB));
            Assert.True(Symbol.IsSymbolAccessible(globalNS, classB));
            Assert.True(Symbol.IsSymbolAccessible(protField, classA));
            Assert.True(Symbol.IsSymbolAccessible(protField, classA, classADerived));
            Assert.False(Symbol.IsSymbolAccessible(protField, classB));
            Assert.False(Symbol.IsSymbolAccessible(protField, classB, classADerived));
            Assert.True(Symbol.IsSymbolAccessible(protField, classA));
            Assert.True(Symbol.IsSymbolAccessible(protField, classADerived, classADerived));
            Assert.False(Symbol.IsSymbolAccessible(protField, classADerived, classADerived2));

            Assert.True(Symbol.IsSymbolAccessible(classA, sourceAssem));
            Assert.True(Symbol.IsSymbolAccessible(aarrayType, sourceAssem));
            Assert.False(Symbol.IsSymbolAccessible(karrayType, sourceAssem));
            Assert.False(Symbol.IsSymbolAccessible(classA, mscorlibAssem));
            Assert.True(Symbol.IsSymbolAccessible(unknownType, sourceAssem));
            Assert.True(Symbol.IsSymbolAccessible(mscorlibAssem, sourceAssem));
        }
Пример #29
0
 public IFileFacade CreateFileFacade(FileSymbol file, AssemblySymbol assembly) => this.backendHelper.CreateFileFacade(file, assembly);
Пример #30
0
        private DynamicTypeDecoder(ImmutableArray <bool> dynamicTransformFlags, bool haveCustomModifierFlags, bool checkLength, AssemblySymbol containingAssembly)
        {
            Debug.Assert(!dynamicTransformFlags.IsEmpty);
            Debug.Assert((object)containingAssembly != null);

            _dynamicTransformFlags   = dynamicTransformFlags;
            _containingAssembly      = containingAssembly;
            _haveCustomModifierFlags = haveCustomModifierFlags;
            _checkLength             = checkLength;
            _index = 0;
        }
Пример #31
0
 public TypeConversions(AssemblySymbol corLibrary)
     : this(corLibrary, currentRecursionDepth : 0)
 {
 }
Пример #32
0
 internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol other)
 {
     return(_underlyingAssembly.AreInternalsVisibleToThisAssembly(other));
 }
Пример #33
0
            private static bool IdentityEqualIgnoringVersionWildcard(AssemblySymbol left, AssemblySymbol right)
            {
                var leftIdentity  = left.Identity;
                var rightIdentity = right.Identity;

                return(AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) &&
                       (left.AssemblyVersionPattern ?? leftIdentity.Version).Equals(right.AssemblyVersionPattern ?? rightIdentity.Version) &&
                       AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity));
            }
Пример #34
0
        /// <summary>
        /// Perform a check whether the type or at least one of its generic arguments
        /// is defined in the specified assemblies. The check is performed recursively.
        /// </summary>
        public static bool IsOrClosedOverATypeFromAssemblies(TypeSymbol symbol, ImmutableArray <AssemblySymbol> assemblies)
        {
            switch (symbol.Kind)
            {
            case SymbolKind.TypeParameter:
                return(false);

            case SymbolKind.ArrayType:
                return(IsOrClosedOverATypeFromAssemblies(((ArrayTypeSymbol)symbol).ElementType.TypeSymbol, assemblies));

            case SymbolKind.PointerType:
                return(IsOrClosedOverATypeFromAssemblies(((PointerTypeSymbol)symbol).PointedAtType.TypeSymbol, assemblies));

            case SymbolKind.DynamicType:
                return(false);

            case SymbolKind.ErrorType:
                goto case SymbolKind.NamedType;

            case SymbolKind.NamedType:
                var            namedType          = (NamedTypeSymbol)symbol;
                AssemblySymbol containingAssembly = symbol.OriginalDefinition.ContainingAssembly;
                int            i;

                if ((object)containingAssembly != null)
                {
                    for (i = 0; i < assemblies.Length; i++)
                    {
                        if (ReferenceEquals(containingAssembly, assemblies[i]))
                        {
                            return(true);
                        }
                    }
                }

                do
                {
                    if (namedType.IsTupleType)
                    {
                        return(IsOrClosedOverATypeFromAssemblies(namedType.TupleUnderlyingType, assemblies));
                    }

                    var arguments = namedType.TypeArgumentsNoUseSiteDiagnostics;
                    int count     = arguments.Length;

                    for (i = 0; i < count; i++)
                    {
                        if (IsOrClosedOverATypeFromAssemblies(arguments[i].TypeSymbol, assemblies))
                        {
                            return(true);
                        }
                    }

                    namedType = namedType.ContainingType;
                }while ((object)namedType != null);

                return(false);

            default:
                throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
            }
        }
Пример #35
0
 private TypeConversions(AssemblySymbol corLibrary, int currentRecursionDepth)
     : base(corLibrary, currentRecursionDepth)
 {
 }
Пример #36
0
 private TypeConversions(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, TypeConversions otherNullabilityOpt)
     : base(corLibrary, currentRecursionDepth, includeNullability, otherNullabilityOpt)
 {
 }
Пример #37
0
 public TypeConversions(AssemblySymbol corLibrary, bool includeNullability = false)
     : this(corLibrary, currentRecursionDepth : 0, includeNullability : includeNullability, otherNullabilityOpt : null)
 {
 }
Пример #38
0
        internal static Symbol GetRuntimeMember(NamedTypeSymbol declaringType, ref MemberDescriptor descriptor, SignatureComparer <MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol accessWithinOpt)
        {
            Symbol     result = null;
            SymbolKind targetSymbolKind;
            MethodKind targetMethodKind = MethodKind.Ordinary;
            bool       isStatic         = (descriptor.Flags & MemberFlags.Static) != 0;

            switch (descriptor.Flags & MemberFlags.KindMask)
            {
            case MemberFlags.Constructor:
                targetSymbolKind = SymbolKind.Method;
                targetMethodKind = MethodKind.Constructor;
                //  static constructors are never called explicitly
                Debug.Assert(!isStatic);
                break;

            case MemberFlags.Method:
                targetSymbolKind = SymbolKind.Method;
                break;

            case MemberFlags.PropertyGet:
                targetSymbolKind = SymbolKind.Method;
                targetMethodKind = MethodKind.PropertyGet;
                break;

            case MemberFlags.Field:
                targetSymbolKind = SymbolKind.Field;
                break;

            case MemberFlags.Property:
                targetSymbolKind = SymbolKind.Property;
                break;

            default:
                throw ExceptionUtilities.UnexpectedValue(descriptor.Flags);
            }

            foreach (var member in declaringType.GetMembers(descriptor.Name))
            {
                Debug.Assert(member.Name.Equals(descriptor.Name));

                if (member.Kind != targetSymbolKind || member.IsStatic != isStatic ||
                    !(member.DeclaredAccessibility == Accessibility.Public || ((object)accessWithinOpt != null && Symbol.IsSymbolAccessible(member, accessWithinOpt))))
                {
                    continue;
                }

                switch (targetSymbolKind)
                {
                case SymbolKind.Method:
                {
                    MethodSymbol method     = (MethodSymbol)member;
                    MethodKind   methodKind = method.MethodKind;
                    // Treat user-defined conversions and operators as ordinary methods for the purpose
                    // of matching them here.
                    if (methodKind == MethodKind.Conversion || methodKind == MethodKind.UserDefinedOperator)
                    {
                        methodKind = MethodKind.Ordinary;
                    }

                    if (method.Arity != descriptor.Arity || methodKind != targetMethodKind ||
                        ((descriptor.Flags & MemberFlags.Virtual) != 0) != (method.IsVirtual || method.IsOverride || method.IsAbstract))
                    {
                        continue;
                    }

                    if (!comparer.MatchMethodSignature(method, descriptor.Signature))
                    {
                        continue;
                    }
                }

                break;

                case SymbolKind.Property:
                {
                    PropertySymbol property = (PropertySymbol)member;
                    if (((descriptor.Flags & MemberFlags.Virtual) != 0) != (property.IsVirtual || property.IsOverride || property.IsAbstract))
                    {
                        continue;
                    }

                    if (!comparer.MatchPropertySignature(property, descriptor.Signature))
                    {
                        continue;
                    }
                }

                break;

                case SymbolKind.Field:
                    if (!comparer.MatchFieldSignature((FieldSymbol)member, descriptor.Signature))
                    {
                        continue;
                    }

                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(targetSymbolKind);
                }

                // ambiguity
                if ((object)result != null)
                {
                    result = null;
                    break;
                }

                result = member;
            }
            return(result);
        }
Пример #39
0
 public virtual TResult VisitAssembly(AssemblySymbol symbol)
 {
     return(DefaultVisit(symbol));
 }
Пример #40
0
 public static bool GivesAccessTo(this AssemblySymbol first, AssemblySymbol second)
 {
     return(first.GetPublicSymbol().GivesAccessTo(second.GetPublicSymbol()));
 }
Пример #41
0
        private static void AssertNoIsByRefLikeAttributeExists(AssemblySymbol assembly)
        {
            var isByRefLikeAttributeTypeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute);

            Assert.Null(assembly.GetTypeByMetadataName(isByRefLikeAttributeTypeName));
        }
Пример #42
0
            internal void CreateSourceAssemblyForCompilation(PhpCompilation compilation)
            {
                if (compilation._lazyAssemblySymbol != null)
                {
                    return;
                }

                // TODO: lock

                Debug.Assert(_lazyExplicitReferences.IsDefault);
                Debug.Assert(_lazyCorLibrary == null);
                Debug.Assert(_lazyPhpCorLibrary == null);

                //
                var externalRefs = CorLibReferences.SelectMany(reference => compilation.Options.MetadataReferenceResolver.ResolveReference(reference, null, new MetadataReferenceProperties()))
                                   .Concat(compilation.ExternalReferences).AsImmutable();
                var assemblies = new List <AssemblySymbol>(externalRefs.Length);

                var referencesMap = new Dictionary <MetadataReference, IAssemblySymbol>();
                var metadataMap   = new Dictionary <IAssemblySymbol, MetadataReference>();
                var assembliesMap = new Dictionary <AssemblyIdentity, PEAssemblySymbol>();

                var refmodules = new List <PEModuleSymbol>();

                foreach (PortableExecutableReference pe in externalRefs)
                {
                    var symbol = PEAssemblySymbol.Create(pe);
                    if (symbol != null)
                    {
                        assemblies.Add(symbol);
                        referencesMap[pe]   = symbol;
                        metadataMap[symbol] = pe;

                        if (_lazyCorLibrary == null && symbol.IsCorLibrary)
                        {
                            _lazyCorLibrary = symbol;
                        }

                        if (_lazyPhpCorLibrary == null && symbol.IsPchpCorLibrary)
                        {
                            _lazyPhpCorLibrary = symbol;
                        }

                        // cache bound assembly symbol
                        _assembliesMap.Add(symbol.Identity, symbol);

                        // list of modules to initialize later
                        refmodules.AddRange(symbol.Modules.Cast <PEModuleSymbol>());
                    }
                }

                //
                _lazyExplicitReferences = externalRefs;
                _lazyImplicitReferences = ImmutableArray <MetadataReference> .Empty;
                _metadataMap            = metadataMap.ToImmutableDictionary();
                _referencesMap          = referencesMap.ToImmutableDictionary();

                //
                var assembly = new SourceAssemblySymbol(compilation, compilation.Options.ModuleName, compilation.Options.ModuleName);

                assembly.SetCorLibrary(_lazyCorLibrary);
                compilation._lazyAssemblySymbol = assembly;

                assembly.SourceModule.SetReferences(new ModuleReferences <AssemblySymbol>(
                                                        assemblies.Select(x => x.Identity).AsImmutable(),
                                                        assemblies.AsImmutable(),
                                                        ImmutableArray <UnifiedAssembly <AssemblySymbol> > .Empty), assembly);

                assemblies.ForEach(ass => ass.SetCorLibrary(_lazyCorLibrary));

                // recursively initialize references of referenced modules
                SetReferencesOfReferencedModules(compilation.Options.MetadataReferenceResolver, refmodules);

                // set cor types for this compilation
                if (_lazyPhpCorLibrary == null)
                {
                    throw new DllNotFoundException("pchpcor.dll not found");
                }
                if (_lazyCorLibrary == null)
                {
                    throw new DllNotFoundException("corlib not found");
                }
                compilation.CoreTypes.Update(_lazyPhpCorLibrary);
                compilation.CoreTypes.Update(_lazyCorLibrary);
            }
Пример #43
0
 public virtual TResult VisitAssembly(AssemblySymbol symbol, TArgument argument)
 {
     return(DefaultVisit(symbol, argument));
 }
Пример #44
0
 public virtual void VisitAssembly(AssemblySymbol symbol)
 {
     DefaultVisit(symbol);
 }
Пример #45
0
        internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol potentialGiverOfAccess)
        {
            IVTConclusion conclusion = MakeFinalIVTDetermination(potentialGiverOfAccess);

            return(conclusion == IVTConclusion.Match || conclusion == IVTConclusion.OneSignedOneNot);
        }
        private static string GetDebuggerDisplayString(AssemblySymbol assembly, int ordinal, int fieldCount)
        {
            NamedTypeSymbol anon;
            if (fieldCount == 0)
            {
                anon = assembly.GetTypeByMetadataName("<>f__AnonymousType0");
            }
            else
            {
                anon = assembly.GetTypeByMetadataName("<>f__AnonymousType" + ordinal + "`" + fieldCount);
            }

            var dd = anon.GetAttributes().Where(a => a.AttributeClass.Name == "DebuggerDisplayAttribute").Single();
            return (string)dd.ConstructorArguments.Single().Value;
        }
Пример #47
0
        private void TestTypeKindHelper(AssemblySymbol assembly)
        {
            var module0 = assembly.Modules[0];

            var system = (
                from n in module0.GlobalNamespace.GetMembers()
                where n.Name.Equals("System")
                select n
                )
                         .Cast <NamespaceSymbol>()
                         .Single();

            var obj = (
                from t in system.GetTypeMembers()
                where t.Name.Equals("Object")
                select t
                ).Single();

            Assert.Equal(TypeKind.Class, obj.TypeKind);

            var @enum = (
                from t in system.GetTypeMembers()
                where t.Name.Equals("Enum")
                select t
                ).Single();

            Assert.Equal(TypeKind.Class, @enum.TypeKind);

            var int32 = (
                from t in system.GetTypeMembers()
                where t.Name.Equals("Int32")
                select t
                ).Single();

            Assert.Equal(TypeKind.Struct, int32.TypeKind);

            var func = (
                from t in system.GetTypeMembers()
                where t.Name.Equals("Func") && t.Arity == 1
                select t
                ).Single();

            Assert.Equal(TypeKind.Delegate, func.TypeKind);

            var collections = (
                from n in system.GetMembers()
                where n.Name.Equals("Collections")
                select n
                )
                              .Cast <NamespaceSymbol>()
                              .Single();

            var ienumerable = (
                from t in collections.GetTypeMembers()
                where t.Name.Equals("IEnumerable")
                select t
                ).Single();

            Assert.Equal(TypeKind.Interface, ienumerable.TypeKind);
            Assert.Null(ienumerable.BaseType());

            var typeCode = (
                from t in system.GetTypeMembers()
                where t.Name.Equals("TypeCode")
                select t
                ).Single();

            Assert.Equal(TypeKind.Enum, typeCode.TypeKind);

            Assert.False(obj.IsAbstract);
            Assert.False(obj.IsSealed);
            Assert.False(obj.IsStatic);

            Assert.True(@enum.IsAbstract);
            Assert.False(@enum.IsSealed);
            Assert.False(@enum.IsStatic);

            Assert.False(func.IsAbstract);
            Assert.True(func.IsSealed);
            Assert.False(func.IsStatic);

            var console = system.GetTypeMembers("Console").Single();

            Assert.False(console.IsAbstract);
            Assert.False(console.IsSealed);
            Assert.True(console.IsStatic);
        }
Пример #48
0
 internal AssemblyReference(AssemblySymbol assemblySymbol, Func <AssemblySymbol, AssemblyIdentity> symbolMapper)
 {
     Debug.Assert((object)assemblySymbol != null);
     this.MetadataIdentity = (symbolMapper != null) ? symbolMapper(assemblySymbol) : assemblySymbol.Identity;
     this.targetAssembly   = assemblySymbol;
 }
            public Test01()
            {
                string source       = @"
using System.Diagnostics;

[assembly: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )]
[module: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )]


[DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )]
class TestClass
{
    [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )]
    public int testField;


    [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )]
    public int TestProperty
    {
        [return: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )]
        get
        {
            return testField;
        }
    }

    [return: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )]
    [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )]
    public T TestMethod<[DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] T>
        ([DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] T testParameter)
    {
        return testParameter;
    }
}";
                var    compilation1 = CSharpCompilation.Create("C1", new[] { Parse(source) }, new[] { OldMsCorLib }, TestOptions.ReleaseDll);

                c1 = new CSharpCompilationReference(compilation1);

                var c1Assembly = compilation1.Assembly;

                var compilation2 = CSharpCompilation.Create("C2", references: new MetadataReference[] { NewMsCorLib, c1 });

                c2 = new CSharpCompilationReference(compilation2);

                var c1AsmRef = compilation2.GetReferencedAssemblySymbol(c1);

                Assert.NotSame(c1Assembly, c1AsmRef);

                c1MscorLibAssemblyRef = compilation1.GetReferencedAssemblySymbol(OldMsCorLib);
                c2MscorlibAssemblyRef = compilation2.GetReferencedAssemblySymbol(NewMsCorLib);
                Assert.NotSame(c1MscorLibAssemblyRef, c2MscorlibAssemblyRef);

                oldMsCorLib_systemType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Type");
                newMsCorLib_systemType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Type");
                Assert.NotSame(oldMsCorLib_systemType, newMsCorLib_systemType);

                oldMsCorLib_debuggerTypeProxyAttributeType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute");
                newMsCorLib_debuggerTypeProxyAttributeType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute");
                Assert.NotSame(oldMsCorLib_debuggerTypeProxyAttributeType, newMsCorLib_debuggerTypeProxyAttributeType);

                oldMsCorLib_debuggerTypeProxyAttributeCtor = (MethodSymbol)oldMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor").Single(
                    m => ((MethodSymbol)m).ParameterCount == 1 && ((MethodSymbol)m).ParameterTypes[0] == oldMsCorLib_systemType);

                newMsCorLib_debuggerTypeProxyAttributeCtor = (MethodSymbol)newMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor").Single(
                    m => ((MethodSymbol)m).ParameterCount == 1 && ((MethodSymbol)m).ParameterTypes[0] == newMsCorLib_systemType);

                Assert.NotSame(oldMsCorLib_debuggerTypeProxyAttributeCtor, newMsCorLib_debuggerTypeProxyAttributeCtor);
            }
Пример #50
0
 private static TypeSymbol DecodeDynamicTypes(TypeSymbol type, AssemblySymbol sourceAssembly, ReadOnlyCollection<byte> bytes)
 {
     var builder = ArrayBuilder<bool>.GetInstance();
     DynamicFlagsCustomTypeInfo.CopyTo(bytes, builder);
     var dynamicType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(
         type,
         sourceAssembly,
         RefKind.None,
         builder.ToImmutableAndFree(),
         checkLength: false);
     Debug.Assert((object)dynamicType != null);
     Debug.Assert(dynamicType != type);
     return dynamicType;
 }
Пример #51
0
 internal static bool IsSymbolAccessibleConditional(
     Symbol symbol,
     AssemblySymbol within,
     ref HashSet<DiagnosticInfo> useSiteDiagnostics)
 {
     return AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteDiagnostics);
 }
Пример #52
0
            internal SourceAssemblySymbol CreateSourceAssemblyForCompilation(PhpCompilation compilation)
            {
                if (compilation._lazyAssemblySymbol != null)
                {
                    return(compilation._lazyAssemblySymbol);
                }

                var resolver   = compilation.Options.MetadataReferenceResolver;
                var moduleName = compilation.MakeSourceModuleName();

                var assemblies = new List <AssemblySymbol>();

                if (_lazyExplicitReferences.IsDefault)
                {
                    //
                    var externalRefs  = compilation.ExternalReferences;
                    var referencesMap = new Dictionary <MetadataReference, IAssemblySymbol>();
                    var metadataMap   = new Dictionary <IAssemblySymbol, MetadataReference>();
                    var assembliesMap = new Dictionary <AssemblyIdentity, PEAssemblySymbol>();
                    var observed      = new HashSet <AssemblyIdentity>();

                    foreach (PortableExecutableReference pe in externalRefs)
                    {
                        var peass = ((AssemblyMetadata)pe.GetMetadata()).GetAssembly();

                        if (!observed.Add(peass.Identity))
                        {
                            // already added reference identity, different metadata
                            referencesMap[pe] = _observedMetadata[peass.Identity];
                            Debug.Assert(referencesMap[pe] != null);
                            continue;
                        }

                        var symbol = _observedMetadata.TryGetOrDefault(peass.Identity) ?? PEAssemblySymbol.Create(pe, peass, isLinked: true);
                        if (symbol != null)
                        {
                            assemblies.Add(symbol);
                            referencesMap[pe]   = symbol;
                            metadataMap[symbol] = pe;

                            if (_lazyCorLibrary == null && symbol.IsCorLibrary)
                            {
                                _lazyCorLibrary = symbol;
                            }

                            if (_lazyPhpCorLibrary == null && symbol.IsPchpCorLibrary)
                            {
                                _lazyPhpCorLibrary = symbol;
                            }

                            // cache bound assembly symbol
                            _observedMetadata[symbol.Identity] = symbol;
                        }
                        else
                        {
                            _diagnostics.Add(Location.None, Errors.ErrorCode.ERR_MetadataFileNotFound, peass.Identity);
                        }
                    }

                    // list of modules to initialize later
                    var refmodules = assemblies.SelectMany(symbol => symbol.Modules.Cast <PEModuleSymbol>()).ToList();

                    //
                    _lazyExplicitReferences = externalRefs;
                    _lazyImplicitReferences = ImmutableArray <MetadataReference> .Empty;
                    _metadataMap            = metadataMap.ToImmutableDictionary();
                    _referencesMap          = referencesMap.ToImmutableDictionary();

                    //
                    assemblies.ForEach(ass => ass.SetCorLibrary(_lazyCorLibrary));

                    // recursively initialize references of referenced modules
                    SetReferencesOfReferencedModules(resolver, refmodules);
                }
                else
                {
                    foreach (PortableExecutableReference pe in _lazyExplicitReferences)
                    {
                        var ass = (AssemblySymbol)_referencesMap[pe];
                        Debug.Assert(ass != null);
                        assemblies.Add(ass);
                    }
                }

                //
                var assembly = new SourceAssemblySymbol(compilation, this.SimpleAssemblyName, moduleName);

                assembly.SetCorLibrary(_lazyCorLibrary);
                assembly.SourceModule.SetReferences(new ModuleReferences <AssemblySymbol>(
                                                        assemblies.Select(x => x.Identity).AsImmutable(),
                                                        assemblies.AsImmutable(),
                                                        ImmutableArray <UnifiedAssembly <AssemblySymbol> > .Empty), assembly);

                // set cor types for this compilation
                if (_lazyPhpCorLibrary == null)
                {
                    _diagnostics.Add(Location.None, Errors.ErrorCode.ERR_MetadataFileNotFound, "Peachpie.Runtime.dll");
                    throw new DllNotFoundException("Peachpie.Runtime not found");
                }
                if (_lazyCorLibrary == null)
                {
                    throw new DllNotFoundException("A corlib not found");
                }

                compilation.CoreTypes.Update(_lazyPhpCorLibrary);
                compilation.CoreTypes.Update(_lazyCorLibrary);

                //
                return(assembly);
            }
Пример #53
0
        public static bool RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(this AssemblySymbol @this, AssemblySymbol that)
        {
            var thisPEAssembly = @this as Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol;

            if (thisPEAssembly != null)
            {
                var thatPEAssembly = that as Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol;

                return(thatPEAssembly != null &&
                       ReferenceEquals(thisPEAssembly.Assembly, thatPEAssembly.Assembly) && @this.HasUnresolvedReferencesByComparisonTo(that));
            }

            var thisRetargetingAssembly = @this as Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingAssemblySymbol;

            if (thisRetargetingAssembly != null)
            {
                var thatRetargetingAssembly = that as Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingAssemblySymbol;

                if (thatRetargetingAssembly != null)
                {
                    return(ReferenceEquals(thisRetargetingAssembly.UnderlyingAssembly, thatRetargetingAssembly.UnderlyingAssembly) &&
                           @this.HasUnresolvedReferencesByComparisonTo(that));
                }

                var thatSourceAssembly = that as SourceAssemblySymbol;

                return(thatSourceAssembly != null && ReferenceEquals(thisRetargetingAssembly.UnderlyingAssembly, thatSourceAssembly) &&
                       @this.HasUnresolvedReferencesByComparisonTo(that));
            }

            return(false);
        }
Пример #54
0
 internal AssemblyReference(AssemblySymbol assemblySymbol)
 {
     Debug.Assert((object)assemblySymbol != null);
     _targetAssembly = assemblySymbol;
 }
Пример #55
0
        // Is a top-level type with accessibility "declaredAccessibility" inside assembly "assembly"
        // accessible from "within", which must be a named type of an assembly.
        private static bool IsNonNestedTypeAccessible(
            AssemblySymbol assembly,
            Accessibility declaredAccessibility,
            Symbol within)
        {
            Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
            Debug.Assert((object)assembly != null);

            switch (declaredAccessibility)
            {
                case Accessibility.NotApplicable:
                case Accessibility.Public:
                    // Public symbols are always accessible from any context
                    return true;

                case Accessibility.Private:
                case Accessibility.Protected:
                case Accessibility.ProtectedAndInternal:
                    // Shouldn't happen except in error cases.
                    return false;

                case Accessibility.Internal:
                case Accessibility.ProtectedOrInternal:

                    // within is typically a type
                    var withinType = within as NamedTypeSymbol;
                    var withinAssembly = (object)withinType != null ? withinType.ContainingAssembly : (AssemblySymbol)within;

                    // An internal type is accessible if we're in the same assembly or we have
                    // friend access to the assembly it was defined in.
                    return (object)withinAssembly == (object)assembly || withinAssembly.HasInternalAccessTo(assembly);

                default:
                    throw ExceptionUtilities.UnexpectedValue(declaredAccessibility);
            }
        }
Пример #56
0
 public static AssemblySymbol[] BoundReferences(this AssemblySymbol @this)
 {
     return((from m in @this.Modules
             from @ref in m.GetReferencedAssemblySymbols()
             select @ref).ToArray());
 }
Пример #57
0
        // Does the assembly has internal accessibility to "toAssembly"?
        internal static bool HasInternalAccessTo(this AssemblySymbol assembly, AssemblySymbol toAssembly)
        {
            if (Equals(assembly, toAssembly))
            {
                return true;
            }

            if (assembly.AreInternalsVisibleToThisAssembly(toAssembly))
            {
                return true;
            }

            // all interactive assemblies are friends of each other:
            if (assembly.IsInteractive && toAssembly.IsInteractive)
            {
                return true;
            }

            return false;
        }
Пример #58
0
        public static bool HasUnresolvedReferencesByComparisonTo(this AssemblySymbol @this, AssemblySymbol that)
        {
            var thisRefs = @this.BoundReferences();
            var thatRefs = that.BoundReferences();

            for (int i = 0; i < Math.Max(thisRefs.Length, thatRefs.Length); i++)
            {
                if (thisRefs[i].IsMissing && !thatRefs[i].IsMissing)
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #59
0
        /// <summary>
        /// Find canonical type for NoPia embedded type.
        /// </summary>
        /// <returns>
        /// Symbol for the canonical type or an ErrorTypeSymbol. Never returns null.
        /// </returns>
        internal static NamedTypeSymbol SubstituteNoPiaLocalType(
            ref MetadataTypeName name,
            bool isInterface,
            TypeSymbol baseType,
            string interfaceGuid,
            string scope,
            string identifier,
            AssemblySymbol referringAssembly)
        {
            NamedTypeSymbol result = null;

            Guid interfaceGuidValue     = new Guid();
            bool haveInterfaceGuidValue = false;
            Guid scopeGuidValue         = new Guid();
            bool haveScopeGuidValue     = false;

            if (isInterface && interfaceGuid != null)
            {
                haveInterfaceGuidValue = Guid.TryParse(interfaceGuid, out interfaceGuidValue);

                if (haveInterfaceGuidValue)
                {
                    // To have consistent errors.
                    scope      = null;
                    identifier = null;
                }
            }

            if (scope != null)
            {
                haveScopeGuidValue = Guid.TryParse(scope, out scopeGuidValue);
            }

            foreach (AssemblySymbol assembly in referringAssembly.GetNoPiaResolutionAssemblies())
            {
                Debug.Assert((object)assembly != null);
                if (ReferenceEquals(assembly, referringAssembly))
                {
                    continue;
                }

                NamedTypeSymbol candidate = assembly.LookupTopLevelMetadataType(ref name, digThroughForwardedTypes: false);
                Debug.Assert(!candidate.IsGenericType);

                // Ignore type forwarders, error symbols and non-public types
                if (candidate.Kind == SymbolKind.ErrorType ||
                    !ReferenceEquals(candidate.ContainingAssembly, assembly) ||
                    candidate.DeclaredAccessibility != Accessibility.Public)
                {
                    continue;
                }

                // Ignore NoPia local types.
                // If candidate is coming from metadata, we don't need to do any special check,
                // because we do not create symbols for local types. However, local types defined in source
                // is another story. However, if compilation explicitly defines a local type, it should be
                // represented by a retargeting assembly, which is supposed to hide the local type.
                Debug.Assert(!(assembly is SourceAssemblySymbol) || !((SourceAssemblySymbol)assembly).SourceModule.MightContainNoPiaLocalTypes());

                string candidateGuid;
                bool   haveCandidateGuidValue = false;
                Guid   candidateGuidValue     = new Guid();

                // The type must be of the same kind (interface, struct, delegate or enum).
                switch (candidate.TypeKind)
                {
                case TypeKind.Interface:
                    if (!isInterface)
                    {
                        continue;
                    }

                    // Get candidate's Guid
                    if (candidate.GetGuidString(out candidateGuid) && candidateGuid != null)
                    {
                        haveCandidateGuidValue = Guid.TryParse(candidateGuid, out candidateGuidValue);
                    }

                    break;

                case TypeKind.Delegate:
                case TypeKind.Enum:
                case TypeKind.Struct:

                    if (isInterface)
                    {
                        continue;
                    }

                    // Let's use a trick. To make sure the kind is the same, make sure
                    // base type is the same.
                    SpecialType baseSpecialType = (candidate.BaseTypeNoUseSiteDiagnostics?.SpecialType).GetValueOrDefault();
                    if (baseSpecialType == SpecialType.None || baseSpecialType != (baseType?.SpecialType).GetValueOrDefault())
                    {
                        continue;
                    }

                    break;

                default:
                    continue;
                }

                if (haveInterfaceGuidValue || haveCandidateGuidValue)
                {
                    if (!haveInterfaceGuidValue || !haveCandidateGuidValue ||
                        candidateGuidValue != interfaceGuidValue)
                    {
                        continue;
                    }
                }
                else
                {
                    if (!haveScopeGuidValue || identifier == null || !identifier.Equals(name.FullName))
                    {
                        continue;
                    }

                    // Scope guid must match candidate's assembly guid.
                    haveCandidateGuidValue = false;
                    if (assembly.GetGuidString(out candidateGuid) && candidateGuid != null)
                    {
                        haveCandidateGuidValue = Guid.TryParse(candidateGuid, out candidateGuidValue);
                    }

                    if (!haveCandidateGuidValue || scopeGuidValue != candidateGuidValue)
                    {
                        continue;
                    }
                }

                // OK. It looks like we found canonical type definition.
                if ((object)result != null)
                {
                    // Ambiguity
                    result = new NoPiaAmbiguousCanonicalTypeSymbol(referringAssembly, result, candidate);
                    break;
                }

                result = candidate;
            }

            if ((object)result == null)
            {
                result = new NoPiaMissingCanonicalTypeSymbol(
                    referringAssembly,
                    name.FullName,
                    interfaceGuid,
                    scope,
                    identifier);
            }

            return(result);
        }
Пример #60
0
        private void TestMissingTypeReferencesHelper1(AssemblySymbol assembly)
        {
            var module0 = assembly.Modules[0];

            var localTC10 = module0.GlobalNamespace.GetTypeMembers("TC10").Single();

            MissingMetadataTypeSymbol @base = (MissingMetadataTypeSymbol)localTC10.BaseType;

            Assert.Equal(SymbolKind.ErrorType, @base.Kind);
            Assert.False(@base.IsNamespace);
            Assert.True(@base.IsType);
            Assert.Equal("Object", @base.Name);
            Assert.Equal("System", @base.ContainingSymbol.Name);
            Assert.Equal(0, @base.Arity);
            Assert.Equal("System.Object[missing]", @base.ToTestDisplayString());
            Assert.NotNull(@base.ContainingAssembly);
            Assert.NotNull(@base.ContainingNamespace);
            Assert.NotNull(@base.ContainingSymbol);
            Assert.True(@base.ContainingAssembly.IsMissing);
            Assert.Equal("mscorlib", @base.ContainingAssembly.Identity.Name);

            var localTC8    = module0.GlobalNamespace.GetTypeMembers("TC8").Single();
            var genericBase = (ErrorTypeSymbol)localTC8.BaseType;

            Assert.Equal("C1<System.Type[missing]>[missing]", genericBase.ToTestDisplayString());

            @base = (MissingMetadataTypeSymbol)genericBase.ConstructedFrom;
            Assert.Equal(SymbolKind.ErrorType, @base.Kind);
            Assert.False(@base.IsNamespace);
            Assert.True(@base.IsType);
            Assert.Equal("C1", @base.Name);
            Assert.Equal(1, @base.Arity);
            Assert.Equal("C1<>[missing]", @base.ToTestDisplayString());
            Assert.NotNull(@base.ContainingAssembly);
            Assert.NotNull(@base.ContainingNamespace);
            Assert.NotNull(@base.ContainingSymbol);
            Assert.True(@base.ContainingAssembly.IsMissing);
            Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name);

            var localTC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single();

            genericBase = (ErrorTypeSymbol)localTC7.BaseType;
            @base       = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;

            Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<TC7_T2>[missing]", genericBase.ToTestDisplayString());
            Assert.True(genericBase.ContainingAssembly.IsMissing);
            Assert.True(@base.ContainingAssembly.IsMissing);
            Assert.Equal(@base.GetUseSiteDiagnostic().ToString(), genericBase.GetUseSiteDiagnostic().ToString());
            Assert.Equal(@base.ErrorInfo.ToString(), genericBase.ErrorInfo.ToString());

            var constructedFrom = genericBase.ConstructedFrom;

            Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<>[missing]", constructedFrom.ToTestDisplayString());

            Assert.Same(constructedFrom, constructedFrom.Construct(constructedFrom.TypeParameters.ToArray()));
            Assert.Equal(genericBase, constructedFrom.Construct(genericBase.TypeArguments));

            genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol;
            Assert.Equal("C1<TC7_T1>[missing].C3[missing]", genericBase.ToTestDisplayString());
            Assert.Same(genericBase, genericBase.ConstructedFrom);

            genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol;
            Assert.Equal("C1<TC7_T1>[missing]", genericBase.ToTestDisplayString());
            Assert.Same(genericBase.OriginalDefinition, genericBase.ConstructedFrom);
            Assert.Equal("C1<>[missing]", genericBase.OriginalDefinition.ToTestDisplayString());

            Assert.Equal(SymbolKind.ErrorType, @base.Kind);
            Assert.False(@base.IsNamespace);
            Assert.True(@base.IsType);
            Assert.Equal("C4", @base.Name);
            Assert.Equal(1, @base.Arity);
            Assert.Equal("C1<>[missing].C3[missing].C4<>[missing]", @base.ToTestDisplayString());
            Assert.NotNull(@base.ContainingAssembly);
            Assert.NotNull(@base.ContainingNamespace);
            Assert.NotNull(@base.ContainingSymbol);
            Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name);

            Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.Kind);
            Assert.NotNull(@base.ContainingSymbol.ContainingAssembly);
            Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingAssembly);

            Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.ContainingSymbol.Kind);
            Assert.NotNull(@base.ContainingSymbol.ContainingSymbol.ContainingAssembly);
            Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingSymbol.ContainingAssembly);
        }