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 
  26 package jdk.nashorn.internal.runtime;
  27 
  28 import static jdk.nashorn.internal.lookup.Lookup.MH;
  29 
  30 import java.lang.invoke.MethodHandle;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.invoke.MethodType;
  33 import java.lang.invoke.SwitchPoint;
  34 import jdk.internal.dynalink.CallSiteDescriptor;
  35 import jdk.internal.dynalink.linker.GuardedInvocation;
  36 import jdk.internal.dynalink.linker.LinkRequest;
  37 import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
  38 import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
  39 import jdk.nashorn.internal.runtime.linker.NashornGuards;
  40 
  41 /**
  42  * This class supports the handling of scope in a with body.
  43  *
  44  */
  45 public final class WithObject extends ScriptObject implements Scope {
  46     private static final MethodHandle WITHEXPRESSIONGUARD    = findOwnMH("withExpressionGuard",  boolean.class, Object.class, PropertyMap.class, SwitchPoint.class);
  47     private static final MethodHandle WITHEXPRESSIONFILTER   = findOwnMH("withFilterExpression", Object.class, Object.class);
  48     private static final MethodHandle WITHSCOPEFILTER        = findOwnMH("withFilterScope",      Object.class, Object.class);
  49     private static final MethodHandle BIND_TO_EXPRESSION_OBJ = findOwnMH("bindToExpression",     Object.class, Object.class, Object.class);
  50     private static final MethodHandle BIND_TO_EXPRESSION_FN  = findOwnMH("bindToExpression",     Object.class, ScriptFunction.class, Object.class);
  51 
  52     /** With expression object. */
  53     private final ScriptObject expression;
  54 
  55     /**
  56      * Constructor
  57      *
  58      * @param scope scope object
  59      * @param expression with expression
  60      */
  61     WithObject(final ScriptObject scope, final ScriptObject expression) {
  62         super(scope, null);
  63         setIsScope();
  64         this.expression = expression;
  65     }
  66 
  67 
  68     /**
  69      * Delete a property based on a key.
  70      * @param key Any valid JavaScript value.
  71      * @param strict strict mode execution.
  72      * @return True if deleted.
  73      */
  74     @Override
  75     public boolean delete(final Object key, final boolean strict) {
  76         final ScriptObject self = expression;
  77         final String propName = JSType.toString(key);
  78 
  79         final FindProperty find = self.findProperty(propName, true);
  80 
  81         if (find != null) {
  82             return self.delete(propName, strict);
  83         }
  84 
  85         return false;
  86     }
  87 
  88 
  89     @Override
  90     public GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request) {
  91         if (request.isCallSiteUnstable()) {
  92             // Fall back to megamorphic invocation which performs a complete lookup each time without further relinking.
  93             return super.lookup(desc, request);
  94         }
  95 
  96         // With scopes can never be observed outside of Nashorn code, so all call sites that can address it will of
  97         // necessity have a Nashorn descriptor - it is safe to cast.
  98         final NashornCallSiteDescriptor ndesc = (NashornCallSiteDescriptor)desc;
  99         FindProperty find = null;
 100         GuardedInvocation link = null;
 101         ScriptObject self = null;
 102 
 103         final boolean isNamedOperation;
 104         final String name;
 105         if(desc.getNameTokenCount() > 2) {
 106             isNamedOperation = true;
 107             name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
 108         } else {
 109             isNamedOperation = false;
 110             name = null;
 111         }
 112 
 113         self = expression;
 114         if (isNamedOperation) {
 115              find = self.findProperty(name, true);
 116         }
 117 
 118         if (find != null) {
 119             link = self.lookup(desc, request);
 120 
 121             if (link != null) {
 122                 return fixExpressionCallSite(ndesc, link);
 123             }
 124         }
 125 
 126         final ScriptObject scope = getProto();
 127         if (isNamedOperation) {
 128             find = scope.findProperty(name, true);
 129         }
 130 
 131         if (find != null) {
 132             return fixScopeCallSite(scope.lookup(desc, request), name, find.getOwner());
 133         }
 134 
 135         // the property is not found - now check for
 136         // __noSuchProperty__ and __noSuchMethod__ in expression
 137         if (self != null) {
 138             final String fallBack;
 139 
 140             final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
 141 
 142             switch (operator) {
 143             case "callMethod":
 144                 throw new AssertionError(); // Nashorn never emits callMethod
 145             case "getMethod":
 146                 fallBack = NO_SUCH_METHOD_NAME;
 147                 break;
 148             case "getProp":
 149             case "getElem":
 150                 fallBack = NO_SUCH_PROPERTY_NAME;
 151                 break;
 152             default:
 153                 fallBack = null;
 154                 break;
 155             }
 156 
 157             if (fallBack != null) {
 158                 find = self.findProperty(fallBack, true);
 159                 if (find != null) {
 160                     switch (operator) {
 161                     case "getMethod":
 162                         link = self.noSuchMethod(desc, request);
 163                         break;
 164                     case "getProp":
 165                     case "getElem":
 166                         link = self.noSuchProperty(desc, request);
 167                         break;
 168                     default:
 169                         break;
 170                     }
 171                 }
 172             }
 173 
 174             if (link != null) {
 175                 return fixExpressionCallSite(ndesc, link);
 176             }
 177         }
 178 
 179         // still not found, may be scope can handle with it's own
 180         // __noSuchProperty__, __noSuchMethod__ etc.
 181         link = scope.lookup(desc, request);
 182 
 183         if (link != null) {
 184             return fixScopeCallSite(link, name, null);
 185         }
 186 
 187         return null;
 188     }
 189 
 190     /**
 191      * Overridden to try to find the property first in the expression object (and its prototypes), and only then in this
 192      * object (and its prototypes).
 193      *
 194      * @param key  Property key.
 195      * @param deep Whether the search should look up proto chain.
 196      * @param stopOnNonScope should a deep search stop on the first non-scope object?
 197      * @param start the object on which the lookup was originally initiated
 198      *
 199      * @return FindPropertyData or null if not found.
 200      */
 201     @Override
 202     FindProperty findProperty(final String key, final boolean deep, final boolean stopOnNonScope, final ScriptObject start) {
 203         final FindProperty exprProperty = expression.findProperty(key, deep, stopOnNonScope, start);
 204         if (exprProperty != null) {
 205              return exprProperty;
 206         }
 207         return super.findProperty(key, deep, stopOnNonScope, start);
 208     }
 209 
 210     @Override
 211     public void setSplitState(final int state) {
 212         getNonWithParent().setSplitState(state);
 213     }
 214 
 215     @Override
 216     public int getSplitState() {
 217         return getNonWithParent().getSplitState();
 218     }
 219 
 220     /**
 221      * Get first parent scope that is not an instance of WithObject.
 222      */
 223     private Scope getNonWithParent() {
 224         ScriptObject proto = getParentScope();
 225 
 226         while (proto != null && proto instanceof WithObject) {
 227             proto = ((WithObject)proto).getParentScope();
 228         }
 229 
 230         assert proto instanceof Scope : "with scope without parent scope";
 231         return (Scope) proto;
 232     }
 233 
 234 
 235     private static GuardedInvocation fixReceiverType(final GuardedInvocation link, final MethodHandle filter) {
 236         // The receiver may be an Object or a ScriptObject.
 237         final MethodType invType = link.getInvocation().type();
 238         final MethodType newInvType = invType.changeParameterType(0, filter.type().returnType());
 239         return link.asType(newInvType);
 240     }
 241 
 242     private static GuardedInvocation fixExpressionCallSite(final NashornCallSiteDescriptor desc, final GuardedInvocation link) {
 243         // If it's not a getMethod, just add an expression filter that converts WithObject in "this" position to its
 244         // expression.
 245         if(!"getMethod".equals(desc.getFirstOperator())) {
 246             return fixReceiverType(link, WITHEXPRESSIONFILTER).filterArguments(0, WITHEXPRESSIONFILTER);
 247         }
 248 
 249         final MethodHandle linkInvocation = link.getInvocation();
 250         final MethodType linkType = linkInvocation.type();
 251         final boolean linkReturnsFunction = ScriptFunction.class.isAssignableFrom(linkType.returnType());
 252         return link.replaceMethods(
 253                 // Make sure getMethod will bind the script functions it receives to WithObject.expression
 254                 MH.foldArguments(linkReturnsFunction ? BIND_TO_EXPRESSION_FN : BIND_TO_EXPRESSION_OBJ,
 255                         filter(linkInvocation.asType(linkType.changeReturnType(
 256                                 linkReturnsFunction ? ScriptFunction.class : Object.class)), WITHEXPRESSIONFILTER)),
 257                 // No clever things for the guard -- it is still identically filtered.
 258                 filterGuard(link, WITHEXPRESSIONFILTER));
 259     }
 260 
 261     private GuardedInvocation fixScopeCallSite(final GuardedInvocation link, final String name, final ScriptObject owner) {
 262         final GuardedInvocation newLink = fixReceiverType(link, WITHSCOPEFILTER);
 263         return link.replaceMethods(filter(newLink.getInvocation(), WITHSCOPEFILTER),
 264                 NashornGuards.combineGuards(expressionGuard(name, owner), filterGuard(newLink, WITHSCOPEFILTER)));
 265     }
 266 
 267     private static MethodHandle filterGuard(final GuardedInvocation link, final MethodHandle filter) {
 268         final MethodHandle test = link.getGuard();
 269         return test == null ? null : filter(test, filter);
 270     }
 271 
 272     private static MethodHandle filter(final MethodHandle mh, final MethodHandle filter) {
 273         return MH.filterArguments(mh, 0, filter.asType(filter.type().changeReturnType(mh.type().parameterType(0))));
 274     }
 275 
 276     /**
 277      * Drops the WithObject wrapper from the expression.
 278      * @param receiver WithObject wrapper.
 279      * @return The with expression.
 280      */
 281     public static Object withFilterExpression(final Object receiver) {
 282         return ((WithObject)receiver).expression;
 283     }
 284 
 285     @SuppressWarnings("unused")
 286     private static Object bindToExpression(final Object fn, final Object receiver) {
 287         return fn instanceof ScriptFunction ? bindToExpression((ScriptFunction) fn, receiver) : fn;
 288     }
 289 
 290     private static Object bindToExpression(final ScriptFunction fn, final Object receiver) {
 291         return fn.makeBoundFunction(withFilterExpression(receiver), new Object[0]);
 292     }
 293 
 294     private MethodHandle expressionGuard(final String name, final ScriptObject owner) {
 295         final PropertyMap map = expression.getMap();
 296         final SwitchPoint sp = expression.getProtoSwitchPoint(name, owner);
 297         return MH.insertArguments(WITHEXPRESSIONGUARD, 1, map, sp);
 298     }
 299 
 300     @SuppressWarnings("unused")
 301     private static boolean withExpressionGuard(final Object receiver, final PropertyMap map, final SwitchPoint sp) {
 302         return ((WithObject)receiver).expression.getMap() == map && (sp == null || !sp.hasBeenInvalidated());
 303     }
 304 
 305     /**
 306      * Drops the WithObject wrapper from the scope.
 307      * @param receiver WithObject wrapper.
 308      * @return The with scope.
 309      */
 310     public static Object withFilterScope(final Object receiver) {
 311         return ((WithObject)receiver).getProto();
 312     }
 313 
 314     /**
 315      * Get the with expression for this {@code WithObject}
 316      * @return the with expression
 317      */
 318     public ScriptObject getExpression() {
 319         return expression;
 320     }
 321 
 322     /**
 323      * Get the parent scope for this {@code WithObject}
 324      * @return the parent scope
 325      */
 326     public ScriptObject getParentScope() {
 327         return getProto();
 328     }
 329 
 330     private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
 331         return MH.findStatic(MethodHandles.lookup(), WithObject.class, name, MH.type(rtype, types));
 332     }
 333 }