Пример #1
0
        public void CreateWorkItems()
        {
            IMethodInfo method = new MethodWrapper(typeof(DummyFixture), "DummyTest");
            ITest test = new TestMethod(method);
            _workItem = WorkItem.CreateWorkItem(test, TestFilter.Empty);

            _context = new TestExecutionContext();
            _workItem.InitializeContext(_context);
        }
Пример #2
0
    public static void resolve(MemberName self, jlClass caller)
    {
#if !FIRST_PASS
        if (self.isMethod() || self.isConstructor())
        {
            TypeWrapper tw = TypeWrapper.FromClass(self.getDeclaringClass());
            if (tw == CoreClasses.java.lang.invoke.MethodHandle.Wrapper &&
                (self.getName() == "invoke" || self.getName() == "invokeExact"))
            {
                typeof(MemberName).GetField("vmindex", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, Int32.MaxValue);
                return;
            }
            MethodWrapper mw = tw.GetMethodWrapper(self.getName(), self.getSignature().Replace('/', '.'), true);
            if (mw != null)
            {
                tw = mw.DeclaringType;
                int index = Array.IndexOf(tw.GetMethods(), mw);
                if (index != -1)
                {
                    // TODO self.setVMIndex(index);
                    typeof(MemberName).GetField("vmindex", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, index);
                    typeof(MemberName).GetField("vmtarget", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, tw);
                    int flags = (int)mw.Modifiers;
                    if (self.isMethod())
                    {
                        flags |= MemberName.IS_METHOD;
                    }
                    else
                    {
                        flags |= MemberName.IS_CONSTRUCTOR;
                    }
                    typeof(MemberName).GetField("flags", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, flags);
                }
            }
        }
        else if (self.isField())
        {
            TypeWrapper tw = TypeWrapper.FromClass(self.getDeclaringClass());
            // TODO should we look in base classes?
            FieldWrapper fw = tw.GetFieldWrapper(self.getName(), self.getSignature().Replace('/', '.'));
            if (fw != null)
            {
                int index = Array.IndexOf(fw.DeclaringType.GetFields(), fw);
                if (index != -1)
                {
                    // TODO self.setVMIndex(index);
                    typeof(MemberName).GetField("vmindex", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, index);
                    typeof(MemberName).GetField("flags", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(self, (int)fw.Modifiers | MemberName.IS_FIELD);
                }
            }
        }
        else
        {
            throw new InvalidOperationException();
        }
#endif
    }
Пример #3
0
        internal static MethodBuilder AddAutomagicSerialization(DynamicTypeWrapper wrapper, TypeBuilder typeBuilder)
        {
            MethodBuilder serializationCtor = null;

            if ((wrapper.Modifiers & IKVM.Attributes.Modifiers.Enum) != 0)
            {
                MarkSerializable(typeBuilder);
            }
            else if (wrapper.IsSubTypeOf(CoreClasses.java.io.Serializable.Wrapper) && IsSafeForAutomagicSerialization(wrapper))
            {
                if (wrapper.IsSubTypeOf(externalizable))
                {
                    MethodWrapper ctor = wrapper.GetMethodWrapper("<init>", "()V", false);
                    if (ctor != null && ctor.IsPublic)
                    {
                        MarkSerializable(typeBuilder);
                        ctor.Link();
                        serializationCtor = AddConstructor(typeBuilder, ctor, null, true);
                        if (!wrapper.BaseTypeWrapper.IsSubTypeOf(CoreClasses.java.io.Serializable.Wrapper))
                        {
                            AddGetObjectData(typeBuilder);
                        }
                        if (wrapper.BaseTypeWrapper.GetMethodWrapper("readResolve", "()Ljava.lang.Object;", true) != null)
                        {
                            RemoveReadResolve(typeBuilder);
                        }
                    }
                }
                else if (wrapper.BaseTypeWrapper.IsSubTypeOf(CoreClasses.java.io.Serializable.Wrapper))
                {
                    MethodBase baseCtor = wrapper.GetBaseSerializationConstructor();
                    if (baseCtor != null && (baseCtor.IsFamily || baseCtor.IsFamilyOrAssembly))
                    {
                        MarkSerializable(typeBuilder);
                        serializationCtor = AddConstructor(typeBuilder, null, baseCtor, false);
                        AddReadResolve(wrapper, typeBuilder);
                    }
                }
                else
                {
                    MethodWrapper baseCtor = wrapper.BaseTypeWrapper.GetMethodWrapper("<init>", "()V", false);
                    if (baseCtor != null && baseCtor.IsAccessibleFrom(wrapper.BaseTypeWrapper, wrapper, wrapper))
                    {
                        MarkSerializable(typeBuilder);
                        AddGetObjectData(typeBuilder);
#if STATIC_COMPILER
                        // because the base type can be a __WorkaroundBaseClass__, we may need to replace the constructor
                        baseCtor = ((AotTypeWrapper)wrapper).ReplaceMethodWrapper(baseCtor);
#endif
                        baseCtor.Link();
                        serializationCtor = AddConstructor(typeBuilder, baseCtor, null, true);
                        AddReadResolve(wrapper, typeBuilder);
                    }
                }
            }
            return(serializationCtor);
        }
Пример #4
0
        static int indexString(IntPtr l, object self, string key)
        {
            Type t = getType(self);

            if (self is IDictionary)
            {
                if (t.IsGenericType && t.GetGenericArguments()[0] != typeof(string))
                {
                    goto IndexProperty;
                }
                object v = (self as IDictionary)[key];
                if (v != null)
                {
                    pushValue(l, true);
                    pushVar(l, v);
                    return(2);
                }
            }

IndexProperty:
            MemberInfo[] mis = t.GetMember(key, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (mis.Length == 0)
            {
                return(error(l, "Can't find " + key));
            }

            pushValue(l, true);
            MemberInfo mi = mis[0];

            switch (mi.MemberType)
            {
            case MemberTypes.Property:
                PropertyInfo p   = (PropertyInfo)mi;
                MethodInfo   get = p.GetGetMethod();
                pushVar(l, get.Invoke(self, null));
                break;

            case MemberTypes.Field:
                FieldInfo f = (FieldInfo)mi;
                pushVar(l, f.GetValue(self));
                break;

            case MemberTypes.Method:
                LuaCSFunction ff = new MethodWrapper(self, mis).invoke;
                pushObject(l, ff);
                break;

            case MemberTypes.Event:
                break;

            default:
                return(1);
            }

            return(2);
        }
Пример #5
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException, ClassNotFoundException
        private void writeObject(ObjectOutputStream @out)
        {
            @out.defaultWriteObject();
            MethodWrapper[] wrappers = new MethodWrapper[functions.Length];
            for (int i = 0; i < wrappers.Length; i++)
            {
                wrappers[i] = new MethodWrapper(functions[i]);
            }
            @out.writeObject(wrappers);
        }
Пример #6
0
        public void CreateWorkItems()
        {
            IMethodInfo method = new MethodWrapper(typeof(DummyFixture), "DummyTest");
            ITest       test   = new TestMethod(method);

            _workItem = WorkItemBuilder.CreateWorkItem(test, TestFilter.Empty);

            _context = new TestExecutionContext();
            _workItem.InitializeContext(_context);
        }
        private static void EmitUnboxNumber(CodeEmitter ilgen, string methodName, string methodSig)
        {
            TypeWrapper tw = ClassLoaderWrapper.LoadClassCritical("java.lang.Number");

            tw.EmitCheckcast(ilgen);
            MethodWrapper mw = tw.GetMethodWrapper(methodName, methodSig, false);

            mw.Link();
            mw.EmitCallvirt(ilgen);
        }
Пример #8
0
        private static bool Class_getPrimitiveClass(DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, MethodWrapper method, MethodAnalyzer ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
        {
            ilgen.LazyEmitPop();
            ilgen.Emit(OpCodes.Ldnull);
            MethodWrapper mw = CoreClasses.java.lang.Class.Wrapper.GetMethodWrapper("<init>", "(Lcli.System.Type;)V", false);

            mw.Link();
            mw.EmitNewobj(ilgen);
            return(true);
        }
Пример #9
0
        private static bool Class_getPrimitiveClass(EmitIntrinsicContext eic)
        {
            eic.Emitter.Emit(OpCodes.Pop);
            eic.Emitter.Emit(OpCodes.Ldnull);
            MethodWrapper mw = CoreClasses.java.lang.Class.Wrapper.GetMethodWrapper("<init>", "(Lcli.System.Type;)V", false);

            mw.Link();
            mw.EmitNewobj(eic.Emitter);
            return(true);
        }
Пример #10
0
        static MessageInvoker()
        {
            _handlers = new ConcurrentDictionary <Type, Func <object, object[], object> >();

            foreach (var i in typeof(T).GetMethods()
                     .Where(x => x.GetCustomAttributes(true).Count(y => y is MessageHandlerAttribute) > 0))
            {
                _handlers.TryAdd(i.GetParameters()[0].ParameterType, MethodWrapper.Wrap(i));
            }
        }
Пример #11
0
        public override void addOption(Options options)
        {
            if (!Options_AddKeybindOption)             // HACK, using reflection to call protected method
            {
                var targetMethod = typeof(ModOptions).method("AddKeybindOption", typeof(string), typeof(string), typeof(GameInput.Device), typeof(KeyCode));
                Options_AddKeybindOption = targetMethod.wrap <AddKeybindOption>(options);
            }

            Options_AddKeybindOption.invoke(id, label, GameInput.Device.Keyboard, KeyCode.A);
        }
Пример #12
0
            public override bool Equals(object obj)
            {
                MethodWrapper other = (MethodWrapper)obj;

                if (method.Name != other.method.Name)
                {
                    return(false);
                }
                return(0 == DiffUtility.Compare(method.Parameters, other.method.Parameters));
            }
Пример #13
0
        static AssetsHelper()
        {
            string bundlePath = Paths.assetsPath + Mod.id + assetsExt;

            if (File.Exists(bundlePath))
            {
                MethodWrapper loadBundle = Type.GetType("UnityEngine.AssetBundle, UnityEngine.AssetBundleModule").method("LoadFromFile", typeof(string)).wrap();
                assetBundle = loadBundle.invoke(bundlePath);
            }
        }
Пример #14
0
        public void TestOnItemSelectedWithSelectedItemTestWithoutChildTestsPushesTestDetailPageToStackAndCaches()
        {
            NUnitRunner runner = new NUnitRunner("runner-name");

            runner.AddTestAssembly(typeof(TestFixtureStubOne).Assembly);
            IMethodInfo    methodOne          = new MethodWrapper(typeof(TestsPageTest), GetType().GetMethods().First());
            IMethodInfo    methodTwo          = new MethodWrapper(typeof(TestsPageTest), GetType().GetMethods().Last());
            ITest          firstTestInstance  = new TestMethod(methodOne);
            ITest          secondTestInstance = new TestMethod(methodTwo);
            TestsViewModel firstTest          = new TestsViewModel(runner, firstTestInstance);
            TestsViewModel secondTest         = new TestsViewModel(runner, secondTestInstance);

            Assert.IsFalse(firstTest.Test.IsSuite);
            Assert.IsFalse(firstTest.Test.HasChildren);
            Assert.IsFalse(secondTest.Test.IsSuite);
            Assert.IsFalse(secondTest.Test.HasChildren);

            SelectedItemChangedEventArgs firstArgs  = new SelectedItemChangedEventArgs(firstTest, 0);
            SelectedItemChangedEventArgs secondArgs = new SelectedItemChangedEventArgs(secondTest, 0);

            TestsPageForTest page = new TestsPageForTest(runner);

            // Load first page
            page.InvokeOnItemSelected(null, firstArgs);

            Assert.AreEqual(1, page.NavigationStack.Count);
            TestDetailPage firstTestsPage = page.NavigationStack.First() as TestDetailPage;

            Assert.IsNotNull(firstTestsPage);
            Assert.AreEqual(firstTest, firstTestsPage.ViewModel);
            Assert.AreEqual(runner, firstTestsPage.ViewModel.TestRunner);
            Assert.AreEqual(firstTestInstance, firstTestsPage.ViewModel.Test);

            // Load second page
            page.InvokeOnItemSelected(null, secondArgs);

            Assert.AreEqual(2, page.NavigationStack.Count);
            TestDetailPage secondTestsPage = page.NavigationStack[1] as TestDetailPage;

            Assert.IsNotNull(secondTestsPage);
            Assert.AreEqual(secondTest, secondTestsPage.ViewModel);
            Assert.AreEqual(runner, secondTestsPage.ViewModel.TestRunner);
            Assert.AreEqual(secondTestInstance, secondTestsPage.ViewModel.Test);

            // Load first page again
            IList <Page> expectedStack = new List <Page>(page.NavigationStack);

            expectedStack.Add(firstTestsPage);

            page.InvokeOnItemSelected(null, firstArgs);

            Assert.AreEqual(3, page.NavigationStack.Count);
            Assert.AreSame(firstTestsPage, page.NavigationStack[2]);
            CollectionAssert.AreEqual(expectedStack, page.NavigationStack);
        }
Пример #15
0
        public static Delegate DynamicCreateDelegate(object obj, Type delegateType, string name, string sig)
        {
#if !WINRT
#if FIRST_PASS
            return(null);
#else
            TypeWrapper   tw = TypeWrapper.FromClass(ikvm.runtime.Util.getClassFromObject(obj));
            MethodWrapper mw = tw.GetMethodWrapper(name, sig, true);
            if (mw == null || mw.IsStatic || !mw.IsPublic)
            {
#if NO_REF_EMIT
                java.lang.invoke.MethodType methodType = MethodHandleUtil.GetDelegateMethodType(delegateType);
                if (methodType.parameterCount() > MethodHandleUtil.MaxArity)
                {
                    throw new NotImplementedException();
                }
                java.lang.invoke.MethodHandle exception = java.lang.invoke.MethodHandles.publicLookup()
                                                          .findConstructor(mw == null || mw.IsStatic ? typeof(java.lang.AbstractMethodError) : typeof(java.lang.IllegalAccessError),
                                                                           java.lang.invoke.MethodType.methodType(typeof(void), typeof(string)))
                                                          .bindTo(tw.Name + ".Invoke" + sig);
                return(Delegate.CreateDelegate(delegateType,
                                               java.lang.invoke.MethodHandles.dropArguments(
                                                   java.lang.invoke.MethodHandles.foldArguments(java.lang.invoke.MethodHandles.throwException(methodType.returnType(), exception.type().returnType()), exception),
                                                   0, methodType.parameterArray()).vmtarget, "Invoke"));
#else
                MethodInfo      invoke         = delegateType.GetMethod("Invoke");
                ParameterInfo[] parameters     = invoke.GetParameters();
                Type[]          parameterTypes = new Type[parameters.Length + 1];
                parameterTypes[0] = typeof(object);
                for (int i = 0; i < parameters.Length; i++)
                {
                    parameterTypes[i + 1] = parameters[i].ParameterType;
                }
                System.Reflection.Emit.DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("Invoke", invoke.ReturnType, parameterTypes);
                CodeEmitter ilgen = CodeEmitter.Create(dm);
                ilgen.Emit(System.Reflection.Emit.OpCodes.Ldstr, tw.Name + ".Invoke" + sig);
                ClassLoaderWrapper.GetBootstrapClassLoader()
                .LoadClassByDottedName(mw == null || mw.IsStatic ? "java.lang.AbstractMethodError" : "java.lang.IllegalAccessError")
                .GetMethodWrapper("<init>", "(Ljava.lang.String;)V", false)
                .EmitNewobj(ilgen);
                ilgen.Emit(System.Reflection.Emit.OpCodes.Throw);
                ilgen.DoEmit();
                return(dm.CreateDelegate(delegateType, obj));
#endif
            }
            else
            {
                mw.ResolveMethod();
                return(Delegate.CreateDelegate(delegateType, obj, (MethodInfo)mw.GetMethod()));
            }
#endif
#else
            throw new NotImplementedException();
#endif
        }
        private static TypeWrapper[] GetImplParameters(ClassFile.ConstantPoolItemMethodHandle implMethod)
        {
            MethodWrapper mw = (MethodWrapper)implMethod.Member;

            TypeWrapper[] parameters = mw.GetParameters();
            if (mw.IsStatic || mw.IsConstructor)
            {
                return(parameters);
            }
            return(ArrayUtil.Concat(mw.DeclaringType, parameters));
        }
Пример #17
0
        public static IReadOnlyCollection <SyntaxKind> GetModifiers(this MethodWrapper accessor, PropertyWrapper property)
        {
            var modifierList = new List <SyntaxKind>(6);

            if (property.Accessibility != accessor.Accessibility)
            {
                modifierList.AddRange(AccessibilityToSyntaxKind(accessor.Accessibility));
            }

            return(modifierList);
        }
Пример #18
0
        public void ValueSourceAttributeShouldThrowInsteadOfReturningNull()
        {
            var method     = new MethodWrapper(GetType(), "ValueSourceMayNotBeNull");
            var parameters = method.GetParameters();

            foreach (var parameter in parameters)
            {
                var dataSource = parameter.GetCustomAttributes <IParameterDataSource>(false)[0];
                Assert.Throws <InvalidDataSourceException>(() => dataSource.GetData(parameter));
            }
        }
Пример #19
0
        public static bool IsDefault(this object target)
        {
            if (target == null)
            {
                return(true);
            }

            var defaultValue = new MethodWrapper().GetDefault(target.GetType());

            return(target.Equals(defaultValue));
        }
Пример #20
0
        internal void EmitThrow(string dottedClassName, string message)
        {
            TypeWrapper exception = ClassLoaderWrapper.GetBootstrapClassLoader().LoadClassByDottedName(dottedClassName);

            Emit(OpCodes.Ldstr, message);
            MethodWrapper mw = exception.GetMethodWrapper("<init>", "(Ljava.lang.String;)V", false);

            mw.Link();
            mw.EmitNewobj(this);
            Emit(OpCodes.Throw);
        }
 private static bool IsBridge(MethodWrapper mw, ClassFile.ConstantPoolItemMethodType[] bridges)
 {
     foreach (ClassFile.ConstantPoolItemMethodType bridge in bridges)
     {
         if (bridge.Signature == mw.Signature)
         {
             return(true);
         }
     }
     return(false);
 }
        public void FixedNameTestMethodBuilderIsResilientToParameterEnumeratingException()
        {
            // Arrange
            var dummyMethod        = new MethodWrapper(typeof(TestNameStrategiesFixture), nameof(TestNameStrategiesFixture.FixedNameDecoratedMethod));
            var sut                = new FixedNameTestMethodBuilder();
            var throwingParameters = Enumerable.Range(0, 1).Select <int, object>(_ => throw new Exception());
            // Act
            var testMethod = sut.Build(dummyMethod, null, throwingParameters, 0);

            // Assert
            Assert.That(testMethod.Name, Is.EqualTo(nameof(TestNameStrategiesFixture.FixedNameDecoratedMethod)));
        }
Пример #23
0
 internal EmitIntrinsicContext(MethodWrapper method, DynamicTypeWrapper.FinishContext context, CodeEmitter ilgen, CodeInfo ma, int opcodeIndex, MethodWrapper caller, ClassFile classFile, Instruction[] code, InstructionFlags[] flags)
 {
     this.Method      = method;
     this.Context     = context;
     this.Emitter     = ilgen;
     this.ma          = ma;
     this.OpcodeIndex = opcodeIndex;
     this.Caller      = caller;
     this.ClassFile   = classFile;
     this.Code        = code;
     this.Flags       = flags;
 }
Пример #24
0
        public void TestConditionalDisplayNamePropertyWithTestIsSuiteAndNotClassAndNotMethodReturnsDisplayName()
        {
            MethodInfo  info        = GetType().GetMethods().First();
            IMethodInfo method      = new MethodWrapper(GetType(), info);
            ITest       testFixture = new TestMethod(method);

            TestsViewModel test = new TestsViewModel(v_Runner, testFixture);

            Assert.IsNotNull(test.Test);
            Assert.AreEqual(method.Name, test.ConditionalDisplayName);
            Assert.AreEqual(test.DisplayName, test.ConditionalDisplayName);
        }
Пример #25
0
 private static object[] BoxArgs(MethodWrapper mw, object[] args)
 {
     TypeWrapper[] paramTypes = mw.GetParameters();
     for (int i = 0; i < paramTypes.Length; i++)
     {
         if (paramTypes[i].IsPrimitive)
         {
             args[i] = JVM.Box(args[i]);
         }
     }
     return(args);
 }
            public IMethodInfo[] GetMethods(BindingFlags flags)
            {
                var methods = Type.GetMethods(flags);
                var result  = new MethodWrapper[methods.Length];

                for (int i = 0; i < methods.Length; i++)
                {
                    result[i] = new MethodWrapper(Type, methods[i]);
                }

                return(result);
            }
Пример #27
0
 private static bool MethodExists(List <MethodWrapper> methods, MethodWrapper mw)
 {
     foreach (MethodWrapper mw1 in methods)
     {
         // TODO what do we do with differing return types?
         if (mw1.Name == mw.Name && mw1.Signature == mw.Signature)
         {
             return(true);
         }
     }
     return(false);
 }
Пример #28
0
 private void AppendDefinitionType(TextBuffer buffer)
 {
     if (DecompilerContext.GetOption(IFernflowerPreferences.Use_Debug_Var_Names))
     {
         MethodWrapper method = (MethodWrapper)DecompilerContext.GetProperty(DecompilerContext
                                                                             .Current_Method_Wrapper);
         if (method != null)
         {
             int?originalIndex = null;
             if (processor != null)
             {
                 originalIndex = processor.GetVarOriginalIndex(index);
             }
             if (originalIndex != null)
             {
                 // first try from signature
                 if (DecompilerContext.GetOption(IFernflowerPreferences.Decompile_Generic_Signatures
                                                 ))
                 {
                     StructLocalVariableTypeTableAttribute attr = method.methodStruct.GetAttribute(StructGeneralAttribute
                                                                                                   .Attribute_Local_Variable_Type_Table);
                     if (attr != null)
                     {
                         string signature = attr.GetSignature(originalIndex, visibleOffset);
                         if (signature != null)
                         {
                             GenericFieldDescriptor descriptor = GenericMain.ParseFieldSignature(signature);
                             if (descriptor != null)
                             {
                                 buffer.Append(GenericMain.GetGenericCastTypeName(descriptor.type));
                                 return;
                             }
                         }
                     }
                 }
                 // then try from descriptor
                 StructLocalVariableTableAttribute attr_1 = method.methodStruct.GetLocalVariableAttr
                                                                ();
                 if (attr_1 != null)
                 {
                     string descriptor = attr_1.GetDescriptor(originalIndex, visibleOffset);
                     if (descriptor != null)
                     {
                         buffer.Append(ExprProcessor.GetCastTypeName(new VarType(descriptor)));
                         return;
                     }
                 }
             }
         }
     }
     buffer.Append(ExprProcessor.GetCastTypeName(GetVarType()));
 }
Пример #29
0
        /// <summary>
        /// Resolves the method as a global function, imported property or a local variable with a delegate.
        /// </summary>
        private void ResolveGetIdentifier(Context ctx, GetIdentifierNode node)
        {
            // local
            var nameInfo = ctx.Scope.FindLocal(node.Identifier);

            if (nameInfo != null)
            {
                ResolveExpression(ctx, node);
                return;
            }

            // function
            try
            {
                _method = ctx.ResolveMethod(
                    ctx.MainType.TypeInfo,
                    node.Identifier,
                    ArgTypes,
                    resolver: (idx, types) => ctx.ResolveLambda(Arguments[idx] as LambdaNode, types)
                    );

                if (_method == null)
                {
                    throw new KeyNotFoundException();
                }

                if (ArgTypes.Length == 0 && node.Identifier.IsAnyOf(EntityNames.RunMethodName, EntityNames.EntryPointMethodName))
                {
                    Error(CompilerMessages.ReservedFunctionInvocation, node.Identifier);
                }

                return;
            }
            catch (AmbiguousMatchException)
            {
                Error(CompilerMessages.FunctionInvocationAmbiguous, node.Identifier);
            }
            catch (KeyNotFoundException)
            {
            }

            // global property with a delegate
            try
            {
                ctx.ResolveGlobalProperty(node.Identifier);
                ResolveExpression(ctx, node);
            }
            catch (KeyNotFoundException)
            {
                Error(CompilerMessages.FunctionNotFound, node.Identifier);
            }
        }
Пример #30
0
        public void WrapsOutFunc()
        {
            var args = new object[] { "1234", null };

            var exec = MethodWrapper.Wrap(OutFuncExample)
                           (this, args);

            var success = (bool)(exec);

            Assert.True(success);
            Assert.Equal("1234", args[0]);
            Assert.Equal(1234, args[1]);
        }
Пример #31
0
 public override TextBuffer ToJava(int indent, BytecodeMappingTracer tracer)
 {
     tracer.AddMapping(bytecode);
     if (exitType == Exit_Return)
     {
         TextBuffer buffer = new TextBuffer("return");
         if (retType.type != ICodeConstants.Type_Void)
         {
             buffer.Append(' ');
             ExprProcessor.GetCastedExprent(value, retType, buffer, indent, false, tracer);
         }
         return(buffer);
     }
     else
     {
         MethodWrapper method = (MethodWrapper)DecompilerContext.GetProperty(DecompilerContext
                                                                             .Current_Method_Wrapper);
         ClassesProcessor.ClassNode node = ((ClassesProcessor.ClassNode)DecompilerContext.
                                            GetProperty(DecompilerContext.Current_Class_Node));
         if (method != null && node != null)
         {
             StructExceptionsAttribute attr = method.methodStruct.GetAttribute(StructGeneralAttribute
                                                                               .Attribute_Exceptions);
             if (attr != null)
             {
                 string classname = null;
                 for (int i = 0; i < attr.GetThrowsExceptions().Count; i++)
                 {
                     string exClassName = attr.GetExcClassname(i, node.classStruct.GetPool());
                     if ("java/lang/Throwable".Equals(exClassName))
                     {
                         classname = exClassName;
                         break;
                     }
                     else if ("java/lang/Exception".Equals(exClassName))
                     {
                         classname = exClassName;
                     }
                 }
                 if (classname != null)
                 {
                     VarType    exType = new VarType(classname, true);
                     TextBuffer buffer = new TextBuffer("throw ");
                     ExprProcessor.GetCastedExprent(value, exType, buffer, indent, false, tracer);
                     return(buffer);
                 }
             }
         }
         return(value.ToJava(indent, tracer).Prepend("throw "));
     }
 }
        public void BuildFromYieldsRunnableTestMethod()
        {
            // Arrange
            var autoDataAttribute = new AutoDataAttribute();
            var fixtureType = this.GetType();

            var methodWrapper = new MethodWrapper(fixtureType, fixtureType.GetMethod("DummyTestMethod"));
            var testSuite = new TestSuite(fixtureType);

            // Act
            var testMethod = autoDataAttribute.BuildFrom(methodWrapper, testSuite).First();

            // Assert
            Assert.That(testMethod.RunState == RunState.Runnable);
        }
		protected override void InitContent()
		{
			foreach (IClass c in currentClass.ClassInheritanceTree) {
				if (c.FullyQualifiedName != currentClass.FullyQualifiedName) {
					foreach (IMethod method in c.Methods) {
						if (!method.IsPrivate && (method.IsAbstract || method.IsVirtual || method.IsOverride)) {
							MethodWrapper newWrapper = new MethodWrapper(method);
							if (!Content.Contains(newWrapper)) {
								Content.Add(newWrapper);
							}
						}
					}
				}
			}
			Content.Sort();
		}
        public void IfCreateParametersThrowsExceptionThenReturnsNotRunnableTestMethodWithExceptionInfoAsSkipReason()
        {
            // Arrange
            // DummyFixture is set up to throw DummyException when invoked by AutoDataAttribute
            var autoDataAttributeStub = new AutoDataAttributeStub(new ThrowingStubFixture());

            var fixtureType = this.GetType();

            var methodWrapper = new MethodWrapper(fixtureType, fixtureType.GetMethod("DummyTestMethod"));
            var testSuite = new TestSuite(fixtureType);

            // Act
            var testMethod = autoDataAttributeStub.BuildFrom(methodWrapper, testSuite).First();

            // Assert
            Assert.That(testMethod.RunState == RunState.NotRunnable);

            Assert.That(testMethod.Properties.Get(PropertyNames.SkipReason),
                Is.EqualTo(ExceptionHelper.BuildMessage(new ThrowingStubFixture.DummyException())));
        }
Пример #35
0
        protected override Type resolve(Context ctx, bool mustReturn)
        {
            var exprType = Expression.Resolve(ctx);
            var idxType = Index.Resolve(ctx);

            if (!exprType.IsArray)
            {
                try
                {
                    _Indexer = ReflectionHelper.ResolveIndexer(exprType, idxType, false);
                }
                catch (LensCompilerException ex)
                {
                    ex.BindToLocation(this);
                    throw;
                }
            }

            var idxDestType = exprType.IsArray ? typeof (int) : _Indexer.ArgumentTypes[0];
            var valDestType = exprType.IsArray ? exprType.GetElementType() : _Indexer.ArgumentTypes[1];

            if(!idxDestType.IsExtendablyAssignableFrom(idxType))
                error(Index, CompilerMessages.ImplicitCastImpossible, idxType, idxDestType);

            ensureLambdaInferred(ctx, Value, valDestType);
            var valType = Value.Resolve(ctx);
            if (!valDestType.IsExtendablyAssignableFrom(valType))
                error(Value, CompilerMessages.ImplicitCastImpossible, valType, valDestType);

            return base.resolve(ctx, mustReturn);
        }
 private void DefineMethod()
 {
     var methodName = string.Format("<{0}>b__1", _methodInfo.Name);
     var methodBuilder = TypeBuilder.DefineMethod(methodName, MethodAttribute);
     methodBuilder.InitLocals = true;
     methodBuilder.SetParameters(new[] { _serviceType });
     methodBuilder.SetReturnType(typeof(void));
     var il = new MethodWrapper(methodBuilder);
     if (HasReturnType())
     {
         il.LoadThis();
     }
     il.LoadArgument(1);
     foreach (var parameter in _methodInfo.GetParameters())
     {
         LoadParameter(il, parameter);
     }
     il.CallVirtualMethod(_methodInfo);
     if (HasReturnType())
     {
         il.StoreToField(ResultField);
     }
     il.DoNothing();
     il.Return();
     Method = methodBuilder;
 }
Пример #37
0
            public void CanRunTestThatWasDiscoveredWithoutReflection()
            {
                var typeUnderTest = typeof(ClassUnderTest);
                var methodUnderTest = typeUnderTest.GetMethod("TestMethod");
                var factAttributeUnderTest = CustomAttributeData.GetCustomAttributes(methodUnderTest).Single(a => a.AttributeType == typeof(FactAttribute));

                var assembly = new AssemblyWrapper(Reflector.Wrap(typeUnderTest.Assembly));
                var type = new TypeWrapper(Reflector.Wrap(typeUnderTest));
                var method = new MethodWrapper(Reflector.Wrap(methodUnderTest));
                var attribute = new AttributeWrapper(Reflector.Wrap(factAttributeUnderTest));
                var testCase = TestableXunitTestCase.Create(assembly, type, method, attribute);

                testCase.RunTests();

                Assert.Collection(testCase.Messages,
                    message => Assert.IsAssignableFrom<ITestStarting>(message),
                    message => Assert.IsAssignableFrom<ITestClassConstructionStarting>(message),
                    message => Assert.IsAssignableFrom<ITestClassConstructionFinished>(message),
                    message =>
                    {
                        var failed = Assert.IsAssignableFrom<ITestFailed>(message);
                        Assert.Equal(typeof(TrueException).FullName, failed.ExceptionType);
                    },
                    message => Assert.IsAssignableFrom<ITestFinished>(message)
                );
            }
 private static bool IsStaticallyInvocable(MethodWrapper mw)
 {
     if (mw == null || mw.DeclaringType.IsUnloadable || mw.DeclaringType.IsGhost || mw.DeclaringType.IsNonPrimitiveValueType || mw.IsFinalizeOrClone || mw.IsDynamicOnly)
     {
         return false;
     }
     if (mw.ReturnType.IsUnloadable || mw.ReturnType.IsGhost || mw.ReturnType.IsNonPrimitiveValueType)
     {
         return false;
     }
     foreach (TypeWrapper tw in mw.GetParameters())
     {
         if (tw.IsUnloadable || tw.IsGhost || tw.IsNonPrimitiveValueType)
         {
             return false;
         }
     }
     return true;
 }
Пример #39
0
        /// <summary>
        /// Attempts to resolve current node and sets either of the following fields:
        /// _Field, _Method, _Property
        /// 
        /// The following fields are also set:
        /// _Type, _Static
        /// </summary>
        private void resolveSelf(Context ctx)
        {
            Action check = () =>
            {
                if (Expression == null && !_IsStatic)
                    error(CompilerMessages.DynamicMemberFromStaticContext, _Type, MemberName);

                if (_Method == null && TypeHints.Count > 0)
                    error(CompilerMessages.TypeArgumentsForNonMethod, _Type, MemberName);
            };

            _Type = StaticType != null
                ? ctx.ResolveType(StaticType)
                : Expression.Resolve(ctx);

            // special case: array length
            if (_Type.IsArray && MemberName == "Length")
            {
                check();
                return;
            }

            // check for field
            try
            {
                _Field = ctx.ResolveField(_Type, MemberName);
                _IsStatic = _Field.IsStatic;

                check();
                return;
            }
            catch (KeyNotFoundException) { }

            // check for property
            try
            {
                _Property = ctx.ResolveProperty(_Type, MemberName);

                if(!_Property.CanGet)
                    error(CompilerMessages.PropertyNoGetter, _Type, MemberName);

                _IsStatic = _Property.IsStatic;

                check();
                return;
            }
            catch (KeyNotFoundException) { }

            // check for event: events are only allowed at the left side of += and -=
            try
            {
                ctx.ResolveEvent(_Type, MemberName);
                error(CompilerMessages.EventAsExpr);
            }
            catch (KeyNotFoundException) { }

            // find method
            var argTypes = TypeHints.Select(t => t.FullSignature == "_" ? null : ctx.ResolveType(t)).ToArray();
            var methods = ctx.ResolveMethodGroup(_Type, MemberName).Where(m => checkMethodArgs(argTypes, m)).ToArray();

            if (methods.Length == 0)
                error(argTypes.Length == 0 ? CompilerMessages.TypeIdentifierNotFound : CompilerMessages.TypeMethodNotFound, _Type.Name, MemberName);

            if (methods.Length > 1)
                error(CompilerMessages.TypeMethodAmbiguous, _Type.Name, MemberName);

            _Method = methods[0];
            if (_Method.ArgumentTypes.Length > 16)
                error(CompilerMessages.CallableTooManyArguments);

            _IsStatic = _Method.IsStatic;

            check();
        }
 public void GetDataOrdersCustomizationAttributes(string methodName)
 {
     // Fixture setup
     var method = new MethodWrapper(typeof(TypeWithCustomizationAttributes), methodName);
     var customizationLog = new List<ICustomization>();
     var fixture = new DelegatingFixture();
     fixture.OnCustomize = c =>
     {
         customizationLog.Add(c);
         return fixture;
     };
     var sut = new AutoDataAttributeStub(fixture);
     // Exercise system
     sut.BuildFrom(method, new TestSuite(this.GetType())).Single();
     // Verify outcome
     Assert.False(customizationLog[0] is FreezeOnMatchCustomization);
     Assert.True(customizationLog[1] is FreezeOnMatchCustomization);
     // Teardown
 }
Пример #41
0
        protected override Type resolve(Context ctx, bool mustReturn)
        {
            var exprType = Expression.Resolve(ctx);
            if (exprType.IsArray)
                return exprType.GetElementType();

            var idxType = Index.Resolve(ctx);
            try
            {
                _Getter = ReflectionHelper.ResolveIndexer(exprType, idxType, true);
                return _Getter.ReturnType;
            }
            catch (LensCompilerException ex)
            {
                ex.BindToLocation(this);
                throw;
            }
        }
Пример #42
0
        /// <summary>
        /// Resolves the method as a global function, imported property or a local variable with a delegate.
        /// </summary>
        private void resolveGetIdentifier(Context ctx, GetIdentifierNode node)
        {
            var nameInfo = ctx.Scope.FindLocal(node.Identifier);
            if (nameInfo != null)
            {
                resolveExpression(ctx, node);
                return;
            }

            try
            {
                _Method = ctx.ResolveMethod(
                    ctx.MainType.TypeInfo,
                    node.Identifier,
                    _ArgTypes,
                    resolver: (idx, types) => ctx.ResolveLambda(Arguments[idx] as LambdaNode, types)
                );

                if (_Method == null)
                    throw new KeyNotFoundException();

                if(_ArgTypes.Length == 0 && node.Identifier.IsAnyOf(EntityNames.RunMethodName, EntityNames.EntryPointMethodName))
                    error(CompilerMessages.ReservedFunctionInvocation, node.Identifier);
            }
            catch (KeyNotFoundException)
            {
                error(CompilerMessages.FunctionNotFound, node.Identifier);
            }
            catch (AmbiguousMatchException)
            {
                error(CompilerMessages.FunctionInvocationAmbiguous, node.Identifier);
            }
        }
Пример #43
0
        public void ValueSourceAttributeShouldThrowInsteadOfReturningNull()
        {
            var method = new MethodWrapper(GetType(), "ValueSourceMayNotBeNull");
            var parameters = method.GetParameters();

            foreach (var parameter in parameters)
            {
                var dataSource = parameter.GetCustomAttributes<IParameterDataSource>(false)[0];
                Assert.Throws<InvalidDataSourceException>(() => dataSource.GetData(parameter)); 
            }
        }
Пример #44
0
		static int indexString(IntPtr l, object self, string key)
		{
			Type t = getType(self);

			if (self is IDictionary)
			{
				if (t.IsGenericType && t.GetGenericArguments()[0] != typeof(string))
				{
					goto IndexProperty;
				}
				object v = (self as IDictionary)[key];
				if (v != null)
				{
					pushValue(l, true);
					pushVar(l, v);
					return 2;
				}
			}

IndexProperty:
            //MemberInfo[] mis = t.GetMember(key, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            //if (mis.Length == 0)
            //{
            //    return error(l, "Can't find " + key);
            //}
            var mis = GetCacheMembers(t, key);
            if (mis == null)
            {
                return error(l, "Can't find " + key);
            }

			pushValue(l, true);
            MemberInfo mi = mis[0];
			switch (mi.MemberType)
			{
				case MemberTypes.Property:
					PropertyInfo p = (PropertyInfo)mi;
					MethodInfo get = p.GetGetMethod();
					pushVar(l, get.Invoke(self, null));
					break;
				case MemberTypes.Field:
					FieldInfo f = (FieldInfo)mi;
					pushVar(l, f.GetValue(self));
					break;
				case MemberTypes.Method:
					LuaCSFunction ff = new MethodWrapper(self, mis).invoke;
					pushObject(l, ff);
					break;
				case MemberTypes.Event:
					break;
				default:
					return 1;
			}

			return 2;

		}
Пример #45
0
        /// <summary>
        /// Resolves the method if the expression was a member getter (obj.field or type::field).
        /// </summary>
        private void resolveGetMember(Context ctx, GetMemberNode node)
        {
            _InvocationSource = node.Expression;
            var type = _InvocationSource != null
                ? _InvocationSource.Resolve(ctx)
                : ctx.ResolveType(node.StaticType);

            checkTypeInSafeMode(ctx, type);

            if (node.TypeHints != null && node.TypeHints.Count > 0)
                _TypeHints = node.TypeHints.Select(x => ctx.ResolveType(x, true)).ToArray();

            try
            {
                // resolve a normal method
                try
                {
                    _Method = ctx.ResolveMethod(
                        type,
                        node.MemberName,
                        _ArgTypes,
                        _TypeHints,
                        (idx, types) => ctx.ResolveLambda(Arguments[idx] as LambdaNode, types)
                    );

                    if (_Method.IsStatic)
                        _InvocationSource = null;

                    return;
                }
                catch (KeyNotFoundException)
                {
                    if (_InvocationSource == null)
                        throw;
                }

                // resolve a callable field
                try
                {
                    ctx.ResolveField(type, node.MemberName);
                    resolveExpression(ctx, node);
                    return;
                }
                catch (KeyNotFoundException) { }

                // resolve a callable property
                try
                {
                    ctx.ResolveProperty(type, node.MemberName);
                    resolveExpression(ctx, node);
                    return;
                }
                catch (KeyNotFoundException) { }

                Arguments = (Arguments[0] is UnitNode)
                    ? new List<NodeBase> {_InvocationSource}
                    : new[] {_InvocationSource}.Union(Arguments).ToList();

                var oldArgTypes = _ArgTypes;
                _ArgTypes = Arguments.Select(a => a.Resolve(ctx)).ToArray();
                _InvocationSource = null;

                try
                {
                    // resolve a local function that is implicitly used as an extension method
                    _Method = ctx.ResolveMethod(
                        ctx.MainType.TypeInfo,
                        node.MemberName,
                        _ArgTypes,
                        resolver: (idx, types) => ctx.ResolveLambda(Arguments[idx] as LambdaNode, types)
                    );

                    return;
                }
                catch (KeyNotFoundException) { }

                // resolve a declared extension method
                // most time-consuming operation, therefore is last checked
                try
                {
                    if(!ctx.Options.AllowExtensionMethods)
                        throw new KeyNotFoundException();

                    _Method = ctx.ResolveExtensionMethod(
                        type,
                        node.MemberName,
                        oldArgTypes,
                        _TypeHints,
                        (idx, types) => ctx.ResolveLambda(Arguments[idx] as LambdaNode, types)
                    );
                }
                catch (KeyNotFoundException)
                {
                    var msg = node.StaticType != null
                        ? CompilerMessages.TypeStaticMethodNotFound
                        : CompilerMessages.TypeMethodNotFound;

                    error(msg, type, node.MemberName);
                }
            }
            catch (AmbiguousMatchException)
            {
                error(CompilerMessages.TypeMethodInvocationAmbiguous, type, node.MemberName);
            }
        }
Пример #46
0
	private static Dictionary<int, string>[] FindLocalVariables(CodeInfo codeInfo, MethodWrapper mw, ClassFile classFile, ClassFile.Method method)
	{
		FindLocalVarState[] state = new FindLocalVarState[method.Instructions.Length];
		state[0].changed = true;
		state[0].sites = new FindLocalVarStoreSite[method.MaxLocals];
		TypeWrapper[] parameters = mw.GetParameters();
		int argpos = 0;
		if (!mw.IsStatic)
		{
			state[0].sites[argpos++].Add(-1);
		}
		for (int i = 0; i < parameters.Length; i++)
		{
			state[0].sites[argpos++].Add(-1);
			if (parameters[i].IsWidePrimitive)
			{
				argpos++;
			}
		}
		return FindLocalVariablesImpl(codeInfo, classFile, method, state);
	}
Пример #47
0
        private static bool checkMethodArgs(Type[] argTypes, MethodWrapper method)
        {
            if(argTypes.Length == 0)
                return true;

            if (method.ArgumentTypes.Length != argTypes.Length)
                return false;

            return !method.ArgumentTypes.Where((p, idx) => argTypes[idx] != null && p != argTypes[idx]).Any();
        }
Пример #48
0
	internal LocalVarInfo(CodeInfo ma, ClassFile classFile, ClassFile.Method method, UntangledExceptionTable exceptions, MethodWrapper mw, ClassLoaderWrapper classLoader)
	{
		Dictionary<int, string>[] localStoreReaders = FindLocalVariables(ma, mw, classFile, method);

		// now that we've done the code flow analysis, we can do a liveness analysis on the local variables
		ClassFile.Method.Instruction[] instructions = method.Instructions;
		Dictionary<long, LocalVar> localByStoreSite = new Dictionary<long, LocalVar>();
		List<LocalVar> locals = new List<LocalVar>();
		for (int i = 0; i < localStoreReaders.Length; i++)
		{
			if (localStoreReaders[i] != null)
			{
				VisitLocalLoads(ma, method, locals, localByStoreSite, localStoreReaders[i], i, classLoader.EmitDebugInfo);
			}
		}
		Dictionary<LocalVar, LocalVar> forwarders = new Dictionary<LocalVar, LocalVar>();
		if (classLoader.EmitDebugInfo)
		{
			InstructionFlags[] flags = MethodAnalyzer.ComputePartialReachability(ma, method.Instructions, exceptions, 0, false);
			// if we're emitting debug info, we need to keep dead stores as well...
			for (int i = 0; i < instructions.Length; i++)
			{
				if ((flags[i] & InstructionFlags.Reachable) != 0
					&& IsStoreLocal(instructions[i].NormalizedOpCode))
				{
					if (!localByStoreSite.ContainsKey(MakeKey(i, instructions[i].NormalizedArg1)))
					{
						LocalVar v = new LocalVar();
						v.local = instructions[i].NormalizedArg1;
						v.type = ma.GetStackTypeWrapper(i, 0);
						FindLvtEntry(v, method, i);
						locals.Add(v);
						localByStoreSite.Add(MakeKey(i, v.local), v);
					}
				}
			}
			// to make the debugging experience better, we have to trust the
			// LocalVariableTable (unless it's clearly bogus) and merge locals
			// together that are the same according to the LVT
			for (int i = 0; i < locals.Count - 1; i++)
			{
				for (int j = i + 1; j < locals.Count; j++)
				{
					LocalVar v1 = (LocalVar)locals[i];
					LocalVar v2 = (LocalVar)locals[j];
					if (v1.name != null && v1.name == v2.name && v1.start_pc == v2.start_pc && v1.end_pc == v2.end_pc)
					{
						// we can only merge if the resulting type is valid (this protects against incorrect
						// LVT data, but is also needed for constructors, where the uninitialized this is a different
						// type from the initialized this)
						TypeWrapper tw = InstructionState.FindCommonBaseType(v1.type, v2.type);
						if (tw != VerifierTypeWrapper.Invalid)
						{
							v1.isArg |= v2.isArg;
							v1.type = tw;
							forwarders.Add(v2, v1);
							locals.RemoveAt(j);
							j--;
						}
					}
				}
			}
		}
		else
		{
			for (int i = 0; i < locals.Count - 1; i++)
			{
				for (int j = i + 1; j < locals.Count; j++)
				{
					LocalVar v1 = (LocalVar)locals[i];
					LocalVar v2 = (LocalVar)locals[j];
					// if the two locals are the same, we merge them, this is a small
					// optimization, it should *not* be required for correctness.
					if (v1.local == v2.local && v1.type == v2.type)
					{
						v1.isArg |= v2.isArg;
						forwarders.Add(v2, v1);
						locals.RemoveAt(j);
						j--;
					}
				}
			}
		}
		invokespecialLocalVars = new LocalVar[instructions.Length][];
		localVars = new LocalVar[instructions.Length];
		for (int i = 0; i < localVars.Length; i++)
		{
			LocalVar v = null;
			if (localStoreReaders[i] != null)
			{
				Debug.Assert(IsLoadLocal(instructions[i].NormalizedOpCode));
				// lame way to look up the local variable for a load
				// (by indirecting through a corresponding store)
				foreach (int store in localStoreReaders[i].Keys)
				{
					v = localByStoreSite[MakeKey(store, instructions[i].NormalizedArg1)];
					break;
				}
			}
			else
			{
				if (instructions[i].NormalizedOpCode == NormalizedByteCode.__invokespecial)
				{
					invokespecialLocalVars[i] = new LocalVar[method.MaxLocals];
					for (int j = 0; j < invokespecialLocalVars[i].Length; j++)
					{
						localByStoreSite.TryGetValue(MakeKey(i, j), out invokespecialLocalVars[i][j]);
					}
				}
				else
				{
					localByStoreSite.TryGetValue(MakeKey(i, instructions[i].NormalizedArg1), out v);
				}
			}
			if (v != null)
			{
				LocalVar fwd;
				if (forwarders.TryGetValue(v, out fwd))
				{
					v = fwd;
				}
				localVars[i] = v;
			}
		}
		this.allLocalVars = locals.ToArray();
	}
Пример #49
0
 internal static Type CreateDelegateType(TypeWrapper tw, MethodWrapper mw)
 {
     TypeWrapper[] args = mw.GetParameters();
     if (!mw.IsStatic)
     {
         args = ArrayUtil.Concat(tw, args);
     }
     return CreateDelegateType(args, mw.ReturnType);
 }
 private void LoadParameter(MethodWrapper il, ParameterInfo parameter)
 {
     var field = GetFieldForParameter(parameter);
     il.LoadThis();
     il.LoadField(field);
 }
Пример #51
0
 public void Setup()
 {
     _testObject = new AsyncSetupTearDownFixture();
     var method = new MethodWrapper(typeof(AsyncSetupTearDownFixture), Success.ElementAt(0));
     _context = new TestExecutionContext {TestObject = _testObject, CurrentResult = new TestCaseResult(new TestMethod(method))};
 }
Пример #52
0
        /// <summary>
        /// Resolves a method from the expression, considering it an instance of a delegate type.
        /// </summary>
        private void resolveExpression(Context ctx, NodeBase node)
        {
            var exprType = node.Resolve(ctx);
            if (!exprType.IsCallableType())
                error(CompilerMessages.TypeNotCallable, exprType);

            try
            {
                // argtypes are required for partial application
                _Method = ctx.ResolveMethod(exprType, "Invoke", _ArgTypes);
            }
            catch (KeyNotFoundException)
            {
                // delegate argument types are mismatched:
                // infer whatever method there is and detect actual error
                _Method = ctx.ResolveMethod(exprType, "Invoke");

                var argTypes = _Method.ArgumentTypes;
                if (argTypes.Length != _ArgTypes.Length)
                    error(CompilerMessages.DelegateArgumentsCountMismatch, exprType, argTypes.Length, _ArgTypes.Length);

                for (var idx = 0; idx < argTypes.Length; idx++)
                {
                    var fromType = _ArgTypes[idx];
                    var toType = argTypes[idx];
                    if (!toType.IsExtendablyAssignableFrom(fromType))
                        error(Arguments[idx], CompilerMessages.ArgumentTypeMismatch, fromType, toType);
                }
            }

            _InvocationSource = node;
        }