예제 #1
0
            //-------------------------------------------------------------------------------------------------------------------------------------------------

            protected override void OnConstructor(MethodMember member, Func <ConstructorDecorationBuilder> decorate)
            {
                decorate()
                .OnSuccess(w =>
                           m_EventHandlerMapField.Assign(w.New <ConcurrentDictionary <Delegate, Delegate> >())
                           );
            }
            protected override IIntermediateInterfaceMethodMember OnGetNewMethod(string name)
            {
                var result = new MethodMember(this.Parent);

                result.AssignName(name);
                return(result);
            }
예제 #3
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------

        public StatementScope(StatementBlock statementBlock, RewriteMode rewriteMode)
        {
            m_Previous = s_Current;
            m_Root     = (m_Previous != null ? m_Previous.Root : this);

            m_StatementBlock = statementBlock;
            m_Writer         = statementBlock.OwnerMethod.TransparentWriter;
            m_OwnerMethod    = statementBlock.OwnerMethod;
            m_OwnerClass     = statementBlock.OwnerMethod.OwnerClass;
            m_Depth          = 1;

            m_ThisExceptionBlockType = ExceptionBlockType.None;
            m_ThisExceptionStatement = null;

            if (m_Previous != null)
            {
                m_InheritedLoopStatement      = m_Previous.InheritedLoopStatement;
                m_InheritedExceptionStatement = m_Previous.InheritedExceptionStatement;
                m_InheritedExceptionBlockType = m_Previous.InheritedExceptionBlockType;
            }

            m_StatementBlock        = statementBlock;
            m_IsRewriteMode         = true;
            m_RewriteInsertionIndex = 0;

            s_Current = this;
        }
예제 #4
0
        private static bool MatchesGeneric(this MethodMember methodMember, MethodReference methodReference)
        {
            var referenceFullName = methodReference.GetElementMethod().GetFullName();
            var memberFullName    = methodMember.FullName;
            var count             = methodReference.GetElementMethod().GenericParameters.Count;

            if (methodMember.GenericParameters.Count != count)
            {
                return(false);
            }

            var parameters = new List <GenericParameter[]>();

            for (var i = 0; i < count; i++)
            {
                parameters.Add(new[]
                {
                    new GenericParameter(methodReference.GetElementMethod().GenericParameters[i].Name),
                    methodMember.GenericParameters[i]
                });
            }

            parameters = parameters.OrderByDescending(genericParameters => genericParameters[0].Name.Length).ToList();

            foreach (var genericParameters in parameters.Where(genericParameters => genericParameters[0] != null)
                     )
            {
                referenceFullName = referenceFullName.Replace(genericParameters[0].Name, genericParameters[1].Name);
                memberFullName    = memberFullName.Replace(genericParameters[0].Name, genericParameters[1].Name);
            }

            return(memberFullName.Equals(referenceFullName));
        }
예제 #5
0
        /// <summary>
        /// Method parameters with the following type are ignored in the schema and will have their value injected:
        /// <list type="bullet">
        /// <item><see cref="IResolveFieldContext"/></item>
        /// </list>
        /// </summary>
        /// <param name="method">Graph endpoint implementation</param>
        /// <remarks>The method's type must be registered in the <see cref="IServiceCollection"/>.</remarks>
        /// <returns>The added <see cref="FieldType"/>.</returns>
        public FieldType AddQuery(MethodMember method)
        {
            var handler  = !method.Static ? this._ServiceProvider.GetRequiredService(method.Type) : null;
            var resolver = new MethodFieldResolver(method, handler);

            return(this.Query.AddField(method.ToFieldType(resolver)));
        }
예제 #6
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------

        private StatementScope(StatementBlock statementBlock, bool attachStatementBlock)
        {
            m_Previous = s_Current;
            m_Root     = m_Previous.Root;

            if (m_Previous == null)
            {
                throw new InvalidOperationException("Parent scope is not present.");
            }

            m_StatementBlock = statementBlock;
            m_Writer         = m_Previous.m_Writer;
            m_OwnerMethod    = m_Previous.m_OwnerMethod;
            m_OwnerClass     = m_Previous.m_OwnerClass;
            m_Depth          = m_Previous.Depth + 1;

            m_InheritedLoopStatement      = m_Previous.InheritedLoopStatement;
            m_ThisExceptionBlockType      = ExceptionBlockType.None;
            m_ThisExceptionStatement      = null;
            m_InheritedExceptionStatement = m_Previous.InheritedExceptionStatement;
            m_InheritedExceptionBlockType = m_Previous.InheritedExceptionBlockType;

            m_StatementBlock = (attachStatementBlock ? AttachStatementBlock(statementBlock) : null);
            s_Current        = this;
        }
예제 #7
0
        private IMember CreatePropertyMember(PropertyDefinition propertyDefinition)
        {
            var typeReference = propertyDefinition.PropertyType;
            var propertyType  = _typeFactory.GetOrCreateStubTypeFromTypeReference(typeReference);

            MethodMember getter    = null;
            var          isVirtual = false;

            if (propertyDefinition.GetMethod != null)
            {
                isVirtual = propertyDefinition.GetMethod.IsVirtual;
                getter    = CreateMethodMember(propertyDefinition.GetMethod);
            }

            MethodMember setter = null;

            if (propertyDefinition.SetMethod != null)
            {
                isVirtual = isVirtual || propertyDefinition.SetMethod.IsVirtual;
                setter    = CreateMethodMember(propertyDefinition.SetMethod);
            }

            return(new PropertyMember(_type, propertyDefinition.Name, propertyDefinition.FullName,
                                      propertyType, isVirtual, getter, setter));
        }
예제 #8
0
 private IEnumerable <MethodSignatureDependency> CreateMethodSignatureDependencies(
     MethodReference methodReference, MethodMember methodMember)
 {
     return(methodReference
            .GetSignatureTypes(_typeFactory)
            .Select(signatureType => new MethodSignatureDependency(methodMember, signatureType)));
 }
예제 #9
0
 public MethodMemberInstance(MethodMember member, IEnumerable <GenericArgument> declaringTypeGenericArguments,
                             IEnumerable <GenericArgument> memberGenericArguments)
 {
     Member                 = member;
     GenericArguments       = declaringTypeGenericArguments;
     MemberGenericArguments = memberGenericArguments;
 }
        public void Visit_MethodBodyStatementsIncluded()
        {
            //-- arrange

            var type1     = new TypeMember(new TypeGeneratorInfo(this.GetType()), "NS1", MemberVisibility.Public, TypeMemberKind.Class, "ClassOne");
            var method1   = new MethodMember(MemberVisibility.Public, MemberModifier.None, "M1", new MethodSignature());
            var variable1 = new LocalVariable {
                Name = "x", Type = typeof(TimeSpan)
            };

            method1.Body = new BlockStatement(
                new VariableDeclarationStatement {
                Variable = variable1
            }
                );

            type1.Members.Add(method1);

            var foundTypes       = new HashSet <TypeMember>();
            var visitorUnderTest = new TypeReferenceMemberVisitor(foundTypes);

            //-- act

            type1.AcceptVisitor(visitorUnderTest);

            //-- assert

            foundTypes.Should().BeEquivalentTo(new TypeMember[] {
                type1, typeof(TimeSpan)
            });
        }
예제 #11
0
            //-----------------------------------------------------------------------------------------------------------------------------------------------------

            protected override void OnMethod(MethodMember member, Func <MethodDecorationBuilder> decorate)
            {
                decorate()
                .OnBefore(w =>
                          m_Log.Add(w.Const(m_LogPrefix + "BEFORE:" + member.Name))
                          )
                .OnReturnValue((w, retVal) =>
                               m_Log.Add(w.Const(m_LogPrefix + "RETVAL:" + member.Name + "=") + retVal.Func <string>(x => x.ToString))
                               )
                .OnReturnVoid(w =>
                              m_Log.Add(w.Const(m_LogPrefix + "RETVOID:" + member.Name))
                              )
                .OnException <ExceptionRepository.TestExceptionOne>((w, e) => {
                    m_Log.Add(w.Const(m_LogPrefix + "EXCEPTION-ONE:" + member.Name + "=") + e.Prop(x => x.Message));
                    w.Throw();
                })
                .OnFailure(w =>
                           m_Log.Add(w.Const(m_LogPrefix + "FAILURE:" + member.Name))
                           )
                .OnSuccess(w =>
                           m_Log.Add(w.Const(m_LogPrefix + "SUCCESS:" + member.Name))
                           )
                .OnAfter(w =>
                         m_Log.Add(w.Const(m_LogPrefix + "AFTER:" + member.Name))
                         );
            }
예제 #12
0
        public static MethodMember CreateStubMethodMember(this MethodBase methodBase)
        {
            var visibility = methodBase.GetVisibility();

            var declaringType = methodBase.DeclaringType.CreateStubClass();
            var parameters    = methodBase.CreateStubParameters().Select(parameter => new TypeInstance <IType>(parameter));
            var methodForm    = methodBase.GetStubMethodForm();

            var isGeneric = methodBase.IsGenericMethod;

            TypeInstance <IType> returnTypeInstance = null;
            string fullName = null;

            if (methodBase is ConstructorInfo constructor)
            {
                var voi = typeof(void).CreateStubClass();
                returnTypeInstance = new TypeInstance <IType>(voi);
                fullName           = constructor.CreateStubFullName(voi);
            }

            if (methodBase is MethodInfo methodInfo)
            {
                var returnType = methodInfo.ReturnType.CreateStubClass();
                returnTypeInstance = new TypeInstance <IType>(returnType);
                fullName           = methodInfo.CreateStubFullName();
            }

            var methodMember = new MethodMember(methodBase.BuildMockMethodName(), fullName, declaringType, visibility,
                                                returnTypeInstance, methodBase.IsVirtual, methodForm, isGeneric, false, false, false);

            methodMember.ParameterInstances.AddRange(parameters);
            return(methodMember);
        }
예제 #13
0
        public void CanEmitMethodBody()
        {
            //-- arrange

            var method = new MethodMember(
                MemberVisibility.Public,
                "TestMethod",
                new MethodSignature {
                ReturnValue = new MethodParameter {
                    Type = typeof(string)
                }
            });

            method.Body = new BlockStatement(
                new ReturnStatement {
                Expression = new ConstantExpression {
                    Value = "ABC"
                }
            }
                );

            var emitterUnderTest = new MethodSyntaxEmitter(method);

            //-- act

            var actualSyntax = emitterUnderTest.EmitSyntax();

            //-- assert

            var expectedCode = "public string TestMethod() { return \"ABC\"; }";

            actualSyntax.Should().BeEquivalentToCode(expectedCode);
        }
        private IEnumerable <IMemberTypeDependency> CreateMethodBodyDependencies(MethodDefinition methodDefinition,
                                                                                 MethodMember methodMember)
        {
            var methodBody = methodDefinition.Resolve().Body;

            if (methodBody == null)
            {
                yield break;
            }

            var visitedMethodReferences = new List <MethodReference> {
                methodDefinition
            };

            var bodyTypes = methodDefinition.GetBodyTypes(_typeFactory).ToList();

            var castTypes = methodDefinition.GetCastTypes(_typeFactory).ToList();

            var typeCheckTypes = methodDefinition.GetTypeCheckTypes(_typeFactory).ToList();

            var metaDataTypes = methodDefinition.GetMetaDataTypes(_typeFactory).ToList();

            var accessedFieldMembers = methodDefinition.GetAccessedFieldMembers(_typeFactory).ToList();

            var calledMethodMembers = CreateMethodBodyDependenciesRecursive(methodBody, visitedMethodReferences,
                                                                            bodyTypes, castTypes, typeCheckTypes, metaDataTypes, accessedFieldMembers);

            foreach (var calledMethodMember in calledMethodMembers.Where(method => !method.Member.IsCompilerGenerated)
                     .Distinct())
            {
                yield return(new MethodCallDependency(methodMember, calledMethodMember));
            }

            foreach (var bodyType in bodyTypes.Where(instance => !instance.Type.IsCompilerGenerated).Distinct())
            {
                yield return(new BodyTypeMemberDependency(methodMember, bodyType));
            }

            foreach (var castType in castTypes.Where(instance => !instance.Type.IsCompilerGenerated).Distinct())
            {
                yield return(new CastTypeDependency(methodMember, castType));
            }

            foreach (var typeCheckType in typeCheckTypes.Where(instance => !instance.Type.IsCompilerGenerated)
                     .Distinct())
            {
                yield return(new TypeCheckDependency(methodMember, typeCheckType));
            }

            foreach (var metaDataType in metaDataTypes.Where(instance => !instance.Type.IsCompilerGenerated).Distinct())
            {
                yield return(new MetaDataDependency(methodMember, metaDataType));
            }

            foreach (var fieldMember in accessedFieldMembers.Where(field => !field.IsCompilerGenerated).Distinct())
            {
                yield return(new AccessFieldDependency(methodMember, fieldMember));
            }
        }
 public MethodCallDependencyTests()
 {
     _classWithConstructors = _architecture.GetClassOfType(typeof(ClassWithConstructors));
     _methodAMember         = _architecture.GetClassOfType(typeof(ClassWithMethodA))
                              .GetMethodMembersWithName(nameof(ClassWithMethodA.MethodA).BuildMethodMemberName()).FirstOrDefault();
     _methodBMember = _architecture.GetClassOfType(typeof(ClassWithMethodB))
                      .GetMethodMembersWithName(nameof(ClassWithMethodB.MethodB).BuildMethodMemberName()).FirstOrDefault();
 }
예제 #16
0
 private IEnumerable <BodyTypeMemberDependency> CreateMethodBodyTypeDependencies(
     MethodDefinition methodDefinition,
     MethodMember methodMember)
 {
     return(methodDefinition
            .GetBodyTypes(_typeFactory)
            .Select(bodyType => new BodyTypeMemberDependency(methodMember, bodyType)));
 }
예제 #17
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------

        public void Attach(StatementScope scope)
        {
            m_OwnerMethod            = scope.OwnerMethod;
            m_ParentBlock            = (scope.Previous != null ? scope.Previous.StatementBlock : null);
            m_Depth                  = (m_ParentBlock != null ? m_ParentBlock.Depth + 1 : 0);
            m_EnclosingTryStatement  = scope.InheritedExceptionStatement;
            m_EnclosingLoopStatement = scope.InheritedLoopStatement;
        }
예제 #18
0
        public static MethodCallDependency CreateStubMethodCallDependency(IMember originMember,
                                                                          MethodMember targetMember)
        {
            var methodCallDependency = new MethodCallDependency(originMember, targetMember);

            methodCallDependency.TargetMember.MemberBackwardsDependencies.Add(methodCallDependency);
            return(methodCallDependency);
        }
예제 #19
0
        /// <summary>
        /// Adds a subquery to an existing parent type that returns a single item.<br />
        /// Method parameters with the following types are ignored in the schema and will have their value injected:
        /// <list type="bullet">
        /// <item><see cref="IResolveFieldContext"/></item>
        /// <item>T</item>
        /// </list>
        /// </summary>
        /// <remarks>The method's type must be registered in the <see cref="IServiceCollection"/>.</remarks>
        /// <param name="method">Graph endpoint implementation</param>
        /// <returns>The added <see cref="FieldType"/>.</returns>
        public FieldType AddSubquery <T>(MethodMember method)
            where T : class
        {
            var handler  = this._ServiceProvider.GetRequiredService(method.Type);
            var resolver = new ItemLoaderFieldResolver <T>(method, handler, this._DataLoader);

            return(this.Query.AddField(method.ToFieldType(resolver)));
        }
예제 #20
0
        /// <summary>
        /// Adds a subquery to an existing parent type that returns a single item mapped to the parent type by a key property.<br />
        /// Method parameters with the following types are ignored in the schema and will have their value injected:
        /// <list type="bullet">
        /// <item><see cref="IResolveFieldContext"/></item>
        /// <item>PARENT</item>
        /// <item>IEnumerable&lt;KEY&gt;</item>
        /// </list>
        /// </summary>
        /// <remarks>The method's type must be registered in the <see cref="IServiceCollection"/>.</remarks>
        /// <typeparam name="PARENT">The parent type to add the endpount to</typeparam>
        /// <typeparam name="CHILD">The mapped child type to be returned</typeparam>
        /// <typeparam name="KEY">The type of the key mapping between the parent and child types.</typeparam>
        /// <param name="method">Graph endpoint implementation</param>
        /// <param name="getParentKey">Gets the key value from the parent instance</param>
        /// <param name="getChildKey">Gets the key value from the child instance</param>
        /// <returns>The added <see cref="FieldType"/>.</returns>
        public FieldType AddSubqueryBatch <PARENT, CHILD, KEY>(MethodMember method, Func <PARENT, KEY> getParentKey, Func <CHILD, KEY> getChildKey)
            where PARENT : class
        {
            var handler  = this._ServiceProvider.GetRequiredService(method.Type);
            var resolver = new BatchLoaderFieldResolver <PARENT, CHILD, KEY>(method, handler, this._DataLoader, getParentKey, getChildKey);

            return(this.Query.AddField(method.ToFieldType(resolver)));
        }
 public PropertyDependencyTests()
 {
     _dependOnClass            = Architecture.GetClassOfType(typeof(PropertyDependOnClass));
     _propertyTestDataClass    = Architecture.GetClassOfType(typeof(PropertyTestDataClass));
     _testStringProperty       = _propertyTestDataClass.GetPropertyMembersWithName("TestStringProperty").ToList().First();
     _testStringPropertyGetter =
         _propertyTestDataClass.GetMethodMembersWithName("get_TestStringProperty()").First();
 }
        public GenericMethodTests()
        {
            var intf = Architecture.GetInterfaceOfType(typeof(IInterfaceWithGenericMethodsWithSameName));

            _oneGenericArgumentMethod = intf.GetMethodMembers()
                                        .First(member => member.GenericParameters.Count == 1);
            _twoGenericArgumentsMethod = intf.GetMethodMembers()
                                         .First(member => member.GenericParameters.Count == 2);
        }
 public CastDependenciesTest()
 {
     _castClassA               = Architecture.GetClassOfType(typeof(CastClassA));
     _castClassB               = Architecture.GetClassOfType(typeof(CastClassB));
     _castInterfaceA           = Architecture.GetInterfaceOfType(typeof(ICastInterfaceA));
     _classWithCastDependency  = Architecture.GetClassOfType(typeof(ClassWithCastDependency));
     _methodWithCastDependency = (MethodMember)_classWithCastDependency.Members
                                 .WhereNameIs("MethodWithCastDependencies(ArchUnitNETTests.Dependencies.CastClassA)").ToList().First();
 }
예제 #24
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------

        #region IBindToMethod Members

        void IBindToMethod.BindToMethod(MethodMember method)
        {
            if (m_HomeStatementBlock == null)
            {
                m_HomeStatementBlock = method.Body;
            }

            method.RegisterLocal(this, out m_LocalIndex);
        }
        public static IPredicate <T> DoNotCallAny(MethodMember method, params MethodMember[] moreMethods)
        {
            var methods = new List <MethodMember> {
                method
            };

            methods.AddRange(moreMethods);
            return(DoNotCallAny(methods));
        }
예제 #26
0
            //-------------------------------------------------------------------------------------------------------------------------------------------------

            protected override void OnMethod(MethodMember member, Func <MethodDecorationBuilder> decorate)
            {
                decorate()
                .OnBefore(w =>
                          m_Log.Add(m_Number.Func <string>(x => x.ToString).ToUpper() + w.Const("-BEFORE:" + member.Name))
                          )
                .OnAfter(w =>
                         m_Log.Add(m_Number.Func <string>(x => x.ToString).ToUpper() + w.Const("-AFTER:" + member.Name))
                         );
            }
예제 #27
0
 private void FindEventHandlers(MethodMember controllerMethod)
 {
     foreach (var statement in controllerMethod.Body.Statements)
     {
         if (TryParseEventHandlerAttachStatement(statement, out var eventName, out var handler))
         {
             EventMap.AddHandler(eventName, handler);
         }
     }
 }
        private static MethodCallDependency CreateStubMethodCallDependency(IMember originMember,
                                                                           MethodMember targetMember)
        {
            var methodCallDependency = new MethodCallDependency(originMember,
                                                                new MethodMemberInstance(targetMember, Enumerable.Empty <GenericArgument>(),
                                                                                         Enumerable.Empty <GenericArgument>()));

            methodCallDependency.TargetMember.MemberBackwardsDependencies.Add(methodCallDependency);
            return(methodCallDependency);
        }
        public void IsId_Without_Correct_Name()
        {
            //Arrange
            var member = new MethodMember(null);

            //Act
            var result = new AutomappingConfiguration().IsId(member);

            //Assert
            Assert.IsFalse(result);
        }
예제 #30
0
 public GeneratorDependenciesTests()
 {
     _accessedClass               = Architecture.GetClassOfType(typeof(AccessedClass));
     _accessedStaticField         = _accessedClass.GetFieldMembersWithName(nameof(AccessedClass.StringField)).First();
     _accessedBoolField           = _accessedClass.GetFieldMembersWithName(nameof(AccessedClass.BoolField)).First();
     _accessedStaticMethodAsField =
         _accessedClass.GetFieldMembersWithName(nameof(AccessedClass.StaticMethodAsField)).First();
     _accessedConstructor          = _accessedClass.Constructors.First();
     _accessedStaticMethodWithBody = _accessedClass
                                     .GetMethodMembersWithName(nameof(AccessedClass.StaticMethodWithBody) + "(System.Int32)").First();
 }
예제 #31
0
 public void ReadDeclaration()
 {
     _member = new MethodMember {
         Name          = _symbol.Name,
         DeclaringType = _modelBuilder.TryGetMember <TypeMember>(_symbol.ContainingType),
         Status        = MemberStatus.Incomplete,
         Visibility    = _symbol.GetMemberVisibility(),
         Modifier      = _symbol.GetMemberModifier(),
         Signature     = MethodReaderMechanism.ReadSignature(_modelBuilder, _symbol),
     };
 }
        public void ShouldMap_Member_Without_CanWrite()
        {
            //Arrange
            var member = new MethodMember(null);

            //Act
            var result = new AutomappingConfiguration().ShouldMap(member);

            //Assert
            Assert.IsFalse(result);
        }