FieldObjectCreator.java revision 1649:50be58e74a21
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.codegen;
27
28import static jdk.nashorn.internal.codegen.CompilerConstants.ARGUMENTS;
29import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup;
30import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor;
31import static jdk.nashorn.internal.codegen.ObjectClassGenerator.PRIMITIVE_FIELD_TYPE;
32import static jdk.nashorn.internal.codegen.ObjectClassGenerator.getFieldName;
33import static jdk.nashorn.internal.codegen.ObjectClassGenerator.getPaddedFieldCount;
34import static jdk.nashorn.internal.runtime.arrays.ArrayIndex.getArrayIndex;
35import static jdk.nashorn.internal.runtime.arrays.ArrayIndex.isValidArrayIndex;
36
37import java.util.List;
38import jdk.nashorn.internal.codegen.types.Type;
39import jdk.nashorn.internal.ir.Symbol;
40import jdk.nashorn.internal.runtime.Context;
41import jdk.nashorn.internal.runtime.JSType;
42import jdk.nashorn.internal.runtime.PropertyMap;
43import jdk.nashorn.internal.runtime.ScriptObject;
44import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
45
46/**
47 * Analyze an object's characteristics for appropriate code generation. This
48 * is used for functions and for objects. A field object take a set of values which
49 * to assign to the various fields in the object. This is done by the generated code
50 *
51 * @param <T> the value type for the fields being written on object creation, e.g. Node
52 * @see jdk.nashorn.internal.ir.Node
53 */
54public abstract class FieldObjectCreator<T> extends ObjectCreator<T> {
55
56    private String                        fieldObjectClassName;
57    private Class<? extends ScriptObject> fieldObjectClass;
58    private int                           fieldCount;
59    private int                           paddedFieldCount;
60    private int                           paramCount;
61
62    /** call site flags to be used for invocations */
63    private final int callSiteFlags;
64    /** are we creating this field object from 'eval' code? */
65    private final boolean evalCode;
66
67    /**
68     * Constructor
69     *
70     * @param codegen  code generator
71     * @param tuples   tuples for fields in object
72     */
73    FieldObjectCreator(final CodeGenerator codegen, final List<MapTuple<T>> tuples) {
74        this(codegen, tuples, false, false);
75    }
76
77    /**
78     * Constructor
79     *
80     * @param codegen      code generator
81     * @param tuples       tuples for fields in object
82     * @param isScope      is this a scope object
83     * @param hasArguments does the created object have an "arguments" property
84     */
85    FieldObjectCreator(final CodeGenerator codegen, final List<MapTuple<T>> tuples, final boolean isScope, final boolean hasArguments) {
86        super(codegen, tuples, isScope, hasArguments);
87        this.callSiteFlags = codegen.getCallSiteFlags();
88        this.evalCode = codegen.isEvalCode();
89        countFields();
90        findClass();
91    }
92
93    @Override
94    public void createObject(final MethodEmitter method) {
95        makeMap();
96        final String className = getClassName();
97        // NOTE: we must load the actual structure class here, because the API operates with Nashorn Type objects,
98        // and Type objects need a loaded class, for better or worse. We also have to be specific and use the type
99        // of the actual structure class, we can't generalize it to e.g. Type.typeFor(ScriptObject.class) as the
100        // exact type information is needed for generating continuations in rest-of methods. If we didn't do this,
101        // object initializers like { x: arr[i] } would fail during deoptimizing compilation on arr[i], as the
102        // values restored from the RewriteException would be cast to "ScriptObject" instead of to e.g. "JO4", and
103        // subsequently the "PUTFIELD J04.L0" instruction in the continuation code would fail bytecode verification.
104        assert fieldObjectClass != null;
105        method._new(fieldObjectClass).dup();
106
107        loadMap(method); //load the map
108
109        if (isScope()) {
110            loadScope(method);
111
112            if (hasArguments()) {
113                method.loadCompilerConstant(ARGUMENTS);
114                method.invoke(constructorNoLookup(className, PropertyMap.class, ScriptObject.class, ARGUMENTS.type()));
115            } else {
116                method.invoke(constructorNoLookup(className, PropertyMap.class, ScriptObject.class));
117            }
118        } else {
119            method.invoke(constructorNoLookup(className, PropertyMap.class));
120        }
121    }
122
123    /**
124     * Create a scope for a for-in/of loop as defined in ES6 13.7.5.13 step 5.g.iii
125     *
126     * @param method the method emitter
127     */
128    void createForInIterationScope(final MethodEmitter method) {
129        assert fieldObjectClass != null;
130        assert isScope();
131        assert getMap() != null;
132
133        final String className = getClassName();
134        method._new(fieldObjectClass).dup();
135        loadMap(method); //load the map
136        loadScope(method);
137        // We create a scope identical to the currently active one, so use its parent as our parent
138        method.invoke(ScriptObject.GET_PROTO);
139        method.invoke(constructorNoLookup(className, PropertyMap.class, ScriptObject.class));
140    }
141
142    @Override
143    public void populateRange(final MethodEmitter method, final Type objectType, final int objectSlot, final int start, final int end) {
144        method.load(objectType, objectSlot);
145        // Set values.
146        for (int i = start; i < end; i++) {
147            final MapTuple<T> tuple = tuples.get(i);
148            //we only load when we have both symbols and values (which can be == the symbol)
149            //if we didn't load, we need an array property
150            if (tuple.symbol != null && tuple.value != null) {
151                final int index = getArrayIndex(tuple.key);
152                method.dup();
153                if (!isValidArrayIndex(index)) {
154                    putField(method, tuple.key, tuple.symbol.getFieldIndex(), tuple);
155                } else {
156                    putSlot(method, ArrayIndex.toLongIndex(index), tuple);
157                }
158
159                //this is a nop of tuple.key isn't e.g. "apply" or another special name
160                method.invalidateSpecialName(tuple.key);
161            }
162        }
163    }
164
165    @Override
166    protected PropertyMap makeMap() {
167        assert propertyMap == null : "property map already initialized";
168        propertyMap = newMapCreator(fieldObjectClass).makeFieldMap(hasArguments(), codegen.useDualFields(), fieldCount, paddedFieldCount, evalCode);
169        return propertyMap;
170    }
171
172    /**
173     * Store a value in a field of the generated class object.
174     *
175     * @param method      Script method.
176     * @param key         Property key.
177     * @param fieldIndex  Field number.
178     * @param tuple       Tuple to store.
179     */
180    private void putField(final MethodEmitter method, final String key, final int fieldIndex, final MapTuple<T> tuple) {
181        final Type    fieldType   = codegen.useDualFields() && tuple.isPrimitive() ? PRIMITIVE_FIELD_TYPE : Type.OBJECT;
182        final String  fieldClass  = getClassName();
183        final String  fieldName   = getFieldName(fieldIndex, fieldType);
184        final String  fieldDesc   = typeDescriptor(fieldType.getTypeClass());
185
186        assert fieldName.equals(getFieldName(fieldIndex, PRIMITIVE_FIELD_TYPE)) || fieldType.isObject() :    key + " object keys must store to L*-fields";
187        assert fieldName.equals(getFieldName(fieldIndex, Type.OBJECT))          || fieldType.isPrimitive() : key + " primitive keys must store to J*-fields";
188
189        loadTuple(method, tuple, true);
190        method.putField(fieldClass, fieldName, fieldDesc);
191    }
192
193    /**
194     * Store a value in an indexed slot of a generated class object.
195     *
196     * @param method Script method.
197     * @param index  Slot index.
198     * @param tuple  Tuple to store.
199     */
200    private void putSlot(final MethodEmitter method, final long index, final MapTuple<T> tuple) {
201        loadIndex(method, index);
202        loadTuple(method, tuple, false); //we don't pack array like objects
203        method.dynamicSetIndex(callSiteFlags);
204    }
205
206    /**
207     * Locate (or indirectly create) the object container class.
208     */
209    private void findClass() {
210        fieldObjectClassName = isScope() ?
211                ObjectClassGenerator.getClassName(fieldCount, paramCount, codegen.useDualFields()) :
212                ObjectClassGenerator.getClassName(paddedFieldCount, codegen.useDualFields());
213
214        try {
215            this.fieldObjectClass = Context.forStructureClass(Compiler.binaryName(fieldObjectClassName));
216        } catch (final ClassNotFoundException e) {
217            throw new AssertionError("Nashorn has encountered an internal error.  Structure can not be created.");
218        }
219    }
220
221    @Override
222    protected Class<? extends ScriptObject> getAllocatorClass() {
223        return fieldObjectClass;
224    }
225
226    /**
227     * Get the class name for the object class,
228     * e.g. {@code com.nashorn.oracle.scripts.JO2P0}
229     *
230     * @return script class name
231     */
232    String getClassName() {
233        return fieldObjectClassName;
234    }
235
236    /**
237     * Tally the number of fields and parameters.
238     */
239    private void countFields() {
240        for (final MapTuple<T> tuple : tuples) {
241            final Symbol symbol = tuple.symbol;
242            if (symbol != null) {
243                if (hasArguments() && symbol.isParam()) {
244                    symbol.setFieldIndex(paramCount++);
245                } else if (!isValidArrayIndex(getArrayIndex(tuple.key))) {
246                    symbol.setFieldIndex(fieldCount++);
247                }
248            }
249        }
250
251        paddedFieldCount = getPaddedFieldCount(fieldCount);
252    }
253
254}
255