nashorn/src/jdk/internal/dynalink/support/CallSiteDescriptorFactory.java
changeset 16234 86cb162cec6c
child 16245 6a1c6c8bc113
equal deleted inserted replaced
16233:95d3e01c04c3 16234:86cb162cec6c
       
     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 /*
       
    27  * This file is available under and governed by the GNU General Public
       
    28  * License version 2 only, as published by the Free Software Foundation.
       
    29  * However, the following notice accompanied the original version of this
       
    30  * file, and Oracle licenses the original version of this file under the BSD
       
    31  * license:
       
    32  */
       
    33 /*
       
    34    Copyright 2009-2013 Attila Szegedi
       
    35 
       
    36    Licensed under both the Apache License, Version 2.0 (the "Apache License")
       
    37    and the BSD License (the "BSD License"), with licensee being free to
       
    38    choose either of the two at their discretion.
       
    39 
       
    40    You may not use this file except in compliance with either the Apache
       
    41    License or the BSD License.
       
    42 
       
    43    If you choose to use this file in compliance with the Apache License, the
       
    44    following notice applies to you:
       
    45 
       
    46        You may obtain a copy of the Apache License at
       
    47 
       
    48            http://www.apache.org/licenses/LICENSE-2.0
       
    49 
       
    50        Unless required by applicable law or agreed to in writing, software
       
    51        distributed under the License is distributed on an "AS IS" BASIS,
       
    52        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
       
    53        implied. See the License for the specific language governing
       
    54        permissions and limitations under the License.
       
    55 
       
    56    If you choose to use this file in compliance with the BSD License, the
       
    57    following notice applies to you:
       
    58 
       
    59        Redistribution and use in source and binary forms, with or without
       
    60        modification, are permitted provided that the following conditions are
       
    61        met:
       
    62        * Redistributions of source code must retain the above copyright
       
    63          notice, this list of conditions and the following disclaimer.
       
    64        * Redistributions in binary form must reproduce the above copyright
       
    65          notice, this list of conditions and the following disclaimer in the
       
    66          documentation and/or other materials provided with the distribution.
       
    67        * Neither the name of the copyright holder nor the names of
       
    68          contributors may be used to endorse or promote products derived from
       
    69          this software without specific prior written permission.
       
    70 
       
    71        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
       
    72        IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
       
    73        TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
       
    74        PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
       
    75        BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
       
    76        CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
       
    77        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
       
    78        BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
       
    79        WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
       
    80        OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
       
    81        ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    82 */
       
    83 
       
    84 package jdk.internal.dynalink.support;
       
    85 
       
    86 import java.lang.invoke.MethodHandles;
       
    87 import java.lang.invoke.MethodHandles.Lookup;
       
    88 import java.lang.invoke.MethodType;
       
    89 import java.lang.ref.WeakReference;
       
    90 import java.util.Arrays;
       
    91 import java.util.Collections;
       
    92 import java.util.List;
       
    93 import java.util.StringTokenizer;
       
    94 import java.util.WeakHashMap;
       
    95 import jdk.internal.dynalink.CallSiteDescriptor;
       
    96 
       
    97 
       
    98 /**
       
    99  * Usable as a default factory for call site descriptor implementations. It is weakly canonicalizing, meaning it will
       
   100  * return the same immutable call site descriptor for identical inputs, i.e. repeated requests for a descriptor
       
   101  * signifying public lookup for "dyn:getProp:color" of type "Object(Object)" will return the same object as long as
       
   102  * a previously created, at least softly reachable one exists. It also uses several different implementations of the
       
   103  * {@link CallSiteDescriptor} internally, and chooses the most space-efficient one based on the input.
       
   104  * @author Attila Szegedi
       
   105  */
       
   106 public class CallSiteDescriptorFactory {
       
   107     private static final WeakHashMap<CallSiteDescriptor, WeakReference<CallSiteDescriptor>> publicDescs =
       
   108             new WeakHashMap<>();
       
   109 
       
   110 
       
   111     private CallSiteDescriptorFactory() {
       
   112     }
       
   113 
       
   114     /**
       
   115      * Creates a new call site descriptor instance. The actual underlying class of the instance is dependent on the
       
   116      * passed arguments to be space efficient; i.e. if you  only use the public lookup, you'll get back an
       
   117      * implementation that doesn't waste space on storing the lookup object.
       
   118      * @param lookup the lookup that determines access rights at the call site. If your language runtime doesn't have
       
   119      * equivalents of Java access concepts, just use {@link MethodHandles#publicLookup()}. Must not be null.
       
   120      * @param name the name of the method at the call site. Must not be null.
       
   121      * @param methodType the type of the method at the call site. Must not be null.
       
   122      * @return a call site descriptor representing the input. Note that although the method name is "create", it will
       
   123      * in fact return a weakly-referenced canonical instance.
       
   124      */
       
   125     public static CallSiteDescriptor create(Lookup lookup, String name, MethodType methodType) {
       
   126         name.getClass(); // NPE check
       
   127         methodType.getClass(); // NPE check
       
   128         lookup.getClass(); // NPE check
       
   129         final String[] tokenizedName = tokenizeName(name);
       
   130         if(isPublicLookup(lookup)) {
       
   131             return getCanonicalPublicDescriptor(createPublicCallSiteDescriptor(tokenizedName, methodType));
       
   132         } else {
       
   133             return new LookupCallSiteDescriptor(tokenizedName, methodType, lookup);
       
   134         }
       
   135     }
       
   136 
       
   137     static CallSiteDescriptor getCanonicalPublicDescriptor(final CallSiteDescriptor desc) {
       
   138         synchronized(publicDescs) {
       
   139             final WeakReference<CallSiteDescriptor> ref = publicDescs.get(desc);
       
   140             if(ref != null) {
       
   141                 final CallSiteDescriptor canonical = ref.get();
       
   142                 if(canonical != null) {
       
   143                     return canonical;
       
   144                 }
       
   145             }
       
   146             publicDescs.put(desc, new WeakReference<>(desc));
       
   147         }
       
   148         return desc;
       
   149     }
       
   150 
       
   151     private static CallSiteDescriptor createPublicCallSiteDescriptor(String[] tokenizedName, MethodType methodType) {
       
   152         final int l = tokenizedName.length;
       
   153         if(l > 0 && tokenizedName[0] == "dyn") {
       
   154             if(l == 2) {
       
   155                 return new UnnamedDynCallSiteDescriptor(tokenizedName[1], methodType);
       
   156             } if (l == 3) {
       
   157                 return new NamedDynCallSiteDescriptor(tokenizedName[1], tokenizedName[2], methodType);
       
   158             }
       
   159         }
       
   160         return new DefaultCallSiteDescriptor(tokenizedName, methodType);
       
   161     }
       
   162 
       
   163     private static boolean isPublicLookup(Lookup lookup) {
       
   164         return lookup == MethodHandles.publicLookup();
       
   165     }
       
   166 
       
   167     /**
       
   168      * Tokenizes the composite name along colons, as well as {@link NameCodec#decode(String) demangles} and interns
       
   169      * the tokens. The first two tokens are not demangled as they are supposed to be the naming scheme and the name of
       
   170      * the operation which can be expected to consist of just alphabetical characters.
       
   171      * @param name the composite name consisting of colon-separated, possibly mangled tokens.
       
   172      * @return an array of tokens
       
   173      */
       
   174     public static String[] tokenizeName(String name) {
       
   175         final StringTokenizer tok = new StringTokenizer(name, CallSiteDescriptor.TOKEN_DELIMITER);
       
   176         final String[] tokens = new String[tok.countTokens()];
       
   177         for(int i = 0; i < tokens.length; ++i) {
       
   178             String token = tok.nextToken();
       
   179             if(i > 1) {
       
   180                 token = NameCodec.decode(token);
       
   181             }
       
   182             tokens[i] = token.intern();
       
   183         }
       
   184         return tokens;
       
   185     }
       
   186 
       
   187     /**
       
   188      * Tokenizes a composite operation name along pipe characters. I.e. if you have a "dyn:getElem|getProp|getMethod"
       
   189      * operation, returns a list of ["getElem", "getProp", "getMethod"]. The tokens are not interned.
       
   190      * @param desc the call site descriptor with the operation
       
   191      * @return a list of tokens
       
   192      */
       
   193     public static List<String> tokenizeOperators(CallSiteDescriptor desc) {
       
   194         final String ops = desc.getNameToken(CallSiteDescriptor.OPERATOR);
       
   195         final StringTokenizer tok = new StringTokenizer(ops, CallSiteDescriptor.OPERATOR_DELIMITER);
       
   196         final int count = tok.countTokens();
       
   197         if(count == 1) {
       
   198             return Collections.singletonList(ops);
       
   199         }
       
   200         final String[] tokens = new String[count];
       
   201         for(int i = 0; i < count; ++i) {
       
   202             tokens[i] = tok.nextToken();
       
   203         }
       
   204         return Arrays.asList(tokens);
       
   205     }
       
   206 
       
   207     /**
       
   208      * Returns a new call site descriptor that is identical to the passed one, except that it has some parameter types
       
   209      * removed from its method type.
       
   210      * @param desc the original call site descriptor
       
   211      * @param start index of the first parameter to remove
       
   212      * @param end index of the first parameter to not remove
       
   213      * @return a new call site descriptor with modified method type
       
   214      */
       
   215     public static CallSiteDescriptor dropParameterTypes(CallSiteDescriptor desc, int start, int end) {
       
   216         return desc.changeMethodType(desc.getMethodType().dropParameterTypes(start, end));
       
   217     }
       
   218 
       
   219     /**
       
   220      * Returns a new call site descriptor that is identical to the passed one, except that it has a single parameter
       
   221      * type changed in its method type.
       
   222      * @param desc the original call site descriptor
       
   223      * @param num index of the parameter to change
       
   224      * @param nptype the new parameter type
       
   225      * @return a new call site descriptor with modified method type
       
   226      */
       
   227     public static CallSiteDescriptor changeParameterType(CallSiteDescriptor desc, int num, Class<?> nptype) {
       
   228         return desc.changeMethodType(desc.getMethodType().changeParameterType(num, nptype));
       
   229     }
       
   230 
       
   231     /**
       
   232      * Returns a new call site descriptor that is identical to the passed one, except that it has the return type
       
   233      * changed in its method type.
       
   234      * @param desc the original call site descriptor
       
   235      * @param nrtype the new return type
       
   236      * @return a new call site descriptor with modified method type
       
   237      */
       
   238     public static CallSiteDescriptor changeReturnType(CallSiteDescriptor desc, Class<?> nrtype) {
       
   239         return desc.changeMethodType(desc.getMethodType().changeReturnType(nrtype));
       
   240     }
       
   241 
       
   242     /**
       
   243      * Returns a new call site descriptor that is identical to the passed one, except that it has additional parameter
       
   244      * types inserted into its method type.
       
   245      * @param desc the original call site descriptor
       
   246      * @param num index at which the new parameters are inserted
       
   247      * @param ptypesToInsert the new types to insert
       
   248      * @return a new call site descriptor with modified method type
       
   249      */
       
   250     public static CallSiteDescriptor insertParameterTypes(CallSiteDescriptor desc, int num, Class<?>... ptypesToInsert) {
       
   251         return desc.changeMethodType(desc.getMethodType().insertParameterTypes(num, ptypesToInsert));
       
   252     }
       
   253 
       
   254     /**
       
   255      * Returns a new call site descriptor that is identical to the passed one, except that it has additional parameter
       
   256      * types inserted into its method type.
       
   257      * @param desc the original call site descriptor
       
   258      * @param num index at which the new parameters are inserted
       
   259      * @param ptypesToInsert the new types to insert
       
   260      * @return a new call site descriptor with modified method type
       
   261      */
       
   262     public static CallSiteDescriptor insertParameterTypes(CallSiteDescriptor desc, int num, List<Class<?>> ptypesToInsert) {
       
   263         return desc.changeMethodType(desc.getMethodType().insertParameterTypes(num, ptypesToInsert));
       
   264     }
       
   265 }