/// <summary> /// Initializes a new instance of the <see cref="GenericParamRow" /> struct. /// </summary> /// <param name="number">The number.</param> /// <param name="flags">The flags.</param> /// <param name="owner">The owner.</param> /// <param name="nameString">The name string.</param> public GenericParamRow(ushort number, GenericParameterAttributes flags, Token owner, HeapIndexToken nameString) { Number = number; Flags = flags; Owner = owner; NameString = nameString; }
public GenericParameterStructure(string name, GenericParameterAttributes attr, IReadOnlyList<CilStructure> constant, Type info = null) { GenericAttributes = attr; Constraints = constant; Info = info; base.Initialize(name, 0); }
/// <summary> /// Initializes a new instance of the <see cref="GenericParamRow"/> struct. /// </summary> /// <param name="number">The number.</param> /// <param name="flags">The flags.</param> /// <param name="owner">The owner table idx.</param> /// <param name="nameStringIdx">The name string idx.</param> public GenericParamRow(ushort number, GenericParameterAttributes flags, Token owner, HeapIndexToken nameStringIdx) { this.number = number; this.flags = flags; this.owner = owner; this.nameStringIdx = nameStringIdx; }
public GenericParameter(string name, ushort index, GenericParameterAttributes attributes, IGenericParamProvider owner) : base(new MetaDataRow(index, (ushort)attributes, 0U, 0U)) { this._name = name; if (string.IsNullOrEmpty(name)) { this._name = string.Format("{0}{1}", owner.ParamType == GenericParamType.Type ? "!" : "!!", index); } this._owner = owner; }
public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); string[] typeParamNames = new string[] { "TFirst" }; GenericTypeParameterBuilder[] typeParams = type.DefineGenericParameters(typeParamNames); GenericTypeParameterBuilder firstTypeParam = typeParams[0]; firstTypeParam.SetGenericParameterAttributes(genericParameterAttributes); Assert.Equal(genericParameterAttributes, firstTypeParam.GenericParameterAttributes); }
// // A true result indicates that a type can never be a value type. This is important when testing variance-compatibility. // private static bool ProvablyAGcReferenceType(this Type t) { if (t.IsGenericParameter) { GenericParameterAttributes attributes = t.GenericParameterAttributes; if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { return(true); // generic parameter with a "class" constraint. } } return(t.ProvablyAGcReferenceTypeHelper()); }
public override void Read() { if (this.fullyRead) { return; } for (uint index = 1; index <= this.Count; index++) { bool gotLock = false; System.Threading.Monitor.Enter(this.syncObject, ref gotLock); if (!base.ItemLoaded(index)) { this.fStream.Seek(this.streamOffset + (index - 1) * this.__size, SeekOrigin.Begin); ushort number = this.reader.ReadUInt16(); GenericParameterAttributes flags = ((GenericParameterAttributes)(this.reader.ReadUInt16())); uint ownerIndex; CliMetadataTypeOrMethodDef ownerSource; switch (this.state) { case 2: case 3: ownerIndex = this.reader.ReadUInt32(); break; default: ownerIndex = this.reader.ReadUInt16(); break; } ownerSource = ((CliMetadataTypeOrMethodDef)(ownerIndex & 1)); ownerIndex = ownerIndex >> 1; uint nameIndex; switch (this.state) { case 1: case 3: nameIndex = this.reader.ReadUInt32(); break; default: nameIndex = this.reader.ReadUInt16(); break; } base.InjectLoadedItem(new CliMetadataGenericParameterLockedTableRow(index, this.state, this.metadataRoot, number, flags, ownerSource, ownerIndex, nameIndex), index); } if (gotLock) { System.Threading.Monitor.Exit(this.syncObject); } } this.fullyRead = true; }
private static VarianceModifier GetVariance(GenericParameterAttributes attr) { switch (attr & GenericParameterAttributes.VarianceMask) { case GenericParameterAttributes.Contravariant: return(VarianceModifier.Contravariant); case GenericParameterAttributes.Covariant: return(VarianceModifier.Covariant); default: return(VarianceModifier.Invariant); } }
public void SetUp() { _position = 7; _name = "_parameter"; _namespace = "namespace"; _genericParameterAttributes = (GenericParameterAttributes)7; _parameter = new MutableGenericParameter(_position, _name, _namespace, _genericParameterAttributes); _baseTypeConstraint = typeof(DomainType); _interfaceConstraint = ReflectionObjectMother.GetSomeInterfaceType(); _constrainedParameter = MutableGenericParameterObjectMother.Create(constraints: new[] { _baseTypeConstraint, _interfaceConstraint }.AsOneTime()); }
internal GenericParameterAttributes GetAttributes() { GenericParameterAttributes result = 0; if (_hasClassConstraint) { result |= GenericParameterAttributes.ReferenceTypeConstraint; } if (_hasNewConstraint) { result |= GenericParameterAttributes.DefaultConstructorConstraint; } return(result); }
private RuntimeType?GetBaseType() { if (IsInterface) { return(null); } if (RuntimeTypeHandle.IsGenericVariable(this)) { Type[] constraints = GetGenericParameterConstraints(); RuntimeType baseType = ObjectType; for (int i = 0; i < constraints.Length; i++) { RuntimeType constraint = (RuntimeType)constraints[i]; if (constraint.IsInterface) { continue; } if (constraint.IsGenericParameter) { GenericParameterAttributes special = constraint.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; if ((special & GenericParameterAttributes.ReferenceTypeConstraint) == 0 && (special & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0) { continue; } } baseType = constraint; } if (baseType == ObjectType) { GenericParameterAttributes special = GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; if ((special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { baseType = ValueType; } } return(baseType); } return(RuntimeTypeHandle.GetBaseType(this)); }
// List the variance and special constraint flags. // private static string ListGenericParameterAttributes(Type t) { string retval; GenericParameterAttributes gpa = t.GenericParameterAttributes; GenericParameterAttributes variance = gpa & GenericParameterAttributes.VarianceMask; // Select the variance flags. if (variance == GenericParameterAttributes.None) { retval = "No variance flag;"; } else { if ((variance & GenericParameterAttributes.Covariant) != 0) { retval = "Covariant;"; } else { retval = "Contravariant;"; } } // Select GenericParameterAttributes constraints = gpa & GenericParameterAttributes.SpecialConstraintMask; if (constraints == GenericParameterAttributes.None) { retval += " No special constraints"; } else { if ((constraints & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { retval += " ReferenceTypeConstraint"; } if ((constraints & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { retval += " NotNullableValueTypeConstraint"; } if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { retval += " DefaultConstructorConstraint"; } } return(retval); }
/// <summary> /// Checks if <paramref name="type"/> satisfies all constraints on <paramref name="parameter"/>. /// </summary> /// <param name="parameter">A generic type parameter.</param> /// <param name="type">A <see cref="Type"/> to be checked against <paramref name="parameter"/>.</param> /// <param name="context">The <see cref="TypeContext"/> in which the check is being performed.</param> /// <returns>True if <paramref name="type"/> satisfies all constraints on <paramref name="parameter"/> and can /// be substituted for it in a constructed generic.</returns> public static bool CanCloseGenericParameter(Type parameter, Type type, TypeContext context = TypeContext.Default) { if (parameter == null) { throw new ArgumentNullException(nameof(parameter)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } if (!parameter.IsGenericParameter) { throw new ArgumentException("Not a generic parameter", nameof(parameter)); } if (type.ContainsGenericParameters) { throw new ArgumentException("Not a closed type", nameof(type)); } // Check special attributes GenericParameterAttributes attributes = parameter.GenericParameterAttributes; if ((attributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint) && !type.IsByRef) || (attributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint) && (!type.IsValueType || type.GetInterfaces().Any(x => x.GetGenericTypeDefinition() == typeof(Nullable <>)))) || (attributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint) && !type.IsValueType && type.GetConstructor(Type.EmptyTypes) == null) || (attributes.HasFlag(GenericParameterAttributes.Covariant) && context == TypeContext.MethodParameter) || (attributes.HasFlag(GenericParameterAttributes.Contravariant) && context == TypeContext.MethodReturn)) { return(false); } // Check type constraints Type[] constraints = parameter.GetGenericParameterConstraints(); for (int i = 0; i < constraints.Length; i++) { if (!constraints[i].IsAssignableFrom(type)) { return(false); } } return(true); }
protected override sealed ICliMetadataGenericParameterTableRow ReadElementAt(uint index) { bool gotLock = false; Monitor.Enter(this.syncObject, ref gotLock); if (index == 0) { return(null); } this.fStream.Seek((this.streamOffset + ((index - 1) * this.__size)), SeekOrigin.Begin); ushort number = this.reader.ReadUInt16(); GenericParameterAttributes flags = ((GenericParameterAttributes)(this.reader.ReadUInt16())); uint ownerIndex; CliMetadataTypeOrMethodDef ownerSource; switch (this.state) { case 2: case 3: ownerIndex = this.reader.ReadUInt32(); break; default: ownerIndex = this.reader.ReadUInt16(); break; } ownerSource = ((CliMetadataTypeOrMethodDef)((ownerIndex & 1))); ownerIndex = (ownerIndex >> 1); uint nameIndex; switch (this.state) { case 1: case 3: nameIndex = this.reader.ReadUInt32(); break; default: nameIndex = this.reader.ReadUInt16(); break; } if (gotLock) { Monitor.Exit(this.syncObject); } return(new CliMetadataGenericParameterLockedTableRow(index, this.state, this.metadataRoot, number, flags, ownerSource, ownerIndex, nameIndex)); }
public ParamModifier GetGenericParamModifier(GenericParameterAttributes attributes) { if (attributes.HasFlag(GenericParameterAttributes.Contravariant)) { return(ParamModifier.In); } else if (attributes.HasFlag(GenericParameterAttributes.Covariant)) { return(ParamModifier.Out); } else { return(ParamModifier.None); } }
/// <summary> /// 对泛型参数进行类型推断。 /// </summary> /// <param name="attr">泛型参数的约束。</param> /// <param name="paramType">形参类型。</param> /// <param name="type">实参类型。</param> /// <param name="lowerBoundAttr">要进行下限推断的泛型参数约束。</param> /// <returns>如果泛型参数的类型推断成功,则为 <c>true</c>;否则为 <c>false</c>。</returns> private bool GenericArgumentInferences(GenericParameterAttributes attr, Type paramType, Type type, GenericParameterAttributes lowerBoundAttr) { Contract.Requires(paramType != null && type != null); attr &= GenericParameterAttributes.VarianceMask; if (attr == GenericParameterAttributes.None || !IsReferenceType(type)) { return(ExactInferences(paramType, type)); } if (attr == lowerBoundAttr) { return(LowerBoundInferences(paramType, type)); } return(UpperBoundInferences(paramType, type)); }
public static RefKindInfo ConvertToStructure(this GenericParameterAttributes attributes) { if ((attributes & GenericParameterAttributes.Covariant) == GenericParameterAttributes.Covariant) { return(RefKindInfo.Out); } else if ((attributes & GenericParameterAttributes.Contravariant) == GenericParameterAttributes.Contravariant) { return(RefKindInfo.In); } else { return(RefKindInfo.None); } }
public MutableGenericParameter( int position, string name, string @namespace, GenericParameterAttributes genericParameterAttributes) : base(name, @namespace, attributes: TypeAttributes.Public, genericTypeDefinition: null, typeArguments: EmptyTypes) { Assertion.IsTrue(position >= 0); _position = position; _genericParameterAttributes = genericParameterAttributes; var baseType = genericParameterAttributes.IsSet(GenericParameterAttributes.NotNullableValueTypeConstraint) ? typeof(ValueType) : typeof(object); SetBaseType(baseType); }
protected bool IsSupportedGenericParameter(TypeReference tref) { if (tref is GenericParameter parameter) { //no support for parameter covariance/contrvariance GenericParameterAttributes attrs = parameter.Attributes; bool isout = (attrs & GenericParameterAttributes.Covariant) != 0; bool isin = (attrs & GenericParameterAttributes.Contravariant) != 0; if (isin || isout) { return(false); } } return(true); }
private RoType?ComputeBaseType() { RoType?baseType = ComputeBaseTypeWithoutDesktopQuirk(); if (baseType != null && baseType.IsGenericParameter) { // .NET Framework quirk: a generic parameter whose constraint is another generic parameter reports its BaseType as System.Object // unless that other generic parameter has a "class" constraint. GenericParameterAttributes genericParameterAttributes = baseType.GenericParameterAttributes; if (0 == (genericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint)) { baseType = Loader.GetCoreType(CoreType.Object); } } return(baseType); }
private static void ListGenericParameterAttributes(Type t, StringBuilder target) { GenericParameterAttributes gpa = t.GenericParameterAttributes; GenericParameterAttributes variance = gpa & GenericParameterAttributes.VarianceMask; // Select the variance flags. if (variance == GenericParameterAttributes.None) { target.AppendLine("- No variance flag"); } else { if ((variance & GenericParameterAttributes.Covariant) != 0) { target.AppendLine("- Covariant"); } else { target.AppendLine("- Contravariant"); } } // Select GenericParameterAttributes constraints = gpa & GenericParameterAttributes.SpecialConstraintMask; if (constraints == GenericParameterAttributes.None) { target.AppendLine("- No special constraints"); } else { if ((constraints & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { target.AppendLine("- ReferenceTypeConstraint (class)"); } if ((constraints & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { target.AppendLine("- NotNullableValueTypeConstraint (struct)"); } if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { target.AppendLine("- DefaultConstructorConstraint (new())"); } } }
private static void DisplayGenericParameter(Type tp) { Console.WriteLine(" Type parameter: {0} position {1}", tp, tp.GenericParameterPosition); Type classConstraint = tp.BaseType; foreach (Type genericParameterConstraint in tp.GetGenericParameterConstraints()) { if (genericParameterConstraint.IsInterface) { Console.WriteLine(" Interface constraint: {0}"); } } if (classConstraint != null) { Console.WriteLine(" Base type constraint: {0}", tp.BaseType); } else { Console.WriteLine(" Base type constraint: None"); } GenericParameterAttributes sConstraints = tp.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; if (sConstraints == GenericParameterAttributes.None) { Console.WriteLine(" No special constraints."); } else { if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.DefaultConstructorConstraint)) { Console.WriteLine(" Must have a parameterless constructor."); } if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.ReferenceTypeConstraint)) { Console.WriteLine(" Must be a reference type."); } if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.NotNullableValueTypeConstraint)) { Console.WriteLine(" Must be a non-nullable value type."); } } }
public static bool CanSpecialize(Type type, GenericParameterAttributes attributes) { if (attributes == GenericParameterAttributes.None) { return(true); } // where T : class if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { if (type.IsValueType) { return(false); } } // where T : new if ((attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { // value types always have default constructors if (!type.IsValueType && (type.GetConstructor(Type.EmptyTypes) == null)) { return(false); } } // where T : struct if ((attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { // must be a value type if (!type.IsValueType) { return(false); } // Make sure that the type is not nullable // this is salways guaranteed in C#, but other languages may be different if (Nullable.GetUnderlyingType(type) != null) { return(false); } } // all other fals indicate variance and don't place any actual restrictions on the generic parameters // but rather how they should be used by the compiler return(true); }
public static string? GetConstraints(Type type) { string? result = default; if (type.IsGenericParameter) { GenericParameterAttributes constraints = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; if ((constraints & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { result = "class"; } else if ((constraints & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { var temp = type.GetCustomAttributes().Any(item => item.GetType().Name == "IsUnmanagedAttribute"); if (temp) { return "unmanaged"; } else { return "struct"; } } if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { if (result != default) { result += ", "; } result += "new()"; } } return result; }
public static MutableGenericParameter Create( int position = 7, string name = "T", string @namespace = "MyNs", GenericParameterAttributes genericParameterAttributes = GenericParameterAttributes.None, IEnumerable <Type> constraints = null, IMemberSelector memberSelector = null) { constraints = constraints ?? Type.EmptyTypes; memberSelector = memberSelector ?? new MemberSelector(new BindingFlagsEvaluator()); var genericParameter = new MutableGenericParameter(position, name, @namespace, genericParameterAttributes); genericParameter.SetGenericParameterConstraints(constraints); return(genericParameter); }
private ReflectionConstraints(string name, Type[] constraints, GenericParameterAttributes attributes) { _name = name; _attributes = attributes; var interfaceConstraintsPos = 0; if ((attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { _baseType = TypeManager.CoreTypes.ValueType; interfaceConstraintsPos = 1; } else if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { if (constraints.Length > 0 && constraints[0].IsClass) { _classConstraint = _baseType = constraints[0]; interfaceConstraintsPos = 1; } else { _baseType = TypeManager.CoreTypes.Object; } } else { _baseType = TypeManager.CoreTypes.Object; } if (constraints.Length > interfaceConstraintsPos) { if (interfaceConstraintsPos == 0) { _interfaceConstraints = constraints; } else { _interfaceConstraints = new Type[constraints.Length - interfaceConstraintsPos]; Array.Copy(constraints, interfaceConstraintsPos, _interfaceConstraints, 0, _interfaceConstraints.Length); } } else { _interfaceConstraints = Type.EmptyTypes; } }
// Try and identify obviously invalid type substitutions. // // It is ok if we miss some, as we catch the exception that will // arise when instantating with an invalid type. static bool AreConstraintsSatisfied(Type type, Type parameterType) { bool areConstraintsSatisfied = true; // Check special constraints GenericParameterAttributes gpa = parameterType.GenericParameterAttributes; if ((gpa & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { if (type.IsValueType) { areConstraintsSatisfied = false; } } // If all special constaints are satisfied, check type constraints if (areConstraintsSatisfied) { Type[] constraints = parameterType.GetGenericParameterConstraints(); foreach (Type c in constraints) { if (c.IsClass) { // Base Type Constraint if (!type.IsSubclassOf(c)) // variance probably needs other checks { areConstraintsSatisfied = false; break; } } else { // Interface constraint if (!type.IsInstanceOfType(c)) { areConstraintsSatisfied = false; break; } } } } return(areConstraintsSatisfied); }
private StringBuilder AppendGenericParameterConstraints(StringBuilder buf, GenericParameter type) { if (MemberFormatterState != MemberFormatterState.WithinGenericTypeParameters) { return(buf.Append(type.Owner is TypeReference ? "!" : "!!")); } GenericParameterAttributes attrs = type.Attributes; if ((attrs & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { buf.Append("class "); } if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { buf.Append("struct "); } if ((attrs & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { buf.Append(".ctor "); } IList <TypeReference> constraints = type.Constraints; MemberFormatterState = 0; if (constraints.Count > 0) { var full = new ILFullMemberFormatter(); buf.Append("(").Append(full.GetName(constraints[0])); for (int i = 1; i < constraints.Count; ++i) { buf.Append(", ").Append(full.GetName(constraints[i])); } buf.Append(") "); } MemberFormatterState = MemberFormatterState.WithinGenericTypeParameters; if ((attrs & GenericParameterAttributes.Covariant) != 0) { buf.Append("+ "); } if ((attrs & GenericParameterAttributes.Contravariant) != 0) { buf.Append("- "); } return(buf); }
private ReflectionConstraints (string name, Type [] constraints, GenericParameterAttributes attrs) { this.name = name; this.attrs = attrs; if ((constraints.Length > 0) && !constraints [0].IsInterface) { class_constraint = constraints [0]; iface_constraints = new Type [constraints.Length - 1]; Array.Copy (constraints, 1, iface_constraints, 0, constraints.Length - 1); } else iface_constraints = constraints; if (HasValueTypeConstraint) base_type = TypeManager.value_type; else if (class_constraint != null) base_type = class_constraint; else base_type = TypeManager.object_type; }
/// <summary> /// 将所给函数的限制列表(where)打印成代码 /// </summary> public static string MethodConstraintsToString(MethodInfo givenMethod) { if (givenMethod.IsGenericMethodDefinition && givenMethod.IsGenericMethod) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); var genericParameters = givenMethod.GetGenericArguments(); for (int i = 0; i < genericParameters.Length; i++) { var genericParameter = genericParameters [i]; string content = string.Empty; GenericParameterAttributes constraints = genericParameter.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; //class if ((constraints & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { content += "class,"; } //new if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { content += "new(),"; } var paramTypeConstraints = genericParameter.GetGenericParameterConstraints(); foreach (var paramTypeConstraint in paramTypeConstraints) { content += TypeToString(paramTypeConstraint); content += ","; } if (!string.IsNullOrEmpty(content)) { content = content.Substring(0, content.Length - 1); builder.Append(" where "); builder.Append(genericParameter.Name); builder.Append(" : "); builder.Append(content); } } return(builder.ToString()); } return(string.Empty); }
private PETypeParameterSymbol( PEModuleSymbol moduleSymbol, Symbol definingSymbol, ushort ordinal, GenericParameterHandle handle ) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)definingSymbol != null); Debug.Assert(ordinal >= 0); Debug.Assert(!handle.IsNil); _containingSymbol = definingSymbol; GenericParameterAttributes flags = 0; try { moduleSymbol.Module.GetGenericParamPropsOrThrow(handle, out _name, out flags); } catch (BadImageFormatException) { if ((object)_name == null) { _name = string.Empty; } _lazyCachedConstraintsUseSiteInfo.Initialize( new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this) ); } // Clear the '.ctor' flag if both '.ctor' and 'valuetype' are // set since '.ctor' is redundant in that case. _flags = ((flags & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0) ? flags : (flags & ~GenericParameterAttributes.DefaultConstructorConstraint); _ordinal = ordinal; _handle = handle; }
public void TestGenericParameterAttributeWithNoneOption() { AssemblyName myAsmName = new AssemblyName("GenericEmitExample1"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, myAsmName.Name); Type baseType = typeof(ExampleBase); TypeBuilder myType = myModule.DefineType("Sample", TypeAttributes.Public); string[] typeParamNames = { "TFirst" }; GenericTypeParameterBuilder[] typeParams = myType.DefineGenericParameters(typeParamNames); GenericTypeParameterBuilder TFirst = typeParams[0]; GenericParameterAttributes gPA = GenericParameterAttributes.None; TFirst.SetGenericParameterAttributes(gPA); Assert.True(TFirst.GenericParameterAttributes.Equals(gPA)); }
private StringBuilder AppendGenericParameterConstraints(StringBuilder buf, GenericParameter type, DynamicParserContext context) { if (MemberFormatterState != MemberFormatterState.WithinGenericTypeParameters) { return(buf); } GenericParameterAttributes attrs = type.Attributes; bool isout = (attrs & GenericParameterAttributes.Covariant) != 0; bool isin = (attrs & GenericParameterAttributes.Contravariant) != 0; if (isin) { buf.Append("In "); } else if (isout) { buf.Append("Out "); } return(buf); }
public static bool IsHasConstraints(TypeInfo type, TypeInfo parameters) { GenericParameterAttributes constraints = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; if (constraints == GenericParameterAttributes.None) { return(true); } if (ContainsAnyFlag(constraints, GenericParameterAttributes.ReferenceTypeConstraint)) { if (!parameters.IsClass && !parameters.IsInterface) { return(false); } } if (ContainsAnyFlag(constraints, GenericParameterAttributes.NotNullableValueTypeConstraint)) { if (!parameters.IsValueType) { return(false); } if (parameters.IsGenericType && parameters.GetGenericTypeDefinition() != typeof(Nullable <>)) { return(false); } } if (ContainsAnyFlag(constraints, GenericParameterAttributes.DefaultConstructorConstraint)) { if (!CanCreateInstanceUsingDefaultConstructor(parameters)) { return(false); } } return(true); }
/// <summary> /// 检查泛型类型参数是否满足泛型委托类型的显示类型转换。 /// </summary> /// <param name="arg">类型参数定义。</param> /// <param name="inputArg">输入泛型类型参数。</param> /// <param name="outputArg">输出泛型类型参数。</param> /// <returns>如果满足泛型委托类型的显示类型转换,则为 <c>true</c>;否则为 <c>false</c>。</returns> private static bool CheckGenericArguments(Type arg, Type inputArg, Type outputArg) { Contract.Requires(arg != null && inputArg != null && outputArg != null); if (inputArg == outputArg) { return(true); } GenericParameterAttributes attrs = arg.GenericParameterAttributes & GenericParameterAttributes.VarianceMask; if (attrs == GenericParameterAttributes.None || inputArg.IsValueType || outputArg.IsValueType) { return(false); } if (attrs == GenericParameterAttributes.Contravariant) { return(true); } Conversion conversion = GetConversion(inputArg, outputArg); return(conversion != null && conversion.ConversionType.IsReference()); }
/// <summary> /// If this type is a generic parameter, for example the T in List of T, /// get the attributes and constraints, otherwise return false. /// </summary> public bool TryGetGenericParameterAttributesAndConstraints( out GenericParameterAttributes parameterAttributes, out ImmutableArray <MrType> constraints) { parameterAttributes = GenericParameterAttributes.None; constraints = ImmutableArray <MrType> .Empty; if (!IsGenericParameter) { return(false); } // Get the GenericParameter struct from its handle var genericParameter = this.Assembly.Reader.GetGenericParameter(this.GenericParameterHandle.Value); // Set the [out] value with the attributes (things like Covariant and ReferenceConstraint) parameterAttributes = genericParameter.Attributes; // Get the constraint handles (if any). Things like String in "where T : String" var genericConstraintHandles = genericParameter.GetConstraints(); var count = genericConstraintHandles.Count; if (count == 0) { // The [out] attributes were already set, and there are no type constraints return(true); } // Convert the constraint handles into types var constraintList = new List <MrType>(count); foreach (var genericConstraintHandle in genericConstraintHandles) { var genericConstraint = this.Assembly.Reader.GetGenericParameterConstraint(genericConstraintHandle); constraintList.Add(this.Assembly.GetTypeFromEntityHandle(genericConstraint.Type, this.TypeDefinition)); } constraints = constraintList.ToImmutableArray(); // [out] parameter return(true); }
private PETypeParameterSymbol( PEModuleSymbol moduleSymbol, Symbol definingSymbol, ushort ordinal, GenericParameterHandle handle) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)definingSymbol != null); Debug.Assert(ordinal >= 0); Debug.Assert(!handle.IsNil); _containingSymbol = definingSymbol; GenericParameterAttributes flags = 0; try { moduleSymbol.Module.GetGenericParamPropsOrThrow(handle, out _name, out flags); } catch (BadImageFormatException) { if ((object)_name == null) { _name = string.Empty; } //_lazyBoundsErrorInfo = new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this); } // Clear the '.ctor' flag if both '.ctor' and 'valuetype' are // set since '.ctor' is redundant in that case. _flags = ((flags & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0) ? flags : (flags & ~GenericParameterAttributes.DefaultConstructorConstraint); _ordinal = ordinal; _handle = handle; }
private bool GetConstraint(GenericParameterAttributes constraintMask, GenericParameterAttributes constraint) { return (constraintMask & constraint) == constraint; }
public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes) { this.attr = genericParameterAttributes; // for now we'll back patch the table this.ModuleBuilder.GenericParam.PatchAttribute(paramPseudoIndex, genericParameterAttributes); }
internal void SetGenParamAttributes(GenericParameterAttributes genericParameterAttributes) { m_genParamAttributes = genericParameterAttributes; }
public void ValidateGenericParamTable() { // AppCS - 7 var expNames = new string[] { "V", "CT", "CO", "T", "CT1", "CO1", "T1" }; var expFlags = new GenericParameterAttributes[] { /* 4 */ GenericParameterAttributes.ReferenceTypeConstraint, /* 6 */ GenericParameterAttributes.ReferenceTypeConstraint | GenericParameterAttributes.Contravariant, /* 1 */ GenericParameterAttributes.Covariant, /* 0 */ GenericParameterAttributes.None, /* 4 */ GenericParameterAttributes.ReferenceTypeConstraint, /* 0x10 */ GenericParameterAttributes.DefaultConstructorConstraint, // Mask 001C /* 0 */ GenericParameterAttributes.None }; var expNumber = new ushort[] { 0, 0, 0, 0, 0, 0, 0 }; var expTypeTokens = new int[] { 0x06000003, 0x02000004, 0x02000005, 0x02000006, 0x02000007, 0x02000008, 0x02000009, }; // --------------------------------------------------- // ModuleCS01 - 5 var modNames = new string[] { "T", "T", "R", "T", "X" }; var modFlags = new GenericParameterAttributes[] { /* 0 */ GenericParameterAttributes.None, /* 4 */ GenericParameterAttributes.ReferenceTypeConstraint, /* 4 */ GenericParameterAttributes.ReferenceTypeConstraint, /* 4 */ GenericParameterAttributes.ReferenceTypeConstraint, /* 0 */ GenericParameterAttributes.None }; var modNumber = new ushort[] { 0, 0, 1, 0, 0 }; var modTypeTokens = new int[] { 0x02000006, 0x02000007, 0x02000007, 0x02000008, 0x06000025, }; var reader = GetMetadataReader(NetModule.AppCS); // Validity Rules Assert.Equal(expNames.Length, reader.GenericParamTable.NumberOfRows); for (int i = 0; i < reader.GenericParamTable.NumberOfRows; i++) { var handle = GenericParameterHandle.FromRowId(i + 1); Assert.Equal(expNames[i], reader.GetString(reader.GenericParamTable.GetName(handle))); Assert.Equal(expFlags[i], reader.GenericParamTable.GetFlags(handle)); Assert.Equal(expNumber[i], reader.GenericParamTable.GetNumber(handle)); Assert.Equal(expTypeTokens[i], reader.GenericParamTable.GetOwner(handle).Token); } // ======================================= reader = GetMetadataReader(NetModule.ModuleCS01, true); // Validity Rules Assert.Equal(modNames.Length, reader.GenericParamTable.NumberOfRows); for (int i = 0; i < reader.GenericParamTable.NumberOfRows; i++) { var handle = GenericParameterHandle.FromRowId(i + 1); Assert.Equal(modNames[i], reader.GetString(reader.GenericParamTable.GetName(handle))); Assert.Equal(modFlags[i], reader.GenericParamTable.GetFlags(handle)); Assert.Equal(modNumber[i], reader.GenericParamTable.GetNumber(handle)); Assert.Equal(modTypeTokens[i], reader.GenericParamTable.GetOwner(handle).Token); } }
/// <summary> /// Resolve the constraints - but only resolve things into Expression's, not /// into actual types. /// </summary> public bool Resolve (IResolveContext ec) { if (resolved) return true; iface_constraints = new ArrayList (2); // TODO: Too expensive allocation type_param_constraints = new ArrayList (); foreach (object obj in constraints) { if (HasConstructorConstraint) { Report.Error (401, loc, "The new() constraint must be the last constraint specified"); return false; } if (obj is SpecialConstraint) { SpecialConstraint sc = (SpecialConstraint) obj; if (sc == SpecialConstraint.Constructor) { if (!HasValueTypeConstraint) { attrs |= GenericParameterAttributes.DefaultConstructorConstraint; continue; } Report.Error (451, loc, "The `new()' constraint " + "cannot be used with the `struct' constraint"); return false; } if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) { Report.Error (449, loc, "The `class' or `struct' " + "constraint must be the first constraint specified"); return false; } if (sc == SpecialConstraint.ReferenceType) attrs |= GenericParameterAttributes.ReferenceTypeConstraint; else attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint; continue; } int errors = Report.Errors; FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false); if (fn == null) { if (errors != Report.Errors) return false; NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ()); return false; } TypeExpr expr; GenericTypeExpr cexpr = fn as GenericTypeExpr; if (cexpr != null) { expr = cexpr.ResolveAsBaseTerminal (ec, false); } else expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false); if ((expr == null) || (expr.Type == null)) return false; if (!ec.GenericDeclContainer.IsAccessibleAs (fn.Type)) { Report.SymbolRelatedToPreviousError (fn.Type); Report.Error (703, loc, "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'", fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ()); return false; } TypeParameterExpr texpr = expr as TypeParameterExpr; if (texpr != null) type_param_constraints.Add (expr); else if (expr.IsInterface) iface_constraints.Add (expr); else if (class_constraint != null || iface_constraints.Count != 0) { Report.Error (406, loc, "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list", expr.GetSignatureForError ()); return false; } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) { Report.Error (450, loc, "`{0}': cannot specify both " + "a constraint class and the `class' " + "or `struct' constraint", expr.GetSignatureForError ()); return false; } else class_constraint = expr; num_constraints++; } ArrayList list = new ArrayList (); foreach (TypeExpr iface_constraint in iface_constraints) { foreach (Type type in list) { if (!type.Equals (iface_constraint.Type)) continue; Report.Error (405, loc, "Duplicate constraint `{0}' for type " + "parameter `{1}'.", iface_constraint.GetSignatureForError (), name); return false; } list.Add (iface_constraint.Type); } foreach (TypeParameterExpr expr in type_param_constraints) { foreach (Type type in list) { if (!type.Equals (expr.Type)) continue; Report.Error (405, loc, "Duplicate constraint `{0}' for type " + "parameter `{1}'.", expr.GetSignatureForError (), name); return false; } list.Add (expr.Type); } iface_constraint_types = new Type [list.Count]; list.CopyTo (iface_constraint_types, 0); if (class_constraint != null) { class_constraint_type = class_constraint.Type; if (class_constraint_type == null) return false; if (class_constraint_type.IsSealed) { if (class_constraint_type.IsAbstract) { Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints", TypeManager.CSharpName (class_constraint_type)); } else { Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " + "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type)); } return false; } if ((class_constraint_type == TypeManager.array_type) || (class_constraint_type == TypeManager.delegate_type) || (class_constraint_type == TypeManager.enum_type) || (class_constraint_type == TypeManager.value_type) || (class_constraint_type == TypeManager.object_type) || class_constraint_type == TypeManager.multicast_delegate_type) { Report.Error (702, loc, "A constraint cannot be special class `{0}'", TypeManager.CSharpName (class_constraint_type)); return false; } } if (class_constraint_type != null) effective_base_type = class_constraint_type; else if (HasValueTypeConstraint) effective_base_type = TypeManager.value_type; else effective_base_type = TypeManager.object_type; if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) attrs |= GenericParameterAttributes.DefaultConstructorConstraint; resolved = true; return true; }
internal void SetGenericParameterAttributes(GenericParameterAttributes attributes) { throw new NotImplementedException(); }
public void SetGenericParameterAttributes (GenericParameterAttributes genericParameterAttributes) { throw new PlatformNotSupportedException (); }
private static bool ContainsAnyFlag(GenericParameterAttributes attributes, GenericParameterAttributes flags) { return (attributes & flags) != GenericParameterAttributes.None; }
} // Write public static void Write(this NativeWriter writer, GenericParameterAttributes value) { writer.WriteUnsigned((uint)value); } // Write
public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes) { m_type.SetGenParamAttributes(genericParameterAttributes); }
/// <summary> /// Initializes a new instance of the <see cref="GenericParameter"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="flags">The flags.</param> public GenericParameter(string name, GenericParameterAttributes flags) { this.name = name; this.flags = flags; }
public static bool GenericParameterAttrTest(GenericParameterAttributes parameterAttrs, GenericParameterAttributes testAttrs) { return ((parameterAttrs & testAttrs) == testAttrs); }
private bool MappingHasConstraint(GenericParameterAttributes constraint) { var constraints = this.Mapping.Argument.GenericParameterAttributes; return (constraints & constraint) != GenericParameterAttributes.None; }
public GenericParameterHandle AddGenericParameter( EntityHandle parent, GenericParameterAttributes attributes, StringHandle name, int index) { _genericParamTable.Add(new GenericParamRow { Flags = (ushort)attributes, Name = name, Number = (ushort)index, Owner = (uint)CodedIndex.ToTypeOrMethodDef(parent) }); return MetadataTokens.GenericParameterHandle(_genericParamTable.Count); }
} // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (GenericParameterAttributes)ivalue; return offset; } // Read
/// <summary> /// 对泛型参数进行类型推断。 /// </summary> /// <param name="attr">泛型参数的约束。</param> /// <param name="paramType">形参类型。</param> /// <param name="type">实参类型。</param> /// <param name="lowerBoundAttr">要进行下限推断的泛型参数约束。</param> /// <returns>如果泛型参数的类型推断成功,则为 <c>true</c>;否则为 <c>false</c>。</returns> private bool GenericArgumentInferences(GenericParameterAttributes attr, Type paramType, Type type, GenericParameterAttributes lowerBoundAttr) { Contract.Requires(paramType != null && type != null); attr &= GenericParameterAttributes.VarianceMask; if (attr == GenericParameterAttributes.None || !IsReferenceType(type)) { return ExactInferences(paramType, type); } if (attr == lowerBoundAttr) { return LowerBoundInferences(paramType, type); } return UpperBoundInferences(paramType, type); }
public GenericParamRow CreateGenericParamRow (ushort _number, GenericParameterAttributes _flags, MetadataToken _owner, uint _name) { GenericParamRow row = new GenericParamRow (); row.Number = _number; row.Flags = _flags; row.Owner = _owner; row.Name = _name; return row; }
private extern static int DefineGenericParam(RuntimeModule module, String name, int tkParent, GenericParameterAttributes attributes, int position, int[] constraints);
private static bool MatchesConstraints(GenericParameterAttributes attributes, Type[] constraints, Type target) { if (constraints.Length == 0 && attributes == GenericParameterAttributes.None) { return true; } for (int i = 0; i < constraints.Length; i++) { if (!constraints[i].IsAssignableFrom(target)) { return false; } } if (attributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint)) { if (target.GetConstructor(new Type[0]) == null) return false; } if (attributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint)) { if (!(target.IsClass || target.IsInterface)) return false; } if (attributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint)) { if (!(target.IsValueType && !target.IsNullable())) return false; } return true; }
public void SetGenericParameterAttributes (GenericParameterAttributes genericParameterAttributes) { this.attrs = genericParameterAttributes; }
private static bool IsGenericArgumentTypeSupported ( Type argumentType, Type[] supportedTypes, bool allowOpen = false, bool allowClosed = true, GenericParameterAttributes allowedParameterAttributes = GenericParameterAttributes.SpecialConstraintMask | GenericParameterAttributes.DefaultConstructorConstraint | GenericParameterAttributes.VarianceMask, GenericParameterAttributes requiredParameterAttributes = GenericParameterAttributes.None ) { if (argumentType.IsGenericParameter) return allowOpen && (argumentType.GenericParameterAttributes & ~allowedParameterAttributes) == GenericParameterAttributes.None && (argumentType.GenericParameterAttributes & requiredParameterAttributes) == requiredParameterAttributes; else if (!allowClosed) return false; foreach (var supportedType in supportedTypes) if (argumentType == supportedType) return true; return false; }
public void GetGenericParamProps(int genericParameter, out GenericParameterAttributes attributes) { int num; _GetGenericParamProps(this.m_metadataImport2, out MetadataArgs.Skip, genericParameter, out num); attributes = (GenericParameterAttributes) num; }
[System.Security.SecurityCritical] // auto-generated public void GetGenericParamProps( int genericParameter, out GenericParameterAttributes attributes) { int _attributes; _GetGenericParamProps(m_metadataImport2, genericParameter, out _attributes); attributes = (GenericParameterAttributes)_attributes; }