NashornStaticClassLinker.java revision 1551:f3b883bec2d0
1/*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package jdk.nashorn.internal.runtime.linker;
27
28import java.lang.reflect.Modifier;
29import jdk.dynalink.CallSiteDescriptor;
30import jdk.dynalink.NamedOperation;
31import jdk.dynalink.StandardOperation;
32import jdk.dynalink.beans.BeansLinker;
33import jdk.dynalink.beans.StaticClass;
34import jdk.dynalink.linker.GuardedInvocation;
35import jdk.dynalink.linker.GuardingDynamicLinker;
36import jdk.dynalink.linker.LinkRequest;
37import jdk.dynalink.linker.LinkerServices;
38import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
39import jdk.dynalink.linker.support.Guards;
40import jdk.nashorn.internal.runtime.Context;
41import jdk.nashorn.internal.runtime.ECMAErrors;
42
43/**
44 * Internal linker for {@link StaticClass} objects, only ever used by Nashorn engine and not exposed to other engines.
45 * It is used for extending the "new" operator on StaticClass in order to be able to instantiate interfaces and abstract
46 * classes by passing a ScriptObject or ScriptFunction as their implementation, e.g.:
47 * <pre>
48 *   var r = new Runnable() { run: function() { print("Hello World" } }
49 * </pre>
50 * or for SAM types, even just passing a function:
51 * <pre>
52 *   var r = new Runnable(function() { print("Hello World" })
53 * </pre>
54 */
55final class NashornStaticClassLinker implements TypeBasedGuardingDynamicLinker {
56    private static final GuardingDynamicLinker staticClassLinker = BeansLinker.getLinkerForClass(StaticClass.class);
57
58    @Override
59    public boolean canLinkType(final Class<?> type) {
60        return type == StaticClass.class;
61    }
62
63    @Override
64    public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
65        final Object self = request.getReceiver();
66        if (self.getClass() != StaticClass.class) {
67            return null;
68        }
69        final Class<?> receiverClass = ((StaticClass) self).getRepresentedClass();
70
71        Bootstrap.checkReflectionAccess(receiverClass, true);
72        final CallSiteDescriptor desc = request.getCallSiteDescriptor();
73        // We intercept "new" on StaticClass instances to provide additional capabilities
74        if (NamedOperation.getBaseOperation(desc.getOperation()) == StandardOperation.NEW) {
75            if (! Modifier.isPublic(receiverClass.getModifiers())) {
76                throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName());
77            }
78
79            // make sure new is on accessible Class
80            Context.checkPackageAccess(receiverClass);
81
82            // Is the class abstract? (This includes interfaces.)
83            if (NashornLinker.isAbstractClass(receiverClass)) {
84                // Change this link request into a link request on the adapter class.
85                final Object[] args = request.getArguments();
86                args[0] = JavaAdapterFactory.getAdapterClassFor(new Class<?>[] { receiverClass }, null,
87                        NashornCallSiteDescriptor.getLookupInternal(request.getCallSiteDescriptor()));
88                final LinkRequest adapterRequest = request.replaceArguments(request.getCallSiteDescriptor(), args);
89                final GuardedInvocation gi = checkNullConstructor(delegate(linkerServices, adapterRequest), receiverClass);
90                // Finally, modify the guard to test for the original abstract class.
91                return gi.replaceMethods(gi.getInvocation(), Guards.getIdentityGuard(self));
92            }
93            // If the class was not abstract, just delegate linking to the standard StaticClass linker. Make an
94            // additional check to ensure we have a constructor. We could just fall through to the next "return"
95            // statement, except we also insert a call to checkNullConstructor() which throws an ECMAScript TypeError
96            // with a more intuitive message when no suitable constructor is found.
97            return checkNullConstructor(delegate(linkerServices, request), receiverClass);
98        }
99        // In case this was not a "new" operation, just delegate to the the standard StaticClass linker.
100        return delegate(linkerServices, request);
101    }
102
103    private static GuardedInvocation delegate(final LinkerServices linkerServices, final LinkRequest request) throws Exception {
104        return NashornBeansLinker.getGuardedInvocation(staticClassLinker, request, linkerServices);
105    }
106
107    private static GuardedInvocation checkNullConstructor(final GuardedInvocation ctorInvocation, final Class<?> receiverClass) {
108        if(ctorInvocation == null) {
109            throw ECMAErrors.typeError("no.constructor.matches.args", receiverClass.getName());
110        }
111        return ctorInvocation;
112    }
113}
114