1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=99:
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
17 * The Original Code is Mozilla Communicator client code, released
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.
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 ***** */
44 * This is a recursive-descent parser for the JavaScript language specified by
45 * "The JavaScript 1.5 Language Specification". It uses lexical and semantic
46 * feedback to disambiguate non-LL(1) structures. It generates trees of nodes
47 * induced by the recursive parsing (not precise syntax trees, see jsparse.h).
48 * After tree construction, it rewrites trees to fold constants and evaluate
49 * compile-time expressions. Finally, it calls js_EmitTree (see jsemit.h) to
52 * This parser attempts no error recovery.
59 #include "jsarena.h" /* Added by JSIFY */
60 #include "jsutil.h" /* Added by JSIFY */
65 #include "jsversion.h"
79 #include "jsstaticcheck.h"
80 #include "jslibmath.h"
83 #if JS_HAS_XML_SUPPORT
87 #if JS_HAS_DESTRUCTURING
94 * Asserts to verify assumptions behind pn_ macros.
96 #define pn_offsetof(m) offsetof(JSParseNode, m)
98 JS_STATIC_ASSERT(pn_offsetof(pn_link
) == pn_offsetof(dn_uses
));
99 JS_STATIC_ASSERT(pn_offsetof(pn_u
.name
.atom
) == pn_offsetof(pn_u
.apair
.atom
));
104 * Insist that the next token be of type tt, or report errno and return null.
105 * NB: this macro uses cx and ts from its lexical environment.
107 #define MUST_MATCH_TOKEN_WITH_FLAGS(tt, errno, __flags) \
109 if (tokenStream.getToken((__flags)) != tt) { \
110 reportErrorNumber(NULL, JSREPORT_ERROR, errno); \
114 #define MUST_MATCH_TOKEN(tt, errno) MUST_MATCH_TOKEN_WITH_FLAGS(tt, errno, 0)
116 #ifdef METER_PARSENODES
117 static uint32 parsenodes
= 0;
118 static uint32 maxparsenodes
= 0;
119 static uint32 recyclednodes
= 0;
123 JSParseNode::become(JSParseNode
*pn2
)
126 JS_ASSERT(!pn2
->pn_defn
);
130 JSParseNode
**pnup
= &pn2
->pn_lexdef
->dn_uses
;
132 pnup
= &(*pnup
)->pn_link
;
134 pn_link
= pn2
->pn_link
;
137 pn2
->pn_used
= false;
140 /* If this is a function node fix up the pn_funbox->node back-pointer. */
141 if (PN_TYPE(pn2
) == TOK_FUNCTION
&& pn2
->pn_arity
== PN_FUNC
)
142 pn2
->pn_funbox
->node
= this;
144 pn_type
= pn2
->pn_type
;
146 pn_arity
= pn2
->pn_arity
;
147 pn_parens
= pn2
->pn_parens
;
157 pn_used
= pn_defn
= false;
158 pn_arity
= PN_NULLARY
;
163 Parser::init(const jschar
*base
, size_t length
,
164 FILE *fp
, const char *filename
, uintN lineno
)
166 JSContext
*cx
= context
;
168 tempPoolMark
= JS_ARENA_MARK(&cx
->tempPool
);
169 if (!tokenStream
.init(base
, length
, fp
, filename
, lineno
)) {
170 JS_ARENA_RELEASE(&cx
->tempPool
, tempPoolMark
);
178 JSContext
*cx
= context
;
181 JSPRINCIPALS_DROP(cx
, principals
);
183 JS_ARENA_RELEASE(&cx
->tempPool
, tempPoolMark
);
187 Parser::setPrincipals(JSPrincipals
*prin
)
189 JS_ASSERT(!principals
);
191 JSPRINCIPALS_HOLD(context
, prin
);
196 Parser::newObjectBox(JSObject
*obj
)
201 * We use JSContext.tempPool to allocate parsed objects and place them on
202 * a list in this Parser to ensure GC safety. Thus the tempPool arenas
203 * containing the entries must be alive until we are done with scanning,
204 * parsing and code generation for the whole script or top-level function.
207 JS_ARENA_ALLOCATE_TYPE(objbox
, JSObjectBox
, &context
->tempPool
);
209 js_ReportOutOfScriptQuota(context
);
212 objbox
->traceLink
= traceListHead
;
213 traceListHead
= objbox
;
214 objbox
->emitLink
= NULL
;
215 objbox
->object
= obj
;
220 Parser::newFunctionBox(JSObject
*obj
, JSParseNode
*fn
, JSTreeContext
*tc
)
223 JS_ASSERT(obj
->isFunction());
226 * We use JSContext.tempPool to allocate parsed objects and place them on
227 * a list in this Parser to ensure GC safety. Thus the tempPool arenas
228 * containing the entries must be alive until we are done with scanning,
229 * parsing and code generation for the whole script or top-level function.
231 JSFunctionBox
*funbox
;
232 JS_ARENA_ALLOCATE_TYPE(funbox
, JSFunctionBox
, &context
->tempPool
);
234 js_ReportOutOfScriptQuota(context
);
237 funbox
->traceLink
= traceListHead
;
238 traceListHead
= funbox
;
239 funbox
->emitLink
= NULL
;
240 funbox
->object
= obj
;
242 funbox
->siblings
= tc
->functionList
;
243 tc
->functionList
= funbox
;
244 ++tc
->parser
->functionCount
;
246 funbox
->parent
= tc
->funbox
;
247 funbox
->methods
= NULL
;
248 funbox
->queued
= false;
249 funbox
->inLoop
= false;
250 for (JSStmtInfo
*stmt
= tc
->topStmt
; stmt
; stmt
= stmt
->down
) {
251 if (STMT_IS_LOOP(stmt
)) {
252 funbox
->inLoop
= true;
256 funbox
->level
= tc
->staticLevel
;
257 funbox
->tcflags
= (TCF_IN_FUNCTION
| (tc
->flags
& (TCF_COMPILE_N_GO
| TCF_STRICT_MODE_CODE
)));
262 JSFunctionBox::joinable() const
264 return FUN_NULL_CLOSURE((JSFunction
*) object
) &&
265 !(tcflags
& (TCF_FUN_USES_ARGUMENTS
| TCF_FUN_USES_OWN_NAME
));
269 JSFunctionBox::shouldUnbrand(uintN methods
, uintN slowMethods
) const
271 if (slowMethods
!= 0) {
272 for (const JSFunctionBox
*funbox
= this; funbox
; funbox
= funbox
->parent
) {
273 if (!(funbox
->tcflags
& TCF_FUN_MODULE_PATTERN
))
283 Parser::trace(JSTracer
*trc
)
285 JSObjectBox
*objbox
= traceListHead
;
287 JS_CALL_OBJECT_TRACER(trc
, objbox
->object
, "parser.object");
288 objbox
= objbox
->traceLink
;
293 UnlinkFunctionBoxes(JSParseNode
*pn
, JSTreeContext
*tc
);
296 UnlinkFunctionBox(JSParseNode
*pn
, JSTreeContext
*tc
)
298 JSFunctionBox
*funbox
= pn
->pn_funbox
;
300 JS_ASSERT(funbox
->node
== pn
);
303 if (funbox
->parent
&& PN_OP(pn
) == JSOP_LAMBDA
) {
305 * Remove pn from funbox->parent's methods list if it's there. See
306 * the TOK_SEMI case in Statement, near the bottom, the TOK_ASSIGN
307 * sub-case matching a constructor method assignment pattern.
309 JS_ASSERT(!pn
->pn_defn
);
310 JS_ASSERT(!pn
->pn_used
);
311 JSParseNode
**pnp
= &funbox
->parent
->methods
;
312 while (JSParseNode
*method
= *pnp
) {
314 *pnp
= method
->pn_link
;
317 pnp
= &method
->pn_link
;
321 JSFunctionBox
**funboxp
= &tc
->functionList
;
323 if (*funboxp
== funbox
) {
324 *funboxp
= funbox
->siblings
;
327 funboxp
= &(*funboxp
)->siblings
;
330 uint32 oldflags
= tc
->flags
;
331 JSFunctionBox
*oldlist
= tc
->functionList
;
333 tc
->flags
= funbox
->tcflags
;
334 tc
->functionList
= funbox
->kids
;
335 UnlinkFunctionBoxes(pn
->pn_body
, tc
);
336 funbox
->kids
= tc
->functionList
;
337 tc
->flags
= oldflags
;
338 tc
->functionList
= oldlist
;
340 // FIXME: use a funbox freelist (consolidate aleFreeList and nodeList).
341 pn
->pn_funbox
= NULL
;
346 UnlinkFunctionBoxes(JSParseNode
*pn
, JSTreeContext
*tc
)
349 switch (pn
->pn_arity
) {
353 UnlinkFunctionBoxes(pn
->pn_kid
, tc
);
356 UnlinkFunctionBoxes(pn
->pn_left
, tc
);
357 UnlinkFunctionBoxes(pn
->pn_right
, tc
);
360 UnlinkFunctionBoxes(pn
->pn_kid1
, tc
);
361 UnlinkFunctionBoxes(pn
->pn_kid2
, tc
);
362 UnlinkFunctionBoxes(pn
->pn_kid3
, tc
);
365 for (JSParseNode
*pn2
= pn
->pn_head
; pn2
; pn2
= pn2
->pn_next
)
366 UnlinkFunctionBoxes(pn2
, tc
);
369 UnlinkFunctionBox(pn
, tc
);
372 UnlinkFunctionBoxes(pn
->maybeExpr(), tc
);
375 UnlinkFunctionBoxes(pn
->pn_tree
, tc
);
381 RecycleFuncNameKids(JSParseNode
*pn
, JSTreeContext
*tc
);
384 RecycleTree(JSParseNode
*pn
, JSTreeContext
*tc
)
386 JSParseNode
*next
, **head
;
391 /* Catch back-to-back dup recycles. */
392 JS_ASSERT(pn
!= tc
->parser
->nodeList
);
394 if (pn
->pn_used
|| pn
->pn_defn
) {
396 * JSAtomLists own definition nodes along with their used-node chains.
397 * Defer recycling such nodes until we unwind to top level to avoid
398 * linkage overhead or (alternatively) unlinking runtime complexity.
399 * Yes, this means dead code can contribute to static analysis results!
401 * Do recycle kids here, since they are no longer needed.
404 RecycleFuncNameKids(pn
, tc
);
406 UnlinkFunctionBoxes(pn
, tc
);
407 head
= &tc
->parser
->nodeList
;
410 #ifdef METER_PARSENODES
418 RecycleFuncNameKids(JSParseNode
*pn
, JSTreeContext
*tc
)
420 switch (pn
->pn_arity
) {
422 UnlinkFunctionBox(pn
, tc
);
427 * Only a definition node might have a non-null strong pn_expr link
428 * to recycle, but we test !pn_used to handle PN_FUNC fall through.
429 * Every node with the pn_used flag set has a non-null pn_lexdef
430 * weak reference to its definition node.
432 if (!pn
->pn_used
&& pn
->pn_expr
) {
433 RecycleTree(pn
->pn_expr
, tc
);
439 JS_ASSERT(PN_TYPE(pn
) == TOK_FUNCTION
);
444 * Allocate a JSParseNode from tc's node freelist or, failing that, from cx's
448 NewOrRecycledNode(JSTreeContext
*tc
)
450 JSParseNode
*pn
, *pn2
;
452 pn
= tc
->parser
->nodeList
;
454 JSContext
*cx
= tc
->parser
->context
;
456 JS_ARENA_ALLOCATE_TYPE(pn
, JSParseNode
, &cx
->tempPool
);
458 js_ReportOutOfScriptQuota(cx
);
460 tc
->parser
->nodeList
= pn
->pn_next
;
462 /* Recycle immediate descendents only, to save work and working set. */
463 switch (pn
->pn_arity
) {
465 RecycleTree(pn
->pn_body
, tc
);
470 while (pn2
&& !pn2
->pn_used
&& !pn2
->pn_defn
)
475 pn2
= RecycleTree(pn2
, tc
);
478 *pn
->pn_tail
= tc
->parser
->nodeList
;
479 tc
->parser
->nodeList
= pn
->pn_head
;
480 #ifdef METER_PARSENODES
481 recyclednodes
+= pn
->pn_count
;
488 RecycleTree(pn
->pn_kid1
, tc
);
489 RecycleTree(pn
->pn_kid2
, tc
);
490 RecycleTree(pn
->pn_kid3
, tc
);
493 if (pn
->pn_left
!= pn
->pn_right
)
494 RecycleTree(pn
->pn_left
, tc
);
495 RecycleTree(pn
->pn_right
, tc
);
498 RecycleTree(pn
->pn_kid
, tc
);
502 RecycleTree(pn
->pn_expr
, tc
);
509 #ifdef METER_PARSENODES
511 if (parsenodes
- recyclednodes
> maxparsenodes
)
512 maxparsenodes
= parsenodes
- recyclednodes
;
514 pn
->pn_used
= pn
->pn_defn
= false;
515 memset(&pn
->pn_u
, 0, sizeof pn
->pn_u
);
521 /* used only by static create methods of subclasses */
524 JSParseNode::create(JSParseNodeArity arity
, JSTreeContext
*tc
)
526 JSParseNode
*pn
= NewOrRecycledNode(tc
);
529 const Token
&tok
= tc
->parser
->tokenStream
.currentToken();
530 pn
->init(tok
.type
, JSOP_NOP
, arity
);
531 pn
->pn_pos
= tok
.pos
;
536 JSParseNode::newBinaryOrAppend(TokenKind tt
, JSOp op
, JSParseNode
*left
, JSParseNode
*right
,
539 JSParseNode
*pn
, *pn1
, *pn2
;
545 * Flatten a left-associative (left-heavy) tree of a given operator into
546 * a list, to reduce js_FoldConstants and js_EmitTree recursion.
548 if (PN_TYPE(left
) == tt
&&
550 (js_CodeSpec
[op
].format
& JOF_LEFTASSOC
)) {
551 if (left
->pn_arity
!= PN_LIST
) {
552 pn1
= left
->pn_left
, pn2
= left
->pn_right
;
553 left
->pn_arity
= PN_LIST
;
554 left
->pn_parens
= false;
557 if (tt
== TOK_PLUS
) {
558 if (pn1
->pn_type
== TOK_STRING
)
559 left
->pn_xflags
|= PNX_STRCAT
;
560 else if (pn1
->pn_type
!= TOK_NUMBER
)
561 left
->pn_xflags
|= PNX_CANTFOLD
;
562 if (pn2
->pn_type
== TOK_STRING
)
563 left
->pn_xflags
|= PNX_STRCAT
;
564 else if (pn2
->pn_type
!= TOK_NUMBER
)
565 left
->pn_xflags
|= PNX_CANTFOLD
;
569 left
->pn_pos
.end
= right
->pn_pos
.end
;
570 if (tt
== TOK_PLUS
) {
571 if (right
->pn_type
== TOK_STRING
)
572 left
->pn_xflags
|= PNX_STRCAT
;
573 else if (right
->pn_type
!= TOK_NUMBER
)
574 left
->pn_xflags
|= PNX_CANTFOLD
;
580 * Fold constant addition immediately, to conserve node space and, what's
581 * more, so js_FoldConstants never sees mixed addition and concatenation
582 * operations with more than one leading non-string operand in a PN_LIST
583 * generated for expressions such as 1 + 2 + "pt" (which should evaluate
584 * to "3pt", not "12pt").
586 if (tt
== TOK_PLUS
&&
587 left
->pn_type
== TOK_NUMBER
&&
588 right
->pn_type
== TOK_NUMBER
) {
589 left
->pn_dval
+= right
->pn_dval
;
590 left
->pn_pos
.end
= right
->pn_pos
.end
;
591 RecycleTree(right
, tc
);
595 pn
= NewOrRecycledNode(tc
);
598 pn
->init(tt
, op
, PN_BINARY
);
599 pn
->pn_pos
.begin
= left
->pn_pos
.begin
;
600 pn
->pn_pos
.end
= right
->pn_pos
.end
;
602 pn
->pn_right
= right
;
603 return (BinaryNode
*)pn
;
609 NameNode::initCommon(JSTreeContext
*tc
)
612 pn_cookie
= FREE_UPVAR_COOKIE
;
613 pn_dflags
= tc
->atTopLevel() ? PND_TOPLEVEL
: 0;
614 if (!tc
->topStmt
|| tc
->topStmt
->type
== STMT_BLOCK
)
615 pn_dflags
|= PND_BLOCKCHILD
;
616 pn_blockid
= tc
->blockid();
620 NameNode::create(JSAtom
*atom
, JSTreeContext
*tc
)
624 pn
= JSParseNode::create(PN_NAME
, tc
);
627 ((NameNode
*)pn
)->initCommon(tc
);
629 return (NameNode
*)pn
;
635 GenerateBlockId(JSTreeContext
*tc
, uint32
& blockid
)
637 if (tc
->blockidGen
== JS_BIT(20)) {
638 JS_ReportErrorNumber(tc
->parser
->context
, js_GetErrorMessage
, NULL
,
639 JSMSG_NEED_DIET
, "program");
642 blockid
= tc
->blockidGen
++;
647 GenerateBlockIdForStmtNode(JSParseNode
*pn
, JSTreeContext
*tc
)
649 JS_ASSERT(tc
->topStmt
);
650 JS_ASSERT(STMT_MAYBE_SCOPE(tc
->topStmt
));
651 JS_ASSERT(pn
->pn_type
== TOK_LC
|| pn
->pn_type
== TOK_LEXICALSCOPE
);
652 if (!GenerateBlockId(tc
, tc
->topStmt
->blockid
))
654 pn
->pn_blockid
= tc
->topStmt
->blockid
;
659 * Parse a top-level JS script.
662 Parser::parse(JSObject
*chain
)
665 * Protect atoms from being collected by a GC activation, which might
666 * - nest on this thread due to out of memory (the so-called "last ditch"
667 * GC attempted within js_NewGCThing), or
668 * - run for any reason on another thread if this thread is suspended on
669 * an object lock before it finishes generating bytecode into a script
670 * protected from the GC by a root or a stack frame reference.
672 JSTreeContext
globaltc(this);
673 globaltc
.scopeChain
= chain
;
674 if (!GenerateBlockId(&globaltc
, globaltc
.bodyid
))
677 JSParseNode
*pn
= statements();
679 if (!tokenStream
.matchToken(TOK_EOF
)) {
680 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_SYNTAX_ERROR
);
683 if (!js_FoldConstants(context
, pn
, &globaltc
))
690 JS_STATIC_ASSERT(FREE_STATIC_LEVEL
== JS_BITMASK(JSFB_LEVEL_BITS
));
693 SetStaticLevel(JSTreeContext
*tc
, uintN staticLevel
)
696 * Reserve FREE_STATIC_LEVEL (0xffff) in order to reserve FREE_UPVAR_COOKIE
697 * (0xffffffff) and other cookies with that level.
699 * This is a lot simpler than error-checking every MAKE_UPVAR_COOKIE, and
700 * practically speaking it leaves more than enough room for upvars. In fact
701 * we might want to split cookie fields giving fewer bits for skip and more
702 * for slot, but only based on evidence.
704 if (staticLevel
>= FREE_STATIC_LEVEL
) {
705 JS_ReportErrorNumber(tc
->parser
->context
, js_GetErrorMessage
, NULL
,
706 JSMSG_TOO_DEEP
, js_function_str
);
709 tc
->staticLevel
= staticLevel
;
714 * Compile a top-level script.
717 Compiler::compileScript(JSContext
*cx
, JSObject
*scopeChain
, JSStackFrame
*callerFrame
,
718 JSPrincipals
*principals
, uint32 tcflags
,
719 const jschar
*chars
, size_t length
,
720 FILE *file
, const char *filename
, uintN lineno
,
721 JSString
*source
/* = NULL */,
722 unsigned staticLevel
/* = 0 */)
724 JSArenaPool codePool
, notePool
;
727 uint32 scriptGlobals
;
729 bool inDirectivePrologue
;
730 #ifdef METER_PARSENODES
731 void *sbrk(ptrdiff_t), *before
= sbrk(0);
734 JS_ASSERT(!(tcflags
& ~(TCF_COMPILE_N_GO
| TCF_NO_SCRIPT_RVAL
| TCF_NEED_MUTABLE_SCRIPT
)));
737 * The scripted callerFrame can only be given for compile-and-go scripts
738 * and non-zero static level requires callerFrame.
740 JS_ASSERT_IF(callerFrame
, tcflags
& TCF_COMPILE_N_GO
);
741 JS_ASSERT_IF(staticLevel
!= 0, callerFrame
);
743 Compiler
compiler(cx
, principals
, callerFrame
);
744 if (!compiler
.init(chars
, length
, file
, filename
, lineno
))
747 JS_InitArenaPool(&codePool
, "code", 1024, sizeof(jsbytecode
),
748 &cx
->scriptStackQuota
);
749 JS_InitArenaPool(¬ePool
, "note", 1024, sizeof(jssrcnote
),
750 &cx
->scriptStackQuota
);
752 Parser
&parser
= compiler
.parser
;
753 TokenStream
&tokenStream
= parser
.tokenStream
;
755 JSCodeGenerator
cg(&parser
, &codePool
, ¬ePool
, tokenStream
.getLineno());
759 MUST_FLOW_THROUGH("out");
761 /* Null script early in case of error, to reduce our code footprint. */
765 cg
.scopeChain
= scopeChain
;
766 if (!SetStaticLevel(&cg
, staticLevel
))
769 /* If this is a direct call to eval, inherit the caller's strictness. */
771 callerFrame
->script
&&
772 callerFrame
->script
->strictModeCode
) {
773 cg
.flags
|= TCF_STRICT_MODE_CODE
;
774 tokenStream
.setStrictMode();
778 * If funbox is non-null after we create the new script, callerFrame->fun
779 * was saved in the 0th object table entry.
784 if (tcflags
& TCF_COMPILE_N_GO
) {
787 * Save eval program source in script->atomMap.vector[0] for the
788 * eval cache (see obj_eval in jsobj.cpp).
790 JSAtom
*atom
= js_AtomizeString(cx
, source
, 0);
791 if (!atom
|| !cg
.atomList
.add(&parser
, atom
))
795 if (callerFrame
&& callerFrame
->fun
) {
797 * An eval script in a caller frame needs to have its enclosing
798 * function captured in case it refers to an upvar, and someone
799 * wishes to decompile it while it's running.
801 funbox
= parser
.newObjectBox(FUN_OBJECT(callerFrame
->fun
));
804 funbox
->emitLink
= cg
.objectList
.lastbox
;
805 cg
.objectList
.lastbox
= funbox
;
806 cg
.objectList
.length
++;
811 * Inline this->statements to emit as we go to save AST space. We must
812 * generate our script-body blockid since we aren't calling Statements.
815 if (!GenerateBlockId(&cg
, bodyid
))
819 #if JS_HAS_XML_SUPPORT
825 CG_SWITCH_TO_PROLOG(&cg
);
826 if (js_Emit1(cx
, &cg
, JSOP_TRACE
) < 0)
828 CG_SWITCH_TO_MAIN(&cg
);
830 inDirectivePrologue
= true;
832 tt
= tokenStream
.peekToken(TSF_OPERAND
);
836 JS_ASSERT(tt
== TOK_ERROR
);
840 pn
= parser
.statement();
843 JS_ASSERT(!cg
.blockNode
);
845 if (inDirectivePrologue
)
846 inDirectivePrologue
= parser
.recognizeDirectivePrologue(pn
);
848 if (!js_FoldConstants(cx
, pn
, &cg
))
851 if (cg
.functionList
) {
852 if (!parser
.analyzeFunctions(cg
.functionList
, cg
.flags
))
854 cg
.functionList
= NULL
;
857 if (!js_EmitTree(cx
, &cg
, pn
))
859 #if JS_HAS_XML_SUPPORT
860 if (PN_TYPE(pn
) != TOK_SEMI
||
862 !TreeTypeIsXML(PN_TYPE(pn
->pn_kid
))) {
866 RecycleTree(pn
, &cg
);
869 #if JS_HAS_XML_SUPPORT
871 * Prevent XML data theft via <script src="http://victim.com/foo.xml">.
872 * For background, see:
874 * https://bugzilla.mozilla.org/show_bug.cgi?id=336551
876 if (pn
&& onlyXML
&& (tcflags
& TCF_NO_SCRIPT_RVAL
)) {
877 parser
.reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_XML_WHOLE_PROGRAM
);
883 * Global variables (gvars) share the atom index space with locals. Due to
884 * incremental code generation we need to patch the bytecode to adjust the
885 * local references to skip the globals.
887 scriptGlobals
= cg
.ngvars
;
888 if (scriptGlobals
!= 0 || cg
.hasSharps()) {
889 jsbytecode
*code
, *end
;
891 const JSCodeSpec
*cs
;
894 if (scriptGlobals
>= SLOTNO_LIMIT
)
897 for (end
= code
+ CG_OFFSET(&cg
); code
!= end
; code
+= len
) {
898 JS_ASSERT(code
< end
);
900 cs
= &js_CodeSpec
[op
];
901 len
= (cs
->length
> 0)
903 : js_GetVariableBytecodeLength(code
);
904 if ((cs
->format
& JOF_SHARPSLOT
) ||
905 JOF_TYPE(cs
->format
) == JOF_LOCAL
||
906 (JOF_TYPE(cs
->format
) == JOF_SLOTATOM
)) {
908 * JSOP_GETARGPROP also has JOF_SLOTATOM type, but it may be
909 * emitted only for a function.
911 JS_ASSERT_IF(!(cs
->format
& JOF_SHARPSLOT
),
912 (JOF_TYPE(cs
->format
) == JOF_SLOTATOM
) ==
913 (op
== JSOP_GETLOCALPROP
));
914 slot
= GET_SLOTNO(code
);
915 slot
+= scriptGlobals
;
916 if (!(cs
->format
& JOF_SHARPSLOT
))
917 slot
+= cg
.sharpSlots();
918 if (slot
>= SLOTNO_LIMIT
)
920 SET_SLOTNO(code
, slot
);
925 #ifdef METER_PARSENODES
926 printf("Parser growth: %d (%u nodes, %u max, %u unrecycled)\n",
927 (char *)sbrk(0) - (char *)before
,
930 parsenodes
- recyclednodes
);
935 * Nowadays the threaded interpreter needs a stop instruction, so we
936 * do have to emit that here.
938 if (js_Emit1(cx
, &cg
, JSOP_STOP
) < 0)
940 #ifdef METER_PARSENODES
941 printf("Code-gen growth: %d (%u bytecodes, %u srcnotes)\n",
942 (char *)sbrk(0) - (char *)before
, CG_OFFSET(&cg
), cg
.noteCount
);
945 JS_DumpArenaStats(stdout
);
947 script
= js_NewScriptFromCG(cx
, &cg
);
948 if (script
&& funbox
&& script
!= script
->emptyScript())
949 script
->savedCallerFun
= true;
951 #ifdef JS_SCOPE_DEPTH_METER
953 JSObject
*obj
= scopeChain
;
955 while ((obj
= obj
->getParent()) != NULL
)
957 JS_BASIC_STATS_ACCUM(&cx
->runtime
->hostenvScopeDepthStats
, depth
);
962 JS_FinishArenaPool(&codePool
);
963 JS_FinishArenaPool(¬ePool
);
967 parser
.reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_TOO_MANY_LOCALS
);
973 * Insist on a final return before control flows out of pn. Try to be a bit
974 * smart about loops: do {...; return e2;} while(0) at the end of a function
975 * that contains an early return e1 will get a strict warning. Similarly for
976 * iloops: while (true){...} is treated as though ... returns.
978 #define ENDS_IN_OTHER 0
979 #define ENDS_IN_RETURN 1
980 #define ENDS_IN_BREAK 2
983 HasFinalReturn(JSParseNode
*pn
)
985 JSParseNode
*pn2
, *pn3
;
986 uintN rv
, rv2
, hasDefault
;
988 switch (pn
->pn_type
) {
991 return ENDS_IN_OTHER
;
992 return HasFinalReturn(pn
->last());
996 return ENDS_IN_OTHER
;
997 return HasFinalReturn(pn
->pn_kid2
) & HasFinalReturn(pn
->pn_kid3
);
1001 if (pn2
->pn_type
== TOK_PRIMARY
&& pn2
->pn_op
== JSOP_TRUE
)
1002 return ENDS_IN_RETURN
;
1003 if (pn2
->pn_type
== TOK_NUMBER
&& pn2
->pn_dval
)
1004 return ENDS_IN_RETURN
;
1005 return ENDS_IN_OTHER
;
1009 if (pn2
->pn_type
== TOK_PRIMARY
) {
1010 if (pn2
->pn_op
== JSOP_FALSE
)
1011 return HasFinalReturn(pn
->pn_left
);
1012 if (pn2
->pn_op
== JSOP_TRUE
)
1013 return ENDS_IN_RETURN
;
1015 if (pn2
->pn_type
== TOK_NUMBER
) {
1016 if (pn2
->pn_dval
== 0)
1017 return HasFinalReturn(pn
->pn_left
);
1018 return ENDS_IN_RETURN
;
1020 return ENDS_IN_OTHER
;
1024 if (pn2
->pn_arity
== PN_TERNARY
&& !pn2
->pn_kid2
)
1025 return ENDS_IN_RETURN
;
1026 return ENDS_IN_OTHER
;
1029 rv
= ENDS_IN_RETURN
;
1030 hasDefault
= ENDS_IN_OTHER
;
1032 if (pn2
->pn_type
== TOK_LEXICALSCOPE
)
1034 for (pn2
= pn2
->pn_head
; rv
&& pn2
; pn2
= pn2
->pn_next
) {
1035 if (pn2
->pn_type
== TOK_DEFAULT
)
1036 hasDefault
= ENDS_IN_RETURN
;
1037 pn3
= pn2
->pn_right
;
1038 JS_ASSERT(pn3
->pn_type
== TOK_LC
);
1040 rv2
= HasFinalReturn(pn3
->last());
1041 if (rv2
== ENDS_IN_OTHER
&& pn2
->pn_next
)
1042 /* Falling through to next case or default. */;
1047 /* If a final switch has no default case, we judge it harshly. */
1052 return ENDS_IN_BREAK
;
1055 return HasFinalReturn(pn
->pn_right
);
1058 return ENDS_IN_RETURN
;
1061 case TOK_LEXICALSCOPE
:
1062 return HasFinalReturn(pn
->expr());
1065 return ENDS_IN_RETURN
;
1068 /* If we have a finally block that returns, we are done. */
1070 rv
= HasFinalReturn(pn
->pn_kid3
);
1071 if (rv
== ENDS_IN_RETURN
)
1075 /* Else check the try block and any and all catch statements. */
1076 rv
= HasFinalReturn(pn
->pn_kid1
);
1078 JS_ASSERT(pn
->pn_kid2
->pn_arity
== PN_LIST
);
1079 for (pn2
= pn
->pn_kid2
->pn_head
; pn2
; pn2
= pn2
->pn_next
)
1080 rv
&= HasFinalReturn(pn2
);
1085 /* Check this catch block's body. */
1086 return HasFinalReturn(pn
->pn_kid3
);
1089 /* Non-binary let statements are let declarations. */
1090 if (pn
->pn_arity
!= PN_BINARY
)
1091 return ENDS_IN_OTHER
;
1092 return HasFinalReturn(pn
->pn_right
);
1095 return ENDS_IN_OTHER
;
1100 ReportBadReturn(JSContext
*cx
, JSTreeContext
*tc
, uintN flags
, uintN errnum
,
1105 JS_ASSERT(tc
->inFunction());
1106 if (tc
->fun
->atom
) {
1107 name
= js_AtomToPrintableString(cx
, tc
->fun
->atom
);
1109 errnum
= anonerrnum
;
1112 return ReportCompileErrorNumber(cx
, TS(tc
->parser
), NULL
, flags
, errnum
, name
);
1116 CheckFinalReturn(JSContext
*cx
, JSTreeContext
*tc
, JSParseNode
*pn
)
1118 JS_ASSERT(tc
->inFunction());
1119 return HasFinalReturn(pn
) == ENDS_IN_RETURN
||
1120 ReportBadReturn(cx
, tc
, JSREPORT_WARNING
| JSREPORT_STRICT
,
1121 JSMSG_NO_RETURN_VALUE
, JSMSG_ANON_NO_RETURN_VALUE
);
1125 * Check that it is permitted to assign to lhs. Strict mode code may not
1126 * assign to 'eval' or 'arguments'.
1129 CheckStrictAssignment(JSContext
*cx
, JSTreeContext
*tc
, JSParseNode
*lhs
)
1131 if (tc
->needStrictChecks() &&
1132 lhs
->pn_type
== TOK_NAME
) {
1133 JSAtom
*atom
= lhs
->pn_atom
;
1134 JSAtomState
*atomState
= &cx
->runtime
->atomState
;
1135 if (atom
== atomState
->evalAtom
|| atom
== atomState
->argumentsAtom
) {
1136 const char *name
= js_AtomToPrintableString(cx
, atom
);
1138 !ReportStrictModeError(cx
, TS(tc
->parser
), tc
, lhs
, JSMSG_DEPRECATED_ASSIGN
,
1148 * Check that it is permitted to introduce a binding for atom. Strict
1149 * mode forbids introducing new definitions for 'eval' or 'arguments'.
1150 * Use pn for reporting error locations, or use tc's token stream if
1154 CheckStrictBinding(JSContext
*cx
, JSTreeContext
*tc
, JSAtom
*atom
, JSParseNode
*pn
)
1156 if (!tc
->needStrictChecks())
1159 JSAtomState
*atomState
= &cx
->runtime
->atomState
;
1160 if (atom
== atomState
->evalAtom
|| atom
== atomState
->argumentsAtom
) {
1161 const char *name
= js_AtomToPrintableString(cx
, atom
);
1163 ReportStrictModeError(cx
, TS(tc
->parser
), tc
, pn
, JSMSG_BAD_BINDING
, name
);
1170 * In strict mode code, all formal parameter names must be distinct. If fun's
1171 * formals are legit given fun's strictness level, return true. Otherwise,
1172 * report an error and return false. Use pn for error position reporting,
1173 * unless we can find something more accurate in tc's decls.
1175 * In some cases the code to parse the argument list will already have noticed
1176 * the duplication; we could try to use that knowledge instead of re-checking
1177 * here. But since the strictness of the function's body determines what
1178 * constraints to apply to the argument list, we can't report the error until
1179 * after we've parsed the body. And as it turns out, the function's local name
1180 * list makes it reasonably cheap to find duplicates after the fact.
1183 CheckStrictFormals(JSContext
*cx
, JSTreeContext
*tc
, JSFunction
*fun
,
1188 if (!tc
->needStrictChecks())
1191 atom
= fun
->findDuplicateFormal();
1194 * We have found a duplicate parameter name. If we can find the
1195 * JSDefinition for the argument, that will have a more accurate source
1198 JSDefinition
*dn
= ALE_DEFN(tc
->decls
.lookup(atom
));
1199 if (dn
->pn_op
== JSOP_GETARG
)
1201 const char *name
= js_AtomToPrintableString(cx
, atom
);
1203 !ReportStrictModeError(cx
, TS(tc
->parser
), tc
, pn
, JSMSG_DUPLICATE_FORMAL
, name
)) {
1208 if (tc
->flags
& (TCF_FUN_PARAM_ARGUMENTS
| TCF_FUN_PARAM_EVAL
)) {
1209 JSAtomState
*atoms
= &cx
->runtime
->atomState
;
1210 atom
= (tc
->flags
& TCF_FUN_PARAM_ARGUMENTS
1211 ? atoms
->argumentsAtom
: atoms
->evalAtom
);
1212 /* The definition's source position will be more precise. */
1213 JSDefinition
*dn
= ALE_DEFN(tc
->decls
.lookup(atom
));
1214 JS_ASSERT(dn
->pn_atom
== atom
);
1215 const char *name
= js_AtomToPrintableString(cx
, atom
);
1217 !ReportStrictModeError(cx
, TS(tc
->parser
), tc
, dn
, JSMSG_BAD_BINDING
, name
)) {
1226 Parser::functionBody()
1228 JSStmtInfo stmtInfo
;
1229 uintN oldflags
, firstLine
;
1232 JS_ASSERT(tc
->inFunction());
1233 js_PushStatement(tc
, &stmtInfo
, STMT_BLOCK
, -1);
1234 stmtInfo
.flags
= SIF_BODY_BLOCK
;
1236 oldflags
= tc
->flags
;
1237 tc
->flags
&= ~(TCF_RETURN_EXPR
| TCF_RETURN_VOID
);
1240 * Save the body's first line, and store it in pn->pn_pos.begin.lineno
1241 * later, because we may have not peeked in tokenStream yet, so statements
1242 * won't acquire a valid pn->pn_pos.begin from the current token.
1244 firstLine
= tokenStream
.getLineno();
1245 #if JS_HAS_EXPR_CLOSURES
1246 if (tokenStream
.currentToken().type
== TOK_LC
) {
1249 pn
= UnaryNode::create(tc
);
1251 pn
->pn_kid
= assignExpr();
1255 if (tc
->flags
& TCF_FUN_IS_GENERATOR
) {
1256 ReportBadReturn(context
, tc
, JSREPORT_ERROR
,
1257 JSMSG_BAD_GENERATOR_RETURN
,
1258 JSMSG_BAD_ANON_GENERATOR_RETURN
);
1261 pn
->pn_type
= TOK_RETURN
;
1262 pn
->pn_op
= JSOP_RETURN
;
1263 pn
->pn_pos
.end
= pn
->pn_kid
->pn_pos
.end
;
1273 JS_ASSERT(!(tc
->topStmt
->flags
& SIF_SCOPE
));
1274 js_PopStatement(tc
);
1275 pn
->pn_pos
.begin
.lineno
= firstLine
;
1277 /* Check for falling off the end of a function that returns a value. */
1278 if (JS_HAS_STRICT_OPTION(context
) && (tc
->flags
& TCF_RETURN_EXPR
) &&
1279 !CheckFinalReturn(context
, tc
, pn
)) {
1284 tc
->flags
= oldflags
| (tc
->flags
& TCF_FUN_FLAGS
);
1288 static JSAtomListElement
*
1289 MakePlaceholder(JSParseNode
*pn
, JSTreeContext
*tc
)
1291 JSAtomListElement
*ale
= tc
->lexdeps
.add(tc
->parser
, pn
->pn_atom
);
1295 JSDefinition
*dn
= (JSDefinition
*)NameNode::create(pn
->pn_atom
, tc
);
1299 ALE_SET_DEFN(ale
, dn
);
1301 dn
->pn_dflags
|= PND_PLACEHOLDER
;
1306 Define(JSParseNode
*pn
, JSAtom
*atom
, JSTreeContext
*tc
, bool let
= false)
1308 JS_ASSERT(!pn
->pn_used
);
1309 JS_ASSERT_IF(pn
->pn_defn
, pn
->isPlaceholder());
1312 JSAtomListElement
*ale
= NULL
;
1313 JSAtomList
*list
= NULL
;
1316 ale
= (list
= &tc
->decls
)->rawLookup(atom
, hep
);
1318 ale
= (list
= &tc
->lexdeps
)->rawLookup(atom
, hep
);
1321 JSDefinition
*dn
= ALE_DEFN(ale
);
1323 JSParseNode
**pnup
= &dn
->dn_uses
;
1325 uintN start
= let
? pn
->pn_blockid
: tc
->bodyid
;
1327 while ((pnu
= *pnup
) != NULL
&& pnu
->pn_blockid
>= start
) {
1328 JS_ASSERT(pnu
->pn_used
);
1329 pnu
->pn_lexdef
= (JSDefinition
*) pn
;
1330 pn
->pn_dflags
|= pnu
->pn_dflags
& PND_USE2DEF_FLAGS
;
1331 pnup
= &pnu
->pn_link
;
1334 if (pnu
!= dn
->dn_uses
) {
1335 *pnup
= pn
->dn_uses
;
1336 pn
->dn_uses
= dn
->dn_uses
;
1339 if ((!pnu
|| pnu
->pn_blockid
< tc
->bodyid
) && list
!= &tc
->decls
)
1340 list
->rawRemove(tc
->parser
, ale
, hep
);
1345 ale
= tc
->decls
.add(tc
->parser
, atom
, let
? JSAtomList::SHADOW
: JSAtomList::UNIQUE
);
1348 ALE_SET_DEFN(ale
, pn
);
1350 pn
->pn_dflags
&= ~PND_PLACEHOLDER
;
1355 LinkUseToDef(JSParseNode
*pn
, JSDefinition
*dn
, JSTreeContext
*tc
)
1357 JS_ASSERT(!pn
->pn_used
);
1358 JS_ASSERT(!pn
->pn_defn
);
1359 JS_ASSERT(pn
!= dn
->dn_uses
);
1360 pn
->pn_link
= dn
->dn_uses
;
1362 dn
->pn_dflags
|= pn
->pn_dflags
& PND_USE2DEF_FLAGS
;
1368 ForgetUse(JSParseNode
*pn
)
1371 JS_ASSERT(!pn
->pn_defn
);
1375 JSParseNode
**pnup
= &pn
->lexdef()->dn_uses
;
1377 while ((pnu
= *pnup
) != pn
)
1378 pnup
= &pnu
->pn_link
;
1379 *pnup
= pn
->pn_link
;
1380 pn
->pn_used
= false;
1383 static JSParseNode
*
1384 MakeAssignment(JSParseNode
*pn
, JSParseNode
*rhs
, JSTreeContext
*tc
)
1386 JSParseNode
*lhs
= NewOrRecycledNode(tc
);
1392 JSDefinition
*dn
= pn
->pn_lexdef
;
1393 JSParseNode
**pnup
= &dn
->dn_uses
;
1396 pnup
= &(*pnup
)->pn_link
;
1398 lhs
->pn_link
= pn
->pn_link
;
1402 pn
->pn_type
= TOK_ASSIGN
;
1403 pn
->pn_op
= JSOP_NOP
;
1404 pn
->pn_arity
= PN_BINARY
;
1405 pn
->pn_parens
= false;
1406 pn
->pn_used
= pn
->pn_defn
= false;
1412 static JSParseNode
*
1413 MakeDefIntoUse(JSDefinition
*dn
, JSParseNode
*pn
, JSAtom
*atom
, JSTreeContext
*tc
)
1416 * If dn is var, const, or let, and it has an initializer, then we must
1417 * rewrite it to be an assignment node, whose freshly allocated left-hand
1418 * side becomes a use of pn.
1420 if (dn
->isBindingForm()) {
1421 JSParseNode
*rhs
= dn
->expr();
1423 JSParseNode
*lhs
= MakeAssignment(dn
, rhs
, tc
);
1426 //pn->dn_uses = lhs;
1427 dn
= (JSDefinition
*) lhs
;
1430 dn
->pn_op
= (js_CodeSpec
[dn
->pn_op
].format
& JOF_SET
) ? JSOP_SETNAME
: JSOP_NAME
;
1431 } else if (dn
->kind() == JSDefinition::FUNCTION
) {
1432 JS_ASSERT(dn
->isTopLevel());
1433 JS_ASSERT(dn
->pn_op
== JSOP_NOP
);
1434 dn
->pn_type
= TOK_NAME
;
1435 dn
->pn_arity
= PN_NAME
;
1439 /* Now make dn no longer a definition, rather a use of pn. */
1440 JS_ASSERT(dn
->pn_type
== TOK_NAME
);
1441 JS_ASSERT(dn
->pn_arity
== PN_NAME
);
1442 JS_ASSERT(dn
->pn_atom
== atom
);
1444 for (JSParseNode
*pnu
= dn
->dn_uses
; pnu
; pnu
= pnu
->pn_link
) {
1445 JS_ASSERT(pnu
->pn_used
);
1446 JS_ASSERT(!pnu
->pn_defn
);
1447 pnu
->pn_lexdef
= (JSDefinition
*) pn
;
1448 pn
->pn_dflags
|= pnu
->pn_dflags
& PND_USE2DEF_FLAGS
;
1450 pn
->pn_dflags
|= dn
->pn_dflags
& PND_USE2DEF_FLAGS
;
1453 dn
->pn_defn
= false;
1455 dn
->pn_lexdef
= (JSDefinition
*) pn
;
1456 dn
->pn_cookie
= FREE_UPVAR_COOKIE
;
1457 dn
->pn_dflags
&= ~PND_BOUND
;
1462 DefineArg(JSParseNode
*pn
, JSAtom
*atom
, uintN i
, JSTreeContext
*tc
)
1464 JSParseNode
*argpn
, *argsbody
;
1466 /* Flag tc so we don't have to lookup arguments on every use. */
1467 if (atom
== tc
->parser
->context
->runtime
->atomState
.argumentsAtom
)
1468 tc
->flags
|= TCF_FUN_PARAM_ARGUMENTS
;
1469 if (atom
== tc
->parser
->context
->runtime
->atomState
.evalAtom
)
1470 tc
->flags
|= TCF_FUN_PARAM_EVAL
;
1473 * Make an argument definition node, distinguished by being in tc->decls
1474 * but having TOK_NAME type and JSOP_NOP op. Insert it in a TOK_ARGSBODY
1475 * list node returned via pn->pn_body.
1477 argpn
= NameNode::create(atom
, tc
);
1480 JS_ASSERT(PN_TYPE(argpn
) == TOK_NAME
&& PN_OP(argpn
) == JSOP_NOP
);
1482 /* Arguments are initialized by definition. */
1483 argpn
->pn_dflags
|= PND_INITIALIZED
;
1484 if (!Define(argpn
, atom
, tc
))
1487 argsbody
= pn
->pn_body
;
1489 argsbody
= ListNode::create(tc
);
1492 argsbody
->pn_type
= TOK_ARGSBODY
;
1493 argsbody
->pn_op
= JSOP_NOP
;
1494 argsbody
->makeEmpty();
1495 pn
->pn_body
= argsbody
;
1497 argsbody
->append(argpn
);
1499 argpn
->pn_op
= JSOP_GETARG
;
1500 argpn
->pn_cookie
= MAKE_UPVAR_COOKIE(tc
->staticLevel
, i
);
1501 argpn
->pn_dflags
|= PND_BOUND
;
1506 * Compile a JS function body, which might appear as the value of an event
1507 * handler attribute in an HTML <INPUT> tag.
1510 Compiler::compileFunctionBody(JSContext
*cx
, JSFunction
*fun
, JSPrincipals
*principals
,
1511 const jschar
*chars
, size_t length
,
1512 const char *filename
, uintN lineno
)
1514 Compiler
compiler(cx
, principals
);
1516 if (!compiler
.init(chars
, length
, NULL
, filename
, lineno
))
1519 /* No early return from after here until the js_FinishArenaPool calls. */
1520 JSArenaPool codePool
, notePool
;
1521 JS_InitArenaPool(&codePool
, "code", 1024, sizeof(jsbytecode
),
1522 &cx
->scriptStackQuota
);
1523 JS_InitArenaPool(¬ePool
, "note", 1024, sizeof(jssrcnote
),
1524 &cx
->scriptStackQuota
);
1526 Parser
&parser
= compiler
.parser
;
1527 TokenStream
&tokenStream
= parser
.tokenStream
;
1529 JSCodeGenerator
funcg(&parser
, &codePool
, ¬ePool
, tokenStream
.getLineno());
1533 funcg
.flags
|= TCF_IN_FUNCTION
;
1535 if (!GenerateBlockId(&funcg
, funcg
.bodyid
))
1538 /* FIXME: make Function format the source for a function definition. */
1539 tokenStream
.mungeCurrentToken(TOK_NAME
);
1540 JSParseNode
*fn
= FunctionNode::create(&funcg
);
1543 fn
->pn_cookie
= FREE_UPVAR_COOKIE
;
1545 uintN nargs
= fun
->nargs
;
1547 jsuword
*names
= js_GetLocalNameArray(cx
, fun
, &cx
->tempPool
);
1551 for (uintN i
= 0; i
< nargs
; i
++) {
1552 JSAtom
*name
= JS_LOCAL_NAME_TO_ATOM(names
[i
]);
1553 if (!DefineArg(fn
, name
, i
, &funcg
)) {
1563 * Farble the body so that it looks like a block statement to js_EmitTree,
1564 * which is called from js_EmitFunctionBody (see jsemit.cpp). After we're
1565 * done parsing, we must fold constants, analyze any nested functions, and
1566 * generate code for this function, including a stop opcode at the end.
1568 tokenStream
.mungeCurrentToken(TOK_LC
);
1569 JSParseNode
*pn
= fn
? parser
.functionBody() : NULL
;
1571 if (!CheckStrictFormals(cx
, &funcg
, fun
, pn
)) {
1573 } else if (!tokenStream
.matchToken(TOK_EOF
)) {
1574 parser
.reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_SYNTAX_ERROR
);
1576 } else if (!js_FoldConstants(cx
, pn
, &funcg
)) {
1577 /* js_FoldConstants reported the error already. */
1579 } else if (funcg
.functionList
&&
1580 !parser
.analyzeFunctions(funcg
.functionList
, funcg
.flags
)) {
1584 JS_ASSERT(PN_TYPE(fn
->pn_body
) == TOK_ARGSBODY
);
1585 fn
->pn_body
->append(pn
);
1586 fn
->pn_body
->pn_pos
= pn
->pn_pos
;
1590 if (!js_EmitFunctionScript(cx
, &funcg
, pn
))
1595 /* Restore saved state and release code generation arenas. */
1596 JS_FinishArenaPool(&codePool
);
1597 JS_FinishArenaPool(¬ePool
);
1602 * Parameter block types for the several Binder functions. We use a common
1603 * helper function signature in order to share code among destructuring and
1604 * simple variable declaration parsers. In the destructuring case, the binder
1605 * function is called indirectly from the variable declaration parser by way
1606 * of CheckDestructuring and its friends.
1609 (*Binder
)(JSContext
*cx
, BindData
*data
, JSAtom
*atom
, JSTreeContext
*tc
);
1612 BindData() : fresh(true) {}
1614 JSParseNode
*pn
; /* name node for definition processing and
1615 error source coordinates */
1616 JSOp op
; /* prolog bytecode or nop */
1617 Binder binder
; /* binder, discriminates u */
1627 BindLocalVariable(JSContext
*cx
, JSFunction
*fun
, JSAtom
*atom
,
1628 JSLocalKind localKind
, bool isArg
)
1630 JS_ASSERT(localKind
== JSLOCAL_VAR
|| localKind
== JSLOCAL_CONST
);
1633 * Don't bind a variable with the hidden name 'arguments', per ECMA-262.
1634 * Instead 'var arguments' always restates the predefined property of the
1635 * activation objects whose name is 'arguments'. Assignment to such a
1636 * variable must be handled specially.
1638 * Special case: an argument named 'arguments' *does* shadow the predefined
1639 * arguments property.
1641 if (atom
== cx
->runtime
->atomState
.argumentsAtom
&& !isArg
)
1644 return js_AddLocal(cx
, fun
, atom
, localKind
);
1647 #if JS_HAS_DESTRUCTURING
1649 BindDestructuringArg(JSContext
*cx
, BindData
*data
, JSAtom
*atom
,
1654 /* Flag tc so we don't have to lookup arguments on every use. */
1655 if (atom
== tc
->parser
->context
->runtime
->atomState
.argumentsAtom
)
1656 tc
->flags
|= TCF_FUN_PARAM_ARGUMENTS
;
1657 if (atom
== tc
->parser
->context
->runtime
->atomState
.evalAtom
)
1658 tc
->flags
|= TCF_FUN_PARAM_EVAL
;
1660 JS_ASSERT(tc
->inFunction());
1662 JSLocalKind localKind
= js_LookupLocal(cx
, tc
->fun
, atom
, NULL
);
1663 if (localKind
!= JSLOCAL_NONE
) {
1664 ReportCompileErrorNumber(cx
, TS(tc
->parser
), NULL
, JSREPORT_ERROR
,
1665 JSMSG_DESTRUCT_DUP_ARG
);
1668 JS_ASSERT(!tc
->decls
.lookup(atom
));
1671 if (!Define(pn
, atom
, tc
))
1674 uintN index
= tc
->fun
->u
.i
.nvars
;
1675 if (!BindLocalVariable(cx
, tc
->fun
, atom
, JSLOCAL_VAR
, true))
1677 pn
->pn_op
= JSOP_SETLOCAL
;
1678 pn
->pn_cookie
= MAKE_UPVAR_COOKIE(tc
->staticLevel
, index
);
1679 pn
->pn_dflags
|= PND_BOUND
;
1682 #endif /* JS_HAS_DESTRUCTURING */
1685 Parser::newFunction(JSTreeContext
*tc
, JSAtom
*atom
, uintN lambda
)
1690 JS_ASSERT((lambda
& ~JSFUN_LAMBDA
) == 0);
1693 * Find the global compilation context in order to pre-set the newborn
1694 * function's parent slot to tc->scopeChain. If the global context is a
1695 * compile-and-go one, we leave the pre-set parent intact; otherwise we
1696 * clear parent and proto.
1700 parent
= tc
->inFunction() ? NULL
: tc
->scopeChain
;
1702 fun
= js_NewFunction(context
, NULL
, NULL
, 0, JSFUN_INTERPRETED
| lambda
,
1705 if (fun
&& !tc
->compileAndGo()) {
1706 FUN_OBJECT(fun
)->clearParent();
1707 FUN_OBJECT(fun
)->clearProto();
1713 MatchOrInsertSemicolon(JSContext
*cx
, TokenStream
*ts
)
1715 TokenKind tt
= ts
->peekTokenSameLine(TSF_OPERAND
);
1716 if (tt
== TOK_ERROR
)
1718 if (tt
!= TOK_EOF
&& tt
!= TOK_EOL
&& tt
!= TOK_SEMI
&& tt
!= TOK_RC
) {
1719 ReportCompileErrorNumber(cx
, ts
, NULL
, JSREPORT_ERROR
, JSMSG_SEMI_BEFORE_STMNT
);
1722 (void) ts
->matchToken(TOK_SEMI
);
1727 Parser::analyzeFunctions(JSFunctionBox
*funbox
, uint32
& tcflags
)
1729 if (!markFunArgs(funbox
, tcflags
))
1731 setFunctionKinds(funbox
, tcflags
);
1736 * Mark as funargs any functions that reach up to one or more upvars across an
1737 * already-known funarg. The parser will flag the o_m lambda as a funarg in:
1739 * function f(o, p) {
1740 * o.m = function o_m(a) {
1741 * function g() { return p; }
1742 * function h() { return a; }
1747 * but without this extra marking phase, function g will not be marked as a
1748 * funarg since it is called from within its parent scope. But g reaches up to
1749 * f's parameter p, so if o_m escapes f's activation scope, g does too and
1750 * cannot use JSOP_GETUPVAR to reach p. In contast function h neither escapes
1751 * nor uses an upvar "above" o_m's level.
1753 * If function g itself contained lambdas that contained non-lambdas that reach
1754 * up above its level, then those non-lambdas would have to be marked too. This
1755 * process is potentially exponential in the number of functions, but generally
1756 * not so complex. But it can't be done during a single recursive traversal of
1757 * the funbox tree, so we must use a work queue.
1759 * Return the minimal "skipmin" for funbox and its siblings. This is the delta
1760 * between the static level of the bodies of funbox and its peers (which must
1761 * be funbox->level + 1), and the static level of the nearest upvar among all
1762 * the upvars contained by funbox and its peers. If there are no upvars, return
1763 * FREE_STATIC_LEVEL. Thus this function never returns 0.
1766 FindFunArgs(JSFunctionBox
*funbox
, int level
, JSFunctionBoxQueue
*queue
)
1768 uintN allskipmin
= FREE_STATIC_LEVEL
;
1771 JSParseNode
*fn
= funbox
->node
;
1772 JSFunction
*fun
= (JSFunction
*) funbox
->object
;
1773 int fnlevel
= level
;
1776 * An eval can leak funbox, functions along its ancestor line, and its
1777 * immediate kids. Since FindFunArgs uses DFS and the parser propagates
1778 * TCF_FUN_HEAVYWEIGHT bottom up, funbox's ancestor function nodes have
1779 * already been marked as funargs by this point. Therefore we have to
1780 * flag only funbox->node and funbox->kids' nodes here.
1782 if (funbox
->tcflags
& TCF_FUN_HEAVYWEIGHT
) {
1784 for (JSFunctionBox
*kid
= funbox
->kids
; kid
; kid
= kid
->siblings
)
1785 kid
->node
->setFunArg();
1789 * Compute in skipmin the least distance from fun's static level up to
1790 * an upvar, whether used directly by fun, or indirectly by a function
1793 uintN skipmin
= FREE_STATIC_LEVEL
;
1794 JSParseNode
*pn
= fn
->pn_body
;
1796 if (pn
->pn_type
== TOK_UPVARS
) {
1797 JSAtomList
upvars(pn
->pn_names
);
1798 JS_ASSERT(upvars
.count
!= 0);
1800 JSAtomListIterator
iter(&upvars
);
1801 JSAtomListElement
*ale
;
1803 while ((ale
= iter()) != NULL
) {
1804 JSDefinition
*lexdep
= ALE_DEFN(ale
)->resolve();
1806 if (!lexdep
->isFreeVar()) {
1807 uintN upvarLevel
= lexdep
->frameLevel();
1809 if (int(upvarLevel
) <= fnlevel
)
1812 uintN skip
= (funbox
->level
+ 1) - upvarLevel
;
1820 * If this function escapes, whether directly (the parser detects such
1821 * escapes) or indirectly (because this non-escaping function uses an
1822 * upvar that reaches across an outer function boundary where the outer
1823 * function escapes), enqueue it for further analysis, and bump fnlevel
1824 * to trap any non-escaping children.
1826 if (fn
->isFunArg()) {
1827 queue
->push(funbox
);
1828 fnlevel
= int(funbox
->level
);
1832 * Now process the current function's children, and recalibrate their
1833 * cumulative skipmin to be relative to the current static level.
1836 uintN kidskipmin
= FindFunArgs(funbox
->kids
, fnlevel
, queue
);
1838 JS_ASSERT(kidskipmin
!= 0);
1839 if (kidskipmin
!= FREE_STATIC_LEVEL
) {
1841 if (kidskipmin
!= 0 && kidskipmin
< skipmin
)
1842 skipmin
= kidskipmin
;
1847 * Finally, after we've traversed all of the current function's kids,
1848 * minimize fun's skipmin against our accumulated skipmin. Do likewise
1849 * with allskipmin, but minimize across funbox and all of its siblings,
1850 * to compute our return value.
1852 if (skipmin
!= FREE_STATIC_LEVEL
) {
1853 fun
->u
.i
.skipmin
= skipmin
;
1854 if (skipmin
< allskipmin
)
1855 allskipmin
= skipmin
;
1857 } while ((funbox
= funbox
->siblings
) != NULL
);
1863 Parser::markFunArgs(JSFunctionBox
*funbox
, uintN tcflags
)
1865 JSFunctionBoxQueue queue
;
1866 if (!queue
.init(functionCount
))
1869 FindFunArgs(funbox
, -1, &queue
);
1870 while ((funbox
= queue
.pull()) != NULL
) {
1871 JSParseNode
*fn
= funbox
->node
;
1872 JS_ASSERT(fn
->isFunArg());
1874 JSParseNode
*pn
= fn
->pn_body
;
1875 if (pn
->pn_type
== TOK_UPVARS
) {
1876 JSAtomList
upvars(pn
->pn_names
);
1877 JS_ASSERT(upvars
.count
!= 0);
1879 JSAtomListIterator
iter(&upvars
);
1880 JSAtomListElement
*ale
;
1882 while ((ale
= iter()) != NULL
) {
1883 JSDefinition
*lexdep
= ALE_DEFN(ale
)->resolve();
1885 if (!lexdep
->isFreeVar() &&
1886 !lexdep
->isFunArg() &&
1887 (lexdep
->kind() == JSDefinition::FUNCTION
||
1888 PN_OP(lexdep
) == JSOP_CALLEE
)) {
1890 * Mark this formerly-Algol-like function as an escaping
1891 * function (i.e., as a funarg), because it is used from a
1892 * funarg and therefore can not use JSOP_{GET,CALL}UPVAR to
1895 * Progress is guaranteed because we set the funarg flag
1896 * here, which suppresses revisiting this function (thanks
1897 * to the !lexdep->isFunArg() test just above).
1899 lexdep
->setFunArg();
1901 JSFunctionBox
*afunbox
;
1902 if (PN_OP(lexdep
) == JSOP_CALLEE
) {
1904 * A named function expression will not appear to be a
1905 * funarg if it is immediately applied. However, if its
1906 * name is used in an escaping function nested within
1907 * it, then it must become flagged as a funarg again.
1911 uintN calleeLevel
= UPVAR_FRAME_SKIP(lexdep
->pn_cookie
);
1912 uintN staticLevel
= afunbox
->level
+ 1U;
1913 while (staticLevel
!= calleeLevel
) {
1914 afunbox
= afunbox
->parent
;
1917 afunbox
->node
->setFunArg();
1919 afunbox
= lexdep
->pn_funbox
;
1921 queue
.push(afunbox
);
1924 * Walk over nested functions again, now that we have
1925 * changed the level across which it is unsafe to access
1926 * upvars using the runtime dynamic link (frame chain).
1929 FindFunArgs(afunbox
->kids
, afunbox
->level
, &queue
);
1938 MinBlockId(JSParseNode
*fn
, uint32 id
)
1940 if (fn
->pn_blockid
< id
)
1943 for (JSParseNode
*pn
= fn
->dn_uses
; pn
; pn
= pn
->pn_link
) {
1944 if (pn
->pn_blockid
< id
)
1952 CanFlattenUpvar(JSDefinition
*dn
, JSFunctionBox
*funbox
, uint32 tcflags
)
1955 * Consider the current function (the lambda, innermost below) using a var
1956 * x defined two static levels up:
1962 * return function () { return x; };
1967 * So long as (1) the initialization in 'var x = 42' dominates all uses of
1968 * g and (2) x is not reassigned, it is safe to optimize the lambda to a
1969 * flat closure. Uncommenting the early call to g makes this optimization
1970 * unsafe (z could name a global setter that calls its argument).
1972 JSFunctionBox
*afunbox
= funbox
;
1973 uintN dnLevel
= dn
->frameLevel();
1975 JS_ASSERT(dnLevel
<= funbox
->level
);
1976 while (afunbox
->level
!= dnLevel
) {
1977 afunbox
= afunbox
->parent
;
1980 * NB: afunbox can't be null because we are sure to find a function box
1981 * whose level == dnLevel before we would try to walk above the root of
1982 * the funbox tree. See bug 493260 comments 16-18.
1984 * Assert but check anyway, to protect future changes that bind eval
1985 * upvars in the parser.
1990 * If this function is reaching up across an enclosing funarg, then we
1991 * cannot copy dn's value into a flat closure slot (the display stops
1992 * working once the funarg escapes).
1994 if (!afunbox
|| afunbox
->node
->isFunArg())
1998 * Reaching up for dn across a generator also means we can't flatten,
1999 * since the generator iterator does not run until later, in general.
2002 if (afunbox
->tcflags
& TCF_FUN_IS_GENERATOR
)
2007 * If afunbox's function (which is at the same level as dn) is in a loop,
2008 * pessimistically assume the variable initializer may be in the same loop.
2009 * A flat closure would then be unsafe, as the captured variable could be
2010 * assigned after the closure is created. See bug 493232.
2012 if (afunbox
->inLoop
)
2016 * |with| and eval used as an operator defeat lexical scoping: they can be
2017 * used to assign to any in-scope variable. Therefore they must disable
2018 * flat closures that use such upvars. The parser detects these as special
2019 * forms and marks the function heavyweight.
2021 if ((afunbox
->parent
? afunbox
->parent
->tcflags
: tcflags
) & TCF_FUN_HEAVYWEIGHT
)
2025 * If afunbox's function is not a lambda, it will be hoisted, so it could
2026 * capture the undefined value that by default initializes var, let, and
2027 * const bindings. And if dn is a function that comes at (meaning a
2028 * function refers to its own name) or strictly after afunbox, we also
2029 * defeat the flat closure optimization for this dn.
2031 JSFunction
*afun
= (JSFunction
*) afunbox
->object
;
2032 if (!(afun
->flags
& JSFUN_LAMBDA
)) {
2033 if (dn
->isBindingForm() || dn
->pn_pos
>= afunbox
->node
->pn_pos
)
2037 if (!dn
->isInitialized())
2040 JSDefinition::Kind dnKind
= dn
->kind();
2041 if (dnKind
!= JSDefinition::CONST
) {
2042 if (dn
->isAssigned())
2046 * Any formal could be mutated behind our back via the arguments
2047 * object, so deoptimize if the outer function uses arguments.
2049 * In a Function constructor call where the final argument -- the body
2050 * source for the function to create -- contains a nested function
2051 * definition or expression, afunbox->parent will be null. The body
2052 * source might use |arguments| outside of any nested functions it may
2053 * contain, so we have to check the tcflags parameter that was passed
2054 * in from Compiler::compileFunctionBody.
2056 if (dnKind
== JSDefinition::ARG
&&
2057 ((afunbox
->parent
? afunbox
->parent
->tcflags
: tcflags
) & TCF_FUN_USES_ARGUMENTS
)) {
2063 * Check quick-and-dirty dominance relation. Function definitions dominate
2064 * their uses thanks to hoisting. Other binding forms hoist as undefined,
2065 * of course, so check forward-reference and blockid relations.
2067 if (dnKind
!= JSDefinition::FUNCTION
) {
2069 * Watch out for code such as
2073 * var jQuery = ... = function (...) {
2074 * return new jQuery.foo.bar(baz);
2079 * where the jQuery variable is not reassigned, but of course is not
2080 * initialized at the time that the would-be-flat closure containing
2081 * the jQuery upvar is formed.
2083 if (dn
->pn_pos
.end
>= afunbox
->node
->pn_pos
.end
)
2085 if (!MinBlockId(afunbox
->node
, dn
->pn_blockid
))
2092 FlagHeavyweights(JSDefinition
*dn
, JSFunctionBox
*funbox
, uint32
& tcflags
)
2094 uintN dnLevel
= dn
->frameLevel();
2096 while ((funbox
= funbox
->parent
) != NULL
) {
2098 * Notice that funbox->level is the static level of the definition or
2099 * expression of the function parsed into funbox, not the static level
2100 * of its body. Therefore we must add 1 to match dn's level to find the
2101 * funbox whose body contains the dn definition.
2103 if (funbox
->level
+ 1U == dnLevel
|| (dnLevel
== 0 && dn
->isLet())) {
2104 funbox
->tcflags
|= TCF_FUN_HEAVYWEIGHT
;
2107 funbox
->tcflags
|= TCF_FUN_ENTRAINS_SCOPES
;
2110 if (!funbox
&& (tcflags
& TCF_IN_FUNCTION
))
2111 tcflags
|= TCF_FUN_HEAVYWEIGHT
;
2115 DeoptimizeUsesWithin(JSDefinition
*dn
, JSFunctionBox
*funbox
, uint32
& tcflags
)
2117 uintN ndeoptimized
= 0;
2118 const TokenPos
&pos
= funbox
->node
->pn_body
->pn_pos
;
2120 for (JSParseNode
*pnu
= dn
->dn_uses
; pnu
; pnu
= pnu
->pn_link
) {
2121 JS_ASSERT(pnu
->pn_used
);
2122 JS_ASSERT(!pnu
->pn_defn
);
2123 if (pnu
->pn_pos
.begin
>= pos
.begin
&& pnu
->pn_pos
.end
<= pos
.end
) {
2124 pnu
->pn_dflags
|= PND_DEOPTIMIZED
;
2129 if (ndeoptimized
!= 0)
2130 FlagHeavyweights(dn
, funbox
, tcflags
);
2134 Parser::setFunctionKinds(JSFunctionBox
*funbox
, uint32
& tcflags
)
2136 #ifdef JS_FUNCTION_METERING
2137 # define FUN_METER(x) JS_RUNTIME_METER(context->runtime, functionMeter.x)
2139 # define FUN_METER(x) ((void)0)
2143 JSParseNode
*fn
= funbox
->node
;
2144 JSParseNode
*pn
= fn
->pn_body
;
2147 setFunctionKinds(funbox
->kids
, tcflags
);
2150 * We've unwound from recursively setting our kids' kinds, which
2151 * also classifies enclosing functions holding upvars referenced in
2152 * those descendants' bodies. So now we can check our "methods".
2154 * Despecialize from branded method-identity-based shape to sprop-
2155 * or slot-based shape if this function smells like a constructor
2156 * and too many of its methods are *not* joinable null closures
2157 * (i.e., they have one or more upvars fetched via the display).
2159 JSParseNode
*pn2
= pn
;
2160 if (PN_TYPE(pn2
) == TOK_UPVARS
)
2162 if (PN_TYPE(pn2
) == TOK_ARGSBODY
)
2165 #if JS_HAS_EXPR_CLOSURES
2166 if (PN_TYPE(pn2
) == TOK_LC
)
2168 if (!(funbox
->tcflags
& TCF_RETURN_EXPR
)) {
2169 uintN methodSets
= 0, slowMethodSets
= 0;
2171 for (JSParseNode
*method
= funbox
->methods
; method
; method
= method
->pn_link
) {
2172 JS_ASSERT(PN_OP(method
) == JSOP_LAMBDA
|| PN_OP(method
) == JSOP_LAMBDA_FC
);
2174 if (!method
->pn_funbox
->joinable())
2178 if (funbox
->shouldUnbrand(methodSets
, slowMethodSets
))
2179 funbox
->tcflags
|= TCF_FUN_UNBRAND_THIS
;
2183 JSFunction
*fun
= (JSFunction
*) funbox
->object
;
2185 JS_ASSERT(FUN_KIND(fun
) == JSFUN_INTERPRETED
);
2188 if (funbox
->tcflags
& TCF_FUN_HEAVYWEIGHT
) {
2190 } else if (pn
->pn_type
!= TOK_UPVARS
) {
2192 * No lexical dependencies => null closure, for best performance.
2193 * A null closure needs no scope chain, but alas we've coupled
2194 * principals-finding to scope (for good fundamental reasons, but
2195 * the implementation overloads the parent slot and we should fix
2196 * that). See, e.g., the JSOP_LAMBDA case in jsinterp.cpp.
2198 * In more detail: the ES3 spec allows the implementation to create
2199 * "joined function objects", or not, at its discretion. But real-
2200 * world implementations always create unique function objects for
2201 * closures, and this can be detected via mutation. Open question:
2202 * do popular implementations create unique function objects for
2205 * FIXME: bug 476950.
2207 FUN_METER(nofreeupvar
);
2208 FUN_SET_KIND(fun
, JSFUN_NULL_CLOSURE
);
2210 JSAtomList
upvars(pn
->pn_names
);
2211 JS_ASSERT(upvars
.count
!= 0);
2213 JSAtomListIterator
iter(&upvars
);
2214 JSAtomListElement
*ale
;
2216 if (!fn
->isFunArg()) {
2218 * This function is Algol-like, it never escapes. So long as it
2219 * does not assign to outer variables, it needs only an upvars
2220 * array in its script and JSOP_{GET,CALL}UPVAR opcodes in its
2221 * bytecode to reach up the frame stack at runtime based on
2222 * those upvars' cookies.
2224 * Any assignments to upvars from functions called by this one
2225 * will be coherent because of the JSOP_{GET,CALL}UPVAR ops,
2226 * which load from stack homes when interpreting or from native
2227 * stack slots when executing a trace.
2229 * We could add JSOP_SETUPVAR, etc., but it is uncommon for a
2230 * nested function to assign to an outer lexical variable, so
2231 * we defer adding yet more code footprint in the absence of
2232 * evidence motivating these opcodes.
2234 bool mutation
= !!(funbox
->tcflags
& TCF_FUN_SETS_OUTER_NAME
);
2238 * Check that at least one outer lexical binding was assigned
2239 * to (global variables don't count). This is conservative: we
2240 * could limit assignments to those in the current function,
2241 * but that's too much work. As with flat closures (handled
2242 * below), we optimize for the case where outer bindings are
2243 * not reassigned anywhere.
2245 while ((ale
= iter()) != NULL
) {
2246 JSDefinition
*lexdep
= ALE_DEFN(ale
)->resolve();
2248 if (!lexdep
->isFreeVar()) {
2249 JS_ASSERT(lexdep
->frameLevel() <= funbox
->level
);
2251 if (lexdep
->isAssigned())
2259 FUN_METER(onlyfreevar
);
2260 FUN_SET_KIND(fun
, JSFUN_NULL_CLOSURE
);
2261 } else if (!mutation
&&
2262 !(funbox
->tcflags
& (TCF_FUN_IS_GENERATOR
| TCF_FUN_ENTRAINS_SCOPES
))) {
2264 * Algol-like functions can read upvars using the dynamic
2265 * link (cx->fp/fp->down), optimized using the cx->display
2266 * lookup table indexed by static level. They do not need
2267 * to entrain and search their environment objects.
2270 FUN_SET_KIND(fun
, JSFUN_NULL_CLOSURE
);
2272 if (!(funbox
->tcflags
& TCF_FUN_IS_GENERATOR
))
2273 FUN_METER(setupvar
);
2276 uintN nupvars
= 0, nflattened
= 0;
2279 * For each lexical dependency from this closure to an outer
2280 * binding, analyze whether it is safe to copy the binding's
2281 * value into a flat closure slot when the closure is formed.
2283 while ((ale
= iter()) != NULL
) {
2284 JSDefinition
*lexdep
= ALE_DEFN(ale
)->resolve();
2286 if (!lexdep
->isFreeVar()) {
2288 if (CanFlattenUpvar(lexdep
, funbox
, tcflags
)) {
2292 DeoptimizeUsesWithin(lexdep
, funbox
, tcflags
);
2297 FUN_METER(onlyfreevar
);
2298 FUN_SET_KIND(fun
, JSFUN_NULL_CLOSURE
);
2299 } else if (nflattened
== nupvars
) {
2300 /* FIXME bug 545759: to test nflattened != 0 */
2302 * We made it all the way through the upvar loop, so it's
2303 * safe to optimize to a flat closure.
2306 FUN_SET_KIND(fun
, JSFUN_FLAT_CLOSURE
);
2307 switch (PN_OP(fn
)) {
2309 fn
->pn_op
= JSOP_DEFFUN_FC
;
2311 case JSOP_DEFLOCALFUN
:
2312 fn
->pn_op
= JSOP_DEFLOCALFUN_FC
;
2315 fn
->pn_op
= JSOP_LAMBDA_FC
;
2318 /* js_EmitTree's case TOK_FUNCTION: will select op. */
2319 JS_ASSERT(PN_OP(fn
) == JSOP_NOP
);
2322 FUN_METER(badfunarg
);
2327 if (FUN_KIND(fun
) == JSFUN_INTERPRETED
&& pn
->pn_type
== TOK_UPVARS
) {
2329 * One or more upvars cannot be safely snapshot into a flat
2330 * closure's dslot (see JSOP_GETDSLOT), so we loop again over
2331 * all upvars, and for each non-free upvar, ensure that its
2332 * containing function has been flagged as heavyweight.
2334 * The emitter must see TCF_FUN_HEAVYWEIGHT accurately before
2335 * generating any code for a tree of nested functions.
2337 JSAtomList
upvars(pn
->pn_names
);
2338 JS_ASSERT(upvars
.count
!= 0);
2340 JSAtomListIterator
iter(&upvars
);
2341 JSAtomListElement
*ale
;
2343 while ((ale
= iter()) != NULL
) {
2344 JSDefinition
*lexdep
= ALE_DEFN(ale
)->resolve();
2345 if (!lexdep
->isFreeVar())
2346 FlagHeavyweights(lexdep
, funbox
, tcflags
);
2350 funbox
= funbox
->siblings
;
2358 const char js_argument_str
[] = "argument";
2359 const char js_variable_str
[] = "variable";
2360 const char js_unknown_str
[] = "unknown";
2363 JSDefinition::kindString(Kind kind
)
2365 static const char *table
[] = {
2366 js_var_str
, js_const_str
, js_let_str
,
2367 js_function_str
, js_argument_str
, js_unknown_str
2370 JS_ASSERT(unsigned(kind
) <= unsigned(ARG
));
2374 static JSFunctionBox
*
2375 EnterFunction(JSParseNode
*fn
, JSTreeContext
*funtc
, JSAtom
*funAtom
= NULL
,
2376 uintN lambda
= JSFUN_LAMBDA
)
2378 JSTreeContext
*tc
= funtc
->parent
;
2379 JSFunction
*fun
= tc
->parser
->newFunction(tc
, funAtom
, lambda
);
2383 /* Create box for fun->object early to protect against last-ditch GC. */
2384 JSFunctionBox
*funbox
= tc
->parser
->newFunctionBox(FUN_OBJECT(fun
), fn
, tc
);
2388 /* Initialize non-default members of funtc. */
2389 funtc
->flags
|= funbox
->tcflags
;
2390 funtc
->blockidGen
= tc
->blockidGen
;
2391 if (!GenerateBlockId(funtc
, funtc
->bodyid
))
2394 funtc
->funbox
= funbox
;
2395 if (!SetStaticLevel(funtc
, tc
->staticLevel
+ 1))
2402 LeaveFunction(JSParseNode
*fn
, JSTreeContext
*funtc
, JSAtom
*funAtom
= NULL
,
2403 uintN lambda
= JSFUN_LAMBDA
)
2405 JSTreeContext
*tc
= funtc
->parent
;
2406 tc
->blockidGen
= funtc
->blockidGen
;
2408 JSFunctionBox
*funbox
= fn
->pn_funbox
;
2409 funbox
->tcflags
|= funtc
->flags
& (TCF_FUN_FLAGS
| TCF_COMPILE_N_GO
| TCF_RETURN_EXPR
);
2411 fn
->pn_dflags
|= PND_INITIALIZED
;
2412 JS_ASSERT_IF(tc
->atTopLevel() && lambda
== 0 && funAtom
,
2413 fn
->pn_dflags
& PND_TOPLEVEL
);
2414 if (!tc
->topStmt
|| tc
->topStmt
->type
== STMT_BLOCK
)
2415 fn
->pn_dflags
|= PND_BLOCKCHILD
;
2418 * Propagate unresolved lexical names up to tc->lexdeps, and save a copy
2419 * of funtc->lexdeps in a TOK_UPVARS node wrapping the function's formal
2420 * params and body. We do this only if there are lexical dependencies not
2421 * satisfied by the function's declarations, to avoid penalizing functions
2422 * that use only their arguments and other local bindings.
2424 if (funtc
->lexdeps
.count
!= 0) {
2425 JSAtomListIterator
iter(&funtc
->lexdeps
);
2426 JSAtomListElement
*ale
;
2427 int foundCallee
= 0;
2429 while ((ale
= iter()) != NULL
) {
2430 JSAtom
*atom
= ALE_ATOM(ale
);
2431 JSDefinition
*dn
= ALE_DEFN(ale
);
2432 JS_ASSERT(dn
->isPlaceholder());
2434 if (atom
== funAtom
&& lambda
!= 0) {
2435 dn
->pn_op
= JSOP_CALLEE
;
2436 dn
->pn_cookie
= MAKE_UPVAR_COOKIE(funtc
->staticLevel
, CALLEE_UPVAR_SLOT
);
2437 dn
->pn_dflags
|= PND_BOUND
;
2440 * If this named function expression uses its own name other
2441 * than to call itself, flag this function specially.
2444 funbox
->tcflags
|= TCF_FUN_USES_OWN_NAME
;
2449 if (!(funbox
->tcflags
& TCF_FUN_SETS_OUTER_NAME
) &&
2452 * Make sure we do not fail to set TCF_FUN_SETS_OUTER_NAME if
2453 * any use of dn in funtc assigns. See NoteLValue for the easy
2454 * backward-reference case; this is the hard forward-reference
2455 * case where we pay a higher price.
2457 for (JSParseNode
*pnu
= dn
->dn_uses
; pnu
; pnu
= pnu
->pn_link
) {
2458 if (pnu
->isAssigned() && pnu
->pn_blockid
>= funtc
->bodyid
) {
2459 funbox
->tcflags
|= TCF_FUN_SETS_OUTER_NAME
;
2465 JSAtomListElement
*outer_ale
= tc
->decls
.lookup(atom
);
2467 outer_ale
= tc
->lexdeps
.lookup(atom
);
2470 * Insert dn's uses list at the front of outer_dn's list.
2472 * Without loss of generality or correctness, we allow a dn to
2473 * be in inner and outer lexdeps, since the purpose of lexdeps
2474 * is one-pass coordination of name use and definition across
2475 * functions, and if different dn's are used we'll merge lists
2476 * when leaving the inner function.
2478 * The dn == outer_dn case arises with generator expressions
2479 * (see CompExprTransplanter::transplant, the PN_FUNC/PN_NAME
2480 * case), and nowhere else, currently.
2482 JSDefinition
*outer_dn
= ALE_DEFN(outer_ale
);
2484 if (dn
!= outer_dn
) {
2485 JSParseNode
**pnup
= &dn
->dn_uses
;
2488 while ((pnu
= *pnup
) != NULL
) {
2489 pnu
->pn_lexdef
= outer_dn
;
2490 pnup
= &pnu
->pn_link
;
2494 * Make dn be a use that redirects to outer_dn, because we
2495 * can't replace dn with outer_dn in all the pn_namesets in
2496 * the AST where it may be. Instead we make it forward to
2497 * outer_dn. See JSDefinition::resolve.
2499 *pnup
= outer_dn
->dn_uses
;
2500 outer_dn
->dn_uses
= dn
;
2501 outer_dn
->pn_dflags
|= dn
->pn_dflags
& ~PND_PLACEHOLDER
;
2502 dn
->pn_defn
= false;
2504 dn
->pn_lexdef
= outer_dn
;
2507 /* Add an outer lexical dependency for ale's definition. */
2508 outer_ale
= tc
->lexdeps
.add(tc
->parser
, atom
);
2511 ALE_SET_DEFN(outer_ale
, ALE_DEFN(ale
));
2515 if (funtc
->lexdeps
.count
- foundCallee
!= 0) {
2516 JSParseNode
*body
= fn
->pn_body
;
2518 fn
->pn_body
= NameSetNode::create(tc
);
2522 fn
->pn_body
->pn_type
= TOK_UPVARS
;
2523 fn
->pn_body
->pn_pos
= body
->pn_pos
;
2525 funtc
->lexdeps
.remove(tc
->parser
, funAtom
);
2526 fn
->pn_body
->pn_names
= funtc
->lexdeps
;
2527 fn
->pn_body
->pn_tree
= body
;
2530 funtc
->lexdeps
.clear();
2537 Parser::functionDef(uintN lambda
, bool namePermitted
)
2539 JSParseNode
*pn
, *body
, *result
;
2541 JSAtomListElement
*ale
;
2542 #if JS_HAS_DESTRUCTURING
2543 JSParseNode
*item
, *list
= NULL
;
2544 bool destructuringArg
= false;
2545 JSAtom
*duplicatedArg
= NULL
;
2549 * Save the current op for later so we can tag the created function as a
2550 * getter/setter if necessary.
2552 JSOp op
= tokenStream
.currentToken().t_op
;
2554 /* Make a TOK_FUNCTION node. */
2555 pn
= FunctionNode::create(tc
);
2559 pn
->pn_cookie
= FREE_UPVAR_COOKIE
;
2562 * If a lambda, give up on JSOP_{GET,CALL}UPVAR usage unless this function
2563 * is immediately applied (we clear PND_FUNARG if so -- see memberExpr).
2565 * Also treat function sub-statements (non-lambda, non-top-level functions)
2566 * as escaping funargs, since we can't statically analyze their definitions
2569 bool topLevel
= tc
->atTopLevel();
2570 pn
->pn_dflags
= (lambda
|| !topLevel
) ? PND_FUNARG
: 0;
2572 /* Scan the optional function name into funAtom. */
2573 JSAtom
*funAtom
= NULL
;
2574 if (namePermitted
) {
2575 tt
= tokenStream
.getToken(TSF_KEYWORD_IS_NAME
);
2576 if (tt
== TOK_NAME
) {
2577 funAtom
= tokenStream
.currentToken().t_atom
;
2579 if (lambda
== 0 && (context
->options
& JSOPTION_ANONFUNFIX
)) {
2580 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_SYNTAX_ERROR
);
2583 tokenStream
.ungetToken();
2588 * Record names for function statements in tc->decls so we know when to
2589 * avoid optimizing variable references that might name a function.
2591 if (lambda
== 0 && funAtom
) {
2592 ale
= tc
->decls
.lookup(funAtom
);
2594 JSDefinition
*dn
= ALE_DEFN(ale
);
2595 JSDefinition::Kind dn_kind
= dn
->kind();
2597 JS_ASSERT(!dn
->pn_used
);
2598 JS_ASSERT(dn
->pn_defn
);
2600 if (JS_HAS_STRICT_OPTION(context
) || dn_kind
== JSDefinition::CONST
) {
2601 const char *name
= js_AtomToPrintableString(context
, funAtom
);
2603 !reportErrorNumber(NULL
,
2604 (dn_kind
!= JSDefinition::CONST
)
2605 ? JSREPORT_WARNING
| JSREPORT_STRICT
2607 JSMSG_REDECLARED_VAR
,
2608 JSDefinition::kindString(dn_kind
),
2615 ALE_SET_DEFN(ale
, pn
);
2617 pn
->dn_uses
= dn
; /* dn->dn_uses is now pn_link */
2619 if (!MakeDefIntoUse(dn
, pn
, funAtom
, tc
))
2622 } else if (topLevel
) {
2624 * If this function was used before it was defined, claim the
2625 * pre-created definition node for this function that primaryExpr
2626 * put in tc->lexdeps on first forward reference, and recycle pn.
2630 ale
= tc
->lexdeps
.rawLookup(funAtom
, hep
);
2632 JSDefinition
*fn
= ALE_DEFN(ale
);
2634 JS_ASSERT(fn
->pn_defn
);
2635 fn
->pn_type
= TOK_FUNCTION
;
2636 fn
->pn_arity
= PN_FUNC
;
2637 fn
->pn_pos
.begin
= pn
->pn_pos
.begin
;
2639 fn
->pn_cookie
= FREE_UPVAR_COOKIE
;
2641 tc
->lexdeps
.rawRemove(tc
->parser
, ale
, hep
);
2642 RecycleTree(pn
, tc
);
2646 if (!Define(pn
, funAtom
, tc
))
2651 * A function nested at top level inside another's body needs only a
2652 * local variable to bind its name to its value, and not an activation
2653 * object property (it might also need the activation property, if the
2654 * outer function contains with statements, e.g., but the stack slot
2655 * wins when jsemit.c's BindNameToSlot can optimize a JSOP_NAME into a
2656 * JSOP_GETLOCAL bytecode).
2659 pn
->pn_dflags
|= PND_TOPLEVEL
;
2661 if (tc
->inFunction()) {
2662 JSLocalKind localKind
;
2666 * Define a local in the outer function so that BindNameToSlot
2667 * can properly optimize accesses. Note that we need a local
2668 * variable, not an argument, for the function statement. Thus
2669 * we add a variable even if a parameter with the given name
2672 localKind
= js_LookupLocal(context
, tc
->fun
, funAtom
, &index
);
2673 switch (localKind
) {
2676 index
= tc
->fun
->u
.i
.nvars
;
2677 if (!js_AddLocal(context
, tc
->fun
, funAtom
, JSLOCAL_VAR
))
2682 pn
->pn_cookie
= MAKE_UPVAR_COOKIE(tc
->staticLevel
, index
);
2683 pn
->pn_dflags
|= PND_BOUND
;
2692 JSTreeContext
*outertc
= tc
;
2694 /* Initialize early for possible flags mutation via destructuringExpr. */
2695 JSTreeContext
funtc(tc
->parser
);
2697 JSFunctionBox
*funbox
= EnterFunction(pn
, &funtc
, funAtom
, lambda
);
2701 JSFunction
*fun
= (JSFunction
*) funbox
->object
;
2704 fun
->flags
|= (op
== JSOP_GETTER
) ? JSPROP_GETTER
: JSPROP_SETTER
;
2706 /* Now parse formal argument list and compute fun->nargs. */
2707 MUST_MATCH_TOKEN(TOK_LP
, JSMSG_PAREN_BEFORE_FORMAL
);
2708 if (!tokenStream
.matchToken(TOK_RP
)) {
2710 tt
= tokenStream
.getToken();
2712 #if JS_HAS_DESTRUCTURING
2717 JSParseNode
*lhs
, *rhs
;
2720 /* See comment below in the TOK_NAME case. */
2722 goto report_dup_and_destructuring
;
2723 destructuringArg
= true;
2726 * A destructuring formal parameter turns into one or more
2727 * local variables initialized from properties of a single
2728 * anonymous positional parameter, so here we must tweak our
2729 * binder and its data.
2732 data
.op
= JSOP_DEFVAR
;
2733 data
.binder
= BindDestructuringArg
;
2734 lhs
= destructuringExpr(&data
, tt
);
2739 * Adjust fun->nargs to count the single anonymous positional
2740 * parameter that is to be destructured.
2743 if (!js_AddLocal(context
, fun
, NULL
, JSLOCAL_ARG
))
2747 * Synthesize a destructuring assignment from the single
2748 * anonymous positional parameter into the destructuring
2749 * left-hand-side expression and accumulate it in list.
2751 rhs
= NameNode::create(context
->runtime
->atomState
.emptyAtom
, &funtc
);
2754 rhs
->pn_type
= TOK_NAME
;
2755 rhs
->pn_op
= JSOP_GETARG
;
2756 rhs
->pn_cookie
= MAKE_UPVAR_COOKIE(funtc
.staticLevel
, slot
);
2757 rhs
->pn_dflags
|= PND_BOUND
;
2759 item
= JSParseNode::newBinaryOrAppend(TOK_ASSIGN
, JSOP_NOP
, lhs
, rhs
, &funtc
);
2763 list
= ListNode::create(&funtc
);
2766 list
->pn_type
= TOK_COMMA
;
2772 #endif /* JS_HAS_DESTRUCTURING */
2776 JSAtom
*atom
= tokenStream
.currentToken().t_atom
;
2777 if (!DefineArg(pn
, atom
, fun
->nargs
, &funtc
))
2779 #ifdef JS_HAS_DESTRUCTURING
2781 * ECMA-262 requires us to support duplicate parameter names, but if the
2782 * parameter list includes destructuring, we consider the code to have
2783 * opted in to higher standards, and forbid duplicates. We may see a
2784 * destructuring parameter later, so always note duplicates now.
2786 * Duplicates are warned about (strict option) or cause errors (strict
2787 * mode code), but we do those tests in one place below, after having
2790 if (js_LookupLocal(context
, fun
, atom
, NULL
) != JSLOCAL_NONE
) {
2791 duplicatedArg
= atom
;
2792 if (destructuringArg
)
2793 goto report_dup_and_destructuring
;
2796 if (!js_AddLocal(context
, fun
, atom
, JSLOCAL_ARG
))
2802 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_MISSING_FORMAL
);
2807 #if JS_HAS_DESTRUCTURING
2808 report_dup_and_destructuring
:
2809 JSDefinition
*dn
= ALE_DEFN(funtc
.decls
.lookup(duplicatedArg
));
2810 reportErrorNumber(dn
, JSREPORT_ERROR
, JSMSG_DESTRUCT_DUP_ARG
);
2814 } while (tokenStream
.matchToken(TOK_COMMA
));
2816 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_AFTER_FORMAL
);
2819 #if JS_HAS_EXPR_CLOSURES
2820 tt
= tokenStream
.getToken(TSF_OPERAND
);
2822 tokenStream
.ungetToken();
2823 fun
->flags
|= JSFUN_EXPR_CLOSURE
;
2826 MUST_MATCH_TOKEN(TOK_LC
, JSMSG_CURLY_BEFORE_BODY
);
2829 body
= functionBody();
2833 if (!CheckStrictBinding(context
, &funtc
, funAtom
, pn
))
2836 if (!CheckStrictFormals(context
, &funtc
, fun
, pn
))
2839 #if JS_HAS_EXPR_CLOSURES
2841 MUST_MATCH_TOKEN(TOK_RC
, JSMSG_CURLY_AFTER_BODY
);
2842 else if (lambda
== 0 && !MatchOrInsertSemicolon(context
, &tokenStream
))
2845 MUST_MATCH_TOKEN(TOK_RC
, JSMSG_CURLY_AFTER_BODY
);
2847 pn
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
2849 #if JS_HAS_DESTRUCTURING
2851 * If there were destructuring formal parameters, prepend the initializing
2852 * comma expression that we synthesized to body. If the body is a lexical
2853 * scope node, we must make a special TOK_SEQ node, to prepend the formal
2854 * parameter destructuring code without bracing the decompilation of the
2855 * function body's lexical scope.
2858 if (body
->pn_arity
!= PN_LIST
) {
2861 block
= ListNode::create(outertc
);
2864 block
->pn_type
= TOK_SEQ
;
2865 block
->pn_pos
= body
->pn_pos
;
2866 block
->initList(body
);
2871 item
= UnaryNode::create(outertc
);
2875 item
->pn_type
= TOK_SEMI
;
2876 item
->pn_pos
.begin
= item
->pn_pos
.end
= body
->pn_pos
.begin
;
2877 item
->pn_kid
= list
;
2878 item
->pn_next
= body
->pn_head
;
2879 body
->pn_head
= item
;
2880 if (body
->pn_tail
== &body
->pn_head
)
2881 body
->pn_tail
= &item
->pn_next
;
2883 body
->pn_xflags
|= PNX_DESTRUCT
;
2888 * If we collected flags that indicate nested heavyweight functions, or
2889 * this function contains heavyweight-making statements (with statement,
2890 * visible eval call, or assignment to 'arguments'), flag the function as
2891 * heavyweight (requiring a call object per invocation).
2893 if (funtc
.flags
& TCF_FUN_HEAVYWEIGHT
) {
2894 fun
->flags
|= JSFUN_HEAVYWEIGHT
;
2895 outertc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
2898 * If this function is a named statement function not at top-level
2899 * (i.e. not a top-level function definiton or expression), then our
2900 * enclosing function, if any, must be heavyweight.
2902 if (!topLevel
&& lambda
== 0 && funAtom
)
2903 outertc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
2909 * ECMA ed. 3 standard: function expression, possibly anonymous.
2912 } else if (!funAtom
) {
2914 * If this anonymous function definition is *not* embedded within a
2915 * larger expression, we treat it as an expression statement, not as
2916 * a function declaration -- and not as a syntax error (as ECMA-262
2917 * Edition 3 would have it). Backward compatibility must trump all,
2918 * unless JSOPTION_ANONFUNFIX is set.
2920 result
= UnaryNode::create(outertc
);
2923 result
->pn_type
= TOK_SEMI
;
2924 result
->pn_pos
= pn
->pn_pos
;
2925 result
->pn_kid
= pn
;
2927 } else if (!topLevel
) {
2929 * ECMA ed. 3 extension: a function expression statement not at the
2930 * top level, e.g., in a compound statement such as the "then" part
2931 * of an "if" statement, binds a closure only if control reaches that
2939 funbox
->kids
= funtc
.functionList
;
2941 pn
->pn_funbox
= funbox
;
2944 pn
->pn_body
->append(body
);
2945 pn
->pn_body
->pn_pos
= body
->pn_pos
;
2950 pn
->pn_blockid
= outertc
->blockid();
2952 if (!LeaveFunction(pn
, &funtc
, funAtom
, lambda
))
2955 /* If the surrounding function is not strict code, reset the lexer. */
2956 if (!(outertc
->flags
& TCF_STRICT_MODE_CODE
))
2957 tokenStream
.setStrictMode(false);
2963 Parser::functionStmt()
2965 return functionDef(0, true);
2969 Parser::functionExpr()
2971 return functionDef(JSFUN_LAMBDA
, true);
2975 * Recognize Directive Prologue members and directives. Assuming pn
2976 * is a candidate for membership in a directive prologue, return
2977 * true if it is in fact a member. Recognize directives and set
2978 * tc's flags accordingly.
2980 * Note that the following is a strict mode function:
2983 * "blah" // inserted semi colon
2989 * That is, a statement can be a Directive Prologue member, even
2990 * if it can't possibly be a directive, now or in the future.
2993 Parser::recognizeDirectivePrologue(JSParseNode
*pn
)
2995 if (!pn
->isDirectivePrologueMember())
2997 if (pn
->isDirective()) {
2998 JSAtom
*directive
= pn
->pn_kid
->pn_atom
;
2999 if (directive
== context
->runtime
->atomState
.useStrictAtom
) {
3000 tc
->flags
|= TCF_STRICT_MODE_CODE
;
3001 tokenStream
.setStrictMode();
3008 * Parse the statements in a block, creating a TOK_LC node that lists the
3009 * statements' trees. If called from block-parsing code, the caller must
3010 * match { before and } after.
3013 Parser::statements()
3015 JSParseNode
*pn
, *pn2
, *saveBlock
;
3017 bool inDirectivePrologue
= tc
->atTopLevel();
3019 JS_CHECK_RECURSION(context
, return NULL
);
3021 pn
= ListNode::create(tc
);
3024 pn
->pn_type
= TOK_LC
;
3026 pn
->pn_blockid
= tc
->blockid();
3027 saveBlock
= tc
->blockNode
;
3031 tt
= tokenStream
.peekToken(TSF_OPERAND
);
3032 if (tt
<= TOK_EOF
|| tt
== TOK_RC
) {
3033 if (tt
== TOK_ERROR
) {
3034 if (tokenStream
.isEOF())
3035 tokenStream
.setUnexpectedEOF();
3042 if (tokenStream
.isEOF())
3043 tokenStream
.setUnexpectedEOF();
3047 if (inDirectivePrologue
)
3048 inDirectivePrologue
= recognizeDirectivePrologue(pn2
);
3050 if (pn2
->pn_type
== TOK_FUNCTION
) {
3052 * PNX_FUNCDEFS notifies the emitter that the block contains top-
3053 * level function definitions that should be processed before the
3056 * TCF_HAS_FUNCTION_STMT is for the TOK_LC case in Statement. It
3057 * is relevant only for function definitions not at top-level,
3058 * which we call function statements.
3060 if (tc
->atTopLevel())
3061 pn
->pn_xflags
|= PNX_FUNCDEFS
;
3063 tc
->flags
|= TCF_HAS_FUNCTION_STMT
;
3069 * Handle the case where there was a let declaration under this block. If
3070 * it replaced tc->blockNode with a new block node then we must refresh pn
3071 * and then restore tc->blockNode.
3073 if (tc
->blockNode
!= pn
)
3075 tc
->blockNode
= saveBlock
;
3077 pn
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
3086 MUST_MATCH_TOKEN(TOK_LP
, JSMSG_PAREN_BEFORE_COND
);
3087 pn
= parenExpr(NULL
, NULL
);
3090 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_AFTER_COND
);
3092 /* Check for (a = b) and warn about possible (a == b) mistype. */
3093 if (pn
->pn_type
== TOK_ASSIGN
&&
3094 pn
->pn_op
== JSOP_NOP
&&
3096 !reportErrorNumber(NULL
, JSREPORT_WARNING
| JSREPORT_STRICT
, JSMSG_EQUAL_AS_ASSIGN
, "")) {
3103 MatchLabel(JSContext
*cx
, TokenStream
*ts
, JSParseNode
*pn
)
3108 tt
= ts
->peekTokenSameLine();
3109 if (tt
== TOK_ERROR
)
3111 if (tt
== TOK_NAME
) {
3112 (void) ts
->getToken();
3113 label
= ts
->currentToken().t_atom
;
3117 pn
->pn_atom
= label
;
3122 BindLet(JSContext
*cx
, BindData
*data
, JSAtom
*atom
, JSTreeContext
*tc
)
3126 JSAtomListElement
*ale
;
3130 * Top-level 'let' is the same as 'var' currently -- this may change in a
3131 * successor standard to ES3.1 that specifies 'let'.
3133 JS_ASSERT(!tc
->atTopLevel());
3136 if (!CheckStrictBinding(cx
, tc
, atom
, pn
))
3139 blockObj
= tc
->blockChain
;
3140 ale
= tc
->decls
.lookup(atom
);
3141 if (ale
&& ALE_DEFN(ale
)->pn_blockid
== tc
->blockid()) {
3142 const char *name
= js_AtomToPrintableString(cx
, atom
);
3144 ReportCompileErrorNumber(cx
, TS(tc
->parser
), pn
,
3145 JSREPORT_ERROR
, JSMSG_REDECLARED_VAR
,
3146 (ale
&& ALE_DEFN(ale
)->isConst())
3154 n
= OBJ_BLOCK_COUNT(cx
, blockObj
);
3155 if (n
== JS_BIT(16)) {
3156 ReportCompileErrorNumber(cx
, TS(tc
->parser
), pn
,
3157 JSREPORT_ERROR
, data
->let
.overflow
);
3162 * Pass push = true to Define so it pushes an ale ahead of any outer scope.
3163 * This is balanced by PopStatement, defined immediately below.
3165 if (!Define(pn
, atom
, tc
, true))
3169 * Assign block-local index to pn->pn_cookie right away, encoding it as an
3170 * upvar cookie whose skip tells the current static level. The emitter will
3171 * adjust the node's slot based on its stack depth model -- and, for global
3172 * and eval code, Compiler::compileScript will adjust the slot again to
3173 * include script->nfixed.
3175 pn
->pn_op
= JSOP_GETLOCAL
;
3176 pn
->pn_cookie
= MAKE_UPVAR_COOKIE(tc
->staticLevel
, n
);
3177 pn
->pn_dflags
|= PND_LET
| PND_BOUND
;
3180 * Define the let binding's property before storing pn in a reserved slot,
3181 * since block_reserveSlots depends on blockObj->scope()->entryCount.
3183 if (!js_DefineBlockVariable(cx
, blockObj
, ATOM_TO_JSID(atom
), n
))
3187 * Store pn temporarily in what would be reserved slots in a cloned block
3188 * object (once the prototype's final population is known, after all 'let'
3189 * bindings for this block have been parsed). We will free these reserved
3190 * slots in jsemit.cpp:EmitEnterBlock.
3192 uintN slot
= JSSLOT_FREE(&js_BlockClass
) + n
;
3193 if (slot
>= blockObj
->numSlots() &&
3194 !blockObj
->growSlots(cx
, slot
+ 1)) {
3197 blockObj
->scope()->freeslot
= slot
+ 1;
3198 blockObj
->setSlot(slot
, PRIVATE_TO_JSVAL(pn
));
3203 PopStatement(JSTreeContext
*tc
)
3205 JSStmtInfo
*stmt
= tc
->topStmt
;
3207 if (stmt
->flags
& SIF_SCOPE
) {
3208 JSObject
*obj
= stmt
->blockObj
;
3209 JSScope
*scope
= obj
->scope();
3210 JS_ASSERT(!OBJ_IS_CLONED_BLOCK(obj
));
3212 for (JSScopeProperty
*sprop
= scope
->lastProperty(); sprop
; sprop
= sprop
->parent
) {
3213 JSAtom
*atom
= JSID_TO_ATOM(sprop
->id
);
3215 /* Beware the empty destructuring dummy. */
3216 if (atom
== tc
->parser
->context
->runtime
->atomState
.emptyAtom
)
3218 tc
->decls
.remove(tc
->parser
, atom
);
3221 js_PopStatement(tc
);
3225 OuterLet(JSTreeContext
*tc
, JSStmtInfo
*stmt
, JSAtom
*atom
)
3227 while (stmt
->downScope
) {
3228 stmt
= js_LexicalLookup(tc
, atom
, NULL
, stmt
->downScope
);
3231 if (stmt
->type
== STMT_BLOCK
)
3238 * If we are generating global or eval-called-from-global code, bind a "gvar"
3239 * here, as soon as possible. The JSOP_GETGVAR, etc., ops speed up interpreted
3240 * global variable access by memoizing name-to-slot mappings during execution
3241 * of the script prolog (via JSOP_DEFVAR/JSOP_DEFCONST). If the memoization
3242 * can't be done due to a pre-existing property of the same name as the var or
3243 * const but incompatible attributes/getter/setter/etc, these ops devolve to
3246 * For now, don't try to lookup eval frame variables at compile time. This is
3247 * sub-optimal: we could handle eval-called-from-global-code gvars since eval
3248 * gets its own script and frame. The eval-from-function-code case is harder,
3249 * since functions do not atomize gvars and then reserve their atom indexes as
3250 * stack frame slots.
3253 BindGvar(JSParseNode
*pn
, JSTreeContext
*tc
, bool inWith
= false)
3255 JS_ASSERT(pn
->pn_op
== JSOP_NAME
);
3256 JS_ASSERT(!tc
->inFunction());
3258 if (tc
->compiling() && !tc
->parser
->callerFrame
) {
3259 JSCodeGenerator
*cg
= (JSCodeGenerator
*) tc
;
3261 /* Index pn->pn_atom so we can map fast global number to name. */
3262 JSAtomListElement
*ale
= cg
->atomList
.add(tc
->parser
, pn
->pn_atom
);
3266 /* Defend against cg->ngvars 16-bit overflow. */
3267 uintN slot
= ALE_INDEX(ale
);
3268 if ((slot
+ 1) >> 16)
3271 if ((uint16
)(slot
+ 1) > cg
->ngvars
)
3272 cg
->ngvars
= (uint16
)(slot
+ 1);
3275 pn
->pn_op
= JSOP_GETGVAR
;
3276 pn
->pn_cookie
= MAKE_UPVAR_COOKIE(tc
->staticLevel
, slot
);
3277 pn
->pn_dflags
|= PND_BOUND
| PND_GVAR
;
3285 BindVarOrConst(JSContext
*cx
, BindData
*data
, JSAtom
*atom
, JSTreeContext
*tc
)
3287 JSParseNode
*pn
= data
->pn
;
3289 /* Default best op for pn is JSOP_NAME; we'll try to improve below. */
3290 pn
->pn_op
= JSOP_NAME
;
3292 if (!CheckStrictBinding(cx
, tc
, atom
, pn
))
3295 JSStmtInfo
*stmt
= js_LexicalLookup(tc
, atom
, NULL
);
3297 if (stmt
&& stmt
->type
== STMT_WITH
) {
3298 data
->fresh
= false;
3299 return tc
->inFunction() || BindGvar(pn
, tc
, true);
3302 JSAtomListElement
*ale
= tc
->decls
.lookup(atom
);
3306 JSDefinition
*dn
= ale
? ALE_DEFN(ale
) : NULL
;
3307 JSDefinition::Kind dn_kind
= dn
? dn
->kind() : JSDefinition::VAR
;
3310 if (dn_kind
== JSDefinition::ARG
) {
3311 name
= js_AtomToPrintableString(cx
, atom
);
3315 if (op
== JSOP_DEFCONST
) {
3316 ReportCompileErrorNumber(cx
, TS(tc
->parser
), pn
,
3317 JSREPORT_ERROR
, JSMSG_REDECLARED_PARAM
,
3321 if (!ReportCompileErrorNumber(cx
, TS(tc
->parser
), pn
,
3322 JSREPORT_WARNING
| JSREPORT_STRICT
,
3323 JSMSG_VAR_HIDES_ARG
, name
)) {
3327 bool error
= (op
== JSOP_DEFCONST
||
3328 dn_kind
== JSDefinition::CONST
||
3329 (dn_kind
== JSDefinition::LET
&&
3330 (stmt
->type
!= STMT_CATCH
|| OuterLet(tc
, stmt
, atom
))));
3332 if (JS_HAS_STRICT_OPTION(cx
)
3333 ? op
!= JSOP_DEFVAR
|| dn_kind
!= JSDefinition::VAR
3335 name
= js_AtomToPrintableString(cx
, atom
);
3337 !ReportCompileErrorNumber(cx
, TS(tc
->parser
), pn
,
3339 ? JSREPORT_WARNING
| JSREPORT_STRICT
3341 JSMSG_REDECLARED_VAR
,
3342 JSDefinition::kindString(dn_kind
),
3351 if (!Define(pn
, atom
, tc
))
3355 * A var declaration never recreates an existing binding, it restates
3356 * it and possibly reinitializes its value. Beware that if pn becomes a
3357 * use of ALE_DEFN(ale), and if we have an initializer for this var or
3358 * const (typically a const would ;-), then pn must be rewritten into a
3359 * TOK_ASSIGN node. See Variables, further below.
3361 * A case such as let (x = 1) { var x = 2; print(x); } is even harder.
3362 * There the x definition is hoisted but the x = 2 assignment mutates
3363 * the block-local binding of x.
3365 JSDefinition
*dn
= ALE_DEFN(ale
);
3367 data
->fresh
= false;
3370 /* Make pnu be a fresh name node that uses dn. */
3371 JSParseNode
*pnu
= pn
;
3374 pnu
= NameNode::create(atom
, tc
);
3379 LinkUseToDef(pnu
, dn
, tc
);
3380 pnu
->pn_op
= JSOP_NAME
;
3383 while (dn
->kind() == JSDefinition::LET
) {
3385 ale
= ALE_NEXT(ale
);
3386 } while (ale
&& ALE_ATOM(ale
) != atom
);
3393 JS_ASSERT_IF(data
->op
== JSOP_DEFCONST
,
3394 dn
->kind() == JSDefinition::CONST
);
3399 * A var or const that is shadowed by one or more let bindings of the
3400 * same name, but that has not been declared until this point, must be
3401 * hoisted above the let bindings.
3406 ale
= tc
->lexdeps
.rawLookup(atom
, hep
);
3409 tc
->lexdeps
.rawRemove(tc
->parser
, ale
, hep
);
3411 JSParseNode
*pn2
= NameNode::create(atom
, tc
);
3415 /* The token stream may be past the location for pn. */
3416 pn2
->pn_type
= TOK_NAME
;
3417 pn2
->pn_pos
= pn
->pn_pos
;
3420 pn
->pn_op
= JSOP_NAME
;
3423 ale
= tc
->decls
.add(tc
->parser
, atom
, JSAtomList::HOIST
);
3426 ALE_SET_DEFN(ale
, pn
);
3428 pn
->pn_dflags
&= ~PND_PLACEHOLDER
;
3431 if (data
->op
== JSOP_DEFCONST
)
3432 pn
->pn_dflags
|= PND_CONST
;
3434 if (!tc
->inFunction())
3435 return BindGvar(pn
, tc
);
3437 if (atom
== cx
->runtime
->atomState
.argumentsAtom
) {
3438 pn
->pn_op
= JSOP_ARGUMENTS
;
3439 pn
->pn_dflags
|= PND_BOUND
;
3443 JSLocalKind localKind
= js_LookupLocal(cx
, tc
->fun
, atom
, NULL
);
3444 if (localKind
== JSLOCAL_NONE
) {
3446 * Property not found in current variable scope: we have not seen this
3447 * variable before. Define a new local variable by adding a property to
3448 * the function's scope and allocating one slot in the function's vars
3449 * frame. Any locals declared in a with statement body are handled at
3450 * runtime, by script prolog JSOP_DEFVAR opcodes generated for global
3451 * and heavyweight-function-local vars.
3453 localKind
= (data
->op
== JSOP_DEFCONST
) ? JSLOCAL_CONST
: JSLOCAL_VAR
;
3455 uintN index
= tc
->fun
->u
.i
.nvars
;
3456 if (!BindLocalVariable(cx
, tc
->fun
, atom
, localKind
, false))
3458 pn
->pn_op
= JSOP_GETLOCAL
;
3459 pn
->pn_cookie
= MAKE_UPVAR_COOKIE(tc
->staticLevel
, index
);
3460 pn
->pn_dflags
|= PND_BOUND
;
3464 if (localKind
== JSLOCAL_ARG
) {
3465 /* We checked errors and strict warnings earlier -- see above. */
3466 JS_ASSERT(ale
&& ALE_DEFN(ale
)->kind() == JSDefinition::ARG
);
3468 /* Not an argument, must be a redeclared local var. */
3469 JS_ASSERT(localKind
== JSLOCAL_VAR
|| localKind
== JSLOCAL_CONST
);
3475 MakeSetCall(JSContext
*cx
, JSParseNode
*pn
, JSTreeContext
*tc
, uintN msg
)
3479 JS_ASSERT(pn
->pn_arity
== PN_LIST
);
3480 JS_ASSERT(pn
->pn_op
== JSOP_CALL
|| pn
->pn_op
== JSOP_EVAL
|| pn
->pn_op
== JSOP_APPLY
);
3482 if (pn2
->pn_type
== TOK_FUNCTION
&& (pn2
->pn_funbox
->tcflags
& TCF_GENEXP_LAMBDA
)) {
3483 ReportCompileErrorNumber(cx
, TS(tc
->parser
), pn
, JSREPORT_ERROR
, msg
);
3486 pn
->pn_op
= JSOP_SETCALL
;
3491 NoteLValue(JSContext
*cx
, JSParseNode
*pn
, JSTreeContext
*tc
, uintN dflag
= PND_ASSIGNED
)
3494 JSDefinition
*dn
= pn
->pn_lexdef
;
3497 * Save the win of PND_INITIALIZED if we can prove 'var x;' and 'x = y'
3498 * occur as direct kids of the same block with no forward refs to x.
3500 if (!(dn
->pn_dflags
& (PND_INITIALIZED
| PND_CONST
| PND_PLACEHOLDER
)) &&
3501 dn
->isBlockChild() &&
3502 pn
->isBlockChild() &&
3503 dn
->pn_blockid
== pn
->pn_blockid
&&
3504 dn
->pn_pos
.end
<= pn
->pn_pos
.begin
&&
3505 dn
->dn_uses
== pn
) {
3506 dflag
= PND_INITIALIZED
;
3509 dn
->pn_dflags
|= dflag
;
3511 if (dn
->frameLevel() != tc
->staticLevel
) {
3513 * The above condition takes advantage of the all-ones nature of
3514 * FREE_UPVAR_COOKIE, and the reserved level FREE_STATIC_LEVEL.
3515 * We make a stronger assertion by excluding FREE_UPVAR_COOKIE.
3517 JS_ASSERT_IF(dn
->pn_cookie
!= FREE_UPVAR_COOKIE
,
3518 dn
->frameLevel() < tc
->staticLevel
);
3519 tc
->flags
|= TCF_FUN_SETS_OUTER_NAME
;
3523 pn
->pn_dflags
|= dflag
;
3525 if (pn
->pn_atom
== cx
->runtime
->atomState
.argumentsAtom
)
3526 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
3529 #if JS_HAS_DESTRUCTURING
3532 BindDestructuringVar(JSContext
*cx
, BindData
*data
, JSParseNode
*pn
,
3538 * Destructuring is a form of assignment, so just as for an initialized
3539 * simple variable, we must check for assignment to 'arguments' and flag
3540 * the enclosing function (if any) as heavyweight.
3542 JS_ASSERT(pn
->pn_type
== TOK_NAME
);
3544 if (atom
== cx
->runtime
->atomState
.argumentsAtom
)
3545 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
3548 if (!data
->binder(cx
, data
, atom
, tc
))
3552 * Select the appropriate name-setting opcode, respecting eager selection
3553 * done by the data->binder function.
3555 if (pn
->pn_dflags
& PND_BOUND
) {
3556 pn
->pn_op
= (pn
->pn_op
== JSOP_ARGUMENTS
)
3558 : (pn
->pn_dflags
& PND_GVAR
)
3562 pn
->pn_op
= (data
->op
== JSOP_DEFCONST
)
3567 if (data
->op
== JSOP_DEFCONST
)
3568 pn
->pn_dflags
|= PND_CONST
;
3570 NoteLValue(cx
, pn
, tc
, PND_INITIALIZED
);
3575 * Here, we are destructuring {... P: Q, ...} = R, where P is any id, Q is any
3576 * LHS expression except a destructuring initialiser, and R is on the stack.
3577 * Because R is already evaluated, the usual LHS-specialized bytecodes won't
3578 * work. After pushing R[P] we need to evaluate Q's "reference base" QB and
3579 * then push its property name QN. At this point the stack looks like
3581 * [... R, R[P], QB, QN]
3583 * We need to set QB[QN] = R[P]. This is a job for JSOP_ENUMELEM, which takes
3584 * its operands with left-hand side above right-hand side:
3586 * [rval, lval, xval]
3588 * and pops all three values, setting lval[xval] = rval. But we cannot select
3589 * JSOP_ENUMELEM yet, because the LHS may turn out to be an arg or local var,
3590 * which can be optimized further. So we select JSOP_SETNAME.
3593 BindDestructuringLHS(JSContext
*cx
, JSParseNode
*pn
, JSTreeContext
*tc
)
3595 switch (pn
->pn_type
) {
3597 NoteLValue(cx
, pn
, tc
);
3602 pn
->pn_op
= JSOP_SETNAME
;
3606 if (!MakeSetCall(cx
, pn
, tc
, JSMSG_BAD_LEFTSIDE_OF_ASS
))
3610 #if JS_HAS_XML_SUPPORT
3612 if (pn
->pn_op
== JSOP_XMLNAME
) {
3613 pn
->pn_op
= JSOP_BINDXMLNAME
;
3620 ReportCompileErrorNumber(cx
, TS(tc
->parser
), pn
,
3621 JSREPORT_ERROR
, JSMSG_BAD_LEFTSIDE_OF_ASS
);
3628 typedef struct FindPropValData
{
3629 uint32 numvars
; /* # of destructuring vars in left side */
3630 uint32 maxstep
; /* max # of steps searching right side */
3631 JSDHashTable table
; /* hash table for O(1) right side search */
3634 typedef struct FindPropValEntry
{
3635 JSDHashEntryHdr hdr
;
3640 #define ASSERT_VALID_PROPERTY_KEY(pnkey) \
3641 JS_ASSERT(((pnkey)->pn_arity == PN_NULLARY && \
3642 ((pnkey)->pn_type == TOK_NUMBER || \
3643 (pnkey)->pn_type == TOK_STRING || \
3644 (pnkey)->pn_type == TOK_NAME)) || \
3645 ((pnkey)->pn_arity == PN_NAME && (pnkey)->pn_type == TOK_NAME))
3647 static JSDHashNumber
3648 HashFindPropValKey(JSDHashTable
*table
, const void *key
)
3650 const JSParseNode
*pnkey
= (const JSParseNode
*)key
;
3652 ASSERT_VALID_PROPERTY_KEY(pnkey
);
3653 return (pnkey
->pn_type
== TOK_NUMBER
)
3654 ? (JSDHashNumber
) JS_HASH_DOUBLE(pnkey
->pn_dval
)
3655 : ATOM_HASH(pnkey
->pn_atom
);
3659 MatchFindPropValEntry(JSDHashTable
*table
,
3660 const JSDHashEntryHdr
*entry
,
3663 const FindPropValEntry
*fpve
= (const FindPropValEntry
*)entry
;
3664 const JSParseNode
*pnkey
= (const JSParseNode
*)key
;
3666 ASSERT_VALID_PROPERTY_KEY(pnkey
);
3667 return pnkey
->pn_type
== fpve
->pnkey
->pn_type
&&
3668 ((pnkey
->pn_type
== TOK_NUMBER
)
3669 ? pnkey
->pn_dval
== fpve
->pnkey
->pn_dval
3670 : pnkey
->pn_atom
== fpve
->pnkey
->pn_atom
);
3673 static const JSDHashTableOps FindPropValOps
= {
3677 MatchFindPropValEntry
,
3678 JS_DHashMoveEntryStub
,
3679 JS_DHashClearEntryStub
,
3680 JS_DHashFinalizeStub
,
3684 #define STEP_HASH_THRESHOLD 10
3685 #define BIG_DESTRUCTURING 5
3686 #define BIG_OBJECT_INIT 20
3688 static JSParseNode
*
3689 FindPropertyValue(JSParseNode
*pn
, JSParseNode
*pnid
, FindPropValData
*data
)
3691 FindPropValEntry
*entry
;
3692 JSParseNode
*pnhit
, *pnhead
, *pnprop
, *pnkey
;
3695 /* If we have a hash table, use it as the sole source of truth. */
3696 if (data
->table
.ops
) {
3697 entry
= (FindPropValEntry
*)
3698 JS_DHashTableOperate(&data
->table
, pnid
, JS_DHASH_LOOKUP
);
3699 return JS_DHASH_ENTRY_IS_BUSY(&entry
->hdr
) ? entry
->pnval
: NULL
;
3702 /* If pn is not an object initialiser node, we can't do anything here. */
3703 if (pn
->pn_type
!= TOK_RC
)
3707 * We must search all the way through pn's list, to handle the case of an
3708 * id duplicated for two or more property initialisers.
3712 ASSERT_VALID_PROPERTY_KEY(pnid
);
3713 pnhead
= pn
->pn_head
;
3714 if (pnid
->pn_type
== TOK_NUMBER
) {
3715 for (pnprop
= pnhead
; pnprop
; pnprop
= pnprop
->pn_next
) {
3716 JS_ASSERT(pnprop
->pn_type
== TOK_COLON
);
3717 if (pnprop
->pn_op
== JSOP_NOP
) {
3718 pnkey
= pnprop
->pn_left
;
3719 ASSERT_VALID_PROPERTY_KEY(pnkey
);
3720 if (pnkey
->pn_type
== TOK_NUMBER
&&
3721 pnkey
->pn_dval
== pnid
->pn_dval
) {
3728 for (pnprop
= pnhead
; pnprop
; pnprop
= pnprop
->pn_next
) {
3729 JS_ASSERT(pnprop
->pn_type
== TOK_COLON
);
3730 if (pnprop
->pn_op
== JSOP_NOP
) {
3731 pnkey
= pnprop
->pn_left
;
3732 ASSERT_VALID_PROPERTY_KEY(pnkey
);
3733 if (pnkey
->pn_type
== pnid
->pn_type
&&
3734 pnkey
->pn_atom
== pnid
->pn_atom
) {
3744 /* Hit via full search -- see whether it's time to create the hash table. */
3745 JS_ASSERT(!data
->table
.ops
);
3746 if (step
> data
->maxstep
) {
3747 data
->maxstep
= step
;
3748 if (step
>= STEP_HASH_THRESHOLD
&&
3749 data
->numvars
>= BIG_DESTRUCTURING
&&
3750 pn
->pn_count
>= BIG_OBJECT_INIT
&&
3751 JS_DHashTableInit(&data
->table
, &FindPropValOps
, pn
,
3752 sizeof(FindPropValEntry
),
3753 JS_DHASH_DEFAULT_CAPACITY(pn
->pn_count
)))
3755 for (pn
= pnhead
; pn
; pn
= pn
->pn_next
) {
3756 JS_ASSERT(pnprop
->pn_type
== TOK_COLON
);
3757 ASSERT_VALID_PROPERTY_KEY(pn
->pn_left
);
3758 entry
= (FindPropValEntry
*)
3759 JS_DHashTableOperate(&data
->table
, pn
->pn_left
,
3761 entry
->pnval
= pn
->pn_right
;
3765 return pnhit
->pn_right
;
3769 * Destructuring patterns can appear in two kinds of contexts:
3771 * - assignment-like: assignment expressions and |for| loop heads. In
3772 * these cases, the patterns' property value positions can be
3773 * arbitrary lvalue expressions; the destructuring is just a fancy
3776 * - declaration-like: |var| and |let| declarations, functions' formal
3777 * parameter lists, |catch| clauses, and comprehension tails. In
3778 * these cases, the patterns' property value positions must be
3779 * simple names; the destructuring defines them as new variables.
3781 * In both cases, other code parses the pattern as an arbitrary
3782 * primaryExpr, and then, here in CheckDestructuring, verify that the
3783 * tree is a valid destructuring expression.
3785 * In assignment-like contexts, we parse the pattern with the
3786 * TCF_DECL_DESTRUCTURING flag clear, so the lvalue expressions in the
3787 * pattern are parsed normally. primaryExpr links variable references
3788 * into the appropriate use chains; creates placeholder definitions;
3789 * and so on. CheckDestructuring is called with |data| NULL (since we
3790 * won't be binding any new names), and we specialize lvalues as
3791 * appropriate. If right is NULL, we just check for well-formed lvalues.
3793 * In declaration-like contexts, the normal variable reference
3794 * processing would just be an obstruction, because we're going to
3795 * define the names that appear in the property value positions as new
3796 * variables anyway. In this case, we parse the pattern with
3797 * TCF_DECL_DESTRUCTURING set, which directs primaryExpr to leave
3798 * whatever name nodes it creates unconnected. Then, here in
3799 * CheckDestructuring, we require the pattern's property value
3800 * positions to be simple names, and define them as appropriate to the
3801 * context. For these calls, |data| points to the right sort of
3804 * See also UndominateInitializers, immediately below. If you change
3805 * either of these functions, you might have to change the other to
3809 CheckDestructuring(JSContext
*cx
, BindData
*data
,
3810 JSParseNode
*left
, JSParseNode
*right
,
3814 FindPropValData fpvd
;
3815 JSParseNode
*lhs
, *rhs
, *pn
, *pn2
;
3817 if (left
->pn_type
== TOK_ARRAYCOMP
) {
3818 ReportCompileErrorNumber(cx
, TS(tc
->parser
), left
, JSREPORT_ERROR
,
3819 JSMSG_ARRAY_COMP_LEFTSIDE
);
3823 #if JS_HAS_DESTRUCTURING_SHORTHAND
3824 if (right
&& right
->pn_arity
== PN_LIST
&& (right
->pn_xflags
& PNX_DESTRUCT
)) {
3825 ReportCompileErrorNumber(cx
, TS(tc
->parser
), right
, JSREPORT_ERROR
,
3826 JSMSG_BAD_OBJECT_INIT
);
3831 fpvd
.table
.ops
= NULL
;
3832 lhs
= left
->pn_head
;
3833 if (left
->pn_type
== TOK_RB
) {
3834 rhs
= (right
&& right
->pn_type
== left
->pn_type
)
3839 pn
= lhs
, pn2
= rhs
;
3841 /* Nullary comma is an elision; binary comma is an expression.*/
3842 if (pn
->pn_type
!= TOK_COMMA
|| pn
->pn_arity
!= PN_NULLARY
) {
3843 if (pn
->pn_type
== TOK_RB
|| pn
->pn_type
== TOK_RC
) {
3844 ok
= CheckDestructuring(cx
, data
, pn
, pn2
, tc
);
3847 if (pn
->pn_type
!= TOK_NAME
)
3850 ok
= BindDestructuringVar(cx
, data
, pn
, tc
);
3852 ok
= BindDestructuringLHS(cx
, pn
, tc
);
3864 JS_ASSERT(left
->pn_type
== TOK_RC
);
3865 fpvd
.numvars
= left
->pn_count
;
3870 JS_ASSERT(lhs
->pn_type
== TOK_COLON
);
3873 if (pn
->pn_type
== TOK_RB
|| pn
->pn_type
== TOK_RC
) {
3875 rhs
= FindPropertyValue(right
, lhs
->pn_left
, &fpvd
);
3876 ok
= CheckDestructuring(cx
, data
, pn
, rhs
, tc
);
3878 if (pn
->pn_type
!= TOK_NAME
)
3881 ok
= BindDestructuringVar(cx
, data
, pn
, tc
);
3883 ok
= BindDestructuringLHS(cx
, pn
, tc
);
3893 * The catch/finally handler implementation in the interpreter assumes
3894 * that any operation that introduces a new scope (like a "let" or "with"
3895 * block) increases the stack depth. This way, it is possible to restore
3896 * the scope chain based on stack depth of the handler alone. "let" with
3897 * an empty destructuring pattern like in
3901 * would violate this assumption as the there would be no let locals to
3902 * store on the stack. To satisfy it we add an empty property to such
3903 * blocks so that OBJ_BLOCK_COUNT(cx, blockObj), which gives the number of
3904 * slots, would be always positive.
3906 * Note that we add such a property even if the block has locals due to
3907 * later let declarations in it. We optimize for code simplicity here,
3908 * not the fastest runtime performance with empty [] or {}.
3911 data
->binder
== BindLet
&&
3912 OBJ_BLOCK_COUNT(cx
, tc
->blockChain
) == 0) {
3913 ok
= !!js_DefineNativeProperty(cx
, tc
->blockChain
,
3914 ATOM_TO_JSID(cx
->runtime
->
3915 atomState
.emptyAtom
),
3916 JSVAL_VOID
, NULL
, NULL
,
3920 JSScopeProperty::HAS_SHORTID
, 0, NULL
);
3929 JS_DHashTableFinish(&fpvd
.table
);
3933 ReportCompileErrorNumber(cx
, TS(tc
->parser
), pn
, JSREPORT_ERROR
,
3934 JSMSG_NO_VARIABLE_NAME
);
3940 * This is a greatly pared down version of CheckDestructuring that extends the
3941 * pn_pos.end source coordinate of each name in a destructuring binding such as
3943 * var [x, y] = [function () y, 42];
3945 * to cover its corresponding initializer, so that the initialized binding does
3946 * not appear to dominate any closures in its initializer. See bug 496134.
3948 * The quick-and-dirty dominance computation in Parser::setFunctionKinds is not
3949 * very precise. With one-pass SSA construction from structured source code
3950 * (see "Single-Pass Generation of Static Single Assignment Form for Structured
3951 * Languages", Brandis and Mössenböck), we could do much better.
3953 * See CheckDestructuring, immediately above. If you change either of these
3954 * functions, you might have to change the other to match.
3957 UndominateInitializers(JSParseNode
*left
, JSParseNode
*right
, JSTreeContext
*tc
)
3959 FindPropValData fpvd
;
3960 JSParseNode
*lhs
, *rhs
;
3962 JS_ASSERT(left
->pn_type
!= TOK_ARRAYCOMP
);
3965 #if JS_HAS_DESTRUCTURING_SHORTHAND
3966 if (right
->pn_arity
== PN_LIST
&& (right
->pn_xflags
& PNX_DESTRUCT
)) {
3967 ReportCompileErrorNumber(tc
->parser
->context
, TS(tc
->parser
), right
, JSREPORT_ERROR
,
3968 JSMSG_BAD_OBJECT_INIT
);
3973 if (right
->pn_type
!= left
->pn_type
)
3976 fpvd
.table
.ops
= NULL
;
3977 lhs
= left
->pn_head
;
3978 if (left
->pn_type
== TOK_RB
) {
3979 rhs
= right
->pn_head
;
3981 while (lhs
&& rhs
) {
3982 /* Nullary comma is an elision; binary comma is an expression.*/
3983 if (lhs
->pn_type
!= TOK_COMMA
|| lhs
->pn_arity
!= PN_NULLARY
) {
3984 if (lhs
->pn_type
== TOK_RB
|| lhs
->pn_type
== TOK_RC
) {
3985 if (!UndominateInitializers(lhs
, rhs
, tc
))
3988 lhs
->pn_pos
.end
= rhs
->pn_pos
.end
;
3996 JS_ASSERT(left
->pn_type
== TOK_RC
);
3997 fpvd
.numvars
= left
->pn_count
;
4001 JS_ASSERT(lhs
->pn_type
== TOK_COLON
);
4002 JSParseNode
*pn
= lhs
->pn_right
;
4004 rhs
= FindPropertyValue(right
, lhs
->pn_left
, &fpvd
);
4005 if (pn
->pn_type
== TOK_RB
|| pn
->pn_type
== TOK_RC
) {
4006 if (rhs
&& !UndominateInitializers(pn
, rhs
, tc
))
4010 pn
->pn_pos
.end
= rhs
->pn_pos
.end
;
4020 Parser::destructuringExpr(BindData
*data
, TokenKind tt
)
4024 tc
->flags
|= TCF_DECL_DESTRUCTURING
;
4025 pn
= primaryExpr(tt
, JS_FALSE
);
4026 tc
->flags
&= ~TCF_DECL_DESTRUCTURING
;
4029 if (!CheckDestructuring(context
, data
, pn
, NULL
, tc
))
4035 * Currently used only #if JS_HAS_DESTRUCTURING, in Statement's TOK_FOR case.
4036 * This function assumes the cloned tree is for use in the same statement and
4037 * binding context as the original tree.
4039 static JSParseNode
*
4040 CloneParseTree(JSParseNode
*opn
, JSTreeContext
*tc
)
4042 JSParseNode
*pn
, *pn2
, *opn2
;
4044 pn
= NewOrRecycledNode(tc
);
4047 pn
->pn_type
= opn
->pn_type
;
4048 pn
->pn_pos
= opn
->pn_pos
;
4049 pn
->pn_op
= opn
->pn_op
;
4050 pn
->pn_used
= opn
->pn_used
;
4051 pn
->pn_defn
= opn
->pn_defn
;
4052 pn
->pn_arity
= opn
->pn_arity
;
4053 pn
->pn_parens
= opn
->pn_parens
;
4055 switch (pn
->pn_arity
) {
4056 #define NULLCHECK(e) JS_BEGIN_MACRO if (!(e)) return NULL; JS_END_MACRO
4059 NULLCHECK(pn
->pn_funbox
=
4060 tc
->parser
->newFunctionBox(opn
->pn_funbox
->object
, pn
, tc
));
4061 NULLCHECK(pn
->pn_body
= CloneParseTree(opn
->pn_body
, tc
));
4062 pn
->pn_cookie
= opn
->pn_cookie
;
4063 pn
->pn_dflags
= opn
->pn_dflags
;
4064 pn
->pn_blockid
= opn
->pn_blockid
;
4069 for (opn2
= opn
->pn_head
; opn2
; opn2
= opn2
->pn_next
) {
4070 NULLCHECK(pn2
= CloneParseTree(opn2
, tc
));
4073 pn
->pn_xflags
= opn
->pn_xflags
;
4077 NULLCHECK(pn
->pn_kid1
= CloneParseTree(opn
->pn_kid1
, tc
));
4078 NULLCHECK(pn
->pn_kid2
= CloneParseTree(opn
->pn_kid2
, tc
));
4079 NULLCHECK(pn
->pn_kid3
= CloneParseTree(opn
->pn_kid3
, tc
));
4083 NULLCHECK(pn
->pn_left
= CloneParseTree(opn
->pn_left
, tc
));
4084 if (opn
->pn_right
!= opn
->pn_left
)
4085 NULLCHECK(pn
->pn_right
= CloneParseTree(opn
->pn_right
, tc
));
4087 pn
->pn_right
= pn
->pn_left
;
4088 pn
->pn_val
= opn
->pn_val
;
4089 pn
->pn_iflags
= opn
->pn_iflags
;
4093 NULLCHECK(pn
->pn_kid
= CloneParseTree(opn
->pn_kid
, tc
));
4094 pn
->pn_num
= opn
->pn_num
;
4095 pn
->pn_hidden
= opn
->pn_hidden
;
4099 // PN_NAME could mean several arms in pn_u, so copy the whole thing.
4100 pn
->pn_u
= opn
->pn_u
;
4103 * The old name is a use of its pn_lexdef. Make the clone also be a
4104 * use of that definition.
4106 JSDefinition
*dn
= pn
->pn_lexdef
;
4108 pn
->pn_link
= dn
->dn_uses
;
4110 } else if (opn
->pn_expr
) {
4111 NULLCHECK(pn
->pn_expr
= CloneParseTree(opn
->pn_expr
, tc
));
4114 * If the old name is a definition, the new one has pn_defn set.
4115 * Make the old name a use of the new node.
4118 opn
->pn_defn
= false;
4119 LinkUseToDef(opn
, (JSDefinition
*) pn
, tc
);
4125 pn
->pn_names
= opn
->pn_names
;
4126 NULLCHECK(pn
->pn_tree
= CloneParseTree(opn
->pn_tree
, tc
));
4130 // Even PN_NULLARY may have data (apair for E4X -- what a botch).
4131 pn
->pn_u
= opn
->pn_u
;
4139 #endif /* JS_HAS_DESTRUCTURING */
4141 extern const char js_with_statement_str
[];
4143 static JSParseNode
*
4144 ContainsStmt(JSParseNode
*pn
, TokenKind tt
)
4146 JSParseNode
*pn2
, *pnt
;
4150 if (PN_TYPE(pn
) == tt
)
4152 switch (pn
->pn_arity
) {
4154 for (pn2
= pn
->pn_head
; pn2
; pn2
= pn2
->pn_next
) {
4155 pnt
= ContainsStmt(pn2
, tt
);
4161 pnt
= ContainsStmt(pn
->pn_kid1
, tt
);
4164 pnt
= ContainsStmt(pn
->pn_kid2
, tt
);
4167 return ContainsStmt(pn
->pn_kid3
, tt
);
4170 * Limit recursion if pn is a binary expression, which can't contain a
4173 if (pn
->pn_op
!= JSOP_NOP
)
4175 pnt
= ContainsStmt(pn
->pn_left
, tt
);
4178 return ContainsStmt(pn
->pn_right
, tt
);
4180 if (pn
->pn_op
!= JSOP_NOP
)
4182 return ContainsStmt(pn
->pn_kid
, tt
);
4184 return ContainsStmt(pn
->maybeExpr(), tt
);
4186 return ContainsStmt(pn
->pn_tree
, tt
);
4193 Parser::returnOrYield(bool useAssignExpr
)
4196 JSParseNode
*pn
, *pn2
;
4198 tt
= tokenStream
.currentToken().type
;
4199 if (tt
== TOK_RETURN
&& !tc
->inFunction()) {
4200 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_RETURN_OR_YIELD
, js_return_str
);
4204 pn
= UnaryNode::create(tc
);
4208 #if JS_HAS_GENERATORS
4209 if (tt
== TOK_YIELD
)
4210 tc
->flags
|= TCF_FUN_IS_GENERATOR
;
4213 /* This is ugly, but we don't want to require a semicolon. */
4214 tt2
= tokenStream
.peekTokenSameLine(TSF_OPERAND
);
4215 if (tt2
== TOK_ERROR
)
4218 if (tt2
!= TOK_EOF
&& tt2
!= TOK_EOL
&& tt2
!= TOK_SEMI
&& tt2
!= TOK_RC
4219 #if JS_HAS_GENERATORS
4220 && (tt
!= TOK_YIELD
||
4221 (tt2
!= tt
&& tt2
!= TOK_RB
&& tt2
!= TOK_RP
&&
4222 tt2
!= TOK_COLON
&& tt2
!= TOK_COMMA
))
4225 pn2
= useAssignExpr
? assignExpr() : expr();
4228 #if JS_HAS_GENERATORS
4229 if (tt
== TOK_RETURN
)
4231 tc
->flags
|= TCF_RETURN_EXPR
;
4232 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
4235 #if JS_HAS_GENERATORS
4236 if (tt
== TOK_RETURN
)
4238 tc
->flags
|= TCF_RETURN_VOID
;
4241 if ((~tc
->flags
& (TCF_RETURN_EXPR
| TCF_FUN_IS_GENERATOR
)) == 0) {
4242 /* As in Python (see PEP-255), disallow return v; in generators. */
4243 ReportBadReturn(context
, tc
, JSREPORT_ERROR
,
4244 JSMSG_BAD_GENERATOR_RETURN
,
4245 JSMSG_BAD_ANON_GENERATOR_RETURN
);
4249 if (JS_HAS_STRICT_OPTION(context
) &&
4250 (~tc
->flags
& (TCF_RETURN_EXPR
| TCF_RETURN_VOID
)) == 0 &&
4251 !ReportBadReturn(context
, tc
, JSREPORT_WARNING
| JSREPORT_STRICT
,
4252 JSMSG_NO_RETURN_VALUE
,
4253 JSMSG_ANON_NO_RETURN_VALUE
)) {
4260 static JSParseNode
*
4261 PushLexicalScope(JSContext
*cx
, TokenStream
*ts
, JSTreeContext
*tc
,
4266 JSObjectBox
*blockbox
;
4268 pn
= LexicalScopeNode::create(tc
);
4272 obj
= js_NewBlockObject(cx
);
4276 blockbox
= tc
->parser
->newObjectBox(obj
);
4280 js_PushBlockScope(tc
, stmt
, obj
, -1);
4281 pn
->pn_type
= TOK_LEXICALSCOPE
;
4282 pn
->pn_op
= JSOP_LEAVEBLOCK
;
4283 pn
->pn_objbox
= blockbox
;
4284 pn
->pn_cookie
= FREE_UPVAR_COOKIE
;
4286 if (!GenerateBlockId(tc
, stmt
->blockid
))
4288 pn
->pn_blockid
= stmt
->blockid
;
4292 #if JS_HAS_BLOCK_SCOPE
4295 Parser::letBlock(JSBool statement
)
4297 JSParseNode
*pn
, *pnblock
, *pnlet
;
4298 JSStmtInfo stmtInfo
;
4300 JS_ASSERT(tokenStream
.currentToken().type
== TOK_LET
);
4302 /* Create the let binary node. */
4303 pnlet
= BinaryNode::create(tc
);
4307 MUST_MATCH_TOKEN(TOK_LP
, JSMSG_PAREN_BEFORE_LET
);
4309 /* This is a let block or expression of the form: let (a, b, c) .... */
4310 pnblock
= PushLexicalScope(context
, &tokenStream
, tc
, &stmtInfo
);
4314 pn
->pn_expr
= pnlet
;
4316 pnlet
->pn_left
= variables(true);
4317 if (!pnlet
->pn_left
)
4319 pnlet
->pn_left
->pn_xflags
= PNX_POPVAR
;
4321 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_AFTER_LET
);
4323 if (statement
&& !tokenStream
.matchToken(TOK_LC
, TSF_OPERAND
)) {
4325 * If this is really an expression in let statement guise, then we
4326 * need to wrap the TOK_LET node in a TOK_SEMI node so that we pop
4327 * the return value of the expression.
4329 pn
= UnaryNode::create(tc
);
4332 pn
->pn_type
= TOK_SEMI
;
4334 pn
->pn_kid
= pnblock
;
4336 statement
= JS_FALSE
;
4340 pnlet
->pn_right
= statements();
4341 if (!pnlet
->pn_right
)
4343 MUST_MATCH_TOKEN(TOK_RC
, JSMSG_CURLY_AFTER_LET
);
4346 * Change pnblock's opcode to the variant that propagates the last
4347 * result down after popping the block, and clear statement.
4349 pnblock
->pn_op
= JSOP_LEAVEBLOCKEXPR
;
4350 pnlet
->pn_right
= assignExpr();
4351 if (!pnlet
->pn_right
)
4359 #endif /* JS_HAS_BLOCK_SCOPE */
4362 PushBlocklikeStatement(JSStmtInfo
*stmt
, JSStmtType type
, JSTreeContext
*tc
)
4364 js_PushStatement(tc
, stmt
, type
, -1);
4365 return GenerateBlockId(tc
, stmt
->blockid
);
4368 static JSParseNode
*
4369 NewBindingNode(JSAtom
*atom
, JSTreeContext
*tc
, bool let
= false)
4371 JSParseNode
*pn
= NULL
;
4373 JSAtomListElement
*ale
= tc
->decls
.lookup(atom
);
4376 JS_ASSERT(!pn
->isPlaceholder());
4378 ale
= tc
->lexdeps
.lookup(atom
);
4381 JS_ASSERT(pn
->isPlaceholder());
4386 JS_ASSERT(pn
->pn_defn
);
4389 * A let binding at top level becomes a var before we get here, so if
4390 * pn and tc have the same blockid then that id must not be the bodyid.
4391 * If pn is a forward placeholder definition from the same or a higher
4392 * block then we claim it.
4394 JS_ASSERT_IF(let
&& pn
->pn_blockid
== tc
->blockid(),
4395 pn
->pn_blockid
!= tc
->bodyid
);
4397 if (pn
->isPlaceholder() && pn
->pn_blockid
>= (let
? tc
->blockid() : tc
->bodyid
)) {
4399 pn
->pn_blockid
= tc
->blockid();
4401 tc
->lexdeps
.remove(tc
->parser
, atom
);
4406 /* Make a new node for this declarator name (or destructuring pattern). */
4407 pn
= NameNode::create(atom
, tc
);
4413 #if JS_HAS_BLOCK_SCOPE
4415 RebindLets(JSParseNode
*pn
, JSTreeContext
*tc
)
4420 switch (pn
->pn_arity
) {
4422 for (JSParseNode
*pn2
= pn
->pn_head
; pn2
; pn2
= pn2
->pn_next
)
4423 RebindLets(pn2
, tc
);
4427 RebindLets(pn
->pn_kid1
, tc
);
4428 RebindLets(pn
->pn_kid2
, tc
);
4429 RebindLets(pn
->pn_kid3
, tc
);
4433 RebindLets(pn
->pn_left
, tc
);
4434 RebindLets(pn
->pn_right
, tc
);
4438 RebindLets(pn
->pn_kid
, tc
);
4442 RebindLets(pn
->pn_body
, tc
);
4446 RebindLets(pn
->maybeExpr(), tc
);
4449 JS_ASSERT(pn
->pn_blockid
> tc
->topStmt
->blockid
);
4450 } else if (pn
->pn_used
) {
4451 if (pn
->pn_lexdef
->pn_blockid
== tc
->topStmt
->blockid
) {
4454 JSAtomListElement
*ale
= tc
->decls
.lookup(pn
->pn_atom
);
4456 while ((ale
= ALE_NEXT(ale
)) != NULL
) {
4457 if (ALE_ATOM(ale
) == pn
->pn_atom
) {
4458 LinkUseToDef(pn
, ALE_DEFN(ale
), tc
);
4464 ale
= tc
->lexdeps
.lookup(pn
->pn_atom
);
4466 ale
= MakePlaceholder(pn
, tc
);
4470 JSDefinition
*dn
= ALE_DEFN(ale
);
4471 dn
->pn_type
= TOK_NAME
;
4472 dn
->pn_op
= JSOP_NOP
;
4474 LinkUseToDef(pn
, ALE_DEFN(ale
), tc
);
4480 RebindLets(pn
->pn_tree
, tc
);
4486 #endif /* JS_HAS_BLOCK_SCOPE */
4492 JSParseNode
*pn
, *pn1
, *pn2
, *pn3
, *pn4
;
4493 JSStmtInfo stmtInfo
, *stmt
, *stmt2
;
4496 JS_CHECK_RECURSION(context
, return NULL
);
4498 tt
= tokenStream
.getToken(TSF_OPERAND
);
4502 #if JS_HAS_XML_SUPPORT
4503 tt
= tokenStream
.peekToken(TSF_KEYWORD_IS_NAME
);
4504 if (tt
== TOK_DBLCOLON
)
4507 return functionStmt();
4510 /* An IF node has three kids: condition, then, and optional else. */
4511 pn
= TernaryNode::create(tc
);
4517 js_PushStatement(tc
, &stmtInfo
, STMT_IF
, -1);
4521 if (tokenStream
.matchToken(TOK_ELSE
, TSF_OPERAND
)) {
4522 stmtInfo
.type
= STMT_ELSE
;
4526 pn
->pn_pos
.end
= pn3
->pn_pos
.end
;
4529 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
4539 JSParseNode
*pn5
, *saveBlock
;
4540 JSBool seenDefault
= JS_FALSE
;
4542 pn
= BinaryNode::create(tc
);
4545 MUST_MATCH_TOKEN(TOK_LP
, JSMSG_PAREN_BEFORE_SWITCH
);
4547 /* pn1 points to the switch's discriminant. */
4548 pn1
= parenExpr(NULL
, NULL
);
4552 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_AFTER_SWITCH
);
4553 MUST_MATCH_TOKEN(TOK_LC
, JSMSG_CURLY_BEFORE_SWITCH
);
4556 * NB: we must push stmtInfo before calling GenerateBlockIdForStmtNode
4557 * because that function states tc->topStmt->blockid.
4559 js_PushStatement(tc
, &stmtInfo
, STMT_SWITCH
, -1);
4561 /* pn2 is a list of case nodes. The default case has pn_left == NULL */
4562 pn2
= ListNode::create(tc
);
4566 if (!GenerateBlockIdForStmtNode(pn2
, tc
))
4568 saveBlock
= tc
->blockNode
;
4569 tc
->blockNode
= pn2
;
4571 while ((tt
= tokenStream
.getToken()) != TOK_RC
) {
4575 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_TOO_MANY_DEFAULTS
);
4578 seenDefault
= JS_TRUE
;
4582 pn3
= BinaryNode::create(tc
);
4585 if (tt
== TOK_CASE
) {
4586 pn3
->pn_left
= expr();
4591 if (pn2
->pn_count
== JS_BIT(16)) {
4592 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_TOO_MANY_CASES
);
4601 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_SWITCH
);
4604 MUST_MATCH_TOKEN(TOK_COLON
, JSMSG_COLON_AFTER_CASE
);
4606 pn4
= ListNode::create(tc
);
4609 pn4
->pn_type
= TOK_LC
;
4611 while ((tt
= tokenStream
.peekToken(TSF_OPERAND
)) != TOK_RC
&&
4612 tt
!= TOK_CASE
&& tt
!= TOK_DEFAULT
) {
4613 if (tt
== TOK_ERROR
)
4618 pn4
->pn_pos
.end
= pn5
->pn_pos
.end
;
4622 /* Fix the PN_LIST so it doesn't begin at the TOK_COLON. */
4624 pn4
->pn_pos
.begin
= pn4
->pn_head
->pn_pos
.begin
;
4625 pn3
->pn_pos
.end
= pn4
->pn_pos
.end
;
4626 pn3
->pn_right
= pn4
;
4630 * Handle the case where there was a let declaration in any case in
4631 * the switch body, but not within an inner block. If it replaced
4632 * tc->blockNode with a new block node then we must refresh pn2 and
4633 * then restore tc->blockNode.
4635 if (tc
->blockNode
!= pn2
)
4636 pn2
= tc
->blockNode
;
4637 tc
->blockNode
= saveBlock
;
4640 pn
->pn_pos
.end
= pn2
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
4647 pn
= BinaryNode::create(tc
);
4650 js_PushStatement(tc
, &stmtInfo
, STMT_WHILE_LOOP
, -1);
4659 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
4664 pn
= BinaryNode::create(tc
);
4667 js_PushStatement(tc
, &stmtInfo
, STMT_DO_LOOP
, -1);
4672 MUST_MATCH_TOKEN(TOK_WHILE
, JSMSG_WHILE_AFTER_DO
);
4677 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
4679 if (JSVERSION_NUMBER(context
) != JSVERSION_ECMA_3
) {
4681 * All legacy and extended versions must do automatic semicolon
4682 * insertion after do-while. See the testcase and discussion in
4683 * http://bugzilla.mozilla.org/show_bug.cgi?id=238945.
4685 (void) tokenStream
.matchToken(TOK_SEMI
);
4692 JSParseNode
*pnseq
= NULL
;
4693 #if JS_HAS_BLOCK_SCOPE
4694 JSParseNode
*pnlet
= NULL
;
4695 JSStmtInfo blockInfo
;
4698 /* A FOR node is binary, left is loop control and right is the body. */
4699 pn
= BinaryNode::create(tc
);
4702 js_PushStatement(tc
, &stmtInfo
, STMT_FOR_LOOP
, -1);
4704 pn
->pn_op
= JSOP_ITER
;
4706 if (tokenStream
.matchToken(TOK_NAME
)) {
4707 if (tokenStream
.currentToken().t_atom
== context
->runtime
->atomState
.eachAtom
)
4708 pn
->pn_iflags
= JSITER_FOREACH
;
4710 tokenStream
.ungetToken();
4713 MUST_MATCH_TOKEN(TOK_LP
, JSMSG_PAREN_AFTER_FOR
);
4714 tt
= tokenStream
.peekToken(TSF_OPERAND
);
4716 #if JS_HAS_BLOCK_SCOPE
4720 if (tt
== TOK_SEMI
) {
4721 if (pn
->pn_iflags
& JSITER_FOREACH
)
4724 /* No initializer -- set first kid of left sub-node to null. */
4728 * Set pn1 to a var list or an initializing expression.
4730 * Set the TCF_IN_FOR_INIT flag during parsing of the first clause
4731 * of the for statement. This flag will be used by the RelExpr
4732 * production; if it is set, then the 'in' keyword will not be
4733 * recognized as an operator, leaving it available to be parsed as
4734 * part of a for/in loop.
4736 * A side effect of this restriction is that (unparenthesized)
4737 * expressions involving an 'in' operator are illegal in the init
4738 * clause of an ordinary for loop.
4740 tc
->flags
|= TCF_IN_FOR_INIT
;
4741 if (tt
== TOK_VAR
) {
4742 (void) tokenStream
.getToken();
4743 pn1
= variables(false);
4744 #if JS_HAS_BLOCK_SCOPE
4745 } else if (tt
== TOK_LET
) {
4747 (void) tokenStream
.getToken();
4748 if (tokenStream
.peekToken() == TOK_LP
) {
4749 pn1
= letBlock(JS_FALSE
);
4750 tt
= TOK_LEXICALSCOPE
;
4752 pnlet
= PushLexicalScope(context
, &tokenStream
, tc
, &blockInfo
);
4755 blockInfo
.flags
|= SIF_FOR_BLOCK
;
4756 pn1
= variables(false);
4762 tc
->flags
&= ~TCF_IN_FOR_INIT
;
4768 * We can be sure that it's a for/in loop if there's still an 'in'
4769 * keyword here, even if JavaScript recognizes 'in' as an operator,
4770 * as we've excluded 'in' from being parsed in RelExpr by setting
4771 * the TCF_IN_FOR_INIT flag in our JSTreeContext.
4773 if (pn1
&& tokenStream
.matchToken(TOK_IN
)) {
4774 pn
->pn_iflags
|= JSITER_ENUMERATE
;
4775 stmtInfo
.type
= STMT_FOR_IN_LOOP
;
4777 /* Check that the left side of the 'in' is valid. */
4778 JS_ASSERT(!TokenKindIsDecl(tt
) || PN_TYPE(pn1
) == tt
);
4779 if (TokenKindIsDecl(tt
)
4780 ? (pn1
->pn_count
> 1 || pn1
->pn_op
== JSOP_DEFCONST
4781 #if JS_HAS_DESTRUCTURING
4782 || (JSVERSION_NUMBER(context
) == JSVERSION_1_7
&&
4783 pn
->pn_op
== JSOP_ITER
&&
4784 !(pn
->pn_iflags
& JSITER_FOREACH
) &&
4785 (pn1
->pn_head
->pn_type
== TOK_RC
||
4786 (pn1
->pn_head
->pn_type
== TOK_RB
&&
4787 pn1
->pn_head
->pn_count
!= 2) ||
4788 (pn1
->pn_head
->pn_type
== TOK_ASSIGN
&&
4789 (pn1
->pn_head
->pn_left
->pn_type
!= TOK_RB
||
4790 pn1
->pn_head
->pn_left
->pn_count
!= 2))))
4793 : (pn1
->pn_type
!= TOK_NAME
&&
4794 pn1
->pn_type
!= TOK_DOT
&&
4795 #if JS_HAS_DESTRUCTURING
4796 ((JSVERSION_NUMBER(context
) == JSVERSION_1_7
&&
4797 pn
->pn_op
== JSOP_ITER
&&
4798 !(pn
->pn_iflags
& JSITER_FOREACH
))
4799 ? (pn1
->pn_type
!= TOK_RB
|| pn1
->pn_count
!= 2)
4800 : (pn1
->pn_type
!= TOK_RB
&& pn1
->pn_type
!= TOK_RC
)) &&
4802 pn1
->pn_type
!= TOK_LP
&&
4803 #if JS_HAS_XML_SUPPORT
4804 (pn1
->pn_type
!= TOK_UNARYOP
||
4805 pn1
->pn_op
!= JSOP_XMLNAME
) &&
4807 pn1
->pn_type
!= TOK_LB
)) {
4808 reportErrorNumber(pn1
, JSREPORT_ERROR
, JSMSG_BAD_FOR_LEFTSIDE
);
4812 /* pn2 points to the name or destructuring pattern on in's left. */
4814 uintN dflag
= PND_ASSIGNED
;
4816 if (TokenKindIsDecl(tt
)) {
4817 /* Tell js_EmitTree(TOK_VAR) that pn1 is part of a for/in. */
4818 pn1
->pn_xflags
|= PNX_FORINVAR
;
4821 * Rewrite 'for (<decl> x = i in o)' where <decl> is 'let',
4822 * 'var', or 'const' to hoist the initializer or the entire
4823 * decl out of the loop head. TOK_VAR is the type for both
4824 * 'var' and 'const'.
4827 if ((pn2
->pn_type
== TOK_NAME
&& pn2
->maybeExpr())
4828 #if JS_HAS_DESTRUCTURING
4829 || pn2
->pn_type
== TOK_ASSIGN
4832 pnseq
= ListNode::create(tc
);
4835 pnseq
->pn_type
= TOK_SEQ
;
4836 pnseq
->pn_pos
.begin
= pn
->pn_pos
.begin
;
4838 #if JS_HAS_BLOCK_SCOPE
4839 if (tt
== TOK_LET
) {
4841 * Hoist just the 'i' from 'for (let x = i in o)' to
4842 * before the loop, glued together via pnseq.
4844 pn3
= UnaryNode::create(tc
);
4847 pn3
->pn_type
= TOK_SEMI
;
4848 pn3
->pn_op
= JSOP_NOP
;
4849 #if JS_HAS_DESTRUCTURING
4850 if (pn2
->pn_type
== TOK_ASSIGN
) {
4851 pn4
= pn2
->pn_right
;
4852 pn2
= pn1
->pn_head
= pn2
->pn_left
;
4857 pn2
->pn_expr
= NULL
;
4859 if (!RebindLets(pn4
, tc
))
4861 pn3
->pn_pos
= pn4
->pn_pos
;
4863 pnseq
->initList(pn3
);
4865 #endif /* JS_HAS_BLOCK_SCOPE */
4867 dflag
= PND_INITIALIZED
;
4870 * All of 'var x = i' is hoisted above 'for (x in o)',
4871 * so clear PNX_FORINVAR.
4873 * Request JSOP_POP here since the var is for a simple
4874 * name (it is not a destructuring binding's left-hand
4875 * side) and it has an initializer.
4877 pn1
->pn_xflags
&= ~PNX_FORINVAR
;
4878 pn1
->pn_xflags
|= PNX_POPVAR
;
4879 pnseq
->initList(pn1
);
4881 #if JS_HAS_DESTRUCTURING
4882 if (pn2
->pn_type
== TOK_ASSIGN
) {
4883 pn1
= CloneParseTree(pn2
->pn_left
, tc
);
4889 JS_ASSERT(pn2
->pn_type
== TOK_NAME
);
4890 pn1
= NameNode::create(pn2
->pn_atom
, tc
);
4893 pn1
->pn_type
= TOK_NAME
;
4894 pn1
->pn_op
= JSOP_NAME
;
4895 pn1
->pn_pos
= pn2
->pn_pos
;
4897 LinkUseToDef(pn1
, (JSDefinition
*) pn2
, tc
);
4906 if (pn2
->pn_type
== TOK_LP
&&
4907 !MakeSetCall(context
, pn2
, tc
, JSMSG_BAD_LEFTSIDE_OF_ASS
)) {
4910 #if JS_HAS_XML_SUPPORT
4911 if (pn2
->pn_type
== TOK_UNARYOP
)
4912 pn2
->pn_op
= JSOP_BINDXMLNAME
;
4916 switch (pn2
->pn_type
) {
4918 /* Beware 'for (arguments in ...)' with or without a 'var'. */
4919 NoteLValue(context
, pn2
, tc
, dflag
);
4922 #if JS_HAS_DESTRUCTURING
4925 JS_ASSERT(pn2
->pn_type
== TOK_RB
|| pn2
->pn_type
== TOK_RC
);
4929 /* Check for valid lvalues in var-less destructuring for-in. */
4930 if (pn1
== pn2
&& !CheckDestructuring(context
, NULL
, pn2
, NULL
, tc
))
4933 if (JSVERSION_NUMBER(context
) == JSVERSION_1_7
) {
4935 * Destructuring for-in requires [key, value] enumeration
4938 JS_ASSERT(pn
->pn_op
== JSOP_ITER
);
4939 if (!(pn
->pn_iflags
& JSITER_FOREACH
))
4940 pn
->pn_iflags
|= JSITER_FOREACH
| JSITER_KEYVALUE
;
4949 * Parse the object expression as the right operand of 'in', first
4950 * removing the top statement from the statement-stack if this is a
4951 * 'for (let x in y)' loop.
4953 #if JS_HAS_BLOCK_SCOPE
4954 JSStmtInfo
*save
= tc
->topStmt
;
4956 tc
->topStmt
= save
->down
;
4959 #if JS_HAS_BLOCK_SCOPE
4964 pn2
= JSParseNode::newBinaryOrAppend(TOK_IN
, JSOP_NOP
, pn1
, pn2
, tc
);
4969 if (pn
->pn_iflags
& JSITER_FOREACH
)
4971 pn
->pn_op
= JSOP_NOP
;
4973 /* Parse the loop condition or null into pn2. */
4974 MUST_MATCH_TOKEN(TOK_SEMI
, JSMSG_SEMI_AFTER_FOR_INIT
);
4975 tt
= tokenStream
.peekToken(TSF_OPERAND
);
4976 if (tt
== TOK_SEMI
) {
4984 /* Parse the update expression or null into pn3. */
4985 MUST_MATCH_TOKEN(TOK_SEMI
, JSMSG_SEMI_AFTER_FOR_COND
);
4986 tt
= tokenStream
.peekToken(TSF_OPERAND
);
4995 /* Build the FORHEAD node to use as the left kid of pn. */
4996 pn4
= TernaryNode::create(tc
);
4999 pn4
->pn_type
= TOK_FORHEAD
;
5000 pn4
->pn_op
= JSOP_NOP
;
5007 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_AFTER_FOR_CTRL
);
5009 /* Parse the loop body into pn->pn_right. */
5015 /* Record the absolute line number for source note emission. */
5016 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
5018 #if JS_HAS_BLOCK_SCOPE
5021 pnlet
->pn_expr
= pn
;
5026 pnseq
->pn_pos
.end
= pn
->pn_pos
.end
;
5034 reportErrorNumber(pn
, JSREPORT_ERROR
, JSMSG_BAD_FOR_EACH_LOOP
);
5039 JSParseNode
*catchList
, *lastCatch
;
5042 * try nodes are ternary.
5043 * kid1 is the try statement
5044 * kid2 is the catch node list or null
5045 * kid3 is the finally statement
5047 * catch nodes are ternary.
5048 * kid1 is the lvalue (TOK_NAME, TOK_LB, or TOK_LC)
5049 * kid2 is the catch guard or null if no guard
5050 * kid3 is the catch block
5052 * catch lvalue nodes are either:
5053 * TOK_NAME for a single identifier
5054 * TOK_RB or TOK_RC for a destructuring left-hand side
5056 * finally nodes are TOK_LC statement lists.
5058 pn
= TernaryNode::create(tc
);
5061 pn
->pn_op
= JSOP_NOP
;
5063 MUST_MATCH_TOKEN(TOK_LC
, JSMSG_CURLY_BEFORE_TRY
);
5064 if (!PushBlocklikeStatement(&stmtInfo
, STMT_TRY
, tc
))
5066 pn
->pn_kid1
= statements();
5069 MUST_MATCH_TOKEN(TOK_RC
, JSMSG_CURLY_AFTER_TRY
);
5073 tt
= tokenStream
.getToken();
5074 if (tt
== TOK_CATCH
) {
5075 catchList
= ListNode::create(tc
);
5078 catchList
->pn_type
= TOK_RESERVED
;
5079 catchList
->makeEmpty();
5083 JSParseNode
*pnblock
;
5086 /* Check for another catch after unconditional catch. */
5087 if (lastCatch
&& !lastCatch
->pn_kid2
) {
5088 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_CATCH_AFTER_GENERAL
);
5093 * Create a lexical scope node around the whole catch clause,
5094 * including the head.
5096 pnblock
= PushLexicalScope(context
, &tokenStream
, tc
, &stmtInfo
);
5099 stmtInfo
.type
= STMT_CATCH
;
5102 * Legal catch forms are:
5104 * catch (lhs if <boolean_expression>)
5105 * where lhs is a name or a destructuring left-hand side.
5106 * (the latter is legal only #ifdef JS_HAS_CATCH_GUARD)
5108 pn2
= TernaryNode::create(tc
);
5111 pnblock
->pn_expr
= pn2
;
5112 MUST_MATCH_TOKEN(TOK_LP
, JSMSG_PAREN_BEFORE_CATCH
);
5115 * Contrary to ECMA Ed. 3, the catch variable is lexically
5116 * scoped, not a property of a new Object instance. This is
5117 * an intentional change that anticipates ECMA Ed. 4.
5121 data
.binder
= BindLet
;
5122 data
.let
.overflow
= JSMSG_TOO_MANY_CATCH_VARS
;
5124 tt
= tokenStream
.getToken();
5126 #if JS_HAS_DESTRUCTURING
5129 pn3
= destructuringExpr(&data
, tt
);
5136 label
= tokenStream
.currentToken().t_atom
;
5137 pn3
= NewBindingNode(label
, tc
, true);
5141 if (!data
.binder(context
, &data
, label
, tc
))
5146 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_CATCH_IDENTIFIER
);
5151 #if JS_HAS_CATCH_GUARD
5153 * We use 'catch (x if x === 5)' (not 'catch (x : x === 5)')
5154 * to avoid conflicting with the JS2/ECMAv4 type annotation
5155 * catchguard syntax.
5157 if (tokenStream
.matchToken(TOK_IF
)) {
5158 pn2
->pn_kid2
= expr();
5163 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_AFTER_CATCH
);
5165 MUST_MATCH_TOKEN(TOK_LC
, JSMSG_CURLY_BEFORE_CATCH
);
5166 pn2
->pn_kid3
= statements();
5169 MUST_MATCH_TOKEN(TOK_RC
, JSMSG_CURLY_AFTER_CATCH
);
5172 catchList
->append(pnblock
);
5174 tt
= tokenStream
.getToken(TSF_OPERAND
);
5175 } while (tt
== TOK_CATCH
);
5177 pn
->pn_kid2
= catchList
;
5179 if (tt
== TOK_FINALLY
) {
5180 MUST_MATCH_TOKEN(TOK_LC
, JSMSG_CURLY_BEFORE_FINALLY
);
5181 if (!PushBlocklikeStatement(&stmtInfo
, STMT_FINALLY
, tc
))
5183 pn
->pn_kid3
= statements();
5186 MUST_MATCH_TOKEN(TOK_RC
, JSMSG_CURLY_AFTER_FINALLY
);
5189 tokenStream
.ungetToken();
5191 if (!catchList
&& !pn
->pn_kid3
) {
5192 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_CATCH_OR_FINALLY
);
5199 pn
= UnaryNode::create(tc
);
5203 /* ECMA-262 Edition 3 says 'throw [no LineTerminator here] Expr'. */
5204 tt
= tokenStream
.peekTokenSameLine(TSF_OPERAND
);
5205 if (tt
== TOK_ERROR
)
5207 if (tt
== TOK_EOF
|| tt
== TOK_EOL
|| tt
== TOK_SEMI
|| tt
== TOK_RC
) {
5208 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_SYNTAX_ERROR
);
5215 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
5216 pn
->pn_op
= JSOP_THROW
;
5220 /* TOK_CATCH and TOK_FINALLY are both handled in the TOK_TRY case */
5222 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_CATCH_WITHOUT_TRY
);
5226 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_FINALLY_WITHOUT_TRY
);
5230 pn
= NullaryNode::create(tc
);
5233 if (!MatchLabel(context
, &tokenStream
, pn
))
5236 label
= pn
->pn_atom
;
5238 for (; ; stmt
= stmt
->down
) {
5240 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_LABEL_NOT_FOUND
);
5243 if (stmt
->type
== STMT_LABEL
&& stmt
->label
== label
)
5247 for (; ; stmt
= stmt
->down
) {
5249 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_TOUGH_BREAK
);
5252 if (STMT_IS_LOOP(stmt
) || stmt
->type
== STMT_SWITCH
)
5257 pn
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
5261 pn
= NullaryNode::create(tc
);
5264 if (!MatchLabel(context
, &tokenStream
, pn
))
5267 label
= pn
->pn_atom
;
5269 for (stmt2
= NULL
; ; stmt
= stmt
->down
) {
5271 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_LABEL_NOT_FOUND
);
5274 if (stmt
->type
== STMT_LABEL
) {
5275 if (stmt
->label
== label
) {
5276 if (!stmt2
|| !STMT_IS_LOOP(stmt2
)) {
5277 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_CONTINUE
);
5287 for (; ; stmt
= stmt
->down
) {
5289 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_CONTINUE
);
5292 if (STMT_IS_LOOP(stmt
))
5297 pn
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
5302 * In most cases, we want the constructs forbidden in strict mode
5303 * code to be a subset of those that JSOPTION_STRICT warns about, and
5304 * we should use ReportStrictModeError. However, 'with' is the sole
5305 * instance of a construct that is forbidden in strict mode code, but
5306 * doesn't even merit a warning under JSOPTION_STRICT. See
5307 * https://bugzilla.mozilla.org/show_bug.cgi?id=514576#c1.
5309 if (tc
->flags
& TCF_STRICT_MODE_CODE
) {
5310 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_STRICT_CODE_WITH
);
5314 pn
= BinaryNode::create(tc
);
5317 MUST_MATCH_TOKEN(TOK_LP
, JSMSG_PAREN_BEFORE_WITH
);
5318 pn2
= parenExpr(NULL
, NULL
);
5321 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_AFTER_WITH
);
5324 js_PushStatement(tc
, &stmtInfo
, STMT_WITH
, -1);
5330 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
5332 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
5336 pn
= variables(false);
5340 /* Tell js_EmitTree to generate a final POP. */
5341 pn
->pn_xflags
|= PNX_POPVAR
;
5344 #if JS_HAS_BLOCK_SCOPE
5348 JSObjectBox
*blockbox
;
5350 /* Check for a let statement or let expression. */
5351 if (tokenStream
.peekToken() == TOK_LP
) {
5352 pn
= letBlock(JS_TRUE
);
5353 if (!pn
|| pn
->pn_op
== JSOP_LEAVEBLOCK
)
5356 /* Let expressions require automatic semicolon insertion. */
5357 JS_ASSERT(pn
->pn_type
== TOK_SEMI
||
5358 pn
->pn_op
== JSOP_LEAVEBLOCKEXPR
);
5363 * This is a let declaration. We must be directly under a block per
5364 * the proposed ES4 specs, but not an implicit block created due to
5365 * 'for (let ...)'. If we pass this error test, make the enclosing
5366 * JSStmtInfo be our scope. Further let declarations in this block
5367 * will find this scope statement and use the same block object.
5369 * If we are the first let declaration in this block (i.e., when the
5370 * enclosing maybe-scope JSStmtInfo isn't yet a scope statement) then
5371 * we also need to set tc->blockNode to be our TOK_LEXICALSCOPE.
5375 (!STMT_MAYBE_SCOPE(stmt
) || (stmt
->flags
& SIF_FOR_BLOCK
))) {
5376 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_LET_DECL_NOT_IN_BLOCK
);
5380 if (stmt
&& (stmt
->flags
& SIF_SCOPE
)) {
5381 JS_ASSERT(tc
->blockChain
== stmt
->blockObj
);
5382 obj
= tc
->blockChain
;
5384 if (!stmt
|| (stmt
->flags
& SIF_BODY_BLOCK
)) {
5386 * ES4 specifies that let at top level and at body-block scope
5387 * does not shadow var, so convert back to var.
5389 tokenStream
.mungeCurrentToken(TOK_VAR
, JSOP_DEFVAR
);
5391 pn
= variables(false);
5394 pn
->pn_xflags
|= PNX_POPVAR
;
5399 * Some obvious assertions here, but they may help clarify the
5400 * situation. This stmt is not yet a scope, so it must not be a
5401 * catch block (catch is a lexical scope by definition).
5403 JS_ASSERT(!(stmt
->flags
& SIF_SCOPE
));
5404 JS_ASSERT(stmt
!= tc
->topScopeStmt
);
5405 JS_ASSERT(stmt
->type
== STMT_BLOCK
||
5406 stmt
->type
== STMT_SWITCH
||
5407 stmt
->type
== STMT_TRY
||
5408 stmt
->type
== STMT_FINALLY
);
5409 JS_ASSERT(!stmt
->downScope
);
5411 /* Convert the block statement into a scope statement. */
5412 JSObject
*obj
= js_NewBlockObject(tc
->parser
->context
);
5416 blockbox
= tc
->parser
->newObjectBox(obj
);
5421 * Insert stmt on the tc->topScopeStmt/stmtInfo.downScope linked
5422 * list stack, if it isn't already there. If it is there, but it
5423 * lacks the SIF_SCOPE flag, it must be a try, catch, or finally
5426 stmt
->flags
|= SIF_SCOPE
;
5427 stmt
->downScope
= tc
->topScopeStmt
;
5428 tc
->topScopeStmt
= stmt
;
5429 JS_SCOPE_DEPTH_METERING(++tc
->scopeDepth
> tc
->maxScopeDepth
&&
5430 (tc
->maxScopeDepth
= tc
->scopeDepth
));
5432 obj
->setParent(tc
->blockChain
);
5433 tc
->blockChain
= obj
;
5434 stmt
->blockObj
= obj
;
5437 pn1
= tc
->blockNode
;
5438 JS_ASSERT(!pn1
|| pn1
->pn_type
!= TOK_LEXICALSCOPE
);
5441 /* Create a new lexical scope node for these statements. */
5442 pn1
= LexicalScopeNode::create(tc
);
5446 pn1
->pn_type
= TOK_LEXICALSCOPE
;
5447 pn1
->pn_op
= JSOP_LEAVEBLOCK
;
5448 pn1
->pn_pos
= tc
->blockNode
->pn_pos
;
5449 pn1
->pn_objbox
= blockbox
;
5450 pn1
->pn_expr
= tc
->blockNode
;
5451 pn1
->pn_blockid
= tc
->blockNode
->pn_blockid
;
5452 tc
->blockNode
= pn1
;
5455 pn
= variables(false);
5458 pn
->pn_xflags
= PNX_POPVAR
;
5461 #endif /* JS_HAS_BLOCK_SCOPE */
5464 pn
= returnOrYield(false);
5473 oldflags
= tc
->flags
;
5474 tc
->flags
= oldflags
& ~TCF_HAS_FUNCTION_STMT
;
5475 if (!PushBlocklikeStatement(&stmtInfo
, STMT_BLOCK
, tc
))
5481 MUST_MATCH_TOKEN(TOK_RC
, JSMSG_CURLY_IN_COMPOUND
);
5485 * If we contain a function statement and our container is top-level
5486 * or another block, flag pn to preserve braces when decompiling.
5488 if ((tc
->flags
& TCF_HAS_FUNCTION_STMT
) &&
5489 (!tc
->topStmt
|| tc
->topStmt
->type
== STMT_BLOCK
)) {
5490 pn
->pn_xflags
|= PNX_NEEDBRACES
;
5492 tc
->flags
= oldflags
| (tc
->flags
& (TCF_FUN_FLAGS
| TCF_RETURN_FLAGS
));
5498 pn
= UnaryNode::create(tc
);
5501 pn
->pn_type
= TOK_SEMI
;
5504 #if JS_HAS_DEBUGGER_KEYWORD
5506 pn
= NullaryNode::create(tc
);
5509 pn
->pn_type
= TOK_DEBUGGER
;
5510 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
5512 #endif /* JS_HAS_DEBUGGER_KEYWORD */
5514 #if JS_HAS_XML_SUPPORT
5516 pn
= UnaryNode::create(tc
);
5519 if (!tokenStream
.matchToken(TOK_NAME
) ||
5520 tokenStream
.currentToken().t_atom
!= context
->runtime
->atomState
.xmlAtom
||
5521 !tokenStream
.matchToken(TOK_NAME
) ||
5522 tokenStream
.currentToken().t_atom
!= context
->runtime
->atomState
.namespaceAtom
||
5523 !tokenStream
.matchToken(TOK_ASSIGN
) ||
5524 tokenStream
.currentToken().t_op
!= JSOP_NOP
) {
5525 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_DEFAULT_XML_NAMESPACE
);
5529 /* Is this an E4X dagger I see before me? */
5530 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
5534 pn
->pn_op
= JSOP_DEFXMLNS
;
5535 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
5544 #if JS_HAS_XML_SUPPORT
5547 tokenStream
.ungetToken();
5552 if (tokenStream
.peekToken() == TOK_COLON
) {
5553 if (pn2
->pn_type
!= TOK_NAME
) {
5554 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_LABEL
);
5557 label
= pn2
->pn_atom
;
5558 for (stmt
= tc
->topStmt
; stmt
; stmt
= stmt
->down
) {
5559 if (stmt
->type
== STMT_LABEL
&& stmt
->label
== label
) {
5560 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_DUPLICATE_LABEL
);
5566 (void) tokenStream
.getToken();
5568 /* Push a label struct and parse the statement. */
5569 js_PushStatement(tc
, &stmtInfo
, STMT_LABEL
, -1);
5570 stmtInfo
.label
= label
;
5575 /* Normalize empty statement to empty block for the decompiler. */
5576 if (pn
->pn_type
== TOK_SEMI
&& !pn
->pn_kid
) {
5577 pn
->pn_type
= TOK_LC
;
5578 pn
->pn_arity
= PN_LIST
;
5582 /* Pop the label, set pn_expr, and return early. */
5584 pn2
->pn_type
= TOK_COLON
;
5585 pn2
->pn_pos
.end
= pn
->pn_pos
.end
;
5590 pn
= UnaryNode::create(tc
);
5593 pn
->pn_type
= TOK_SEMI
;
5594 pn
->pn_pos
= pn2
->pn_pos
;
5597 switch (PN_TYPE(pn2
)) {
5600 * Flag lambdas immediately applied as statements as instances of
5601 * the JS "module pattern". See CheckForImmediatelyAppliedLambda.
5603 if (PN_TYPE(pn2
->pn_head
) == TOK_FUNCTION
&&
5604 !pn2
->pn_head
->pn_funbox
->node
->isFunArg()) {
5605 pn2
->pn_head
->pn_funbox
->tcflags
|= TCF_FUN_MODULE_PATTERN
;
5610 * Keep track of all apparent methods created by assignments such
5611 * as this.foo = function (...) {...} in a function that could end
5612 * up a constructor function. See Parser::setFunctionKinds.
5615 PN_OP(pn2
) == JSOP_NOP
&&
5616 PN_OP(pn2
->pn_left
) == JSOP_SETPROP
&&
5617 PN_OP(pn2
->pn_left
->pn_expr
) == JSOP_THIS
&&
5618 PN_OP(pn2
->pn_right
) == JSOP_LAMBDA
) {
5619 JS_ASSERT(!pn2
->pn_defn
);
5620 JS_ASSERT(!pn2
->pn_used
);
5621 pn2
->pn_right
->pn_link
= tc
->funbox
->methods
;
5622 tc
->funbox
->methods
= pn2
->pn_right
;
5630 /* Check termination of this primitive statement. */
5631 return MatchOrInsertSemicolon(context
, &tokenStream
) ? pn
: NULL
;
5635 NoteArgumentsUse(JSTreeContext
*tc
)
5637 JS_ASSERT(tc
->inFunction());
5638 tc
->flags
|= TCF_FUN_USES_ARGUMENTS
;
5640 tc
->funbox
->node
->pn_dflags
|= PND_FUNARG
;
5644 Parser::variables(bool inLetHead
)
5648 JSStmtInfo
*scopeStmt
;
5650 JSParseNode
*pn
, *pn2
;
5654 * The three options here are:
5655 * - TOK_LET: We are parsing a let declaration.
5656 * - TOK_LP: We are parsing the head of a let block.
5657 * - Otherwise, we're parsing var declarations.
5659 tt
= tokenStream
.currentToken().type
;
5660 let
= (tt
== TOK_LET
|| tt
== TOK_LP
);
5661 JS_ASSERT(let
|| tt
== TOK_VAR
);
5663 #if JS_HAS_BLOCK_SCOPE
5664 bool popScope
= (inLetHead
|| (let
&& (tc
->flags
& TCF_IN_FOR_INIT
)));
5665 JSStmtInfo
*save
= tc
->topStmt
, *saveScope
= tc
->topScopeStmt
;
5668 /* Make sure that statement set up the tree context correctly. */
5669 scopeStmt
= tc
->topScopeStmt
;
5671 while (scopeStmt
&& !(scopeStmt
->flags
& SIF_SCOPE
)) {
5672 JS_ASSERT(!STMT_MAYBE_SCOPE(scopeStmt
));
5673 scopeStmt
= scopeStmt
->downScope
;
5675 JS_ASSERT(scopeStmt
);
5678 data
.op
= let
? JSOP_NOP
: tokenStream
.currentToken().t_op
;
5679 pn
= ListNode::create(tc
);
5682 pn
->pn_op
= data
.op
;
5686 * SpiderMonkey const is really "write once per initialization evaluation"
5687 * var, whereas let is block scoped. ES-Harmony wants block-scoped const so
5688 * this code will change soon.
5691 JS_ASSERT(tc
->blockChain
== scopeStmt
->blockObj
);
5692 data
.binder
= BindLet
;
5693 data
.let
.overflow
= JSMSG_TOO_MANY_LOCALS
;
5695 data
.binder
= BindVarOrConst
;
5699 tt
= tokenStream
.getToken();
5700 #if JS_HAS_DESTRUCTURING
5701 if (tt
== TOK_LB
|| tt
== TOK_LC
) {
5702 tc
->flags
|= TCF_DECL_DESTRUCTURING
;
5703 pn2
= primaryExpr(tt
, JS_FALSE
);
5704 tc
->flags
&= ~TCF_DECL_DESTRUCTURING
;
5708 if (!CheckDestructuring(context
, &data
, pn2
, NULL
, tc
))
5710 if ((tc
->flags
& TCF_IN_FOR_INIT
) &&
5711 tokenStream
.peekToken() == TOK_IN
) {
5716 MUST_MATCH_TOKEN(TOK_ASSIGN
, JSMSG_BAD_DESTRUCT_DECL
);
5717 if (tokenStream
.currentToken().t_op
!= JSOP_NOP
)
5720 #if JS_HAS_BLOCK_SCOPE
5722 tc
->topStmt
= save
->down
;
5723 tc
->topScopeStmt
= saveScope
->downScope
;
5726 JSParseNode
*init
= assignExpr();
5727 #if JS_HAS_BLOCK_SCOPE
5730 tc
->topScopeStmt
= saveScope
;
5734 if (!init
|| !UndominateInitializers(pn2
, init
, tc
))
5737 pn2
= JSParseNode::newBinaryOrAppend(TOK_ASSIGN
, JSOP_NOP
, pn2
, init
, tc
);
5743 #endif /* JS_HAS_DESTRUCTURING */
5745 if (tt
!= TOK_NAME
) {
5746 if (tt
!= TOK_ERROR
) {
5747 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_NO_VARIABLE_NAME
);
5752 atom
= tokenStream
.currentToken().t_atom
;
5753 pn2
= NewBindingNode(atom
, tc
, let
);
5756 if (data
.op
== JSOP_DEFCONST
)
5757 pn2
->pn_dflags
|= PND_CONST
;
5759 if (!data
.binder(context
, &data
, atom
, tc
))
5763 if (tokenStream
.matchToken(TOK_ASSIGN
)) {
5764 if (tokenStream
.currentToken().t_op
!= JSOP_NOP
)
5767 #if JS_HAS_BLOCK_SCOPE
5769 tc
->topStmt
= save
->down
;
5770 tc
->topScopeStmt
= saveScope
->downScope
;
5773 JSParseNode
*init
= assignExpr();
5774 #if JS_HAS_BLOCK_SCOPE
5777 tc
->topScopeStmt
= saveScope
;
5784 pn2
= MakeAssignment(pn2
, init
, tc
);
5788 pn2
->pn_expr
= init
;
5791 pn2
->pn_op
= (PN_OP(pn2
) == JSOP_ARGUMENTS
)
5793 : (pn2
->pn_dflags
& PND_GVAR
)
5795 : (pn2
->pn_dflags
& PND_BOUND
)
5797 : (data
.op
== JSOP_DEFCONST
)
5801 NoteLValue(context
, pn2
, tc
, data
.fresh
? PND_INITIALIZED
: PND_ASSIGNED
);
5803 /* The declarator's position must include the initializer. */
5804 pn2
->pn_pos
.end
= init
->pn_pos
.end
;
5806 if (tc
->inFunction() &&
5807 atom
== context
->runtime
->atomState
.argumentsAtom
) {
5808 NoteArgumentsUse(tc
);
5810 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
5813 } while (tokenStream
.matchToken(TOK_COMMA
));
5815 pn
->pn_pos
.end
= pn
->last()->pn_pos
.end
;
5819 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_VAR_INIT
);
5826 JSParseNode
*pn
= assignExpr();
5827 if (pn
&& tokenStream
.matchToken(TOK_COMMA
)) {
5828 JSParseNode
*pn2
= ListNode::create(tc
);
5831 pn2
->pn_pos
.begin
= pn
->pn_pos
.begin
;
5835 #if JS_HAS_GENERATORS
5837 if (pn2
->pn_type
== TOK_YIELD
&& !pn2
->pn_parens
) {
5838 reportErrorNumber(pn2
, JSREPORT_ERROR
, JSMSG_BAD_GENERATOR_SYNTAX
, js_yield_str
);
5846 } while (tokenStream
.matchToken(TOK_COMMA
));
5847 pn
->pn_pos
.end
= pn
->last()->pn_pos
.end
;
5853 Parser::assignExpr()
5855 JS_CHECK_RECURSION(context
, return NULL
);
5857 #if JS_HAS_GENERATORS
5858 if (tokenStream
.matchToken(TOK_YIELD
, TSF_OPERAND
))
5859 return returnOrYield(true);
5862 JSParseNode
*pn
= condExpr();
5866 TokenKind tt
= tokenStream
.getToken();
5867 if (tt
!= TOK_ASSIGN
) {
5868 tokenStream
.ungetToken();
5872 JSOp op
= tokenStream
.currentToken().t_op
;
5873 switch (pn
->pn_type
) {
5875 if (!CheckStrictAssignment(context
, tc
, pn
))
5877 pn
->pn_op
= JSOP_SETNAME
;
5878 NoteLValue(context
, pn
, tc
);
5881 pn
->pn_op
= JSOP_SETPROP
;
5884 pn
->pn_op
= JSOP_SETELEM
;
5886 #if JS_HAS_DESTRUCTURING
5890 if (op
!= JSOP_NOP
) {
5891 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_DESTRUCT_ASS
);
5894 JSParseNode
*rhs
= assignExpr();
5895 if (!rhs
|| !CheckDestructuring(context
, NULL
, pn
, rhs
, tc
))
5897 return JSParseNode::newBinaryOrAppend(TOK_ASSIGN
, op
, pn
, rhs
, tc
);
5901 if (!MakeSetCall(context
, pn
, tc
, JSMSG_BAD_LEFTSIDE_OF_ASS
))
5904 #if JS_HAS_XML_SUPPORT
5906 if (pn
->pn_op
== JSOP_XMLNAME
) {
5907 pn
->pn_op
= JSOP_SETXMLNAME
;
5913 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_LEFTSIDE_OF_ASS
);
5917 JSParseNode
*rhs
= assignExpr();
5918 if (rhs
&& PN_TYPE(pn
) == TOK_NAME
&& pn
->pn_used
) {
5919 JSDefinition
*dn
= pn
->pn_lexdef
;
5922 * If the definition is not flagged as assigned, we must have imputed
5923 * the initialized flag to it, to optimize for flat closures. But that
5924 * optimization uses source coordinates to check dominance relations,
5925 * so we must extend the end of the definition to cover the right-hand
5926 * side of this assignment, i.e., the initializer.
5928 if (!dn
->isAssigned()) {
5929 JS_ASSERT(dn
->isInitialized());
5930 dn
->pn_pos
.end
= rhs
->pn_pos
.end
;
5934 return JSParseNode::newBinaryOrAppend(TOK_ASSIGN
, op
, pn
, rhs
, tc
);
5940 JSParseNode
*pn
= orExpr();
5941 if (pn
&& tokenStream
.matchToken(TOK_HOOK
)) {
5942 JSParseNode
*pn1
= pn
;
5943 pn
= TernaryNode::create(tc
);
5948 * Always accept the 'in' operator in the middle clause of a ternary,
5949 * where it's unambiguous, even if we might be parsing the init of a
5952 uintN oldflags
= tc
->flags
;
5953 tc
->flags
&= ~TCF_IN_FOR_INIT
;
5954 JSParseNode
*pn2
= assignExpr();
5955 tc
->flags
= oldflags
| (tc
->flags
& TCF_FUN_FLAGS
);
5959 MUST_MATCH_TOKEN(TOK_COLON
, JSMSG_COLON_IN_COND
);
5960 JSParseNode
*pn3
= assignExpr();
5963 pn
->pn_pos
.begin
= pn1
->pn_pos
.begin
;
5964 pn
->pn_pos
.end
= pn3
->pn_pos
.end
;
5975 JSParseNode
*pn
= andExpr();
5976 while (pn
&& tokenStream
.matchToken(TOK_OR
))
5977 pn
= JSParseNode::newBinaryOrAppend(TOK_OR
, JSOP_OR
, pn
, andExpr(), tc
);
5984 JSParseNode
*pn
= bitOrExpr();
5985 while (pn
&& tokenStream
.matchToken(TOK_AND
))
5986 pn
= JSParseNode::newBinaryOrAppend(TOK_AND
, JSOP_AND
, pn
, bitOrExpr(), tc
);
5993 JSParseNode
*pn
= bitXorExpr();
5994 while (pn
&& tokenStream
.matchToken(TOK_BITOR
))
5995 pn
= JSParseNode::newBinaryOrAppend(TOK_BITOR
, JSOP_BITOR
, pn
, bitXorExpr(), tc
);
6000 Parser::bitXorExpr()
6002 JSParseNode
*pn
= bitAndExpr();
6003 while (pn
&& tokenStream
.matchToken(TOK_BITXOR
)) {
6004 pn
= JSParseNode::newBinaryOrAppend(TOK_BITXOR
, JSOP_BITXOR
, pn
, bitAndExpr(), tc
);
6010 Parser::bitAndExpr()
6012 JSParseNode
*pn
= eqExpr();
6013 while (pn
&& tokenStream
.matchToken(TOK_BITAND
))
6014 pn
= JSParseNode::newBinaryOrAppend(TOK_BITAND
, JSOP_BITAND
, pn
, eqExpr(), tc
);
6021 JSParseNode
*pn
= relExpr();
6022 while (pn
&& tokenStream
.matchToken(TOK_EQOP
)) {
6023 JSOp op
= tokenStream
.currentToken().t_op
;
6024 pn
= JSParseNode::newBinaryOrAppend(TOK_EQOP
, op
, pn
, relExpr(), tc
);
6032 uintN inForInitFlag
= tc
->flags
& TCF_IN_FOR_INIT
;
6035 * Uses of the in operator in shiftExprs are always unambiguous,
6036 * so unset the flag that prohibits recognizing it.
6038 tc
->flags
&= ~TCF_IN_FOR_INIT
;
6040 JSParseNode
*pn
= shiftExpr();
6042 (tokenStream
.matchToken(TOK_RELOP
) ||
6044 * Recognize the 'in' token as an operator only if we're not
6045 * currently in the init expr of a for loop.
6047 (inForInitFlag
== 0 && tokenStream
.matchToken(TOK_IN
)) ||
6048 tokenStream
.matchToken(TOK_INSTANCEOF
))) {
6049 TokenKind tt
= tokenStream
.currentToken().type
;
6050 JSOp op
= tokenStream
.currentToken().t_op
;
6051 pn
= JSParseNode::newBinaryOrAppend(tt
, op
, pn
, shiftExpr(), tc
);
6053 /* Restore previous state of inForInit flag. */
6054 tc
->flags
|= inForInitFlag
;
6062 JSParseNode
*pn
= addExpr();
6063 while (pn
&& tokenStream
.matchToken(TOK_SHOP
)) {
6064 JSOp op
= tokenStream
.currentToken().t_op
;
6065 pn
= JSParseNode::newBinaryOrAppend(TOK_SHOP
, op
, pn
, addExpr(), tc
);
6073 JSParseNode
*pn
= mulExpr();
6075 (tokenStream
.matchToken(TOK_PLUS
) ||
6076 tokenStream
.matchToken(TOK_MINUS
))) {
6077 TokenKind tt
= tokenStream
.currentToken().type
;
6078 JSOp op
= (tt
== TOK_PLUS
) ? JSOP_ADD
: JSOP_SUB
;
6079 pn
= JSParseNode::newBinaryOrAppend(tt
, op
, pn
, mulExpr(), tc
);
6087 JSParseNode
*pn
= unaryExpr();
6088 while (pn
&& (tokenStream
.matchToken(TOK_STAR
) || tokenStream
.matchToken(TOK_DIVOP
))) {
6089 TokenKind tt
= tokenStream
.currentToken().type
;
6090 JSOp op
= tokenStream
.currentToken().t_op
;
6091 pn
= JSParseNode::newBinaryOrAppend(tt
, op
, pn
, unaryExpr(), tc
);
6096 static JSParseNode
*
6097 SetLvalKid(JSContext
*cx
, TokenStream
*ts
, JSTreeContext
*tc
,
6098 JSParseNode
*pn
, JSParseNode
*kid
, const char *name
)
6100 if (kid
->pn_type
!= TOK_NAME
&&
6101 kid
->pn_type
!= TOK_DOT
&&
6102 (kid
->pn_type
!= TOK_LP
||
6103 (kid
->pn_op
!= JSOP_CALL
&& kid
->pn_op
!= JSOP_EVAL
&& kid
->pn_op
!= JSOP_APPLY
)) &&
6104 #if JS_HAS_XML_SUPPORT
6105 (kid
->pn_type
!= TOK_UNARYOP
|| kid
->pn_op
!= JSOP_XMLNAME
) &&
6107 kid
->pn_type
!= TOK_LB
) {
6108 ReportCompileErrorNumber(cx
, ts
, NULL
, JSREPORT_ERROR
, JSMSG_BAD_OPERAND
, name
);
6111 if (!CheckStrictAssignment(cx
, tc
, kid
))
6117 static const char incop_name_str
[][10] = {"increment", "decrement"};
6120 SetIncOpKid(JSContext
*cx
, TokenStream
*ts
, JSTreeContext
*tc
,
6121 JSParseNode
*pn
, JSParseNode
*kid
,
6122 TokenKind tt
, JSBool preorder
)
6126 kid
= SetLvalKid(cx
, ts
, tc
, pn
, kid
, incop_name_str
[tt
== TOK_DEC
]);
6129 switch (kid
->pn_type
) {
6131 op
= (tt
== TOK_INC
)
6132 ? (preorder
? JSOP_INCNAME
: JSOP_NAMEINC
)
6133 : (preorder
? JSOP_DECNAME
: JSOP_NAMEDEC
);
6134 NoteLValue(cx
, kid
, tc
);
6138 op
= (tt
== TOK_INC
)
6139 ? (preorder
? JSOP_INCPROP
: JSOP_PROPINC
)
6140 : (preorder
? JSOP_DECPROP
: JSOP_PROPDEC
);
6144 if (!MakeSetCall(cx
, kid
, tc
, JSMSG_BAD_INCOP_OPERAND
))
6147 #if JS_HAS_XML_SUPPORT
6149 if (kid
->pn_op
== JSOP_XMLNAME
)
6150 kid
->pn_op
= JSOP_SETXMLNAME
;
6154 op
= (tt
== TOK_INC
)
6155 ? (preorder
? JSOP_INCELEM
: JSOP_ELEMINC
)
6156 : (preorder
? JSOP_DECELEM
: JSOP_ELEMDEC
);
6170 JSParseNode
*pn
, *pn2
;
6172 JS_CHECK_RECURSION(context
, return NULL
);
6174 TokenKind tt
= tokenStream
.getToken(TSF_OPERAND
);
6179 pn
= UnaryNode::create(tc
);
6182 pn
->pn_type
= TOK_UNARYOP
; /* PLUS and MINUS are binary */
6183 pn
->pn_op
= tokenStream
.currentToken().t_op
;
6187 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
6193 pn
= UnaryNode::create(tc
);
6196 pn2
= memberExpr(JS_TRUE
);
6199 if (!SetIncOpKid(context
, &tokenStream
, tc
, pn
, pn2
, tt
, JS_TRUE
))
6201 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
6206 pn
= UnaryNode::create(tc
);
6212 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
6215 * Under ECMA3, deleting any unary expression is valid -- it simply
6216 * returns true. Here we fold constants before checking for a call
6217 * expression, in order to rule out delete of a generator expression.
6219 if (!js_FoldConstants(context
, pn2
, tc
))
6221 switch (pn2
->pn_type
) {
6223 if (pn2
->pn_op
!= JSOP_SETCALL
&&
6224 !MakeSetCall(context
, pn2
, tc
, JSMSG_BAD_DELETE_OPERAND
)) {
6229 if (!ReportStrictModeError(context
, &tokenStream
, tc
, pn
,
6230 JSMSG_DEPRECATED_DELETE_OPERAND
))
6232 pn2
->pn_op
= JSOP_DELNAME
;
6233 if (pn2
->pn_atom
== context
->runtime
->atomState
.argumentsAtom
)
6234 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
6245 tokenStream
.ungetToken();
6246 pn
= memberExpr(JS_TRUE
);
6250 /* Don't look across a newline boundary for a postfix incop. */
6251 if (tokenStream
.onCurrentLine(pn
->pn_pos
)) {
6252 tt
= tokenStream
.peekTokenSameLine(TSF_OPERAND
);
6253 if (tt
== TOK_INC
|| tt
== TOK_DEC
) {
6254 (void) tokenStream
.getToken();
6255 pn2
= UnaryNode::create(tc
);
6258 if (!SetIncOpKid(context
, &tokenStream
, tc
, pn2
, pn
, tt
, JS_FALSE
))
6260 pn2
->pn_pos
.begin
= pn
->pn_pos
.begin
;
6269 #if JS_HAS_GENERATORS
6272 * A dedicated helper for transplanting the comprehension expression E in
6274 * [E for (V in I)] // array comprehension
6275 * (E for (V in I)) // generator expression
6277 * from its initial location in the AST, on the left of the 'for', to its final
6278 * position on the right. To avoid a separate pass we do this by adjusting the
6279 * blockids and name binding links that were established when E was parsed.
6281 * A generator expression desugars like so:
6283 * (E for (V in I)) => (function () { for (var V in I) yield E; })()
6285 * so the transplanter must adjust static level as well as blockid. E's source
6286 * coordinates in root->pn_pos are critical to deciding which binding links to
6287 * preserve and which to cut.
6289 * NB: This is not a general tree transplanter -- it knows in particular that
6290 * the one or more bindings induced by V have not yet been created.
6292 class CompExprTransplanter
{
6300 CompExprTransplanter(JSParseNode
*pn
, JSTreeContext
*tc
, bool ge
, uintN adj
)
6301 : root(pn
), tc(tc
), genexp(ge
), adjust(adj
), funcLevel(0)
6305 bool transplant(JSParseNode
*pn
);
6309 * Any definitions nested within the comprehension expression of a generator
6310 * expression must move "down" one static level, which of course increases the
6311 * upvar-frame-skip count.
6314 BumpStaticLevel(JSParseNode
*pn
, JSTreeContext
*tc
)
6316 if (pn
->pn_cookie
!= FREE_UPVAR_COOKIE
) {
6317 uintN level
= UPVAR_FRAME_SKIP(pn
->pn_cookie
) + 1;
6319 JS_ASSERT(level
>= tc
->staticLevel
);
6320 if (level
>= FREE_STATIC_LEVEL
) {
6321 JS_ReportErrorNumber(tc
->parser
->context
, js_GetErrorMessage
, NULL
,
6322 JSMSG_TOO_DEEP
, js_function_str
);
6326 pn
->pn_cookie
= MAKE_UPVAR_COOKIE(level
, UPVAR_FRAME_SLOT(pn
->pn_cookie
));
6332 AdjustBlockId(JSParseNode
*pn
, uintN adjust
, JSTreeContext
*tc
)
6334 JS_ASSERT(pn
->pn_arity
== PN_LIST
|| pn
->pn_arity
== PN_FUNC
|| pn
->pn_arity
== PN_NAME
);
6335 pn
->pn_blockid
+= adjust
;
6336 if (pn
->pn_blockid
>= tc
->blockidGen
)
6337 tc
->blockidGen
= pn
->pn_blockid
+ 1;
6341 CompExprTransplanter::transplant(JSParseNode
*pn
)
6346 switch (pn
->pn_arity
) {
6348 for (JSParseNode
*pn2
= pn
->pn_head
; pn2
; pn2
= pn2
->pn_next
)
6350 if (pn
->pn_pos
>= root
->pn_pos
)
6351 AdjustBlockId(pn
, adjust
, tc
);
6355 transplant(pn
->pn_kid1
);
6356 transplant(pn
->pn_kid2
);
6357 transplant(pn
->pn_kid3
);
6361 transplant(pn
->pn_left
);
6363 /* Binary TOK_COLON nodes can have left == right. See bug 492714. */
6364 if (pn
->pn_right
!= pn
->pn_left
)
6365 transplant(pn
->pn_right
);
6369 transplant(pn
->pn_kid
);
6375 * Only the first level of transplant recursion through functions needs
6376 * to reparent the funbox, since all descendant functions are correctly
6377 * linked under the top-most funbox. But every visit to this case needs
6378 * to update funbox->level.
6380 * Recall that funbox->level is the static level of the code containing
6381 * the definition or expression of the function and not the static level
6382 * of the function's body.
6384 JSFunctionBox
*funbox
= pn
->pn_funbox
;
6386 funbox
->level
= tc
->staticLevel
+ funcLevel
;
6387 if (++funcLevel
== 1 && genexp
) {
6388 JSFunctionBox
*parent
= tc
->funbox
;
6390 JSFunctionBox
**funboxp
= &tc
->parent
->functionList
;
6391 while (*funboxp
!= funbox
)
6392 funboxp
= &(*funboxp
)->siblings
;
6393 *funboxp
= funbox
->siblings
;
6395 funbox
->parent
= parent
;
6396 funbox
->siblings
= parent
->kids
;
6397 parent
->kids
= funbox
;
6398 funbox
->level
= tc
->staticLevel
;
6404 transplant(pn
->maybeExpr());
6405 if (pn
->pn_arity
== PN_FUNC
)
6409 if (genexp
&& !BumpStaticLevel(pn
, tc
))
6411 } else if (pn
->pn_used
) {
6412 JS_ASSERT(pn
->pn_op
!= JSOP_NOP
);
6413 JS_ASSERT(pn
->pn_cookie
== FREE_UPVAR_COOKIE
);
6415 JSDefinition
*dn
= pn
->pn_lexdef
;
6416 JS_ASSERT(dn
->pn_defn
);
6419 * Adjust the definition's block id only if it is a placeholder not
6420 * to the left of the root node, and if pn is the last use visited
6421 * in the comprehension expression (to avoid adjusting the blockid
6424 * Non-placeholder definitions within the comprehension expression
6425 * will be visited further below.
6427 if (dn
->isPlaceholder() && dn
->pn_pos
>= root
->pn_pos
&& dn
->dn_uses
== pn
) {
6428 if (genexp
&& !BumpStaticLevel(dn
, tc
))
6430 AdjustBlockId(dn
, adjust
, tc
);
6433 JSAtom
*atom
= pn
->pn_atom
;
6435 JSStmtInfo
*stmt
= js_LexicalLookup(tc
, atom
, NULL
);
6436 JS_ASSERT(!stmt
|| stmt
!= tc
->topStmt
);
6438 if (genexp
&& PN_OP(dn
) != JSOP_CALLEE
) {
6439 JS_ASSERT(!tc
->decls
.lookup(atom
));
6441 if (dn
->pn_pos
< root
->pn_pos
|| dn
->isPlaceholder()) {
6442 JSAtomListElement
*ale
= tc
->lexdeps
.add(tc
->parser
, dn
->pn_atom
);
6446 if (dn
->pn_pos
>= root
->pn_pos
) {
6447 tc
->parent
->lexdeps
.remove(tc
->parser
, atom
);
6449 JSDefinition
*dn2
= (JSDefinition
*)NameNode::create(dn
->pn_atom
, tc
);
6453 dn2
->pn_type
= dn
->pn_type
;
6454 dn2
->pn_pos
= root
->pn_pos
;
6455 dn2
->pn_defn
= true;
6456 dn2
->pn_dflags
|= PND_PLACEHOLDER
;
6458 JSParseNode
**pnup
= &dn
->dn_uses
;
6460 while ((pnu
= *pnup
) != NULL
&& pnu
->pn_pos
>= root
->pn_pos
) {
6461 pnu
->pn_lexdef
= dn2
;
6462 dn2
->pn_dflags
|= pnu
->pn_dflags
& PND_USE2DEF_FLAGS
;
6463 pnup
= &pnu
->pn_link
;
6465 dn2
->dn_uses
= dn
->dn_uses
;
6466 dn
->dn_uses
= *pnup
;
6472 ALE_SET_DEFN(ale
, dn
);
6477 if (pn
->pn_pos
>= root
->pn_pos
)
6478 AdjustBlockId(pn
, adjust
, tc
);
6482 transplant(pn
->pn_tree
);
6489 * Starting from a |for| keyword after the first array initialiser element or
6490 * an expression in an open parenthesis, parse the tail of the comprehension
6491 * or generator expression signified by this |for| keyword in context.
6493 * Return null on failure, else return the top-most parse node for the array
6494 * comprehension or generator expression, with a unary node as the body of the
6495 * (possibly nested) for-loop, initialized by |type, op, kid|.
6498 Parser::comprehensionTail(JSParseNode
*kid
, uintN blockid
,
6499 TokenKind type
, JSOp op
)
6502 JSParseNode
*pn
, *pn2
, *pn3
, **pnp
;
6503 JSStmtInfo stmtInfo
;
6508 JS_ASSERT(tokenStream
.currentToken().type
== TOK_FOR
);
6510 if (type
== TOK_SEMI
) {
6512 * Generator expression desugars to an immediately applied lambda that
6513 * yields the next value from a for-in loop (possibly nested, and with
6514 * optional if guard). Make pn be the TOK_LC body node.
6516 pn
= PushLexicalScope(context
, &tokenStream
, tc
, &stmtInfo
);
6519 adjust
= pn
->pn_blockid
- blockid
;
6521 JS_ASSERT(type
== TOK_ARRAYPUSH
);
6524 * Make a parse-node and literal object representing the block scope of
6525 * this array comprehension. Our caller in primaryExpr, the TOK_LB case
6526 * aka the array initialiser case, has passed the blockid to claim for
6527 * the comprehension's block scope. We allocate that id or one above it
6528 * here, by calling js_PushLexicalScope.
6530 * In the case of a comprehension expression that has nested blocks
6531 * (e.g., let expressions), we will allocate a higher blockid but then
6532 * slide all blocks "to the right" to make room for the comprehension's
6535 adjust
= tc
->blockid();
6536 pn
= PushLexicalScope(context
, &tokenStream
, tc
, &stmtInfo
);
6540 JS_ASSERT(blockid
<= pn
->pn_blockid
);
6541 JS_ASSERT(blockid
< tc
->blockidGen
);
6542 JS_ASSERT(tc
->bodyid
< blockid
);
6543 pn
->pn_blockid
= stmtInfo
.blockid
= blockid
;
6544 JS_ASSERT(adjust
< blockid
);
6545 adjust
= blockid
- adjust
;
6550 CompExprTransplanter
transplanter(kid
, tc
, type
== TOK_SEMI
, adjust
);
6551 transplanter
.transplant(kid
);
6555 data
.binder
= BindLet
;
6556 data
.let
.overflow
= JSMSG_ARRAY_INIT_TOO_BIG
;
6560 * FOR node is binary, left is loop control and right is body. Use
6561 * index to count each block-local let-variable on the left-hand side
6564 pn2
= BinaryNode::create(tc
);
6568 pn2
->pn_op
= JSOP_ITER
;
6569 pn2
->pn_iflags
= JSITER_ENUMERATE
;
6570 if (tokenStream
.matchToken(TOK_NAME
)) {
6571 if (tokenStream
.currentToken().t_atom
== context
->runtime
->atomState
.eachAtom
)
6572 pn2
->pn_iflags
|= JSITER_FOREACH
;
6574 tokenStream
.ungetToken();
6576 MUST_MATCH_TOKEN(TOK_LP
, JSMSG_PAREN_AFTER_FOR
);
6579 tt
= tokenStream
.getToken();
6581 #if JS_HAS_DESTRUCTURING
6584 tc
->flags
|= TCF_DECL_DESTRUCTURING
;
6585 pn3
= primaryExpr(tt
, JS_FALSE
);
6586 tc
->flags
&= ~TCF_DECL_DESTRUCTURING
;
6593 atom
= tokenStream
.currentToken().t_atom
;
6596 * Create a name node with pn_op JSOP_NAME. We can't set pn_op to
6597 * JSOP_GETLOCAL here, because we don't yet know the block's depth
6598 * in the operand stack frame. The code generator computes that,
6599 * and it tries to bind all names to slots, so we must let it do
6602 pn3
= NewBindingNode(atom
, tc
, true);
6608 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_NO_VARIABLE_NAME
);
6614 MUST_MATCH_TOKEN(TOK_IN
, JSMSG_IN_AFTER_FOR_NAME
);
6615 JSParseNode
*pn4
= expr();
6618 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_AFTER_FOR_CTRL
);
6621 #if JS_HAS_DESTRUCTURING
6624 if (!CheckDestructuring(context
, &data
, pn3
, NULL
, tc
))
6627 if (JSVERSION_NUMBER(context
) == JSVERSION_1_7
) {
6628 /* Destructuring requires [key, value] enumeration in JS1.7. */
6629 if (pn3
->pn_type
!= TOK_RB
|| pn3
->pn_count
!= 2) {
6630 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_FOR_LEFTSIDE
);
6634 JS_ASSERT(pn2
->pn_op
== JSOP_ITER
);
6635 JS_ASSERT(pn2
->pn_iflags
& JSITER_ENUMERATE
);
6636 if (!(pn2
->pn_iflags
& JSITER_FOREACH
))
6637 pn2
->pn_iflags
|= JSITER_FOREACH
| JSITER_KEYVALUE
;
6644 if (!data
.binder(context
, &data
, atom
, tc
))
6651 pn2
->pn_left
= JSParseNode::newBinaryOrAppend(TOK_IN
, JSOP_NOP
, pn3
, pn4
, tc
);
6655 pnp
= &pn2
->pn_right
;
6656 } while (tokenStream
.matchToken(TOK_FOR
));
6658 if (tokenStream
.matchToken(TOK_IF
)) {
6659 pn2
= TernaryNode::create(tc
);
6662 pn2
->pn_kid1
= condition();
6666 pnp
= &pn2
->pn_kid2
;
6669 pn2
= UnaryNode::create(tc
);
6672 pn2
->pn_type
= type
;
6681 #if JS_HAS_GENERATOR_EXPRS
6684 * Starting from a |for| keyword after an expression, parse the comprehension
6685 * tail completing this generator expression. Wrap the expression at kid in a
6686 * generator function that is immediately called to evaluate to the generator
6687 * iterator that is the value of this generator expression.
6689 * Callers pass a blank unary node via pn, which generatorExpr fills in as the
6690 * yield expression, which ComprehensionTail in turn wraps in a TOK_SEMI-type
6691 * expression-statement node that constitutes the body of the |for| loop(s) in
6692 * the generator function.
6694 * Note how unlike Python, we do not evaluate the expression to the right of
6695 * the first |in| in the chain of |for| heads. Instead, a generator expression
6696 * is merely sugar for a generator function expression and its application.
6699 Parser::generatorExpr(JSParseNode
*pn
, JSParseNode
*kid
)
6701 /* Initialize pn, connecting it to kid. */
6702 JS_ASSERT(pn
->pn_arity
== PN_UNARY
);
6703 pn
->pn_type
= TOK_YIELD
;
6704 pn
->pn_op
= JSOP_YIELD
;
6705 pn
->pn_parens
= true;
6706 pn
->pn_pos
= kid
->pn_pos
;
6708 pn
->pn_hidden
= true;
6710 /* Make a new node for the desugared generator function. */
6711 JSParseNode
*genfn
= FunctionNode::create(tc
);
6714 genfn
->pn_type
= TOK_FUNCTION
;
6715 genfn
->pn_op
= JSOP_LAMBDA
;
6716 JS_ASSERT(!genfn
->pn_body
);
6717 genfn
->pn_dflags
= PND_FUNARG
;
6720 JSTreeContext
*outertc
= tc
;
6721 JSTreeContext
gentc(tc
->parser
);
6723 JSFunctionBox
*funbox
= EnterFunction(genfn
, &gentc
);
6728 * We have to dance around a bit to propagate sharp variables from
6729 * outertc to gentc before setting TCF_HAS_SHARPS implicitly by
6730 * propagating all of outertc's TCF_FUN_FLAGS flags. As below, we have
6731 * to be conservative by leaving TCF_HAS_SHARPS set in outertc if we
6732 * do propagate to gentc.
6734 if (outertc
->flags
& TCF_HAS_SHARPS
) {
6735 gentc
.flags
|= TCF_IN_FUNCTION
;
6736 if (!gentc
.ensureSharpSlots())
6741 * We assume conservatively that any deoptimization flag in tc->flags
6742 * besides TCF_FUN_PARAM_ARGUMENTS can come from the kid. So we
6743 * propagate these flags into genfn. For code simplicity we also do
6744 * not detect if the flags were only set in the kid and could be
6745 * removed from tc->flags.
6747 gentc
.flags
|= TCF_FUN_IS_GENERATOR
| TCF_GENEXP_LAMBDA
|
6748 (tc
->flags
& (TCF_FUN_FLAGS
& ~TCF_FUN_PARAM_ARGUMENTS
));
6749 funbox
->tcflags
|= gentc
.flags
;
6750 genfn
->pn_funbox
= funbox
;
6751 genfn
->pn_blockid
= gentc
.bodyid
;
6753 JSParseNode
*body
= comprehensionTail(pn
, outertc
->blockid());
6756 JS_ASSERT(!genfn
->pn_body
);
6757 genfn
->pn_body
= body
;
6758 genfn
->pn_pos
.begin
= body
->pn_pos
.begin
= kid
->pn_pos
.begin
;
6759 genfn
->pn_pos
.end
= body
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
6761 if (!LeaveFunction(genfn
, &gentc
))
6766 * Our result is a call expression that invokes the anonymous generator
6769 JSParseNode
*result
= ListNode::create(tc
);
6772 result
->pn_type
= TOK_LP
;
6773 result
->pn_op
= JSOP_CALL
;
6774 result
->pn_pos
.begin
= genfn
->pn_pos
.begin
;
6775 result
->initList(genfn
);
6779 static const char js_generator_str
[] = "generator";
6781 #endif /* JS_HAS_GENERATOR_EXPRS */
6782 #endif /* JS_HAS_GENERATORS */
6785 Parser::argumentList(JSParseNode
*listNode
)
6787 if (tokenStream
.matchToken(TOK_RP
, TSF_OPERAND
))
6791 JSParseNode
*argNode
= assignExpr();
6794 #if JS_HAS_GENERATORS
6795 if (argNode
->pn_type
== TOK_YIELD
&&
6796 !argNode
->pn_parens
&&
6797 tokenStream
.peekToken() == TOK_COMMA
) {
6798 reportErrorNumber(argNode
, JSREPORT_ERROR
, JSMSG_BAD_GENERATOR_SYNTAX
, js_yield_str
);
6802 #if JS_HAS_GENERATOR_EXPRS
6803 if (tokenStream
.matchToken(TOK_FOR
)) {
6804 JSParseNode
*pn
= UnaryNode::create(tc
);
6807 argNode
= generatorExpr(pn
, argNode
);
6810 if (listNode
->pn_count
> 1 ||
6811 tokenStream
.peekToken() == TOK_COMMA
) {
6812 reportErrorNumber(argNode
, JSREPORT_ERROR
, JSMSG_BAD_GENERATOR_SYNTAX
,
6818 listNode
->append(argNode
);
6819 } while (tokenStream
.matchToken(TOK_COMMA
));
6821 if (tokenStream
.getToken() != TOK_RP
) {
6822 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_PAREN_AFTER_ARGS
);
6828 /* Check for an immediately-applied (new'ed) lambda and clear PND_FUNARG. */
6829 static JSParseNode
*
6830 CheckForImmediatelyAppliedLambda(JSParseNode
*pn
)
6832 if (pn
->pn_type
== TOK_FUNCTION
) {
6833 JS_ASSERT(pn
->pn_arity
== PN_FUNC
);
6835 JSFunctionBox
*funbox
= pn
->pn_funbox
;
6836 JS_ASSERT(((JSFunction
*) funbox
->object
)->flags
& JSFUN_LAMBDA
);
6837 if (!(funbox
->tcflags
& (TCF_FUN_USES_ARGUMENTS
| TCF_FUN_USES_OWN_NAME
)))
6838 pn
->pn_dflags
&= ~PND_FUNARG
;
6844 Parser::memberExpr(JSBool allowCallSyntax
)
6846 JSParseNode
*pn
, *pn2
, *pn3
;
6848 JS_CHECK_RECURSION(context
, return NULL
);
6850 /* Check for new expression first. */
6851 TokenKind tt
= tokenStream
.getToken(TSF_OPERAND
);
6852 if (tt
== TOK_NEW
) {
6853 pn
= ListNode::create(tc
);
6856 pn2
= memberExpr(JS_FALSE
);
6859 pn2
= CheckForImmediatelyAppliedLambda(pn2
);
6860 pn
->pn_op
= JSOP_NEW
;
6862 pn
->pn_pos
.begin
= pn2
->pn_pos
.begin
;
6864 if (tokenStream
.matchToken(TOK_LP
) && !argumentList(pn
))
6866 if (pn
->pn_count
> ARGC_LIMIT
) {
6867 JS_ReportErrorNumber(context
, js_GetErrorMessage
, NULL
,
6868 JSMSG_TOO_MANY_CON_ARGS
);
6871 pn
->pn_pos
.end
= pn
->last()->pn_pos
.end
;
6873 pn
= primaryExpr(tt
, JS_FALSE
);
6877 if (pn
->pn_type
== TOK_ANYNAME
||
6878 pn
->pn_type
== TOK_AT
||
6879 pn
->pn_type
== TOK_DBLCOLON
) {
6880 pn2
= NewOrRecycledNode(tc
);
6883 pn2
->pn_type
= TOK_UNARYOP
;
6884 pn2
->pn_pos
= pn
->pn_pos
;
6885 pn2
->pn_op
= JSOP_XMLNAME
;
6886 pn2
->pn_arity
= PN_UNARY
;
6887 pn2
->pn_parens
= false;
6893 while ((tt
= tokenStream
.getToken()) > TOK_EOF
) {
6894 if (tt
== TOK_DOT
) {
6895 pn2
= NameNode::create(NULL
, tc
);
6898 #if JS_HAS_XML_SUPPORT
6899 tt
= tokenStream
.getToken(TSF_OPERAND
| TSF_KEYWORD_IS_NAME
);
6900 pn3
= primaryExpr(tt
, JS_TRUE
);
6904 /* Check both tt and pn_type, to distinguish |x.(y)| and |x.y::z| from |x.y|. */
6905 if (tt
== TOK_NAME
&& pn3
->pn_type
== TOK_NAME
) {
6906 pn2
->pn_op
= JSOP_GETPROP
;
6908 pn2
->pn_atom
= pn3
->pn_atom
;
6909 RecycleTree(pn3
, tc
);
6912 pn2
->pn_type
= TOK_FILTER
;
6913 pn2
->pn_op
= JSOP_FILTER
;
6915 /* A filtering predicate is like a with statement. */
6916 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
6917 } else if (TokenKindIsXML(PN_TYPE(pn3
))) {
6918 pn2
->pn_type
= TOK_LB
;
6919 pn2
->pn_op
= JSOP_GETELEM
;
6921 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_NAME_AFTER_DOT
);
6924 pn2
->pn_arity
= PN_BINARY
;
6926 pn2
->pn_right
= pn3
;
6929 MUST_MATCH_TOKEN_WITH_FLAGS(TOK_NAME
, JSMSG_NAME_AFTER_DOT
, TSF_KEYWORD_IS_NAME
);
6930 pn2
->pn_op
= JSOP_GETPROP
;
6932 pn2
->pn_atom
= tokenStream
.currentToken().t_atom
;
6934 pn2
->pn_pos
.begin
= pn
->pn_pos
.begin
;
6935 pn2
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
6936 #if JS_HAS_XML_SUPPORT
6937 } else if (tt
== TOK_DBLDOT
) {
6938 pn2
= BinaryNode::create(tc
);
6941 tt
= tokenStream
.getToken(TSF_OPERAND
| TSF_KEYWORD_IS_NAME
);
6942 pn3
= primaryExpr(tt
, JS_TRUE
);
6946 if (tt
== TOK_NAME
&& !pn3
->pn_parens
) {
6947 pn3
->pn_type
= TOK_STRING
;
6948 pn3
->pn_arity
= PN_NULLARY
;
6949 pn3
->pn_op
= JSOP_QNAMEPART
;
6950 } else if (!TokenKindIsXML(tt
)) {
6951 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_NAME_AFTER_DOT
);
6954 pn2
->pn_op
= JSOP_DESCENDANTS
;
6956 pn2
->pn_right
= pn3
;
6957 pn2
->pn_pos
.begin
= pn
->pn_pos
.begin
;
6958 pn2
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
6960 } else if (tt
== TOK_LB
) {
6961 pn2
= BinaryNode::create(tc
);
6968 MUST_MATCH_TOKEN(TOK_RB
, JSMSG_BRACKET_IN_INDEX
);
6969 pn2
->pn_pos
.begin
= pn
->pn_pos
.begin
;
6970 pn2
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
6973 * Optimize o['p'] to o.p by rewriting pn2, but avoid rewriting
6974 * o['0'] to use JSOP_GETPROP, to keep fast indexing disjoint in
6975 * the interpreter from fast property access. However, if the
6976 * bracketed string is a uint32, we rewrite pn3 to be a number
6977 * instead of a string.
6980 if (pn3
->pn_type
== TOK_STRING
) {
6983 if (!js_IdIsIndex(ATOM_TO_JSID(pn3
->pn_atom
), &index
)) {
6984 pn2
->pn_type
= TOK_DOT
;
6985 pn2
->pn_op
= JSOP_GETPROP
;
6986 pn2
->pn_arity
= PN_NAME
;
6988 pn2
->pn_atom
= pn3
->pn_atom
;
6991 pn3
->pn_type
= TOK_NUMBER
;
6992 pn3
->pn_op
= JSOP_DOUBLE
;
6993 pn3
->pn_dval
= index
;
6995 pn2
->pn_op
= JSOP_GETELEM
;
6997 pn2
->pn_right
= pn3
;
6999 } else if (allowCallSyntax
&& tt
== TOK_LP
) {
7000 pn2
= ListNode::create(tc
);
7003 pn2
->pn_op
= JSOP_CALL
;
7005 pn
= CheckForImmediatelyAppliedLambda(pn
);
7006 if (pn
->pn_op
== JSOP_NAME
) {
7007 if (pn
->pn_atom
== context
->runtime
->atomState
.evalAtom
) {
7008 /* Select JSOP_EVAL and flag tc as heavyweight. */
7009 pn2
->pn_op
= JSOP_EVAL
;
7010 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
7012 } else if (pn
->pn_op
== JSOP_GETPROP
) {
7013 if (pn
->pn_atom
== context
->runtime
->atomState
.applyAtom
||
7014 pn
->pn_atom
== context
->runtime
->atomState
.callAtom
) {
7015 /* Select JSOP_APPLY given foo.apply(...). */
7016 pn2
->pn_op
= JSOP_APPLY
;
7021 pn2
->pn_pos
.begin
= pn
->pn_pos
.begin
;
7023 if (!argumentList(pn2
))
7025 if (pn2
->pn_count
> ARGC_LIMIT
) {
7026 JS_ReportErrorNumber(context
, js_GetErrorMessage
, NULL
,
7027 JSMSG_TOO_MANY_FUN_ARGS
);
7030 pn2
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
7032 tokenStream
.ungetToken();
7038 if (tt
== TOK_ERROR
)
7044 Parser::bracketedExpr()
7050 * Always accept the 'in' operator in a parenthesized expression,
7051 * where it's unambiguous, even if we might be parsing the init of a
7054 oldflags
= tc
->flags
;
7055 tc
->flags
&= ~TCF_IN_FOR_INIT
;
7057 tc
->flags
= oldflags
| (tc
->flags
& TCF_FUN_FLAGS
);
7061 #if JS_HAS_XML_SUPPORT
7064 Parser::endBracketedExpr()
7068 pn
= bracketedExpr();
7072 MUST_MATCH_TOKEN(TOK_RB
, JSMSG_BRACKET_AFTER_ATTR_EXPR
);
7077 * From the ECMA-357 grammar in 11.1.1 and 11.1.2:
7079 * AttributeIdentifier:
7080 * @ PropertySelector
7081 * @ QualifiedIdentifier
7088 * QualifiedIdentifier:
7089 * PropertySelector :: PropertySelector
7090 * PropertySelector :: [ Expression ]
7092 * We adapt AttributeIdentifier and QualifiedIdentier to be LL(1), like so:
7094 * AttributeIdentifier:
7095 * @ QualifiedIdentifier
7102 * QualifiedIdentifier:
7103 * PropertySelector :: PropertySelector
7104 * PropertySelector :: [ Expression ]
7107 * As PrimaryExpression: Identifier is in ECMA-262 and we want the semantics
7108 * for that rule to result in a name node, but ECMA-357 extends the grammar
7109 * to include PrimaryExpression: QualifiedIdentifier, we must factor further:
7111 * QualifiedIdentifier:
7112 * PropertySelector QualifiedSuffix
7115 * :: PropertySelector
7119 * And use this production instead of PrimaryExpression: QualifiedIdentifier:
7121 * PrimaryExpression:
7122 * Identifier QualifiedSuffix
7124 * We hoist the :: match into callers of QualifiedSuffix, in order to tweak
7125 * PropertySelector vs. Identifier pn_arity, pn_op, and other members.
7128 Parser::propertySelector()
7132 pn
= NullaryNode::create(tc
);
7135 if (pn
->pn_type
== TOK_STAR
) {
7136 pn
->pn_type
= TOK_ANYNAME
;
7137 pn
->pn_op
= JSOP_ANYNAME
;
7138 pn
->pn_atom
= context
->runtime
->atomState
.starAtom
;
7140 JS_ASSERT(pn
->pn_type
== TOK_NAME
);
7141 pn
->pn_op
= JSOP_QNAMEPART
;
7142 pn
->pn_arity
= PN_NAME
;
7143 pn
->pn_atom
= tokenStream
.currentToken().t_atom
;
7144 pn
->pn_cookie
= FREE_UPVAR_COOKIE
;
7150 Parser::qualifiedSuffix(JSParseNode
*pn
)
7152 JSParseNode
*pn2
, *pn3
;
7155 JS_ASSERT(tokenStream
.currentToken().type
== TOK_DBLCOLON
);
7156 pn2
= NameNode::create(NULL
, tc
);
7160 /* Left operand of :: must be evaluated if it is an identifier. */
7161 if (pn
->pn_op
== JSOP_QNAMEPART
)
7162 pn
->pn_op
= JSOP_NAME
;
7164 tt
= tokenStream
.getToken(TSF_KEYWORD_IS_NAME
);
7165 if (tt
== TOK_STAR
|| tt
== TOK_NAME
) {
7166 /* Inline and specialize propertySelector for JSOP_QNAMECONST. */
7167 pn2
->pn_op
= JSOP_QNAMECONST
;
7168 pn2
->pn_pos
.begin
= pn
->pn_pos
.begin
;
7169 pn2
->pn_atom
= (tt
== TOK_STAR
)
7170 ? context
->runtime
->atomState
.starAtom
7171 : tokenStream
.currentToken().t_atom
;
7173 pn2
->pn_cookie
= FREE_UPVAR_COOKIE
;
7178 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_SYNTAX_ERROR
);
7181 pn3
= endBracketedExpr();
7185 pn2
->pn_op
= JSOP_QNAME
;
7186 pn2
->pn_arity
= PN_BINARY
;
7187 pn2
->pn_pos
.begin
= pn
->pn_pos
.begin
;
7188 pn2
->pn_pos
.end
= pn3
->pn_pos
.end
;
7190 pn2
->pn_right
= pn3
;
7195 Parser::qualifiedIdentifier()
7199 pn
= propertySelector();
7202 if (tokenStream
.matchToken(TOK_DBLCOLON
)) {
7203 /* Hack for bug 496316. Slowing down E4X won't make it go away, alas. */
7204 tc
->flags
|= TCF_FUN_HEAVYWEIGHT
;
7205 pn
= qualifiedSuffix(pn
);
7211 Parser::attributeIdentifier()
7213 JSParseNode
*pn
, *pn2
;
7216 JS_ASSERT(tokenStream
.currentToken().type
== TOK_AT
);
7217 pn
= UnaryNode::create(tc
);
7220 pn
->pn_op
= JSOP_TOATTRNAME
;
7221 tt
= tokenStream
.getToken(TSF_KEYWORD_IS_NAME
);
7222 if (tt
== TOK_STAR
|| tt
== TOK_NAME
) {
7223 pn2
= qualifiedIdentifier();
7224 } else if (tt
== TOK_LB
) {
7225 pn2
= endBracketedExpr();
7227 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_SYNTAX_ERROR
);
7237 * Make a TOK_LC unary node whose pn_kid is an expression.
7240 Parser::xmlExpr(JSBool inTag
)
7242 JSParseNode
*pn
, *pn2
;
7244 JS_ASSERT(tokenStream
.currentToken().type
== TOK_LC
);
7245 pn
= UnaryNode::create(tc
);
7250 * Turn off XML tag mode. We save the old value of the flag because it may
7251 * already be off: XMLExpr is called both from within a tag, and from
7252 * within text contained in an element, but outside of any start, end, or
7255 bool oldflag
= tokenStream
.isXMLTagMode();
7256 tokenStream
.setXMLTagMode(false);
7261 MUST_MATCH_TOKEN(TOK_RC
, JSMSG_CURLY_IN_XML_EXPR
);
7262 tokenStream
.setXMLTagMode(oldflag
);
7264 pn
->pn_op
= inTag
? JSOP_XMLTAGEXPR
: JSOP_XMLELTEXPR
;
7269 * Make a terminal node for one of TOK_XMLNAME, TOK_XMLATTR, TOK_XMLSPACE,
7270 * TOK_XMLTEXT, TOK_XMLCDATA, TOK_XMLCOMMENT, or TOK_XMLPI. When converting
7271 * parse tree to XML, we preserve a TOK_XMLSPACE node only if it's the sole
7272 * child of a container tag.
7275 Parser::xmlAtomNode()
7277 JSParseNode
*pn
= NullaryNode::create(tc
);
7280 const Token
&tok
= tokenStream
.currentToken();
7281 pn
->pn_op
= tok
.t_op
;
7282 pn
->pn_atom
= tok
.t_atom
;
7283 if (tok
.type
== TOK_XMLPI
)
7284 pn
->pn_atom2
= tok
.t_atom2
;
7289 * Parse the productions:
7292 * XMLName XMLNameExpr?
7293 * { Expr } XMLNameExpr?
7295 * Return a PN_LIST, PN_UNARY, or PN_NULLARY according as XMLNameExpr produces
7296 * a list of names and/or expressions, a single expression, or a single name.
7297 * If PN_LIST or PN_NULLARY, pn_type will be TOK_XMLNAME; if PN_UNARY, pn_type
7301 Parser::xmlNameExpr()
7303 JSParseNode
*pn
, *pn2
, *list
;
7308 tt
= tokenStream
.currentToken().type
;
7310 pn2
= xmlExpr(JS_TRUE
);
7314 JS_ASSERT(tt
== TOK_XMLNAME
);
7315 pn2
= xmlAtomNode();
7324 list
= ListNode::create(tc
);
7327 list
->pn_type
= TOK_XMLNAME
;
7328 list
->pn_pos
.begin
= pn
->pn_pos
.begin
;
7330 list
->pn_xflags
= PNX_CANTFOLD
;
7333 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
7336 } while ((tt
= tokenStream
.getToken()) == TOK_XMLNAME
|| tt
== TOK_LC
);
7338 tokenStream
.ungetToken();
7343 * Macro to test whether an XMLNameExpr or XMLTagContent node can be folded
7344 * at compile time into a JSXML tree.
7346 #define XML_FOLDABLE(pn) ((pn)->pn_arity == PN_LIST \
7347 ? ((pn)->pn_xflags & PNX_CANTFOLD) == 0 \
7348 : (pn)->pn_type != TOK_LC)
7351 * Parse the productions:
7355 * XMLTagContent S XMLNameExpr S? = S? XMLAttr
7356 * XMLTagContent S XMLNameExpr S? = S? { Expr }
7358 * Return a PN_LIST, PN_UNARY, or PN_NULLARY according to how XMLTagContent
7359 * produces a list of name and attribute values and/or braced expressions, a
7360 * single expression, or a single name.
7362 * If PN_LIST or PN_NULLARY, pn_type will be TOK_XMLNAME for the case where
7363 * XMLTagContent: XMLNameExpr. If pn_type is not TOK_XMLNAME but pn_arity is
7364 * PN_LIST, pn_type will be tagtype. If PN_UNARY, pn_type will be TOK_LC and
7365 * we parsed exactly one expression.
7368 Parser::xmlTagContent(TokenKind tagtype
, JSAtom
**namep
)
7370 JSParseNode
*pn
, *pn2
, *list
;
7376 *namep
= (pn
->pn_arity
== PN_NULLARY
) ? pn
->pn_atom
: NULL
;
7379 while (tokenStream
.matchToken(TOK_XMLSPACE
)) {
7380 tt
= tokenStream
.getToken();
7381 if (tt
!= TOK_XMLNAME
&& tt
!= TOK_LC
) {
7382 tokenStream
.ungetToken();
7386 pn2
= xmlNameExpr();
7390 list
= ListNode::create(tc
);
7393 list
->pn_type
= tagtype
;
7394 list
->pn_pos
.begin
= pn
->pn_pos
.begin
;
7399 if (!XML_FOLDABLE(pn2
))
7400 pn
->pn_xflags
|= PNX_CANTFOLD
;
7402 tokenStream
.matchToken(TOK_XMLSPACE
);
7403 MUST_MATCH_TOKEN(TOK_ASSIGN
, JSMSG_NO_ASSIGN_IN_XML_ATTR
);
7404 tokenStream
.matchToken(TOK_XMLSPACE
);
7406 tt
= tokenStream
.getToken();
7407 if (tt
== TOK_XMLATTR
) {
7408 pn2
= xmlAtomNode();
7409 } else if (tt
== TOK_LC
) {
7410 pn2
= xmlExpr(JS_TRUE
);
7411 pn
->pn_xflags
|= PNX_CANTFOLD
;
7413 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_XML_ATTR_VALUE
);
7418 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
7425 #define XML_CHECK_FOR_ERROR_AND_EOF(tt,result) \
7427 if ((tt) <= TOK_EOF) { \
7428 if ((tt) == TOK_EOF) { \
7429 reportErrorNumber(NULL, JSREPORT_ERROR, JSMSG_END_OF_XML_SOURCE); \
7436 * Consume XML element tag content, including the TOK_XMLETAGO (</) sequence
7437 * that opens the end tag for the container.
7440 Parser::xmlElementContent(JSParseNode
*pn
)
7442 tokenStream
.setXMLTagMode(false);
7444 TokenKind tt
= tokenStream
.getToken(TSF_XMLTEXTMODE
);
7445 XML_CHECK_FOR_ERROR_AND_EOF(tt
, JS_FALSE
);
7447 JS_ASSERT(tt
== TOK_XMLSPACE
|| tt
== TOK_XMLTEXT
);
7448 JSAtom
*textAtom
= tokenStream
.currentToken().t_atom
;
7450 /* Non-zero-length XML text scanned. */
7451 JSParseNode
*pn2
= xmlAtomNode();
7454 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
7458 tt
= tokenStream
.getToken(TSF_OPERAND
);
7459 XML_CHECK_FOR_ERROR_AND_EOF(tt
, JS_FALSE
);
7460 if (tt
== TOK_XMLETAGO
)
7465 pn2
= xmlExpr(JS_FALSE
);
7466 pn
->pn_xflags
|= PNX_CANTFOLD
;
7467 } else if (tt
== TOK_XMLSTAGO
) {
7468 pn2
= xmlElementOrList(JS_FALSE
);
7470 pn2
->pn_xflags
&= ~PNX_XMLROOT
;
7471 pn
->pn_xflags
|= pn2
->pn_xflags
;
7474 JS_ASSERT(tt
== TOK_XMLCDATA
|| tt
== TOK_XMLCOMMENT
||
7476 pn2
= xmlAtomNode();
7480 pn
->pn_pos
.end
= pn2
->pn_pos
.end
;
7483 tokenStream
.setXMLTagMode(true);
7485 JS_ASSERT(tokenStream
.currentToken().type
== TOK_XMLETAGO
);
7490 * Return a PN_LIST node containing an XML or XMLList Initialiser.
7493 Parser::xmlElementOrList(JSBool allowList
)
7495 JSParseNode
*pn
, *pn2
, *list
;
7497 JSAtom
*startAtom
, *endAtom
;
7499 JS_CHECK_RECURSION(context
, return NULL
);
7501 JS_ASSERT(tokenStream
.currentToken().type
== TOK_XMLSTAGO
);
7502 pn
= ListNode::create(tc
);
7506 tokenStream
.setXMLTagMode(true);
7507 tt
= tokenStream
.getToken();
7508 if (tt
== TOK_ERROR
)
7511 if (tt
== TOK_XMLNAME
|| tt
== TOK_LC
) {
7513 * XMLElement. Append the tag and its contents, if any, to pn.
7515 pn2
= xmlTagContent(TOK_XMLSTAGO
, &startAtom
);
7518 tokenStream
.matchToken(TOK_XMLSPACE
);
7520 tt
= tokenStream
.getToken();
7521 if (tt
== TOK_XMLPTAGC
) {
7522 /* Point tag (/>): recycle pn if pn2 is a list of tag contents. */
7523 if (pn2
->pn_type
== TOK_XMLSTAGO
) {
7525 RecycleTree(pn
, tc
);
7528 JS_ASSERT(pn2
->pn_type
== TOK_XMLNAME
||
7529 pn2
->pn_type
== TOK_LC
);
7531 if (!XML_FOLDABLE(pn2
))
7532 pn
->pn_xflags
|= PNX_CANTFOLD
;
7534 pn
->pn_type
= TOK_XMLPTAGC
;
7535 pn
->pn_xflags
|= PNX_XMLROOT
;
7537 /* We had better have a tag-close (>) at this point. */
7538 if (tt
!= TOK_XMLTAGC
) {
7539 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_XML_TAG_SYNTAX
);
7542 pn2
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
7544 /* Make sure pn2 is a TOK_XMLSTAGO list containing tag contents. */
7545 if (pn2
->pn_type
!= TOK_XMLSTAGO
) {
7547 if (!XML_FOLDABLE(pn2
))
7548 pn
->pn_xflags
|= PNX_CANTFOLD
;
7550 pn
= ListNode::create(tc
);
7555 /* Now make pn a nominal-root TOK_XMLELEM list containing pn2. */
7556 pn
->pn_type
= TOK_XMLELEM
;
7557 pn
->pn_pos
.begin
= pn2
->pn_pos
.begin
;
7559 if (!XML_FOLDABLE(pn2
))
7560 pn
->pn_xflags
|= PNX_CANTFOLD
;
7561 pn
->pn_xflags
|= PNX_XMLROOT
;
7563 /* Get element contents and delimiting end-tag-open sequence. */
7564 if (!xmlElementContent(pn
))
7567 tt
= tokenStream
.getToken();
7568 XML_CHECK_FOR_ERROR_AND_EOF(tt
, NULL
);
7569 if (tt
!= TOK_XMLNAME
&& tt
!= TOK_LC
) {
7570 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_XML_TAG_SYNTAX
);
7574 /* Parse end tag; check mismatch at compile-time if we can. */
7575 pn2
= xmlTagContent(TOK_XMLETAGO
, &endAtom
);
7578 if (pn2
->pn_type
== TOK_XMLETAGO
) {
7579 /* Oops, end tag has attributes! */
7580 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_XML_TAG_SYNTAX
);
7583 if (endAtom
&& startAtom
&& endAtom
!= startAtom
) {
7584 JSString
*str
= ATOM_TO_STRING(startAtom
);
7586 /* End vs. start tag name mismatch: point to the tag name. */
7587 reportErrorNumber(pn2
, JSREPORT_UC
| JSREPORT_ERROR
, JSMSG_XML_TAG_NAME_MISMATCH
,
7592 /* Make a TOK_XMLETAGO list with pn2 as its single child. */
7593 JS_ASSERT(pn2
->pn_type
== TOK_XMLNAME
|| pn2
->pn_type
== TOK_LC
);
7594 list
= ListNode::create(tc
);
7597 list
->pn_type
= TOK_XMLETAGO
;
7598 list
->initList(pn2
);
7600 if (!XML_FOLDABLE(pn2
)) {
7601 list
->pn_xflags
|= PNX_CANTFOLD
;
7602 pn
->pn_xflags
|= PNX_CANTFOLD
;
7605 tokenStream
.matchToken(TOK_XMLSPACE
);
7606 MUST_MATCH_TOKEN(TOK_XMLTAGC
, JSMSG_BAD_XML_TAG_SYNTAX
);
7609 /* Set pn_op now that pn has been updated to its final value. */
7610 pn
->pn_op
= JSOP_TOXML
;
7611 } else if (allowList
&& tt
== TOK_XMLTAGC
) {
7612 /* XMLList Initialiser. */
7613 pn
->pn_type
= TOK_XMLLIST
;
7614 pn
->pn_op
= JSOP_TOXMLLIST
;
7616 pn
->pn_xflags
|= PNX_XMLROOT
;
7617 if (!xmlElementContent(pn
))
7620 MUST_MATCH_TOKEN(TOK_XMLTAGC
, JSMSG_BAD_XML_LIST_SYNTAX
);
7622 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_XML_NAME_SYNTAX
);
7625 tokenStream
.setXMLTagMode(false);
7627 pn
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
7632 Parser::xmlElementOrListRoot(JSBool allowList
)
7638 * Force XML support to be enabled so that comments and CDATA literals
7639 * are recognized, instead of <! followed by -- starting an HTML comment
7640 * to end of line (used in script tags to hide content from old browsers
7641 * that don't recognize <script>).
7643 oldopts
= JS_SetOptions(context
, context
->options
| JSOPTION_XML
);
7644 pn
= xmlElementOrList(allowList
);
7645 JS_SetOptions(context
, oldopts
);
7650 Parser::parseXMLText(JSObject
*chain
, bool allowList
)
7653 * Push a compiler frame if we have no frames, or if the top frame is a
7654 * lightweight function activation, or if its scope chain doesn't match
7655 * the one passed to us.
7657 JSTreeContext
xmltc(this);
7658 xmltc
.scopeChain
= chain
;
7660 /* Set XML-only mode to turn off special treatment of {expr} in XML. */
7661 tokenStream
.setXMLOnlyMode();
7662 TokenKind tt
= tokenStream
.getToken(TSF_OPERAND
);
7665 if (tt
!= TOK_XMLSTAGO
) {
7666 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_XML_MARKUP
);
7669 pn
= xmlElementOrListRoot(allowList
);
7671 tokenStream
.setXMLOnlyMode(false);
7676 #endif /* JS_HAS_XMLSUPPORT */
7678 #if JS_HAS_BLOCK_SCOPE
7680 * Check whether blockid is an active scoping statement in tc. This code is
7681 * necessary to qualify tc->decls.lookup() hits in primaryExpr's TOK_NAME case
7682 * (below) where the hits come from Scheme-ish let bindings in for loop heads
7683 * and let blocks and expressions (not let declarations).
7685 * Unlike let declarations ("let as the new var"), which is a kind of letrec
7686 * due to hoisting, let in a for loop head, let block, or let expression acts
7687 * like Scheme's let: initializers are evaluated without the new let bindings
7690 * Name binding analysis is eager with fixups, rather than multi-pass, and let
7691 * bindings push on the front of the tc->decls JSAtomList (either the singular
7692 * list or on a hash chain -- see JSAtomList::AddHow) in order to shadow outer
7693 * scope bindings of the same name.
7695 * This simplifies binding lookup code at the price of a linear search here,
7696 * but only if code uses let (var predominates), and even then this function's
7697 * loop iterates more than once only in crazy cases.
7700 BlockIdInScope(uintN blockid
, JSTreeContext
*tc
)
7702 if (blockid
> tc
->blockid())
7704 for (JSStmtInfo
*stmt
= tc
->topScopeStmt
; stmt
; stmt
= stmt
->downScope
) {
7705 if (stmt
->blockid
== blockid
)
7713 Parser::primaryExpr(TokenKind tt
, JSBool afterDot
)
7715 JSParseNode
*pn
, *pn2
, *pn3
;
7718 JS_CHECK_RECURSION(context
, return NULL
);
7722 #if JS_HAS_XML_SUPPORT
7723 if (tokenStream
.matchToken(TOK_DBLCOLON
, TSF_KEYWORD_IS_NAME
)) {
7724 pn2
= NullaryNode::create(tc
);
7727 pn2
->pn_type
= TOK_FUNCTION
;
7728 pn
= qualifiedSuffix(pn2
);
7734 pn
= functionExpr();
7744 pn
= ListNode::create(tc
);
7747 pn
->pn_type
= TOK_RB
;
7748 pn
->pn_op
= JSOP_NEWINIT
;
7751 #if JS_HAS_GENERATORS
7752 pn
->pn_blockid
= tc
->blockidGen
;
7755 matched
= tokenStream
.matchToken(TOK_RB
, TSF_OPERAND
);
7757 for (index
= 0; ; index
++) {
7758 if (index
== JS_ARGS_LENGTH_MAX
) {
7759 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_ARRAY_INIT_TOO_BIG
);
7763 tt
= tokenStream
.peekToken(TSF_OPERAND
);
7765 pn
->pn_xflags
|= PNX_ENDCOMMA
;
7769 if (tt
== TOK_COMMA
) {
7770 /* So CURRENT_TOKEN gets TOK_COMMA and not TOK_LB. */
7771 tokenStream
.matchToken(TOK_COMMA
);
7772 pn2
= NullaryNode::create(tc
);
7773 pn
->pn_xflags
|= PNX_HOLEY
;
7781 if (tt
!= TOK_COMMA
) {
7782 /* If we didn't already match TOK_COMMA in above case. */
7783 if (!tokenStream
.matchToken(TOK_COMMA
))
7788 #if JS_HAS_GENERATORS
7790 * At this point, (index == 0 && pn->pn_count != 0) implies one
7791 * element initialiser was parsed.
7793 * An array comprehension of the form:
7795 * [i * j for (i in o) for (j in p) if (i != j)]
7797 * translates to roughly the following let expression:
7799 * let (array = new Array, i, j) {
7800 * for (i in o) let {
7808 * where array is a nameless block-local variable. The "roughly"
7809 * means that an implementation may optimize away the array.push.
7810 * An array comprehension opens exactly one block scope, no matter
7811 * how many for heads it contains.
7813 * Each let () {...} or for (let ...) ... compiles to:
7815 * JSOP_ENTERBLOCK <o> ... JSOP_LEAVEBLOCK <n>
7817 * where <o> is a literal object representing the block scope,
7818 * with <n> properties, naming each var declared in the block.
7820 * Each var declaration in a let-block binds a name in <o> at
7821 * compile time, and allocates a slot on the operand stack at
7822 * runtime via JSOP_ENTERBLOCK. A block-local var is accessed
7823 * by the JSOP_GETLOCAL and JSOP_SETLOCAL ops, and iterated with
7824 * JSOP_FORLOCAL. These ops all have an immediate operand, the
7825 * local slot's stack index from fp->spbase.
7827 * The array comprehension iteration step, array.push(i * j) in
7828 * the example above, is done by <i * j>; JSOP_ARRAYCOMP <array>,
7829 * where <array> is the index of array's stack slot.
7831 if (index
== 0 && pn
->pn_count
!= 0 && tokenStream
.matchToken(TOK_FOR
)) {
7832 JSParseNode
*pnexp
, *pntop
;
7834 /* Relabel pn as an array comprehension node. */
7835 pn
->pn_type
= TOK_ARRAYCOMP
;
7838 * Remove the comprehension expression from pn's linked list
7839 * and save it via pnexp. We'll re-install it underneath the
7840 * ARRAYPUSH node after we parse the rest of the comprehension.
7843 JS_ASSERT(pn
->pn_count
== 1 || pn
->pn_count
== 2);
7844 pn
->pn_tail
= (--pn
->pn_count
== 1)
7845 ? &pn
->pn_head
->pn_next
7847 *pn
->pn_tail
= NULL
;
7849 pntop
= comprehensionTail(pnexp
, pn
->pn_blockid
,
7850 TOK_ARRAYPUSH
, JSOP_ARRAYPUSH
);
7855 #endif /* JS_HAS_GENERATORS */
7857 MUST_MATCH_TOKEN(TOK_RB
, JSMSG_BRACKET_AFTER_LIST
);
7859 pn
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
7869 * A map from property names we've seen thus far to bit masks.
7870 * (We use ALE_INDEX/ALE_SET_INDEX). An atom's mask includes
7871 * JSPROP_SETTER if we've seen a setter for it, JSPROP_GETTER
7872 * if we've seen as getter, and both of those if we've just
7873 * seen an ordinary value.
7875 JSAutoAtomList
seen(tc
->parser
);
7877 pn
= ListNode::create(tc
);
7880 pn
->pn_type
= TOK_RC
;
7881 pn
->pn_op
= JSOP_NEWINIT
;
7884 afterComma
= JS_FALSE
;
7887 tt
= tokenStream
.getToken(TSF_KEYWORD_IS_NAME
);
7890 pn3
= NullaryNode::create(tc
);
7893 pn3
->pn_dval
= tokenStream
.currentToken().t_dval
;
7894 if (tc
->needStrictChecks()) {
7895 atom
= js_AtomizeDouble(context
, pn3
->pn_dval
);
7899 atom
= NULL
; /* for the compiler */
7904 atom
= tokenStream
.currentToken().t_atom
;
7905 if (atom
== context
->runtime
->atomState
.getAtom
)
7907 else if (atom
== context
->runtime
->atomState
.setAtom
)
7912 tt
= tokenStream
.getToken(TSF_KEYWORD_IS_NAME
);
7913 if (tt
== TOK_NAME
|| tt
== TOK_STRING
) {
7914 atom
= tokenStream
.currentToken().t_atom
;
7915 pn3
= NameNode::create(atom
, tc
);
7918 } else if (tt
== TOK_NUMBER
) {
7919 pn3
= NullaryNode::create(tc
);
7922 pn3
->pn_dval
= tokenStream
.currentToken().t_dval
;
7923 if (tc
->needStrictChecks()) {
7924 atom
= js_AtomizeDouble(context
, pn3
->pn_dval
);
7928 atom
= NULL
; /* for the compiler */
7931 tokenStream
.ungetToken();
7935 /* We have to fake a 'function' token here. */
7936 tokenStream
.mungeCurrentToken(TOK_FUNCTION
, JSOP_NOP
);
7937 pn2
= functionDef(JSFUN_LAMBDA
, false);
7938 pn2
= JSParseNode::newBinaryOrAppend(TOK_COLON
, op
, pn3
, pn2
, tc
);
7943 atom
= tokenStream
.currentToken().t_atom
;
7944 pn3
= NullaryNode::create(tc
);
7947 pn3
->pn_atom
= atom
;
7952 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_PROP_ID
);
7957 tt
= tokenStream
.getToken();
7958 if (tt
== TOK_COLON
) {
7959 pnval
= assignExpr();
7961 #if JS_HAS_DESTRUCTURING_SHORTHAND
7962 if (tt
!= TOK_COMMA
&& tt
!= TOK_RC
) {
7964 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_COLON_AFTER_ID
);
7966 #if JS_HAS_DESTRUCTURING_SHORTHAND
7970 * Support, e.g., |var {x, y} = o| as destructuring shorthand
7971 * for |var {x: x, y: y} = o|, per proposed JS2/ES4 for JS1.8.
7973 tokenStream
.ungetToken();
7974 pn
->pn_xflags
|= PNX_DESTRUCT
;
7976 if (pnval
->pn_type
== TOK_NAME
) {
7977 pnval
->pn_arity
= PN_NAME
;
7978 ((NameNode
*)pnval
)->initCommon(tc
);
7983 pn2
= JSParseNode::newBinaryOrAppend(TOK_COLON
, op
, pn3
, pnval
, tc
);
7990 * In strict mode code, check for duplicate property names. Treat
7991 * getters and setters as distinct attributes of each property. A
7992 * plain old value conflicts with a getter or a setter.
7994 if (tc
->needStrictChecks()) {
7995 unsigned attributesMask
;
7996 if (op
== JSOP_INITPROP
) {
7997 attributesMask
= JSPROP_GETTER
| JSPROP_SETTER
;
7998 } else if (op
== JSOP_GETTER
) {
7999 attributesMask
= JSPROP_GETTER
;
8000 } else if (op
== JSOP_SETTER
) {
8001 attributesMask
= JSPROP_SETTER
;
8003 JS_NOT_REACHED("bad opcode in object initializer");
8008 * Use only string-valued atoms for detecting duplicate
8009 * properties so that 1 and "1" properly collide.
8011 if (ATOM_IS_DOUBLE(atom
)) {
8012 JSString
*str
= js_NumberToString(context
, pn3
->pn_dval
);
8015 atom
= js_AtomizeString(context
, str
, 0);
8020 JSAtomListElement
*ale
= seen
.lookup(atom
);
8022 if (ALE_INDEX(ale
) & attributesMask
) {
8023 const char *name
= js_AtomToPrintableString(context
, atom
);
8025 !ReportStrictModeError(context
, &tokenStream
, tc
, NULL
,
8026 JSMSG_DUPLICATE_PROPERTY
, name
)) {
8030 ALE_SET_INDEX(ale
, attributesMask
| ALE_INDEX(ale
));
8032 ale
= seen
.add(tc
->parser
, atom
);
8035 ALE_SET_INDEX(ale
, attributesMask
);
8039 tt
= tokenStream
.getToken();
8042 if (tt
!= TOK_COMMA
) {
8043 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_CURLY_AFTER_LIST
);
8046 afterComma
= JS_TRUE
;
8050 pn
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
8054 #if JS_HAS_BLOCK_SCOPE
8056 pn
= letBlock(JS_FALSE
);
8062 #if JS_HAS_SHARP_VARS
8064 pn
= UnaryNode::create(tc
);
8067 pn
->pn_num
= (jsint
) tokenStream
.currentToken().t_dval
;
8068 tt
= tokenStream
.getToken(TSF_OPERAND
);
8069 pn
->pn_kid
= primaryExpr(tt
, JS_FALSE
);
8072 if (PN_TYPE(pn
->pn_kid
) == TOK_USESHARP
||
8073 PN_TYPE(pn
->pn_kid
) == TOK_DEFSHARP
||
8074 PN_TYPE(pn
->pn_kid
) == TOK_STRING
||
8075 PN_TYPE(pn
->pn_kid
) == TOK_NUMBER
||
8076 PN_TYPE(pn
->pn_kid
) == TOK_PRIMARY
) {
8077 reportErrorNumber(pn
->pn_kid
, JSREPORT_ERROR
, JSMSG_BAD_SHARP_VAR_DEF
);
8080 if (!tc
->ensureSharpSlots())
8085 /* Check for forward/dangling references at runtime, to allow eval. */
8086 pn
= NullaryNode::create(tc
);
8089 if (!tc
->ensureSharpSlots())
8091 pn
->pn_num
= (jsint
) tokenStream
.currentToken().t_dval
;
8093 #endif /* JS_HAS_SHARP_VARS */
8099 pn
= parenExpr(NULL
, &genexp
);
8102 pn
->pn_parens
= true;
8104 MUST_MATCH_TOKEN(TOK_RP
, JSMSG_PAREN_IN_PAREN
);
8108 #if JS_HAS_XML_SUPPORT
8110 pn
= qualifiedIdentifier();
8116 pn
= attributeIdentifier();
8122 pn
= xmlElementOrListRoot(JS_TRUE
);
8126 #endif /* JS_HAS_XML_SUPPORT */
8129 #if JS_HAS_SHARP_VARS
8133 #if JS_HAS_XML_SUPPORT
8135 case TOK_XMLCOMMENT
:
8138 pn
= NullaryNode::create(tc
);
8141 pn
->pn_atom
= tokenStream
.currentToken().t_atom
;
8142 #if JS_HAS_XML_SUPPORT
8143 if (tt
== TOK_XMLPI
)
8144 pn
->pn_atom2
= tokenStream
.currentToken().t_atom2
;
8147 pn
->pn_op
= tokenStream
.currentToken().t_op
;
8151 pn
= NameNode::create(tokenStream
.currentToken().t_atom
, tc
);
8154 JS_ASSERT(tokenStream
.currentToken().t_op
== JSOP_NAME
);
8155 pn
->pn_op
= JSOP_NAME
;
8157 if ((tc
->flags
& (TCF_IN_FUNCTION
| TCF_FUN_PARAM_ARGUMENTS
)) == TCF_IN_FUNCTION
&&
8158 pn
->pn_atom
== context
->runtime
->atomState
.argumentsAtom
) {
8160 * Flag arguments usage so we can avoid unsafe optimizations such
8161 * as formal parameter assignment analysis (because of the hated
8162 * feature whereby arguments alias formals). We do this even for
8163 * a reference of the form foo.arguments, which ancient code may
8164 * still use instead of arguments (more hate).
8166 NoteArgumentsUse(tc
);
8169 * Bind early to JSOP_ARGUMENTS to relieve later code from having
8170 * to do this work (new rule for the emitter to count on).
8172 if (!afterDot
&& !(tc
->flags
& TCF_DECL_DESTRUCTURING
) && !tc
->inStatement(STMT_WITH
)) {
8173 pn
->pn_op
= JSOP_ARGUMENTS
;
8174 pn
->pn_dflags
|= PND_BOUND
;
8176 } else if ((!afterDot
8177 #if JS_HAS_XML_SUPPORT
8178 || tokenStream
.peekToken() == TOK_DBLCOLON
8180 ) && !(tc
->flags
& TCF_DECL_DESTRUCTURING
)) {
8181 JSStmtInfo
*stmt
= js_LexicalLookup(tc
, pn
->pn_atom
, NULL
);
8182 if (!stmt
|| stmt
->type
!= STMT_WITH
) {
8185 JSAtomListElement
*ale
= tc
->decls
.lookup(pn
->pn_atom
);
8188 #if JS_HAS_BLOCK_SCOPE
8190 * Skip out-of-scope let bindings along an ALE list or hash
8191 * chain. These can happen due to |let (x = x) x| block and
8192 * expression bindings, where the x on the right of = comes
8193 * from an outer scope. See bug 496532.
8195 while (dn
->isLet() && !BlockIdInScope(dn
->pn_blockid
, tc
)) {
8197 ale
= ALE_NEXT(ale
);
8198 } while (ale
&& ALE_ATOM(ale
) != pn
->pn_atom
);
8209 ale
= tc
->lexdeps
.lookup(pn
->pn_atom
);
8214 * No definition before this use in any lexical scope.
8215 * Add a mapping in tc->lexdeps from pn->pn_atom to a
8216 * new node for the forward-referenced definition. This
8217 * placeholder definition node will be adopted when we
8218 * parse the real defining declaration form, or left as
8219 * a free variable definition if we never see the real
8222 ale
= MakePlaceholder(pn
, tc
);
8228 * In case this is a forward reference to a function,
8229 * we pessimistically set PND_FUNARG if the next token
8230 * is not a left parenthesis.
8232 * If the definition eventually parsed into dn is not a
8233 * function, this flag won't hurt, and if we do parse a
8234 * function with pn's name, then the PND_FUNARG flag is
8235 * necessary for safe context->display-based optimiza-
8236 * tion of the closure's static link.
8238 JS_ASSERT(PN_TYPE(dn
) == TOK_NAME
);
8239 JS_ASSERT(dn
->pn_op
== JSOP_NOP
);
8240 if (tokenStream
.peekToken() != TOK_LP
)
8241 dn
->pn_dflags
|= PND_FUNARG
;
8245 JS_ASSERT(dn
->pn_defn
);
8246 LinkUseToDef(pn
, dn
, tc
);
8248 /* Here we handle the backward function reference case. */
8249 if (tokenStream
.peekToken() != TOK_LP
)
8250 dn
->pn_dflags
|= PND_FUNARG
;
8252 pn
->pn_dflags
|= (dn
->pn_dflags
& PND_FUNARG
);
8256 #if JS_HAS_XML_SUPPORT
8257 if (tokenStream
.matchToken(TOK_DBLCOLON
)) {
8262 * Here primaryExpr is called after . or .. followed by a name
8263 * followed by ::. This is the only case where a keyword after
8264 * . or .. is not treated as a property name.
8266 str
= ATOM_TO_STRING(pn
->pn_atom
);
8267 tt
= js_CheckKeyword(str
->chars(), str
->length());
8268 if (tt
== TOK_FUNCTION
) {
8269 pn
->pn_arity
= PN_NULLARY
;
8270 pn
->pn_type
= TOK_FUNCTION
;
8271 } else if (tt
!= TOK_EOF
) {
8272 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_KEYWORD_NOT_NS
);
8276 pn
= qualifiedSuffix(pn
);
8287 pn
= NullaryNode::create(tc
);
8291 obj
= js_NewRegExpObject(context
, &tokenStream
,
8292 tokenStream
.getTokenbuf().begin(),
8293 tokenStream
.getTokenbuf().length(),
8294 tokenStream
.currentToken().t_reflags
);
8297 if (!tc
->compileAndGo()) {
8302 pn
->pn_objbox
= tc
->parser
->newObjectBox(obj
);
8306 pn
->pn_op
= JSOP_REGEXP
;
8311 pn
= NullaryNode::create(tc
);
8314 pn
->pn_op
= JSOP_DOUBLE
;
8315 pn
->pn_dval
= tokenStream
.currentToken().t_dval
;
8319 pn
= NullaryNode::create(tc
);
8322 pn
->pn_op
= tokenStream
.currentToken().t_op
;
8326 /* The scanner or one of its subroutines reported the error. */
8330 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_SYNTAX_ERROR
);
8337 Parser::parenExpr(JSParseNode
*pn1
, JSBool
*genexp
)
8342 JS_ASSERT(tokenStream
.currentToken().type
== TOK_LP
);
8343 begin
= tokenStream
.currentToken().pos
.begin
;
8347 pn
= bracketedExpr();
8351 #if JS_HAS_GENERATOR_EXPRS
8352 if (tokenStream
.matchToken(TOK_FOR
)) {
8353 if (pn
->pn_type
== TOK_YIELD
&& !pn
->pn_parens
) {
8354 reportErrorNumber(pn
, JSREPORT_ERROR
, JSMSG_BAD_GENERATOR_SYNTAX
, js_yield_str
);
8357 if (pn
->pn_type
== TOK_COMMA
&& !pn
->pn_parens
) {
8358 reportErrorNumber(pn
->last(), JSREPORT_ERROR
, JSMSG_BAD_GENERATOR_SYNTAX
,
8363 pn1
= UnaryNode::create(tc
);
8367 pn
= generatorExpr(pn1
, pn
);
8370 pn
->pn_pos
.begin
= begin
;
8372 if (tokenStream
.getToken() != TOK_RP
) {
8373 reportErrorNumber(NULL
, JSREPORT_ERROR
, JSMSG_BAD_GENERATOR_SYNTAX
,
8377 pn
->pn_pos
.end
= tokenStream
.currentToken().pos
.end
;
8381 #endif /* JS_HAS_GENERATOR_EXPRS */
8387 * Fold from one constant type to another.
8388 * XXX handles only strings and numbers for now
8391 FoldType(JSContext
*cx
, JSParseNode
*pn
, TokenKind type
)
8393 if (PN_TYPE(pn
) != type
) {
8396 if (pn
->pn_type
== TOK_STRING
) {
8398 if (!JS_ValueToNumber(cx
, ATOM_KEY(pn
->pn_atom
), &d
))
8401 pn
->pn_type
= TOK_NUMBER
;
8402 pn
->pn_op
= JSOP_DOUBLE
;
8407 if (pn
->pn_type
== TOK_NUMBER
) {
8408 JSString
*str
= js_NumberToString(cx
, pn
->pn_dval
);
8411 pn
->pn_atom
= js_AtomizeString(cx
, str
, 0);
8414 pn
->pn_type
= TOK_STRING
;
8415 pn
->pn_op
= JSOP_STRING
;
8426 * Fold two numeric constants. Beware that pn1 and pn2 are recycled, unless
8427 * one of them aliases pn, so you can't safely fetch pn2->pn_next, e.g., after
8428 * a successful call to this function.
8431 FoldBinaryNumeric(JSContext
*cx
, JSOp op
, JSParseNode
*pn1
, JSParseNode
*pn2
,
8432 JSParseNode
*pn
, JSTreeContext
*tc
)
8437 JS_ASSERT(pn1
->pn_type
== TOK_NUMBER
&& pn2
->pn_type
== TOK_NUMBER
);
8443 i
= js_DoubleToECMAInt32(d
);
8444 j
= js_DoubleToECMAInt32(d2
);
8446 d
= (op
== JSOP_LSH
) ? i
<< j
: i
>> j
;
8450 j
= js_DoubleToECMAInt32(d2
);
8452 d
= js_DoubleToECMAUint32(d
) >> j
;
8470 /* XXX MSVC miscompiles such that (NaN == 0) */
8471 if (JSDOUBLE_IS_NaN(d2
))
8475 if (d
== 0 || JSDOUBLE_IS_NaN(d
))
8477 else if (JSDOUBLE_IS_NEG(d
) != JSDOUBLE_IS_NEG(d2
))
8478 d
= js_NegativeInfinity
;
8480 d
= js_PositiveInfinity
;
8497 /* Take care to allow pn1 or pn2 to alias pn. */
8499 RecycleTree(pn1
, tc
);
8501 RecycleTree(pn2
, tc
);
8502 pn
->pn_type
= TOK_NUMBER
;
8503 pn
->pn_op
= JSOP_DOUBLE
;
8504 pn
->pn_arity
= PN_NULLARY
;
8509 #if JS_HAS_XML_SUPPORT
8512 FoldXMLConstants(JSContext
*cx
, JSParseNode
*pn
, JSTreeContext
*tc
)
8515 JSParseNode
**pnp
, *pn1
, *pn2
;
8516 JSString
*accum
, *str
;
8519 JS_ASSERT(pn
->pn_arity
== PN_LIST
);
8524 if ((pn
->pn_xflags
& PNX_CANTFOLD
) == 0) {
8525 if (tt
== TOK_XMLETAGO
)
8526 accum
= ATOM_TO_STRING(cx
->runtime
->atomState
.etagoAtom
);
8527 else if (tt
== TOK_XMLSTAGO
|| tt
== TOK_XMLPTAGC
)
8528 accum
= ATOM_TO_STRING(cx
->runtime
->atomState
.stagoAtom
);
8532 * GC Rooting here is tricky: for most of the loop, |accum| is safe via
8533 * the newborn string root. However, when |pn2->pn_type| is TOK_XMLCDATA,
8534 * TOK_XMLCOMMENT, or TOK_XMLPI it is knocked out of the newborn root.
8535 * Therefore, we have to add additonal protection from GC nesting under
8538 for (pn2
= pn1
, i
= j
= 0; pn2
; pn2
= pn2
->pn_next
, i
++) {
8539 /* The parser already rejected end-tags with attributes. */
8540 JS_ASSERT(tt
!= TOK_XMLETAGO
|| i
== 0);
8541 switch (pn2
->pn_type
) {
8550 if (pn2
->pn_arity
== PN_LIST
)
8552 str
= ATOM_TO_STRING(pn2
->pn_atom
);
8556 str
= js_MakeXMLCDATAString(cx
, ATOM_TO_STRING(pn2
->pn_atom
));
8561 case TOK_XMLCOMMENT
:
8562 str
= js_MakeXMLCommentString(cx
, ATOM_TO_STRING(pn2
->pn_atom
));
8568 str
= js_MakeXMLPIString(cx
, ATOM_TO_STRING(pn2
->pn_atom
),
8569 ATOM_TO_STRING(pn2
->pn_atom2
));
8576 JS_ASSERT(*pnp
== pn1
);
8577 if ((tt
== TOK_XMLSTAGO
|| tt
== TOK_XMLPTAGC
) &&
8578 (i
& 1) ^ (j
& 1)) {
8579 #ifdef DEBUG_brendanXXX
8580 printf("1: %d, %d => ", i
, j
);
8582 js_FileEscapedString(stdout
, accum
, 0);
8584 fputs("NULL", stdout
);
8585 fputc('\n', stdout
);
8587 } else if (accum
&& pn1
!= pn2
) {
8588 while (pn1
->pn_next
!= pn2
) {
8589 pn1
= RecycleTree(pn1
, tc
);
8592 pn1
->pn_type
= TOK_XMLTEXT
;
8593 pn1
->pn_op
= JSOP_STRING
;
8594 pn1
->pn_arity
= PN_NULLARY
;
8595 pn1
->pn_atom
= js_AtomizeString(cx
, accum
, 0);
8598 JS_ASSERT(pnp
!= &pn1
->pn_next
);
8601 pnp
= &pn2
->pn_next
;
8609 AutoValueRooter
tvr(cx
, accum
);
8610 str
= ((tt
== TOK_XMLSTAGO
|| tt
== TOK_XMLPTAGC
) && i
!= 0)
8611 ? js_AddAttributePart(cx
, i
& 1, accum
, str
)
8612 : js_ConcatStrings(cx
, accum
, str
);
8616 #ifdef DEBUG_brendanXXX
8617 printf("2: %d, %d => ", i
, j
);
8618 js_FileEscapedString(stdout
, str
, 0);
8619 printf(" (%u)\n", str
->length());
8628 if ((pn
->pn_xflags
& PNX_CANTFOLD
) == 0) {
8629 if (tt
== TOK_XMLPTAGC
)
8630 str
= ATOM_TO_STRING(cx
->runtime
->atomState
.ptagcAtom
);
8631 else if (tt
== TOK_XMLSTAGO
|| tt
== TOK_XMLETAGO
)
8632 str
= ATOM_TO_STRING(cx
->runtime
->atomState
.tagcAtom
);
8635 accum
= js_ConcatStrings(cx
, accum
, str
);
8640 JS_ASSERT(*pnp
== pn1
);
8641 while (pn1
->pn_next
) {
8642 pn1
= RecycleTree(pn1
, tc
);
8645 pn1
->pn_type
= TOK_XMLTEXT
;
8646 pn1
->pn_op
= JSOP_STRING
;
8647 pn1
->pn_arity
= PN_NULLARY
;
8648 pn1
->pn_atom
= js_AtomizeString(cx
, accum
, 0);
8651 JS_ASSERT(pnp
!= &pn1
->pn_next
);
8655 if (pn1
&& pn
->pn_count
== 1) {
8657 * Only one node under pn, and it has been folded: move pn1 onto pn
8658 * unless pn is an XML root (in which case we need it to tell the code
8659 * generator to emit a JSOP_TOXML or JSOP_TOXMLLIST op). If pn is an
8660 * XML root *and* it's a point-tag, rewrite it to TOK_XMLELEM to avoid
8661 * extra "<" and "/>" bracketing at runtime.
8663 if (!(pn
->pn_xflags
& PNX_XMLROOT
)) {
8665 } else if (tt
== TOK_XMLPTAGC
) {
8666 pn
->pn_type
= TOK_XMLELEM
;
8667 pn
->pn_op
= JSOP_TOXML
;
8673 #endif /* JS_HAS_XML_SUPPORT */
8676 Boolish(JSParseNode
*pn
)
8678 switch (pn
->pn_op
) {
8680 return pn
->pn_dval
!= 0 && !JSDOUBLE_IS_NaN(pn
->pn_dval
);
8683 return ATOM_TO_STRING(pn
->pn_atom
)->length() != 0;
8685 #if JS_HAS_GENERATOR_EXPRS
8689 * A generator expression as an if or loop condition has no effects, it
8690 * simply results in a truthy object reference. This condition folding
8691 * is needed for the decompiler. See bug 442342 and bug 443074.
8693 if (pn
->pn_count
!= 1)
8695 JSParseNode
*pn2
= pn
->pn_head
;
8696 if (pn2
->pn_type
!= TOK_FUNCTION
)
8698 if (!(pn2
->pn_funbox
->tcflags
& TCF_GENEXP_LAMBDA
))
8720 js_FoldConstants(JSContext
*cx
, JSParseNode
*pn
, JSTreeContext
*tc
, bool inCond
)
8722 JSParseNode
*pn1
= NULL
, *pn2
= NULL
, *pn3
= NULL
;
8724 JS_CHECK_RECURSION(cx
, return JS_FALSE
);
8726 switch (pn
->pn_arity
) {
8729 uint32 oldflags
= tc
->flags
;
8730 JSFunctionBox
*oldlist
= tc
->functionList
;
8732 tc
->flags
= pn
->pn_funbox
->tcflags
;
8733 tc
->functionList
= pn
->pn_funbox
->kids
;
8734 if (!js_FoldConstants(cx
, pn
->pn_body
, tc
))
8736 pn
->pn_funbox
->kids
= tc
->functionList
;
8737 tc
->flags
= oldflags
;
8738 tc
->functionList
= oldlist
;
8744 /* Propagate inCond through logical connectives. */
8745 bool cond
= inCond
&& (pn
->pn_type
== TOK_OR
|| pn
->pn_type
== TOK_AND
);
8747 /* Don't fold a parenthesized call expression. See bug 537673. */
8748 pn1
= pn2
= pn
->pn_head
;
8749 if ((pn
->pn_type
== TOK_LP
|| pn
->pn_type
== TOK_NEW
) && pn2
->pn_parens
)
8752 /* Save the list head in pn1 for later use. */
8753 for (; pn2
; pn2
= pn2
->pn_next
) {
8754 if (!js_FoldConstants(cx
, pn2
, tc
, cond
))
8761 /* Any kid may be null (e.g. for (;;)). */
8765 if (pn1
&& !js_FoldConstants(cx
, pn1
, tc
, pn
->pn_type
== TOK_IF
))
8768 if (!js_FoldConstants(cx
, pn2
, tc
, pn
->pn_type
== TOK_FORHEAD
))
8770 if (pn
->pn_type
== TOK_FORHEAD
&& pn2
->pn_op
== JSOP_TRUE
) {
8771 RecycleTree(pn2
, tc
);
8775 if (pn3
&& !js_FoldConstants(cx
, pn3
, tc
))
8783 /* Propagate inCond through logical connectives. */
8784 if (pn
->pn_type
== TOK_OR
|| pn
->pn_type
== TOK_AND
) {
8785 if (!js_FoldConstants(cx
, pn1
, tc
, inCond
))
8787 if (!js_FoldConstants(cx
, pn2
, tc
, inCond
))
8792 /* First kid may be null (for default case in switch). */
8793 if (pn1
&& !js_FoldConstants(cx
, pn1
, tc
, pn
->pn_type
== TOK_WHILE
))
8795 if (!js_FoldConstants(cx
, pn2
, tc
, pn
->pn_type
== TOK_DO
))
8803 * Kludge to deal with typeof expressions: because constant folding
8804 * can turn an expression into a name node, we have to check here,
8805 * before folding, to see if we should throw undefined name errors.
8807 * NB: We know that if pn->pn_op is JSOP_TYPEOF, pn1 will not be
8808 * null. This assumption does not hold true for other unary
8811 if (pn
->pn_op
== JSOP_TYPEOF
&& pn1
->pn_type
!= TOK_NAME
)
8812 pn
->pn_op
= JSOP_TYPEOFEXPR
;
8814 if (pn1
&& !js_FoldConstants(cx
, pn1
, tc
, pn
->pn_op
== JSOP_NOT
))
8820 * Skip pn1 down along a chain of dotted member expressions to avoid
8821 * excessive recursion. Our only goal here is to fold constants (if
8822 * any) in the primary expression operand to the left of the first
8827 while (pn1
&& pn1
->pn_arity
== PN_NAME
&& !pn1
->pn_used
)
8829 if (pn1
&& !js_FoldConstants(cx
, pn1
, tc
))
8836 if (!js_FoldConstants(cx
, pn1
, tc
))
8844 switch (pn
->pn_type
) {
8846 if (ContainsStmt(pn2
, TOK_VAR
) || ContainsStmt(pn3
, TOK_VAR
))
8851 /* Reduce 'if (C) T; else E' into T for true C, E for false. */
8852 switch (pn1
->pn_type
) {
8854 if (pn1
->pn_dval
== 0 || JSDOUBLE_IS_NaN(pn1
->pn_dval
))
8858 if (ATOM_TO_STRING(pn1
->pn_atom
)->length() == 0)
8862 if (pn1
->pn_op
== JSOP_TRUE
)
8864 if (pn1
->pn_op
== JSOP_FALSE
|| pn1
->pn_op
== JSOP_NULL
) {
8870 /* Early return to dodge common code that copies pn2 to pn. */
8874 #if JS_HAS_GENERATOR_EXPRS
8875 /* Don't fold a trailing |if (0)| in a generator expression. */
8876 if (!pn2
&& (tc
->flags
& TCF_GENEXP_LAMBDA
))
8880 if (pn2
&& !pn2
->pn_defn
)
8882 if (!pn2
|| (pn
->pn_type
== TOK_SEMI
&& !pn
->pn_kid
)) {
8884 * False condition and no else, or an empty then-statement was
8885 * moved up over pn. Either way, make pn an empty block (not an
8886 * empty statement, which does not decompile, even when labeled).
8887 * NB: pn must be a TOK_IF as TOK_HOOK can never have a null kid
8888 * or an empty statement for a child.
8890 pn
->pn_type
= TOK_LC
;
8891 pn
->pn_arity
= PN_LIST
;
8894 RecycleTree(pn2
, tc
);
8895 if (pn3
&& pn3
!= pn2
)
8896 RecycleTree(pn3
, tc
);
8902 if (pn
->pn_arity
== PN_LIST
) {
8903 JSParseNode
**pnp
= &pn
->pn_head
;
8904 JS_ASSERT(*pnp
== pn1
);
8906 int cond
= Boolish(pn1
);
8907 if (cond
== (pn
->pn_type
== TOK_OR
)) {
8908 for (pn2
= pn1
->pn_next
; pn2
; pn2
= pn3
) {
8910 RecycleTree(pn2
, tc
);
8913 pn1
->pn_next
= NULL
;
8917 JS_ASSERT(cond
== (pn
->pn_type
== TOK_AND
));
8918 if (pn
->pn_count
== 1)
8920 *pnp
= pn1
->pn_next
;
8921 RecycleTree(pn1
, tc
);
8924 pnp
= &pn1
->pn_next
;
8926 } while ((pn1
= *pnp
) != NULL
);
8928 // We may have to change arity from LIST to BINARY.
8930 if (pn
->pn_count
== 2) {
8932 pn1
->pn_next
= NULL
;
8933 JS_ASSERT(!pn2
->pn_next
);
8934 pn
->pn_arity
= PN_BINARY
;
8937 } else if (pn
->pn_count
== 1) {
8939 RecycleTree(pn1
, tc
);
8942 int cond
= Boolish(pn1
);
8943 if (cond
== (pn
->pn_type
== TOK_OR
)) {
8944 RecycleTree(pn2
, tc
);
8946 } else if (cond
!= -1) {
8947 JS_ASSERT(cond
== (pn
->pn_type
== TOK_AND
));
8948 RecycleTree(pn1
, tc
);
8957 * Compound operators such as *= should be subject to folding, in case
8958 * the left-hand side is constant, and so that the decompiler produces
8959 * the same string that you get from decompiling a script or function
8960 * compiled from that same string. As with +, += is special.
8962 if (pn
->pn_op
== JSOP_NOP
)
8964 if (pn
->pn_op
!= JSOP_ADD
)
8969 if (pn
->pn_arity
== PN_LIST
) {
8970 size_t length
, length2
;
8972 JSString
*str
, *str2
;
8975 * Any string literal term with all others number or string means
8976 * this is a concatenation. If any term is not a string or number
8977 * literal, we can't fold.
8979 JS_ASSERT(pn
->pn_count
> 2);
8980 if (pn
->pn_xflags
& PNX_CANTFOLD
)
8982 if (pn
->pn_xflags
!= PNX_STRCAT
)
8985 /* Ok, we're concatenating: convert non-string constant operands. */
8987 for (pn2
= pn1
; pn2
; pn2
= pn2
->pn_next
) {
8988 if (!FoldType(cx
, pn2
, TOK_STRING
))
8990 /* XXX fold only if all operands convert to string */
8991 if (pn2
->pn_type
!= TOK_STRING
)
8993 length
+= ATOM_TO_STRING(pn2
->pn_atom
)->flatLength();
8996 /* Allocate a new buffer and string descriptor for the result. */
8997 chars
= (jschar
*) cx
->malloc((length
+ 1) * sizeof(jschar
));
9000 str
= js_NewString(cx
, chars
, length
);
9006 /* Fill the buffer, advancing chars and recycling kids as we go. */
9007 for (pn2
= pn1
; pn2
; pn2
= RecycleTree(pn2
, tc
)) {
9008 str2
= ATOM_TO_STRING(pn2
->pn_atom
);
9009 length2
= str2
->flatLength();
9010 js_strncpy(chars
, str2
->flatChars(), length2
);
9015 /* Atomize the result string and mutate pn to refer to it. */
9016 pn
->pn_atom
= js_AtomizeString(cx
, str
, 0);
9019 pn
->pn_type
= TOK_STRING
;
9020 pn
->pn_op
= JSOP_STRING
;
9021 pn
->pn_arity
= PN_NULLARY
;
9025 /* Handle a binary string concatenation. */
9026 JS_ASSERT(pn
->pn_arity
== PN_BINARY
);
9027 if (pn1
->pn_type
== TOK_STRING
|| pn2
->pn_type
== TOK_STRING
) {
9028 JSString
*left
, *right
, *str
;
9030 if (!FoldType(cx
, (pn1
->pn_type
!= TOK_STRING
) ? pn1
: pn2
,
9034 if (pn1
->pn_type
!= TOK_STRING
|| pn2
->pn_type
!= TOK_STRING
)
9036 left
= ATOM_TO_STRING(pn1
->pn_atom
);
9037 right
= ATOM_TO_STRING(pn2
->pn_atom
);
9038 str
= js_ConcatStrings(cx
, left
, right
);
9041 pn
->pn_atom
= js_AtomizeString(cx
, str
, 0);
9044 pn
->pn_type
= TOK_STRING
;
9045 pn
->pn_op
= JSOP_STRING
;
9046 pn
->pn_arity
= PN_NULLARY
;
9047 RecycleTree(pn1
, tc
);
9048 RecycleTree(pn2
, tc
);
9052 /* Can't concatenate string literals, let's try numbers. */
9060 if (pn
->pn_arity
== PN_LIST
) {
9061 JS_ASSERT(pn
->pn_count
> 2);
9062 for (pn2
= pn1
; pn2
; pn2
= pn2
->pn_next
) {
9063 if (!FoldType(cx
, pn2
, TOK_NUMBER
))
9066 for (pn2
= pn1
; pn2
; pn2
= pn2
->pn_next
) {
9067 /* XXX fold only if all operands convert to number */
9068 if (pn2
->pn_type
!= TOK_NUMBER
)
9072 JSOp op
= PN_OP(pn
);
9076 if (!FoldBinaryNumeric(cx
, op
, pn1
, pn2
, pn
, tc
))
9078 while ((pn2
= pn3
) != NULL
) {
9080 if (!FoldBinaryNumeric(cx
, op
, pn
, pn2
, pn
, tc
))
9085 JS_ASSERT(pn
->pn_arity
== PN_BINARY
);
9086 if (!FoldType(cx
, pn1
, TOK_NUMBER
) ||
9087 !FoldType(cx
, pn2
, TOK_NUMBER
)) {
9090 if (pn1
->pn_type
== TOK_NUMBER
&& pn2
->pn_type
== TOK_NUMBER
) {
9091 if (!FoldBinaryNumeric(cx
, PN_OP(pn
), pn1
, pn2
, pn
, tc
))
9098 if (pn1
->pn_type
== TOK_NUMBER
) {
9101 /* Operate on one numeric constant. */
9103 switch (pn
->pn_op
) {
9105 d
= ~js_DoubleToECMAInt32(d
);
9116 pn
->pn_type
= TOK_PRIMARY
;
9117 pn
->pn_op
= (d
== 0 || JSDOUBLE_IS_NaN(d
)) ? JSOP_TRUE
: JSOP_FALSE
;
9118 pn
->pn_arity
= PN_NULLARY
;
9122 /* Return early to dodge the common TOK_NUMBER code. */
9125 pn
->pn_type
= TOK_NUMBER
;
9126 pn
->pn_op
= JSOP_DOUBLE
;
9127 pn
->pn_arity
= PN_NULLARY
;
9129 RecycleTree(pn1
, tc
);
9130 } else if (pn1
->pn_type
== TOK_PRIMARY
) {
9131 if (pn
->pn_op
== JSOP_NOT
&&
9132 (pn1
->pn_op
== JSOP_TRUE
||
9133 pn1
->pn_op
== JSOP_FALSE
)) {
9135 pn
->pn_op
= (pn
->pn_op
== JSOP_TRUE
) ? JSOP_FALSE
: JSOP_TRUE
;
9136 RecycleTree(pn1
, tc
);
9141 #if JS_HAS_XML_SUPPORT
9148 if (pn
->pn_arity
== PN_LIST
) {
9149 JS_ASSERT(pn
->pn_type
== TOK_XMLLIST
|| pn
->pn_count
!= 0);
9150 if (!FoldXMLConstants(cx
, pn
, tc
))
9156 if (pn1
->pn_type
== TOK_XMLNAME
) {
9158 JSObjectBox
*xmlbox
;
9160 v
= ATOM_KEY(pn1
->pn_atom
);
9161 if (!js_ToAttributeName(cx
, &v
))
9163 JS_ASSERT(!JSVAL_IS_PRIMITIVE(v
));
9165 xmlbox
= tc
->parser
->newObjectBox(JSVAL_TO_OBJECT(v
));
9169 pn
->pn_type
= TOK_XMLNAME
;
9170 pn
->pn_op
= JSOP_OBJECT
;
9171 pn
->pn_arity
= PN_NULLARY
;
9172 pn
->pn_objbox
= xmlbox
;
9173 RecycleTree(pn1
, tc
);
9176 #endif /* JS_HAS_XML_SUPPORT */
9182 int cond
= Boolish(pn
);
9184 switch (pn
->pn_arity
) {
9189 RecycleTree(pn2
, tc
);
9190 } while ((pn2
= pn3
) != NULL
);
9193 RecycleFuncNameKids(pn
, tc
);
9198 JS_NOT_REACHED("unhandled arity");
9200 pn
->pn_type
= TOK_PRIMARY
;
9201 pn
->pn_op
= cond
? JSOP_TRUE
: JSOP_FALSE
;
9202 pn
->pn_arity
= PN_NULLARY
;