示例#1
0
        public Helper(IModule module, PeReader.DefaultHost host, Log.Log logger)
        {
            this.host = host;
            this.logger = logger;
            this.module = module;

            // get all needed functions and namespaces
            this.systemString = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.String");
            this.systemIOTextWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.TextWriter");
            this.systemIOStreamWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.StreamWriter");
            this.systemInt32 = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Int32");
            this.systemObject = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Object");
            this.systemConsole = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Console");
            this.systemRandom = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Random");

            ITypeReference[] concatThreeParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString, this.host.PlatformType.SystemString };
            ITypeReference[] concatTwoParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString };
            ITypeReference[] streamWriterAppendTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemBoolean };

            this.stringConcatThree = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatThreeParameterTypes);
            this.stringConcatTwo = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatTwoParameterTypes);
            this.textWriterWriteLine = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("WriteLine"), this.host.PlatformType.SystemString);
            this.streamWriterCtor = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), this.host.PlatformType.SystemString);
            this.streamWriterCtorAppend = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), streamWriterAppendTypes);
            this.textWriterWrite = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Write"), this.host.PlatformType.SystemString);
            this.int32ToString = TypeHelper.GetMethod(systemInt32, this.host.NameTable.GetNameFor("ToString"));
            this.textWriterClose = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Close"));
            this.objectGetHashCode = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor("GetHashCode"));
            this.systemConsoleWriteLine = TypeHelper.GetMethod(systemConsole, host.NameTable.GetNameFor("WriteLine"), host.PlatformType.SystemString);
            this.objectCtor = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor(".ctor"));
            this.systemRandomCtor = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor(".ctor"));
            this.systemRandomNext = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor("Next"), host.PlatformType.SystemInt32);
        }
示例#2
0
        internal MappedField(string name, INamedTypeDefinition containingType, ITypeReference type, byte[] block)
            : base(name, containingType, type)
        {
            Debug.Assert(block != null);

            _block = block;
        }
示例#3
0
 private TypeMetricsWithMethodMetrics TypeAndMethods(PdbReader pdb, IMetadataHost host, INamedTypeDefinition type)
 {
     var typeAndMethods = new TypeMetricsWithMethodMetrics();
     typeAndMethods.AddMethodReports(AnalyzeMethods(type, pdb, host));
     typeAndMethods.Type = AnalyzeType(type, pdb, typeAndMethods.Methods);
     return typeAndMethods;
 }
 private static IEnumerable <string> GetGenericConstraints(INamedTypeDefinition type)
 {
     return(from g in type.GenericParameters
            from c in g.Constraints
            from t in c.GetAllRealTypeReferences()
            select t.ToString());
 }
示例#5
0
        private bool WeHidThisType(INamedTypeDefinition type)
        {
            // walk up all the declaring types to see if we hid one of them
            INamedTypeDefinition curType = type;

            while (curType != null && curType != Dummy.Type)
            {
                if (ShouldHideType(curType))
                {
                    return(true);
                }

                INestedTypeDefinition nestedType = curType as INestedTypeDefinition;
                if (nestedType != null)
                {
                    curType = Util.CanonicalizeType(nestedType.ContainingType);
                }
                else
                {
                    curType = null;
                }
            }

            return(false);
        }
示例#6
0
        public TypeNodeTag(TUITreeNode treeNode, INamedTypeDefinition type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (treeNode == null)
            {
                throw new ArgumentNullException("treeNode");
            }

            bs = type.BaseClasses;

            B = new ArrayList();

            foreach (ITypeReference r in bs)
            {
                B.Add(r.ToString());

                //if (r.ResolvedType.BaseClasses != null)
                //{
                //    foreach (ITypeReference rr in r.ResolvedType.BaseClasses)
                //        B.Add(rr.ToString());
                //}
            }

            this.UITreeNode = treeNode;
            this.Type       = type;
        }
示例#7
0
 public static int NotStaticAndPublic(INamedTypeDefinition type)
 {
     return type.Fields.Count(f
         => !f.IsStatic
         && f.Visibility == TypeMemberVisibility.Public
         && !f.IsGeneratedCode());
 }
示例#8
0
        private void CheckSurface(INamedTypeDefinition type, IAssembly originalAssembly)
        {
            var typeName = TypeHelper.GetTypeName(type, NameFormattingOptions.UseGenericTypeNameSuffix);

            if (ExcludeTypeFromComparison(type, typeName))
            {
                return;
            }
            var original = originalAssembly.GetCorresponding(type);

            if (original != null)
            {
                CheckTypeSurface(type, original);
            }
            else
            {
                if (type.IsInterface && !TypeHelper.IsVisibleOutsideAssembly(type))
                {
                    // Allow internal interfaces to be in our contract reference assemblies in order to get right virtual bits on some members.
                    Warning("Interface {0} only exists in contract reference assembly, but it is internal only, so allowed.", TypeHelper.GetTypeName(type));
                }
                else
                {
                    Error("Type {0} is in contract assembly but not in original assembly", typeName);
                }
            }
        }
 /// <summary>
 /// Returns the data in model file that corresponds to passed CCI2 type member
 /// </summary>
 /// <param name="typeDef">The CCI2 type member to look up</param>
 /// <returns>MemberElementBase of the data loaded from model file, or null if no entry exists</returns>
 public MemberElement this[ITypeDefinitionMember memberDef]
 {
     get
     {
         INamedTypeDefinition typeDef = Util.ContainingTypeDefinition(memberDef);
         AssemblyElement      assembly;
         string assemblyName = GetAssemblyName(typeDef);
         if (_reader.Model.Assemblies.TryGetValue(assemblyName, out assembly))
         {
             TypeElement type;
             string      typeName = _formatter.GetTypeSignature(typeDef);
             if (assembly.Types.TryGetValue(typeName, out type))
             {
                 // Try to return the member data if there
                 MemberElement member;
                 string        memberName = _formatter.GetMemberSignature(memberDef, true);
                 if (type.Members.TryGetValue(memberName, out member))
                 {
                     return(member);
                 }
             }
         }
         return(null);
     }
 }
示例#10
0
        private void MutateType(INamedTypeDefinition iTypeDef, Element element)
        {
            NamedTypeDefinition typeDef = iTypeDef as NamedTypeDefinition;

            if (typeDef == null)
            {
                throw new Exception("Invalid namedType definition.");
            }
            if (_applyAnnotations)
            {
                SecurityTransparencyStatus currentStatus = GetMarkedSecurityAnnotation(typeDef.Attributes, typeDef);
                if (element.SecurityTransparencyStatus != SecurityTransparencyStatus.Undefined && element.SecurityTransparencyStatus != SecurityTransparencyStatus.Transparent && currentStatus != element.SecurityTransparencyStatus)
                {
                    RemoveSecurityTransparencyAttributes(typeDef.Attributes, typeDef);
                    AddSecurityTransparencyAttribute(typeDef.Attributes, element.SecurityTransparencyStatus, typeDef);
                }
            }

            AddFaaAttributeIfNeeded(element, typeDef.Attributes, typeDef);

            if (_changeVisibility && element.ShouldMakeInternal)
            {
                MakeInternal(typeDef);
            }
        }
示例#11
0
        public Helper(IModule module, PeReader.DefaultHost host, Log.Log logger)
        {
            this.host   = host;
            this.logger = logger;
            this.module = module;

            // get all needed functions and namespaces
            this.systemString         = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.String");
            this.systemIOTextWriter   = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.TextWriter");
            this.systemIOStreamWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.StreamWriter");
            this.systemInt32          = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Int32");
            this.systemObject         = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Object");
            this.systemConsole        = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Console");
            this.systemRandom         = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Random");

            ITypeReference[] concatThreeParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString, this.host.PlatformType.SystemString };
            ITypeReference[] concatTwoParameterTypes   = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString };
            ITypeReference[] streamWriterAppendTypes   = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemBoolean };

            this.stringConcatThree      = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatThreeParameterTypes);
            this.stringConcatTwo        = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatTwoParameterTypes);
            this.textWriterWriteLine    = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("WriteLine"), this.host.PlatformType.SystemString);
            this.streamWriterCtor       = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), this.host.PlatformType.SystemString);
            this.streamWriterCtorAppend = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), streamWriterAppendTypes);
            this.textWriterWrite        = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Write"), this.host.PlatformType.SystemString);
            this.int32ToString          = TypeHelper.GetMethod(systemInt32, this.host.NameTable.GetNameFor("ToString"));
            this.textWriterClose        = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Close"));
            this.objectGetHashCode      = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor("GetHashCode"));
            this.systemConsoleWriteLine = TypeHelper.GetMethod(systemConsole, host.NameTable.GetNameFor("WriteLine"), host.PlatformType.SystemString);
            this.objectCtor             = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor(".ctor"));
            this.systemRandomCtor       = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor(".ctor"));
            this.systemRandomNext       = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor("Next"), host.PlatformType.SystemInt32);
        }
示例#12
0
 public static int NotStaticAndPublic(INamedTypeDefinition type)
 {
     return(type.Fields.Count(f
                              => !f.IsStatic &&
                              f.Visibility == TypeMemberVisibility.Public &&
                              !f.IsGeneratedCode()));
 }
示例#13
0
 private static IMethodDefinition GetMethod(INamedTypeDefinition original, IMethodDefinition method)
 {
     foreach (var candidate in original.GetMembersNamed(method.Name, false))
     {
         IMethodDefinition candidateMethod = candidate as IMethodDefinition;
         if (candidateMethod == null)
         {
             continue;
         }
         if (candidateMethod.GenericParameterCount != method.GenericParameterCount)
         {
             continue;
         }
         if (candidateMethod.ParameterCount != method.ParameterCount)
         {
             continue;
         }
         if (!ParameterTypesMatch(candidateMethod.Parameters, method.Parameters))
         {
             continue;
         }
         if (!TypesMatchSyntactically(candidateMethod.Type, method.Type))
         {
             continue;
         }
         return(candidateMethod);
     }
     return(null);
 }
示例#14
0
        public override void TraverseChildren(INamedTypeDefinition type)
        {
            if (type.Attributes.Count() > 1)
            {
                foreach (var atr in type.Attributes)
                {
                    // We look only for Scope annotation attributes.
                    if (Microsoft.Cci.TypeHelper.GetTypeName(atr.Type, NameFormattingOptions.Signature) != "ScopeRuntime.ScopeAnnotationAttribute")
                    {
                        continue;
                    }

                    if (atr.Arguments.Count() < 2)
                    {
                        continue;
                    }

                    if (atr.Arguments.ElementAt(0) is Microsoft.Cci.IMetadataConstant)
                    {
                        var argName = (atr.Arguments.ElementAt(0) as Microsoft.Cci.IMetadataConstant).Value.ToString();
                        if (argName == "OriginalClassName")
                        {
                            UDFS.Add((atr.Arguments.ElementAt(1) as Microsoft.Cci.IMetadataConstant).Value.ToString());
                        }
                    }
                }
            }

            base.TraverseChildren(type);
        }
示例#15
0
        private string GetClassImageKey(INamedTypeDefinition type)
        {
            if (type is INamespaceTypeDefinition)
            {
                return((type as INamespaceTypeDefinition).IsPublic
                    ? NodeImages.Keys.ClassImage
                    : NodeImages.Keys.ClassInternalImage);
            }
            else if (type is INestedTypeDefinition)
            {
                switch ((type as INestedTypeDefinition).Visibility)
                {
                case TypeMemberVisibility.Private:
                    return(NodeImages.Keys.ClassPrivateImage);

                case TypeMemberVisibility.Family:
                case TypeMemberVisibility.FamilyOrAssembly:
                    return(NodeImages.Keys.ClassProtectedImage);

                case TypeMemberVisibility.Assembly:
                case TypeMemberVisibility.FamilyAndAssembly:
                    return(NodeImages.Keys.ClassInternalImage);

                default:
                    return(NodeImages.Keys.ClassImage);
                }
            }
            else
            {
                return(NodeImages.Keys.ClassImage);
            }
        }
示例#16
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);
            }
示例#17
0
 private static IEnumerable<string> GetGenericConstraints(INamedTypeDefinition type)
 {
     return from g in type.GenericParameters
            from c in g.Constraints
            from t in c.GetAllRealTypeReferences()
            select t.ToString();
 }
示例#18
0
 private void AddToAllTypes(INamedTypeDefinition type)
 {
     this.allTypes.Add(type);
     foreach (var nestedType in type.NestedTypes)
     {
         this.AddToAllTypes(nestedType);
     }
 }
        public void ShouldFindTypeByIdentifier()
        {
            var searcher = new CciMethodMatcher(_context);
            var types    = _module.GetAllTypes();
            INamedTypeDefinition method = types.SingleOrDefault(searcher.Matches);

            Assert.IsNotNull(method);
        }
 public override void TraverseChildren(INamedTypeDefinition namedTypeDefinition)
 {
     if (!_filter.Include(namedTypeDefinition))
     {
         return;
     }
     base.TraverseChildren(namedTypeDefinition);
 }
        // called from Traverser
        // set in Main
        public static void TypeDefinitionTranslatorTraverse(INamedTypeDefinition typeDef)
        {
            TypeDefinitionTranslator t = new TypeDefinitionTranslator(typeDef);
            // todo: improve this piece of code
            StreamWriter streamWriter = Program.streamWriter;

            streamWriter.WriteLine(t.Translate());
        }
 public override void Visit(INamedTypeDefinition namedTypeDefinition)
 {
     if (Process(namedTypeDefinition))
     {
         visitor.Visit(namedTypeDefinition);
     }
     base.Visit(namedTypeDefinition);
 }
示例#23
0
        public override Assembly Visit(Assembly assembly)
        {
            _nsobject = UnitHelper.FindType(host.NameTable, assembly, "NObjective.Proxies.NSObject");
            //_proxyBaseClassAttribute = UnitHelper.FindType( host.NameTable, assembly, "NObjective.ProxyBaseClassAttribute" );

            _nsobjectHandle = _nsobject.Fields.First(x => x.Name.Value == "Handle");

            return(base.Visit(assembly));
        }
示例#24
0
 private void GenerateWorkForVirtuals(IClosureVisitor visitor)
 {
     INamedTypeDefinition[] defs = new INamedTypeDefinition[_depot.TypesClosure.Values.Count];
     _depot.TypesClosure.Values.CopyTo(defs, 0);
     foreach (INamedTypeDefinition type in defs)
     {
         GenerateWorkForVirtuals(type, visitor);
     }
 }
示例#25
0
 public TypeIdentifier(INamedTypeDefinition type)
 {
     var module = TypeHelper.GetDefiningUnit(type) as IModule;
     if (module == null || module == Dummy.Module || module == Dummy.Assembly)
     {
         throw new Exception(type.Name.Value + " has invalid container.");
     }
     _moduleName = module.ModuleName.Value;
     _typeName = type.Name.Value;
 }
示例#26
0
        internal SynthesizedStaticField(string name, INamedTypeDefinition containingType, ITypeReference type)
        {
            Debug.Assert(name != null);
            Debug.Assert(containingType != null);
            Debug.Assert(type != null);

            _containingType = containingType;
            _type           = type;
            _name           = name;
        }
示例#27
0
        static public TreeNode BuildTypeNodes(INamedTypeDefinition type)
        {
            var node = new TreeNode();

            CreateTreeNodes(new TypeNodeTag <TreeNode>(node, type));

            // Add nested types nodes.
            foreach (var t in type.NestedTypes)
            {
                node.Nodes.Add(BuildTypeNodes(t));
            }

            var methods = new List <IMethodReference>();

            foreach (var m in type.Methods)
            {
                methods.Add(m);
            }

            // fields
            foreach (var f in type.Fields)
            {
                node.Nodes.Add(BuildFieldNodes(f));
            }

            // events
            foreach (var e in type.Events)
            {
                node.Nodes.Add(BuildEventNodes(e));

                foreach (var m in e.Accessors)
                {
                    methods.Remove(m);
                }
            }

            // properties
            foreach (var p in type.Properties)
            {
                node.Nodes.Add(BuildPropertyNodes(p));

                foreach (var m in p.Accessors)
                {
                    methods.Remove(m);
                }
            }

            // methods
            foreach (var m in methods)
            {
                node.Nodes.Add(BuildMethodNodes(m.ResolvedMethod));
            }

            return(node);
        }
示例#28
0
        private void ProcessGenericType(ITypeDefinition cl, StreamWriter classesSW,
                                        IModule mod, ISet <ITypeDefinition> processedTypes)
        {
            IGenericTypeInstance gcl = cl as IGenericTypeInstance;

            if (gcl != null && !processedTypes.Contains(gcl))
            {
                INamedTypeDefinition         templateType = gcl.GenericType.ResolvedType;
                IEnumerable <ITypeReference> genArgs      = gcl.GenericArguments;
                string argStr = "";
                foreach (ITypeReference ty in genArgs)
                {
                    ITypeDefinition tyDefn = ty.ResolvedType;
                    if (tyDefn is IGenericTypeInstance)
                    {
                        IModule mod1 = TypeHelper.GetDefiningUnit(tyDefn) as IModule;
                        ProcessGenericType(tyDefn, classesSW, mod1, processedTypes);
                    }
                    else
                    {
                        if (!processedTypes.Contains(tyDefn))
                        {
                            IModule mod1 = TypeHelper.GetDefiningUnit(tyDefn) as IModule;
                            classesSW.WriteLine("CLASS:" + tyDefn.FullName() + " ARGS:" + " MODULE:" + mod1.Name.Value);
                            processedTypes.Add(tyDefn);
                        }
                    }
                    argStr += tyDefn.FullName() + ";";
                }
                if (!argStr.Equals(""))
                {
                    argStr = argStr.TrimEnd(';');
                }

                IDictionary <string, ITypeDefinition> nestedTypeMap = new Dictionary <string, ITypeDefinition>();
                FillNestedTypeMap(gcl, nestedTypeMap, "", false);
                int nestedCnt = nestedTypeMap.Count;
                if (nestedCnt > 0)
                {
                    classesSW.WriteLine("CLASS:" + templateType.FullName() + " ARGS:" + argStr + " MODULE:" + mod.Name.Value +
                                        " NESTED_CNT:" + nestedCnt);
                }
                else
                {
                    classesSW.WriteLine("CLASS:" + templateType.FullName() + " ARGS:" + argStr + " MODULE:" + mod.Name.Value);
                }
                processedTypes.Add(gcl);
                foreach (KeyValuePair <string, ITypeDefinition> entry in nestedTypeMap)
                {
                    classesSW.WriteLine("CLASS:" + templateType.FullName() + " ARGS:" + argStr + " MODULE:" + mod.Name.Value +
                                        " NESTED_CLASS:" + entry.Key);
                    processedTypes.Add(entry.Value);
                }
            }
        }
示例#29
0
 /// <summary>
 /// Traverses only the nested types and methods and collects together all of the private helper types that are introduced by the compiler
 /// when methods that contain closures or iterators are compiled.
 /// </summary>
 public override void TraverseChildren(INamedTypeDefinition typeDefinition)
 {
     foreach (ITypeDefinition nestedType in typeDefinition.NestedTypes)
     {
         this.Traverse(nestedType);
     }
     foreach (IMethodDefinition method in typeDefinition.Methods)
     {
         this.Traverse(method);
     }
 }
示例#30
0
        /// <summary>
        /// Finds a type in the given module using the given type name, expressed in C# notation with dots separating both namespaces and types.
        /// If no such type can be found Dummy.NamespaceTypeDefinition is returned.
        /// </summary>
        /// <param name="nameTable">A collection of IName instances that represent names that are commonly used during compilation.
        /// This is a provided as a parameter to the host environment in order to allow more than one host
        /// environment to co-exist while agreeing on how to map strings to IName instances.</param>
        /// <param name="unit">The unit of metadata to search for the type.</param>
        /// <param name="typeName">A string containing the fully qualified type name, using C# formatting conventions.</param>
        /// <param name="genericParameterCount">The number of generic parameters the returned type should have.</param>
        public static INamedTypeDefinition FindType(INameTable nameTable, IUnit unit, string typeName, int genericParameterCount)
        {
            int offset = 0;
            INamedTypeDefinition /*?*/ result = GetType(nameTable, unit.UnitNamespaceRoot, typeName, genericParameterCount, ref offset);

            if (result != null)
            {
                return(result);
            }
            return(Dummy.NamespaceTypeDefinition);
        }
示例#31
0
        /// <summary>
        /// Creates a new instance of the class.
        /// </summary>
        /// <param name="container">The containing assembly.</param>
        /// <param name="typeDef">The CCI type definition.</param>
        internal ScriptType(ScriptAssembly container, INamedTypeDefinition typeDef)
        {
            if (container == null || typeDef == null)
            {
                throw new InvalidOperationException();
            }

            _container = container;
            _cciType   = typeDef;
            _id        = GetKey(this);
        }
示例#32
0
        public TypeIdentifier(INamedTypeDefinition type)
        {
            var module = TypeHelper.GetDefiningUnit(type) as IModule;

            if (module == null || module == Dummy.Module || module == Dummy.Assembly)
            {
                throw new Exception(type.Name.Value + " has invalid container.");
            }
            _moduleName = module.ModuleName.Value;
            _typeName   = type.Name.Value;
        }
示例#33
0
 private IFieldDefinition CreateFunctionPointerField(INamedTypeDefinition typeDefinition, string fieldName)
 {
     return(new FieldDefinition
     {
         IsStatic = true,
         Visibility = TypeMemberVisibility.Private,
         Type = this.platformType.SystemIntPtr,
         ContainingTypeDefinition = typeDefinition,
         Name = this.nameTable.GetNameFor(fieldName)
     });
 }
示例#34
0
        /// <summary>
        /// Finds a type in the given module using the given type name, expressed in C# notion with dots separating both namespaces and types.
        /// If no such type can be found Dummy.NamespaceTypeDefinition is returned.
        /// </summary>
        /// <param name="nameTable">The table used to intern name strings.</param>
        /// <param name="module">The module to search for the type.</param>
        /// <param name="typeName">A string containing the fully qualified type name, using C# formatting conventions.</param>
        public static INamedTypeDefinition FindType(INameTable nameTable, IModule module, string typeName)
        {
            int offset = 0;
            INamedTypeDefinition /*?*/ result = GetType(nameTable, module.UnitNamespaceRoot, typeName, ref offset);

            if (result != null)
            {
                return(result);
            }
            return(Dummy.NamespaceTypeDefinition);
        }
示例#35
0
 private static void AddNestedTypeDocIds(List <string> docIds, INamedTypeDefinition type)
 {
     foreach (var nestedType in type.NestedTypes)
     {
         if (TypeHelper.IsVisibleOutsideAssembly(nestedType))
         {
             docIds.Add(TypeHelper.GetTypeName(nestedType, NameFormattingOptions.DocumentationId));
         }
         AddNestedTypeDocIds(docIds, nestedType);
     }
 }
示例#36
0
 protected override TypeMetricsReport AnalyzeType(INamedTypeDefinition type, PdbReader pdb, IEnumerable<MethodMetricsReport> methods)
 {
     return new TypeMetricsReport
     {
         Name = type.Name(),
         FullName = type.FullName(),
         Namespaces = type.Namespaces(),
         CompilerGenerated = type.IsGeneratedCode(),
         NumberOfNonStaticPublicFields = NumberOfNonStaticPublicFields.Of(type),
         NumberOfMethods = NumberOfMethods.Of(type),
         DirectDependencies = DirectDependencies.Of(type, methods)
     };
 }
        //private IApiInformationProvider m_apiInformation;

        // this method takes into account the FrameworkInternal annotation
        private bool IsTypeExternallyVisible2(INamedTypeDefinition type)
        {
            INamespaceTypeDefinition nsType = type as INamespaceTypeDefinition;
            if (nsType != null)
                return nsType.IsPublic || m_implModel.IsFrameworkInternal(type);

            INestedTypeDefinition nestedType = type as INestedTypeDefinition;
            if (nestedType != null)
            {
                return IsMemberExternallyVisible2(nestedType);
            }

            throw new Exception("We shouldn't ask this question on anything else");
        }
示例#38
0
        public static IEnumerable<string> Of(INamedTypeDefinition type, IEnumerable<MethodMetricsReport> methods)
        {
            var typesOfMethods = GetMethodTypes(methods).ToList();
            var typesOfFields = GetFieldTypes(type.Fields).ToList();
            var typesOfAncestors = GetAncestorTypes(type).ToList();
            var typesOfGenerics = GetGenericConstraints(type).ToList();

            return Enumerable.Empty<string>()
                .Union(type.FullName().Return())
                .Union(typesOfMethods)
                .Union(typesOfFields)
                .Union(typesOfAncestors)
                .Union(typesOfGenerics)
                .ToList();
        }
示例#39
0
 /// <summary>
 /// Returns the data in model file that corresponds to passed CCI2 type
 /// </summary>
 /// <param name="typeDef">The CCI2 type to look up</param>
 /// <returns>TypeElementBase of the data loaded from model file, or null if no entry exists</returns>
 public TypeElement this[INamedTypeDefinition typeDef]
 {
     get
     {
         AssemblyElement assembly;
         string assemblyName = GetAssemblyName(typeDef);
         if (_reader.Model.Assemblies.TryGetValue(assemblyName, out assembly))
         {
             TypeElement type;
             string typeName = _formatter.GetTypeSignature(typeDef);
             if (assembly.Types.TryGetValue(typeName, out type))
                 return type;
         }
         return null;
     }
 }
        private InstrumentAttribute GetAttributeFromType(INamedTypeDefinition type)
        {
            var attributes = type.Attributes ?? Enumerable.Empty<ICustomAttribute>();
            var matchingAttribute = attributes.Where(x => TypeHelper.GetTypeName(x.Type).EndsWith("InstrumentAttribute")).FirstOrDefault();

            InstrumentAttribute toReturn = null;
            Type instrumentAttributeType = typeof(InstrumentAttribute);

            if (matchingAttribute != null)
            {
                toReturn = new InstrumentAttribute();

                foreach (var namedArgument in matchingAttribute.NamedArguments)
                {
                    var matchingProperty = instrumentAttributeType.GetProperty(namedArgument.ArgumentName.Value, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                    if (matchingProperty != null)
                    {
                        matchingProperty.SetValue(toReturn, (namedArgument.ArgumentValue as IMetadataConstant).Value);
                    }
                }
            }

            return toReturn;
        }
示例#41
0
        //
        // Some types may have base types with no default ctors
        // and no ctors themselves.  In those cases, the compiler 
        // cannot instantiate the type without an explicit ctor
        // that calls one of the included base type ctors.
        //
        private void GenerateWorkForCtors(INamedTypeDefinition type, IClosureVisitor visitor)
        {
            if (TypeHelper.BaseClass(type) == null)
                return;

            List<IMethodDefinition> ctors = GetCtors(type, true);
            if (ctors.Count != 0)
                return;

            List<IMethodDefinition> baseCtors = GetCtors(Util.CanonicalizeType(TypeHelper.BaseClass(type)), true);

            if (baseCtors.Count == 0)
                return;

            int nDefaultCtors = 0;
            foreach (IMethodDefinition ctor in baseCtors)
            {
                if (Util.ParameterCount(ctor) == 0)
                {
                    nDefaultCtors++;
                }
            }

            if (nDefaultCtors != 0)
                return;

            // TODO: Shouldn't this be part of implclosure?
            ctors = GetCtors(type, false);
            foreach (IMethodDefinition baseCtor in baseCtors)
            {
                foreach (IMethodDefinition ctor in ctors)
                {
                    if (MethodCallsMethod(ctor, baseCtor))
                    {
                        AddMemberReference(ctor);
                        return;  // @TODO: we may need to add more than just the first one we find..
                    }
                }
            }

            // at this point, no included ctor in the base type is 
            // being called by any of the ctors in the derived type
            // so we have to get a little more creative

            if (ctors.Count > 0)
            {
                IMethodDefinition fallback = FindCalledBaseCtor(ctors[0]);
                if (null != fallback)
                {
                    AddMemberReference(ctors[0]);
                    AddMemberReference(fallback);
                }
            }
        }
示例#42
0
 private List<IMethodDefinition> GetCtors(INamedTypeDefinition type, bool includedCtorOnly)
 {
     List<IMethodDefinition> ctors = new List<IMethodDefinition>();
     foreach (IMethodDefinition meth in type.Methods)
     {
         if (meth.IsConstructor &&
              (_depot.MethodsClosure.ContainsKey(meth.InternedKey) ||
               !includedCtorOnly))
         {
             ctors.Add(meth);
         }
     }
     return ctors;
 }
示例#43
0
        private void GenerateWorkForVirtuals(INamedTypeDefinition type, IClosureVisitor visitor)
        {
            // TODO: can we use INamedTypeDefinition.ExplicitImplementationOverrides instead?
            //foreach (IMethodImplementation methodImpl in type.ExplicitImplementationOverrides)
            //{
            //    ITypeReference declType = methodImpl.ImplementedMethod.ContainingType;
            //    if (_depot.TypesClosure.ContainsKey(declType.ResolvedType.InternedKey))
            //    {
            //        AddMemberReference(methodImpl);
            //    }
            //}


            // TODO: Events?
            foreach (ITypeDefinitionMember member in type.Members)
            {
                IMethodDefinition method = member as IMethodDefinition;
                IPropertyDefinition property = member as IPropertyDefinition;
                IEventDefinition eventDef = member as IEventDefinition;
                if (((method == null) || !method.IsVirtual) &&
                    ((property == null) || !Util.IsPropertyVirtual(property)) &&
                    ((eventDef == null) || !Util.IsEventVirtual(eventDef)))
                {
                    continue;
                }

                //
                // If this or any related member on a base type or interface is in the closure,
                // we must ensure that all related members are also in the closure.
                //

                bool includeRelatedMembers = false;
                List<ITypeDefinitionMember> relatedMembers = Util.FindRelatedMembers(member,
                    delegate (INamedTypeReference myType)
                    {
                        return _depot.TypesClosure.ContainsKey(myType.InternedKey) || !CanInclude(myType);
                    }
                );

                foreach (ITypeDefinitionMember m in relatedMembers)
                {
                    ITypeDefinitionMember specializedMember = Util.CanonicalizeMember(m);
                    if (_depot.ContainsMember(specializedMember) || !CanInclude(Util.CanonicalizeType(specializedMember.ContainingType)))
                        includeRelatedMembers = true;
                }

                if (includeRelatedMembers)
                {
                    foreach (ITypeDefinitionMember m in relatedMembers)
                    {
                        INamedTypeDefinition canonicalDeclaringType = Util.CanonicalizeType(m.ContainingType);

                        if (CanInclude(canonicalDeclaringType))
                        {
                            // TODO: Won't AddMemberReference add the type definition anyway?
                            // Since these members could have resolved to another assembly, check whether we can include them.
                            if (!_depot.TypesClosure.ContainsKey(canonicalDeclaringType.InternedKey))
                                Console.Error.WriteLine("ERROR: declaring type {0} of {1} not present in closure", canonicalDeclaringType, m);
                            AddMemberReference(Util.CanonicalizeMember(m));
                        }
                    }
                }
            }
        }
示例#44
0
        private static void AddTypeAndNestedTypesToTable(Dictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable, INamedTypeDefinition type)
        {
            if (type != null)
            {
                IReadOnlyList<INamedTypeDefinition> seedTypes;
                string docId = TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId);
                if (!typeTable.TryGetValue(docId, out seedTypes))
                {
                    seedTypes = new List<INamedTypeDefinition>(1);
                    typeTable.Add(docId, seedTypes);
                }
                if (!seedTypes.Contains(type))
                    ((List<INamedTypeDefinition>)seedTypes).Add(type);

                foreach (INestedTypeDefinition nestedType in type.NestedTypes)
                {
                    if (TypeHelper.IsVisibleOutsideAssembly(nestedType))
                        AddTypeAndNestedTypesToTable(typeTable, nestedType);
                }
            }
        }
示例#45
0
        private bool WeHidThisType(INamedTypeDefinition type)
        {
            // walk up all the declaring types to see if we hid one of them
            INamedTypeDefinition curType = type;
            while (curType != null && curType != Dummy.Type)
            {
                if (ShouldHideType(curType))
                    return true;

                INestedTypeDefinition nestedType = curType as INestedTypeDefinition;
                if (nestedType != null)
                    curType = Util.CanonicalizeType(nestedType.ContainingType);
                else
                    curType = null;
            }

            return false;
        }
示例#46
0
 private bool IsHiddenTypeCandidate(INamedTypeDefinition type)
 {
     return !Util.IsApi(GetIncludeStatus(type)) && Util.IsTypeExternallyVisible(type);
 }
示例#47
0
 /// <summary>
 /// Traverses the children of the named type definition.
 /// </summary>
 public virtual void TraverseChildren(INamedTypeDefinition namedTypeDefinition)
 {
     Contract.Requires(namedTypeDefinition != null);
       this.TraverseChildren((ITypeDefinition)namedTypeDefinition);
 }
        private void AddMembersWithExternalRelatives(INamedTypeDefinition type)
        {
            foreach (ITypeDefinitionMember member in type.Members)
            {
                List<ITypeDefinitionMember> members = Util.FindRelatedExternalMembers(member, m_implModel.CanInclude);

                if (members.Count != 0)
                {
                    // This member is related to an external member, so we need to add it here. 
                    AddMemberReference(member);
                    // TODO: Only add if the related member is abstract?
                }
            }
        }
示例#49
0
 /// <summary>
 /// Performs some computation with the given named type definition.
 /// </summary>
 public void Visit(INamedTypeDefinition namedTypeDefinition)
 {
     this.Visit((ITypeDefinition)namedTypeDefinition);
 }
示例#50
0
            // This shouldn't be necessary, but CCI is putting a nonzero TypeDefId in the ExportedTypes table
            // for nested types if NamespaceAliasForType.AliasedType is set to an ITypeDefinition
            // so we make an ITypeReference copy as a workaround.
            private static INamedTypeReference ConvertDefinitionToReferenceIfTypeIsNested(INamedTypeDefinition typeDef, IMetadataHost host)
            {
                var nestedTypeDef = typeDef as INestedTypeDefinition;
                if (nestedTypeDef == null)
                    return typeDef;

                var typeRef = new NestedTypeReference();
                typeRef.Copy(nestedTypeDef, host.InternFactory);
                return typeRef;
            }
示例#51
0
            private void AddTypeForward(Assembly assembly, INamedTypeDefinition seedType)
            {
                var alias = new NamespaceAliasForType();
                alias.AliasedType = ConvertDefinitionToReferenceIfTypeIsNested(seedType, _seedHost);
                alias.IsPublic = true;

                if (assembly.ExportedTypes == null)
                    assembly.ExportedTypes = new List<IAliasForType>();
                assembly.ExportedTypes.Add(alias);
            }
示例#52
0
 public CalledBaseCtorFinder(IMethodDefinition ctor)
 {
     _targetType = Util.CanonicalizeType(TypeHelper.BaseClass(Util.ContainingTypeDefinition(ctor)));
     _baseCtor = null;
 }
示例#53
0
        private IncludeStatus GetIncludeStatus(INamedTypeDefinition type)
        {
            ThinType modelType;
            if (!_rootTypes.TryGetValue(type, out modelType))
            {
                if (_depot.TypesClosure.ContainsKey(type.InternedKey))
                {
                    // Special case ImplRoot
                    // TODO: Visitor should set status instead.
                    if (_closureStatus == IncludeStatus.ApiRoot && !Util.IsTypeExternallyVisible(type))
                    {
                        return IncludeStatus.ImplRoot;
                    }

                    return _closureStatus;
                }

                return IncludeStatus.Exclude;
            }

            return modelType.IncludeStatus;
        }
示例#54
0
 /// <summary>
 /// Given a parent type and mangled type name of the nested type, this method resolves it.
 /// </summary>
 /// <param name="parentType"></param>
 /// <param name="typeName"></param>
 /// <returns></returns>
 internal INamedTypeDefinition/*?*/ ResolveNestedTypeDefinition(INamedTypeDefinition parentType, IName typeName) {
   var mdParentType = parentType as TypeBase;
   if (mdParentType != null) {
     uint typeToken = this.NestedTypeTokenTable.Find(TokenTypeIds.TypeDef | mdParentType.TypeDefRowId, (uint)typeName.UniqueKey);
     if (typeToken == 0 || ((typeToken & TokenTypeIds.TokenTypeMask) != TokenTypeIds.TypeDef)) return null;
     return this.GetTypeDefinitionAtRowWorker(typeToken & TokenTypeIds.RIDMask);
   }
   ushort genericParamCount;
   string unmangledTypeName;
   TypeCache.SplitMangledTypeName(typeName.Value, out unmangledTypeName, out genericParamCount);
   return TypeHelper.GetNestedType(parentType, this.NameTable.GetNameFor(unmangledTypeName), genericParamCount);
 }
示例#55
0
 private bool ShouldHideType(INamedTypeDefinition type)
 {
     return IsHiddenTypeCandidate(type);
 }
示例#56
0
 public bool /*IApiInformationProvider.*/IsFrameworkInternal(INamedTypeDefinition type)
 {
     return _rootTypes.ContainsKey(type) && _rootTypes[type].IncludeStatus == IncludeStatus.ApiFxInternal;
 }
示例#57
0
 private bool TypeIsVisibleInApi(INamedTypeDefinition type)
 {
     // either we hid it or its already hidden
     // @TODO: what about private types?
     return !WeHidThisType(type) && Util.IsTypeExternallyVisible(type);
 }
示例#58
0
 public bool ContainsType(INamedTypeDefinition typeDef)
 {
     return TypesClosure.ContainsKey(typeDef.InternedKey);
 }
示例#59
0
 private void GenerateWorkForVirtuals(IClosureVisitor visitor)
 {
     INamedTypeDefinition[] defs = new INamedTypeDefinition[_depot.TypesClosure.Values.Count];
     _depot.TypesClosure.Values.CopyTo(defs, 0);
     foreach (INamedTypeDefinition type in defs)
     {
         GenerateWorkForVirtuals(type, visitor);
     }
 }
示例#60
0
 private static void AddNestedTypeDocIds(List<string> docIds, INamedTypeDefinition type)
 {
     foreach (var nestedType in type.NestedTypes)
     {
         if (TypeHelper.IsVisibleOutsideAssembly(nestedType))
             docIds.Add(TypeHelper.GetTypeName(nestedType, NameFormattingOptions.DocumentationId));
         AddNestedTypeDocIds(docIds, nestedType);
     }
 }