1 ;;; js2-mode.el --- an improved JavaScript editing mode
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Version: See `js2-mode-version'
8 ;; Keywords: languages, javascript
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; This JavaScript editing mode supports:
29 ;; - strict recognition of the Ecma-262 language standard
30 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
31 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
32 ;; - accurate syntax highlighting using a recursive-descent parser
33 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
34 ;; - undeclared-variable warnings using a configurable externs framework
35 ;; - "bouncing" line indentation to choose among alternate indentation points
36 ;; - smart line-wrapping within comments and strings
38 ;; - show some or all function bodies as {...}
39 ;; - show some or all block comments as /*...*/
40 ;; - context-sensitive menu bar and popup menus
41 ;; - code browsing using the `imenu' package
42 ;; - typing helpers such as automatic insertion of matching braces/parens
43 ;; - many customization options
45 ;; To customize how it works:
46 ;; M-x customize-group RET js2-mode RET
50 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
51 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
52 ;; `js2-mode' current as the EcmaScript language standard evolves.
54 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
55 ;; customizable. It is a surprising amount of work to support customizable
56 ;; indentation. The current compromise is that the tab key lets you cycle among
57 ;; various likely indentation points, similar to the behavior of python-mode.
59 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
60 ;; and `mumamo', although it could be made to do so with some effort.
61 ;; This means that `js2-mode' is currently only useful for editing JavaScript
62 ;; files, and not for editing JavaScript within <script> tags or templates.
70 (require 'cc-cmds) ; for `c-fill-paragraph'
73 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
74 (require 'cc-langs) ; it's here in Emacs 21...
75 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77 ;;; Externs (variables presumed to be defined by the host system)
79 (defvar js2-ecma-262-externs
81 '(Array Boolean Date Error EvalError Function Infinity
82 Math NaN Number Object RangeError ReferenceError RegExp
83 String SyntaxError TypeError URIError arguments
84 decodeURI decodeURIComponent encodeURI
85 encodeURIComponent escape eval isFinite isNaN
86 parseFloat parseInt undefined unescape))
87 "Ecma-262 externs. Included in `js2-externs' by default.")
89 (defvar js2-browser-externs
92 Attr CDATASection CharacterData Comment DOMException
93 DOMImplementation Document DocumentFragment
94 DocumentType Element Entity EntityReference
95 ExceptionCode NamedNodeMap Node NodeList Notation
96 ProcessingInstruction Text
99 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
100 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
101 HTMLBodyElement HTMLButtonElement HTMLCollection
102 HTMLDListElement HTMLDirectoryElement HTMLDivElement
103 HTMLDocument HTMLElement HTMLFieldSetElement
104 HTMLFontElement HTMLFormElement HTMLFrameElement
105 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
106 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
107 HTMLImageElement HTMLInputElement HTMLIsIndexElement
108 HTMLLIElement HTMLLabelElement HTMLLegendElement
109 HTMLLinkElement HTMLMapElement HTMLMenuElement
110 HTMLMetaElement HTMLModElement HTMLOListElement
111 HTMLObjectElement HTMLOptGroupElement
112 HTMLOptionElement HTMLOptionsCollection
113 HTMLParagraphElement HTMLParamElement HTMLPreElement
114 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
115 HTMLStyleElement HTMLTableCaptionElement
116 HTMLTableCellElement HTMLTableColElement
117 HTMLTableElement HTMLTableRowElement
118 HTMLTableSectionElement HTMLTextAreaElement
119 HTMLTitleElement HTMLUListElement
122 DOMConfiguration DOMError DOMException
123 DOMImplementationList DOMImplementationSource
124 DOMLocator DOMStringList NameList TypeInfo
128 alert confirm document java navigator prompt screen
132 CSSCharsetRule CSSFontFace CSSFontFaceRule
133 CSSImportRule CSSMediaRule CSSPageRule
134 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
135 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
136 CSSValue CSSValueList Counter DOMImplementationCSS
137 DocumentCSS DocumentStyle ElementCSSInlineStyle
138 LinkStyle MediaList RGBColor Rect StyleSheet
139 StyleSheetList ViewCSS
142 EventListener EventTarget Event DocumentEvent UIEvent
143 MouseEvent MutationEvent KeyboardEvent
146 DocumentRange Range RangeException
149 XPathResult XMLHttpRequest))
151 You can cause these to be included or excluded with the custom
152 variable `js2-include-browser-externs'.")
154 (defvar js2-rhino-externs
156 '(Packages importClass importPackage com org java
157 ;; Global object (shell) externs
158 defineClass deserialize doctest gc help load
159 loadClass print quit readFile readUrl runCommand seal
160 serialize spawn sync toint32 version))
161 "Mozilla Rhino externs.
162 Set `js2-include-rhino-externs' to t to include them.")
164 (defvar js2-gears-externs
167 ;; TODO(stevey): add these
169 "Google Gears externs.
170 Set `js2-include-gears-externs' to t to include them.")
174 (defvar js2-emacs22 (>= emacs-major-version 22))
176 (defcustom js2-highlight-level 2
177 "Amount of syntax highlighting to perform.
178 0 or a negative value means do no highlighting.
179 1 adds basic syntax highlighting.
180 2 adds highlighting of some Ecma built-in properties.
181 3 adds highlighting of many Ecma built-in functions."
183 :type '(choice (const :tag "None" 0)
184 (const :tag "Basic" 1)
185 (const :tag "Include Properties" 2)
186 (const :tag "Include Functions" 3)))
188 (defvar js2-mode-dev-mode-p nil
189 "Non-nil if running in development mode. Normally nil.")
191 (defgroup js2-mode nil
192 "An improved JavaScript mode."
195 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
196 (numberp c-basic-offset))
199 "Number of spaces to indent nested statements.
200 Similar to `c-basic-offset'."
203 (make-variable-buffer-local 'js2-basic-offset)
205 ;; TODO(stevey): move this code into a separate minor mode.
206 (defcustom js2-mirror-mode nil
207 "Non-nil to insert closing brackets, parens, etc. automatically."
211 (defcustom js2-auto-indent-p nil
212 "Automatic indentation with punctuation characters.
213 If non-nil, the current line is indented when certain punctuations
218 (defcustom js2-bounce-indent-p nil
219 "Non-nil to have indent-line function choose among alternatives.
220 If nil, the indent-line function will indent to a predetermined column
221 based on heuristic guessing. If non-nil, then if the current line is
222 already indented to that predetermined column, indenting will choose
223 another likely column and indent to that spot. Repeated invocation of
224 the indent-line function will cycle among the computed alternatives.
225 See the function `js2-bounce-indent' for details."
229 (defcustom js2-consistent-level-indent-inner-bracket-p t
230 "Non-nil to make indentation level inner bracket consistent,
231 regardless of the beginning bracket position."
235 (defcustom js2-indent-on-enter-key nil
236 "Non-nil to have Enter/Return key indent the line.
237 This is unusual for Emacs modes but common in IDEs like Eclipse."
241 (defcustom js2-enter-indents-newline nil
242 "Non-nil to have Enter/Return key indent the newly-inserted line.
243 This is unusual for Emacs modes but common in IDEs like Eclipse."
247 (defcustom js2-rebind-eol-bol-keys t
248 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
249 If non-nil, bounce between bol/eol and first/last non-whitespace char."
253 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
254 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
255 Each value in the list is passed to `define-key'."
259 (defcustom js2-idle-timer-delay 0.2
260 "Delay in secs before re-parsing after user makes changes.
261 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
264 (make-variable-buffer-local 'js2-idle-timer-delay)
266 (defcustom js2-dynamic-idle-timer-adjust 0
267 "Positive to adjust `js2-idle-timer-delay' based on file size.
268 The idea is that for short files, parsing is faster so we can be
269 more responsive to user edits without interfering with editing.
270 The buffer length in characters (typically bytes) is divided by
271 this value and used to multiply `js2-idle-timer-delay' for the
272 buffer. For example, a 21k file and 10k adjust yields 21k/10k
273 == 2, so js2-idle-timer-delay is multiplied by 2.
274 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
275 `js2-idle-timer-delay' is not dependent on the file size."
279 (defcustom js2-mode-escape-quotes t
280 "Non-nil to disable automatic quote-escaping inside strings."
284 (defcustom js2-mode-squeeze-spaces t
285 "Non-nil to normalize whitespace when filling in comments.
286 Multiple runs of spaces are converted to a single space."
290 (defcustom js2-mode-show-parse-errors t
291 "True to highlight parse errors."
295 (defcustom js2-mode-show-strict-warnings t
296 "Non-nil to emit Ecma strict-mode warnings.
297 Some of the warnings can be individually disabled by other flags,
298 even if this flag is non-nil."
302 (defcustom js2-strict-trailing-comma-warning t
303 "Non-nil to warn about trailing commas in array literals.
304 Ecma-262 forbids them, but many browsers permit them. IE is the
305 big exception, and can produce bugs if you have trailing commas."
309 (defcustom js2-strict-missing-semi-warning t
310 "Non-nil to warn about semicolon auto-insertion after statement.
311 Technically this is legal per Ecma-262, but some style guides disallow
316 (defcustom js2-missing-semi-one-line-override nil
317 "Non-nil to permit missing semicolons in one-line functions.
318 In one-liner functions such as `function identity(x) {return x}'
319 people often omit the semicolon for a cleaner look. If you are
320 such a person, you can suppress the missing-semicolon warning
321 by setting this variable to t."
325 (defcustom js2-strict-inconsistent-return-warning t
326 "Non-nil to warn about mixing returns with value-returns.
327 It's perfectly legal to have a `return' and a `return foo' in the
328 same function, but it's often an indicator of a bug, and it also
329 interferes with type inference (in systems that support it.)"
333 (defcustom js2-strict-cond-assign-warning t
334 "Non-nil to warn about expressions like if (a = b).
335 This often should have been '==' instead of '='. If the warning
336 is enabled, you can suppress it on a per-expression basis by
337 parenthesizing the expression, e.g. if ((a = b)) ..."
341 (defcustom js2-strict-cond-assign-warning t
342 "Non-nil to warn about expressions like if (a = b).
343 This often should have been '==' instead of '='. If the warning
344 is enabled, you can suppress it on a per-expression basis by
345 parenthesizing the expression, e.g. if ((a = b)) ..."
349 (defcustom js2-strict-var-redeclaration-warning t
350 "Non-nil to warn about redeclaring variables in a script or function."
354 (defcustom js2-strict-var-hides-function-arg-warning t
355 "Non-nil to warn about a var decl hiding a function argument."
359 (defcustom js2-skip-preprocessor-directives nil
360 "Non-nil to treat lines beginning with # as comments.
361 Useful for viewing Mozilla JavaScript source code."
365 (defcustom js2-language-version 180
366 "Configures what JavaScript language version to recognize.
367 Currently versions 150, 160, 170 and 180 are supported, corresponding
368 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
369 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
370 and 1.8 adds function closures."
374 (defcustom js2-allow-keywords-as-property-names t
375 "If non-nil, you can use JavaScript keywords as object property names.
378 var foo = {int: 5, while: 6, continue: 7};
381 Ecma-262 forbids this syntax, but many browsers support it."
385 (defcustom js2-instanceof-has-side-effects nil
386 "If non-nil, treats the instanceof operator as having side effects.
387 This is useful for xulrunner apps."
391 (defcustom js2-cleanup-whitespace nil
392 "Non-nil to invoke `delete-trailing-whitespace' before saves."
396 (defcustom js2-move-point-on-right-click t
397 "Non-nil to move insertion point when you right-click.
398 This makes right-click context menu behavior a bit more intuitive,
399 since menu operations generally apply to the point. The exception
400 is if there is a region selection, in which case the point does -not-
401 move, so cut/copy/paste etc. can work properly.
403 Note that IntelliJ moves the point, and Eclipse leaves it alone,
404 so this behavior is customizable."
408 (defcustom js2-allow-rhino-new-expr-initializer t
409 "Non-nil to support a Rhino's experimental syntactic construct.
411 Rhino supports the ability to follow a `new' expression with an object
412 literal, which is used to set additional properties on the new object
413 after calling its constructor. Syntax:
415 new <expr> [ ( arglist ) ] [initializer]
417 Hence, this expression:
419 new Object {a: 1, b: 2}
421 results in an Object with properties a=1 and b=2. This syntax is
422 apparently not configurable in Rhino - it's currently always enabled,
423 as of Rhino version 1.7R2."
427 (defcustom js2-allow-member-expr-as-function-name nil
428 "Non-nil to support experimental Rhino syntax for function names.
430 Rhino supports an experimental syntax configured via the Rhino Context
431 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
433 function <member-expr> ( [ arg-list ] ) { <body> }
435 Where member-expr is a non-parenthesized 'member expression', which
436 is anything at the grammar level of a new-expression or lower, meaning
437 any expression that does not involve infix or unary operators.
439 When <member-expr> is not a simple identifier, then it is syntactic
440 sugar for assigning the anonymous function to the <member-expr>. Hence,
443 function a.b().c[2] (x, y) { ... }
447 a.b().c[2] = function(x, y) {...}
449 which doesn't seem particularly useful, but Rhino permits it."
453 (defvar js2-mode-version 20101228
454 "Release number for `js2-mode'.")
458 (defmacro js2-deflocal (name value &optional comment)
459 "Define a buffer-local variable NAME with VALUE and COMMENT."
461 (defvar ,name ,value ,comment)
462 (make-variable-buffer-local ',name)))
464 ;; We record the start and end position of each token.
465 (js2-deflocal js2-token-beg 1)
466 (js2-deflocal js2-token-end -1)
468 (defvar js2-EOF_CHAR -1
469 "Represents end of stream. Distinct from js2-EOF token type.")
471 ;; I originally used symbols to represent tokens, but Rhino uses
472 ;; ints and then sets various flag bits in them, so ints it is.
473 ;; The upshot is that we need a `js2-' prefix in front of each name.
474 (defvar js2-ERROR -1)
477 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
478 (defvar js2-LEAVEWITH 3)
479 (defvar js2-RETURN 4)
483 (defvar js2-SETNAME 8)
485 (defvar js2-BITXOR 10)
486 (defvar js2-BITAND 11)
496 (defvar js2-ADD 21) ; infix plus
497 (defvar js2-SUB 22) ; infix minus
502 (defvar js2-BITNOT 27)
503 (defvar js2-POS 28) ; unary plus
504 (defvar js2-NEG 29) ; unary minus
506 (defvar js2-DELPROP 31)
507 (defvar js2-TYPEOF 32)
508 (defvar js2-GETPROP 33)
509 (defvar js2-GETPROPNOWARN 34)
510 (defvar js2-SETPROP 35)
511 (defvar js2-GETELEM 36)
512 (defvar js2-SETELEM 37)
514 (defvar js2-NAME 39) ; an identifier
515 (defvar js2-NUMBER 40)
516 (defvar js2-STRING 41)
519 (defvar js2-FALSE 44)
521 (defvar js2-SHEQ 46) ; shallow equality (===)
522 (defvar js2-SHNE 47) ; shallow inequality (!==)
523 (defvar js2-REGEXP 48)
524 (defvar js2-BINDNAME 49)
525 (defvar js2-THROW 50)
526 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
528 (defvar js2-INSTANCEOF 53)
529 (defvar js2-LOCAL_LOAD 54)
530 (defvar js2-GETVAR 55)
531 (defvar js2-SETVAR 56)
532 (defvar js2-CATCH_SCOPE 57)
533 (defvar js2-ENUM_INIT_KEYS 58)
534 (defvar js2-ENUM_INIT_VALUES 59)
535 (defvar js2-ENUM_INIT_ARRAY 60)
536 (defvar js2-ENUM_NEXT 61)
537 (defvar js2-ENUM_ID 62)
538 (defvar js2-THISFN 63)
539 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
540 (defvar js2-ARRAYLIT 65) ; array literal
541 (defvar js2-OBJECTLIT 66) ; object literal
542 (defvar js2-GET_REF 67) ; *reference
543 (defvar js2-SET_REF 68) ; *reference = something
544 (defvar js2-DEL_REF 69) ; delete reference
545 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
546 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
547 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
550 (defvar js2-DEFAULTNAMESPACE 73)
551 (defvar js2-ESCXMLATTR 74)
552 (defvar js2-ESCXMLTEXT 75)
553 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
554 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
555 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
556 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
558 (defvar js2-first-bytecode js2-ENTERWITH)
559 (defvar js2-last-bytecode js2-REF_NS_NAME)
562 (defvar js2-SEMI 81) ; semicolon
563 (defvar js2-LB 82) ; left and right brackets
565 (defvar js2-LC 84) ; left and right curly-braces
567 (defvar js2-LP 86) ; left and right parens
569 (defvar js2-COMMA 88) ; comma operator
571 (defvar js2-ASSIGN 89) ; simple assignment (=)
572 (defvar js2-ASSIGN_BITOR 90) ; |=
573 (defvar js2-ASSIGN_BITXOR 91) ; ^=
574 (defvar js2-ASSIGN_BITAND 92) ; &=
575 (defvar js2-ASSIGN_LSH 93) ; <<=
576 (defvar js2-ASSIGN_RSH 94) ; >>=
577 (defvar js2-ASSIGN_URSH 95) ; >>>=
578 (defvar js2-ASSIGN_ADD 96) ; +=
579 (defvar js2-ASSIGN_SUB 97) ; -=
580 (defvar js2-ASSIGN_MUL 98) ; *=
581 (defvar js2-ASSIGN_DIV 99) ; /=
582 (defvar js2-ASSIGN_MOD 100) ; %=
584 (defvar js2-first-assign js2-ASSIGN)
585 (defvar js2-last-assign js2-ASSIGN_MOD)
587 (defvar js2-HOOK 101) ; conditional (?:)
588 (defvar js2-COLON 102)
589 (defvar js2-OR 103) ; logical or (||)
590 (defvar js2-AND 104) ; logical and (&&)
591 (defvar js2-INC 105) ; increment/decrement (++ --)
593 (defvar js2-DOT 107) ; member operator (.)
594 (defvar js2-FUNCTION 108) ; function keyword
595 (defvar js2-EXPORT 109) ; export keyword
596 (defvar js2-IMPORT 110) ; import keyword
597 (defvar js2-IF 111) ; if keyword
598 (defvar js2-ELSE 112) ; else keyword
599 (defvar js2-SWITCH 113) ; switch keyword
600 (defvar js2-CASE 114) ; case keyword
601 (defvar js2-DEFAULT 115) ; default keyword
602 (defvar js2-WHILE 116) ; while keyword
603 (defvar js2-DO 117) ; do keyword
604 (defvar js2-FOR 118) ; for keyword
605 (defvar js2-BREAK 119) ; break keyword
606 (defvar js2-CONTINUE 120) ; continue keyword
607 (defvar js2-VAR 121) ; var keyword
608 (defvar js2-WITH 122) ; with keyword
609 (defvar js2-CATCH 123) ; catch keyword
610 (defvar js2-FINALLY 124) ; finally keyword
611 (defvar js2-VOID 125) ; void keyword
612 (defvar js2-RESERVED 126) ; reserved keywords
614 (defvar js2-EMPTY 127)
616 ;; Types used for the parse tree - never returned by scanner.
618 (defvar js2-BLOCK 128) ; statement block
619 (defvar js2-LABEL 129) ; label
620 (defvar js2-TARGET 130)
621 (defvar js2-LOOP 131)
622 (defvar js2-EXPR_VOID 132) ; expression statement in functions
623 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
625 (defvar js2-SCRIPT 135) ; top-level node for entire script
626 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
627 (defvar js2-USE_STACK 137)
628 (defvar js2-SETPROP_OP 138) ; x.y op= something
629 (defvar js2-SETELEM_OP 139) ; x[y] op= something
630 (defvar js2-LOCAL_BLOCK 140)
631 (defvar js2-SET_REF_OP 141) ; *reference op= something
634 (defvar js2-DOTDOT 142) ; member operator (..)
635 (defvar js2-COLONCOLON 143) ; namespace::name
636 (defvar js2-XML 144) ; XML type
637 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
638 (defvar js2-XMLATTR 146) ; @
639 (defvar js2-XMLEND 147)
641 ;; Optimizer-only tokens
642 (defvar js2-TO_OBJECT 148)
643 (defvar js2-TO_DOUBLE 149)
645 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
646 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
647 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
648 (defvar js2-CONST 153)
649 (defvar js2-SETCONST 154)
650 (defvar js2-SETCONSTVAR 155)
651 (defvar js2-ARRAYCOMP 156)
652 (defvar js2-LETEXPR 157)
653 (defvar js2-WITHEXPR 158)
654 (defvar js2-DEBUGGER 159)
656 (defvar js2-COMMENT 160)
657 (defvar js2-ENUM 161) ; for "enum" reserved word
659 (defconst js2-num-tokens (1+ js2-ENUM))
661 (defconst js2-debug-print-trees nil)
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
675 (js2-deflocal js2-ts-regexp-flags nil
676 "Token stream buffer-local variable.")
678 (js2-deflocal js2-ts-string ""
679 "Token stream buffer-local variable.
680 Last string scanned.")
682 (js2-deflocal js2-ts-number nil
683 "Token stream buffer-local variable.
684 Last literal number scanned.")
686 (js2-deflocal js2-ts-hit-eof nil
687 "Token stream buffer-local variable.")
689 (js2-deflocal js2-ts-line-start 0
690 "Token stream buffer-local variable.")
692 (js2-deflocal js2-ts-lineno 1
693 "Token stream buffer-local variable.")
695 (js2-deflocal js2-ts-line-end-char -1
696 "Token stream buffer-local variable.")
698 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
699 "Token stream buffer-local variable.
700 Current scan position.")
702 (js2-deflocal js2-ts-is-xml-attribute nil
703 "Token stream buffer-local variable.")
705 (js2-deflocal js2-ts-xml-is-tag-content nil
706 "Token stream buffer-local variable.")
708 (js2-deflocal js2-ts-xml-open-tags-count 0
709 "Token stream buffer-local variable.")
711 (js2-deflocal js2-ts-string-buffer nil
712 "Token stream buffer-local variable.
713 List of chars built up while scanning various tokens.")
715 (js2-deflocal js2-ts-comment-type nil
716 "Token stream buffer-local variable.")
720 (js2-deflocal js2-parsed-errors nil
721 "List of errors produced during scanning/parsing.")
723 (js2-deflocal js2-parsed-warnings nil
724 "List of warnings produced during scanning/parsing.")
726 (js2-deflocal js2-recover-from-parse-errors t
727 "Non-nil to continue parsing after a syntax error.
729 In recovery mode, the AST will be built in full, and any error
730 nodes will be flagged with appropriate error information. If
731 this flag is nil, a syntax error will result in an error being
734 The variable is automatically buffer-local, because different
735 modes that use the parser will need different settings.")
737 (js2-deflocal js2-parse-hook nil
738 "List of callbacks for receiving parsing progress.")
740 (defvar js2-parse-finished-hook nil
741 "List of callbacks to notify when parsing finishes.
742 Not called if parsing was interrupted.")
744 (js2-deflocal js2-is-eval-code nil
745 "True if we're evaluating code in a string.
746 If non-nil, the tokenizer will record the token text, and the AST nodes
747 will record their source text. Off by default for IDE modes, since the
748 text is available in the buffer.")
750 (defvar js2-parse-ide-mode t
751 "Non-nil if the parser is being used for `js2-mode'.
752 If non-nil, the parser will set text properties for fontification
753 and the syntax table. The value should be nil when using the
754 parser as a frontend to an interpreter or byte compiler.")
756 ;;; Parser instance variables (buffer-local vars for js2-parse)
758 (defconst js2-clear-ti-mask #xFFFF
759 "Mask to clear token information bits.")
761 (defconst js2-ti-after-eol (lsh 1 16)
762 "Flag: first token of the source line.")
764 (defconst js2-ti-check-label (lsh 1 17)
765 "Flag: indicates to check for label.")
767 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
769 (js2-deflocal js2-compiler-generate-debug-info t)
770 (js2-deflocal js2-compiler-use-dynamic-scope nil)
771 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
772 (js2-deflocal js2-compiler-xml-available t)
773 (js2-deflocal js2-compiler-optimization-level 0)
774 (js2-deflocal js2-compiler-generating-source t)
775 (js2-deflocal js2-compiler-strict-mode nil)
776 (js2-deflocal js2-compiler-report-warning-as-error nil)
777 (js2-deflocal js2-compiler-generate-observer-count nil)
778 (js2-deflocal js2-compiler-activation-names nil)
782 ;; There's a compileFunction method in Context.java - may need it.
783 (js2-deflocal js2-called-by-compile-function nil
784 "True if `js2-parse' was called by `js2-compile-function'.
785 Will only be used when we finish implementing the interpreter.")
787 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
789 (js2-deflocal js2-current-flagged-token js2-EOF)
790 (js2-deflocal js2-current-token js2-EOF)
792 ;; SKIP: node factory - we're going to just call functions directly,
793 ;; and eventually go to a unified AST format.
795 (js2-deflocal js2-nesting-of-function 0)
797 (js2-deflocal js2-recorded-assignments nil
798 "Tracks assignments found during parsing.")
800 (defmacro js2-in-lhs (body)
801 `(let ((js2-is-in-lhs t))
804 (defmacro js2-in-rhs (body)
805 `(let ((js2-is-in-lhs nil))
808 (js2-deflocal js2-is-in-lhs nil
809 "True while parsing lhs statement")
811 (defcustom js2-global-externs nil
812 "A list of any extern names you'd like to consider always declared.
813 This list is global and is used by all js2-mode files.
814 You can create buffer-local externs list using `js2-additional-externs'.
816 There is also a buffer-local variable `js2-default-externs',
817 which is initialized by default to include the Ecma-262 externs
818 and the standard browser externs. The three lists are all
819 checked during highlighting."
823 (js2-deflocal js2-default-externs nil
824 "Default external declarations.
826 These are currently only used for highlighting undeclared variables,
827 which only worries about top-level (unqualified) references.
828 As js2-mode's processing improves, we will flesh out this list.
830 The initial value is set to `js2-ecma-262-externs', unless you
831 have set `js2-include-browser-externs', in which case the browser
832 externs are also included.
834 See `js2-additional-externs' for more information.")
836 (defcustom js2-include-browser-externs t
837 "Non-nil to include browser externs in the master externs list.
838 If you work on JavaScript files that are not intended for browsers,
839 such as Mozilla Rhino server-side JavaScript, set this to nil.
840 You can always include them on a per-file basis by calling
841 `js2-add-browser-externs' from a function on `js2-mode-hook'.
843 See `js2-additional-externs' for more information about externs."
847 (defcustom js2-include-rhino-externs t
848 "Non-nil to include Mozilla Rhino externs in the master externs list.
849 See `js2-additional-externs' for more information about externs."
853 (defcustom js2-include-gears-externs t
854 "Non-nil to include Google Gears externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
859 (js2-deflocal js2-additional-externs nil
860 "A buffer-local list of additional external declarations.
861 It is used to decide whether variables are considered undeclared
862 for purposes of highlighting.
864 Each entry is a lisp string. The string should be the fully qualified
865 name of an external entity. All externs should be added to this list,
866 so that as js2-mode's processing improves it can take advantage of them.
868 You may want to declare your externs in three ways.
869 First, you can add externs that are valid for all your JavaScript files.
870 You should probably do this by adding them to `js2-global-externs', which
871 is a global list used for all js2-mode files.
873 Next, you can add a function to `js2-mode-hook' that adds additional
874 externs appropriate for the specific file, perhaps based on its path.
875 These should go in `js2-additional-externs', which is buffer-local.
877 Finally, you can add a function to `js2-post-parse-callbacks',
878 which is called after parsing completes, and `root' is bound to
879 the root of the parse tree. At this stage you can set up an AST
880 node visitor using `js2-visit-ast' and examine the parse tree
881 for specific import patterns that may imply the existence of
882 other externs, possibly tied to your build system. These should also
883 be added to `js2-additional-externs'.
885 Your post-parse callback may of course also use the simpler and
886 faster (but perhaps less robust) approach of simply scanning the
887 buffer text for your imports, using regular expressions.")
890 ;; SKIP: encoded-source
892 ;;; The following variables are per-function and should be saved/restored
893 ;;; during function parsing...
895 (js2-deflocal js2-current-script-or-fn nil)
896 (js2-deflocal js2-current-scope nil)
897 (js2-deflocal js2-nesting-of-with 0)
898 (js2-deflocal js2-label-set nil
899 "An alist mapping label names to nodes.")
901 (js2-deflocal js2-loop-set nil)
902 (js2-deflocal js2-loop-and-switch-set nil)
903 (js2-deflocal js2-has-return-value nil)
904 (js2-deflocal js2-end-flags 0)
906 ;;; ...end of per function variables
908 ;; Without 2-token lookahead, labels are a problem.
909 ;; These vars store the token info of the last matched name,
910 ;; iff it wasn't the last matched token. Only valid in some contexts.
911 (defvar js2-prev-name-token-start nil)
912 (defvar js2-prev-name-token-string nil)
914 (defsubst js2-save-name-token-data (pos name)
915 (setq js2-prev-name-token-start pos
916 js2-prev-name-token-string name))
918 ;; These flags enumerate the possible ways a statement/function can
919 ;; terminate. These flags are used by endCheck() and by the Parser to
920 ;; detect inconsistent return usage.
922 ;; END_UNREACHED is reserved for code paths that are assumed to always be
923 ;; able to execute (example: throw, continue)
925 ;; END_DROPS_OFF indicates if the statement can transfer control to the
926 ;; next one. Statement such as return dont. A compound statement may have
927 ;; some branch that drops off control to the next statement.
929 ;; END_RETURNS indicates that the statement can return (without arguments)
930 ;; END_RETURNS_VALUE indicates that the statement can return a value.
932 ;; A compound statement such as
936 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
938 (defconst js2-end-unreached #x0)
939 (defconst js2-end-drops-off #x1)
940 (defconst js2-end-returns #x2)
941 (defconst js2-end-returns-value #x4)
942 (defconst js2-end-yields #x8)
944 ;; Rhino awkwardly passes a statementLabel parameter to the
945 ;; statementHelper() function, the main statement parser, which
946 ;; is then used by quite a few of the sub-parsers. We just make
947 ;; it a buffer-local variable and make sure it's cleaned up properly.
948 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
950 ;; Similarly, Rhino passes an inForInit boolean through about half
951 ;; the expression parsers. We use a dynamically-scoped variable,
952 ;; which makes it easier to funcall the parsers individually without
953 ;; worrying about whether they take the parameter or not.
954 (js2-deflocal js2-in-for-init nil)
955 (js2-deflocal js2-temp-name-counter 0)
956 (js2-deflocal js2-parse-stmt-count 0)
958 (defsubst js2-get-next-temp-name ()
959 (format "$%d" (incf js2-temp-name-counter)))
961 (defvar js2-parse-interruptable-p t
962 "Set this to nil to force parse to continue until finished.
963 This will mostly be useful for interpreters.")
965 (defvar js2-statements-per-pause 50
966 "Pause after this many statements to check for user input.
967 If user input is pending, stop the parse and discard the tree.
968 This makes for a smoother user experience for large files.
969 You may have to wait a second or two before the highlighting
970 and error-reporting appear, but you can always type ahead if
971 you wish. This appears to be more or less how Eclipse, IntelliJ
972 and other editors work.")
974 (js2-deflocal js2-record-comments t
975 "Instructs the scanner to record comments in `js2-scanned-comments'.")
977 (js2-deflocal js2-scanned-comments nil
978 "List of all comments from the current parse.")
980 (defcustom js2-mode-indent-inhibit-undo nil
981 "Non-nil to disable collection of Undo information when indenting lines.
982 Some users have requested this behavior. It's nil by default because
983 other Emacs modes don't work this way."
987 (defcustom js2-mode-indent-ignore-first-tab nil
988 "If non-nil, ignore first TAB keypress if we look indented properly.
989 It's fairly common for users to navigate to an already-indented line
990 and press TAB for reassurance that it's been indented. For this class
991 of users, we want the first TAB press on a line to be ignored if the
992 line is already indented to one of the precomputed alternatives.
994 This behavior is only partly implemented. If you TAB-indent a line,
995 navigate to another line, and then navigate back, it fails to clear
996 the last-indented variable, so it thinks you've already hit TAB once,
997 and performs the indent. A full solution would involve getting on the
998 point-motion hooks for the entire buffer. If we come across another
999 use cases that requires watching point motion, I'll consider doing it.
1001 If you set this variable to nil, then the TAB key will always change
1002 the indentation of the current line, if more than one alternative
1003 indentation spot exists."
1007 (defvar js2-indent-hook nil
1008 "A hook for user-defined indentation rules.
1010 Functions on this hook should expect two arguments: (LIST INDEX)
1011 The LIST argument is the list of computed indentation points for
1012 the current line. INDEX is the list index of the indentation point
1013 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1014 indent function is not going to change the current line indentation.
1016 If a hook function on this list returns a non-nil value, then
1017 `js2-bounce-indent' assumes the hook function has performed its own
1018 indentation, and will do nothing. If all hook functions on the list
1019 return nil, then `js2-bounce-indent' will use its computed indentation
1020 and reindent the line.
1022 When hook functions on this hook list are called, the variable
1023 `js2-mode-ast' may or may not be set, depending on whether the
1024 parse tree is available. If the variable is nil, you can pass a
1025 callback to `js2-mode-wait-for-parse', and your callback will be
1026 called after the new parse tree is built. This can take some time
1029 (defface js2-warning-face
1030 `((((class color) (background light))
1031 (:underline "orange"))
1032 (((class color) (background dark))
1033 (:underline "orange"))
1035 "Face for JavaScript warnings."
1038 (defface js2-error-face
1039 `((((class color) (background light))
1040 (:foreground "red"))
1041 (((class color) (background dark))
1042 (:foreground "red"))
1043 (t (:foreground "red")))
1044 "Face for JavaScript errors."
1047 (defface js2-jsdoc-tag-face
1048 '((t :foreground "SlateGray"))
1049 "Face used to highlight @whatever tags in jsdoc comments."
1052 (defface js2-jsdoc-type-face
1053 '((t :foreground "SteelBlue"))
1054 "Face used to highlight {FooBar} types in jsdoc comments."
1057 (defface js2-jsdoc-value-face
1058 '((t :foreground "PeachPuff3"))
1059 "Face used to highlight tag values in jsdoc comments."
1062 (defface js2-function-param-face
1063 '((t :foreground "SeaGreen"))
1064 "Face used to highlight function parameters in javascript."
1067 (defface js2-instance-member-face
1068 '((t :foreground "DarkOrchid"))
1069 "Face used to highlight instance variables in javascript.
1070 Not currently used."
1073 (defface js2-private-member-face
1074 '((t :foreground "PeachPuff3"))
1075 "Face used to highlight calls to private methods in javascript.
1076 Not currently used."
1079 (defface js2-private-function-call-face
1080 '((t :foreground "goldenrod"))
1081 "Face used to highlight calls to private functions in javascript.
1082 Not currently used."
1085 (defface js2-jsdoc-html-tag-name-face
1087 '((((class color) (min-colors 88) (background light))
1088 (:foreground "rosybrown"))
1089 (((class color) (min-colors 8) (background dark))
1090 (:foreground "yellow"))
1091 (((class color) (min-colors 8) (background light))
1092 (:foreground "magenta")))
1093 '((((type tty pc) (class color) (background light))
1094 (:foreground "magenta"))
1095 (((type tty pc) (class color) (background dark))
1096 (:foreground "yellow"))
1097 (t (:foreground "RosyBrown"))))
1098 "Face used to highlight jsdoc html tag names"
1101 (defface js2-jsdoc-html-tag-delimiter-face
1103 '((((class color) (min-colors 88) (background light))
1104 (:foreground "dark khaki"))
1105 (((class color) (min-colors 8) (background dark))
1106 (:foreground "green"))
1107 (((class color) (min-colors 8) (background light))
1108 (:foreground "green")))
1109 '((((type tty pc) (class color) (background light))
1110 (:foreground "green"))
1111 (((type tty pc) (class color) (background dark))
1112 (:foreground "green"))
1113 (t (:foreground "dark khaki"))))
1114 "Face used to highlight brackets in jsdoc html tags."
1117 (defface js2-magic-paren-face
1119 "Face used to color parens that will be auto-overwritten."
1122 (defcustom js2-post-parse-callbacks nil
1123 "A list of callback functions invoked after parsing finishes.
1124 Currently, the main use for this function is to add synthetic
1125 declarations to `js2-recorded-assignments', which see."
1129 (defface js2-external-variable-face
1130 '((t :foreground "orange"))
1131 "Face used to highlight assignments to undeclared variables.
1132 An undeclared variable is any variable not declared with var or let
1133 in the current scope or any lexically enclosing scope. If you assign
1134 to such a variable, then you are either expecting it to originate from
1135 another file, or you've got a potential bug."
1138 (defcustom js2-highlight-external-variables t
1139 "Non-nil to higlight assignments to undeclared variables."
1143 (defcustom js2-auto-insert-catch-block t
1144 "Non-nil to insert matching catch block on open-curly after `try'."
1148 (defvar js2-mode-map
1149 (let ((map (make-sparse-keymap))
1151 (define-key map [mouse-1] #'js2-mode-show-node)
1152 (define-key map (kbd "C-m") #'js2-enter-key)
1153 (when js2-rebind-eol-bol-keys
1154 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1155 (define-key map (kbd "C-e") #'js2-end-of-line))
1156 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1157 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1158 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1159 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1160 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1161 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1162 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1163 (define-key map (kbd "C-c C-`") #'js2-next-error)
1164 ;; also define user's preference for next-error, if available
1165 (if (setq keys (where-is-internal #'next-error))
1166 (define-key map (car keys) #'js2-next-error))
1167 (define-key map (or (car (where-is-internal #'mark-defun))
1170 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1172 #'js2-narrow-to-defun)
1173 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1174 (when js2-auto-indent-p
1176 (define-key map key #'js2-insert-and-indent))
1179 (define-key map [menu-bar javascript]
1180 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1182 (define-key map [menu-bar javascript customize-js2-mode]
1183 '(menu-item "Customize js2-mode" js2-mode-customize
1184 :help "Customize the behavior of this mode"))
1186 (define-key map [menu-bar javascript js2-force-refresh]
1187 '(menu-item "Force buffer refresh" js2-mode-reset
1188 :help "Re-parse the buffer from scratch"))
1190 (define-key map [menu-bar javascript separator-2]
1193 (define-key map [menu-bar javascript next-error]
1194 '(menu-item "Next warning or error" js2-next-error
1195 :enabled (and js2-mode-ast
1196 (or (js2-ast-root-errors js2-mode-ast)
1197 (js2-ast-root-warnings js2-mode-ast)))
1198 :help "Move to next warning or error"))
1200 (define-key map [menu-bar javascript display-errors]
1201 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1202 :visible (not js2-mode-show-parse-errors)
1203 :help "Turn on display of warnings and errors"))
1205 (define-key map [menu-bar javascript hide-errors]
1206 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1207 :visible js2-mode-show-parse-errors
1208 :help "Turn off display of warnings and errors"))
1210 (define-key map [menu-bar javascript separator-1]
1213 (define-key map [menu-bar javascript js2-toggle-function]
1214 '(menu-item "Show/collapse element" js2-mode-toggle-element
1215 :help "Hide or show function body or comment"))
1217 (define-key map [menu-bar javascript show-comments]
1218 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1219 :visible js2-mode-comments-hidden
1220 :help "Expand all hidden block comments"))
1222 (define-key map [menu-bar javascript hide-comments]
1223 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1224 :visible (not js2-mode-comments-hidden)
1225 :help "Show block comments as /*...*/"))
1227 (define-key map [menu-bar javascript show-all-functions]
1228 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1229 :visible js2-mode-functions-hidden
1230 :help "Expand all hidden function bodies"))
1232 (define-key map [menu-bar javascript hide-all-functions]
1233 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1234 :visible (not js2-mode-functions-hidden)
1235 :help "Show {...} for all top-level function bodies"))
1238 "Keymap used in `js2-mode' buffers.")
1240 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1242 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1243 "Matches a //-comment line. Must be first non-whitespace on line.
1244 First match-group is the leading whitespace.")
1246 (defvar js2-mode-hook nil)
1248 (js2-deflocal js2-mode-ast nil "Private variable.")
1249 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1250 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1251 (js2-deflocal js2-mode-parsing nil "Private variable.")
1252 (js2-deflocal js2-mode-node-overlay nil)
1254 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1255 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1257 (js2-deflocal js2-mode-fontifications nil "Private variable")
1258 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1259 (js2-deflocal js2-imenu-recorder nil "Private variable")
1260 (js2-deflocal js2-imenu-function-map nil "Private variable")
1262 (defvar js2-paragraph-start
1263 "\\(@[a-zA-Z]+\\>\\|$\\)")
1265 ;; Note that we also set a 'c-in-sws text property in html comments,
1266 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1267 (defvar js2-syntactic-ws-start
1268 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1270 (defvar js2-syntactic-ws-end
1271 "\\s \\|[\n\r/]\\|\\s!")
1273 (defvar js2-syntactic-eol
1274 (concat "\\s *\\(/\\*[^*\n\r]*"
1275 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1277 "\\(//\\|/\\*[^*\n\r]*"
1278 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1280 "Copied from `java-mode'. Needed for some cc-engine functions.")
1282 (defvar js2-comment-prefix-regexp
1285 (defvar js2-comment-start-skip
1286 "\\(//+\\|/\\*+\\)\\s *")
1288 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1289 "Non-nil to emit status messages during parsing.")
1291 (defvar js2-mode-functions-hidden nil "private variable")
1292 (defvar js2-mode-comments-hidden nil "private variable")
1294 (defvar js2-mode-syntax-table
1295 (let ((table (make-syntax-table)))
1296 (c-populate-syntax-table table)
1298 "Syntax table used in js2-mode buffers.")
1300 (defvar js2-mode-abbrev-table nil
1301 "Abbrev table in use in `js2-mode' buffers.")
1302 (define-abbrev-table 'js2-mode-abbrev-table ())
1304 (defvar js2-mode-pending-parse-callbacks nil
1305 "List of functions waiting to be notified that parse is finished.")
1307 (defvar js2-mode-last-indented-line -1)
1309 ;;; Localizable error and warning messages
1311 ;; Messages are copied from Rhino's Messages.properties.
1312 ;; Many of the Java-specific messages have been elided.
1313 ;; Add any js2-specific ones at the end, so we can keep
1314 ;; this file synced with changes to Rhino's.
1316 (defvar js2-message-table
1317 (make-hash-table :test 'equal :size 250)
1318 "Contains localized messages for js2-mode.")
1320 ;; TODO(stevey): construct this table at compile-time.
1321 (defmacro js2-msg (key &rest strings)
1322 `(puthash ,key (funcall #'concat ,@strings)
1325 (defun js2-get-msg (msg-key)
1326 "Look up a localized message.
1327 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1328 the correct number of ARGS must be provided."
1329 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1330 (args (if (listp msg-key) (cdr msg-key)))
1331 (msg (gethash key js2-message-table)))
1333 (apply #'format msg args)
1334 key))) ; default to showing the key
1336 (js2-msg "msg.dup.parms"
1337 "Duplicate parameter name '%s'.")
1339 (js2-msg "msg.too.big.jump"
1340 "Program too complex: jump offset too big.")
1342 (js2-msg "msg.too.big.index"
1343 "Program too complex: internal index exceeds 64K limit.")
1345 (js2-msg "msg.while.compiling.fn"
1346 "Encountered code generation error while compiling function '%s': %s")
1348 (js2-msg "msg.while.compiling.script"
1349 "Encountered code generation error while compiling script: %s")
1352 (js2-msg "msg.ctor.not.found"
1353 "Constructor for '%s' not found.")
1355 (js2-msg "msg.not.ctor"
1356 "'%s' is not a constructor.")
1359 (js2-msg "msg.varargs.ctor"
1360 "Method or constructor '%s' must be static "
1361 "with the signature (Context cx, Object[] args, "
1362 "Function ctorObj, boolean inNewExpr) "
1363 "to define a variable arguments constructor.")
1365 (js2-msg "msg.varargs.fun"
1366 "Method '%s' must be static with the signature "
1367 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1368 "to define a variable arguments function.")
1370 (js2-msg "msg.incompat.call"
1371 "Method '%s' called on incompatible object.")
1373 (js2-msg "msg.bad.parms"
1374 "Unsupported parameter type '%s' in method '%s'.")
1376 (js2-msg "msg.bad.method.return"
1377 "Unsupported return type '%s' in method '%s'.")
1379 (js2-msg "msg.bad.ctor.return"
1380 "Construction of objects of type '%s' is not supported.")
1382 (js2-msg "msg.no.overload"
1383 "Method '%s' occurs multiple times in class '%s'.")
1385 (js2-msg "msg.method.not.found"
1386 "Method '%s' not found in '%s'.")
1390 (js2-msg "msg.bad.for.in.lhs"
1391 "Invalid left-hand side of for..in loop.")
1393 (js2-msg "msg.mult.index"
1394 "Only one variable allowed in for..in loop.")
1396 (js2-msg "msg.bad.for.in.destruct"
1397 "Left hand side of for..in loop must be an array of "
1398 "length 2 to accept key/value pair.")
1400 (js2-msg "msg.cant.convert"
1401 "Can't convert to type '%s'.")
1403 (js2-msg "msg.bad.assign.left"
1404 "Invalid assignment left-hand side.")
1406 (js2-msg "msg.bad.decr"
1407 "Invalid decerement operand.")
1409 (js2-msg "msg.bad.incr"
1410 "Invalid increment operand.")
1412 (js2-msg "msg.bad.yield"
1413 "yield must be in a function.")
1415 (js2-msg "msg.yield.parenthesized"
1416 "yield expression must be parenthesized.")
1419 (js2-msg "msg.cant.call.indirect"
1420 "Function '%s' must be called directly, and not by way of a "
1421 "function of another name.")
1423 (js2-msg "msg.eval.nonstring"
1424 "Calling eval() with anything other than a primitive "
1425 "string value will simply return the value. "
1426 "Is this what you intended?")
1428 (js2-msg "msg.eval.nonstring.strict"
1429 "Calling eval() with anything other than a primitive "
1430 "string value is not allowed in strict mode.")
1432 (js2-msg "msg.bad.destruct.op"
1433 "Invalid destructuring assignment operator")
1436 (js2-msg "msg.only.from.new"
1437 "'%s' may only be invoked from a `new' expression.")
1439 (js2-msg "msg.deprec.ctor"
1440 "The '%s' constructor is deprecated.")
1443 (js2-msg "msg.no.function.ref.found"
1444 "no source found to decompile function reference %s")
1446 (js2-msg "msg.arg.isnt.array"
1447 "second argument to Function.prototype.apply must be an array")
1450 (js2-msg "msg.bad.esc.mask"
1451 "invalid string escape mask")
1454 (js2-msg "msg.bad.quant"
1455 "Invalid quantifier %s")
1457 (js2-msg "msg.overlarge.backref"
1458 "Overly large back reference %s")
1460 (js2-msg "msg.overlarge.min"
1461 "Overly large minimum %s")
1463 (js2-msg "msg.overlarge.max"
1464 "Overly large maximum %s")
1466 (js2-msg "msg.zero.quant"
1467 "Zero quantifier %s")
1469 (js2-msg "msg.max.lt.min"
1470 "Maximum %s less than minimum")
1472 (js2-msg "msg.unterm.quant"
1473 "Unterminated quantifier %s")
1475 (js2-msg "msg.unterm.paren"
1476 "Unterminated parenthetical %s")
1478 (js2-msg "msg.unterm.class"
1479 "Unterminated character class %s")
1481 (js2-msg "msg.bad.range"
1482 "Invalid range in character class.")
1484 (js2-msg "msg.trail.backslash"
1485 "Trailing \\ in regular expression.")
1487 (js2-msg "msg.re.unmatched.right.paren"
1488 "unmatched ) in regular expression.")
1490 (js2-msg "msg.no.regexp"
1491 "Regular expressions are not available.")
1493 (js2-msg "msg.bad.backref"
1494 "back-reference exceeds number of capturing parentheses.")
1496 (js2-msg "msg.bad.regexp.compile"
1497 "Only one argument may be specified if the first "
1498 "argument to RegExp.prototype.compile is a RegExp object.")
1501 (js2-msg "msg.got.syntax.errors"
1502 "Compilation produced %s syntax errors.")
1504 (js2-msg "msg.var.redecl"
1505 "TypeError: redeclaration of var %s.")
1507 (js2-msg "msg.const.redecl"
1508 "TypeError: redeclaration of const %s.")
1510 (js2-msg "msg.let.redecl"
1511 "TypeError: redeclaration of variable %s.")
1513 (js2-msg "msg.parm.redecl"
1514 "TypeError: redeclaration of formal parameter %s.")
1516 (js2-msg "msg.fn.redecl"
1517 "TypeError: redeclaration of function %s.")
1519 (js2-msg "msg.let.decl.not.in.block"
1520 "SyntaxError: let declaration not directly within block")
1523 (js2-msg "msg.dup.label"
1526 (js2-msg "msg.undef.label"
1529 (js2-msg "msg.bad.break"
1530 "unlabelled break must be inside loop or switch")
1532 (js2-msg "msg.continue.outside"
1533 "continue must be inside loop")
1535 (js2-msg "msg.continue.nonloop"
1536 "continue can only use labels of iteration statements")
1538 (js2-msg "msg.bad.throw.eol"
1539 "Line terminator is not allowed between the throw "
1540 "keyword and throw expression.")
1542 (js2-msg "msg.no.paren.parms"
1543 "missing ( before function parameters.")
1545 (js2-msg "msg.no.parm"
1546 "missing formal parameter")
1548 (js2-msg "msg.no.paren.after.parms"
1549 "missing ) after formal parameters")
1551 (js2-msg "msg.no.brace.body"
1552 "missing '{' before function body")
1554 (js2-msg "msg.no.brace.after.body"
1555 "missing } after function body")
1557 (js2-msg "msg.no.paren.cond"
1558 "missing ( before condition")
1560 (js2-msg "msg.no.paren.after.cond"
1561 "missing ) after condition")
1563 (js2-msg "msg.no.semi.stmt"
1564 "missing ; before statement")
1566 (js2-msg "msg.missing.semi"
1567 "missing ; after statement")
1569 (js2-msg "msg.no.name.after.dot"
1570 "missing name after . operator")
1572 (js2-msg "msg.no.name.after.coloncolon"
1573 "missing name after :: operator")
1575 (js2-msg "msg.no.name.after.dotdot"
1576 "missing name after .. operator")
1578 (js2-msg "msg.no.name.after.xmlAttr"
1579 "missing name after .@")
1581 (js2-msg "msg.no.bracket.index"
1582 "missing ] in index expression")
1584 (js2-msg "msg.no.paren.switch"
1585 "missing ( before switch expression")
1587 (js2-msg "msg.no.paren.after.switch"
1588 "missing ) after switch expression")
1590 (js2-msg "msg.no.brace.switch"
1591 "missing '{' before switch body")
1593 (js2-msg "msg.bad.switch"
1594 "invalid switch statement")
1596 (js2-msg "msg.no.colon.case"
1597 "missing : after case expression")
1599 (js2-msg "msg.double.switch.default"
1600 "double default label in the switch statement")
1602 (js2-msg "msg.no.while.do"
1603 "missing while after do-loop body")
1605 (js2-msg "msg.no.paren.for"
1606 "missing ( after for")
1608 (js2-msg "msg.no.semi.for"
1609 "missing ; after for-loop initializer")
1611 (js2-msg "msg.no.semi.for.cond"
1612 "missing ; after for-loop condition")
1614 (js2-msg "msg.in.after.for.name"
1615 "missing in after for")
1617 (js2-msg "msg.no.paren.for.ctrl"
1618 "missing ) after for-loop control")
1620 (js2-msg "msg.no.paren.with"
1621 "missing ( before with-statement object")
1623 (js2-msg "msg.no.paren.after.with"
1624 "missing ) after with-statement object")
1626 (js2-msg "msg.no.paren.after.let"
1627 "missing ( after let")
1629 (js2-msg "msg.no.paren.let"
1630 "missing ) after variable list")
1632 (js2-msg "msg.no.curly.let"
1633 "missing } after let statement")
1635 (js2-msg "msg.bad.return"
1638 (js2-msg "msg.no.brace.block"
1639 "missing } in compound statement")
1641 (js2-msg "msg.bad.label"
1644 (js2-msg "msg.bad.var"
1645 "missing variable name")
1647 (js2-msg "msg.bad.var.init"
1648 "invalid variable initialization")
1650 (js2-msg "msg.no.colon.cond"
1651 "missing : in conditional expression")
1653 (js2-msg "msg.no.paren.arg"
1654 "missing ) after argument list")
1656 (js2-msg "msg.no.bracket.arg"
1657 "missing ] after element list")
1659 (js2-msg "msg.bad.prop"
1660 "invalid property id")
1662 (js2-msg "msg.no.colon.prop"
1663 "missing : after property id")
1665 (js2-msg "msg.no.brace.prop"
1666 "missing } after property list")
1668 (js2-msg "msg.no.paren"
1669 "missing ) in parenthetical")
1671 (js2-msg "msg.reserved.id"
1672 "identifier is a reserved word")
1674 (js2-msg "msg.no.paren.catch"
1675 "missing ( before catch-block condition")
1677 (js2-msg "msg.bad.catchcond"
1678 "invalid catch block condition")
1680 (js2-msg "msg.catch.unreachable"
1681 "any catch clauses following an unqualified catch are unreachable")
1683 (js2-msg "msg.no.brace.try"
1684 "missing '{' before try block")
1686 (js2-msg "msg.no.brace.catchblock"
1687 "missing '{' before catch-block body")
1689 (js2-msg "msg.try.no.catchfinally"
1690 "'try' without 'catch' or 'finally'")
1692 (js2-msg "msg.no.return.value"
1693 "function %s does not always return a value")
1695 (js2-msg "msg.anon.no.return.value"
1696 "anonymous function does not always return a value")
1698 (js2-msg "msg.return.inconsistent"
1699 "return statement is inconsistent with previous usage")
1701 (js2-msg "msg.generator.returns"
1702 "TypeError: generator function '%s' returns a value")
1704 (js2-msg "msg.anon.generator.returns"
1705 "TypeError: anonymous generator function returns a value")
1707 (js2-msg "msg.syntax"
1710 (js2-msg "msg.unexpected.eof"
1711 "Unexpected end of file")
1713 (js2-msg "msg.XML.bad.form"
1714 "illegally formed XML syntax")
1716 (js2-msg "msg.XML.not.available"
1717 "XML runtime not available")
1719 (js2-msg "msg.too.deep.parser.recursion"
1720 "Too deep recursion while parsing")
1722 (js2-msg "msg.no.side.effects"
1723 "Code has no side effects")
1725 (js2-msg "msg.extra.trailing.comma"
1726 "Trailing comma is not legal in an ECMA-262 object initializer")
1728 (js2-msg "msg.array.trailing.comma"
1729 "Trailing comma yields different behavior across browsers")
1731 (js2-msg "msg.equal.as.assign"
1732 (concat "Test for equality (==) mistyped as assignment (=)?"
1733 " (parenthesize to suppress warning)"))
1735 (js2-msg "msg.var.hides.arg"
1736 "Variable %s hides argument")
1738 (js2-msg "msg.destruct.assign.no.init"
1739 "Missing = in destructuring declaration")
1742 (js2-msg "msg.no.properties"
1743 "%s has no properties.")
1745 (js2-msg "msg.invalid.iterator"
1746 "Invalid iterator value")
1748 (js2-msg "msg.iterator.primitive"
1749 "__iterator__ returned a primitive value")
1751 (js2-msg "msg.assn.create.strict"
1752 "Assignment to undeclared variable %s")
1754 (js2-msg "msg.ref.undefined.prop"
1755 "Reference to undefined property '%s'")
1757 (js2-msg "msg.prop.not.found"
1758 "Property %s not found.")
1760 (js2-msg "msg.invalid.type"
1761 "Invalid JavaScript value of type %s")
1763 (js2-msg "msg.primitive.expected"
1764 "Primitive type expected (had %s instead)")
1766 (js2-msg "msg.namespace.expected"
1767 "Namespace object expected to left of :: (found %s instead)")
1769 (js2-msg "msg.null.to.object"
1770 "Cannot convert null to an object.")
1772 (js2-msg "msg.undef.to.object"
1773 "Cannot convert undefined to an object.")
1775 (js2-msg "msg.cyclic.value"
1776 "Cyclic %s value not allowed.")
1778 (js2-msg "msg.is.not.defined"
1779 "'%s' is not defined.")
1781 (js2-msg "msg.undef.prop.read"
1782 "Cannot read property '%s' from %s")
1784 (js2-msg "msg.undef.prop.write"
1785 "Cannot set property '%s' of %s to '%s'")
1787 (js2-msg "msg.undef.prop.delete"
1788 "Cannot delete property '%s' of %s")
1790 (js2-msg "msg.undef.method.call"
1791 "Cannot call method '%s' of %s")
1793 (js2-msg "msg.undef.with"
1794 "Cannot apply 'with' to %s")
1796 (js2-msg "msg.isnt.function"
1797 "%s is not a function, it is %s.")
1799 (js2-msg "msg.isnt.function.in"
1800 "Cannot call property %s in object %s. "
1801 "It is not a function, it is '%s'.")
1803 (js2-msg "msg.function.not.found"
1804 "Cannot find function %s.")
1806 (js2-msg "msg.function.not.found.in"
1807 "Cannot find function %s in object %s.")
1809 (js2-msg "msg.isnt.xml.object"
1810 "%s is not an xml object.")
1812 (js2-msg "msg.no.ref.to.get"
1813 "%s is not a reference to read reference value.")
1815 (js2-msg "msg.no.ref.to.set"
1816 "%s is not a reference to set reference value to %s.")
1818 (js2-msg "msg.no.ref.from.function"
1819 "Function %s can not be used as the left-hand "
1820 "side of assignment or as an operand of ++ or -- operator.")
1822 (js2-msg "msg.bad.default.value"
1823 "Object's getDefaultValue() method returned an object.")
1825 (js2-msg "msg.instanceof.not.object"
1826 "Can't use instanceof on a non-object.")
1828 (js2-msg "msg.instanceof.bad.prototype"
1829 "'prototype' property of %s is not an object.")
1831 (js2-msg "msg.bad.radix"
1832 "illegal radix %s.")
1835 (js2-msg "msg.default.value"
1836 "Cannot find default value for object.")
1838 (js2-msg "msg.zero.arg.ctor"
1839 "Cannot load class '%s' which has no zero-parameter constructor.")
1841 (js2-msg "msg.ctor.multiple.parms"
1842 "Can't define constructor or class %s since more than "
1843 "one constructor has multiple parameters.")
1845 (js2-msg "msg.extend.scriptable"
1846 "%s must extend ScriptableObject in order to define property %s.")
1848 (js2-msg "msg.bad.getter.parms"
1849 "In order to define a property, getter %s must have zero "
1850 "parameters or a single ScriptableObject parameter.")
1852 (js2-msg "msg.obj.getter.parms"
1853 "Expected static or delegated getter %s to take "
1854 "a ScriptableObject parameter.")
1856 (js2-msg "msg.getter.static"
1857 "Getter and setter must both be static or neither be static.")
1859 (js2-msg "msg.setter.return"
1860 "Setter must have void return type: %s")
1862 (js2-msg "msg.setter2.parms"
1863 "Two-parameter setter must take a ScriptableObject as "
1864 "its first parameter.")
1866 (js2-msg "msg.setter1.parms"
1867 "Expected single parameter setter for %s")
1869 (js2-msg "msg.setter2.expected"
1870 "Expected static or delegated setter %s to take two parameters.")
1872 (js2-msg "msg.setter.parms"
1873 "Expected either one or two parameters for setter.")
1875 (js2-msg "msg.setter.bad.type"
1876 "Unsupported parameter type '%s' in setter '%s'.")
1878 (js2-msg "msg.add.sealed"
1879 "Cannot add a property to a sealed object: %s.")
1881 (js2-msg "msg.remove.sealed"
1882 "Cannot remove a property from a sealed object: %s.")
1884 (js2-msg "msg.modify.sealed"
1885 "Cannot modify a property of a sealed object: %s.")
1887 (js2-msg "msg.modify.readonly"
1888 "Cannot modify readonly property: %s.")
1891 (js2-msg "msg.missing.exponent"
1894 (js2-msg "msg.caught.nfe"
1895 "number format error")
1897 (js2-msg "msg.unterminated.string.lit"
1898 "unterminated string literal")
1900 (js2-msg "msg.unterminated.comment"
1901 "unterminated comment")
1903 (js2-msg "msg.unterminated.re.lit"
1904 "unterminated regular expression literal")
1906 (js2-msg "msg.invalid.re.flag"
1907 "invalid flag after regular expression")
1909 (js2-msg "msg.no.re.input.for"
1912 (js2-msg "msg.illegal.character"
1913 "illegal character")
1915 (js2-msg "msg.invalid.escape"
1916 "invalid Unicode escape sequence")
1918 (js2-msg "msg.bad.namespace"
1919 "not a valid default namespace statement. "
1920 "Syntax is: default xml namespace = EXPRESSION;")
1922 ;; TokensStream warnings
1923 (js2-msg "msg.bad.octal.literal"
1924 "illegal octal literal digit %s; "
1925 "interpreting it as a decimal digit")
1927 (js2-msg "msg.reserved.keyword"
1928 "illegal usage of future reserved keyword %s; "
1929 "interpreting it as ordinary identifier")
1931 (js2-msg "msg.script.is.not.constructor"
1932 "Script objects are not constructors.")
1935 (js2-msg "msg.arraylength.bad"
1936 "Inappropriate array length.")
1939 (js2-msg "msg.arraylength.too.big"
1940 "Array length %s exceeds supported capacity limit.")
1943 (js2-msg "msg.bad.uri"
1944 "Malformed URI sequence.")
1947 (js2-msg "msg.bad.precision"
1948 "Precision %s out of range.")
1951 (js2-msg "msg.send.newborn"
1952 "Attempt to send value to newborn generator")
1954 (js2-msg "msg.already.exec.gen"
1955 "Already executing generator")
1957 (js2-msg "msg.StopIteration.invalid"
1958 "StopIteration may not be changed to an arbitrary object.")
1961 (js2-msg "msg.yield.closing"
1962 "Yield from closing generator")
1966 (defun js2-delete-if (predicate list)
1967 "Remove all items satisfying PREDICATE in LIST."
1968 (loop for item in list
1969 if (not (funcall predicate item))
1972 (defun js2-position (element list)
1973 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1974 Returns nil if element is not found in the list."
1977 (while (and list (not found))
1978 (if (eq element (car list))
1980 (setq count (1+ count)
1984 (defun js2-find-if (predicate list)
1985 "Find first item satisfying PREDICATE in LIST."
1987 (while (and list (not result))
1988 (if (funcall predicate (car list))
1989 (setq result (car list)))
1990 (setq list (cdr list)))
1993 (defmacro js2-time (form)
1994 "Evaluate FORM, discard result, and return elapsed time in sec"
1996 (let ((beg (make-symbol "--js2-time-beg--"))
1997 (delta (make-symbol "--js2-time-end--")))
1998 `(let ((,beg (current-time))
2001 (/ (truncate (* (- (float-time (current-time))
2006 (defsubst js2-same-line (pos)
2007 "Return t if POS is on the same line as current point."
2008 (and (>= pos (point-at-bol))
2009 (<= pos (point-at-eol))))
2011 (defsubst js2-same-line-2 (p1 p2)
2012 "Return t if p1 is on the same line as p2."
2015 (js2-same-line p2)))
2017 (defun js2-code-bug ()
2018 "Signal an error when we encounter an unexpected code path."
2019 (error "failed assertion"))
2021 ;; I'd like to associate errors with nodes, but for now the
2022 ;; easiest thing to do is get the context info from the last token.
2023 (defsubst js2-record-parse-error (msg &optional arg pos len)
2024 (push (list (list msg arg)
2025 (or pos js2-token-beg)
2026 (or len (- js2-token-end js2-token-beg)))
2029 (defsubst js2-report-error (msg &optional msg-arg pos len)
2030 "Signal a syntax error or record a parse error."
2031 (if js2-recover-from-parse-errors
2032 (js2-record-parse-error msg msg-arg pos len)
2033 (signal 'js2-syntax-error
2037 (goto-char js2-ts-cursor)
2041 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2042 (if js2-compiler-report-warning-as-error
2043 (js2-report-error msg msg-arg pos len)
2044 (push (list (list msg msg-arg)
2045 (or pos js2-token-beg)
2046 (or len (- js2-token-end js2-token-beg)))
2047 js2-parsed-warnings)))
2049 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2050 (if js2-compiler-strict-mode
2051 (js2-report-warning msg-id msg-arg beg
2052 (and beg end (- end beg)))))
2054 (put 'js2-syntax-error 'error-conditions
2055 '(error syntax-error js2-syntax-error))
2056 (put 'js2-syntax-error 'error-message "Syntax error")
2058 (put 'js2-parse-error 'error-conditions
2059 '(error parse-error js2-parse-error))
2060 (put 'js2-parse-error 'error-message "Parse error")
2062 (defmacro js2-clear-flag (flags flag)
2063 `(setq ,flags (logand ,flags (lognot ,flag))))
2065 (defmacro js2-set-flag (flags flag)
2066 "Logical-or FLAG into FLAGS."
2067 `(setq ,flags (logior ,flags ,flag)))
2069 (defsubst js2-flag-set-p (flags flag)
2070 (/= 0 (logand flags flag)))
2072 (defsubst js2-flag-not-set-p (flags flag)
2073 (zerop (logand flags flag)))
2075 ;; Stolen shamelessly from James Clark's nxml-mode.
2076 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2077 "Evaluate BODY without any text property changes modifying the buffer.
2078 Any text properties changes happen as usual but the changes are not treated as
2079 modifications to the buffer."
2080 (declare (indent 0) (debug t))
2081 (let ((modified (make-symbol "modified")))
2082 `(let ((,modified (buffer-modified-p))
2083 (inhibit-read-only t)
2084 (inhibit-modification-hooks t)
2085 (buffer-undo-list t)
2086 (deactivate-mark nil)
2087 ;; Apparently these avoid file locking problems.
2088 (buffer-file-name nil)
2089 (buffer-file-truename nil))
2093 (restore-buffer-modified-p nil))))))
2095 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2096 "Evaluate BODY with the _ character set to be word-syntax."
2097 (declare (indent 0) (debug t))
2098 (let ((old-syntax (make-symbol "old-syntax")))
2099 `(let ((,old-syntax (string (char-syntax ?_))))
2102 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2104 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2106 (defsubst js2-char-uppercase-p (c)
2107 "Return t if C is an uppercase character.
2108 Handles unicode and latin chars properly."
2109 (/= c (downcase c)))
2111 (defsubst js2-char-lowercase-p (c)
2112 "Return t if C is an uppercase character.
2113 Handles unicode and latin chars properly."
2116 ;;; AST struct and function definitions
2118 ;; flags for ast node property 'member-type (used for e4x operators)
2119 (defvar js2-property-flag #x1 "property access: element is valid name")
2120 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2121 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2123 (defsubst js2-relpos (pos anchor)
2124 "Convert POS to be relative to ANCHOR.
2125 If POS is nil, returns nil."
2126 (and pos (- pos anchor)))
2128 (defsubst js2-make-pad (indent)
2131 (make-string (* indent js2-basic-offset) ? )))
2133 (defsubst js2-visit-ast (node callback)
2134 "Visit every node in ast NODE with visitor CALLBACK.
2136 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2137 called twice: once to visit the node, and again after all the node's
2138 children have been processed. The END-P argument is nil on the first
2139 call and non-nil on the second call. The return value of the callback
2140 affects the traversal: if non-nil, the children of NODE are processed.
2141 If the callback returns nil, or if the node has no children, then the
2142 callback is called immediately with a non-nil END-P argument.
2144 The node traversal is approximately lexical-order, although there
2145 are currently no guarantees around this."
2146 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2148 (when (funcall callback node nil)
2151 ((eq vfunc 'js2-visit-none)
2152 nil) ; don't even bother calling it
2153 ;; Each AST node type has to define a `js2-visitor' function
2154 ;; that takes a node and a callback, and calls `js2-visit-ast'
2155 ;; on each child of the node.
2157 (funcall vfunc node callback))
2159 (error "%s does not define a visitor-traversal function"
2161 ;; call the end-visit
2162 (funcall callback node t)))
2164 (defstruct (js2-node
2165 (:constructor nil)) ; abstract
2166 "Base AST node type."
2167 (type -1) ; token type
2168 (pos -1) ; start position of this AST node in parsed input
2169 (len 1) ; num characters spanned by the node
2170 props ; optional node property list (an alist)
2171 parent) ; link to parent node; null for root
2173 (defsubst js2-node-get-prop (node prop &optional default)
2174 (or (cadr (assoc prop (js2-node-props node))) default))
2176 (defsubst js2-node-set-prop (node prop value)
2177 (setf (js2-node-props node)
2178 (cons (list prop value) (js2-node-props node))))
2180 (defsubst js2-fixup-starts (n nodes)
2181 "Adjust the start positions of NODES to be relative to N.
2182 Any node in the list may be nil, for convenience."
2183 (dolist (node nodes)
2185 (setf (js2-node-pos node) (- (js2-node-pos node)
2186 (js2-node-pos n))))))
2188 (defsubst js2-node-add-children (parent &rest nodes)
2189 "Set parent node of NODES to PARENT, and return PARENT.
2190 Does nothing if we're not recording parent links.
2191 If any given node in NODES is nil, doesn't record that link."
2192 (js2-fixup-starts parent nodes)
2193 (dolist (node nodes)
2195 (setf (js2-node-parent node) parent))))
2197 ;; Non-recursive since it's called a frightening number of times.
2198 (defsubst js2-node-abs-pos (n)
2199 (let ((pos (js2-node-pos n)))
2200 (while (setq n (js2-node-parent n))
2201 (setq pos (+ pos (js2-node-pos n))))
2204 (defsubst js2-node-abs-end (n)
2205 "Return absolute buffer position of end of N."
2206 (+ (js2-node-abs-pos n) (js2-node-len n)))
2208 ;; It's important to make sure block nodes have a lisp list for the
2209 ;; child nodes, to limit printing recursion depth in an AST that
2210 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2211 ;; a sufficiently large vector tree.
2213 (defstruct (js2-block-node
2216 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2221 "A block of statements."
2222 kids) ; a lisp list of the child statement nodes
2224 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2225 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2227 (defsubst js2-visit-block (ast callback)
2228 "Visit the `js2-block-node' children of AST."
2229 (dolist (kid (js2-block-node-kids ast))
2230 (js2-visit-ast kid callback)))
2232 (defun js2-print-block (n i)
2233 (let ((pad (js2-make-pad i)))
2235 (dolist (kid (js2-block-node-kids n))
2236 (js2-print-ast kid (1+ i)))
2239 (defstruct (js2-scope
2240 (:include js2-block-node)
2242 (:constructor make-js2-scope (&key (type js2-BLOCK)
2246 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2247 ;; I don't have one of those handy, so I'll use an alist for now.
2248 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2249 ;; and is much lighter-weight to construct (both CPU and mem).
2250 ;; The keys are interned strings (symbols) for faster lookup.
2251 ;; Should switch to hybrid alist/hashtable eventually.
2252 symbol-table ; an alist of (symbol . js2-symbol)
2253 parent-scope ; a `js2-scope'
2254 top) ; top-level `js2-scope' (script/function)
2256 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2257 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2259 (defun js2-scope-set-parent-scope (scope parent)
2260 (setf (js2-scope-parent-scope scope) parent
2261 (js2-scope-top scope) (if (null parent)
2263 (js2-scope-top parent))))
2265 (defun js2-node-get-enclosing-scope (node)
2266 "Return the innermost `js2-scope' node surrounding NODE.
2267 Returns nil if there is no enclosing scope node."
2268 (let ((parent (js2-node-parent node)))
2269 (while (not (js2-scope-p parent))
2270 (setq parent (js2-node-parent parent)))
2273 (defun js2-get-defining-scope (scope name)
2274 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2275 Returns `js2-scope' in which NAME is defined, or nil if not found."
2276 (let ((sym (if (symbolp name)
2282 (while (and scope continue)
2283 (if (and (setq table (js2-scope-symbol-table scope))
2287 (setq scope (js2-scope-parent-scope scope))))
2290 (defsubst js2-scope-get-symbol (scope name)
2291 "Return symbol table entry for NAME in SCOPE.
2292 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2293 (and (js2-scope-symbol-table scope)
2294 (cdr (assq (if (symbolp name)
2297 (js2-scope-symbol-table scope)))))
2299 (defsubst js2-scope-put-symbol (scope name symbol)
2300 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2301 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2302 (let* ((table (js2-scope-symbol-table scope))
2303 (sym (if (symbolp name) name (intern name)))
2304 (entry (assq sym table)))
2306 (setcdr entry symbol)
2307 (push (cons sym symbol)
2308 (js2-scope-symbol-table scope)))))
2310 (defstruct (js2-symbol
2312 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2313 "A symbol table entry."
2314 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2315 ;; js2-LET, or js2-CONST
2318 ast-node) ; a `js2-node'
2320 (defstruct (js2-error-node
2322 (:constructor nil) ; silence emacs21 byte-compiler
2323 (:constructor make-js2-error-node (&key (type js2-ERROR)
2326 "AST node representing a parse error.")
2328 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2329 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2331 (defstruct (js2-script-node
2332 (:include js2-scope)
2334 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2339 functions ; lisp list of nested functions
2340 regexps ; lisp list of (string . flags)
2341 symbols ; alist (every symbol gets unique index)
2343 var-names ; vector of string names
2344 consts ; bool-vector matching var-decls
2345 (temp-number 0)) ; for generating temp variables
2347 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2348 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2350 (defun js2-print-script (node indent)
2351 (dolist (kid (js2-block-node-kids node))
2352 (js2-print-ast kid indent)))
2354 (defstruct (js2-ast-root
2355 (:include js2-script-node)
2357 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2361 "The root node of a js2 AST."
2362 buffer ; the source buffer from which the code was parsed
2363 comments ; a lisp list of comments, ordered by start position
2364 errors ; a lisp list of errors found during parsing
2365 warnings ; a lisp list of warnings found during parsing
2366 node-count) ; number of nodes in the tree, including the root
2368 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2369 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2371 (defun js2-visit-ast-root (ast callback)
2372 (dolist (kid (js2-ast-root-kids ast))
2373 (js2-visit-ast kid callback))
2374 (dolist (comment (js2-ast-root-comments ast))
2375 (js2-visit-ast comment callback)))
2377 (defstruct (js2-comment-node
2380 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2383 (format js2-ts-comment-type))))
2384 format) ; 'line, 'block, 'jsdoc or 'html
2386 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2387 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2389 (defun js2-print-comment (n i)
2390 ;; We really ought to link end-of-line comments to their nodes.
2391 ;; Or maybe we could add a new comment type, 'endline.
2392 (insert (js2-make-pad i)
2393 (js2-node-string n)))
2395 (defstruct (js2-expr-stmt-node
2398 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2402 "An expression statement."
2405 (defsubst js2-expr-stmt-node-set-has-result (node)
2406 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2407 (setf (js2-node-type node) js2-EXPR_RESULT))
2409 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2410 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2412 (defun js2-visit-expr-stmt-node (n v)
2413 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2415 (defun js2-print-expr-stmt-node (n indent)
2416 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2419 (defstruct (js2-loop-node
2420 (:include js2-scope)
2422 "Abstract supertype of loop nodes."
2423 body ; a `js2-block-node'
2424 lp ; position of left-paren, nil if omitted
2425 rp) ; position of right-paren, nil if omitted
2427 (defstruct (js2-do-node
2428 (:include js2-loop-node)
2430 (:constructor make-js2-do-node (&key (type js2-DO)
2438 "AST node for do-loop."
2439 condition ; while (expression)
2440 while-pos) ; buffer position of 'while' keyword
2442 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2443 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2445 (defun js2-visit-do-node (n v)
2446 (js2-visit-ast (js2-do-node-body n) v)
2447 (js2-visit-ast (js2-do-node-condition n) v))
2449 (defun js2-print-do-node (n i)
2450 (let ((pad (js2-make-pad i)))
2451 (insert pad "do {\n")
2452 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2453 (js2-print-ast kid (1+ i)))
2454 (insert pad "} while (")
2455 (js2-print-ast (js2-do-node-condition n) 0)
2458 (defstruct (js2-while-node
2459 (:include js2-loop-node)
2461 (:constructor make-js2-while-node (&key (type js2-WHILE)
2468 "AST node for while-loop."
2469 condition) ; while-condition
2471 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2472 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2474 (defun js2-visit-while-node (n v)
2475 (js2-visit-ast (js2-while-node-condition n) v)
2476 (js2-visit-ast (js2-while-node-body n) v))
2478 (defun js2-print-while-node (n i)
2479 (let ((pad (js2-make-pad i)))
2480 (insert pad "while (")
2481 (js2-print-ast (js2-while-node-condition n) 0)
2483 (js2-print-body (js2-while-node-body n) (1+ i))
2484 (insert pad "}\n")))
2486 (defstruct (js2-for-node
2487 (:include js2-loop-node)
2489 (:constructor make-js2-for-node (&key (type js2-FOR)
2498 "AST node for a C-style for-loop."
2499 init ; initialization expression
2500 condition ; loop condition
2501 update) ; update clause
2503 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2504 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2506 (defun js2-visit-for-node (n v)
2507 (js2-visit-ast (js2-for-node-init n) v)
2508 (js2-visit-ast (js2-for-node-condition n) v)
2509 (js2-visit-ast (js2-for-node-update n) v)
2510 (js2-visit-ast (js2-for-node-body n) v))
2512 (defun js2-print-for-node (n i)
2513 (let ((pad (js2-make-pad i)))
2514 (insert pad "for (")
2515 (js2-print-ast (js2-for-node-init n) 0)
2517 (js2-print-ast (js2-for-node-condition n) 0)
2519 (js2-print-ast (js2-for-node-update n) 0)
2521 (js2-print-body (js2-for-node-body n) (1+ i))
2522 (insert pad "}\n")))
2524 (defstruct (js2-for-in-node
2525 (:include js2-loop-node)
2527 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2538 "AST node for a for..in loop."
2539 iterator ; [var] foo in ...
2540 object ; object over which we're iterating
2541 in-pos ; buffer position of 'in' keyword
2542 each-pos ; buffer position of 'each' keyword, if foreach-p
2543 foreach-p) ; t if it's a for-each loop
2545 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2546 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2548 (defun js2-visit-for-in-node (n v)
2549 (js2-visit-ast (js2-for-in-node-iterator n) v)
2550 (js2-visit-ast (js2-for-in-node-object n) v)
2551 (js2-visit-ast (js2-for-in-node-body n) v))
2553 (defun js2-print-for-in-node (n i)
2554 (let ((pad (js2-make-pad i))
2555 (foreach (js2-for-in-node-foreach-p n)))
2560 (js2-print-ast (js2-for-in-node-iterator n) 0)
2562 (js2-print-ast (js2-for-in-node-object n) 0)
2564 (js2-print-body (js2-for-in-node-body n) (1+ i))
2565 (insert pad "}\n")))
2567 (defstruct (js2-return-node
2570 (:constructor make-js2-return-node (&key (type js2-RETURN)
2574 "AST node for a return statement."
2575 retval) ; expression to return, or 'undefined
2577 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2578 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2580 (defun js2-visit-return-node (n v)
2581 (if (js2-return-node-retval n)
2582 (js2-visit-ast (js2-return-node-retval n) v)))
2584 (defun js2-print-return-node (n i)
2585 (insert (js2-make-pad i) "return")
2586 (when (js2-return-node-retval n)
2588 (js2-print-ast (js2-return-node-retval n) 0))
2591 (defstruct (js2-if-node
2594 (:constructor make-js2-if-node (&key (type js2-IF)
2603 "AST node for an if-statement."
2604 condition ; expression
2605 then-part ; statement or block
2606 else-pos ; optional buffer position of 'else' keyword
2607 else-part ; optional statement or block
2608 lp ; position of left-paren, nil if omitted
2609 rp) ; position of right-paren, nil if omitted
2611 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2612 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2614 (defun js2-visit-if-node (n v)
2615 (js2-visit-ast (js2-if-node-condition n) v)
2616 (js2-visit-ast (js2-if-node-then-part n) v)
2617 (if (js2-if-node-else-part n)
2618 (js2-visit-ast (js2-if-node-else-part n) v)))
2620 (defun js2-print-if-node (n i)
2621 (let ((pad (js2-make-pad i))
2622 (then-part (js2-if-node-then-part n))
2623 (else-part (js2-if-node-else-part n)))
2625 (js2-print-ast (js2-if-node-condition n) 0)
2627 (js2-print-body then-part (1+ i))
2632 ((js2-if-node-p else-part)
2634 (js2-print-body else-part i))
2636 (insert " else {\n")
2637 (js2-print-body else-part (1+ i))
2638 (insert pad "}\n")))))
2640 (defstruct (js2-try-node
2643 (:constructor make-js2-try-node (&key (type js2-TRY)
2649 "AST node for a try-statement."
2651 catch-clauses ; a lisp list of `js2-catch-node'
2652 finally-block) ; a `js2-finally-node'
2654 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2655 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2657 (defun js2-visit-try-node (n v)
2658 (js2-visit-ast (js2-try-node-try-block n) v)
2659 (dolist (clause (js2-try-node-catch-clauses n))
2660 (js2-visit-ast clause v))
2661 (if (js2-try-node-finally-block n)
2662 (js2-visit-ast (js2-try-node-finally-block n) v)))
2664 (defun js2-print-try-node (n i)
2665 (let ((pad (js2-make-pad i))
2666 (catches (js2-try-node-catch-clauses n))
2667 (finally (js2-try-node-finally-block n)))
2668 (insert pad "try {\n")
2669 (js2-print-body (js2-try-node-try-block n) (1+ i))
2672 (dolist (catch catches)
2673 (js2-print-ast catch i)))
2675 (js2-print-ast finally i)
2678 (defstruct (js2-catch-node
2681 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2690 "AST node for a catch clause."
2691 var-name ; a `js2-name-node'
2692 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2693 guard-expr ; catch condition, a `js2-node'
2694 block ; statements, a `js2-block-node'
2695 lp ; buffer position of left-paren, nil if omitted
2696 rp) ; buffer position of right-paren, nil if omitted
2698 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2699 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2701 (defun js2-visit-catch-node (n v)
2702 (js2-visit-ast (js2-catch-node-var-name n) v)
2703 (when (js2-catch-node-guard-kwd n)
2704 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2705 (js2-visit-ast (js2-catch-node-block n) v))
2707 (defun js2-print-catch-node (n i)
2708 (let ((pad (js2-make-pad i))
2709 (guard-kwd (js2-catch-node-guard-kwd n))
2710 (guard-expr (js2-catch-node-guard-expr n)))
2712 (js2-print-ast (js2-catch-node-var-name n) 0)
2715 (js2-print-ast guard-expr 0))
2717 (js2-print-body (js2-catch-node-block n) (1+ i))
2720 (defstruct (js2-finally-node
2723 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2727 "AST node for a finally clause."
2728 body) ; a `js2-node', often but not always a block node
2730 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2731 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2733 (defun js2-visit-finally-node (n v)
2734 (js2-visit-ast (js2-finally-node-body n) v))
2736 (defun js2-print-finally-node (n i)
2737 (let ((pad (js2-make-pad i)))
2738 (insert " finally {\n")
2739 (js2-print-body (js2-finally-node-body n) (1+ i))
2740 (insert pad "}\n")))
2742 (defstruct (js2-switch-node
2745 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2752 "AST node for a switch statement."
2753 discriminant ; a `js2-node' (switch expression)
2754 cases ; a lisp list of `js2-case-node'
2755 lp ; position of open-paren for discriminant, nil if omitted
2756 rp) ; position of close-paren for discriminant, nil if omitted
2758 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2759 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2761 (defun js2-visit-switch-node (n v)
2762 (js2-visit-ast (js2-switch-node-discriminant n) v)
2763 (dolist (c (js2-switch-node-cases n))
2764 (js2-visit-ast c v)))
2766 (defun js2-print-switch-node (n i)
2767 (let ((pad (js2-make-pad i))
2768 (cases (js2-switch-node-cases n)))
2769 (insert pad "switch (")
2770 (js2-print-ast (js2-switch-node-discriminant n) 0)
2772 (dolist (case cases)
2773 (js2-print-ast case i))
2774 (insert pad "}\n")))
2776 (defstruct (js2-case-node
2777 (:include js2-block-node)
2779 (:constructor make-js2-case-node (&key (type js2-CASE)
2784 "AST node for a case clause of a switch statement."
2785 expr) ; the case expression (nil for default)
2787 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2788 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2790 (defun js2-visit-case-node (n v)
2791 (if (js2-case-node-expr n) ; nil for default: case
2792 (js2-visit-ast (js2-case-node-expr n) v))
2793 (js2-visit-block n v))
2795 (defun js2-print-case-node (n i)
2796 (let ((pad (js2-make-pad i))
2797 (expr (js2-case-node-expr n)))
2800 (insert "default:\n")
2802 (js2-print-ast expr 0)
2804 (dolist (kid (js2-case-node-kids n))
2805 (js2-print-ast kid (1+ i)))))
2807 (defstruct (js2-throw-node
2810 (:constructor make-js2-throw-node (&key (type js2-THROW)
2814 "AST node for a throw statement."
2815 expr) ; the expression to throw
2817 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2818 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2820 (defun js2-visit-throw-node (n v)
2821 (js2-visit-ast (js2-throw-node-expr n) v))
2823 (defun js2-print-throw-node (n i)
2824 (insert (js2-make-pad i) "throw ")
2825 (js2-print-ast (js2-throw-node-expr n) 0)
2828 (defstruct (js2-with-node
2831 (:constructor make-js2-with-node (&key (type js2-WITH)
2838 "AST node for a with-statement."
2841 lp ; buffer position of left-paren around object, nil if omitted
2842 rp) ; buffer position of right-paren around object, nil if omitted
2844 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2845 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2847 (defun js2-visit-with-node (n v)
2848 (js2-visit-ast (js2-with-node-object n) v)
2849 (js2-visit-ast (js2-with-node-body n) v))
2851 (defun js2-print-with-node (n i)
2852 (let ((pad (js2-make-pad i)))
2853 (insert pad "with (")
2854 (js2-print-ast (js2-with-node-object n) 0)
2856 (js2-print-body (js2-with-node-body n) (1+ i))
2857 (insert pad "}\n")))
2859 (defstruct (js2-label-node
2862 (:constructor make-js2-label-node (&key (type js2-LABEL)
2866 "AST node for a statement label or case label."
2868 loop) ; for validating and code-generating continue-to-label
2870 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2871 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2873 (defun js2-print-label (n i)
2874 (insert (js2-make-pad i)
2875 (js2-label-node-name n)
2878 (defstruct (js2-labeled-stmt-node
2881 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2882 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2883 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2888 "AST node for a statement with one or more labels.
2889 Multiple labels for a statement are collapsed into the labels field."
2890 labels ; lisp list of `js2-label-node'
2891 stmt) ; the statement these labels are for
2893 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2894 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2896 (defun js2-get-label-by-name (lbl-stmt name)
2897 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2898 Returns nil if no such label is in the list."
2899 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2901 (while (and label-list (not result))
2902 (if (string= (js2-label-node-name (car label-list)) name)
2903 (setq result (car label-list))
2904 (setq label-list (cdr label-list))))
2907 (defun js2-visit-labeled-stmt (n v)
2908 (dolist (label (js2-labeled-stmt-node-labels n))
2909 (js2-visit-ast label v))
2910 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2912 (defun js2-print-labeled-stmt (n i)
2913 (dolist (label (js2-labeled-stmt-node-labels n))
2914 (js2-print-ast label i))
2915 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2917 (defun js2-labeled-stmt-node-contains (node label)
2918 "Return t if NODE contains LABEL in its label set.
2919 NODE is a `js2-labels-node'. LABEL is an identifier."
2920 (loop for nl in (js2-labeled-stmt-node-labels node)
2921 if (string= label (js2-label-node-name nl))
2923 finally return nil))
2925 (defsubst js2-labeled-stmt-node-add-label (node label)
2926 "Add a `js2-label-node' to the label set for this statement."
2927 (setf (js2-labeled-stmt-node-labels node)
2928 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2930 (defstruct (js2-jump-node
2933 "Abstract supertype of break and continue nodes."
2934 label ; `js2-name-node' for location of label identifier, if present
2935 target) ; target js2-labels-node or loop/switch statement
2937 (defun js2-visit-jump-node (n v)
2938 ;; we don't visit the target, since it's a back-link
2939 (if (js2-jump-node-label n)
2940 (js2-visit-ast (js2-jump-node-label n) v)))
2942 (defstruct (js2-break-node
2943 (:include js2-jump-node)
2945 (:constructor make-js2-break-node (&key (type js2-BREAK)
2950 "AST node for a break statement.
2951 The label field is a `js2-name-node', possibly nil, for the named label
2952 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2953 is the target of the break - a label node or enclosing loop/switch statement.")
2955 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2956 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2958 (defun js2-print-break-node (n i)
2959 (insert (js2-make-pad i) "break")
2960 (when (js2-break-node-label n)
2962 (js2-print-ast (js2-break-node-label n) 0))
2965 (defstruct (js2-continue-node
2966 (:include js2-jump-node)
2968 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2973 "AST node for a continue statement.
2974 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2975 It is nil if continue specifies no label. The target field is the jump target:
2976 a `js2-label-node' or the innermost enclosing loop.")
2978 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2979 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2981 (defun js2-print-continue-node (n i)
2982 (insert (js2-make-pad i) "continue")
2983 (when (js2-continue-node-label n)
2985 (js2-print-ast (js2-continue-node-label n) 0))
2988 (defstruct (js2-function-node
2989 (:include js2-script-node)
2991 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2995 (form 'FUNCTION_STATEMENT)
3001 "AST node for a function declaration.
3002 The `params' field is a lisp list of nodes. Each node is either a simple
3003 `js2-name-node', or if it's a destructuring-assignment parameter, a
3004 `js2-array-node' or `js2-object-node'."
3005 ftype ; FUNCTION, GETTER or SETTER
3006 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3007 name ; function name (a `js2-name-node', or nil if anonymous)
3008 params ; a lisp list of destructuring forms or simple name nodes
3009 body ; a `js2-block-node' or expression node (1.8 only)
3010 lp ; position of arg-list open-paren, or nil if omitted
3011 rp ; position of arg-list close-paren, or nil if omitted
3012 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3013 needs-activation ; t if we need an activation object for this frame
3014 is-generator ; t if this function contains a yield
3015 member-expr) ; nonstandard Ecma extension from Rhino
3017 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3018 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3020 (defun js2-visit-function-node (n v)
3021 (if (js2-function-node-name n)
3022 (js2-visit-ast (js2-function-node-name n) v))
3023 (dolist (p (js2-function-node-params n))
3024 (js2-visit-ast p v))
3025 (when (js2-function-node-body n)
3026 (js2-visit-ast (js2-function-node-body n) v)))
3028 (defun js2-print-function-node (n i)
3029 (let ((pad (js2-make-pad i))
3030 (getter (js2-node-get-prop n 'GETTER_SETTER))
3031 (name (js2-function-node-name n))
3032 (params (js2-function-node-params n))
3033 (body (js2-function-node-body n))
3034 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3036 (insert pad "function"))
3039 (js2-print-ast name 0))
3041 (loop with len = (length params)
3045 (js2-print-ast param 0)
3051 ;; TODO: fix this to be smarter about indenting, etc.
3052 (js2-print-body body (1+ i))
3057 (defsubst js2-function-name (node)
3058 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3059 (and (js2-function-node-name node)
3060 (js2-name-node-name (js2-function-node-name node))))
3062 ;; Having this be an expression node makes it more flexible.
3063 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3064 ;; that work better if you assume it's an expression. Whenever we have
3065 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3066 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3067 (defstruct (js2-var-decl-node
3070 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3075 "AST node for a variable declaration list (VAR, CONST or LET).
3076 The node bounds differ depending on the declaration type. For VAR or
3077 CONST declarations, the bounds include the var/const keyword. For LET
3078 declarations, the node begins at the position of the first child."
3079 kids ; a lisp list of `js2-var-init-node' structs.
3080 decl-type) ; js2-VAR, js2-CONST or js2-LET
3082 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3083 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3085 (defun js2-visit-var-decl (n v)
3086 (dolist (kid (js2-var-decl-node-kids n))
3087 (js2-visit-ast kid v)))
3089 (defun js2-print-var-decl (n i)
3090 (let ((pad (js2-make-pad i))
3091 (tt (js2-var-decl-node-decl-type n)))
3094 ((= tt js2-VAR) "var ")
3095 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3096 ((= tt js2-CONST) "const ")
3098 (error "malformed var-decl node"))))
3099 (loop with kids = (js2-var-decl-node-kids n)
3100 with len = (length kids)
3104 (js2-print-ast kid 0)
3108 (defstruct (js2-var-init-node
3111 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3116 "AST node for a variable declaration.
3117 The type field will be js2-CONST for a const decl."
3118 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3119 initializer) ; initializer expression, a `js2-node'
3121 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3122 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3124 (defun js2-visit-var-init-node (n v)
3125 (js2-visit-ast (js2-var-init-node-target n) v)
3126 (if (js2-var-init-node-initializer n)
3127 (js2-visit-ast (js2-var-init-node-initializer n) v)))
3129 (defun js2-print-var-init-node (n i)
3130 (let ((pad (js2-make-pad i))
3131 (name (js2-var-init-node-target n))
3132 (init (js2-var-init-node-initializer n)))
3134 (js2-print-ast name 0)
3137 (js2-print-ast init 0))))
3139 (defstruct (js2-cond-node
3142 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3150 "AST node for the ternary operator"
3154 q-pos ; buffer position of ?
3155 c-pos) ; buffer position of :
3157 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3158 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3160 (defun js2-visit-cond-node (n v)
3161 (js2-visit-ast (js2-cond-node-test-expr n) v)
3162 (js2-visit-ast (js2-cond-node-true-expr n) v)
3163 (js2-visit-ast (js2-cond-node-false-expr n) v))
3165 (defun js2-print-cond-node (n i)
3166 (let ((pad (js2-make-pad i)))
3168 (js2-print-ast (js2-cond-node-test-expr n) 0)
3170 (js2-print-ast (js2-cond-node-true-expr n) 0)
3172 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3174 (defstruct (js2-infix-node
3177 (:constructor make-js2-infix-node (&key type
3183 "Represents infix expressions.
3184 Includes assignment ops like `|=', and the comma operator.
3185 The type field inherited from `js2-node' holds the operator."
3186 op-pos ; buffer position where operator begins
3187 left ; any `js2-node'
3188 right) ; any `js2-node'
3190 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3191 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3193 (defun js2-visit-infix-node (n v)
3194 (when (js2-infix-node-left n)
3195 (js2-visit-ast (js2-infix-node-left n) v))
3196 (when (js2-infix-node-right n)
3197 (js2-visit-ast (js2-infix-node-right n) v)))
3199 (defconst js2-operator-tokens
3200 (let ((table (make-hash-table :test 'eq))
3202 (list (cons js2-IN "in")
3203 (cons js2-TYPEOF "typeof")
3204 (cons js2-INSTANCEOF "instanceof")
3205 (cons js2-DELPROP "delete")
3206 (cons js2-COMMA ",")
3207 (cons js2-COLON ":")
3212 (cons js2-BITOR "|")
3213 (cons js2-BITXOR "^")
3214 (cons js2-BITAND "&")
3223 (cons js2-URSH ">>>")
3224 (cons js2-ADD "+") ; infix plus
3225 (cons js2-SUB "-") ; infix minus
3230 (cons js2-BITNOT "~")
3231 (cons js2-POS "+") ; unary plus
3232 (cons js2-NEG "-") ; unary minus
3233 (cons js2-SHEQ "===") ; shallow equality
3234 (cons js2-SHNE "!==") ; shallow inequality
3235 (cons js2-ASSIGN "=")
3236 (cons js2-ASSIGN_BITOR "|=")
3237 (cons js2-ASSIGN_BITXOR "^=")
3238 (cons js2-ASSIGN_BITAND "&=")
3239 (cons js2-ASSIGN_LSH "<<=")
3240 (cons js2-ASSIGN_RSH ">>=")
3241 (cons js2-ASSIGN_URSH ">>>=")
3242 (cons js2-ASSIGN_ADD "+=")
3243 (cons js2-ASSIGN_SUB "-=")
3244 (cons js2-ASSIGN_MUL "*=")
3245 (cons js2-ASSIGN_DIV "/=")
3246 (cons js2-ASSIGN_MOD "%="))))
3247 (loop for (k . v) in tokens do
3248 (puthash k v table))
3251 (defun js2-print-infix-node (n i)
3252 (let* ((tt (js2-node-type n))
3253 (op (gethash tt js2-operator-tokens)))
3255 (error "unrecognized infix operator %s" (js2-node-type n)))
3256 (insert (js2-make-pad i))
3257 (js2-print-ast (js2-infix-node-left n) 0)
3258 (unless (= tt js2-COMMA)
3262 (js2-print-ast (js2-infix-node-right n) 0)))
3264 (defstruct (js2-assign-node
3265 (:include js2-infix-node)
3267 (:constructor make-js2-assign-node (&key type
3273 "Represents any assignment.
3274 The type field holds the actual assignment operator.")
3276 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3277 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3279 (defstruct (js2-unary-node
3282 (:constructor make-js2-unary-node (&key type ; required
3286 "AST node type for unary operator nodes.
3287 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3288 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3289 property is added if the operator follows the operand."
3290 operand) ; a `js2-node' expression
3292 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3293 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3295 (defun js2-visit-unary-node (n v)
3296 (js2-visit-ast (js2-unary-node-operand n) v))
3298 (defun js2-print-unary-node (n i)
3299 (let* ((tt (js2-node-type n))
3300 (op (gethash tt js2-operator-tokens))
3301 (postfix (js2-node-get-prop n 'postfix)))
3303 (error "unrecognized unary operator %s" tt))
3304 (insert (js2-make-pad i))
3307 (if (or (= tt js2-TYPEOF)
3310 (js2-print-ast (js2-unary-node-operand n) 0)
3314 (defstruct (js2-let-node
3315 (:include js2-scope)
3317 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3324 "AST node for a let expression or a let statement.
3325 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3326 vars ; a `js2-var-decl-node'
3327 body ; a `js2-node' representing the expression or body block
3331 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3332 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3334 (defun js2-visit-let-node (n v)
3335 (when (js2-let-node-vars n)
3336 (js2-visit-ast (js2-let-node-vars n) v))
3337 (when (js2-let-node-body n)
3338 (js2-visit-ast (js2-let-node-body n) v)))
3340 (defun js2-print-let-node (n i)
3341 (insert (js2-make-pad i) "let (")
3342 (js2-print-ast (js2-let-node-vars n) 0)
3344 (js2-print-ast (js2-let-node-body n) i))
3346 (defstruct (js2-keyword-node
3349 (:constructor make-js2-keyword-node (&key type
3351 (len (- js2-ts-cursor pos)))))
3352 "AST node representing a literal keyword such as `null'.
3353 Used for `null', `this', `true', `false' and `debugger'.
3354 The node type is set to js2-NULL, js2-THIS, etc.")
3356 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3357 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3359 (defun js2-print-keyword-node (n i)
3360 (insert (js2-make-pad i)
3361 (let ((tt (js2-node-type n)))
3363 ((= tt js2-THIS) "this")
3364 ((= tt js2-NULL) "null")
3365 ((= tt js2-TRUE) "true")
3366 ((= tt js2-FALSE) "false")
3367 ((= tt js2-DEBUGGER) "debugger")
3368 (t (error "Invalid keyword literal type: %d" tt))))))
3370 (defsubst js2-this-node-p (node)
3371 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3372 (eq (js2-node-type node) js2-THIS))
3374 (defstruct (js2-new-node
3377 (:constructor make-js2-new-node (&key (type js2-NEW)
3385 "AST node for new-expression such as new Foo()."
3386 target ; an identifier or reference
3387 args ; a lisp list of argument nodes
3388 lp ; position of left-paren, nil if omitted
3389 rp ; position of right-paren, nil if omitted
3390 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3392 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3393 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3395 (defun js2-visit-new-node (n v)
3396 (js2-visit-ast (js2-new-node-target n) v)
3397 (dolist (arg (js2-new-node-args n))
3398 (js2-visit-ast arg v))
3399 (when (js2-new-node-initializer n)
3400 (js2-visit-ast (js2-new-node-initializer n) v)))
3402 (defun js2-print-new-node (n i)
3403 (insert (js2-make-pad i) "new ")
3404 (js2-print-ast (js2-new-node-target n))
3406 (js2-print-list (js2-new-node-args n))
3408 (when (js2-new-node-initializer n)
3410 (js2-print-ast (js2-new-node-initializer n))))
3412 (defstruct (js2-name-node
3415 (:constructor make-js2-name-node (&key (type js2-NAME)
3417 (len (- js2-ts-cursor
3419 (name js2-ts-string))))
3420 "AST node for a JavaScript identifier"
3422 scope) ; a `js2-scope' (optional, used for codegen)
3424 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3425 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3427 (defun js2-print-name-node (n i)
3428 (insert (js2-make-pad i)
3429 (js2-name-node-name n)))
3431 (defsubst js2-name-node-length (node)
3432 "Return identifier length of NODE, a `js2-name-node'.
3433 Returns 0 if NODE is nil or its identifier field is nil."
3435 (length (js2-name-node-name node))
3438 (defstruct (js2-number-node
3441 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3443 (len (- js2-ts-cursor
3445 (value js2-ts-string)
3446 (num-value js2-ts-number))))
3447 "AST node for a number literal."
3448 value ; the original string, e.g. "6.02e23"
3449 num-value) ; the parsed number value
3451 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3452 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3454 (defun js2-print-number-node (n i)
3455 (insert (js2-make-pad i)
3456 (number-to-string (js2-number-node-num-value n))))
3458 (defstruct (js2-regexp-node
3461 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3463 (len (- js2-ts-cursor
3467 "AST node for a regular expression literal."
3468 value ; the regexp string, without // delimiters
3469 flags) ; a string of flags, e.g. `mi'.
3471 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3472 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3474 (defun js2-print-regexp (n i)
3475 (insert (js2-make-pad i)
3477 (js2-regexp-node-value n)
3479 (if (js2-regexp-node-flags n)
3480 (insert (js2-regexp-node-flags n))))
3482 (defstruct (js2-string-node
3485 (:constructor make-js2-string-node (&key (type js2-STRING)
3487 (len (- js2-ts-cursor
3489 (value js2-ts-string))))
3491 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3492 You can tell the quote type by looking at the first character."
3493 value) ; the characters of the string, including the quotes
3495 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3496 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3498 (defun js2-print-string-node (n i)
3499 (insert (js2-make-pad i)
3500 (js2-node-string n)))
3502 (defstruct (js2-array-node
3505 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3509 "AST node for an array literal."
3510 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3512 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3513 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3515 (defun js2-visit-array-node (n v)
3516 (dolist (e (js2-array-node-elems n))
3517 (when e ; can be nil, e.g. [a, ,b]
3518 (js2-visit-ast e v))))
3520 (defun js2-print-array-node (n i)
3521 (insert (js2-make-pad i) "[")
3522 (js2-print-list (js2-array-node-elems n))
3525 (defstruct (js2-object-node
3528 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3532 "AST node for an object literal expression."
3533 elems) ; a lisp list of `js2-object-prop-node'
3535 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3536 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3538 (defun js2-visit-object-node (n v)
3539 (dolist (e (js2-object-node-elems n))
3540 (js2-visit-ast e v)))
3542 (defun js2-print-object-node (n i)
3543 (insert (js2-make-pad i) "{")
3544 (js2-print-list (js2-object-node-elems n))
3547 (defstruct (js2-object-prop-node
3548 (:include js2-infix-node)
3550 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3556 "AST node for an object literal prop:value entry.
3557 The `left' field is the property: a name node, string node or number node.
3558 The `right' field is a `js2-node' representing the initializer value.")
3560 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3561 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3563 (defun js2-print-object-prop-node (n i)
3564 (insert (js2-make-pad i))
3565 (js2-print-ast (js2-object-prop-node-left n) 0)
3567 (js2-print-ast (js2-object-prop-node-right n) 0))
3569 (defstruct (js2-getter-setter-node
3570 (:include js2-infix-node)
3572 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3577 "AST node for a getter/setter property in an object literal.
3578 The `left' field is the `js2-name-node' naming the getter/setter prop.
3579 The `right' field is always an anonymous `js2-function-node' with a node
3580 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3582 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3583 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3585 (defun js2-print-getter-setter (n i)
3586 (let ((pad (js2-make-pad i))
3587 (left (js2-getter-setter-node-left n))
3588 (right (js2-getter-setter-node-right n)))
3590 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3591 (js2-print-ast left 0)
3592 (js2-print-ast right 0)))
3594 (defstruct (js2-prop-get-node
3595 (:include js2-infix-node)
3597 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3602 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3604 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3605 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3607 (defun js2-visit-prop-get-node (n v)
3608 (when (js2-prop-get-node-left n)
3609 (js2-visit-ast (js2-prop-get-node-left n) v))
3610 (when (js2-prop-get-node-right n)
3611 (js2-visit-ast (js2-prop-get-node-right n) v)))
3613 (defun js2-print-prop-get-node (n i)
3614 (insert (js2-make-pad i))
3615 (js2-print-ast (js2-prop-get-node-left n) 0)
3617 (js2-print-ast (js2-prop-get-node-right n) 0))
3619 (defstruct (js2-elem-get-node
3622 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3629 "AST node for an array index expression such as foo[bar]."
3630 target ; a `js2-node' - the expression preceding the "."
3631 element ; a `js2-node' - the expression in brackets
3632 lb ; position of left-bracket, nil if omitted
3633 rb) ; position of right-bracket, nil if omitted
3635 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3636 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3638 (defun js2-visit-elem-get-node (n v)
3639 (when (js2-elem-get-node-target n)
3640 (js2-visit-ast (js2-elem-get-node-target n) v))
3641 (when (js2-elem-get-node-element n)
3642 (js2-visit-ast (js2-elem-get-node-element n) v)))
3644 (defun js2-print-elem-get-node (n i)
3645 (insert (js2-make-pad i))
3646 (js2-print-ast (js2-elem-get-node-target n) 0)
3648 (js2-print-ast (js2-elem-get-node-element n) 0)
3651 (defstruct (js2-call-node
3654 (:constructor make-js2-call-node (&key (type js2-CALL)
3661 "AST node for a JavaScript function call."
3662 target ; a `js2-node' evaluating to the function to call
3663 args ; a lisp list of `js2-node' arguments
3664 lp ; position of open-paren, or nil if missing
3665 rp) ; position of close-paren, or nil if missing
3667 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3668 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3670 (defun js2-visit-call-node (n v)
3671 (js2-visit-ast (js2-call-node-target n) v)
3672 (dolist (arg (js2-call-node-args n))
3673 (js2-visit-ast arg v)))
3675 (defun js2-print-call-node (n i)
3676 (insert (js2-make-pad i))
3677 (js2-print-ast (js2-call-node-target n) 0)
3679 (js2-print-list (js2-call-node-args n))
3682 (defstruct (js2-yield-node
3685 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3689 "AST node for yield statement or expression."
3690 value) ; optional: value to be yielded
3692 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3693 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3695 (defun js2-visit-yield-node (n v)
3696 (js2-visit-ast (js2-yield-node-value n) v))
3698 (defun js2-print-yield-node (n i)
3699 (insert (js2-make-pad i))
3701 (when (js2-yield-node-value n)
3703 (js2-print-ast (js2-yield-node-value n) 0)))
3705 (defstruct (js2-paren-node
3708 (:constructor make-js2-paren-node (&key (type js2-LP)
3712 "AST node for a parenthesized expression.
3713 In particular, used when the parens are syntactically optional,
3714 as opposed to required parens such as those enclosing an if-conditional."
3717 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3718 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3720 (defun js2-visit-paren-node (n v)
3721 (js2-visit-ast (js2-paren-node-expr n) v))
3723 (defun js2-print-paren-node (n i)
3724 (insert (js2-make-pad i))
3726 (js2-print-ast (js2-paren-node-expr n) 0)
3729 (defstruct (js2-array-comp-node
3730 (:include js2-scope)
3732 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3741 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3742 result ; result expression (just after left-bracket)
3743 loops ; a lisp list of `js2-array-comp-loop-node'
3744 filter ; guard/filter expression
3745 if-pos ; buffer pos of 'if' keyword, if present, else nil
3746 lp ; buffer position of if-guard left-paren, or nil if not present
3747 rp) ; buffer position of if-guard right-paren, or nil if not present
3749 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3750 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3752 (defun js2-visit-array-comp-node (n v)
3753 (js2-visit-ast (js2-array-comp-node-result n) v)
3754 (dolist (l (js2-array-comp-node-loops n))
3755 (js2-visit-ast l v))
3756 (if (js2-array-comp-node-filter n)
3757 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3759 (defun js2-print-array-comp-node (n i)
3760 (let ((pad (js2-make-pad i))
3761 (result (js2-array-comp-node-result n))
3762 (loops (js2-array-comp-node-loops n))
3763 (filter (js2-array-comp-node-filter n)))
3765 (js2-print-ast result 0)
3768 (js2-print-ast l 0))
3771 (js2-print-ast filter 0))
3774 (defstruct (js2-array-comp-loop-node
3775 (:include js2-for-in-node)
3777 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3787 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3789 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3790 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3792 (defun js2-visit-array-comp-loop (n v)
3793 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3794 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3796 (defun js2-print-array-comp-loop (n i)
3798 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3800 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3803 (defstruct (js2-empty-expr-node
3806 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3809 "AST node for an empty expression.")
3811 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3812 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3814 (defstruct (js2-xml-node
3815 (:include js2-block-node)
3817 (:constructor make-js2-xml-node (&key (type js2-XML)
3821 "AST node for initial parse of E4X literals.
3822 The kids field is a list of XML fragments, each a `js2-string-node' or
3823 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3825 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3826 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3828 (defun js2-print-xml-node (n i)
3829 (dolist (kid (js2-xml-node-kids n))
3830 (js2-print-ast kid i)))
3832 (defstruct (js2-xml-js-expr-node
3833 (:include js2-xml-node)
3835 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3839 "AST node for an embedded JavaScript {expression} in an E4X literal.
3840 The start and end fields correspond to the curly-braces."
3841 expr) ; a `js2-expr-node' of some sort
3843 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3844 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3846 (defun js2-visit-xml-js-expr (n v)
3847 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3849 (defun js2-print-xml-js-expr (n i)
3850 (insert (js2-make-pad i))
3852 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3855 (defstruct (js2-xml-dot-query-node
3856 (:include js2-infix-node)
3858 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3865 "AST node for an E4X foo.(bar) filter expression.
3866 Note that the left-paren is automatically the character immediately
3867 following the dot (.) in the operator. No whitespace is permitted
3868 between the dot and the lp by the scanner."
3871 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3872 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3874 (defun js2-print-xml-dot-query (n i)
3875 (insert (js2-make-pad i))
3876 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3878 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3881 (defstruct (js2-xml-ref-node
3883 (:constructor nil)) ; abstract
3884 "Base type for E4X XML attribute-access or property-get expressions.
3885 Such expressions can take a variety of forms. The general syntax has
3888 - (optional) an @ (specifying an attribute access)
3889 - (optional) a namespace (a `js2-name-node') and double-colon
3890 - (required) either a `js2-name-node' or a bracketed [expression]
3892 The property-name expressions (examples: ns::name, @name) are
3893 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3894 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3896 This node type (or more specifically, its subclasses) will sometimes
3897 be the right-hand child of a `js2-prop-get-node' or a
3898 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3899 The `js2-xml-ref-node' may also be a standalone primary expression with
3900 no explicit target, which is valid in certain expression contexts such as
3902 company..employee.(@id < 100)
3904 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3905 expression whose parent is a `js2-xml-dot-query-node'."
3910 (defsubst js2-xml-ref-node-attr-access-p (node)
3911 "Return non-nil if this expression began with an @-token."
3912 (and (numberp (js2-xml-ref-node-at-pos node))
3913 (plusp (js2-xml-ref-node-at-pos node))))
3915 (defstruct (js2-xml-prop-ref-node
3916 (:include js2-xml-ref-node)
3918 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3925 "AST node for an E4X XML [expr] property-ref expression.
3926 The JavaScript syntax is an optional @, an optional ns::, and a name.
3928 [ '@' ] [ name '::' ] name
3930 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3931 @ns::*, @*::attr, @*::*, and @*.
3933 The node starts at the @ token, if present. Otherwise it starts at the
3934 namespace name. The node bounds extend through the closing right-bracket,
3935 or if it is missing due to a syntax error, through the end of the index
3939 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3940 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3942 (defun js2-visit-xml-prop-ref-node (n v)
3943 (if (js2-xml-prop-ref-node-namespace n)
3944 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3945 (if (js2-xml-prop-ref-node-propname n)
3946 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3948 (defun js2-print-xml-prop-ref-node (n i)
3949 (insert (js2-make-pad i))
3950 (if (js2-xml-ref-node-attr-access-p n)
3952 (when (js2-xml-prop-ref-node-namespace n)
3953 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3955 (if (js2-xml-prop-ref-node-propname n)
3956 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3958 (defstruct (js2-xml-elem-ref-node
3959 (:include js2-xml-ref-node)
3961 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3970 "AST node for an E4X XML [expr] member-ref expression.
3973 [ '@' ] [ name '::' ] '[' expr ']'
3975 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3977 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3978 is not a legal E4X XML element-ref expression, since it's already used
3979 for standard JavaScript element-get array indexing. Hence, a
3980 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3981 non-nil namespace node, or both.
3983 The node starts at the @ token, if present. Otherwise it starts
3984 at the namespace name. The node bounds extend through the closing
3985 right-bracket, or if it is missing due to a syntax error, through the
3986 end of the index expression."
3987 expr ; the bracketed index expression
3991 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3992 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3994 (defun js2-visit-xml-elem-ref-node (n v)
3995 (if (js2-xml-elem-ref-node-namespace n)
3996 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
3997 (if (js2-xml-elem-ref-node-expr n)
3998 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
4000 (defun js2-print-xml-elem-ref-node (n i)
4001 (insert (js2-make-pad i))
4002 (if (js2-xml-ref-node-attr-access-p n)
4004 (when (js2-xml-elem-ref-node-namespace n)
4005 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4008 (if (js2-xml-elem-ref-node-expr n)
4009 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4012 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4014 (defstruct (js2-xml-start-tag-node
4015 (:include js2-xml-node)
4017 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4024 "AST node for an XML start-tag. Not currently used.
4025 The `kids' field is a lisp list of child content nodes."
4026 name ; a `js2-xml-name-node'
4027 attrs ; a lisp list of `js2-xml-attr-node'
4028 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4030 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4031 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4033 (defun js2-visit-xml-start-tag (n v)
4034 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4035 (dolist (attr (js2-xml-start-tag-node-attrs n))
4036 (js2-visit-ast attr v))
4037 (js2-visit-block n v))
4039 (defun js2-print-xml-start-tag (n i)
4040 (insert (js2-make-pad i) "<")
4041 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4042 (when (js2-xml-start-tag-node-attrs n)
4044 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4047 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4048 ;; and add the end-tag to the kids list of the parent as well.
4049 (defstruct (js2-xml-end-tag-node
4050 (:include js2-xml-node)
4052 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4056 "AST node for an XML end-tag. Not currently used."
4057 name) ; a `js2-xml-name-node'
4059 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4060 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4062 (defun js2-visit-xml-end-tag (n v)
4063 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4065 (defun js2-print-xml-end-tag (n i)
4066 (insert (js2-make-pad i))
4068 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4071 (defstruct (js2-xml-name-node
4072 (:include js2-xml-node)
4074 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4079 "AST node for an E4X XML name. Not currently used.
4080 Any XML name can be qualified with a namespace, hence the namespace field.
4081 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4082 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4083 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4084 namespace) ; a `js2-string-node'
4086 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4087 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4089 (defun js2-visit-xml-name-node (n v)
4090 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4092 (defun js2-print-xml-name-node (n i)
4093 (insert (js2-make-pad i))
4094 (when (js2-xml-name-node-namespace n)
4095 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4097 (dolist (kid (js2-xml-name-node-kids n))
4098 (js2-print-ast kid 0)))
4100 (defstruct (js2-xml-pi-node
4101 (:include js2-xml-node)
4103 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4108 "AST node for an E4X XML processing instruction. Not currently used."
4109 name ; a `js2-xml-name-node'
4110 attrs) ; a list of `js2-xml-attr-node'
4112 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4113 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4115 (defun js2-visit-xml-pi-node (n v)
4116 (js2-visit-ast (js2-xml-pi-node-name n) v)
4117 (dolist (attr (js2-xml-pi-node-attrs n))
4118 (js2-visit-ast attr v)))
4120 (defun js2-print-xml-pi-node (n i)
4121 (insert (js2-make-pad i) "<?")
4122 (js2-print-ast (js2-xml-pi-node-name n))
4123 (when (js2-xml-pi-node-attrs n)
4125 (js2-print-list (js2-xml-pi-node-attrs n)))
4128 (defstruct (js2-xml-cdata-node
4129 (:include js2-xml-node)
4131 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4135 "AST node for a CDATA escape section. Not currently used."
4136 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4138 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4139 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4141 (defun js2-visit-xml-cdata-node (n v)
4142 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4144 (defun js2-print-xml-cdata-node (n i)
4145 (insert (js2-make-pad i))
4146 (js2-print-ast (js2-xml-cdata-node-content n)))
4148 (defstruct (js2-xml-attr-node
4149 (:include js2-xml-node)
4151 (:constructor make-js2-attr-node (&key (type js2-XML)
4158 "AST node representing a foo='bar' XML attribute value. Not yet used."
4159 name ; a `js2-xml-name-node'
4160 value ; a `js2-xml-name-node'
4161 eq-pos ; buffer position of "=" sign
4162 quote-type) ; 'single or 'double
4164 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4165 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4167 (defun js2-visit-xml-attr-node (n v)
4168 (js2-visit-ast (js2-xml-attr-node-name n) v)
4169 (js2-visit-ast (js2-xml-attr-node-value n) v))
4171 (defun js2-print-xml-attr-node (n i)
4172 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4175 (insert (js2-make-pad i))
4176 (js2-print-ast (js2-xml-attr-node-name n) 0)
4178 (js2-print-ast (js2-xml-attr-node-value n) 0)
4181 (defstruct (js2-xml-text-node
4182 (:include js2-xml-node)
4184 (:constructor make-js2-text-node (&key (type js2-XML)
4188 "AST node for an E4X XML text node. Not currently used."
4189 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4191 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4192 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4194 (defun js2-visit-xml-text-node (n v)
4195 (js2-visit-ast (js2-xml-text-node-content n) v))
4197 (defun js2-print-xml-text-node (n i)
4198 (insert (js2-make-pad i))
4199 (dolist (kid (js2-xml-text-node-content n))
4200 (js2-print-ast kid)))
4202 (defstruct (js2-xml-comment-node
4203 (:include js2-xml-node)
4205 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4208 "AST node for E4X XML comment. Not currently used.")
4210 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4211 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4213 (defun js2-print-xml-comment (n i)
4214 (insert (js2-make-pad i)
4215 (js2-node-string n)))
4219 (defsubst js2-node-line (n)
4220 "Fetch the source line number at the start of node N.
4221 This is O(n) in the length of the source buffer; use prudently."
4222 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4224 (defsubst js2-block-node-kid (n i)
4225 "Return child I of node N, or nil if there aren't that many."
4226 (nth i (js2-block-node-kids n)))
4228 (defsubst js2-block-node-first (n)
4229 "Return first child of block node N, or nil if there is none."
4230 (first (js2-block-node-kids n)))
4232 (defun js2-node-root (n)
4233 "Return the root of the AST containing N.
4234 If N has no parent pointer, returns N."
4235 (let ((parent (js2-node-parent n)))
4237 (js2-node-root parent)
4240 (defun js2-node-position-in-parent (node &optional parent)
4241 "Return the position of NODE in parent's block-kids list.
4242 PARENT can be supplied if known. Positioned returned is zero-indexed.
4243 Returns 0 if NODE is not a child of a block statement, or if NODE
4244 is not a statement node."
4245 (let ((p (or parent (js2-node-parent node)))
4247 (if (not (js2-block-node-p p))
4249 (or (js2-position node (js2-block-node-kids p))
4252 (defsubst js2-node-short-name (n)
4253 "Return the short name of node N as a string, e.g. `js2-if-node'."
4254 (substring (symbol-name (aref n 0))
4255 (length "cl-struct-")))
4257 (defsubst js2-node-child-list (node)
4258 "Return the child list for NODE, a lisp list of nodes.
4259 Works for block nodes, array nodes, obj literals, funarg lists,
4260 var decls and try nodes (for catch clauses). Note that you should call
4261 `js2-block-node-kids' on the function body for the body statements.
4262 Returns nil for zero-length child lists or unsupported nodes."
4264 ((js2-function-node-p node)
4265 (js2-function-node-params node))
4266 ((js2-block-node-p node)
4267 (js2-block-node-kids node))
4268 ((js2-try-node-p node)
4269 (js2-try-node-catch-clauses node))
4270 ((js2-array-node-p node)
4271 (js2-array-node-elems node))
4272 ((js2-object-node-p node)
4273 (js2-object-node-elems node))
4274 ((js2-call-node-p node)
4275 (js2-call-node-args node))
4276 ((js2-new-node-p node)
4277 (js2-new-node-args node))
4278 ((js2-var-decl-node-p node)
4279 (js2-var-decl-node-kids node))
4283 (defsubst js2-node-set-child-list (node kids)
4284 "Set the child list for NODE to KIDS."
4286 ((js2-function-node-p node)
4287 (setf (js2-function-node-params node) kids))
4288 ((js2-block-node-p node)
4289 (setf (js2-block-node-kids node) kids))
4290 ((js2-try-node-p node)
4291 (setf (js2-try-node-catch-clauses node) kids))
4292 ((js2-array-node-p node)
4293 (setf (js2-array-node-elems node) kids))
4294 ((js2-object-node-p node)
4295 (setf (js2-object-node-elems node) kids))
4296 ((js2-call-node-p node)
4297 (setf (js2-call-node-args node) kids))
4298 ((js2-new-node-p node)
4299 (setf (js2-new-node-args node) kids))
4300 ((js2-var-decl-node-p node)
4301 (setf (js2-var-decl-node-kids node) kids))
4303 (error "Unsupported node type: %s" (js2-node-short-name node))))
4306 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4307 (defconst js2-paren-expr-nodes
4308 '(cl-struct-js2-array-comp-loop-node
4309 cl-struct-js2-array-comp-node
4310 cl-struct-js2-call-node
4311 cl-struct-js2-catch-node
4312 cl-struct-js2-do-node
4313 cl-struct-js2-elem-get-node
4314 cl-struct-js2-for-in-node
4315 cl-struct-js2-for-node
4316 cl-struct-js2-function-node
4317 cl-struct-js2-if-node
4318 cl-struct-js2-let-node
4319 cl-struct-js2-new-node
4320 cl-struct-js2-paren-node
4321 cl-struct-js2-switch-node
4322 cl-struct-js2-while-node
4323 cl-struct-js2-with-node
4324 cl-struct-js2-xml-dot-query-node)
4325 "Node types that can have a parenthesized child expression.
4326 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4328 (defsubst js2-paren-expr-node-p (node)
4329 "Return t for nodes that typically have a parenthesized child expression.
4330 Useful for computing the indentation anchors for arg-lists and conditions.
4331 Note that it may return a false positive, for instance when NODE is
4332 a `js2-new-node' and there are no arguments or parentheses."
4333 (memq (aref node 0) js2-paren-expr-nodes))
4335 ;; Fake polymorphism... yech.
4336 (defsubst js2-node-lp (node)
4337 "Return relative left-paren position for NODE, if applicable.
4338 For `js2-elem-get-node' structs, returns left-bracket position.
4339 Note that the position may be nil in the case of a parse error."
4341 ((js2-elem-get-node-p node)
4342 (js2-elem-get-node-lb node))
4343 ((js2-loop-node-p node)
4344 (js2-loop-node-lp node))
4345 ((js2-function-node-p node)
4346 (js2-function-node-lp node))
4347 ((js2-if-node-p node)
4348 (js2-if-node-lp node))
4349 ((js2-new-node-p node)
4350 (js2-new-node-lp node))
4351 ((js2-call-node-p node)
4352 (js2-call-node-lp node))
4353 ((js2-paren-node-p node)
4354 (js2-node-pos node))
4355 ((js2-switch-node-p node)
4356 (js2-switch-node-lp node))
4357 ((js2-catch-node-p node)
4358 (js2-catch-node-lp node))
4359 ((js2-let-node-p node)
4360 (js2-let-node-lp node))
4361 ((js2-array-comp-node-p node)
4362 (js2-array-comp-node-lp node))
4363 ((js2-with-node-p node)
4364 (js2-with-node-lp node))
4365 ((js2-xml-dot-query-node-p node)
4366 (1+ (js2-infix-node-op-pos node)))
4368 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4370 ;; Fake polymorphism... blech.
4371 (defsubst js2-node-rp (node)
4372 "Return relative right-paren position for NODE, if applicable.
4373 For `js2-elem-get-node' structs, returns right-bracket position.
4374 Note that the position may be nil in the case of a parse error."
4376 ((js2-elem-get-node-p node)
4377 (js2-elem-get-node-lb node))
4378 ((js2-loop-node-p node)
4379 (js2-loop-node-rp node))
4380 ((js2-function-node-p node)
4381 (js2-function-node-rp node))
4382 ((js2-if-node-p node)
4383 (js2-if-node-rp node))
4384 ((js2-new-node-p node)
4385 (js2-new-node-rp node))
4386 ((js2-call-node-p node)
4387 (js2-call-node-rp node))
4388 ((js2-paren-node-p node)
4389 (+ (js2-node-pos node) (js2-node-len node)))
4390 ((js2-switch-node-p node)
4391 (js2-switch-node-rp node))
4392 ((js2-catch-node-p node)
4393 (js2-catch-node-rp node))
4394 ((js2-let-node-p node)
4395 (js2-let-node-rp node))
4396 ((js2-array-comp-node-p node)
4397 (js2-array-comp-node-rp node))
4398 ((js2-with-node-p node)
4399 (js2-with-node-rp node))
4400 ((js2-xml-dot-query-node-p node)
4401 (1+ (js2-xml-dot-query-node-rp node)))
4403 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4405 (defsubst js2-node-first-child (node)
4406 "Returns the first element of `js2-node-child-list' for NODE."
4407 (car (js2-node-child-list node)))
4409 (defsubst js2-node-last-child (node)
4410 "Returns the last element of `js2-node-last-child' for NODE."
4411 (car (last (js2-node-child-list node))))
4413 (defun js2-node-prev-sibling (node)
4414 "Return the previous statement in parent.
4415 Works for parents supported by `js2-node-child-list'.
4416 Returns nil if NODE is not in the parent, or PARENT is
4417 not a supported node, or if NODE is the first child."
4418 (let* ((p (js2-node-parent node))
4419 (kids (js2-node-child-list p))
4422 (not (eq node (cadr kids))))
4423 (setq kids (cdr kids)
4427 (defun js2-node-next-sibling (node)
4428 "Return the next statement in parent block.
4429 Returns nil if NODE is not in the block, or PARENT is not
4430 a block node, or if NODE is the last statement."
4431 (let* ((p (js2-node-parent node))
4432 (kids (js2-node-child-list p)))
4434 (not (eq node (car kids))))
4435 (setq kids (cdr kids)))
4438 (defun js2-node-find-child-before (pos parent &optional after)
4439 "Find the last child that starts before POS in parent.
4440 If AFTER is non-nil, returns first child starting after POS.
4441 POS is an absolute buffer position. PARENT is any node
4442 supported by `js2-node-child-list'.
4443 Returns nil if no applicable child is found."
4444 (let ((kids (if (js2-function-node-p parent)
4445 (js2-block-node-kids (js2-function-node-body parent))
4446 (js2-node-child-list parent)))
4447 (beg (if (js2-function-node-p parent)
4448 (js2-node-abs-pos (js2-function-node-body parent))
4449 (js2-node-abs-pos parent)))
4454 (setq fn (if after '> '<))
4455 (while (and kids continue)
4456 (setq kid (car kids))
4457 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4459 continue (if after nil t))
4460 (setq continue (if after t nil)))
4461 (setq kids (cdr kids)))
4464 (defun js2-node-find-child-after (pos parent)
4465 "Find first child that starts after POS in parent.
4466 POS is an absolute buffer position. PARENT is any node
4467 supported by `js2-node-child-list'.
4468 Returns nil if no applicable child is found."
4469 (js2-node-find-child-before pos parent 'after))
4471 (defun js2-node-replace-child (pos parent new-node)
4472 "Replace node at index POS in PARENT with NEW-NODE.
4473 Only works for parents supported by `js2-node-child-list'."
4474 (let ((kids (js2-node-child-list parent))
4477 (setq kids (cdr kids)
4479 (setcar kids new-node)
4480 (js2-node-add-children parent new-node)))
4482 (defun js2-node-buffer (n)
4483 "Return the buffer associated with AST N.
4484 Returns nil if the buffer is not set as a property on the root
4485 node, or if parent links were not recorded during parsing."
4486 (let ((root (js2-node-root n)))
4488 (js2-ast-root-p root)
4489 (js2-ast-root-buffer root))))
4491 (defsubst js2-block-node-push (n kid)
4492 "Push js2-node KID onto the end of js2-block-node N's child list.
4493 KID is always added to the -end- of the kids list.
4494 Function also calls `js2-node-add-children' to add the parent link."
4495 (let ((kids (js2-node-child-list n)))
4497 (setcdr kids (nconc (cdr kids) (list kid)))
4498 (js2-node-set-child-list n (list kid)))
4499 (js2-node-add-children n kid)))
4501 (defun js2-node-string (node)
4502 (let ((buf (js2-node-buffer node))
4505 (error "No buffer available for node %s" node))
4508 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4509 (+ pos (js2-node-len node))))))
4511 ;; Container for storing the node we're looking for in a traversal.
4512 (js2-deflocal js2-discovered-node nil)
4514 ;; Keep track of absolute node position during traversals.
4515 (js2-deflocal js2-visitor-offset nil)
4517 (js2-deflocal js2-node-search-point nil)
4519 (when js2-mode-dev-mode-p
4520 (defun js2-find-node-at-point ()
4522 (let ((node (js2-node-at-point)))
4523 (message "%s" (or node "No node found at point"))))
4524 (defun js2-node-name-at-point ()
4526 (let ((node (js2-node-at-point)))
4527 (message "%s" (if node
4528 (js2-node-short-name node)
4529 "No node found at point.")))))
4531 (defun js2-node-at-point (&optional pos skip-comments)
4532 "Return AST node at POS, a buffer position, defaulting to current point.
4533 The `js2-mode-ast' variable must be set to the current parse tree.
4534 Signals an error if the AST (`js2-mode-ast') is nil.
4535 Always returns a node - if it can't find one, it returns the root.
4536 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4537 (let ((ast js2-mode-ast)
4540 (error "No JavaScript AST available"))
4541 ;; Look through comments first, since they may be inside nodes that
4542 ;; would otherwise report a match.
4543 (setq pos (or pos (point))
4544 result (if (> pos (js2-node-abs-end ast))
4546 (if (not skip-comments)
4547 (js2-comment-at-point pos))))
4549 (setq js2-discovered-node nil
4550 js2-visitor-offset 0
4551 js2-node-search-point pos)
4553 (catch 'js2-visit-done
4554 (js2-visit-ast ast #'js2-node-at-point-visitor))
4555 (setq js2-visitor-offset nil
4556 js2-node-search-point nil))
4557 (setq result js2-discovered-node))
4558 ;; may have found a comment beyond end of last child node,
4559 ;; since visiting the ast-root looks at the comment-list last.
4560 (if (and skip-comments
4561 (js2-comment-node-p result))
4563 (or result js2-mode-ast)))
4565 (defun js2-node-at-point-visitor (node end-p)
4566 (let ((rel-pos (js2-node-pos node))
4569 (point js2-node-search-point))
4572 ;; this evaluates to a non-nil return value, even if it's zero
4573 (decf js2-visitor-offset rel-pos))
4574 ;; we already looked for comments before visiting, and don't want them now
4575 ((js2-comment-node-p node)
4578 (setq abs-pos (incf js2-visitor-offset rel-pos)
4579 ;; we only want to use the node if the point is before
4580 ;; the last character position in the node, so we decrement
4581 ;; the absolute end by 1.
4582 abs-end (+ abs-pos (js2-node-len node) -1))
4584 ;; If this node starts after search-point, stop the search.
4586 (throw 'js2-visit-done nil))
4587 ;; If this node ends before the search-point, don't check kids.
4591 ;; Otherwise point is within this node, possibly in a child.
4592 (setq js2-discovered-node node)
4593 t)))))) ; keep processing kids to look for more specific match
4595 (defsubst js2-block-comment-p (node)
4596 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4597 (and (js2-comment-node-p node)
4598 (memq (js2-comment-node-format node) '(jsdoc block))))
4600 ;; TODO: put the comments in a vector and binary-search them instead
4601 (defun js2-comment-at-point (&optional pos)
4602 "Look through scanned comment nodes for one containing POS.
4603 POS is a buffer position that defaults to current point.
4604 Function returns nil if POS was not in any comment node."
4605 (let ((ast js2-mode-ast)
4606 (x (or pos (point)))
4610 (error "No JavaScript AST available"))
4612 ;; Comments are stored in lexical order.
4613 (dolist (comment (js2-ast-root-comments ast) nil)
4614 (setq beg (js2-node-abs-pos comment)
4615 end (+ beg (js2-node-len comment)))
4618 (throw 'done comment))))))
4620 (defun js2-mode-find-parent-fn (node)
4621 "Find function enclosing NODE.
4622 Returns nil if NODE is not inside a function."
4623 (setq node (js2-node-parent node))
4624 (while (and node (not (js2-function-node-p node)))
4625 (setq node (js2-node-parent node)))
4626 (and (js2-function-node-p node) node))
4628 (defun js2-mode-find-enclosing-fn (node)
4629 "Find function or root enclosing NODE."
4630 (if (js2-ast-root-p node)
4632 (setq node (js2-node-parent node))
4633 (while (not (or (js2-ast-root-p node)
4634 (js2-function-node-p node)))
4635 (setq node (js2-node-parent node)))
4638 (defun js2-mode-find-enclosing-node (beg end)
4639 "Find script or function fully enclosing BEG and END."
4640 (let ((node (js2-node-at-point beg))
4644 (if (or (js2-ast-root-p node)
4645 (and (js2-function-node-p node)
4646 (<= (setq pos (js2-node-abs-pos node)) beg)
4647 (>= (+ pos (js2-node-len node)) end)))
4649 (setq node (js2-node-parent node))))
4652 (defun js2-node-parent-script-or-fn (node)
4653 "Find script or function immediately enclosing NODE.
4654 If NODE is the ast-root, returns nil."
4655 (if (js2-ast-root-p node)
4657 (setq node (js2-node-parent node))
4658 (while (and node (not (or (js2-function-node-p node)
4659 (js2-script-node-p node))))
4660 (setq node (js2-node-parent node)))
4663 (defsubst js2-nested-function-p (node)
4664 "Return t if NODE is a nested function, or is inside a nested function."
4665 (js2-function-node-p (if (js2-function-node-p node)
4666 (js2-node-parent-script-or-fn node)
4667 (js2-node-parent-script-or-fn
4668 (js2-node-parent-script-or-fn node)))))
4670 (defsubst js2-function-param-node-p (node)
4671 "Return non-nil if NODE is a param node of a `js2-function-node'."
4672 (let ((parent (js2-node-parent node)))
4674 (js2-function-node-p parent)
4675 (memq node (js2-function-node-params parent)))))
4677 (defsubst js2-mode-shift-kids (kids start offset)
4679 (if (> (js2-node-pos kid) start)
4680 (incf (js2-node-pos kid) offset))))
4682 (defsubst js2-mode-shift-children (parent start offset)
4683 "Update start-positions of all children of PARENT beyond START."
4684 (let ((root (js2-node-root parent)))
4685 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4686 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4688 (defsubst js2-node-is-descendant (node ancestor)
4689 "Return t if NODE is a descendant of ANCESTOR."
4691 (not (eq node ancestor)))
4692 (setq node (js2-node-parent node)))
4695 ;;; visitor infrastructure
4697 (defun js2-visit-none (node callback)
4698 "Visitor for AST node that have no node children."
4701 (defun js2-print-none (node indent)
4702 "Visitor for AST node with no printed representation.")
4704 (defun js2-print-body (node indent)
4705 "Print a statement, or a block without braces."
4706 (if (js2-block-node-p node)
4707 (dolist (kid (js2-block-node-kids node))
4708 (js2-print-ast kid indent))
4709 (js2-print-ast node indent)))
4711 (defun js2-print-list (args &optional delimiter)
4712 (loop with len = (length args)
4716 (js2-print-ast arg 0)
4718 (insert (or delimiter ", ")))))
4720 (defun js2-print-tree (ast)
4721 "Prints an AST to the current buffer.
4722 Makes `js2-ast-parent-nodes' available to the printer functions."
4723 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4724 (js2-print-ast ast)))
4726 (defun js2-print-ast (node &optional indent)
4727 "Helper function for printing AST nodes.
4728 Requires `js2-ast-parent-nodes' to be non-nil.
4729 You should use `js2-print-tree' instead of this function."
4730 (let ((printer (get (aref node 0) 'js2-printer))
4732 (pos (js2-node-abs-pos node)))
4733 ;; TODO: wedge comments in here somewhere
4735 (funcall printer node i))))
4737 (defconst js2-side-effecting-tokens
4738 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4739 (dolist (tt (list js2-ASSIGN
4808 (if js2-instanceof-has-side-effects
4809 (aset tokens js2-INSTANCEOF t))
4812 (defun js2-node-has-side-effects (node)
4813 "Return t if NODE has side effects."
4814 (when node ; makes it easier to handle malformed expressions
4815 (let ((tt (js2-node-type node)))
4817 ;; This doubtless needs some work, since EXPR_VOID is used
4818 ;; in several ways in Rhino, and I may not have caught them all.
4819 ;; I'll wait for people to notice incorrect warnings.
4820 ((and (= tt js2-EXPR_VOID)
4821 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4822 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4824 (js2-node-has-side-effects (js2-infix-node-right node)))
4827 (or (js2-node-has-side-effects (js2-infix-node-right node))
4828 (js2-node-has-side-effects (js2-infix-node-left node))))
4830 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4831 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4832 ((js2-paren-node-p node)
4833 (js2-node-has-side-effects (js2-paren-node-expr node)))
4834 ((= tt js2-ERROR) ; avoid cascaded error messages
4837 (aref js2-side-effecting-tokens tt))))))
4839 (defun js2-member-expr-leftmost-name (node)
4840 "For an expr such as foo.bar.baz, return leftmost node foo.
4841 NODE is any `js2-node' object. If it represents a member expression,
4842 which is any sequence of property gets, element-gets, function calls,
4843 or xml descendants/filter operators, then we look at the lexically
4844 leftmost (first) node in the chain. If it is a name-node we return it.
4845 Note that NODE can be a raw name-node and it will be returned as well.
4846 If NODE is not a name-node or member expression, or if it is a member
4847 expression whose leftmost target is not a name node, returns nil."
4850 (while (and continue (not result))
4852 ((js2-name-node-p node)
4854 ((js2-prop-get-node-p node)
4855 (setq node (js2-prop-get-node-left node)))
4856 ;; TODO: handle call-nodes, xml-nodes, others?
4858 (setq continue nil))))
4861 (defconst js2-stmt-node-types
4865 js2-DEFAULT ; e4x "default xml namespace" statement
4877 "Node types that only appear in statement contexts.
4878 The list does not include nodes that always appear as the child
4879 of another specific statement type, such as switch-cases,
4880 catch and finally blocks, and else-clauses. The list also excludes
4881 nodes like yield, let and var, which may appear in either expression
4882 or statement context, and in the latter context always have a
4883 `js2-expr-stmt-node' parent. Finally, the list does not include
4884 functions or scripts, which are treated separately from statements
4885 by the JavaScript parser and runtime.")
4887 (defun js2-stmt-node-p (node)
4888 "Heuristic for figuring out if NODE is a statement.
4889 Some node types can appear in either an expression context or a
4890 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4891 For these node types in a statement context, the parent will be a
4892 `js2-expr-stmt-node'.
4893 Functions aren't included in the check."
4894 (memq (js2-node-type node) js2-stmt-node-types))
4896 (defsubst js2-mode-find-first-stmt (node)
4897 "Search upward starting from NODE looking for a statement.
4898 For purposes of this function, a `js2-function-node' counts."
4899 (while (not (or (js2-stmt-node-p node)
4900 (js2-function-node-p node)))
4901 (setq node (js2-node-parent node)))
4904 (defun js2-node-parent-stmt (node)
4905 "Return the node's first ancestor that is a statement.
4906 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4907 appearing in a statement context will have a parent that is a
4908 `js2-expr-stmt-node' that will be returned by this function."
4909 (let ((parent (js2-node-parent node)))
4910 (if (or (null parent)
4911 (js2-stmt-node-p parent)
4912 (and (js2-function-node-p parent)
4913 (not (eq (js2-function-node-form parent)
4914 'FUNCTION_EXPRESSION))))
4916 (js2-node-parent-stmt parent))))
4918 ;; In the Mozilla Rhino sources, Roshan James writes:
4919 ;; Does consistent-return analysis on the function body when strict mode is
4922 ;; function (x) { return (x+1) }
4926 ;; function (x) { if (x < 0) return (x+1); }
4928 ;; is not because the function can potentially return a value when the
4929 ;; condition is satisfied and if not, the function does not explicitly
4932 ;; This extends to checking mismatches such as "return" and "return <value>"
4933 ;; used in the same function. Warnings are not emitted if inconsistent
4934 ;; returns exist in code that can be statically shown to be unreachable.
4936 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4938 ;; emits no warning. However if the loop had a break statement, then a
4939 ;; warning would be emitted.
4941 ;; The consistency analysis looks at control structures such as loops, ifs,
4942 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4943 ;; warns the user about an inconsistent set of termination possibilities.
4945 ;; These flags enumerate the possible ways a statement/function can
4946 ;; terminate. These flags are used by endCheck() and by the Parser to
4947 ;; detect inconsistent return usage.
4949 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4950 ;; able to execute (example: throw, continue)
4952 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4953 ;; next one. Statement such as return dont. A compound statement may have
4954 ;; some branch that drops off control to the next statement.
4956 ;; END_RETURNS indicates that the statement can return with no value.
4957 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4959 ;; A compound statement such as
4963 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4965 (defconst js2-END_UNREACHED 0)
4966 (defconst js2-END_DROPS_OFF 1)
4967 (defconst js2-END_RETURNS 2)
4968 (defconst js2-END_RETURNS_VALUE 4)
4969 (defconst js2-END_YIELDS 8)
4971 (defun js2-has-consistent-return-usage (node)
4972 "Check that every return usage in a function body is consistent.
4973 Returns t if the function satisfies strict mode requirement."
4974 (let ((n (js2-end-check node)))
4975 ;; either it doesn't return a value in any branch...
4976 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4977 ;; or it returns a value (or is unreached) at every branch
4978 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4982 (defun js2-end-check-if (node)
4983 "Returns in the then and else blocks must be consistent with each other.
4984 If there is no else block, then the return statement can fall through.
4985 Returns logical OR of END_* flags"
4986 (let ((th (js2-if-node-then-part node))
4987 (el (js2-if-node-else-part node)))
4990 (logior (js2-end-check th) (if el
4992 js2-END_DROPS_OFF)))))
4994 (defun js2-end-check-switch (node)
4995 "Consistency of return statements is checked between the case statements.
4996 If there is no default, then the switch can fall through. If there is a
4997 default, we check to see if all code paths in the default return or if
4998 there is a code path that can fall through.
4999 Returns logical OR of END_* flags."
5000 (let ((rv js2-END_UNREACHED)
5002 ;; examine the cases
5004 (dolist (c (js2-switch-node-cases node))
5005 (if (js2-case-node-expr c)
5006 (js2-set-flag rv (js2-end-check-block c))
5007 (setq default-case c)
5008 (throw 'break nil))))
5009 ;; we don't care how the cases drop into each other
5010 (js2-clear-flag rv js2-END_DROPS_OFF)
5011 ;; examine the default
5012 (js2-set-flag rv (if default-case
5013 (js2-end-check default-case)
5017 (defun js2-end-check-try (node)
5018 "If the block has a finally, return consistency is checked in the
5019 finally block. If all code paths in the finally return, then the
5020 returns in the try-catch blocks don't matter. If there is a code path
5021 that does not return or if there is no finally block, the returns
5022 of the try and catch blocks are checked for mismatch.
5023 Returns logical OR of END_* flags."
5024 (let ((finally (js2-try-node-finally-block node))
5026 ;; check the finally if it exists
5027 (setq rv (if finally
5028 (js2-end-check (js2-finally-node-body finally))
5030 ;; If the finally block always returns, then none of the returns
5031 ;; in the try or catch blocks matter.
5032 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5033 (js2-clear-flag rv js2-END_DROPS_OFF)
5034 ;; examine the try block
5035 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5036 ;; check each catch block
5037 (dolist (cb (js2-try-node-catch-clauses node))
5038 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5041 (defun js2-end-check-loop (node)
5042 "Return statement in the loop body must be consistent. The default
5043 assumption for any kind of a loop is that it will eventually terminate.
5044 The only exception is a loop with a constant true condition. Code that
5045 follows such a loop is examined only if one can statically determine
5046 that there is a break out of the loop.
5048 for(... ; ... ; ...) {}
5053 Returns logical OR of END_* flags."
5054 (let ((rv (js2-end-check (js2-loop-node-body node)))
5056 ((js2-while-node-p node)
5057 (js2-while-node-condition node))
5058 ((js2-do-node-p node)
5059 (js2-do-node-condition node))
5060 ((js2-for-node-p node)
5061 (js2-for-node-condition node)))))
5063 ;; check to see if the loop condition is always true
5065 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5066 (js2-clear-flag rv js2-END_DROPS_OFF))
5068 ;; look for effect of breaks
5069 (js2-set-flag rv (js2-node-get-prop node
5074 (defun js2-end-check-block (node)
5075 "A general block of code is examined statement by statement.
5076 If any statement (even a compound one) returns in all branches, then
5077 subsequent statements are not examined.
5078 Returns logical OR of END_* flags."
5079 (let* ((rv js2-END_DROPS_OFF)
5080 (kids (js2-block-node-kids node))
5082 ;; Check each statment. If the statement can continue onto the next
5083 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5084 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5085 (js2-clear-flag rv js2-END_DROPS_OFF)
5086 (js2-set-flag rv (js2-end-check n))
5087 (setq kids (cdr kids)
5091 (defun js2-end-check-label (node)
5092 "A labeled statement implies that there may be a break to the label.
5093 The function processes the labeled statement and then checks the
5094 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5096 Returns logical OR of END_* flags."
5097 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5098 (logior rv (js2-node-get-prop node
5100 js2-END_UNREACHED))))
5102 (defun js2-end-check-break (node)
5103 "When a break is encountered annotate the statement being broken
5104 out of by setting its CONTROL_BLOCK_PROP property.
5105 Returns logical OR of END_* flags."
5106 (and (js2-break-node-target node)
5107 (js2-node-set-prop (js2-break-node-target node)
5112 (defun js2-end-check (node)
5113 "Examine the body of a function, doing a basic reachability analysis.
5114 Returns a combination of flags END_* flags that indicate
5115 how the function execution can terminate. These constitute only the
5116 pessimistic set of termination conditions. It is possible that at
5117 runtime certain code paths will never be actually taken. Hence this
5118 analysis will flag errors in cases where there may not be errors.
5119 Returns logical OR of END_* flags"
5122 ((js2-break-node-p node)
5123 (js2-end-check-break node))
5124 ((js2-expr-stmt-node-p node)
5125 (if (setq kid (js2-expr-stmt-node-expr node))
5128 ((or (js2-continue-node-p node)
5129 (js2-throw-node-p node))
5131 ((js2-return-node-p node)
5132 (if (setq kid (js2-return-node-retval node))
5133 js2-END_RETURNS_VALUE
5135 ((js2-loop-node-p node)
5136 (js2-end-check-loop node))
5137 ((js2-switch-node-p node)
5138 (js2-end-check-switch node))
5139 ((js2-labeled-stmt-node-p node)
5140 (js2-end-check-label node))
5141 ((js2-if-node-p node)
5142 (js2-end-check-if node))
5143 ((js2-try-node-p node)
5144 (js2-end-check-try node))
5145 ((js2-block-node-p node)
5146 (if (null (js2-block-node-kids node))
5148 (js2-end-check-block node)))
5149 ((js2-yield-node-p node)
5152 js2-END_DROPS_OFF))))
5154 (defun js2-always-defined-boolean-p (node)
5155 "Check if NODE always evaluates to true or false in boolean context.
5156 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5158 (let ((tt (js2-node-type node))
5161 ((or (= tt js2-FALSE) (= tt js2-NULL))
5166 (setq num (js2-number-node-num-value node))
5167 (if (and (not (eq num 0.0e+NaN))
5174 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5175 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5177 (defvar js2-tokens nil
5178 "List of all defined token names.") ; initialized in `js2-token-names'
5180 (defconst js2-token-names
5181 (let* ((names (make-vector js2-num-tokens -1))
5182 (case-fold-search nil) ; only match js2-UPPER_CASE
5183 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5184 (loop for sym in syms
5187 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5189 (aset names (symbol-value sym) ; code, e.g. 152
5190 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5191 (push sym js2-tokens)))
5193 "Vector mapping int values to token string names, sans `js2-' prefix.")
5195 (defun js2-token-name (tok)
5196 "Return a string name for TOK, a token symbol or code.
5197 Signals an error if it's not a recognized token."
5200 (setq code (symbol-value tok)))
5203 (if (and (numberp code)
5205 (< code js2-num-tokens))
5206 (aref js2-token-names code)
5207 (error "Invalid token: %s" code)))))
5209 (defsubst js2-token-sym (tok)
5210 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5211 (intern (js2-token-name tok)))
5213 (defconst js2-token-codes
5214 (let ((table (make-hash-table :test 'eq :size 256)))
5215 (loop for name across js2-token-names
5216 for sym = (intern (concat "js2-" name))
5218 (puthash sym (symbol-value sym) table))
5219 ;; clean up a few that are "wrong" in Rhino's token codes
5220 (puthash 'js2-DELETE js2-DELPROP table)
5222 "Hashtable mapping token symbols to their bytecodes.")
5224 (defsubst js2-token-code (sym)
5225 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5226 (or (gethash sym js2-token-codes)
5227 (error "Invalid token symbol: %s " sym))) ; signal code bug
5229 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5230 (setq js2-token-end js2-ts-cursor)
5231 (js2-report-error msg nil
5232 (or beg js2-token-beg)
5233 (or len (- js2-token-end js2-token-beg)))
5235 (throw 'return js2-ERROR)))
5237 (defsubst js2-get-string-from-buffer ()
5238 "Reverse the char accumulator and return it as a string."
5239 (setq js2-token-end js2-ts-cursor)
5240 (if js2-ts-string-buffer
5241 (apply #'string (nreverse js2-ts-string-buffer))
5244 ;; TODO: could potentially avoid a lot of consing by allocating a
5245 ;; char buffer the way Rhino does.
5246 (defsubst js2-add-to-string (c)
5247 (push c js2-ts-string-buffer))
5249 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5250 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5251 ;; any other character: when it's not part of the current token, we
5252 ;; unget it, allowing it to be read again by the following call.
5253 (defsubst js2-unget-char ()
5254 (decf js2-ts-cursor))
5256 ;; Rhino distinguishes \r and \n line endings. We don't need to
5257 ;; because we only scan from Emacs buffers, which always use \n.
5258 (defsubst js2-get-char ()
5259 "Read and return the next character from the input buffer.
5260 Increments `js2-ts-lineno' if the return value is a newline char.
5261 Updates `js2-ts-cursor' to the point after the returned char.
5262 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5263 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5265 ;; check for end of buffer
5266 (if (>= js2-ts-cursor (point-max))
5267 (setq js2-ts-hit-eof t
5268 js2-ts-cursor (1+ js2-ts-cursor)
5269 c js2-EOF_CHAR) ; return value
5270 ;; otherwise read next char
5271 (setq c (char-before (incf js2-ts-cursor)))
5272 ;; if we read a newline, update counters
5274 (setq js2-ts-line-start js2-ts-cursor
5275 js2-ts-lineno (1+ js2-ts-lineno)))
5276 ;; TODO: skip over format characters
5279 (defsubst js2-read-unicode-escape ()
5280 "Read a \\uNNNN sequence from the input.
5281 Assumes the ?\ and ?u have already been read.
5282 Returns the unicode character, or nil if it wasn't a valid character.
5283 Doesn't change the values of any scanner variables."
5284 ;; I really wish I knew a better way to do this, but I can't
5285 ;; find the Emacs function that takes a 16-bit int and converts
5286 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5287 ;; Have to first check that it's 4 hex characters or it may stop
5290 (let ((s (buffer-substring-no-properties js2-ts-cursor
5291 (+ 4 js2-ts-cursor))))
5292 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5293 (read (concat "?\\u" s))))))
5295 (defsubst js2-match-char (test)
5296 "Consume and return next character if it matches TEST, a character.
5297 Returns nil and consumes nothing if TEST is not the next character."
5298 (let ((c (js2-get-char)))
5304 (defsubst js2-peek-char ()
5309 (defsubst js2-java-identifier-start-p (c)
5312 (js2-char-uppercase-p c)
5313 (js2-char-lowercase-p c)))
5315 (defsubst js2-java-identifier-part-p (c)
5316 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5317 ;; TODO: make me Unicode-friendly. See comments above.
5320 (js2-char-uppercase-p c)
5321 (js2-char-lowercase-p c)
5322 (and (>= c ?0) (<= c ?9))))
5324 (defsubst js2-alpha-p (c)
5325 (cond ((and (<= ?A c) (<= c ?Z)) t)
5326 ((and (<= ?a c) (<= c ?z)) t)
5329 (defsubst js2-digit-p (c)
5330 (and (<= ?0 c) (<= c ?9)))
5332 (defsubst js2-js-space-p (c)
5334 (memq c '(#x20 #x9 #xB #xC #xD))
5337 ;; TODO: change this nil to check for Unicode space character
5340 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5342 (defsubst js2-skip-line ()
5343 "Skip to end of line"
5345 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5347 (setq js2-token-end js2-ts-cursor)))
5349 (defun js2-init-scanner (&optional buf line)
5350 "Create token stream for BUF starting on LINE.
5351 BUF defaults to current-buffer and line defaults to 1.
5353 A buffer can only have one scanner active at a time, which yields
5354 dramatically simpler code than using a defstruct. If you need to
5355 have simultaneous scanners in a buffer, copy the regions to scan
5360 (setq js2-ts-dirty-line nil
5361 js2-ts-regexp-flags nil
5366 js2-ts-lineno (or line 1)
5367 js2-ts-line-end-char -1
5368 js2-ts-cursor (point-min)
5369 js2-ts-is-xml-attribute nil
5370 js2-ts-xml-is-tag-content nil
5371 js2-ts-xml-open-tags-count 0
5372 js2-ts-string-buffer nil)))
5374 ;; This function uses the cached op, string and number fields in
5375 ;; TokenStream; if getToken has been called since the passed token
5376 ;; was scanned, the op or string printed may be incorrect.
5377 (defun js2-token-to-string (token)
5378 ;; Not sure where this function is used in Rhino. Not tested.
5379 (if (not js2-debug-print-trees)
5381 (let ((name (js2-token-name token)))
5383 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5384 (concat name " `" js2-ts-string "'"))
5385 ((eq token js2-NUMBER)
5386 (format "NUMBER %g" js2-ts-number))
5390 (defconst js2-keywords
5392 case catch const continue
5393 debugger default delete do
5395 false finally for function
5396 if in instanceof import
5401 this throw true try typeof
5406 ;; Token names aren't exactly the same as the keywords, unfortunately.
5407 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5408 (defconst js2-kwd-tokens
5409 (let ((table (make-vector js2-num-tokens nil))
5412 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5413 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5415 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5416 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5421 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5426 (aset table i 'font-lock-keyword-face))
5427 (aset table js2-STRING 'font-lock-string-face)
5428 (aset table js2-REGEXP 'font-lock-string-face)
5429 (aset table js2-COMMENT 'font-lock-comment-face)
5430 (aset table js2-THIS 'font-lock-builtin-face)
5431 (aset table js2-VOID 'font-lock-constant-face)
5432 (aset table js2-NULL 'font-lock-constant-face)
5433 (aset table js2-TRUE 'font-lock-constant-face)
5434 (aset table js2-FALSE 'font-lock-constant-face)
5436 "Vector whose values are non-nil for tokens that are keywords.
5437 The values are default faces to use for highlighting the keywords.")
5439 (defconst js2-reserved-words
5447 implements import int interface
5450 package private protected public
5451 short static super synchronized
5455 (defconst js2-keyword-names
5456 (let ((table (make-hash-table :test 'equal)))
5457 (loop for k in js2-keywords
5459 (symbol-name k) ; instanceof
5460 (intern (concat "js2-"
5461 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5464 "JavaScript keywords by name, mapped to their symbols.")
5466 (defconst js2-reserved-word-names
5467 (let ((table (make-hash-table :test 'equal)))
5468 (loop for k in js2-reserved-words
5470 (puthash (symbol-name k) 'js2-RESERVED table))
5472 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5474 (defsubst js2-collect-string (buf)
5475 "Convert BUF, a list of chars, to a string.
5476 Reverses BUF before converting."
5480 ((null buf) ; for emacs21 compat
5484 (apply #'string (nreverse buf))
5487 (defun js2-string-to-keyword (s)
5488 "Return token for S, a string, if S is a keyword or reserved word.
5489 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5490 (or (gethash s js2-keyword-names)
5491 (gethash s js2-reserved-word-names)))
5493 (defsubst js2-ts-set-char-token-bounds ()
5494 "Used when next token is one character."
5495 (setq js2-token-beg (1- js2-ts-cursor)
5496 js2-token-end js2-ts-cursor))
5498 (defsubst js2-ts-return (token)
5499 "Return an N-character TOKEN from `js2-get-token'.
5500 Updates `js2-token-end' accordingly."
5501 (setq js2-token-end js2-ts-cursor)
5502 (throw 'return token))
5504 (defsubst js2-x-digit-to-int (c accumulator)
5505 "Build up a hex number.
5506 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5507 corresponding number. Otherwise return -1."
5510 ;; Use 0..9 < A..Z < a..z
5515 (throw 'check nil)))
5519 (throw 'check nil)))
5523 (throw 'check nil))))
5525 (logior c (lsh accumulator 4))))
5527 (defun js2-get-token ()
5528 "Return next JavaScript token, an int such as js2-RETURN."
5532 is-unicode-escape-start
5546 ;; Eat whitespace, possibly sensitive to newlines.
5549 (setq c (js2-get-char))
5551 ((eq c js2-EOF_CHAR)
5552 (js2-ts-set-char-token-bounds)
5553 (throw 'return js2-EOF))
5555 (js2-ts-set-char-token-bounds)
5556 (setq js2-ts-dirty-line nil)
5557 (throw 'return js2-EOL))
5558 ((not (js2-js-space-p c))
5559 (if (/= c ?-) ; in case end of HTML comment
5560 (setq js2-ts-dirty-line t))
5561 (setq continue nil))))
5562 ;; Assume the token will be 1 char - fixed up below.
5563 (js2-ts-set-char-token-bounds)
5565 (throw 'return js2-XMLATTR))
5566 ;; identifier/keyword/instanceof?
5567 ;; watch out for starting with a <backslash>
5570 (setq c (js2-get-char))
5572 (setq identifier-start t
5573 is-unicode-escape-start t
5574 js2-ts-string-buffer nil)
5575 (setq identifier-start nil)
5579 (when (setq identifier-start (js2-java-identifier-start-p c))
5580 (setq js2-ts-string-buffer nil)
5581 (js2-add-to-string c))))
5582 (when identifier-start
5583 (setq contains-escape is-unicode-escape-start)
5586 (if is-unicode-escape-start
5587 ;; strictly speaking we should probably push-back
5588 ;; all the bad characters if the <backslash>uXXXX
5589 ;; sequence is malformed. But since there isn't a
5590 ;; correct context(is there?) for a bad Unicode
5591 ;; escape sequence in an identifier, we can report
5596 (setq c (js2-get-char)
5597 escape-val (js2-x-digit-to-int c escape-val))
5598 ;; Next check takes care of c < 0 and bad escape
5599 (if (minusp escape-val)
5600 (throw 'break nil)))
5601 (if (minusp escape-val)
5602 (js2-report-scan-error "msg.invalid.escape" t))
5603 (js2-add-to-string escape-val)
5604 (setq is-unicode-escape-start nil))
5605 (setq c (js2-get-char))
5608 (setq c (js2-get-char))
5610 (setq is-unicode-escape-start t
5612 (js2-report-scan-error "msg.illegal.character" t)))
5614 (if (or (eq c js2-EOF_CHAR)
5615 (not (js2-java-identifier-part-p c)))
5617 (js2-add-to-string c))))))
5619 (setq str (js2-get-string-from-buffer))
5620 (unless contains-escape
5621 ;; OPT we shouldn't have to make a string (object!) to
5622 ;; check if it's a keyword.
5623 ;; Return the corresponding token if it's a keyword
5624 (when (setq result (js2-string-to-keyword str))
5625 (if (and (< js2-language-version 170)
5626 (memq result '(js2-LET js2-YIELD)))
5627 ;; LET and YIELD are tokens only in 1.7 and later
5628 (setq result 'js2-NAME))
5629 (if (not (eq result 'js2-RESERVED))
5630 (throw 'return (js2-token-code result)))
5631 (js2-report-warning "msg.reserved.keyword" str)))
5632 ;; If we want to intern these as Rhino does, just use (intern str)
5633 (setq js2-ts-string str)
5634 (throw 'return js2-NAME)) ; end identifier/kwd check
5636 (when (or (js2-digit-p c)
5637 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5638 (setq js2-ts-string-buffer nil
5641 (setq c (js2-get-char))
5643 ((or (eq c ?x) (eq c ?X))
5645 (setq c (js2-get-char)))
5649 (js2-add-to-string ?0))))
5651 (while (<= 0 (js2-x-digit-to-int c 0))
5652 (js2-add-to-string c)
5653 (setq c (js2-get-char)))
5654 (while (and (<= ?0 c) (<= c ?9))
5655 ;; We permit 08 and 09 as decimal numbers, which
5656 ;; makes our behavior a superset of the ECMA
5657 ;; numeric grammar. We might not always be so
5658 ;; permissive, so we warn about it.
5659 (when (and (eq base 8) (>= c ?8))
5660 (js2-report-warning "msg.bad.octal.literal"
5661 (if (eq c ?8) "8" "9"))
5663 (js2-add-to-string c)
5664 (setq c (js2-get-char))))
5666 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5667 (setq is-integer nil)
5670 (js2-add-to-string c)
5671 (setq c (js2-get-char))
5672 while (js2-digit-p c)))
5673 (when (memq c '(?e ?E))
5674 (js2-add-to-string c)
5675 (setq c (js2-get-char))
5676 (when (memq c '(?+ ?-))
5677 (js2-add-to-string c)
5678 (setq c (js2-get-char)))
5679 (unless (js2-digit-p c)
5680 (js2-report-scan-error "msg.missing.exponent" t))
5682 (js2-add-to-string c)
5683 (setq c (js2-get-char))
5684 while (js2-digit-p c))))
5686 (setq js2-ts-string (js2-get-string-from-buffer)
5688 (if (and (eq base 10) (not is-integer))
5689 (string-to-number js2-ts-string)
5690 ;; TODO: call runtime number-parser. Some of it is in
5691 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5692 (string-to-number js2-ts-string)))
5693 (throw 'return js2-NUMBER))
5695 (when (memq c '(?\" ?\'))
5696 ;; We attempt to accumulate a string the fast way, by
5697 ;; building it directly out of the reader. But if there
5698 ;; are any escaped characters in the string, we revert to
5699 ;; building it out of a string buffer.
5701 js2-ts-string-buffer nil
5704 (while (/= c quote-char)
5706 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5708 (setq js2-token-end js2-ts-cursor)
5709 (js2-report-error "msg.unterminated.string.lit")
5710 (throw 'return js2-STRING))
5712 ;; We've hit an escaped character
5713 (setq c (js2-get-char))
5722 (setq c1 (js2-read-unicode-escape))
5723 (if js2-parse-ide-mode
5726 ;; just copy the string in IDE-mode
5727 (js2-add-to-string ?\\)
5728 (js2-add-to-string ?u)
5730 (js2-add-to-string (js2-get-char)))
5731 (setq c (js2-get-char))) ; added at end of loop
5732 ;; flag it as an invalid escape
5733 (js2-report-warning "msg.invalid.escape"
5734 nil (- js2-ts-cursor 2) 6))
5735 ;; Get 4 hex digits; if the u escape is not
5736 ;; followed by 4 hex digits, use 'u' + the
5737 ;; literal character sequence that follows.
5738 (js2-add-to-string ?u)
5741 (setq c (js2-get-char)
5742 escape-val (js2-x-digit-to-int c escape-val))
5743 (if (minusp escape-val)
5744 (throw 'continue nil))
5745 (js2-add-to-string c))
5746 ;; prepare for replace of stored 'u' sequence by escape value
5747 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5750 ;; Get 2 hex digits, defaulting to 'x'+literal
5751 ;; sequence, as above.
5752 (setq c (js2-get-char)
5753 escape-val (js2-x-digit-to-int c 0))
5754 (if (minusp escape-val)
5756 (js2-add-to-string ?x)
5757 (throw 'continue nil))
5760 escape-val (js2-x-digit-to-int c escape-val))
5761 (if (minusp escape-val)
5763 (js2-add-to-string ?x)
5764 (js2-add-to-string c1)
5765 (throw 'continue nil))
5767 (setq c escape-val))))
5769 ;; Remove line terminator after escape to follow
5770 ;; SpiderMonkey and C/C++
5771 (setq c (js2-get-char))
5772 (throw 'continue nil))
5774 (when (and (<= ?0 c) (< c ?8))
5777 (when (and (<= ?0 c) (< c ?8))
5778 (setq val (- (+ (* 8 val) c) ?0)
5780 (when (and (<= ?0 c)
5783 ;; c is 3rd char of octal sequence only
5784 ;; if the resulting val <= 0377
5785 (setq val (- (+ (* 8 val) c) ?0)
5789 (js2-add-to-string c)
5790 (setq c (js2-get-char)))))
5791 (setq js2-ts-string (js2-get-string-from-buffer))
5792 (throw 'return js2-STRING))
5795 (throw 'return js2-SEMI))
5797 (throw 'return js2-LB))
5799 (throw 'return js2-RB))
5801 (throw 'return js2-LC))
5803 (throw 'return js2-RC))
5805 (throw 'return js2-LP))
5807 (throw 'return js2-RP))
5809 (throw 'return js2-COMMA))
5811 (throw 'return js2-HOOK))
5813 (if (js2-match-char ?:)
5814 (js2-ts-return js2-COLONCOLON)
5815 (throw 'return js2-COLON)))
5817 (if (js2-match-char ?.)
5818 (js2-ts-return js2-DOTDOT)
5819 (if (js2-match-char ?\()
5820 (js2-ts-return js2-DOTQUERY)
5821 (throw 'return js2-DOT))))
5823 (if (js2-match-char ?|)
5824 (throw 'return js2-OR)
5825 (if (js2-match-char ?=)
5826 (js2-ts-return js2-ASSIGN_BITOR)
5827 (throw 'return js2-BITOR))))
5829 (if (js2-match-char ?=)
5830 (js2-ts-return js2-ASSIGN_BITOR)
5831 (throw 'return js2-BITXOR)))
5833 (if (js2-match-char ?&)
5834 (throw 'return js2-AND)
5835 (if (js2-match-char ?=)
5836 (js2-ts-return js2-ASSIGN_BITAND)
5837 (throw 'return js2-BITAND))))
5839 (if (js2-match-char ?=)
5840 (if (js2-match-char ?=)
5841 (js2-ts-return js2-SHEQ)
5842 (throw 'return js2-EQ))
5843 (throw 'return js2-ASSIGN)))
5845 (if (js2-match-char ?=)
5846 (if (js2-match-char ?=)
5847 (js2-ts-return js2-SHNE)
5848 (js2-ts-return js2-NE))
5849 (throw 'return js2-NOT)))
5851 ;; NB:treat HTML begin-comment as comment-till-eol
5852 (when (js2-match-char ?!)
5853 (when (js2-match-char ?-)
5854 (when (js2-match-char ?-)
5856 (setq js2-ts-comment-type 'html)
5857 (throw 'return js2-COMMENT)))
5859 (if (js2-match-char ?<)
5860 (if (js2-match-char ?=)
5861 (js2-ts-return js2-ASSIGN_LSH)
5862 (js2-ts-return js2-LSH))
5863 (if (js2-match-char ?=)
5864 (js2-ts-return js2-LE)
5865 (throw 'return js2-LT))))
5867 (if (js2-match-char ?>)
5868 (if (js2-match-char ?>)
5869 (if (js2-match-char ?=)
5870 (js2-ts-return js2-ASSIGN_URSH)
5871 (js2-ts-return js2-URSH))
5872 (if (js2-match-char ?=)
5873 (js2-ts-return js2-ASSIGN_RSH)
5874 (js2-ts-return js2-RSH)))
5875 (if (js2-match-char ?=)
5876 (js2-ts-return js2-GE)
5877 (throw 'return js2-GT))))
5879 (if (js2-match-char ?=)
5880 (js2-ts-return js2-ASSIGN_MUL)
5881 (throw 'return js2-MUL)))
5883 ;; is it a // comment?
5884 (when (js2-match-char ?/)
5885 (setq js2-token-beg (- js2-ts-cursor 2))
5887 (setq js2-ts-comment-type 'line)
5888 ;; include newline so highlighting goes to end of window
5889 (incf js2-token-end)
5890 (throw 'return js2-COMMENT))
5891 ;; is it a /* comment?
5892 (when (js2-match-char ?*)
5893 (setq look-for-slash nil
5894 js2-token-beg (- js2-ts-cursor 2)
5896 (if (js2-match-char ?*)
5898 (setq look-for-slash t)
5902 (setq c (js2-get-char))
5904 ((eq c js2-EOF_CHAR)
5905 (setq js2-token-end (1- js2-ts-cursor))
5906 (js2-report-error "msg.unterminated.comment")
5907 (throw 'return js2-COMMENT))
5909 (setq look-for-slash t))
5912 (js2-ts-return js2-COMMENT)))
5914 (setq look-for-slash nil
5915 js2-token-end js2-ts-cursor)))))
5916 (if (js2-match-char ?=)
5917 (js2-ts-return js2-ASSIGN_DIV)
5918 (throw 'return js2-DIV)))
5920 (when js2-skip-preprocessor-directives
5922 (setq js2-ts-comment-type 'preprocessor
5923 js2-token-end js2-ts-cursor)
5924 (throw 'return js2-COMMENT))
5925 (throw 'return js2-ERROR))
5927 (if (js2-match-char ?=)
5928 (js2-ts-return js2-ASSIGN_MOD)
5929 (throw 'return js2-MOD)))
5931 (throw 'return js2-BITNOT))
5933 (if (js2-match-char ?=)
5934 (js2-ts-return js2-ASSIGN_ADD)
5935 (if (js2-match-char ?+)
5936 (js2-ts-return js2-INC)
5937 (throw 'return js2-ADD))))
5940 ((js2-match-char ?=)
5941 (setq c js2-ASSIGN_SUB))
5942 ((js2-match-char ?-)
5943 (unless js2-ts-dirty-line
5944 ;; treat HTML end-comment after possible whitespace
5945 ;; after line start as comment-until-eol
5946 (when (js2-match-char ?>)
5948 (setq js2-ts-comment-type 'html)
5949 (throw 'return js2-COMMENT)))
5953 (setq js2-ts-dirty-line t)
5956 (js2-report-scan-error "msg.illegal.character")))))))
5958 (defun js2-read-regexp (start-token)
5959 "Called by parser when it gets / or /= in literal context."
5962 in-class ; inside a '[' .. ']' character-class
5965 (setq js2-token-beg js2-ts-cursor
5966 js2-ts-string-buffer nil
5967 js2-ts-regexp-flags nil)
5968 (if (eq start-token js2-ASSIGN_DIV)
5970 (js2-add-to-string ?=)
5971 (if (not (eq start-token js2-DIV))
5972 (error "failed assertion")))
5973 (while (and (not err)
5974 (or (/= (setq c (js2-get-char)) ?/)
5979 (setq js2-token-end (1- js2-ts-cursor)
5981 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5982 (js2-report-error "msg.unterminated.re.lit"))
5985 (js2-add-to-string c)
5986 (setq c (js2-get-char)))
5990 (setq in-class nil)))
5991 (js2-add-to-string c))))
5995 ((js2-match-char ?g)
5997 ((js2-match-char ?i)
5999 ((js2-match-char ?m)
6002 (setq continue nil))))
6003 (if (js2-alpha-p (js2-peek-char))
6004 (js2-report-scan-error "msg.invalid.re.flag" t
6006 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6007 js2-ts-regexp-flags (js2-collect-string flags)
6008 js2-token-end js2-ts-cursor)
6009 ;; tell `parse-partial-sexp' to ignore this range of chars
6010 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6012 (defun js2-get-first-xml-token ()
6013 (setq js2-ts-xml-open-tags-count 0
6014 js2-ts-is-xml-attribute nil
6015 js2-ts-xml-is-tag-content nil)
6017 (js2-get-next-xml-token))
6019 (defsubst js2-xml-discard-string ()
6020 "Throw away the string in progress and flag an XML parse error."
6021 (setq js2-ts-string-buffer nil
6023 (js2-report-scan-error "msg.XML.bad.form" t))
6025 (defun js2-get-next-xml-token ()
6026 (setq js2-ts-string-buffer nil ; for recording the XML
6027 js2-token-beg js2-ts-cursor)
6032 (setq c (js2-get-char))
6035 (throw 'return js2-ERROR))
6036 (js2-ts-xml-is-tag-content
6039 (js2-add-to-string c)
6040 (setq js2-ts-xml-is-tag-content nil
6041 js2-ts-is-xml-attribute nil))
6043 (js2-add-to-string c)
6044 (when (eq ?> (js2-peek-char))
6045 (setq c (js2-get-char))
6046 (js2-add-to-string c)
6047 (setq js2-ts-xml-is-tag-content nil)
6048 (decf js2-ts-xml-open-tags-count)))
6051 (setq js2-ts-string (js2-get-string-from-buffer))
6052 (throw 'return js2-XML))
6054 (js2-add-to-string c)
6055 (unless (js2-read-quoted-string c)
6056 (throw 'return js2-ERROR)))
6058 (js2-add-to-string c)
6059 (setq js2-ts-is-xml-attribute t))
6061 (js2-add-to-string c))
6063 (js2-add-to-string c)
6064 (setq js2-ts-is-xml-attribute nil)))
6065 (when (and (not js2-ts-xml-is-tag-content)
6066 (zerop js2-ts-xml-open-tags-count))
6067 (setq js2-ts-string (js2-get-string-from-buffer))
6068 (throw 'return js2-XMLEND)))
6070 ;; else not tag content
6073 (js2-add-to-string c)
6074 (setq c (js2-peek-char))
6077 (setq c (js2-get-char)) ;; skip !
6078 (js2-add-to-string c)
6079 (setq c (js2-peek-char))
6082 (setq c (js2-get-char)) ;; skip -
6083 (js2-add-to-string c)
6086 (js2-add-to-string c)
6087 (unless (js2-read-xml-comment)
6088 (throw 'return js2-ERROR)))
6089 (js2-xml-discard-string)
6090 (throw 'return js2-ERROR)))
6092 (setq c (js2-get-char)) ;; skip [
6093 (js2-add-to-string c)
6094 (if (and (= (js2-get-char) ?C)
6095 (= (js2-get-char) ?D)
6096 (= (js2-get-char) ?A)
6097 (= (js2-get-char) ?T)
6098 (= (js2-get-char) ?A)
6099 (= (js2-get-char) ?\[))
6101 (js2-add-to-string ?C)
6102 (js2-add-to-string ?D)
6103 (js2-add-to-string ?A)
6104 (js2-add-to-string ?T)
6105 (js2-add-to-string ?A)
6106 (js2-add-to-string ?\[)
6107 (unless (js2-read-cdata)
6108 (throw 'return js2-ERROR)))
6109 (js2-xml-discard-string)
6110 (throw 'return js2-ERROR)))
6112 (unless (js2-read-entity)
6113 (throw 'return js2-ERROR)))))
6115 (setq c (js2-get-char)) ;; skip ?
6116 (js2-add-to-string c)
6117 (unless (js2-read-PI)
6118 (throw 'return js2-ERROR)))
6121 (setq c (js2-get-char)) ;; skip /
6122 (js2-add-to-string c)
6123 (when (zerop js2-ts-xml-open-tags-count)
6124 (js2-xml-discard-string)
6125 (throw 'return js2-ERROR))
6126 (setq js2-ts-xml-is-tag-content t)
6127 (decf js2-ts-xml-open-tags-count))
6130 (setq js2-ts-xml-is-tag-content t)
6131 (incf js2-ts-xml-open-tags-count))))
6134 (setq js2-ts-string (js2-get-string-from-buffer))
6135 (throw 'return js2-XML))
6137 (js2-add-to-string c))))))))
6138 (setq js2-token-end js2-ts-cursor)
6141 (defun js2-read-quoted-string (quote)
6144 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6145 (js2-add-to-string c)
6148 (js2-xml-discard-string) ;; throw away string in progress
6151 (defun js2-read-xml-comment ()
6152 (let ((c (js2-get-char)))
6154 (while (/= c js2-EOF_CHAR)
6156 (js2-add-to-string c)
6157 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6158 (setq c (js2-get-char))
6159 (js2-add-to-string c)
6160 (if (eq (js2-peek-char) ?>)
6162 (setq c (js2-get-char)) ;; skip >
6163 (js2-add-to-string c)
6165 (throw 'continue nil)))
6166 (setq c (js2-get-char))))
6167 (js2-xml-discard-string)
6170 (defun js2-read-cdata ()
6171 (let ((c (js2-get-char)))
6173 (while (/= c js2-EOF_CHAR)
6175 (js2-add-to-string c)
6176 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6177 (setq c (js2-get-char))
6178 (js2-add-to-string c)
6179 (if (eq (js2-peek-char) ?>)
6181 (setq c (js2-get-char)) ;; Skip >
6182 (js2-add-to-string c)
6184 (throw 'continue nil)))
6185 (setq c (js2-get-char))))
6186 (js2-xml-discard-string)
6189 (defun js2-read-entity ()
6193 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6194 (js2-add-to-string c)
6200 (if (zerop decl-tags)
6201 (throw 'return t)))))
6202 (js2-xml-discard-string)
6205 (defun js2-read-PI ()
6206 "Scan an XML processing instruction."
6209 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6210 (js2-add-to-string c)
6211 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6212 (setq c (js2-get-char)) ;; Skip >
6213 (js2-add-to-string c)
6215 (js2-xml-discard-string)
6218 (defun js2-scanner-get-line ()
6219 "Return the text of the current scan line."
6220 (buffer-substring (point-at-bol) (point-at-eol)))
6224 (defsubst js2-set-face (beg end face &optional record)
6225 "Fontify a region. If RECORD is non-nil, record for later."
6226 (when (plusp js2-highlight-level)
6227 (setq beg (min (point-max) beg)
6228 beg (max (point-min) beg)
6229 end (min (point-max) end)
6230 end (max (point-min) end))
6232 (push (list beg end face) js2-mode-fontifications)
6233 (put-text-property beg end 'face face))))
6235 (defsubst js2-set-kid-face (pos kid len face)
6236 "Set-face on a child node.
6237 POS is absolute buffer position of parent.
6238 KID is the child node.
6239 LEN is the length to fontify.
6240 FACE is the face to fontify with."
6241 (js2-set-face (+ pos (js2-node-pos kid))
6242 (+ pos (js2-node-pos kid) (js2-node-len kid))
6245 (defsubst js2-fontify-kwd (start length)
6246 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6248 (defsubst js2-clear-face (beg end)
6249 (remove-text-properties beg end '(face nil
6254 (defsubst js2-record-text-property (beg end prop value)
6255 "Record a text property to set when parsing finishes."
6256 (push (list beg end prop value) js2-mode-deferred-properties))
6258 (defconst js2-ecma-global-props
6261 '("Infinity" "NaN" "undefined" "arguments") t)
6263 "Value properties of the Ecma-262 Global Object.
6264 Shown at or above `js2-highlight-level' 2.")
6266 ;; might want to add the name "arguments" to this list?
6267 (defconst js2-ecma-object-props
6270 '("prototype" "__proto__" "__parent__") t)
6272 "Value properties of the Ecma-262 Object constructor.
6273 Shown at or above `js2-highlight-level' 2.")
6275 (defconst js2-ecma-global-funcs
6279 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6280 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6282 "Function properties of the Ecma-262 Global object.
6283 Shown at or above `js2-highlight-level' 2.")
6285 (defconst js2-ecma-number-props
6287 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6289 "POSITIVE_INFINITY") t)
6291 "Properties of the Ecma-262 Number constructor.
6292 Shown at or above `js2-highlight-level' 2.")
6294 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6295 "Properties of the Ecma-262 Date constructor.
6296 Shown at or above `js2-highlight-level' 2.")
6298 (defconst js2-ecma-math-props
6301 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6304 "Properties of the Ecma-262 Math object.
6305 Shown at or above `js2-highlight-level' 2.")
6307 (defconst js2-ecma-math-funcs
6310 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6311 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6313 "Function properties of the Ecma-262 Math object.
6314 Shown at or above `js2-highlight-level' 2.")
6316 (defconst js2-ecma-function-props
6320 '(;; properties of the Object prototype object
6321 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6322 "toLocaleString" "toString" "valueOf"
6323 ;; properties of the Function prototype object
6325 ;; properties of the Array prototype object
6326 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6328 ;; properties of the String prototype object
6329 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6330 "localeCompare" "match" "replace" "search" "split" "substring"
6331 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6333 ;; properties of the Number prototype object
6334 "toExponential" "toFixed" "toPrecision"
6335 ;; properties of the Date prototype object
6336 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6337 "getMinutes" "getMonth" "getSeconds" "getTime"
6338 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6339 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6340 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6341 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6342 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6343 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6344 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6345 "toTimeString" "toUTCString"
6346 ;; properties of the RegExp prototype object
6348 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6349 "toSource" "__defineGetter__" "__defineSetter__"
6350 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6351 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6354 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6355 Shown at or above `js2-highlight-level' 3.")
6357 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6358 (let ((target-name (and target
6359 (js2-name-node-p target)
6360 (js2-name-node-name target)))
6361 (prop-name (if prop (js2-name-node-name prop)))
6362 (level1 (>= js2-highlight-level 1))
6363 (level2 (>= js2-highlight-level 2))
6364 (level3 (>= js2-highlight-level 3))
6372 ((and level3 (string-match js2-ecma-function-props prop-name))
6373 (setq face 'font-lock-builtin-face))
6374 ((and target-name prop)
6376 ((string= target-name "Date")
6377 (if (string-match js2-ecma-date-props prop-name)
6378 (setq face 'font-lock-builtin-face)))
6379 ((string= target-name "Math")
6380 (if (string-match js2-ecma-math-funcs prop-name)
6381 (setq face 'font-lock-builtin-face)))))))
6383 (if (string-match js2-ecma-global-funcs prop-name)
6384 (setq face 'font-lock-builtin-face))))
6388 ((string= target-name "Number")
6389 (if (string-match js2-ecma-number-props prop-name)
6390 (setq face 'font-lock-constant-face)))
6391 ((string= target-name "Math")
6392 (if (string-match js2-ecma-math-props prop-name)
6393 (setq face 'font-lock-constant-face)))))
6395 (if (string-match js2-ecma-object-props prop-name)
6396 (setq face 'font-lock-constant-face)))))
6398 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6399 (js2-node-pos prop))) ; relative
6400 (+ pos (js2-node-len prop))
6403 (defun js2-parse-highlight-member-expr-node (node)
6404 "Perform syntax highlighting of EcmaScript built-in properties.
6405 The variable `js2-highlight-level' governs this highighting."
6406 (let (face target prop name pos end parent call-p callee)
6408 ;; case 1: simple name, e.g. foo
6409 ((js2-name-node-p node)
6410 (setq name (js2-name-node-name node))
6411 ;; possible for name to be nil in rare cases - saw it when
6412 ;; running js2-mode on an elisp buffer. Might as well try to
6413 ;; make it so js2-mode never barfs.
6415 (setq face (if (string-match js2-ecma-global-props name)
6416 'font-lock-constant-face))
6418 (setq pos (js2-node-pos node)
6419 end (+ pos (js2-node-len node)))
6420 (js2-set-face pos end face))))
6421 ;; case 2: property access or function call
6422 ((or (js2-prop-get-node-p node)
6423 ;; highlight function call if expr is a prop-get node
6424 ;; or a plain name (i.e. unqualified function call)
6425 (and (setq call-p (js2-call-node-p node))
6426 (setq callee (js2-call-node-target node)) ; separate setq!
6427 (or (js2-prop-get-node-p callee)
6428 (js2-name-node-p callee))))
6430 node (if call-p callee node))
6431 (if (and call-p (js2-name-node-p callee))
6433 (setq target (js2-prop-get-node-left node)
6434 prop (js2-prop-get-node-right node)))
6436 ((js2-name-node-p target)
6437 (if (js2-name-node-p prop)
6438 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6439 (js2-parse-highlight-prop-get parent target prop call-p)
6440 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6441 (js2-parse-highlight-prop-get parent target nil call-p)))
6442 ((js2-name-node-p prop)
6443 ;; case 2c: complex target, simple name, e.g. x[y].bar
6444 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6446 (defun js2-parse-highlight-member-expr-fn-name (expr)
6447 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6448 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6449 We currently only handle the case where the last component is a prop-get
6450 of a simple name. Called before EXPR has a parent node."
6452 (name (and (js2-prop-get-node-p expr)
6453 (js2-prop-get-node-right expr))))
6454 (when (js2-name-node-p name)
6455 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6456 (js2-node-pos name)))
6457 (+ pos (js2-node-len name))
6458 'font-lock-function-name-face
6461 ;; source: http://jsdoc.sourceforge.net/
6462 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6463 ;; allows type specifications, and needs work before entering the wild.
6465 (defconst js2-jsdoc-param-tag-regexp
6466 (concat "^\\s-*\\*+\\s-*\\(@"
6467 "\\(?:param\\|argument\\)"
6469 "\\s-*\\({[^}]+}\\)?" ; optional type
6470 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6472 "Matches jsdoc tags with optional type and optional param name.")
6474 (defconst js2-jsdoc-typed-tag-regexp
6475 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6489 "\\)\\)\\s-*\\({[^}]+}\\)?")
6490 "Matches jsdoc tags with optional type.")
6492 (defconst js2-jsdoc-arg-tag-regexp
6493 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6516 "\\)\\)\\s-+\\([^ \t]+\\)")
6517 "Matches jsdoc tags with a single argument.")
6519 (defconst js2-jsdoc-empty-tag-regexp
6520 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6560 "Matches empty jsdoc tags.")
6562 (defconst js2-jsdoc-link-tag-regexp
6563 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6564 "Matches a jsdoc link or code tag.")
6566 (defconst js2-jsdoc-see-tag-regexp
6567 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6568 "Matches a jsdoc @see tag.")
6570 (defconst js2-jsdoc-html-tag-regexp
6571 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6572 "Matches a simple (no attributes) html start- or end-tag.")
6574 (defsubst js2-jsdoc-highlight-helper ()
6575 (js2-set-face (match-beginning 1)
6577 'js2-jsdoc-tag-face)
6578 (if (match-beginning 2)
6580 (goto-char (match-beginning 2))
6581 (= (char-after) ?{))
6582 (js2-set-face (1+ (match-beginning 2))
6584 'js2-jsdoc-type-face)
6585 (js2-set-face (match-beginning 2)
6587 'js2-jsdoc-value-face)))
6588 (if (match-beginning 3)
6589 (js2-set-face (match-beginning 3)
6591 'js2-jsdoc-value-face)))
6593 (defun js2-highlight-jsdoc (ast)
6594 "Highlight doc comment tags."
6595 (let ((comments (js2-ast-root-comments ast))
6598 (dolist (node comments)
6599 (when (eq (js2-comment-node-format node) 'jsdoc)
6600 (setq beg (js2-node-abs-pos node)
6601 end (+ beg (js2-node-len node)))
6603 (narrow-to-region beg end)
6604 (dolist (re (list js2-jsdoc-param-tag-regexp
6605 js2-jsdoc-typed-tag-regexp
6606 js2-jsdoc-arg-tag-regexp
6607 js2-jsdoc-link-tag-regexp
6608 js2-jsdoc-see-tag-regexp
6609 js2-jsdoc-empty-tag-regexp))
6611 (while (re-search-forward re nil t)
6612 (js2-jsdoc-highlight-helper)))
6613 ;; simple highlighting for html tags
6615 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6616 (js2-set-face (match-beginning 1)
6618 'js2-jsdoc-html-tag-delimiter-face)
6619 (js2-set-face (match-beginning 2)
6621 'js2-jsdoc-html-tag-name-face)
6622 (js2-set-face (match-beginning 3)
6624 'js2-jsdoc-html-tag-delimiter-face))))))))
6626 (defun js2-highlight-assign-targets (node left right)
6627 "Highlight function properties and external variables."
6628 (let (leftpos end name)
6629 ;; highlight vars and props assigned function values
6630 (when (js2-function-node-p right)
6632 ;; var foo = function() {...}
6633 ((js2-name-node-p left)
6635 ;; foo.bar.baz = function() {...}
6636 ((and (js2-prop-get-node-p left)
6637 (js2-name-node-p (js2-prop-get-node-right left)))
6638 (setq name (js2-prop-get-node-right left))))
6640 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6641 (+ leftpos (js2-node-len name))
6642 'font-lock-function-name-face
6644 ;; save variable assignments so we can check for undeclared later
6645 ;; (can't do it here since var decls can come at end of script)
6646 (when (and js2-highlight-external-variables
6647 (setq name (js2-member-expr-leftmost-name left)))
6648 (push (list name js2-current-scope
6649 (setq leftpos (js2-node-abs-pos name))
6650 (setq end (+ leftpos (js2-node-len name))))
6651 js2-recorded-assignments))))
6653 (defun js2-highlight-undeclared-vars ()
6654 "After entire parse is finished, look for undeclared variable assignments.
6655 We have to wait until entire buffer is parsed, since JavaScript permits var
6656 decls to occur after they're used.
6658 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6659 it is considered declared."
6661 (dolist (entry js2-recorded-assignments)
6662 (destructuring-bind (name-node scope pos end) entry
6663 (setq name (js2-name-node-name name-node))
6664 (unless (or (member name js2-global-externs)
6665 (member name js2-default-externs)
6666 (member name js2-additional-externs)
6667 (js2-get-defining-scope scope name))
6668 (js2-set-face pos end 'js2-external-variable-face 'record)
6669 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6670 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6671 (setq js2-recorded-assignments nil)))
6675 ;; We currently only support imenu, but eventually should support speedbar and
6676 ;; possibly other browsing mechanisms.
6678 ;; The basic strategy is to identify function assignment targets of the form
6679 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6680 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6681 ;; for imenu after parsing is finished.
6683 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6684 ;; JavaScript, and the general problem is undecidable. However, several forms
6685 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6688 ;; function foo() -- function declaration
6689 ;; foo = function() -- function expression assigned to variable
6690 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6691 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6692 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6693 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6694 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6695 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6696 ;; function foo() {function bar() {...}} -- nested function
6697 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6699 ;; This list boils down to a few forms that can be combined recursively.
6700 ;; Top-level named function declarations include both the left-hand (name)
6701 ;; and the right-hand (function value) expressions needed to produce an imenu
6702 ;; entry. The other "right-hand" forms we need to look for are:
6703 ;; - functions declared as props/getters/setters in object literals
6704 ;; - nested named function declarations
6705 ;; The "left-hand" expressions that functions can be assigned to include:
6706 ;; - local/global variables
6707 ;; - nested property-get expressions like a.b.c.d
6708 ;; - element gets like foo[10] or foo['bar'] where the index
6709 ;; expression can be trivially converted to a property name. They
6710 ;; effectively then become property gets.
6712 ;; All the different definition types are canonicalized into the form
6713 ;; foo.bar.baz = position-of-function-keyword
6715 ;; We need to build a trie-like structure for imenu. As an example,
6716 ;; consider the following JavaScript code:
6718 ;; a = function() {...} // function at position 5
6719 ;; b = function() {...} // function at position 25
6720 ;; foo = function() {...} // function at position 100
6721 ;; foo.bar = function() {...} // function at position 200
6722 ;; foo.bar.baz = function() {...} // function at position 300
6723 ;; foo.bar.zab = function() {...} // function at position 400
6725 ;; During parsing we accumulate an entry for each definition in
6726 ;; the variable `js2-imenu-recorder', like so:
6732 ;; (foo bar baz 300)
6733 ;; (foo bar zab 400))
6735 ;; After parsing these entries are merged into this alist-trie:
6739 ;; (foo (<definition> . 3)
6740 ;; (bar (<definition> . 6)
6744 ;; Note the wacky need for a <definition> name. The token can be anything
6745 ;; that isn't a valid JavaScript identifier, because you might make foo
6746 ;; a function and then start setting properties on it that are also functions.
6748 (defsubst js2-prop-node-name (node)
6749 "Return the name of a node that may be a property-get/property-name.
6750 If NODE is not a valid name-node, string-node or integral number-node,
6751 returns nil. Otherwise returns the string name/value of the node."
6753 ((js2-name-node-p node)
6754 (js2-name-node-name node))
6755 ((js2-string-node-p node)
6756 (js2-string-node-value node))
6757 ((and (js2-number-node-p node)
6758 (string-match "^[0-9]+$" (js2-number-node-value node)))
6759 (js2-number-node-value node))
6760 ((js2-this-node-p node)
6763 (defsubst js2-node-qname-component (node)
6764 "Test function: return the name of this node, if it contributes to a qname.
6765 Returns nil if the node doesn't contribute."
6767 (or (js2-prop-node-name node)
6768 (if (and (js2-function-node-p node)
6769 (js2-function-node-name node))
6770 (js2-name-node-name (js2-function-node-name node))))))
6772 (defsubst js2-record-function-qname (fn-node qname)
6773 "Associate FN-NODE with its QNAME for later lookup.
6774 This is used in postprocessing the chain list. When we find a chain
6775 whose first element is a js2-THIS keyword node, we look up the parent
6776 function and see (using this map) whether it is the tail of a chain.
6777 If so, we replace the this-node with a copy of the parent's qname."
6778 (unless js2-imenu-function-map
6779 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6780 (puthash fn-node qname js2-imenu-function-map))
6782 (defun js2-record-imenu-functions (node &optional var)
6783 "Record function definitions for imenu.
6784 NODE is a function node or an object literal.
6785 VAR, if non-nil, is the expression that NODE is being assigned to."
6786 (when js2-parse-ide-mode
6787 (let ((fun-p (js2-function-node-p node))
6788 qname left fname-node pos)
6790 ;; non-anonymous function declaration?
6793 (setq fname-node (js2-function-node-name node)))
6794 (push (setq qname (list fname-node (js2-node-pos node)))
6796 (js2-record-function-qname node qname))
6797 ;; for remaining forms, compute left-side tree branch first
6798 ((and var (setq qname (js2-compute-nested-prop-get var)))
6800 ;; foo.bar.baz = function
6802 (push (nconc qname (list (js2-node-pos node)))
6804 (js2-record-function-qname node qname))
6805 ;; foo.bar.baz = object-literal
6806 ;; look for nested functions: {a: {b: function() {...} }}
6807 ((js2-object-node-p node)
6808 (js2-record-object-literal node qname))))))))
6810 (defun js2-compute-nested-prop-get (node)
6811 "If NODE is of form foo.bar.baz, return component nodes as a list.
6812 Otherwise returns nil. Element-gets can be treated as property-gets
6813 if the index expression is a name, a string, or a positive integer."
6814 (let (left right head)
6816 ((or (js2-name-node-p node)
6817 (js2-this-node-p node))
6819 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6820 ((js2-prop-get-node-p node) ; includes elem-get nodes
6821 (setq left (js2-prop-get-node-left node)
6822 right (js2-prop-get-node-right node))
6823 (if (and (or (js2-prop-get-node-p left) ; left == foo.bar
6824 (js2-name-node-p left)
6825 (js2-this-node-p left)) ; or left == foo
6826 (or (js2-name-node-p right) ; .bar
6827 (js2-string-node-p right) ; ['bar']
6828 (and (js2-number-node-p right) ; [10]
6829 (string-match "^[0-9]+$"
6830 (js2-number-node-value right)))))
6831 (if (setq head (js2-compute-nested-prop-get left))
6832 (nconc head (list right))))))))
6834 (defun js2-record-object-literal (node qname)
6835 "Recursively process an object literal looking for functions.
6836 NODE is an object literal that is the right-hand child of an assignment
6837 expression. QNAME is a list of nodes representing the assignment target,
6838 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6839 We do a depth-first traversal of NODE. Any functions we find are prefixed
6840 with QNAME plus the property name of the function and appended to the
6841 variable `js2-imenu-recorder'."
6842 ;; Elements are relative to parent position, which is still absolute,
6843 ;; since the parser passes the assignment target and value expressions
6844 ;; to us before they are added as children of the assignment node.
6845 (let ((pos (js2-node-pos node))
6847 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6848 (setq left (js2-infix-node-left e))
6850 ;; foo: function() {...}
6851 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6852 (when (js2-prop-node-name left)
6853 ;; As a policy decision, we record the position of the property,
6854 ;; not the position of the `function' keyword, since the property
6855 ;; is effectively the name of the function.
6856 (push (append qname (list left) (list (+ pos (js2-node-pos e))))
6858 (js2-record-function-qname right qname)))
6859 ;; foo: {object-literal} -- add foo to qname and recurse
6860 ((js2-object-node-p right)
6861 (js2-record-object-literal right
6862 (append qname (list (js2-infix-node-left e)))))))))
6864 (defsubst js2-node-top-level-decl-p (node)
6865 "Return t if NODE's name is defined in the top-level scope.
6866 Also returns t if NODE's name is not defined in any scope, since it implies
6867 that it's an external variable, which must also be in the top-level scope."
6868 (let* ((name (js2-prop-node-name node))
6869 (this-scope (js2-node-get-enclosing-scope node))
6872 ((js2-this-node-p node)
6876 ((setq defining-scope (js2-get-defining-scope this-scope name))
6877 (js2-ast-root-p defining-scope))
6880 (defun js2-browse-postprocess-chains (chains)
6881 "Modify function-declaration name chains after parsing finishes.
6882 Some of the information is only available after the parse tree is complete.
6883 For instance, following a 'this' reference requires a parent function node."
6884 (let (result head fn parent-chain p elem)
6885 (dolist (chain chains)
6886 ;; examine the head of each node to get its defining scope
6887 (setq head (car chain))
6889 ;; if top-level/external, keep as-is
6890 ((js2-node-top-level-decl-p head)
6891 (push chain result))
6892 ;; check for a this-reference
6893 ((eq (js2-node-type head) js2-THIS)
6894 (setq fn (js2-node-parent-script-or-fn head))
6895 ;; if there is no parent function, or if the parent function
6896 ;; is nested, discard the head node and keep the rest of the chain.
6897 (if (or (null fn) (js2-nested-function-p fn))
6898 (push (cdr chain) result)
6899 ;; else look up parent in function-map. If not found, discard chain.
6900 (when (setq parent-chain (and js2-imenu-function-map
6901 (gethash fn js2-imenu-function-map)))
6902 ;; else discard head node and prefix parent fn qname, which is
6903 ;; the parent-chain sans tail, to this chain.
6904 (push (append (butlast parent-chain) (cdr chain)) result))))))
6905 ;; finally replace each node in each chain with its name.
6906 (dolist (chain result)
6909 (if (js2-node-p (setq elem (car p)))
6910 (setcar p (js2-node-qname-component elem)))
6914 ;; Merge name chains into a trie-like tree structure of nested lists.
6915 ;; To simplify construction of the trie, we first build it out using the rule
6916 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6917 ;; [key, num-or-list]. The second element can be a number; if so, this key
6918 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6919 ;; associated with the key at this level.) Otherwise the second element is
6920 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6921 ;; a simple recursive formulation.
6923 ;; js2-mode is building the data structure for imenu. The imenu documentation
6924 ;; claims that it's the structure above, but in practice it wants the children
6925 ;; at the same list level as the key for that level, which is how I've drawn
6926 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6927 ;; list wrapper around the children at each level.
6929 ;; A completed nested imenu-alist entry looks like this:
6931 ;; ("<definition>" . 7)
6936 ;; In particular, the documentation for `imenu--index-alist' says that
6937 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6938 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6940 (defsubst js2-treeify (lst)
6941 "Convert (a b c d) to (a ((b ((c d)))))"
6942 (if (null (cddr lst)) ; list length <= 2
6944 (list (car lst) (list (js2-treeify (cdr lst))))))
6946 (defun js2-build-alist-trie (chains trie)
6947 "Merge declaration name chains into a trie-like alist structure for imenu.
6948 CHAINS is the qname chain list produced during parsing. TRIE is a
6949 list of elements built up so far."
6950 (let (head tail pos branch kids)
6951 (dolist (chain chains)
6952 (setq head (car chain)
6954 pos (if (numberp (car tail)) (car tail))
6955 branch (js2-find-if (lambda (n)
6956 (string= (car n) head))
6958 kids (second branch))
6960 ;; case 1: this key isn't in the trie yet
6963 (setcdr (last trie) (list (js2-treeify chain)))
6964 (setq trie (list (js2-treeify chain)))))
6965 ;; case 2: key is present with a single number entry: replace w/ list
6966 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6967 ;; ("<definition>" 20)))
6969 (setcar (cdr branch)
6970 (list (list "<definition-1>" kids)
6972 (list "<definition-2>" pos)
6973 (js2-treeify tail)))))
6974 ;; case 3: key is there (with kids), and we're a number entry
6978 (list (format "<definition-%d>"
6979 (1+ (loop for kid in kids
6980 count (eq ?< (aref (car kid) 0)))))
6982 ;; case 4: key is there with kids, need to merge in our chain
6984 (js2-build-alist-trie (list tail) kids))))
6987 (defun js2-flatten-trie (trie)
6988 "Convert TRIE to imenu-format.
6989 Recurses through nodes, and for each one whose second element is a list,
6990 appends the list's flattened elements to the current element. Also
6991 changes the tails into conses. For instance, this pre-flattened trie
7003 Note that the root of the trie has no key, just a list of chains.
7004 This is also true for the value of any key with multiple children,
7005 e.g. key 'c' in the example above."
7008 (mapcar #'js2-flatten-trie trie))
7010 (if (numberp (second trie))
7011 (cons (car trie) (second trie))
7012 ;; else pop list and append its kids
7013 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7015 (defun js2-build-imenu-index ()
7016 "Turn `js2-imenu-recorder' into an imenu data structure."
7017 (unless (eq js2-imenu-recorder 'empty)
7018 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7019 (result (js2-build-alist-trie chains nil)))
7020 (js2-flatten-trie result))))
7022 (defun js2-test-print-chains (chains)
7023 "Print a list of qname chains.
7024 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7025 i.e. one or more nodes, and an integer position as the list tail."
7026 (mapconcat (lambda (chain)
7028 (mapconcat (lambda (elem)
7029 (if (js2-node-p elem)
7030 (or (js2-node-qname-component elem)
7032 (number-to-string elem)))
7041 (defconst js2-version "1.8.0"
7042 "Version of JavaScript supported, plus minor js2 version.")
7044 (defmacro js2-record-face (face)
7045 "Record a style run of FACE for the current token."
7046 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7048 (defsubst js2-node-end (n)
7049 "Computes the absolute end of node N.
7050 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7051 is only true until the node is added to its parent; i.e., while parsing."
7055 (defsubst js2-record-comment ()
7056 "Record a comment in `js2-scanned-comments'."
7057 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7058 :format js2-ts-comment-type)
7059 js2-scanned-comments)
7060 (when js2-parse-ide-mode
7061 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7063 'font-lock-comment-face))
7064 (when (memq js2-ts-comment-type '(html preprocessor))
7065 ;; Tell cc-engine the bounds of the comment.
7066 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7068 ;; This function is called depressingly often, so it should be fast.
7069 ;; Most of the time it's looking at the same token it peeked before.
7070 (defsubst js2-peek-token ()
7071 "Returns the next token without consuming it.
7072 If previous token was consumed, calls scanner to get new token.
7073 If previous token was -not- consumed, returns it (idempotent).
7075 This function will not return a newline (js2-EOL) - instead, it
7076 gobbles newlines until it finds a non-newline token, and flags
7077 that token as appearing just after a newline.
7079 This function will also not return a js2-COMMENT. Instead, it
7080 records comments found in `js2-scanned-comments'. If the token
7081 returned by this function immediately follows a jsdoc comment,
7082 the token is flagged as such.
7084 Note that this function always returned the un-flagged token!
7085 The flags, if any, are saved in `js2-current-flagged-token'."
7086 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7087 js2-current-token ; most common case - return already-peeked token
7088 (let ((tt (js2-get-token)) ; call scanner
7091 ;; process comments and whitespace
7092 (while (or (= tt js2-EOL)
7097 (if js2-record-comments
7098 (js2-record-comment)))
7099 (setq tt (js2-get-token))) ; call scanner
7100 (setq js2-current-token tt
7101 js2-current-flagged-token (if saw-eol
7102 (logior tt js2-ti-after-eol)
7104 ;; perform lexical fontification as soon as token is scanned
7105 (when js2-parse-ide-mode
7108 (js2-record-face 'js2-error-face))
7109 ((setq face (aref js2-kwd-tokens tt))
7110 (js2-record-face face))
7111 ((and (= tt js2-NAME)
7112 (equal js2-ts-string "undefined"))
7113 (js2-record-face 'font-lock-constant-face))))
7114 tt))) ; return unflagged token
7116 (defsubst js2-peek-flagged-token ()
7117 "Returns the current token along with any flags set for it."
7119 js2-current-flagged-token)
7121 (defsubst js2-consume-token ()
7122 (setq js2-current-flagged-token js2-EOF))
7124 (defsubst js2-next-token ()
7127 (js2-consume-token)))
7129 (defsubst js2-next-flagged-token ()
7131 (prog1 js2-current-flagged-token
7132 (js2-consume-token)))
7134 (defsubst js2-match-token (match)
7135 "Consume and return t if next token matches MATCH, a bytecode.
7136 Returns nil and consumes nothing if MATCH is not the next token."
7137 (if (/= (js2-peek-token) match)
7142 (defsubst js2-valid-prop-name-token (tt)
7144 (and js2-allow-keywords-as-property-names
7146 (aref js2-kwd-tokens tt))))
7148 (defsubst js2-match-prop-name ()
7149 "Consume token and return t if next token is a valid property name.
7150 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7151 is non-nil and it's a keyword token."
7152 (if (js2-valid-prop-name-token (js2-peek-token))
7158 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7159 (if (js2-match-prop-name)
7161 (js2-report-error msg-id nil pos len)
7164 (defsubst js2-peek-token-or-eol ()
7165 "Return js2-EOL if the current token immediately follows a newline.
7166 Else returns the current token. Used in situations where we don't
7167 consider certain token types valid if they are preceded by a newline.
7168 One example is the postfix ++ or -- operator, which has to be on the
7169 same line as its operand."
7170 (let ((tt (js2-peek-token)))
7171 ;; Check for last peeked token flags
7172 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7176 (defsubst js2-set-check-for-label ()
7177 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7178 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7180 (defsubst js2-must-match (token msg-id &optional pos len)
7181 "Match next token to token code TOKEN, or record a syntax error.
7182 MSG-ID is the error message to report if the match fails.
7183 Returns t on match, nil if no match."
7184 (if (js2-match-token token)
7186 (js2-report-error msg-id nil pos len)
7189 (defsubst js2-inside-function ()
7190 (plusp js2-nesting-of-function))
7192 (defsubst js2-set-requires-activation ()
7193 (if (js2-function-node-p js2-current-script-or-fn)
7194 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7196 (defsubst js2-check-activation-name (name token)
7197 (when (js2-inside-function)
7198 ;; skip language-version 1.2 check from Rhino
7199 (if (or (string= "arguments" name)
7200 (and js2-compiler-activation-names ; only used in codegen
7201 (gethash name js2-compiler-activation-names)))
7202 (js2-set-requires-activation))))
7204 (defsubst js2-set-is-generator ()
7205 (if (js2-function-node-p js2-current-script-or-fn)
7206 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7208 (defsubst js2-must-have-xml ()
7209 (unless js2-compiler-xml-available
7210 (js2-report-error "msg.XML.not.available")))
7212 (defsubst js2-push-scope (scope)
7213 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7214 (assert (js2-scope-p scope))
7215 (assert (null (js2-scope-parent-scope scope)))
7216 (assert (not (eq js2-current-scope scope)))
7217 (setf (js2-scope-parent-scope scope) js2-current-scope
7218 js2-current-scope scope))
7220 (defsubst js2-pop-scope ()
7221 (setq js2-current-scope
7222 (js2-scope-parent-scope js2-current-scope)))
7224 (defsubst js2-enter-loop (loop-node)
7225 (push loop-node js2-loop-set)
7226 (push loop-node js2-loop-and-switch-set)
7227 (js2-push-scope loop-node)
7228 ;; Tell the current labeled statement (if any) its statement,
7229 ;; and set the jump target of the first label to the loop.
7230 ;; These are used in `js2-parse-continue' to verify that the
7231 ;; continue target is an actual labeled loop. (And for codegen.)
7232 (when js2-labeled-stmt
7233 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7234 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7235 js2-labeled-stmt))) loop-node)))
7237 (defsubst js2-exit-loop ()
7239 (pop js2-loop-and-switch-set)
7242 (defsubst js2-enter-switch (switch-node)
7243 (push switch-node js2-loop-and-switch-set))
7245 (defsubst js2-exit-switch ()
7246 (pop js2-loop-and-switch-set))
7248 (defun js2-parse (&optional buf cb)
7249 "Tells the js2 parser to parse a region of JavaScript.
7251 BUF is a buffer or buffer name containing the code to parse.
7252 Call `narrow-to-region' first to parse only part of the buffer.
7254 The returned AST root node is given some additional properties:
7255 `node-count' - total number of nodes in the AST
7256 `buffer' - BUF. The buffer it refers to may change or be killed,
7257 so the value is not necessarily reliable.
7259 An optional callback CB can be specified to report parsing
7260 progress. If `(functionp CB)' returns t, it will be called with
7261 the current line number once before parsing begins, then again
7262 each time the lexer reaches a new line number.
7264 CB can also be a list of the form `(symbol cb ...)' to specify
7265 multiple callbacks with different criteria. Each symbol is a
7266 criterion keyword, and the following element is the callback to
7269 :line - called whenever the line number changes
7270 :token - called for each new token consumed
7272 The list of criteria could be extended to include entering or
7273 leaving a statement, an expression, or a function definition."
7274 (if (and cb (not (functionp cb)))
7275 (error "criteria callbacks not yet implemented"))
7276 (let ((inhibit-point-motion-hooks t)
7277 (js2-compiler-xml-available (>= js2-language-version 160))
7278 ;; This is a recursive-descent parser, so give it a big stack.
7279 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7280 (max-specpdl-size (max max-specpdl-size 3000))
7281 (case-fold-search nil)
7283 (or buf (setq buf (current-buffer)))
7284 (message nil) ; clear any error message from previous parse
7287 (setq js2-scanned-comments nil
7288 js2-parsed-errors nil
7289 js2-parsed-warnings nil
7290 js2-imenu-recorder nil
7291 js2-imenu-function-map nil
7294 (setq ast (js2-with-unmodifying-text-property-changes
7296 (unless js2-ts-hit-eof
7297 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7298 (setf (js2-ast-root-errors ast) js2-parsed-errors
7299 (js2-ast-root-warnings ast) js2-parsed-warnings)
7300 ;; if we didn't find any declarations, put a dummy in this list so we
7301 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7302 (unless js2-imenu-recorder
7303 (setq js2-imenu-recorder 'empty))
7304 (run-hooks 'js2-parse-finished-hook)
7307 ;; Corresponds to Rhino's Parser.parse() method.
7308 (defun js2-do-parse ()
7309 "Parse current buffer starting from current point.
7310 Scanner should be initialized."
7311 (let ((pos js2-ts-cursor)
7312 (end js2-ts-cursor) ; in case file is empty
7314 ;; initialize buffer-local parsing vars
7315 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7316 js2-current-script-or-fn root
7317 js2-current-scope root
7318 js2-current-flagged-token js2-EOF
7319 js2-nesting-of-function 0
7320 js2-labeled-stmt nil
7321 js2-recorded-assignments nil) ; for js2-highlight
7322 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7323 (if (= tt js2-FUNCTION)
7326 (setq n (js2-parse-function (if js2-called-by-compile-function
7327 'FUNCTION_EXPRESSION
7328 'FUNCTION_STATEMENT)))
7329 (js2-record-imenu-functions n))
7330 ;; not a function - parse a statement
7331 (setq n (js2-parse-statement)))
7332 ;; add function or statement to script
7333 (setq end (js2-node-end n))
7334 (js2-block-node-push root n))
7335 ;; add comments to root in lexical order
7336 (when js2-scanned-comments
7337 ;; if we find a comment beyond end of normal kids, use its end
7338 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7339 (dolist (comment js2-scanned-comments)
7340 (push comment (js2-ast-root-comments root))
7341 (js2-node-add-children root comment)))
7342 (setf (js2-node-len root) (- end pos))
7343 ;; Give extensions a chance to muck with things before highlighting starts.
7344 (dolist (callback js2-post-parse-callbacks)
7346 (js2-highlight-undeclared-vars)
7349 (defun js2-function-parser ()
7351 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7353 (defun js2-parse-function-closure-body (fn-node)
7354 "Parse a JavaScript 1.8 function closure body."
7355 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7357 (js2-report-error "msg.no.brace.body" nil
7358 (js2-node-pos fn-node)
7359 (- js2-ts-cursor (js2-node-pos fn-node)))
7360 (js2-node-add-children fn-node
7361 (setf (js2-function-node-body fn-node)
7362 (js2-parse-expr t))))))
7364 (defun js2-parse-function-body (fn-node)
7365 (js2-must-match js2-LC "msg.no.brace.body"
7366 (js2-node-pos fn-node)
7367 (- js2-ts-cursor (js2-node-pos fn-node)))
7368 (let ((pos js2-token-beg) ; LC position
7369 (pn (make-js2-block-node)) ; starts at LC position
7372 (incf js2-nesting-of-function)
7374 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7377 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7378 (js2-parse-statement)
7380 (js2-parse-function 'FUNCTION_STATEMENT))))
7381 (decf js2-nesting-of-function))
7382 (setq end js2-token-end) ; assume no curly and leave at current token
7383 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7384 (setq end js2-token-end))
7385 (setf (js2-node-pos pn) pos
7386 (js2-node-len pn) (- end pos))
7387 (setf (js2-function-node-body fn-node) pn)
7388 (js2-node-add-children fn-node pn)
7391 (defun js2-parse-function-params (fn-node pos)
7392 (if (js2-match-token js2-RP)
7393 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7394 (let (params len param)
7395 (loop for tt = (js2-peek-token)
7398 ;; destructuring param
7399 ((or (= tt js2-LB) (= tt js2-LC))
7400 (push (js2-parse-primary-expr-lhs) params))
7403 (js2-must-match js2-NAME "msg.no.parm")
7404 (js2-record-face 'js2-function-param-face)
7405 (setq param (js2-create-name-node))
7406 (js2-define-symbol js2-LP js2-ts-string param)
7407 (push param params)))
7409 (js2-match-token js2-COMMA))
7410 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7411 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7413 (js2-node-add-children fn-node p)
7414 (push p (js2-function-node-params fn-node))))))
7416 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7417 "Possibly show inconsistent-return warning.
7418 Last token scanned is the close-curly for the function body."
7419 (when (and js2-mode-show-strict-warnings
7420 js2-strict-inconsistent-return-warning
7421 (not (js2-has-consistent-return-usage
7422 (js2-function-node-body fn-node))))
7423 ;; Have it extend from close-curly to bol or beginning of block.
7424 (let ((pos (save-excursion
7425 (goto-char js2-token-end)
7426 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7428 (end js2-token-end))
7429 (if (plusp (js2-name-node-length name))
7430 (js2-add-strict-warning "msg.no.return.value"
7431 (js2-name-node-name name) pos end)
7432 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7434 (defun js2-parse-function (function-type)
7435 "Function parser. FUNCTION-TYPE is a symbol."
7436 (let ((pos js2-token-beg) ; start of 'function' keyword
7442 (synthetic-type function-type)
7444 ;; parse function name, expression, or non-name (anonymous)
7446 ;; function foo(...)
7447 ((js2-match-token js2-NAME)
7448 (setq name (js2-create-name-node t)
7449 name-beg js2-token-beg
7450 name-end js2-token-end)
7451 (unless (js2-match-token js2-LP)
7452 (when js2-allow-member-expr-as-function-name
7453 ;; function foo.bar(...)
7454 (setq member-expr-node name
7456 member-expr-node (js2-parse-member-expr-tail
7457 nil member-expr-node)))
7458 (js2-must-match js2-LP "msg.no.paren.parms")))
7459 ((js2-match-token js2-LP)
7460 nil) ; anonymous function: leave name as null
7462 ;; function random-member-expr(...)
7463 (when js2-allow-member-expr-as-function-name
7464 ;; Note that memberExpr can not start with '(' like
7465 ;; in function (1+2).toString(), because 'function (' already
7466 ;; processed as anonymous function
7467 (setq member-expr-node (js2-parse-member-expr)))
7468 (js2-must-match js2-LP "msg.no.paren.parms")))
7469 (if (= js2-current-token js2-LP) ; eventually matched LP?
7470 (setq lp js2-token-beg))
7471 (if member-expr-node
7473 (setq synthetic-type 'FUNCTION_EXPRESSION)
7474 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7476 (js2-set-face name-beg name-end
7477 'font-lock-function-name-face 'record)))
7478 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7479 (plusp (js2-name-node-length name)))
7480 ;; Function statements define a symbol in the enclosing scope
7481 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7482 (setf fn-node (make-js2-function-node :pos pos
7485 :lp (if lp (- lp pos))))
7486 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7487 ;; 1. Nested functions are not affected by the dynamic scope flag
7488 ;; as dynamic scope is already a parent of their scope.
7489 ;; 2. Functions defined under the with statement also immune to
7490 ;; this setup, in which case dynamic scope is ignored in favor
7491 ;; of the with object.
7492 (setf (js2-function-node-ignore-dynamic fn-node) t))
7493 ;; dynamically bind all the per-function variables
7494 (let ((js2-current-script-or-fn fn-node)
7495 (js2-current-scope fn-node)
7496 (js2-nesting-of-with 0)
7500 js2-loop-and-switch-set)
7501 (js2-parse-function-params fn-node pos)
7502 (if (and (>= js2-language-version 180)
7503 (/= (js2-peek-token) js2-LC))
7504 (js2-parse-function-closure-body fn-node)
7505 (js2-parse-function-body fn-node))
7507 (js2-node-add-children fn-node name))
7508 (js2-check-inconsistent-return-warning fn-node name)
7509 ;; Function expressions define a name only in the body of the
7510 ;; function, and only if not hidden by a parameter name
7512 (eq synthetic-type 'FUNCTION_EXPRESSION)
7513 (null (js2-scope-get-symbol js2-current-scope
7514 (js2-name-node-name name))))
7515 (js2-define-symbol js2-FUNCTION
7516 (js2-name-node-name name)
7519 (eq function-type 'FUNCTION_EXPRESSION_STATEMENT))
7520 (js2-record-imenu-functions fn-node)))
7521 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7522 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7523 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7524 ;; We wait until after parsing the function to set its parent scope,
7525 ;; since `js2-define-symbol' needs the defining-scope check to stop
7526 ;; at the function boundary when checking for redeclarations.
7527 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7530 (defun js2-parse-statements (&optional parent)
7531 "Parse a statement list. Last token consumed must be js2-LC.
7533 PARENT can be a `js2-block-node', in which case the statements are
7534 appended to PARENT. Otherwise a new `js2-block-node' is created
7537 This function does not match the closing js2-RC: the caller
7538 matches the RC so it can provide a suitable error message if not
7539 matched. This means it's up to the caller to set the length of
7540 the node to include the closing RC. The node start pos is set to
7541 the absolute buffer start position, and the caller should fix it
7542 up to be relative to the parent node. All children of this block
7543 node are given relative start positions and correct lengths."
7544 (let ((pn (or parent (make-js2-block-node)))
7546 (setf (js2-node-pos pn) js2-token-beg)
7547 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7549 (js2-block-node-push pn (js2-parse-statement)))
7552 (defun js2-parse-statement ()
7553 (let (tt pn beg end)
7554 ;; coarse-grained user-interrupt check - needs work
7555 (and js2-parse-interruptable-p
7556 (zerop (% (incf js2-parse-stmt-count)
7557 js2-statements-per-pause))
7559 (throw 'interrupted t))
7560 (setq pn (js2-statement-helper))
7561 ;; no-side-effects warning check
7562 (unless (js2-node-has-side-effects pn)
7563 (setq end (js2-node-end pn))
7566 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7567 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7570 ;; These correspond to the switch cases in Parser.statementHelper
7571 (defconst js2-parsers
7572 (let ((parsers (make-vector js2-num-tokens
7573 #'js2-parse-expr-stmt)))
7574 (aset parsers js2-BREAK #'js2-parse-break)
7575 (aset parsers js2-CONST #'js2-parse-const-var)
7576 (aset parsers js2-CONTINUE #'js2-parse-continue)
7577 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7578 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7579 (aset parsers js2-DO #'js2-parse-do)
7580 (aset parsers js2-FOR #'js2-parse-for)
7581 (aset parsers js2-FUNCTION #'js2-function-parser)
7582 (aset parsers js2-IF #'js2-parse-if)
7583 (aset parsers js2-LC #'js2-parse-block)
7584 (aset parsers js2-LET #'js2-parse-let-stmt)
7585 (aset parsers js2-NAME #'js2-parse-name-or-label)
7586 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7587 (aset parsers js2-SEMI #'js2-parse-semi)
7588 (aset parsers js2-SWITCH #'js2-parse-switch)
7589 (aset parsers js2-THROW #'js2-parse-throw)
7590 (aset parsers js2-TRY #'js2-parse-try)
7591 (aset parsers js2-VAR #'js2-parse-const-var)
7592 (aset parsers js2-WHILE #'js2-parse-while)
7593 (aset parsers js2-WITH #'js2-parse-with)
7594 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7596 "A vector mapping token types to parser functions.")
7598 (defsubst js2-parse-warn-missing-semi (beg end)
7599 (and js2-mode-show-strict-warnings
7600 js2-strict-missing-semi-warning
7601 (js2-add-strict-warning
7602 "msg.missing.semi" nil
7603 ;; back up to beginning of statement or line
7604 (max beg (save-excursion
7609 (defconst js2-no-semi-insertion
7621 "List of tokens that don't do automatic semicolon insertion.")
7623 (defconst js2-autoinsert-semi-and-warn
7624 (list js2-ERROR js2-EOF js2-RC))
7626 (defun js2-statement-helper ()
7627 (let* ((tt (js2-peek-token))
7630 (parser (if (= tt js2-ERROR)
7632 (aref js2-parsers tt)))
7635 ;; If the statement is set, then it's been told its label by now.
7636 (and js2-labeled-stmt
7637 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7638 (setq js2-labeled-stmt nil))
7639 (setq pn (funcall parser))
7640 ;; Don't do auto semi insertion for certain statement types.
7641 (unless (or (memq first-tt js2-no-semi-insertion)
7642 (js2-labeled-stmt-node-p pn))
7643 (js2-auto-insert-semicolon pn))
7646 (defun js2-auto-insert-semicolon (pn)
7647 (let* ((tt-flagged (js2-peek-flagged-token))
7648 (tt (logand tt-flagged js2-clear-ti-mask))
7649 (pos (js2-node-pos pn)))
7652 ;; Consume ';' as a part of expression
7654 ;; extend the node bounds to include the semicolon.
7655 (setf (js2-node-len pn) (- js2-token-end pos)))
7656 ((memq tt js2-autoinsert-semi-and-warn)
7658 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7660 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7661 ;; Report error if no EOL or autoinsert ';' otherwise
7662 (js2-report-error "msg.no.semi.stmt")
7663 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7665 (defun js2-parse-condition ()
7666 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7667 The parens are discarded and the expression node is returned.
7668 The `pos' field of the return value is set to an absolute position
7669 that must be fixed up by the caller.
7670 Return value is a list (EXPR LP RP), with absolute paren positions."
7672 (if (js2-must-match js2-LP "msg.no.paren.cond")
7673 (setq lp js2-token-beg))
7674 (setq pn (js2-parse-expr))
7675 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7676 (setq rp js2-token-beg))
7677 ;; Report strict warning on code like "if (a = 7) ..."
7678 (if (and js2-strict-cond-assign-warning
7679 (js2-assign-node-p pn))
7680 (js2-add-strict-warning "msg.equal.as.assign" nil
7682 (+ (js2-node-pos pn)
7683 (js2-node-len pn))))
7686 (defun js2-parse-if ()
7687 "Parser for if-statement. Last matched token must be js2-IF."
7688 (let ((pos js2-token-beg)
7696 (setq cond (js2-parse-condition)
7697 if-true (js2-parse-statement)
7698 if-false (if (js2-match-token js2-ELSE)
7700 (setq else-pos (- js2-token-beg pos))
7701 (js2-parse-statement)))
7702 end (js2-node-end (or if-false if-true))
7703 pn (make-js2-if-node :pos pos
7705 :condition (car cond)
7709 :lp (js2-relpos (second cond) pos)
7710 :rp (js2-relpos (third cond) pos)))
7711 (js2-node-add-children pn (car cond) if-true if-false)
7714 (defun js2-parse-switch ()
7715 "Parser for if-statement. Last matched token must be js2-SWITCH."
7716 (let ((pos js2-token-beg)
7729 (if (js2-must-match js2-LP "msg.no.paren.switch")
7730 (setq lp js2-token-beg))
7731 (setq discriminant (js2-parse-expr)
7732 pn (make-js2-switch-node :discriminant discriminant
7734 :lp (js2-relpos lp pos)))
7735 (js2-node-add-children pn discriminant)
7736 (js2-enter-switch pn)
7739 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7740 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7741 (js2-must-match js2-LC "msg.no.brace.switch")
7744 (setq tt (js2-next-token)
7745 case-pos js2-token-beg)
7748 (setf (js2-node-len pn) (- js2-token-end pos))
7749 (throw 'break nil)) ; done
7751 (setq case-expr (js2-parse-expr))
7752 (js2-must-match js2-COLON "msg.no.colon.case"))
7755 (js2-report-error "msg.double.switch.default"))
7758 (js2-must-match js2-COLON "msg.no.colon.case"))
7760 (js2-report-error "msg.bad.switch")
7761 (throw 'break nil)))
7762 (setq case-node (make-js2-case-node :pos case-pos
7763 :len (- js2-token-end case-pos)
7765 (js2-node-add-children case-node case-expr)
7766 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7770 (setf stmt (js2-parse-statement)
7771 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7772 (js2-block-node-push case-node stmt))
7773 (push case-node cases)))
7774 ;; add cases last, as pushing reverses the order to be correct
7776 (js2-node-add-children pn kid)
7777 (push kid (js2-switch-node-cases pn)))
7779 (js2-exit-switch))))
7781 (defun js2-parse-while ()
7782 "Parser for while-statement. Last matched token must be js2-WHILE."
7783 (let ((pos js2-token-beg)
7784 (pn (make-js2-while-node))
7791 (setf cond (js2-parse-condition)
7792 (js2-while-node-condition pn) (car cond)
7793 body (js2-parse-statement)
7794 (js2-while-node-body pn) body
7795 (js2-node-len pn) (- (js2-node-end body) pos)
7796 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7797 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7798 (js2-node-add-children pn body (car cond)))
7802 (defun js2-parse-do ()
7803 "Parser for do-statement. Last matched token must be js2-DO."
7804 (let ((pos js2-token-beg)
7805 (pn (make-js2-do-node))
7813 (setq body (js2-parse-statement))
7814 (js2-must-match js2-WHILE "msg.no.while.do")
7815 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7816 cond (js2-parse-condition)
7817 (js2-do-node-condition pn) (car cond)
7818 (js2-do-node-body pn) body
7820 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7821 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7822 (js2-node-add-children pn (car cond) body))
7824 ;; Always auto-insert semicolon to follow SpiderMonkey:
7825 ;; It is required by ECMAScript but is ignored by the rest of
7826 ;; world; see bug 238945
7827 (if (js2-match-token js2-SEMI)
7828 (setq end js2-ts-cursor))
7829 (setf (js2-node-len pn) (- end pos))
7832 (defun js2-parse-for ()
7833 "Parser for for-statement. Last matched token must be js2-FOR.
7834 Parses for, for-in, and for each-in statements."
7835 (let ((for-pos js2-token-beg)
7842 init ; Node init is also foo in 'foo in object'
7843 cond ; Node cond is also object in 'foo in object'
7844 incr ; 3rd section of for-loop initializer
7850 ;; See if this is a for each () instead of just a for ()
7851 (when (js2-match-token js2-NAME)
7852 (if (string= "each" js2-ts-string)
7855 each-pos (- js2-token-beg for-pos)) ; relative
7856 (js2-record-face 'font-lock-keyword-face))
7857 (js2-report-error "msg.no.paren.for")))
7858 (if (js2-must-match js2-LP "msg.no.paren.for")
7859 (setq lp (- js2-token-beg for-pos)))
7860 (setq tt (js2-peek-token))
7861 ;; parse init clause
7862 (let ((js2-in-for-init t)) ; set as dynamic variable
7865 (setq init (make-js2-empty-expr-node)))
7866 ((or (= tt js2-VAR) (= tt js2-LET))
7868 (setq init (js2-parse-variables tt js2-token-beg)))
7870 (setq init (js2-parse-expr)))))
7871 (if (js2-match-token js2-IN)
7873 in-pos (- js2-token-beg for-pos)
7874 cond (js2-parse-expr)) ; object over which we're iterating
7875 ;; else ordinary for loop - parse cond and incr
7876 (js2-must-match js2-SEMI "msg.no.semi.for")
7877 (setq cond (if (= (js2-peek-token) js2-SEMI)
7878 (make-js2-empty-expr-node) ; no loop condition
7880 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7881 (setq tmp-pos js2-token-end
7882 incr (if (= (js2-peek-token) js2-RP)
7883 (make-js2-empty-expr-node :pos tmp-pos)
7885 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7886 (setq rp (- js2-token-beg for-pos)))
7888 (setq pn (make-js2-for-node :init init
7893 ;; cond could be null if 'in obj' got eaten by the init node.
7894 (if (js2-infix-node-p init)
7895 ;; it was (foo in bar) instead of (var foo in bar)
7896 (setq cond (js2-infix-node-right init)
7897 init (js2-infix-node-left init))
7898 (if (and (js2-var-decl-node-p init)
7899 (> (length (js2-var-decl-node-kids init)) 1))
7900 (js2-report-error "msg.mult.index")))
7901 (setq pn (make-js2-for-in-node :iterator init
7904 :foreach-p is-for-each
7911 ;; We have to parse the body -after- creating the loop node,
7912 ;; so that the loop node appears in the js2-loop-set, allowing
7913 ;; break/continue statements to find the enclosing loop.
7914 (setf body (js2-parse-statement)
7915 (js2-loop-node-body pn) body
7916 (js2-node-pos pn) for-pos
7917 (js2-node-len pn) (- (js2-node-end body) for-pos))
7918 (js2-node-add-children pn init cond incr body))
7923 (defun js2-parse-try ()
7924 "Parser for try-statement. Last matched token must be js2-TRY."
7925 (let ((try-pos js2-token-beg)
7943 (if (/= (js2-peek-token) js2-LC)
7944 (js2-report-error "msg.no.brace.try"))
7945 (setq try-block (js2-parse-statement)
7946 try-end (js2-node-end try-block)
7947 peek (js2-peek-token))
7950 (while (js2-match-token js2-CATCH)
7951 (setq catch-pos js2-token-beg
7956 (if saw-default-catch
7957 (js2-report-error "msg.catch.unreachable"))
7958 (if (js2-must-match js2-LP "msg.no.paren.catch")
7959 (setq lp (- js2-token-beg catch-pos)))
7960 (js2-must-match js2-NAME "msg.bad.catchcond")
7961 (setq var-name (js2-create-name-node))
7962 (if (js2-match-token js2-IF)
7963 (setq guard-kwd (- js2-token-beg catch-pos)
7964 catch-cond (js2-parse-expr))
7965 (setq saw-default-catch t))
7966 (if (js2-must-match js2-RP "msg.bad.catchcond")
7967 (setq rp (- js2-token-beg catch-pos)))
7968 (js2-must-match js2-LC "msg.no.brace.catchblock")
7969 (setq block (js2-parse-statements)
7970 try-end (js2-node-end block)
7971 catch-node (make-js2-catch-node :pos catch-pos
7973 :guard-expr catch-cond
7974 :guard-kwd guard-kwd
7978 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7979 (setq try-end js2-token-beg))
7980 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7981 (js2-node-len catch-node) (- try-end catch-pos))
7982 (js2-node-add-children catch-node var-name catch-cond block)
7983 (push catch-node catch-blocks)))
7984 ((/= peek js2-FINALLY)
7985 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7986 (js2-node-pos try-block)
7987 (- (setq try-end (js2-node-end try-block))
7988 (js2-node-pos try-block)))))
7989 (when (js2-match-token js2-FINALLY)
7990 (setq finally-pos js2-token-beg
7991 block (js2-parse-statement)
7992 try-end (js2-node-end block)
7993 finally-block (make-js2-finally-node :pos finally-pos
7994 :len (- try-end finally-pos)
7996 (js2-node-add-children finally-block block))
7997 (setq pn (make-js2-try-node :pos try-pos
7998 :len (- try-end try-pos)
7999 :try-block try-block
8000 :finally-block finally-block))
8001 (js2-node-add-children pn try-block finally-block)
8002 ;; push them onto the try-node, which reverses and corrects their order
8003 (dolist (cb catch-blocks)
8004 (js2-node-add-children pn cb)
8005 (push cb (js2-try-node-catch-clauses pn)))
8008 (defun js2-parse-throw ()
8009 "Parser for throw-statement. Last matched token must be js2-THROW."
8010 (let ((pos js2-token-beg)
8014 (if (= (js2-peek-token-or-eol) js2-EOL)
8015 ;; ECMAScript does not allow new lines before throw expression,
8017 (js2-report-error "msg.bad.throw.eol"))
8018 (setq expr (js2-parse-expr)
8019 pn (make-js2-throw-node :pos pos
8020 :len (- (js2-node-end expr) pos)
8022 (js2-node-add-children pn expr)
8025 (defsubst js2-match-jump-label-name (label-name)
8026 "If break/continue specified a label, return that label's labeled stmt.
8027 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8028 does not match an existing label, reports an error and returns nil."
8029 (let ((bundle (cdr (assoc label-name js2-label-set))))
8031 (js2-report-error "msg.undef.label"))
8034 (defun js2-parse-break ()
8035 "Parser for break-statement. Last matched token must be js2-BREAK."
8036 (let ((pos js2-token-beg)
8038 break-target ; statement to break from
8039 break-label ; in "break foo", name-node representing the foo
8040 labels ; matching labeled statement to break to
8042 (js2-consume-token) ; `break'
8043 (when (eq (js2-peek-token-or-eol) js2-NAME)
8045 (setq break-label (js2-create-name-node)
8046 end (js2-node-end break-label)
8047 ;; matchJumpLabelName only matches if there is one
8048 labels (js2-match-jump-label-name js2-ts-string)
8049 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8050 (unless (or break-target break-label)
8051 ;; no break target specified - try for innermost enclosing loop/switch
8052 (if (null js2-loop-and-switch-set)
8054 (js2-report-error "msg.bad.break" nil pos (length "break")))
8055 (setq break-target (car js2-loop-and-switch-set))))
8056 (setq pn (make-js2-break-node :pos pos
8059 :target break-target))
8060 (js2-node-add-children pn break-label) ; but not break-target
8063 (defun js2-parse-continue ()
8064 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8065 (let ((pos js2-token-beg)
8067 label ; optional user-specified label, a `js2-name-node'
8068 labels ; current matching labeled stmt, if any
8069 target ; the `js2-loop-node' target of this continue stmt
8071 (js2-consume-token) ; `continue'
8072 (when (= (js2-peek-token-or-eol) js2-NAME)
8074 (setq label (js2-create-name-node)
8075 end (js2-node-end label)
8076 ;; matchJumpLabelName only matches if there is one
8077 labels (js2-match-jump-label-name js2-ts-string)))
8079 ((null labels) ; no current label to go to
8080 (if (null js2-loop-set) ; no loop to continue to
8081 (js2-report-error "msg.continue.outside" nil pos
8082 (length "continue"))
8083 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8085 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8086 (setq target (js2-labeled-stmt-node-stmt labels))
8087 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8088 (setq pn (make-js2-continue-node :pos pos
8092 (js2-node-add-children pn label) ; but not target - it's not our child
8095 (defun js2-parse-with ()
8096 "Parser for with-statement. Last matched token must be js2-WITH."
8098 (let ((pos js2-token-beg)
8100 (if (js2-must-match js2-LP "msg.no.paren.with")
8101 (setq lp js2-token-beg))
8102 (setq obj (js2-parse-expr))
8103 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8104 (setq rp js2-token-beg))
8105 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8106 (setq body (js2-parse-statement)))
8107 (setq pn (make-js2-with-node :pos pos
8108 :len (- (js2-node-end body) pos)
8111 :lp (js2-relpos lp pos)
8112 :rp (js2-relpos rp pos)))
8113 (js2-node-add-children pn obj body)
8116 (defun js2-parse-const-var ()
8117 "Parser for var- or const-statement.
8118 Last matched token must be js2-CONST or js2-VAR."
8119 (let ((tt (js2-peek-token))
8124 (setq expr (js2-parse-variables tt js2-token-beg)
8125 pn (make-js2-expr-stmt-node :pos pos
8126 :len (- (js2-node-end expr) pos)
8128 (js2-node-add-children pn expr)
8131 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8132 (let ((pn (make-js2-expr-stmt-node :pos pos
8133 :len (js2-node-len expr)
8134 :type (if (js2-inside-function)
8139 (js2-node-add-children pn expr))
8142 (defun js2-parse-let-stmt ()
8143 "Parser for let-statement. Last matched token must be js2-LET."
8145 (let ((pos js2-token-beg)
8148 (if (= (js2-peek-token) js2-LP)
8149 ;; let expression in statement context
8150 (setq expr (js2-parse-let pos 'statement)
8151 pn (js2-wrap-with-expr-stmt pos expr t))
8152 ;; else we're looking at a statement like let x=6, y=7;
8153 (setf expr (js2-parse-variables js2-LET pos)
8154 pn (js2-wrap-with-expr-stmt pos expr t)
8155 (js2-node-type pn) js2-EXPR_RESULT))
8158 (defun js2-parse-ret-yield ()
8159 (js2-parse-return-or-yield (js2-peek-token) nil))
8161 (defconst js2-parse-return-stmt-enders
8162 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8164 (defsubst js2-now-all-set (before after mask)
8165 "Return whether or not the bits in the mask have changed to all set.
8166 BEFORE is bits before change, AFTER is bits after change, and MASK is
8167 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8169 (and (/= (logand before mask) mask)
8170 (= (logand after mask) mask)))
8172 (defun js2-parse-return-or-yield (tt expr-context)
8173 (let ((pos js2-token-beg)
8175 (before js2-end-flags)
8176 (inside-function (js2-inside-function))
8180 (unless inside-function
8181 (js2-report-error (if (eq tt js2-RETURN)
8185 ;; This is ugly, but we don't want to require a semicolon.
8186 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8187 (setq e (js2-parse-expr)
8188 end (js2-node-end e)))
8191 (js2-set-flag js2-end-flags (if (null e)
8193 js2-end-returns-value))
8194 (setq ret (make-js2-return-node :pos pos
8197 (js2-node-add-children ret e)
8198 ;; See if we need a strict mode warning.
8199 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8200 ;; more thorough and accurate than this before/after flag check.
8201 ;; E.g. if there's a finally-block that always returns, we shouldn't
8202 ;; show a warning generated by inconsistent returns in the catch blocks.
8203 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8204 ;; so we know which returns/yields to highlight, and we should get rid of
8205 ;; all the checking in `js2-parse-return-or-yield'.
8206 (if (and js2-strict-inconsistent-return-warning
8207 (js2-now-all-set before js2-end-flags
8208 (logior js2-end-returns js2-end-returns-value)))
8209 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8211 (unless (js2-inside-function)
8212 (js2-report-error "msg.bad.yield"))
8213 (js2-set-flag js2-end-flags js2-end-yields)
8214 (setq ret (make-js2-yield-node :pos pos
8217 (js2-node-add-children ret e)
8218 (unless expr-context
8220 ret (js2-wrap-with-expr-stmt pos e t))
8221 (js2-set-requires-activation)
8222 (js2-set-is-generator))))
8223 ;; see if we are mixing yields and value returns.
8224 (when (and inside-function
8225 (js2-now-all-set before js2-end-flags
8226 (logior js2-end-yields js2-end-returns-value)))
8227 (setq name (js2-function-name js2-current-script-or-fn))
8228 (if (zerop (length name))
8229 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8230 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8233 (defun js2-parse-debugger ()
8235 (make-js2-keyword-node :type js2-DEBUGGER))
8237 (defun js2-parse-block ()
8238 "Parser for a curly-delimited statement block.
8239 Last token matched must be js2-LC."
8240 (let ((pos js2-token-beg)
8241 (pn (make-js2-scope)))
8246 (js2-parse-statements pn)
8247 (js2-must-match js2-RC "msg.no.brace.block")
8248 (setf (js2-node-len pn) (- js2-token-end pos)))
8252 ;; for js2-ERROR too, to have a node for error recovery to work on
8253 (defun js2-parse-semi ()
8254 "Parse a statement or handle an error.
8255 Last matched token is js-SEMI or js-ERROR."
8256 (let ((tt (js2-peek-token)) pos len)
8258 (if (eq tt js2-SEMI)
8259 (make-js2-empty-expr-node :len 1)
8260 (setq pos js2-token-beg
8261 len (- js2-token-beg pos))
8262 (js2-report-error "msg.syntax" nil pos len)
8263 (make-js2-error-node :pos pos :len len))))
8265 (defun js2-parse-default-xml-namespace ()
8266 "Parse a `default xml namespace = <expr>' e4x statement."
8267 (let ((pos js2-token-beg)
8268 end len expr unary es)
8271 (js2-set-requires-activation)
8272 (setq len (- js2-ts-cursor pos))
8273 (unless (and (js2-match-token js2-NAME)
8274 (string= js2-ts-string "xml"))
8275 (js2-report-error "msg.bad.namespace" nil pos len))
8276 (unless (and (js2-match-token js2-NAME)
8277 (string= js2-ts-string "namespace"))
8278 (js2-report-error "msg.bad.namespace" nil pos len))
8279 (unless (js2-match-token js2-ASSIGN)
8280 (js2-report-error "msg.bad.namespace" nil pos len))
8281 (setq expr (js2-parse-expr)
8282 end (js2-node-end expr)
8283 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8287 (js2-node-add-children unary expr)
8288 (make-js2-expr-stmt-node :pos pos
8292 (defun js2-record-label (label bundle)
8293 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8295 (let ((name (js2-label-node-name label))
8298 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8299 ;; flag both labels if possible when used in editing mode
8300 (if (and js2-parse-ide-mode
8301 (setq dup (js2-get-label-by-name labeled-stmt name)))
8302 (js2-report-error "msg.dup.label" nil
8303 (js2-node-abs-pos dup) (js2-node-len dup)))
8304 (js2-report-error "msg.dup.label" nil
8305 (js2-node-pos label) (js2-node-len label)))
8306 (js2-labeled-stmt-node-add-label bundle label)
8307 (js2-node-add-children bundle label)
8308 ;; Add one reference to the bundle per label in `js2-label-set'
8309 (push (cons name bundle) js2-label-set)))
8311 (defun js2-parse-name-or-label ()
8312 "Parser for identifier or label. Last token matched must be js2-NAME.
8313 Called when we found a name in a statement context. If it's a label, we gather
8314 up any following labels and the next non-label statement into a
8315 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8316 expression and return it wrapped in a `js2-expr-stmt-node'."
8317 (let ((pos js2-token-beg)
8324 ;; set check for label and call down to `js2-parse-primary-expr'
8325 (js2-set-check-for-label)
8326 (setq expr (js2-parse-expr))
8327 (if (/= (js2-node-type expr) js2-LABEL)
8328 ;; Parsed non-label expression - wrap with expression stmt.
8329 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8330 ;; else parsed a label
8331 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8332 (js2-record-label expr bundle)
8333 ;; look for more labels
8334 (while (and continue (= (js2-peek-token) js2-NAME))
8335 (js2-set-check-for-label)
8336 (setq expr (js2-parse-expr))
8337 (if (/= (js2-node-type expr) js2-LABEL)
8339 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8341 (js2-auto-insert-semicolon stmt))
8342 (js2-record-label expr bundle)))
8343 ;; no more labels; now parse the labeled statement
8346 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8347 (setq stmt (js2-statement-helper))))
8348 ;; remove the labels for this statement from the global set
8349 (dolist (label (js2-labeled-stmt-node-labels bundle))
8350 (setq js2-label-set (remove label js2-label-set))))
8351 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8352 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8353 (js2-node-add-children bundle stmt)
8356 (defun js2-parse-expr-stmt ()
8357 "Default parser in statement context, if no recognized statement found."
8358 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8360 (defun js2-parse-variables (decl-type pos)
8361 "Parse a comma-separated list of variable declarations.
8362 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8364 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8365 For 'var' or 'const', the keyword should be the token last scanned.
8367 POS is the position where the node should start. It's sometimes the
8368 var/const/let keyword, and other times the beginning of the first token
8369 in the first variable declaration.
8371 Returns the parsed `js2-var-decl-node' expression node."
8372 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8384 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8385 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8386 ;; var {a, b} = baz;
8388 (setq destructuring nil
8391 kid-pos js2-token-beg
8394 (if (or (= tt js2-LB) (= tt js2-LC))
8395 ;; Destructuring assignment, e.g., var [a, b] = ...
8396 (setq destructuring (js2-parse-primary-expr-lhs)
8397 end (js2-node-end destructuring))
8398 ;; Simple variable name
8399 (when (js2-must-match js2-NAME "msg.bad.var")
8400 (setq name (js2-create-name-node)
8404 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8405 (when (js2-match-token js2-ASSIGN)
8406 (setq init (js2-parse-assign-expr)
8407 end (js2-node-end init))
8408 (if (and js2-parse-ide-mode
8409 (or (js2-object-node-p init)
8410 (js2-function-node-p init)))
8411 (js2-record-imenu-functions init name)))
8413 (js2-set-face nbeg nend (if (js2-function-node-p init)
8414 'font-lock-function-name-face
8415 'font-lock-variable-name-face)
8417 (setq vi (make-js2-var-init-node :pos kid-pos
8418 :len (- end kid-pos)
8422 (if (and (null init) (not js2-in-for-init))
8423 (js2-report-error "msg.destruct.assign.no.init"))
8424 (setf (js2-var-init-node-target vi) destructuring))
8425 (setf (js2-var-init-node-target vi) name))
8426 (setf (js2-var-init-node-initializer vi) init)
8427 (js2-node-add-children vi name destructuring init)
8428 (js2-block-node-push result vi)
8429 (unless (js2-match-token js2-COMMA)
8430 (setq continue nil)))
8431 (setf (js2-node-len result) (- end pos))
8434 (defun js2-parse-let (pos &optional stmt-p)
8435 "Parse a let expression or statement.
8436 A let-expression is of the form `let (vars) expr'.
8437 A let-statment is of the form `let (vars) {statements}'.
8438 The third form of let is a variable declaration list, handled
8439 by `js2-parse-variables'."
8440 (let ((pn (make-js2-let-node :pos pos))
8442 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8443 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8447 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8448 (if (js2-must-match js2-RP "msg.no.paren.let")
8449 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8450 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8454 (setf beg js2-token-beg ; position stmt at LC
8455 body (js2-parse-statements))
8456 (js2-must-match js2-RC "msg.no.curly.let")
8457 (setf (js2-node-len body) (- js2-token-end beg)
8458 (js2-node-len pn) (- js2-token-end pos)
8459 (js2-let-node-body pn) body
8460 (js2-node-type pn) js2-LET))
8462 (setf body (js2-parse-expr)
8463 (js2-node-len pn) (- (js2-node-end body) pos)
8464 (js2-let-node-body pn) body))
8465 (js2-node-add-children pn vars body))
8469 (defsubst js2-define-new-symbol (decl-type name node)
8470 (js2-scope-put-symbol js2-current-scope
8472 (make-js2-symbol decl-type name node)))
8474 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8475 "Define a symbol in the current scope.
8476 If NODE is non-nil, it is the AST node associated with the symbol."
8477 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8478 (symbol (if defining-scope
8479 (js2-scope-get-symbol defining-scope name)))
8480 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8482 ((and symbol ; already defined
8483 (or (= sdt js2-CONST) ; old version is const
8484 (= decl-type js2-CONST) ; new version is const
8485 ;; two let-bound vars in this block have same name
8486 (and (= sdt js2-LET)
8487 (eq defining-scope js2-current-scope))))
8490 ((= sdt js2-CONST) "msg.const.redecl")
8491 ((= sdt js2-LET) "msg.let.redecl")
8492 ((= sdt js2-VAR) "msg.var.redecl")
8493 ((= sdt js2-FUNCTION) "msg.function.redecl")
8494 (t "msg.parm.redecl"))
8496 ((= decl-type js2-LET)
8497 (if (and (not ignore-not-in-block)
8498 (or (= (js2-node-type js2-current-scope) js2-IF)
8499 (js2-loop-node-p js2-current-scope)))
8500 (js2-report-error "msg.let.decl.not.in.block")
8501 (js2-define-new-symbol decl-type name node)))
8502 ((or (= decl-type js2-VAR)
8503 (= decl-type js2-CONST)
8504 (= decl-type js2-FUNCTION))
8506 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8507 (js2-add-strict-warning "msg.var.redecl" name)
8508 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8509 (js2-add-strict-warning "msg.var.hides.arg" name)))
8510 (js2-define-new-symbol decl-type name node)))
8511 ((= decl-type js2-LP)
8513 ;; must be duplicate parameter. Second parameter hides the
8514 ;; first, so go ahead and add the second pararameter
8515 (js2-report-warning "msg.dup.parms" name))
8516 (js2-define-new-symbol decl-type name node))
8517 (t (js2-code-bug)))))
8519 (defun js2-parse-expr (&optional oneshot)
8520 (let* ((pn (js2-parse-assign-expr))
8521 (pos (js2-node-pos pn))
8525 (while (and (not oneshot)
8526 (js2-match-token js2-COMMA))
8527 (setq op-pos (- js2-token-beg pos)) ; relative
8528 (if (= (js2-peek-token) js2-YIELD)
8529 (js2-report-error "msg.yield.parenthesized"))
8530 (setq right (js2-parse-assign-expr)
8532 pn (make-js2-infix-node :type js2-COMMA
8534 :len (- js2-ts-cursor pos)
8538 (js2-node-add-children pn left right))
8541 (defun js2-parse-assign-expr ()
8542 (let ((tt (js2-peek-token))
8548 (if (= tt js2-YIELD)
8549 (js2-parse-return-or-yield tt t)
8550 ;; not yield - parse assignment expression
8551 (setq pn (js2-parse-cond-expr)
8552 tt (js2-peek-token))
8553 (when (and (<= js2-first-assign tt)
8554 (<= tt js2-last-assign))
8555 ;; tt express assignment (=, |=, ^=, ..., %=)
8557 (setq op-pos (- js2-token-beg pos) ; relative
8559 right (js2-parse-assign-expr)
8560 pn (make-js2-assign-node :type tt
8562 :len (- (js2-node-end right) pos)
8566 (when js2-parse-ide-mode
8567 (js2-highlight-assign-targets pn left right)
8568 (if (or (js2-function-node-p right)
8569 (js2-object-node-p right))
8570 (js2-record-imenu-functions right left)))
8571 ;; do this last so ide checks above can use absolute positions
8572 (js2-node-add-children pn left right))
8575 (defun js2-parse-cond-expr ()
8576 (let ((pos js2-token-beg)
8577 (pn (js2-parse-or-expr))
8583 (when (js2-match-token js2-HOOK)
8584 (setq q-pos (- js2-token-beg pos)
8585 if-true (js2-parse-assign-expr))
8586 (js2-must-match js2-COLON "msg.no.colon.cond")
8587 (setq c-pos (- js2-token-beg pos)
8588 if-false (js2-parse-assign-expr)
8590 pn (make-js2-cond-node :pos pos
8591 :len (- (js2-node-end if-false) pos)
8592 :test-expr test-expr
8594 :false-expr if-false
8597 (js2-node-add-children pn test-expr if-true if-false))
8600 (defun js2-make-binary (type left parser)
8601 "Helper for constructing a binary-operator AST node.
8602 LEFT is the left-side-expression, already parsed, and the
8603 binary operator should have just been matched.
8604 PARSER is a function to call to parse the right operand,
8605 or a `js2-node' struct if it has already been parsed."
8606 (let* ((pos (js2-node-pos left))
8607 (op-pos (- js2-token-beg pos))
8608 (right (if (js2-node-p parser)
8611 (pn (make-js2-infix-node :type type
8613 :len (- (js2-node-end right) pos)
8617 (js2-node-add-children pn left right)
8620 (defun js2-parse-or-expr ()
8621 (let ((pn (js2-parse-and-expr)))
8622 (when (js2-match-token js2-OR)
8623 (setq pn (js2-make-binary js2-OR
8625 'js2-parse-or-expr)))
8628 (defun js2-parse-and-expr ()
8629 (let ((pn (js2-parse-bit-or-expr)))
8630 (when (js2-match-token js2-AND)
8631 (setq pn (js2-make-binary js2-AND
8633 'js2-parse-and-expr)))
8636 (defun js2-parse-bit-or-expr ()
8637 (let ((pn (js2-parse-bit-xor-expr)))
8638 (while (js2-match-token js2-BITOR)
8639 (setq pn (js2-make-binary js2-BITOR
8641 'js2-parse-bit-xor-expr)))
8644 (defun js2-parse-bit-xor-expr ()
8645 (let ((pn (js2-parse-bit-and-expr)))
8646 (while (js2-match-token js2-BITXOR)
8647 (setq pn (js2-make-binary js2-BITXOR
8649 'js2-parse-bit-and-expr)))
8652 (defun js2-parse-bit-and-expr ()
8653 (let ((pn (js2-parse-eq-expr)))
8654 (while (js2-match-token js2-BITAND)
8655 (setq pn (js2-make-binary js2-BITAND
8657 'js2-parse-eq-expr)))
8660 (defconst js2-parse-eq-ops
8661 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8663 (defun js2-parse-eq-expr ()
8664 (let ((pn (js2-parse-rel-expr))
8666 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8668 (setq pn (js2-make-binary tt
8670 'js2-parse-rel-expr)))
8673 (defconst js2-parse-rel-ops
8674 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8676 (defun js2-parse-rel-expr ()
8677 (let ((pn (js2-parse-shift-expr))
8681 (setq tt (js2-peek-token))
8683 ((and js2-in-for-init (= tt js2-IN))
8684 (setq continue nil))
8685 ((memq tt js2-parse-rel-ops)
8687 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8689 (setq continue nil))))
8692 (defconst js2-parse-shift-ops
8693 (list js2-LSH js2-URSH js2-RSH))
8695 (defun js2-parse-shift-expr ()
8696 (let ((pn (js2-parse-add-expr))
8700 (setq tt (js2-peek-token))
8701 (if (memq tt js2-parse-shift-ops)
8704 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8705 (setq continue nil)))
8708 (defun js2-parse-add-expr ()
8709 (let ((pn (js2-parse-mul-expr))
8713 (setq tt (js2-peek-token))
8714 (if (or (= tt js2-ADD) (= tt js2-SUB))
8717 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8718 (setq continue nil)))
8721 (defconst js2-parse-mul-ops
8722 (list js2-MUL js2-DIV js2-MOD))
8724 (defun js2-parse-mul-expr ()
8725 (let ((pn (js2-parse-unary-expr))
8729 (setq tt (js2-peek-token))
8730 (if (memq tt js2-parse-mul-ops)
8733 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8734 (setq continue nil)))
8737 (defsubst js2-make-unary (type parser &rest args)
8738 "Make a unary node of type TYPE.
8739 PARSER is either a node (for postfix operators) or a function to call
8740 to parse the operand (for prefix operators)."
8741 (let* ((pos js2-token-beg)
8742 (postfix (js2-node-p parser))
8745 (apply parser args)))
8748 (if postfix ; e.g. i++
8749 (setq pos (js2-node-pos expr)
8751 (setq end (js2-node-end expr)))
8752 (setq pn (make-js2-unary-node :type type
8756 (js2-node-add-children pn expr)
8759 (defconst js2-incrementable-node-types
8760 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8761 "Node types that can be the operand of a ++ or -- operator.")
8763 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8764 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8765 js2-incrementable-node-types)
8766 (js2-report-error (if (= tt js2-INC)
8769 nil beg (- end beg))))
8771 (defun js2-parse-unary-expr ()
8772 (let ((tt (js2-peek-token))
8775 ((or (= tt js2-VOID)
8780 (js2-make-unary tt 'js2-parse-unary-expr))
8783 ;; Convert to special POS token in decompiler and parse tree
8784 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8787 ;; Convert to special NEG token in decompiler and parse tree
8788 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8793 (setq beg js2-token-beg
8795 expr (js2-make-unary tt 'js2-parse-member-expr t))
8796 (js2-check-bad-inc-dec tt beg end expr)))
8799 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8802 (make-js2-error-node)) ; try to continue
8804 js2-compiler-xml-available)
8805 ;; XML stream encountered in expression.
8807 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8809 (setq pn (js2-parse-member-expr t)
8810 ;; Don't look across a newline boundary for a postfix incop.
8811 tt (js2-peek-token-or-eol))
8812 (when (or (= tt js2-INC) (= tt js2-DEC))
8815 pn (js2-make-unary tt expr))
8816 (js2-node-set-prop pn 'postfix t)
8817 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8820 (defun js2-parse-xml-initializer ()
8821 "Parse an E4X XML initializer.
8822 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8823 Then I'll postprocess the result, depending on whether we're in IDE
8824 mode or codegen mode, and generate the appropriate rewritten AST.
8825 IDE mode uses a rich AST that models the XML structure. Codegen mode
8826 just concatenates everything and makes a new XML or XMLList out of it."
8827 (let ((tt (js2-get-first-xml-token))
8835 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8836 (js2-report-error "msg.syntax"))
8837 (setq pn-xml (make-js2-xml-node))
8840 (setq first-token nil)
8841 (setq tt (js2-get-next-xml-token)))
8843 ;; js2-XML means we found a {expr} in the XML stream.
8844 ;; The js2-ts-string is the XML up to the left-curly.
8846 (push (make-js2-string-node :pos js2-token-beg
8847 :len (- js2-ts-cursor js2-token-beg))
8849 (js2-must-match js2-LC "msg.syntax")
8850 (setq expr-pos js2-ts-cursor
8851 expr (if (eq (js2-peek-token) js2-RC)
8852 (make-js2-empty-expr-node :pos expr-pos)
8854 (js2-must-match js2-RC "msg.syntax")
8855 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8856 :len (js2-node-len expr)
8858 (js2-node-add-children pn expr)
8860 ;; a js2-XMLEND token means we hit the final close-tag.
8862 (push (make-js2-string-node :pos js2-token-beg
8863 :len (- js2-ts-cursor js2-token-beg))
8865 (dolist (kid (nreverse kids))
8866 (js2-block-node-push pn-xml kid))
8867 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8868 (js2-node-pos pn-xml))
8871 (js2-report-error "msg.syntax")
8872 (setq continue nil))))
8876 (defun js2-parse-argument-list ()
8877 "Parse an argument list and return it as a lisp list of nodes.
8878 Returns the list in reverse order. Consumes the right-paren token."
8880 (unless (js2-match-token js2-RP)
8882 (if (= (js2-peek-token) js2-YIELD)
8883 (js2-report-error "msg.yield.parenthesized"))
8884 (push (js2-parse-assign-expr) result)
8886 (js2-match-token js2-COMMA))
8887 (js2-must-match js2-RP "msg.no.paren.arg")
8890 (defun js2-parse-member-expr (&optional allow-call-syntax)
8891 (let ((tt (js2-peek-token))
8901 (setq pn (js2-parse-primary-expr))
8902 ;; parse a 'new' expression
8904 (setq pos js2-token-beg
8906 target (js2-parse-member-expr)
8907 end (js2-node-end target)
8908 pn (make-js2-new-node :pos pos
8911 (js2-node-add-children pn target)
8912 (when (js2-match-token js2-LP)
8913 ;; Add the arguments to pn, if any are supplied.
8914 (setf beg pos ; start of "new" keyword
8916 args (nreverse (js2-parse-argument-list))
8917 (js2-new-node-args pn) args
8919 (js2-new-node-lp pn) (- pos beg)
8920 (js2-new-node-rp pn) (- end 1 beg))
8921 (apply #'js2-node-add-children pn args))
8922 (when (and js2-allow-rhino-new-expr-initializer
8923 (js2-match-token js2-LC))
8924 (setf init (js2-parse-object-literal)
8925 end (js2-node-end init)
8926 (js2-new-node-initializer pn) init)
8927 (js2-node-add-children pn init))
8928 (setf (js2-node-len pn) (- end beg))) ; end outer if
8929 (js2-parse-member-expr-tail allow-call-syntax pn)))
8931 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8932 "Parse a chain of property/array accesses or function calls.
8933 Includes parsing for E4X operators like `..' and `.@'.
8934 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8935 Returns an expression tree that includes PN, the parent node."
8936 (let ((beg (js2-node-pos pn))
8940 (setq tt (js2-peek-token))
8942 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8943 (setq pn (js2-parse-property-access tt pn)))
8944 ((= tt js2-DOTQUERY)
8945 (setq pn (js2-parse-dot-query pn)))
8947 (setq pn (js2-parse-element-get pn)))
8949 (if allow-call-syntax
8950 (setq pn (js2-parse-function-call pn))
8951 (setq continue nil)))
8953 (setq continue nil))))
8954 (if (>= js2-highlight-level 2)
8955 (js2-parse-highlight-member-expr-node pn))
8958 (defun js2-parse-dot-query (pn)
8959 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8960 Last token parsed must be `js2-DOTQUERY'."
8961 (let ((pos (js2-node-pos pn))
8967 (js2-set-requires-activation)
8968 (setq op-pos js2-token-beg
8969 expr (js2-parse-expr)
8970 end (js2-node-end expr)
8971 pn (make-js2-xml-dot-query-node :left pn
8975 (js2-node-add-children pn
8976 (js2-xml-dot-query-node-left pn)
8977 (js2-xml-dot-query-node-right pn))
8978 (if (js2-must-match js2-RP "msg.no.paren")
8979 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8981 (setf (js2-node-len pn) (- end pos))
8984 (defun js2-parse-element-get (pn)
8985 "Parse an element-get expression, e.g. foo[bar].
8986 Last token parsed must be `js2-RB'."
8987 (let ((lb js2-token-beg)
8988 (pos (js2-node-pos pn))
8992 (setq expr (js2-parse-expr))
8993 (if (js2-must-match js2-RB "msg.no.bracket.index")
8994 (setq rb js2-token-beg))
8995 (setq pn (make-js2-elem-get-node :target pn
8998 :lb (js2-relpos lb pos)
8999 :rb (js2-relpos rb pos)
9000 :len (- js2-token-end pos)))
9001 (js2-node-add-children pn
9002 (js2-elem-get-node-target pn)
9003 (js2-elem-get-node-element pn))
9006 (defun js2-parse-function-call (pn)
9008 (pos (js2-node-pos pn)))
9010 (setq pn (make-js2-call-node :pos pos
9012 :lp (- js2-token-beg pos)))
9013 (js2-node-add-children pn (js2-call-node-target pn))
9014 ;; Add the arguments to pn, if any are supplied.
9015 (setf args (nreverse (js2-parse-argument-list))
9016 (js2-call-node-rp pn) (- js2-token-beg pos)
9017 (js2-call-node-args pn) args)
9018 (apply #'js2-node-add-children pn args)
9019 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9022 (defun js2-parse-property-access (tt pn)
9023 "Parse a property access, XML descendants access, or XML attr access."
9024 (let ((member-type-flags 0)
9025 (dot-pos js2-token-beg)
9026 (dot-len (if (= tt js2-DOTDOT) 2 1))
9028 ref ; right side of . or .. operator
9031 (when (= tt js2-DOTDOT)
9033 (setq member-type-flags js2-descendants-flag))
9034 (if (not js2-compiler-xml-available)
9036 (js2-must-match-prop-name "msg.no.name.after.dot")
9037 (setq name (js2-create-name-node t js2-GETPROP)
9038 result (make-js2-prop-get-node :left pn
9041 :len (- js2-token-end
9043 (js2-node-add-children result pn name)
9045 ;; otherwise look for XML operators
9046 (setf result (if (= tt js2-DOT)
9047 (make-js2-prop-get-node)
9048 (make-js2-infix-node :type js2-DOTDOT))
9049 (js2-node-pos result) (js2-node-pos pn)
9050 (js2-infix-node-op-pos result) dot-pos
9051 (js2-infix-node-left result) pn ; do this after setting position
9052 tt (js2-next-token))
9054 ;; needed for generator.throw()
9056 (js2-save-name-token-data js2-token-beg "throw")
9057 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9058 ;; handles: name, ns::name, ns::*, ns::[expr]
9059 ((js2-valid-prop-name-token tt)
9060 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9061 ;; handles: *, *::name, *::*, *::[expr]
9063 (js2-save-name-token-data js2-token-beg "*")
9064 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9065 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9067 (setq result (js2-parse-attribute-access)))
9069 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9071 (setf (js2-node-len result) (- (js2-node-end ref)
9072 (js2-node-pos result))
9073 (js2-infix-node-right result) ref))
9074 (if (js2-infix-node-p result)
9075 (js2-node-add-children result
9076 (js2-infix-node-left result)
9077 (js2-infix-node-right result)))
9080 (defun js2-parse-attribute-access ()
9081 "Parse an E4X XML attribute expression.
9082 This includes expressions of the forms:
9084 @attr @ns::attr @ns::*
9086 @[expr] @*::[expr] @ns::[expr]
9088 Called if we peeked an '@' token."
9089 (let ((tt (js2-next-token))
9090 (at-pos js2-token-beg))
9092 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9093 ((js2-valid-prop-name-token tt)
9094 (js2-parse-property-name at-pos js2-ts-string 0))
9095 ;; handles: @*, @*::name, @*::*, @*::[expr]
9097 (js2-save-name-token-data js2-token-beg "*")
9098 (js2-parse-property-name js2-token-beg "*" 0))
9101 (js2-parse-xml-elem-ref at-pos))
9103 (js2-report-error "msg.no.name.after.xmlAttr")
9104 ;; Avoid cascaded errors that happen if we make an error node here.
9105 (js2-save-name-token-data js2-token-beg "")
9106 (js2-parse-property-name js2-token-beg "" 0)))))
9108 (defun js2-parse-property-name (at-pos s member-type-flags)
9109 "Check if :: follows name in which case it becomes qualified name.
9111 AT-POS is a natural number if we just read an '@' token, else nil.
9112 S is the name or string that was matched: an identifier, 'throw' or '*'.
9113 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9115 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9116 operator, or the name is followed by ::. For a plain name, returns a
9117 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9118 (let ((pos (or at-pos js2-token-beg))
9120 (name (js2-create-name-node t js2-current-token))
9126 (when (js2-match-token js2-COLONCOLON)
9128 colon-pos js2-token-beg
9129 tt (js2-next-token))
9131 ;; handles name::name
9132 ((js2-valid-prop-name-token tt)
9133 (setq name (js2-create-name-node)))
9136 (js2-save-name-token-data js2-token-beg "*")
9137 (setq name (js2-create-name-node)))
9138 ;; handles name::[expr]
9140 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9142 (js2-report-error "msg.no.name.after.coloncolon"))))
9143 (if (and (null ns) (zerop member-type-flags))
9147 (make-js2-xml-prop-ref-node :pos pos
9148 :len (- (js2-node-end name) pos)
9150 :colon-pos colon-pos
9152 (js2-node-add-children pn name))))))
9154 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9155 "Parse the [expr] portion of an xml element reference.
9156 For instance, @[expr], @*::[expr], or ns::[expr]."
9157 (let* ((lb js2-token-beg)
9158 (pos (or at-pos lb))
9160 (expr (js2-parse-expr))
9161 (end (js2-node-end expr))
9163 (if (js2-must-match js2-RB "msg.no.bracket.index")
9164 (setq rb js2-token-beg
9168 (make-js2-xml-elem-ref-node :pos pos
9170 :namespace namespace
9171 :colon-pos colon-pos
9174 :lb (js2-relpos lb pos)
9175 :rb (js2-relpos rb pos)))
9176 (js2-node-add-children pn namespace expr))))
9178 (defsubst js2-parse-primary-expr-lhs ()
9179 (let ((js2-is-in-lhs t))
9180 (js2-parse-primary-expr)))
9182 (defun js2-parse-primary-expr ()
9183 "Parses a literal (leaf) expression of some sort.
9184 Includes complex literals such as functions, object-literals,
9185 array-literals, array comprehensions and regular expressions."
9186 (let ((tt-flagged (js2-next-flagged-token))
9187 pn ; parent node (usually return value)
9189 px-pos ; paren-expr pos
9191 flags ; regexp flags
9193 (setq tt js2-current-token)
9195 ((= tt js2-FUNCTION)
9196 (js2-parse-function 'FUNCTION_EXPRESSION))
9198 (js2-parse-array-literal))
9200 (js2-parse-object-literal))
9202 (js2-parse-let js2-token-beg))
9204 (setq px-pos js2-token-beg
9205 expr (js2-parse-expr))
9206 (js2-must-match js2-RP "msg.no.paren")
9207 (setq pn (make-js2-paren-node :pos px-pos
9209 :len (- js2-token-end px-pos)))
9210 (js2-node-add-children pn (js2-paren-node-expr pn))
9214 (js2-parse-attribute-access))
9216 (js2-parse-name tt-flagged tt))
9218 (make-js2-number-node))
9221 (make-js2-string-node)
9222 (js2-record-face 'font-lock-string-face)))
9223 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9224 ;; Got / or /= which in this context means a regexp literal
9225 (setq px-pos js2-token-beg)
9226 (js2-read-regexp tt)
9227 (setq flags js2-ts-regexp-flags
9228 js2-ts-regexp-flags nil)
9230 (make-js2-regexp-node :pos px-pos
9231 :len (- js2-ts-cursor px-pos)
9232 :value js2-ts-string
9234 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9235 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9236 ((or (= tt js2-NULL)
9240 (make-js2-keyword-node :type tt))
9241 ((= tt js2-RESERVED)
9242 (js2-report-error "msg.reserved.id")
9243 (make-js2-name-node))
9245 ;; the scanner or one of its subroutines reported the error.
9246 (make-js2-error-node))
9248 (setq px-pos (point-at-bol)
9249 len (- js2-ts-cursor px-pos))
9250 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9251 (make-js2-error-node :pos px-pos :len len))
9253 (js2-report-error "msg.syntax")
9254 (make-js2-error-node)))))
9256 (defun js2-parse-name (tt-flagged tt)
9257 (let ((name js2-ts-string)
9258 (name-pos js2-token-beg))
9259 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9260 (= (js2-peek-token) js2-COLON))
9262 ;; Do not consume colon, it is used as unwind indicator
9263 ;; to return to statementHelper.
9264 (make-js2-label-node :pos name-pos
9265 :len (- js2-token-end name-pos)
9267 (js2-set-face name-pos
9269 'font-lock-variable-name-face 'record))
9270 ;; Otherwise not a label, just a name. Unfortunately peeking
9271 ;; the next token to check for a colon has biffed js2-token-beg
9272 ;; and js2-token-end. We store the name's bounds in buffer vars
9273 ;; and `js2-create-name-node' uses them.
9274 (js2-save-name-token-data name-pos name)
9275 (if js2-compiler-xml-available
9276 (js2-parse-property-name nil name 0)
9277 (js2-create-name-node 'check-activation)))))
9279 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9280 (js2-add-strict-warning
9282 ;; back up from comma to beginning of line or array/objlit
9284 (js2-node-pos (car elems))
9287 (goto-char comma-pos)
9288 (back-to-indentation)
9292 (defun js2-parse-array-literal ()
9293 (let ((pos js2-token-beg)
9295 (after-lb-or-comma t)
9302 (setq tt (js2-peek-token))
9307 (setq after-comma js2-token-end)
9308 (if (not after-lb-or-comma)
9309 (setq after-lb-or-comma t)
9313 (= tt js2-EOF)) ; prevent infinite loop
9315 (js2-report-error "msg.no.bracket.arg" nil pos)
9316 (js2-consume-token))
9319 pn (make-js2-array-node :pos pos
9320 :len (- js2-ts-cursor pos)
9321 :elems (nreverse elems)))
9322 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9324 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9325 pos elems after-comma)))
9326 ;; destructuring binding
9328 (push (if (or (= tt js2-LC)
9331 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9332 (js2-parse-primary-expr-lhs)
9335 (js2-report-error "msg.bad.var")
9336 (make-js2-error-node))
9338 (setq after-lb-or-comma nil
9341 ((and (>= js2-language-version 170)
9342 (= tt js2-FOR) ; check for array comprehension
9343 (not after-lb-or-comma) ; "for" can't follow a comma
9344 elems ; must have at least 1 element
9345 (not (cdr elems))) ; but no 2nd element
9347 pn (js2-parse-array-comprehension (car elems) pos)))
9351 (unless after-lb-or-comma
9352 (js2-report-error "msg.no.bracket.arg"))
9353 (push (js2-parse-assign-expr) elems)
9354 (setq after-lb-or-comma nil
9358 (defun js2-parse-array-comprehension (expr pos)
9359 "Parse a JavaScript 1.7 Array Comprehension.
9360 EXPR is the first expression after the opening left-bracket.
9361 POS is the beginning of the LB token preceding EXPR.
9362 We should have just parsed the 'for' keyword before calling this function."
9367 (while (= (js2-peek-token) js2-FOR)
9368 (push (js2-parse-array-comp-loop) loops))
9369 (when (= (js2-peek-token) js2-IF)
9371 (setq if-pos (- js2-token-beg pos) ; relative
9372 filter (js2-parse-condition)))
9373 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9374 (setq result (make-js2-array-comp-node :pos pos
9375 :len (- js2-ts-cursor pos)
9377 :loops (nreverse loops)
9378 :filter (car filter)
9379 :lp (js2-relpos (second filter) pos)
9380 :rp (js2-relpos (third filter) pos)
9382 (apply #'js2-node-add-children result expr (car filter)
9383 (js2-array-comp-node-loops result))
9386 (defun js2-parse-array-comp-loop ()
9387 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9388 Last token peeked should be the initial FOR."
9389 (let ((pos js2-token-beg)
9390 (pn (make-js2-array-comp-loop-node))
9399 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9403 (when (js2-match-token js2-NAME)
9404 (if (string= js2-ts-string "each")
9407 each-pos (- js2-token-beg pos)) ; relative
9408 (js2-record-face 'font-lock-keyword-face))
9409 (js2-report-error "msg.no.paren.for")))
9410 (if (js2-must-match js2-LP "msg.no.paren.for")
9411 (setq lp (- js2-token-beg pos)))
9412 (setq tt (js2-peek-token))
9416 ;; handle destructuring assignment
9417 (setq iter (js2-parse-primary-expr-lhs)))
9418 ((js2-valid-prop-name-token tt)
9420 (setq iter (js2-create-name-node)))
9422 (js2-report-error "msg.bad.var")))
9423 ;; Define as a let since we want the scope of the variable to
9424 ;; be restricted to the array comprehension
9425 (if (js2-name-node-p iter)
9426 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9427 (if (js2-must-match js2-IN "msg.in.after.for.name")
9428 (setq in-pos (- js2-token-beg pos)))
9429 (setq obj (js2-parse-expr))
9430 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9431 (setq rp (- js2-token-beg pos)))
9432 (setf (js2-node-pos pn) pos
9433 (js2-node-len pn) (- js2-ts-cursor pos)
9434 (js2-array-comp-loop-node-iterator pn) iter
9435 (js2-array-comp-loop-node-object pn) obj
9436 (js2-array-comp-loop-node-in-pos pn) in-pos
9437 (js2-array-comp-loop-node-each-pos pn) each-pos
9438 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9439 (js2-array-comp-loop-node-lp pn) lp
9440 (js2-array-comp-loop-node-rp pn) rp)
9441 (js2-node-add-children pn iter obj))
9445 (defun js2-parse-object-literal ()
9446 (let ((pos js2-token-beg)
9453 (setq tt (js2-peek-token))
9455 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9456 ((or (js2-valid-prop-name-token tt)
9458 (setq after-comma nil
9459 result (js2-parse-named-prop tt))
9460 (if (and (null result)
9461 (not js2-recover-from-parse-errors))
9463 (push result elems)))
9464 ;; {12: x} or {10.7: x}
9467 (setq after-comma nil)
9468 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9473 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9474 pos elems after-comma)))
9476 (js2-report-error "msg.bad.prop")
9477 (unless js2-recover-from-parse-errors
9478 (setq continue nil)))) ; end switch
9479 (if (js2-match-token js2-COMMA)
9480 (setq after-comma js2-token-end)
9481 (setq continue nil))) ; end loop
9482 (js2-must-match js2-RC "msg.no.brace.prop")
9483 (setq result (make-js2-object-node :pos pos
9484 :len (- js2-ts-cursor pos)
9485 :elems (nreverse elems)))
9486 (apply #'js2-node-add-children result (js2-object-node-elems result))
9489 (defun js2-parse-named-prop (tt)
9490 "Parse a name, string, or getter/setter object property.
9491 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9493 (let ((string-prop (and (= tt js2-STRING)
9494 (make-js2-string-node)))
9496 (ppos js2-token-beg)
9497 (pend js2-token-end)
9498 (name (js2-create-name-node))
9499 (prop js2-ts-string))
9501 ;; getter/setter prop
9502 ((and (= tt js2-NAME)
9503 (= (js2-peek-token) js2-NAME)
9504 (or (string= prop "get")
9505 (string= prop "set")))
9508 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9509 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9510 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9511 (js2-parse-getter-setter-prop ppos name (string= prop "get"))))
9512 ;; abbreviated destructuring bind e.g., {a, b} = c;
9513 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9514 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9515 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9516 ;; assignment but it's difficult because it requires looking ahead of expression.
9519 (let ((ctk (js2-peek-token)))
9520 (or (= ctk js2-COMMA)
9522 (js2-valid-prop-name-token ctk))))
9523 (js2-set-face ppos pend 'font-lock-variable-name-face 'record)
9528 (setq expr (js2-parse-plain-property (or string-prop name)))
9529 (js2-set-face ppos pend
9530 (if (js2-function-node-p
9531 (js2-object-prop-node-right expr))
9532 'font-lock-function-name-face
9533 'font-lock-variable-name-face)
9536 (defun js2-parse-plain-property (prop)
9537 "Parse a non-getter/setter property in an object literal.
9538 PROP is the node representing the property: a number, name or string."
9539 (js2-must-match js2-COLON "msg.no.colon.prop")
9540 (let* ((pos (js2-node-pos prop))
9541 (colon (- js2-token-beg pos))
9542 (expr (js2-parse-assign-expr))
9543 (result (make-js2-object-prop-node
9545 ;; don't include last consumed token in length
9546 :len (- (+ (js2-node-pos expr)
9547 (js2-node-len expr))
9552 (js2-node-add-children result prop expr)
9555 (defun js2-parse-getter-setter-prop (pos prop get-p)
9556 "Parse getter or setter property in an object literal.
9557 JavaScript syntax is:
9559 { get foo() {...}, set foo(x) {...} }
9561 and expression closure style is also supported
9563 { get foo() x, set foo(x) _x = x }
9565 POS is the start position of the `get' or `set' keyword.
9566 PROP is the `js2-name-node' representing the property name.
9567 GET-P is non-nil if the keyword was `get'."
9568 (let ((type (if get-p js2-GET js2-SET))
9571 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9572 ;; it has to be an anonymous function, as we already parsed the name
9573 (if (/= (js2-node-type fn) js2-FUNCTION)
9574 (js2-report-error "msg.bad.prop")
9575 (if (plusp (length (js2-function-name fn)))
9576 (js2-report-error "msg.bad.prop")))
9577 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9578 (setq end (js2-node-end fn)
9579 result (make-js2-getter-setter-node :type type
9584 (js2-node-add-children result prop fn)
9587 (defun js2-create-name-node (&optional check-activation-p token)
9588 "Create a name node using the token info from last scanned name.
9589 In some cases we need to either synthesize a name node, or we lost
9590 the name token information by peeking. If the TOKEN parameter is
9591 not `js2-NAME', then we use the token info saved in instance vars."
9592 (let ((beg js2-token-beg)
9595 (when (/= js2-current-token js2-NAME)
9596 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9597 s js2-prev-name-token-string
9598 js2-prev-name-token-start nil
9599 js2-prev-name-token-string nil))
9600 (setq name (make-js2-name-node :pos beg
9603 (if check-activation-p
9604 (js2-check-activation-name s (or token js2-NAME)))
9607 ;;; Indentation support
9609 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9610 ;; Karl cleverly deduces that the desired indentation level is often a
9611 ;; function of paren/bracket/brace nesting depth, which can be determined
9612 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9613 ;; then does some equally clever checks to see if we're in the context of a
9614 ;; substatement of a possibly braceless statement keyword such as if, while,
9615 ;; or finally. This approach yields pretty good results.
9617 ;; The indenter is often "wrong", however, and needs to be overridden.
9618 ;; The right long-term solution is probably to emulate (or integrate
9619 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9620 ;; parse tree from `js2-parse' is present, which is not true at the
9621 ;; moment the user is typing, computing indentation is still thousands
9622 ;; of lines of code to handle every possible syntactic edge case.
9624 ;; In the meantime, the compromise solution is that we offer a "bounce
9625 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9626 ;; current line indent among various likely guess points. This approach
9627 ;; is far from perfect, but should at least make it slightly easier to
9628 ;; move the line towards its desired indentation when manually
9629 ;; overriding Karl's heuristic nesting guesser.
9631 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9632 ;; extensions such as `let' and Array comprehensions. Major kudos to
9633 ;; Karl for coming up with the initial approach, which packs a lot of
9634 ;; punch for so little code.
9636 (defconst js-possibly-braceless-keyword-re
9638 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9640 "Regular expression matching keywords that are optionally
9641 followed by an opening brace.")
9643 (defconst js-possibly-braceless-keywords-re
9644 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9645 "Regular expression which matches the keywords which are consist of more than 2 words
9646 like 'if else' and 'for each', and optionally followed by an opening brace.")
9648 (defconst js-indent-operator-re
9649 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9650 (regexp-opt '("in" "instanceof") 'words))
9651 "Regular expression matching operators that affect indentation
9652 of continued expressions.")
9654 ;; This function has horrible results if you're typing an array
9655 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9656 ;; in conjunction with electric-indent, so just disabling it.
9657 (defsubst js2-code-at-bol-p ()
9658 "Return t if the first character on line is non-whitespace."
9661 (defun js2-insert-and-indent (key)
9662 "Run command bound to key and indent current line. Runs the command
9663 bound to KEY in the global keymap and indents the current line."
9664 (interactive (list (this-command-keys)))
9665 (let ((cmd (lookup-key (current-global-map) key)))
9667 (call-interactively cmd)))
9668 ;; don't do the electric keys inside comments or strings,
9669 ;; and don't do bounce-indent with them.
9670 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9671 (js2-bounce-indent-p (js2-code-at-bol-p)))
9672 (unless (or (nth 3 parse-state)
9673 (nth 4 parse-state))
9674 (indent-according-to-mode))))
9676 (defun js-re-search-forward-inner (regexp &optional bound count)
9677 "Auxiliary function for `js-re-search-forward'."
9679 (saved-point (point-min)))
9681 (re-search-forward regexp bound)
9682 (setq parse (parse-partial-sexp saved-point (point)))
9683 (cond ((nth 3 parse)
9685 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9686 (save-excursion (end-of-line) (point)) t))
9690 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9691 (re-search-forward "\\*/"))
9693 (setq count (1- count))))
9694 (setq saved-point (point))))
9697 (defun js-re-search-forward (regexp &optional bound noerror count)
9698 "Search forward but ignore strings and comments. Invokes
9699 `re-search-forward' but treats the buffer as if strings and
9700 comments have been removed."
9701 (let ((saved-point (point))
9704 '(js-re-search-forward-inner regexp bound 1))
9706 '(js-re-search-backward-inner regexp bound (- count)))
9708 '(js-re-search-forward-inner regexp bound count)))))
9712 (goto-char saved-point)
9714 (error (error-message-string err)))))))
9716 (defun js-re-search-backward-inner (regexp &optional bound count)
9717 "Auxiliary function for `js-re-search-backward'."
9719 (saved-point (point-min)))
9721 (re-search-backward regexp bound)
9722 (setq parse (parse-partial-sexp saved-point (point)))
9723 (cond ((nth 3 parse)
9725 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9726 (save-excursion (beginning-of-line) (point)) t))
9728 (goto-char (nth 8 parse)))
9730 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9731 (re-search-backward "/\\*"))
9733 (setq count (1- count))))))
9736 (defun js-re-search-backward (regexp &optional bound noerror count)
9737 "Search backward but ignore strings and comments. Invokes
9738 `re-search-backward' but treats the buffer as if strings and
9739 comments have been removed."
9740 (let ((saved-point (point))
9743 '(js-re-search-backward-inner regexp bound 1))
9745 '(js-re-search-forward-inner regexp bound (- count)))
9747 '(js-re-search-backward-inner regexp bound count)))))
9751 (goto-char saved-point)
9753 (error (error-message-string err)))))))
9755 (defun js-looking-at-operator-p ()
9756 "Return non-nil if text after point is an operator (that is not
9759 (and (looking-at js-indent-operator-re)
9760 (or (not (looking-at ":"))
9762 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9763 (looking-at "?")))))))
9765 (defun js-continued-expression-p ()
9766 "Returns non-nil if the current line continues an expression."
9768 (back-to-indentation)
9769 (or (js-looking-at-operator-p)
9771 (and (js-re-search-backward "\n" nil t)
9773 (skip-chars-backward " \t")
9775 (and (js-looking-at-operator-p)
9776 (and (progn (backward-char)
9777 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9779 (defun js-end-of-do-while-loop-p ()
9780 "Returns non-nil if word after point is `while' of a do-while
9781 statement, else returns nil. A braceless do-while statement
9782 spanning several lines requires that the start of the loop is
9783 indented to the same column as the current line."
9787 (when (looking-at "\\s-*\\<while\\>")
9789 (skip-chars-backward "[ \t\n]*}")
9790 (looking-at "[ \t\n]*}"))
9792 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9793 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9794 (or (looking-at "\\<do\\>")
9795 (let ((saved-indent (current-indentation)))
9796 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9797 (/= (current-indentation) saved-indent)))
9798 (and (looking-at "[ \t]*\\<do\\>")
9799 (not (js-re-search-forward
9800 "\\<while\\>" (point-at-eol) t))
9801 (= (current-indentation) saved-indent)))))))))
9803 (defun js-get-multiline-declaration-offset ()
9804 "Returns offset (> 0) if the current line is part of
9805 multi-line variable declaration like below example, and
9806 returns 0 otherwise.
9813 (let* ((node (js2-node-at-point))
9814 (pnode (and node (js2-node-parent node)))
9815 (pnode-type (and pnode (js2-node-type pnode))))
9817 (= js2-NAME (js2-node-type node))
9819 (= js2-VAR pnode-type)
9820 (= js2-LET pnode-type)
9821 (= js2-CONST pnode-type)))
9822 (if (= js2-CONST pnode-type)
9827 (defun js-ctrl-statement-indentation ()
9828 "Returns the proper indentation of the current line if it
9829 starts the body of a control statement without braces, else
9831 (let (forward-sexp-function) ; temporarily unbind it
9833 (back-to-indentation)
9834 (when (save-excursion
9835 (and (not (js2-same-line (point-min)))
9836 (not (looking-at "{"))
9837 (js-re-search-backward "[[:graph:]]" nil t)
9838 (not (looking-at "[{([]"))
9841 ;; scan-sexps sometimes throws an error
9842 (ignore-errors (backward-sexp))
9843 (when (looking-at "(") (backward-word 1))
9844 (and (save-excursion
9845 (skip-chars-backward " \t}" (point-at-bol))
9847 (and (backward-word 1)
9848 (skip-chars-backward " \t}" (point-at-bol))
9850 (looking-at js-possibly-braceless-keywords-re))))
9851 (looking-at js-possibly-braceless-keyword-re)
9852 (not (js-end-of-do-while-loop-p))))))
9854 (goto-char (match-beginning 0))
9855 (+ (current-indentation) js2-basic-offset))))))
9857 (defun js2-indent-in-array-comp (parse-status)
9858 "Return non-nil if we think we're in an array comprehension.
9859 In particular, return the buffer position of the first `for' kwd."
9860 (let ((end (point)))
9861 (when (nth 1 parse-status)
9863 (goto-char (nth 1 parse-status))
9864 (when (looking-at "\\[")
9867 (if (looking-at "[[{]")
9868 (let (forward-sexp-function) ; use lisp version
9869 (forward-sexp) ; skip destructuring form
9871 (if (and (/= (char-after) ?,) ; regular array
9873 (match-beginning 0)))
9874 ;; to skip arbitrary expressions we need the parser,
9875 ;; so we'll just guess at it.
9876 (if (re-search-forward "[^,]* \\(for\\) " end t)
9877 (match-beginning 1))))))))
9879 (defun js2-array-comp-indentation (parse-status for-kwd)
9880 (if (js2-same-line for-kwd)
9881 ;; first continuation line
9883 (goto-char (nth 1 parse-status))
9885 (skip-chars-forward " \t")
9891 (defun js-proper-indentation (parse-status)
9892 "Return the proper indentation for the current line."
9894 (back-to-indentation)
9895 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9896 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9897 (continued-expr-p (js-continued-expression-p))
9898 (multiline-declaration-offset (js-get-multiline-declaration-offset))
9899 (bracket (nth 1 parse-status))
9902 ;; indent array comprehension continuation lines specially
9904 (not (js2-same-line bracket))
9905 (setq beg (js2-indent-in-array-comp parse-status))
9906 (>= (point) (save-excursion
9908 (point-at-bol)))) ; at or after first loop?
9909 (js2-array-comp-indentation parse-status beg))
9916 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9917 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9918 (when (save-excursion (skip-chars-backward " \t)")
9922 (not js2-consistent-level-indent-inner-bracket-p))
9923 (progn (goto-char (1+ (nth 1 p)))
9924 (skip-chars-forward " \t"))
9925 (back-to-indentation))
9926 (cond (same-indent-p
9929 (+ (current-column) (* 2 js2-basic-offset)))
9930 ((> multiline-declaration-offset 0)
9931 (+ (current-column) js2-basic-offset multiline-declaration-offset))
9933 (+ (current-column) js2-basic-offset)))))
9935 (unless same-indent-p
9937 (skip-chars-forward " \t"))
9940 (continued-expr-p js2-basic-offset)
9942 ((> multiline-declaration-offset 0)
9943 (+ multiline-declaration-offset))
9947 (defun js2-lineup-comment (parse-status)
9948 "Indent a multi-line block comment continuation line."
9949 (let* ((beg (nth 8 parse-status))
9950 (first-line (js2-same-line beg))
9951 (offset (save-excursion
9953 (if (looking-at "/\\*")
9954 (+ 1 (current-column))
9957 (indent-line-to offset))))
9959 (defun js2-backward-sws ()
9960 "Move backward through whitespace and comments."
9962 (while (forward-comment -1)))
9964 (defun js2-forward-sws ()
9965 "Move forward through whitespace and comments."
9967 (while (forward-comment 1)))
9969 (defsubst js2-current-indent (&optional pos)
9970 "Return column of indentation on current line.
9971 If POS is non-nil, go to that point and return indentation for that line."
9975 (back-to-indentation)
9978 (defsubst js2-arglist-close ()
9979 "Return non-nil if we're on a line beginning with a close-paren/brace."
9982 (goto-char (point-at-bol))
9984 (looking-at "[])}]"))))
9986 (defsubst js2-indent-looks-like-label-p ()
9987 (goto-char (point-at-bol))
9989 (looking-at (concat js2-mode-identifier-re ":")))
9991 (defun js2-indent-in-objlit-p (parse-status)
9992 "Return non-nil if this looks like an object-literal entry."
9993 (let ((start (nth 1 parse-status)))
9997 (and (zerop (forward-line -1))
9998 (not (< (point) start)) ; crossed a {} boundary
9999 (js2-indent-looks-like-label-p)))
10001 (js2-indent-looks-like-label-p)))))
10003 ;; if prev line looks like foobar({ then we're passing an object
10004 ;; literal to a function call, and people pretty much always want to
10005 ;; de-dent back to the previous line, so move the 'basic-offset'
10006 ;; position to the front.
10007 (defsubst js2-indent-objlit-arg-p (parse-status)
10009 (back-to-indentation)
10011 (and (eq (1- (point)) (nth 1 parse-status))
10012 (eq (char-before) ?{)
10015 (skip-chars-backward " \t")
10016 (eq (char-before) ?\()))))
10018 (defsubst js2-indent-case-block-p ()
10020 (back-to-indentation)
10022 (goto-char (point-at-bol))
10023 (skip-chars-forward " \t")
10025 (looking-at "case\\s-.+:"))))
10027 (defsubst js2-syntax-bol ()
10028 "Return the point at the first non-whitespace char on the line.
10029 Returns `point-at-bol' if the line is empty."
10031 (beginning-of-line)
10032 (skip-chars-forward " \t")
10035 (defun js2-bounce-indent (normal-col parse-status)
10036 "Cycle among alternate computed indentation positions.
10037 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10038 of the buffer to the current point. NORMAL-COL is the indentation
10039 column computed by the heuristic guesser based on current paren,
10040 bracket, brace and statement nesting."
10041 (let ((cur-indent (js2-current-indent))
10042 (old-buffer-undo-list buffer-undo-list)
10043 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10044 (current-line (save-excursion
10045 (forward-line 0) ; move to bol
10046 (1+ (count-lines (point-min) (point)))))
10055 ;; temporarily don't record undo info, if user requested this
10056 (if js2-mode-indent-inhibit-undo
10057 (setq buffer-undo-list t))
10060 ;; first likely point: indent from beginning of previous code line
10061 (push (setq basic-offset
10063 (back-to-indentation)
10065 (back-to-indentation)
10066 (setq prev-line-col (current-column)))
10070 ;; (first + epsilon) likely point: indent 2x from beginning of
10071 ;; previous code line. Some companies like this approach. Ahem.
10072 ;; Seriously, though -- 4-space indent for expression continuation
10073 ;; lines isn't a bad idea. We should eventually implement it
10075 (push (setq basic-offset
10077 (back-to-indentation)
10079 (back-to-indentation)
10080 (setq prev-line-col (current-column)))
10081 (* 2 js2-basic-offset)))
10084 ;; second likely point: indent from assign-expr RHS. This
10085 ;; is just a crude guess based on finding " = " on the previous
10086 ;; line containing actual code.
10087 (setq pos (save-excursion
10090 (goto-char (point-at-bol))
10091 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10093 (goto-char (match-end 1))
10094 (skip-chars-forward " \t\r\n")
10095 (current-column)))))
10097 (incf pos js2-basic-offset)
10098 (unless (member pos positions)
10099 (push pos positions)))
10101 ;; third likely point: same indent as previous line of code.
10102 ;; Make it the first likely point if we're not on an
10103 ;; arglist-close line and previous line ends in a comma, or
10104 ;; both this line and prev line look like object-literal
10106 (setq pos (save-excursion
10107 (goto-char (point-at-bol))
10109 (back-to-indentation)
10112 ;; while we're here, look for trailing comma
10113 (if (save-excursion
10114 (goto-char (point-at-eol))
10116 (eq (char-before) ?,))
10117 (setq arglist-cont (1- (point)))))))
10119 (if (and (or arglist-cont
10120 (js2-indent-in-objlit-p parse-status))
10121 (not (js2-arglist-close)))
10122 (setq same-indent pos))
10123 (unless (member pos positions)
10124 (push pos positions)))
10126 ;; fourth likely point: first preceding code with less indentation
10127 ;; than the immediately preceding code line.
10128 (setq pos (save-excursion
10130 (back-to-indentation)
10131 (setq anchor (current-column))
10132 (while (and (zerop (forward-line -1))
10134 (back-to-indentation)
10137 (setq pos (current-column))))
10138 (unless (member pos positions)
10139 (push pos positions))
10141 ;; put nesting-heuristic position first in list, sort rest
10142 (setq positions (nreverse (sort positions '<)))
10143 (setq positions (cons normal-col (delete normal-col positions)))
10145 ;; comma-list continuation lines: prev line indent takes precedence
10149 (sort (delete same-indent positions) '<))))
10151 ;; common special cases where we want to indent in from previous line
10152 (if (or (js2-indent-case-block-p)
10153 (js2-indent-objlit-arg-p parse-status))
10156 (delete basic-offset positions))))
10158 ;; record whether we're already sitting on one of the alternatives
10159 (setq pos (member cur-indent positions))
10161 ;; case 0: we're one one of the alternatives and this is the
10162 ;; first time they've pressed TAB on this line (best-guess).
10163 ((and js2-mode-indent-ignore-first-tab
10165 ;; first time pressing TAB on this line?
10166 (not (eq js2-mode-last-indented-line current-line)))
10168 (setq computed-pos nil))
10169 ;; case 1: only one computed position => use it
10170 ((null (cdr positions))
10171 (setq computed-pos 0))
10172 ;; case 2: not on any of the computed spots => use main spot
10174 (setq computed-pos 0))
10175 ;; case 3: on last position: cycle to first position
10177 (setq computed-pos 0))
10178 ;; case 4: on intermediate position: cycle to next position
10180 (setq computed-pos (js2-position (second pos) positions))))
10182 ;; see if any hooks want to indent; otherwise we do it
10183 (loop with result = nil
10184 for hook in js2-indent-hook
10185 while (null result)
10187 (setq result (funcall hook positions computed-pos))
10189 (unless (or result (null computed-pos))
10190 (indent-line-to (nth computed-pos positions)))))
10193 (if js2-mode-indent-inhibit-undo
10194 (setq buffer-undo-list old-buffer-undo-list))
10195 ;; see commentary for `js2-mode-last-indented-line'
10196 (setq js2-mode-last-indented-line current-line))))
10198 (defsubst js2-1-line-comment-continuation-p ()
10199 "Return t if we're in a 1-line comment continuation.
10200 If so, we don't ever want to use bounce-indent."
10205 (looking-at "\\s-*//"))
10209 (when (looking-at "\\s-*$")
10212 (looking-at "\\s-*//"))))))
10214 (defun js2-indent-line ()
10215 "Indent the current line as JavaScript source text."
10222 ;; don't whine about errors/warnings when we're indenting.
10223 ;; This has to be set before calling parse-partial-sexp below.
10224 (inhibit-point-motion-hooks t))
10225 (setq parse-status (save-excursion
10226 (parse-partial-sexp (point-min)
10228 offset (- (point) (save-excursion
10229 (back-to-indentation)
10230 (setq current-indent (current-column))
10232 (js2-with-underscore-as-word-syntax
10233 (if (nth 4 parse-status)
10234 (js2-lineup-comment parse-status)
10235 (setq indent-col (js-proper-indentation parse-status))
10236 ;; see comments below about js2-mode-last-indented-line
10239 ;; bounce-indenting is disabled during electric-key indent.
10240 ;; It doesn't work well on first line of buffer.
10241 ((and js2-bounce-indent-p
10242 (not (js2-same-line (point-min)))
10243 (not (js2-1-line-comment-continuation-p)))
10244 (js2-bounce-indent indent-col parse-status)
10246 ;; just indent to the guesser's likely spot
10247 ((/= current-indent indent-col)
10248 (indent-line-to indent-col)
10250 (when (and moved (plusp offset))
10251 (forward-char offset)))))))
10253 (defun js2-indent-region (start end)
10254 "Indent the region, but don't use bounce indenting."
10255 (let ((js2-bounce-indent-p nil)
10256 (indent-region-function nil))
10257 (indent-region start end nil))) ; nil for byte-compiler
10259 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10263 "Major mode for editing JavaScript code."
10265 (kill-all-local-variables)
10266 (set-syntax-table js2-mode-syntax-table)
10267 (use-local-map js2-mode-map)
10268 (setq major-mode 'js2-mode
10269 mode-name "JavaScript-IDE"
10270 comment-start "//" ; used by comment-region; don't change it
10272 (setq local-abbrev-table js2-mode-abbrev-table)
10273 (set (make-local-variable 'max-lisp-eval-depth)
10274 (max max-lisp-eval-depth 3000))
10275 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10276 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10278 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10279 ;; on most platforms other than the one I originally wrote it on. So it's
10280 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10281 ;; with our binding of the RET key inside comments: short lines stay short.
10282 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10284 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10285 (set (make-local-variable 'next-error-function) #'js2-next-error)
10286 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10287 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10288 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10289 ;; for characters inside regexp literals.
10290 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10291 ;; this is necessary to make `show-paren-function' work properly
10292 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10293 ;; needed for M-x rgrep, among other things
10294 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10296 ;; some variables needed by cc-engine for paragraph-fill, etc.
10297 (setq c-buffer-is-cc-mode t
10298 c-comment-prefix-regexp js2-comment-prefix-regexp
10299 c-comment-start-regexp "/[*/]\\|\\s|"
10300 c-paragraph-start js2-paragraph-start
10301 c-paragraph-separate "$"
10302 comment-start-skip js2-comment-start-skip
10303 c-syntactic-ws-start js2-syntactic-ws-start
10304 c-syntactic-ws-end js2-syntactic-ws-end
10305 c-syntactic-eol js2-syntactic-eol)
10307 (setq js2-default-externs
10308 (append js2-ecma-262-externs
10309 (if js2-include-browser-externs
10310 js2-browser-externs)
10311 (if js2-include-gears-externs
10313 (if js2-include-rhino-externs
10314 js2-rhino-externs)))
10316 ;; We do our own syntax highlighting based on the parse tree.
10317 ;; However, we want minor modes that add keywords to highlight properly
10318 ;; (examples: doxymacs, column-marker). We do this by not letting
10319 ;; font-lock unfontify anything, and telling it to fontify after we
10320 ;; re-parse and re-highlight the buffer. (We currently don't do any
10321 ;; work with regions other than the whole buffer.)
10322 (dolist (var '(font-lock-unfontify-buffer-function
10323 font-lock-unfontify-region-function))
10324 (set (make-local-variable var) (lambda (&rest args) t)))
10326 ;; Don't let font-lock do syntactic (string/comment) fontification.
10327 (set (make-local-variable #'font-lock-syntactic-face-function)
10328 (lambda (state) nil))
10330 ;; Experiment: make reparse-delay longer for longer files.
10331 (if (plusp js2-dynamic-idle-timer-adjust)
10332 (setq js2-idle-timer-delay
10333 (* js2-idle-timer-delay
10334 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10336 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10337 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10338 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10339 (imenu-add-to-menubar (concat "IM-" mode-name))
10340 (when js2-mirror-mode
10341 (js2-enter-mirror-mode))
10342 (add-to-invisibility-spec '(js2-outline . t))
10343 (set (make-local-variable 'line-move-ignore-invisible) t)
10344 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10345 (setq js2-mode-functions-hidden nil
10346 js2-mode-comments-hidden nil
10347 js2-mode-buffer-dirty-p t
10348 js2-mode-parsing nil)
10350 (run-hooks 'js2-mode-hook))
10352 (defun js2-mode-exit ()
10353 "Exit `js2-mode' and clean up."
10355 (when js2-mode-node-overlay
10356 (delete-overlay js2-mode-node-overlay)
10357 (setq js2-mode-node-overlay nil))
10358 (js2-remove-overlays)
10359 (setq js2-mode-ast nil)
10360 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10361 (remove-from-invisibility-spec '(js2-outline . t))
10362 (js2-mode-show-all)
10363 (js2-with-unmodifying-text-property-changes
10364 (js2-clear-face (point-min) (point-max))))
10366 (defun js2-before-save ()
10367 "Clean up whitespace before saving file.
10368 You can disable this by customizing `js2-cleanup-whitespace'."
10369 (when js2-cleanup-whitespace
10370 (let ((col (current-column)))
10371 (delete-trailing-whitespace)
10372 ;; don't change trailing whitespace on current line
10373 (unless (eq (current-column) col)
10374 (indent-to col)))))
10376 (defsubst js2-mode-reset-timer ()
10377 "Cancel any existing parse timer and schedule a new one."
10378 (if js2-mode-parse-timer
10379 (cancel-timer js2-mode-parse-timer))
10380 (setq js2-mode-parsing nil)
10381 (setq js2-mode-parse-timer
10382 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10384 (defun js2-mode-edit (beg end len)
10385 "Schedule a new parse after buffer is edited.
10386 Buffer edit spans from BEG to END and is of length LEN.
10387 Also clears the `js2-magic' bit on autoinserted parens/brackets
10388 if the edit occurred on a line different from the magic paren."
10389 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10390 (line (if magic-pos (line-number-at-pos magic-pos))))
10392 (or (/= (line-number-at-pos beg) line)
10394 (/= (line-number-at-pos end) line)))
10395 (js2-mode-mundanify-parens)))
10396 (setq js2-mode-buffer-dirty-p t)
10397 (js2-mode-hide-overlay)
10398 (js2-mode-reset-timer))
10400 (defun js2-mode-run-font-lock ()
10401 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10402 This is intended to allow modes that install their own font-lock keywords
10403 to work with js2-mode. In practice it never seems to work for long.
10404 Hopefully the Emacs maintainers can help figure out a way to make it work."
10405 (when (and (boundp 'font-lock-keywords)
10407 (boundp 'font-lock-mode)
10409 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10410 ;; play nicely with js2-mode. They go out of their way to fail to
10411 ;; provide any option for saying "look, fontify the farging buffer
10412 ;; with just the keywords already". Argh.
10413 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10414 (let (font-lock-verbose)
10415 (font-lock-fontify-buffer))))
10417 (defun js2-reparse (&optional force)
10418 "Re-parse current buffer after user finishes some data entry.
10419 If we get any user input while parsing, including cursor motion,
10420 we discard the parse and reschedule it. If FORCE is nil, then the
10421 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10424 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10425 (unless js2-mode-parsing
10426 (setq js2-mode-parsing t)
10428 (when (or js2-mode-buffer-dirty-p force)
10429 (js2-remove-overlays)
10430 (js2-with-unmodifying-text-property-changes
10431 (remove-text-properties (point-min) (point-max) '(syntax-table))
10432 (setq js2-mode-buffer-dirty-p nil
10433 js2-mode-fontifications nil
10434 js2-mode-deferred-properties nil
10435 js2-additional-externs nil)
10436 (if js2-mode-verbose-parse-p
10437 (message "parsing..."))
10440 (setq interrupted-p
10441 (catch 'interrupted
10442 (setq js2-mode-ast (js2-parse))
10443 (when (plusp js2-highlight-level)
10444 (js2-mode-fontify-regions))
10445 (js2-mode-remove-suppressed-warnings)
10446 (js2-mode-show-warnings)
10447 (js2-mode-show-errors)
10448 (js2-mode-run-font-lock) ; note: doesn't work
10449 (js2-mode-highlight-magic-parens)
10450 (if (>= js2-highlight-level 1)
10451 (js2-highlight-jsdoc js2-mode-ast))
10455 ;; unfinished parse => try again
10456 (setq js2-mode-buffer-dirty-p t)
10457 (js2-mode-reset-timer))
10458 (if js2-mode-verbose-parse-p
10459 (message "Parse time: %s" time)))))
10460 (setq js2-mode-parsing nil)
10461 (unless interrupted-p
10462 (setq js2-mode-parse-timer nil))))))
10464 (defun js2-mode-show-node ()
10465 "Debugging aid: highlight selected AST node on mouse click."
10467 (let ((node (js2-node-at-point))
10470 (when js2-mode-show-overlay
10472 (message "No node found at location %s" (point))
10473 (setq beg (js2-node-abs-pos node)
10474 end (+ beg (js2-node-len node)))
10475 (if js2-mode-node-overlay
10476 (move-overlay js2-mode-node-overlay beg end)
10477 (setq js2-mode-node-overlay (make-overlay beg end))
10478 (overlay-put js2-mode-node-overlay 'face 'highlight))
10479 (js2-with-unmodifying-text-property-changes
10480 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10481 (message "%s, parent: %s"
10482 (js2-node-short-name node)
10483 (if (js2-node-parent node)
10484 (js2-node-short-name (js2-node-parent node))
10487 (defun js2-mode-hide-overlay (&optional p1 p2)
10488 "Remove the debugging overlay when the point moves.
10489 P1 and P2 are the old and new values of point, respectively."
10490 (when js2-mode-node-overlay
10491 (let ((beg (overlay-start js2-mode-node-overlay))
10492 (end (overlay-end js2-mode-node-overlay)))
10493 ;; Sometimes we're called spuriously.
10497 (js2-with-unmodifying-text-property-changes
10498 (remove-text-properties beg end '(point-left nil)))
10499 (delete-overlay js2-mode-node-overlay)
10500 (setq js2-mode-node-overlay nil)))))
10502 (defun js2-mode-reset ()
10503 "Debugging helper: reset everything."
10508 (defsubst js2-mode-show-warn-or-err (e face)
10509 "Highlight a warning or error E with FACE.
10510 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10511 (let* ((key (first e))
10513 (end (+ beg (third e)))
10514 ;; Don't inadvertently go out of bounds.
10515 (beg (max (point-min) (min beg (point-max))))
10516 (end (max (point-min) (min end (point-max))))
10517 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10518 (ovl (make-overlay beg end)))
10519 (overlay-put ovl 'face face)
10520 (overlay-put ovl 'js2-error t)
10521 (put-text-property beg end 'help-echo (js2-get-msg key))
10522 (put-text-property beg end 'point-entered #'js2-echo-error)))
10524 (defun js2-remove-overlays ()
10525 "Remove overlays from buffer that have a `js2-error' property."
10526 (let ((beg (point-min))
10529 (dolist (o (overlays-in beg end))
10530 (when (overlay-get o 'js2-error)
10531 (delete-overlay o))))))
10533 (defun js2-error-at-point (&optional pos)
10534 "Return non-nil if there's an error overlay at POS.
10535 Defaults to point."
10536 (loop with pos = (or pos (point))
10537 for o in (overlays-at pos)
10538 thereis (overlay-get o 'js2-error)))
10540 (defun js2-mode-fontify-regions ()
10541 "Apply fontifications recorded during parsing."
10542 ;; We defer clearing faces as long as possible to eliminate flashing.
10543 (js2-clear-face (point-min) (point-max))
10544 ;; have to reverse the recorded fontifications so that errors and
10545 ;; warnings overwrite the normal fontifications
10546 (dolist (f (nreverse js2-mode-fontifications))
10547 (put-text-property (first f) (second f) 'face (third f)))
10548 (setq js2-mode-fontifications nil)
10549 (dolist (p js2-mode-deferred-properties)
10550 (apply #'put-text-property p))
10551 (setq js2-mode-deferred-properties nil))
10553 (defun js2-mode-show-errors ()
10554 "Highlight syntax errors."
10555 (when js2-mode-show-parse-errors
10556 (dolist (e (js2-ast-root-errors js2-mode-ast))
10557 (js2-mode-show-warn-or-err e 'js2-error-face))))
10559 (defun js2-mode-remove-suppressed-warnings ()
10560 "Take suppressed warnings out of the AST warnings list.
10561 This ensures that the counts and `next-error' are correct."
10562 (setf (js2-ast-root-warnings js2-mode-ast)
10565 (let ((key (caar e)))
10567 (and (not js2-strict-trailing-comma-warning)
10568 (string-match "trailing\\.comma" key))
10569 (and (not js2-strict-cond-assign-warning)
10570 (string= key "msg.equal.as.assign"))
10571 (and js2-missing-semi-one-line-override
10572 (string= key "msg.missing.semi")
10573 (let* ((beg (second e))
10574 (node (js2-node-at-point beg))
10575 (fn (js2-mode-find-parent-fn node))
10576 (body (and fn (js2-function-node-body fn)))
10577 (lc (and body (js2-node-abs-pos body)))
10578 (rc (and lc (+ lc (js2-node-len body)))))
10583 (and (js2-same-line lc)
10584 (js2-same-line rc))))))))))
10585 (js2-ast-root-warnings js2-mode-ast))))
10587 (defun js2-mode-show-warnings ()
10588 "Highlight strict-mode warnings."
10589 (when js2-mode-show-strict-warnings
10590 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10591 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10593 (defun js2-echo-error (old-point new-point)
10594 "Called by point-motion hooks."
10595 (let ((msg (get-text-property new-point 'help-echo)))
10599 (defalias #'js2-echo-help #'js2-echo-error)
10601 (defun js2-enter-key ()
10602 "Handle user pressing the Enter key."
10604 (let ((parse-status (save-excursion
10605 (parse-partial-sexp (point-min) (point)))))
10607 ;; check if we're inside a string
10608 ((nth 3 parse-status)
10609 (js2-mode-split-string parse-status))
10610 ;; check if inside a block comment
10611 ((nth 4 parse-status)
10612 (js2-mode-extend-comment))
10614 ;; should probably figure out what the mode-map says we should do
10615 (if js2-indent-on-enter-key
10616 (let ((js2-bounce-indent-p nil))
10617 (js2-indent-line)))
10619 (if js2-enter-indents-newline
10620 (let ((js2-bounce-indent-p nil))
10621 (js2-indent-line)))))))
10623 (defun js2-mode-split-string (parse-status)
10624 "Turn a newline in mid-string into a string concatenation.
10625 PARSE-STATUS is as documented in `parse-partial-sexp'."
10626 (let* ((col (current-column))
10627 (quote-char (nth 3 parse-status))
10628 (quote-string (string quote-char))
10629 (string-beg (nth 8 parse-status))
10630 (indent (save-match-data
10633 (back-to-indentation)
10634 (if (looking-at "\\+")
10637 (goto-char string-beg)
10638 (if (looking-back "\\+\\s-+")
10639 (goto-char (match-beginning 0)))
10640 (current-column))))))
10641 (insert quote-char "\n")
10643 (insert "+ " quote-string)
10645 (insert quote-string)
10646 (backward-char 1))))
10648 (defun js2-mode-extend-comment ()
10649 "When inside a comment block, add comment prefix."
10650 (let (star single col first-line needs-close)
10652 (back-to-indentation)
10654 ((looking-at "\\*[^/]")
10656 col (current-column)))
10657 ((looking-at "/\\*")
10660 col (1+ (current-column))))
10663 col (current-column)))))
10664 ;; Heuristic for whether we need to close the comment:
10665 ;; if we've got a parse error here, assume it's an unterminated
10669 (eq (get-text-property (1- (point)) 'point-entered)
10671 ;; The heuristic above doesn't work well when we're
10672 ;; creating a comment and there's another one downstream,
10673 ;; as our parser thinks this one ends at the end of the
10674 ;; next one. (You can have a /* inside a js block comment.)
10675 ;; So just close it if the next non-ws char isn't a *.
10679 (skip-chars-forward " \t\r\n")
10680 (not (eq (char-after) ?*))))))
10686 (if (and first-line needs-close)
10692 (when (save-excursion
10693 (and (zerop (forward-line 1))
10694 (looking-at "\\s-*//")))
10696 (insert "// "))))))
10698 (defun js2-beginning-of-line ()
10699 "Toggles point between bol and first non-whitespace char in line.
10700 Also moves past comment delimiters when inside comments."
10705 (back-to-indentation))
10707 (skip-chars-forward "/ \t"))
10708 ((and (eq (char-after) ?*)
10709 (setq node (js2-comment-at-point))
10710 (memq (js2-comment-node-format node) '(jsdoc block))
10712 (skip-chars-backward " \t")
10714 (skip-chars-forward "\* \t"))
10716 (goto-char (point-at-bol))))))
10718 (defun js2-end-of-line ()
10719 "Toggles point between eol and last non-whitespace char in line."
10722 (skip-chars-backward " \t")
10723 (goto-char (point-at-eol))))
10725 (defun js2-enter-mirror-mode()
10726 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10729 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10730 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10731 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10732 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10733 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10734 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10735 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10736 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10738 (defun js2-leave-mirror-mode()
10739 "Turns off mirror mode."
10741 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10742 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10744 (defsubst js2-mode-inside-string ()
10745 "Return non-nil if inside a string.
10746 Actually returns the quote character that begins the string."
10747 (let ((parse-state (save-excursion
10748 (parse-partial-sexp (point-min) (point)))))
10749 (nth 3 parse-state)))
10751 (defsubst js2-mode-inside-comment-or-string ()
10752 "Return non-nil if inside a comment or string."
10754 (let ((comment-start
10756 (goto-char (point-at-bol))
10757 (if (re-search-forward "//" (point-at-eol) t)
10758 (match-beginning 0)))))
10760 (<= comment-start (point))))
10761 (let ((parse-state (save-excursion
10762 (parse-partial-sexp (point-min) (point)))))
10763 (or (nth 3 parse-state)
10764 (nth 4 parse-state)))))
10766 (defsubst js2-make-magic-delimiter (delim &optional pos)
10767 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10768 Sets value of `js2-magic' text property to line number at POS."
10770 'js2-magic (line-number-at-pos pos)
10771 'face 'js2-magic-paren-face))
10773 (defun js2-mode-match-delimiter (open close)
10774 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10775 The rule we use, which as far as we can tell is how Eclipse works,
10776 is that we insert the match if we're not in a comment or string,
10777 and the next non-whitespace character is either punctuation or
10778 occurs on another line."
10780 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10781 (not (js2-mode-inside-comment-or-string)))
10783 (insert (js2-make-magic-delimiter close)))
10784 (when js2-auto-indent-p
10785 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10786 (js2-indent-line)))))
10788 (defun js2-mode-match-bracket ()
10789 "Insert matching bracket."
10791 (js2-mode-match-delimiter "[" "]"))
10793 (defun js2-mode-match-paren ()
10794 "Insert matching paren unless already inserted."
10796 (js2-mode-match-delimiter "(" ")"))
10798 (defun js2-mode-match-curly (arg)
10799 "Insert matching curly-brace.
10800 With prefix arg, no formatting or indentation will occur -- the close-brace
10801 is simply inserted directly at the point."
10805 (current-prefix-arg
10806 (js2-mode-match-delimiter "{" "}"))
10807 ((and js2-auto-insert-catch-block
10808 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10810 (match-beginning 1))))
10811 (js2-insert-catch-skel try-pos))
10813 ;; Otherwise try to do something smarter.
10815 (unless (or (not (looking-at "\\s-*$"))
10817 (skip-chars-forward " \t\r\n")
10818 (and (looking-at "}")
10819 (js2-error-at-point)))
10820 (js2-mode-inside-comment-or-string))
10822 ;; absolutely mystifying bug: when inserting the next "\n",
10823 ;; the buffer-undo-list is given two new entries: the inserted range,
10824 ;; and the incorrect position of the point. It's recorded incorrectly
10825 ;; as being before the opening "{", not after it. But it's recorded
10826 ;; as the correct value if you're debugging `js2-mode-match-curly'
10827 ;; in edebug. I have no idea why it's doing this, but incrementing
10828 ;; the inserted position fixes the problem, so that the undo takes us
10829 ;; back to just after the user-inserted "{".
10832 (incf (cadr buffer-undo-list)))
10836 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10837 (js2-indent-line))))))))
10839 (defun js2-insert-catch-skel (try-pos)
10840 "Complete a try/catch block after inserting a { following a try keyword.
10841 Rationale is that a try always needs a catch or a finally, and the catch is
10842 the more likely of the two.
10844 TRY-POS is the buffer position of the try keyword. The open-curly should
10845 already have been inserted."
10847 (let ((try-col (save-excursion
10848 (goto-char try-pos)
10849 (current-column))))
10852 (js2-indent-line) ;; indent the blank line where cursor will end up
10855 (indent-to try-col)
10856 (insert "} catch (x) {\n\n")
10857 (indent-to try-col)
10860 (defun js2-mode-highlight-magic-parens ()
10861 "Re-highlight magic parens after parsing nukes the 'face prop."
10862 (let ((beg (point-min))
10864 (while (setq beg (next-single-property-change beg 'js2-magic))
10865 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10866 (if (get-text-property beg 'js2-magic)
10867 (js2-with-unmodifying-text-property-changes
10868 (put-text-property beg (or end (1+ beg))
10869 'face 'js2-magic-paren-face))))))
10871 (defun js2-mode-mundanify-parens ()
10872 "Clear all magic parens and brackets."
10873 (let ((beg (point-min))
10875 (while (setq beg (next-single-property-change beg 'js2-magic))
10876 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10877 (remove-text-properties beg (or end (1+ beg))
10878 '(js2-magic face)))))
10880 (defsubst js2-match-quote (quote-string)
10881 (let ((start-quote (js2-mode-inside-string)))
10883 ;; inside a comment - don't do quote-matching, since we can't
10884 ;; reliably figure out if we're in a string inside the comment
10885 ((js2-comment-at-point)
10886 (insert quote-string))
10888 ;; not in string => insert matched quotes
10889 (insert quote-string)
10890 ;; exception: if we're just before a word, don't double it.
10891 (unless (looking-at "[^ \t\r\n]")
10893 (insert quote-string))))
10894 ((looking-at quote-string)
10895 (if (looking-back "[^\\]\\\\")
10896 (insert quote-string)
10898 ((and js2-mode-escape-quotes
10901 (re-search-forward quote-string (point-at-eol) t))))
10902 ;; inside terminated string, escape quote (unless already escaped)
10903 (insert (if (looking-back "[^\\]\\\\")
10905 (concat "\\" quote-string))))
10907 (insert quote-string))))) ; else terminate the string
10909 (defun js2-mode-match-single-quote ()
10910 "Insert matching single-quote."
10912 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10913 ;; don't match inside comments, since apostrophe is more common
10914 (if (nth 4 parse-status)
10916 (js2-match-quote "'"))))
10918 (defun js2-mode-match-double-quote ()
10919 "Insert matching double-quote."
10921 (js2-match-quote "\""))
10923 ;; Eclipse works as follows:
10924 ;; * type an open-paren and it auto-inserts close-paren
10925 ;; - auto-inserted paren gets a green bracket
10926 ;; - green bracket means typing close-paren there will skip it
10927 ;; * if you insert any text on a different line, it turns off
10928 (defun js2-mode-magic-close-paren ()
10929 "Skip over close-paren rather than inserting, where appropriate."
10931 (let* ((here (point))
10932 (parse-status (parse-partial-sexp (point-min) here))
10933 (open-pos (nth 1 parse-status))
10934 (close last-input-event)
10943 (if (and (eq (char-after) close)
10944 (eq open (char-after open-pos))
10945 (js2-same-line open-pos)
10946 (get-text-property here 'js2-magic))
10948 (remove-text-properties here (1+ here) '(js2-magic face))
10950 (insert-char close 1))
10951 (blink-matching-open)))
10953 (defun js2-mode-wait-for-parse (callback)
10954 "Invoke CALLBACK when parsing is finished.
10955 If parsing is already finished, calls CALLBACK immediately."
10956 (if (not js2-mode-buffer-dirty-p)
10958 (push callback js2-mode-pending-parse-callbacks)
10959 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10961 (defun js2-mode-parse-finished ()
10962 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10963 ;; We can't let errors propagate up, since it prevents the
10964 ;; `js2-parse' method from completing normally and returning
10965 ;; the ast, which makes things mysteriously not work right.
10967 (dolist (cb js2-mode-pending-parse-callbacks)
10968 (condition-case err
10970 (error (message "%s" err))))
10971 (setq js2-mode-pending-parse-callbacks nil)))
10973 (defun js2-mode-flag-region (from to flag)
10974 "Hide or show text from FROM to TO, according to FLAG.
10975 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10976 Returns the created overlay if FLAG is non-nil."
10977 (remove-overlays from to 'invisible 'js2-outline)
10979 (let ((o (make-overlay from to)))
10980 (overlay-put o 'invisible 'js2-outline)
10981 (overlay-put o 'isearch-open-invisible
10982 'js2-isearch-open-invisible)
10985 ;; Function to be set as an outline-isearch-open-invisible' property
10986 ;; to the overlay that makes the outline invisible (see
10987 ;; `js2-mode-flag-region').
10988 (defun js2-isearch-open-invisible (overlay)
10989 ;; We rely on the fact that isearch places point on the matched text.
10990 (js2-mode-show-element))
10992 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10993 "Return cons cell of bounds of folding overlay at POS.
10994 Returns nil if not found."
10995 (let ((overlays (overlays-at (or pos (point))))
10997 (while (and overlays
10999 (if (overlay-get (car overlays) 'invisible)
11000 (setq o (car overlays))
11001 (setq overlays (cdr overlays))))
11003 (cons (overlay-start o) (overlay-end o)))))
11005 (defun js2-mode-function-at-point (&optional pos)
11006 "Return the innermost function node enclosing current point.
11007 Returns nil if point is not in a function."
11008 (let ((node (js2-node-at-point pos)))
11009 (while (and node (not (js2-function-node-p node)))
11010 (setq node (js2-node-parent node)))
11011 (if (js2-function-node-p node)
11014 (defun js2-mode-toggle-element ()
11015 "Hide or show the foldable element at the point."
11017 (let (comment fn pos)
11021 ;; /* ... */ comment?
11022 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11023 (if (js2-mode-invisible-overlay-bounds
11024 (setq pos (+ 3 (js2-node-abs-pos comment))))
11027 (js2-mode-show-element))
11028 (js2-mode-hide-element)))
11031 (back-to-indentation)
11032 (looking-at js2-mode-//-comment-re))
11033 (js2-mode-toggle-//-comment))
11035 ((setq fn (js2-mode-function-at-point))
11036 (setq pos (and (js2-function-node-body fn)
11037 (js2-node-abs-pos (js2-function-node-body fn))))
11038 (goto-char (1+ pos))
11039 (if (js2-mode-invisible-overlay-bounds)
11040 (js2-mode-show-element)
11041 (js2-mode-hide-element)))
11043 (message "Nothing at point to hide or show")))))))
11045 (defun js2-mode-hide-element ()
11046 "Fold/hide contents of a block, showing ellipses.
11047 Show the hidden text with \\[js2-mode-show-element]."
11049 (if js2-mode-buffer-dirty-p
11050 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11051 (let (node body beg end)
11053 ((js2-mode-invisible-overlay-bounds)
11054 (message "already hidden"))
11056 (setq node (js2-node-at-point))
11058 ((js2-block-comment-p node)
11059 (js2-mode-hide-comment node))
11061 (while (and node (not (js2-function-node-p node)))
11062 (setq node (js2-node-parent node)))
11064 (setq body (js2-function-node-body node)))
11066 (setq beg (js2-node-abs-pos body)
11067 end (+ beg (js2-node-len body)))
11068 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11069 (message "No collapsable element found at point"))))))))
11071 (defun js2-mode-show-element ()
11072 "Show the hidden element at current point."
11074 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11076 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11077 (message "Nothing to un-hide"))))
11079 (defun js2-mode-show-all ()
11080 "Show all of the text in the buffer."
11082 (js2-mode-flag-region (point-min) (point-max) nil))
11084 (defun js2-mode-toggle-hide-functions ()
11086 (if js2-mode-functions-hidden
11087 (js2-mode-show-functions)
11088 (js2-mode-hide-functions)))
11090 (defun js2-mode-hide-functions ()
11091 "Hides all non-nested function bodies in the buffer.
11092 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11093 to open an individual entry."
11095 (if js2-mode-buffer-dirty-p
11096 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11097 (if (null js2-mode-ast)
11098 (message "Oops - parsing failed")
11099 (setq js2-mode-functions-hidden t)
11100 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11102 (defun js2-mode-function-hider (n endp)
11104 (let ((tt (js2-node-type n))
11107 ((and (= tt js2-FUNCTION)
11108 (setq body (js2-function-node-body n)))
11109 (setq beg (js2-node-abs-pos body)
11110 end (+ beg (js2-node-len body)))
11111 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11112 nil) ; don't process children of function
11114 t))))) ; keep processing other AST nodes
11116 (defun js2-mode-show-functions ()
11117 "Un-hide any folded function bodies in the buffer."
11119 (setq js2-mode-functions-hidden nil)
11121 (goto-char (point-min))
11122 (while (/= (goto-char (next-overlay-change (point)))
11124 (dolist (o (overlays-at (point)))
11125 (when (and (overlay-get o 'invisible)
11126 (not (overlay-get o 'comment)))
11127 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11129 (defun js2-mode-hide-comment (n)
11130 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11133 (beg (+ (js2-node-abs-pos n) head))
11134 (end (- (+ beg (js2-node-len n)) head 2))
11135 (o (js2-mode-flag-region beg end 'hide)))
11136 (overlay-put o 'comment t)))
11138 (defun js2-mode-toggle-hide-comments ()
11139 "Folds all block comments in the buffer.
11140 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11141 to open an individual entry."
11143 (if js2-mode-comments-hidden
11144 (js2-mode-show-comments)
11145 (js2-mode-hide-comments)))
11147 (defun js2-mode-hide-comments ()
11149 (if js2-mode-buffer-dirty-p
11150 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11151 (if (null js2-mode-ast)
11152 (message "Oops - parsing failed")
11153 (setq js2-mode-comments-hidden t)
11154 (dolist (n (js2-ast-root-comments js2-mode-ast))
11155 (let ((format (js2-comment-node-format n)))
11156 (when (js2-block-comment-p n)
11157 (js2-mode-hide-comment n))))
11158 (js2-mode-hide-//-comments)))
11160 (defsubst js2-mode-extend-//-comment (direction)
11161 "Find start or end of a block of similar //-comment lines.
11162 DIRECTION is -1 to look back, 1 to look forward.
11163 INDENT is the indentation level to match.
11164 Returns the end-of-line position of the furthest adjacent
11165 //-comment line with the same indentation as the current line.
11166 If there is no such matching line, returns current end of line."
11167 (let ((pos (point-at-eol))
11168 (indent (current-indentation)))
11171 (while (and (zerop (forward-line direction))
11172 (looking-at js2-mode-//-comment-re)
11173 (eq indent (length (match-string 1))))
11174 (setq pos (point-at-eol)))
11177 (defun js2-mode-hide-//-comments ()
11178 "Fold adjacent 1-line comments, showing only snippet of first one."
11182 (goto-char (point-min))
11183 (while (re-search-forward js2-mode-//-comment-re nil t)
11185 end (js2-mode-extend-//-comment 1))
11186 (unless (eq beg end)
11187 (overlay-put (js2-mode-flag-region beg end 'hide)
11190 (forward-char 1))))))
11192 (defun js2-mode-toggle-//-comment ()
11193 "Fold or un-fold any multi-line //-comment at point.
11194 Caller should have determined that this line starts with a //-comment."
11195 (let* ((beg (point-at-eol))
11199 (if (js2-mode-invisible-overlay-bounds)
11200 (js2-mode-show-element)
11201 ;; else hide the comment
11202 (setq beg (js2-mode-extend-//-comment -1)
11203 end (js2-mode-extend-//-comment 1))
11204 (unless (eq beg end)
11205 (overlay-put (js2-mode-flag-region beg end 'hide)
11208 (defun js2-mode-show-comments ()
11209 "Un-hide any hidden comments, leaving other hidden elements alone."
11211 (setq js2-mode-comments-hidden nil)
11213 (goto-char (point-min))
11214 (while (/= (goto-char (next-overlay-change (point)))
11216 (dolist (o (overlays-at (point)))
11217 (when (overlay-get o 'comment)
11218 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11220 (defun js2-mode-display-warnings-and-errors ()
11221 "Turn on display of warnings and errors."
11223 (setq js2-mode-show-parse-errors t
11224 js2-mode-show-strict-warnings t)
11225 (js2-reparse 'force))
11227 (defun js2-mode-hide-warnings-and-errors ()
11228 "Turn off display of warnings and errors."
11230 (setq js2-mode-show-parse-errors nil
11231 js2-mode-show-strict-warnings nil)
11232 (js2-reparse 'force))
11234 (defun js2-mode-toggle-warnings-and-errors ()
11235 "Toggle the display of warnings and errors.
11236 Some users don't like having warnings/errors reported while they type."
11238 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11239 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11240 (if (interactive-p)
11241 (message "warnings and errors %s"
11242 (if js2-mode-show-parse-errors
11245 (js2-reparse 'force))
11247 (defun js2-mode-customize ()
11249 (customize-group 'js2-mode))
11251 (defun js2-mode-forward-sexp (&optional arg)
11252 "Move forward across one statement or balanced expression.
11253 With ARG, do it that many times. Negative arg -N means
11254 move backward across N balanced expressions."
11256 (setq arg (or arg 1))
11257 (if js2-mode-buffer-dirty-p
11258 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11259 (let (node end (start (point)))
11262 ;; could probably make this better for some cases:
11263 ;; - if in statement block (e.g. function body), go to parent
11264 ;; - infix exprs like (foo in bar) - maybe go to beginning
11265 ;; of infix expr if in the right-side expression?
11266 ((and arg (minusp arg))
11267 (dotimes (i (- arg))
11269 (forward-char -1) ; enter the node we backed up to
11270 (setq node (js2-node-at-point (point) t))
11271 (goto-char (if node
11272 (js2-node-abs-pos node)
11279 (setq node (js2-node-at-point (point) t)
11280 end (if node (+ (js2-node-abs-pos node)
11281 (js2-node-len node))))
11282 (goto-char (or end (point-max))))))))
11284 (defun js2-next-error (&optional arg reset)
11285 "Move to next parse error.
11286 Typically invoked via \\[next-error].
11287 ARG is the number of errors, forward or backward, to move.
11288 RESET means start over from the beginning."
11290 (if (or (null js2-mode-ast)
11291 (and (null (js2-ast-root-errors js2-mode-ast))
11292 (null (js2-ast-root-warnings js2-mode-ast))))
11293 (message "No errors")
11295 (goto-char (point-min)))
11296 (let* ((errs (copy-sequence
11297 (append (js2-ast-root-errors js2-mode-ast)
11298 (js2-ast-root-warnings js2-mode-ast))))
11302 (backward (minusp count))
11303 (sorter (if backward '> '<))
11304 (stopper (if backward '< '>))
11305 (count (abs count))
11308 ;; sort by start position
11309 (setq errs (sort errs (lambda (e1 e2)
11310 (funcall sorter (second e1) (second e2))))
11312 ;; find nth error with pos > start
11313 (while (and errs continue)
11314 (when (funcall stopper (cadar errs) start)
11315 (setq err (car errs))
11316 (if (zerop (decf count))
11317 (setq continue nil)))
11318 (setq errs (cdr errs)))
11320 (goto-char (second err))
11321 ;; wrap around to first error
11322 (goto-char (second (car all-errs)))
11323 ;; if we were already on it, echo msg again
11324 (if (= (point) start)
11325 (js2-echo-error (point) (point)))))))
11327 (defun js2-down-mouse-3 ()
11328 "Make right-click move the point to the click location.
11329 This makes right-click context menu operations a bit more intuitive.
11330 The point will not move if the region is active, however, to avoid
11331 destroying the region selection."
11333 (when (and js2-move-point-on-right-click
11335 (let ((e last-input-event))
11337 (goto-char (cadadr e))))))
11339 (defun js2-mode-create-imenu-index ()
11340 "Return an alist for `imenu--index-alist'."
11341 ;; This is built up in `js2-parse-record-imenu' during parsing.
11343 ;; if we have an ast but no recorder, they're requesting a rescan
11344 (unless js2-imenu-recorder
11345 (js2-reparse 'force))
11347 (js2-build-imenu-index)
11348 (setq js2-imenu-recorder nil
11349 js2-imenu-function-map nil))))
11351 (defun js2-mode-find-tag ()
11352 "Replacement for `find-tag-default'.
11353 `find-tag-default' returns a ridiculous answer inside comments."
11355 (js2-with-underscore-as-word-syntax
11357 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11358 (looking-back "[A-Za-z0-9_$]"))
11359 (setq beg (progn (forward-word -1) (point))
11360 end (progn (forward-word 1) (point)))
11361 (setq beg (progn (forward-word 1) (point))
11362 end (progn (forward-word -1) (point))))
11363 (replace-regexp-in-string
11365 (buffer-substring-no-properties beg end))))))
11367 (defun js2-mode-forward-sibling ()
11368 "Move to the end of the sibling following point in parent.
11369 Returns non-nil if successful, or nil if there was no following sibling."
11370 (let* ((node (js2-node-at-point))
11371 (parent (js2-mode-find-enclosing-fn node))
11373 (when (setq sib (js2-node-find-child-after (point) parent))
11374 (goto-char (+ (js2-node-abs-pos sib)
11375 (js2-node-len sib))))))
11377 (defun js2-mode-backward-sibling ()
11378 "Move to the beginning of the sibling node preceding point in parent.
11379 Parent is defined as the enclosing script or function."
11380 (let* ((node (js2-node-at-point))
11381 (parent (js2-mode-find-enclosing-fn node))
11383 (when (setq sib (js2-node-find-child-before (point) parent))
11384 (goto-char (js2-node-abs-pos sib)))))
11386 (defun js2-beginning-of-defun ()
11387 "Go to line on which current function starts, and return non-nil.
11388 If we're not in a function, go to beginning of previous script-level element."
11390 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11393 ((and (js2-function-node-p parent)
11394 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11397 (js2-mode-backward-sibling)))))
11399 (defun js2-end-of-defun ()
11400 "Go to the char after the last position of the current function.
11401 If we're not in a function, skips over the next script-level element."
11403 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11404 (if (not (js2-function-node-p parent))
11405 ;; punt: skip over next script-level element beyond point
11406 (js2-mode-forward-sibling)
11407 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11408 (js2-node-len parent)))))))
11410 (defun js2-mark-defun (&optional allow-extend)
11411 "Put mark at end of this function, point at beginning.
11412 The function marked is the one that contains point.
11414 Interactively, if this command is repeated,
11415 or (in Transient Mark mode) if the mark is active,
11416 it marks the next defun after the ones already marked."
11419 (when (and allow-extend
11420 (or (and (eq last-command this-command) (mark t))
11421 (and transient-mark-mode mark-active)))
11422 (let ((sib (save-excursion
11424 (if (js2-mode-forward-sibling)
11431 ;; no more siblings - try extending to enclosing node
11432 (goto-char (mark t)))))
11433 (when (not extended)
11434 (let ((node (js2-node-at-point (point) t)) ; skip comments
11435 ast fn stmt parent beg end)
11436 (when (js2-ast-root-p node)
11438 node (or (js2-node-find-child-after (point) node)
11439 (js2-node-find-child-before (point) node))))
11440 ;; only mark whole buffer if we can't find any children
11443 (if (js2-function-node-p node)
11445 (setq fn (js2-mode-find-enclosing-fn node)
11446 stmt (if (or (null fn)
11447 (js2-ast-root-p fn))
11448 (js2-mode-find-first-stmt node))
11449 parent (or stmt fn)))
11450 (setq beg (js2-node-abs-pos parent)
11451 end (+ beg (js2-node-len parent)))
11454 (exchange-point-and-mark)))))
11456 (defun js2-narrow-to-defun ()
11457 "Narrow to the function enclosing point."
11459 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11460 (fn (if (js2-script-node-p node)
11462 (js2-mode-find-enclosing-fn node)))
11463 (beg (js2-node-abs-pos fn)))
11464 (unless (js2-ast-root-p fn)
11465 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11467 (provide 'js2-mode)
11469 ;;; js2-mode.el ends here