Code

moving trunk for module inkscape
[inkscape.git] / src / extension / script / js / jsatom.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  *
3  * ***** BEGIN LICENSE BLOCK *****
4  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is Mozilla Communicator client code, released
17  * March 31, 1998.
18  *
19  * The Initial Developer of the Original Code is
20  * Netscape Communications Corporation.
21  * Portions created by the Initial Developer are Copyright (C) 1998
22  * the Initial Developer. All Rights Reserved.
23  *
24  * Contributor(s):
25  *
26  * Alternatively, the contents of this file may be used under the terms of
27  * either of the GNU General Public License Version 2 or later (the "GPL"),
28  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29  * in which case the provisions of the GPL or the LGPL are applicable instead
30  * of those above. If you wish to allow use of your version of this file only
31  * under the terms of either the GPL or the LGPL, and not to allow others to
32  * use your version of this file under the terms of the MPL, indicate your
33  * decision by deleting the provisions above and replace them with the notice
34  * and other provisions required by the GPL or the LGPL. If you do not delete
35  * the provisions above, a recipient may use your version of this file under
36  * the terms of any one of the MPL, the GPL or the LGPL.
37  *
38  * ***** END LICENSE BLOCK ***** */
40 /*
41  * JS atom table.
42  */
43 #include "jsstddef.h"
44 #include <stdlib.h>
45 #include <string.h>
46 #include "jstypes.h"
47 #include "jsutil.h" /* Added by JSIFY */
48 #include "jshash.h" /* Added by JSIFY */
49 #include "jsprf.h"
50 #include "jsapi.h"
51 #include "jsatom.h"
52 #include "jscntxt.h"
53 #include "jsgc.h"
54 #include "jslock.h"
55 #include "jsnum.h"
56 #include "jsopcode.h"
57 #include "jsstr.h"
59 JS_FRIEND_API(const char *)
60 js_AtomToPrintableString(JSContext *cx, JSAtom *atom)
61 {
62     JSString *str;
63     const char *bytes;
65     str = js_QuoteString(cx, ATOM_TO_STRING(atom), 0);
66     if (!str)
67         return NULL;
68     bytes = js_GetStringBytes(str);
69     if (!bytes)
70         JS_ReportOutOfMemory(cx);
71     return bytes;
72 }
74 extern const char js_Error_str[];       /* trivial, from jsexn.h */
76 /*
77  * Keep this in sync with jspubtd.h -- an assertion below will insist that
78  * its length match the JSType enum's JSTYPE_LIMIT limit value.
79  */
80 const char *js_type_str[] = {
81     "undefined",
82     "object",
83     "function",
84     "string",
85     "number",
86     "boolean",
87 };
89 const char *js_boolean_str[] = {
90     js_false_str,
91     js_true_str
92 };
94 const char js_Arguments_str[]       = "Arguments";
95 const char js_Array_str[]           = "Array";
96 const char js_Boolean_str[]         = "Boolean";
97 const char js_Call_str[]            = "Call";
98 const char js_Date_str[]            = "Date";
99 const char js_Function_str[]        = "Function";
100 const char js_Math_str[]            = "Math";
101 const char js_Number_str[]          = "Number";
102 const char js_Object_str[]          = "Object";
103 const char js_RegExp_str[]          = "RegExp";
104 const char js_Script_str[]          = "Script";
105 const char js_String_str[]          = "String";
106 const char js_anonymous_str[]       = "anonymous";
107 const char js_arguments_str[]       = "arguments";
108 const char js_arity_str[]           = "arity";
109 const char js_callee_str[]          = "callee";
110 const char js_caller_str[]          = "caller";
111 const char js_class_prototype_str[] = "prototype";
112 const char js_constructor_str[]     = "constructor";
113 const char js_count_str[]           = "__count__";
114 const char js_eval_str[]            = "eval";
115 const char js_getter_str[]          = "getter";
116 const char js_get_str[]             = "get";
117 const char js_index_str[]           = "index";
118 const char js_input_str[]           = "input";
119 const char js_length_str[]          = "length";
120 const char js_name_str[]            = "name";
121 const char js_noSuchMethod_str[]    = "__noSuchMethod__";
122 const char js_parent_str[]          = "__parent__";
123 const char js_proto_str[]           = "__proto__";
124 const char js_setter_str[]          = "setter";
125 const char js_set_str[]             = "set";
126 const char js_toSource_str[]        = "toSource";
127 const char js_toString_str[]        = "toString";
128 const char js_toLocaleString_str[]  = "toLocaleString";
129 const char js_valueOf_str[]         = "valueOf";
131 #define HASH_OBJECT(o)  ((JSHashNumber)(o) >> JSVAL_TAGBITS)
132 #define HASH_INT(i)     ((JSHashNumber)(i))
133 #define HASH_DOUBLE(dp) ((JSHashNumber)(((uint32*)(dp))[0] ^ ((uint32*)(dp))[1]))
134 #define HASH_BOOLEAN(b) ((JSHashNumber)(b))
136 JS_STATIC_DLL_CALLBACK(JSHashNumber)
137 js_hash_atom_key(const void *key)
139     jsval v;
140     jsdouble *dp;
142     /* Order JSVAL_IS_* tests by likelihood of success. */
143     v = (jsval)key;
144     if (JSVAL_IS_STRING(v))
145         return js_HashString(JSVAL_TO_STRING(v));
146     if (JSVAL_IS_INT(v))
147         return HASH_INT(JSVAL_TO_INT(v));
148     if (JSVAL_IS_DOUBLE(v)) {
149         dp = JSVAL_TO_DOUBLE(v);
150         return HASH_DOUBLE(dp);
151     }
152     if (JSVAL_IS_OBJECT(v))
153         return HASH_OBJECT(JSVAL_TO_OBJECT(v));
154     if (JSVAL_IS_BOOLEAN(v))
155         return HASH_BOOLEAN(JSVAL_TO_BOOLEAN(v));
156     return (JSHashNumber)v;
159 JS_STATIC_DLL_CALLBACK(intN)
160 js_compare_atom_keys(const void *k1, const void *k2)
162     jsval v1, v2;
164     v1 = (jsval)k1, v2 = (jsval)k2;
165     if (JSVAL_IS_STRING(v1) && JSVAL_IS_STRING(v2))
166         return !js_CompareStrings(JSVAL_TO_STRING(v1), JSVAL_TO_STRING(v2));
167     if (JSVAL_IS_DOUBLE(v1) && JSVAL_IS_DOUBLE(v2)) {
168         double d1 = *JSVAL_TO_DOUBLE(v1);
169         double d2 = *JSVAL_TO_DOUBLE(v2);
170         if (JSDOUBLE_IS_NaN(d1))
171             return JSDOUBLE_IS_NaN(d2);
172 #if defined(XP_WIN)
173         /* XXX MSVC miscompiles such that (NaN == 0) */
174         if (JSDOUBLE_IS_NaN(d2))
175             return JS_FALSE;
176 #endif
177         return d1 == d2;
178     }
179     return v1 == v2;
182 JS_STATIC_DLL_CALLBACK(int)
183 js_compare_stub(const void *v1, const void *v2)
185     return 1;
188 /* These next two are exported to jsscript.c and used similarly there. */
189 void * JS_DLL_CALLBACK
190 js_alloc_table_space(void *priv, size_t size)
192     return malloc(size);
195 void JS_DLL_CALLBACK
196 js_free_table_space(void *priv, void *item)
198     free(item);
201 JS_STATIC_DLL_CALLBACK(JSHashEntry *)
202 js_alloc_atom(void *priv, const void *key)
204     JSAtomState *state = (JSAtomState *) priv;
205     JSAtom *atom;
207     atom = (JSAtom *) malloc(sizeof(JSAtom));
208     if (!atom)
209         return NULL;
210 #ifdef JS_THREADSAFE
211     state->tablegen++;
212 #endif
213     atom->entry.key = key;
214     atom->entry.value = NULL;
215     atom->flags = 0;
216     atom->number = state->number++;
217     return &atom->entry;
220 JS_STATIC_DLL_CALLBACK(void)
221 js_free_atom(void *priv, JSHashEntry *he, uintN flag)
223     if (flag != HT_FREE_ENTRY)
224         return;
225 #ifdef JS_THREADSAFE
226     ((JSAtomState *)priv)->tablegen++;
227 #endif
228     free(he);
231 static JSHashAllocOps atom_alloc_ops = {
232     js_alloc_table_space,   js_free_table_space,
233     js_alloc_atom,          js_free_atom
234 };
236 #define JS_ATOM_HASH_SIZE   1024
238 JSBool
239 js_InitAtomState(JSContext *cx, JSAtomState *state)
241     state->table = JS_NewHashTable(JS_ATOM_HASH_SIZE, js_hash_atom_key,
242                                    js_compare_atom_keys, js_compare_stub,
243                                    &atom_alloc_ops, state);
244     if (!state->table) {
245         JS_ReportOutOfMemory(cx);
246         return JS_FALSE;
247     }
249     state->runtime = cx->runtime;
250 #ifdef JS_THREADSAFE
251     js_InitLock(&state->lock);
252     state->tablegen = 0;
253 #endif
255     if (!js_InitPinnedAtoms(cx, state)) {
256         js_FreeAtomState(cx, state);
257         return JS_FALSE;
258     }
259     return JS_TRUE;
262 JSBool
263 js_InitPinnedAtoms(JSContext *cx, JSAtomState *state)
265     uintN i;
267 #define FROB(lval,str)                                                        \
268     JS_BEGIN_MACRO                                                            \
269         if (!(state->lval = js_Atomize(cx, str, strlen(str), ATOM_PINNED)))   \
270             return JS_FALSE;                                                  \
271     JS_END_MACRO
273     JS_ASSERT(sizeof js_type_str / sizeof js_type_str[0] == JSTYPE_LIMIT);
274     for (i = 0; i < JSTYPE_LIMIT; i++)
275         FROB(typeAtoms[i],        js_type_str[i]);
277     FROB(booleanAtoms[0],         js_false_str);
278     FROB(booleanAtoms[1],         js_true_str);
279     FROB(nullAtom,                js_null_str);
281     FROB(ArgumentsAtom,           js_Arguments_str);
282     FROB(ArrayAtom,               js_Array_str);
283     FROB(BooleanAtom,             js_Boolean_str);
284     FROB(CallAtom,                js_Call_str);
285     FROB(DateAtom,                js_Date_str);
286     FROB(ErrorAtom,               js_Error_str);
287     FROB(FunctionAtom,            js_Function_str);
288     FROB(MathAtom,                js_Math_str);
289     FROB(NumberAtom,              js_Number_str);
290     FROB(ObjectAtom,              js_Object_str);
291     FROB(RegExpAtom,              js_RegExp_str);
292     FROB(ScriptAtom,              js_Script_str);
293     FROB(StringAtom,              js_String_str);
294     FROB(anonymousAtom,           js_anonymous_str);
295     FROB(argumentsAtom,           js_arguments_str);
296     FROB(arityAtom,               js_arity_str);
297     FROB(calleeAtom,              js_callee_str);
298     FROB(callerAtom,              js_caller_str);
299     FROB(classPrototypeAtom,      js_class_prototype_str);
300     FROB(constructorAtom,         js_constructor_str);
301     FROB(countAtom,               js_count_str);
302     FROB(evalAtom,                js_eval_str);
303     FROB(getAtom,                 js_get_str);
304     FROB(getterAtom,              js_getter_str);
305     FROB(indexAtom,               js_index_str);
306     FROB(inputAtom,               js_input_str);
307     FROB(lengthAtom,              js_length_str);
308     FROB(nameAtom,                js_name_str);
309     FROB(noSuchMethodAtom,        js_noSuchMethod_str);
310     FROB(parentAtom,              js_parent_str);
311     FROB(protoAtom,               js_proto_str);
312     FROB(setAtom,                 js_set_str);
313     FROB(setterAtom,              js_setter_str);
314     FROB(toSourceAtom,            js_toSource_str);
315     FROB(toStringAtom,            js_toString_str);
316     FROB(toLocaleStringAtom,      js_toLocaleString_str);
317     FROB(valueOfAtom,             js_valueOf_str);
319 #undef FROB
321     memset(&state->lazy, 0, sizeof state->lazy);
322     return JS_TRUE;
325 /* NB: cx unused; js_FinishAtomState calls us with null cx. */
326 void
327 js_FreeAtomState(JSContext *cx, JSAtomState *state)
329     if (state->table)
330         JS_HashTableDestroy(state->table);
331 #ifdef JS_THREADSAFE
332     js_FinishLock(&state->lock);
333 #endif
334     memset(state, 0, sizeof *state);
337 typedef struct UninternArgs {
338     JSRuntime   *rt;
339     jsatomid    leaks;
340 } UninternArgs;
342 JS_STATIC_DLL_CALLBACK(intN)
343 js_atom_uninterner(JSHashEntry *he, intN i, void *arg)
345     JSAtom *atom;
346     UninternArgs *args;
348     atom = (JSAtom *)he;
349     args = (UninternArgs *)arg;
350     if (ATOM_IS_STRING(atom))
351         js_FinalizeStringRT(args->rt, ATOM_TO_STRING(atom));
352     else if (ATOM_IS_OBJECT(atom))
353         args->leaks++;
354     return HT_ENUMERATE_NEXT;
357 void
358 js_FinishAtomState(JSAtomState *state)
360     UninternArgs args;
362     if (!state->table)
363         return;
364     args.rt = state->runtime;
365     args.leaks = 0;
366     JS_HashTableEnumerateEntries(state->table, js_atom_uninterner, &args);
367 #ifdef DEBUG
368     if (args.leaks != 0) {
369         fprintf(stderr,
370 "JS engine warning: %lu atoms remain after destroying the JSRuntime.\n"
371 "                   These atoms may point to freed memory. Things reachable\n"
372 "                   through them have not been finalized.\n",
373                 (unsigned long) args.leaks);
374     }
375 #endif
376     js_FreeAtomState(NULL, state);
379 typedef struct MarkArgs {
380     uintN           gcflags;
381     JSGCThingMarker mark;
382     void            *data;
383 } MarkArgs;
385 JS_STATIC_DLL_CALLBACK(intN)
386 js_atom_marker(JSHashEntry *he, intN i, void *arg)
388     JSAtom *atom;
389     MarkArgs *args;
390     jsval key;
392     atom = (JSAtom *)he;
393     args = (MarkArgs *)arg;
394     if ((atom->flags & (ATOM_PINNED | ATOM_INTERNED)) ||
395         (args->gcflags & GC_KEEP_ATOMS)) {
396         atom->flags |= ATOM_MARK;
397         key = ATOM_KEY(atom);
398         if (JSVAL_IS_GCTHING(key))
399             args->mark(JSVAL_TO_GCTHING(key), args->data);
400     }
401     return HT_ENUMERATE_NEXT;
404 void
405 js_MarkAtomState(JSAtomState *state, uintN gcflags, JSGCThingMarker mark,
406                  void *data)
408     MarkArgs args;
410     if (!state->table)
411         return;
412     args.gcflags = gcflags;
413     args.mark = mark;
414     args.data = data;
415     JS_HashTableEnumerateEntries(state->table, js_atom_marker, &args);
418 JS_STATIC_DLL_CALLBACK(intN)
419 js_atom_sweeper(JSHashEntry *he, intN i, void *arg)
421     JSAtom *atom;
422     JSAtomState *state;
424     atom = (JSAtom *)he;
425     if (atom->flags & ATOM_MARK) {
426         atom->flags &= ~ATOM_MARK;
427         state = (JSAtomState *)arg;
428         state->liveAtoms++;
429         return HT_ENUMERATE_NEXT;
430     }
431     JS_ASSERT((atom->flags & (ATOM_PINNED | ATOM_INTERNED)) == 0);
432     atom->entry.key = NULL;
433     atom->flags = 0;
434     return HT_ENUMERATE_REMOVE;
437 void
438 js_SweepAtomState(JSAtomState *state)
440     state->liveAtoms = 0;
441     if (state->table)
442         JS_HashTableEnumerateEntries(state->table, js_atom_sweeper, state);
445 JS_STATIC_DLL_CALLBACK(intN)
446 js_atom_unpinner(JSHashEntry *he, intN i, void *arg)
448     JSAtom *atom;
450     atom = (JSAtom *)he;
451     atom->flags &= ~ATOM_PINNED;
452     return HT_ENUMERATE_NEXT;
455 void
456 js_UnpinPinnedAtoms(JSAtomState *state)
458     if (state->table)
459         JS_HashTableEnumerateEntries(state->table, js_atom_unpinner, NULL);
462 static JSAtom *
463 js_AtomizeHashedKey(JSContext *cx, jsval key, JSHashNumber keyHash, uintN flags)
465     JSAtomState *state;
466     JSHashTable *table;
467     JSHashEntry *he, **hep;
468     JSAtom *atom;
470     state = &cx->runtime->atomState;
471     JS_LOCK(&state->lock, cx);
472     table = state->table;
473     hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
474     if ((he = *hep) == NULL) {
475         he = JS_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
476         if (!he) {
477             JS_ReportOutOfMemory(cx);
478             atom = NULL;
479             goto out;
480         }
481     }
483     atom = (JSAtom *)he;
484     atom->flags |= flags;
485     cx->lastAtom = atom;
486 out:
487     JS_UNLOCK(&state->lock,cx);
488     return atom;
491 JSAtom *
492 js_AtomizeObject(JSContext *cx, JSObject *obj, uintN flags)
494     jsval key;
495     JSHashNumber keyHash;
497     /* XXX must be set in the following order or MSVC1.52 will crash */
498     keyHash = HASH_OBJECT(obj);
499     key = OBJECT_TO_JSVAL(obj);
500     return js_AtomizeHashedKey(cx, key, keyHash, flags);
503 JSAtom *
504 js_AtomizeBoolean(JSContext *cx, JSBool b, uintN flags)
506     jsval key;
507     JSHashNumber keyHash;
509     key = BOOLEAN_TO_JSVAL(b);
510     keyHash = HASH_BOOLEAN(b);
511     return js_AtomizeHashedKey(cx, key, keyHash, flags);
514 JSAtom *
515 js_AtomizeInt(JSContext *cx, jsint i, uintN flags)
517     jsval key;
518     JSHashNumber keyHash;
520     key = INT_TO_JSVAL(i);
521     keyHash = HASH_INT(i);
522     return js_AtomizeHashedKey(cx, key, keyHash, flags);
525 /* Worst-case alignment grain and aligning macro for 2x-sized buffer. */
526 #define ALIGNMENT(t)    JS_MAX(JSVAL_ALIGN, sizeof(t))
527 #define ALIGN(b,t)      ((t*) &(b)[ALIGNMENT(t) - (jsuword)(b) % ALIGNMENT(t)])
529 JSAtom *
530 js_AtomizeDouble(JSContext *cx, jsdouble d, uintN flags)
532     jsdouble *dp;
533     JSHashNumber keyHash;
534     jsval key;
535     JSAtomState *state;
536     JSHashTable *table;
537     JSHashEntry *he, **hep;
538     JSAtom *atom;
539     char buf[2 * ALIGNMENT(double)];
541     dp = ALIGN(buf, double);
542     *dp = d;
543     keyHash = HASH_DOUBLE(dp);
544     key = DOUBLE_TO_JSVAL(dp);
545     state = &cx->runtime->atomState;
546     JS_LOCK(&state->lock, cx);
547     table = state->table;
548     hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
549     if ((he = *hep) == NULL) {
550 #ifdef JS_THREADSAFE
551         uint32 gen = state->tablegen;
552 #endif
553         JS_UNLOCK(&state->lock,cx);
554         if (!js_NewDoubleValue(cx, d, &key))
555             return NULL;
556         JS_LOCK(&state->lock, cx);
557 #ifdef JS_THREADSAFE
558         if (state->tablegen != gen) {
559             hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
560             if ((he = *hep) != NULL) {
561                 atom = (JSAtom *)he;
562                 goto out;
563             }
564         }
565 #endif
566         he = JS_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
567         if (!he) {
568             JS_ReportOutOfMemory(cx);
569             atom = NULL;
570             goto out;
571         }
572     }
574     atom = (JSAtom *)he;
575     atom->flags |= flags;
576     cx->lastAtom = atom;
577 out:
578     JS_UNLOCK(&state->lock,cx);
579     return atom;
582 JSAtom *
583 js_AtomizeString(JSContext *cx, JSString *str, uintN flags)
585     JSHashNumber keyHash;
586     jsval key;
587     JSAtomState *state;
588     JSHashTable *table;
589     JSHashEntry *he, **hep;
590     JSAtom *atom;
592     keyHash = js_HashString(str);
593     key = STRING_TO_JSVAL(str);
594     state = &cx->runtime->atomState;
595     JS_LOCK(&state->lock, cx);
596     table = state->table;
597     hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
598     if ((he = *hep) == NULL) {
599 #ifdef JS_THREADSAFE
600         uint32 gen = state->tablegen;
601         JS_UNLOCK(&state->lock, cx);
602 #endif
604         if (flags & ATOM_TMPSTR) {
605             str = (flags & ATOM_NOCOPY)
606                   ? js_NewString(cx, str->chars, str->length, 0)
607                   : js_NewStringCopyN(cx, str->chars, str->length, 0);
608             if (!str)
609                 return NULL;
610             key = STRING_TO_JSVAL(str);
611         } else {
612             if (!JS_MakeStringImmutable(cx, str))
613                 return NULL;
614         }
616 #ifdef JS_THREADSAFE
617         JS_LOCK(&state->lock, cx);
618         if (state->tablegen != gen) {
619             hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
620             if ((he = *hep) != NULL) {
621                 atom = (JSAtom *)he;
622                 if (flags & ATOM_NOCOPY)
623                     str->chars = NULL;
624                 goto out;
625             }
626         }
627 #endif
629         he = JS_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
630         if (!he) {
631             JS_ReportOutOfMemory(cx);
632             atom = NULL;
633             goto out;
634         }
635     }
637     atom = (JSAtom *)he;
638     atom->flags |= flags & (ATOM_PINNED | ATOM_INTERNED);
639     cx->lastAtom = atom;
640 out:
641     JS_UNLOCK(&state->lock,cx);
642     return atom;
645 JS_FRIEND_API(JSAtom *)
646 js_Atomize(JSContext *cx, const char *bytes, size_t length, uintN flags)
648     jschar *chars;
649     JSString *str;
650     JSAtom *atom;
651     char buf[2 * ALIGNMENT(JSString)];
653     /*
654      * Avoiding the malloc in js_InflateString on shorter strings saves us
655      * over 20,000 malloc calls on mozilla browser startup. This compares to
656      * only 131 calls where the string is longer than a 31 char (net) buffer.
657      * The vast majority of atomized strings are already in the hashtable. So
658      * js_AtomizeString rarely has to copy the temp string we make.
659      */
660 #define ATOMIZE_BUF_MAX 32
661     jschar inflated[ATOMIZE_BUF_MAX];
663     if (length < ATOMIZE_BUF_MAX) {
664         js_InflateStringToBuffer(inflated, bytes, length);
665         chars = inflated;
666     } else {
667         chars = js_InflateString(cx, bytes, length);
668         if (!chars)
669             return NULL;
670         flags |= ATOM_NOCOPY;
671     }
673     str = ALIGN(buf, JSString);
675     str->chars = chars;
676     str->length = length;
677     atom = js_AtomizeString(cx, str, ATOM_TMPSTR | flags);
678     if (chars != inflated && (!atom || ATOM_TO_STRING(atom)->chars != chars))
679         JS_free(cx, chars);
680     return atom;
683 JS_FRIEND_API(JSAtom *)
684 js_AtomizeChars(JSContext *cx, const jschar *chars, size_t length, uintN flags)
686     JSString *str;
687     char buf[2 * ALIGNMENT(JSString)];
689     str = ALIGN(buf, JSString);
690     str->chars = (jschar *)chars;
691     str->length = length;
692     return js_AtomizeString(cx, str, ATOM_TMPSTR | flags);
695 JSAtom *
696 js_AtomizeValue(JSContext *cx, jsval value, uintN flags)
698     if (JSVAL_IS_STRING(value))
699         return js_AtomizeString(cx, JSVAL_TO_STRING(value), flags);
700     if (JSVAL_IS_INT(value))
701         return js_AtomizeInt(cx, JSVAL_TO_INT(value), flags);
702     if (JSVAL_IS_DOUBLE(value))
703         return js_AtomizeDouble(cx, *JSVAL_TO_DOUBLE(value), flags);
704     if (JSVAL_IS_OBJECT(value))
705         return js_AtomizeObject(cx, JSVAL_TO_OBJECT(value), flags);
706     if (JSVAL_IS_BOOLEAN(value))
707         return js_AtomizeBoolean(cx, JSVAL_TO_BOOLEAN(value), flags);
708     return js_AtomizeHashedKey(cx, value, (JSHashNumber)value, flags);
711 JSAtom *
712 js_ValueToStringAtom(JSContext *cx, jsval v)
714     JSString *str;
716     str = js_ValueToString(cx, v);
717     if (!str)
718         return NULL;
719     return js_AtomizeString(cx, str, 0);
722 JS_STATIC_DLL_CALLBACK(JSHashNumber)
723 js_hash_atom_ptr(const void *key)
725     const JSAtom *atom = key;
726     return atom->number;
729 JS_STATIC_DLL_CALLBACK(void *)
730 js_alloc_temp_space(void *priv, size_t size)
732     JSContext *cx = priv;
733     void *space;
735     JS_ARENA_ALLOCATE(space, &cx->tempPool, size);
736     if (!space)
737         JS_ReportOutOfMemory(cx);
738     return space;
741 JS_STATIC_DLL_CALLBACK(void)
742 js_free_temp_space(void *priv, void *item)
746 JS_STATIC_DLL_CALLBACK(JSHashEntry *)
747 js_alloc_temp_entry(void *priv, const void *key)
749     JSContext *cx = priv;
750     JSAtomListElement *ale;
752     JS_ARENA_ALLOCATE_TYPE(ale, JSAtomListElement, &cx->tempPool);
753     if (!ale) {
754         JS_ReportOutOfMemory(cx);
755         return NULL;
756     }
757     return &ale->entry;
760 JS_STATIC_DLL_CALLBACK(void)
761 js_free_temp_entry(void *priv, JSHashEntry *he, uintN flag)
765 static JSHashAllocOps temp_alloc_ops = {
766     js_alloc_temp_space,    js_free_temp_space,
767     js_alloc_temp_entry,    js_free_temp_entry
768 };
770 JSAtomListElement *
771 js_IndexAtom(JSContext *cx, JSAtom *atom, JSAtomList *al)
773     JSAtomListElement *ale, *ale2, *next;
774     JSHashEntry **hep;
776     ATOM_LIST_LOOKUP(ale, hep, al, atom);
777     if (!ale) {
778         if (al->count <= 5) {
779             /* Few enough for linear search, no hash table needed. */
780             JS_ASSERT(!al->table);
781             ale = (JSAtomListElement *)js_alloc_temp_entry(cx, atom);
782             if (!ale)
783                 return NULL;
784             ALE_SET_ATOM(ale, atom);
785             ALE_SET_NEXT(ale, al->list);
786             al->list = ale;
787         } else {
788             /* We want to hash.  Have we already made a hash table? */
789             if (!al->table) {
790                 /* No hash table yet, so hep had better be null! */
791                 JS_ASSERT(!hep);
792                 al->table = JS_NewHashTable(8, js_hash_atom_ptr,
793                                             JS_CompareValues, JS_CompareValues,
794                                             &temp_alloc_ops, cx);
795                 if (!al->table)
796                     return NULL;
798                 /* Insert each ale on al->list into the new hash table. */
799                 for (ale2 = al->list; ale2; ale2 = next) {
800                     next = ALE_NEXT(ale2);
801                     ale2->entry.keyHash = ALE_ATOM(ale2)->number;
802                     hep = JS_HashTableRawLookup(al->table, ale2->entry.keyHash,
803                                                 ale2->entry.key);
804                     ALE_SET_NEXT(ale2, *hep);
805                     *hep = &ale2->entry;
806                 }
807                 al->list = NULL;
809                 /* Set hep for insertion of atom's ale, immediately below. */
810                 hep = JS_HashTableRawLookup(al->table, atom->number, atom);
811             }
813             /* Finally, add an entry for atom into the hash bucket at hep. */
814             ale = (JSAtomListElement *)
815                   JS_HashTableRawAdd(al->table, hep, atom->number, atom, NULL);
816             if (!ale)
817                 return NULL;
818         }
820         ALE_SET_INDEX(ale, al->count++);
821     }
822     return ale;
825 JS_FRIEND_API(JSAtom *)
826 js_GetAtom(JSContext *cx, JSAtomMap *map, jsatomid i)
828     JSAtom *atom;
829     static JSAtom dummy;
831     JS_ASSERT(map->vector && i < map->length);
832     if (!map->vector || i >= map->length) {
833         char numBuf[12];
834         JS_snprintf(numBuf, sizeof numBuf, "%lu", (unsigned long)i);
835         JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
836                              JSMSG_BAD_ATOMIC_NUMBER, numBuf);
837         return &dummy;
838     }
839     atom = map->vector[i];
840     JS_ASSERT(atom);
841     return atom;
844 JS_STATIC_DLL_CALLBACK(intN)
845 js_map_atom(JSHashEntry *he, intN i, void *arg)
847     JSAtomListElement *ale = (JSAtomListElement *)he;
848     JSAtom **vector = arg;
850     vector[ALE_INDEX(ale)] = ALE_ATOM(ale);
851     return HT_ENUMERATE_NEXT;
854 #ifdef DEBUG
855 jsrefcount js_atom_map_count;
856 jsrefcount js_atom_map_hash_table_count;
857 #endif
859 JS_FRIEND_API(JSBool)
860 js_InitAtomMap(JSContext *cx, JSAtomMap *map, JSAtomList *al)
862     JSAtom **vector;
863     JSAtomListElement *ale;
864     uint32 count;
866 #ifdef DEBUG
867     JS_ATOMIC_INCREMENT(&js_atom_map_count);
868 #endif
869     ale = al->list;
870     if (!ale && !al->table) {
871         map->vector = NULL;
872         map->length = 0;
873         return JS_TRUE;
874     }
876     count = al->count;
877     if (count >= ATOM_INDEX_LIMIT) {
878         JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
879                              JSMSG_TOO_MANY_LITERALS);
880         return JS_FALSE;
881     }
882     vector = (JSAtom **) JS_malloc(cx, (size_t) count * sizeof *vector);
883     if (!vector)
884         return JS_FALSE;
886     if (al->table) {
887 #ifdef DEBUG
888         JS_ATOMIC_INCREMENT(&js_atom_map_hash_table_count);
889 #endif
890         JS_HashTableEnumerateEntries(al->table, js_map_atom, vector);
891     } else {
892         do {
893             vector[ALE_INDEX(ale)] = ALE_ATOM(ale);
894         } while ((ale = ALE_NEXT(ale)) != NULL);
895     }
896     ATOM_LIST_INIT(al);
898     map->vector = vector;
899     map->length = (jsatomid)count;
900     return JS_TRUE;
903 JS_FRIEND_API(void)
904 js_FreeAtomMap(JSContext *cx, JSAtomMap *map)
906     if (map->vector) {
907         JS_free(cx, map->vector);
908         map->vector = NULL;
909     }
910     map->length = 0;