1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
|
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=78:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef jsparse_h___
#define jsparse_h___
/*
* JS parser definitions.
*/
#include "jsversion.h"
#include "jsprvtd.h"
#include "jspubtd.h"
#include "jsatom.h"
#include "jsscan.h"
JS_BEGIN_EXTERN_C
/*
* Parsing builds a tree of nodes that directs code generation. This tree is
* not a concrete syntax tree in all respects (for example, || and && are left
* associative, but (A && B && C) translates into the right-associated tree
* <A && <B && C>> so that code generation can emit a left-associative branch
* around <B && C> when A is false). Nodes are labeled by token type, with a
* JSOp secondary label when needed:
*
* Label Variant Members
* ----- ------- -------
* <Definitions>
* TOK_FUNCTION name pn_funbox: ptr to JSFunctionBox holding function
* object containing arg and var properties. We
* create the function object at parse (not emit)
* time to specialize arg and var bytecodes early.
* pn_body: TOK_UPVARS if the function's source body
* depends on outer names, else TOK_ARGSBODY
* if formal parameters, else TOK_LC node for
* function body statements
* pn_cookie: static level and var index for function
* pn_dflags: PND_* definition/use flags (see below)
* pn_blockid: block id number
* TOK_ARGSBODY list list of formal parameters followed by TOK_LC node
* for function body statements as final element
* pn_count: 1 + number of formal parameters
* TOK_UPVARS nameset pn_names: lexical dependencies (JSDefinitions)
* defined in enclosing scopes, or ultimately not
* defined (free variables, either global property
* references or reference errors).
* pn_argsbody: TOK_ARGSBODY or TOK_LC node
*
* <Statements>
* TOK_LC list pn_head: list of pn_count statements
* TOK_IF ternary pn_kid1: cond, pn_kid2: then, pn_kid3: else or null
* TOK_SWITCH binary pn_left: discriminant
* pn_right: list of TOK_CASE nodes, with at most one
* TOK_DEFAULT node, or if there are let bindings
* in the top level of the switch body's cases, a
* TOK_LEXICALSCOPE node that contains the list of
* TOK_CASE nodes.
* TOK_CASE, binary pn_left: case expr or null if TOK_DEFAULT
* TOK_DEFAULT pn_right: TOK_LC node for this case's statements
* pn_val: constant value if lookup or table switch
* TOK_WHILE binary pn_left: cond, pn_right: body
* TOK_DO binary pn_left: body, pn_right: cond
* TOK_FOR binary pn_left: either
* for/in loop: a binary TOK_IN node with
* pn_left: TOK_VAR or TOK_NAME to left of 'in'
* if TOK_VAR, its pn_xflags may have PNX_POPVAR
* and PNX_FORINVAR bits set
* pn_right: object expr to right of 'in'
* for(;;) loop: a ternary TOK_RESERVED node with
* pn_kid1: init expr before first ';'
* pn_kid2: cond expr before second ';'
* pn_kid3: update expr after second ';'
* any kid may be null
* pn_right: body
* TOK_THROW unary pn_op: JSOP_THROW, pn_kid: exception
* TOK_TRY ternary pn_kid1: try block
* pn_kid2: null or TOK_RESERVED list of
* TOK_LEXICALSCOPE nodes, each with pn_expr pointing
* to a TOK_CATCH node
* pn_kid3: null or finally block
* TOK_CATCH ternary pn_kid1: TOK_NAME, TOK_RB, or TOK_RC catch var node
* (TOK_RB or TOK_RC if destructuring)
* pn_kid2: null or the catch guard expression
* pn_kid3: catch block statements
* TOK_BREAK name pn_atom: label or null
* TOK_CONTINUE name pn_atom: label or null
* TOK_WITH binary pn_left: head expr, pn_right: body
* TOK_VAR list pn_head: list of TOK_NAME or TOK_ASSIGN nodes
* each name node has
* pn_used: false
* pn_atom: variable name
* pn_expr: initializer or null
* each assignment node has
* pn_left: TOK_NAME with pn_used true and
* pn_lexdef (NOT pn_expr) set
* pn_right: initializer
* TOK_RETURN unary pn_kid: return expr or null
* TOK_SEMI unary pn_kid: expr or null statement
* TOK_COLON name pn_atom: label, pn_expr: labeled statement
*
* <Expressions>
* All left-associated binary trees of the same type are optimized into lists
* to avoid recursion when processing expression chains.
* TOK_COMMA list pn_head: list of pn_count comma-separated exprs
* TOK_ASSIGN binary pn_left: lvalue, pn_right: rvalue
* pn_op: JSOP_ADD for +=, etc.
* TOK_HOOK ternary pn_kid1: cond, pn_kid2: then, pn_kid3: else
* TOK_OR binary pn_left: first in || chain, pn_right: rest of chain
* TOK_AND binary pn_left: first in && chain, pn_right: rest of chain
* TOK_BITOR binary pn_left: left-assoc | expr, pn_right: ^ expr
* TOK_BITXOR binary pn_left: left-assoc ^ expr, pn_right: & expr
* TOK_BITAND binary pn_left: left-assoc & expr, pn_right: EQ expr
* TOK_EQOP binary pn_left: left-assoc EQ expr, pn_right: REL expr
* pn_op: JSOP_EQ, JSOP_NE,
* JSOP_STRICTEQ, JSOP_STRICTNE
* TOK_RELOP binary pn_left: left-assoc REL expr, pn_right: SH expr
* pn_op: JSOP_LT, JSOP_LE, JSOP_GT, JSOP_GE
* TOK_SHOP binary pn_left: left-assoc SH expr, pn_right: ADD expr
* pn_op: JSOP_LSH, JSOP_RSH, JSOP_URSH
* TOK_PLUS, binary pn_left: left-assoc ADD expr, pn_right: MUL expr
* pn_xflags: if a left-associated binary TOK_PLUS
* tree has been flattened into a list (see above
* under <Expressions>), pn_xflags will contain
* PNX_STRCAT if at least one list element is a
* string literal (TOK_STRING); if such a list has
* any non-string, non-number term, pn_xflags will
* contain PNX_CANTFOLD.
* pn_
* TOK_MINUS pn_op: JSOP_ADD, JSOP_SUB
* TOK_STAR, binary pn_left: left-assoc MUL expr, pn_right: UNARY expr
* TOK_DIVOP pn_op: JSOP_MUL, JSOP_DIV, JSOP_MOD
* TOK_UNARYOP unary pn_kid: UNARY expr, pn_op: JSOP_NEG, JSOP_POS,
* JSOP_NOT, JSOP_BITNOT, JSOP_TYPEOF, JSOP_VOID
* TOK_INC, unary pn_kid: MEMBER expr
* TOK_DEC
* TOK_NEW list pn_head: list of ctor, arg1, arg2, ... argN
* pn_count: 1 + N (where N is number of args)
* ctor is a MEMBER expr
* TOK_DELETE unary pn_kid: MEMBER expr
* TOK_DOT, name pn_expr: MEMBER expr to left of .
* TOK_DBLDOT pn_atom: name to right of .
* TOK_LB binary pn_left: MEMBER expr to left of [
* pn_right: expr between [ and ]
* TOK_LP list pn_head: list of call, arg1, arg2, ... argN
* pn_count: 1 + N (where N is number of args)
* call is a MEMBER expr naming a callable object
* TOK_RB list pn_head: list of pn_count array element exprs
* [,,] holes are represented by TOK_COMMA nodes
* pn_xflags: PN_ENDCOMMA if extra comma at end
* TOK_RC list pn_head: list of pn_count binary TOK_COLON nodes
* TOK_COLON binary key-value pair in object initializer or
* destructuring lhs
* pn_left: property id, pn_right: value
* var {x} = object destructuring shorthand shares
* PN_NAME node for x on left and right of TOK_COLON
* node in TOK_RC's list, has PNX_DESTRUCT flag
* TOK_DEFSHARP unary pn_num: jsint value of n in #n=
* pn_kid: primary function, paren, name, object or
* array literal expressions
* TOK_USESHARP nullary pn_num: jsint value of n in #n#
* TOK_RP unary pn_kid: parenthesized expression
* TOK_NAME, name pn_atom: name, string, or object atom
* TOK_STRING, pn_op: JSOP_NAME, JSOP_STRING, or JSOP_OBJECT, or
* JSOP_REGEXP
* TOK_REGEXP If JSOP_NAME, pn_op may be JSOP_*ARG or JSOP_*VAR
* with pn_cookie telling (staticLevel, slot) (see
* jsscript.h's UPVAR macros) and pn_dflags telling
* const-ness and static analysis results
* TOK_NAME name If pn_used, TOK_NAME uses the lexdef member instead
* of the expr member it overlays
* TOK_NUMBER dval pn_dval: double value of numeric literal
* TOK_PRIMARY nullary pn_op: JSOp bytecode
*
* <E4X node descriptions>
* TOK_ANYNAME nullary pn_op: JSOP_ANYNAME
* pn_atom: cx->runtime->atomState.starAtom
* TOK_AT unary pn_op: JSOP_TOATTRNAME; pn_kid attribute id/expr
* TOK_DBLCOLON binary pn_op: JSOP_QNAME
* pn_left: TOK_ANYNAME or TOK_NAME node
* pn_right: TOK_STRING "*" node, or expr within []
* name pn_op: JSOP_QNAMECONST
* pn_expr: TOK_ANYNAME or TOK_NAME left operand
* pn_atom: name on right of ::
* TOK_XMLELEM list XML element node
* pn_head: start tag, content1, ... contentN, end tag
* pn_count: 2 + N where N is number of content nodes
* N may be > x.length() if {expr} embedded
* TOK_XMLLIST list XML list node
* pn_head: content1, ... contentN
* TOK_XMLSTAGO, list XML start, end, and point tag contents
* TOK_XMLETAGC, pn_head: tag name or {expr}, ... XML attrs ...
* TOK_XMLPTAGO
* TOK_XMLNAME nullary pn_atom: XML name, with no {expr} embedded
* TOK_XMLNAME list pn_head: tag name or {expr}, ... name or {expr}
* TOK_XMLATTR, nullary pn_atom: attribute value string; pn_op: JSOP_STRING
* TOK_XMLCDATA,
* TOK_XMLCOMMENT
* TOK_XMLPI nullary pn_atom: XML processing instruction target
* pn_atom2: XML PI content, or null if no content
* TOK_XMLTEXT nullary pn_atom: marked-up text, or null if empty string
* TOK_LC unary {expr} in XML tag or content; pn_kid is expr
*
* So an XML tag with no {expr} and three attributes is a list with the form:
*
* (tagname attrname1 attrvalue1 attrname2 attrvalue2 attrname2 attrvalue3)
*
* An XML tag with embedded expressions like so:
*
* <name1{expr1} name2{expr2}name3={expr3}>
*
* would have the form:
*
* ((name1 {expr1}) (name2 {expr2} name3) {expr3})
*
* where () bracket a list with elements separated by spaces, and {expr} is a
* TOK_LC unary node with expr as its kid.
*
* Thus, the attribute name/value pairs occupy successive odd and even list
* locations, where pn_head is the TOK_XMLNAME node at list location 0. The
* parser builds the same sort of structures for elements:
*
* <a x={x}>Hi there!<b y={y}>How are you?</b><answer>{x + y}</answer></a>
*
* translates to:
*
* ((a x {x}) 'Hi there!' ((b y {y}) 'How are you?') ((answer) {x + y}))
*
* <Non-E4X node descriptions, continued>
*
* Label Variant Members
* ----- ------- -------
* TOK_LEXICALSCOPE name pn_op: JSOP_LEAVEBLOCK or JSOP_LEAVEBLOCKEXPR
* pn_objbox: block object in JSObjectBox holder
* pn_expr: block body
* TOK_ARRAYCOMP list pn_head: list of pn_count (1 or 2) elements
* if pn_count is 2, first element is #n=[...]
* last element is block enclosing for loop(s)
* and optionally if-guarded TOK_ARRAYPUSH
* TOK_ARRAYPUSH unary pn_op: JSOP_ARRAYCOMP
* pn_kid: array comprehension expression
*/
typedef enum JSParseNodeArity {
PN_NULLARY, /* 0 kids, only pn_atom/pn_dval/etc. */
PN_UNARY, /* one kid, plus a couple of scalars */
PN_BINARY, /* two kids, plus a couple of scalars */
PN_TERNARY, /* three kids */
PN_FUNC, /* function definition node */
PN_LIST, /* generic singly linked list */
PN_NAME, /* name use or definition node */
PN_NAMESET /* JSAtomList + JSParseNode ptr */
} JSParseNodeArity;
struct JSDefinition;
struct JSParseNode {
uint32 pn_type:16, /* TOK_* type, see jsscan.h */
pn_op:8, /* see JSOp enum and jsopcode.tbl */
pn_arity:6, /* see JSParseNodeArity enum */
pn_used:1, /* name node is on a use-chain */
pn_defn:1; /* this node is a JSDefinition */
#define PN_OP(pn) ((JSOp)(pn)->pn_op)
#define PN_TYPE(pn) ((JSTokenType)(pn)->pn_type)
JSTokenPos pn_pos; /* two 16-bit pairs here, for 64 bits */
int32 pn_offset; /* first generated bytecode offset */
JSParseNode *pn_next; /* intrinsic link in parent PN_LIST */
JSParseNode *pn_link; /* def/use link (alignment freebie) */
union {
struct { /* list of next-linked nodes */
JSParseNode *head; /* first node in list */
JSParseNode **tail; /* ptr to ptr to last node in list */
uint32 count; /* number of nodes in list */
uint32 xflags:12, /* extra flags, see below */
blockid:20; /* see name variant below */
} list;
struct { /* ternary: if, for(;;), ?: */
JSParseNode *kid1; /* condition, discriminant, etc. */
JSParseNode *kid2; /* then-part, case list, etc. */
JSParseNode *kid3; /* else-part, default case, etc. */
} ternary;
struct { /* two kids if binary */
JSParseNode *left;
JSParseNode *right;
jsval val; /* switch case value */
uintN iflags; /* JSITER_* flags for TOK_FOR node */
} binary;
struct { /* one kid if unary */
JSParseNode *kid;
jsint num; /* -1 or sharp variable number */
JSBool hidden; /* hidden genexp-induced JSOP_YIELD */
} unary;
struct { /* name, labeled statement, etc. */
union {
JSAtom *atom; /* lexical name or label atom */
JSFunctionBox *funbox; /* function object */
JSObjectBox *objbox; /* block or regexp object */
};
union {
JSParseNode *expr; /* function body, var initializer, or
base object of TOK_DOT */
JSDefinition *lexdef; /* lexical definition for this use */
};
uint32 cookie; /* upvar cookie with absolute frame
level (not relative skip), possibly
in current frame */
uint32 dflags:12, /* definition/use flags, see below */
blockid:20; /* block number, for subset dominance
computation */
} name;
struct { /* lexical dependencies + sub-tree */
JSAtomSet names; /* set of names with JSDefinitions */
JSParseNode *tree; /* sub-tree containing name uses */
} nameset;
struct { /* PN_NULLARY variant for E4X */
JSAtom *atom; /* first atom in pair */
JSAtom *atom2; /* second atom in pair or null */
} apair;
jsdouble dval; /* aligned numeric literal value */
} pn_u;
#define pn_funbox pn_u.name.funbox
#define pn_body pn_u.name.expr
#define pn_cookie pn_u.name.cookie
#define pn_dflags pn_u.name.dflags
#define pn_blockid pn_u.name.blockid
#define pn_index pn_u.name.blockid /* reuse as object table index */
#define pn_head pn_u.list.head
#define pn_tail pn_u.list.tail
#define pn_count pn_u.list.count
#define pn_xflags pn_u.list.xflags
#define pn_kid1 pn_u.ternary.kid1
#define pn_kid2 pn_u.ternary.kid2
#define pn_kid3 pn_u.ternary.kid3
#define pn_left pn_u.binary.left
#define pn_right pn_u.binary.right
#define pn_val pn_u.binary.val
#define pn_iflags pn_u.binary.iflags
#define pn_kid pn_u.unary.kid
#define pn_num pn_u.unary.num
#define pn_hidden pn_u.unary.hidden
#define pn_atom pn_u.name.atom
#define pn_objbox pn_u.name.objbox
#define pn_expr pn_u.name.expr
#define pn_lexdef pn_u.name.lexdef
#define pn_names pn_u.nameset.names
#define pn_tree pn_u.nameset.tree
#define pn_dval pn_u.dval
#define pn_atom2 pn_u.apair.atom2
/*
* The pn_expr and lexdef members are arms of an unsafe union. Unless you
* know exactly what you're doing, use only the following methods to access
* them. For less overhead and assertions for protection, use pn->expr()
* and pn->lexdef(). Otherwise, use pn->maybeExpr() and pn->maybeLexDef().
*/
JSParseNode *expr() const {
JS_ASSERT(!pn_used);
JS_ASSERT(pn_arity == PN_NAME || pn_arity == PN_FUNC);
return pn_expr;
}
JSDefinition *lexdef() const {
JS_ASSERT(pn_used);
JS_ASSERT(pn_arity == PN_NAME);
return pn_lexdef;
}
JSParseNode *maybeExpr() { return pn_used ? NULL : expr(); }
JSDefinition *maybeLexDef() { return pn_used ? lexdef() : NULL; }
/* PN_FUNC and PN_NAME pn_dflags bits. */
#define PND_LET 0x01 /* let (block-scoped) binding */
#define PND_CONST 0x02 /* const binding (orthogonal to let) */
#define PND_INITIALIZED 0x04 /* initialized declaration */
#define PND_ASSIGNED 0x08 /* set if ever LHS of assignment */
#define PND_TOPLEVEL 0x10 /* function at top of body or prog */
#define PND_BLOCKCHILD 0x20 /* use or def is direct block child */
#define PND_GVAR 0x40 /* gvar binding, can't close over
because it could be deleted */
#define PND_PLACEHOLDER 0x80 /* placeholder definition for lexdep */
#define PND_FUNARG 0x100 /* downward or upward funarg usage */
#define PND_BOUND 0x200 /* bound to a stack or global slot */
/* PN_LIST pn_xflags bits. */
#define PNX_STRCAT 0x01 /* TOK_PLUS list has string term */
#define PNX_CANTFOLD 0x02 /* TOK_PLUS list has unfoldable term */
#define PNX_POPVAR 0x04 /* TOK_VAR last result needs popping */
#define PNX_FORINVAR 0x08 /* TOK_VAR is left kid of TOK_IN node,
which is left kid of TOK_FOR */
#define PNX_ENDCOMMA 0x10 /* array literal has comma at end */
#define PNX_XMLROOT 0x20 /* top-most node in XML literal tree */
#define PNX_GROUPINIT 0x40 /* var [a, b] = [c, d]; unit list */
#define PNX_NEEDBRACES 0x80 /* braces necessary due to closure */
#define PNX_FUNCDEFS 0x100 /* contains top-level function
statements */
#define PNX_DESTRUCT 0x200 /* destructuring special cases:
1. shorthand syntax used, at present
object destructuring ({x,y}) only;
2. the first child of function body
is code evaluating destructuring
arguments */
#define PNX_HOLEY 0x400 /* array initialiser has holes */
uintN frameLevel() const {
JS_ASSERT(pn_arity == PN_FUNC || pn_arity == PN_NAME);
return UPVAR_FRAME_SKIP(pn_cookie);
}
uintN frameSlot() const {
JS_ASSERT(pn_arity == PN_FUNC || pn_arity == PN_NAME);
return UPVAR_FRAME_SLOT(pn_cookie);
}
bool test(uintN flag) const {
JS_ASSERT(pn_arity == PN_FUNC || pn_arity == PN_NAME);
return !!(pn_dflags & flag);
}
bool isLet() const { return test(PND_LET); }
bool isConst() const { return test(PND_CONST); }
bool isInitialized() const { return test(PND_INITIALIZED); }
bool isTopLevel() const { return test(PND_TOPLEVEL); }
bool isBlockChild() const { return test(PND_BLOCKCHILD); }
bool isPlaceholder() const { return test(PND_PLACEHOLDER); }
/* Defined below, see after struct JSDefinition. */
bool isAssigned() const;
bool isFunArg() const;
void setFunArg();
void become(JSParseNode *pn2);
void clear();
/* True if pn is a parsenode representing a literal constant. */
bool isLiteral() const {
return PN_TYPE(this) == TOK_NUMBER ||
PN_TYPE(this) == TOK_STRING ||
(PN_TYPE(this) == TOK_PRIMARY && PN_OP(this) != JSOP_THIS);
}
/*
* Compute a pointer to the last element in a singly-linked list. NB: list
* must be non-empty for correct PN_LAST usage -- this is asserted!
*/
JSParseNode *last() const {
JS_ASSERT(pn_arity == PN_LIST);
JS_ASSERT(pn_count != 0);
return (JSParseNode *)((char *)pn_tail - offsetof(JSParseNode, pn_next));
}
void makeEmpty() {
JS_ASSERT(pn_arity == PN_LIST);
pn_head = NULL;
pn_tail = &pn_head;
pn_count = 0;
pn_xflags = 0;
pn_blockid = 0;
}
void initList(JSParseNode *pn) {
JS_ASSERT(pn_arity == PN_LIST);
pn_head = pn;
pn_tail = &pn->pn_next;
pn_count = 1;
pn_xflags = 0;
pn_blockid = 0;
}
void append(JSParseNode *pn) {
JS_ASSERT(pn_arity == PN_LIST);
*pn_tail = pn;
pn_tail = &pn->pn_next;
pn_count++;
}
};
/*
* JSDefinition is a degenerate subtype of the PN_FUNC and PN_NAME variants of
* JSParseNode, allocated only for function, var, const, and let declarations
* that define truly lexical bindings. This means that a child of a TOK_VAR
* list may be a JSDefinition instead of a JSParseNode. The pn_defn bit is set
* for all JSDefinitions, clear otherwise.
*
* Note that not all var declarations are definitions: JS allows multiple var
* declarations in a function or script, but only the first creates the hoisted
* binding. JS programmers do redeclare variables for good refactoring reasons,
* for example:
*
* function foo() {
* ...
* for (var i ...) ...;
* ...
* for (var i ...) ...;
* ...
* }
*
* Not all definitions bind lexical variables, alas. In global and eval code
* var may re-declare a pre-existing property having any attributes, with or
* without JSPROP_PERMANENT. In eval code, indeed, ECMA-262 Editions 1 through
* 3 require function and var to bind deletable bindings. Global vars thus are
* properties of the global object, so they can be aliased even if they can't
* be deleted.
*
* Only bindings within function code may be treated as lexical, of course with
* the caveat that hoisting means use before initialization is allowed. We deal
* with use before declaration in one pass as follows (error checking elided):
*
* for (each use of unqualified name x in parse order) {
* if (this use of x is a declaration) {
* if (x in tc->decls) { // redeclaring
* pn = allocate a PN_NAME JSParseNode;
* } else { // defining
* dn = lookup x in tc->lexdeps;
* if (dn) { // use before def
* remove x from tc->lexdeps;
* } else { // def before use
* dn = allocate a PN_NAME JSDefinition;
* map x to dn via tc->decls;
* }
* pn = dn;
* }
* insert pn into its parent TOK_VAR list;
* } else {
* pn = allocate a JSParseNode for this reference to x;
* dn = lookup x in tc's lexical scope chain;
* if (!dn) {
* dn = lookup x in tc->lexdeps;
* if (!dn) {
* dn = pre-allocate a JSDefinition for x;
* map x to dn in tc->lexdeps;
* }
* }
* append pn to dn's use chain;
* }
* }
*
* See jsemit.h for JSTreeContext and its top*Stmt, decls, and lexdeps members.
*
* Notes:
*
* 0. To avoid bloating JSParseNode, we steal a bit from pn_arity for pn_defn
* and set it on a JSParseNode instead of allocating a JSDefinition.
*
* 1. Due to hoisting, a definition cannot be eliminated even if its "Variable
* statement" (ECMA-262 12.2) can be proven to be dead code. RecycleTree in
* jsparse.cpp will not recycle a node whose pn_defn bit is set.
*
* 2. "lookup x in tc's lexical scope chain" gives up on def/use chaining if a
* with statement is found along the the scope chain, which includes tc,
* tc->parent, etc. Thus we eagerly connect an inner function's use of an
* outer's var x if the var x was parsed before the inner function.
*
* 3. A use may be eliminated as dead by the constant folder, which therefore
* must remove the dead name node from its singly-linked use chain, which
* would mean hashing to find the definition node and searching to update
* the pn_link pointing at the use to be removed. This is costly, so as for
* dead definitions, we do not recycle dead pn_used nodes.
*
* At the end of parsing a function body or global or eval program, tc->lexdeps
* holds the lexical dependencies of the parsed unit. The name to def/use chain
* mappings are then merged into the parent tc->lexdeps.
*
* Thus if a later var x is parsed in the outer function satisfying an earlier
* inner function's use of x, we will remove dn from tc->lexdeps and re-use it
* as the new definition node in the outer function's parse tree.
*
* When the compiler unwinds from the outermost tc, tc->lexdeps contains the
* definition nodes with use chains for all free variables. These are either
* global variables or reference errors.
*
* We analyze whether a binding is initialized, whether the bound names is ever
* assigned apart from its initializer, and if the bound name definition or use
* is in a direct child of a block. These PND_* flags allow a subset dominance
* computation telling whether an initialized var dominates its uses. An inner
* function using only such outer vars (and formal parameters) can be optimized
* into a flat closure. See JSOP_{GET,CALL}DSLOT.
*
* Another important subset dominance relation: ... { var x = ...; ... x ... }
* where x is not assigned after initialization and not used outside the block.
* This style is common in the absence of 'let'. Even though the var x is not
* at top level, we can tell its initialization dominates all uses cheaply,
* because the above one-pass algorithm sees the definition before any uses,
* and because all uses are contained in the same block as the definition.
*
* We also analyze function uses to flag upward/downward funargs, optimizing
* Algol-like (not passed as funargs, only ever called) lightweight functions
* using cx->display. See JSOP_{GET,CALL}UPVAR.
*
* This means that closure optimizations may be frustrated by with, eval, or
* assignment to an outer var. Such hard cases require heavyweight functions
* and JSOP_NAME, etc.
*/
#define dn_uses pn_link
struct JSDefinition : public JSParseNode
{
/*
* We store definition pointers in PN_NAMESET JSAtomLists in the AST, but
* due to redefinition these nodes may become uses of other definitions.
* This is unusual, so we simply chase the pn_lexdef link to find the final
* definition node. See methods called from JSCompiler::analyzeFunctions.
*
* FIXME: MakeAssignment mutates for want of a parent link...
*/
JSDefinition *resolve() {
JSParseNode *pn = this;
while (!pn->pn_defn) {
if (pn->pn_type == TOK_ASSIGN) {
pn = pn->pn_left;
continue;
}
pn = pn->lexdef();
}
return (JSDefinition *) pn;
}
bool test(uintN flag) const {
JS_ASSERT(pn_defn);
if (pn_dflags & flag)
return true;
#ifdef DEBUG
for (JSParseNode *pn = dn_uses; pn; pn = pn->pn_link) {
JS_ASSERT(!pn->pn_defn);
JS_ASSERT(!(pn->pn_dflags & flag));
}
#endif
return false;
}
bool isAssigned() const {
return test(PND_ASSIGNED);
}
bool isFunArg() const {
return test(PND_FUNARG);
}
bool isFreeVar() const {
JS_ASSERT(pn_defn);
return pn_cookie == FREE_UPVAR_COOKIE || test(PND_GVAR);
}
// Grr, windows.h or something under it #defines CONST...
#ifdef CONST
# undef CONST
#endif
enum Kind { VAR, CONST, LET, FUNCTION, ARG, UNKNOWN };
bool isBindingForm() { return int(kind()) <= int(LET); }
static const char *kindString(Kind kind);
Kind kind() {
if (PN_TYPE(this) == TOK_FUNCTION)
return FUNCTION;
JS_ASSERT(PN_TYPE(this) == TOK_NAME);
if (PN_OP(this) == JSOP_NOP)
return UNKNOWN;
if (PN_OP(this) == JSOP_GETARG)
return ARG;
if (isConst())
return CONST;
if (isLet())
return LET;
return VAR;
}
};
/*
* These two are overridden by JSDefinition and we cannot afford virtual
* methods -- so we use the mighty 'if' statement!
*/
inline bool
JSParseNode::isAssigned() const
{
#ifdef DEBUG
if (pn_defn)
return ((JSDefinition *)this)->isAssigned();
#endif
return test(PND_ASSIGNED);
}
inline bool
JSParseNode::isFunArg() const
{
#ifdef DEBUG
if (pn_defn)
return ((JSDefinition *)this)->isFunArg();
#endif
return test(PND_FUNARG);
}
inline void
JSParseNode::setFunArg()
{
/*
* pn_defn NAND pn_used must be true, per this chart:
*
* pn_defn pn_used
* 0 0 anonymous function used implicitly, e.g. by
* hidden yield in a genexp
* 0 1 a use of a definition or placeholder
* 1 0 a definition or placeholder
* 1 1 error: this case must not be possible
*/
JS_ASSERT(!(pn_defn & pn_used));
if (pn_used)
pn_lexdef->pn_dflags |= PND_FUNARG;
pn_dflags |= PND_FUNARG;
}
struct JSObjectBox {
JSObjectBox *traceLink;
JSObjectBox *emitLink;
JSObject *object;
};
#define JSFB_LEVEL_BITS 14
struct JSFunctionBox : public JSObjectBox
{
JSParseNode *node;
JSFunctionBox *siblings;
JSFunctionBox *kids;
JSFunctionBox *parent;
uint32 queued:1,
inLoop:1, /* in a loop in parent function */
level:JSFB_LEVEL_BITS,
tcflags:16;
};
struct JSFunctionBoxQueue {
JSFunctionBox **vector;
size_t head, tail;
size_t lengthMask;
size_t count() { return head - tail; }
size_t length() { return lengthMask + 1; }
JSFunctionBoxQueue()
: vector(NULL), head(0), tail(0), lengthMask(0) { }
bool init(uint32 count) {
lengthMask = JS_BITMASK(JS_CeilingLog2(count));
vector = new JSFunctionBox*[length()];
return !!vector;
}
~JSFunctionBoxQueue() { delete[] vector; }
void push(JSFunctionBox *funbox) {
if (!funbox->queued) {
JS_ASSERT(count() < length());
vector[head++ & lengthMask] = funbox;
funbox->queued = true;
}
}
JSFunctionBox *pull() {
if (tail == head)
return NULL;
JS_ASSERT(tail < head);
JSFunctionBox *funbox = vector[tail++ & lengthMask];
funbox->queued = false;
return funbox;
}
};
#define NUM_TEMP_FREELISTS 6U /* 32 to 2048 byte size classes (32 bit) */
struct JSCompiler {
JSContext *context;
JSAtomListElement *aleFreeList;
void *tempFreeList[NUM_TEMP_FREELISTS];
JSTokenStream tokenStream;
void *tempPoolMark; /* initial JSContext.tempPool mark */
JSPrincipals *principals; /* principals associated with source */
JSStackFrame *callerFrame; /* scripted caller frame for eval and dbgapi */
JSParseNode *nodeList; /* list of recyclable parse-node structs */
uint32 functionCount; /* number of functions in current unit */
JSObjectBox *traceListHead; /* list of parsed object for GC tracing */
JSTempValueRooter tempRoot; /* root to trace traceListHead */
JSCompiler(JSContext *cx, JSPrincipals *prin = NULL, JSStackFrame *cfp = NULL)
: context(cx), aleFreeList(NULL), principals(NULL), callerFrame(cfp),
nodeList(NULL), functionCount(0), traceListHead(NULL)
{
memset(tempFreeList, 0, sizeof tempFreeList);
setPrincipals(prin);
JS_ASSERT_IF(cfp, cfp->script);
}
~JSCompiler();
/*
* Initialize a compiler. Parameters are passed on to js_InitTokenStream.
* The compiler owns the arena pool "tops-of-stack" space above the current
* JSContext.tempPool mark. This means you cannot allocate from tempPool
* and save the pointer beyond the next JSCompiler destructor invocation.
*/
bool init(const jschar *base, size_t length,
FILE *fp, const char *filename, uintN lineno);
void setPrincipals(JSPrincipals *prin);
/*
* Parse a top-level JS script.
*/
JSParseNode *parse(JSObject *chain);
#if JS_HAS_XML_SUPPORT
JSParseNode *parseXMLText(JSObject *chain, bool allowList);
#endif
/*
* Allocate a new parsed object or function container from cx->tempPool.
*/
JSObjectBox *newObjectBox(JSObject *obj);
JSFunctionBox *newFunctionBox(JSObject *obj, JSParseNode *fn, JSTreeContext *tc);
/*
* Create a new function object given tree context (tc), optional name
* (atom may be null) and lambda flag (JSFUN_LAMBDA or 0).
*/
JSFunction *newFunction(JSTreeContext *tc, JSAtom *atom, uintN lambda);
/*
* Analyze the tree of functions nested within a single compilation unit,
* starting at funbox, recursively walking its kids, then following its
* siblings, their kids, etc.
*/
bool analyzeFunctions(JSFunctionBox *funbox, uint16& tcflags);
bool markFunArgs(JSFunctionBox *funbox, uintN tcflags);
void setFunctionKinds(JSFunctionBox *funbox, uint16& tcflags);
void trace(JSTracer *trc);
static bool
compileFunctionBody(JSContext *cx, JSFunction *fun, JSPrincipals *principals,
const jschar *chars, size_t length,
const char *filename, uintN lineno);
static JSScript *
compileScript(JSContext *cx, JSObject *scopeChain, JSStackFrame *callerFrame,
JSPrincipals *principals, uint32 tcflags,
const jschar *chars, size_t length,
FILE *file, const char *filename, uintN lineno,
JSString *source = NULL);
};
/*
* Convenience macro to access JSCompiler.tokenStream as a pointer.
*/
#define TS(jsc) (&(jsc)->tokenStream)
extern JSBool
js_FoldConstants(JSContext *cx, JSParseNode *pn, JSTreeContext *tc,
bool inCond = false);
JS_END_EXTERN_C
#endif /* jsparse_h___ */
|