示例#1
0
        // the function returns true if the given type reference depends in a type parameter
        // not necessarily the type must be declared as class Type<T>
        // it could be nested and implicitly depend on a generic parameter
        // it could inherit a generic parameter
        // there are some situations that can only be resolved if the definition is present
        private static bool IsParametericType(ITypeReference typeReference)
        {
            if (typeReference is IGenericTypeInstanceReference)
            {
                return(true);
            }

            INestedTypeReference nestedType = typeReference as INestedTypeReference;

            if (nestedType != null && !(nestedType is Dummy))
            {
                // check Inner example in TestAxiomsGenerics2
                // it is a nested type reference, and also a INamedTypeReference but GenericParameterCount is zero and DoesNotInheritGenericParameters is true
                var res = !nestedType.ResolvedType.DoesNotInheritGenericParameters; //|| IsParametericType(nestedType.ResolvedType.BaseClasses.First());

                return(res);
            }

            INamedTypeReference namedType = typeReference as INamedTypeReference;

            if (namedType != null)
            {
                return(namedType.GenericParameterCount > 0);
            }

            return(false);
        }
示例#2
0
            public bool AddTypeReference(INamedTypeReference type)
            {
                // TODO: Optionally add all members for interfaces, and add all abstract members for abstract classes
                INamedTypeDefinition typeDef = Util.ResolveTypeThrowing(type);

                IAssembly assembly = TypeHelper.GetDefiningUnit(typeDef) as IAssembly;
                AddAssemblyReference(assembly);

                if (!TypesClosure.ContainsKey(typeDef.InternedKey))
                {
                    TypesClosure.Add(typeDef.InternedKey, typeDef);

                    _workList.Enqueue(typeDef);

                    if (Util.IsDelegateType(typeDef))
                    {
                        foreach (ITypeDefinitionMember member in typeDef.Members)
                        {
                            AddMemberReference(member);
                        }
                    }

                    return true;
                }

                return false;
            }
示例#3
0
        private static string GetEscapedMetadataName(INamedTypeReference namedType)
        {
            var           pooled      = PooledStringBuilder.GetInstance();
            StringBuilder mangledName = pooled.Builder;

            const string needsEscaping = "\\[]*.+,& ";

            if (namedType.AssociatedFileIdentifier is string fileIdentifier)
            {
                Debug.Assert(needsEscaping.All(c => !fileIdentifier.Contains(c)));
                mangledName.Append(fileIdentifier);
            }

            foreach (var ch in namedType.Name)
            {
                if (needsEscaping.IndexOf(ch) >= 0)
                {
                    mangledName.Append('\\');
                }

                mangledName.Append(ch);
            }

            if (namedType.MangleName && namedType.GenericParameterCount > 0)
            {
                mangledName.Append(MetadataHelpers.GetAritySuffix(namedType.GenericParameterCount));
            }

            return(pooled.ToStringAndFree());
        }
示例#4
0
            public bool AddTypeReference(INamedTypeReference type)
            {
                // TODO: Optionally add all members for interfaces, and add all abstract members for abstract classes
                INamedTypeDefinition typeDef = Util.ResolveTypeThrowing(type);

                IAssembly assembly = TypeHelper.GetDefiningUnit(typeDef) as IAssembly;

                AddAssemblyReference(assembly);

                if (!TypesClosure.ContainsKey(typeDef.InternedKey))
                {
                    TypesClosure.Add(typeDef.InternedKey, typeDef);

                    _workList.Enqueue(typeDef);

                    if (Util.IsDelegateType(typeDef))
                    {
                        foreach (ITypeDefinitionMember member in typeDef.Members)
                        {
                            AddMemberReference(member);
                        }
                    }

                    return(true);
                }

                return(false);
            }
示例#5
0
 internal TypeInferencer(INamedTypeReference containingType, IMetadataHost host) {
   Contract.Requires(containingType != null);
   Contract.Requires(host != null);
   this.containingType = containingType;
   this.host = host;
   this.platformType = containingType.PlatformType;
 }
示例#6
0
 public static IGenericTypeInstanceReference MakeGenericType(
     this INamedTypeReference genericType,
     IInternFactory internFactory,
     params ITypeReference[] genericArguments
     )
 {
     return(genericType.MakeGenericType(internFactory, genericArguments as IEnumerable <ITypeReference>));
 }
示例#7
0
 internal TypeInferencer(INamedTypeReference containingType, IMetadataHost host)
 {
     Contract.Requires(containingType != null);
     Contract.Requires(host != null);
     this.containingType = containingType;
     this.host           = host;
     this.platformType   = containingType.PlatformType;
 }
 public override void Visit(INamedTypeReference namedTypeReference)
 {
     if (Process(namedTypeReference))
     {
         visitor.Visit(namedTypeReference);
     }
     base.Visit(namedTypeReference);
 }
            public override bool Matches(ITypeReference typeReference)
            {
                INamedTypeReference named = typeReference as INamedTypeReference;

                return(named != null &&
                       !named.Name.Value.StartsWith("<") &&
                       !named.Name.Value.Contains("="));
            }
示例#10
0
        public static string GetMangledName(INamedTypeReference namedType)
        {
            string unmangledName = namedType.Name;

            return(namedType.MangleName
                                ? MetadataHelpers.ComposeAritySuffixedMetadataName(unmangledName, namedType.GenericParameterCount)
                                : unmangledName);
        }
示例#11
0
 /// <summary>
 /// This is "ugly" but I don't know how to query a type by name
 /// Inspired in Zvonimir code
 /// </summary>
 /// <param name="host"></param>
 public static void InitializeScopeTypes(IMetadataHost host, IAssembly scopeRuntime)
 {
     foreach (var type in scopeRuntime.GetAllTypes())
     {
         if (type.GetFullName() == "ScopeRuntime.Reducer")
         {
             Reducer = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.Processor")
         {
             Processor = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.Producer")
         {
             Producer = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.Row")
         {
             Row = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.RowSet")
         {
             RowSet = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.RowList")
         {
             RowList = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.ColumnData")
         {
             ColumnData = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.ColumnData<T>")
         {
             ColumnData_Generic = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.Schema")
         {
             Schema = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.Combiner")
         {
             Combiner = type;
         }
         else if (type.GetFullName() == "ScopeRuntime.ScopeMap<K, V>")
         {
             ScopeMap = type;
         }
         if (type.ContainingNamespace() == "ScopeRuntime")
         {
             scopeTypes.Add(type);
         }
     }
 }
示例#12
0
 public static IGenericTypeInstanceReference MakeGenericType(
     this INamedTypeReference genericType,
     IInternFactory internFactory,
     IEnumerable <ITypeReference> genericArguments
     )
 {
     return(new Microsoft.Cci.Immutable.GenericTypeInstanceReference(
                genericType,
                genericArguments,
                internFactory
                ));
 }
示例#13
0
        public static List <ITypeDefinitionMember> FindRelatedExternalMembers(ITypeDefinitionMember member, CanIncludeCheck canInclude)
        {
            List <ITypeDefinitionMember>      relatedMembers     = new List <ITypeDefinitionMember>();
            Dictionary <uint, ITypeReference> participatingTypes = new Dictionary <uint, ITypeReference>();

            ITypeDefinition currentType = member.ContainingTypeDefinition;

            do
            {
                //
                // add the type
                //
                if (!canInclude(Util.CanonicalizeTypeReference(currentType)))
                {
                    participatingTypes.Add(currentType.InternedKey, currentType);
                }

                //
                // add any interfaces it implements that are part of the closure
                //

                foreach (ITypeReference iface in currentType.Interfaces)
                {
                    INamedTypeReference ifaceTemplate = Util.CanonicalizeTypeReference(iface);
                    // check the closure against the template type, but add
                    // the specialized type to participatingTypes so that
                    // argument matching works
                    if (!canInclude(ifaceTemplate) &&
                        !participatingTypes.ContainsKey(iface.InternedKey))
                    {
                        // Should we add ifaceTemplate or iface?
                        participatingTypes.Add(iface.InternedKey, iface);
                    }
                }

                //
                // go up to the base type
                //
                currentType = TypeHelper.BaseClass(currentType);
            }while (currentType != null);

            foreach (ITypeReference type in participatingTypes.Values)
            {
                ITypeDefinitionMember relatedMember = FindRelatedMember(type, member);
                if (null != relatedMember)
                {
                    relatedMembers.Add(relatedMember);
                }
            }

            return(relatedMembers);
        }
示例#14
0
        public override void Visit(ITypeMemberReference member)
        {
            // The member can resolve to an external assembly, so we need to check whether we can include the external assembly.
            INamedTypeReference containingType = Util.CanonicalizeType(Util.CanonicalizeMemberReference(member).ContainingType);

            if (m_implModel.CanInclude(containingType))
            {
                AddTypeReference(containingType);
                if (member != null)
                {
                    AddMemberReference(Util.CanonicalizeMember(member));
                    return;
                }
            }
        }
示例#15
0
        public override void AddTypeReference(INamedTypeReference type)
        {
            INamedTypeDefinition typeDef = Util.CanonicalizeType(type);

            // For enums, we want to include all their values.
            // TODO: Should this be optional?
            if (typeDef.IsEnum)
            {
                foreach (ITypeDefinitionMember member in typeDef.Members)
                {
                    AddMemberReference(member);
                }
            }

            base.AddTypeReference(type);
        }
        public override void AddTypeReference(INamedTypeReference type)
        {
            INamedTypeDefinition typeDef = Util.CanonicalizeType(type);

            // For enums, we want to include all their values.
            // TODO: Should this be optional?
            if (typeDef.IsEnum)
            {
                foreach (ITypeDefinitionMember member in typeDef.Members)
                {
                    AddMemberReference(member);
                }
            }

            base.AddTypeReference(type);
        }
示例#17
0
        public static INamedTypeDefinition ResolveTypeThrowing(INamedTypeReference typeRef)
        {
            INamedTypeDefinition result = typeRef.ResolvedType;
            if (result == Dummy.Type ||
                result == Dummy.NamespaceTypeDefinition ||
                result == Dummy.NestedType)
            {
                throw new Exception(String.Format("Cannot resolve type '{0}'. Are all dependent assemblies loaded?", typeRef.ToString()));
            }
            if (result == Dummy.GenericTypeParameter)
            {
                throw new InvalidOperationException("Why is a generic parameter being resolved?");
            }

            Debug.Assert(!result.GetType().Name.Contains("Dummy"));
            return result;
        }
示例#18
0
        public static INamedTypeDefinition ResolveTypeThrowing(INamedTypeReference typeRef)
        {
            INamedTypeDefinition result = typeRef.ResolvedType;

            if (result == Dummy.Type ||
                result == Dummy.NamespaceTypeDefinition ||
                result == Dummy.NestedType)
            {
                throw new Exception(String.Format("Cannot resolve type '{0}'. Are all dependent assemblies loaded?", typeRef.ToString()));
            }
            if (result == Dummy.GenericTypeParameter)
            {
                throw new InvalidOperationException("Why is a generic parameter being resolved?");
            }

            Debug.Assert(!result.GetType().Name.Contains("Dummy"));
            return(result);
        }
示例#19
0
        /// <summary>
        /// Caching GenericTypeInstanceRefernece objects based on interned key, avoiding GenericTypeInstance.InitializeIfNecessary expense
        /// </summary>
        public IGenericTypeInstanceReference GetOrMakeGenericTypeInstanceReference(INamedTypeReference genericTypeReference, IEnumerable <ITypeReference> genericArguments)
        {
            InternFactory factory = m_factory as InternFactory;

            if (factory != null && !factory.InternKeysAreReliablyUnique)
            {
                return(new Microsoft.Cci.Immutable.GenericTypeInstanceReference(genericTypeReference, genericArguments, this, true));
            }

            uint key = m_factory.GetGenericTypeInstanceReferenceInternedKey(genericTypeReference, genericArguments);

            IGenericTypeInstanceReference type = null;

            object value;

            if (m_objects.TryGetValue(key, out value))
            {
                type = value as IGenericTypeInstanceReference;

                if (type != null && !SequenceEquals(genericArguments, type.GenericArguments))
                {
                    // We can currently get problematic cache hits here for different objects representing the same type.
                    // e.g. SignatureGenericTypeParameter from ref signature can substitute for GenericTypeParameter
                    // from def signature. This breaks assumptions that were there prior to the sharing of generic
                    // type instances that was introduced by the caching intern factory. In that particular case, it breaks
                    // the subsequent specialization of the type parameter.
                    //
                    // We should investigate how to share more in these cases, but in the meantime, we conservatively
                    // only use an existing instantiation if the genericArguments are identical object references and
                    // otherwise force a cache miss here.
                    type = null;
                }
            }

            if (type == null)
            {
                type           = new Microsoft.Cci.Immutable.GenericTypeInstanceReference(genericTypeReference, genericArguments, this, true);
                m_objects[key] = type;
            }

            return(type);
        }
示例#20
0
        public virtual void VisitNode(IReference node)
        {
            IAssembly             assembly = node as IAssembly;
            INamedTypeDefinition  type     = node as INamedTypeDefinition;
            ITypeDefinitionMember member   = node as ITypeDefinitionMember;
            IAliasForType         alias    = node as IAliasForType;

            if (assembly != null)
            {
                if (m_implModel.CanIncludeAssembly(assembly.AssemblyIdentity))
                {
                    Visit(assembly);
                }
            }
            else if (type != null)
            {
                INamedTypeReference typeRef = Util.CanonicalizeTypeReference(type);
                if (m_implModel.CanInclude(typeRef))
                {
                    Visit(type);
                }
            }
            else if (member != null)
            {
                INamedTypeReference typeRef = Util.CanonicalizeTypeReference(member.ContainingType);
                if (m_implModel.CanInclude(typeRef))
                {
                    Visit(member);
                }
            }
            else if (alias != null)
            {
                Visit(alias);
            }
            else
            {
                throw new Exception("Illegal node: " + node.GetType().Name);
            }
        }
示例#21
0
        private static string GetMangledAndEscapedName(INamedTypeReference namedType)
        {
            var           pooled      = PooledStringBuilder.GetInstance();
            StringBuilder mangledName = pooled.Builder;

            const string needsEscaping = "\\[]*.+,& ";

            foreach (var ch in namedType.Name)
            {
                if (needsEscaping.IndexOf(ch) >= 0)
                {
                    mangledName.Append('\\');
                }

                mangledName.Append(ch);
            }

            if (namedType.MangleName && namedType.GenericParameterCount > 0)
            {
                mangledName.Append(MetadataHelpers.GetAritySuffix(namedType.GenericParameterCount));
            }

            return(pooled.ToStringAndFree());
        }
示例#22
0
 public bool CanInclude(INamedTypeReference typeRef)
 {
     return(CanIncludeUnit(TypeHelper.GetDefiningUnitReference(typeRef)));
 }
示例#23
0
 public virtual void AddTypeReference(INamedTypeReference type)
 {
     m_implModel.AddTypeReference(type);
 }
示例#24
0
 public virtual void AddTypeReference(INamedTypeReference type)
 {
     Debug.Assert(CanInclude(type));
     _depot.AddTypeReference(type);
 }
示例#25
0
 public override void Visit(INamedTypeReference namedTypeReference)
 {
     allElements.Add(new InvokInfo(Traverser, "INamedTypeReference", namedTypeReference));
 }
示例#26
0
        /// <summary>
        /// Caching GenericTypeInstanceRefernece objects based on interned key, avoiding GenericTypeInstance.InitializeIfNecessary expense
        /// </summary>
        public IGenericTypeInstanceReference GetOrMakeGenericTypeInstanceReference(INamedTypeReference genericTypeReference, IEnumerable<ITypeReference> genericArguments)
        {
            InternFactory factory = m_factory as InternFactory;
            if (factory != null && !factory.InternKeysAreReliablyUnique)
            {
                return new Microsoft.Cci.Immutable.GenericTypeInstanceReference(genericTypeReference, genericArguments, this, true);
            }

            uint key = m_factory.GetGenericTypeInstanceReferenceInternedKey(genericTypeReference, genericArguments);

            IGenericTypeInstanceReference type = null;

            object value;

            if (m_objects.TryGetValue(key, out value))
            {
                type = value as IGenericTypeInstanceReference;

                if (type != null && !SequenceEquals(genericArguments, type.GenericArguments))
                {
                    // We can currently get problematic cache hits here for different objects representing the same type.
                    // e.g. SignatureGenericTypeParameter from ref signature can substitute for GenericTypeParameter
                    // from def signature. This breaks assumptions that were there prior to the sharing of generic
                    // type instances that was introduced by the caching intern factory. In that particular case, it breaks
                    // the subsequent specialization of the type parameter.
                    //
                    // We should investigate how to share more in these cases, but in the meantime, we conservatively
                    // only use an existing instantiation if the genericArguments are identical object references and 
                    // otherwise force a cache miss here.
                    type = null;
                }
            }

            if (type == null)
            {
                type = new Microsoft.Cci.Immutable.GenericTypeInstanceReference(genericTypeReference, genericArguments, this, true);
                m_objects[key] = type;
            }

            return type;
        }
示例#27
0
 public bool CanInclude(INamedTypeReference typeRef)
 {
     return CanIncludeUnit(TypeHelper.GetDefiningUnitReference(typeRef));
 }
 private ITypeReference Instantiate(uint typeSpecToken, INamedTypeReference templateTypeReference, ushort genericArgumentCount) {
   //It would be very desirable to cache these objects by structure so that we can reuse them.
   //However, it is not safe at this point to use the intern table because we might still be reading the
   //signature of a generic method whose generic parameters feature in the arguments to the generic type.
   //We cannot compute the intern key of a generic method type parameter before we are able to compute the intern key of the generic method.
   var genericArgumentArray = new ITypeReference[genericArgumentCount];
   for (int i = 0; i < genericArgumentCount; ++i) genericArgumentArray[i] = this.GetTypeReference()??Dummy.TypeReference;
   if (typeSpecToken != 0xFFFFFFFF)
     return new GenericTypeInstanceReferenceWithToken(typeSpecToken, templateTypeReference, IteratorHelper.GetReadonly(genericArgumentArray), this.PEFileToObjectModel.InternFactory);
   else
     return new GenericTypeInstanceReference(templateTypeReference, IteratorHelper.GetReadonly(genericArgumentArray), this.PEFileToObjectModel.InternFactory);
 }
示例#29
0
 public static bool SameType(this INamedTypeReference containingType, ITypeDefinition iteratorClass)
 {
     return(containingType.TypeEquals(iteratorClass));
 }
 private static bool SeeIfTypeNamesAreMangled(INamedTypeReference/*?*/ templateTypeReference) {
   if (templateTypeReference == null) return false;
   if (templateTypeReference.MangleName) return true;
   var nestedTypeReference = templateTypeReference as INestedTypeReference;
   if (nestedTypeReference != null) return SeeIfTypeNamesAreMangled(nestedTypeReference.ContainingType as INamedTypeReference);
   return false;
 }
示例#31
0
            public Assembly GenerateFacade(IAssembly contractAssembly, IAssemblyReference seedCoreAssemblyReference, bool ignoreMissingTypes, IAssembly overrideContractAssembly = null, bool buildPartialReferenceFacade = false)
            {
                Assembly assembly;

                if (overrideContractAssembly != null)
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost);
                    assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present
                }
                else
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost);
                    assembly = copier.Copy(contractAssembly);

                    // if building a reference facade don't strip the contract
                    if (!buildPartialReferenceFacade)
                    {
                        ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null);
                        rewriter.Rewrite(assembly);
                    }
                }

                string contractAssemblyName = contractAssembly.AssemblyIdentity.Name.Value;
                IEnumerable <string> docIds = _docIdTable[contractAssemblyName];

                // Add all the type forwards
                bool error = false;

                Dictionary <string, INamedTypeDefinition> existingDocIds = assembly.AllTypes.ToDictionary(typeDef => typeDef.RefDocId(), typeDef => typeDef);
                IEnumerable <string> docIdsToForward = buildPartialReferenceFacade ? existingDocIds.Keys : docIds.Where(id => !existingDocIds.ContainsKey(id));
                Dictionary <string, INamedTypeReference> forwardedTypes = new Dictionary <string, INamedTypeReference>();

                foreach (string docId in docIdsToForward)
                {
                    IReadOnlyList <INamedTypeDefinition> seedTypes;
                    if (!_typeTable.TryGetValue(docId, out seedTypes))
                    {
                        if (!ignoreMissingTypes && !buildPartialReferenceFacade)
                        {
                            Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId);
                            error = true;
                        }
                        continue;
                    }

                    INamedTypeDefinition seedType = GetSeedType(docId, seedTypes);
                    if (seedType == null)
                    {
                        TraceDuplicateSeedTypeError(docId, seedTypes);
                        error = true;
                        continue;
                    }

                    if (buildPartialReferenceFacade)
                    {
                        // honor preferSeedType for keeping contract type
                        string preferredSeedAssembly;
                        bool   keepType = _seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly) &&
                                          contractAssemblyName.Equals(preferredSeedAssembly, StringComparison.OrdinalIgnoreCase);

                        if (keepType)
                        {
                            continue;
                        }

                        assembly.AllTypes.Remove(existingDocIds[docId]);
                        forwardedTypes.Add(docId, seedType);
                    }

                    AddTypeForward(assembly, seedType);
                }

                if (buildPartialReferenceFacade)
                {
                    if (forwardedTypes.Count == 0)
                    {
                        Trace.TraceError("Did not find any types in any of the seed assemblies.");
                        return(null);
                    }
                    else
                    {
                        // for any thing that's now a typeforward, make sure typerefs point to that rather than
                        // the type previously inside the assembly.
                        TypeReferenceRewriter typeRefRewriter = new TypeReferenceRewriter(_seedHost, oldType =>
                        {
                            INamedTypeReference newType = null;
                            return(forwardedTypes.TryGetValue(oldType.DocId(), out newType) ? newType : oldType);
                        });

                        typeRefRewriter.Rewrite(assembly);
                    }
                }

                if (error)
                {
                    return(null);
                }

                if (_assemblyFileVersion != null)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                }

                if (_buildDesignTimeFacades)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly));
                    assembly.Flags |= ReferenceAssemblyFlag;
                }

                if (_clearBuildAndRevision)
                {
                    assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0);
                }

                AddWin32VersionResource(contractAssembly.Location, assembly);

                return(assembly);
            }
示例#32
0
 private ITypeReference Specialize(uint typeSpecToken, INamedTypeReference namedTypeReference, ref ushort genericArgumentCount, bool outer) {
   if (genericArgumentCount == 0) return namedTypeReference;
   var nestedTypeReference = namedTypeReference as INestedTypeReference;
   if (nestedTypeReference != null) {
     Contract.Assume(!(nestedTypeReference is ISpecializedNestedTypeReference)); //the type reference comes from the metadata, which is always fully unspecialized
     var containingType = this.Specialize(0, (INamedTypeReference)nestedTypeReference.ContainingType, ref genericArgumentCount, outer: false);
     if (containingType != nestedTypeReference.ContainingType)
       namedTypeReference = new SpecializedNestedTypeReference(nestedTypeReference, containingType, this.PEFileToObjectModel.InternFactory);
   }
   var genericParametersCount = namedTypeReference.GenericParameterCount;
   if (genericParametersCount == 0) {
     if (genericArgumentCount == 0 || !outer) return namedTypeReference;
     //If we get here we believed that namedTypeReference has no type parameters because it has no tick in its name.
     //However, there actually are generic types without ticks, so we better now change our belief to match this signature.
     //This does not work for nested generics, but that is just too bad.
     genericParametersCount = genericArgumentCount;
   }
   genericArgumentCount -= genericParametersCount;
   var genericArgumentArray = new ITypeReference[genericParametersCount];
   //TODO: it would be very desirable to cache these objects by structure so that we can reuse them.
   //However, it is not safe at this point to use the intern table because we might still be reading the
   //signature of a generic method whose generic parameters feature in the arguments to the generic type.
   //We cannot compute the intern key of a generic method type parameter before we are able to compute the intern key of the generic method.
   for (int i = 0; i < genericParametersCount; ++i) genericArgumentArray[i] = this.GetTypeReference()??Dummy.TypeReference;
   if (outer && typeSpecToken != 0xFFFFFFFF)
     return new GenericTypeInstanceReferenceWithToken(typeSpecToken, namedTypeReference, IteratorHelper.GetReadonly(genericArgumentArray), this.PEFileToObjectModel.InternFactory);
   else
     return new GenericTypeInstanceReference(namedTypeReference, IteratorHelper.GetReadonly(genericArgumentArray), this.PEFileToObjectModel.InternFactory);
 }
 /// <summary>
 /// Performs some computation with the given named type reference.
 /// </summary>
 public virtual void Visit(INamedTypeReference namedTypeReference)
 {
     
 }
示例#34
0
 /// <summary>
 /// Provides the host with an opportunity to substitute one type reference for another during metadata reading.
 /// This avoids the cost of rewriting the entire unit in order to make such changes.
 /// </summary>
 /// <param name="referringUnit">The unit that contains the reference.</param>
 /// <param name="typeReference">A named type reference encountered during metadata reading.</param>
 /// <returns>
 /// Usually the value in typeReference, but occassionally something else.
 /// </returns>
 public INamedTypeReference Redirect(IUnit referringUnit, INamedTypeReference typeReference) {
   Contract.Requires(referringUnit != null);
   Contract.Requires(typeReference != null);
   Contract.Ensures(Contract.Result<INamedTypeReference>() != null);
   throw new NotImplementedException();
 }
示例#35
0
 internal TypeInferencer(INamedTypeReference containingType, IMetadataHost host)
 {
     this.containingType = containingType;
     this.host           = host;
     this.platformType   = containingType.PlatformType;
 }
 public override void Visit(INamedTypeReference namedTypeReference)
 {
     if(Process(namedTypeReference)){visitor.Visit(namedTypeReference);}
     base.Visit(namedTypeReference);
 }
 private ITypeReference SpecializeAndOrInstantiate(uint typeSpecToken, INamedTypeReference namedTypeReference, ref ushort genericArgumentCount, bool outer) {
   if (genericArgumentCount == 0) return namedTypeReference;
   var nestedTypeReference = namedTypeReference as INestedTypeReference;
   if (nestedTypeReference != null) {
     Contract.Assume(!(nestedTypeReference is ISpecializedNestedTypeReference)); //the type reference comes from the metadata, which is always fully unspecialized
     var containingType = this.SpecializeAndOrInstantiate(0, (INamedTypeReference)nestedTypeReference.ContainingType, ref genericArgumentCount, outer: false);
     if (containingType != nestedTypeReference.ContainingType)
       namedTypeReference = new SpecializedNestedTypeReference(nestedTypeReference, containingType, this.PEFileToObjectModel.InternFactory);
   }
   if (genericArgumentCount <= 0) return namedTypeReference;
   var genericParametersCount = namedTypeReference.GenericParameterCount;
   genericArgumentCount -= genericParametersCount;
   if (genericArgumentCount < 0) { genericParametersCount += genericArgumentCount; };
   if (genericParametersCount == 0) return namedTypeReference;
   return this.Instantiate(typeSpecToken, namedTypeReference, genericParametersCount);
 }
示例#38
0
        public static string Serialize(INamedTypeReference type)
        {
            var types = new INamedTypeReference[] { type };

            return(Serialize(type));
        }
示例#39
0
        public static List <ITypeDefinitionMember> FindRelatedMembers(ITypeDefinitionMember member, TypeIncluded includeType)
        {
            List <ITypeDefinitionMember>      relatedMembers     = new List <ITypeDefinitionMember>();
            Dictionary <uint, ITypeReference> participatingTypes = new Dictionary <uint, ITypeReference>();

            ITypeDefinition currentType = member.ContainingTypeDefinition;

            do
            {
                //
                // add the type
                //
                participatingTypes.Add(currentType.InternedKey, currentType);

                //
                // add any interfaces it implements that are part of the closure
                //
                foreach (ITypeReference iface in currentType.Interfaces)
                {
                    INamedTypeReference ifaceTemplate = Util.CanonicalizeTypeReference(iface);
                    // check the closure against the template type, but add
                    // the specialized type to participatingTypes so that
                    // argument matching works
                    if (includeType(ifaceTemplate) &&
                        !participatingTypes.ContainsKey(iface.InternedKey))
                    {
                        // Should we add ifaceTemplate or iface?
                        participatingTypes.Add(iface.InternedKey, iface);
                    }
                }

                //
                // go up to the base type
                //
                currentType = TypeHelper.BaseClass(currentType);
            }while (currentType != null);

            foreach (ITypeReference type in participatingTypes.Values)
            {
                ITypeDefinitionMember relatedMember = FindRelatedMember(type, member);
                if (null != relatedMember)
                {
                    relatedMembers.Add(relatedMember);
                }
                // TODO: Review
                foreach (IMethodImplementation methodImpl in Util.CanonicalizeType(type).ExplicitImplementationOverrides)
                {
                    ITypeDefinitionMember implementingMethod = Util.CanonicalizeMember(methodImpl.ImplementingMethod);
                    ITypeDefinitionMember implementedMethod  = Util.CanonicalizeMember(methodImpl.ImplementedMethod);
                    bool implementedTypeIncluded             = includeType(Util.CanonicalizeType(implementedMethod.ContainingType));

                    if ((implementedMethod == member) ||
                        (implementingMethod == member && implementedTypeIncluded))
                    {
                        if (!relatedMembers.Contains(implementingMethod))
                        {
                            relatedMembers.Add(implementingMethod);
                        }
                        if (!relatedMembers.Contains(implementedMethod))
                        {
                            relatedMembers.Add(implementedMethod);
                        }
                    }
                }
            }

            return(relatedMembers);
        }
示例#40
0
        private static string GetMangledAndEscapedName(INamedTypeReference namedType)
        {
            var pooled = PooledStringBuilder.GetInstance();
            StringBuilder mangledName = pooled.Builder;

            const string needsEscaping = "\\[]*.+,& ";
            foreach (var ch in namedType.Name)
            {
                if (needsEscaping.IndexOf(ch) >= 0)
                {
                    mangledName.Append('\\');
                }

                mangledName.Append(ch);
            }

            if (namedType.MangleName && namedType.GenericParameterCount > 0)
            {
                mangledName.Append(MetadataHelpers.GetAritySuffix(namedType.GenericParameterCount));
            }

            return pooled.ToStringAndFree();
        }
示例#41
0
 internal TypeInferencer(INamedTypeReference containingType, IMetadataHost host)
 {
     this.containingType = containingType;
       this.host = host;
       this.platformType = containingType.PlatformType;
 }
示例#42
0
 /// <summary>
 /// Performs some computation with the given named type reference.
 /// </summary>
 public void Visit(INamedTypeReference namedTypeReference)
 {
     this.Visit((ITypeReference)namedTypeReference);
 }
 /// <summary>
 /// Rewrites the named specified type reference.
 /// </summary>
 public virtual INamedTypeReference Rewrite(INamedTypeReference typeReference)
 {
     return typeReference;
 }
示例#44
0
 private ITypeReference GetSpecializedTypeReference(PEFileToObjectModel peFileToObjectModel, INamedTypeReference nominalType, out int argumentUsed, bool mostNested) {
   argumentUsed = 0;
   int len = this.GenericArguments.Count;
   var nestedType = nominalType as INestedTypeReference;
   if (nestedType != null) {
     var parentTemplate = this.GetSpecializedTypeReference(peFileToObjectModel, (INamedTypeReference)nestedType.ContainingType, out argumentUsed, mostNested: false);
     if (parentTemplate != nestedType.ContainingType)
       nominalType = new SpecializedNestedTypeReference(nestedType, parentTemplate, peFileToObjectModel.InternFactory);
   }
   var argsToUse = mostNested ? len-argumentUsed : nominalType.GenericParameterCount;
   if (argsToUse == 0) return nominalType;
   var genericArgumentsReferences = new ITypeReference[argsToUse];
   for (int i = 0; i < argsToUse; ++i)
     genericArgumentsReferences[i] = this.GenericArguments[i+argumentUsed].GetAsTypeReference(peFileToObjectModel, peFileToObjectModel.Module)??Dummy.TypeReference;
   argumentUsed += argsToUse;
   return new GenericTypeInstanceReference(nominalType, IteratorHelper.GetReadonly(genericArgumentsReferences), peFileToObjectModel.InternFactory);
 }
 private ITypeReference Specialize(uint typeSpecToken, INamedTypeReference namedTypeReference, ref ushort genericArgumentCount, bool outer) {
   if (genericArgumentCount == 0) return namedTypeReference;
   var nestedTypeReference = namedTypeReference as INestedTypeReference;
   if (nestedTypeReference != null) {
     Contract.Assume(!(nestedTypeReference is ISpecializedNestedTypeReference)); //the type reference comes from the metadata, which is always fully unspecialized
     var containingType = this.Specialize(0, (INamedTypeReference)nestedTypeReference.ContainingType, ref genericArgumentCount, outer: false);
     if (containingType != nestedTypeReference.ContainingType)
       namedTypeReference = new SpecializedNestedTypeReference(nestedTypeReference, containingType, this.PEFileToObjectModel.InternFactory);
   }
   var genericParametersCount = namedTypeReference.GenericParameterCount;
   if (genericParametersCount == 0) {
     if (genericArgumentCount == 0 || !outer) return namedTypeReference;
     //If we get here we believed that namedTypeReference has no type parameters because it has no tick in its name.
     //However, there actually are generic types without ticks, so we better now change our belief to match this signature.
     //This does not work for nested generics, but that is just too bad.
     genericParametersCount = genericArgumentCount;
   }
   genericArgumentCount -= genericParametersCount;
   var genericArgumentArray = new ITypeReference[genericParametersCount];
   for (int i = 0; i < genericParametersCount; ++i) genericArgumentArray[i] = this.GetTypeReference()??Dummy.TypeReference;
   if (outer)
     return new GenericTypeInstanceReferenceWithToken(typeSpecToken, namedTypeReference, IteratorHelper.GetReadonly(genericArgumentArray), this.PEFileToObjectModel.InternFactory);
   else
     return new GenericTypeInstanceReference(namedTypeReference, IteratorHelper.GetReadonly(genericArgumentArray), this.PEFileToObjectModel.InternFactory);
 }
示例#46
0
 public virtual void AddTypeReference(INamedTypeReference type)
 {
     Debug.Assert(CanInclude(type));
     _depot.AddTypeReference(type);
 }
 /// <summary>
 /// Performs some computation with the given named type reference.
 /// </summary>
 public virtual void Visit(INamedTypeReference namedTypeReference)
 {
 }
示例#48
0
 /// <summary>
 /// Provides the host with an opportunity to substitute one named type reference for another during metadata reading.
 /// This avoids the cost of rewriting the entire unit in order to make such changes.
 /// </summary>
 /// <param name="referringUnit">The unit that contains the reference.</param>
 /// <param name="typeReference">A named type reference encountered during metadata reading.</param>
 /// <returns>
 /// Usually the value in typeReference, but occassionally something else.
 /// </returns>
 public virtual INamedTypeReference Redirect(IUnit referringUnit, INamedTypeReference typeReference) {
   return typeReference;
 }
 /// <summary>
 /// Provides the host with an opportunity to substitute one type reference for another during metadata reading.
 /// This avoids the cost of rewriting the entire unit in order to make such changes.
 /// </summary>
 /// <param name="referringUnit">The unit that contains the reference.</param>
 /// <param name="typeReference">A type reference encountered during metadata reading.</param>
 /// <returns>
 /// Usually the value in typeReference, but occassionally something else.
 /// </returns>
 public override INamedTypeReference Redirect(IUnit referringUnit, INamedTypeReference typeReference) {
   if (!this.projectToCLRTypes) return typeReference;
   var referringModule = referringUnit as IModule;
   if (referringModule == null || referringModule.ContainingAssembly == null || !(referringModule.ContainingAssembly.ContainsForeignTypes)) return typeReference;
   var platformType = (WindowsRuntimePlatform)this.PlatformType;
   var namespaceTypeReference = typeReference as INamespaceTypeReference;
   if (namespaceTypeReference == null) return typeReference;
   var namespaceReference = namespaceTypeReference.ContainingUnitNamespace as INestedUnitNamespaceReference;
   if (namespaceReference == null) return typeReference;
   if (this.IsWindowsFoundationMetadata(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.SystemAttributeUsageAttribute.Name) return platformType.SystemAttributeUsageAttribute;
     if (namespaceTypeReference.Name == platformType.SystemAttributeTargets.Name) return platformType.SystemAttributeTargets;
   } else if (this.IsWindowsUI(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.WindowsUIColor.Name) return platformType.WindowsUIColor;
   } else if (this.IsWindowsFoundation(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.SystemDateTime.Name) return platformType.SystemDateTimeOffset;
     if (namespaceTypeReference.Name == platformType.SystemEventHandler1.Name && namespaceTypeReference.GenericParameterCount == 1)
       return platformType.SystemEventHandler1;
     if (namespaceTypeReference.Name == platformType.SystemRuntimeInteropServicesWindowsRuntimeEventRegistrationToken.Name)
       return platformType.SystemRuntimeInteropServicesWindowsRuntimeEventRegistrationToken;
     if (namespaceTypeReference.Name == this.HResult) return platformType.SystemException;
     if (namespaceTypeReference.Name == this.IReference && namespaceTypeReference.GenericParameterCount == 1)
       return platformType.SystemNullable1;
     if (namespaceTypeReference.Name == platformType.WindowsFoundationPoint.Name) return platformType.WindowsFoundationPoint;
     if (namespaceTypeReference.Name == platformType.WindowsFoundationRect.Name) return platformType.WindowsFoundationRect;
     if (namespaceTypeReference.Name == platformType.WindowsFoundationSize.Name) return platformType.WindowsFoundationSize;
     if (namespaceTypeReference.Name == platformType.SystemTimeSpan.Name) return platformType.SystemTimeSpan;
     if (namespaceTypeReference.Name == platformType.SystemUri.Name) return platformType.SystemUri;
     if (namespaceTypeReference.Name == this.IClosable) return platformType.SystemIDisposable;
   } else if (this.IsWindowsFoundationCollections(namespaceReference)) {
     if (namespaceTypeReference.Name == this.IIterable) return platformType.SystemCollectionsGenericIEnumerable;
     if (namespaceTypeReference.Name == this.IVector) return platformType.SystemCollectionsGenericIList;
     if (namespaceTypeReference.Name == this.IVectorView) return platformType.SystemCollectionsGenericReadOnlyList;
     if (namespaceTypeReference.Name == this.IMap) return platformType.SystemCollectionsGenericIDictionary;
     if (namespaceTypeReference.Name == this.IMapView) return platformType.SystemCollectionsGenericReadOnlyDictionary;
     if (namespaceTypeReference.Name == this.IKeyValuePair) return platformType.SystemCollectionsGenericKeyValuePair;
   } else if (this.IsWindowsUIXamlInput(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.SystemWindowsInputICommand.Name) return platformType.SystemWindowsInputICommand;
   } else if (this.IsWindowsUIXamlInterop(namespaceReference)) {
     if (namespaceTypeReference.Name == this.IBindableIterable) return platformType.SystemCollectionsIEnumerable;
     if (namespaceTypeReference.Name == this.IBindableVector) return platformType.SystemCollectionsIList;
     if (namespaceTypeReference.Name == this.INotifyCollectionChanged) return platformType.SystemCollectionsSpecializedINotifyColletionChanged;
     if (namespaceTypeReference.Name == this.NotifyCollectionChangedEventHandler) return platformType.SystemCollectionsSpecializedNotifyCollectionChangedEventHandler;
     if (namespaceTypeReference.Name == this.NotifyCollectionChangedEventArgs) return platformType.SystemCollectionsSpecializedNotifyCollectionChangedEventArgs;
     if (namespaceTypeReference.Name == this.NotifyCollectionChangedAction) return platformType.SystemCollectionsSpecializedNotifyCollectionChangedAction;
     if (namespaceTypeReference.Name == this.TypeName) return platformType.SystemType;
   } else if (this.IsWindowsUIXamlData(namespaceReference)) {
     if (namespaceTypeReference.Name == this.INotifyPropertyChanged) return platformType.SystemComponentModelINotifyPropertyChanged;
     if (namespaceTypeReference.Name == this.PropertyChangedEventArgs) return platformType.SystemComponentModelPropertyChangedEventArgs;
     if (namespaceTypeReference.Name == this.PropertyChangedEventHandler) return platformType.SystemComponentModelPropertyChangedEventHandler;
   } else if (this.IsWindowsUIXaml(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlCornerRadius.Name) return platformType.WindowsUIXamlCornerRadius;
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlDuration.Name) return platformType.WindowsUIXamlDuration;
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlDurationType.Name) return platformType.WindowsUIXamlDurationType;
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlGridLength.Name) return platformType.WindowsUIXamlGridLength;
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlGridUnitType.Name) return platformType.WindowsUIXamlGridUnitType;
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlThickness.Name) return platformType.WindowsUIXamlThickness;
   } else if (this.IsWindowsUIXamlControlsPrimitives(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlControlsPrimitivesGeneratorPosition.Name)
       return platformType.WindowsUIXamlControlsPrimitivesGeneratorPosition;
   } else if (this.IsWindowsUIXamlMedia(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlMediaMatrix.Name) return platformType.WindowsUIXamlMediaMatrix;
   } else if (this.IsWindowsUIXamlMediaAnimation(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlMediaAnimationKeyTime.Name)
       return platformType.WindowsUIXamlMediaAnimationKeyTime;
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlMediaAnimationRepeatBehavior.Name)
       return platformType.WindowsUIXamlMediaAnimationRepeatBehavior;
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlMediaAnimationRepeatBehaviorType.Name)
       return platformType.WindowsUIXamlMediaAnimationRepeatBehaviorType;
   } else if (this.IsWindowsUIXamlMediaMedia3D(namespaceReference)) {
     if (namespaceTypeReference.Name == platformType.WindowsUIXamlMediaMedia3DMatrix3D.Name)
       return platformType.WindowsUIXamlMediaMedia3DMatrix3D;
   }
   return typeReference;
 }
示例#50
0
        private static void WriteType(ITypeReference type, TextWriter writer, bool omitOutermostTypeFormals)
        {
            Contract.Requires(type != null);
            Contract.Requires(writer != null);

            IArrayType array = type as IArrayType;

            if (array != null)
            {
                Contract.Assume(array.ElementType != null, "lack of CCI2 contracts");

                WriteType(array.ElementType, writer);
                writer.Write("[");
                if (array.Rank > 1)
                {
                    for (int i = 0; i < array.Rank; i++)
                    {
                        if (i > 0)
                        {
                            writer.Write(",");
                        }
                        writer.Write("0:");
                    }
                }
                writer.Write("]");
                return;
            }

            IManagedPointerTypeReference reference = type as IManagedPointerTypeReference;;

            if (reference != null)
            {
                Contract.Assume(reference.TargetType != null, "lack of CCI2 contracts");

                var referencedType = reference.TargetType;
                WriteType(referencedType, writer);
                writer.Write("@");
                return;
            }

            IPointerTypeReference pointer = type as IPointerTypeReference;

            if (pointer != null)
            {
                Contract.Assume(pointer.TargetType != null, "lack of CCI2 contracts");

                WriteType(pointer.TargetType, writer);
                writer.Write("*");
                return;
            }

            IModifiedTypeReference modref = type as IModifiedTypeReference;

            if (modref != null)
            {
                Contract.Assume(modref.UnmodifiedType != null, "lack of CCI2 contracts");
                Contract.Assume(modref.CustomModifiers != null, "lack of CCI2 contracts");

                WriteType(modref.UnmodifiedType, writer);
                foreach (var modifier in modref.CustomModifiers)
                {
                    Contract.Assume(modifier != null, "lack of collection contracts and CCI2 contracts");
                    Contract.Assume(modifier.Modifier != null, "lack of CCI2 contracts");

                    if (modifier.IsOptional)
                    {
                        writer.Write("!");
                    }
                    else
                    {
                        writer.Write("|");
                    }
                    WriteType(modifier.Modifier, writer);
                }
                return;
            }

            IGenericTypeParameterReference gtp = type as IGenericTypeParameterReference;

            if (gtp != null)
            {
                writer.Write("`");
                writer.Write(gtp.Index);
                return;
            }
            IGenericMethodParameterReference gmp = type as IGenericMethodParameterReference;

            if (gmp != null)
            {
                writer.Write("``");
                writer.Write(gmp.Index);
                return;
            }

            IGenericTypeInstanceReference instance = type as IGenericTypeInstanceReference;

            if (instance != null)
            {
                Contract.Assume(instance.GenericType != null, "lack of CCI2 contracts");
                Contract.Assume(instance.GenericArguments != null, "lack of CCI2 contracts");

                WriteType(instance.GenericType, writer, true);
                writer.Write("{");
                var first = true;
                foreach (var arg in instance.GenericArguments)
                {
                    Contract.Assume(arg != null, "lack of collection and CCI2 contracts");

                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        writer.Write(",");
                    }
                    WriteType(arg, writer);
                }
                writer.Write("}");
                return;
            }

            // namespace or nested
            INamedTypeReference  named  = (INamedTypeReference)type;
            INestedTypeReference nested = type as INestedTypeReference;

            if (nested != null)
            {
                Contract.Assume(nested.ContainingType != null, "lack of CCI2 contracts");

                // names of nested types begin with outer type name
                WriteType(nested.ContainingType, writer);
                writer.Write(".");
                // continue to write type sig
            }

            INamespaceTypeReference nt = type as INamespaceTypeReference;

            if (nt != null)
            {
                Contract.Assume(nt.ContainingUnitNamespace != null, "lack of CCI2 contracts");

                WriteNamespaceAndSeparator(nt.ContainingUnitNamespace, writer);
                // continue to write type sig
            }
            // name
            writer.Write(named.Name.Value);
            // generic parameters
            if (omitOutermostTypeFormals)
            {
                return;
            }

            if (named.GenericParameterCount > 0)
            {
                writer.Write("`{0}", named.GenericParameterCount);
            }
        }
示例#51
0
 public virtual void AddTypeReference(INamedTypeReference type)
 {
     m_implModel.AddTypeReference(type);
 }