8005801: Refactor findSetMethod
authorattila
Tue, 08 Jan 2013 14:14:17 +0100
changeset 16159 db1b36bd37c4
parent 16158 8f3a55a03b3b
child 16160 d6b675e0ce7a
8005801: Refactor findSetMethod Summary: findSetMethod() was a very large single method, very unreadable and unmaintainable. It was broken into easy-to-understand pieces. The refactoring required introduction of a comand-object like entity, SetMethodCreator, to contain the nontrivial transient state of the algorithm that made the original big method so resistant to refactoring in the first place. Reviewed-by: lagergren, sundar
nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java
nashorn/src/jdk/nashorn/internal/runtime/SetMethodCreator.java
nashorn/src/jdk/nashorn/internal/runtime/SpillProperty.java
nashorn/src/jdk/nashorn/internal/runtime/linker/Mangler.java
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java	Tue Jan 08 13:50:11 2013 +0100
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java	Tue Jan 08 14:14:17 2013 +0100
@@ -132,10 +132,11 @@
     /** Indexed array data. */
     private ArrayData arrayData;
 
-    private static final MethodHandle SETEMBED           = findOwnMH("setEmbed",         void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, MethodHandle.class, int.class, Object.class, Object.class);
-    private static final MethodHandle SETSPILL           = findOwnMH("setSpill",         void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, int.class, Object.class, Object.class);
-    private static final MethodHandle SETSPILLWITHNEW    = findOwnMH("setSpillWithNew",  void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, int.class, Object.class, Object.class);
-    private static final MethodHandle SETSPILLWITHGROW   = findOwnMH("setSpillWithGrow", void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, int.class, int.class, Object.class, Object.class);
+    static final MethodHandle SETEMBED           = findOwnMH("setEmbed",         void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, MethodHandle.class, int.class, Object.class, Object.class);
+    static final MethodHandle SETSPILL           = findOwnMH("setSpill",         void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, int.class, Object.class, Object.class);
+    static final MethodHandle SETSPILLWITHNEW    = findOwnMH("setSpillWithNew",  void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, int.class, Object.class, Object.class);
+    static final MethodHandle SETSPILLWITHGROW   = findOwnMH("setSpillWithGrow", void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, int.class, int.class, Object.class, Object.class);
+
     private static final MethodHandle TRUNCATINGFILTER   = findOwnMH("truncatingFilter", Object[].class, int.class, Object[].class);
     private static final MethodHandle KNOWNFUNCPROPGUARD = findOwnMH("knownFunctionPropertyGuard", boolean.class, Object.class, PropertyMap.class, MethodHandle.class, Object.class, ScriptFunction.class);
 
@@ -218,13 +219,14 @@
     }
 
     /**
-     * Bind the method handle to the specified receiver.
+     * Bind the method handle to the specified receiver, while preserving its original type (it will just ignore the
+     * first argument in lieu of the bound argument).
      * @param methodHandle Method handle to bind to.
      * @param receiver     Object to bind.
      * @return Bound method handle.
      */
-    private static MethodHandle bindTo(final MethodHandle methodHandle, final Object receiver) {
-        return MH.dropArguments(MH.bindTo(methodHandle, receiver), 0, Object.class);
+    static MethodHandle bindTo(final MethodHandle methodHandle, final Object receiver) {
+        return MH.dropArguments(MH.bindTo(methodHandle, receiver), 0, methodHandle.type().parameterType(0));
     }
 
     /**
@@ -1724,138 +1726,43 @@
      * @return GuardedInvocation to be invoked at call site.
      */
     protected GuardedInvocation findSetMethod(final CallSiteDescriptor desc, final boolean megaMorphic) {
-        final String      name     = desc.getNameToken(2);
+        final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
         if(megaMorphic) {
             return findMegaMorphicSetMethod(desc, name);
         }
 
-        final MethodType  callType = desc.getMethodType();
-        final PropertyMap oldMap   = getMap();
-        final Class<?>    type     = callType.parameterType(1);
-
         FindProperty find = findProperty(name, true);
-        if (!isScope()) {
-            // not a scope search. We don't want any inherited a property
-            // unless it happens to be a user defined accessor property.
-            if (find != null && find.isInherited()) {
-               final Property inherited = find.getProperty();
-               if (!(inherited instanceof UserAccessorProperty)) {
-                   // we should only use inherited user accessor property
-                   find = null;
-                   // but we should still check if inherited data property is not writable!
-                   if (isExtensible() && !inherited.isWritable()) {
-                       if (NashornCallSiteDescriptor.isStrict(desc)) {
-                           typeError(Context.getGlobal(), "property.not.writable", name, ScriptRuntime.safeToString((this)));
-                       }
-                       assert !NashornCallSiteDescriptor.isFastScope(desc);
-                       return new GuardedInvocation(Lookup.EMPTY_SETTER, oldMap.getProtoGetSwitchPoint(name),
-                               NashornGuards.getMapGuard(oldMap));
-                   }
-               }
+        // If it's not a scope search, then we don't want any inherited properties except those with user defined accessors.
+        if (!isScope() && find != null && find.isInherited() && !(find.getProperty() instanceof UserAccessorProperty)) {
+            // We should still check if inherited data property is not writable
+            if (isExtensible() && !find.isWritable()) {
+                return createEmptySetMethod(desc, "property.not.writable", false);
             }
+            // Otherwise, forget the found property
+            find = null;
         }
 
-        MethodHandle methodHandle = null;
-        Property     property     = null;
-        int          invokeFlags  = 0;
-
         if (find != null) {
-            if (!find.isWritable()) {
-                if (NashornCallSiteDescriptor.isStrict(desc)) {
-                    typeError(Context.getGlobal(), "property.not.writable", name, ScriptRuntime.safeToString(this));
-                }
-
-                return new GuardedInvocation(Lookup.EMPTY_SETTER, oldMap.getProtoGetSwitchPoint(name),
-                        NashornGuards.getMapGuard(oldMap));
-            }
-
-            property     = find.getProperty();
-            methodHandle = find.getSetter(type, NashornCallSiteDescriptor.isStrict(desc));
-
-            assert methodHandle != null;
-            assert property     != null;
-
-            final ScriptFunction setter = find.getSetterFunction();
-
-            invokeFlags = 0;
-            if (setter != null && setter.isStrict()) {
-                invokeFlags = NashornCallSiteDescriptor.CALLSITE_STRICT;
-            }
-
-            if (!property.hasSetterFunction() && find.isInherited()) {
-                methodHandle = bindTo(methodHandle, find.getOwner());
+            if(!find.isWritable()) {
+                // Existing, non-writable property
+                return createEmptySetMethod(desc, "property.not.writable", true);
             }
         } else if (!isExtensible()) {
-            if (NashornCallSiteDescriptor.isStrict(desc)) {
-                typeError(Context.getGlobal(), "object.non.extensible", name, ScriptRuntime.safeToString(this));
-            }
-
-            assert !NashornCallSiteDescriptor.isFastScope(desc);
-            return new GuardedInvocation(Lookup.EMPTY_SETTER, oldMap.getProtoGetSwitchPoint(name), NashornGuards.getMapGuard(oldMap));
+            // Non-existing property on a non-extensible object
+            return createEmptySetMethod(desc, "object.non.extensible", false);
         }
 
-        if (methodHandle == null) {
-            // In strict mode, assignment can not create a new variable.
-            // See also ECMA Annex C item 4. ReferenceError is thrown.
-            if (NashornCallSiteDescriptor.isScope(desc) && NashornCallSiteDescriptor.isStrict(desc)) {
-                referenceError(Context.getGlobal(), "not.defined", name);
-            }
-
-            if (isScope()) {
-                final ScriptObject global = Context.getGlobal();
-                methodHandle = global.addSpill(name);
-                methodHandle = bindTo(methodHandle, global);
-            } else {
-                int i = findEmbed();
-
-                if (i >= EMBED_SIZE) {
-                    i = oldMap.getSpillLength();
-
-                    final MethodHandle getter =
-                        MH.asType(
-                            MH.insertArguments(
-                                MH.arrayElementGetter(Object[].class),
-                                1,
-                                i),
-                            Lookup.GET_OBJECT_TYPE);
-                    final MethodHandle setter =
-                        MH.asType(
-                            MH.insertArguments(
-                            MH.arrayElementSetter(Object[].class),
-                            1,
-                            i),
-                            Lookup.SET_OBJECT_TYPE);
-
-                    property = new SpillProperty(name, Property.IS_SPILL, i, getter, setter);
-
-                    final PropertyMap newMap = oldMap.addProperty(property);
-
-                    i = property.getSlot();
-
-                    if (spill == null) {
-                        methodHandle = MH.insertArguments(SETSPILLWITHNEW,  0, desc, oldMap, newMap, i);
-                    } else if (i < spill.length) {
-                        methodHandle = MH.insertArguments(SETSPILL,         0, desc, oldMap, newMap, i);
-                    } else {
-                        final int newLength = (i + SPILL_RATE) / SPILL_RATE * SPILL_RATE;
-                        methodHandle = MH.insertArguments(SETSPILLWITHGROW, 0, desc, oldMap, newMap, i, newLength);
-                    }
-                } else {
-                    useEmbed(i);
-                    property = new SpillProperty(name, 0, i, GET_EMBED[i], SET_EMBED[i]);
-                    final PropertyMap newMap = oldMap.addProperty(property);
-                    //TODO specfields
-                    methodHandle = MH.insertArguments(SETEMBED, 0, desc, oldMap, newMap, property.getSetter(Object.class, getMap()), i);
-                }
-
-                notifyPropertyAdded(this, property);
-            }
-        }
-
-        // the guard has to use old map because the setter is valid only for incoming object with this map
-        return new NashornGuardedInvocation(methodHandle, null, ObjectClassGenerator.OBJECT_FIELDS_ONLY &&
-                NashornCallSiteDescriptor.isFastScope(desc) && (property == null || !property.canChangeType()) ?
-                    null : NashornGuards.getMapGuard(oldMap), invokeFlags);
+        return new SetMethodCreator(this, find, desc).createGuardedInvocation();
+    }
+
+    private GuardedInvocation createEmptySetMethod(final CallSiteDescriptor desc, String strictErrorMessage, boolean canBeFastScope) {
+        final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
+        if (NashornCallSiteDescriptor.isStrict(desc)) {
+               typeError(Context.getGlobal(), strictErrorMessage, name, ScriptRuntime.safeToString((this)));
+           }
+           assert canBeFastScope || !NashornCallSiteDescriptor.isFastScope(desc);
+           final PropertyMap map = getMap();
+           return new GuardedInvocation(Lookup.EMPTY_SETTER, map.getProtoGetSwitchPoint(name), NashornGuards.getMapGuard(map));
     }
 
     @SuppressWarnings("unused")
@@ -2169,7 +2076,7 @@
         return spillProperty.getSetter(type, getMap()); //TODO specfields
     }
 
-    private MethodHandle addSpill(final String key) {
+    MethodHandle addSpill(final String key) {
         return addSpill(key, 0);
     }
 
@@ -3216,8 +3123,8 @@
     /** Embed offset */
     public static final int EMBED_OFFSET = 32 - EMBED_SIZE;
 
-    private static final MethodHandle[] GET_EMBED;
-    private static final MethodHandle[] SET_EMBED;
+    static final MethodHandle[] GET_EMBED;
+    static final MethodHandle[] SET_EMBED;
 
     static {
         GET_EMBED = new MethodHandle[EMBED_SIZE];
@@ -3230,11 +3137,11 @@
         }
     }
 
-    private void useEmbed(final int i) {
+    void useEmbed(final int i) {
         flags |= 1 << (EMBED_OFFSET + i);
     }
 
-    private int findEmbed() {
+    int findEmbed() {
         final int bits  = ~(flags >>> EMBED_OFFSET);
         final int least = bits ^ -bits;
         final int index = Integer.numberOfTrailingZeros(least) - 1;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk/nashorn/internal/runtime/SetMethodCreator.java	Tue Jan 08 14:14:17 2013 +0100
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.nashorn.internal.runtime;
+
+import static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
+import static jdk.nashorn.internal.runtime.linker.Lookup.MH;
+
+import java.lang.invoke.MethodHandle;
+
+import jdk.nashorn.internal.codegen.objects.ObjectClassGenerator;
+import jdk.nashorn.internal.runtime.linker.Lookup;
+import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
+import jdk.nashorn.internal.runtime.linker.NashornGuardedInvocation;
+import jdk.nashorn.internal.runtime.linker.NashornGuards;
+
+import org.dynalang.dynalink.CallSiteDescriptor;
+import org.dynalang.dynalink.linker.GuardedInvocation;
+
+/**
+ * Instances of this class are quite ephemeral; they only exist for the duration of an invocation of
+ * {@link ScriptObject#findSetMethod(CallSiteDescriptor, boolean)} and serve as the actual encapsulation of the
+ * algorithm for creating an appropriate property setter method.
+ */
+class SetMethodCreator {
+    // See constructor parameters for description of fields
+    private final ScriptObject sobj;
+    private final PropertyMap map;
+    private final FindProperty find;
+    private final CallSiteDescriptor desc;
+
+    /**
+     * Creates a new property setter method creator.
+     * @param sobj the object for which we're creating the property setter
+     * @param find a result of a {@link ScriptObject#findProperty(String, boolean)} on the object for the property we
+     * want to create a setter for. Can be null if the property does not yet exist on the object.
+     * @param desc the descriptor of the call site that triggered the property setter lookup
+     */
+    SetMethodCreator(final ScriptObject sobj, final FindProperty find, final CallSiteDescriptor desc) {
+        this.sobj = sobj;
+        this.map = sobj.getMap();
+        this.find = find;
+        this.desc = desc;
+    }
+
+    private String getName() {
+        return desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
+    }
+
+    private PropertyMap getMap() {
+        return map;
+    }
+
+    /**
+     * Creates the actual guarded invocation that represents the dynamic setter method for the property.
+     * @return the actual guarded invocation that represents the dynamic setter method for the property.
+     */
+    GuardedInvocation createGuardedInvocation() {
+        return createSetMethod().createGuardedInvocation();
+    }
+
+    /**
+     * This class encapsulates the results of looking up a setter method; it's basically a triple of a method hanle,
+     * a Property object, and flags for invocation.
+     *
+     */
+    private class SetMethod {
+        private final MethodHandle methodHandle;
+        private final Property property;
+        private final int invokeFlags;
+
+        /**
+         * Creates a new lookup result.
+         * @param methodHandle the actual method handle
+         * @param property the property object. Can be null in case we're creating a new property in the global object.
+         * @param invokeFlags flags for the invocation. Normally either 0, or
+         * {@link NashornCallSiteDescriptor#CALLSITE_STRICT} when an existing property with a strict function for a
+         * property setter is discovered.
+         */
+        SetMethod(final MethodHandle methodHandle, final Property property, final int invokeFlags) {
+            assert methodHandle != null;
+            this.methodHandle = methodHandle;
+            this.property = property;
+            this.invokeFlags = invokeFlags;
+        }
+
+        /**
+         * Composes from its components an actual guarded invocation that represents the dynamic setter method for the property.
+         * @return the composed guarded invocation that represents the dynamic setter method for the property.
+         */
+        GuardedInvocation createGuardedInvocation() {
+            return new NashornGuardedInvocation(methodHandle, null, getGuard(), invokeFlags);
+        }
+
+        private MethodHandle getGuard() {
+            return needsNoGuard() ? null : NashornGuards.getMapGuard(getMap());
+        }
+
+        private boolean needsNoGuard() {
+            return NashornCallSiteDescriptor.isFastScope(desc) &&
+                    (ObjectClassGenerator.OBJECT_FIELDS_ONLY || isPropertyTypeStable());
+        }
+
+        private boolean isPropertyTypeStable() {
+            return property == null || !property.canChangeType();
+        }
+    }
+
+    private SetMethod createSetMethod() {
+        if (find != null) {
+            return createExistingPropertySetter();
+        }
+
+        checkStrictCreateNewVariable();
+
+        if (sobj.isScope()) {
+            return createGlobalPropertySetter();
+        }
+
+        return createNewPropertySetter();
+    }
+
+    private void checkStrictCreateNewVariable() {
+        // In strict mode, assignment can not create a new variable.
+        // See also ECMA Annex C item 4. ReferenceError is thrown.
+        if (NashornCallSiteDescriptor.isScope(desc) && NashornCallSiteDescriptor.isStrict(desc)) {
+            referenceError(Context.getGlobal(), "not.defined", getName());
+        }
+    }
+
+    private SetMethod createExistingPropertySetter() {
+        final Property property = find.getProperty();
+        final Class<?> type = desc.getMethodType().parameterType(1);
+        final MethodHandle methodHandle = find.getSetter(type, NashornCallSiteDescriptor.isStrict(desc));
+
+        assert methodHandle != null;
+        assert property     != null;
+
+        final MethodHandle boundHandle;
+        if (!property.hasSetterFunction() && find.isInherited()) {
+            boundHandle = ScriptObject.bindTo(methodHandle, find.getOwner());
+        } else {
+            boundHandle = methodHandle;
+        }
+        return new SetMethod(boundHandle, property, getExistingPropertySetterInvokeFlags());
+    }
+
+    private int getExistingPropertySetterInvokeFlags() {
+        final ScriptFunction setter = find.getSetterFunction();
+        if (setter != null && setter.isStrict()) {
+            return NashornCallSiteDescriptor.CALLSITE_STRICT;
+        }
+        return 0;
+    }
+
+    private SetMethod createGlobalPropertySetter() {
+        final ScriptObject global = Context.getGlobal();
+        return new SetMethod(ScriptObject.bindTo(global.addSpill(getName()), global), null, 0);
+    }
+
+    private SetMethod createNewPropertySetter() {
+        final int nextEmbed = sobj.findEmbed();
+        final SetMethod sm;
+        if (nextEmbed >= ScriptObject.EMBED_SIZE) {
+            sm = createNewSpillPropertySetter();
+        } else {
+            sm = createNewEmbedPropertySetter(nextEmbed);
+        }
+
+        sobj.notifyPropertyAdded(sobj, sm.property);
+        return sm;
+    }
+
+    private SetMethod createNewSpillPropertySetter() {
+        final int nextSpill = getMap().getSpillLength();
+
+        final Property property = createSpillProperty(nextSpill);
+        return new SetMethod(createSpillMethodHandle(nextSpill, property), property, 0);
+    }
+
+    private Property createSpillProperty(final int nextSpill) {
+        final MethodHandle getter = MH.asType(MH.insertArguments(MH.arrayElementGetter(Object[].class), 1, nextSpill), Lookup.GET_OBJECT_TYPE);
+        final MethodHandle setter = MH.asType(MH.insertArguments(MH.arrayElementSetter(Object[].class), 1, nextSpill), Lookup.SET_OBJECT_TYPE);
+
+        return new SpillProperty(getName(), Property.IS_SPILL, nextSpill, getter, setter);
+    }
+
+    private MethodHandle createSpillMethodHandle(final int nextSpill, Property property) {
+        final PropertyMap oldMap = getMap();
+        final PropertyMap newMap = getNewMap(property);
+
+        final Object[] spill = sobj.spill;
+        if (spill == null) {
+            return MH.insertArguments(ScriptObject.SETSPILLWITHNEW,  0, desc, oldMap, newMap, nextSpill);
+        } else if (nextSpill < spill.length) {
+            return MH.insertArguments(ScriptObject.SETSPILL,         0, desc, oldMap, newMap, nextSpill);
+        } else {
+            final int newLength = (nextSpill + ScriptObject.SPILL_RATE) / ScriptObject.SPILL_RATE * ScriptObject.SPILL_RATE;
+            return MH.insertArguments(ScriptObject.SETSPILLWITHGROW, 0, desc, oldMap, newMap, nextSpill, newLength);
+        }
+    }
+
+    private SetMethod createNewEmbedPropertySetter(final int nextEmbed) {
+        sobj.useEmbed(nextEmbed);
+        final Property property = new SpillProperty(getName(), 0, nextEmbed, ScriptObject.GET_EMBED[nextEmbed], ScriptObject.SET_EMBED[nextEmbed]);
+        //TODO specfields
+        final MethodHandle methodHandle = MH.insertArguments(ScriptObject.SETEMBED, 0, desc, getMap(), getNewMap(property), property.getSetter(Object.class, getMap()), nextEmbed);
+        return new SetMethod(methodHandle, property, 0);
+    }
+
+    private PropertyMap getNewMap(Property property) {
+        return getMap().addProperty(property);
+    }
+}
--- a/nashorn/src/jdk/nashorn/internal/runtime/SpillProperty.java	Tue Jan 08 13:50:11 2013 +0100
+++ b/nashorn/src/jdk/nashorn/internal/runtime/SpillProperty.java	Tue Jan 08 14:14:17 2013 +0100
@@ -43,7 +43,7 @@
     private static final MethodHandle SPILLGETTER = MH.asType(MH.getter(MethodHandles.lookup(), ScriptObject.class, "spill", Object[].class), Lookup.GET_OBJECT_TYPE);
 
     /** Property slot in spill */
-    int slot;
+    private final int slot;
 
     /**
      * Constructor
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/Mangler.java	Tue Jan 08 13:50:11 2013 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,140 +0,0 @@
-/*
- * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package jdk.nashorn.internal.runtime.linker;
-
-import java.util.Arrays;
-
-/**
- * Used to mangle java visible names. Currently used only to transform script file
- * name to be safely used as part of generated Script class name.
- */
-public class Mangler {
-    /** Beginning of escape sequence (mu as in municode.) */
-    private static final char ESCAPE = '\u03BC';
-
-    /** Hexadecimal base. */
-    private static final char hexBase = 'A';
-
-    /** Hexadecimal characters. */
-    private static final char[] hexCharacters = new char[] {
-        '0',
-        '1',
-        '2',
-        '3',
-        '4',
-        '5',
-        '6',
-        '7',
-        '8',
-        '9',
-        hexBase + 0,
-        hexBase + 1,
-        hexBase + 2,
-        hexBase + 3,
-        hexBase + 4,
-        hexBase + 5
-    };
-
-    private Mangler() {
-    }
-
-    /**
-     * Mangles a user supplied name so it is java identifier safe.
-     * @param name Name to be mangled
-     * @return Mangled name or null if not mangled.
-     */
-    public static String mangle(final String name) {
-        final int length = name.length();
-        final char[] buffer = new char[length * 5];
-        boolean mangled = false;
-        int pos = 0;
-
-        for (int i = 0; i < length; i++) {
-            final char ch = name.charAt(i);
-
-            if (! Character.isJavaIdentifierPart(ch)) {
-                buffer[pos++] = ESCAPE;
-                buffer[pos++] = hexCharacters[(ch >>> 12) & 0xF];
-                buffer[pos++] = hexCharacters[(ch >>>  8) & 0xF];
-                buffer[pos++] = hexCharacters[(ch >>>  4) & 0xF];
-                buffer[pos++] = hexCharacters[ ch         & 0xF];
-                mangled = true;
-            } else if (ch == ESCAPE) {
-                buffer[pos++] = ESCAPE;
-                buffer[pos++] = ESCAPE;
-                mangled = true;
-            } else {
-                buffer[pos++] = ch;
-            }
-        }
-
-        return mangled ? new String(Arrays.copyOf(buffer, pos)) : null;
-    }
-
-    /**
-     * Convert a character to a hexadecimal digit. Assumes [0-9A-F].
-     * @param ch Character to convert.
-     * @return Hexadecimal digit.
-     */
-    private static int fromHex(final char ch) {
-        return ch >= hexBase ? ch - hexBase + 10 : ch - '0';
-    }
-
-    /**
-     * Unmangles a name. Assumes name mangled by this package.
-     * @param name Mangled name.
-     * @return Unmangled name.
-     */
-    public static String unmangle(final String name) {
-        final int length = name.length();
-        char[] buffer = new char[length];
-        int pos = 0;
-
-        for (int i = 0; i < length; ) {
-            char ch = name.charAt(i++);
-
-            if (ch == ESCAPE) {
-                final char ch0 = name.charAt(i++);
-
-                if (ch0 == ESCAPE) {
-                    // pass thru
-                } else {
-                     final char ch1 = name.charAt(i++);
-                     final char ch2 = name.charAt(i++);
-                     final char ch3 = name.charAt(i++);
-
-                     ch = (char)(fromHex(ch0) << 12 | fromHex(ch1) << 8 | fromHex(ch2) << 4 | fromHex(ch3));
-                }
-            }
-
-            buffer[pos++] = ch;
-        }
-
-        buffer = Arrays.copyOf(buffer, pos);
-
-        return new String(buffer);
-    }
-}