public GenericContext Clone () { GenericContext ctx = new GenericContext (); ctx.Type = m_type; ctx.Method = m_method; return ctx; }
public void InstantiatePropertySignatureWithGenericPropertyType() { var signature = PropertySignature.CreateStatic(new GenericParameterSignature(GenericParameterType.Type, 0)); var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null); var newSignature = signature.InstantiateGenericTypes(context); var expected = PropertySignature.CreateStatic(_module.CorLibTypeFactory.String); Assert.Equal(expected, newSignature, Comparer); }
public MethodSpecificationMethod(GenericContext gc, MethodSpecificationHandle handle) : base(gc) { ms = cx.mdReader.GetMethodSpecification(handle); typeParams = ms.DecodeSignature(cx.TypeSignatureDecoder, gc); unboundMethod = (Method)cx.CreateGeneric(gc, ms.Method); declaringType = unboundMethod.DeclaringType; ShortId = unboundMethod.ShortId + openAngle + CIL.Id.CommaSeparatedList(typeParams.Select(p => p.ShortId)) + closeAngle; }
public void InstantiateSimpleGenericInstanceType() { var signature = new GenericInstanceTypeSignature(_dummyGenericType, false, new GenericParameterSignature(GenericParameterType.Type, 0)); var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null); var newSignature = signature.InstantiateGenericTypes(context); Assert.Equal(new GenericInstanceTypeSignature(_dummyGenericType, false, _module.CorLibTypeFactory.String), newSignature, Comparer); }
public ILStructure(PEFile module, MethodDefinitionHandle handle, GenericContext genericContext, ILStructureType type, int startOffset, int endOffset, int loopEntryPoint) { Debug.Assert(startOffset < endOffset); this.Module = module; this.MethodHandle = handle; this.GenericContext = genericContext; this.Type = type; this.StartOffset = startOffset; this.EndOffset = endOffset; this.LoopEntryPointOffset = loopEntryPoint; }
public ILStructure(PEFile module, MethodDefinitionHandle handle, GenericContext genericContext, ILStructureType type, int startOffset, int endOffset, ExceptionRegion handler = default) { Debug.Assert(startOffset < endOffset); this.Module = module; this.MethodHandle = handle; this.GenericContext = genericContext; this.Type = type; this.StartOffset = startOffset; this.EndOffset = endOffset; this.ExceptionHandler = handler; }
static GenericInstanceType ConstructGenericType(GenericContext context, TypeDefinition typeDefinition, IEnumerable <TypeReference> genericArguments) { var inflatedType = new GenericInstanceType(typeDefinition); foreach (var genericArgument in genericArguments) { inflatedType.GenericArguments.Add(InflateType(context, genericArgument)); } return(inflatedType); }
public static TypeReference InflateType(GenericContext context, TypeReference typeReference) { var typeDefinition = InflateTypeWithoutException(context, typeReference); if (typeDefinition == null) { throw new InvalidOperationException($"Unable to resolve a reference to the type '{typeReference.FullName}' in the assembly '{typeReference.Module.Assembly.FullName}'. Does this type exist in a different assembly in the project?"); } return(typeDefinition); }
private ISymbolNode GenericLookupFieldHelper( CORINFO_RUNTIME_LOOKUP_KIND runtimeLookupKind, ReadyToRunFixupKind fixupKind, FieldDesc fieldArgument, GenericContext methodContext, SignatureContext signatureContext) { GenericLookupKey key = new GenericLookupKey(runtimeLookupKind, fixupKind, typeArgument: null, methodArgument: null, fieldArgument: fieldArgument, methodContext, signatureContext); return(_genericLookupHelpers.GetOrAdd(key)); }
public void TestInitExceptions() { GenericContext context = null; try { context = new GenericContext().Build(); } catch (Exception e) { Assert.AreEqual("Schema cannot be null or empty.", e.Message); } Assert.IsNull(context); }
public Property(GenericContext gc, Type type, PropertyDefinitionHandle handle) : base(gc.cx) { pd = cx.mdReader.GetPropertyDefinition(handle); this.type = type; var id = type.ShortId + gc.cx.Dot + cx.ShortName(pd.Name); var signature = pd.DecodeSignature(new SignatureDecoder(), gc); id += "(" + CIL.Id.CommaSeparatedList(signature.ParameterTypes.Select(p => p.MakeId(gc))) + ")"; ShortId = id; }
public Traveller FindUserByEmail(string email) { using (var context = new GenericContext <Traveller>()) { var item = context.Entity.Where <Traveller>(t => t.email == email).SingleOrDefault(); if (item == null) { return(null); } return(item); } }
public Traveller FindUserByLogin(string login) { using (var context = new GenericContext <Traveller>()) { var item = context.Entity.Where <Traveller>(t => t.login == login).SingleOrDefault(); if (item == null) { return(null); } return(item); } }
public T Get(int id) { using (var context = new GenericContext <T>()) { var item = context.Entity.Find(id); if (item == null) { return(null); } return(item); } }
public SaleTicket GetSaleTicket(int sale_id) { using (var context = new GenericContext <SaleTicket>()) { var item = context.Entity.Where <SaleTicket>(t => t.sale_id == sale_id).SingleOrDefault(); if (item == null) { return(null); } return(item); } }
public void ResolveMethodGenericParameterWithMethod() { var genericInstance = new GenericInstanceMethodSignature(); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var context = new GenericContext(null, genericInstance); var parameter = new GenericParameterSignature(GenericParameterType.Method, 0); Assert.Equal("System.String", context.GetTypeArgument(parameter).FullName); }
public void ResolveTypeGenericParameterWithOnlyMethodShouldThrow() { var genericInstance = new GenericInstanceMethodSignature(); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var context = new GenericContext(null, genericInstance); var parameter = new GenericParameterSignature(GenericParameterType.Type, 0); Assert.Throws <ArgumentOutOfRangeException>(() => context.GetTypeArgument(parameter)); }
public ISymbolNode GenericLookupHelper( CORINFO_RUNTIME_LOOKUP_KIND runtimeLookupKind, ReadyToRunHelperId helperId, object helperArgument, GenericContext methodContext, SignatureContext signatureContext) { switch (helperId) { case ReadyToRunHelperId.TypeHandle: return(GenericLookupTypeHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_TypeHandle, (TypeDesc)helperArgument, methodContext, signatureContext)); case ReadyToRunHelperId.MethodHandle: return(GenericLookupMethodHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_MethodHandle, (MethodWithToken)helperArgument, methodContext, signatureContext)); case ReadyToRunHelperId.MethodEntry: return(GenericLookupMethodHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_MethodEntry, (MethodWithToken)helperArgument, methodContext, signatureContext)); case ReadyToRunHelperId.MethodDictionary: return(GenericLookupMethodHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_MethodHandle, (MethodWithToken)helperArgument, methodContext, signatureContext)); case ReadyToRunHelperId.VirtualDispatchCell: return(GenericLookupMethodHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_VirtualEntry, (MethodWithToken)helperArgument, methodContext, signatureContext)); default: throw new NotImplementedException(); } }
private void DecodeSignature() { var propertyDef = module.metadata.GetPropertyDefinition(propertyHandle); var genericContext = new GenericContext(DeclaringType.TypeParameters); IType returnType; IParameter[] parameters; try { var signature = propertyDef.DecodeSignature(module.TypeProvider, genericContext); var accessors = propertyDef.GetAccessors(); var declTypeDef = this.DeclaringTypeDefinition; ParameterHandleCollection?parameterHandles; Nullability nullableContext; if (!accessors.Getter.IsNil) { var getter = module.metadata.GetMethodDefinition(accessors.Getter); parameterHandles = getter.GetParameters(); nullableContext = getter.GetCustomAttributes().GetNullableContext(module.metadata) ?? declTypeDef?.NullableContext ?? Nullability.Oblivious; } else if (!accessors.Setter.IsNil) { var setter = module.metadata.GetMethodDefinition(accessors.Setter); parameterHandles = setter.GetParameters(); nullableContext = setter.GetCustomAttributes().GetNullableContext(module.metadata) ?? declTypeDef?.NullableContext ?? Nullability.Oblivious; } else { parameterHandles = null; nullableContext = declTypeDef?.NullableContext ?? Nullability.Oblivious; } // We call OptionsForEntity() for the declaring type, not the property itself, // because the property's accessibilty isn't stored in metadata but computed. // Otherwise we'd get infinite recursion, because computing the accessibility // requires decoding the signature for the GetBaseMembers() call. // Roslyn uses the same workaround (see the NullableTypeDecoder.TransformType // call in PEPropertySymbol). var typeOptions = module.OptionsForEntity(declTypeDef); (returnType, parameters, _) = MetadataMethod.DecodeSignature( module, this, signature, parameterHandles, nullableContext, typeOptions, returnTypeAttributes: propertyDef.GetCustomAttributes()); } catch (BadImageFormatException) { returnType = SpecialType.UnknownType; parameters = Empty <IParameter> .Array; } LazyInit.GetOrSet(ref this.returnType, returnType); LazyInit.GetOrSet(ref this.parameters, parameters); }
public List <Sale> GetUserSales(int user_id) { using (var context = new GenericContext <Sale>()) { var item = context.Entity.Where <Sale>(s => s.traveller_id == user_id).OrderBy(s => s.sale_date).ToList(); if (item == null) { return(null); } return(item); } }
private static bool MatchParameters(GenericContext <ParameterDefinition> baseParameterType, GenericContext <ParameterDefinition> parameterType) { if (baseParameterType.Item.IsIn != parameterType.Item.IsIn || baseParameterType.Item.IsOut != parameterType.Item.IsOut) { return(false); } var baseParam = baseParameterType.ResolveWithContext(baseParameterType.Item.ParameterType); var param = parameterType.ResolveWithContext(parameterType.Item.ParameterType); return(IsSameType(baseParam, param)); }
public void ResolveTypeGenericParameterWithType() { var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List <>)), false); genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string))); var context = new GenericContext(genericInstance, null); var parameter = new GenericParameterSignature(GenericParameterType.Type, 0); Assert.Equal("System.String", context.GetTypeArgument(parameter).FullName); }
public virtual void Disassemble(PEFile module, MethodDefinitionHandle handle) { this.module = module ?? throw new ArgumentNullException(nameof(module)); metadata = module.Metadata; genericContext = new GenericContext(handle, module); signatureDecoder = new DisassemblerSignatureProvider(module, output); var methodDefinition = metadata.GetMethodDefinition(handle); // start writing IL code output.WriteLine("// Method begins at RVA 0x{0:x4}", methodDefinition.RelativeVirtualAddress); if (methodDefinition.RelativeVirtualAddress == 0) { output.WriteLine("// Code size {0} (0x{0:x})", 0); output.WriteLine(".maxstack {0}", 0); output.WriteLine(); return; } var body = module.Reader.GetMethodBody(methodDefinition.RelativeVirtualAddress); var blob = body.GetILReader(); output.WriteLine("// Code size {0} (0x{0:x})", blob.Length); output.WriteLine(".maxstack {0}", body.MaxStack); var entrypointHandle = MetadataTokens.MethodDefinitionHandle(module.Reader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress); if (handle == entrypointHandle) { output.WriteLine(".entrypoint"); } DisassembleLocalsBlock(body); output.WriteLine(); sequencePoints = DebugInfo?.GetSequencePoints(handle) ?? EmptyList <DebugInfo.SequencePoint> .Instance; nextSequencePointIndex = 0; if (DetectControlStructure && blob.Length > 0) { blob.Reset(); HashSet <int> branchTargets = GetBranchTargets(blob); blob.Reset(); WriteStructureBody(new ILStructure(module, handle, genericContext, body), branchTargets, ref blob); } else { while (blob.RemainingBytes > 0) { WriteInstruction(output, metadata, handle, ref blob); } WriteExceptionHandlers(module, handle, body); } sequencePoints = null; }
public void WriteId(TextWriter trapFile, GenericContext gc) { genericType.WriteId(trapFile, gc); trapFile.Write('<'); var index = 0; foreach (var arg in typeArguments) { trapFile.WriteSeparator(",", ref index); arg.WriteId(trapFile, gc); } trapFile.Write('>'); }
private void Dispose(bool disposing) { if (!disposing) { return; } if (_context == null) { return; } _context.Dispose(); _context = null; }
public void TestInitFull() { GenericContext context = new GenericContext() .SetSchema("iglu:com.acme/custom_events/jsonchema/1-0-0") .Add("demo", "context") .Build(); Assert.NotNull(context); Assert.AreEqual(1, context.GetData().Count); Assert.AreEqual("iglu:com.acme/custom_events/jsonchema/1-0-0", context.GetSchema()); CollectionAssert.AreEquivalent(JSON.Deserialize <Dictionary <string, object> >("{\"data\":{\"demo\":\"context\"}, \"schema\":\"iglu:com.acme/custom_events/jsonchema/1-0-0\"}"), JSON.Deserialize <Dictionary <string, object> >(context.GetJson().ToString())); }
/// <inheritdoc /> public TypeMemoryLayout VisitGenericInstanceType(GenericInstanceTypeSignature signature) { // Enter new generic context. var oldContext = _currentGenericContext; _currentGenericContext = _currentGenericContext.WithType(signature); var result = VisitTypeDefOrRef(signature.GenericType); // Leave generic context. _currentGenericContext = oldContext; return(result); }
public void TestInitFull() { GenericContext context = new GenericContext() .SetSchema("iglu:com.acme/custom_events/jsonchema/1-0-0") .Add("demo", "context") .Build(); Assert.NotNull(context); Assert.AreEqual(1, context.GetData().Count); Assert.AreEqual("iglu:com.acme/custom_events/jsonchema/1-0-0", context.GetSchema()); Assert.AreEqual("{\"data\":{\"demo\":\"context\"}, \"schema\":\"iglu:com.acme/custom_events/jsonchema/1-0-0\"}", context.GetJson().ToString()); }
public DefinitionMethod(GenericContext gc, MethodDefinitionHandle handle) : base(gc) { md = cx.mdReader.GetMethodDefinition(handle); this.gc = gc; name = cx.GetId(md.Name); declaringType = (Type)cx.CreateGeneric(this, md.GetDeclaringType()); signature = md.DecodeSignature(new SignatureDecoder(), this); ShortId = MakeMethodId(declaringType, name); methodDebugInformation = cx.GetMethodDebugInformation(handle); }
public static void initDb(GenericContext _context) { _context.Database.EnsureCreated(); if (_context.Users.Any()) { return; } var user = new User("Bruno Afonso", Convert.ToDateTime("25/04/1995")); _context.Users.Add(user); _context.SaveChanges(); }
public DefinitionMethod(GenericContext gc, MethodDefinitionHandle handle) : base(gc) { md = Cx.MdReader.GetMethodDefinition(handle); this.gc = gc; this.handle = handle; name = Cx.GetString(md.Name); declaringType = (Type)Cx.CreateGeneric(this, md.GetDeclaringType()); signature = md.DecodeSignature(new SignatureDecoder(), this); methodDebugInformation = Cx.GetMethodDebugInformation(handle); }
private void RecurseAfferentCouplings(string fullName, int depth, Dictionary<string, bool> history, bool inInheritanceChain, TypeDefinition inheritedTypeContext, AffectedGraph graph, MemberReference parent, List<string> breadCrumbs, GenericContext genericContext) { var afferentEntry = _cache.TryGetAfferentCouplingNode(fullName); if (afferentEntry == null) return; genericContext.SetIndirectConstraintsOn(afferentEntry.MemberReference, parent, inInheritanceChain); if (!inInheritanceChain && genericContext.IsClear()) { lock (history) //double lock, TryCutPointPrune already did this { if (!history.ContainsKey(fullName)) { history.Add(fullName, true); } } } foreach (var current in afferentEntry.Couplings) { if (current.IgnoreWalk) continue; var proposed = genericContext.GetGenericContextOf(current.ActualReference); if (!genericContext.CanTransitionTo(proposed)) { WriteWalkerDebug("Generics truncate", depth); continue; } var newContext = genericContext.TransitionTo(proposed); FillAfferentGraph(current.To, history, graph, afferentEntry.MemberReference, depth + 1, inheritedTypeContext, inInheritanceChain && current.IsSelfCall, breadCrumbs, newContext, current.IsSelfCall); } }
private MethodBase ResolveOverload(MemberInfo[] members, Cci.IMethodReference methodRef) { IEnumerable<Cci.IParameterTypeInformation> paramRefs = methodRef.GetParameters(_context); Type[] reusableResolvedParameters = null; Type[] typeGenericParameters = members[0].DeclaringType.GetGenericArguments(); MethodBase candidate = null; foreach (MethodBase method in members) { Debug.Assert(!method.IsGenericMethod || method.IsGenericMethodDefinition); if (methodRef.AcceptsExtraArguments && method.CallingConvention != CallingConventions.VarArgs) { continue; } if (methodRef.IsGeneric != method.IsGenericMethodDefinition) { continue; } Type[] methodGenericParameters = (methodRef.IsGeneric) ? method.GetGenericArguments() : Type.EmptyTypes; if (methodGenericParameters.Length != methodRef.GenericParameterCount) { continue; } GenericContext genericContext = new GenericContext(typeGenericParameters, methodGenericParameters); Type[] resolvedParameters = reusableResolvedParameters ?? ResolveMethodParameters(methodRef, paramRefs, genericContext); if (ParametersMatch(resolvedParameters, method.GetParameters()) && ReturnTypeMatches(methodRef, method, genericContext)) { Debug.Assert(candidate == null); candidate = method; #if !DEBUG break; #endif } // We can reuse resolved parameters if the method isn't generic. // If it is its signature might contain references to its generic parameters which are different for each overload. if (reusableResolvedParameters == null && !methodRef.IsGeneric) { reusableResolvedParameters = resolvedParameters; } } Debug.Assert(candidate != null); return candidate; }
private ParameterInfo MakeParameterInfo(MethodBase containingMethod, int position, Cci.ITypeReference typeRef, GenericContext genericContext, ImmutableArray<Cci.ICustomModifier> customModifiers, bool isByReference) { var type = ResolveType(typeRef, genericContext); if (isByReference) { type = type.MakeByRefType(); } if (customModifiers != null) { Type[] reqMods, optMods; ResolveCustomModifiers(customModifiers, out reqMods, out optMods); return new ModifiedParameterInfo(containingMethod, position, type, reqMods, optMods); } else { return new SimpleParameterInfo(containingMethod, position, type); } }
public ImportContext(IGenericParameterProvider provider) { m_genContext = new GenericContext (provider); }
public ImportContext(IImporter importer) { m_genContext = new GenericContext (); m_importer = importer; }
private Type ResolveType( Cci.ITypeReference typeRef, GenericContext genericContext = default(GenericContext), TypeBuilder dependentType = null, bool valueTypeDependency = false) { var typeDef = typeRef.AsTypeDefinition(_context); if (typeDef != null && IsLocal(typeRef)) { var builder = _typeBuilders[typeDef]; if (dependentType != null && (!valueTypeDependency || builder.IsValueType)) { AddDependency(dependentType, builder); } return builder; } Type result; Cci.IGenericParameterReference genericParamRef; Cci.IGenericTypeInstanceReference genericRef; Cci.ISpecializedNestedTypeReference specializedNestedRef; Cci.INestedTypeReference nestedRef; Cci.IArrayTypeReference arrayType; Cci.IManagedPointerTypeReference refType; Cci.IPointerTypeReference ptrType; Cci.INamespaceTypeReference nsType; Cci.IModifiedTypeReference modType; if ((nsType = typeRef.AsNamespaceTypeReference) != null) { // cache lookup (no type dependencies to track): if (_typeRefs.TryGetValue(typeRef, out result)) { return result; } // a namespace type builder would already be found in type builders, so we don't get here: Debug.Assert(!IsLocal(typeRef)); Cci.IUnitReference unitRef = nsType.GetUnit(_context); Cci.IAssemblyReference assemblyRef; var moduleRef = unitRef as Cci.IModuleReference; if (moduleRef != null) { if (ReferenceEquals(moduleRef.GetContainingAssembly(_context), _module.GetContainingAssembly(_context))) { throw new NotSupportedException("Ref.Emit limitation: modules not supported"); } else { assemblyRef = moduleRef.GetContainingAssembly(_context); } } else { assemblyRef = unitRef as Cci.IAssemblyReference; } // We only track dependency among type builders so we don't need to track it here. result = ResolveType(ResolveAssembly(assemblyRef), nsType); } else if ((specializedNestedRef = typeRef.AsSpecializedNestedTypeReference) != null) { Type unspecialized = ResolveType(specializedNestedRef.UnspecializedVersion, genericContext, dependentType, valueTypeDependency); // the resulting type doesn't depend on generic arguments if it is not a value type: if (valueTypeDependency && !unspecialized.IsValueType) { dependentType = null; } Type[] typeArgs = ResolveGenericArguments(specializedNestedRef, genericContext, dependentType); // cache lookup (all type dependencies already established above): if (_typeRefs.TryGetValue(typeRef, out result)) { return result; } result = unspecialized.MakeGenericType(typeArgs); } else if ((genericRef = typeRef.AsGenericTypeInstanceReference) != null) { Type genericType = ResolveType(genericRef.GenericType, genericContext, dependentType, valueTypeDependency); // the resulting type doesn't depend on generic arguments if it is not a value type: if (valueTypeDependency && !genericType.IsValueType) { dependentType = null; } Type[] typeArgs = ResolveGenericArguments(genericRef, genericContext, dependentType); // cache lookup (all type dependencies already established above): if (_typeRefs.TryGetValue(typeRef, out result)) { return result; } result = genericType.MakeGenericType(typeArgs); } else if ((nestedRef = typeRef.AsNestedTypeReference) != null) { // cache lookup (no type dependencies to track): if (_typeRefs.TryGetValue(typeRef, out result)) { return result; } // a nested type builder would already be found in type builders, so we don't get here: Debug.Assert(!IsLocal(typeRef)); // we only track dependency among type builders so we don't need to track it here: Type containingType = ResolveType(nestedRef.GetContainingType(_context), genericContext); result = containingType.GetNestedType(Cci.MetadataWriter.GetMangledName(nestedRef), BindingFlags.Public | BindingFlags.NonPublic); } else if ((arrayType = typeRef as Cci.IArrayTypeReference) != null) { // an array isn't a value type -> don't propagate dependency: Type elementType = ResolveType(arrayType.GetElementType(_context), genericContext, valueTypeDependency ? null : dependentType); // cache lookup (all type dependencies already established above): if (_typeRefs.TryGetValue(typeRef, out result)) { return result; } result = (arrayType.Rank > 1) ? elementType.MakeArrayType((int)arrayType.Rank) : elementType.MakeArrayType(); } else if ((refType = typeRef as Cci.IManagedPointerTypeReference) != null) { // a managed pointer isn't a value type -> don't propagate dependency: Type elementType = ResolveType(refType.GetTargetType(_context), genericContext, valueTypeDependency ? null : dependentType); // cache lookup (all type dependencies already established above): if (_typeRefs.TryGetValue(typeRef, out result)) { return result; } result = elementType.MakeByRefType(); } else if ((ptrType = typeRef as Cci.IPointerTypeReference) != null) { // a pointer isn't a value type -> don't propagate dependency: Type elementType = ResolveType(ptrType.GetTargetType(_context), genericContext, valueTypeDependency ? null : dependentType); // cache lookup (all type dependencies already established above): if (_typeRefs.TryGetValue(typeRef, out result)) { return result; } result = elementType.MakePointerType(); } else if ((modType = typeRef as Cci.IModifiedTypeReference) != null) { Type[] reqMods, optMods; ResolveCustomModifiers(modType, dependentType, out reqMods, out optMods); Type unmodified = ResolveType(modType.UnmodifiedType, genericContext, dependentType, valueTypeDependency); // cache lookup (all type dependencies already established above): if (_typeRefs.TryGetValue(typeRef, out result)) { return result; } result = new ModifiedType(unmodified, reqMods, optMods); } else if ((genericParamRef = typeRef as Cci.IGenericParameterReference) != null) { GenericTypeParameterBuilder builder; if (_genericParameterBuilders.TryGetValue(genericParamRef, out builder)) { return builder; } Debug.Assert(!genericContext.IsNull); if (genericParamRef.AsGenericMethodParameterReference != null) { // Note that all occurrences of M in the following snippet refer to the same // IGenericMethodParameterReference object // // void foo<M>() // { // C<M>.bar<T>(T, M); // } // // Though in the context of C<M>.bar<T>(T, M) method reference only T is bound to the generic parameter of method bar. // We never get to resolve M here, because it can only be a GenericTypeParameterBuilder resolved earlier. return genericContext.MethodParameters[genericParamRef.AsGenericMethodParameterReference.Index]; } else { return genericContext.TypeParameters[GetConsolidatedGenericTypeParameterIndex(genericParamRef.AsGenericTypeParameterReference)]; } } else { throw ExceptionUtilities.Unreachable; } // do not cache if the lookup is relative to a generic context: if (genericContext.IsNull) { _typeRefs.Add(typeRef, result); } return result; }
private Type ResolveParameterType(Cci.IParameterTypeInformation parameter, GenericContext genericContext = default(GenericContext)) { var parameterType = ResolveType(parameter.GetType(_context), genericContext); if (parameter.IsByReference) { parameterType = parameterType.MakeByRefType(); } if (parameter.CustomModifiers.Any()) { Type[] reqMods, optMods; ResolveCustomModifiers(parameter.CustomModifiers, out reqMods, out optMods); return new ModifiedType(parameterType, reqMods, optMods); } else { return parameterType; } }
private Type[] ResolveMethodParameters(Cci.IMethodReference methodRef, IEnumerable<Cci.IParameterTypeInformation> paramRefs, GenericContext genericContext) { var paramTypes = new Type[methodRef.ParameterCount]; int i = 0; foreach (var paramRef in paramRefs) { paramTypes[i++] = ResolveParameterType(paramRef, genericContext); } return paramTypes; }
private bool ReturnTypeMatches(Cci.IMethodReference methodRef, MethodBase method, GenericContext genericContext) { MethodInfo methodInfo = method as MethodInfo; if (methodInfo == null) { return true; } return methodInfo.ReturnType.IsEquivalentTo(ResolveType(methodRef.GetType(_context), genericContext)); }
private void FillAfferentGraph(string fullName, Dictionary<string, bool> cutPoints, AffectedGraph graph, MemberReference parent, int depth, TypeDefinition inheritedTypeContext, bool inVirtual, List<string> breadCrumbs, GenericContext genericContext, bool inSelf) { WriteWalkerDebug(fullName, depth); if (TryBreadCrumbsPrune(fullName, depth, breadCrumbs)) { if (parent != null) { WriteWalkerDebug("truncating but adding connection to " + fullName, depth); graph.AddConnection(parent.GetCacheName(), fullName, false); } return; } breadCrumbs.Add(fullName); if (TryCutPointPrune(fullName, depth, cutPoints)) { if (parent != null) { WriteWalkerDebug("bread crumbs truncating but adding connection to " + fullName, depth); graph.AddConnection(parent.GetCacheName(), fullName, false); } return; } var efferentEntry = _cache.TryGetEfferentCouplingNode(fullName); var afferentEntry = _cache.TryGetEfferentCouplingNode(fullName); MethodDefinition currentDefinition = null; if (efferentEntry != null) { TypeReference parentType = null; if (parent != null) parentType = parent.DeclaringType; var definition = efferentEntry.MemberReference.DeclaringType.ThreadSafeResolve(); if (TryInterfacePrune(fullName, depth, breadCrumbs, efferentEntry, parentType, definition)) return; if (TryInheritancePrune(fullName, depth, breadCrumbs, inVirtual, definition, inheritedTypeContext)) {return;} inheritedTypeContext = GetNewTypeContext(inheritedTypeContext, definition); currentDefinition = efferentEntry.MemberReference as MethodDefinition; if (currentDefinition != null) { if(currentDefinition.DeclaringType == null) {} if (parent is FieldReference && currentDefinition.IsConstructor) { breadCrumbs.Remove(fullName); return; } } } var touse = afferentEntry ?? efferentEntry; WriteWalkerDebug("adding node " + fullName, depth); var newnode = GetGraphNode(fullName, touse, parent == null, false); graph.AddNode(newnode); if (parent != null) { graph.AddConnection(parent.GetCacheName(), newnode.FullName, false); } if(currentDefinition != null) RecurseSynonyms(depth, cutPoints, inheritedTypeContext, currentDefinition, graph, breadCrumbs, genericContext); RecurseAfferentCouplings(fullName, depth, cutPoints, inVirtual, inheritedTypeContext, graph, parent, breadCrumbs, genericContext); breadCrumbs.Remove(fullName); }
public ImportContext(IImporter importer, IGenericParameterProvider provider) { m_importer = importer; m_genContext = new GenericContext (provider); }
public ImportContext() { m_genContext = new GenericContext (); }
private void RecurseSynonyms(int depth, Dictionary<string, bool> history, TypeDefinition inheritedTypeContext, MethodDefinition currentDefinition, AffectedGraph graph, List<string> breadCrumbs, GenericContext genericContext) { var synonyms = SynonymFinder.FindSynonymsFor(currentDefinition); foreach (var current in synonyms) { var c = current as MethodDefinition; if (c == null) continue; //shouldn't happen if (!c.DeclaringType.IsInterface) { FillAfferentGraph(current.GetCacheName(), history, graph, currentDefinition, depth + 1, inheritedTypeContext, true, breadCrumbs, genericContext, true); //always a base } else { FillAfferentGraph(current.GetCacheName(), history, graph, currentDefinition, depth + 1, inheritedTypeContext, false, breadCrumbs, genericContext, false); } } }
private Type[] ResolveGenericArguments(Cci.ITypeReference typeRef, GenericContext genericContext, TypeBuilder dependentType) { List<Cci.ITypeReference> argRefs = new List<Cci.ITypeReference>(); GetConsolidatedGenericArguments(argRefs, typeRef); return argRefs.Select(arg => ResolveType(arg, genericContext, dependentType)).ToArray(); }
private FieldInfo ResolveField(Cci.IFieldReference fieldRef) { var fieldDef = fieldRef.GetResolvedField(_context); if (fieldDef != null && IsLocal(fieldRef.GetContainingType(_context))) { return _fieldBuilders[fieldDef]; } FieldInfo result; if (_fieldRefs.TryGetValue(fieldRef, out result)) { return result; } Type declaringType = ResolveType(fieldRef.GetContainingType(_context)); Cci.ISpecializedFieldReference specializedRef = fieldRef.AsSpecializedFieldReference; if (specializedRef != null) { if (IsLocal(specializedRef.UnspecializedVersion.GetContainingType(_context))) { // declaring type is TypeBuilder or TypeBuilderInstantiation since it's defined in the module being built: FieldBuilder fieldBuilder = _fieldBuilders[(Cci.IFieldDefinition)specializedRef.UnspecializedVersion.AsDefinition(_context)]; result = TypeBuilder.GetField(declaringType, fieldBuilder); } else { FieldInfo unspecializedDefinition = ResolveField(specializedRef.UnspecializedVersion); result = new FieldRef(declaringType, fieldRef.Name, unspecializedDefinition.FieldType); } } else { GenericContext genericContext; if (declaringType.IsGenericTypeDefinition) { genericContext = new GenericContext(declaringType.GetGenericArguments(), Type.EmptyTypes); } else { genericContext = default(GenericContext); } // TODO: modifiers? Type fieldType = ResolveType(fieldRef.GetType(_context), genericContext); result = new FieldRef(declaringType, fieldRef.Name, fieldType); } _fieldRefs.Add(fieldRef, result); return result; }
private MemberInfo ResolveTypeMemberRef(Type type, string name, ByteReader sig, Type[] genericTypeArguments, Type[] genericMethodArguments) { IGenericContext context; if ((genericTypeArguments == null && genericMethodArguments == null) || type.IsGenericType) { context = type; } else { context = new GenericContext(genericTypeArguments, genericMethodArguments); } if (sig.PeekByte() == Signature.FIELD) { Type org = type; FieldSignature fieldSig = FieldSignature.ReadSig(this, sig, context); do { FieldInfo field = type.FindField(name, fieldSig); if (field != null) { return field; } type = type.BaseType; } while (type != null); throw new MissingFieldException(org.ToString(), name); } else { Type org = type; MethodSignature methodSig = MethodSignature.ReadSig(this, sig, context); do { MethodBase method = type.FindMethod(name, methodSig); if (method != null) { return method; } type = type.BaseType; } while (type != null); return universe.GetMissingMethodOrThrow(org, name, methodSig); } }
public ImportContext(ReflectionHelper helper, IGenericParameterProvider provider) { m_helper = helper; m_genContext = new GenericContext (provider); }