Bug 576148: Factor out js::UpvarCookie. (r=mrbkap, dvander)
[mozilla-central.git] / js / src / jsscript.h
blob2de5a5e42cec16513810719945616881fe9a620c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=79 ft=cpp:
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
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/
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.
17 * The Original Code is Mozilla Communicator client code, released
18 * March 31, 1998.
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.
25 * Contributor(s):
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.
39 * ***** END LICENSE BLOCK ***** */
41 #ifndef jsscript_h___
42 #define jsscript_h___
44 * JS script descriptor.
46 #include "jsatom.h"
47 #include "jsprvtd.h"
48 #include "jsdbgapi.h"
50 JS_BEGIN_EXTERN_C
53 * Type of try note associated with each catch or finally block, and also with
54 * for-in loops.
56 typedef enum JSTryNoteKind {
57 JSTRY_CATCH,
58 JSTRY_FINALLY,
59 JSTRY_ITER
60 } JSTryNoteKind;
62 namespace js {
65 * Indicates a location in the stack that an upvar value can be retrieved from
66 * as a two tuple of (level, slot).
68 * Some existing client code uses the level value as a delta, or level "skip"
69 * quantity. We could probably document that through use of more types at some
70 * point in the future.
72 * Existing XDR code wants this to be backed by a 32b integer for serialization,
73 * so we oblige.
75 * TODO: consider giving more bits to the slot value and takings ome from the level.
77 class UpvarCookie
79 uint32 value;
81 static const uint32 FREE_VALUE = 0xfffffffful;
83 public:
85 * All levels above-and-including FREE_LEVEL are reserved so that
86 * FREE_VALUE can be used as a special value.
88 static const uint16 FREE_LEVEL = 0x3fff;
89 static const uint16 CALLEE_SLOT = 0xffff;
90 static bool isLevelReserved(uint16 level) { return level >= FREE_LEVEL; }
92 bool isFree() const { return value == FREE_VALUE; }
93 uint32 asInteger() const { return value; }
94 /* isFree check should be performed before using these accessors. */
95 uint16 level() const { JS_ASSERT(!isFree()); return value >> 16; }
96 uint16 slot() const { JS_ASSERT(!isFree()); return value; }
98 void set(const UpvarCookie &other) { set(other.level(), other.slot()); }
99 void set(uint16 newLevel, uint16 newSlot) { value = (uint32(newLevel) << 16) | newSlot; }
100 void makeFree() { set(0xffff, 0xffff); JS_ASSERT(isFree()); }
102 JS_STATIC_ASSERT(sizeof(UpvarCookie) == sizeof(uint32));
107 * Exception handling record.
109 struct JSTryNote {
110 uint8 kind; /* one of JSTryNoteKind */
111 uint8 padding; /* explicit padding on uint16 boundary */
112 uint16 stackDepth; /* stack depth upon exception handler entry */
113 uint32 start; /* start of the try statement or for-in loop
114 relative to script->main */
115 uint32 length; /* length of the try statement or for-in loop */
118 typedef struct JSTryNoteArray {
119 JSTryNote *vector; /* array of indexed try notes */
120 uint32 length; /* count of indexed try notes */
121 } JSTryNoteArray;
123 typedef struct JSObjectArray {
124 JSObject **vector; /* array of indexed objects */
125 uint32 length; /* count of indexed objects */
126 } JSObjectArray;
128 typedef struct JSUpvarArray {
129 js::UpvarCookie *vector; /* array of indexed upvar cookies */
130 uint32 length; /* count of indexed upvar cookies */
131 } JSUpvarArray;
133 #define JS_OBJECT_ARRAY_SIZE(length) \
134 (offsetof(JSObjectArray, vector) + sizeof(JSObject *) * (length))
136 #if defined DEBUG && defined JS_THREADSAFE
137 # define CHECK_SCRIPT_OWNER 1
138 #endif
140 struct JSScript {
141 jsbytecode *code; /* bytecodes and their immediate operands */
142 uint32 length; /* length of code vector */
143 uint16 version; /* JS version under which script was compiled */
144 uint16 nfixed; /* number of slots besides stack operands in
145 slot array */
146 uint8 objectsOffset; /* offset to the array of nested function,
147 block, scope, xml and one-time regexps
148 objects or 0 if none */
149 uint8 upvarsOffset; /* offset of the array of display ("up")
150 closure vars or 0 if none */
151 uint8 regexpsOffset; /* offset to the array of to-be-cloned
152 regexps or 0 if none. */
153 uint8 trynotesOffset; /* offset to the array of try notes or
154 0 if none */
155 bool noScriptRval:1; /* no need for result value of last
156 expression statement */
157 bool savedCallerFun:1; /* object 0 is caller function */
158 bool hasSharps:1; /* script uses sharp variables */
159 bool strictModeCode:1; /* code is in strict mode */
161 jsbytecode *main; /* main entry point, after predef'ing prolog */
162 JSAtomMap atomMap; /* maps immediate index to literal struct */
163 const char *filename; /* source filename or null */
164 uint32 lineno; /* base line number of script */
165 uint16 nslots; /* vars plus maximum stack depth */
166 uint16 staticLevel;/* static level for display maintenance */
167 JSPrincipals *principals;/* principals for this script */
168 union {
169 JSObject *object; /* optional Script-class object wrapper */
170 JSScript *nextToGC; /* next to GC in rt->scriptsToGC list */
171 } u;
172 #ifdef CHECK_SCRIPT_OWNER
173 JSThread *owner; /* for thread-safe life-cycle assertions */
174 #endif
176 /* Script notes are allocated right after the code. */
177 jssrcnote *notes() { return (jssrcnote *)(code + length); }
179 JSObjectArray *objects() {
180 JS_ASSERT(objectsOffset != 0);
181 return (JSObjectArray *)((uint8 *) this + objectsOffset);
184 JSUpvarArray *upvars() {
185 JS_ASSERT(upvarsOffset != 0);
186 return (JSUpvarArray *) ((uint8 *) this + upvarsOffset);
189 JSObjectArray *regexps() {
190 JS_ASSERT(regexpsOffset != 0);
191 return (JSObjectArray *) ((uint8 *) this + regexpsOffset);
194 JSTryNoteArray *trynotes() {
195 JS_ASSERT(trynotesOffset != 0);
196 return (JSTryNoteArray *) ((uint8 *) this + trynotesOffset);
199 JSAtom *getAtom(size_t index) {
200 JS_ASSERT(index < atomMap.length);
201 return atomMap.vector[index];
204 JSObject *getObject(size_t index) {
205 JSObjectArray *arr = objects();
206 JS_ASSERT(index < arr->length);
207 return arr->vector[index];
210 inline JSFunction *getFunction(size_t index);
212 inline JSObject *getRegExp(size_t index);
215 * The isEmpty method tells whether this script has code that computes any
216 * result (not return value, result AKA normal completion value) other than
217 * JSVAL_VOID, or any other effects. It has a fast path for the case where
218 * |this| is the emptyScript singleton, but it also checks this->length and
219 * this->code, to handle debugger-generated mutable empty scripts.
221 inline bool isEmpty() const;
224 * Accessor for the emptyScriptConst singleton, to consolidate const_cast.
225 * See the private member declaration.
227 static JSScript *emptyScript() {
228 return const_cast<JSScript *>(&emptyScriptConst);
231 private:
233 * Use const to put this in read-only memory if possible. We are stuck with
234 * non-const JSScript * and jsbytecode * by legacy code (back in the 1990s,
235 * const wasn't supported correctly on all target platforms). The debugger
236 * does mutate bytecode, and script->u.object may be set after construction
237 * in some cases, so making JSScript pointers const will be "hard".
239 static const JSScript emptyScriptConst;
242 #define SHARP_NSLOTS 2 /* [#array, #depth] slots if the script
243 uses sharp variables */
245 static JS_INLINE uintN
246 StackDepth(JSScript *script)
248 return script->nslots - script->nfixed;
252 * If pc_ does not point within script_'s bytecode, then it must point into an
253 * imacro body, so we use cx->runtime common atoms instead of script_'s atoms.
254 * This macro uses cx from its callers' environments in the pc-in-imacro case.
256 #define JS_GET_SCRIPT_ATOM(script_, pc_, index, atom) \
257 JS_BEGIN_MACRO \
258 if ((pc_) < (script_)->code || \
259 (script_)->code + (script_)->length <= (pc_)) { \
260 JS_ASSERT((size_t)(index) < js_common_atom_count); \
261 (atom) = COMMON_ATOMS_START(&cx->runtime->atomState)[index]; \
262 } else { \
263 (atom) = script_->getAtom(index); \
265 JS_END_MACRO
267 extern JS_FRIEND_DATA(JSClass) js_ScriptClass;
269 extern JSObject *
270 js_InitScriptClass(JSContext *cx, JSObject *obj);
273 * On first new context in rt, initialize script runtime state, specifically
274 * the script filename table and its lock.
276 extern JSBool
277 js_InitRuntimeScriptState(JSRuntime *rt);
280 * On JS_DestroyRuntime(rt), forcibly free script filename prefixes and any
281 * script filename table entries that have not been GC'd.
283 * This allows script filename prefixes to outlive any context in rt.
285 extern void
286 js_FreeRuntimeScriptState(JSRuntime *rt);
288 extern const char *
289 js_SaveScriptFilename(JSContext *cx, const char *filename);
291 extern const char *
292 js_SaveScriptFilenameRT(JSRuntime *rt, const char *filename, uint32 flags);
294 extern uint32
295 js_GetScriptFilenameFlags(const char *filename);
297 extern void
298 js_MarkScriptFilename(const char *filename);
300 extern void
301 js_MarkScriptFilenames(JSRuntime *rt);
303 extern void
304 js_SweepScriptFilenames(JSRuntime *rt);
307 * Two successively less primitive ways to make a new JSScript. The first
308 * does *not* call a non-null cx->runtime->newScriptHook -- only the second,
309 * js_NewScriptFromCG, calls this optional debugger hook.
311 * The js_NewScript function can't know whether the script it creates belongs
312 * to a function, or is top-level or eval code, but the debugger wants access
313 * to the newly made script's function, if any -- so callers of js_NewScript
314 * are responsible for notifying the debugger after successfully creating any
315 * kind (function or other) of new JSScript.
317 * NB: js_NewScript always creates a new script; it never returns the empty
318 * script singleton (JSScript::emptyScript()). Callers who know they can use
319 * that read-only singleton are responsible for choosing it instead of calling
320 * js_NewScript with length and nsrcnotes equal to 1 and other parameters save
321 * cx all zero.
323 extern JSScript *
324 js_NewScript(JSContext *cx, uint32 length, uint32 nsrcnotes, uint32 natoms,
325 uint32 nobjects, uint32 nupvars, uint32 nregexps,
326 uint32 ntrynotes);
328 extern JSScript *
329 js_NewScriptFromCG(JSContext *cx, JSCodeGenerator *cg);
332 * New-script-hook calling is factored from js_NewScriptFromCG so that it
333 * and callers of js_XDRScript can share this code. In the case of callers
334 * of js_XDRScript, the hook should be invoked only after successful decode
335 * of any owning function (the fun parameter) or script object (null fun).
337 extern JS_FRIEND_API(void)
338 js_CallNewScriptHook(JSContext *cx, JSScript *script, JSFunction *fun);
340 extern JS_FRIEND_API(void)
341 js_CallDestroyScriptHook(JSContext *cx, JSScript *script);
343 extern void
344 js_DestroyScript(JSContext *cx, JSScript *script);
346 extern void
347 js_TraceScript(JSTracer *trc, JSScript *script);
350 * To perturb as little code as possible, we introduce a js_GetSrcNote lookup
351 * cache without adding an explicit cx parameter. Thus js_GetSrcNote becomes
352 * a macro that uses cx from its calls' lexical environments.
354 #define js_GetSrcNote(script,pc) js_GetSrcNoteCached(cx, script, pc)
356 extern jssrcnote *
357 js_GetSrcNoteCached(JSContext *cx, JSScript *script, jsbytecode *pc);
360 * NOTE: use js_FramePCToLineNumber(cx, fp) when you have an active fp, in
361 * preference to js_PCToLineNumber (cx, fp->script fp->regs->pc), because
362 * fp->imacpc may be non-null, indicating an active imacro.
364 extern uintN
365 js_FramePCToLineNumber(JSContext *cx, JSStackFrame *fp);
367 extern uintN
368 js_PCToLineNumber(JSContext *cx, JSScript *script, jsbytecode *pc);
370 extern jsbytecode *
371 js_LineNumberToPC(JSScript *script, uintN lineno);
373 extern JS_FRIEND_API(uintN)
374 js_GetScriptLineExtent(JSScript *script);
376 static JS_INLINE JSOp
377 js_GetOpcode(JSContext *cx, JSScript *script, jsbytecode *pc)
379 JSOp op = (JSOp) *pc;
380 if (op == JSOP_TRAP)
381 op = JS_GetTrapOpcode(cx, script, pc);
382 return op;
386 * If magic is non-null, js_XDRScript succeeds on magic number mismatch but
387 * returns false in *magic; it reflects a match via a true *magic out param.
388 * If magic is null, js_XDRScript returns false on bad magic number errors,
389 * which it reports.
391 * NB: after a successful JSXDR_DECODE, and provided that *scriptp is not the
392 * JSScript::emptyScript() immutable singleton, js_XDRScript callers must do
393 * any required subsequent set-up of owning function or script object and then
394 * call js_CallNewScriptHook.
396 * If the caller requires a mutable empty script (for debugging or u.object
397 * ownership setting), pass true for needMutableScript. Otherwise pass false.
398 * Call js_CallNewScriptHook only with a mutable script, i.e. never with the
399 * JSScript::emptyScript() singleton.
401 extern JSBool
402 js_XDRScript(JSXDRState *xdr, JSScript **scriptp, bool needMutableScript,
403 JSBool *hasMagic);
405 JS_END_EXTERN_C
407 #endif /* jsscript_h___ */