/// <summary> /// Constrcuts a new GenericMapping for a specific mapping of generic parameters to type arguments. /// </summary> /// <param name="parameters">The generic parameters that should be mapped.</param> /// <param name="arguments">The type arguments to map generic parameters to.</param> protected GenericMapping(IGenericParameter[] parameters, IType[] arguments) { for (int i = 0; i < parameters.Length; i++) { _map.Add(parameters[i], arguments[i]); } }
private IEnumerable <Action> GetConstraints(IGenericParameter parameter) { if (parameter.MustBeValueType) { yield return(() => WriteKeyword("struct", noSpace: true)); } else { if (parameter.MustBeReferenceType) { yield return(() => WriteKeyword("class", noSpace: true)); } } foreach (var constraint in parameter.Constraints) { // Skip valuetype because we should get it below. if (TypeHelper.TypesAreEquivalent(constraint, constraint.PlatformType.SystemValueType) && parameter.MustBeValueType) { continue; } yield return(() => WriteTypeName(constraint, noSpace: true)); } // new constraint cannot be put on structs and needs to be the last constraint if (!parameter.MustBeValueType && parameter.MustHaveDefaultConstructor) { yield return () => { WriteKeyword("new", noSpace: true); WriteSymbol("("); WriteSymbol(")"); } } ; } }
/// <summary> /// Creates a generic parameter specialization from a generic parameter /// and a parent type that is itself an (indirect) generic type. /// </summary> /// <param name="declaration"> /// The generic parameter to specialize. /// </param> /// <param name="parentMember"> /// A specialization of the generic declaration's parent member. /// </param> /// <returns>A specialization of the generic declaration.</returns> internal static IndirectGenericParameterSpecialization Create( IGenericParameter declaration, IGenericMember parentMember) { return(instanceCache.Intern( new IndirectGenericParameterSpecialization(declaration, parentMember))); }
private void InitializeClosureDependencies() { foreach (TypedArgument argument in Arguments) { BlockExpression closure = argument.Expression as BlockExpression; if (closure == null) { continue; } // ICallableType callableType = closure.ExpressionType as ICallableType; ICallableType callableType = argument.FormalType as ICallableType; if (callableType == null) { continue; } TypeCollector collector = new TypeCollector(delegate(IType t) { IGenericParameter gp = t as IGenericParameter; return(gp != null && InferredTypes.ContainsKey(gp)); }); foreach (IType inputType in GetParameterTypes(callableType.GetSignature())) { collector.Visit(inputType); } foreach (IGenericParameter gp in collector.Matches) { RecordClosureDependency(closure, gp); } } }
private IEnumerable <string> GetConstraints(IGenericParameter parameter) { if (parameter.MustBeValueType) { yield return("struct"); } else { if (parameter.MustBeReferenceType) { yield return("class"); } if (parameter.MustHaveDefaultConstructor) { yield return("new()"); } } foreach (var constraint in parameter.Constraints) { // Skip valuetype becaue we should get it above. if (TypeHelper.TypesAreEquivalent(constraint, constraint.PlatformType.SystemValueType) && parameter.MustBeValueType) { continue; } yield return(constraint.FullName()); } }
public virtual void Visit(IGenericParameter genericParameter) { this.Visit(genericParameter.GetAttributes(Context)); this.Visit(genericParameter.GetConstraints(Context)); genericParameter.Dispatch(this); }
private void NoteGenericParameterFlow(ITypeDefinition actual, IGenericParameter formal) { if (createInstanceStrategy == TypeVariableCreateInstanceStrategy.ConstructAllConcreteParameters) { if (!(actual is IGenericParameter)) { // actual is concrete ITypeDefinition unspecializedConcreteType = GarbageCollectHelper.UnspecializeAndResolveTypeReference(actual); unspecializedTypesPassedAsTypeVariables.Add(unspecializedConcreteType); if (GarbageCollectHelper.TypeIsConstructable(unspecializedConcreteType)) { // t-devinc: We should associate a reason with this construction found ConstructionFound(unspecializedConcreteType); IMethodDefinition defaultConstructor = TypeHelper.GetMethod(unspecializedConcreteType, wholeProgram.Host().NameTable.GetNameFor(".ctor")); if (!(defaultConstructor is Dummy)) { // t-devinc: Add reason for this NotePotentialNonVirtualMethodReachedForReason(defaultConstructor, null); } } } } }
/// <summary> /// Maps a type involving generic parameters to the corresponding type after substituting concrete /// arguments for generic parameters. /// </summary> /// <remarks> /// If the source type is a generic parameter, it is mapped to the corresponding argument. /// If the source type is an open generic type using any of the specified generic parameters, it /// is mapped to a closed constructed type based on the specified arguments. /// </remarks> override public IType MapType(IType sourceType) { if (sourceType == _genericSource) { return(_constructedOwner as IType); } IGenericParameter gp = sourceType as IGenericParameter; if (gp != null) { // Map type parameters declared on our source if (_map.ContainsKey(gp)) { return(_map[gp]); } // Map type parameters declared on members of our source (methods / nested types) return(GenericsServices.GetGenericParameters(Map(gp.DeclaringEntity))[gp.GenericParameterPosition]); } // TODO: Map nested types // GenericType[of T].NestedType => GenericType[of int].NestedType return(base.MapType(sourceType)); }
/// <summary> /// Adds a generic parameter to this generic member. /// </summary> /// <param name="genericParameter">The generic parameter to add.</param> public void AddGenericParameter(IGenericParameter genericParameter) { ContractHelpers.Assert( object.Equals(this, genericParameter.ParentMember), "Generic parameters can only be added to their declaring member."); genericParamList.Add(genericParameter); }
public override void Visit(IGenericParameter genericParameter) { if (Process(genericParameter)) { visitor.Visit(genericParameter); } base.Visit(genericParameter); }
/// <summary> /// Constrcuts a new GenericMapping for a specific mapping of generic parameters to type arguments. /// </summary> /// <param name="parameters">The generic parameters that should be mapped.</param> /// <param name="arguments">The type arguments to map generic parameters to.</param> protected GenericMapping(TypeSystemServices tss, IGenericParameter[] parameters, IType[] arguments) { _tss = tss; for (int i = 0; i < parameters.Length; i++) { _map.Add(parameters[i], arguments[i]); } }
private void RecordClosureDependency(BlockExpression closure, IGenericParameter genericParameter) { if (!_closureDependencies.ContainsKey(closure)) { _closureDependencies.Add(closure, new List <InferredType>()); } _closureDependencies[closure].AddUnique(InferredTypes[genericParameter]); }
private bool Fix(IGenericParameter genericParameter, InferredType inferredType) { if (inferredType.Fix()) { Context.TraceVerbose("Generic parameter {0} fixed to {1}.", genericParameter.Name, inferredType.ResultingType); return(true); } return(false); }
private void NoteTypeVariableConstructed(IGenericParameter typeVariable) { if (constructedGenericParameters.Count() == 0) { NoteFirstTypeVariableConstructed(); } constructedGenericParameters.Add(typeVariable); }
protected override bool InferGenericParameter(IGenericParameter formalType, IType actualType, TypeInference inference) { // Generic parameters occuring in closures are a result of untyped input types and should be skipped if (_currentClosure != null && actualType == formalType) { return(true); } return(base.InferGenericParameter(formalType, actualType, inference)); }
/// <summary> /// Checks if a specified type argument violates the constraints /// declared on a specified type paramter. /// </summary> public bool ViolatesParameterConstraints(IGenericParameter parameter, TypeReference argumentNode) { IType argument = TypeSystemServices.GetEntity(argumentNode) as IType; // Ensure argument is a valid type if (argument == null || TypeSystemServices.IsError(argument)) { return(false); } bool valid = true; // Check type semantics constraints if (parameter.IsClass && !argument.IsClass) { Errors.Add(CompilerErrorFactory.GenericArgumentMustBeReferenceType(ConstructionNode, parameter, argument)); valid = false; } if (parameter.IsValueType && !argument.IsValueType) { Errors.Add(CompilerErrorFactory.GenericArgumentMustBeValueType(argumentNode, parameter, argument)); valid = false; } // Check for default constructor if (parameter.MustHaveDefaultConstructor && !HasDefaultConstructor(argument)) { Errors.Add(CompilerErrorFactory.GenericArgumentMustHaveDefaultConstructor(argumentNode, parameter, argument)); valid = false; } // Check base type constraints IType[] baseTypes = parameter.GetTypeConstraints(); if (baseTypes != null) { foreach (IType baseType in baseTypes) { // Don't check for System.ValueType supertype constraint // if parameter also has explicit value type constraint if (baseType == _tss.ValueTypeType && parameter.IsValueType) { continue; } if (!baseType.IsAssignableFrom(argument)) { Errors.Add(CompilerErrorFactory.GenericArgumentMustHaveBaseType(argumentNode, parameter, argument, baseType)); valid = false; } } } return(!valid); }
private void WriteGenericParameter(IGenericParameter param) { switch (param.Variance) { case TypeParameterVariance.Contravariant: WriteKeyword("in"); break; case TypeParameterVariance.Covariant: WriteKeyword("out"); break; } WriteTypeName(param, noSpace: true); }
private void WriteGenericParameter(IGenericParameter param) { switch (param.Variance) { case TypeParameterVariance.Contravariant: WriteKeyword("in"); break; case TypeParameterVariance.Covariant: WriteKeyword("out"); break; } WriteTypeName(param, noSpace: true); }
public IType GetInferredType(IGenericParameter gp) { if (InferredTypes.ContainsKey(gp)) { return InferredTypes[gp].ResultingType; } else { return null; } }
void _IIntermediateGenericType <TTypeIdentifier> .ItemRemoved(IGenericParameter parameter) { const int DISP_STATE_DISPOSING = 1; lock (this.SyncObject) if (this.disposeState == DISP_STATE_DISPOSING) { return; } this.OnTypeParameterRemoved(arg1: (IIntermediateGenericTypeParameter <TTypeIdentifier, TType, TIntermediateType>)parameter); }
public IType GetInferredType(IGenericParameter gp) { if (InferredTypes.ContainsKey(gp)) { return(InferredTypes[gp].ResultingType); } else { return(null); } }
private void LoadGenericParameters() { var declaringGenericParameters = _declaringType.GenericParameters; var genericParameters = new IGenericParameter[declaringGenericParameters.Count]; for (int i = 0; i < genericParameters.Length; i++) { genericParameters[i] = new ReferencedGenericParameter(declaringGenericParameters[i], this); } _genericParameters = ReadOnlyList <IGenericParameter> .Create(genericParameters); }
private IType BoxTypeArgumentIfNecessary(IType typeArgument, IGenericParameter parameter) { if (parameter.IsReferenceType()) { // Already pre-boxed. return(typeArgument); } else { return(TypeHelpers.BoxIfReferenceType(typeArgument)); } }
private IEnumerable<Action> GetConstraints(IGenericParameter parameter, byte? methodNullableContextValue) { parameter.Attributes.TryGetAttributeOfType(CSharpCciExtensions.NullableAttributeFullName, out ICustomAttribute nullableAttribute); object nullableAttributeValue = nullableAttribute.GetAttributeArgumentValue<byte>() ?? methodNullableContextValue ?? TypeNullableContextValue ?? ModuleNullableContextValue; if (parameter.MustBeValueType) yield return () => WriteKeyword("struct", noSpace: true); else { if (parameter.MustBeReferenceType) yield return () => { WriteKeyword("class", noSpace: true); if (nullableAttribute != null) { WriteNullableSymbolForReferenceType(nullableAttributeValue, arrayIndex: 0); } }; } // If there are no struct or class constraints and contains a nullableAttributeValue then it might have a notnull constraint if (!parameter.MustBeValueType && !parameter.MustBeReferenceType && nullableAttributeValue != null) { if (((byte)nullableAttributeValue & 1) != 0) { yield return () => WriteKeyword("notnull", noSpace: true); } } var assemblyLocation = parameter.Locations.FirstOrDefault()?.Document?.Location; int constraintIndex = 0; foreach (var constraint in parameter.Constraints) { // Skip valuetype because we should get it above. if (!TypeHelper.TypesAreEquivalent(constraint, constraint.PlatformType.SystemValueType) && !parameter.MustBeValueType) { if (assemblyLocation != null) { nullableAttributeValue = parameter.GetGenericParameterConstraintConstructorArgument(constraintIndex, assemblyLocation, _metadataReaderCache, CSharpCciExtensions.NullableConstructorArgumentParser) ?? nullableAttributeValue; } constraintIndex++; yield return () => WriteTypeName(constraint, noSpace: true, nullableAttributeArgument: nullableAttributeValue ?? methodNullableContextValue ?? TypeNullableContextValue ?? ModuleNullableContextValue); } } // new constraint cannot be put on structs and needs to be the last constraint if (!parameter.MustBeValueType && parameter.MustHaveDefaultConstructor) yield return () => { WriteKeyword("new", noSpace: true); WriteSymbol("("); WriteSymbol(")"); }; }
/// <summary> /// Yields the generic parameters used in a (bound) type. /// </summary> public static IEnumerable <IGenericParameter> FindGenericParameters(IType type) { IGenericParameter genericParameter = type as IGenericParameter; if (genericParameter != null) { yield return(genericParameter); yield break; } if (type is IArrayType) { foreach (IGenericParameter gp in FindGenericParameters(type.ElementType)) { yield return(gp); } yield break; } if (type.ConstructedInfo != null) { foreach (IType typeArgument in type.ConstructedInfo.GenericArguments) { foreach (IGenericParameter gp in FindGenericParameters(typeArgument)) { yield return(gp); } } yield break; } ICallableType callableType = type as ICallableType; if (callableType != null) { CallableSignature signature = callableType.GetSignature(); foreach (IGenericParameter gp in FindGenericParameters(signature.ReturnType)) { yield return(gp); } foreach (IParameter parameter in signature.Parameters) { foreach (IGenericParameter gp in FindGenericParameters(parameter.Type)) { yield return(gp); } } yield break; } }
public static string PrintConstraints(IGenericParameter genpar) { bool first = true; StringBuilder cstr = new StringBuilder(); if (genpar.MustBeReferenceType) { cstr.Append("class"); first = false; } if (genpar.MustBeValueType) { cstr.Append("struct"); first = false; } foreach (var c in genpar.Constraints) { if (TypeHelper.TypesAreEquivalent(c, c.PlatformType.SystemValueType)) { continue; } if (first) { first = false; } else { cstr.Append(","); } cstr.Append(GetSignature(c.ResolvedType)); } if (genpar.MustHaveDefaultConstructor && !genpar.MustBeValueType) { if (first) { first = false; } else { cstr.Append(","); } cstr.Append("new ()"); } return(cstr.ToString()); }
public override bool Resolve(List targetList, string name, EntityType flags) { // Try to resolve name as a generic parameter if (NameResolutionService.IsFlagSet(flags, EntityType.Type)) { IGenericParameter gp = GetGenericParameter(name); if (gp != null) { targetList.Add(gp); return(true); } } return(base.Resolve(targetList, name, flags)); }
public bool Resolve(List targetList, string name, EntityType filter) { if (_type.GenericInfo != null && filter == EntityType.Type) { IGenericParameter match = Array.Find( _type.GenericInfo.GenericParameters, delegate(IGenericParameter gp) { return(gp.Name == name); }); if (match != null) { targetList.AddUnique(match); return(true); } } return(false); }
private bool FixAll(Predicate <InferredType> predicate) { bool wasFixed = false; foreach (KeyValuePair <IGenericParameter, InferredType> kvp in InferredTypes) { IGenericParameter gp = kvp.Key; InferredType inferredType = kvp.Value; if (!inferredType.Fixed && predicate(inferredType)) { wasFixed |= Fix(gp, inferredType); } } return(wasFixed); }
protected virtual bool InferGenericParameter(IGenericParameter formalType, IType actualType, TypeInference inference) { if (InferredTypes.ContainsKey(formalType)) { InferredType inferredType = InferredTypes[formalType]; if ((inference & TypeInference.AllowContravariance) != TypeInference.AllowContravariance) { inferredType.ApplyLowerBound(actualType); } if ((inference & TypeInference.AllowCovariance) != TypeInference.AllowCovariance) { inferredType.ApplyUpperBound(actualType); } } return(true); }
/// <summary> /// Determines whether two types are equivalent (Cecil/Reflector) /// </summary> /// <param name="typeref">Cecil type reference</param> /// <param name="type">Reflector type reference</param> /// <returns>true if equivalent</returns> private static bool TypeMatches(TypeReference typeref, IType type) { if (type is ITypeReference) { var ityperef = (ITypeReference)type; if (typeref.Namespace == ityperef.Namespace && IsSameName(typeref.Name, ityperef.Name)) { if (typeref.DeclaringType != null && (ityperef.Owner) is ITypeReference) { return(TypeMatches(typeref.DeclaringType, ((ITypeReference)ityperef.Owner))); } else { return(true); } } return(false); } else if (type is IGenericParameter) { IGenericParameter igenprm = (IGenericParameter)type; return(typeref.Name.StartsWith(igenprm.Name)); } else if (type is IGenericArgument) { IGenericArgument igenarg = (IGenericArgument)type; return(TypeMatches(typeref, igenarg.Owner.GenericArguments[igenarg.Position])); } else if ((type is IArrayType) && (typeref is ArrayType)) { IArrayType iarrtyp = (IArrayType)type; return(TypeMatches(((ArrayType)typeref).ElementType, iarrtyp.ElementType)); } else if ((type is IReferenceType) && (typeref is ByReferenceType)) { IReferenceType iref = (IReferenceType)type; return(TypeMatches(((ByReferenceType)typeref).ElementType, iref.ElementType)); } else if ((type is IPointerType) && (typeref is PointerType)) { IPointerType ipt = (IPointerType)type; return(TypeMatches(((PointerType)typeref).ElementType, ipt.ElementType)); } return(false); }
private DifferenceType DiffConstraints(IDifferences differences, IReference target, IEnumerable <IGenericParameter> implGenericParams, IEnumerable <IGenericParameter> contractGenericParams) { int beforeCount = differences.Count(); IGenericParameter[] implParams = implGenericParams.ToArray(); IGenericParameter[] contractParams = contractGenericParams.ToArray(); // We shoudn't hit this because the types/members shouldn't be matched up if they have different generic argument lists if (implParams.Length != contractParams.Length) { return(DifferenceType.Changed); } for (int i = 0; i < implParams.Length; i++) { IGenericParameter implParam = implParams[i]; IGenericParameter contractParam = contractParams[i]; if (contractParam.Variance != TypeParameterVariance.NonVariant && contractParam.Variance != implParam.Variance) { differences.AddIncompatibleDifference("CannotChangeVariance", "Variance on generic parameter '{0}' for '{1}' is '{2}' in the implementation but '{3}' in the contract.", implParam.FullName(), target.FullName(), implParam.Variance, contractParam.Variance); } string implConstraints = string.Join(",", GetConstraints(implParam).OrderBy(s => s, StringComparer.OrdinalIgnoreCase)); string contractConstraints = string.Join(",", GetConstraints(contractParam).OrderBy(s => s, StringComparer.OrdinalIgnoreCase)); if (!string.Equals(implConstraints, contractConstraints)) { differences.AddIncompatibleDifference("CannotChangeGenericConstraints", "Constraints for generic parameter '{0}' for '{1}' is '{2}' in the implementation but '{3}' in the contract.", implParam.FullName(), target.FullName(), implConstraints, contractConstraints); } } if (differences.Count() != beforeCount) { return(DifferenceType.Changed); } return(DifferenceType.Unknown); }
/// <summary> /// Attempts to infer the type of generic parameters that occur in a formal parameter type /// according to its actual argument type. /// </summary> /// <returns>False if inference failed; otherwise, true. </returns> protected bool Infer(IType formalType, IType actualType, TypeInference inference) { // Skip unspecified actual types if (actualType == null) { return(true); } IGenericParameter gp = formalType as IGenericParameter; if (null != gp) { return(InferGenericParameter(gp, actualType, inference)); } ICallableType callableType = formalType as ICallableType; if (null != callableType) { return(InferCallableType(callableType, actualType, inference)); } if (formalType.ConstructedInfo != null) { return(InferConstructedType(formalType, actualType, inference)); } IArrayType arrayType = formalType as IArrayType; if (null != arrayType) { return(InferArrayType(arrayType, actualType, inference)); } if (formalType.IsByRef) { return(Infer(formalType.ElementType, actualType, inference)); } return(InferSimpleType(formalType, actualType, inference)); }
/// <summary> /// Test whether one generic argument equals another /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (this == obj) { return(true); } IGenericParameter igp = obj as IGenericParameter; if (igp == null) { return(false); } if (this.Name != igp.Name || //(!this.Owner.Equals(igp.Owner)) || this.Position != igp.Position || this.Constraints.Count != igp.Constraints.Count || this.Attributes.Count != igp.Attributes.Count) { return(false); } for (int i = 0; i < this.Constraints.Count; i++) { if (!this.Constraints[i].Equals(igp.Constraints[i])) { return(false); } } for (int i = 0; i < this.Attributes.Count; i++) { if (!this.Attributes[i].Equals(igp.Attributes[i])) { return(false); } } return(true); }
private IEnumerable<string> GetConstraints(IGenericParameter parameter) { if (parameter.MustBeValueType) yield return "struct"; else { if (parameter.MustBeReferenceType) yield return "class"; if (parameter.MustHaveDefaultConstructor) yield return "new()"; } foreach (var constraint in parameter.Constraints) { // Skip valuetype becaue we should get it above. if (TypeHelper.TypesAreEquivalent(constraint, constraint.PlatformType.SystemValueType) && parameter.MustBeValueType) continue; yield return constraint.FullName(); } }
private IEnumerable<Action> GetConstraints(IGenericParameter parameter) { if (parameter.MustBeValueType) yield return () => WriteKeyword("struct", noSpace: true); else { if (parameter.MustBeReferenceType) yield return () => WriteKeyword("class", noSpace: true); } foreach (var constraint in parameter.Constraints) { // Skip valuetype becaue we should get it below. if (TypeHelper.TypesAreEquivalent(constraint, constraint.PlatformType.SystemValueType) && parameter.MustBeValueType) continue; yield return () => WriteTypeName(constraint, noSpace: true); } // new constaint cannot be put on structs and needs to be the last constraint if (!parameter.MustBeValueType && parameter.MustHaveDefaultConstructor) yield return () => { WriteKeyword("new", noSpace: true); WriteSymbol("("); WriteSymbol(")"); }; }
/// <summary> /// Performs some computation with the given generic parameter. /// </summary> public virtual void Visit(IGenericParameter genericParameter) { this.Visit((INamedTypeDefinition)genericParameter); }
private void SetDependency(IGenericParameter dependant, IGenericParameter dependee) { InferredTypes[dependant].SetDependencyOn(InferredTypes[dependee]); }
private void InitializeDependencies(IGenericParameter[] genericParameters, CallableSignature signature) { IType[] parameterTypes = GetParameterTypes(signature); foreach (IType parameterType in parameterTypes) { ICallableType callableParameterType = parameterType as ICallableType; if (callableParameterType == null) continue; CalculateDependencies(callableParameterType.GetSignature()); } }
public void DeclareGenericParameters(INodeWithGenericParameters node, IGenericParameter[] parameters) { DeclareGenericParameters(node, parameters, 0); }
public static CompilerError GenericArgumentMustHaveDefaultConstructor(Node node, IGenericParameter parameter, IType argument) { return new CompilerError("BCE0148", SafeLexicalInfo(node), argument, parameter); }
protected override bool InferGenericParameter(IGenericParameter formalType, IType actualType, TypeInference inference) { // Generic parameters occuring in closures are a result of untyped input types and should be skipped if (_currentClosure != null && actualType == formalType) return true; return base.InferGenericParameter(formalType, actualType, inference); }
private bool Fix(IGenericParameter genericParameter, InferredType inferredType) { if (inferredType.Fix()) { Context.TraceVerbose("Generic parameter {0} fixed to {1}.", genericParameter.Name, inferredType.ResultingType); return true; } return false; }
private static IDictionary<IType, IType> CreateDictionaryMapping(IGenericParameter[] from, IGenericParameter[] to) { var mappings = new Dictionary<IType, IType>(from.Length); for (int i=0; i<from.Length; ++i) mappings.Add(from[i], to[i]); return mappings; }
public static CompilerError GenericArgumentMustBeValueType(Node node, IGenericParameter parameter, IType argument) { return new CompilerError("BCE0147", SafeLexicalInfo(node), argument, parameter); }
public static CompilerError GenericArgumentMustHaveBaseType(Node node, IGenericParameter parameter, IType argument, IType baseType) { return Instantiate("BCE0149", node, argument, baseType, parameter, parameter.DeclaringEntity); }
public static CompilerError GenericArgumentMustHaveBaseType(Node node, IGenericParameter parameter, IType argument, IType baseType) { return new CompilerError("BCE0149", SafeLexicalInfo(node), argument, parameter, baseType); }
public GenericMappedTypeParameter(TypeSystemServices tss, IGenericParameter source, GenericMapping mapping) : base(tss) { _source = source; _mapping = mapping; }
/// <summary> /// Performs some computation with the given generic parameter. /// </summary> public void Visit(IGenericParameter genericParameter) { this.Visit((INamedTypeDefinition)genericParameter); Hashtable constraintTable = null; foreach (var constraint in genericParameter.Constraints) { if (constraint.TypeCode == PrimitiveTypeCode.Void) this.ReportError(MetadataError.ConstraintMayNotBeVoid, constraint, genericParameter); if (constraintTable == null) constraintTable = new Hashtable(); var key = constraint.InternedKey; if (constraintTable.Find(key) == 0) constraintTable.Add(key, key); else this.ReportError(MetadataError.DuplicateConstraint, constraint, genericParameter); } }
/// <summary> /// Checks if a specified type argument violates the constraints /// declared on a specified type paramter. /// </summary> public bool ViolatesParameterConstraints(IGenericParameter parameter, IType argument) { // Ensure argument is a valid type if (argument == null || TypeSystemServices.IsError(argument)) { return false; } bool valid = true; // Check type semantics constraints if (parameter.IsClass && !argument.IsClass) { Errors.Add(CompilerErrorFactory.GenericArgumentMustBeReferenceType(ConstructionNode, parameter, argument)); valid = false; } if (parameter.IsValueType && !argument.IsValueType) { Errors.Add(CompilerErrorFactory.GenericArgumentMustBeValueType(ConstructionNode, parameter, argument)); valid = false; } if (parameter.MustHaveDefaultConstructor && !HasDefaultConstructor(argument)) { Errors.Add(CompilerErrorFactory.GenericArgumentMustHaveDefaultConstructor(ConstructionNode, parameter, argument)); valid = false; } // Check base type constraints IType[] baseTypes = parameter.GetTypeConstraints(); if (baseTypes != null) { foreach (IType baseType in baseTypes) { // Don't check for System.ValueType supertype constraint // if parameter also has explicit value type constraint if (baseType == _tss.ValueTypeType && parameter.IsValueType) continue; if (!baseType.IsAssignableFrom(argument)) { Errors.Add(CompilerErrorFactory.GenericArgumentMustHaveBaseType(ConstructionNode, parameter, argument, baseType)); valid = false; } } } return !valid; }
public static CompilerError GenericArgumentMustBeValueType(Node node, IGenericParameter parameter, IType argument) { return Instantiate("BCE0147", node, argument, parameter, parameter.DeclaringEntity); }
public static CompilerError GenericArgumentMustHaveDefaultConstructor(Node node, IGenericParameter parameter, IType argument) { return Instantiate("BCE0148", node, argument, parameter, parameter.DeclaringEntity); }
private void NoteGenericParameterFlow(ITypeDefinition actual, IGenericParameter formal) { if (createInstanceStrategy == TypeVariableCreateInstanceStrategy.ConstructAllConcreteParameters) { if (!(actual is IGenericParameter)) { // actual is concrete ITypeDefinition unspecializedConcreteType = GarbageCollectHelper.UnspecializeAndResolveTypeReference(actual); unspecializedTypesPassedAsTypeVariables.Add(unspecializedConcreteType); if (GarbageCollectHelper.TypeIsConstructable(unspecializedConcreteType)) { // t-devinc: We should associate a reason with this construction found ConstructionFound(unspecializedConcreteType); IMethodDefinition defaultConstructor = TypeHelper.GetMethod(unspecializedConcreteType, wholeProgram.Host().NameTable.GetNameFor(".ctor")); if (!(defaultConstructor is Dummy)) { // t-devinc: Add reason for this NotePotentialNonVirtualMethodReachedForReason(defaultConstructor, null); } } } } }
/// <summary> /// Visits the specified generic parameter. /// </summary> /// <param name="genericParameter">The generic parameter.</param> public virtual void Visit(IGenericParameter genericParameter) { if (this.stopTraversal) return; //^ int oldCount = this.path.Count; this.path.Push(genericParameter); this.Visit(genericParameter.Attributes); this.Visit(genericParameter.Constraints); //^ assume this.path.Count == oldCount; //True because all of the virtual methods of this class promise not decrease this.path.Count. this.path.Pop(); genericParameter.Dispatch(this); }
/// <summary> /// Traverses the children of the generic parameter. /// </summary> public virtual void TraverseChildren(IGenericParameter genericParameter) { Contract.Requires(genericParameter != null); this.TraverseChildren((INamedTypeDefinition)genericParameter); if (this.stopTraversal) return; this.Traverse(genericParameter.Constraints); }
private void RecordClosureDependency(BlockExpression closure, IGenericParameter genericParameter) { if (!_closureDependencies.ContainsKey(closure)) { _closureDependencies.Add(closure, new List<InferredType>()); } _closureDependencies[closure].AddUnique(InferredTypes[genericParameter]); }
public void DeclareGenericParameters(INodeWithGenericParameters node, IGenericParameter[] parameters, int parameterIndexDelta) { for (int i=0; i < parameters.Length; ++i) { var prototype = parameters[i]; var newParameter = CreateGenericParameterDeclaration(parameterIndexDelta + i, prototype.Name); node.GenericParameters.Add(newParameter); } }
public override void Visit(IGenericParameter genericParameter) { this.Visit(genericParameter.GetAttributes(Context)); this.VisitTypeReferencesThatNeedTokens(genericParameter.GetConstraints(Context)); }
public virtual void Visit(IGenericParameter genericParameter) { this.Visit(genericParameter.GetAttributes(Context)); this.Visit(genericParameter.GetConstraints(Context)); genericParameter.Dispatch(this); }
protected virtual bool InferGenericParameter(IGenericParameter formalType, IType actualType, TypeInference inference) { if (InferredTypes.ContainsKey(formalType)) { InferredType inferredType = InferredTypes[formalType]; if ((inference & TypeInference.AllowContravariance) != TypeInference.AllowContravariance) { inferredType.ApplyLowerBound(actualType); } if ((inference & TypeInference.AllowCovariance) != TypeInference.AllowCovariance) { inferredType.ApplyUpperBound(actualType); } } return true; }