Back to index

lightning-sunbird  0.9+nobinonly
jsemit.h
Go to the documentation of this file.
00001 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
00002  * vim: set ts=8 sw=4 et tw=78:
00003  *
00004  * ***** BEGIN LICENSE BLOCK *****
00005  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00006  *
00007  * The contents of this file are subject to the Mozilla Public License Version
00008  * 1.1 (the "License"); you may not use this file except in compliance with
00009  * the License. You may obtain a copy of the License at
00010  * http://www.mozilla.org/MPL/
00011  *
00012  * Software distributed under the License is distributed on an "AS IS" basis,
00013  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00014  * for the specific language governing rights and limitations under the
00015  * License.
00016  *
00017  * The Original Code is Mozilla Communicator client code, released
00018  * March 31, 1998.
00019  *
00020  * The Initial Developer of the Original Code is
00021  * Netscape Communications Corporation.
00022  * Portions created by the Initial Developer are Copyright (C) 1998
00023  * the Initial Developer. All Rights Reserved.
00024  *
00025  * Contributor(s):
00026  *
00027  * Alternatively, the contents of this file may be used under the terms of
00028  * either of the GNU General Public License Version 2 or later (the "GPL"),
00029  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00030  * in which case the provisions of the GPL or the LGPL are applicable instead
00031  * of those above. If you wish to allow use of your version of this file only
00032  * under the terms of either the GPL or the LGPL, and not to allow others to
00033  * use your version of this file under the terms of the MPL, indicate your
00034  * decision by deleting the provisions above and replace them with the notice
00035  * and other provisions required by the GPL or the LGPL. If you do not delete
00036  * the provisions above, a recipient may use your version of this file under
00037  * the terms of any one of the MPL, the GPL or the LGPL.
00038  *
00039  * ***** END LICENSE BLOCK ***** */
00040 
00041 #ifndef jsemit_h___
00042 #define jsemit_h___
00043 /*
00044  * JS bytecode generation.
00045  */
00046 
00047 #include "jsstddef.h"
00048 #include "jstypes.h"
00049 #include "jsatom.h"
00050 #include "jsopcode.h"
00051 #include "jsprvtd.h"
00052 #include "jspubtd.h"
00053 
00054 JS_BEGIN_EXTERN_C
00055 
00056 /*
00057  * NB: If you add enumerators for scope statements, add them between STMT_WITH
00058  * and STMT_CATCH, or you will break the STMT_TYPE_IS_SCOPE macro.  If you add
00059  * non-looping statement enumerators, add them before STMT_DO_LOOP or you will
00060  * break the STMT_TYPE_IS_LOOP macro.
00061  *
00062  * Also remember to keep the statementName array in jsemit.c in sync.
00063  */
00064 typedef enum JSStmtType {
00065     STMT_LABEL,                 /* labeled statement:  L: s */
00066     STMT_IF,                    /* if (then) statement */
00067     STMT_ELSE,                  /* else clause of if statement */
00068     STMT_BODY,                  /* synthetic body of function with
00069                                    destructuring formal parameters */
00070     STMT_BLOCK,                 /* compound statement: { s1[;... sN] } */
00071     STMT_SWITCH,                /* switch statement */
00072     STMT_WITH,                  /* with statement */
00073     STMT_CATCH,                 /* catch block */
00074     STMT_TRY,                   /* try block */
00075     STMT_FINALLY,               /* finally block */
00076     STMT_SUBROUTINE,            /* gosub-target subroutine body */
00077     STMT_DO_LOOP,               /* do/while loop statement */
00078     STMT_FOR_LOOP,              /* for loop statement */
00079     STMT_FOR_IN_LOOP,           /* for/in loop statement */
00080     STMT_WHILE_LOOP             /* while loop statement */
00081 } JSStmtType;
00082 
00083 #define STMT_TYPE_IN_RANGE(t,b,e) ((uint)((t) - (b)) <= (uintN)((e) - (b)))
00084 
00085 /*
00086  * A comment on the encoding of the JSStmtType enum and type-testing macros:
00087  *
00088  * STMT_TYPE_MAYBE_SCOPE tells whether a statement type is always, or may
00089  * become, a lexical scope.  It therefore includes block and switch (the two
00090  * low-numbered "maybe" scope types) and excludes with (with has dynamic scope
00091  * pending the "reformed with" in ES4/JS2).  It includes all try-catch-finally
00092  * types, which are high-numbered maybe-scope types.
00093  *
00094  * STMT_TYPE_LINKS_SCOPE tells whether a JSStmtInfo of the given type eagerly
00095  * links to other scoping statement info records.  It excludes the two early
00096  * "maybe" types, block and switch, as well as the try and both finally types,
00097  * since try and the other trailing maybe-scope types don't need block scope
00098  * unless they contain let declarations.
00099  *
00100  * We treat with as a static scope because it prevents lexical binding from
00101  * continuing further up the static scope chain.  With the "reformed with"
00102  * proposal for JS2, we'll be able to model it statically, too.
00103  */
00104 #define STMT_TYPE_MAYBE_SCOPE(type)                                           \
00105     (type != STMT_WITH &&                                                     \
00106      STMT_TYPE_IN_RANGE(type, STMT_BLOCK, STMT_SUBROUTINE))
00107 
00108 #define STMT_TYPE_LINKS_SCOPE(type)                                           \
00109     STMT_TYPE_IN_RANGE(type, STMT_WITH, STMT_CATCH)
00110 
00111 #define STMT_TYPE_IS_TRYING(type)                                             \
00112     STMT_TYPE_IN_RANGE(type, STMT_TRY, STMT_SUBROUTINE)
00113 
00114 #define STMT_TYPE_IS_LOOP(type) ((type) >= STMT_DO_LOOP)
00115 
00116 #define STMT_MAYBE_SCOPE(stmt)  STMT_TYPE_MAYBE_SCOPE((stmt)->type)
00117 #define STMT_LINKS_SCOPE(stmt)  (STMT_TYPE_LINKS_SCOPE((stmt)->type) ||       \
00118                                  ((stmt)->flags & SIF_SCOPE))
00119 #define STMT_IS_TRYING(stmt)    STMT_TYPE_IS_TRYING((stmt)->type)
00120 #define STMT_IS_LOOP(stmt)      STMT_TYPE_IS_LOOP((stmt)->type)
00121 
00122 typedef struct JSStmtInfo JSStmtInfo;
00123 
00124 struct JSStmtInfo {
00125     uint16          type;           /* statement type */
00126     uint16          flags;          /* flags, see below */
00127     ptrdiff_t       update;         /* loop update offset (top if none) */
00128     ptrdiff_t       breaks;         /* offset of last break in loop */
00129     ptrdiff_t       continues;      /* offset of last continue in loop */
00130     JSAtom          *atom;          /* name of LABEL, or block scope object */
00131     JSStmtInfo      *down;          /* info for enclosing statement */
00132     JSStmtInfo      *downScope;     /* next enclosing lexical scope */
00133 };
00134 
00135 #define SIF_SCOPE        0x0001     /* statement has its own lexical scope */
00136 #define SIF_BODY_BLOCK   0x0002     /* STMT_BLOCK type is a function body */
00137 
00138 /*
00139  * To reuse space in JSStmtInfo, rename breaks and continues for use during
00140  * try/catch/finally code generation and backpatching.  To match most common
00141  * use cases, the macro argument is a struct, not a struct pointer.  Only a
00142  * loop, switch, or label statement info record can have breaks and continues,
00143  * and only a for loop has an update backpatch chain, so it's safe to overlay
00144  * these for the "trying" JSStmtTypes.
00145  */
00146 #define CATCHNOTE(stmt)  ((stmt).update)
00147 #define GOSUBS(stmt)     ((stmt).breaks)
00148 #define GUARDJUMP(stmt)  ((stmt).continues)
00149 
00150 #define AT_TOP_LEVEL(tc)                                                      \
00151     (!(tc)->topStmt || ((tc)->topStmt->flags & SIF_BODY_BLOCK))
00152 
00153 #define SET_STATEMENT_TOP(stmt, top)                                          \
00154     ((stmt)->update = (top), (stmt)->breaks = (stmt)->continues = (-1))
00155 
00156 struct JSTreeContext {              /* tree context for semantic checks */
00157     uint16          flags;          /* statement state flags, see below */
00158     uint16          numGlobalVars;  /* max. no. of global variables/regexps */
00159     uint32          tryCount;       /* total count of try statements parsed */
00160     uint32          globalUses;     /* optimizable global var uses in total */
00161     uint32          loopyGlobalUses;/* optimizable global var uses in loops */
00162     JSStmtInfo      *topStmt;       /* top of statement info stack */
00163     JSStmtInfo      *topScopeStmt;  /* top lexical scope statement */
00164     JSObject        *blockChain;    /* compile time block scope chain (NB: one
00165                                        deeper than the topScopeStmt/downScope
00166                                        chain when in head of let block/expr) */
00167     JSParseNode     *blockNode;     /* parse node for a lexical scope.
00168                                        XXX combine with blockChain? */
00169     JSAtomList      decls;          /* function, const, and var declarations */
00170     JSParseNode     *nodeList;      /* list of recyclable parse-node structs */
00171 };
00172 
00173 #define TCF_COMPILING          0x01 /* generating bytecode; this tc is a cg */
00174 #define TCF_IN_FUNCTION        0x02 /* parsing inside function body */
00175 #define TCF_RETURN_EXPR        0x04 /* function has 'return expr;' */
00176 #define TCF_RETURN_VOID        0x08 /* function has 'return;' */
00177 #define TCF_RETURN_FLAGS       0x0C /* propagate these out of blocks */
00178 #define TCF_IN_FOR_INIT        0x10 /* parsing init expr of for; exclude 'in' */
00179 #define TCF_FUN_CLOSURE_VS_VAR 0x20 /* function and var with same name */
00180 #define TCF_FUN_USES_NONLOCALS 0x40 /* function refers to non-local names */
00181 #define TCF_FUN_HEAVYWEIGHT    0x80 /* function needs Call object per call */
00182 #define TCF_FUN_IS_GENERATOR  0x100 /* parsed yield statement in function */
00183 #define TCF_FUN_FLAGS         0x1E0 /* flags to propagate from FunctionBody */
00184 #define TCF_HAS_DEFXMLNS      0x200 /* default xml namespace = ...; parsed */
00185 #define TCF_HAS_FUNCTION_STMT 0x400 /* block contains a function statement */
00186 
00187 #define TREE_CONTEXT_INIT(tc)                                                 \
00188     ((tc)->flags = (tc)->numGlobalVars = 0,                                   \
00189      (tc)->tryCount = (tc)->globalUses = (tc)->loopyGlobalUses = 0,           \
00190      (tc)->topStmt = (tc)->topScopeStmt = NULL,                               \
00191      (tc)->blockChain = NULL,                                                 \
00192      ATOM_LIST_INIT(&(tc)->decls),                                            \
00193      (tc)->nodeList = NULL, (tc)->blockNode = NULL)
00194 
00195 #define TREE_CONTEXT_FINISH(tc)                                               \
00196     ((void)0)
00197 
00198 /*
00199  * Span-dependent instructions are jumps whose span (from the jump bytecode to
00200  * the jump target) may require 2 or 4 bytes of immediate operand.
00201  */
00202 typedef struct JSSpanDep    JSSpanDep;
00203 typedef struct JSJumpTarget JSJumpTarget;
00204 
00205 struct JSSpanDep {
00206     ptrdiff_t       top;        /* offset of first bytecode in an opcode */
00207     ptrdiff_t       offset;     /* offset - 1 within opcode of jump operand */
00208     ptrdiff_t       before;     /* original offset - 1 of jump operand */
00209     JSJumpTarget    *target;    /* tagged target pointer or backpatch delta */
00210 };
00211 
00212 /*
00213  * Jump targets are stored in an AVL tree, for O(log(n)) lookup with targets
00214  * sorted by offset from left to right, so that targets after a span-dependent
00215  * instruction whose jump offset operand must be extended can be found quickly
00216  * and adjusted upward (toward higher offsets).
00217  */
00218 struct JSJumpTarget {
00219     ptrdiff_t       offset;     /* offset of span-dependent jump target */
00220     int             balance;    /* AVL tree balance number */
00221     JSJumpTarget    *kids[2];   /* left and right AVL tree child pointers */
00222 };
00223 
00224 #define JT_LEFT                 0
00225 #define JT_RIGHT                1
00226 #define JT_OTHER_DIR(dir)       (1 - (dir))
00227 #define JT_IMBALANCE(dir)       (((dir) << 1) - 1)
00228 #define JT_DIR(imbalance)       (((imbalance) + 1) >> 1)
00229 
00230 /*
00231  * Backpatch deltas are encoded in JSSpanDep.target if JT_TAG_BIT is clear,
00232  * so we can maintain backpatch chains when using span dependency records to
00233  * hold jump offsets that overflow 16 bits.
00234  */
00235 #define JT_TAG_BIT              ((jsword) 1)
00236 #define JT_UNTAG_SHIFT          1
00237 #define JT_SET_TAG(jt)          ((JSJumpTarget *)((jsword)(jt) | JT_TAG_BIT))
00238 #define JT_CLR_TAG(jt)          ((JSJumpTarget *)((jsword)(jt) & ~JT_TAG_BIT))
00239 #define JT_HAS_TAG(jt)          ((jsword)(jt) & JT_TAG_BIT)
00240 
00241 #define BITS_PER_PTRDIFF        (sizeof(ptrdiff_t) * JS_BITS_PER_BYTE)
00242 #define BITS_PER_BPDELTA        (BITS_PER_PTRDIFF - 1 - JT_UNTAG_SHIFT)
00243 #define BPDELTA_MAX             (((ptrdiff_t)1 << BITS_PER_BPDELTA) - 1)
00244 #define BPDELTA_TO_JT(bp)       ((JSJumpTarget *)((bp) << JT_UNTAG_SHIFT))
00245 #define JT_TO_BPDELTA(jt)       ((ptrdiff_t)((jsword)(jt) >> JT_UNTAG_SHIFT))
00246 
00247 #define SD_SET_TARGET(sd,jt)    ((sd)->target = JT_SET_TAG(jt))
00248 #define SD_GET_TARGET(sd)       (JS_ASSERT(JT_HAS_TAG((sd)->target)),         \
00249                                  JT_CLR_TAG((sd)->target))
00250 #define SD_SET_BPDELTA(sd,bp)   ((sd)->target = BPDELTA_TO_JT(bp))
00251 #define SD_GET_BPDELTA(sd)      (JS_ASSERT(!JT_HAS_TAG((sd)->target)),        \
00252                                  JT_TO_BPDELTA((sd)->target))
00253 
00254 /* Avoid asserting twice by expanding SD_GET_TARGET in the "then" clause. */
00255 #define SD_SPAN(sd,pivot)       (SD_GET_TARGET(sd)                            \
00256                                  ? JT_CLR_TAG((sd)->target)->offset - (pivot) \
00257                                  : 0)
00258 
00259 struct JSCodeGenerator {
00260     JSTreeContext   treeContext;    /* base state: statement info stack, etc. */
00261 
00262     JSArenaPool     *codePool;      /* pointer to thread code arena pool */
00263     JSArenaPool     *notePool;      /* pointer to thread srcnote arena pool */
00264     void            *codeMark;      /* low watermark in cg->codePool */
00265     void            *noteMark;      /* low watermark in cg->notePool */
00266     void            *tempMark;      /* low watermark in cx->tempPool */
00267 
00268     struct {
00269         jsbytecode  *base;          /* base of JS bytecode vector */
00270         jsbytecode  *limit;         /* one byte beyond end of bytecode */
00271         jsbytecode  *next;          /* pointer to next free bytecode */
00272         jssrcnote   *notes;         /* source notes, see below */
00273         uintN       noteCount;      /* number of source notes so far */
00274         uintN       noteMask;       /* growth increment for notes */
00275         ptrdiff_t   lastNoteOffset; /* code offset for last source note */
00276         uintN       currentLine;    /* line number for tree-based srcnote gen */
00277     } prolog, main, *current;
00278 
00279     const char      *filename;      /* null or weak link to source filename */
00280     uintN           firstLine;      /* first line, for js_NewScriptFromCG */
00281     JSPrincipals    *principals;    /* principals for constant folding eval */
00282     JSAtomList      atomList;       /* literals indexed for mapping */
00283 
00284     intN            stackDepth;     /* current stack depth in script frame */
00285     uintN           maxStackDepth;  /* maximum stack depth so far */
00286 
00287     JSTryNote       *tryBase;       /* first exception handling note */
00288     JSTryNote       *tryNext;       /* next available note */
00289     size_t          tryNoteSpace;   /* # of bytes allocated at tryBase */
00290 
00291     JSSpanDep       *spanDeps;      /* span dependent instruction records */
00292     JSJumpTarget    *jumpTargets;   /* AVL tree of jump target offsets */
00293     JSJumpTarget    *jtFreeList;    /* JT_LEFT-linked list of free structs */
00294     uintN           numSpanDeps;    /* number of span dependencies */
00295     uintN           numJumpTargets; /* number of jump targets */
00296     ptrdiff_t       spanDepTodo;    /* offset from main.base of potentially
00297                                        unoptimized spandeps */
00298 
00299     uintN           arrayCompSlot;  /* stack slot of array in comprehension */
00300 
00301     uintN           emitLevel;      /* js_EmitTree recursion level */
00302     JSAtomList      constList;      /* compile time constants */
00303     JSCodeGenerator *parent;        /* Enclosing function or global context */
00304 };
00305 
00306 #define CG_BASE(cg)             ((cg)->current->base)
00307 #define CG_LIMIT(cg)            ((cg)->current->limit)
00308 #define CG_NEXT(cg)             ((cg)->current->next)
00309 #define CG_CODE(cg,offset)      (CG_BASE(cg) + (offset))
00310 #define CG_OFFSET(cg)           PTRDIFF(CG_NEXT(cg), CG_BASE(cg), jsbytecode)
00311 
00312 #define CG_NOTES(cg)            ((cg)->current->notes)
00313 #define CG_NOTE_COUNT(cg)       ((cg)->current->noteCount)
00314 #define CG_NOTE_MASK(cg)        ((cg)->current->noteMask)
00315 #define CG_LAST_NOTE_OFFSET(cg) ((cg)->current->lastNoteOffset)
00316 #define CG_CURRENT_LINE(cg)     ((cg)->current->currentLine)
00317 
00318 #define CG_PROLOG_BASE(cg)      ((cg)->prolog.base)
00319 #define CG_PROLOG_LIMIT(cg)     ((cg)->prolog.limit)
00320 #define CG_PROLOG_NEXT(cg)      ((cg)->prolog.next)
00321 #define CG_PROLOG_CODE(cg,poff) (CG_PROLOG_BASE(cg) + (poff))
00322 #define CG_PROLOG_OFFSET(cg)    PTRDIFF(CG_PROLOG_NEXT(cg), CG_PROLOG_BASE(cg),\
00323                                         jsbytecode)
00324 
00325 #define CG_SWITCH_TO_MAIN(cg)   ((cg)->current = &(cg)->main)
00326 #define CG_SWITCH_TO_PROLOG(cg) ((cg)->current = &(cg)->prolog)
00327 
00328 /*
00329  * Initialize cg to allocate bytecode space from codePool, source note space
00330  * from notePool, and all other arena-allocated temporaries from cx->tempPool.
00331  * Return true on success.  Report an error and return false if the initial
00332  * code segment can't be allocated.
00333  */
00334 extern JS_FRIEND_API(JSBool)
00335 js_InitCodeGenerator(JSContext *cx, JSCodeGenerator *cg,
00336                      JSArenaPool *codePool, JSArenaPool *notePool,
00337                      const char *filename, uintN lineno,
00338                      JSPrincipals *principals);
00339 
00340 /*
00341  * Release cg->codePool, cg->notePool, and cx->tempPool to marks set by
00342  * js_InitCodeGenerator.  Note that cgs are magic: they own the arena pool
00343  * "tops-of-stack" space above their codeMark, noteMark, and tempMark points.
00344  * This means you cannot alloc from tempPool and save the pointer beyond the
00345  * next JS_FinishCodeGenerator.
00346  */
00347 extern JS_FRIEND_API(void)
00348 js_FinishCodeGenerator(JSContext *cx, JSCodeGenerator *cg);
00349 
00350 /*
00351  * Emit one bytecode.
00352  */
00353 extern ptrdiff_t
00354 js_Emit1(JSContext *cx, JSCodeGenerator *cg, JSOp op);
00355 
00356 /*
00357  * Emit two bytecodes, an opcode (op) with a byte of immediate operand (op1).
00358  */
00359 extern ptrdiff_t
00360 js_Emit2(JSContext *cx, JSCodeGenerator *cg, JSOp op, jsbytecode op1);
00361 
00362 /*
00363  * Emit three bytecodes, an opcode with two bytes of immediate operands.
00364  */
00365 extern ptrdiff_t
00366 js_Emit3(JSContext *cx, JSCodeGenerator *cg, JSOp op, jsbytecode op1,
00367          jsbytecode op2);
00368 
00369 /*
00370  * Emit (1 + extra) bytecodes, for N bytes of op and its immediate operand.
00371  */
00372 extern ptrdiff_t
00373 js_EmitN(JSContext *cx, JSCodeGenerator *cg, JSOp op, size_t extra);
00374 
00375 /*
00376  * Unsafe macro to call js_SetJumpOffset and return false if it does.
00377  */
00378 #define CHECK_AND_SET_JUMP_OFFSET(cx,cg,pc,off)                               \
00379     JS_BEGIN_MACRO                                                            \
00380         if (!js_SetJumpOffset(cx, cg, pc, off))                               \
00381             return JS_FALSE;                                                  \
00382     JS_END_MACRO
00383 
00384 #define CHECK_AND_SET_JUMP_OFFSET_AT(cx,cg,off)                               \
00385     CHECK_AND_SET_JUMP_OFFSET(cx, cg, CG_CODE(cg,off), CG_OFFSET(cg) - (off))
00386 
00387 extern JSBool
00388 js_SetJumpOffset(JSContext *cx, JSCodeGenerator *cg, jsbytecode *pc,
00389                  ptrdiff_t off);
00390 
00391 /* Test whether we're in a statement of given type. */
00392 extern JSBool
00393 js_InStatement(JSTreeContext *tc, JSStmtType type);
00394 
00395 /* Test whether we're in a with statement. */
00396 #define js_InWithStatement(tc)      js_InStatement(tc, STMT_WITH)
00397 
00398 /*
00399  * Test whether atom refers to a global variable (or is a reference error).
00400  * Return true in *loopyp if any loops enclose the lexical reference, false
00401  * otherwise.
00402  */
00403 extern JSBool
00404 js_IsGlobalReference(JSTreeContext *tc, JSAtom *atom, JSBool *loopyp);
00405 
00406 /*
00407  * Push the C-stack-allocated struct at stmt onto the stmtInfo stack.
00408  */
00409 extern void
00410 js_PushStatement(JSTreeContext *tc, JSStmtInfo *stmt, JSStmtType type,
00411                  ptrdiff_t top);
00412 
00413 /*
00414  * Push a block scope statement and link blockAtom's object-valued key into
00415  * tc->blockChain.  To pop this statement info record, use js_PopStatement as
00416  * usual, or if appropriate (if generating code), js_PopStatementCG.
00417  */
00418 extern void
00419 js_PushBlockScope(JSTreeContext *tc, JSStmtInfo *stmt, JSAtom *blockAtom,
00420                   ptrdiff_t top);
00421 
00422 /*
00423  * Pop tc->topStmt.  If the top JSStmtInfo struct is not stack-allocated, it
00424  * is up to the caller to free it.
00425  */
00426 extern void
00427 js_PopStatement(JSTreeContext *tc);
00428 
00429 /*
00430  * Like js_PopStatement(&cg->treeContext), also patch breaks and continues
00431  * unless the top statement info record represents a try-catch-finally suite.
00432  * May fail if a jump offset overflows.
00433  */
00434 extern JSBool
00435 js_PopStatementCG(JSContext *cx, JSCodeGenerator *cg);
00436 
00437 /*
00438  * Define and lookup a primitive jsval associated with the const named by atom.
00439  * js_DefineCompileTimeConstant analyzes the constant-folded initializer at pn
00440  * and saves the const's value in cg->constList, if it can be used at compile
00441  * time.  It returns true unless an error occurred.
00442  *
00443  * If the initializer's value could not be saved, js_LookupCompileTimeConstant
00444  * calls will return the undefined value.  js_LookupCompileTimeConstant tries
00445  * to find a const value memorized for atom, returning true with *vp set to a
00446  * value other than undefined if the constant was found, true with *vp set to
00447  * JSVAL_VOID if not found, and false on error.
00448  */
00449 extern JSBool
00450 js_DefineCompileTimeConstant(JSContext *cx, JSCodeGenerator *cg, JSAtom *atom,
00451                              JSParseNode *pn);
00452 
00453 extern JSBool
00454 js_LookupCompileTimeConstant(JSContext *cx, JSCodeGenerator *cg, JSAtom *atom,
00455                              jsval *vp);
00456 
00457 /*
00458  * Find a lexically scoped variable (one declared by let, catch, or an array
00459  * comprehension) named by atom, looking in tc's compile-time scopes.
00460  *
00461  * If a WITH statement is reached along the scope stack, return its statement
00462  * info record, so callers can tell that atom is ambiguous.  If slotp is not
00463  * null, then if atom is found, set *slotp to its stack slot, otherwise to -1.
00464  * This means that if slotp is not null, all the block objects on the lexical
00465  * scope chain must have had their depth slots computed by the code generator,
00466  * so the caller must be under js_EmitTree.
00467  *
00468  * In any event, directly return the statement info record in which atom was
00469  * found.  Otherwise return null.
00470  */
00471 extern JSStmtInfo *
00472 js_LexicalLookup(JSTreeContext *tc, JSAtom *atom, jsint *slotp,
00473                  JSBool letdecl);
00474 
00475 /*
00476  * Emit code into cg for the tree rooted at pn.
00477  */
00478 extern JSBool
00479 js_EmitTree(JSContext *cx, JSCodeGenerator *cg, JSParseNode *pn);
00480 
00481 /*
00482  * Emit function code into cg for the tree rooted at body.
00483  */
00484 extern JSBool
00485 js_EmitFunctionBytecode(JSContext *cx, JSCodeGenerator *cg, JSParseNode *body);
00486 
00487 /*
00488  * Emit code into cg for the tree rooted at body, then create a persistent
00489  * script for fun from cg.
00490  */
00491 extern JSBool
00492 js_EmitFunctionBody(JSContext *cx, JSCodeGenerator *cg, JSParseNode *body,
00493                     JSFunction *fun);
00494 
00495 /*
00496  * Source notes generated along with bytecode for decompiling and debugging.
00497  * A source note is a uint8 with 5 bits of type and 3 of offset from the pc of
00498  * the previous note.  If 3 bits of offset aren't enough, extended delta notes
00499  * (SRC_XDELTA) consisting of 2 set high order bits followed by 6 offset bits
00500  * are emitted before the next note.  Some notes have operand offsets encoded
00501  * immediately after them, in note bytes or byte-triples.
00502  *
00503  *                 Source Note               Extended Delta
00504  *              +7-6-5-4-3+2-1-0+           +7-6-5+4-3-2-1-0+
00505  *              |note-type|delta|           |1 1| ext-delta |
00506  *              +---------+-----+           +---+-----------+
00507  *
00508  * At most one "gettable" note (i.e., a note of type other than SRC_NEWLINE,
00509  * SRC_SETLINE, and SRC_XDELTA) applies to a given bytecode.
00510  *
00511  * NB: the js_SrcNoteSpec array in jsemit.c is indexed by this enum, so its
00512  * initializers need to match the order here.
00513  *
00514  * Note on adding new source notes: every pair of bytecodes (A, B) where A and
00515  * B have disjoint sets of source notes that could apply to each bytecode may
00516  * reuse the same note type value for two notes (snA, snB) that have the same
00517  * arity, offsetBias, and isSpanDep initializers in js_SrcNoteSpec.  This is
00518  * why SRC_IF and SRC_INITPROP have the same value below.  For bad historical
00519  * reasons, some bytecodes below that could be overlayed have not been, but
00520  * before using SRC_EXTENDED, consider compressing the existing note types.
00521  *
00522  * Don't forget to update JSXDR_BYTECODE_VERSION in jsxdrapi.h for all such
00523  * incompatible source note or other bytecode changes.
00524  */
00525 typedef enum JSSrcNoteType {
00526     SRC_NULL        = 0,        /* terminates a note vector */
00527     SRC_IF          = 1,        /* JSOP_IFEQ bytecode is from an if-then */
00528     SRC_INITPROP    = 1,        /* disjoint meaning applied to JSOP_INITELEM or
00529                                    to an index label in a regular (structuring)
00530                                    or a destructuring object initialiser */
00531     SRC_IF_ELSE     = 2,        /* JSOP_IFEQ bytecode is from an if-then-else */
00532     SRC_WHILE       = 3,        /* JSOP_IFEQ is from a while loop */
00533     SRC_FOR         = 4,        /* JSOP_NOP or JSOP_POP in for loop head */
00534     SRC_CONTINUE    = 5,        /* JSOP_GOTO is a continue, not a break;
00535                                    also used on JSOP_ENDINIT if extra comma
00536                                    at end of array literal: [1,2,,] */
00537     SRC_DECL        = 6,        /* type of a declaration (var, const, let*) */
00538     SRC_DESTRUCT    = 6,        /* JSOP_DUP starting a destructuring assignment
00539                                    operation, with SRC_DECL_* offset operand */
00540     SRC_PCDELTA     = 7,        /* distance forward from comma-operator to
00541                                    next POP, or from CONDSWITCH to first CASE
00542                                    opcode, etc. -- always a forward delta */
00543     SRC_GROUPASSIGN = 7,        /* SRC_DESTRUCT variant for [a, b] = [c, d] */
00544     SRC_ASSIGNOP    = 8,        /* += or another assign-op follows */
00545     SRC_COND        = 9,        /* JSOP_IFEQ is from conditional ?: operator */
00546     SRC_BRACE       = 10,       /* mandatory brace, for scope or to avoid
00547                                    dangling else */
00548     SRC_HIDDEN      = 11,       /* opcode shouldn't be decompiled */
00549     SRC_PCBASE      = 12,       /* distance back from annotated getprop or
00550                                    setprop op to left-most obj.prop.subprop
00551                                    bytecode -- always a backward delta */
00552     SRC_METHODBASE  = 13,       /* SRC_PCBASE variant for obj.function::foo
00553                                    gets and sets; disjoint from SRC_LABEL by
00554                                    bytecode to which it applies */
00555     SRC_LABEL       = 13,       /* JSOP_NOP for label: with atomid immediate */
00556     SRC_LABELBRACE  = 14,       /* JSOP_NOP for label: {...} begin brace */
00557     SRC_ENDBRACE    = 15,       /* JSOP_NOP for label: {...} end brace */
00558     SRC_BREAK2LABEL = 16,       /* JSOP_GOTO for 'break label' with atomid */
00559     SRC_CONT2LABEL  = 17,       /* JSOP_GOTO for 'continue label' with atomid */
00560     SRC_SWITCH      = 18,       /* JSOP_*SWITCH with offset to end of switch,
00561                                    2nd off to first JSOP_CASE if condswitch */
00562     SRC_FUNCDEF     = 19,       /* JSOP_NOP for function f() with atomid */
00563     SRC_CATCH       = 20,       /* catch block has guard */
00564     SRC_EXTENDED    = 21,       /* extended source note, 32-159, in next byte */
00565     SRC_NEWLINE     = 22,       /* bytecode follows a source newline */
00566     SRC_SETLINE     = 23,       /* a file-absolute source line number note */
00567     SRC_XDELTA      = 24        /* 24-31 are for extended delta notes */
00568 } JSSrcNoteType;
00569 
00570 /*
00571  * Constants for the SRC_DECL source note.  Note that span-dependent bytecode
00572  * selection means that any SRC_DECL offset greater than SRC_DECL_LET may need
00573  * to be adjusted, but these "offsets" are too small to span a span-dependent
00574  * instruction, so can be used to denote distinct declaration syntaxes to the
00575  * decompiler.
00576  *
00577  * NB: the var_prefix array in jsopcode.c depends on these dense indexes from
00578  * SRC_DECL_VAR through SRC_DECL_LET.
00579  */
00580 #define SRC_DECL_VAR            0
00581 #define SRC_DECL_CONST          1
00582 #define SRC_DECL_LET            2
00583 #define SRC_DECL_NONE           3
00584 
00585 #define SN_TYPE_BITS            5
00586 #define SN_DELTA_BITS           3
00587 #define SN_XDELTA_BITS          6
00588 #define SN_TYPE_MASK            (JS_BITMASK(SN_TYPE_BITS) << SN_DELTA_BITS)
00589 #define SN_DELTA_MASK           ((ptrdiff_t)JS_BITMASK(SN_DELTA_BITS))
00590 #define SN_XDELTA_MASK          ((ptrdiff_t)JS_BITMASK(SN_XDELTA_BITS))
00591 
00592 #define SN_MAKE_NOTE(sn,t,d)    (*(sn) = (jssrcnote)                          \
00593                                           (((t) << SN_DELTA_BITS)             \
00594                                            | ((d) & SN_DELTA_MASK)))
00595 #define SN_MAKE_XDELTA(sn,d)    (*(sn) = (jssrcnote)                          \
00596                                           ((SRC_XDELTA << SN_DELTA_BITS)      \
00597                                            | ((d) & SN_XDELTA_MASK)))
00598 
00599 #define SN_IS_XDELTA(sn)        ((*(sn) >> SN_DELTA_BITS) >= SRC_XDELTA)
00600 #define SN_TYPE(sn)             (SN_IS_XDELTA(sn) ? SRC_XDELTA                \
00601                                                   : *(sn) >> SN_DELTA_BITS)
00602 #define SN_SET_TYPE(sn,type)    SN_MAKE_NOTE(sn, type, SN_DELTA(sn))
00603 #define SN_IS_GETTABLE(sn)      (SN_TYPE(sn) < SRC_NEWLINE)
00604 
00605 #define SN_DELTA(sn)            ((ptrdiff_t)(SN_IS_XDELTA(sn)                 \
00606                                              ? *(sn) & SN_XDELTA_MASK         \
00607                                              : *(sn) & SN_DELTA_MASK))
00608 #define SN_SET_DELTA(sn,delta)  (SN_IS_XDELTA(sn)                             \
00609                                  ? SN_MAKE_XDELTA(sn, delta)                  \
00610                                  : SN_MAKE_NOTE(sn, SN_TYPE(sn), delta))
00611 
00612 #define SN_DELTA_LIMIT          ((ptrdiff_t)JS_BIT(SN_DELTA_BITS))
00613 #define SN_XDELTA_LIMIT         ((ptrdiff_t)JS_BIT(SN_XDELTA_BITS))
00614 
00615 /*
00616  * Offset fields follow certain notes and are frequency-encoded: an offset in
00617  * [0,0x7f] consumes one byte, an offset in [0x80,0x7fffff] takes three, and
00618  * the high bit of the first byte is set.
00619  */
00620 #define SN_3BYTE_OFFSET_FLAG    0x80
00621 #define SN_3BYTE_OFFSET_MASK    0x7f
00622 
00623 typedef struct JSSrcNoteSpec {
00624     const char      *name;      /* name for disassembly/debugging output */
00625     uint8           arity;      /* number of offset operands */
00626     uint8           offsetBias; /* bias of offset(s) from annotated pc */
00627     int8            isSpanDep;  /* 1 or -1 if offsets could span extended ops,
00628                                    0 otherwise; sign tells span direction */
00629 } JSSrcNoteSpec;
00630 
00631 extern JS_FRIEND_DATA(JSSrcNoteSpec) js_SrcNoteSpec[];
00632 extern JS_FRIEND_API(uintN)          js_SrcNoteLength(jssrcnote *sn);
00633 
00634 #define SN_LENGTH(sn)           ((js_SrcNoteSpec[SN_TYPE(sn)].arity == 0) ? 1 \
00635                                  : js_SrcNoteLength(sn))
00636 #define SN_NEXT(sn)             ((sn) + SN_LENGTH(sn))
00637 
00638 /* A source note array is terminated by an all-zero element. */
00639 #define SN_MAKE_TERMINATOR(sn)  (*(sn) = SRC_NULL)
00640 #define SN_IS_TERMINATOR(sn)    (*(sn) == SRC_NULL)
00641 
00642 /*
00643  * Append a new source note of the given type (and therefore size) to cg's
00644  * notes dynamic array, updating cg->noteCount.  Return the new note's index
00645  * within the array pointed at by cg->current->notes.  Return -1 if out of
00646  * memory.
00647  */
00648 extern intN
00649 js_NewSrcNote(JSContext *cx, JSCodeGenerator *cg, JSSrcNoteType type);
00650 
00651 extern intN
00652 js_NewSrcNote2(JSContext *cx, JSCodeGenerator *cg, JSSrcNoteType type,
00653                ptrdiff_t offset);
00654 
00655 extern intN
00656 js_NewSrcNote3(JSContext *cx, JSCodeGenerator *cg, JSSrcNoteType type,
00657                ptrdiff_t offset1, ptrdiff_t offset2);
00658 
00659 /*
00660  * NB: this function can add at most one extra extended delta note.
00661  */
00662 extern jssrcnote *
00663 js_AddToSrcNoteDelta(JSContext *cx, JSCodeGenerator *cg, jssrcnote *sn,
00664                      ptrdiff_t delta);
00665 
00666 /*
00667  * Get and set the offset operand identified by which (0 for the first, etc.).
00668  */
00669 extern JS_FRIEND_API(ptrdiff_t)
00670 js_GetSrcNoteOffset(jssrcnote *sn, uintN which);
00671 
00672 extern JSBool
00673 js_SetSrcNoteOffset(JSContext *cx, JSCodeGenerator *cg, uintN index,
00674                     uintN which, ptrdiff_t offset);
00675 
00676 /*
00677  * Finish taking source notes in cx's notePool, copying final notes to the new
00678  * stable store allocated by the caller and passed in via notes.  Return false
00679  * on malloc failure, which means this function reported an error.
00680  *
00681  * To compute the number of jssrcnotes to allocate and pass in via notes, use
00682  * the CG_COUNT_FINAL_SRCNOTES macro.  This macro knows a lot about details of
00683  * js_FinishTakingSrcNotes, SO DON'T CHANGE jsemit.c's js_FinishTakingSrcNotes
00684  * FUNCTION WITHOUT CHECKING WHETHER THIS MACRO NEEDS CORRESPONDING CHANGES!
00685  */
00686 #define CG_COUNT_FINAL_SRCNOTES(cg, cnt)                                      \
00687     JS_BEGIN_MACRO                                                            \
00688         ptrdiff_t diff_ = CG_PROLOG_OFFSET(cg) - (cg)->prolog.lastNoteOffset; \
00689         cnt = (cg)->prolog.noteCount + (cg)->main.noteCount + 1;              \
00690         if ((cg)->prolog.noteCount &&                                         \
00691             (cg)->prolog.currentLine != (cg)->firstLine) {                    \
00692             if (diff_ > SN_DELTA_MASK)                                        \
00693                 cnt += JS_HOWMANY(diff_ - SN_DELTA_MASK, SN_XDELTA_MASK);     \
00694             cnt += 2 + (((cg)->firstLine > SN_3BYTE_OFFSET_MASK) << 1);       \
00695         } else if (diff_ > 0) {                                               \
00696             if (cg->main.noteCount) {                                         \
00697                 jssrcnote *sn_ = (cg)->main.notes;                            \
00698                 diff_ -= SN_IS_XDELTA(sn_)                                    \
00699                          ? SN_XDELTA_MASK - (*sn_ & SN_XDELTA_MASK)           \
00700                          : SN_DELTA_MASK - (*sn_ & SN_DELTA_MASK);            \
00701             }                                                                 \
00702             if (diff_ > 0)                                                    \
00703                 cnt += JS_HOWMANY(diff_, SN_XDELTA_MASK);                     \
00704         }                                                                     \
00705     JS_END_MACRO
00706 
00707 extern JSBool
00708 js_FinishTakingSrcNotes(JSContext *cx, JSCodeGenerator *cg, jssrcnote *notes);
00709 
00710 /*
00711  * Allocate cg->treeContext.tryCount notes (plus one for the end sentinel)
00712  * from cx->tempPool and set up cg->tryBase/tryNext for exactly tryCount
00713  * js_NewTryNote calls.  The storage is freed by js_FinishCodeGenerator.
00714  */
00715 extern JSBool
00716 js_AllocTryNotes(JSContext *cx, JSCodeGenerator *cg);
00717 
00718 /*
00719  * Grab the next trynote slot in cg, filling it in appropriately.
00720  */
00721 extern JSTryNote *
00722 js_NewTryNote(JSContext *cx, JSCodeGenerator *cg, ptrdiff_t start,
00723               ptrdiff_t end, ptrdiff_t catchStart);
00724 
00725 /*
00726  * Finish generating exception information into the space at notes.  As with
00727  * js_FinishTakingSrcNotes, the caller must use CG_COUNT_FINAL_TRYNOTES(cg) to
00728  * preallocate enough space in a JSTryNote[] to pass as the notes parameter of
00729  * js_FinishTakingTryNotes.
00730  */
00731 #define CG_COUNT_FINAL_TRYNOTES(cg, cnt)                                      \
00732     JS_BEGIN_MACRO                                                            \
00733         cnt = ((cg)->tryNext > (cg)->tryBase)                                 \
00734               ? PTRDIFF(cg->tryNext, cg->tryBase, JSTryNote) + 1              \
00735               : 0;                                                            \
00736     JS_END_MACRO
00737 
00738 extern void
00739 js_FinishTakingTryNotes(JSContext *cx, JSCodeGenerator *cg, JSTryNote *notes);
00740 
00741 JS_END_EXTERN_C
00742 
00743 #endif /* jsemit_h___ */