Imported Upstream version 1.0.0
[platform/upstream/js.git] / js / src / jsapi.h
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  * vim: set ts=8 sw=4 et tw=78:
3  *
4  * ***** BEGIN LICENSE BLOCK *****
5  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6  *
7  * The contents of this file are subject to the Mozilla Public License Version
8  * 1.1 (the "License"); you may not use this file except in compliance with
9  * the License. You may obtain a copy of the License at
10  * http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14  * for the specific language governing rights and limitations under the
15  * License.
16  *
17  * The Original Code is Mozilla Communicator client code, released
18  * March 31, 1998.
19  *
20  * The Initial Developer of the Original Code is
21  * Netscape Communications Corporation.
22  * Portions created by the Initial Developer are Copyright (C) 1998
23  * the Initial Developer. All Rights Reserved.
24  *
25  * Contributor(s):
26  *
27  * Alternatively, the contents of this file may be used under the terms of
28  * either of the GNU General Public License Version 2 or later (the "GPL"),
29  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30  * in which case the provisions of the GPL or the LGPL are applicable instead
31  * of those above. If you wish to allow use of your version of this file only
32  * under the terms of either the GPL or the LGPL, and not to allow others to
33  * use your version of this file under the terms of the MPL, indicate your
34  * decision by deleting the provisions above and replace them with the notice
35  * and other provisions required by the GPL or the LGPL. If you do not delete
36  * the provisions above, a recipient may use your version of this file under
37  * the terms of any one of the MPL, the GPL or the LGPL.
38  *
39  * ***** END LICENSE BLOCK ***** */
40
41 #ifndef jsapi_h___
42 #define jsapi_h___
43 /*
44  * JavaScript API.
45  */
46 #include <stddef.h>
47 #include <stdio.h>
48 #include "js-config.h"
49 #include "jspubtd.h"
50 #include "jsutil.h"
51
52 JS_BEGIN_EXTERN_C
53
54 /*
55  * In release builds, jsval and jsid are defined to be integral types. This
56  * prevents many bugs from being caught at compile time. E.g.:
57  *
58  *  jsval v = ...
59  *  if (v == JS_TRUE)  // error
60  *    ...
61  *
62  *  jsid id = v;       // error
63  *
64  * To catch more errors, jsval and jsid are given struct types in debug builds.
65  * Struct assignment and (in C++) operator== allow correct code to be mostly
66  * oblivious to the change. This feature can be explicitly disabled in debug
67  * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES.
68  */
69 #ifdef JS_USE_JSVAL_JSID_STRUCT_TYPES
70
71 /* Well-known JS values. N.B. These constants are initialized at startup. */
72 extern JS_PUBLIC_DATA(jsval) JSVAL_NULL;
73 extern JS_PUBLIC_DATA(jsval) JSVAL_ZERO;
74 extern JS_PUBLIC_DATA(jsval) JSVAL_ONE;
75 extern JS_PUBLIC_DATA(jsval) JSVAL_FALSE;
76 extern JS_PUBLIC_DATA(jsval) JSVAL_TRUE;
77 extern JS_PUBLIC_DATA(jsval) JSVAL_VOID;
78
79 #else
80
81 /* Well-known JS values. */
82 #define JSVAL_NULL   BUILD_JSVAL(JSVAL_TAG_NULL,      0)
83 #define JSVAL_ZERO   BUILD_JSVAL(JSVAL_TAG_INT32,     0)
84 #define JSVAL_ONE    BUILD_JSVAL(JSVAL_TAG_INT32,     1)
85 #define JSVAL_FALSE  BUILD_JSVAL(JSVAL_TAG_BOOLEAN,   JS_FALSE)
86 #define JSVAL_TRUE   BUILD_JSVAL(JSVAL_TAG_BOOLEAN,   JS_TRUE)
87 #define JSVAL_VOID   BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0)
88
89 #endif
90
91 /************************************************************************/
92
93 static JS_ALWAYS_INLINE JSBool
94 JSVAL_IS_NULL(jsval v)
95 {
96     jsval_layout l;
97     l.asBits = JSVAL_BITS(v);
98     return JSVAL_IS_NULL_IMPL(l);
99 }
100
101 static JS_ALWAYS_INLINE JSBool
102 JSVAL_IS_VOID(jsval v)
103 {
104     jsval_layout l;
105     l.asBits = JSVAL_BITS(v);
106     return JSVAL_IS_UNDEFINED_IMPL(l);
107 }
108
109 static JS_ALWAYS_INLINE JSBool
110 JSVAL_IS_INT(jsval v)
111 {
112     jsval_layout l;
113     l.asBits = JSVAL_BITS(v);
114     return JSVAL_IS_INT32_IMPL(l);
115 }
116
117 static JS_ALWAYS_INLINE jsint
118 JSVAL_TO_INT(jsval v)
119 {
120     jsval_layout l;
121     JS_ASSERT(JSVAL_IS_INT(v));
122     l.asBits = JSVAL_BITS(v);
123     return JSVAL_TO_INT32_IMPL(l);
124 }
125
126 #define JSVAL_INT_BITS          32
127 #define JSVAL_INT_MIN           ((jsint)0x80000000)
128 #define JSVAL_INT_MAX           ((jsint)0x7fffffff)
129
130 static JS_ALWAYS_INLINE jsval
131 INT_TO_JSVAL(int32 i)
132 {
133     return IMPL_TO_JSVAL(INT32_TO_JSVAL_IMPL(i));
134 }
135
136 static JS_ALWAYS_INLINE JSBool
137 JSVAL_IS_DOUBLE(jsval v)
138 {
139     jsval_layout l;
140     l.asBits = JSVAL_BITS(v);
141     return JSVAL_IS_DOUBLE_IMPL(l);
142 }
143
144 static JS_ALWAYS_INLINE jsdouble
145 JSVAL_TO_DOUBLE(jsval v)
146 {
147     jsval_layout l;
148     JS_ASSERT(JSVAL_IS_DOUBLE(v));
149     l.asBits = JSVAL_BITS(v);
150     return l.asDouble;
151 }
152
153 static JS_ALWAYS_INLINE jsval
154 DOUBLE_TO_JSVAL(jsdouble d)
155 {
156     d = JS_CANONICALIZE_NAN(d);
157     return IMPL_TO_JSVAL(DOUBLE_TO_JSVAL_IMPL(d));
158 }
159
160 static JS_ALWAYS_INLINE jsval
161 UINT_TO_JSVAL(uint32 i)
162 {
163     if (i <= JSVAL_INT_MAX)
164         return INT_TO_JSVAL((int32)i);
165     return DOUBLE_TO_JSVAL((jsdouble)i);
166 }
167
168 static JS_ALWAYS_INLINE JSBool
169 JSVAL_IS_NUMBER(jsval v)
170 {
171     jsval_layout l;
172     l.asBits = JSVAL_BITS(v);
173     return JSVAL_IS_NUMBER_IMPL(l);
174 }
175
176 static JS_ALWAYS_INLINE JSBool
177 JSVAL_IS_STRING(jsval v)
178 {
179     jsval_layout l;
180     l.asBits = JSVAL_BITS(v);
181     return JSVAL_IS_STRING_IMPL(l);
182 }
183
184 static JS_ALWAYS_INLINE JSString *
185 JSVAL_TO_STRING(jsval v)
186 {
187     jsval_layout l;
188     JS_ASSERT(JSVAL_IS_STRING(v));
189     l.asBits = JSVAL_BITS(v);
190     return JSVAL_TO_STRING_IMPL(l);
191 }
192
193 static JS_ALWAYS_INLINE jsval
194 STRING_TO_JSVAL(JSString *str)
195 {
196     return IMPL_TO_JSVAL(STRING_TO_JSVAL_IMPL(str));
197 }
198
199 static JS_ALWAYS_INLINE JSBool
200 JSVAL_IS_OBJECT(jsval v)
201 {
202     jsval_layout l;
203     l.asBits = JSVAL_BITS(v);
204     return JSVAL_IS_OBJECT_OR_NULL_IMPL(l);
205 }
206
207 static JS_ALWAYS_INLINE JSObject *
208 JSVAL_TO_OBJECT(jsval v)
209 {
210     jsval_layout l;
211     JS_ASSERT(JSVAL_IS_OBJECT(v));
212     l.asBits = JSVAL_BITS(v);
213     return JSVAL_TO_OBJECT_IMPL(l);
214 }
215
216 static JS_ALWAYS_INLINE jsval
217 OBJECT_TO_JSVAL(JSObject *obj)
218 {
219     if (obj)
220         return IMPL_TO_JSVAL(OBJECT_TO_JSVAL_IMPL(obj));
221     return JSVAL_NULL;
222 }
223
224 static JS_ALWAYS_INLINE JSBool
225 JSVAL_IS_BOOLEAN(jsval v)
226 {
227     jsval_layout l;
228     l.asBits = JSVAL_BITS(v);
229     return JSVAL_IS_BOOLEAN_IMPL(l);
230 }
231
232 static JS_ALWAYS_INLINE JSBool
233 JSVAL_TO_BOOLEAN(jsval v)
234 {
235     jsval_layout l;
236     JS_ASSERT(JSVAL_IS_BOOLEAN(v));
237     l.asBits = JSVAL_BITS(v);
238     return JSVAL_TO_BOOLEAN_IMPL(l);
239 }
240
241 static JS_ALWAYS_INLINE jsval
242 BOOLEAN_TO_JSVAL(JSBool b)
243 {
244     return IMPL_TO_JSVAL(BOOLEAN_TO_JSVAL_IMPL(b));
245 }
246
247 static JS_ALWAYS_INLINE JSBool
248 JSVAL_IS_PRIMITIVE(jsval v)
249 {
250     jsval_layout l;
251     l.asBits = JSVAL_BITS(v);
252     return JSVAL_IS_PRIMITIVE_IMPL(l);
253 }
254
255 static JS_ALWAYS_INLINE JSBool
256 JSVAL_IS_GCTHING(jsval v)
257 {
258     jsval_layout l;
259     l.asBits = JSVAL_BITS(v);
260     return JSVAL_IS_GCTHING_IMPL(l);
261 }
262
263 static JS_ALWAYS_INLINE void *
264 JSVAL_TO_GCTHING(jsval v)
265 {
266     jsval_layout l;
267     JS_ASSERT(JSVAL_IS_GCTHING(v));
268     l.asBits = JSVAL_BITS(v);
269     return JSVAL_TO_GCTHING_IMPL(l);
270 }
271
272 /* To be GC-safe, privates are tagged as doubles. */
273
274 static JS_ALWAYS_INLINE jsval
275 PRIVATE_TO_JSVAL(void *ptr)
276 {
277     return IMPL_TO_JSVAL(PRIVATE_PTR_TO_JSVAL_IMPL(ptr));
278 }
279
280 static JS_ALWAYS_INLINE void *
281 JSVAL_TO_PRIVATE(jsval v)
282 {
283     jsval_layout l;
284     JS_ASSERT(JSVAL_IS_DOUBLE(v));
285     l.asBits = JSVAL_BITS(v);
286     return JSVAL_TO_PRIVATE_PTR_IMPL(l);
287 }
288
289 /************************************************************************/
290
291 /*
292  * A jsid is an identifier for a property or method of an object which is
293  * either a 31-bit signed integer, interned string or object. If XML is
294  * enabled, there is an additional singleton jsid value; see
295  * JS_DEFAULT_XML_NAMESPACE_ID below. Finally, there is an additional jsid
296  * value, JSID_VOID, which does not occur in JS scripts but may be used to
297  * indicate the absence of a valid jsid.
298  *
299  * A jsid is not implicitly convertible to or from a jsval; JS_ValueToId or
300  * JS_IdToValue must be used instead.
301  */
302
303 #define JSID_TYPE_STRING                 0x0
304 #define JSID_TYPE_INT                    0x1
305 #define JSID_TYPE_VOID                   0x2
306 #define JSID_TYPE_OBJECT                 0x4
307 #define JSID_TYPE_DEFAULT_XML_NAMESPACE  0x6
308 #define JSID_TYPE_MASK                   0x7
309
310 /*
311  * Avoid using canonical 'id' for jsid parameters since this is a magic word in
312  * Objective-C++ which, apparently, wants to be able to #include jsapi.h.
313  */
314 #define id iden
315
316 static JS_ALWAYS_INLINE JSBool
317 JSID_IS_STRING(jsid id)
318 {
319     return (JSID_BITS(id) & JSID_TYPE_MASK) == 0;
320 }
321
322 static JS_ALWAYS_INLINE JSString *
323 JSID_TO_STRING(jsid id)
324 {
325     JS_ASSERT(JSID_IS_STRING(id));
326     return (JSString *)(JSID_BITS(id));
327 }
328
329 static JS_ALWAYS_INLINE JSBool
330 JSID_IS_ZERO(jsid id)
331 {
332     return JSID_BITS(id) == 0;
333 }
334
335 JS_PUBLIC_API(JSBool)
336 JS_StringHasBeenInterned(JSString *str);
337
338 /* A jsid may only hold an interned JSString. */
339 static JS_ALWAYS_INLINE jsid
340 INTERNED_STRING_TO_JSID(JSString *str)
341 {
342     jsid id;
343     JS_ASSERT(str);
344     JS_ASSERT(JS_StringHasBeenInterned(str));
345     JS_ASSERT(((size_t)str & JSID_TYPE_MASK) == 0);
346     JSID_BITS(id) = (size_t)str;
347     return id;
348 }
349
350 static JS_ALWAYS_INLINE JSBool
351 JSID_IS_INT(jsid id)
352 {
353     return !!(JSID_BITS(id) & JSID_TYPE_INT);
354 }
355
356 static JS_ALWAYS_INLINE int32
357 JSID_TO_INT(jsid id)
358 {
359     JS_ASSERT(JSID_IS_INT(id));
360     return ((int32)JSID_BITS(id)) >> 1;
361 }
362
363 /*
364  * Note: when changing these values, verify that their use in
365  * js_CheckForStringIndex is still valid.
366  */
367 #define JSID_INT_MIN  (-(1 << 30))
368 #define JSID_INT_MAX  ((1 << 30) - 1)
369
370 static JS_ALWAYS_INLINE JSBool
371 INT_FITS_IN_JSID(int32 i)
372 {
373     return ((jsuint)(i) - (jsuint)JSID_INT_MIN <=
374             (jsuint)(JSID_INT_MAX - JSID_INT_MIN));
375 }
376
377 static JS_ALWAYS_INLINE jsid
378 INT_TO_JSID(int32 i)
379 {
380     jsid id;
381     JS_ASSERT(INT_FITS_IN_JSID(i));
382     JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT);
383     return id;
384 }
385
386 static JS_ALWAYS_INLINE JSBool
387 JSID_IS_OBJECT(jsid id)
388 {
389     return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_OBJECT &&
390            (size_t)JSID_BITS(id) != JSID_TYPE_OBJECT;
391 }
392
393 static JS_ALWAYS_INLINE JSObject *
394 JSID_TO_OBJECT(jsid id)
395 {
396     JS_ASSERT(JSID_IS_OBJECT(id));
397     return (JSObject *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK);
398 }
399
400 static JS_ALWAYS_INLINE jsid
401 OBJECT_TO_JSID(JSObject *obj)
402 {
403     jsid id;
404     JS_ASSERT(obj != NULL);
405     JS_ASSERT(((size_t)obj & JSID_TYPE_MASK) == 0);
406     JSID_BITS(id) = ((size_t)obj | JSID_TYPE_OBJECT);
407     return id;
408 }
409
410 static JS_ALWAYS_INLINE JSBool
411 JSID_IS_GCTHING(jsid id)
412 {
413     return JSID_IS_STRING(id) || JSID_IS_OBJECT(id);
414 }
415
416 static JS_ALWAYS_INLINE void *
417 JSID_TO_GCTHING(jsid id)
418 {
419     return (void *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK);
420 }
421
422 /*
423  * The magic XML namespace id is not a valid jsid. Global object classes in
424  * embeddings that enable JS_HAS_XML_SUPPORT (E4X) should handle this id.
425  */
426
427 static JS_ALWAYS_INLINE JSBool
428 JSID_IS_DEFAULT_XML_NAMESPACE(jsid id)
429 {
430     JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_DEFAULT_XML_NAMESPACE,
431                  JSID_BITS(id) == JSID_TYPE_DEFAULT_XML_NAMESPACE);
432     return ((size_t)JSID_BITS(id) == JSID_TYPE_DEFAULT_XML_NAMESPACE);
433 }
434
435 #ifdef JS_USE_JSVAL_JSID_STRUCT_TYPES
436 extern JS_PUBLIC_DATA(jsid) JS_DEFAULT_XML_NAMESPACE_ID;
437 #else
438 #define JS_DEFAULT_XML_NAMESPACE_ID ((jsid)JSID_TYPE_DEFAULT_XML_NAMESPACE)
439 #endif
440
441 /*
442  * A void jsid is not a valid id and only arises as an exceptional API return
443  * value, such as in JS_NextProperty. Embeddings must not pass JSID_VOID into
444  * JSAPI entry points expecting a jsid and do not need to handle JSID_VOID in
445  * hooks receiving a jsid except when explicitly noted in the API contract.
446  */
447
448 static JS_ALWAYS_INLINE JSBool
449 JSID_IS_VOID(jsid id)
450 {
451     JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID,
452                  JSID_BITS(id) == JSID_TYPE_VOID);
453     return ((size_t)JSID_BITS(id) == JSID_TYPE_VOID);
454 }
455
456 static JS_ALWAYS_INLINE JSBool
457 JSID_IS_EMPTY(jsid id)
458 {
459     return ((size_t)JSID_BITS(id) == JSID_TYPE_OBJECT);
460 }
461
462 #undef id
463
464 #ifdef JS_USE_JSVAL_JSID_STRUCT_TYPES
465 extern JS_PUBLIC_DATA(jsid) JSID_VOID;
466 extern JS_PUBLIC_DATA(jsid) JSID_EMPTY;
467 #else
468 # define JSID_VOID      ((jsid)JSID_TYPE_VOID)
469 # define JSID_EMPTY     ((jsid)JSID_TYPE_OBJECT)
470 #endif
471
472 /************************************************************************/
473
474 /* Lock and unlock the GC thing held by a jsval. */
475 #define JSVAL_LOCK(cx,v)        (JSVAL_IS_GCTHING(v)                          \
476                                  ? JS_LockGCThing(cx, JSVAL_TO_GCTHING(v))    \
477                                  : JS_TRUE)
478 #define JSVAL_UNLOCK(cx,v)      (JSVAL_IS_GCTHING(v)                          \
479                                  ? JS_UnlockGCThing(cx, JSVAL_TO_GCTHING(v))  \
480                                  : JS_TRUE)
481
482 /* Property attributes, set in JSPropertySpec and passed to API functions. */
483 #define JSPROP_ENUMERATE        0x01    /* property is visible to for/in loop */
484 #define JSPROP_READONLY         0x02    /* not settable: assignment is no-op */
485 #define JSPROP_PERMANENT        0x04    /* property cannot be deleted */
486 #define JSPROP_GETTER           0x10    /* property holds getter function */
487 #define JSPROP_SETTER           0x20    /* property holds setter function */
488 #define JSPROP_SHARED           0x40    /* don't allocate a value slot for this
489                                            property; don't copy the property on
490                                            set of the same-named property in an
491                                            object that delegates to a prototype
492                                            containing this property */
493 #define JSPROP_INDEX            0x80    /* name is actually (jsint) index */
494 #define JSPROP_SHORTID          0x100   /* set in JSPropertyDescriptor.attrs
495                                            if getters/setters use a shortid */
496
497 /* Function flags, set in JSFunctionSpec and passed to JS_NewFunction etc. */
498 #define JSFUN_LAMBDA            0x08    /* expressed, not declared, function */
499 #define JSFUN_HEAVYWEIGHT       0x80    /* activation requires a Call object */
500
501 #define JSFUN_HEAVYWEIGHT_TEST(f)  ((f) & JSFUN_HEAVYWEIGHT)
502
503 /* 0x0100 is unused */
504 #define JSFUN_CONSTRUCTOR     0x0200    /* native that can be called as a ctor
505                                            without creating a this object */
506
507 #define JSFUN_FLAGS_MASK      0x07f8    /* overlay JSFUN_* attributes --
508                                            bits 12-15 are used internally to
509                                            flag interpreted functions */
510
511 #define JSFUN_STUB_GSOPS      0x1000    /* use JS_PropertyStub getter/setter
512                                            instead of defaulting to class gsops
513                                            for property holding function */
514
515 /*
516  * Re-use JSFUN_LAMBDA, which applies only to scripted functions, for use in
517  * JSFunctionSpec arrays that specify generic native prototype methods, i.e.,
518  * methods of a class prototype that are exposed as static methods taking an
519  * extra leading argument: the generic |this| parameter.
520  *
521  * If you set this flag in a JSFunctionSpec struct's flags initializer, then
522  * that struct must live at least as long as the native static method object
523  * created due to this flag by JS_DefineFunctions or JS_InitClass.  Typically
524  * JSFunctionSpec structs are allocated in static arrays.
525  */
526 #define JSFUN_GENERIC_NATIVE    JSFUN_LAMBDA
527
528 /*
529  * Microseconds since the epoch, midnight, January 1, 1970 UTC.  See the
530  * comment in jstypes.h regarding safe int64 usage.
531  */
532 extern JS_PUBLIC_API(int64)
533 JS_Now(void);
534
535 /* Don't want to export data, so provide accessors for non-inline jsvals. */
536 extern JS_PUBLIC_API(jsval)
537 JS_GetNaNValue(JSContext *cx);
538
539 extern JS_PUBLIC_API(jsval)
540 JS_GetNegativeInfinityValue(JSContext *cx);
541
542 extern JS_PUBLIC_API(jsval)
543 JS_GetPositiveInfinityValue(JSContext *cx);
544
545 extern JS_PUBLIC_API(jsval)
546 JS_GetEmptyStringValue(JSContext *cx);
547
548 extern JS_PUBLIC_API(JSString *)
549 JS_GetEmptyString(JSRuntime *rt);
550
551 /*
552  * Format is a string of the following characters (spaces are insignificant),
553  * specifying the tabulated type conversions:
554  *
555  *   b      JSBool          Boolean
556  *   c      uint16/jschar   ECMA uint16, Unicode char
557  *   i      int32           ECMA int32
558  *   u      uint32          ECMA uint32
559  *   j      int32           Rounded int32 (coordinate)
560  *   d      jsdouble        IEEE double
561  *   I      jsdouble        Integral IEEE double
562  *   S      JSString *      Unicode string, accessed by a JSString pointer
563  *   W      jschar *        Unicode character vector, 0-terminated (W for wide)
564  *   o      JSObject *      Object reference
565  *   f      JSFunction *    Function private
566  *   v      jsval           Argument value (no conversion)
567  *   *      N/A             Skip this argument (no vararg)
568  *   /      N/A             End of required arguments
569  *
570  * The variable argument list after format must consist of &b, &c, &s, e.g.,
571  * where those variables have the types given above.  For the pointer types
572  * char *, JSString *, and JSObject *, the pointed-at memory returned belongs
573  * to the JS runtime, not to the calling native code.  The runtime promises
574  * to keep this memory valid so long as argv refers to allocated stack space
575  * (so long as the native function is active).
576  *
577  * Fewer arguments than format specifies may be passed only if there is a /
578  * in format after the last required argument specifier and argc is at least
579  * the number of required arguments.  More arguments than format specifies
580  * may be passed without error; it is up to the caller to deal with trailing
581  * unconverted arguments.
582  */
583 extern JS_PUBLIC_API(JSBool)
584 JS_ConvertArguments(JSContext *cx, uintN argc, jsval *argv, const char *format,
585                     ...);
586
587 #ifdef va_start
588 extern JS_PUBLIC_API(JSBool)
589 JS_ConvertArgumentsVA(JSContext *cx, uintN argc, jsval *argv,
590                       const char *format, va_list ap);
591 #endif
592
593 #ifdef JS_ARGUMENT_FORMATTER_DEFINED
594
595 /*
596  * Add and remove a format string handler for JS_{Convert,Push}Arguments{,VA}.
597  * The handler function has this signature (see jspubtd.h):
598  *
599  *   JSBool MyArgumentFormatter(JSContext *cx, const char *format,
600  *                              JSBool fromJS, jsval **vpp, va_list *app);
601  *
602  * It should return true on success, and return false after reporting an error
603  * or detecting an already-reported error.
604  *
605  * For a given format string, for example "AA", the formatter is called from
606  * JS_ConvertArgumentsVA like so:
607  *
608  *   formatter(cx, "AA...", JS_TRUE, &sp, &ap);
609  *
610  * sp points into the arguments array on the JS stack, while ap points into
611  * the stdarg.h va_list on the C stack.  The JS_TRUE passed for fromJS tells
612  * the formatter to convert zero or more jsvals at sp to zero or more C values
613  * accessed via pointers-to-values at ap, updating both sp (via *vpp) and ap
614  * (via *app) to point past the converted arguments and their result pointers
615  * on the C stack.
616  *
617  * When called from JS_PushArgumentsVA, the formatter is invoked thus:
618  *
619  *   formatter(cx, "AA...", JS_FALSE, &sp, &ap);
620  *
621  * where JS_FALSE for fromJS means to wrap the C values at ap according to the
622  * format specifier and store them at sp, updating ap and sp appropriately.
623  *
624  * The "..." after "AA" is the rest of the format string that was passed into
625  * JS_{Convert,Push}Arguments{,VA}.  The actual format trailing substring used
626  * in each Convert or PushArguments call is passed to the formatter, so that
627  * one such function may implement several formats, in order to share code.
628  *
629  * Remove just forgets about any handler associated with format.  Add does not
630  * copy format, it points at the string storage allocated by the caller, which
631  * is typically a string constant.  If format is in dynamic storage, it is up
632  * to the caller to keep the string alive until Remove is called.
633  */
634 extern JS_PUBLIC_API(JSBool)
635 JS_AddArgumentFormatter(JSContext *cx, const char *format,
636                         JSArgumentFormatter formatter);
637
638 extern JS_PUBLIC_API(void)
639 JS_RemoveArgumentFormatter(JSContext *cx, const char *format);
640
641 #endif /* JS_ARGUMENT_FORMATTER_DEFINED */
642
643 extern JS_PUBLIC_API(JSBool)
644 JS_ConvertValue(JSContext *cx, jsval v, JSType type, jsval *vp);
645
646 extern JS_PUBLIC_API(JSBool)
647 JS_ValueToObject(JSContext *cx, jsval v, JSObject **objp);
648
649 extern JS_PUBLIC_API(JSFunction *)
650 JS_ValueToFunction(JSContext *cx, jsval v);
651
652 extern JS_PUBLIC_API(JSFunction *)
653 JS_ValueToConstructor(JSContext *cx, jsval v);
654
655 extern JS_PUBLIC_API(JSString *)
656 JS_ValueToString(JSContext *cx, jsval v);
657
658 extern JS_PUBLIC_API(JSString *)
659 JS_ValueToSource(JSContext *cx, jsval v);
660
661 extern JS_PUBLIC_API(JSBool)
662 JS_ValueToNumber(JSContext *cx, jsval v, jsdouble *dp);
663
664 extern JS_PUBLIC_API(JSBool)
665 JS_DoubleIsInt32(jsdouble d, jsint *ip);
666
667 /*
668  * Convert a value to a number, then to an int32, according to the ECMA rules
669  * for ToInt32.
670  */
671 extern JS_PUBLIC_API(JSBool)
672 JS_ValueToECMAInt32(JSContext *cx, jsval v, int32 *ip);
673
674 /*
675  * Convert a value to a number, then to a uint32, according to the ECMA rules
676  * for ToUint32.
677  */
678 extern JS_PUBLIC_API(JSBool)
679 JS_ValueToECMAUint32(JSContext *cx, jsval v, uint32 *ip);
680
681 /*
682  * Convert a value to a number, then to an int32 if it fits by rounding to
683  * nearest; but failing with an error report if the double is out of range
684  * or unordered.
685  */
686 extern JS_PUBLIC_API(JSBool)
687 JS_ValueToInt32(JSContext *cx, jsval v, int32 *ip);
688
689 /*
690  * ECMA ToUint16, for mapping a jsval to a Unicode point.
691  */
692 extern JS_PUBLIC_API(JSBool)
693 JS_ValueToUint16(JSContext *cx, jsval v, uint16 *ip);
694
695 extern JS_PUBLIC_API(JSBool)
696 JS_ValueToBoolean(JSContext *cx, jsval v, JSBool *bp);
697
698 extern JS_PUBLIC_API(JSType)
699 JS_TypeOfValue(JSContext *cx, jsval v);
700
701 extern JS_PUBLIC_API(const char *)
702 JS_GetTypeName(JSContext *cx, JSType type);
703
704 extern JS_PUBLIC_API(JSBool)
705 JS_StrictlyEqual(JSContext *cx, jsval v1, jsval v2, JSBool *equal);
706
707 extern JS_PUBLIC_API(JSBool)
708 JS_SameValue(JSContext *cx, jsval v1, jsval v2, JSBool *same);
709
710 /************************************************************************/
711
712 /*
713  * Initialization, locking, contexts, and memory allocation.
714  *
715  * It is important that the first runtime and first context be created in a
716  * single-threaded fashion, otherwise the behavior of the library is undefined.
717  * See: http://developer.mozilla.org/en/docs/Category:JSAPI_Reference
718  */
719 #define JS_NewRuntime       JS_Init
720 #define JS_DestroyRuntime   JS_Finish
721 #define JS_LockRuntime      JS_Lock
722 #define JS_UnlockRuntime    JS_Unlock
723
724 extern JS_PUBLIC_API(JSRuntime *)
725 JS_NewRuntime(uint32 maxbytes);
726
727 /* Deprecated. */
728 #define JS_CommenceRuntimeShutDown(rt) ((void) 0)
729
730 extern JS_PUBLIC_API(void)
731 JS_DestroyRuntime(JSRuntime *rt);
732
733 extern JS_PUBLIC_API(void)
734 JS_ShutDown(void);
735
736 JS_PUBLIC_API(void *)
737 JS_GetRuntimePrivate(JSRuntime *rt);
738
739 JS_PUBLIC_API(void)
740 JS_SetRuntimePrivate(JSRuntime *rt, void *data);
741
742 extern JS_PUBLIC_API(void)
743 JS_BeginRequest(JSContext *cx);
744
745 extern JS_PUBLIC_API(void)
746 JS_EndRequest(JSContext *cx);
747
748 /* Yield to pending GC operations, regardless of request depth */
749 extern JS_PUBLIC_API(void)
750 JS_YieldRequest(JSContext *cx);
751
752 extern JS_PUBLIC_API(jsrefcount)
753 JS_SuspendRequest(JSContext *cx);
754
755 extern JS_PUBLIC_API(void)
756 JS_ResumeRequest(JSContext *cx, jsrefcount saveDepth);
757
758 extern JS_PUBLIC_API(JSBool)
759 JS_IsInRequest(JSContext *cx);
760
761 #ifdef __cplusplus
762 JS_END_EXTERN_C
763
764 class JSAutoRequest {
765   public:
766     JSAutoRequest(JSContext *cx JS_GUARD_OBJECT_NOTIFIER_PARAM)
767         : mContext(cx), mSaveDepth(0) {
768         JS_GUARD_OBJECT_NOTIFIER_INIT;
769         JS_BeginRequest(mContext);
770     }
771     ~JSAutoRequest() {
772         JS_EndRequest(mContext);
773     }
774
775     void suspend() {
776         mSaveDepth = JS_SuspendRequest(mContext);
777     }
778     void resume() {
779         JS_ResumeRequest(mContext, mSaveDepth);
780     }
781
782   protected:
783     JSContext *mContext;
784     jsrefcount mSaveDepth;
785     JS_DECL_USE_GUARD_OBJECT_NOTIFIER
786
787 #if 0
788   private:
789     static void *operator new(size_t) CPP_THROW_NEW { return 0; };
790     static void operator delete(void *, size_t) { };
791 #endif
792 };
793
794 class JSAutoSuspendRequest {
795   public:
796     JSAutoSuspendRequest(JSContext *cx JS_GUARD_OBJECT_NOTIFIER_PARAM)
797         : mContext(cx), mSaveDepth(0) {
798         JS_GUARD_OBJECT_NOTIFIER_INIT;
799         if (mContext) {
800             mSaveDepth = JS_SuspendRequest(mContext);
801         }
802     }
803     ~JSAutoSuspendRequest() {
804         resume();
805     }
806
807     void resume() {
808         if (mContext) {
809             JS_ResumeRequest(mContext, mSaveDepth);
810             mContext = 0;
811         }
812     }
813
814   protected:
815     JSContext *mContext;
816     jsrefcount mSaveDepth;
817     JS_DECL_USE_GUARD_OBJECT_NOTIFIER
818
819 #if 0
820   private:
821     static void *operator new(size_t) CPP_THROW_NEW { return 0; };
822     static void operator delete(void *, size_t) { };
823 #endif
824 };
825
826 class JSAutoCheckRequest {
827   public:
828     JSAutoCheckRequest(JSContext *cx JS_GUARD_OBJECT_NOTIFIER_PARAM) {
829 #if defined JS_THREADSAFE && defined DEBUG
830         mContext = cx;
831         JS_ASSERT(JS_IsInRequest(cx));
832 #endif
833         JS_GUARD_OBJECT_NOTIFIER_INIT;
834     }
835
836     ~JSAutoCheckRequest() {
837 #if defined JS_THREADSAFE && defined DEBUG
838         JS_ASSERT(JS_IsInRequest(mContext));
839 #endif
840     }
841
842
843   private:
844 #if defined JS_THREADSAFE && defined DEBUG
845     JSContext *mContext;
846 #endif
847     JS_DECL_USE_GUARD_OBJECT_NOTIFIER
848 };
849
850 JS_BEGIN_EXTERN_C
851 #endif
852
853 extern JS_PUBLIC_API(void)
854 JS_Lock(JSRuntime *rt);
855
856 extern JS_PUBLIC_API(void)
857 JS_Unlock(JSRuntime *rt);
858
859 extern JS_PUBLIC_API(JSContextCallback)
860 JS_SetContextCallback(JSRuntime *rt, JSContextCallback cxCallback);
861
862 extern JS_PUBLIC_API(JSContext *)
863 JS_NewContext(JSRuntime *rt, size_t stackChunkSize);
864
865 extern JS_PUBLIC_API(void)
866 JS_DestroyContext(JSContext *cx);
867
868 extern JS_PUBLIC_API(void)
869 JS_DestroyContextNoGC(JSContext *cx);
870
871 extern JS_PUBLIC_API(void)
872 JS_DestroyContextMaybeGC(JSContext *cx);
873
874 extern JS_PUBLIC_API(void *)
875 JS_GetContextPrivate(JSContext *cx);
876
877 extern JS_PUBLIC_API(void)
878 JS_SetContextPrivate(JSContext *cx, void *data);
879
880 extern JS_PUBLIC_API(JSRuntime *)
881 JS_GetRuntime(JSContext *cx);
882
883 extern JS_PUBLIC_API(JSContext *)
884 JS_ContextIterator(JSRuntime *rt, JSContext **iterp);
885
886 extern JS_PUBLIC_API(JSVersion)
887 JS_GetVersion(JSContext *cx);
888
889 extern JS_PUBLIC_API(JSVersion)
890 JS_SetVersion(JSContext *cx, JSVersion version);
891
892 extern JS_PUBLIC_API(const char *)
893 JS_VersionToString(JSVersion version);
894
895 extern JS_PUBLIC_API(JSVersion)
896 JS_StringToVersion(const char *string);
897
898 /*
899  * JS options are orthogonal to version, and may be freely composed with one
900  * another as well as with version.
901  *
902  * JSOPTION_VAROBJFIX is recommended -- see the comments associated with the
903  * prototypes for JS_ExecuteScript, JS_EvaluateScript, etc.
904  */
905 #define JSOPTION_STRICT         JS_BIT(0)       /* warn on dubious practice */
906 #define JSOPTION_WERROR         JS_BIT(1)       /* convert warning to error */
907 #define JSOPTION_VAROBJFIX      JS_BIT(2)       /* make JS_EvaluateScript use
908                                                    the last object on its 'obj'
909                                                    param's scope chain as the
910                                                    ECMA 'variables object' */
911 #define JSOPTION_PRIVATE_IS_NSISUPPORTS \
912                                 JS_BIT(3)       /* context private data points
913                                                    to an nsISupports subclass */
914 #define JSOPTION_COMPILE_N_GO   JS_BIT(4)       /* caller of JS_Compile*Script
915                                                    promises to execute compiled
916                                                    script once only; enables
917                                                    compile-time scope chain
918                                                    resolution of consts. */
919 #define JSOPTION_ATLINE         JS_BIT(5)       /* //@line number ["filename"]
920                                                    option supported for the
921                                                    XUL preprocessor and kindred
922                                                    beasts. */
923 #define JSOPTION_XML            JS_BIT(6)       /* EMCAScript for XML support:
924                                                    parse <!-- --> as a token,
925                                                    not backward compatible with
926                                                    the comment-hiding hack used
927                                                    in HTML script tags. */
928 #define JSOPTION_DONT_REPORT_UNCAUGHT \
929                                 JS_BIT(8)       /* When returning from the
930                                                    outermost API call, prevent
931                                                    uncaught exceptions from
932                                                    being converted to error
933                                                    reports */
934
935 #define JSOPTION_RELIMIT        JS_BIT(9)       /* Throw exception on any
936                                                    regular expression which
937                                                    backtracks more than n^3
938                                                    times, where n is length
939                                                    of the input string */
940 #define JSOPTION_ANONFUNFIX     JS_BIT(10)      /* Disallow function () {} in
941                                                    statement context per
942                                                    ECMA-262 Edition 3. */
943
944 #define JSOPTION_JIT            JS_BIT(11)      /* Enable JIT compilation. */
945
946 #define JSOPTION_NO_SCRIPT_RVAL JS_BIT(12)      /* A promise to the compiler
947                                                    that a null rval out-param
948                                                    will be passed to each call
949                                                    to JS_ExecuteScript. */
950 #define JSOPTION_UNROOTED_GLOBAL JS_BIT(13)     /* The GC will not root the
951                                                    contexts' global objects
952                                                    (see JS_GetGlobalObject),
953                                                    leaving that up to the
954                                                    embedding. */
955
956 #define JSOPTION_METHODJIT      JS_BIT(14)      /* Whole-method JIT. */
957 #define JSOPTION_PROFILING      JS_BIT(15)      /* Profiler to make tracer/methodjit choices. */
958 #define JSOPTION_METHODJIT_ALWAYS \
959                                 JS_BIT(16)      /* Always whole-method JIT,
960                                                    don't tune at run-time. */
961
962 /* Options which reflect compile-time properties of scripts. */
963 #define JSCOMPILEOPTION_MASK    (JSOPTION_XML | JSOPTION_ANONFUNFIX)
964
965 #define JSRUNOPTION_MASK        (JS_BITMASK(17) & ~JSCOMPILEOPTION_MASK)
966 #define JSALLOPTION_MASK        (JSCOMPILEOPTION_MASK | JSRUNOPTION_MASK)
967
968 extern JS_PUBLIC_API(uint32)
969 JS_GetOptions(JSContext *cx);
970
971 extern JS_PUBLIC_API(uint32)
972 JS_SetOptions(JSContext *cx, uint32 options);
973
974 extern JS_PUBLIC_API(uint32)
975 JS_ToggleOptions(JSContext *cx, uint32 options);
976
977 extern JS_PUBLIC_API(const char *)
978 JS_GetImplementationVersion(void);
979
980 extern JS_PUBLIC_API(JSCompartmentCallback)
981 JS_SetCompartmentCallback(JSRuntime *rt, JSCompartmentCallback callback);
982
983 extern JS_PUBLIC_API(JSWrapObjectCallback)
984 JS_SetWrapObjectCallbacks(JSRuntime *rt,
985                           JSWrapObjectCallback callback,
986                           JSPreWrapCallback precallback);
987
988 extern JS_PUBLIC_API(JSCrossCompartmentCall *)
989 JS_EnterCrossCompartmentCall(JSContext *cx, JSObject *target);
990
991 extern JS_PUBLIC_API(void)
992 JS_LeaveCrossCompartmentCall(JSCrossCompartmentCall *call);
993
994 extern JS_PUBLIC_API(void *)
995 JS_SetCompartmentPrivate(JSContext *cx, JSCompartment *compartment, void *data);
996
997 extern JS_PUBLIC_API(void *)
998 JS_GetCompartmentPrivate(JSContext *cx, JSCompartment *compartment);
999
1000 extern JS_PUBLIC_API(JSBool)
1001 JS_WrapObject(JSContext *cx, JSObject **objp);
1002
1003 extern JS_PUBLIC_API(JSBool)
1004 JS_WrapValue(JSContext *cx, jsval *vp);
1005
1006 extern JS_PUBLIC_API(JSObject *)
1007 JS_TransplantObject(JSContext *cx, JSObject *origobj, JSObject *target);
1008
1009 extern JS_FRIEND_API(JSObject *)
1010 js_TransplantObjectWithWrapper(JSContext *cx,
1011                                JSObject *origobj,
1012                                JSObject *origwrapper,
1013                                JSObject *targetobj,
1014                                JSObject *targetwrapper);
1015
1016 extern JS_FRIEND_API(JSObject *)
1017 js_TransplantObjectWithWrapper(JSContext *cx,
1018                                JSObject *origobj,
1019                                JSObject *origwrapper,
1020                                JSObject *targetobj,
1021                                JSObject *targetwrapper);
1022
1023 #ifdef __cplusplus
1024 JS_END_EXTERN_C
1025
1026 class JS_PUBLIC_API(JSAutoEnterCompartment)
1027 {
1028     JSCrossCompartmentCall *call;
1029
1030   public:
1031     JSAutoEnterCompartment() : call(NULL) {}
1032
1033     bool enter(JSContext *cx, JSObject *target);
1034
1035     void enterAndIgnoreErrors(JSContext *cx, JSObject *target);
1036
1037     bool entered() const { return call != NULL; }
1038
1039     ~JSAutoEnterCompartment() {
1040         if (call && call != reinterpret_cast<JSCrossCompartmentCall*>(1))
1041             JS_LeaveCrossCompartmentCall(call);
1042     }
1043
1044     void swap(JSAutoEnterCompartment &other) {
1045         JSCrossCompartmentCall *tmp = call;
1046         call = other.call;
1047         other.call = tmp;
1048     }
1049 };
1050
1051 JS_BEGIN_EXTERN_C
1052 #endif
1053
1054 extern JS_PUBLIC_API(JSObject *)
1055 JS_GetGlobalObject(JSContext *cx);
1056
1057 extern JS_PUBLIC_API(void)
1058 JS_SetGlobalObject(JSContext *cx, JSObject *obj);
1059
1060 /*
1061  * Initialize standard JS class constructors, prototypes, and any top-level
1062  * functions and constants associated with the standard classes (e.g. isNaN
1063  * for Number).
1064  *
1065  * NB: This sets cx's global object to obj if it was null.
1066  */
1067 extern JS_PUBLIC_API(JSBool)
1068 JS_InitStandardClasses(JSContext *cx, JSObject *obj);
1069
1070 /*
1071  * Resolve id, which must contain either a string or an int, to a standard
1072  * class name in obj if possible, defining the class's constructor and/or
1073  * prototype and storing true in *resolved.  If id does not name a standard
1074  * class or a top-level property induced by initializing a standard class,
1075  * store false in *resolved and just return true.  Return false on error,
1076  * as usual for JSBool result-typed API entry points.
1077  *
1078  * This API can be called directly from a global object class's resolve op,
1079  * to define standard classes lazily.  The class's enumerate op should call
1080  * JS_EnumerateStandardClasses(cx, obj), to define eagerly during for..in
1081  * loops any classes not yet resolved lazily.
1082  */
1083 extern JS_PUBLIC_API(JSBool)
1084 JS_ResolveStandardClass(JSContext *cx, JSObject *obj, jsid id,
1085                         JSBool *resolved);
1086
1087 extern JS_PUBLIC_API(JSBool)
1088 JS_EnumerateStandardClasses(JSContext *cx, JSObject *obj);
1089
1090 /*
1091  * Enumerate any already-resolved standard class ids into ida, or into a new
1092  * JSIdArray if ida is null.  Return the augmented array on success, null on
1093  * failure with ida (if it was non-null on entry) destroyed.
1094  */
1095 extern JS_PUBLIC_API(JSIdArray *)
1096 JS_EnumerateResolvedStandardClasses(JSContext *cx, JSObject *obj,
1097                                     JSIdArray *ida);
1098
1099 extern JS_PUBLIC_API(JSBool)
1100 JS_GetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
1101                   JSObject **objp);
1102
1103 extern JS_PUBLIC_API(JSObject *)
1104 JS_GetScopeChain(JSContext *cx);
1105
1106 extern JS_PUBLIC_API(JSObject *)
1107 JS_GetGlobalForObject(JSContext *cx, JSObject *obj);
1108
1109 extern JS_PUBLIC_API(JSObject *)
1110 JS_GetGlobalForScopeChain(JSContext *cx);
1111
1112 #ifdef JS_HAS_CTYPES
1113 /*
1114  * Initialize the 'ctypes' object on a global variable 'obj'. The 'ctypes'
1115  * object will be sealed.
1116  */
1117 extern JS_PUBLIC_API(JSBool)
1118 JS_InitCTypesClass(JSContext *cx, JSObject *global);
1119
1120 /*
1121  * Convert a unicode string 'source' of length 'slen' to the platform native
1122  * charset, returning a null-terminated string allocated with JS_malloc. On
1123  * failure, this function should report an error.
1124  */
1125 typedef char *
1126 (* JSCTypesUnicodeToNativeFun)(JSContext *cx, const jschar *source, size_t slen);
1127
1128 /*
1129  * Set of function pointers that ctypes can use for various internal functions.
1130  * See JS_SetCTypesCallbacks below. Providing NULL for a function is safe,
1131  * and will result in the applicable ctypes functionality not being available.
1132  */
1133 struct JSCTypesCallbacks {
1134     JSCTypesUnicodeToNativeFun unicodeToNative;
1135 };
1136
1137 typedef struct JSCTypesCallbacks JSCTypesCallbacks;
1138
1139 /*
1140  * Set the callbacks on the provided 'ctypesObj' object. 'callbacks' should be a
1141  * pointer to static data that exists for the lifetime of 'ctypesObj', but it
1142  * may safely be altered after calling this function and without having
1143  * to call this function again.
1144  */
1145 extern JS_PUBLIC_API(JSBool)
1146 JS_SetCTypesCallbacks(JSContext *cx, JSObject *ctypesObj, JSCTypesCallbacks *callbacks);
1147 #endif
1148
1149 /*
1150  * Macros to hide interpreter stack layout details from a JSFastNative using
1151  * its jsval *vp parameter. The stack layout underlying invocation can't change
1152  * without breaking source and binary compatibility (argv[-2] is well-known to
1153  * be the callee jsval, and argv[-1] is as well known to be |this|).
1154  *
1155  * Note well: However, argv[-1] may be JSVAL_NULL where with slow natives it
1156  * is the global object, so embeddings implementing fast natives *must* call
1157  * JS_THIS or JS_THIS_OBJECT and test for failure indicated by a null return,
1158  * which should propagate as a false return from native functions and hooks.
1159  *
1160  * To reduce boilerplace checks, JS_InstanceOf and JS_GetInstancePrivate now
1161  * handle a null obj parameter by returning false (throwing a TypeError if
1162  * given non-null argv), so most native functions that type-check their |this|
1163  * parameter need not add null checking.
1164  *
1165  * NB: there is an anti-dependency between JS_CALLEE and JS_SET_RVAL: native
1166  * methods that may inspect their callee must defer setting their return value
1167  * until after any such possible inspection. Otherwise the return value will be
1168  * inspected instead of the callee function object.
1169  *
1170  * WARNING: These are not (yet) mandatory macros, but new code outside of the
1171  * engine should use them. In the Mozilla 2.0 milestone their definitions may
1172  * change incompatibly.
1173  *
1174  * N.B. constructors must not use JS_THIS, as no 'this' object has been created.
1175  */
1176
1177 #define JS_CALLEE(cx,vp)        ((vp)[0])
1178 #define JS_THIS(cx,vp)          JS_ComputeThis(cx, vp)
1179 #define JS_THIS_OBJECT(cx,vp)   (JSVAL_TO_OBJECT(JS_THIS(cx,vp)))
1180 #define JS_ARGV(cx,vp)          ((vp) + 2)
1181 #define JS_RVAL(cx,vp)          (*(vp))
1182 #define JS_SET_RVAL(cx,vp,v)    (*(vp) = (v))
1183
1184 extern JS_PUBLIC_API(jsval)
1185 JS_ComputeThis(JSContext *cx, jsval *vp);
1186
1187 #ifdef __cplusplus
1188 #undef JS_THIS
1189 static inline jsval
1190 JS_THIS(JSContext *cx, jsval *vp)
1191 {
1192     return JSVAL_IS_PRIMITIVE(vp[1]) ? JS_ComputeThis(cx, vp) : vp[1];
1193 }
1194 #endif
1195
1196 /*
1197  * |this| is passed to functions in ES5 without change.  Functions themselves
1198  * do any post-processing they desire to box |this|, compute the global object,
1199  * &c.  Use this macro to retrieve a function's unboxed |this| value.
1200  *
1201  * This macro must not be used in conjunction with JS_THIS or JS_THIS_OBJECT,
1202  * or vice versa.  Either use the provided this value with this macro, or
1203  * compute the boxed this value using those.
1204  *
1205  * N.B. constructors must not use JS_THIS_VALUE, as no 'this' object has been
1206  * created.
1207  */
1208 #define JS_THIS_VALUE(cx,vp)    ((vp)[1])
1209
1210 extern JS_PUBLIC_API(void *)
1211 JS_malloc(JSContext *cx, size_t nbytes);
1212
1213 extern JS_PUBLIC_API(void *)
1214 JS_realloc(JSContext *cx, void *p, size_t nbytes);
1215
1216 extern JS_PUBLIC_API(void)
1217 JS_free(JSContext *cx, void *p);
1218
1219 extern JS_PUBLIC_API(void)
1220 JS_updateMallocCounter(JSContext *cx, size_t nbytes);
1221
1222 extern JS_PUBLIC_API(char *)
1223 JS_strdup(JSContext *cx, const char *s);
1224
1225 extern JS_PUBLIC_API(JSBool)
1226 JS_NewNumberValue(JSContext *cx, jsdouble d, jsval *rval);
1227
1228 /*
1229  * A GC root is a pointer to a jsval, JSObject * or JSString * that itself
1230  * points into the GC heap. JS_AddValueRoot takes a pointer to a jsval and
1231  * JS_AddGCThingRoot takes a pointer to a JSObject * or JString *.
1232  *
1233  * Note that, since JS_Add*Root stores the address of a variable (of type
1234  * jsval, JSString *, or JSObject *), that variable must live until
1235  * JS_Remove*Root is called to remove that variable. For example, after:
1236  *
1237  *   void some_function() {
1238  *     jsval v;
1239  *     JS_AddNamedRootedValue(cx, &v, "name");
1240  *
1241  * the caller must perform
1242  *
1243  *     JS_RemoveRootedValue(cx, &v);
1244  *
1245  * before some_function() returns.
1246  *
1247  * Also, use JS_AddNamed*Root(cx, &structPtr->memberObj, "structPtr->memberObj")
1248  * in preference to JS_Add*Root(cx, &structPtr->memberObj), in order to identify
1249  * roots by their source callsites.  This way, you can find the callsite while
1250  * debugging if you should fail to do JS_Remove*Root(cx, &structPtr->memberObj)
1251  * before freeing structPtr's memory.
1252  */
1253 extern JS_PUBLIC_API(JSBool)
1254 JS_AddValueRoot(JSContext *cx, jsval *vp);
1255
1256 extern JS_PUBLIC_API(JSBool)
1257 JS_AddStringRoot(JSContext *cx, JSString **rp);
1258
1259 extern JS_PUBLIC_API(JSBool)
1260 JS_AddObjectRoot(JSContext *cx, JSObject **rp);
1261
1262 extern JS_PUBLIC_API(JSBool)
1263 JS_AddGCThingRoot(JSContext *cx, void **rp);
1264
1265 #ifdef NAME_ALL_GC_ROOTS
1266 #define JS_DEFINE_TO_TOKEN(def) #def
1267 #define JS_DEFINE_TO_STRING(def) JS_DEFINE_TO_TOKEN(def)
1268 #define JS_AddValueRoot(cx,vp) JS_AddNamedValueRoot((cx), (vp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__))
1269 #define JS_AddStringRoot(cx,rp) JS_AddNamedStringRoot((cx), (rp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__))
1270 #define JS_AddObjectRoot(cx,rp) JS_AddNamedObjectRoot((cx), (rp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__))
1271 #define JS_AddGCThingRoot(cx,rp) JS_AddNamedGCThingRoot((cx), (rp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__))
1272 #endif
1273
1274 extern JS_PUBLIC_API(JSBool)
1275 JS_AddNamedValueRoot(JSContext *cx, jsval *vp, const char *name);
1276
1277 extern JS_PUBLIC_API(JSBool)
1278 JS_AddNamedStringRoot(JSContext *cx, JSString **rp, const char *name);
1279
1280 extern JS_PUBLIC_API(JSBool)
1281 JS_AddNamedObjectRoot(JSContext *cx, JSObject **rp, const char *name);
1282
1283 extern JS_PUBLIC_API(JSBool)
1284 JS_AddNamedGCThingRoot(JSContext *cx, void **rp, const char *name);
1285
1286 extern JS_PUBLIC_API(JSBool)
1287 JS_RemoveValueRoot(JSContext *cx, jsval *vp);
1288
1289 extern JS_PUBLIC_API(JSBool)
1290 JS_RemoveStringRoot(JSContext *cx, JSString **rp);
1291
1292 extern JS_PUBLIC_API(JSBool)
1293 JS_RemoveObjectRoot(JSContext *cx, JSObject **rp);
1294
1295 extern JS_PUBLIC_API(JSBool)
1296 JS_RemoveGCThingRoot(JSContext *cx, void **rp);
1297
1298 /* TODO: remove these APIs */
1299
1300 extern JS_FRIEND_API(JSBool)
1301 js_AddRootRT(JSRuntime *rt, jsval *vp, const char *name);
1302
1303 extern JS_FRIEND_API(JSBool)
1304 js_AddGCThingRootRT(JSRuntime *rt, void **rp, const char *name);
1305
1306 extern JS_FRIEND_API(JSBool)
1307 js_RemoveRoot(JSRuntime *rt, void *rp);
1308
1309 #ifdef __cplusplus
1310 JS_END_EXTERN_C
1311
1312 namespace JS {
1313
1314 /*
1315  * Protecting non-jsval, non-JSObject *, non-JSString * values from collection
1316  *
1317  * Most of the time, the garbage collector's conservative stack scanner works
1318  * behind the scenes, finding all live values and protecting them from being
1319  * collected. However, when JSAPI client code obtains a pointer to data the
1320  * scanner does not know about, owned by an object the scanner does know about,
1321  * Care Must Be Taken.
1322  *
1323  * The scanner recognizes only a select set of types: pointers to JSObjects and
1324  * similar things (JSFunctions, and so on), pointers to JSStrings, and jsvals.
1325  * So while the scanner finds all live |JSString| pointers, it does not notice
1326  * |jschar| pointers.
1327  *
1328  * So suppose we have:
1329  *
1330  *   void f(JSString *str) {
1331  *     const jschar *ch = JS_GetStringCharsZ(str);
1332  *     ... do stuff with ch, but no uses of str ...;
1333  *   }
1334  *
1335  * After the call to |JS_GetStringCharsZ|, there are no further uses of
1336  * |str|, which means that the compiler is within its rights to not store
1337  * it anywhere. But because the stack scanner will not notice |ch|, there
1338  * is no longer any live value in this frame that would keep the string
1339  * alive. If |str| is the last reference to that |JSString|, and the
1340  * collector runs while we are using |ch|, the string's array of |jschar|s
1341  * may be freed out from under us.
1342  *
1343  * Note that there is only an issue when 1) we extract a thing X the scanner
1344  * doesn't recognize from 2) a thing Y the scanner does recognize, and 3) if Y
1345  * gets garbage-collected, then X gets freed. If we have code like this:
1346  *
1347  *   void g(JSObject *obj) {
1348  *     jsval x;
1349  *     JS_GetProperty(obj, "x", &x);
1350  *     ... do stuff with x ...
1351  *   }
1352  *
1353  * there's no problem, because the value we've extracted, x, is a jsval, a
1354  * type that the conservative scanner recognizes.
1355  *
1356  * Conservative GC frees us from the obligation to explicitly root the types it
1357  * knows about, but when we work with derived values like |ch|, we must root
1358  * their owners, as the derived value alone won't keep them alive.
1359  *
1360  * A JS::Anchor is a kind of GC root that allows us to keep the owners of
1361  * derived values like |ch| alive throughout the Anchor's lifetime. We could
1362  * fix the above code as follows:
1363  *
1364  *   void f(JSString *str) {
1365  *     JS::Anchor<JSString *> a_str(str);
1366  *     const jschar *ch = JS_GetStringCharsZ(str);
1367  *     ... do stuff with ch, but no uses of str ...;
1368  *   }
1369  *
1370  * This simply ensures that |str| will be live until |a_str| goes out of scope.
1371  * As long as we don't retain a pointer to the string's characters for longer
1372  * than that, we have avoided all garbage collection hazards.
1373  */
1374 template<typename T> class AnchorPermitted;
1375 template<> class AnchorPermitted<JSObject *> { };
1376 template<> class AnchorPermitted<const JSObject *> { };
1377 template<> class AnchorPermitted<JSFunction *> { };
1378 template<> class AnchorPermitted<const JSFunction *> { };
1379 template<> class AnchorPermitted<JSString *> { };
1380 template<> class AnchorPermitted<const JSString *> { };
1381 template<> class AnchorPermitted<jsval> { };
1382
1383 template<typename T>
1384 class Anchor: AnchorPermitted<T> {
1385   public:
1386     Anchor() { }
1387     explicit Anchor(T t) { hold = t; }
1388     inline ~Anchor();
1389     T &get() { return hold; }
1390     void set(const T &t) { hold = t; }
1391     void clear() { hold = 0; }
1392   private:
1393     T hold;
1394     /* Anchors should not be assigned or passed to functions. */
1395     Anchor(const Anchor &);
1396     const Anchor &operator=(const Anchor &);
1397 };
1398
1399 #ifdef __GNUC__
1400 template<typename T>
1401 inline Anchor<T>::~Anchor() {
1402     /*
1403      * No code is generated for this. But because this is marked 'volatile', G++ will
1404      * assume it has important side-effects, and won't delete it. (G++ never looks at
1405      * the actual text and notices it's empty.) And because we have passed |hold| to
1406      * it, GCC will keep |hold| alive until this point.
1407      *
1408      * The "memory" clobber operand ensures that G++ will not move prior memory
1409      * accesses after the asm --- it's a barrier. Unfortunately, it also means that
1410      * G++ will assume that all memory has changed after the asm, as it would for a
1411      * call to an unknown function. I don't know of a way to avoid that consequence.
1412      */
1413     asm volatile("":: "g" (hold) : "memory");
1414 }
1415 #else
1416 template<typename T>
1417 inline Anchor<T>::~Anchor() {
1418     /*
1419      * An adequate portable substitute, for non-structure types.
1420      *
1421      * The compiler promises that, by the end of an expression statement, the
1422      * last-stored value to a volatile object is the same as it would be in an
1423      * unoptimized, direct implementation (the "abstract machine" whose behavior the
1424      * language spec describes). However, the compiler is still free to reorder
1425      * non-volatile accesses across this store --- which is what we must prevent. So
1426      * assigning the held value to a volatile variable, as we do here, is not enough.
1427      *
1428      * In our case, however, garbage collection only occurs at function calls, so it
1429      * is sufficient to ensure that the destructor's store isn't moved earlier across
1430      * any function calls that could collect. It is hard to imagine the compiler
1431      * analyzing the program so thoroughly that it could prove that such motion was
1432      * safe. In practice, compilers treat calls to the collector as opaque operations
1433      * --- in particular, as operations which could access volatile variables, across
1434      * which this destructor must not be moved.
1435      *
1436      * ("Objection, your honor!  *Alleged* killer whale!")
1437      *
1438      * The disadvantage of this approach is that it does generate code for the store.
1439      * We do need to use Anchors in some cases where cycles are tight.
1440      */
1441     volatile T sink;
1442     sink = hold;
1443 }
1444
1445 #ifdef JS_USE_JSVAL_JSID_STRUCT_TYPES
1446 /*
1447  * The default assignment operator for |struct C| has the signature:
1448  *
1449  *   C& C::operator=(const C&)
1450  *
1451  * And in particular requires implicit conversion of |this| to type |C| for the return
1452  * value. But |volatile C| cannot thus be converted to |C|, so just doing |sink = hold| as
1453  * in the non-specialized version would fail to compile. Do the assignment on asBits
1454  * instead, since I don't think we want to give jsval_layout an assignment operator
1455  * returning |volatile jsval_layout|.
1456  */
1457 template<>
1458 inline Anchor<jsval>::~Anchor() {
1459     volatile jsval sink;
1460     sink.asBits = hold.asBits;
1461 }
1462 #endif
1463 #endif
1464
1465 }  /* namespace JS */
1466
1467 JS_BEGIN_EXTERN_C
1468 #endif
1469
1470 /*
1471  * C-compatible version of the Anchor class. It should be called after the last
1472  * use of the variable it protects.
1473  */
1474 extern JS_NEVER_INLINE JS_PUBLIC_API(void)
1475 JS_AnchorPtr(void *p);
1476
1477 /*
1478  * This symbol may be used by embedders to detect the change from the old
1479  * JS_AddRoot(JSContext *, void *) APIs to the new ones above.
1480  */
1481 #define JS_TYPED_ROOTING_API
1482
1483 /* Obsolete rooting APIs. */
1484 #define JS_ClearNewbornRoots(cx) ((void) 0)
1485 #define JS_EnterLocalRootScope(cx) (JS_TRUE)
1486 #define JS_LeaveLocalRootScope(cx) ((void) 0)
1487 #define JS_LeaveLocalRootScopeWithResult(cx, rval) ((void) 0)
1488 #define JS_ForgetLocalRoot(cx, thing) ((void) 0)
1489
1490 typedef enum JSGCRootType {
1491     JS_GC_ROOT_VALUE_PTR,
1492     JS_GC_ROOT_GCTHING_PTR
1493 } JSGCRootType;
1494
1495 #ifdef DEBUG
1496 extern JS_PUBLIC_API(void)
1497 JS_DumpNamedRoots(JSRuntime *rt,
1498                   void (*dump)(const char *name, void *rp, JSGCRootType type, void *data),
1499                   void *data);
1500 #endif
1501
1502 /*
1503  * Call JS_MapGCRoots to map the GC's roots table using map(rp, name, data).
1504  * The root is pointed at by rp; if the root is unnamed, name is null; data is
1505  * supplied from the third parameter to JS_MapGCRoots.
1506  *
1507  * The map function should return JS_MAP_GCROOT_REMOVE to cause the currently
1508  * enumerated root to be removed.  To stop enumeration, set JS_MAP_GCROOT_STOP
1509  * in the return value.  To keep on mapping, return JS_MAP_GCROOT_NEXT.  These
1510  * constants are flags; you can OR them together.
1511  *
1512  * This function acquires and releases rt's GC lock around the mapping of the
1513  * roots table, so the map function should run to completion in as few cycles
1514  * as possible.  Of course, map cannot call JS_GC, JS_MaybeGC, JS_BeginRequest,
1515  * or any JS API entry point that acquires locks, without double-tripping or
1516  * deadlocking on the GC lock.
1517  *
1518  * The JSGCRootType parameter indicates whether rp is a pointer to a Value
1519  * (which is obtained by '(Value *)rp') or a pointer to a GC-thing pointer
1520  * (which is obtained by '(void **)rp').
1521  *
1522  * JS_MapGCRoots returns the count of roots that were successfully mapped.
1523  */
1524 #define JS_MAP_GCROOT_NEXT      0       /* continue mapping entries */
1525 #define JS_MAP_GCROOT_STOP      1       /* stop mapping entries */
1526 #define JS_MAP_GCROOT_REMOVE    2       /* remove and free the current entry */
1527
1528 typedef intN
1529 (* JSGCRootMapFun)(void *rp, JSGCRootType type, const char *name, void *data);
1530
1531 extern JS_PUBLIC_API(uint32)
1532 JS_MapGCRoots(JSRuntime *rt, JSGCRootMapFun map, void *data);
1533
1534 extern JS_PUBLIC_API(JSBool)
1535 JS_LockGCThing(JSContext *cx, void *thing);
1536
1537 extern JS_PUBLIC_API(JSBool)
1538 JS_LockGCThingRT(JSRuntime *rt, void *thing);
1539
1540 extern JS_PUBLIC_API(JSBool)
1541 JS_UnlockGCThing(JSContext *cx, void *thing);
1542
1543 extern JS_PUBLIC_API(JSBool)
1544 JS_UnlockGCThingRT(JSRuntime *rt, void *thing);
1545
1546 /*
1547  * Register externally maintained GC roots.
1548  *
1549  * traceOp: the trace operation. For each root the implementation should call
1550  *          JS_CallTracer whenever the root contains a traceable thing.
1551  * data:    the data argument to pass to each invocation of traceOp.
1552  */
1553 extern JS_PUBLIC_API(void)
1554 JS_SetExtraGCRoots(JSRuntime *rt, JSTraceDataOp traceOp, void *data);
1555
1556 /*
1557  * For implementors of JSMarkOp. All new code should implement JSTraceOp
1558  * instead.
1559  */
1560 extern JS_PUBLIC_API(void)
1561 JS_MarkGCThing(JSContext *cx, jsval v, const char *name, void *arg);
1562
1563 /*
1564  * JS_CallTracer API and related macros for implementors of JSTraceOp, to
1565  * enumerate all references to traceable things reachable via a property or
1566  * other strong ref identified for debugging purposes by name or index or
1567  * a naming callback.
1568  *
1569  * By definition references to traceable things include non-null pointers
1570  * to JSObject, JSString and jsdouble and corresponding jsvals.
1571  *
1572  * See the JSTraceOp typedef in jspubtd.h.
1573  */
1574
1575 /* Trace kinds to pass to JS_Tracing. */
1576 #define JSTRACE_OBJECT  0
1577 #define JSTRACE_STRING  1
1578
1579 /*
1580  * Use the following macros to check if a particular jsval is a traceable
1581  * thing and to extract the thing and its kind to pass to JS_CallTracer.
1582  */
1583 static JS_ALWAYS_INLINE JSBool
1584 JSVAL_IS_TRACEABLE(jsval v)
1585 {
1586     jsval_layout l;
1587     l.asBits = JSVAL_BITS(v);
1588     return JSVAL_IS_TRACEABLE_IMPL(l);
1589 }
1590
1591 static JS_ALWAYS_INLINE void *
1592 JSVAL_TO_TRACEABLE(jsval v)
1593 {
1594     return JSVAL_TO_GCTHING(v);
1595 }
1596
1597 static JS_ALWAYS_INLINE uint32
1598 JSVAL_TRACE_KIND(jsval v)
1599 {
1600     jsval_layout l;
1601     JS_ASSERT(JSVAL_IS_GCTHING(v));
1602     l.asBits = JSVAL_BITS(v);
1603     return JSVAL_TRACE_KIND_IMPL(l);
1604 }
1605
1606 struct JSTracer {
1607     JSContext           *context;
1608     JSTraceCallback     callback;
1609     JSTraceNamePrinter  debugPrinter;
1610     const void          *debugPrintArg;
1611     size_t              debugPrintIndex;
1612 };
1613
1614 /*
1615  * The method to call on each reference to a traceable thing stored in a
1616  * particular JSObject or other runtime structure. With DEBUG defined the
1617  * caller before calling JS_CallTracer must initialize JSTracer fields
1618  * describing the reference using the macros below.
1619  */
1620 extern JS_PUBLIC_API(void)
1621 JS_CallTracer(JSTracer *trc, void *thing, uint32 kind);
1622
1623 /*
1624  * Set debugging information about a reference to a traceable thing to prepare
1625  * for the following call to JS_CallTracer.
1626  *
1627  * When printer is null, arg must be const char * or char * C string naming
1628  * the reference and index must be either (size_t)-1 indicating that the name
1629  * alone describes the reference or it must be an index into some array vector
1630  * that stores the reference.
1631  *
1632  * When printer callback is not null, the arg and index arguments are
1633  * available to the callback as debugPrinterArg and debugPrintIndex fields
1634  * of JSTracer.
1635  *
1636  * The storage for name or callback's arguments needs to live only until
1637  * the following call to JS_CallTracer returns.
1638  */
1639 #ifdef DEBUG
1640 # define JS_SET_TRACING_DETAILS(trc, printer, arg, index)                     \
1641     JS_BEGIN_MACRO                                                            \
1642         (trc)->debugPrinter = (printer);                                      \
1643         (trc)->debugPrintArg = (arg);                                         \
1644         (trc)->debugPrintIndex = (index);                                     \
1645     JS_END_MACRO
1646 #else
1647 # define JS_SET_TRACING_DETAILS(trc, printer, arg, index)                     \
1648     JS_BEGIN_MACRO                                                            \
1649     JS_END_MACRO
1650 #endif
1651
1652 /*
1653  * Convenience macro to describe the argument of JS_CallTracer using C string
1654  * and index.
1655  */
1656 # define JS_SET_TRACING_INDEX(trc, name, index)                               \
1657     JS_SET_TRACING_DETAILS(trc, NULL, name, index)
1658
1659 /*
1660  * Convenience macro to describe the argument of JS_CallTracer using C string.
1661  */
1662 # define JS_SET_TRACING_NAME(trc, name)                                       \
1663     JS_SET_TRACING_DETAILS(trc, NULL, name, (size_t)-1)
1664
1665 /*
1666  * Convenience macro to invoke JS_CallTracer using C string as the name for
1667  * the reference to a traceable thing.
1668  */
1669 # define JS_CALL_TRACER(trc, thing, kind, name)                               \
1670     JS_BEGIN_MACRO                                                            \
1671         JS_SET_TRACING_NAME(trc, name);                                       \
1672         JS_CallTracer((trc), (thing), (kind));                                \
1673     JS_END_MACRO
1674
1675 /*
1676  * Convenience macros to invoke JS_CallTracer when jsval represents a
1677  * reference to a traceable thing.
1678  */
1679 #define JS_CALL_VALUE_TRACER(trc, val, name)                                  \
1680     JS_BEGIN_MACRO                                                            \
1681         if (JSVAL_IS_TRACEABLE(val)) {                                        \
1682             JS_CALL_TRACER((trc), JSVAL_TO_GCTHING(val),                      \
1683                            JSVAL_TRACE_KIND(val), name);                      \
1684         }                                                                     \
1685     JS_END_MACRO
1686
1687 #define JS_CALL_OBJECT_TRACER(trc, object, name)                              \
1688     JS_BEGIN_MACRO                                                            \
1689         JSObject *obj_ = (object);                                            \
1690         JS_ASSERT(obj_);                                                      \
1691         JS_CALL_TRACER((trc), obj_, JSTRACE_OBJECT, name);                    \
1692     JS_END_MACRO
1693
1694 #define JS_CALL_STRING_TRACER(trc, string, name)                              \
1695     JS_BEGIN_MACRO                                                            \
1696         JSString *str_ = (string);                                            \
1697         JS_ASSERT(str_);                                                      \
1698         JS_CALL_TRACER((trc), str_, JSTRACE_STRING, name);                    \
1699     JS_END_MACRO
1700
1701 /*
1702  * API for JSTraceCallback implementations.
1703  */
1704 # define JS_TRACER_INIT(trc, cx_, callback_)                                  \
1705     JS_BEGIN_MACRO                                                            \
1706         (trc)->context = (cx_);                                               \
1707         (trc)->callback = (callback_);                                        \
1708         (trc)->debugPrinter = NULL;                                           \
1709         (trc)->debugPrintArg = NULL;                                          \
1710         (trc)->debugPrintIndex = (size_t)-1;                                  \
1711     JS_END_MACRO
1712
1713 extern JS_PUBLIC_API(void)
1714 JS_TraceChildren(JSTracer *trc, void *thing, uint32 kind);
1715
1716 extern JS_PUBLIC_API(void)
1717 JS_TraceRuntime(JSTracer *trc);
1718
1719 #ifdef DEBUG
1720
1721 extern JS_PUBLIC_API(void)
1722 JS_PrintTraceThingInfo(char *buf, size_t bufsize, JSTracer *trc,
1723                        void *thing, uint32 kind, JSBool includeDetails);
1724
1725 /*
1726  * DEBUG-only method to dump the object graph of heap-allocated things.
1727  *
1728  * fp:              file for the dump output.
1729  * start:           when non-null, dump only things reachable from start
1730  *                  thing. Otherwise dump all things reachable from the
1731  *                  runtime roots.
1732  * startKind:       trace kind of start if start is not null. Must be 0 when
1733  *                  start is null.
1734  * thingToFind:     dump only paths in the object graph leading to thingToFind
1735  *                  when non-null.
1736  * maxDepth:        the upper bound on the number of edges to descend from the
1737  *                  graph roots.
1738  * thingToIgnore:   thing to ignore during the graph traversal when non-null.
1739  */
1740 extern JS_PUBLIC_API(JSBool)
1741 JS_DumpHeap(JSContext *cx, FILE *fp, void* startThing, uint32 startKind,
1742             void *thingToFind, size_t maxDepth, void *thingToIgnore);
1743
1744 #endif
1745
1746 /*
1747  * Garbage collector API.
1748  */
1749 extern JS_PUBLIC_API(void)
1750 JS_GC(JSContext *cx);
1751
1752 extern JS_PUBLIC_API(void)
1753 JS_MaybeGC(JSContext *cx);
1754
1755 extern JS_PUBLIC_API(JSGCCallback)
1756 JS_SetGCCallback(JSContext *cx, JSGCCallback cb);
1757
1758 extern JS_PUBLIC_API(JSGCCallback)
1759 JS_SetGCCallbackRT(JSRuntime *rt, JSGCCallback cb);
1760
1761 extern JS_PUBLIC_API(JSBool)
1762 JS_IsGCMarkingTracer(JSTracer *trc);
1763
1764 extern JS_PUBLIC_API(JSBool)
1765 JS_IsAboutToBeFinalized(JSContext *cx, void *thing);
1766
1767 typedef enum JSGCParamKey {
1768     /* Maximum nominal heap before last ditch GC. */
1769     JSGC_MAX_BYTES          = 0,
1770
1771     /* Number of JS_malloc bytes before last ditch GC. */
1772     JSGC_MAX_MALLOC_BYTES   = 1,
1773
1774     /* Hoard stackPools for this long, in ms, default is 30 seconds. */
1775     JSGC_STACKPOOL_LIFESPAN = 2,
1776
1777     /*
1778      * The factor that defines when the GC is invoked. The factor is a
1779      * percent of the memory allocated by the GC after the last run of
1780      * the GC. When the current memory allocated by the GC is more than
1781      * this percent then the GC is invoked. The factor cannot be less
1782      * than 100 since the current memory allocated by the GC cannot be less
1783      * than the memory allocated after the last run of the GC.
1784      */
1785     JSGC_TRIGGER_FACTOR = 3,
1786
1787     /* Amount of bytes allocated by the GC. */
1788     JSGC_BYTES = 4,
1789
1790     /* Number of times when GC was invoked. */
1791     JSGC_NUMBER = 5,
1792
1793     /* Max size of the code cache in bytes. */
1794     JSGC_MAX_CODE_CACHE_BYTES = 6,
1795
1796     /* Select GC mode. */
1797     JSGC_MODE = 7,
1798
1799     /* Number of GC chunks waiting to expire. */
1800     JSGC_UNUSED_CHUNKS = 8
1801 } JSGCParamKey;
1802
1803 typedef enum JSGCMode {
1804     /* Perform only global GCs. */
1805     JSGC_MODE_GLOBAL = 0,
1806
1807     /* Perform per-compartment GCs until too much garbage has accumulated. */
1808     JSGC_MODE_COMPARTMENT = 1
1809 } JSGCMode;
1810
1811 extern JS_PUBLIC_API(void)
1812 JS_SetGCParameter(JSRuntime *rt, JSGCParamKey key, uint32 value);
1813
1814 extern JS_PUBLIC_API(uint32)
1815 JS_GetGCParameter(JSRuntime *rt, JSGCParamKey key);
1816
1817 extern JS_PUBLIC_API(void)
1818 JS_SetGCParameterForThread(JSContext *cx, JSGCParamKey key, uint32 value);
1819
1820 extern JS_PUBLIC_API(uint32)
1821 JS_GetGCParameterForThread(JSContext *cx, JSGCParamKey key);
1822
1823 /*
1824  * Flush the code cache for the current thread. The operation might be
1825  * delayed if the cache cannot be flushed currently because native
1826  * code is currently executing.
1827  */
1828
1829 extern JS_PUBLIC_API(void)
1830 JS_FlushCaches(JSContext *cx);
1831
1832 /*
1833  * Add a finalizer for external strings created by JS_NewExternalString (see
1834  * below) using a type-code returned from this function, and that understands
1835  * how to free or release the memory pointed at by JS_GetStringChars(str).
1836  *
1837  * Return a nonnegative type index if there is room for finalizer in the
1838  * global GC finalizers table, else return -1.  If the engine is compiled
1839  * JS_THREADSAFE and used in a multi-threaded environment, this function must
1840  * be invoked on the primordial thread only, at startup -- or else the entire
1841  * program must single-thread itself while loading a module that calls this
1842  * function.
1843  */
1844 extern JS_PUBLIC_API(intN)
1845 JS_AddExternalStringFinalizer(JSStringFinalizeOp finalizer);
1846
1847 /*
1848  * Remove finalizer from the global GC finalizers table, returning its type
1849  * code if found, -1 if not found.
1850  *
1851  * As with JS_AddExternalStringFinalizer, there is a threading restriction
1852  * if you compile the engine JS_THREADSAFE: this function may be called for a
1853  * given finalizer pointer on only one thread; different threads may call to
1854  * remove distinct finalizers safely.
1855  *
1856  * You must ensure that all strings with finalizer's type have been collected
1857  * before calling this function.  Otherwise, string data will be leaked by the
1858  * GC, for want of a finalizer to call.
1859  */
1860 extern JS_PUBLIC_API(intN)
1861 JS_RemoveExternalStringFinalizer(JSStringFinalizeOp finalizer);
1862
1863 /*
1864  * Create a new JSString whose chars member refers to external memory, i.e.,
1865  * memory requiring spe, type-specific finalization.  The type code must
1866  * be a nonnegative return value from JS_AddExternalStringFinalizer.
1867  */
1868 extern JS_PUBLIC_API(JSString *)
1869 JS_NewExternalString(JSContext *cx, jschar *chars, size_t length, intN type);
1870
1871 /*
1872  * Returns the external-string finalizer index for this string, or -1 if it is
1873  * an "internal" (native to JS engine) string.
1874  */
1875 extern JS_PUBLIC_API(intN)
1876 JS_GetExternalStringGCType(JSRuntime *rt, JSString *str);
1877
1878 /*
1879  * Deprecated. Use JS_SetNativeStackQuoata instead.
1880  */
1881 extern JS_PUBLIC_API(void)
1882 JS_SetThreadStackLimit(JSContext *cx, jsuword limitAddr);
1883
1884 /*
1885  * Set the size of the native stack that should not be exceed. To disable
1886  * stack size checking pass 0.
1887  */
1888 extern JS_PUBLIC_API(void)
1889 JS_SetNativeStackQuota(JSContext *cx, size_t stackSize);
1890
1891
1892 /*
1893  * Set the quota on the number of bytes that stack-like data structures can
1894  * use when the runtime compiles and executes scripts. These structures
1895  * consume heap space, so JS_SetThreadStackLimit does not bound their size.
1896  * The default quota is 128MB which is very generous.
1897  *
1898  * The function must be called before any script compilation or execution API
1899  * calls, i.e. either immediately after JS_NewContext or from JSCONTEXT_NEW
1900  * context callback.
1901  */
1902 extern JS_PUBLIC_API(void)
1903 JS_SetScriptStackQuota(JSContext *cx, size_t quota);
1904
1905 #define JS_DEFAULT_SCRIPT_STACK_QUOTA   ((size_t) 0x8000000)
1906
1907 /************************************************************************/
1908
1909 /*
1910  * Classes, objects, and properties.
1911  */
1912 typedef void (*JSClassInternal)();
1913
1914 /* For detailed comments on the function pointer types, see jspubtd.h. */
1915 struct JSClass {
1916     const char          *name;
1917     uint32              flags;
1918
1919     /* Mandatory non-null function pointer members. */
1920     JSPropertyOp        addProperty;
1921     JSPropertyOp        delProperty;
1922     JSPropertyOp        getProperty;
1923     JSStrictPropertyOp  setProperty;
1924     JSEnumerateOp       enumerate;
1925     JSResolveOp         resolve;
1926     JSConvertOp         convert;
1927     JSFinalizeOp        finalize;
1928
1929     /* Optionally non-null members start here. */
1930     JSClassInternal     reserved0;
1931     JSCheckAccessOp     checkAccess;
1932     JSNative            call;
1933     JSNative            construct;
1934     JSXDRObjectOp       xdrObject;
1935     JSHasInstanceOp     hasInstance;
1936     JSMarkOp            mark;
1937
1938     JSClassInternal     reserved1;
1939     void                *reserved[19];
1940 };
1941
1942 #define JSCLASS_HAS_PRIVATE             (1<<0)  /* objects have private slot */
1943 #define JSCLASS_NEW_ENUMERATE           (1<<1)  /* has JSNewEnumerateOp hook */
1944 #define JSCLASS_NEW_RESOLVE             (1<<2)  /* has JSNewResolveOp hook */
1945 #define JSCLASS_PRIVATE_IS_NSISUPPORTS  (1<<3)  /* private is (nsISupports *) */
1946 #define JSCLASS_NEW_RESOLVE_GETS_START  (1<<5)  /* JSNewResolveOp gets starting
1947                                                    object in prototype chain
1948                                                    passed in via *objp in/out
1949                                                    parameter */
1950 #define JSCLASS_CONSTRUCT_PROTOTYPE     (1<<6)  /* call constructor on class
1951                                                    prototype */
1952 #define JSCLASS_DOCUMENT_OBSERVER       (1<<7)  /* DOM document observer */
1953
1954 /*
1955  * To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or
1956  * JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where
1957  * n is a constant in [1, 255].  Reserved slots are indexed from 0 to n-1.
1958  */
1959 #define JSCLASS_RESERVED_SLOTS_SHIFT    8       /* room for 8 flags below */
1960 #define JSCLASS_RESERVED_SLOTS_WIDTH    8       /* and 16 above this field */
1961 #define JSCLASS_RESERVED_SLOTS_MASK     JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH)
1962 #define JSCLASS_HAS_RESERVED_SLOTS(n)   (((n) & JSCLASS_RESERVED_SLOTS_MASK)  \
1963                                          << JSCLASS_RESERVED_SLOTS_SHIFT)
1964 #define JSCLASS_RESERVED_SLOTS(clasp)   (((clasp)->flags                      \
1965                                           >> JSCLASS_RESERVED_SLOTS_SHIFT)    \
1966                                          & JSCLASS_RESERVED_SLOTS_MASK)
1967
1968 #define JSCLASS_HIGH_FLAGS_SHIFT        (JSCLASS_RESERVED_SLOTS_SHIFT +       \
1969                                          JSCLASS_RESERVED_SLOTS_WIDTH)
1970
1971 #define JSCLASS_INTERNAL_FLAG1          (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0))
1972 #define JSCLASS_IS_ANONYMOUS            (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1))
1973 #define JSCLASS_IS_GLOBAL               (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2))
1974
1975 /* Indicates that JSClass.mark is a tracer with JSTraceOp type. */
1976 #define JSCLASS_MARK_IS_TRACE           (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3))
1977 #define JSCLASS_INTERNAL_FLAG2          (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4))
1978
1979 /* Indicate whether the proto or ctor should be frozen. */
1980 #define JSCLASS_FREEZE_PROTO            (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5))
1981 #define JSCLASS_FREEZE_CTOR             (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6))
1982
1983 /* Additional global reserved slots, beyond those for standard prototypes. */
1984 #define JSRESERVED_GLOBAL_SLOTS_COUNT     6
1985 #define JSRESERVED_GLOBAL_THIS            (JSProto_LIMIT * 3)
1986 #define JSRESERVED_GLOBAL_THROWTYPEERROR  (JSRESERVED_GLOBAL_THIS + 1)
1987 #define JSRESERVED_GLOBAL_REGEXP_STATICS  (JSRESERVED_GLOBAL_THROWTYPEERROR + 1)
1988 #define JSRESERVED_GLOBAL_FUNCTION_NS     (JSRESERVED_GLOBAL_REGEXP_STATICS + 1)
1989 #define JSRESERVED_GLOBAL_EVAL_ALLOWED    (JSRESERVED_GLOBAL_FUNCTION_NS + 1)
1990 #define JSRESERVED_GLOBAL_FLAGS           (JSRESERVED_GLOBAL_EVAL_ALLOWED + 1)
1991
1992 /* Global flags. */
1993 #define JSGLOBAL_FLAGS_CLEARED          0x1
1994
1995 /*
1996  * ECMA-262 requires that most constructors used internally create objects
1997  * with "the original Foo.prototype value" as their [[Prototype]] (__proto__)
1998  * member initial value.  The "original ... value" verbiage is there because
1999  * in ECMA-262, global properties naming class objects are read/write and
2000  * deleteable, for the most part.
2001  *
2002  * Implementing this efficiently requires that global objects have classes
2003  * with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was
2004  * prevously allowed, but is now an ES5 violation and thus unsupported.
2005  */
2006 #define JSCLASS_GLOBAL_FLAGS                                                  \
2007     (JSCLASS_IS_GLOBAL |                                                      \
2008      JSCLASS_HAS_RESERVED_SLOTS(JSRESERVED_GLOBAL_THIS + JSRESERVED_GLOBAL_SLOTS_COUNT))
2009
2010 /* Fast access to the original value of each standard class's prototype. */
2011 #define JSCLASS_CACHED_PROTO_SHIFT      (JSCLASS_HIGH_FLAGS_SHIFT + 8)
2012 #define JSCLASS_CACHED_PROTO_WIDTH      8
2013 #define JSCLASS_CACHED_PROTO_MASK       JS_BITMASK(JSCLASS_CACHED_PROTO_WIDTH)
2014 #define JSCLASS_HAS_CACHED_PROTO(key)   ((key) << JSCLASS_CACHED_PROTO_SHIFT)
2015 #define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey)                         \
2016                                          (((clasp)->flags                     \
2017                                            >> JSCLASS_CACHED_PROTO_SHIFT)     \
2018                                           & JSCLASS_CACHED_PROTO_MASK))
2019
2020 /* Initializer for unused members of statically initialized JSClass structs. */
2021 #define JSCLASS_NO_INTERNAL_MEMBERS     0,{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
2022 #define JSCLASS_NO_OPTIONAL_MEMBERS     0,0,0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS
2023
2024 struct JSIdArray {
2025     jsint length;
2026     jsid  vector[1];    /* actually, length jsid words */
2027 };
2028
2029 extern JS_PUBLIC_API(void)
2030 JS_DestroyIdArray(JSContext *cx, JSIdArray *ida);
2031
2032 extern JS_PUBLIC_API(JSBool)
2033 JS_ValueToId(JSContext *cx, jsval v, jsid *idp);
2034
2035 extern JS_PUBLIC_API(JSBool)
2036 JS_IdToValue(JSContext *cx, jsid id, jsval *vp);
2037
2038 /*
2039  * JSNewResolveOp flag bits.
2040  */
2041 #define JSRESOLVE_QUALIFIED     0x01    /* resolve a qualified property id */
2042 #define JSRESOLVE_ASSIGNING     0x02    /* resolve on the left of assignment */
2043 #define JSRESOLVE_DETECTING     0x04    /* 'if (o.p)...' or '(o.p) ?...:...' */
2044 #define JSRESOLVE_DECLARING     0x08    /* var, const, or function prolog op */
2045 #define JSRESOLVE_CLASSNAME     0x10    /* class name used when constructing */
2046 #define JSRESOLVE_WITH          0x20    /* resolve inside a with statement */
2047
2048 extern JS_PUBLIC_API(JSBool)
2049 JS_PropertyStub(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
2050
2051 extern JS_PUBLIC_API(JSBool)
2052 JS_StrictPropertyStub(JSContext *cx, JSObject *obj, jsid id, JSBool strict, jsval *vp);
2053
2054 extern JS_PUBLIC_API(JSBool)
2055 JS_EnumerateStub(JSContext *cx, JSObject *obj);
2056
2057 extern JS_PUBLIC_API(JSBool)
2058 JS_ResolveStub(JSContext *cx, JSObject *obj, jsid id);
2059
2060 extern JS_PUBLIC_API(JSBool)
2061 JS_ConvertStub(JSContext *cx, JSObject *obj, JSType type, jsval *vp);
2062
2063 extern JS_PUBLIC_API(void)
2064 JS_FinalizeStub(JSContext *cx, JSObject *obj);
2065
2066 struct JSConstDoubleSpec {
2067     jsdouble        dval;
2068     const char      *name;
2069     uint8           flags;
2070     uint8           spare[3];
2071 };
2072
2073 /*
2074  * To define an array element rather than a named property member, cast the
2075  * element's index to (const char *) and initialize name with it, and set the
2076  * JSPROP_INDEX bit in flags.
2077  */
2078 struct JSPropertySpec {
2079     const char            *name;
2080     int8                  tinyid;
2081     uint8                 flags;
2082     JSPropertyOp          getter;
2083     JSStrictPropertyOp    setter;
2084 };
2085
2086 struct JSFunctionSpec {
2087     const char      *name;
2088     JSNative        call;
2089     uint16          nargs;
2090     uint16          flags;
2091 };
2092
2093 /*
2094  * Terminating sentinel initializer to put at the end of a JSFunctionSpec array
2095  * that's passed to JS_DefineFunctions or JS_InitClass.
2096  */
2097 #define JS_FS_END JS_FS(NULL,NULL,0,0)
2098
2099 /*
2100  * Initializer macros for a JSFunctionSpec array element. JS_FN (whose name
2101  * pays homage to the old JSNative/JSFastNative split) simply adds the flag
2102  * JSFUN_STUB_GSOPS.
2103  */
2104 #define JS_FS(name,call,nargs,flags)                                          \
2105     {name, call, nargs, flags}
2106 #define JS_FN(name,call,nargs,flags)                                          \
2107     {name, call, nargs, (flags) | JSFUN_STUB_GSOPS}
2108
2109 extern JS_PUBLIC_API(JSObject *)
2110 JS_InitClass(JSContext *cx, JSObject *obj, JSObject *parent_proto,
2111              JSClass *clasp, JSNative constructor, uintN nargs,
2112              JSPropertySpec *ps, JSFunctionSpec *fs,
2113              JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
2114
2115 #ifdef JS_THREADSAFE
2116 extern JS_PUBLIC_API(JSClass *)
2117 JS_GetClass(JSContext *cx, JSObject *obj);
2118
2119 #define JS_GET_CLASS(cx,obj) JS_GetClass(cx, obj)
2120 #else
2121 extern JS_PUBLIC_API(JSClass *)
2122 JS_GetClass(JSObject *obj);
2123
2124 #define JS_GET_CLASS(cx,obj) JS_GetClass(obj)
2125 #endif
2126
2127 extern JS_PUBLIC_API(JSBool)
2128 JS_InstanceOf(JSContext *cx, JSObject *obj, JSClass *clasp, jsval *argv);
2129
2130 extern JS_PUBLIC_API(JSBool)
2131 JS_HasInstance(JSContext *cx, JSObject *obj, jsval v, JSBool *bp);
2132
2133 extern JS_PUBLIC_API(void *)
2134 JS_GetPrivate(JSContext *cx, JSObject *obj);
2135
2136 extern JS_PUBLIC_API(JSBool)
2137 JS_SetPrivate(JSContext *cx, JSObject *obj, void *data);
2138
2139 extern JS_PUBLIC_API(void *)
2140 JS_GetInstancePrivate(JSContext *cx, JSObject *obj, JSClass *clasp,
2141                       jsval *argv);
2142
2143 extern JS_PUBLIC_API(JSObject *)
2144 JS_GetPrototype(JSContext *cx, JSObject *obj);
2145
2146 extern JS_PUBLIC_API(JSBool)
2147 JS_SetPrototype(JSContext *cx, JSObject *obj, JSObject *proto);
2148
2149 extern JS_PUBLIC_API(JSObject *)
2150 JS_GetParent(JSContext *cx, JSObject *obj);
2151
2152 extern JS_PUBLIC_API(JSBool)
2153 JS_SetParent(JSContext *cx, JSObject *obj, JSObject *parent);
2154
2155 extern JS_PUBLIC_API(JSObject *)
2156 JS_GetConstructor(JSContext *cx, JSObject *proto);
2157
2158 /*
2159  * Get a unique identifier for obj, good for the lifetime of obj (even if it
2160  * is moved by a copying GC).  Return false on failure (likely out of memory),
2161  * and true with *idp containing the unique id on success.
2162  */
2163 extern JS_PUBLIC_API(JSBool)
2164 JS_GetObjectId(JSContext *cx, JSObject *obj, jsid *idp);
2165
2166 extern JS_PUBLIC_API(JSObject *)
2167 JS_NewGlobalObject(JSContext *cx, JSClass *clasp);
2168
2169 extern JS_PUBLIC_API(JSObject *)
2170 JS_NewCompartmentAndGlobalObject(JSContext *cx, JSClass *clasp, JSPrincipals *principals);
2171
2172 extern JS_PUBLIC_API(JSObject *)
2173 JS_NewObject(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent);
2174
2175 /* Queries the [[Extensible]] property of the object. */
2176 extern JS_PUBLIC_API(JSBool)
2177 JS_IsExtensible(JSObject *obj);
2178
2179 /*
2180  * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default
2181  * proto if proto's actual parameter value is null.
2182  */
2183 extern JS_PUBLIC_API(JSObject *)
2184 JS_NewObjectWithGivenProto(JSContext *cx, JSClass *clasp, JSObject *proto,
2185                            JSObject *parent);
2186
2187 /*
2188  * Freeze obj, and all objects it refers to, recursively. This will not recurse
2189  * through non-extensible objects, on the assumption that those are already
2190  * deep-frozen.
2191  */
2192 extern JS_PUBLIC_API(JSBool)
2193 JS_DeepFreezeObject(JSContext *cx, JSObject *obj);
2194
2195 /*
2196  * Freezes an object; see ES5's Object.freeze(obj) method.
2197  */
2198 extern JS_PUBLIC_API(JSBool)
2199 JS_FreezeObject(JSContext *cx, JSObject *obj);
2200
2201 extern JS_PUBLIC_API(JSObject *)
2202 JS_ConstructObject(JSContext *cx, JSClass *clasp, JSObject *proto,
2203                    JSObject *parent);
2204
2205 extern JS_PUBLIC_API(JSObject *)
2206 JS_ConstructObjectWithArguments(JSContext *cx, JSClass *clasp, JSObject *proto,
2207                                 JSObject *parent, uintN argc, jsval *argv);
2208
2209 extern JS_PUBLIC_API(JSObject *)
2210 JS_New(JSContext *cx, JSObject *ctor, uintN argc, jsval *argv);
2211
2212 extern JS_PUBLIC_API(JSObject *)
2213 JS_DefineObject(JSContext *cx, JSObject *obj, const char *name, JSClass *clasp,
2214                 JSObject *proto, uintN attrs);
2215
2216 extern JS_PUBLIC_API(JSBool)
2217 JS_DefineConstDoubles(JSContext *cx, JSObject *obj, JSConstDoubleSpec *cds);
2218
2219 extern JS_PUBLIC_API(JSBool)
2220 JS_DefineProperties(JSContext *cx, JSObject *obj, JSPropertySpec *ps);
2221
2222 extern JS_PUBLIC_API(JSBool)
2223 JS_DefineProperty(JSContext *cx, JSObject *obj, const char *name, jsval value,
2224                   JSPropertyOp getter, JSStrictPropertyOp setter, uintN attrs);
2225
2226 extern JS_PUBLIC_API(JSBool)
2227 JS_DefinePropertyById(JSContext *cx, JSObject *obj, jsid id, jsval value,
2228                       JSPropertyOp getter, JSStrictPropertyOp setter, uintN attrs);
2229
2230 extern JS_PUBLIC_API(JSBool)
2231 JS_DefineOwnProperty(JSContext *cx, JSObject *obj, jsid id, jsval descriptor, JSBool *bp);
2232
2233 /*
2234  * Determine the attributes (JSPROP_* flags) of a property on a given object.
2235  *
2236  * If the object does not have a property by that name, *foundp will be
2237  * JS_FALSE and the value of *attrsp is undefined.
2238  */
2239 extern JS_PUBLIC_API(JSBool)
2240 JS_GetPropertyAttributes(JSContext *cx, JSObject *obj, const char *name,
2241                          uintN *attrsp, JSBool *foundp);
2242
2243 /*
2244  * The same, but if the property is native, return its getter and setter via
2245  * *getterp and *setterp, respectively (and only if the out parameter pointer
2246  * is not null).
2247  */
2248 extern JS_PUBLIC_API(JSBool)
2249 JS_GetPropertyAttrsGetterAndSetter(JSContext *cx, JSObject *obj,
2250                                    const char *name,
2251                                    uintN *attrsp, JSBool *foundp,
2252                                    JSPropertyOp *getterp,
2253                                    JSStrictPropertyOp *setterp);
2254
2255 extern JS_PUBLIC_API(JSBool)
2256 JS_GetPropertyAttrsGetterAndSetterById(JSContext *cx, JSObject *obj,
2257                                        jsid id,
2258                                        uintN *attrsp, JSBool *foundp,
2259                                        JSPropertyOp *getterp,
2260                                        JSStrictPropertyOp *setterp);
2261
2262 /*
2263  * Set the attributes of a property on a given object.
2264  *
2265  * If the object does not have a property by that name, *foundp will be
2266  * JS_FALSE and nothing will be altered.
2267  */
2268 extern JS_PUBLIC_API(JSBool)
2269 JS_SetPropertyAttributes(JSContext *cx, JSObject *obj, const char *name,
2270                          uintN attrs, JSBool *foundp);
2271
2272 extern JS_PUBLIC_API(JSBool)
2273 JS_DefinePropertyWithTinyId(JSContext *cx, JSObject *obj, const char *name,
2274                             int8 tinyid, jsval value,
2275                             JSPropertyOp getter, JSStrictPropertyOp setter,
2276                             uintN attrs);
2277
2278 extern JS_PUBLIC_API(JSBool)
2279 JS_AliasProperty(JSContext *cx, JSObject *obj, const char *name,
2280                  const char *alias);
2281
2282 extern JS_PUBLIC_API(JSBool)
2283 JS_AlreadyHasOwnProperty(JSContext *cx, JSObject *obj, const char *name,
2284                          JSBool *foundp);
2285
2286 extern JS_PUBLIC_API(JSBool)
2287 JS_AlreadyHasOwnPropertyById(JSContext *cx, JSObject *obj, jsid id,
2288                              JSBool *foundp);
2289
2290 extern JS_PUBLIC_API(JSBool)
2291 JS_HasProperty(JSContext *cx, JSObject *obj, const char *name, JSBool *foundp);
2292
2293 extern JS_PUBLIC_API(JSBool)
2294 JS_HasPropertyById(JSContext *cx, JSObject *obj, jsid id, JSBool *foundp);
2295
2296 extern JS_PUBLIC_API(JSBool)
2297 JS_LookupProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp);
2298
2299 extern JS_PUBLIC_API(JSBool)
2300 JS_LookupPropertyById(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
2301
2302 extern JS_PUBLIC_API(JSBool)
2303 JS_LookupPropertyWithFlags(JSContext *cx, JSObject *obj, const char *name,
2304                            uintN flags, jsval *vp);
2305
2306 extern JS_PUBLIC_API(JSBool)
2307 JS_LookupPropertyWithFlagsById(JSContext *cx, JSObject *obj, jsid id,
2308                                uintN flags, JSObject **objp, jsval *vp);
2309
2310 struct JSPropertyDescriptor {
2311     JSObject           *obj;
2312     uintN              attrs;
2313     JSPropertyOp       getter;
2314     JSStrictPropertyOp setter;
2315     jsval              value;
2316     uintN              shortid;
2317 };
2318
2319 /*
2320  * Like JS_GetPropertyAttrsGetterAndSetterById but will return a property on
2321  * an object on the prototype chain (returned in objp). If data->obj is null,
2322  * then this property was not found on the prototype chain.
2323  */
2324 extern JS_PUBLIC_API(JSBool)
2325 JS_GetPropertyDescriptorById(JSContext *cx, JSObject *obj, jsid id, uintN flags,
2326                              JSPropertyDescriptor *desc);
2327
2328 extern JS_PUBLIC_API(JSBool)
2329 JS_GetOwnPropertyDescriptor(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
2330
2331 extern JS_PUBLIC_API(JSBool)
2332 JS_GetProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp);
2333
2334 extern JS_PUBLIC_API(JSBool)
2335 JS_GetPropertyDefault(JSContext *cx, JSObject *obj, const char *name, jsval def, jsval *vp);
2336
2337 extern JS_PUBLIC_API(JSBool)
2338 JS_GetPropertyById(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
2339
2340 extern JS_PUBLIC_API(JSBool)
2341 JS_GetPropertyByIdDefault(JSContext *cx, JSObject *obj, jsid id, jsval def, jsval *vp);
2342
2343 extern JS_PUBLIC_API(JSBool)
2344 JS_GetMethodById(JSContext *cx, JSObject *obj, jsid id, JSObject **objp,
2345                  jsval *vp);
2346
2347 extern JS_PUBLIC_API(JSBool)
2348 JS_GetMethod(JSContext *cx, JSObject *obj, const char *name, JSObject **objp,
2349              jsval *vp);
2350
2351 extern JS_PUBLIC_API(JSBool)
2352 JS_SetProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp);
2353
2354 extern JS_PUBLIC_API(JSBool)
2355 JS_SetPropertyById(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
2356
2357 extern JS_PUBLIC_API(JSBool)
2358 JS_DeleteProperty(JSContext *cx, JSObject *obj, const char *name);
2359
2360 extern JS_PUBLIC_API(JSBool)
2361 JS_DeleteProperty2(JSContext *cx, JSObject *obj, const char *name,
2362                    jsval *rval);
2363
2364 extern JS_PUBLIC_API(JSBool)
2365 JS_DeletePropertyById(JSContext *cx, JSObject *obj, jsid id);
2366
2367 extern JS_PUBLIC_API(JSBool)
2368 JS_DeletePropertyById2(JSContext *cx, JSObject *obj, jsid id, jsval *rval);
2369
2370 extern JS_PUBLIC_API(JSBool)
2371 JS_DefineUCProperty(JSContext *cx, JSObject *obj,
2372                     const jschar *name, size_t namelen, jsval value,
2373                     JSPropertyOp getter, JSStrictPropertyOp setter,
2374                     uintN attrs);
2375
2376 /*
2377  * Determine the attributes (JSPROP_* flags) of a property on a given object.
2378  *
2379  * If the object does not have a property by that name, *foundp will be
2380  * JS_FALSE and the value of *attrsp is undefined.
2381  */
2382 extern JS_PUBLIC_API(JSBool)
2383 JS_GetUCPropertyAttributes(JSContext *cx, JSObject *obj,
2384                            const jschar *name, size_t namelen,
2385                            uintN *attrsp, JSBool *foundp);
2386
2387 /*
2388  * The same, but if the property is native, return its getter and setter via
2389  * *getterp and *setterp, respectively (and only if the out parameter pointer
2390  * is not null).
2391  */
2392 extern JS_PUBLIC_API(JSBool)
2393 JS_GetUCPropertyAttrsGetterAndSetter(JSContext *cx, JSObject *obj,
2394                                      const jschar *name, size_t namelen,
2395                                      uintN *attrsp, JSBool *foundp,
2396                                      JSPropertyOp *getterp,
2397                                      JSStrictPropertyOp *setterp);
2398
2399 /*
2400  * Set the attributes of a property on a given object.
2401  *
2402  * If the object does not have a property by that name, *foundp will be
2403  * JS_FALSE and nothing will be altered.
2404  */
2405 extern JS_PUBLIC_API(JSBool)
2406 JS_SetUCPropertyAttributes(JSContext *cx, JSObject *obj,
2407                            const jschar *name, size_t namelen,
2408                            uintN attrs, JSBool *foundp);
2409
2410
2411 extern JS_PUBLIC_API(JSBool)
2412 JS_DefineUCPropertyWithTinyId(JSContext *cx, JSObject *obj,
2413                               const jschar *name, size_t namelen,
2414                               int8 tinyid, jsval value,
2415                               JSPropertyOp getter, JSStrictPropertyOp setter,
2416                               uintN attrs);
2417
2418 extern JS_PUBLIC_API(JSBool)
2419 JS_AlreadyHasOwnUCProperty(JSContext *cx, JSObject *obj, const jschar *name,
2420                            size_t namelen, JSBool *foundp);
2421
2422 extern JS_PUBLIC_API(JSBool)
2423 JS_HasUCProperty(JSContext *cx, JSObject *obj,
2424                  const jschar *name, size_t namelen,
2425                  JSBool *vp);
2426
2427 extern JS_PUBLIC_API(JSBool)
2428 JS_LookupUCProperty(JSContext *cx, JSObject *obj,
2429                     const jschar *name, size_t namelen,
2430                     jsval *vp);
2431
2432 extern JS_PUBLIC_API(JSBool)
2433 JS_GetUCProperty(JSContext *cx, JSObject *obj,
2434                  const jschar *name, size_t namelen,
2435                  jsval *vp);
2436
2437 extern JS_PUBLIC_API(JSBool)
2438 JS_SetUCProperty(JSContext *cx, JSObject *obj,
2439                  const jschar *name, size_t namelen,
2440                  jsval *vp);
2441
2442 extern JS_PUBLIC_API(JSBool)
2443 JS_DeleteUCProperty2(JSContext *cx, JSObject *obj,
2444                      const jschar *name, size_t namelen,
2445                      jsval *rval);
2446
2447 extern JS_PUBLIC_API(JSObject *)
2448 JS_NewArrayObject(JSContext *cx, jsint length, jsval *vector);
2449
2450 extern JS_PUBLIC_API(JSBool)
2451 JS_IsArrayObject(JSContext *cx, JSObject *obj);
2452
2453 extern JS_PUBLIC_API(JSBool)
2454 JS_GetArrayLength(JSContext *cx, JSObject *obj, jsuint *lengthp);
2455
2456 extern JS_PUBLIC_API(JSBool)
2457 JS_SetArrayLength(JSContext *cx, JSObject *obj, jsuint length);
2458
2459 extern JS_PUBLIC_API(JSBool)
2460 JS_HasArrayLength(JSContext *cx, JSObject *obj, jsuint *lengthp);
2461
2462 extern JS_PUBLIC_API(JSBool)
2463 JS_DefineElement(JSContext *cx, JSObject *obj, jsint index, jsval value,
2464                  JSPropertyOp getter, JSStrictPropertyOp setter, uintN attrs);
2465
2466 extern JS_PUBLIC_API(JSBool)
2467 JS_AliasElement(JSContext *cx, JSObject *obj, const char *name, jsint alias);
2468
2469 extern JS_PUBLIC_API(JSBool)
2470 JS_AlreadyHasOwnElement(JSContext *cx, JSObject *obj, jsint index,
2471                         JSBool *foundp);
2472
2473 extern JS_PUBLIC_API(JSBool)
2474 JS_HasElement(JSContext *cx, JSObject *obj, jsint index, JSBool *foundp);
2475
2476 extern JS_PUBLIC_API(JSBool)
2477 JS_LookupElement(JSContext *cx, JSObject *obj, jsint index, jsval *vp);
2478
2479 extern JS_PUBLIC_API(JSBool)
2480 JS_GetElement(JSContext *cx, JSObject *obj, jsint index, jsval *vp);
2481
2482 extern JS_PUBLIC_API(JSBool)
2483 JS_SetElement(JSContext *cx, JSObject *obj, jsint index, jsval *vp);
2484
2485 extern JS_PUBLIC_API(JSBool)
2486 JS_DeleteElement(JSContext *cx, JSObject *obj, jsint index);
2487
2488 extern JS_PUBLIC_API(JSBool)
2489 JS_DeleteElement2(JSContext *cx, JSObject *obj, jsint index, jsval *rval);
2490
2491 extern JS_PUBLIC_API(void)
2492 JS_ClearScope(JSContext *cx, JSObject *obj);
2493
2494 extern JS_PUBLIC_API(JSIdArray *)
2495 JS_Enumerate(JSContext *cx, JSObject *obj);
2496
2497 /*
2498  * Create an object to iterate over enumerable properties of obj, in arbitrary
2499  * property definition order.  NB: This differs from longstanding for..in loop
2500  * order, which uses order of property definition in obj.
2501  */
2502 extern JS_PUBLIC_API(JSObject *)
2503 JS_NewPropertyIterator(JSContext *cx, JSObject *obj);
2504
2505 /*
2506  * Return true on success with *idp containing the id of the next enumerable
2507  * property to visit using iterobj, or JSID_IS_VOID if there is no such property
2508  * left to visit.  Return false on error.
2509  */
2510 extern JS_PUBLIC_API(JSBool)
2511 JS_NextProperty(JSContext *cx, JSObject *iterobj, jsid *idp);
2512
2513 extern JS_PUBLIC_API(JSBool)
2514 JS_CheckAccess(JSContext *cx, JSObject *obj, jsid id, JSAccessMode mode,
2515                jsval *vp, uintN *attrsp);
2516
2517 extern JS_PUBLIC_API(JSBool)
2518 JS_GetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, jsval *vp);
2519
2520 extern JS_PUBLIC_API(JSBool)
2521 JS_SetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, jsval v);
2522
2523 /************************************************************************/
2524
2525 /*
2526  * Security protocol.
2527  */
2528 struct JSPrincipals {
2529     char *codebase;
2530
2531     /* XXX unspecified and unused by Mozilla code -- can we remove these? */
2532     void * (* getPrincipalArray)(JSContext *cx, JSPrincipals *);
2533     JSBool (* globalPrivilegesEnabled)(JSContext *cx, JSPrincipals *);
2534
2535     /* Don't call "destroy"; use reference counting macros below. */
2536     jsrefcount refcount;
2537
2538     void   (* destroy)(JSContext *cx, JSPrincipals *);
2539     JSBool (* subsume)(JSPrincipals *, JSPrincipals *);
2540 };
2541
2542 #ifdef JS_THREADSAFE
2543 #define JSPRINCIPALS_HOLD(cx, principals)   JS_HoldPrincipals(cx,principals)
2544 #define JSPRINCIPALS_DROP(cx, principals)   JS_DropPrincipals(cx,principals)
2545
2546 extern JS_PUBLIC_API(jsrefcount)
2547 JS_HoldPrincipals(JSContext *cx, JSPrincipals *principals);
2548
2549 extern JS_PUBLIC_API(jsrefcount)
2550 JS_DropPrincipals(JSContext *cx, JSPrincipals *principals);
2551
2552 #else
2553 #define JSPRINCIPALS_HOLD(cx, principals)   (++(principals)->refcount)
2554 #define JSPRINCIPALS_DROP(cx, principals)                                     \
2555     ((--(principals)->refcount == 0)                                          \
2556      ? ((*(principals)->destroy)((cx), (principals)), 0)                      \
2557      : (principals)->refcount)
2558 #endif
2559
2560
2561 struct JSSecurityCallbacks {
2562     JSCheckAccessOp            checkObjectAccess;
2563     JSPrincipalsTranscoder     principalsTranscoder;
2564     JSObjectPrincipalsFinder   findObjectPrincipals;
2565     JSCSPEvalChecker           contentSecurityPolicyAllows;
2566 };
2567
2568 extern JS_PUBLIC_API(JSSecurityCallbacks *)
2569 JS_SetRuntimeSecurityCallbacks(JSRuntime *rt, JSSecurityCallbacks *callbacks);
2570
2571 extern JS_PUBLIC_API(JSSecurityCallbacks *)
2572 JS_GetRuntimeSecurityCallbacks(JSRuntime *rt);
2573
2574 extern JS_PUBLIC_API(JSSecurityCallbacks *)
2575 JS_SetContextSecurityCallbacks(JSContext *cx, JSSecurityCallbacks *callbacks);
2576
2577 extern JS_PUBLIC_API(JSSecurityCallbacks *)
2578 JS_GetSecurityCallbacks(JSContext *cx);
2579
2580 /************************************************************************/
2581
2582 /*
2583  * Functions and scripts.
2584  */
2585 extern JS_PUBLIC_API(JSFunction *)
2586 JS_NewFunction(JSContext *cx, JSNative call, uintN nargs, uintN flags,
2587                JSObject *parent, const char *name);
2588
2589 /*
2590  * Create the function with the name given by the id. JSID_IS_STRING(id) must
2591  * be true.
2592  */
2593 extern JS_PUBLIC_API(JSFunction *)
2594 JS_NewFunctionById(JSContext *cx, JSNative call, uintN nargs, uintN flags,
2595                    JSObject *parent, jsid id);
2596
2597 extern JS_PUBLIC_API(JSObject *)
2598 JS_GetFunctionObject(JSFunction *fun);
2599
2600 /*
2601  * Return the function's identifier as a JSString, or null if fun is unnamed.
2602  * The returned string lives as long as fun, so you don't need to root a saved
2603  * reference to it if fun is well-connected or rooted, and provided you bound
2604  * the use of the saved reference by fun's lifetime.
2605  */
2606 extern JS_PUBLIC_API(JSString *)
2607 JS_GetFunctionId(JSFunction *fun);
2608
2609 /*
2610  * Return JSFUN_* flags for fun.
2611  */
2612 extern JS_PUBLIC_API(uintN)
2613 JS_GetFunctionFlags(JSFunction *fun);
2614
2615 /*
2616  * Return the arity (length) of fun.
2617  */
2618 extern JS_PUBLIC_API(uint16)
2619 JS_GetFunctionArity(JSFunction *fun);
2620
2621 /*
2622  * Infallible predicate to test whether obj is a function object (faster than
2623  * comparing obj's class name to "Function", but equivalent unless someone has
2624  * overwritten the "Function" identifier with a different constructor and then
2625  * created instances using that constructor that might be passed in as obj).
2626  */
2627 extern JS_PUBLIC_API(JSBool)
2628 JS_ObjectIsFunction(JSContext *cx, JSObject *obj);
2629
2630 extern JS_PUBLIC_API(JSBool)
2631 JS_ObjectIsCallable(JSContext *cx, JSObject *obj);
2632
2633 extern JS_PUBLIC_API(JSBool)
2634 JS_DefineFunctions(JSContext *cx, JSObject *obj, JSFunctionSpec *fs);
2635
2636 extern JS_PUBLIC_API(JSFunction *)
2637 JS_DefineFunction(JSContext *cx, JSObject *obj, const char *name, JSNative call,
2638                   uintN nargs, uintN attrs);
2639
2640 extern JS_PUBLIC_API(JSFunction *)
2641 JS_DefineUCFunction(JSContext *cx, JSObject *obj,
2642                     const jschar *name, size_t namelen, JSNative call,
2643                     uintN nargs, uintN attrs);
2644
2645 extern JS_PUBLIC_API(JSFunction *)
2646 JS_DefineFunctionById(JSContext *cx, JSObject *obj, jsid id, JSNative call,
2647                       uintN nargs, uintN attrs);
2648
2649 extern JS_PUBLIC_API(JSObject *)
2650 JS_CloneFunctionObject(JSContext *cx, JSObject *funobj, JSObject *parent);
2651
2652 /*
2653  * Given a buffer, return JS_FALSE if the buffer might become a valid
2654  * javascript statement with the addition of more lines.  Otherwise return
2655  * JS_TRUE.  The intent is to support interactive compilation - accumulate
2656  * lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to
2657  * the compiler.
2658  */
2659 extern JS_PUBLIC_API(JSBool)
2660 JS_BufferIsCompilableUnit(JSContext *cx, JSObject *obj,
2661                           const char *bytes, size_t length);
2662
2663 extern JS_PUBLIC_API(JSObject *)
2664 JS_CompileScript(JSContext *cx, JSObject *obj,
2665                  const char *bytes, size_t length,
2666                  const char *filename, uintN lineno);
2667
2668 extern JS_PUBLIC_API(JSObject *)
2669 JS_CompileScriptForPrincipals(JSContext *cx, JSObject *obj,
2670                               JSPrincipals *principals,
2671                               const char *bytes, size_t length,
2672                               const char *filename, uintN lineno);
2673
2674 extern JS_PUBLIC_API(JSObject *)
2675 JS_CompileScriptForPrincipalsVersion(JSContext *cx, JSObject *obj,
2676                                      JSPrincipals *principals,
2677                                      const char *bytes, size_t length,
2678                                      const char *filename, uintN lineno,
2679                                      JSVersion version);
2680
2681 extern JS_PUBLIC_API(JSObject *)
2682 JS_CompileUCScript(JSContext *cx, JSObject *obj,
2683                    const jschar *chars, size_t length,
2684                    const char *filename, uintN lineno);
2685
2686 extern JS_PUBLIC_API(JSObject *)
2687 JS_CompileUCScriptForPrincipals(JSContext *cx, JSObject *obj,
2688                                 JSPrincipals *principals,
2689                                 const jschar *chars, size_t length,
2690                                 const char *filename, uintN lineno);
2691
2692 extern JS_PUBLIC_API(JSObject *)
2693 JS_CompileUCScriptForPrincipalsVersion(JSContext *cx, JSObject *obj,
2694                                        JSPrincipals *principals,
2695                                        const jschar *chars, size_t length,
2696                                        const char *filename, uintN lineno,
2697                                        JSVersion version);
2698
2699 extern JS_PUBLIC_API(JSObject *)
2700 JS_CompileFile(JSContext *cx, JSObject *obj, const char *filename);
2701
2702 extern JS_PUBLIC_API(JSObject *)
2703 JS_CompileFileHandle(JSContext *cx, JSObject *obj, const char *filename,
2704                      FILE *fh);
2705
2706 extern JS_PUBLIC_API(JSObject *)
2707 JS_CompileFileHandleForPrincipals(JSContext *cx, JSObject *obj,
2708                                   const char *filename, FILE *fh,
2709                                   JSPrincipals *principals);
2710
2711 extern JS_PUBLIC_API(JSObject *)
2712 JS_CompileFileHandleForPrincipalsVersion(JSContext *cx, JSObject *obj,
2713                                          const char *filename, FILE *fh,
2714                                          JSPrincipals *principals,
2715                                          JSVersion version);
2716
2717 extern JS_PUBLIC_API(JSFunction *)
2718 JS_CompileFunction(JSContext *cx, JSObject *obj, const char *name,
2719                    uintN nargs, const char **argnames,
2720                    const char *bytes, size_t length,
2721                    const char *filename, uintN lineno);
2722
2723 extern JS_PUBLIC_API(JSFunction *)
2724 JS_CompileFunctionForPrincipals(JSContext *cx, JSObject *obj,
2725                                 JSPrincipals *principals, const char *name,
2726                                 uintN nargs, const char **argnames,
2727                                 const char *bytes, size_t length,
2728                                 const char *filename, uintN lineno);
2729
2730 extern JS_PUBLIC_API(JSFunction *)
2731 JS_CompileUCFunction(JSContext *cx, JSObject *obj, const char *name,
2732                      uintN nargs, const char **argnames,
2733                      const jschar *chars, size_t length,
2734                      const char *filename, uintN lineno);
2735
2736 extern JS_PUBLIC_API(JSFunction *)
2737 JS_CompileUCFunctionForPrincipals(JSContext *cx, JSObject *obj,
2738                                   JSPrincipals *principals, const char *name,
2739                                   uintN nargs, const char **argnames,
2740                                   const jschar *chars, size_t length,
2741                                   const char *filename, uintN lineno);
2742
2743 extern JS_PUBLIC_API(JSFunction *)
2744 JS_CompileUCFunctionForPrincipalsVersion(JSContext *cx, JSObject *obj,
2745                                          JSPrincipals *principals, const char *name,
2746                                          uintN nargs, const char **argnames,
2747                                          const jschar *chars, size_t length,
2748                                          const char *filename, uintN lineno,
2749                                          JSVersion version);
2750
2751 extern JS_PUBLIC_API(JSString *)
2752 JS_DecompileScriptObject(JSContext *cx, JSObject *scriptObj, const char *name, uintN indent);
2753
2754 /*
2755  * API extension: OR this into indent to avoid pretty-printing the decompiled
2756  * source resulting from JS_DecompileFunction{,Body}.
2757  */
2758 #define JS_DONT_PRETTY_PRINT    ((uintN)0x8000)
2759
2760 extern JS_PUBLIC_API(JSString *)
2761 JS_DecompileFunction(JSContext *cx, JSFunction *fun, uintN indent);
2762
2763 extern JS_PUBLIC_API(JSString *)
2764 JS_DecompileFunctionBody(JSContext *cx, JSFunction *fun, uintN indent);
2765
2766 /*
2767  * NB: JS_ExecuteScript and the JS_Evaluate*Script* quadruplets use the obj
2768  * parameter as the initial scope chain header, the 'this' keyword value, and
2769  * the variables object (ECMA parlance for where 'var' and 'function' bind
2770  * names) of the execution context for script.
2771  *
2772  * Using obj as the variables object is problematic if obj's parent (which is
2773  * the scope chain link; see JS_SetParent and JS_NewObject) is not null: in
2774  * this case, variables created by 'var x = 0', e.g., go in obj, but variables
2775  * created by assignment to an unbound id, 'x = 0', go in the last object on
2776  * the scope chain linked by parent.
2777  *
2778  * ECMA calls that last scoping object the "global object", but note that many
2779  * embeddings have several such objects.  ECMA requires that "global code" be
2780  * executed with the variables object equal to this global object.  But these
2781  * JS API entry points provide freedom to execute code against a "sub-global",
2782  * i.e., a parented or scoped object, in which case the variables object will
2783  * differ from the last object on the scope chain, resulting in confusing and
2784  * non-ECMA explicit vs. implicit variable creation.
2785  *
2786  * Caveat embedders: unless you already depend on this buggy variables object
2787  * binding behavior, you should call JS_SetOptions(cx, JSOPTION_VAROBJFIX) or
2788  * JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_VAROBJFIX) -- the latter if
2789  * someone may have set other options on cx already -- for each context in the
2790  * application, if you pass parented objects as the obj parameter, or may ever
2791  * pass such objects in the future.
2792  *
2793  * Why a runtime option?  The alternative is to add six or so new API entry
2794  * points with signatures matching the following six, and that doesn't seem
2795  * worth the code bloat cost.  Such new entry points would probably have less
2796  * obvious names, too, so would not tend to be used.  The JS_SetOption call,
2797  * OTOH, can be more easily hacked into existing code that does not depend on
2798  * the bug; such code can continue to use the familiar JS_EvaluateScript,
2799  * etc., entry points.
2800  */
2801 extern JS_PUBLIC_API(JSBool)
2802 JS_ExecuteScript(JSContext *cx, JSObject *obj, JSObject *scriptObj, jsval *rval);
2803
2804 extern JS_PUBLIC_API(JSBool)
2805 JS_ExecuteScriptVersion(JSContext *cx, JSObject *obj, JSObject *scriptObj, jsval *rval,
2806                         JSVersion version);
2807
2808 /*
2809  * Execute either the function-defining prolog of a script, or the script's
2810  * main body, but not both.
2811  */
2812 typedef enum JSExecPart { JSEXEC_PROLOG, JSEXEC_MAIN } JSExecPart;
2813
2814 extern JS_PUBLIC_API(JSBool)
2815 JS_EvaluateScript(JSContext *cx, JSObject *obj,
2816                   const char *bytes, uintN length,
2817                   const char *filename, uintN lineno,
2818                   jsval *rval);
2819
2820 extern JS_PUBLIC_API(JSBool)
2821 JS_EvaluateScriptForPrincipals(JSContext *cx, JSObject *obj,
2822                                JSPrincipals *principals,
2823                                const char *bytes, uintN length,
2824                                const char *filename, uintN lineno,
2825                                jsval *rval);
2826
2827 extern JS_PUBLIC_API(JSBool)
2828 JS_EvaluateScriptForPrincipalsVersion(JSContext *cx, JSObject *obj,
2829                                       JSPrincipals *principals,
2830                                       const char *bytes, uintN length,
2831                                       const char *filename, uintN lineno,
2832                                       jsval *rval, JSVersion version);
2833
2834 extern JS_PUBLIC_API(JSBool)
2835 JS_EvaluateUCScript(JSContext *cx, JSObject *obj,
2836                     const jschar *chars, uintN length,
2837                     const char *filename, uintN lineno,
2838                     jsval *rval);
2839
2840 extern JS_PUBLIC_API(JSBool)
2841 JS_EvaluateUCScriptForPrincipalsVersion(JSContext *cx, JSObject *obj,
2842                                         JSPrincipals *principals,
2843                                         const jschar *chars, uintN length,
2844                                         const char *filename, uintN lineno,
2845                                         jsval *rval, JSVersion version);
2846
2847 extern JS_PUBLIC_API(JSBool)
2848 JS_EvaluateUCScriptForPrincipals(JSContext *cx, JSObject *obj,
2849                                  JSPrincipals *principals,
2850                                  const jschar *chars, uintN length,
2851                                  const char *filename, uintN lineno,
2852                                  jsval *rval);
2853
2854 extern JS_PUBLIC_API(JSBool)
2855 JS_CallFunction(JSContext *cx, JSObject *obj, JSFunction *fun, uintN argc,
2856                 jsval *argv, jsval *rval);
2857
2858 extern JS_PUBLIC_API(JSBool)
2859 JS_CallFunctionName(JSContext *cx, JSObject *obj, const char *name, uintN argc,
2860                     jsval *argv, jsval *rval);
2861
2862 extern JS_PUBLIC_API(JSBool)
2863 JS_CallFunctionValue(JSContext *cx, JSObject *obj, jsval fval, uintN argc,
2864                      jsval *argv, jsval *rval);
2865
2866 #ifdef __cplusplus
2867 JS_END_EXTERN_C
2868
2869 namespace JS {
2870
2871 static inline bool
2872 Call(JSContext *cx, JSObject *thisObj, JSFunction *fun, uintN argc, jsval *argv, jsval *rval) {
2873     return !!JS_CallFunction(cx, thisObj, fun, argc, argv, rval);
2874 }
2875
2876 static inline bool
2877 Call(JSContext *cx, JSObject *thisObj, const char *name, uintN argc, jsval *argv, jsval *rval) {
2878     return !!JS_CallFunctionName(cx, thisObj, name, argc, argv, rval);
2879 }
2880
2881 static inline bool
2882 Call(JSContext *cx, JSObject *thisObj, jsval fun, uintN argc, jsval *argv, jsval *rval) {
2883     return !!JS_CallFunctionValue(cx, thisObj, fun, argc, argv, rval);
2884 }
2885
2886 extern JS_PUBLIC_API(bool)
2887 Call(JSContext *cx, jsval thisv, jsval fun, uintN argc, jsval *argv, jsval *rval);
2888
2889 static inline bool
2890 Call(JSContext *cx, jsval thisv, JSObject *funObj, uintN argc, jsval *argv, jsval *rval) {
2891     return Call(cx, thisv, OBJECT_TO_JSVAL(funObj), argc, argv, rval);
2892 }
2893
2894 } /* namespace js */
2895
2896 JS_BEGIN_EXTERN_C
2897 #endif /* __cplusplus */
2898
2899 /*
2900  * These functions allow setting an operation callback that will be called
2901  * from the thread the context is associated with some time after any thread
2902  * triggered the callback using JS_TriggerOperationCallback(cx).
2903  *
2904  * In a threadsafe build the engine internally triggers operation callbacks
2905  * under certain circumstances (i.e. GC and title transfer) to force the
2906  * context to yield its current request, which the engine always
2907  * automatically does immediately prior to calling the callback function.
2908  * The embedding should thus not rely on callbacks being triggered through
2909  * the external API only.
2910  *
2911  * Important note: Additional callbacks can occur inside the callback handler
2912  * if it re-enters the JS engine. The embedding must ensure that the callback
2913  * is disconnected before attempting such re-entry.
2914  */
2915
2916 extern JS_PUBLIC_API(JSOperationCallback)
2917 JS_SetOperationCallback(JSContext *cx, JSOperationCallback callback);
2918
2919 extern JS_PUBLIC_API(JSOperationCallback)
2920 JS_GetOperationCallback(JSContext *cx);
2921
2922 extern JS_PUBLIC_API(void)
2923 JS_TriggerOperationCallback(JSContext *cx);
2924
2925 extern JS_PUBLIC_API(void)
2926 JS_TriggerAllOperationCallbacks(JSRuntime *rt);
2927
2928 extern JS_PUBLIC_API(JSBool)
2929 JS_IsRunning(JSContext *cx);
2930
2931 /*
2932  * Saving and restoring frame chains.
2933  *
2934  * These two functions are used to set aside cx's call stack while that stack
2935  * is inactive. After a call to JS_SaveFrameChain, it looks as if there is no
2936  * code running on cx. Before calling JS_RestoreFrameChain, cx's call stack
2937  * must be balanced and all nested calls to JS_SaveFrameChain must have had
2938  * matching JS_RestoreFrameChain calls.
2939  *
2940  * JS_SaveFrameChain deals with cx not having any code running on it. A null
2941  * return does not signify an error, and JS_RestoreFrameChain handles a null
2942  * frame pointer argument safely.
2943  */
2944 extern JS_PUBLIC_API(JSStackFrame *)
2945 JS_SaveFrameChain(JSContext *cx);
2946
2947 extern JS_PUBLIC_API(void)
2948 JS_RestoreFrameChain(JSContext *cx, JSStackFrame *fp);
2949
2950 /************************************************************************/
2951
2952 /*
2953  * Strings.
2954  *
2955  * NB: JS_NewUCString takes ownership of bytes on success, avoiding a copy;
2956  * but on error (signified by null return), it leaves chars owned by the
2957  * caller. So the caller must free bytes in the error case, if it has no use
2958  * for them. In contrast, all the JS_New*StringCopy* functions do not take
2959  * ownership of the character memory passed to them -- they copy it.
2960  */
2961 extern JS_PUBLIC_API(JSString *)
2962 JS_NewStringCopyN(JSContext *cx, const char *s, size_t n);
2963
2964 extern JS_PUBLIC_API(JSString *)
2965 JS_NewStringCopyZ(JSContext *cx, const char *s);
2966
2967 extern JS_PUBLIC_API(JSString *)
2968 JS_InternJSString(JSContext *cx, JSString *str);
2969
2970 extern JS_PUBLIC_API(JSString *)
2971 JS_InternString(JSContext *cx, const char *s);
2972
2973 extern JS_PUBLIC_API(JSString *)
2974 JS_NewUCString(JSContext *cx, jschar *chars, size_t length);
2975
2976 extern JS_PUBLIC_API(JSString *)
2977 JS_NewUCStringCopyN(JSContext *cx, const jschar *s, size_t n);
2978
2979 extern JS_PUBLIC_API(JSString *)
2980 JS_NewUCStringCopyZ(JSContext *cx, const jschar *s);
2981
2982 extern JS_PUBLIC_API(JSString *)
2983 JS_InternUCStringN(JSContext *cx, const jschar *s, size_t length);
2984
2985 extern JS_PUBLIC_API(JSString *)
2986 JS_InternUCString(JSContext *cx, const jschar *s);
2987
2988 extern JS_PUBLIC_API(JSBool)
2989 JS_CompareStrings(JSContext *cx, JSString *str1, JSString *str2, int32 *result);
2990
2991 extern JS_PUBLIC_API(JSBool)
2992 JS_StringEqualsAscii(JSContext *cx, JSString *str, const char *asciiBytes, JSBool *match);
2993
2994 extern JS_PUBLIC_API(size_t)
2995 JS_PutEscapedString(JSContext *cx, char *buffer, size_t size, JSString *str, char quote);
2996
2997 extern JS_PUBLIC_API(JSBool)
2998 JS_FileEscapedString(FILE *fp, JSString *str, char quote);
2999
3000 /*
3001  * Extracting string characters and length.
3002  *
3003  * While getting the length of a string is infallible, getting the chars can
3004  * fail. As indicated by the lack of a JSContext parameter, there are two
3005  * special cases where getting the chars is infallible:
3006  *
3007  * The first case is interned strings, i.e., strings from JS_InternString or
3008  * JSID_TO_STRING(id), using JS_GetInternedStringChars*.
3009  *
3010  * The second case is "flat" strings that have been explicitly prepared in a
3011  * fallible context by JS_FlattenString. To catch errors, a separate opaque
3012  * JSFlatString type is returned by JS_FlattenString and expected by
3013  * JS_GetFlatStringChars. Note, though, that this is purely a syntactic
3014  * distinction: the input and output of JS_FlattenString are the same actual
3015  * GC-thing so only one needs to be rooted. If a JSString is known to be flat,
3016  * JS_ASSERT_STRING_IS_FLAT can be used to make a debug-checked cast. Example:
3017  *
3018  *   // in a fallible context
3019  *   JSFlatString *fstr = JS_FlattenString(cx, str);
3020  *   if (!fstr)
3021  *     return JS_FALSE;
3022  *   JS_ASSERT(fstr == JS_ASSERT_STRING_IS_FLAT(str));
3023  *
3024  *   // in an infallible context, for the same 'str'
3025  *   const jschar *chars = JS_GetFlatStringChars(fstr)
3026  *   JS_ASSERT(chars);
3027  *
3028  * The CharsZ APIs guarantee that the returned array has a null character at
3029  * chars[length]. This can require additional copying so clients should prefer
3030  * APIs without CharsZ if possible. The infallible functions also return
3031  * null-terminated arrays. (There is no additional cost or non-Z alternative
3032  * for the infallible functions, so 'Z' is left out of the identifier.)
3033  */
3034
3035 extern JS_PUBLIC_API(size_t)
3036 JS_GetStringLength(JSString *str);
3037
3038 extern JS_PUBLIC_API(const jschar *)
3039 JS_GetStringCharsAndLength(JSContext *cx, JSString *str, size_t *length);
3040
3041 extern JS_PUBLIC_API(const jschar *)
3042 JS_GetInternedStringChars(JSString *str);
3043
3044 extern JS_PUBLIC_API(const jschar *)
3045 JS_GetInternedStringCharsAndLength(JSString *str, size_t *length);
3046
3047 extern JS_PUBLIC_API(const jschar *)
3048 JS_GetStringCharsZ(JSContext *cx, JSString *str);
3049
3050 extern JS_PUBLIC_API(const jschar *)
3051 JS_GetStringCharsZAndLength(JSContext *cx, JSString *str, size_t *length);
3052
3053 extern JS_PUBLIC_API(JSFlatString *)
3054 JS_FlattenString(JSContext *cx, JSString *str);
3055
3056 extern JS_PUBLIC_API(const jschar *)
3057 JS_GetFlatStringChars(JSFlatString *str);
3058
3059 static JS_ALWAYS_INLINE JSFlatString *
3060 JSID_TO_FLAT_STRING(jsid id)
3061 {
3062     JS_ASSERT(JSID_IS_STRING(id));
3063     return (JSFlatString *)(JSID_BITS(id));
3064 }
3065
3066 static JS_ALWAYS_INLINE JSFlatString *
3067 JS_ASSERT_STRING_IS_FLAT(JSString *str)
3068 {
3069     JS_ASSERT(JS_GetFlatStringChars((JSFlatString *)str));
3070     return (JSFlatString *)str;
3071 }
3072
3073 static JS_ALWAYS_INLINE JSString *
3074 JS_FORGET_STRING_FLATNESS(JSFlatString *fstr)
3075 {
3076     return (JSString *)fstr;
3077 }
3078
3079 /*
3080  * Additional APIs that avoid fallibility when given a flat string.
3081  */
3082
3083 extern JS_PUBLIC_API(JSBool)
3084 JS_FlatStringEqualsAscii(JSFlatString *str, const char *asciiBytes);
3085
3086 extern JS_PUBLIC_API(size_t)
3087 JS_PutEscapedFlatString(char *buffer, size_t size, JSFlatString *str, char quote);
3088
3089 /*
3090  * This function is now obsolete and behaves the same as JS_NewUCString.  Use
3091  * JS_NewUCString instead.
3092  */
3093 extern JS_PUBLIC_API(JSString *)
3094 JS_NewGrowableString(JSContext *cx, jschar *chars, size_t length);
3095
3096 /*
3097  * Mutable string support.  A string's characters are never mutable in this JS
3098  * implementation, but a dependent string is a substring of another dependent
3099  * or immutable string, and a rope is a lazily concatenated string that creates
3100  * its underlying buffer the first time it is accessed.  Even after a rope
3101  * creates its underlying buffer, it still considered mutable.  The direct data
3102  * members of the (opaque to API clients) JSString struct may be changed in a
3103  * single-threaded way for dependent strings and ropes.
3104  *
3105  * Therefore mutable strings (ropes and dependent strings) cannot be used by
3106  * more than one thread at a time.  You may call JS_MakeStringImmutable to
3107  * convert the string from a mutable string to an immutable (and therefore
3108  * thread-safe) string.  The engine takes care of converting ropes and dependent
3109  * strings to immutable for you if you store strings in multi-threaded objects
3110  * using JS_SetProperty or kindred API entry points.
3111  *
3112  * If you store a JSString pointer in a native data structure that is (safely)
3113  * accessible to multiple threads, you must call JS_MakeStringImmutable before
3114  * retiring the store.
3115  */
3116
3117 /*
3118  * Create a dependent string, i.e., a string that owns no character storage,
3119  * but that refers to a slice of another string's chars.  Dependent strings
3120  * are mutable by definition, so the thread safety comments above apply.
3121  */
3122 extern JS_PUBLIC_API(JSString *)
3123 JS_NewDependentString(JSContext *cx, JSString *str, size_t start,
3124                       size_t length);
3125
3126 /*
3127  * Concatenate two strings, possibly resulting in a rope.
3128  * See above for thread safety comments.
3129  */
3130 extern JS_PUBLIC_API(JSString *)
3131 JS_ConcatStrings(JSContext *cx, JSString *left, JSString *right);
3132
3133 /*
3134  * Convert a dependent string into an independent one.  This function does not
3135  * change the string's mutability, so the thread safety comments above apply.
3136  */
3137 extern JS_PUBLIC_API(const jschar *)
3138 JS_UndependString(JSContext *cx, JSString *str);
3139
3140 /*
3141  * Convert a mutable string (either rope or dependent) into an immutable,
3142  * thread-safe one.
3143  */
3144 extern JS_PUBLIC_API(JSBool)
3145 JS_MakeStringImmutable(JSContext *cx, JSString *str);
3146
3147 /*
3148  * Return JS_TRUE if C (char []) strings passed via the API and internally
3149  * are UTF-8.
3150  */
3151 JS_PUBLIC_API(JSBool)
3152 JS_CStringsAreUTF8(void);
3153
3154 /*
3155  * Update the value to be returned by JS_CStringsAreUTF8(). Once set, it
3156  * can never be changed. This API must be called before the first call to
3157  * JS_NewRuntime.
3158  */
3159 JS_PUBLIC_API(void)
3160 JS_SetCStringsAreUTF8(void);
3161
3162 /*
3163  * Character encoding support.
3164  *
3165  * For both JS_EncodeCharacters and JS_DecodeBytes, set *dstlenp to the size
3166  * of the destination buffer before the call; on return, *dstlenp contains the
3167  * number of bytes (JS_EncodeCharacters) or jschars (JS_DecodeBytes) actually
3168  * stored.  To determine the necessary destination buffer size, make a sizing
3169  * call that passes NULL for dst.
3170  *
3171  * On errors, the functions report the error. In that case, *dstlenp contains
3172  * the number of characters or bytes transferred so far.  If cx is NULL, no
3173  * error is reported on failure, and the functions simply return JS_FALSE.
3174  *
3175  * NB: Neither function stores an additional zero byte or jschar after the
3176  * transcoded string.
3177  *
3178  * If JS_CStringsAreUTF8() is true then JS_EncodeCharacters encodes to
3179  * UTF-8, and JS_DecodeBytes decodes from UTF-8, which may create additional
3180  * errors if the character sequence is malformed.  If UTF-8 support is
3181  * disabled, the functions deflate and inflate, respectively.
3182  */
3183 JS_PUBLIC_API(JSBool)
3184 JS_EncodeCharacters(JSContext *cx, const jschar *src, size_t srclen, char *dst,
3185                     size_t *dstlenp);
3186
3187 JS_PUBLIC_API(JSBool)
3188 JS_DecodeBytes(JSContext *cx, const char *src, size_t srclen, jschar *dst,
3189                size_t *dstlenp);
3190
3191 /*
3192  * A variation on JS_EncodeCharacters where a null terminated string is
3193  * returned that you are expected to call JS_free on when done.
3194  */
3195 JS_PUBLIC_API(char *)
3196 JS_EncodeString(JSContext *cx, JSString *str);
3197
3198 /*
3199  * Get number of bytes in the string encoding (without accounting for a
3200  * terminating zero bytes. The function returns (size_t) -1 if the string
3201  * can not be encoded into bytes and reports an error using cx accordingly.
3202  */
3203 JS_PUBLIC_API(size_t)
3204 JS_GetStringEncodingLength(JSContext *cx, JSString *str);
3205
3206 /*
3207  * Encode string into a buffer. The function does not stores an additional
3208  * zero byte. The function returns (size_t) -1 if the string can not be
3209  * encoded into bytes with no error reported. Otherwise it returns the number
3210  * of bytes that are necessary to encode the string. If that exceeds the
3211  * length parameter, the string will be cut and only length bytes will be
3212  * written into the buffer.
3213  *
3214  * If JS_CStringsAreUTF8() is true, the string does not fit into the buffer
3215  * and the the first length bytes ends in the middle of utf-8 encoding for
3216  * some character, then such partial utf-8 encoding is replaced by zero bytes.
3217  * This way the result always represents the valid UTF-8 sequence.
3218  */
3219 JS_PUBLIC_API(size_t)
3220 JS_EncodeStringToBuffer(JSString *str, char *buffer, size_t length);
3221
3222 #ifdef __cplusplus
3223
3224 class JSAutoByteString {
3225   public:
3226     JSAutoByteString(JSContext *cx, JSString *str JS_GUARD_OBJECT_NOTIFIER_PARAM)
3227       : mBytes(JS_EncodeString(cx, str)) {
3228         JS_ASSERT(cx);
3229         JS_GUARD_OBJECT_NOTIFIER_INIT;
3230     }
3231
3232     JSAutoByteString(JS_GUARD_OBJECT_NOTIFIER_PARAM0)
3233       : mBytes(NULL) {
3234         JS_GUARD_OBJECT_NOTIFIER_INIT;
3235     }
3236
3237     ~JSAutoByteString() {
3238         js_free(mBytes);
3239     }
3240
3241     /* Take ownership of the given byte array. */
3242     void initBytes(char *bytes) {
3243         JS_ASSERT(!mBytes);
3244         mBytes = bytes;
3245     }
3246
3247     char *encode(JSContext *cx, JSString *str) {
3248         JS_ASSERT(!mBytes);
3249         JS_ASSERT(cx);
3250         mBytes = JS_EncodeString(cx, str);
3251         return mBytes;
3252     }
3253
3254     void clear() {
3255         js_free(mBytes);
3256         mBytes = NULL;
3257     }
3258
3259     char *ptr() const {
3260         return mBytes;
3261     }
3262
3263     bool operator!() const {
3264         return !mBytes;
3265     }
3266
3267   private:
3268     char        *mBytes;
3269     JS_DECL_USE_GUARD_OBJECT_NOTIFIER
3270
3271     /* Copy and assignment are not supported. */
3272     JSAutoByteString(const JSAutoByteString &another);
3273     JSAutoByteString &operator=(const JSAutoByteString &another);
3274 };
3275
3276 #endif
3277
3278 /************************************************************************/
3279 /*
3280  * JSON functions
3281  */
3282 typedef JSBool (* JSONWriteCallback)(const jschar *buf, uint32 len, void *data);
3283
3284 /*
3285  * JSON.stringify as specified by ES3.1 (draft)
3286  */
3287 JS_PUBLIC_API(JSBool)
3288 JS_Stringify(JSContext *cx, jsval *vp, JSObject *replacer, jsval space,
3289              JSONWriteCallback callback, void *data);
3290
3291 /*
3292  * Retrieve a toJSON function. If found, set vp to its result.
3293  */
3294 JS_PUBLIC_API(JSBool)
3295 JS_TryJSON(JSContext *cx, jsval *vp);
3296
3297 /*
3298  * JSON.parse as specified by ES3.1 (draft)
3299  */
3300 JS_PUBLIC_API(JSONParser *)
3301 JS_BeginJSONParse(JSContext *cx, jsval *vp);
3302
3303 JS_PUBLIC_API(JSBool)
3304 JS_ConsumeJSONText(JSContext *cx, JSONParser *jp, const jschar *data, uint32 len);
3305
3306 JS_PUBLIC_API(JSBool)
3307 JS_FinishJSONParse(JSContext *cx, JSONParser *jp, jsval reviver);
3308
3309 /************************************************************************/
3310
3311 /* API for the HTML5 internal structured cloning algorithm. */
3312
3313 /* The maximum supported structured-clone serialization format version. */
3314 #define JS_STRUCTURED_CLONE_VERSION 1
3315
3316 struct JSStructuredCloneCallbacks {
3317     ReadStructuredCloneOp read;
3318     WriteStructuredCloneOp write;
3319     StructuredCloneErrorOp reportError;
3320 };
3321
3322 JS_PUBLIC_API(JSBool)
3323 JS_ReadStructuredClone(JSContext *cx, const uint64 *data, size_t nbytes,
3324                        uint32 version, jsval *vp,
3325                        const JSStructuredCloneCallbacks *optionalCallbacks,
3326                        void *closure);
3327
3328 /* Note: On success, the caller is responsible for calling js_free(*datap). */
3329 JS_PUBLIC_API(JSBool)
3330 JS_WriteStructuredClone(JSContext *cx, jsval v, uint64 **datap, size_t *nbytesp,
3331                         const JSStructuredCloneCallbacks *optionalCallbacks,
3332                         void *closure);
3333
3334 JS_PUBLIC_API(JSBool)
3335 JS_StructuredClone(JSContext *cx, jsval v, jsval *vp,
3336                    const JSStructuredCloneCallbacks *optionalCallbacks,
3337                    void *closure);
3338
3339 #ifdef __cplusplus
3340 /* RAII sugar for JS_WriteStructuredClone. */
3341 class JSAutoStructuredCloneBuffer {
3342     JSContext *cx_;
3343     uint64 *data_;
3344     size_t nbytes_;
3345     uint32 version_;
3346
3347   public:
3348     JSAutoStructuredCloneBuffer()
3349         : cx_(NULL), data_(NULL), nbytes_(0), version_(JS_STRUCTURED_CLONE_VERSION) {}
3350
3351     ~JSAutoStructuredCloneBuffer() { clear(); }
3352
3353     JSContext *cx() const { return cx_; }
3354     uint64 *data() const { return data_; }
3355     size_t nbytes() const { return nbytes_; }
3356
3357     void clear(JSContext *cx=NULL) {
3358         if (data_) {
3359             if (!cx)
3360                 cx = cx_;
3361             JS_ASSERT(cx);
3362             JS_free(cx, data_);
3363             cx_ = NULL;
3364             data_ = NULL;
3365             nbytes_ = 0;
3366             version_ = 0;
3367         }
3368     }
3369
3370     /*
3371      * Adopt some memory. It will be automatically freed by the destructor.
3372      * data must have been allocated using JS_malloc.
3373      */
3374     void adopt(JSContext *cx, uint64 *data, size_t nbytes,
3375                uint32 version=JS_STRUCTURED_CLONE_VERSION) {
3376         clear(cx);
3377         cx_ = cx;
3378         data_ = data;
3379         nbytes_ = nbytes;
3380         version_ = version;
3381     }
3382
3383     /*
3384      * Remove the buffer so that it will not be automatically freed.
3385      * After this, the caller is responsible for calling JS_free(*datap).
3386      */
3387     void steal(uint64 **datap, size_t *nbytesp, JSContext **cxp=NULL,
3388                uint32 *versionp=NULL) {
3389         *datap = data_;
3390         *nbytesp = nbytes_;
3391         if (cxp)
3392             *cxp = cx_;
3393         if (versionp)
3394             *versionp = version_;
3395
3396         cx_ = NULL;
3397         data_ = NULL;
3398         nbytes_ = 0;
3399         version_ = 0;
3400     }
3401
3402     bool read(jsval *vp, JSContext *cx=NULL,
3403               const JSStructuredCloneCallbacks *optionalCallbacks=NULL,
3404               void *closure=NULL) const {
3405         if (!cx)
3406             cx = cx_;
3407         JS_ASSERT(cx);
3408         JS_ASSERT(data_);
3409         return !!JS_ReadStructuredClone(cx, data_, nbytes_, version_, vp,
3410                                         optionalCallbacks, closure);
3411     }
3412
3413     bool write(JSContext *cx, jsval v,
3414                const JSStructuredCloneCallbacks *optionalCallbacks=NULL,
3415                void *closure=NULL) {
3416         clear(cx);
3417         cx_ = cx;
3418         bool ok = !!JS_WriteStructuredClone(cx, v, &data_, &nbytes_,
3419                                             optionalCallbacks, closure);
3420         if (!ok) {
3421             data_ = NULL;
3422             nbytes_ = 0;
3423             version_ = JS_STRUCTURED_CLONE_VERSION;
3424         }
3425         return ok;
3426     }
3427
3428     /**
3429      * Swap ownership with another JSAutoStructuredCloneBuffer.
3430      */
3431     void swap(JSAutoStructuredCloneBuffer &other) {
3432         JSContext *cx = other.cx_;
3433         uint64 *data = other.data_;
3434         size_t nbytes = other.nbytes_;
3435         uint32 version = other.version_;
3436
3437         other.cx_ = this->cx_;
3438         other.data_ = this->data_;
3439         other.nbytes_ = this->nbytes_;
3440         other.version_ = this->version_;
3441
3442         this->cx_ = cx;
3443         this->data_ = data;
3444         this->nbytes_ = nbytes;
3445         this->version_ = version;
3446     }
3447
3448   private:
3449     /* Copy and assignment are not supported. */
3450     JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer &other);
3451     JSAutoStructuredCloneBuffer &operator=(const JSAutoStructuredCloneBuffer &other);
3452 };
3453 #endif
3454
3455 /* API for implementing custom serialization behavior (for ImageData, File, etc.) */
3456
3457 /* The range of tag values the application may use for its own custom object types. */
3458 #define JS_SCTAG_USER_MIN  ((uint32) 0xFFFF8000)
3459 #define JS_SCTAG_USER_MAX  ((uint32) 0xFFFFFFFF)
3460
3461 #define JS_SCERR_RECURSION 0
3462
3463 JS_PUBLIC_API(void)
3464 JS_SetStructuredCloneCallbacks(JSRuntime *rt, const JSStructuredCloneCallbacks *callbacks);
3465
3466 JS_PUBLIC_API(JSBool)
3467 JS_ReadUint32Pair(JSStructuredCloneReader *r, uint32 *p1, uint32 *p2);
3468
3469 JS_PUBLIC_API(JSBool)
3470 JS_ReadBytes(JSStructuredCloneReader *r, void *p, size_t len);
3471
3472 JS_PUBLIC_API(JSBool)
3473 JS_WriteUint32Pair(JSStructuredCloneWriter *w, uint32 tag, uint32 data);
3474
3475 JS_PUBLIC_API(JSBool)
3476 JS_WriteBytes(JSStructuredCloneWriter *w, const void *p, size_t len);
3477
3478 /************************************************************************/
3479
3480 /*
3481  * Locale specific string conversion and error message callbacks.
3482  */
3483 struct JSLocaleCallbacks {
3484     JSLocaleToUpperCase     localeToUpperCase;
3485     JSLocaleToLowerCase     localeToLowerCase;
3486     JSLocaleCompare         localeCompare;
3487     JSLocaleToUnicode       localeToUnicode;
3488     JSErrorCallback         localeGetErrorMessage;
3489 };
3490
3491 /*
3492  * Establish locale callbacks. The pointer must persist as long as the
3493  * JSContext.  Passing NULL restores the default behaviour.
3494  */
3495 extern JS_PUBLIC_API(void)
3496 JS_SetLocaleCallbacks(JSContext *cx, JSLocaleCallbacks *callbacks);
3497
3498 /*
3499  * Return the address of the current locale callbacks struct, which may
3500  * be NULL.
3501  */
3502 extern JS_PUBLIC_API(JSLocaleCallbacks *)
3503 JS_GetLocaleCallbacks(JSContext *cx);
3504
3505 /************************************************************************/
3506
3507 /*
3508  * Error reporting.
3509  */
3510
3511 /*
3512  * Report an exception represented by the sprintf-like conversion of format
3513  * and its arguments.  This exception message string is passed to a pre-set
3514  * JSErrorReporter function (set by JS_SetErrorReporter; see jspubtd.h for
3515  * the JSErrorReporter typedef).
3516  */
3517 extern JS_PUBLIC_API(void)
3518 JS_ReportError(JSContext *cx, const char *format, ...);
3519
3520 /*
3521  * Use an errorNumber to retrieve the format string, args are char *
3522  */
3523 extern JS_PUBLIC_API(void)
3524 JS_ReportErrorNumber(JSContext *cx, JSErrorCallback errorCallback,
3525                      void *userRef, const uintN errorNumber, ...);
3526
3527 /*
3528  * Use an errorNumber to retrieve the format string, args are jschar *
3529  */
3530 extern JS_PUBLIC_API(void)
3531 JS_ReportErrorNumberUC(JSContext *cx, JSErrorCallback errorCallback,
3532                      void *userRef, const uintN errorNumber, ...);
3533
3534 /*
3535  * As above, but report a warning instead (JSREPORT_IS_WARNING(report.flags)).
3536  * Return true if there was no error trying to issue the warning, and if the
3537  * warning was not converted into an error due to the JSOPTION_WERROR option
3538  * being set, false otherwise.
3539  */
3540 extern JS_PUBLIC_API(JSBool)
3541 JS_ReportWarning(JSContext *cx, const char *format, ...);
3542
3543 extern JS_PUBLIC_API(JSBool)
3544 JS_ReportErrorFlagsAndNumber(JSContext *cx, uintN flags,
3545                              JSErrorCallback errorCallback, void *userRef,
3546                              const uintN errorNumber, ...);
3547
3548 extern JS_PUBLIC_API(JSBool)
3549 JS_ReportErrorFlagsAndNumberUC(JSContext *cx, uintN flags,
3550                                JSErrorCallback errorCallback, void *userRef,
3551                                const uintN errorNumber, ...);
3552
3553 /*
3554  * Complain when out of memory.
3555  */
3556 extern JS_PUBLIC_API(void)
3557 JS_ReportOutOfMemory(JSContext *cx);
3558
3559 /*
3560  * Complain when an allocation size overflows the maximum supported limit.
3561  */
3562 extern JS_PUBLIC_API(void)
3563 JS_ReportAllocationOverflow(JSContext *cx);
3564
3565 struct JSErrorReport {
3566     const char      *filename;      /* source file name, URL, etc., or null */
3567     uintN           lineno;         /* source line number */
3568     const char      *linebuf;       /* offending source line without final \n */
3569     const char      *tokenptr;      /* pointer to error token in linebuf */
3570     const jschar    *uclinebuf;     /* unicode (original) line buffer */
3571     const jschar    *uctokenptr;    /* unicode (original) token pointer */
3572     uintN           flags;          /* error/warning, etc. */
3573     uintN           errorNumber;    /* the error number, e.g. see js.msg */
3574     const jschar    *ucmessage;     /* the (default) error message */
3575     const jschar    **messageArgs;  /* arguments for the error message */
3576 };
3577
3578 /*
3579  * JSErrorReport flag values.  These may be freely composed.
3580  */
3581 #define JSREPORT_ERROR      0x0     /* pseudo-flag for default case */
3582 #define JSREPORT_WARNING    0x1     /* reported via JS_ReportWarning */
3583 #define JSREPORT_EXCEPTION  0x2     /* exception was thrown */
3584 #define JSREPORT_STRICT     0x4     /* error or warning due to strict option */
3585
3586 /*
3587  * This condition is an error in strict mode code, a warning if
3588  * JS_HAS_STRICT_OPTION(cx), and otherwise should not be reported at
3589  * all.  We check the strictness of the context's top frame's script;
3590  * where that isn't appropriate, the caller should do the right checks
3591  * itself instead of using this flag.
3592  */
3593 #define JSREPORT_STRICT_MODE_ERROR 0x8
3594
3595 /*
3596  * If JSREPORT_EXCEPTION is set, then a JavaScript-catchable exception
3597  * has been thrown for this runtime error, and the host should ignore it.
3598  * Exception-aware hosts should also check for JS_IsExceptionPending if
3599  * JS_ExecuteScript returns failure, and signal or propagate the exception, as
3600  * appropriate.
3601  */
3602 #define JSREPORT_IS_WARNING(flags)      (((flags) & JSREPORT_WARNING) != 0)
3603 #define JSREPORT_IS_EXCEPTION(flags)    (((flags) & JSREPORT_EXCEPTION) != 0)
3604 #define JSREPORT_IS_STRICT(flags)       (((flags) & JSREPORT_STRICT) != 0)
3605 #define JSREPORT_IS_STRICT_MODE_ERROR(flags) (((flags) &                      \
3606                                               JSREPORT_STRICT_MODE_ERROR) != 0)
3607
3608 extern JS_PUBLIC_API(JSErrorReporter)
3609 JS_SetErrorReporter(JSContext *cx, JSErrorReporter er);
3610
3611 /************************************************************************/
3612
3613 /*
3614  * Dates.
3615  */
3616
3617 extern JS_PUBLIC_API(JSObject *)
3618 JS_NewDateObject(JSContext *cx, int year, int mon, int mday, int hour, int min, int sec);
3619
3620 extern JS_PUBLIC_API(JSObject *)
3621 JS_NewDateObjectMsec(JSContext *cx, jsdouble msec);
3622
3623 /*
3624  * Infallible predicate to test whether obj is a date object.
3625  */
3626 extern JS_PUBLIC_API(JSBool)
3627 JS_ObjectIsDate(JSContext *cx, JSObject *obj);
3628
3629 /************************************************************************/
3630
3631 /*
3632  * Regular Expressions.
3633  */
3634 #define JSREG_FOLD      0x01    /* fold uppercase to lowercase */
3635 #define JSREG_GLOB      0x02    /* global exec, creates array of matches */
3636 #define JSREG_MULTILINE 0x04    /* treat ^ and $ as begin and end of line */
3637 #define JSREG_STICKY    0x08    /* only match starting at lastIndex */
3638 #define JSREG_FLAT      0x10    /* parse as a flat regexp */
3639 #define JSREG_NOCOMPILE 0x20    /* do not try to compile to native code */
3640
3641 extern JS_PUBLIC_API(JSObject *)
3642 JS_NewRegExpObject(JSContext *cx, JSObject *obj, char *bytes, size_t length, uintN flags);
3643
3644 extern JS_PUBLIC_API(JSObject *)
3645 JS_NewUCRegExpObject(JSContext *cx, JSObject *obj, jschar *chars, size_t length, uintN flags);
3646
3647 extern JS_PUBLIC_API(void)
3648 JS_SetRegExpInput(JSContext *cx, JSObject *obj, JSString *input, JSBool multiline);
3649
3650 extern JS_PUBLIC_API(void)
3651 JS_ClearRegExpStatics(JSContext *cx, JSObject *obj);
3652
3653 extern JS_PUBLIC_API(JSBool)
3654 JS_ExecuteRegExp(JSContext *cx, JSObject *obj, JSObject *reobj, jschar *chars, size_t length,
3655                  size_t *indexp, JSBool test, jsval *rval);
3656
3657 /* RegExp interface for clients without a global object. */
3658
3659 extern JS_PUBLIC_API(JSObject *)
3660 JS_NewRegExpObjectNoStatics(JSContext *cx, char *bytes, size_t length, uintN flags);
3661
3662 extern JS_PUBLIC_API(JSObject *)
3663 JS_NewUCRegExpObjectNoStatics(JSContext *cx, jschar *chars, size_t length, uintN flags);
3664
3665 extern JS_PUBLIC_API(JSBool)
3666 JS_ExecuteRegExpNoStatics(JSContext *cx, JSObject *reobj, jschar *chars, size_t length,
3667                           size_t *indexp, JSBool test, jsval *rval);
3668
3669 /************************************************************************/
3670
3671 extern JS_PUBLIC_API(JSBool)
3672 JS_IsExceptionPending(JSContext *cx);
3673
3674 extern JS_PUBLIC_API(JSBool)
3675 JS_GetPendingException(JSContext *cx, jsval *vp);
3676
3677 extern JS_PUBLIC_API(void)
3678 JS_SetPendingException(JSContext *cx, jsval v);
3679
3680 extern JS_PUBLIC_API(void)
3681 JS_ClearPendingException(JSContext *cx);
3682
3683 extern JS_PUBLIC_API(JSBool)
3684 JS_ReportPendingException(JSContext *cx);
3685
3686 /*
3687  * Save the current exception state.  This takes a snapshot of cx's current
3688  * exception state without making any change to that state.
3689  *
3690  * The returned state pointer MUST be passed later to JS_RestoreExceptionState
3691  * (to restore that saved state, overriding any more recent state) or else to
3692  * JS_DropExceptionState (to free the state struct in case it is not correct
3693  * or desirable to restore it).  Both Restore and Drop free the state struct,
3694  * so callers must stop using the pointer returned from Save after calling the
3695  * Release or Drop API.
3696  */
3697 extern JS_PUBLIC_API(JSExceptionState *)
3698 JS_SaveExceptionState(JSContext *cx);
3699
3700 extern JS_PUBLIC_API(void)
3701 JS_RestoreExceptionState(JSContext *cx, JSExceptionState *state);
3702
3703 extern JS_PUBLIC_API(void)
3704 JS_DropExceptionState(JSContext *cx, JSExceptionState *state);
3705
3706 /*
3707  * If the given value is an exception object that originated from an error,
3708  * the exception will contain an error report struct, and this API will return
3709  * the address of that struct.  Otherwise, it returns NULL.  The lifetime of
3710  * the error report struct that might be returned is the same as the lifetime
3711  * of the exception object.
3712  */
3713 extern JS_PUBLIC_API(JSErrorReport *)
3714 JS_ErrorFromException(JSContext *cx, jsval v);
3715
3716 /*
3717  * Given a reported error's message and JSErrorReport struct pointer, throw
3718  * the corresponding exception on cx.
3719  */
3720 extern JS_PUBLIC_API(JSBool)
3721 JS_ThrowReportedError(JSContext *cx, const char *message,
3722                       JSErrorReport *reportp);
3723
3724 /*
3725  * Throws a StopIteration exception on cx.
3726  */
3727 extern JS_PUBLIC_API(JSBool)
3728 JS_ThrowStopIteration(JSContext *cx);
3729
3730 /*
3731  * Associate the current thread with the given context.  This is done
3732  * implicitly by JS_NewContext.
3733  *
3734  * Returns the old thread id for this context, which should be treated as
3735  * an opaque value.  This value is provided for comparison to 0, which
3736  * indicates that ClearContextThread has been called on this context
3737  * since the last SetContextThread, or non-0, which indicates the opposite.
3738  */
3739 extern JS_PUBLIC_API(jsword)
3740 JS_GetContextThread(JSContext *cx);
3741
3742 extern JS_PUBLIC_API(jsword)
3743 JS_SetContextThread(JSContext *cx);
3744
3745 extern JS_PUBLIC_API(jsword)
3746 JS_ClearContextThread(JSContext *cx);
3747
3748 /************************************************************************/
3749
3750 /*
3751  * JS_IsConstructing must be called from within a native given the
3752  * native's original cx and vp arguments. If JS_IsConstructing is true,
3753  * JS_THIS must not be used; the constructor should construct and return a
3754  * new object. Otherwise, the native is called as an ordinary function and
3755  * JS_THIS may be used.
3756  */
3757 static JS_ALWAYS_INLINE JSBool
3758 JS_IsConstructing(JSContext *cx, const jsval *vp)
3759 {
3760     jsval_layout l;
3761
3762 #ifdef DEBUG
3763     JSObject *callee = JSVAL_TO_OBJECT(JS_CALLEE(cx, vp));
3764     if (JS_ObjectIsFunction(cx, callee)) {
3765         JSFunction *fun = JS_ValueToFunction(cx, JS_CALLEE(cx, vp));
3766         JS_ASSERT((JS_GetFunctionFlags(fun) & JSFUN_CONSTRUCTOR) != 0);
3767     } else {
3768         JS_ASSERT(JS_GET_CLASS(cx, callee)->construct != NULL);
3769     }
3770 #endif
3771
3772     l.asBits = JSVAL_BITS(vp[1]);
3773     return JSVAL_IS_MAGIC_IMPL(l);
3774 }
3775
3776 /*
3777  * In the case of a constructor called from JS_ConstructObject and
3778  * JS_InitClass where the class has the JSCLASS_CONSTRUCT_PROTOTYPE flag set,
3779  * the JS engine passes the constructor a non-standard 'this' object. In such
3780  * cases, the following query provides the additional information of whether a
3781  * special 'this' was supplied. E.g.:
3782  *
3783  *   JSBool foo_native(JSContext *cx, uintN argc, jsval *vp) {
3784  *     JSObject *maybeThis;
3785  *     if (JS_IsConstructing_PossiblyWithGivenThisObject(cx, vp, &maybeThis)) {
3786  *       // native called as a constructor
3787  *       if (maybeThis)
3788  *         // native called as a constructor with maybeThis as 'this'
3789  *     } else {
3790  *       // native called as function, maybeThis is still uninitialized
3791  *     }
3792  *   }
3793  *
3794  * Note that embeddings do not need to use this query unless they use the
3795  * aforementioned API/flags.
3796  */
3797 static JS_ALWAYS_INLINE JSBool
3798 JS_IsConstructing_PossiblyWithGivenThisObject(JSContext *cx, const jsval *vp,
3799                                               JSObject **maybeThis)
3800 {
3801     jsval_layout l;
3802     JSBool isCtor;
3803
3804 #ifdef DEBUG
3805     JSObject *callee = JSVAL_TO_OBJECT(JS_CALLEE(cx, vp));
3806     if (JS_ObjectIsFunction(cx, callee)) {
3807         JSFunction *fun = JS_ValueToFunction(cx, JS_CALLEE(cx, vp));
3808         JS_ASSERT((JS_GetFunctionFlags(fun) & JSFUN_CONSTRUCTOR) != 0);
3809     } else {
3810         JS_ASSERT(JS_GET_CLASS(cx, callee)->construct != NULL);
3811     }
3812 #endif
3813
3814     l.asBits = JSVAL_BITS(vp[1]);
3815     isCtor = JSVAL_IS_MAGIC_IMPL(l);
3816     if (isCtor)
3817         *maybeThis = MAGIC_JSVAL_TO_OBJECT_OR_NULL_IMPL(l);
3818     return isCtor;
3819 }
3820
3821 /*
3822  * If a constructor does not have any static knowledge about the type of
3823  * object to create, it can request that the JS engine create a default new
3824  * 'this' object, as is done for non-constructor natives when called with new.
3825  */
3826 extern JS_PUBLIC_API(JSObject *)
3827 JS_NewObjectForConstructor(JSContext *cx, const jsval *vp);
3828
3829 /************************************************************************/
3830
3831 #ifdef DEBUG
3832 #define JS_GC_ZEAL 1
3833 #endif
3834
3835 #ifdef JS_GC_ZEAL
3836 extern JS_PUBLIC_API(void)
3837 JS_SetGCZeal(JSContext *cx, uint8 zeal);
3838 #endif
3839
3840 JS_END_EXTERN_C
3841
3842 #endif /* jsapi_h___ */