/// <summary> /// Transform open generic types to closed instantiation using context information. /// As an example, if B{T} inherits from A{T}, running it with B{C} as context and A{B.T} as type, ti will return A{C}. /// </summary> public static TypeReference Process(TypeReference context, TypeReference type) { if (type == null) return null; var genericInstanceTypeContext = context as GenericInstanceType; if (genericInstanceTypeContext == null) return type; if (genericInstanceTypeContext.ContainsGenericParameter()) return type; // Build dictionary that will map generic type to their real implementation type var resolvedType = context.Resolve(); var genericTypeMapping = new Dictionary<TypeReference, TypeReference>(); for (int i = 0; i < resolvedType.GenericParameters.Count; ++i) { var genericParameter = context.GetElementType().Resolve().GenericParameters[i]; genericTypeMapping.Add(genericParameter, genericInstanceTypeContext.GenericArguments[i]); } var visitor = new ResolveGenericsVisitor(genericTypeMapping); var result = visitor.VisitDynamic(type); // Make sure type is closed now if (result.ContainsGenericParameter()) throw new InvalidOperationException("Unsupported generic resolution."); return result; }
public virtual TypeReference GetSerializer(TypeReference objectType) { // Check if objectType matches genericSerializableType. // Note: Not perfectly valid but hopefully it should be fast enough. if (objectType.IsGenericInstance && checkInterfaces) { if (objectType.GetElementType().Resolve().Interfaces.Any(x => x.IsGenericInstance && x.GetElementType().FullName == genericSerializableType.FullName)) return CreateSerializer(objectType); } if (objectType.IsGenericInstance && objectType.GetElementType().FullName == genericSerializableType.FullName) return CreateSerializer(objectType); return null; }
public string create(TypeReference typeRef) { if (typeRef.IsGenericInstance) { var git = (GenericInstanceType)typeRef; if (git.ElementType.FullName == "System.Nullable`1" && git.GenericArguments.Count == 1 && git.GenericArguments[0] != null) { typeRef = git.GenericArguments[0]; } } string prefix = getPrefix(typeRef); var elementType = typeRef.GetElementType(); if (elementType is GenericParameter) return genericParamNameCreator.create(); NameCreator nc; var typeFullName = typeRef.FullName; if (typeNames.TryGetValue(typeFullName, out nc)) return nc.create(); var name = elementType.FullName; var parts = name.Replace('/', '.').Split(new char[] { '.' }); var newName = parts[parts.Length - 1]; int tickIndex = newName.LastIndexOf('`'); if (tickIndex > 0) newName = newName.Substring(0, tickIndex); return addTypeName(typeFullName, newName, prefix).create(); }
public static TypeDefinition Resolve(IAssemblyResolver resolver, TypeReference type) { type = type.GetElementType (); var scope = type.Scope; switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: var assembly = resolver.Resolve ((AssemblyNameReference) scope); if (assembly == null) return null; return GetType (assembly.MainModule, type); case MetadataScopeType.ModuleDefinition: return GetType ((ModuleDefinition) scope, type); case MetadataScopeType.ModuleReference: var modules = type.Module.Assembly.Modules; var module_ref = (ModuleReference) scope; for (int i = 0; i < modules.Count; i++) { var netmodule = modules [i]; if (netmodule.Name == module_ref.Name) return GetType (netmodule, type); } break; } throw new NotSupportedException (); }
public override void VisitTypeReference(TypeReference type) { if (type.GetElementType() is GenericParameter) return; var scope = GetAssemblyNameReference(type.Scope); MapReference(scope, type); }
private static bool IsStringOrSBuilder (TypeReference reference) { switch (reference.GetElementType ().FullName) { case "System.String": case "System.Text.StringBuilder": return true; default: return false; } }
/// <summary> /// Default ctor /// </summary> public InstanceOfConditionInclude(TypeReference instanceOfCondition) { if (instanceOfCondition == null) throw new ArgumentNullException("instanceOfCondition"); this.instanceOfCondition = instanceOfCondition.GetElementType().Resolve(); if (this.instanceOfCondition == null) throw new CompilerException(string.Format("Cannot resolve InstanceOfCondition {0}", instanceOfCondition.FullName)); var attr = this.instanceOfCondition.GetDexOrJavaImportAttribute(); className = (attr != null) ? (string)attr.ConstructorArguments[0].Value : null; }
public static bool IsSimilarType(Type thisType, Mono.Cecil.TypeReference type) { // Ignore any 'ref' types if (thisType.IsByRef) { thisType = thisType.GetElementType(); } if (type.IsByReference) { if (type.IsArray) { var array_type = type as ArrayType; type = array_type.ElementType; } else { type = type.GetElementType(); } } // Handle array types if (thisType.IsArray && type.IsArray) { Mono.Cecil.ArrayType at = type as Mono.Cecil.ArrayType; // Dimensions must be the same. if (thisType.GetArrayRank() != at.Rank) { return(false); } // Base type of array must be the same. var array_type = type as ArrayType; return(IsSimilarType(thisType.GetElementType(), array_type.ElementType)); } if (thisType.IsArray && !type.IsArray) { return(false); } if (type.IsArray && !thisType.IsArray) { return(false); } // If the types are identical, or they're both generic parameters // or the special 'T' type, treat as a match // Match also if thisType is generic and type can be unified with thisType. if (thisType.Name == type.Name || // identical types. ((thisType.IsGenericParameter || thisType == typeof(T)) && (type.IsGenericParameter || type.Name.Equals("T"))) || // using "T" as matching generic type. IsUnifiableMono(thisType, type)) { return(true); } return(false); }
public static void DuplicateReturnValue(List<Instruction> instructions, TypeReference methodReturnType) { // Duplicate the stack (this should be the return value) instructions.Add(Instruction.Create(OpCodes.Dup)); if (methodReturnType != null && methodReturnType.GetElementType().IsGenericParameter) { // Generic parameters must be boxed before access instructions.Add(Instruction.Create(OpCodes.Box, methodReturnType)); } }
public static int GetArrayInfo(Mono.Cecil.TypeReference type, out Mono.Cecil.TypeReference elementType) { elementType = type; int rank = 0; while (type.IsArray) { rank++; elementType = type = type.GetElementType(); } return(rank); }
public IEnumerable<TypeReference> EnumerateSubTypesFromSerializer(TypeReference serializerType) { // Check if serializer type name matches if (serializerType.IsGenericInstance && serializerType.GetElementType().FullName == genericSerializerTypeFullName) { if (genericSerializableType != null) // Transforms genericSerializerType{T1, T2} into genericSerializableType{T1, T2} return Enumerable.Repeat(genericSerializableType.MakeGenericType(((GenericInstanceType)serializerType).GenericArguments.ToArray()), 1); else // Transforms genericSerializerType{T1, T2} into T1, T2 return ((GenericInstanceType)serializerType).GenericArguments; } return null; }
/// <summary> /// Default ctor /// </summary> public InstanceOfConditionInclude(TypeReference instanceOfCondition) { if (instanceOfCondition == null) { throw new ArgumentNullException("instanceOfCondition"); } this.instanceOfCondition = instanceOfCondition.GetElementType().Resolve(); if (this.instanceOfCondition == null) { throw new CompilerException(string.Format("Cannot resolve InstanceOfCondition {0}", instanceOfCondition.FullName)); } var attr = this.instanceOfCondition.GetDexOrJavaImportAttribute(); className = (attr != null) ? (string)attr.ConstructorArguments[0].Value : null; }
public TypeDefinition Resolve (TypeReference type) { type = type.GetElementType (); if (type is TypeDefinition) return (TypeDefinition) type; AssemblyNameReference reference = type.Scope as AssemblyNameReference; if (reference != null) { AssemblyDefinition assembly = Resolve (reference); return assembly.MainModule.GetType (type.FullName); } ModuleDefinition module = type.Scope as ModuleDefinition; if (module != null) return module.GetType (type.FullName); throw new NotImplementedException (); }
public virtual TypeDefinition Resolve(TypeReference type) { Mixin.CheckType(type); type = type.GetElementType(); var scope = type.Scope; if (scope == null) { return(null); } switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: var assembly = assembly_resolver.Resolve((AssemblyNameReference)scope); if (assembly == null) { return(null); } return(GetType(assembly.MainModule, type)); case MetadataScopeType.ModuleDefinition: return(GetType((ModuleDefinition)scope, type)); case MetadataScopeType.ModuleReference: var modules = type.Module.Assembly.Modules; var module_ref = (ModuleReference)scope; for (int i = 0; i < modules.Count; i++) { var netmodule = modules [i]; if (netmodule.Name == module_ref.Name) { return(GetType(netmodule, type)); } } break; } throw new NotSupportedException(); }
public virtual TypeDefinition Resolve(TypeReference type) { Mixin.CheckType(type); type = type.GetElementType(); IMetadataScope scope = type.Scope; if (scope == null) { return(null); } switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: { AssemblyDefinition assemblyDefinition = assembly_resolver.Resolve((AssemblyNameReference)scope); if (assemblyDefinition == null) { return(null); } return(GetType(assemblyDefinition.MainModule, type)); } case MetadataScopeType.ModuleDefinition: return(GetType((ModuleDefinition)scope, type)); case MetadataScopeType.ModuleReference: { Collection <ModuleDefinition> modules = type.Module.Assembly.Modules; ModuleReference moduleReference = (ModuleReference)scope; for (int i = 0; i < modules.Count; i++) { ModuleDefinition moduleDefinition = modules[i]; if (moduleDefinition.Name == moduleReference.Name) { return(GetType(moduleDefinition, type)); } } break; } } throw new NotSupportedException(); }
public static bool AreEqual(TypeReference firstType, TypeReference secondType) { if (firstType.GetFriendlyFullName(null) == secondType.GetFriendlyFullName(null)) { return true; } TypeReference firstTypeRef = firstType.GetElementType(); TypeReference secondTypeRef = secondType.GetElementType(); if (firstTypeRef.HasGenericParameters && secondTypeRef.HasGenericParameters) { if (firstTypeRef.FullName == secondTypeRef.FullName && firstTypeRef.GenericParameters.Count == secondTypeRef.GenericParameters.Count) { return true; } } return false; }
private string GetMonoEmbeddedFullTypeNameFor(TypeReference type) { TypeSpecification typeSpecification = type as TypeSpecification; string fullName; if (typeSpecification != null && typeSpecification.IsRequiredModifier) { fullName = typeSpecification.ElementType.FullName; } else { if (type.IsRequiredModifier) { fullName = type.GetElementType().FullName; } else { fullName = type.FullName; } } return fullName.Replace('/', '+').Replace('<', '[').Replace('>', ']'); }
static void AppendType(TypeReference type, StringBuilder name, bool fq_name, bool top_level) { var element_type = type.GetElementType(); var declaring_type = element_type.DeclaringType; if (declaring_type != null) { AppendType(declaring_type, name, false, top_level); name.Append('+'); } var @namespace = type.Namespace; if (!string.IsNullOrEmpty(@namespace)) { AppendNamePart(@namespace, name); name.Append('.'); } AppendNamePart(element_type.Name, name); if (!fq_name) { return; } if (type.IsTypeSpecification()) { AppendTypeSpecification((TypeSpecification)type, name); } if (RequiresFullyQualifiedName(type, top_level)) { name.Append(", "); name.Append(GetScopeFullName(type)); } }
/*Telerik Authorship*/ private TypeReference DeepCloneType(TypeReference toClone) { if (toClone is ByReferenceType) { TypeReference clonedElementType = DeepCloneType((toClone as ByReferenceType).ElementType); return(new ByReferenceType(clonedElementType)); } if (toClone is GenericInstanceType) { GenericInstanceType original = toClone as GenericInstanceType; // for proof of concept - should clone all types for consistency GenericInstanceType result = new GenericInstanceType(toClone.GetElementType()); foreach (TypeReference argument in (toClone as GenericInstanceType).GenericArguments) { TypeReference clonedArgument = DeepCloneType(argument); // clone the arguments as well, as they might be another GenericInstanceTypes result.GenericArguments.Add(clonedArgument); } result.PostionToArgument.Clear(); return(result); } return(toClone); }
public string create(TypeReference typeRef) { if (typeRef.IsGenericInstance) { var git = (GenericInstanceType)typeRef; if (git.ElementType.FullName == "System.Nullable`1" && git.GenericArguments.Count == 1 && git.GenericArguments[0] != null) { typeRef = git.GenericArguments[0]; } } string prefix = getPrefix(typeRef); var elementType = typeRef.GetElementType(); if (elementType is GenericParameter) return genericParamNameCreator.create(); NameCreator nc; var typeFullName = typeRef.FullName; if (typeNames.TryGetValue(typeFullName, out nc)) return nc.create(); var fullName = elementType.FullName; string shortName; var dict = prefix == "" ? fullNameToShortName : fullNameToShortNamePrefix; if (!dict.TryGetValue(fullName, out shortName)) { fullName = fullName.Replace('/', '.'); int index = fullName.LastIndexOf('.'); shortName = index > 0 ? fullName.Substring(index + 1) : fullName; index = shortName.LastIndexOf('`'); if (index > 0) shortName = shortName.Substring(0, index); } return addTypeName(typeFullName, shortName, prefix).create(); }
static void AddType (HashSet<TypeReference> typeset, TypeReference type) { // we're interested in the array element type, not the array itself if (type.IsArray) type = type.GetElementType (); // only keep stuff from this assembly, which means we have a TypeDefinition (not a TypeReference) // and types that are not visible outside the assembly (since this is what we check for) TypeDefinition td = (type as TypeDefinition); if ((td != null) && !td.IsVisible ()) typeset.Add (type); }
public static Type CreateBlittableTypeMono(Mono.Cecil.TypeReference hostType, bool declare_parent_chain) { try { Mono.Cecil.TypeDefinition td = hostType.Resolve(); String name; SR.TypeFilter tf; // Declare parent chain since TypeBuilder works top down not bottom up. if (declare_parent_chain) { name = hostType.FullName; name = name.Replace('+', '.'); tf = new SR.TypeFilter((Type t, object o) => { return(t.FullName == name); }); } else { name = hostType.Name; tf = new SR.TypeFilter((Type t, object o) => { return(t.Name == name); }); } // Find if blittable type for hostType was already performed. Data data = new Data(); Type[] types = data.mb.FindTypes(tf, null); // If blittable type was not created, create one with all fields corresponding // to that in host, with special attention to arrays. if (types.Length == 0) { if (hostType.IsArray) { // Recurse Type elementType = CreateBlittableTypeMono(hostType.GetElementType(), true); object array_obj = Array.CreateInstance(elementType, 0); Type array_type = array_obj.GetType(); TypeBuilder tb = null; tb = data.mb.DefineType( array_type.Name, SR.TypeAttributes.Public | SR.TypeAttributes.Sealed | SR.TypeAttributes.SequentialLayout | SR.TypeAttributes.Serializable, typeof(ValueType)); return(tb.CreateType()); } else if (Campy.Types.Utils.ReflectionCecilInterop.IsStruct(hostType) || !hostType.IsValueType) { TypeBuilder tb = null; tb = data.mb.DefineType( name, SR.TypeAttributes.Public | SR.TypeAttributes.Sealed | SR.TypeAttributes.SequentialLayout | SR.TypeAttributes.Serializable, typeof(ValueType)); var fields = td.Fields; foreach (var field in fields) { if (field.FieldType.IsArray) { // Convert byte, int, etc., in host type to pointer in blittable type. // With array, we need to also encode the length. tb.DefineField(field.Name, typeof(IntPtr), SR.FieldAttributes.Public); tb.DefineField(field.Name + "Len0", typeof(Int32), SR.FieldAttributes.Public); } else { // For non-array type fields, just define the field as is. tb.DefineField(field.Name, Campy.Types.Utils.ReflectionCecilInterop.ConvertToSystemReflectionType(field.FieldType), SR.FieldAttributes.Public); } } return(tb.CreateType()); } else { return(null); } } else { return(types[0]); } } catch { return(null); } }
private TypeReference ProcessTypeReference(TypeReference type, IGenericParameterProvider owner) { if (type == null) return null; // ref types if (type is ByReferenceType) { var elementType = ProcessTypeReference(type.GetElementType(), owner); if (elementType != type.GetElementType()) type = new ByReferenceType(elementType); return type; } // Generic MVar/Var if (type is GenericParameter) { var genericParameter = (GenericParameter)type; if ((genericParameter.MetadataType == MetadataType.MVar || genericParameter.MetadataType == MetadataType.Var) && genericParameter.Owner is MethodReference) { if (genericParameter.Owner != null && owner != null) { return owner.GenericParameters.Concat(genericParameter.Owner.GenericParameters).First(x => x.Name == type.Name); } } return type; } // Is it an async-related type? var asyncBridgeType = asyncBridgeAssembly.MainModule.GetTypeResolved(type.Namespace, type.Name); if (asyncBridgeType == null) return type; // First work on inner TypeReference if there is a GenericInstanceType around it. var genericInstanceType = type as GenericInstanceType; if (genericInstanceType != null) { type = genericInstanceType.ElementType; } var newType = assembly.MainModule.Import(new TypeReference(type.Namespace, type.Name, asyncBridgeAssembly.MainModule, asyncBridgeAssembly.Name, type.IsValueType)); for (int i = 0; i < type.GenericParameters.Count; ++i) { newType.GenericParameters.Add(new GenericParameter(type.GenericParameters[i].Name, newType)); foreach (var constraint in type.GenericParameters[i].Constraints) newType.GenericParameters[i].Constraints.Add(ProcessTypeReference(constraint, newType)); } if (genericInstanceType != null) { var newGenericType = new GenericInstanceType(newType); foreach (var genericArgument in genericInstanceType.GenericArguments) { newGenericType.GenericArguments.Add(ProcessTypeReference(genericArgument, newGenericType)); } newType = newGenericType; } return newType; }
private TypeReference ReadTypeSignature(ElementType etype) { switch (etype) { case ElementType.Void: { return(this.TypeSystem.Void); } case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.String: case ElementType.Void | ElementType.Boolean | ElementType.Char | ElementType.I1 | ElementType.U1 | ElementType.I2 | ElementType.U2 | ElementType.ByRef | ElementType.ValueType | ElementType.Class | ElementType.Var | ElementType.Array | ElementType.GenericInst | ElementType.TypedByRef: case ElementType.Boolean | ElementType.I4 | ElementType.I8 | ElementType.ByRef | ElementType.Class | ElementType.I: { return(this.GetPrimitiveType(etype)); } case ElementType.Ptr: { return(new PointerType(this.ReadTypeSignature())); } case ElementType.ByRef: { return(new ByReferenceType(this.ReadTypeSignature())); } case ElementType.ValueType: { TypeReference typeDefOrRef = this.GetTypeDefOrRef(this.ReadTypeTokenSignature()); typeDefOrRef.IsValueType = true; return(typeDefOrRef); } case ElementType.Class: { return(this.GetTypeDefOrRef(this.ReadTypeTokenSignature())); } case ElementType.Var: { return(this.GetGenericParameter(GenericParameterType.Type, base.ReadCompressedUInt32())); } case ElementType.Array: { return(this.ReadArrayTypeSignature()); } case ElementType.GenericInst: { TypeReference typeReference = this.GetTypeDefOrRef(this.ReadTypeTokenSignature()); GenericInstanceType genericInstanceType = new GenericInstanceType(typeReference); this.ReadGenericInstanceSignature(typeReference, genericInstanceType); if (base.ReadByte() == 17) { genericInstanceType.IsValueType = true; typeReference.GetElementType().IsValueType = true; } return(genericInstanceType); } case ElementType.TypedByRef: { return(this.TypeSystem.TypedReference); } case ElementType.I: { return(this.TypeSystem.IntPtr); } case ElementType.U: { return(this.TypeSystem.UIntPtr); } case ElementType.FnPtr: { FunctionPointerType functionPointerType = new FunctionPointerType(); this.ReadMethodSignature(functionPointerType); return(functionPointerType); } case ElementType.Object: { return(this.TypeSystem.Object); } case ElementType.SzArray: { return(new ArrayType(this.ReadTypeSignature())); } case ElementType.MVar: { return(this.GetGenericParameter(GenericParameterType.Method, base.ReadCompressedUInt32())); } case ElementType.CModReqD: { return(new RequiredModifierType(this.GetTypeDefOrRef(this.ReadTypeTokenSignature()), this.ReadTypeSignature())); } case ElementType.CModOpt: { return(new OptionalModifierType(this.GetTypeDefOrRef(this.ReadTypeTokenSignature()), this.ReadTypeSignature())); } default: { if (etype == ElementType.Sentinel) { return(new SentinelType(this.ReadTypeSignature())); } if (etype == ElementType.Pinned) { return(new PinnedType(this.ReadTypeSignature())); } return(this.GetPrimitiveType(etype)); } } }
static Type resolve(TypeReference typeReference) { if (typeReference == null) return null; var elemType = typeReference.GetElementType(); var resolver = getAssemblyResolver(elemType); var resolvedType = resolver.resolve(elemType); if (resolvedType != null) return fixType(typeReference, resolvedType); throw new ApplicationException(string.Format("Could not resolve type {0} ({1:X8}) in assembly {2}", typeReference, typeReference.MetadataToken.ToUInt32(), resolver)); }
public static bool TypesAreAssignable(TypeReference target, TypeReference source) { bool result; // All values are assignable to object if (target.FullName == "System.Object") return true; int targetDepth, sourceDepth; if (TypesAreEqual(FullyDereferenceType(target, out targetDepth), FullyDereferenceType(source, out sourceDepth))) { if (targetDepth == sourceDepth) return true; } // Complex hack necessary because System.Array and T[] do not implement IEnumerable<T> var targetGit = target as GenericInstanceType; if ( (targetGit != null) && (targetGit.Name == "IEnumerable`1") && source.IsArray && (targetGit.GenericArguments.FirstOrDefault() == source.GetElementType()) ) return true; var cacheKey = new Tuple<string, string>(target.FullName, source.FullName); if (TypeAssignabilityCache.TryGetValue(cacheKey, out result)) return result; var dSource = GetTypeDefinition(source); if (dSource == null) result = false; else if (TypesAreEqual(target, dSource)) result = true; else if ((dSource.BaseType != null) && TypesAreAssignable(target, dSource.BaseType)) result = true; else { foreach (var iface in dSource.Interfaces) { if (TypesAreAssignable(target, iface)) { result = true; break; } } } TypeAssignabilityCache[cacheKey] = result; return result; }
protected override TypeReference GetElementType(TypeReference type) { return type.GetElementType (); }
private static bool IsRedirectedType(TypeReference type) { var typeRefProjection = type.GetElementType().projection as TypeReferenceProjection; return(typeRefProjection != null && typeRefProjection.Treatment == TypeReferenceTreatment.UseProjectionInfo); }
public static TypeDefinition ToTypeDefinition(TypeReference reference, IEmitter emitter) { if (reference == null) { return null; } try { if (reference.IsGenericInstance) { reference = reference.GetElementType(); } string key = BridgeTypes.GetTypeDefinitionKey(reference.FullName); if (emitter.TypeDefinitions.ContainsKey(reference.FullName)) { return emitter.TypeDefinitions[reference.FullName]; } return reference.Resolve(); } catch { } return null; }
/*Telerik Authorship*/ internal TypeDefinition Resolve(TypeReference type, ICollection <string> visitedDlls) { if (type == null) { throw new ArgumentNullException("type"); } // TODO: The following code must be uncommented when bug 284860 (the one with the Resolver) is fixed. //if (type is ArrayType) //{ // type = type.Module.TypeSystem.LookupType("System", "Array"); //} //else //{ type = type.GetElementType(); //} IMetadataScope scope = type.Scope; if (scope == null) { return(null); } switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: /*Telerik Authorship*/ TargetArchitecture architecture = type.Module.GetModuleArchitecture(); var assembly = assembly_resolver.Resolve((AssemblyNameReference)scope, type.Module.ModuleDirectoryPath, architecture); if (assembly == null) { return(null); } /*Telerik Authorship*/ if (visitedDlls.Contains(assembly.MainModule.FilePath)) { return(null); } visitedDlls.Add(assembly.MainModule.FilePath); return(GetType(assembly.MainModule, type, visitedDlls)); case MetadataScopeType.ModuleDefinition: ModuleDefinition theModule = (ModuleDefinition)scope; /*Telerik Authorship*/ if (visitedDlls.Contains(theModule.FilePath)) { return(null); } visitedDlls.Add(theModule.FilePath); return(GetType(theModule, type, visitedDlls)); case MetadataScopeType.ModuleReference: var modules = type.Module.Assembly.Modules; var module_ref = (ModuleReference)scope; for (int i = 0; i < modules.Count; i++) { var netmodule = modules[i]; if (netmodule.Name == module_ref.Name) { /*Telerik Authorship*/ if (visitedDlls.Contains(netmodule.FilePath)) { return(null); } visitedDlls.Add(netmodule.FilePath); return(GetType(netmodule, type, visitedDlls)); } } break; } throw new NotSupportedException(); }
internal IType GetType(object token, IType contextType, IMethod contextMethod) { int hash = token.GetHashCode(); IType res; if (mapTypeToken.TryGetValue(hash, out res)) { return(res); } Mono.Cecil.ModuleDefinition module = null; KeyValuePair <string, IType>[] genericArguments = null; string typename = null; string scope = null; bool dummyGenericInstance = false; if (token is Mono.Cecil.TypeDefinition) { Mono.Cecil.TypeDefinition _def = (token as Mono.Cecil.TypeDefinition); module = _def.Module; typename = _def.FullName; scope = GetAssemblyName(_def.Scope); } else if (token is Mono.Cecil.TypeReference) { Mono.Cecil.TypeReference _ref = (token as Mono.Cecil.TypeReference); if (_ref.IsGenericParameter) { IType t = null; if (contextType != null) { t = contextType.FindGenericArgument(_ref.Name); } if (t == null && contextMethod != null && contextMethod is ILMethod) { t = ((ILMethod)contextMethod).FindGenericArgument(_ref.Name); } return(t); } if (_ref.IsByReference) { var t = GetType(_ref.GetElementType(), contextType, contextMethod); if (t != null) { res = t.MakeByRefType(); if (res is ILType) { ///Unify the TypeReference ((ILType)res).TypeReference = _ref; } mapTypeToken[hash] = res; if (!string.IsNullOrEmpty(res.FullName)) { mapType[res.FullName] = res; } return(res); } return(null); } if (_ref.IsArray) { var t = GetType(_ref.GetElementType(), contextType, contextMethod); if (t != null) { res = t.MakeArrayType(); if (res is ILType) { ///Unify the TypeReference ((ILType)res).TypeReference = _ref; } mapTypeToken[hash] = res; if (!string.IsNullOrEmpty(res.FullName)) { mapType[res.FullName] = res; } return(res); } return(t); } module = _ref.Module; if (_ref.IsGenericInstance) { GenericInstanceType gType = (GenericInstanceType)_ref; typename = gType.ElementType.FullName; scope = GetAssemblyName(gType.ElementType.Scope); TypeReference tr = gType.ElementType; genericArguments = new KeyValuePair <string, IType> [gType.GenericArguments.Count]; for (int i = 0; i < genericArguments.Length; i++) { string key = tr.GenericParameters[i].Name; IType val; if (gType.GenericArguments[i].IsGenericParameter) { val = contextType.FindGenericArgument(gType.GenericArguments[i].Name); dummyGenericInstance = true; if (val == null) { if (contextMethod != null && contextMethod is ILMethod) { val = ((ILMethod)contextMethod).FindGenericArgument(gType.GenericArguments[i].Name); } else { return(null); } } } else { val = GetType(gType.GenericArguments[i], contextType, contextMethod); } if (val != null) { genericArguments[i] = new KeyValuePair <string, IType>(key, val); } else { genericArguments = null; break; } } } else { typename = _ref.FullName; scope = GetAssemblyName(_ref.Scope); } } else { throw new NotImplementedException(); } res = GetType(typename); if (res == null) { typename = typename.Replace("/", "+"); res = GetType(typename); } if (res == null && scope != null) { res = GetType(typename + ", " + scope); } if (res == null) { if (scope != null) { string aname = scope.Split(',')[0]; foreach (var i in loadedAssemblies) { if (aname == i.GetName().Name) { res = GetType(typename + ", " + i.FullName); if (res != null) { break; } } } } if (res == null) { foreach (var j in loadedAssemblies) { res = GetType(typename + ", " + j.FullName); if (res != null) { break; } } } if (res != null && scope != null) { mapType[typename + ", " + scope] = res; } } if (res == null) { throw new KeyNotFoundException("Cannot find Type:" + typename); } if (genericArguments != null) { res = res.MakeGenericInstance(genericArguments); if (!dummyGenericInstance && res is ILType) { ((ILType)res).TypeReference = (TypeReference)token; } if (!string.IsNullOrEmpty(res.FullName)) { mapType[res.FullName] = res; } } if (!dummyGenericInstance) { mapTypeToken[hash] = res; } return(res); }
public string newName(TypeReference typeRef) { var elementType = typeRef.GetElementType(); if (elementType is GenericParameter) return genericParamNameCreator.newName(); var name = elementType.FullName; INameCreator nc; if (typeNames.TryGetValue(name, out nc)) return nc.newName(); var parts = name.Replace('/', '.').Split(new char[] { '.' }); var newName = parts[parts.Length - 1]; int tickIndex = newName.LastIndexOf('`'); if (tickIndex > 0) newName = newName.Substring(0, tickIndex); return insertTypeName(name, newName).newName(); }
private static bool AreSameElementTypes (TypeReference a, TypeReference b) { return a.GetElementType ().FullName == b.GetElementType ().FullName; }
public override TypeReference GetElementType() { return(element_type.GetElementType()); }
public BridgeType Get(TypeReference type, bool safe = false) { var name = type.FullName; if (type.IsGenericInstance) { /*try { name = type.Resolve().FullName; } catch { try { var elementType = type.GetElementType(); name = elementType != null ? elementType.FullName : type.FullName; } catch { name = type.FullName; } }*/ name = type.GetElementType().FullName; } var bridgeType = typesOfFullName_.GetOrDefault(name); if(bridgeType != null) { return bridgeType; } if (!safe) { throw new Exception("Cannot find type: " + type.FullName); } return null; }
/// <summary> /// Checks if <paramref name="supposedSubType"/> is subtype of <paramref name="type"/>. /// </summary> /// <param name="type">The supposed parent type.</param> /// <param name="supposedSubType">The supposed inheriting type.</param> /// <returns>Returns True if <paramref name="supposedSubType"/> is subtype of <paramref name="type"/>.</returns> private bool IsSubtype(TypeReference type, TypeReference supposedSubType) { type = RemoveModifiers(type); supposedSubType = RemoveModifiers(supposedSubType); if (supposedSubType.GetFriendlyFullName(null) == type.GetFriendlyFullName(null) || type.FullName == "System.Object") { ///The types are the same, or the check is if a type inherits Object return true; } if (IsArrayAssignable(type, supposedSubType)) { return true; } TypeDefinition supposedSubTypeDef = supposedSubType.Resolve(); if (supposedSubTypeDef == null) { //happens with generics only; return true; } if (type is GenericInstanceType) { type = type.GetElementType(); } while (supposedSubTypeDef != null) { if (type.GetFriendlyFullName(null) == supposedSubTypeDef.GetFriendlyFullName(null)) { ///Must be here, since mono fails on resolving types sometimes. return true; } foreach (TypeReference @interface in supposedSubTypeDef.Interfaces) { if (@interface.Name == type.Name) { return true; } } if (supposedSubTypeDef.BaseType == null) { ///We are at the root of the class hierarcy, and no match was made. return false; } supposedSubTypeDef = supposedSubTypeDef.BaseType.Resolve(); } return false; }
public static bool TypesAreAssignable(ITypeInfoSource typeInfo, TypeReference target, TypeReference source) { if ((target == null) || (source == null)) return false; // All values are assignable to object if (target.FullName == "System.Object") return true; int targetDepth, sourceDepth; if (TypesAreEqual(FullyDereferenceType(target, out targetDepth), FullyDereferenceType(source, out sourceDepth))) { if (targetDepth == sourceDepth) return true; } // HACK: System.Array and T[] do not implement IEnumerable<T> if ( source.IsArray && (target.Namespace == "System.Collections.Generic") ) { var targetGit = target as GenericInstanceType; if ( (targetGit != null) && (targetGit.Name == "IEnumerable`1") && (targetGit.GenericArguments.FirstOrDefault() == source.GetElementType()) ) return true; } // HACK: The .NET type system treats pointers and ints as assignable to each other if (IsIntegral(target) && IsPointer(source)) return true; var cacheKey = new Tuple<string, string>(target.FullName, source.FullName); return typeInfo.AssignabilityCache.GetOrCreate( cacheKey, (key) => { bool result = false; var dSource = GetTypeDefinition(source); if (TypeInBases(source, target, false)) result = true; else if (dSource == null) result = false; else if (TypesAreEqual(target, dSource)) result = true; else if ((dSource.BaseType != null) && TypesAreAssignable(typeInfo, target, dSource.BaseType)) result = true; else { foreach (var iface in dSource.Interfaces) { if (TypesAreAssignable(typeInfo, target, iface)) { result = true; break; } } } return result; } ); }
bool IsVisibleFrom (TypeDefinition type, TypeReference reference) { if (reference == null) return true; if (reference is GenericParameter || reference.GetElementType () is GenericParameter) return true; TypeDefinition other = reference.Resolve (); if (other == null) return true; if (!AreInDifferentAssemblies (type, other)) return true; if (IsPublic (other)) return true; return false; }
private TypeReference Import(TypeReference typeReference) { return this.typeMap.GetOrCreate(typeReference, () => { if (typeReference.IsByReference) return Import(typeReference.GetElementType()).MakeByReferenceType(); var sourceInstance = typeReference as GenericInstanceType; if (sourceInstance != null) { var destInstance = new GenericInstanceType(Import(sourceInstance.ElementType)); destInstance.GenericArguments.AddRange( sourceInstance.GenericArguments.Select(Import)); return destInstance; } return this.destinationModule.Import(typeReference); }); }
/// <summary> /// This method resolves a type. This method ignores the methods and fields. You have to /// resolve them manually. /// </summary> /// <param name="hostModule">The module in which the changes are made.</param> /// <param name="type">The type to resolve.</param> /// <param name="AddedClasses">Newly added classes to lookup while resolving.</param> /// <param name="TypesMap">A map of types to lookup while resolving.</param> /// <returns></returns> protected static TypeReference Resolve( ModuleDefinition hostModule, TypeReference type, Dictionary<TypeReference, TypeDefinition> AddedClasses, Dictionary<TypeReference, TypeReference> TypesMap) { if (type is GenericInstanceType) { GenericInstanceType gType = (GenericInstanceType)type; GenericInstanceType nType = new GenericInstanceType(Resolve(hostModule, gType.ElementType, AddedClasses, TypesMap)); foreach (TypeReference t in gType.GenericArguments) { nType.GenericArguments.Add(Resolve(hostModule, t, AddedClasses, TypesMap)); } return nType; } if (type == null || type is GenericParameter || (type.IsArray && type.GetElementType() is GenericParameter)) return type; if (TypesMap.ContainsKey(type)) return hostModule.Import(TypesMap[type]); foreach (TypeReference addedType in AddedClasses.Keys) { if (addedType == type) { return hostModule.Import(AddedClasses[addedType]); } } if (type.Module != hostModule) { TypeDefinition t = hostModule.GetType(type.FullName); if (t != null) { return (TypeReference)t; } if (hostModule == null || type == null) return type; else { try { return hostModule.Import(type); } catch (Exception e) { System.Console.WriteLine(type.GetElementType()); System.Console.WriteLine(type.GetType().FullName); throw e; } } } else return type; }
private TypeReference ReadTypeSignature(ElementType etype) { switch (etype) { case ElementType.ValueType: { TypeReference typeDefOrRef2 = GetTypeDefOrRef(ReadTypeTokenSignature()); typeDefOrRef2.KnownValueType(); return(typeDefOrRef2); } case ElementType.Class: return(GetTypeDefOrRef(ReadTypeTokenSignature())); case ElementType.Ptr: return(new PointerType(ReadTypeSignature())); case ElementType.FnPtr: { FunctionPointerType functionPointerType = new FunctionPointerType(); ReadMethodSignature(functionPointerType); return(functionPointerType); } case ElementType.ByRef: return(new ByReferenceType(ReadTypeSignature())); case ElementType.Pinned: return(new PinnedType(ReadTypeSignature())); case ElementType.SzArray: return(new ArrayType(ReadTypeSignature())); case ElementType.Array: return(ReadArrayTypeSignature()); case ElementType.CModOpt: return(new OptionalModifierType(GetTypeDefOrRef(ReadTypeTokenSignature()), ReadTypeSignature())); case ElementType.CModReqD: return(new RequiredModifierType(GetTypeDefOrRef(ReadTypeTokenSignature()), ReadTypeSignature())); case ElementType.Sentinel: return(new SentinelType(ReadTypeSignature())); case ElementType.Var: return(GetGenericParameter(GenericParameterType.Type, base.ReadCompressedUInt32())); case ElementType.MVar: return(GetGenericParameter(GenericParameterType.Method, base.ReadCompressedUInt32())); case ElementType.GenericInst: { bool num = base.ReadByte() == 17; TypeReference typeDefOrRef = GetTypeDefOrRef(ReadTypeTokenSignature()); GenericInstanceType genericInstanceType = new GenericInstanceType(typeDefOrRef); ReadGenericInstanceSignature(typeDefOrRef, genericInstanceType); if (num) { genericInstanceType.KnownValueType(); typeDefOrRef.GetElementType().KnownValueType(); } return(genericInstanceType); } case ElementType.Object: return(TypeSystem.Object); case ElementType.Void: return(TypeSystem.Void); case ElementType.TypedByRef: return(TypeSystem.TypedReference); case ElementType.I: return(TypeSystem.IntPtr); case ElementType.U: return(TypeSystem.UIntPtr); default: return(GetPrimitiveType(etype)); } }
public static bool verifyType(TypeReference typeReference, string assembly, string type, string extra = "") { return typeReference != null && MemberReferenceHelper.getCanonicalizedTypeRefName(typeReference.GetElementType()) == "[" + assembly + "]" + type && typeReference.FullName == type + extra; }
private void Visit(TypeReference type, string referencingEntityName) { if (type == null) return; if (type.Scope == _module) return; if (type.GetElementType().IsGenericParameter) return; var genericInstance = type as GenericInstanceType; if (genericInstance != null) DispatchGenericArguments(genericInstance, referencingEntityName); _visitor.Visit(type.GetElementType(), referencingEntityName); }
private static void GetXmlDocParameterPathRecursive(TypeReference paramType, bool explicitMode, StringBuilder currentPath) { if (paramType == null) return; if (paramType.GenericParameters.Count > 0) { currentPath.Append( paramType.Namespace + ((CanAppendSpecialExplicitChar() && explicitMode) ? "#" : ".") + StripGenericName(paramType.Name)); // list parameters or types bool firstAppend = true; currentPath.Append("{"); foreach (GenericParameter TempType in paramType.GenericParameters) { if (!firstAppend) currentPath.Append(","); currentPath.Append(GetXmlDocParameterPath(TempType, explicitMode)); firstAppend = false; } currentPath.Append("}"); } else if (paramType is GenericInstanceType) { var thisGenericType = paramType as GenericInstanceType; // if nested, scan enclosing type if (paramType.DeclaringType != null) currentPath.Append(GetXmlDocParameterPath(paramType.DeclaringType, explicitMode)); // determine namespace string strNamespace = String.Empty; if ((paramType.Namespace != null && paramType.Namespace.Length > 0) || paramType.DeclaringType != null) { strNamespace = paramType.Namespace + ((CanAppendSpecialExplicitChar() && explicitMode) ? "#" : "."); } currentPath.Append(strNamespace + StripGenericName(thisGenericType.Name)); // list parameters or types bool firstAppend = true; currentPath.Append("{"); foreach (TypeReference tempTypeRef in thisGenericType.GenericArguments) { if (!firstAppend) currentPath.Append(","); currentPath.Append(GetXmlDocParameterPath(tempTypeRef, explicitMode)); firstAppend = false; } currentPath.Append("}"); } else if (paramType is GenericParameter) { var thisGenParam = paramType as GenericParameter; if (explicitMode) { // in explicit mode we print parameter name currentPath.Append(thisGenParam.Name); } else { // in non-explicit mode we print parameter order int paramOrder = 0; // find for (int i = 0; i < thisGenParam.Owner.GenericParameters.Count; i++) { if (thisGenParam.Owner.GenericParameters[i].Name == paramType.Name) { paramOrder = i; break; } } if (thisGenParam.Owner is MethodReference) currentPath.Append("``" + paramOrder); else currentPath.Append("`" + paramOrder); } } else if (paramType is PointerType) { // parameter is pointer type currentPath.Append(GetXmlDocParameterPath((paramType as PointerType).ElementType, explicitMode)); currentPath.Append("*"); } else if (paramType is ArrayType) { var thisArrayType = paramType as ArrayType; if (thisArrayType.ElementType != null) currentPath.Append(GetXmlDocParameterPath(thisArrayType.ElementType, explicitMode)); int iRank = thisArrayType.Rank; if (iRank == 1) { currentPath.Append("[]"); } else { bool firstAppend = true; currentPath.Append("["); for (int i = 0; i < (explicitMode ? iRank - 1 : iRank); i++) { // in explicit mode for .NET3.5/VS2008, // there is no separator char "," used for multi-dimensional array, // so there are three cases when comma shall be added: // firstAppend = false; ExplicitMode = false; CanAppendSpecialExplicitChar() = true; // firstAppend = false; ExplicitMode = false; CanAppendSpecialExplicitChar() = false; // firstAppend = false; ExplicitMode = true; CanAppendSpecialExplicitChar() = false; // below this is stored in decent manner if (!firstAppend && (!explicitMode || !CanAppendSpecialExplicitChar())) currentPath.Append(","); currentPath.Append(((CanAppendSpecialExplicitChar() && explicitMode) ? "@" : "0:")); if (thisArrayType.Dimensions[i].UpperBound > 0) currentPath.Append(thisArrayType.Dimensions[i].UpperBound.ToString()); firstAppend = false; } currentPath.Append("]"); } } else if (paramType is ByReferenceType) { // parameter is passed by reference currentPath.Append(GetXmlDocParameterPath((paramType as ByReferenceType).ElementType, false)); currentPath.Append("@"); } else if (paramType.IsOptionalModifier) { currentPath.Append(GetXmlDocParameterPath(paramType.GetElementType(), explicitMode)); currentPath.Append("!"); currentPath.Append(GetXmlDocParameterPath((paramType as IModifierType).ModifierType, explicitMode)); } else if (paramType.IsRequiredModifier) { currentPath.Append(GetXmlDocParameterPath(paramType.GetElementType(), explicitMode)); currentPath.Append("|"); currentPath.Append(GetXmlDocParameterPath((paramType as IModifierType).ModifierType, explicitMode)); } else if (paramType is FunctionPointerType) { // type is function pointer var thisFuncPtr = paramType as FunctionPointerType; string tempString = String.Empty; // return type currentPath.Append("=FUNC:"); currentPath.Append(GetXmlDocParameterPath(thisFuncPtr.ReturnType, explicitMode)); // method's parameters if (thisFuncPtr.Parameters.Count > 0) { bool firstAppend = true; currentPath.Append("("); foreach (ParameterDefinition tempParam in thisFuncPtr.Parameters) { if (!firstAppend) currentPath.Append(","); currentPath.Append(GetXmlDocParameterPath(tempParam.ParameterType, explicitMode)); firstAppend = false; } currentPath.Append(")"); } else { currentPath.Append("(System.Void)"); } } else if (paramType is PinnedType) { // type is pinned type currentPath.Append(GetXmlDocParameterPath((paramType as PinnedType).ElementType, explicitMode)); currentPath.Append("^"); } else if (paramType is TypeReference) { // if nested, scan enclosing type if (paramType.DeclaringType != null) currentPath.Append(GetXmlDocParameterPath(paramType.DeclaringType, explicitMode)); // determine namespace string strNamespace = String.Empty; if ((paramType.Namespace != null && paramType.Namespace.Length > 0) || paramType.DeclaringType != null) { strNamespace = paramType.Namespace + ((CanAppendSpecialExplicitChar() && explicitMode) ? "#" : "."); } // concrete type currentPath.Append( strNamespace + ((CanAppendSpecialExplicitChar() && explicitMode) ? paramType.Name.Replace(".", "#") : paramType.Name)); } }
private TypeReference ReadTypeSignature(ElementType etype) { ElementType type3 = etype; switch (type3) { case ElementType.Void: return(this.TypeSystem.Void); case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.String: case (ElementType.Array | ElementType.Boolean | ElementType.Void): case (ElementType.Boolean | ElementType.ByRef | ElementType.I4): break; case ElementType.Ptr: return(new PointerType(this.ReadTypeSignature())); case ElementType.ByRef: return(new ByReferenceType(this.ReadTypeSignature())); case ElementType.ValueType: { TypeReference typeDefOrRef = this.GetTypeDefOrRef(this.ReadTypeTokenSignature()); typeDefOrRef.IsValueType = true; return(typeDefOrRef); } case ElementType.Class: return(this.GetTypeDefOrRef(this.ReadTypeTokenSignature())); case ElementType.Var: return(this.GetGenericParameter(GenericParameterType.Type, base.ReadCompressedUInt32())); case ElementType.Array: return(this.ReadArrayTypeSignature()); case ElementType.GenericInst: { bool flag = base.ReadByte() == 0x11; TypeReference typeDefOrRef = this.GetTypeDefOrRef(this.ReadTypeTokenSignature()); GenericInstanceType instance = new GenericInstanceType(typeDefOrRef); this.ReadGenericInstanceSignature(typeDefOrRef, instance); if (flag) { instance.IsValueType = true; typeDefOrRef.GetElementType().IsValueType = true; } return(instance); } case ElementType.TypedByRef: return(this.TypeSystem.TypedReference); case ElementType.I: return(this.TypeSystem.IntPtr); case ElementType.U: return(this.TypeSystem.UIntPtr); case ElementType.FnPtr: { FunctionPointerType method = new FunctionPointerType(); this.ReadMethodSignature(method); return(method); } case ElementType.Object: return(this.TypeSystem.Object); case ElementType.SzArray: return(new ArrayType(this.ReadTypeSignature())); case ElementType.MVar: return(this.GetGenericParameter(GenericParameterType.Method, base.ReadCompressedUInt32())); case ElementType.CModReqD: return(new RequiredModifierType(this.GetTypeDefOrRef(this.ReadTypeTokenSignature()), this.ReadTypeSignature())); case ElementType.CModOpt: return(new OptionalModifierType(this.GetTypeDefOrRef(this.ReadTypeTokenSignature()), this.ReadTypeSignature())); default: if (type3 == ElementType.Sentinel) { return(new SentinelType(this.ReadTypeSignature())); } if (type3 != ElementType.Pinned) { break; } return(new PinnedType(this.ReadTypeSignature())); } return(this.GetPrimitiveType(etype)); }