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 jdk.internal.dynalink.CallSiteDescriptor;
  34 import jdk.internal.dynalink.linker.GuardedInvocation;
  35 import jdk.internal.dynalink.linker.LinkRequest;
  36 import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
  37 import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
  38 
  39 
  40 /**
  41  * This class supports the handling of scope in a with body.
  42  *
  43  */
  44 public final class WithObject extends ScriptObject implements Scope {
  45 
  46     private static final MethodHandle WITHEXPRESSIONFILTER   = findOwnMH("withFilterExpression", Object.class, Object.class);
  47     private static final MethodHandle WITHSCOPEFILTER        = findOwnMH("withFilterScope",      Object.class, Object.class);
  48     private static final MethodHandle BIND_TO_EXPRESSION_OBJ = findOwnMH("bindToExpression",     Object.class, Object.class, Object.class);
  49     private static final MethodHandle BIND_TO_EXPRESSION_FN  = findOwnMH("bindToExpression",     Object.class, ScriptFunction.class, Object.class);
  50 
  51     /** With expression object. */
  52     private final Object expression;
  53 
  54     /**
  55      * Constructor
  56      *
  57      * @param scope scope object
  58      * @param expression with expression
  59      */
  60     WithObject(final ScriptObject scope, final Object expression) {
  61         super(scope, null);
  62         setIsScope();
  63         this.expression = expression;
  64     }
  65 

  66     /**
  67      * Delete a property based on a key.
  68      * @param key Any valid JavaScript value.
  69      * @param strict strict mode execution.
  70      * @return True if deleted.
  71      */
  72     @Override
  73     public boolean delete(final Object key, final boolean strict) {
  74         if (expression instanceof ScriptObject) {
  75             final ScriptObject self = (ScriptObject)expression;
  76             final String propName = JSType.toString(key);
  77 
  78             final FindProperty find = self.findProperty(propName, true);
  79 
  80             if (find != null) {
  81                 return self.delete(propName, strict);
  82             }
  83         }
  84 
  85         return false;
  86     }
  87 
  88 
  89     @Override
  90     public GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request) {
  91         // With scopes can never be observed outside of Nashorn code, so all call sites that can address it will of
  92         // necessity have a Nashorn descriptor - it is safe to cast.
  93         final NashornCallSiteDescriptor ndesc = (NashornCallSiteDescriptor)desc;
  94         FindProperty find = null;
  95         GuardedInvocation link = null;
  96         ScriptObject self = null;
  97 
  98         final boolean isNamedOperation;
  99         final String name;
 100         if(desc.getNameTokenCount() > 2) {
 101             isNamedOperation = true;
 102             name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
 103         } else {
 104             isNamedOperation = false;
 105             name = null;
 106         }
 107 
 108         if (expression instanceof ScriptObject) {
 109             self = (ScriptObject)expression;
 110             if (isNamedOperation) {
 111                 find = self.findProperty(name, true);
 112             }
 113 
 114             if (find != null) {
 115                 link = self.lookup(desc, request);
 116 
 117                 if (link != null) {
 118                     return fixExpressionCallSite(ndesc, link);
 119                 }
 120             }
 121         }
 122 
 123         final ScriptObject scope = getProto();
 124         if (isNamedOperation) {
 125             find = scope.findProperty(name, true);
 126         }
 127 
 128         if (find != null) {
 129             return fixScopeCallSite(scope.lookup(desc, request));
 130         }
 131 
 132         // the property is not found - now check for
 133         // __noSuchProperty__ and __noSuchMethod__ in expression
 134         if (self != null) {
 135             final String fallBack;
 136 
 137             final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
 138 
 139             switch (operator) {
 140             case "callMethod":
 141                 throw new AssertionError(); // Nashorn never emits callMethod
 142             case "getMethod":
 143                 fallBack = NO_SUCH_METHOD_NAME;
 144                 break;
 145             case "getProp":
 146             case "getElem":
 147                 fallBack = NO_SUCH_PROPERTY_NAME;
 148                 break;
 149             default:
 150                 fallBack = null;
 151                 break;
 152             }
 153 
 154             if (fallBack != null) {
 155                 find = self.findProperty(fallBack, true);
 156                 if (find != null) {
 157                     switch (operator) {
 158                     case "getMethod":
 159                         link = self.noSuchMethod(desc, request);
 160                         break;
 161                     case "getProp":
 162                     case "getElem":
 163                         link = self.noSuchProperty(desc, request);
 164                         break;
 165                     default:
 166                         break;
 167                     }
 168                 }
 169             }
 170 
 171             if (link != null) {
 172                 return fixExpressionCallSite(ndesc, link);
 173             }
 174         }
 175 
 176         // still not found, may be scope can handle with it's own
 177         // __noSuchProperty__, __noSuchMethod__ etc.
 178         link = scope.lookup(desc, request);
 179 
 180         if (link != null) {
 181             return fixScopeCallSite(link);
 182         }
 183 
 184         return null;
 185     }
 186 
 187     /**
 188      * Overridden to try to find the property first in the expression object (and its prototypes), and only then in this
 189      * object (and its prototypes).
 190      *
 191      * @param key  Property key.
 192      * @param deep Whether the search should look up proto chain.
 193      * @param stopOnNonScope should a deep search stop on the first non-scope object?
 194      * @param start the object on which the lookup was originally initiated
 195      *
 196      * @return FindPropertyData or null if not found.
 197      */
 198     @Override
 199     FindProperty findProperty(final String key, final boolean deep, final boolean stopOnNonScope, final ScriptObject start) {
 200         if (expression instanceof ScriptObject) {
 201             final FindProperty exprProperty = ((ScriptObject)expression).findProperty(key, deep, stopOnNonScope, start);
 202             if(exprProperty != null) {
 203                 return exprProperty;
 204             }
 205         }
 206         return super.findProperty(key, deep, stopOnNonScope, start);
 207     }
 208 
 209     @Override
 210     public void setSplitState(final int state) {
 211         getNonWithParent().setSplitState(state);
 212     }
 213 
 214     @Override
 215     public int getSplitState() {
 216         return getNonWithParent().getSplitState();
 217     }
 218 
 219     /**
 220      * Get first parent scope that is not an instance of WithObject.
 221      */
 222     private Scope getNonWithParent() {
 223         ScriptObject proto = getProto();
 224 
 225         while (proto != null && proto instanceof WithObject) {
 226             proto = proto.getProto();
 227         }
 228 
 229         assert proto instanceof Scope : "with scope without parent scope";
 230         return (Scope) proto;
 231     }
 232 

 233     private static GuardedInvocation fixReceiverType(final GuardedInvocation link, final MethodHandle filter) {
 234         // The receiver may be an Object or a ScriptObject.
 235         final MethodType invType = link.getInvocation().type();
 236         final MethodType newInvType = invType.changeParameterType(0, filter.type().returnType());
 237         return link.asType(newInvType);
 238     }
 239 
 240     private static GuardedInvocation fixExpressionCallSite(final NashornCallSiteDescriptor desc, final GuardedInvocation link) {
 241         // If it's not a getMethod, just add an expression filter that converts WithObject in "this" position to its
 242         // expression.
 243         if(!"getMethod".equals(desc.getFirstOperator())) {
 244             return fixReceiverType(link, WITHEXPRESSIONFILTER).filterArguments(0, WITHEXPRESSIONFILTER);
 245         }
 246 
 247         final MethodHandle linkInvocation = link.getInvocation();
 248         final MethodType linkType = linkInvocation.type();
 249         final boolean linkReturnsFunction = ScriptFunction.class.isAssignableFrom(linkType.returnType());
 250         return link.replaceMethods(
 251                 // Make sure getMethod will bind the script functions it receives to WithObject.expression
 252                 MH.foldArguments(linkReturnsFunction ? BIND_TO_EXPRESSION_FN : BIND_TO_EXPRESSION_OBJ,
 253                         filter(linkInvocation.asType(linkType.changeReturnType(
 254                                 linkReturnsFunction ? ScriptFunction.class : Object.class)), WITHEXPRESSIONFILTER)),
 255                 // No clever things for the guard -- it is still identically filtered.
 256                 filterGuard(link, WITHEXPRESSIONFILTER));
 257     }
 258 
 259     private static GuardedInvocation fixScopeCallSite(final GuardedInvocation link) {
 260         final GuardedInvocation newLink = fixReceiverType(link, WITHSCOPEFILTER);
 261         return link.replaceMethods(filter(newLink.getInvocation(), WITHSCOPEFILTER), filterGuard(newLink, WITHSCOPEFILTER));




 262     }
 263 
 264     private static MethodHandle filterGuard(final GuardedInvocation link, final MethodHandle filter) {
 265         final MethodHandle test = link.getGuard();
 266         return test == null ? null : filter(test, filter);
 267     }
 268 
 269     private static MethodHandle filter(final MethodHandle mh, final MethodHandle filter) {
 270         return MH.filterArguments(mh, 0, filter);
 271     }
 272 
 273     /**
 274      * Drops the WithObject wrapper from the expression.
 275      * @param receiver WithObject wrapper.
 276      * @return The with expression.
 277      */
 278     public static Object withFilterExpression(final Object receiver) {
 279         return ((WithObject)receiver).expression;
 280     }
 281 
 282 
 283     @SuppressWarnings("unused")
 284     private static Object bindToExpression(final Object fn, final Object receiver) {
 285         return fn instanceof ScriptFunction ? bindToExpression((ScriptFunction) fn, receiver) : fn;
 286     }
 287 
 288     private static Object bindToExpression(final ScriptFunction fn, final Object receiver) {
 289         return fn.makeBoundFunction(withFilterExpression(receiver), new Object[0]);
 290     }
 291 











 292     /**
 293      * Drops the WithObject wrapper from the scope.
 294      * @param receiver WithObject wrapper.
 295      * @return The with scope.
 296      */
 297     public static Object withFilterScope(final Object receiver) {
 298         return ((WithObject)receiver).getProto();
 299     }
 300 
 301     /**
 302      * Get the with expression for this {@code WithObject}
 303      * @return the with expression
 304      */
 305     public Object getExpression() {
 306         return expression;




 307     }
 308 
 309     private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
 310         return MH.findStatic(MethodHandles.lookup(), WithObject.class, name, MH.type(rtype, types));
 311     }
 312 }
--- EOF ---