internal virtual LambdaForm FilterArgumentForm(int pos, BasicType newType)
        {
            Transform  key  = Transform.Of(Transform.Kind.FILTER_ARG, pos, newType.ordinal());
            LambdaForm form = GetInCache(key);

            if (form != null)
            {
                assert(form.Arity_Renamed == LambdaForm.Arity_Renamed);
                assert(form.ParameterType(pos) == newType);
                return(form);
            }

            BasicType  oldType    = LambdaForm.ParameterType(pos);
            MethodType filterType = MethodType.MethodType(oldType.basicTypeClass(), newType.basicTypeClass());

            form = MakeArgumentCombinationForm(pos, filterType, false, false);
            return(PutInCache(key, form));
        }
Beispiel #2
0
 static CallSite()
 {
     MethodHandleImpl.InitStatics();
     try
     {
         GET_TARGET = IMPL_LOOKUP.findVirtual(typeof(CallSite), "getTarget", MethodType.MethodType(typeof(MethodHandle)));
         THROW_UCS  = IMPL_LOOKUP.findStatic(typeof(CallSite), "uninitializedCallSite", MethodType.MethodType(typeof(Object), typeof(Object[])));
     }
     catch (ReflectiveOperationException e)
     {
         throw newInternalError(e);
     }
     try
     {
         TARGET_OFFSET = UNSAFE.objectFieldOffset(typeof(CallSite).getDeclaredField("target"));
     }
     catch (Exception ex)
     {
         throw new Error(ex);
     }
 }
        private static LambdaForm MakePreparedFieldLambdaForm(sbyte formOp, bool isVolatile, int ftypeKind)
        {
            bool    isGetter  = (formOp & 1) == (AF_GETFIELD & 1);
            bool    isStatic  = (formOp >= AF_GETSTATIC);
            bool    needsInit = (formOp >= AF_GETSTATIC_INIT);
            bool    needsCast = (ftypeKind == FT_CHECKED_REF);
            Wrapper fw        = (needsCast ? Wrapper.OBJECT : Wrapper.values()[ftypeKind]);
            Class   ft        = fw.primitiveType();

            assert(FtypeKind(needsCast ? typeof(String) : ft) == ftypeKind);
            String tname  = fw.primitiveSimpleName();
            String ctname = char.ToUpper(tname.CharAt(0)) + tname.Substring(1);

            if (isVolatile)
            {
                ctname += "Volatile";
            }
            String     getOrPut   = (isGetter ? "get" : "put");
            String     linkerName = (getOrPut + ctname);         // getObject, putIntVolatile, etc.
            MethodType linkerType;

            if (isGetter)
            {
                linkerType = MethodType.MethodType(ft, typeof(Object), typeof(long));
            }
            else
            {
                linkerType = MethodType.methodType(typeof(void), typeof(Object), typeof(long), ft);
            }
            MemberName linker = new MemberName(typeof(Unsafe), linkerName, linkerType, REF_invokeVirtual);

            try
            {
                linker = IMPL_NAMES.ResolveOrFail(REF_invokeVirtual, linker, null, typeof(NoSuchMethodException));
            }
            catch (ReflectiveOperationException ex)
            {
                throw newInternalError(ex);
            }

            // What is the external type of the lambda form?
            MethodType mtype;

            if (isGetter)
            {
                mtype = MethodType.MethodType(ft);
            }
            else
            {
                mtype = MethodType.MethodType(typeof(void), ft);
            }
            mtype = mtype.BasicType();             // erase short to int, etc.
            if (!isStatic)
            {
                mtype = mtype.InsertParameterTypes(0, typeof(Object));
            }
            const int DMH_THIS = 0;
            const int ARG_BASE = 1;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int ARG_LIMIT = ARG_BASE + mtype.parameterCount();
            int ARG_LIMIT = ARG_BASE + mtype.ParameterCount();
            // if this is for non-static access, the base pointer is stored at this index:
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int OBJ_BASE = isStatic ? -1 : ARG_BASE;
            int OBJ_BASE = isStatic ? -1 : ARG_BASE;
            // if this is for write access, the value to be written is stored at this index:
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int SET_VALUE = isGetter ? -1 : ARG_LIMIT - 1;
            int SET_VALUE  = isGetter ? -1 : ARG_LIMIT - 1;
            int nameCursor = ARG_LIMIT;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int F_HOLDER = (isStatic ? nameCursor++ : -1);
            int F_HOLDER = (isStatic ? nameCursor++: -1);             // static base if any
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int F_OFFSET = nameCursor++;
            int F_OFFSET = nameCursor++;             // Either static offset or field offset.
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1);
            int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++: -1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int INIT_BAR = (needsInit ? nameCursor++ : -1);
            int INIT_BAR = (needsInit ? nameCursor++: -1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int PRE_CAST = (needsCast && !isGetter ? nameCursor++ : -1);
            int PRE_CAST = (needsCast && !isGetter ? nameCursor++: -1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int LINKER_CALL = nameCursor++;
            int LINKER_CALL = nameCursor++;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1);
            int POST_CAST = (needsCast && isGetter ? nameCursor++: -1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int RESULT = nameCursor-1;
            int RESULT = nameCursor - 1;             // either the call or the cast

            Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.InvokerType());
            if (needsInit)
            {
                names[INIT_BAR] = new Name(Lazy.NF_ensureInitialized, names[DMH_THIS]);
            }
            if (needsCast && !isGetter)
            {
                names[PRE_CAST] = new Name(Lazy.NF_checkCast, names[DMH_THIS], names[SET_VALUE]);
            }
            Object[] outArgs = new Object[1 + linkerType.ParameterCount()];
            assert(outArgs.Length == (isGetter ? 3 : 4));
            outArgs[0] = UNSAFE;
            if (isStatic)
            {
                outArgs[1] = names[F_HOLDER] = new Name(Lazy.NF_staticBase, names[DMH_THIS]);
                outArgs[2] = names[F_OFFSET] = new Name(Lazy.NF_staticOffset, names[DMH_THIS]);
            }
            else
            {
                outArgs[1] = names[OBJ_CHECK] = new Name(Lazy.NF_checkBase, names[OBJ_BASE]);
                outArgs[2] = names[F_OFFSET] = new Name(Lazy.NF_fieldOffset, names[DMH_THIS]);
            }
            if (!isGetter)
            {
                outArgs[3] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]);
            }
            foreach (Object a in outArgs)
            {
                assert(a != null);
            }
            names[LINKER_CALL] = new Name(linker, outArgs);
            if (needsCast && isGetter)
            {
                names[POST_CAST] = new Name(Lazy.NF_checkCast, names[DMH_THIS], names[LINKER_CALL]);
            }
            foreach (Name n in names)
            {
                assert(n != null);
            }
            String fieldOrStatic = (isStatic ? "Static" : "Field");
            String lambdaName    = (linkerName + fieldOrStatic);          // significant only for debugging

            if (needsCast)
            {
                lambdaName += "Cast";
            }
            if (needsInit)
            {
                lambdaName += "Init";
            }
            return(new LambdaForm(lambdaName, ARG_LIMIT, names, RESULT));
        }
        internal virtual LambdaForm FilterReturnForm(BasicType newType, bool constantZero)
        {
            Transform.Kind kind = (constantZero ? Transform.Kind.FILTER_RETURN_TO_ZERO : Transform.Kind.FILTER_RETURN);
            Transform      key  = Transform.Of(kind, newType.ordinal());
            LambdaForm     form = GetInCache(key);

            if (form != null)
            {
                assert(form.Arity_Renamed == LambdaForm.Arity_Renamed);
                assert(form.ReturnType() == newType);
                return(form);
            }
            LambdaFormBuffer buf = Buffer();

            buf.StartEdit();

            int  insPos = LambdaForm.Names.Length;
            Name callFilter;

            if (constantZero)
            {
                // Synthesize a constant zero value for the given type.
                if (newType == V_TYPE)
                {
                    callFilter = null;
                }
                else
                {
                    callFilter = new Name(constantZero(newType));
                }
            }
            else
            {
                BoundMethodHandle.SpeciesData oldData = OldSpeciesData();
                BoundMethodHandle.SpeciesData newData = NewSpeciesData(L_TYPE);

                // The newly created LF will run with a different BMH.
                // Switch over any pre-existing BMH field references to the new BMH class.
                Name oldBaseAddress = LambdaForm.Parameter(0);                 // BMH holding the values
                buf.ReplaceFunctions(oldData.GetterFunctions(), newData.GetterFunctions(), oldBaseAddress);
                Name newBaseAddress = oldBaseAddress.withConstraint(newData);
                buf.RenameParameter(0, newBaseAddress);

                Name getFilter = new Name(newData.GetterFunction(oldData.FieldCount()), newBaseAddress);
                buf.InsertExpression(insPos++, getFilter);
                BasicType oldType = LambdaForm.ReturnType();
                if (oldType == V_TYPE)
                {
                    MethodType filterType = MethodType.MethodType(newType.basicTypeClass());
                    callFilter = new Name(filterType, getFilter);
                }
                else
                {
                    MethodType filterType = MethodType.MethodType(newType.basicTypeClass(), oldType.basicTypeClass());
                    callFilter = new Name(filterType, getFilter, LambdaForm.Names[LambdaForm.Result]);
                }
            }

            if (callFilter != null)
            {
                buf.InsertExpression(insPos++, callFilter);
            }
            buf.Result = callFilter;

            form = buf.EndEdit();
            return(PutInCache(key, form));
        }
        /// <summary>
        /// Produces an instance of the given single-method interface which redirects
        /// its calls to the given method handle.
        /// <para>
        /// A single-method interface is an interface which declares a uniquely named method.
        /// When determining the uniquely named method of a single-method interface,
        /// the public {@code Object} methods ({@code toString}, {@code equals}, {@code hashCode})
        /// are disregarded.  For example, <seealso cref="java.util.Comparator"/> is a single-method interface,
        /// even though it re-declares the {@code Object.equals} method.
        /// </para>
        /// <para>
        /// The interface must be public.  No additional access checks are performed.
        /// </para>
        /// <para>
        /// The resulting instance of the required type will respond to
        /// invocation of the type's uniquely named method by calling
        /// the given target on the incoming arguments,
        /// and returning or throwing whatever the target
        /// returns or throws.  The invocation will be as if by
        /// {@code target.invoke}.
        /// The target's type will be checked before the
        /// instance is created, as if by a call to {@code asType},
        /// which may result in a {@code WrongMethodTypeException}.
        /// </para>
        /// <para>
        /// The uniquely named method is allowed to be multiply declared,
        /// with distinct type descriptors.  (E.g., it can be overloaded,
        /// or can possess bridge methods.)  All such declarations are
        /// connected directly to the target method handle.
        /// Argument and return types are adjusted by {@code asType}
        /// for each individual declaration.
        /// </para>
        /// <para>
        /// The wrapper instance will implement the requested interface
        /// and its super-types, but no other single-method interfaces.
        /// This means that the instance will not unexpectedly
        /// pass an {@code instanceof} test for any unrequested type.
        /// <p style="font-size:smaller;">
        /// <em>Implementation Note:</em>
        /// Therefore, each instance must implement a unique single-method interface.
        /// Implementations may not bundle together
        /// multiple single-method interfaces onto single implementation classes
        /// in the style of <seealso cref="java.awt.AWTEventMulticaster"/>.
        /// </para>
        /// <para>
        /// The method handle may throw an <em>undeclared exception</em>,
        /// which means any checked exception (or other checked throwable)
        /// not declared by the requested type's single abstract method.
        /// If this happens, the throwable will be wrapped in an instance of
        /// <seealso cref="java.lang.reflect.UndeclaredThrowableException UndeclaredThrowableException"/>
        /// and thrown in that wrapped form.
        /// </para>
        /// <para>
        /// Like <seealso cref="java.lang.Integer#valueOf Integer.valueOf"/>,
        /// {@code asInterfaceInstance} is a factory method whose results are defined
        /// by their behavior.
        /// It is not guaranteed to return a new instance for every call.
        /// </para>
        /// <para>
        /// Because of the possibility of <seealso cref="java.lang.reflect.Method#isBridge bridge methods"/>
        /// and other corner cases, the interface may also have several abstract methods
        /// with the same name but having distinct descriptors (types of returns and parameters).
        /// In this case, all the methods are bound in common to the one given target.
        /// The type check and effective {@code asType} conversion is applied to each
        /// method type descriptor, and all abstract methods are bound to the target in common.
        /// Beyond this type check, no further checks are made to determine that the
        /// abstract methods are related in any way.
        /// </para>
        /// <para>
        /// Future versions of this API may accept additional types,
        /// such as abstract classes with single abstract methods.
        /// Future versions of this API may also equip wrapper instances
        /// with one or more additional public "marker" interfaces.
        /// </para>
        /// <para>
        /// If a security manager is installed, this method is caller sensitive.
        /// During any invocation of the target method handle via the returned wrapper,
        /// the original creator of the wrapper (the caller) will be visible
        /// to context checks requested by the security manager.
        ///
        /// </para>
        /// </summary>
        /// @param <T> the desired type of the wrapper, a single-method interface </param>
        /// <param name="intfc"> a class object representing {@code T} </param>
        /// <param name="target"> the method handle to invoke from the wrapper </param>
        /// <returns> a correctly-typed wrapper for the given target </returns>
        /// <exception cref="NullPointerException"> if either argument is null </exception>
        /// <exception cref="IllegalArgumentException"> if the {@code intfc} is not a
        ///         valid argument to this method </exception>
        /// <exception cref="WrongMethodTypeException"> if the target cannot
        ///         be converted to the type required by the requested interface </exception>
        // Other notes to implementors:
        // <p>
        // No stable mapping is promised between the single-method interface and
        // the implementation class C.  Over time, several implementation
        // classes might be used for the same type.
        // <p>
        // If the implementation is able
        // to prove that a wrapper of the required type
        // has already been created for a given
        // method handle, or for another method handle with the
        // same behavior, the implementation may return that wrapper in place of
        // a new wrapper.
        // <p>
        // This method is designed to apply to common use cases
        // where a single method handle must interoperate with
        // an interface that implements a function-like
        // API.  Additional variations, such as single-abstract-method classes with
        // private constructors, or interfaces with multiple but related
        // entry points, must be covered by hand-written or automatically
        // generated adapter classes.
        //
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @CallerSensitive public static <T> T asInterfaceInstance(final Class intfc, final MethodHandle target)
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET:
        public static T asInterfaceInstance <T>(Class intfc, MethodHandle target)
        {
            if (!intfc.Interface || !Modifier.IsPublic(intfc.Modifiers))
            {
                throw newIllegalArgumentException("not a public interface", intfc.Name);
            }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final MethodHandle mh;
            MethodHandle mh;

            if (System.SecurityManager != null)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final Class caller = sun.reflect.Reflection.getCallerClass();
                Class caller = Reflection.CallerClass;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final ClassLoader ccl = caller != null ? caller.getClassLoader() : null;
                ClassLoader ccl = caller != null ? caller.ClassLoader : null;
                ReflectUtil.checkProxyPackageAccess(ccl, intfc);
                mh = ccl != null?BindCaller(target, caller) : target;
            }
            else
            {
                mh = target;
            }
            ClassLoader proxyLoader = intfc.ClassLoader;

            if (proxyLoader == null)
            {
                ClassLoader cl = Thread.CurrentThread.ContextClassLoader;                 // avoid use of BCP
                proxyLoader = cl != null ? cl : ClassLoader.SystemClassLoader;
            }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final Method[] methods = getSingleNameMethods(intfc);
            Method[] methods = GetSingleNameMethods(intfc);
            if (methods == null)
            {
                throw newIllegalArgumentException("not a single-method interface", intfc.Name);
            }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final MethodHandle[] vaTargets = new MethodHandle[methods.length];
            MethodHandle[] vaTargets = new MethodHandle[methods.Length];
            for (int i = 0; i < methods.Length; i++)
            {
                Method       sm          = methods[i];
                MethodType   smMT        = MethodType.MethodType(sm.ReturnType, sm.ParameterTypes);
                MethodHandle checkTarget = mh.AsType(smMT);                 // make throw WMT
                checkTarget  = checkTarget.AsType(checkTarget.Type().ChangeReturnType(typeof(Object)));
                vaTargets[i] = checkTarget.AsSpreader(typeof(Object[]), smMT.ParameterCount());
            }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final InvocationHandler ih = new InvocationHandler()
            InvocationHandler ih = new InvocationHandlerAnonymousInnerClassHelper(intfc, target, methods, vaTargets);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final Object proxy;
            Object proxy;

            if (System.SecurityManager != null)
            {
                // sun.invoke.WrapperInstance is a restricted interface not accessible
                // by any non-null class loader.
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final ClassLoader loader = proxyLoader;
                ClassLoader loader = proxyLoader;
                proxy = AccessController.doPrivileged(new PrivilegedActionAnonymousInnerClassHelper(intfc, ih, loader));
            }
            else
            {
                proxy = Proxy.NewProxyInstance(proxyLoader, new Class[] { intfc, typeof(WrapperInstance) }, ih);
            }
            return(intfc.Cast(proxy));
        }