~ubuntu-branches/ubuntu/karmic/rhino/karmic

« back to all changes in this revision

Viewing changes to src/org/mozilla/javascript/IdScriptable.java

  • Committer: Bazaar Package Importer
  • Author(s): Jerry Haltom
  • Date: 2005-03-19 16:56:07 UTC
  • mto: (11.1.1 squeeze)
  • mto: This revision was merged to the branch mainline in revision 3.
  • Revision ID: james.westby@ubuntu.com-20050319165607-geu3j3fnqlkpqkh1
Tags: upstream-1.6.R1
ImportĀ upstreamĀ versionĀ 1.6.R1

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*-
2
 
 *
3
 
 * The contents of this file are subject to the Netscape Public
4
 
 * License Version 1.1 (the "License"); you may not use this file
5
 
 * except in compliance with the License. You may obtain a copy of
6
 
 * the License at http://www.mozilla.org/NPL/
7
 
 *
8
 
 * Software distributed under the License is distributed on an "AS
9
 
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
10
 
 * implied. See the License for the specific language governing
11
 
 * rights and limitations under the License.
12
 
 *
13
 
 * The Original Code is Rhino code, released
14
 
 * May 6, 1999.
15
 
 *
16
 
 * The Initial Developer of the Original Code is Netscape
17
 
 * Communications Corporation.  Portions created by Netscape are
18
 
 * Copyright (C) 1997-1999 Netscape Communications Corporation. All
19
 
 * Rights Reserved.
20
 
 *
21
 
 * Contributor(s):
22
 
 * Igor Bukanov
23
 
 *
24
 
 * Alternatively, the contents of this file may be used under the
25
 
 * terms of the GNU Public License (the "GPL"), in which case the
26
 
 * provisions of the GPL are applicable instead of those above.
27
 
 * If you wish to allow use of your version of this file only
28
 
 * under the terms of the GPL and not to allow others to use your
29
 
 * version of this file under the NPL, indicate your decision by
30
 
 * deleting the provisions above and replace them with the notice
31
 
 * and other provisions required by the GPL.  If you do not delete
32
 
 * the provisions above, a recipient may use your version of this
33
 
 * file under either the NPL or the GPL.
34
 
 */
35
 
 
36
 
package org.mozilla.javascript;
37
 
 
38
 
/**
39
 
Base class for native object implementation that uses IdFunction to export its methods to script via <class-name>.prototype object.
40
 
 
41
 
Any descendant should implement at least the following methods:
42
 
    mapNameToId
43
 
    getIdName
44
 
    execMethod
45
 
    methodArity
46
 
 
47
 
To define non-function properties, the descendant should customize
48
 
    getIdValue
49
 
    setIdValue
50
 
    getIdDefaultAttributes
51
 
    maxInstanceId
52
 
to get/set property value and provide its default attributes.
53
 
 
54
 
To customize initializition of constructor and protype objects, descendant
55
 
may override scopeInit or fillConstructorProperties methods.
56
 
 
57
 
*/
58
 
public abstract class IdScriptable extends ScriptableObject
59
 
    implements IdFunctionMaster
60
 
{
61
 
    /** NULL_TAG can be used to distinguish between uninitialized and null
62
 
     ** values
63
 
     */
64
 
    protected static final Object NULL_TAG = new Object();
65
 
 
66
 
    public IdScriptable() {
67
 
        activateIdMap(maxInstanceId());
68
 
    }
69
 
    
70
 
    public boolean has(String name, Scriptable start) {
71
 
        if (maxId != 0) {
72
 
            int id = mapNameToId(name);
73
 
            if (id != 0) {
74
 
                return hasValue(id);
75
 
            }
76
 
        }
77
 
        return super.has(name, start);
78
 
    }
79
 
 
80
 
    public Object get(String name, Scriptable start) {
81
 
        if (CACHE_NAMES) {
82
 
            int maxId = this.maxId;
83
 
            L:if (maxId != 0) {
84
 
                Object[] data = idMapData;
85
 
                if (data == null) { 
86
 
                    int id = mapNameToId(name);
87
 
                    if (id != 0) {
88
 
                        return getIdValue(id);
89
 
                    }
90
 
                }
91
 
                else {
92
 
                    int id = lastIdCache;
93
 
                    if (data[id - 1 + maxId] != name) {
94
 
                        id = mapNameToId(name);
95
 
                        if (id == 0) { break L; }
96
 
                           data[id - 1 + maxId] = name;
97
 
                           lastIdCache = id;
98
 
                    }
99
 
                    Object value = data[id - 1];
100
 
                    if (value == null) {
101
 
                        value = getIdValue(id);
102
 
                    }
103
 
                    else if (value == NULL_TAG) {
104
 
                        value = null;
105
 
                    }
106
 
                    return value;
107
 
                }
108
 
            }
109
 
        }
110
 
        else {
111
 
            if (maxId != 0) {
112
 
                int id = mapNameToId(name);
113
 
                if (id != 0) {
114
 
                    Object[] data = idMapData;
115
 
                    if (data == null) { 
116
 
                        return getIdValue(id);
117
 
                    }
118
 
                    else {
119
 
                        Object value = data[id - 1];
120
 
                        if (value == null) {
121
 
                            value = getIdValue(id);
122
 
                        }
123
 
                        else if (value == NULL_TAG) {
124
 
                            value = null;
125
 
                        }
126
 
                        return value;
127
 
                    }
128
 
                }
129
 
            }
130
 
        }
131
 
        return super.get(name, start);
132
 
    }
133
 
 
134
 
    public void put(String name, Scriptable start, Object value) {
135
 
        if (maxId != 0) {
136
 
            int id = mapNameToId(name);
137
 
            if (id != 0) {
138
 
                int attr = getAttributes(id);
139
 
                if ((attr & READONLY) == 0) {
140
 
                    if (start == this) {
141
 
                        setIdValue(id, value);
142
 
                    }
143
 
                    else {
144
 
                        start.put(name, start, value);
145
 
                    }
146
 
                }
147
 
                return;
148
 
            }
149
 
        }
150
 
        super.put(name, start, value);
151
 
    }
152
 
 
153
 
    public void delete(String name) {
154
 
        if (maxId != 0) {
155
 
            int id = mapNameToId(name);
156
 
            if (id != 0) {
157
 
                // Let the super class to throw exceptions for sealed objects
158
 
                if (!isSealed()) {
159
 
                    int attr = getAttributes(id);
160
 
                    if ((attr & PERMANENT) == 0) {
161
 
                        deleteIdValue(id);
162
 
                    }
163
 
                    return;
164
 
                }
165
 
            }
166
 
        }
167
 
        super.delete(name);
168
 
    }
169
 
 
170
 
    public int getAttributes(String name, Scriptable start)
171
 
        throws PropertyException
172
 
    {
173
 
        if (maxId != 0) {
174
 
            int id = mapNameToId(name);
175
 
            if (id != 0) {
176
 
                if (hasValue(id)) {
177
 
                    return getAttributes(id);
178
 
                }
179
 
                // For ids with deleted values super will throw exceptions
180
 
            }
181
 
        }
182
 
        return super.getAttributes(name, start);
183
 
    }
184
 
 
185
 
    public void setAttributes(String name, Scriptable start,
186
 
                              int attributes)
187
 
        throws PropertyException
188
 
    {
189
 
        if (maxId != 0) {
190
 
            int id = mapNameToId(name);
191
 
            if (id != 0) {
192
 
                if (hasValue(id)) {
193
 
                    synchronized (this) {
194
 
                        setAttributes(id, attributes);
195
 
                    }
196
 
                    return;
197
 
                }
198
 
                // For ids with deleted values super will throw exceptions
199
 
            }
200
 
        }
201
 
        super.setAttributes(name, start, attributes);
202
 
    }
203
 
 
204
 
    synchronized void addPropertyAttribute(int attribute) {
205
 
        extraIdAttributes |= (byte)attribute;
206
 
        super.addPropertyAttribute(attribute);
207
 
    }
208
 
 
209
 
    /**
210
 
     * Redefine ScriptableObject.defineProperty to allow changing
211
 
     * values/attributes of id-based properties unless 
212
 
     * getIdDefaultAttributes contains the READONLY attribute.
213
 
     * @see #getIdDefaultAttributes
214
 
     * @see org.mozilla.javascript.ScriptableObject#defineProperty
215
 
     */
216
 
    public void defineProperty(String propertyName, Object value,
217
 
                               int attributes)
218
 
    {
219
 
        if (maxId != 0) {
220
 
            int id = mapNameToId(propertyName);
221
 
            if (id != 0) {
222
 
                int default_attributes = getIdDefaultAttributes(id);
223
 
                if ((default_attributes & READONLY) != 0) {
224
 
                    // It is a bug to redefine id with readonly attributes
225
 
                    throw new RuntimeException
226
 
                        ("Attempt to redefine read-only id " + propertyName);
227
 
                }
228
 
                setAttributes(id, attributes);
229
 
                setIdValue(id, value);
230
 
                return;
231
 
            }
232
 
        }
233
 
        super.defineProperty(propertyName, value, attributes);
234
 
    }
235
 
 
236
 
    Object[] getIds(boolean getAll) {
237
 
        Object[] result = super.getIds(getAll);
238
 
        
239
 
        if (maxId != 0) {
240
 
            Object[] ids = null;
241
 
            int count = 0;
242
 
            
243
 
            for (int id = maxId; id != 0; --id) {
244
 
                if (hasValue(id)) {
245
 
                    if (getAll || (getAttributes(id) & DONTENUM) == 0) {
246
 
                        if (count == 0) {
247
 
                            // Need extra room for nor more then [1..id] names
248
 
                            ids = new Object[id];
249
 
                        }
250
 
                        ids[count++] = getIdName(id);
251
 
                    }
252
 
                }
253
 
            }
254
 
            if (count != 0) {
255
 
                if (result.length == 0 && ids.length == count) {
256
 
                    result = ids;
257
 
                }
258
 
                else {
259
 
                    Object[] tmp = new Object[result.length + count];
260
 
                    System.arraycopy(result, 0, tmp, 0, result.length);
261
 
                    System.arraycopy(ids, 0, tmp, result.length, count);
262
 
                    result = tmp;
263
 
                }
264
 
            }
265
 
        }
266
 
        return result;
267
 
    }
268
 
 
269
 
    /** Return maximum id number that should be present in each instance. */
270
 
    protected int maxInstanceId() { return 0; }
271
 
 
272
 
    /**
273
 
     * Map name to id of prototype or instance property.
274
 
     * Should return 0 if not found
275
 
     */
276
 
    protected abstract int mapNameToId(String name);
277
 
 
278
 
    /** Map id back to property name it defines.
279
 
     */
280
 
    protected abstract String getIdName(int id);
281
 
 
282
 
    /** Get default attributes for id. 
283
 
     ** Default implementation return DONTENUM that is the standard attribute 
284
 
     ** for core EcmaScript function. Typically descendants need to overwrite
285
 
     ** this for non-function attributes like length to return
286
 
     ** DONTENUM | READONLY | PERMANENT or DONTENUM | PERMANENT
287
 
     */
288
 
    protected int getIdDefaultAttributes(int id) {
289
 
        return DONTENUM;
290
 
    }
291
 
 
292
 
    /** Check if id value exists.
293
 
     ** Default implementation always returns true */
294
 
    protected boolean hasIdValue(int id) {
295
 
        return true;
296
 
    }
297
 
 
298
 
    /** Get id value. 
299
 
     ** If id value is constant, descendant can call cacheIdValue to store
300
 
     ** value in the permanent cache.
301
 
     ** Default implementation creates IdFunction instance for given id
302
 
     ** and cache its value
303
 
     */
304
 
    protected Object getIdValue(int id) {
305
 
        IdFunction f = newIdFunction(id);
306
 
        f.setParentScope(getParentScope());
307
 
        return cacheIdValue(id, f);
308
 
    }
309
 
 
310
 
    /**
311
 
     * Set id value. 
312
 
     * IdScriptable never calls this method if result of
313
 
     * <code>getIdDefaultAttributes(id)</code> contains READONLY attribute.
314
 
     * Descendants can overwrite this method to provide custom handler for
315
 
     * property assignments.
316
 
     */
317
 
    protected void setIdValue(int id, Object value) {
318
 
        synchronized (this) {
319
 
            ensureIdData()[id - 1] = (value != null) ? value : NULL_TAG;
320
 
        }
321
 
    }
322
 
    
323
 
    /**
324
 
     * Store value in permanent cache unless value was already assigned to id.
325
 
     * After this call IdScriptable never calls hasIdValue and getIdValue 
326
 
     * for the given id.
327
 
     */
328
 
    protected Object cacheIdValue(int id, Object value) {
329
 
        synchronized (this) {
330
 
            Object[] data = ensureIdData();
331
 
            Object curValue = data[id - 1];
332
 
            if (curValue == null) {
333
 
                data[id - 1] = (value != null) ? value : NULL_TAG;
334
 
            }
335
 
            else {
336
 
                value = curValue;
337
 
            }
338
 
        }
339
 
        return value;
340
 
    }
341
 
    
342
 
    /**
343
 
     * Delete value represented by id so hasIdValue return false. 
344
 
     * IdScriptable never calls this method if result of
345
 
     * <code>getIdDefaultAttributes(id)</code> contains PERMANENT attribute.
346
 
     * Descendants can overwrite this method to provide custom handler for
347
 
     * property delete.
348
 
     */
349
 
    protected void deleteIdValue(int id) {
350
 
        synchronized (this) {
351
 
            ensureIdData()[id - 1] = NOT_FOUND;
352
 
        }
353
 
    }
354
 
    
355
 
    /** 'thisObj' will be null if invoked as constructor, in which case
356
 
     ** instance of Scriptable should be returned. */
357
 
    public Object execMethod(int methodId, IdFunction function,
358
 
                             Context cx, Scriptable scope,
359
 
                             Scriptable thisObj, Object[] args)
360
 
        throws JavaScriptException
361
 
    {
362
 
        throw IdFunction.onBadMethodId(this, methodId);
363
 
    }
364
 
 
365
 
    /** Get arity or defined argument count for method with given id. 
366
 
     ** Should return -1 if methodId is not known or can not be used
367
 
     ** with execMethod call. */
368
 
    public int methodArity(int methodId) {
369
 
        return -1;
370
 
    }
371
 
    
372
 
    /** Activate id support with the given maximum id */
373
 
    protected void activateIdMap(int maxId) {
374
 
        this.maxId = maxId;
375
 
    }
376
 
    
377
 
    /** Sets whether newly constructed function objects should be sealed */
378
 
    protected void setSealFunctionsFlag(boolean sealed) {
379
 
        setSetupFlag(SEAL_FUNCTIONS_FLAG, sealed);
380
 
    }
381
 
    
382
 
    /** 
383
 
     * Set parameters of function properties. 
384
 
     * Currently only determines whether functions should use dynamic scope.
385
 
     * @param cx context to read function parameters.
386
 
     * 
387
 
     * @see org.mozilla.javascript.Context#hasCompileFunctionsWithDynamicScope
388
 
     */
389
 
    protected void setFunctionParametrs(Context cx) {
390
 
        setSetupFlag(USE_DYNAMIC_SCOPE_FLAG,
391
 
                     cx.hasCompileFunctionsWithDynamicScope());
392
 
    }
393
 
    
394
 
    private void setSetupFlag(int flag, boolean value) {
395
 
        setupFlags = (byte)(value ? setupFlags | flag : setupFlags & ~flag);
396
 
    }
397
 
 
398
 
    /** 
399
 
     * Prepare this object to serve as the prototype property of constructor 
400
 
     * object with name <code>getClassName()<code> defined in
401
 
     * <code>scope</code>.
402
 
     * @param maxId maximum id available in prototype object
403
 
     * @param cx current context
404
 
     * @param scope object to define constructor in.
405
 
     * @param sealed indicates whether object and all its properties should 
406
 
     *        be sealed 
407
 
     */ 
408
 
    public void addAsPrototype(int maxId, Context cx, Scriptable scope, 
409
 
                               boolean sealed) 
410
 
    {
411
 
        activateIdMap(maxId);
412
 
 
413
 
        setSealFunctionsFlag(sealed);
414
 
        setFunctionParametrs(cx);
415
 
        
416
 
        int constructorId = mapNameToId("constructor");
417
 
        if (constructorId == 0) {
418
 
            // It is a bug to call this function without id for constructor 
419
 
            throw new RuntimeException("No id for constructor property");
420
 
        }
421
 
 
422
 
        IdFunction ctor = newIdFunction(constructorId);
423
 
        ctor.initAsConstructor(scope, this);
424
 
        fillConstructorProperties(cx, ctor, sealed);
425
 
        if (sealed) {
426
 
            ctor.sealObject();
427
 
            ctor.addPropertyAttribute(READONLY);
428
 
        }
429
 
 
430
 
        setParentScope(ctor);
431
 
        setPrototype(getObjectPrototype(scope));
432
 
        cacheIdValue(constructorId, ctor);
433
 
 
434
 
        if (sealed) {
435
 
            sealObject();
436
 
        }
437
 
 
438
 
        defineProperty(scope, getClassName(), ctor, ScriptableObject.DONTENUM);
439
 
    }
440
 
 
441
 
    protected void fillConstructorProperties
442
 
        (Context cx, IdFunction ctor, boolean sealed)
443
 
    {
444
 
    }
445
 
 
446
 
    protected void addIdFunctionProperty
447
 
        (Scriptable obj, int id, boolean sealed)
448
 
    {
449
 
        IdFunction f = newIdFunction(id);
450
 
        if (sealed) { f.sealObject(); }
451
 
        defineProperty(obj, getIdName(id), f, DONTENUM);
452
 
    }
453
 
 
454
 
    /** 
455
 
     * Utility method for converting target object into native this.
456
 
     * Possible usage would be to have a private function like realThis:
457
 
     * <pre>
458
 
       private NativeSomething realThis(Scriptable thisObj,
459
 
                                        IdFunction f, boolean readOnly)
460
 
       {
461
 
           while (!(thisObj instanceof NativeSomething)) {
462
 
               thisObj = nextInstanceCheck(thisObj, f, readOnly);
463
 
           }
464
 
           return (NativeSomething)thisObj;
465
 
       }
466
 
    * </pre>
467
 
    * Note that although such function can be implemented universally via
468
 
    * java.lang.Class.isInstance(), it would be much more slower.
469
 
    * @param readOnly specify if the function f does not change state of object.
470
 
    * @return Scriptable object suitable for a check by the instanceof operator.
471
 
    * @throws RuntimeException if no more instanceof target can be found
472
 
    */
473
 
    protected Scriptable nextInstanceCheck(Scriptable thisObj,
474
 
                                           IdFunction f,
475
 
                                           boolean readOnly)
476
 
    {
477
 
        if (readOnly && 0 != (setupFlags & USE_DYNAMIC_SCOPE_FLAG)) {
478
 
            // for read only functions under dynamic scope look prototype chain
479
 
            thisObj = thisObj.getPrototype();
480
 
            if (thisObj != null) { return thisObj; }
481
 
        }
482
 
        throw NativeGlobal.typeError1("msg.incompat.call", 
483
 
                                      f.getFunctionName(), f);
484
 
    }
485
 
 
486
 
    protected IdFunction newIdFunction(int id) {
487
 
        IdFunction f = new IdFunction(this, getIdName(id), id);
488
 
        if (0 != (setupFlags & SEAL_FUNCTIONS_FLAG)) { f.sealObject(); }
489
 
        return f;
490
 
    }
491
 
 
492
 
    protected final Object wrap_double(double x) {
493
 
        return (x == x) ? new Double(x) : ScriptRuntime.NaNobj;
494
 
    }
495
 
 
496
 
    protected final Object wrap_int(int x) {
497
 
        byte b = (byte)x;
498
 
        if (b == x) { return new Byte(b); }
499
 
        return new Integer(x);
500
 
    }
501
 
 
502
 
    protected final Object wrap_long(long x) {
503
 
        int i = (int)x;
504
 
        if (i == x) { return wrap_int(i); }
505
 
        return new Long(x);
506
 
    }
507
 
 
508
 
    protected final Object wrap_boolean(boolean x) {
509
 
        return x ? Boolean.TRUE : Boolean.FALSE;
510
 
    }
511
 
    
512
 
    private boolean hasValue(int id) {
513
 
        Object value;
514
 
        Object[] data = idMapData;
515
 
        if (data == null || (value = data[id - 1]) == null) {
516
 
            return hasIdValue(id);
517
 
        }
518
 
        else {
519
 
            return value != NOT_FOUND;
520
 
        }
521
 
    }
522
 
 
523
 
    // Must be called only from synchronized (this)
524
 
    private Object[] ensureIdData() {
525
 
        Object[] data = idMapData;
526
 
        if (data == null) { 
527
 
            idMapData = data = new Object[CACHE_NAMES ? maxId * 2 : maxId];
528
 
        }
529
 
        return data;
530
 
    }
531
 
    
532
 
    private int getAttributes(int id) {
533
 
        int attributes = getIdDefaultAttributes(id) | extraIdAttributes;
534
 
        byte[] array = attributesArray;
535
 
        if (array != null) {
536
 
            attributes |= 0xFF & array[id - 1];
537
 
        }
538
 
        return attributes;
539
 
    }
540
 
 
541
 
    private void setAttributes(int id, int attributes) {
542
 
        int defaultAttrs = getIdDefaultAttributes(id);
543
 
        if ((attributes & defaultAttrs) != defaultAttrs) {
544
 
            // It is a bug to set attributes to less restrictive values 
545
 
            // then given by defaultAttrs
546
 
            throw new RuntimeException("Attempt to unset default attributes");
547
 
        }
548
 
        // Store only additional bits
549
 
        attributes &= ~defaultAttrs;
550
 
        byte[] array = attributesArray;
551
 
        if (array == null && attributes != 0) {
552
 
            synchronized (this) {
553
 
                array = attributesArray;
554
 
                if (array == null) {
555
 
                    attributesArray = array = new byte[maxId];
556
 
                }
557
 
            }
558
 
        }
559
 
        if (array != null) {
560
 
            array[id - 1] = (byte)attributes;
561
 
        }
562
 
    }
563
 
 
564
 
    private int maxId;
565
 
    private Object[] idMapData;
566
 
    private byte[] attributesArray;
567
 
 
568
 
    private static final boolean CACHE_NAMES = true;
569
 
    private int lastIdCache;
570
 
 
571
 
    private static final int USE_DYNAMIC_SCOPE_FLAG = 1 << 0;
572
 
    private static final int SEAL_FUNCTIONS_FLAG    = 1 << 1;
573
 
    
574
 
    private byte setupFlags;
575
 
    private byte extraIdAttributes;
576
 
}
577