jsapi.h revision 6b15695578f07a3f72c4c9475c1a261a3021472a
2712N/A/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- 2712N/A * ***** BEGIN LICENSE BLOCK ***** 2712N/A * Version: MPL 1.1/GPL 2.0/LGPL 2.1 2712N/A * The contents of this file are subject to the Mozilla Public License Version 2712N/A * 1.1 (the "License"); you may not use this file except in compliance with 2712N/A * the License. You may obtain a copy of the License at 2712N/A * Software distributed under the License is distributed on an "AS IS" basis, 2712N/A * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 2712N/A * for the specific language governing rights and limitations under the 2712N/A * The Original Code is Mozilla Communicator client code, released 2712N/A * The Initial Developer of the Original Code is 2712N/A * Netscape Communications Corporation. 2712N/A * Portions created by the Initial Developer are Copyright (C) 1998 2712N/A * the Initial Developer. All Rights Reserved. 2712N/A * Alternatively, the contents of this file may be used under the terms of 2712N/A * either of the GNU General Public License Version 2 or later (the "GPL"), 2712N/A * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), 2712N/A * in which case the provisions of the GPL or the LGPL are applicable instead 2712N/A * of those above. If you wish to allow use of your version of this file only 2712N/A * under the terms of either the GPL or the LGPL, and not to allow others to 2712N/A * use your version of this file under the terms of the MPL, indicate your 2712N/A * decision by deleting the provisions above and replace them with the notice 2712N/A * and other provisions required by the GPL or the LGPL. If you do not delete 2712N/A * the provisions above, a recipient may use your version of this file under 2712N/A * the terms of any one of the MPL, the GPL or the LGPL. 2712N/A * ***** END LICENSE BLOCK ***** */ 2712N/A * Type tags stored in the low bits of a jsval. 2712N/A/* Type tag bitfield length and derived macros. */ 2712N/A/* Predicates for type testing. */ 2712N/A/* Objects, strings, and doubles are GC'ed. */ 2712N/A/* Lock and unlock the GC thing held by a jsval. */ 2712N/A/* Domain limits for the jsval int type. */ 2712N/A/* Convert between boolean and jsval. */ 2712N/A/* A private data pointer (2-byte-aligned) can be stored as an int jsval. */ 2712N/A/* Property attributes, set in JSPropertySpec and passed to API functions. */ 2712N/A property; don't copy the property on 2712N/A set of the same-named property in an 2712N/A object that delegates to a prototype 2712N/A containing this property */ 2712N/A/* Function flags, set in JSFunctionSpec and passed to JS_NewFunction etc. */ 2712N/A * Well-known JS values. The extern'd variables are initialized when the 2712N/A * first JSContext is created by JS_NewContext (see below). 2712N/A * Microseconds since the epoch, midnight, January 1, 1970 UTC. See the 2712N/A/* Don't want to export data, so provide accessors for non-inline jsvals. */ 2712N/A * Format is a string of the following characters (spaces are insignificant), 2712N/A * specifying the tabulated type conversions: 2712N/A * j int32 Rounded int32 (coordinate) 2712N/A * I jsdouble Integral IEEE double 2712N/A * S JSString * Unicode string, accessed by a JSString pointer 2712N/A * W jschar * Unicode character vector, 0-terminated (W for wide) 2712N/A * o JSObject * Object reference 2712N/A * f JSFunction * Function private 2712N/A * v jsval Argument value (no conversion) 2712N/A * * N/A Skip this argument (no vararg) 2712N/A * / N/A End of required arguments 2712N/A * The variable argument list after format must consist of &b, &c, &s, e.g., 2712N/A * where those variables have the types given above. For the pointer types 2712N/A * char *, JSString *, and JSObject *, the pointed-at memory returned belongs 2712N/A * to the JS runtime, not to the calling native code. The runtime promises 2712N/A * to keep this memory valid so long as argv refers to allocated stack space 2712N/A * (so long as the native function is active). 2712N/A * Fewer arguments than format specifies may be passed only if there is a / 2712N/A * in format after the last required argument specifier and argc is at least 2712N/A * the number of required arguments. More arguments than format specifies 2712N/A * may be passed without error; it is up to the caller to deal with trailing 2712N/A * Inverse of JS_ConvertArguments: scan format and convert trailing arguments 2712N/A * into jsvals, GC-rooted if necessary by the JS stack. Return null on error, 2712N/A * and a pointer to the new argument vector on success. Also return a stack 2712N/A * mark on success via *markp, in which case the caller must eventually clean 2712N/A * up by calling JS_PopArguments. 2712N/A * Note that the number of actual arguments supplied is specified exclusively 2712N/A * by format, so there is no argc parameter. 2712N/A * Add and remove a format string handler for JS_{Convert,Push}Arguments{,VA}. 2712N/A * JSBool MyArgumentFormatter(JSContext *cx, const char *format, 2712N/A * JSBool fromJS, jsval **vpp, va_list *app); 2712N/A * It should return true on success, and return false after reporting an error 2712N/A * or detecting an already-reported error. 2712N/A * For a given format string, for example "AA", the formatter is called from 2712N/A * JS_ConvertArgumentsVA like so: 2712N/A * formatter(cx, "AA...", JS_TRUE, &sp, &ap); 2712N/A * sp points into the arguments array on the JS stack, while ap points into 2712N/A * the stdarg.h va_list on the C stack. The JS_TRUE passed for fromJS tells 2712N/A * the formatter to convert zero or more jsvals at sp to zero or more C values 2712N/A * accessed via pointers-to-values at ap, updating both sp (via *vpp) and ap 2712N/A * (via *app) to point past the converted arguments and their result pointers 2712N/A * When called from JS_PushArgumentsVA, the formatter is invoked thus: 2712N/A * formatter(cx, "AA...", JS_FALSE, &sp, &ap); 2712N/A * where JS_FALSE for fromJS means to wrap the C values at ap according to the 2712N/A * format specifier and store them at sp, updating ap and sp appropriately. 2712N/A * The "..." after "AA" is the rest of the format string that was passed into 2712N/A * JS_{Convert,Push}Arguments{,VA}. The actual format trailing substring used 2712N/A * in each Convert or PushArguments call is passed to the formatter, so that 2712N/A * one such function may implement several formats, in order to share code. 2712N/A * Remove just forgets about any handler associated with format. Add does not 2712N/A * copy format, it points at the string storage allocated by the caller, which 2712N/A * is typically a string constant. If format is in dynamic storage, it is up 2712N/A * to the caller to keep the string alive until Remove is called. 2712N/A#
endif /* JS_ARGUMENT_FORMATTER_DEFINED */ * Convert a value to a number, then to an int32, according to the ECMA rules * Convert a value to a number, then to a uint32, according to the ECMA rules * Convert a value to a number, then to an int32 if it fits by rounding to * nearest; but failing with an error report if the double is out of range * ECMA ToUint16, for mapping a jsval to a Unicode point. /************************************************************************/ * Initialization, locking, contexts, and memory allocation. /* Yield to pending GC operations, regardless of request depth */ #
endif /* JS_THREADSAFE */ * JS options are orthogonal to version, and may be freely composed with one * another as well as with version. * JSOPTION_VAROBJFIX is recommended -- see the comments associated with the * prototypes for JS_ExecuteScript, JS_EvaluateScript, etc. the last object on its 'obj' param's scope chain as the ECMA 'variables object' */ JS_BIT(
3)
/* context private data points to an nsISupports subclass */ * Initialize standard JS class constructors, prototypes, and any top-level * functions and constants associated with the standard classes (e.g. isNaN * NB: This sets cx's global object to obj if it was null. * Resolve id, which must contain either a string or an int, to a standard * class name in obj if possible, defining the class's constructor and/or * prototype and storing true in *resolved. If id does not name a standard * class or a top-level property induced by initializing a standard class, * store false in *resolved and just return true. Return false on error, * as usual for JSBool result-typed API entry points. * This API can be called directly from a global object class's resolve op, * to define standard classes lazily. The class's enumerate op should call * JS_EnumerateStandardClasses(cx, obj), to define eagerly during for..in * loops any classes not yet resolved lazily. * A JS GC root is a pointer to a JSObject *, JSString *, or jsdouble * that * itself points into the GC heap (more recently, we support this extension: * a root may be a pointer to a jsval v for which JSVAL_IS_GCTHING(v) is true). * Therefore, you never pass JSObject *obj to JS_AddRoot(cx, obj). You always * call JS_AddRoot(cx, &obj), passing obj by reference. And later, before obj * or the structure it is embedded within goes out of scope or is freed, you * must call JS_RemoveRoot(cx, &obj). * Also, use JS_AddNamedRoot(cx, &structPtr->memberObj, "structPtr->memberObj") * in preference to JS_AddRoot(cx, &structPtr->memberObj), in order to identify * roots by their source callsites. This way, you can find the callsite while * debugging if you should fail to do JS_RemoveRoot(cx, &structPtr->memberObj) * before freeing structPtr's memory. * The last GC thing of each type (object, string, double, external string * types) created on a given context is kept alive until another thing of the * same type is created, using a newborn root in the context. These newborn * roots help native code protect newly-created GC-things from GC invocations * activated before those things can be rooted using local or global roots. * However, the newborn roots can also entrain great gobs of garbage, so the * JS_GC entry point clears them for the context on which GC is being forced. * Embeddings may need to do likewise for all contexts. * which proposes switching (with an #ifdef, alas, if we want to maintain API * compatibility) to a JNI-like extensible local root frame stack model. * Call JS_MapGCRoots to map the GC's roots table using map(rp, name, data). * The root is pointed at by rp; if the root is unnamed, name is null; data is * supplied from the third parameter to JS_MapGCRoots. * The map function should return JS_MAP_GCROOT_REMOVE to cause the currently * enumerated root to be removed. To stop enumeration, set JS_MAP_GCROOT_STOP * in the return value. To keep on mapping, return JS_MAP_GCROOT_NEXT. These * constants are flags; you can OR them together. * This function acquires and releases rt's GC lock around the mapping of the * roots table, so the map function should run to completion in as few cycles * as possible. Of course, map cannot call JS_GC, JS_MaybeGC, JS_BeginRequest, * or any JS API entry point that acquires locks, without double-tripping or * deadlocking on the GC lock. * JS_MapGCRoots returns the count of roots that were successfully mapped. * For implementors of JSObjectOps.mark, to mark a GC-thing reachable via a * property or other strong ref identified for debugging purposes by name. * The name argument's storage needs to live only as long as the call to * The final arg is used by GC_MARK_DEBUG code to build a ref path through * the GC's live thing graph. Implementors of JSObjectOps.mark should pass * its final arg through to this function when marking all GC-things that are * directly reachable from the object being marked. * See the JSMarkOp typedef in jspubtd.h, and the JSObjectOps struct below. * Add an external string finalizer, one created by JS_NewExternalString (see * below) using a type-code returned from this function, and that understands * how to free or release the memory pointed at by JS_GetStringChars(str). * Return a nonnegative type index if there is room for finalizer in the * global GC finalizers table, else return -1. If the engine is compiled * JS_THREADSAFE and used in a multi-threaded environment, this function must * be invoked on the primordial thread only, at startup -- or else the entire * program must single-thread itself while loading a module that calls this * Remove finalizer from the global GC finalizers table, returning its type * code if found, -1 if not found. * As with JS_AddExternalStringFinalizer, there is a threading restriction * if you compile the engine JS_THREADSAFE: this function may be called for a * given finalizer pointer on only one thread; different threads may call to * remove distinct finalizers safely. * You must ensure that all strings with finalizer's type have been collected * before calling this function. Otherwise, string data will be leaked by the * GC, for want of a finalizer to call. * Create a new JSString whose chars member refers to external memory, i.e., * memory requiring special, type-specific finalization. The type code must * be a nonnegative return value from JS_AddExternalStringFinalizer. * Returns the external-string finalizer index for this string, or -1 if it is * an "internal" (native to JS engine) string. * Sets maximum (if stack grows upward) or minimum (downward) legal stack byte * address in limitAddr for the thread or process stack used by cx. To disable * stack size checking, pass 0 for limitAddr. /************************************************************************/ * Classes, objects, and properties. /* For detailed comments on the function pointer types, see jspubtd.h. */ /* Mandatory non-null function pointer members. */ /* Optionally non-null members start here. */ object in prototype chain passed in via *objp in/out * JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where * n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. /* Initializer for unused members of statically initialized JSClass structs. */ /* For detailed comments on these function pointer types, see jspubtd.h. */ /* Mandatory non-null function pointer members. */ /* Optionally non-null members start here. */ * Classes that expose JSObjectOps via a non-null getObjectOps class hook may * derive a property structure from this struct, return a pointer to it from * lookupProperty and defineProperty, and use the pointer to avoid rehashing * in getAttributes and setAttributes. * The jsid type contains either an int jsval (see JSVAL_IS_INT above), or an * internal pointer that is opaque to users of this API, but which users may * convert from and to a jsval using JS_ValueToId and JS_IdToValue. * To define an array element rather than a named property member, cast the * element's index to (const char *) and initialize name with it, and set the * JSPROP_INDEX bit in flags. uint16 extra;
/* number of arg slots for local GC roots */ * Get a unique identifier for obj, good for the lifetime of obj (even if it * is moved by a copying GC). Return false on failure (likely out of memory), * and true with *idp containing the unique id on success. * Determine the attributes (JSPROP_* flags) of a property on a given object. * If the object does not have a property by that name, *foundp will be * JS_FALSE and the value of *attrsp is undefined. * Set the attributes of a property on a given object. * If the object does not have a property by that name, *foundp will be * JS_FALSE and nothing will be altered. * Determine the attributes (JSPROP_* flags) of a property on a given object. * If the object does not have a property by that name, *foundp will be * JS_FALSE and the value of *attrsp is undefined. * Set the attributes of a property on a given object. * If the object does not have a property by that name, *foundp will be * JS_FALSE and nothing will be altered. /************************************************************************/ /* Don't call "destroy"; use reference counting macros below. */ /************************************************************************/ * Deprecated, useful only for diagnostics. Use JS_GetFunctionId instead for * anonymous vs. "anonymous" disambiguation and Unicode fidelity. * Return the function's identifier as a JSString, or null if fun is unnamed. * The returned string lives as long as fun, so you don't need to root a saved * reference to it if fun is well-connected or rooted, and provided you bound * the use of the saved reference by fun's lifetime. * Prefer JS_GetFunctionId over JS_GetFunctionName because it returns null for * truly anonymous functions, and because it doesn't chop to ISO-Latin-1 chars * from UTF-16-ish jschars. * Return JSFUN_* flags for fun. * Infallible predicate to test whether obj is a function object (faster than * comparing obj's class name to "Function", but equivalent unless someone has * overwritten the "Function" identifier with a different constructor and then * created instances using that constructor that might be passed in as obj). * Given a buffer, return JS_FALSE if the buffer might become a valid * javascript statement with the addition of more lines. Otherwise return * JS_TRUE. The intent is to support interactive compilation - accumulate * lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to * The JSScript objects returned by the following functions refer to string and * other kinds of literals, including doubles and RegExp objects. These * literals are vulnerable to garbage collection; to root script objects and * prevent literals from being collected, create a rootable object using * JS_NewScriptObject, and root the resulting object using JS_Add[Named]Root. * NB: you must use JS_NewScriptObject and root a pointer to its return value * in order to keep a JSScript and its atoms safe from garbage collection after * creating the script via JS_Compile* and before a JS_ExecuteScript* call. * E.g., and without error checks: * JSScript *script = JS_CompileFile(cx, global, filename); * JSObject *scrobj = JS_NewScriptObject(cx, script); * JS_AddNamedRoot(cx, &scrobj, "scrobj"); * JS_ExecuteScript(cx, global, script, &result); * } while (!JSVAL_IS_BOOLEAN(result) || JSVAL_TO_BOOLEAN(result)); * JS_RemoveRoot(cx, &scrobj); * Infallible getter for a script's object. If JS_NewScriptObject has not been * called on script yet, the return value will be null. * API extension: OR this into indent to avoid pretty-printing the decompiled * source resulting from JS_DecompileFunction{,Body}. * NB: JS_ExecuteScript, JS_ExecuteScriptPart, and the JS_Evaluate*Script* * quadruplets all use the obj parameter as the initial scope chain header, * the 'this' keyword value, and the variables object (ECMA parlance for where * 'var' and 'function' bind names) of the execution context for script. * Using obj as the variables object is problematic if obj's parent (which is * the scope chain link; see JS_SetParent and JS_NewObject) is not null: in * this case, variables created by 'var x = 0', e.g., go in obj, but variables * created by assignment to an unbound id, 'x = 0', go in the last object on * the scope chain linked by parent. * ECMA calls that last scoping object the "global object", but note that many * embeddings have several such objects. ECMA requires that "global code" be * executed with the variables object equal to this global object. But these * JS API entry points provide freedom to execute code against a "sub-global", * i.e., a parented or scoped object, in which case the variables object will * differ from the last object on the scope chain, resulting in confusing and * non-ECMA explicit vs. implicit variable creation. * Caveat embedders: unless you already depend on this buggy variables object * binding behavior, you should call JS_SetOptions(cx, JSOPTION_VAROBJFIX) or * JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_VAROBJFIX) -- the latter if * someone may have set other options on cx already -- for each context in the * application, if you pass parented objects as the obj parameter, or may ever * pass such objects in the future. * Why a runtime option? The alternative is to add six or so new API entry * points with signatures matching the following six, and that doesn't seem * worth the code bloat cost. Such new entry points would probably have less * obvious names, too, so would not tend to be used. The JS_SetOption call, * OTOH, can be more easily hacked into existing code that does not depend on * the bug; such code can continue to use the familiar JS_EvaluateScript, * Execute either the function-defining prolog of a script, or the script's * main body, but not both. * Returns true if a script is executing and its current bytecode is a set * (assignment) operation, even if there are native (no script) stack frames * between the script and the caller to JS_IsAssigning. * Set the second return value, which should be a string or int jsval that * identifies a property in the returned object, to form an ECMA reference * type value (obj, id). Only native methods can return reference types, * and if the returned value is used on the left-hand side of an assignment * op, the identified property will be set. If the return value is in an * r-value, the interpreter just gets obj[id]'s value. /************************************************************************/ * NB: JS_NewString takes ownership of bytes on success, avoiding a copy; but * on error (signified by null return), it leaves bytes owned by the caller. * So the caller must free bytes in the error case, if it has no use for them. * In contrast, all the JS_New*StringCopy* functions do not take ownership of * the character memory passed to them -- they copy it. * Mutable string support. A string's characters are never mutable in this JS * implementation, but a growable string has a buffer that can be reallocated, * and a dependent string is a substring of another (growable, dependent, or * immutable) string. The direct data members of the (opaque to API clients) * JSString struct may be changed in a single-threaded way for growable and * Therefore mutable strings cannot be used by more than one thread at a time. * You may call JS_MakeStringImmutable to convert the string from a mutable * (growable or dependent) string to an immutable (and therefore thread-safe) * string. The engine takes care of converting growable and dependent strings * to immutable for you if you store strings in multi-threaded objects using * JS_SetProperty or kindred API entry points. * If you store a JSString pointer in a native data structure that is (safely) * accessible to multiple threads, you must call JS_MakeStringImmutable before * Create a dependent string, i.e., a string that owns no character storage, * but that refers to a slice of another string's chars. Dependent strings * are mutable by definition, so the thread safety comments above apply. * Concatenate two strings, resulting in a new growable string. If you create * the left string and pass it to JS_ConcatStrings on a single thread, try to * use JS_NewGrowableString to create the left string -- doing so helps Concat * avoid allocating a new buffer for the result and copying left's chars into * the new buffer. See above for thread safety comments. * Convert a dependent string into an independent one. This function does not * change the string's mutability, so the thread safety comments above apply. * Convert a mutable string (either growable or dependent) into an immutable, /************************************************************************/ * Locale specific string conversion callback. * Establish locale callbacks. The pointer must persist as long as the * JSContext. Passing NULL restores the default behaviour. * Return the address of the current locale callbacks struct, which may /************************************************************************/ * Report an exception represented by the sprintf-like conversion of format * and its arguments. This exception message string is passed to a pre-set * JSErrorReporter function (set by JS_SetErrorReporter; see jspubtd.h for * the JSErrorReporter typedef). * Use an errorNumber to retrieve the format string, args are char * * Use an errorNumber to retrieve the format string, args are jschar * * As above, but report a warning instead (JSREPORT_IS_WARNING(report.flags)). * Return true if there was no error trying to issue the warning, and if the * warning was not converted into an error due to the JSOPTION_WERROR option * being set, false otherwise. * Complain when out of memory. const char *
filename;
/* source file name, URL, etc., or null */ const char *
linebuf;
/* offending source line without final \n */ const char *
tokenptr;
/* pointer to error token in linebuf */ * JSErrorReport flag values. These may be freely composed. * If JSREPORT_EXCEPTION is set, then a JavaScript-catchable exception * has been thrown for this runtime error, and the host should ignore it. * Exception-aware hosts should also check for JS_IsExceptionPending if * JS_ExecuteScript returns failure, and signal or propagate the exception, as /************************************************************************/ #
define JSREG_FOLD 0x01 /* fold uppercase to lowercase */#
define JSREG_GLOB 0x02 /* global exec, creates array of matches *//* TODO: compile, exec, get/set other statics... */ /************************************************************************/ * Save the current exception state. This takes a snapshot of cx's current * exception state without making any change to that state. * The returned state pointer MUST be passed later to JS_RestoreExceptionState * (to restore that saved state, overriding any more recent state) or else to * JS_DropExceptionState (to free the state struct in case it is not correct * or desirable to restore it). Both Restore and Drop free the state struct, * so callers must stop using the pointer returned from Save after calling the * If the given value is an exception object that originated from an error, * the exception will contain an error report struct, and this API will return * the address of that struct. Otherwise, it returns NULL. The lifetime of * the error report struct that might be returned is the same as the lifetime * of the exception object. * Associate the current thread with the given context. This is done * implicitly by JS_NewContext. * Returns the old thread id for this context, which should be treated as * an opaque value. This value is provided for comparison to 0, which * indicates that ClearContextThread has been called on this context * since the last SetContextThread, or non-0, which indicates the opposite. #
endif /* JS_THREADSAFE *//************************************************************************/