protected override ArgumentReference[] GetBaseCtorArguments(Type targetFieldType, ProxyGenerationOptions proxyGenerationOptions, out IConstructorInfo baseConstructor) { if (proxyGenerationOptions.Selector == null) { baseConstructor = InvocationMethods.CompositionInvocationConstructorNoSelector; return new[] { new ArgumentReference(targetFieldType), new ArgumentReference(typeof(object)), new ArgumentReference(typeof(IInterceptor[])), new ArgumentReference(typeof(IMethodInfo)), new ArgumentReference(typeof(object[])), }; } baseConstructor = InvocationMethods.CompositionInvocationConstructorWithSelector; return new[] { new ArgumentReference(targetFieldType), new ArgumentReference(typeof(object)), new ArgumentReference(typeof(IInterceptor[])), new ArgumentReference(typeof(IMethodInfo)), new ArgumentReference(typeof(object[])), new ArgumentReference(typeof(IInterceptorSelector)), new ArgumentReference(typeof(IInterceptor[]).MakeByRefType()) }; }
public void ConstructorWrapper(Type type) { ConstructorInfo target = type.GetConstructors(All)[0]; IConstructorInfo info = GetConstructor(target); WrapperAssert.AreEquivalent(target, info, false); }
internal UnresolvedConstructorInfo(IConstructorInfo adapter) { if (adapter == null) throw new ArgumentNullException("adapter"); this.adapter = adapter; }
protected IConstructorInfo GetConstructor(ConstructorInfo member) { IConstructorInfo wrapper = GetType(member.DeclaringType).GetConstructors(All)[0]; Assert.IsNotNull(wrapper, "Could not find constructor '{0}'.", member); return(wrapper); }
public void AccessorCreatesNewObjectsThroughSlotBinding() { DataSource source = new DataSource("data"); source.AddDataSet(new ItemSequenceDataSet(new IDataItem[] { new ListDataItem <object>(new object[] { 42, typeof(int) }, null, false) }, 2)); IDataSourceResolver resolver = Mocks.StrictMock <IDataSourceResolver>(); using (Mocks.Record()) { Expect.Call(resolver.ResolveDataSource("data")).Repeat.Twice().Return(source); } using (Mocks.Playback()) { ITypeInfo type = Reflector.Wrap(typeof(Holder <>)); IConstructorInfo constructor = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; ISlotInfo valueSlot = constructor.Parameters[0]; ISlotInfo typeSlot = (IGenericParameterInfo)type.GenericArguments[0]; DataBindingContext context = new DataBindingContext(new NullConverter()); ObjectDataBinder binder = new ObjectDataBinder(type); binder.SetSlotBinder(valueSlot, new ScalarDataBinder(new DataBinding(0, null), "data")); binder.SetSlotBinder(typeSlot, new ScalarDataBinder(new DataBinding(1, null), "data")); IDataAccessor accessor = binder.Register(context, resolver); List <IDataItem> items = new List <IDataItem>(context.GetItems(true)); Assert.Count(1, items); Holder <int> holder = (Holder <int>)accessor.GetValue(items[0]); Assert.AreEqual(42, holder.Value, "Should have set the value via the constructor parameter."); } }
protected override ArgumentReference[] GetBaseCtorArguments(Type targetFieldType, ProxyGenerationOptions proxyGenerationOptions, out IConstructorInfo baseConstructor) { if (proxyGenerationOptions.Selector == null) { baseConstructor = InvocationMethods.InheritanceInvocationConstructorNoSelector; return(new[] { new ArgumentReference(typeof(Type)), new ArgumentReference(typeof(object)), new ArgumentReference(typeof(IInterceptor[])), new ArgumentReference(typeof(IMethodInfo)), new ArgumentReference(typeof(object[])) }); } baseConstructor = InvocationMethods.InheritanceInvocationConstructorWithSelector; return(new[] { new ArgumentReference(typeof(Type)), new ArgumentReference(typeof(object)), new ArgumentReference(typeof(IInterceptor[])), new ArgumentReference(typeof(IMethodInfo)), new ArgumentReference(typeof(object[])), new ArgumentReference(typeof(IInterceptorSelector)), new ArgumentReference(typeof(IInterceptor[]).MakeByRefType()) }); }
public void EmitNewobj(IConstructorInfo constructorInfo) { if (constructorInfo == null) { throw new ArgumentNullException(nameof(constructorInfo)); } generator.Emit(OpCodes.Newobj, ((EmitConstructorInfo)constructorInfo).ConstructorInfo); }
internal UnresolvedConstructorInfo(IConstructorInfo adapter) { if (adapter == null) { throw new ArgumentNullException("adapter"); } this.adapter = adapter; }
public ILGeneration(IILGenerator generator, CodeGenerationStore store, CurrentMethodInfo currentMethodInfo, IType[] delegateConstructorTypes, IConstructorInfo baseConstructorCall, SimpleTypeChecker typeChecker) { this.generator = generator; this.store = store; this.currentMethodInfo = currentMethodInfo; this.delegateConstructorTypes = delegateConstructorTypes; this.baseConstructorCall = baseConstructorCall; this.typeChecker = typeChecker; }
private bool IsConstructorVisible(IConstructorInfo constructor) { return(constructor.IsPublic || constructor.IsFamily || constructor.IsFamilyOrAssembly #if !Silverlight || (constructor.IsAssembly && InternalsUtil.IsInternalToDynamicProxy(constructor.DeclaringType.Assembly()))); #else ; #endif }
internal static ConstructorInfo AsConstructorInfo(this IConstructorInfo wrapper) { if (wrapper is ConstructorInfoWrapper) { return((ConstructorInfo)((ConstructorInfoWrapper)wrapper).Inner); } else { throw new NotSupportedException(string.Format("Cannot handle '{0}'.", wrapper.GetType())); } }
/// <summary> /// Verifies that the attribute is being used correctly. /// </summary> /// <param name="containingScope">The containing scope.</param> /// <param name="constructor">The constructor.</param> /// <exception cref="PatternUsageErrorException">Thrown if the attribute is being used incorrectly.</exception> protected virtual void Validate(IPatternScope containingScope, IConstructorInfo constructor) { if (!containingScope.CanAddTestParameter || constructor == null) { ThrowUsageErrorException("This attribute can only be used on a test type constructor."); } if (constructor.IsStatic) { ThrowUsageErrorException("This attribute cannot be used on a static constructor."); } }
private static object[] GetConstructorAndArgs(Type attributeType, Attribute attribute, out IConstructorInfo ctor) { ctor = attributeType.GetConstructors()[0].AsIConstructorInfo(); var constructorParams = ctor.GetParameters(); if (constructorParams.Length == 0) { return new object[0]; } return InitializeConstructorArgs(attributeType, attribute, constructorParams); }
/// <inheritdoc /> public override void Consume(IPatternScope containingScope, ICodeElementInfo codeElement, bool skipChildren) { //TODO: Review: Issue 762: Shouldn't the base method be invoked here? //base.Consume(containingScope, codeElement, skipChildren); IConstructorInfo constructor = codeElement as IConstructorInfo; Validate(containingScope, constructor); IPatternScope dataContextScope = containingScope.CreateChildTestDataContextScope(codeElement); InitializeDataContext(dataContextScope, constructor); }
protected ConstructorDeclarationSyntax ResolveConstructor(IConstructorInfo ctor, SyntaxToken name) { IReadOnlyList <IParameterInfo> paramz = ctor.Parameters; return(ConstructorDeclaration ( name ) .WithModifiers ( modifiers: TokenList ( Token(SyntaxKind.PublicKeyword) ) ) .WithParameterList ( parameterList: ParameterList ( paramz.ToSyntaxList ( param => Parameter ( identifier: Identifier(param.Name) ) .WithType ( type: ResolveType(param.Type) ) ) ) ) .WithInitializer ( initializer: ConstructorInitializer ( SyntaxKind.BaseConstructorInitializer, ArgumentList ( paramz.ToSyntaxList ( param => Argument ( expression: IdentifierName(param.Name) ) ) ) ) ) .WithBody(Block())); }
/// <summary> /// Consumes type constructors. /// </summary> /// <param name="typeScope">The scope to be used as the containing scope.</param> /// <param name="type">The type whose constructors are to be consumed.</param> protected void ConsumeConstructors(IPatternScope typeScope, ITypeInfo type) { if (ShouldConsumeConstructors(type)) { // FIXME: Currently we arbitrarily choose the first constructor and throw away the rest. // This should be replaced by a more intelligent mechanism that supports a constructor // selection policy based on some criterion. IConstructorInfo constructor = GetFirstConstructorWithPreferenceForPublicConsructor(type); if (constructor != null) { typeScope.Consume(constructor, false, DefaultConstructorPattern); } } }
private bool VerifyIfBaseImplementsGetObjectData(Type baseType, IList <IMethodInfo> methodsToSkip) { if (!typeof(ISerializable).IsAssignableFrom(baseType)) { return(false); } if (IsDelegate(baseType)) { //working around bug in CLR which returns true for "does this type implement ISerializable" for delegates return(false); } // If base type implements ISerializable, we have to make sure // the GetObjectData is marked as virtual var getObjectDataMethod = baseType.GetInterfaceMap(typeof(ISerializable)).TargetMethods[0]; if (getObjectDataMethod.IsPrivate) //explicit interface implementation { return(false); } if (!getObjectDataMethod.IsVirtual || getObjectDataMethod.IsFinal) { var message = String.Format("The type {0} implements ISerializable, but GetObjectData is not marked as virtual. " + "Dynamic Proxy needs types implementing ISerializable to mark GetObjectData as virtual " + "to ensure correct serialization process.", baseType.FullName); throw new ArgumentException(message); } methodsToSkip.Add(getObjectDataMethod); serializationConstructor = baseType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null); if (serializationConstructor == null) { var message = String.Format("The type {0} implements ISerializable, " + "but failed to provide a deserialization constructor", baseType.FullName); throw new ArgumentException(message); } return(true); }
internal static ConstructorInfo AsConstructorInfo(this IConstructorInfo info) { if (info == null) { return(null); } if (info is ConstructorInfoWrapper) { return(((ConstructorInfoWrapper)info).Inner); } else { throw new NotSupportedException(string.Format("Cannot handle '{0}'.", info.GetType())); } }
/// <summary> /// Initializes the <see cref="PatternTestDataContext" />. /// </summary> /// <param name="dataContextScope">The data context scope.</param> /// <param name="constructor">The constructor.</param> protected virtual void InitializeDataContext(IPatternScope dataContextScope, IConstructorInfo constructor) { ITypeInfo declaringType = constructor.DeclaringType; if (declaringType.IsGenericTypeDefinition) { dataContextScope.TestDataContextBuilder.ImplicitDataBindingIndexOffset = declaringType.GenericArguments.Count; } foreach (IParameterInfo parameter in constructor.Parameters) { dataContextScope.Consume(parameter, false, DefaultConstructorParameterPattern); } dataContextScope.Process(constructor); }
private static IConstructorInfo GetFirstConstructorWithPreferenceForPublicConsructor(ITypeInfo type) { IConstructorInfo result = null; foreach (IConstructorInfo constructor in type.GetConstructors(ConstructorBindingFlags)) { if (constructor.IsPublic) { return(constructor); } if (result == null) { result = constructor; } } return(result); }
/// <summary> /// Resolves a reflected constructor to its native <see cref="ConstructorInfo" /> object. /// </summary> /// <param name="constructor">The reflected constructor.</param> /// <param name="throwOnError">If true, throws an exception if resolution fails, /// otherwise returns an unresolved <see cref="ConstructorInfo" />.</param> /// <returns>The resolved <see cref="ConstructorInfo" />.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="constructor"/> /// is null.</exception> /// <exception cref="ReflectionResolveException">Thrown if <paramref name="constructor"/> /// could not be resolved.</exception> public static ConstructorInfo ResolveConstructor(IConstructorInfo constructor, bool throwOnError) { if (constructor == null) { throw new ArgumentNullException("constructor"); } try { Type resolvedType = constructor.DeclaringType.Resolve(throwOnError); if (!Reflector.IsUnresolved(resolvedType)) { BindingFlags bindingFlags = (constructor.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) | (constructor.IsStatic ? BindingFlags.Static : BindingFlags.Instance); Type[] resolvedParameterTypes = ResolveParameterTypes(constructor.Parameters); ConstructorInfo resolvedConstructor = resolvedType.GetConstructor( bindingFlags, null, resolvedParameterTypes, null); if (resolvedConstructor != null) { return(resolvedConstructor); } } } catch (Exception ex) { if (throwOnError) { throw new ReflectionResolveException(constructor, ex); } } if (throwOnError) { throw new ReflectionResolveException(constructor); } return(UnresolvedCodeElementFactory.Instance.Wrap(constructor)); }
public void SpecPropertiesDescribeTheObject() { ITypeInfo type = Reflector.Wrap(typeof(GenericClass <>)); IConstructorInfo constructor = type.GetConstructors(PublicInstance)[1]; IParameterInfo constructorParameter = constructor.Parameters[0]; IFieldInfo field = type.GetFields(PublicInstance)[0]; IPropertyInfo property = type.GetProperties(PublicInstance)[0]; Dictionary <ISlotInfo, object> slotValues = new Dictionary <ISlotInfo, object>(); slotValues.Add((IGenericParameterInfo)type.GenericArguments[0], typeof(int)); slotValues.Add(constructorParameter, 1); slotValues.Add(field, 2); slotValues.Add(property, 3); ObjectCreationSpec spec = new ObjectCreationSpec(type, slotValues, NullConverter.Instance); Assert.AreSame(type, spec.Type); Assert.AreSame(slotValues, spec.SlotValues); Assert.AreSame(NullConverter.Instance, spec.Converter); Assert.AreEqual(typeof(GenericClass <int>), spec.ResolvedType); Assert.AreEqual(constructor, Reflector.Wrap(spec.ResolvedConstructor)); Assert.AreElementsEqual(new object[] { 1 }, spec.ResolvedConstructorArguments); List <KeyValuePair <FieldInfo, object> > fieldValues = new List <KeyValuePair <FieldInfo, object> >(spec.ResolvedFieldValues); Assert.Count(1, fieldValues); Assert.AreEqual(field, Reflector.Wrap(fieldValues[0].Key)); Assert.AreEqual(2, fieldValues[0].Value); List <KeyValuePair <PropertyInfo, object> > propertyValues = new List <KeyValuePair <PropertyInfo, object> >(spec.ResolvedPropertyValues); Assert.Count(1, propertyValues); Assert.AreEqual(property, Reflector.Wrap(propertyValues[0].Key)); Assert.AreEqual(3, propertyValues[0].Value); }
public void EmitNewobj(IConstructorInfo constructor) { OpCodes.AddCallInstruction(constructor, "newobj"); }
public void EmitConstructorCall(IConstructorInfo constructorInfo) { OpCodes.AddCallInstruction(constructorInfo, "call"); }
protected override ClassDeclarationSyntax ResolveConstructor(ClassDeclarationSyntax cls, object context, IConstructorInfo ctor) => cls.AddMembers ( ResolveConstructor(ctor, cls.Identifier) );
public Constructor(IConstructorInfo constructorInfo) { _constructorInfo = constructorInfo; _parameters = constructorInfo.GetParameters(); }
internal static IConstructorInfo GetConstructor(Type invocationType, IConstructorInfo constructor) { return TypeBuilder.GetConstructor(invocationType, constructor.AsConstructorInfo()).AsIConstructorInfo(); }
private bool VerifyIfBaseImplementsGetObjectData(Type baseType, IList<IMethodInfo> methodsToSkip) { if (!typeof(ISerializable).IsAssignableFrom(baseType)) { return false; } if (IsDelegate(baseType)) { //working around bug in CLR which returns true for "does this type implement ISerializable" for delegates return false; } // If base type implements ISerializable, we have to make sure // the GetObjectData is marked as virtual var getObjectDataMethod = baseType.GetInterfaceMap(typeof(ISerializable)).TargetMethods[0]; if (getObjectDataMethod.IsPrivate) //explicit interface implementation { return false; } if (!getObjectDataMethod.IsVirtual || getObjectDataMethod.IsFinal) { var message = String.Format("The type {0} implements ISerializable, but GetObjectData is not marked as virtual. " + "Dynamic Proxy needs types implementing ISerializable to mark GetObjectData as virtual " + "to ensure correct serialization process.", baseType.FullName); throw new ArgumentException(message); } methodsToSkip.Add(getObjectDataMethod); serializationConstructor = baseType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null); if (serializationConstructor == null) { var message = String.Format("The type {0} implements ISerializable, " + "but failed to provide a deserialization constructor", baseType.FullName); throw new ArgumentException(message); } return true; }
/// <summary> /// Creates a <see cref="ConstructorInfo" /> wrapper for <see cref="IConstructorInfo" />. /// </summary> /// <param name="adapter">The adapter.</param> /// <returns>The unresolved constructor.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception> public abstract ConstructorInfo Wrap(IConstructorInfo adapter);
/// <summary> /// Resolves a reflected constructor to its native <see cref="ConstructorInfo" /> object. /// </summary> /// <param name="constructor">The reflected constructor.</param> /// <param name="throwOnError">If true, throws an exception if resolution fails, /// otherwise returns an unresolved <see cref="ConstructorInfo" />.</param> /// <returns>The resolved <see cref="ConstructorInfo" />.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="constructor"/> /// is null.</exception> /// <exception cref="ReflectionResolveException">Thrown if <paramref name="constructor"/> /// could not be resolved.</exception> public static ConstructorInfo ResolveConstructor(IConstructorInfo constructor, bool throwOnError) { if (constructor == null) throw new ArgumentNullException("constructor"); try { Type resolvedType = constructor.DeclaringType.Resolve(throwOnError); if (!Reflector.IsUnresolved(resolvedType)) { BindingFlags bindingFlags = (constructor.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) | (constructor.IsStatic ? BindingFlags.Static : BindingFlags.Instance); Type[] resolvedParameterTypes = ResolveParameterTypes(constructor.Parameters); ConstructorInfo resolvedConstructor = resolvedType.GetConstructor( bindingFlags, null, resolvedParameterTypes, null); if (resolvedConstructor != null) return resolvedConstructor; } } catch (Exception ex) { if (throwOnError) throw new ReflectionResolveException(constructor, ex); } if (throwOnError) throw new ReflectionResolveException(constructor); return UnresolvedCodeElementFactory.Instance.Wrap(constructor); }
/// <inheritdoc /> public bool Equals(IConstructorInfo other) { return Equals((object)other); }
public override ConstructorInfo Wrap(IConstructorInfo adapter) { return new UnresolvedConstructorInfo(adapter); }
public bool Equals(IConstructorInfo other) { return(Equals((object)other)); }
protected internal override ClassDeclarationSyntax ResolveConstructor(ClassDeclarationSyntax cls, object context, IConstructorInfo ctor) => throw new NotImplementedException();
protected void GenerateConstructor(ClassEmitter emitter, IConstructorInfo baseConstructor, params FieldReference[] fields) { ArgumentReference[] args; ParameterInfo[] baseConstructorParams = null; if (baseConstructor != null) { baseConstructorParams = baseConstructor.GetParameters(); } if (baseConstructorParams != null && baseConstructorParams.Length != 0) { args = new ArgumentReference[fields.Length + baseConstructorParams.Length]; var offset = fields.Length; for (var i = offset; i < offset + baseConstructorParams.Length; i++) { var paramInfo = baseConstructorParams[i - offset]; args[i] = new ArgumentReference(paramInfo.ParameterType); } } else { args = new ArgumentReference[fields.Length]; } for (var i = 0; i < fields.Length; i++) { args[i] = new ArgumentReference(fields[i].Reference.FieldType); } var constructor = emitter.CreateConstructor(args); if (baseConstructorParams != null && baseConstructorParams.Length != 0) { var last = baseConstructorParams.Last(); if (last.ParameterType.IsArray && last.HasAttribute(typeof(ParamArrayAttribute))) { var parameter = constructor.ConstructorBuilder.DefineParameter(args.Length, ParameterAttributes.None, last.Name); var builder = AttributeUtil.CreateBuilder <ParamArrayAttribute>(); parameter.SetCustomAttribute(builder); } } for (var i = 0; i < fields.Length; i++) { constructor.CodeBuilder.AddStatement(new AssignStatement(fields[i], args[i].ToExpression())); } // Invoke base constructor if (baseConstructor != null) { Debug.Assert(baseConstructorParams != null); var slice = new ArgumentReference[baseConstructorParams.Length]; Array.Copy(args, fields.Length, slice, 0, baseConstructorParams.Length); constructor.CodeBuilder.InvokeBaseConstructor(baseConstructor, slice); } else { constructor.CodeBuilder.InvokeBaseConstructor(); } constructor.CodeBuilder.AddStatement(new ReturnStatement()); }
/// <summary> /// Initializes the <see cref="PatternTestDataContext" />. /// </summary> /// <param name="dataContextScope">The data context scope.</param> /// <param name="constructor">The constructor.</param> protected virtual void InitializeDataContext(IPatternScope dataContextScope, IConstructorInfo constructor) { ITypeInfo declaringType = constructor.DeclaringType; if (declaringType.IsGenericTypeDefinition) dataContextScope.TestDataContextBuilder.ImplicitDataBindingIndexOffset = declaringType.GenericArguments.Count; foreach (IParameterInfo parameter in constructor.Parameters) dataContextScope.Consume(parameter, false, DefaultConstructorParameterPattern); dataContextScope.Process(constructor); }
protected override ClassDeclarationSyntax ResolveConstructor(ClassDeclarationSyntax cls, object context, IConstructorInfo ctor) => cls;
internal static ConstructorInfo GetConstructor(Type type, IConstructorInfo ctr) { throw new NotImplementedException(); }
internal static ConstructorInfo AsConstructorInfo(this IConstructorInfo wrapper) { throw new NotImplementedException("This operation has not been implemented."); }
internal static IConstructorInfo GetConstructor(Type invocationType, IConstructorInfo constructor) { return(TypeBuilder.GetConstructor(invocationType, constructor.AsConstructorInfo()).AsIConstructorInfo()); }
/// <summary> /// Verifies that the attribute is being used correctly. /// </summary> /// <param name="containingScope">The containing scope.</param> /// <param name="constructor">The constructor.</param> /// <exception cref="PatternUsageErrorException">Thrown if the attribute is being used incorrectly.</exception> protected virtual void Validate(IPatternScope containingScope, IConstructorInfo constructor) { if (!containingScope.CanAddTestParameter || constructor == null) ThrowUsageErrorException("This attribute can only be used on a test type constructor."); if (constructor.IsStatic) ThrowUsageErrorException("This attribute cannot be used on a static constructor."); }