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 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This JavaScript editing mode supports:
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
71 (require 'cc-cmds) ; for `c-fill-paragraph'
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
78 ;;; Externs (variables presumed to be defined by the host system)
80 (defvar js2-ecma-262-externs
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
90 (defvar js2-browser-externs
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
129 window alert confirm document java navigator prompt screen
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
147 DocumentRange Range RangeException
150 XPathResult XMLHttpRequest))
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
155 (defvar js2-rhino-externs
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
165 (defvar js2-gears-externs
168 ;; TODO(stevey): add these
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
175 (defvar js2-emacs22 (>= emacs-major-version 22))
177 (defcustom js2-highlight-level 2
178 "Amount of syntax highlighting to perform.
179 0 or a negative value means do no highlighting.
180 1 adds basic syntax highlighting.
181 2 adds highlighting of some Ecma built-in properties.
182 3 adds highlighting of many Ecma built-in functions."
184 :type '(choice (const :tag "None" 0)
185 (const :tag "Basic" 1)
186 (const :tag "Include Properties" 2)
187 (const :tag "Include Functions" 3)))
189 (defvar js2-mode-dev-mode-p nil
190 "Non-nil if running in development mode. Normally nil.")
192 (defgroup js2-mode nil
193 "An improved JavaScript mode."
196 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
197 (numberp c-basic-offset))
200 "Number of spaces to indent nested statements.
201 Similar to `c-basic-offset'."
204 (make-variable-buffer-local 'js2-basic-offset)
206 ;; TODO(stevey): move this code into a separate minor mode.
207 (defcustom js2-mirror-mode nil
208 "Non-nil to insert closing brackets, parens, etc. automatically."
212 (defcustom js2-auto-indent-p nil
213 "Automatic indentation with punctuation characters.
214 If non-nil, the current line is indented when certain punctuations
219 (defcustom js2-bounce-indent-p nil
220 "Non-nil to have indent-line function choose among alternatives.
221 If nil, the indent-line function will indent to a predetermined column
222 based on heuristic guessing. If non-nil, then if the current line is
223 already indented to that predetermined column, indenting will choose
224 another likely column and indent to that spot. Repeated invocation of
225 the indent-line function will cycle among the computed alternatives.
226 See the function `js2-bounce-indent' for details."
230 (defcustom js2-consistent-level-indent-inner-bracket-p t
231 "Non-nil to make indentation level inner bracket consistent,
232 regardless of the beginning bracket position."
236 (defcustom js2-use-ast-for-indentation-p nil
237 "Non-nil to use AST for indentation and make it more robust."
241 (defcustom js2-indent-on-enter-key nil
242 "Non-nil to have Enter/Return key indent the line.
243 This is unusual for Emacs modes but common in IDEs like Eclipse."
247 (defcustom js2-enter-indents-newline nil
248 "Non-nil to have Enter/Return key indent the newly-inserted line.
249 This is unusual for Emacs modes but common in IDEs like Eclipse."
253 (defcustom js2-rebind-eol-bol-keys t
254 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
255 If non-nil, bounce between bol/eol and first/last non-whitespace char."
259 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
260 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
261 Each value in the list is passed to `define-key'."
265 (defcustom js2-idle-timer-delay 0.2
266 "Delay in secs before re-parsing after user makes changes.
267 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
270 (make-variable-buffer-local 'js2-idle-timer-delay)
272 (defcustom js2-dynamic-idle-timer-adjust 0
273 "Positive to adjust `js2-idle-timer-delay' based on file size.
274 The idea is that for short files, parsing is faster so we can be
275 more responsive to user edits without interfering with editing.
276 The buffer length in characters (typically bytes) is divided by
277 this value and used to multiply `js2-idle-timer-delay' for the
278 buffer. For example, a 21k file and 10k adjust yields 21k/10k
279 == 2, so js2-idle-timer-delay is multiplied by 2.
280 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
281 `js2-idle-timer-delay' is not dependent on the file size."
285 (defcustom js2-mode-escape-quotes t
286 "Non-nil to disable automatic quote-escaping inside strings."
290 (defcustom js2-mode-squeeze-spaces t
291 "Non-nil to normalize whitespace when filling in comments.
292 Multiple runs of spaces are converted to a single space."
296 (defcustom js2-mode-show-parse-errors t
297 "True to highlight parse errors."
301 (defcustom js2-mode-show-strict-warnings t
302 "Non-nil to emit Ecma strict-mode warnings.
303 Some of the warnings can be individually disabled by other flags,
304 even if this flag is non-nil."
308 (defcustom js2-strict-trailing-comma-warning t
309 "Non-nil to warn about trailing commas in array literals.
310 Ecma-262 forbids them, but many browsers permit them. IE is the
311 big exception, and can produce bugs if you have trailing commas."
315 (defcustom js2-strict-missing-semi-warning t
316 "Non-nil to warn about semicolon auto-insertion after statement.
317 Technically this is legal per Ecma-262, but some style guides disallow
322 (defcustom js2-missing-semi-one-line-override nil
323 "Non-nil to permit missing semicolons in one-line functions.
324 In one-liner functions such as `function identity(x) {return x}'
325 people often omit the semicolon for a cleaner look. If you are
326 such a person, you can suppress the missing-semicolon warning
327 by setting this variable to t."
331 (defcustom js2-strict-inconsistent-return-warning t
332 "Non-nil to warn about mixing returns with value-returns.
333 It's perfectly legal to have a `return' and a `return foo' in the
334 same function, but it's often an indicator of a bug, and it also
335 interferes with type inference (in systems that support it.)"
339 (defcustom js2-strict-cond-assign-warning t
340 "Non-nil to warn about expressions like if (a = b).
341 This often should have been '==' instead of '='. If the warning
342 is enabled, you can suppress it on a per-expression basis by
343 parenthesizing the expression, e.g. if ((a = b)) ..."
347 (defcustom js2-strict-cond-assign-warning t
348 "Non-nil to warn about expressions like if (a = b).
349 This often should have been '==' instead of '='. If the warning
350 is enabled, you can suppress it on a per-expression basis by
351 parenthesizing the expression, e.g. if ((a = b)) ..."
355 (defcustom js2-strict-var-redeclaration-warning t
356 "Non-nil to warn about redeclaring variables in a script or function."
360 (defcustom js2-strict-var-hides-function-arg-warning t
361 "Non-nil to warn about a var decl hiding a function argument."
365 (defcustom js2-skip-preprocessor-directives nil
366 "Non-nil to treat lines beginning with # as comments.
367 Useful for viewing Mozilla JavaScript source code."
371 (defcustom js2-language-version 180
372 "Configures what JavaScript language version to recognize.
373 Currently versions 150, 160, 170 and 180 are supported, corresponding
374 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
375 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
376 and 1.8 adds function closures."
380 (defcustom js2-allow-keywords-as-property-names t
381 "If non-nil, you can use JavaScript keywords as object property names.
384 var foo = {int: 5, while: 6, continue: 7};
387 Ecma-262 forbids this syntax, but many browsers support it."
391 (defcustom js2-instanceof-has-side-effects nil
392 "If non-nil, treats the instanceof operator as having side effects.
393 This is useful for xulrunner apps."
397 (defcustom js2-cleanup-whitespace nil
398 "Non-nil to invoke `delete-trailing-whitespace' before saves."
402 (defcustom js2-move-point-on-right-click t
403 "Non-nil to move insertion point when you right-click.
404 This makes right-click context menu behavior a bit more intuitive,
405 since menu operations generally apply to the point. The exception
406 is if there is a region selection, in which case the point does -not-
407 move, so cut/copy/paste etc. can work properly.
409 Note that IntelliJ moves the point, and Eclipse leaves it alone,
410 so this behavior is customizable."
414 (defcustom js2-allow-rhino-new-expr-initializer t
415 "Non-nil to support a Rhino's experimental syntactic construct.
417 Rhino supports the ability to follow a `new' expression with an object
418 literal, which is used to set additional properties on the new object
419 after calling its constructor. Syntax:
421 new <expr> [ ( arglist ) ] [initializer]
423 Hence, this expression:
425 new Object {a: 1, b: 2}
427 results in an Object with properties a=1 and b=2. This syntax is
428 apparently not configurable in Rhino - it's currently always enabled,
429 as of Rhino version 1.7R2."
433 (defcustom js2-allow-member-expr-as-function-name nil
434 "Non-nil to support experimental Rhino syntax for function names.
436 Rhino supports an experimental syntax configured via the Rhino Context
437 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
439 function <member-expr> ( [ arg-list ] ) { <body> }
441 Where member-expr is a non-parenthesized 'member expression', which
442 is anything at the grammar level of a new-expression or lower, meaning
443 any expression that does not involve infix or unary operators.
445 When <member-expr> is not a simple identifier, then it is syntactic
446 sugar for assigning the anonymous function to the <member-expr>. Hence,
449 function a.b().c[2] (x, y) { ... }
453 a.b().c[2] = function(x, y) {...}
455 which doesn't seem particularly useful, but Rhino permits it."
459 (defvar js2-mode-version 20101228
460 "Release number for `js2-mode'.")
464 (defmacro js2-deflocal (name value &optional comment)
465 "Define a buffer-local variable NAME with VALUE and COMMENT."
467 (defvar ,name ,value ,comment)
468 (make-variable-buffer-local ',name)))
470 ;; We record the start and end position of each token.
471 (js2-deflocal js2-token-beg 1)
472 (js2-deflocal js2-token-end -1)
474 (defvar js2-EOF_CHAR -1
475 "Represents end of stream. Distinct from js2-EOF token type.")
477 ;; I originally used symbols to represent tokens, but Rhino uses
478 ;; ints and then sets various flag bits in them, so ints it is.
479 ;; The upshot is that we need a `js2-' prefix in front of each name.
480 (defvar js2-ERROR -1)
483 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
484 (defvar js2-LEAVEWITH 3)
485 (defvar js2-RETURN 4)
489 (defvar js2-SETNAME 8)
491 (defvar js2-BITXOR 10)
492 (defvar js2-BITAND 11)
502 (defvar js2-ADD 21) ; infix plus
503 (defvar js2-SUB 22) ; infix minus
508 (defvar js2-BITNOT 27)
509 (defvar js2-POS 28) ; unary plus
510 (defvar js2-NEG 29) ; unary minus
512 (defvar js2-DELPROP 31)
513 (defvar js2-TYPEOF 32)
514 (defvar js2-GETPROP 33)
515 (defvar js2-GETPROPNOWARN 34)
516 (defvar js2-SETPROP 35)
517 (defvar js2-GETELEM 36)
518 (defvar js2-SETELEM 37)
520 (defvar js2-NAME 39) ; an identifier
521 (defvar js2-NUMBER 40)
522 (defvar js2-STRING 41)
525 (defvar js2-FALSE 44)
527 (defvar js2-SHEQ 46) ; shallow equality (===)
528 (defvar js2-SHNE 47) ; shallow inequality (!==)
529 (defvar js2-REGEXP 48)
530 (defvar js2-BINDNAME 49)
531 (defvar js2-THROW 50)
532 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
534 (defvar js2-INSTANCEOF 53)
535 (defvar js2-LOCAL_LOAD 54)
536 (defvar js2-GETVAR 55)
537 (defvar js2-SETVAR 56)
538 (defvar js2-CATCH_SCOPE 57)
539 (defvar js2-ENUM_INIT_KEYS 58)
540 (defvar js2-ENUM_INIT_VALUES 59)
541 (defvar js2-ENUM_INIT_ARRAY 60)
542 (defvar js2-ENUM_NEXT 61)
543 (defvar js2-ENUM_ID 62)
544 (defvar js2-THISFN 63)
545 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
546 (defvar js2-ARRAYLIT 65) ; array literal
547 (defvar js2-OBJECTLIT 66) ; object literal
548 (defvar js2-GET_REF 67) ; *reference
549 (defvar js2-SET_REF 68) ; *reference = something
550 (defvar js2-DEL_REF 69) ; delete reference
551 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
552 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
553 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
556 (defvar js2-DEFAULTNAMESPACE 73)
557 (defvar js2-ESCXMLATTR 74)
558 (defvar js2-ESCXMLTEXT 75)
559 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
560 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
561 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
562 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
564 (defvar js2-first-bytecode js2-ENTERWITH)
565 (defvar js2-last-bytecode js2-REF_NS_NAME)
568 (defvar js2-SEMI 81) ; semicolon
569 (defvar js2-LB 82) ; left and right brackets
571 (defvar js2-LC 84) ; left and right curly-braces
573 (defvar js2-LP 86) ; left and right parens
575 (defvar js2-COMMA 88) ; comma operator
577 (defvar js2-ASSIGN 89) ; simple assignment (=)
578 (defvar js2-ASSIGN_BITOR 90) ; |=
579 (defvar js2-ASSIGN_BITXOR 91) ; ^=
580 (defvar js2-ASSIGN_BITAND 92) ; &=
581 (defvar js2-ASSIGN_LSH 93) ; <<=
582 (defvar js2-ASSIGN_RSH 94) ; >>=
583 (defvar js2-ASSIGN_URSH 95) ; >>>=
584 (defvar js2-ASSIGN_ADD 96) ; +=
585 (defvar js2-ASSIGN_SUB 97) ; -=
586 (defvar js2-ASSIGN_MUL 98) ; *=
587 (defvar js2-ASSIGN_DIV 99) ; /=
588 (defvar js2-ASSIGN_MOD 100) ; %=
590 (defvar js2-first-assign js2-ASSIGN)
591 (defvar js2-last-assign js2-ASSIGN_MOD)
593 (defvar js2-HOOK 101) ; conditional (?:)
594 (defvar js2-COLON 102)
595 (defvar js2-OR 103) ; logical or (||)
596 (defvar js2-AND 104) ; logical and (&&)
597 (defvar js2-INC 105) ; increment/decrement (++ --)
599 (defvar js2-DOT 107) ; member operator (.)
600 (defvar js2-FUNCTION 108) ; function keyword
601 (defvar js2-EXPORT 109) ; export keyword
602 (defvar js2-IMPORT 110) ; import keyword
603 (defvar js2-IF 111) ; if keyword
604 (defvar js2-ELSE 112) ; else keyword
605 (defvar js2-SWITCH 113) ; switch keyword
606 (defvar js2-CASE 114) ; case keyword
607 (defvar js2-DEFAULT 115) ; default keyword
608 (defvar js2-WHILE 116) ; while keyword
609 (defvar js2-DO 117) ; do keyword
610 (defvar js2-FOR 118) ; for keyword
611 (defvar js2-BREAK 119) ; break keyword
612 (defvar js2-CONTINUE 120) ; continue keyword
613 (defvar js2-VAR 121) ; var keyword
614 (defvar js2-WITH 122) ; with keyword
615 (defvar js2-CATCH 123) ; catch keyword
616 (defvar js2-FINALLY 124) ; finally keyword
617 (defvar js2-VOID 125) ; void keyword
618 (defvar js2-RESERVED 126) ; reserved keywords
620 (defvar js2-EMPTY 127)
622 ;; Types used for the parse tree - never returned by scanner.
624 (defvar js2-BLOCK 128) ; statement block
625 (defvar js2-LABEL 129) ; label
626 (defvar js2-TARGET 130)
627 (defvar js2-LOOP 131)
628 (defvar js2-EXPR_VOID 132) ; expression statement in functions
629 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
631 (defvar js2-SCRIPT 135) ; top-level node for entire script
632 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
633 (defvar js2-USE_STACK 137)
634 (defvar js2-SETPROP_OP 138) ; x.y op= something
635 (defvar js2-SETELEM_OP 139) ; x[y] op= something
636 (defvar js2-LOCAL_BLOCK 140)
637 (defvar js2-SET_REF_OP 141) ; *reference op= something
640 (defvar js2-DOTDOT 142) ; member operator (..)
641 (defvar js2-COLONCOLON 143) ; namespace::name
642 (defvar js2-XML 144) ; XML type
643 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
644 (defvar js2-XMLATTR 146) ; @
645 (defvar js2-XMLEND 147)
647 ;; Optimizer-only tokens
648 (defvar js2-TO_OBJECT 148)
649 (defvar js2-TO_DOUBLE 149)
651 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
652 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
653 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
654 (defvar js2-CONST 153)
655 (defvar js2-SETCONST 154)
656 (defvar js2-SETCONSTVAR 155)
657 (defvar js2-ARRAYCOMP 156)
658 (defvar js2-LETEXPR 157)
659 (defvar js2-WITHEXPR 158)
660 (defvar js2-DEBUGGER 159)
662 (defvar js2-COMMENT 160)
663 (defvar js2-ENUM 161) ; for "enum" reserved word
665 (defconst js2-num-tokens (1+ js2-ENUM))
667 (defconst js2-debug-print-trees nil)
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
681 (js2-deflocal js2-ts-regexp-flags nil
682 "Token stream buffer-local variable.")
684 (js2-deflocal js2-ts-string ""
685 "Token stream buffer-local variable.
686 Last string scanned.")
688 (js2-deflocal js2-ts-number nil
689 "Token stream buffer-local variable.
690 Last literal number scanned.")
692 (js2-deflocal js2-ts-hit-eof nil
693 "Token stream buffer-local variable.")
695 (js2-deflocal js2-ts-line-start 0
696 "Token stream buffer-local variable.")
698 (js2-deflocal js2-ts-lineno 1
699 "Token stream buffer-local variable.")
701 (js2-deflocal js2-ts-line-end-char -1
702 "Token stream buffer-local variable.")
704 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
705 "Token stream buffer-local variable.
706 Current scan position.")
708 (js2-deflocal js2-ts-is-xml-attribute nil
709 "Token stream buffer-local variable.")
711 (js2-deflocal js2-ts-xml-is-tag-content nil
712 "Token stream buffer-local variable.")
714 (js2-deflocal js2-ts-xml-open-tags-count 0
715 "Token stream buffer-local variable.")
717 (js2-deflocal js2-ts-string-buffer nil
718 "Token stream buffer-local variable.
719 List of chars built up while scanning various tokens.")
721 (js2-deflocal js2-ts-comment-type nil
722 "Token stream buffer-local variable.")
726 (js2-deflocal js2-parsed-errors nil
727 "List of errors produced during scanning/parsing.")
729 (js2-deflocal js2-parsed-warnings nil
730 "List of warnings produced during scanning/parsing.")
732 (js2-deflocal js2-recover-from-parse-errors t
733 "Non-nil to continue parsing after a syntax error.
735 In recovery mode, the AST will be built in full, and any error
736 nodes will be flagged with appropriate error information. If
737 this flag is nil, a syntax error will result in an error being
740 The variable is automatically buffer-local, because different
741 modes that use the parser will need different settings.")
743 (js2-deflocal js2-parse-hook nil
744 "List of callbacks for receiving parsing progress.")
746 (defvar js2-parse-finished-hook nil
747 "List of callbacks to notify when parsing finishes.
748 Not called if parsing was interrupted.")
750 (js2-deflocal js2-is-eval-code nil
751 "True if we're evaluating code in a string.
752 If non-nil, the tokenizer will record the token text, and the AST nodes
753 will record their source text. Off by default for IDE modes, since the
754 text is available in the buffer.")
756 (defvar js2-parse-ide-mode t
757 "Non-nil if the parser is being used for `js2-mode'.
758 If non-nil, the parser will set text properties for fontification
759 and the syntax table. The value should be nil when using the
760 parser as a frontend to an interpreter or byte compiler.")
762 ;;; Parser instance variables (buffer-local vars for js2-parse)
764 (defconst js2-clear-ti-mask #xFFFF
765 "Mask to clear token information bits.")
767 (defconst js2-ti-after-eol (lsh 1 16)
768 "Flag: first token of the source line.")
770 (defconst js2-ti-check-label (lsh 1 17)
771 "Flag: indicates to check for label.")
773 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
775 (js2-deflocal js2-compiler-generate-debug-info t)
776 (js2-deflocal js2-compiler-use-dynamic-scope nil)
777 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
778 (js2-deflocal js2-compiler-xml-available t)
779 (js2-deflocal js2-compiler-optimization-level 0)
780 (js2-deflocal js2-compiler-generating-source t)
781 (js2-deflocal js2-compiler-strict-mode nil)
782 (js2-deflocal js2-compiler-report-warning-as-error nil)
783 (js2-deflocal js2-compiler-generate-observer-count nil)
784 (js2-deflocal js2-compiler-activation-names nil)
788 ;; There's a compileFunction method in Context.java - may need it.
789 (js2-deflocal js2-called-by-compile-function nil
790 "True if `js2-parse' was called by `js2-compile-function'.
791 Will only be used when we finish implementing the interpreter.")
793 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
795 (js2-deflocal js2-current-flagged-token js2-EOF)
796 (js2-deflocal js2-current-token js2-EOF)
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
801 (js2-deflocal js2-nesting-of-function 0)
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
806 (defmacro js2-in-lhs (body)
807 `(let ((js2-is-in-lhs t))
810 (defmacro js2-in-rhs (body)
811 `(let ((js2-is-in-lhs nil))
814 (js2-deflocal js2-is-in-lhs nil
815 "True while parsing lhs statement")
817 (defcustom js2-global-externs nil
818 "A list of any extern names you'd like to consider always declared.
819 This list is global and is used by all js2-mode files.
820 You can create buffer-local externs list using `js2-additional-externs'.
822 There is also a buffer-local variable `js2-default-externs',
823 which is initialized by default to include the Ecma-262 externs
824 and the standard browser externs. The three lists are all
825 checked during highlighting."
829 (js2-deflocal js2-default-externs nil
830 "Default external declarations.
832 These are currently only used for highlighting undeclared variables,
833 which only worries about top-level (unqualified) references.
834 As js2-mode's processing improves, we will flesh out this list.
836 The initial value is set to `js2-ecma-262-externs', unless you
837 have set `js2-include-browser-externs', in which case the browser
838 externs are also included.
840 See `js2-additional-externs' for more information.")
842 (defcustom js2-include-browser-externs t
843 "Non-nil to include browser externs in the master externs list.
844 If you work on JavaScript files that are not intended for browsers,
845 such as Mozilla Rhino server-side JavaScript, set this to nil.
846 You can always include them on a per-file basis by calling
847 `js2-add-browser-externs' from a function on `js2-mode-hook'.
849 See `js2-additional-externs' for more information about externs."
853 (defcustom js2-include-rhino-externs t
854 "Non-nil to include Mozilla Rhino externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
859 (defcustom js2-include-gears-externs t
860 "Non-nil to include Google Gears externs in the master externs list.
861 See `js2-additional-externs' for more information about externs."
865 (js2-deflocal js2-additional-externs nil
866 "A buffer-local list of additional external declarations.
867 It is used to decide whether variables are considered undeclared
868 for purposes of highlighting.
870 Each entry is a lisp string. The string should be the fully qualified
871 name of an external entity. All externs should be added to this list,
872 so that as js2-mode's processing improves it can take advantage of them.
874 You may want to declare your externs in three ways.
875 First, you can add externs that are valid for all your JavaScript files.
876 You should probably do this by adding them to `js2-global-externs', which
877 is a global list used for all js2-mode files.
879 Next, you can add a function to `js2-mode-hook' that adds additional
880 externs appropriate for the specific file, perhaps based on its path.
881 These should go in `js2-additional-externs', which is buffer-local.
883 Finally, you can add a function to `js2-post-parse-callbacks',
884 which is called after parsing completes, and `root' is bound to
885 the root of the parse tree. At this stage you can set up an AST
886 node visitor using `js2-visit-ast' and examine the parse tree
887 for specific import patterns that may imply the existence of
888 other externs, possibly tied to your build system. These should also
889 be added to `js2-additional-externs'.
891 Your post-parse callback may of course also use the simpler and
892 faster (but perhaps less robust) approach of simply scanning the
893 buffer text for your imports, using regular expressions.")
896 ;; SKIP: encoded-source
898 ;;; The following variables are per-function and should be saved/restored
899 ;;; during function parsing...
901 (js2-deflocal js2-current-script-or-fn nil)
902 (js2-deflocal js2-current-scope nil)
903 (js2-deflocal js2-nesting-of-with 0)
904 (js2-deflocal js2-label-set nil
905 "An alist mapping label names to nodes.")
907 (js2-deflocal js2-loop-set nil)
908 (js2-deflocal js2-loop-and-switch-set nil)
909 (js2-deflocal js2-has-return-value nil)
910 (js2-deflocal js2-end-flags 0)
912 ;;; ...end of per function variables
914 ;; Without 2-token lookahead, labels are a problem.
915 ;; These vars store the token info of the last matched name,
916 ;; iff it wasn't the last matched token. Only valid in some contexts.
917 (defvar js2-prev-name-token-start nil)
918 (defvar js2-prev-name-token-string nil)
920 (defsubst js2-save-name-token-data (pos name)
921 (setq js2-prev-name-token-start pos
922 js2-prev-name-token-string name))
924 ;; These flags enumerate the possible ways a statement/function can
925 ;; terminate. These flags are used by endCheck() and by the Parser to
926 ;; detect inconsistent return usage.
928 ;; END_UNREACHED is reserved for code paths that are assumed to always be
929 ;; able to execute (example: throw, continue)
931 ;; END_DROPS_OFF indicates if the statement can transfer control to the
932 ;; next one. Statement such as return dont. A compound statement may have
933 ;; some branch that drops off control to the next statement.
935 ;; END_RETURNS indicates that the statement can return (without arguments)
936 ;; END_RETURNS_VALUE indicates that the statement can return a value.
938 ;; A compound statement such as
942 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
944 (defconst js2-end-unreached #x0)
945 (defconst js2-end-drops-off #x1)
946 (defconst js2-end-returns #x2)
947 (defconst js2-end-returns-value #x4)
948 (defconst js2-end-yields #x8)
950 ;; Rhino awkwardly passes a statementLabel parameter to the
951 ;; statementHelper() function, the main statement parser, which
952 ;; is then used by quite a few of the sub-parsers. We just make
953 ;; it a buffer-local variable and make sure it's cleaned up properly.
954 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
956 ;; Similarly, Rhino passes an inForInit boolean through about half
957 ;; the expression parsers. We use a dynamically-scoped variable,
958 ;; which makes it easier to funcall the parsers individually without
959 ;; worrying about whether they take the parameter or not.
960 (js2-deflocal js2-in-for-init nil)
961 (js2-deflocal js2-temp-name-counter 0)
962 (js2-deflocal js2-parse-stmt-count 0)
964 (defsubst js2-get-next-temp-name ()
965 (format "$%d" (incf js2-temp-name-counter)))
967 (defvar js2-parse-interruptable-p t
968 "Set this to nil to force parse to continue until finished.
969 This will mostly be useful for interpreters.")
971 (defvar js2-statements-per-pause 50
972 "Pause after this many statements to check for user input.
973 If user input is pending, stop the parse and discard the tree.
974 This makes for a smoother user experience for large files.
975 You may have to wait a second or two before the highlighting
976 and error-reporting appear, but you can always type ahead if
977 you wish. This appears to be more or less how Eclipse, IntelliJ
978 and other editors work.")
980 (js2-deflocal js2-record-comments t
981 "Instructs the scanner to record comments in `js2-scanned-comments'.")
983 (js2-deflocal js2-scanned-comments nil
984 "List of all comments from the current parse.")
986 (defcustom js2-mode-indent-inhibit-undo nil
987 "Non-nil to disable collection of Undo information when indenting lines.
988 Some users have requested this behavior. It's nil by default because
989 other Emacs modes don't work this way."
993 (defcustom js2-mode-indent-ignore-first-tab nil
994 "If non-nil, ignore first TAB keypress if we look indented properly.
995 It's fairly common for users to navigate to an already-indented line
996 and press TAB for reassurance that it's been indented. For this class
997 of users, we want the first TAB press on a line to be ignored if the
998 line is already indented to one of the precomputed alternatives.
1000 This behavior is only partly implemented. If you TAB-indent a line,
1001 navigate to another line, and then navigate back, it fails to clear
1002 the last-indented variable, so it thinks you've already hit TAB once,
1003 and performs the indent. A full solution would involve getting on the
1004 point-motion hooks for the entire buffer. If we come across another
1005 use cases that requires watching point motion, I'll consider doing it.
1007 If you set this variable to nil, then the TAB key will always change
1008 the indentation of the current line, if more than one alternative
1009 indentation spot exists."
1013 (defvar js2-indent-hook nil
1014 "A hook for user-defined indentation rules.
1016 Functions on this hook should expect two arguments: (LIST INDEX)
1017 The LIST argument is the list of computed indentation points for
1018 the current line. INDEX is the list index of the indentation point
1019 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1020 indent function is not going to change the current line indentation.
1022 If a hook function on this list returns a non-nil value, then
1023 `js2-bounce-indent' assumes the hook function has performed its own
1024 indentation, and will do nothing. If all hook functions on the list
1025 return nil, then `js2-bounce-indent' will use its computed indentation
1026 and reindent the line.
1028 When hook functions on this hook list are called, the variable
1029 `js2-mode-ast' may or may not be set, depending on whether the
1030 parse tree is available. If the variable is nil, you can pass a
1031 callback to `js2-mode-wait-for-parse', and your callback will be
1032 called after the new parse tree is built. This can take some time
1035 (defface js2-warning-face
1036 `((((class color) (background light))
1037 (:underline "orange"))
1038 (((class color) (background dark))
1039 (:underline "orange"))
1041 "Face for JavaScript warnings."
1044 (defface js2-error-face
1045 `((((class color) (background light))
1046 (:foreground "red"))
1047 (((class color) (background dark))
1048 (:foreground "red"))
1049 (t (:foreground "red")))
1050 "Face for JavaScript errors."
1053 (defface js2-jsdoc-tag-face
1054 '((t :foreground "SlateGray"))
1055 "Face used to highlight @whatever tags in jsdoc comments."
1058 (defface js2-jsdoc-type-face
1059 '((t :foreground "SteelBlue"))
1060 "Face used to highlight {FooBar} types in jsdoc comments."
1063 (defface js2-jsdoc-value-face
1064 '((t :foreground "PeachPuff3"))
1065 "Face used to highlight tag values in jsdoc comments."
1068 (defface js2-function-param-face
1069 '((t :foreground "SeaGreen"))
1070 "Face used to highlight function parameters in javascript."
1073 (defface js2-instance-member-face
1074 '((t :foreground "DarkOrchid"))
1075 "Face used to highlight instance variables in javascript.
1076 Not currently used."
1079 (defface js2-private-member-face
1080 '((t :foreground "PeachPuff3"))
1081 "Face used to highlight calls to private methods in javascript.
1082 Not currently used."
1085 (defface js2-private-function-call-face
1086 '((t :foreground "goldenrod"))
1087 "Face used to highlight calls to private functions in javascript.
1088 Not currently used."
1091 (defface js2-jsdoc-html-tag-name-face
1093 '((((class color) (min-colors 88) (background light))
1094 (:foreground "rosybrown"))
1095 (((class color) (min-colors 8) (background dark))
1096 (:foreground "yellow"))
1097 (((class color) (min-colors 8) (background light))
1098 (:foreground "magenta")))
1099 '((((type tty pc) (class color) (background light))
1100 (:foreground "magenta"))
1101 (((type tty pc) (class color) (background dark))
1102 (:foreground "yellow"))
1103 (t (:foreground "RosyBrown"))))
1104 "Face used to highlight jsdoc html tag names"
1107 (defface js2-jsdoc-html-tag-delimiter-face
1109 '((((class color) (min-colors 88) (background light))
1110 (:foreground "dark khaki"))
1111 (((class color) (min-colors 8) (background dark))
1112 (:foreground "green"))
1113 (((class color) (min-colors 8) (background light))
1114 (:foreground "green")))
1115 '((((type tty pc) (class color) (background light))
1116 (:foreground "green"))
1117 (((type tty pc) (class color) (background dark))
1118 (:foreground "green"))
1119 (t (:foreground "dark khaki"))))
1120 "Face used to highlight brackets in jsdoc html tags."
1123 (defface js2-magic-paren-face
1125 "Face used to color parens that will be auto-overwritten."
1128 (defcustom js2-post-parse-callbacks nil
1129 "A list of callback functions invoked after parsing finishes.
1130 Currently, the main use for this function is to add synthetic
1131 declarations to `js2-recorded-identifiers', which see."
1135 (defface js2-external-variable-face
1136 '((t :foreground "orange"))
1137 "Face used to highlight undeclared variable identifiers.
1138 An undeclared variable is any variable not declared with var or let
1139 in the current scope or any lexically enclosing scope. If you use
1140 such a variable, then you are either expecting it to originate from
1141 another file, or you've got a potential bug."
1144 (defcustom js2-highlight-external-variables t
1145 "Non-nil to highlight undeclared variable identifiers."
1149 (defcustom js2-auto-insert-catch-block t
1150 "Non-nil to insert matching catch block on open-curly after `try'."
1154 (defvar js2-mode-map
1155 (let ((map (make-sparse-keymap))
1157 (define-key map [mouse-1] #'js2-mode-show-node)
1158 (define-key map (kbd "C-m") #'js2-enter-key)
1159 (when js2-rebind-eol-bol-keys
1160 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1161 (define-key map (kbd "C-e") #'js2-end-of-line))
1162 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1163 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1164 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1165 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1166 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1167 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1168 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1169 (define-key map (kbd "C-c C-`") #'js2-next-error)
1170 ;; also define user's preference for next-error, if available
1171 (if (setq keys (where-is-internal #'next-error))
1172 (define-key map (car keys) #'js2-next-error))
1173 (define-key map (or (car (where-is-internal #'mark-defun))
1176 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1178 #'js2-narrow-to-defun)
1179 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1180 (when js2-auto-indent-p
1182 (define-key map key #'js2-insert-and-indent))
1185 (define-key map [menu-bar javascript]
1186 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1188 (define-key map [menu-bar javascript customize-js2-mode]
1189 '(menu-item "Customize js2-mode" js2-mode-customize
1190 :help "Customize the behavior of this mode"))
1192 (define-key map [menu-bar javascript js2-force-refresh]
1193 '(menu-item "Force buffer refresh" js2-mode-reset
1194 :help "Re-parse the buffer from scratch"))
1196 (define-key map [menu-bar javascript separator-2]
1199 (define-key map [menu-bar javascript next-error]
1200 '(menu-item "Next warning or error" js2-next-error
1201 :enabled (and js2-mode-ast
1202 (or (js2-ast-root-errors js2-mode-ast)
1203 (js2-ast-root-warnings js2-mode-ast)))
1204 :help "Move to next warning or error"))
1206 (define-key map [menu-bar javascript display-errors]
1207 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1208 :visible (not js2-mode-show-parse-errors)
1209 :help "Turn on display of warnings and errors"))
1211 (define-key map [menu-bar javascript hide-errors]
1212 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1213 :visible js2-mode-show-parse-errors
1214 :help "Turn off display of warnings and errors"))
1216 (define-key map [menu-bar javascript separator-1]
1219 (define-key map [menu-bar javascript js2-toggle-function]
1220 '(menu-item "Show/collapse element" js2-mode-toggle-element
1221 :help "Hide or show function body or comment"))
1223 (define-key map [menu-bar javascript show-comments]
1224 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1225 :visible js2-mode-comments-hidden
1226 :help "Expand all hidden block comments"))
1228 (define-key map [menu-bar javascript hide-comments]
1229 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1230 :visible (not js2-mode-comments-hidden)
1231 :help "Show block comments as /*...*/"))
1233 (define-key map [menu-bar javascript show-all-functions]
1234 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1235 :visible js2-mode-functions-hidden
1236 :help "Expand all hidden function bodies"))
1238 (define-key map [menu-bar javascript hide-all-functions]
1239 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1240 :visible (not js2-mode-functions-hidden)
1241 :help "Show {...} for all top-level function bodies"))
1244 "Keymap used in `js2-mode' buffers.")
1246 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1248 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1249 "Matches a //-comment line. Must be first non-whitespace on line.
1250 First match-group is the leading whitespace.")
1252 (defvar js2-mode-hook nil)
1254 (js2-deflocal js2-mode-ast nil "Private variable.")
1255 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1256 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1257 (js2-deflocal js2-mode-parsing nil "Private variable.")
1258 (js2-deflocal js2-mode-node-overlay nil)
1260 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1261 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1263 (js2-deflocal js2-mode-fontifications nil "Private variable")
1264 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1265 (js2-deflocal js2-imenu-recorder nil "Private variable")
1266 (js2-deflocal js2-imenu-function-map nil "Private variable")
1268 (defvar js2-paragraph-start
1269 "\\(@[a-zA-Z]+\\>\\|$\\)")
1271 ;; Note that we also set a 'c-in-sws text property in html comments,
1272 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1273 (defvar js2-syntactic-ws-start
1274 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1276 (defvar js2-syntactic-ws-end
1277 "\\s \\|[\n\r/]\\|\\s!")
1279 (defvar js2-syntactic-eol
1280 (concat "\\s *\\(/\\*[^*\n\r]*"
1281 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1283 "\\(//\\|/\\*[^*\n\r]*"
1284 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1286 "Copied from `java-mode'. Needed for some cc-engine functions.")
1288 (defvar js2-comment-prefix-regexp
1291 (defvar js2-comment-start-skip
1292 "\\(//+\\|/\\*+\\)\\s *")
1294 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1295 "Non-nil to emit status messages during parsing.")
1297 (defvar js2-mode-functions-hidden nil "private variable")
1298 (defvar js2-mode-comments-hidden nil "private variable")
1300 (defvar js2-mode-syntax-table
1301 (let ((table (make-syntax-table)))
1302 (c-populate-syntax-table table)
1304 "Syntax table used in js2-mode buffers.")
1306 (defvar js2-mode-abbrev-table nil
1307 "Abbrev table in use in `js2-mode' buffers.")
1308 (define-abbrev-table 'js2-mode-abbrev-table ())
1310 (defvar js2-mode-pending-parse-callbacks nil
1311 "List of functions waiting to be notified that parse is finished.")
1313 (defvar js2-mode-last-indented-line -1)
1315 ;;; Localizable error and warning messages
1317 ;; Messages are copied from Rhino's Messages.properties.
1318 ;; Many of the Java-specific messages have been elided.
1319 ;; Add any js2-specific ones at the end, so we can keep
1320 ;; this file synced with changes to Rhino's.
1322 (defvar js2-message-table
1323 (make-hash-table :test 'equal :size 250)
1324 "Contains localized messages for js2-mode.")
1326 ;; TODO(stevey): construct this table at compile-time.
1327 (defmacro js2-msg (key &rest strings)
1328 `(puthash ,key (funcall #'concat ,@strings)
1331 (defun js2-get-msg (msg-key)
1332 "Look up a localized message.
1333 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1334 the correct number of ARGS must be provided."
1335 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1336 (args (if (listp msg-key) (cdr msg-key)))
1337 (msg (gethash key js2-message-table)))
1339 (apply #'format msg args)
1340 key))) ; default to showing the key
1342 (js2-msg "msg.dup.parms"
1343 "Duplicate parameter name '%s'.")
1345 (js2-msg "msg.too.big.jump"
1346 "Program too complex: jump offset too big.")
1348 (js2-msg "msg.too.big.index"
1349 "Program too complex: internal index exceeds 64K limit.")
1351 (js2-msg "msg.while.compiling.fn"
1352 "Encountered code generation error while compiling function '%s': %s")
1354 (js2-msg "msg.while.compiling.script"
1355 "Encountered code generation error while compiling script: %s")
1358 (js2-msg "msg.ctor.not.found"
1359 "Constructor for '%s' not found.")
1361 (js2-msg "msg.not.ctor"
1362 "'%s' is not a constructor.")
1365 (js2-msg "msg.varargs.ctor"
1366 "Method or constructor '%s' must be static "
1367 "with the signature (Context cx, Object[] args, "
1368 "Function ctorObj, boolean inNewExpr) "
1369 "to define a variable arguments constructor.")
1371 (js2-msg "msg.varargs.fun"
1372 "Method '%s' must be static with the signature "
1373 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1374 "to define a variable arguments function.")
1376 (js2-msg "msg.incompat.call"
1377 "Method '%s' called on incompatible object.")
1379 (js2-msg "msg.bad.parms"
1380 "Unsupported parameter type '%s' in method '%s'.")
1382 (js2-msg "msg.bad.method.return"
1383 "Unsupported return type '%s' in method '%s'.")
1385 (js2-msg "msg.bad.ctor.return"
1386 "Construction of objects of type '%s' is not supported.")
1388 (js2-msg "msg.no.overload"
1389 "Method '%s' occurs multiple times in class '%s'.")
1391 (js2-msg "msg.method.not.found"
1392 "Method '%s' not found in '%s'.")
1396 (js2-msg "msg.bad.for.in.lhs"
1397 "Invalid left-hand side of for..in loop.")
1399 (js2-msg "msg.mult.index"
1400 "Only one variable allowed in for..in loop.")
1402 (js2-msg "msg.bad.for.in.destruct"
1403 "Left hand side of for..in loop must be an array of "
1404 "length 2 to accept key/value pair.")
1406 (js2-msg "msg.cant.convert"
1407 "Can't convert to type '%s'.")
1409 (js2-msg "msg.bad.assign.left"
1410 "Invalid assignment left-hand side.")
1412 (js2-msg "msg.bad.decr"
1413 "Invalid decerement operand.")
1415 (js2-msg "msg.bad.incr"
1416 "Invalid increment operand.")
1418 (js2-msg "msg.bad.yield"
1419 "yield must be in a function.")
1421 (js2-msg "msg.yield.parenthesized"
1422 "yield expression must be parenthesized.")
1425 (js2-msg "msg.cant.call.indirect"
1426 "Function '%s' must be called directly, and not by way of a "
1427 "function of another name.")
1429 (js2-msg "msg.eval.nonstring"
1430 "Calling eval() with anything other than a primitive "
1431 "string value will simply return the value. "
1432 "Is this what you intended?")
1434 (js2-msg "msg.eval.nonstring.strict"
1435 "Calling eval() with anything other than a primitive "
1436 "string value is not allowed in strict mode.")
1438 (js2-msg "msg.bad.destruct.op"
1439 "Invalid destructuring assignment operator")
1442 (js2-msg "msg.only.from.new"
1443 "'%s' may only be invoked from a `new' expression.")
1445 (js2-msg "msg.deprec.ctor"
1446 "The '%s' constructor is deprecated.")
1449 (js2-msg "msg.no.function.ref.found"
1450 "no source found to decompile function reference %s")
1452 (js2-msg "msg.arg.isnt.array"
1453 "second argument to Function.prototype.apply must be an array")
1456 (js2-msg "msg.bad.esc.mask"
1457 "invalid string escape mask")
1460 (js2-msg "msg.bad.quant"
1461 "Invalid quantifier %s")
1463 (js2-msg "msg.overlarge.backref"
1464 "Overly large back reference %s")
1466 (js2-msg "msg.overlarge.min"
1467 "Overly large minimum %s")
1469 (js2-msg "msg.overlarge.max"
1470 "Overly large maximum %s")
1472 (js2-msg "msg.zero.quant"
1473 "Zero quantifier %s")
1475 (js2-msg "msg.max.lt.min"
1476 "Maximum %s less than minimum")
1478 (js2-msg "msg.unterm.quant"
1479 "Unterminated quantifier %s")
1481 (js2-msg "msg.unterm.paren"
1482 "Unterminated parenthetical %s")
1484 (js2-msg "msg.unterm.class"
1485 "Unterminated character class %s")
1487 (js2-msg "msg.bad.range"
1488 "Invalid range in character class.")
1490 (js2-msg "msg.trail.backslash"
1491 "Trailing \\ in regular expression.")
1493 (js2-msg "msg.re.unmatched.right.paren"
1494 "unmatched ) in regular expression.")
1496 (js2-msg "msg.no.regexp"
1497 "Regular expressions are not available.")
1499 (js2-msg "msg.bad.backref"
1500 "back-reference exceeds number of capturing parentheses.")
1502 (js2-msg "msg.bad.regexp.compile"
1503 "Only one argument may be specified if the first "
1504 "argument to RegExp.prototype.compile is a RegExp object.")
1507 (js2-msg "msg.got.syntax.errors"
1508 "Compilation produced %s syntax errors.")
1510 (js2-msg "msg.var.redecl"
1511 "TypeError: redeclaration of var %s.")
1513 (js2-msg "msg.const.redecl"
1514 "TypeError: redeclaration of const %s.")
1516 (js2-msg "msg.let.redecl"
1517 "TypeError: redeclaration of variable %s.")
1519 (js2-msg "msg.parm.redecl"
1520 "TypeError: redeclaration of formal parameter %s.")
1522 (js2-msg "msg.fn.redecl"
1523 "TypeError: redeclaration of function %s.")
1525 (js2-msg "msg.let.decl.not.in.block"
1526 "SyntaxError: let declaration not directly within block")
1529 (js2-msg "msg.dup.label"
1532 (js2-msg "msg.undef.label"
1535 (js2-msg "msg.bad.break"
1536 "unlabelled break must be inside loop or switch")
1538 (js2-msg "msg.continue.outside"
1539 "continue must be inside loop")
1541 (js2-msg "msg.continue.nonloop"
1542 "continue can only use labels of iteration statements")
1544 (js2-msg "msg.bad.throw.eol"
1545 "Line terminator is not allowed between the throw "
1546 "keyword and throw expression.")
1548 (js2-msg "msg.no.paren.parms"
1549 "missing ( before function parameters.")
1551 (js2-msg "msg.no.parm"
1552 "missing formal parameter")
1554 (js2-msg "msg.no.paren.after.parms"
1555 "missing ) after formal parameters")
1557 (js2-msg "msg.no.brace.body"
1558 "missing '{' before function body")
1560 (js2-msg "msg.no.brace.after.body"
1561 "missing } after function body")
1563 (js2-msg "msg.no.paren.cond"
1564 "missing ( before condition")
1566 (js2-msg "msg.no.paren.after.cond"
1567 "missing ) after condition")
1569 (js2-msg "msg.no.semi.stmt"
1570 "missing ; before statement")
1572 (js2-msg "msg.missing.semi"
1573 "missing ; after statement")
1575 (js2-msg "msg.no.name.after.dot"
1576 "missing name after . operator")
1578 (js2-msg "msg.no.name.after.coloncolon"
1579 "missing name after :: operator")
1581 (js2-msg "msg.no.name.after.dotdot"
1582 "missing name after .. operator")
1584 (js2-msg "msg.no.name.after.xmlAttr"
1585 "missing name after .@")
1587 (js2-msg "msg.no.bracket.index"
1588 "missing ] in index expression")
1590 (js2-msg "msg.no.paren.switch"
1591 "missing ( before switch expression")
1593 (js2-msg "msg.no.paren.after.switch"
1594 "missing ) after switch expression")
1596 (js2-msg "msg.no.brace.switch"
1597 "missing '{' before switch body")
1599 (js2-msg "msg.bad.switch"
1600 "invalid switch statement")
1602 (js2-msg "msg.no.colon.case"
1603 "missing : after case expression")
1605 (js2-msg "msg.double.switch.default"
1606 "double default label in the switch statement")
1608 (js2-msg "msg.no.while.do"
1609 "missing while after do-loop body")
1611 (js2-msg "msg.no.paren.for"
1612 "missing ( after for")
1614 (js2-msg "msg.no.semi.for"
1615 "missing ; after for-loop initializer")
1617 (js2-msg "msg.no.semi.for.cond"
1618 "missing ; after for-loop condition")
1620 (js2-msg "msg.in.after.for.name"
1621 "missing in after for")
1623 (js2-msg "msg.no.paren.for.ctrl"
1624 "missing ) after for-loop control")
1626 (js2-msg "msg.no.paren.with"
1627 "missing ( before with-statement object")
1629 (js2-msg "msg.no.paren.after.with"
1630 "missing ) after with-statement object")
1632 (js2-msg "msg.no.paren.after.let"
1633 "missing ( after let")
1635 (js2-msg "msg.no.paren.let"
1636 "missing ) after variable list")
1638 (js2-msg "msg.no.curly.let"
1639 "missing } after let statement")
1641 (js2-msg "msg.bad.return"
1644 (js2-msg "msg.no.brace.block"
1645 "missing } in compound statement")
1647 (js2-msg "msg.bad.label"
1650 (js2-msg "msg.bad.var"
1651 "missing variable name")
1653 (js2-msg "msg.bad.var.init"
1654 "invalid variable initialization")
1656 (js2-msg "msg.no.colon.cond"
1657 "missing : in conditional expression")
1659 (js2-msg "msg.no.paren.arg"
1660 "missing ) after argument list")
1662 (js2-msg "msg.no.bracket.arg"
1663 "missing ] after element list")
1665 (js2-msg "msg.bad.prop"
1666 "invalid property id")
1668 (js2-msg "msg.no.colon.prop"
1669 "missing : after property id")
1671 (js2-msg "msg.no.brace.prop"
1672 "missing } after property list")
1674 (js2-msg "msg.no.paren"
1675 "missing ) in parenthetical")
1677 (js2-msg "msg.reserved.id"
1678 "identifier is a reserved word")
1680 (js2-msg "msg.no.paren.catch"
1681 "missing ( before catch-block condition")
1683 (js2-msg "msg.bad.catchcond"
1684 "invalid catch block condition")
1686 (js2-msg "msg.catch.unreachable"
1687 "any catch clauses following an unqualified catch are unreachable")
1689 (js2-msg "msg.no.brace.try"
1690 "missing '{' before try block")
1692 (js2-msg "msg.no.brace.catchblock"
1693 "missing '{' before catch-block body")
1695 (js2-msg "msg.try.no.catchfinally"
1696 "'try' without 'catch' or 'finally'")
1698 (js2-msg "msg.no.return.value"
1699 "function %s does not always return a value")
1701 (js2-msg "msg.anon.no.return.value"
1702 "anonymous function does not always return a value")
1704 (js2-msg "msg.return.inconsistent"
1705 "return statement is inconsistent with previous usage")
1707 (js2-msg "msg.generator.returns"
1708 "TypeError: generator function '%s' returns a value")
1710 (js2-msg "msg.anon.generator.returns"
1711 "TypeError: anonymous generator function returns a value")
1713 (js2-msg "msg.syntax"
1716 (js2-msg "msg.unexpected.eof"
1717 "Unexpected end of file")
1719 (js2-msg "msg.XML.bad.form"
1720 "illegally formed XML syntax")
1722 (js2-msg "msg.XML.not.available"
1723 "XML runtime not available")
1725 (js2-msg "msg.too.deep.parser.recursion"
1726 "Too deep recursion while parsing")
1728 (js2-msg "msg.no.side.effects"
1729 "Code has no side effects")
1731 (js2-msg "msg.extra.trailing.comma"
1732 "Trailing comma is not legal in an ECMA-262 object initializer")
1734 (js2-msg "msg.array.trailing.comma"
1735 "Trailing comma yields different behavior across browsers")
1737 (js2-msg "msg.equal.as.assign"
1738 (concat "Test for equality (==) mistyped as assignment (=)?"
1739 " (parenthesize to suppress warning)"))
1741 (js2-msg "msg.var.hides.arg"
1742 "Variable %s hides argument")
1744 (js2-msg "msg.destruct.assign.no.init"
1745 "Missing = in destructuring declaration")
1748 (js2-msg "msg.no.properties"
1749 "%s has no properties.")
1751 (js2-msg "msg.invalid.iterator"
1752 "Invalid iterator value")
1754 (js2-msg "msg.iterator.primitive"
1755 "__iterator__ returned a primitive value")
1757 (js2-msg "msg.assn.create.strict"
1758 "Assignment to undeclared variable %s")
1760 (js2-msg "msg.ref.undefined.prop"
1761 "Reference to undefined property '%s'")
1763 (js2-msg "msg.prop.not.found"
1764 "Property %s not found.")
1766 (js2-msg "msg.invalid.type"
1767 "Invalid JavaScript value of type %s")
1769 (js2-msg "msg.primitive.expected"
1770 "Primitive type expected (had %s instead)")
1772 (js2-msg "msg.namespace.expected"
1773 "Namespace object expected to left of :: (found %s instead)")
1775 (js2-msg "msg.null.to.object"
1776 "Cannot convert null to an object.")
1778 (js2-msg "msg.undef.to.object"
1779 "Cannot convert undefined to an object.")
1781 (js2-msg "msg.cyclic.value"
1782 "Cyclic %s value not allowed.")
1784 (js2-msg "msg.is.not.defined"
1785 "'%s' is not defined.")
1787 (js2-msg "msg.undef.prop.read"
1788 "Cannot read property '%s' from %s")
1790 (js2-msg "msg.undef.prop.write"
1791 "Cannot set property '%s' of %s to '%s'")
1793 (js2-msg "msg.undef.prop.delete"
1794 "Cannot delete property '%s' of %s")
1796 (js2-msg "msg.undef.method.call"
1797 "Cannot call method '%s' of %s")
1799 (js2-msg "msg.undef.with"
1800 "Cannot apply 'with' to %s")
1802 (js2-msg "msg.isnt.function"
1803 "%s is not a function, it is %s.")
1805 (js2-msg "msg.isnt.function.in"
1806 "Cannot call property %s in object %s. "
1807 "It is not a function, it is '%s'.")
1809 (js2-msg "msg.function.not.found"
1810 "Cannot find function %s.")
1812 (js2-msg "msg.function.not.found.in"
1813 "Cannot find function %s in object %s.")
1815 (js2-msg "msg.isnt.xml.object"
1816 "%s is not an xml object.")
1818 (js2-msg "msg.no.ref.to.get"
1819 "%s is not a reference to read reference value.")
1821 (js2-msg "msg.no.ref.to.set"
1822 "%s is not a reference to set reference value to %s.")
1824 (js2-msg "msg.no.ref.from.function"
1825 "Function %s can not be used as the left-hand "
1826 "side of assignment or as an operand of ++ or -- operator.")
1828 (js2-msg "msg.bad.default.value"
1829 "Object's getDefaultValue() method returned an object.")
1831 (js2-msg "msg.instanceof.not.object"
1832 "Can't use instanceof on a non-object.")
1834 (js2-msg "msg.instanceof.bad.prototype"
1835 "'prototype' property of %s is not an object.")
1837 (js2-msg "msg.bad.radix"
1838 "illegal radix %s.")
1841 (js2-msg "msg.default.value"
1842 "Cannot find default value for object.")
1844 (js2-msg "msg.zero.arg.ctor"
1845 "Cannot load class '%s' which has no zero-parameter constructor.")
1847 (js2-msg "msg.ctor.multiple.parms"
1848 "Can't define constructor or class %s since more than "
1849 "one constructor has multiple parameters.")
1851 (js2-msg "msg.extend.scriptable"
1852 "%s must extend ScriptableObject in order to define property %s.")
1854 (js2-msg "msg.bad.getter.parms"
1855 "In order to define a property, getter %s must have zero "
1856 "parameters or a single ScriptableObject parameter.")
1858 (js2-msg "msg.obj.getter.parms"
1859 "Expected static or delegated getter %s to take "
1860 "a ScriptableObject parameter.")
1862 (js2-msg "msg.getter.static"
1863 "Getter and setter must both be static or neither be static.")
1865 (js2-msg "msg.setter.return"
1866 "Setter must have void return type: %s")
1868 (js2-msg "msg.setter2.parms"
1869 "Two-parameter setter must take a ScriptableObject as "
1870 "its first parameter.")
1872 (js2-msg "msg.setter1.parms"
1873 "Expected single parameter setter for %s")
1875 (js2-msg "msg.setter2.expected"
1876 "Expected static or delegated setter %s to take two parameters.")
1878 (js2-msg "msg.setter.parms"
1879 "Expected either one or two parameters for setter.")
1881 (js2-msg "msg.setter.bad.type"
1882 "Unsupported parameter type '%s' in setter '%s'.")
1884 (js2-msg "msg.add.sealed"
1885 "Cannot add a property to a sealed object: %s.")
1887 (js2-msg "msg.remove.sealed"
1888 "Cannot remove a property from a sealed object: %s.")
1890 (js2-msg "msg.modify.sealed"
1891 "Cannot modify a property of a sealed object: %s.")
1893 (js2-msg "msg.modify.readonly"
1894 "Cannot modify readonly property: %s.")
1897 (js2-msg "msg.missing.exponent"
1900 (js2-msg "msg.caught.nfe"
1901 "number format error")
1903 (js2-msg "msg.unterminated.string.lit"
1904 "unterminated string literal")
1906 (js2-msg "msg.unterminated.comment"
1907 "unterminated comment")
1909 (js2-msg "msg.unterminated.re.lit"
1910 "unterminated regular expression literal")
1912 (js2-msg "msg.invalid.re.flag"
1913 "invalid flag after regular expression")
1915 (js2-msg "msg.no.re.input.for"
1918 (js2-msg "msg.illegal.character"
1919 "illegal character")
1921 (js2-msg "msg.invalid.escape"
1922 "invalid Unicode escape sequence")
1924 (js2-msg "msg.bad.namespace"
1925 "not a valid default namespace statement. "
1926 "Syntax is: default xml namespace = EXPRESSION;")
1928 ;; TokensStream warnings
1929 (js2-msg "msg.bad.octal.literal"
1930 "illegal octal literal digit %s; "
1931 "interpreting it as a decimal digit")
1933 (js2-msg "msg.reserved.keyword"
1934 "illegal usage of future reserved keyword %s; "
1935 "interpreting it as ordinary identifier")
1937 (js2-msg "msg.script.is.not.constructor"
1938 "Script objects are not constructors.")
1941 (js2-msg "msg.arraylength.bad"
1942 "Inappropriate array length.")
1945 (js2-msg "msg.arraylength.too.big"
1946 "Array length %s exceeds supported capacity limit.")
1949 (js2-msg "msg.bad.uri"
1950 "Malformed URI sequence.")
1953 (js2-msg "msg.bad.precision"
1954 "Precision %s out of range.")
1957 (js2-msg "msg.send.newborn"
1958 "Attempt to send value to newborn generator")
1960 (js2-msg "msg.already.exec.gen"
1961 "Already executing generator")
1963 (js2-msg "msg.StopIteration.invalid"
1964 "StopIteration may not be changed to an arbitrary object.")
1967 (js2-msg "msg.yield.closing"
1968 "Yield from closing generator")
1972 (defun js2-delete-if (predicate list)
1973 "Remove all items satisfying PREDICATE in LIST."
1974 (loop for item in list
1975 if (not (funcall predicate item))
1978 (defun js2-position (element list)
1979 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1980 Returns nil if element is not found in the list."
1983 (while (and list (not found))
1984 (if (eq element (car list))
1986 (setq count (1+ count)
1990 (defun js2-find-if (predicate list)
1991 "Find first item satisfying PREDICATE in LIST."
1993 (while (and list (not result))
1994 (if (funcall predicate (car list))
1995 (setq result (car list)))
1996 (setq list (cdr list)))
1999 (defmacro js2-time (form)
2000 "Evaluate FORM, discard result, and return elapsed time in sec"
2002 (let ((beg (make-symbol "--js2-time-beg--"))
2003 (delta (make-symbol "--js2-time-end--")))
2004 `(let ((,beg (current-time))
2007 (/ (truncate (* (- (float-time (current-time))
2012 (defsubst js2-same-line (pos)
2013 "Return t if POS is on the same line as current point."
2014 (and (>= pos (point-at-bol))
2015 (<= pos (point-at-eol))))
2017 (defsubst js2-same-line-2 (p1 p2)
2018 "Return t if p1 is on the same line as p2."
2021 (js2-same-line p2)))
2023 (defun js2-code-bug ()
2024 "Signal an error when we encounter an unexpected code path."
2025 (error "failed assertion"))
2027 (defsubst js2-record-text-property (beg end prop value)
2028 "Record a text property to set when parsing finishes."
2029 (push (list beg end prop value) js2-mode-deferred-properties))
2031 ;; I'd like to associate errors with nodes, but for now the
2032 ;; easiest thing to do is get the context info from the last token.
2033 (defsubst js2-record-parse-error (msg &optional arg pos len)
2034 (push (list (list msg arg)
2035 (or pos js2-token-beg)
2036 (or len (- js2-token-end js2-token-beg)))
2039 (defsubst js2-report-error (msg &optional msg-arg pos len)
2040 "Signal a syntax error or record a parse error."
2041 (if js2-recover-from-parse-errors
2042 (js2-record-parse-error msg msg-arg pos len)
2043 (signal 'js2-syntax-error
2047 (goto-char js2-ts-cursor)
2051 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2052 (if js2-compiler-report-warning-as-error
2053 (js2-report-error msg msg-arg pos len)
2054 (push (list (list msg msg-arg)
2055 (or pos js2-token-beg)
2056 (or len (- js2-token-end js2-token-beg)))
2057 js2-parsed-warnings)))
2059 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2060 (if js2-compiler-strict-mode
2061 (js2-report-warning msg-id msg-arg beg
2062 (and beg end (- end beg)))))
2064 (put 'js2-syntax-error 'error-conditions
2065 '(error syntax-error js2-syntax-error))
2066 (put 'js2-syntax-error 'error-message "Syntax error")
2068 (put 'js2-parse-error 'error-conditions
2069 '(error parse-error js2-parse-error))
2070 (put 'js2-parse-error 'error-message "Parse error")
2072 (defmacro js2-clear-flag (flags flag)
2073 `(setq ,flags (logand ,flags (lognot ,flag))))
2075 (defmacro js2-set-flag (flags flag)
2076 "Logical-or FLAG into FLAGS."
2077 `(setq ,flags (logior ,flags ,flag)))
2079 (defsubst js2-flag-set-p (flags flag)
2080 (/= 0 (logand flags flag)))
2082 (defsubst js2-flag-not-set-p (flags flag)
2083 (zerop (logand flags flag)))
2085 ;; Stolen shamelessly from James Clark's nxml-mode.
2086 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2087 "Evaluate BODY without any text property changes modifying the buffer.
2088 Any text properties changes happen as usual but the changes are not treated as
2089 modifications to the buffer."
2090 (declare (indent 0) (debug t))
2091 (let ((modified (make-symbol "modified")))
2092 `(let ((,modified (buffer-modified-p))
2093 (inhibit-read-only t)
2094 (inhibit-modification-hooks t)
2095 (buffer-undo-list t)
2096 (deactivate-mark nil)
2097 ;; Apparently these avoid file locking problems.
2098 (buffer-file-name nil)
2099 (buffer-file-truename nil))
2103 (restore-buffer-modified-p nil))))))
2105 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2106 "Evaluate BODY with the _ character set to be word-syntax."
2107 (declare (indent 0) (debug t))
2108 (let ((old-syntax (make-symbol "old-syntax")))
2109 `(let ((,old-syntax (string (char-syntax ?_))))
2112 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2114 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2116 (defsubst js2-char-uppercase-p (c)
2117 "Return t if C is an uppercase character.
2118 Handles unicode and latin chars properly."
2119 (/= c (downcase c)))
2121 (defsubst js2-char-lowercase-p (c)
2122 "Return t if C is an uppercase character.
2123 Handles unicode and latin chars properly."
2126 ;;; AST struct and function definitions
2128 ;; flags for ast node property 'member-type (used for e4x operators)
2129 (defvar js2-property-flag #x1 "property access: element is valid name")
2130 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2131 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2133 (defsubst js2-relpos (pos anchor)
2134 "Convert POS to be relative to ANCHOR.
2135 If POS is nil, returns nil."
2136 (and pos (- pos anchor)))
2138 (defsubst js2-make-pad (indent)
2141 (make-string (* indent js2-basic-offset) ? )))
2143 (defsubst js2-visit-ast (node callback)
2144 "Visit every node in ast NODE with visitor CALLBACK.
2146 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2147 called twice: once to visit the node, and again after all the node's
2148 children have been processed. The END-P argument is nil on the first
2149 call and non-nil on the second call. The return value of the callback
2150 affects the traversal: if non-nil, the children of NODE are processed.
2151 If the callback returns nil, or if the node has no children, then the
2152 callback is called immediately with a non-nil END-P argument.
2154 The node traversal is approximately lexical-order, although there
2155 are currently no guarantees around this."
2157 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2159 (when (funcall callback node nil)
2162 ((eq vfunc 'js2-visit-none)
2163 nil) ; don't even bother calling it
2164 ;; Each AST node type has to define a `js2-visitor' function
2165 ;; that takes a node and a callback, and calls `js2-visit-ast'
2166 ;; on each child of the node.
2168 (funcall vfunc node callback))
2170 (error "%s does not define a visitor-traversal function"
2172 ;; call the end-visit
2173 (funcall callback node t))))
2175 (defstruct (js2-node
2176 (:constructor nil)) ; abstract
2177 "Base AST node type."
2178 (type -1) ; token type
2179 (pos -1) ; start position of this AST node in parsed input
2180 (len 1) ; num characters spanned by the node
2181 props ; optional node property list (an alist)
2182 parent) ; link to parent node; null for root
2184 (defsubst js2-node-get-prop (node prop &optional default)
2185 (or (cadr (assoc prop (js2-node-props node))) default))
2187 (defsubst js2-node-set-prop (node prop value)
2188 (setf (js2-node-props node)
2189 (cons (list prop value) (js2-node-props node))))
2191 (defsubst js2-fixup-starts (n nodes)
2192 "Adjust the start positions of NODES to be relative to N.
2193 Any node in the list may be nil, for convenience."
2194 (dolist (node nodes)
2196 (setf (js2-node-pos node) (- (js2-node-pos node)
2197 (js2-node-pos n))))))
2199 (defsubst js2-node-add-children (parent &rest nodes)
2200 "Set parent node of NODES to PARENT, and return PARENT.
2201 Does nothing if we're not recording parent links.
2202 If any given node in NODES is nil, doesn't record that link."
2203 (js2-fixup-starts parent nodes)
2204 (dolist (node nodes)
2206 (setf (js2-node-parent node) parent))))
2208 ;; Non-recursive since it's called a frightening number of times.
2209 (defsubst js2-node-abs-pos (n)
2210 (let ((pos (js2-node-pos n)))
2211 (while (setq n (js2-node-parent n))
2212 (setq pos (+ pos (js2-node-pos n))))
2215 (defsubst js2-node-abs-end (n)
2216 "Return absolute buffer position of end of N."
2217 (+ (js2-node-abs-pos n) (js2-node-len n)))
2219 ;; It's important to make sure block nodes have a lisp list for the
2220 ;; child nodes, to limit printing recursion depth in an AST that
2221 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2222 ;; a sufficiently large vector tree.
2224 (defstruct (js2-block-node
2227 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2232 "A block of statements."
2233 kids) ; a lisp list of the child statement nodes
2235 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2236 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2238 (defsubst js2-visit-block (ast callback)
2239 "Visit the `js2-block-node' children of AST."
2240 (dolist (kid (js2-block-node-kids ast))
2241 (js2-visit-ast kid callback)))
2243 (defun js2-print-block (n i)
2244 (let ((pad (js2-make-pad i)))
2246 (dolist (kid (js2-block-node-kids n))
2247 (js2-print-ast kid (1+ i)))
2250 (defstruct (js2-scope
2251 (:include js2-block-node)
2253 (:constructor make-js2-scope (&key (type js2-BLOCK)
2257 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2258 ;; I don't have one of those handy, so I'll use an alist for now.
2259 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2260 ;; and is much lighter-weight to construct (both CPU and mem).
2261 ;; The keys are interned strings (symbols) for faster lookup.
2262 ;; Should switch to hybrid alist/hashtable eventually.
2263 symbol-table ; an alist of (symbol . js2-symbol)
2264 parent-scope ; a `js2-scope'
2265 top) ; top-level `js2-scope' (script/function)
2267 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2268 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2270 (defun js2-scope-set-parent-scope (scope parent)
2271 (setf (js2-scope-parent-scope scope) parent
2272 (js2-scope-top scope) (if (null parent)
2274 (js2-scope-top parent))))
2276 (defun js2-node-get-enclosing-scope (node)
2277 "Return the innermost `js2-scope' node surrounding NODE.
2278 Returns nil if there is no enclosing scope node."
2279 (let ((parent (js2-node-parent node)))
2280 (while (not (js2-scope-p parent))
2281 (setq parent (js2-node-parent parent)))
2284 (defun js2-get-defining-scope (scope name)
2285 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2286 Returns `js2-scope' in which NAME is defined, or nil if not found."
2287 (let ((sym (if (symbolp name)
2293 (while (and scope continue)
2294 (if (and (setq table (js2-scope-symbol-table scope))
2298 (setq scope (js2-scope-parent-scope scope))))
2301 (defsubst js2-scope-get-symbol (scope name)
2302 "Return symbol table entry for NAME in SCOPE.
2303 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2304 (and (js2-scope-symbol-table scope)
2305 (cdr (assq (if (symbolp name)
2308 (js2-scope-symbol-table scope)))))
2310 (defsubst js2-scope-put-symbol (scope name symbol)
2311 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2312 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2313 (let* ((table (js2-scope-symbol-table scope))
2314 (sym (if (symbolp name) name (intern name)))
2315 (entry (assq sym table)))
2317 (setcdr entry symbol)
2318 (push (cons sym symbol)
2319 (js2-scope-symbol-table scope)))))
2321 (defstruct (js2-symbol
2323 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2324 "A symbol table entry."
2325 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2326 ;; js2-LET, or js2-CONST
2329 ast-node) ; a `js2-node'
2331 (defstruct (js2-error-node
2333 (:constructor nil) ; silence emacs21 byte-compiler
2334 (:constructor make-js2-error-node (&key (type js2-ERROR)
2337 "AST node representing a parse error.")
2339 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2340 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2342 (defstruct (js2-script-node
2343 (:include js2-scope)
2345 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2350 functions ; lisp list of nested functions
2351 regexps ; lisp list of (string . flags)
2352 symbols ; alist (every symbol gets unique index)
2354 var-names ; vector of string names
2355 consts ; bool-vector matching var-decls
2356 (temp-number 0)) ; for generating temp variables
2358 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2359 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2361 (defun js2-print-script (node indent)
2362 (dolist (kid (js2-block-node-kids node))
2363 (js2-print-ast kid indent)))
2365 (defstruct (js2-ast-root
2366 (:include js2-script-node)
2368 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2372 "The root node of a js2 AST."
2373 buffer ; the source buffer from which the code was parsed
2374 comments ; a lisp list of comments, ordered by start position
2375 errors ; a lisp list of errors found during parsing
2376 warnings ; a lisp list of warnings found during parsing
2377 node-count) ; number of nodes in the tree, including the root
2379 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2380 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2382 (defun js2-visit-ast-root (ast callback)
2383 (dolist (kid (js2-ast-root-kids ast))
2384 (js2-visit-ast kid callback))
2385 (dolist (comment (js2-ast-root-comments ast))
2386 (js2-visit-ast comment callback)))
2388 (defstruct (js2-comment-node
2391 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2394 (format js2-ts-comment-type))))
2395 format) ; 'line, 'block, 'jsdoc or 'html
2397 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2398 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2400 (defun js2-print-comment (n i)
2401 ;; We really ought to link end-of-line comments to their nodes.
2402 ;; Or maybe we could add a new comment type, 'endline.
2403 (insert (js2-make-pad i)
2404 (js2-node-string n)))
2406 (defstruct (js2-expr-stmt-node
2409 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2413 "An expression statement."
2416 (defsubst js2-expr-stmt-node-set-has-result (node)
2417 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2418 (setf (js2-node-type node) js2-EXPR_RESULT))
2420 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2421 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2423 (defun js2-visit-expr-stmt-node (n v)
2424 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2426 (defun js2-print-expr-stmt-node (n indent)
2427 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2430 (defstruct (js2-loop-node
2431 (:include js2-scope)
2433 "Abstract supertype of loop nodes."
2434 body ; a `js2-block-node'
2435 lp ; position of left-paren, nil if omitted
2436 rp) ; position of right-paren, nil if omitted
2438 (defstruct (js2-do-node
2439 (:include js2-loop-node)
2441 (:constructor make-js2-do-node (&key (type js2-DO)
2449 "AST node for do-loop."
2450 condition ; while (expression)
2451 while-pos) ; buffer position of 'while' keyword
2453 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2454 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2456 (defun js2-visit-do-node (n v)
2457 (js2-visit-ast (js2-do-node-body n) v)
2458 (js2-visit-ast (js2-do-node-condition n) v))
2460 (defun js2-print-do-node (n i)
2461 (let ((pad (js2-make-pad i)))
2462 (insert pad "do {\n")
2463 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2464 (js2-print-ast kid (1+ i)))
2465 (insert pad "} while (")
2466 (js2-print-ast (js2-do-node-condition n) 0)
2469 (defstruct (js2-while-node
2470 (:include js2-loop-node)
2472 (:constructor make-js2-while-node (&key (type js2-WHILE)
2479 "AST node for while-loop."
2480 condition) ; while-condition
2482 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2483 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2485 (defun js2-visit-while-node (n v)
2486 (js2-visit-ast (js2-while-node-condition n) v)
2487 (js2-visit-ast (js2-while-node-body n) v))
2489 (defun js2-print-while-node (n i)
2490 (let ((pad (js2-make-pad i)))
2491 (insert pad "while (")
2492 (js2-print-ast (js2-while-node-condition n) 0)
2494 (js2-print-body (js2-while-node-body n) (1+ i))
2495 (insert pad "}\n")))
2497 (defstruct (js2-for-node
2498 (:include js2-loop-node)
2500 (:constructor make-js2-for-node (&key (type js2-FOR)
2509 "AST node for a C-style for-loop."
2510 init ; initialization expression
2511 condition ; loop condition
2512 update) ; update clause
2514 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2515 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2517 (defun js2-visit-for-node (n v)
2518 (js2-visit-ast (js2-for-node-init n) v)
2519 (js2-visit-ast (js2-for-node-condition n) v)
2520 (js2-visit-ast (js2-for-node-update n) v)
2521 (js2-visit-ast (js2-for-node-body n) v))
2523 (defun js2-print-for-node (n i)
2524 (let ((pad (js2-make-pad i)))
2525 (insert pad "for (")
2526 (js2-print-ast (js2-for-node-init n) 0)
2528 (js2-print-ast (js2-for-node-condition n) 0)
2530 (js2-print-ast (js2-for-node-update n) 0)
2532 (js2-print-body (js2-for-node-body n) (1+ i))
2533 (insert pad "}\n")))
2535 (defstruct (js2-for-in-node
2536 (:include js2-loop-node)
2538 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2549 "AST node for a for..in loop."
2550 iterator ; [var] foo in ...
2551 object ; object over which we're iterating
2552 in-pos ; buffer position of 'in' keyword
2553 each-pos ; buffer position of 'each' keyword, if foreach-p
2554 foreach-p) ; t if it's a for-each loop
2556 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2557 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2559 (defun js2-visit-for-in-node (n v)
2560 (js2-visit-ast (js2-for-in-node-iterator n) v)
2561 (js2-visit-ast (js2-for-in-node-object n) v)
2562 (js2-visit-ast (js2-for-in-node-body n) v))
2564 (defun js2-print-for-in-node (n i)
2565 (let ((pad (js2-make-pad i))
2566 (foreach (js2-for-in-node-foreach-p n)))
2571 (js2-print-ast (js2-for-in-node-iterator n) 0)
2573 (js2-print-ast (js2-for-in-node-object n) 0)
2575 (js2-print-body (js2-for-in-node-body n) (1+ i))
2576 (insert pad "}\n")))
2578 (defstruct (js2-return-node
2581 (:constructor make-js2-return-node (&key (type js2-RETURN)
2585 "AST node for a return statement."
2586 retval) ; expression to return, or 'undefined
2588 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2589 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2591 (defun js2-visit-return-node (n v)
2592 (js2-visit-ast (js2-return-node-retval n) v))
2594 (defun js2-print-return-node (n i)
2595 (insert (js2-make-pad i) "return")
2596 (when (js2-return-node-retval n)
2598 (js2-print-ast (js2-return-node-retval n) 0))
2601 (defstruct (js2-if-node
2604 (:constructor make-js2-if-node (&key (type js2-IF)
2613 "AST node for an if-statement."
2614 condition ; expression
2615 then-part ; statement or block
2616 else-pos ; optional buffer position of 'else' keyword
2617 else-part ; optional statement or block
2618 lp ; position of left-paren, nil if omitted
2619 rp) ; position of right-paren, nil if omitted
2621 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2622 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2624 (defun js2-visit-if-node (n v)
2625 (js2-visit-ast (js2-if-node-condition n) v)
2626 (js2-visit-ast (js2-if-node-then-part n) v)
2627 (js2-visit-ast (js2-if-node-else-part n) v))
2629 (defun js2-print-if-node (n i)
2630 (let ((pad (js2-make-pad i))
2631 (then-part (js2-if-node-then-part n))
2632 (else-part (js2-if-node-else-part n)))
2634 (js2-print-ast (js2-if-node-condition n) 0)
2636 (js2-print-body then-part (1+ i))
2641 ((js2-if-node-p else-part)
2643 (js2-print-body else-part i))
2645 (insert " else {\n")
2646 (js2-print-body else-part (1+ i))
2647 (insert pad "}\n")))))
2649 (defstruct (js2-try-node
2652 (:constructor make-js2-try-node (&key (type js2-TRY)
2658 "AST node for a try-statement."
2660 catch-clauses ; a lisp list of `js2-catch-node'
2661 finally-block) ; a `js2-finally-node'
2663 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2664 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2666 (defun js2-visit-try-node (n v)
2667 (js2-visit-ast (js2-try-node-try-block n) v)
2668 (dolist (clause (js2-try-node-catch-clauses n))
2669 (js2-visit-ast clause v))
2670 (js2-visit-ast (js2-try-node-finally-block n) v))
2672 (defun js2-print-try-node (n i)
2673 (let ((pad (js2-make-pad i))
2674 (catches (js2-try-node-catch-clauses n))
2675 (finally (js2-try-node-finally-block n)))
2676 (insert pad "try {\n")
2677 (js2-print-body (js2-try-node-try-block n) (1+ i))
2680 (dolist (catch catches)
2681 (js2-print-ast catch i)))
2683 (js2-print-ast finally i)
2686 (defstruct (js2-catch-node
2689 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2698 "AST node for a catch clause."
2699 param ; destructuring form or simple name node
2700 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2701 guard-expr ; catch condition, a `js2-node'
2702 block ; statements, a `js2-block-node'
2703 lp ; buffer position of left-paren, nil if omitted
2704 rp) ; buffer position of right-paren, nil if omitted
2706 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2707 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2709 (defun js2-visit-catch-node (n v)
2710 (js2-visit-ast (js2-catch-node-param n) v)
2711 (when (js2-catch-node-guard-kwd n)
2712 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2713 (js2-visit-ast (js2-catch-node-block n) v))
2715 (defun js2-print-catch-node (n i)
2716 (let ((pad (js2-make-pad i))
2717 (guard-kwd (js2-catch-node-guard-kwd n))
2718 (guard-expr (js2-catch-node-guard-expr n)))
2720 (js2-print-ast (js2-catch-node-param n) 0)
2723 (js2-print-ast guard-expr 0))
2725 (js2-print-body (js2-catch-node-block n) (1+ i))
2728 (defstruct (js2-finally-node
2731 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2735 "AST node for a finally clause."
2736 body) ; a `js2-node', often but not always a block node
2738 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2739 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2741 (defun js2-visit-finally-node (n v)
2742 (js2-visit-ast (js2-finally-node-body n) v))
2744 (defun js2-print-finally-node (n i)
2745 (let ((pad (js2-make-pad i)))
2746 (insert " finally {\n")
2747 (js2-print-body (js2-finally-node-body n) (1+ i))
2748 (insert pad "}\n")))
2750 (defstruct (js2-switch-node
2753 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2760 "AST node for a switch statement."
2761 discriminant ; a `js2-node' (switch expression)
2762 cases ; a lisp list of `js2-case-node'
2763 lp ; position of open-paren for discriminant, nil if omitted
2764 rp) ; position of close-paren for discriminant, nil if omitted
2766 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2767 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2769 (defun js2-visit-switch-node (n v)
2770 (js2-visit-ast (js2-switch-node-discriminant n) v)
2771 (dolist (c (js2-switch-node-cases n))
2772 (js2-visit-ast c v)))
2774 (defun js2-print-switch-node (n i)
2775 (let ((pad (js2-make-pad i))
2776 (cases (js2-switch-node-cases n)))
2777 (insert pad "switch (")
2778 (js2-print-ast (js2-switch-node-discriminant n) 0)
2780 (dolist (case cases)
2781 (js2-print-ast case i))
2782 (insert pad "}\n")))
2784 (defstruct (js2-case-node
2785 (:include js2-block-node)
2787 (:constructor make-js2-case-node (&key (type js2-CASE)
2792 "AST node for a case clause of a switch statement."
2793 expr) ; the case expression (nil for default)
2795 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2796 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2798 (defun js2-visit-case-node (n v)
2799 (js2-visit-ast (js2-case-node-expr n) v)
2800 (js2-visit-block n v))
2802 (defun js2-print-case-node (n i)
2803 (let ((pad (js2-make-pad i))
2804 (expr (js2-case-node-expr n)))
2807 (insert "default:\n")
2809 (js2-print-ast expr 0)
2811 (dolist (kid (js2-case-node-kids n))
2812 (js2-print-ast kid (1+ i)))))
2814 (defstruct (js2-throw-node
2817 (:constructor make-js2-throw-node (&key (type js2-THROW)
2821 "AST node for a throw statement."
2822 expr) ; the expression to throw
2824 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2825 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2827 (defun js2-visit-throw-node (n v)
2828 (js2-visit-ast (js2-throw-node-expr n) v))
2830 (defun js2-print-throw-node (n i)
2831 (insert (js2-make-pad i) "throw ")
2832 (js2-print-ast (js2-throw-node-expr n) 0)
2835 (defstruct (js2-with-node
2838 (:constructor make-js2-with-node (&key (type js2-WITH)
2845 "AST node for a with-statement."
2848 lp ; buffer position of left-paren around object, nil if omitted
2849 rp) ; buffer position of right-paren around object, nil if omitted
2851 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2852 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2854 (defun js2-visit-with-node (n v)
2855 (js2-visit-ast (js2-with-node-object n) v)
2856 (js2-visit-ast (js2-with-node-body n) v))
2858 (defun js2-print-with-node (n i)
2859 (let ((pad (js2-make-pad i)))
2860 (insert pad "with (")
2861 (js2-print-ast (js2-with-node-object n) 0)
2863 (js2-print-body (js2-with-node-body n) (1+ i))
2864 (insert pad "}\n")))
2866 (defstruct (js2-label-node
2869 (:constructor make-js2-label-node (&key (type js2-LABEL)
2873 "AST node for a statement label or case label."
2875 loop) ; for validating and code-generating continue-to-label
2877 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2878 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2880 (defun js2-print-label (n i)
2881 (insert (js2-make-pad i)
2882 (js2-label-node-name n)
2885 (defstruct (js2-labeled-stmt-node
2888 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2889 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2890 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2895 "AST node for a statement with one or more labels.
2896 Multiple labels for a statement are collapsed into the labels field."
2897 labels ; lisp list of `js2-label-node'
2898 stmt) ; the statement these labels are for
2900 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2901 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2903 (defun js2-get-label-by-name (lbl-stmt name)
2904 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2905 Returns nil if no such label is in the list."
2906 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2908 (while (and label-list (not result))
2909 (if (string= (js2-label-node-name (car label-list)) name)
2910 (setq result (car label-list))
2911 (setq label-list (cdr label-list))))
2914 (defun js2-visit-labeled-stmt (n v)
2915 (dolist (label (js2-labeled-stmt-node-labels n))
2916 (js2-visit-ast label v))
2917 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2919 (defun js2-print-labeled-stmt (n i)
2920 (dolist (label (js2-labeled-stmt-node-labels n))
2921 (js2-print-ast label i))
2922 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2924 (defun js2-labeled-stmt-node-contains (node label)
2925 "Return t if NODE contains LABEL in its label set.
2926 NODE is a `js2-labels-node'. LABEL is an identifier."
2927 (loop for nl in (js2-labeled-stmt-node-labels node)
2928 if (string= label (js2-label-node-name nl))
2930 finally return nil))
2932 (defsubst js2-labeled-stmt-node-add-label (node label)
2933 "Add a `js2-label-node' to the label set for this statement."
2934 (setf (js2-labeled-stmt-node-labels node)
2935 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2937 (defstruct (js2-jump-node
2940 "Abstract supertype of break and continue nodes."
2941 label ; `js2-name-node' for location of label identifier, if present
2942 target) ; target js2-labels-node or loop/switch statement
2944 (defun js2-visit-jump-node (n v)
2945 (js2-visit-ast (js2-jump-node-label n) v))
2947 (defstruct (js2-break-node
2948 (:include js2-jump-node)
2950 (:constructor make-js2-break-node (&key (type js2-BREAK)
2955 "AST node for a break statement.
2956 The label field is a `js2-name-node', possibly nil, for the named label
2957 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2958 is the target of the break - a label node or enclosing loop/switch statement.")
2960 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2961 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2963 (defun js2-print-break-node (n i)
2964 (insert (js2-make-pad i) "break")
2965 (when (js2-break-node-label n)
2967 (js2-print-ast (js2-break-node-label n) 0))
2970 (defstruct (js2-continue-node
2971 (:include js2-jump-node)
2973 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2978 "AST node for a continue statement.
2979 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2980 It is nil if continue specifies no label. The target field is the jump target:
2981 a `js2-label-node' or the innermost enclosing loop.")
2983 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2984 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2986 (defun js2-print-continue-node (n i)
2987 (insert (js2-make-pad i) "continue")
2988 (when (js2-continue-node-label n)
2990 (js2-print-ast (js2-continue-node-label n) 0))
2993 (defstruct (js2-function-node
2994 (:include js2-script-node)
2996 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3000 (form 'FUNCTION_STATEMENT)
3006 "AST node for a function declaration.
3007 The `params' field is a lisp list of nodes. Each node is either a simple
3008 `js2-name-node', or if it's a destructuring-assignment parameter, a
3009 `js2-array-node' or `js2-object-node'."
3010 ftype ; FUNCTION, GETTER or SETTER
3011 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3012 name ; function name (a `js2-name-node', or nil if anonymous)
3013 params ; a lisp list of destructuring forms or simple name nodes
3014 body ; a `js2-block-node' or expression node (1.8 only)
3015 lp ; position of arg-list open-paren, or nil if omitted
3016 rp ; position of arg-list close-paren, or nil if omitted
3017 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3018 needs-activation ; t if we need an activation object for this frame
3019 is-generator ; t if this function contains a yield
3020 member-expr) ; nonstandard Ecma extension from Rhino
3022 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3023 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3025 (defun js2-visit-function-node (n v)
3026 (js2-visit-ast (js2-function-node-name n) v)
3027 (dolist (p (js2-function-node-params n))
3028 (js2-visit-ast p v))
3029 (js2-visit-ast (js2-function-node-body n) v))
3031 (defun js2-print-function-node (n i)
3032 (let ((pad (js2-make-pad i))
3033 (getter (js2-node-get-prop n 'GETTER_SETTER))
3034 (name (js2-function-node-name n))
3035 (params (js2-function-node-params n))
3036 (body (js2-function-node-body n))
3037 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3039 (insert pad "function"))
3042 (js2-print-ast name 0))
3044 (loop with len = (length params)
3048 (js2-print-ast param 0)
3054 ;; TODO: fix this to be smarter about indenting, etc.
3055 (js2-print-body body (1+ i))
3060 (defsubst js2-function-name (node)
3061 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3062 (and (js2-function-node-name node)
3063 (js2-name-node-name (js2-function-node-name node))))
3065 ;; Having this be an expression node makes it more flexible.
3066 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3067 ;; that work better if you assume it's an expression. Whenever we have
3068 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3069 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3070 (defstruct (js2-var-decl-node
3073 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3078 "AST node for a variable declaration list (VAR, CONST or LET).
3079 The node bounds differ depending on the declaration type. For VAR or
3080 CONST declarations, the bounds include the var/const keyword. For LET
3081 declarations, the node begins at the position of the first child."
3082 kids ; a lisp list of `js2-var-init-node' structs.
3083 decl-type) ; js2-VAR, js2-CONST or js2-LET
3085 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3086 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3088 (defun js2-visit-var-decl (n v)
3089 (dolist (kid (js2-var-decl-node-kids n))
3090 (js2-visit-ast kid v)))
3092 (defun js2-print-var-decl (n i)
3093 (let ((pad (js2-make-pad i))
3094 (tt (js2-var-decl-node-decl-type n)))
3097 ((= tt js2-VAR) "var ")
3098 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3099 ((= tt js2-CONST) "const ")
3101 (error "malformed var-decl node"))))
3102 (loop with kids = (js2-var-decl-node-kids n)
3103 with len = (length kids)
3107 (js2-print-ast kid 0)
3111 (defstruct (js2-var-init-node
3114 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3119 "AST node for a variable declaration.
3120 The type field will be js2-CONST for a const decl."
3121 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3122 initializer) ; initializer expression, a `js2-node'
3124 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3125 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3127 (defun js2-visit-var-init-node (n v)
3128 (js2-visit-ast (js2-var-init-node-target n) v)
3129 (js2-visit-ast (js2-var-init-node-initializer n) v))
3131 (defun js2-print-var-init-node (n i)
3132 (let ((pad (js2-make-pad i))
3133 (name (js2-var-init-node-target n))
3134 (init (js2-var-init-node-initializer n)))
3136 (js2-print-ast name 0)
3139 (js2-print-ast init 0))))
3141 (defstruct (js2-cond-node
3144 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3152 "AST node for the ternary operator"
3156 q-pos ; buffer position of ?
3157 c-pos) ; buffer position of :
3159 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3160 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3162 (defun js2-visit-cond-node (n v)
3163 (js2-visit-ast (js2-cond-node-test-expr n) v)
3164 (js2-visit-ast (js2-cond-node-true-expr n) v)
3165 (js2-visit-ast (js2-cond-node-false-expr n) v))
3167 (defun js2-print-cond-node (n i)
3168 (let ((pad (js2-make-pad i)))
3170 (js2-print-ast (js2-cond-node-test-expr n) 0)
3172 (js2-print-ast (js2-cond-node-true-expr n) 0)
3174 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3176 (defstruct (js2-infix-node
3179 (:constructor make-js2-infix-node (&key type
3185 "Represents infix expressions.
3186 Includes assignment ops like `|=', and the comma operator.
3187 The type field inherited from `js2-node' holds the operator."
3188 op-pos ; buffer position where operator begins
3189 left ; any `js2-node'
3190 right) ; any `js2-node'
3192 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3193 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3195 (defun js2-visit-infix-node (n v)
3196 (js2-visit-ast (js2-infix-node-left n) v)
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 (js2-visit-ast (js2-let-node-vars n) v)
3336 (js2-visit-ast (js2-let-node-body n) v))
3338 (defun js2-print-let-node (n i)
3339 (insert (js2-make-pad i) "let (")
3340 (js2-print-ast (js2-let-node-vars n) 0)
3342 (js2-print-ast (js2-let-node-body n) i))
3344 (defstruct (js2-keyword-node
3347 (:constructor make-js2-keyword-node (&key type
3349 (len (- js2-ts-cursor pos)))))
3350 "AST node representing a literal keyword such as `null'.
3351 Used for `null', `this', `true', `false' and `debugger'.
3352 The node type is set to js2-NULL, js2-THIS, etc.")
3354 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3355 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3357 (defun js2-print-keyword-node (n i)
3358 (insert (js2-make-pad i)
3359 (let ((tt (js2-node-type n)))
3361 ((= tt js2-THIS) "this")
3362 ((= tt js2-NULL) "null")
3363 ((= tt js2-TRUE) "true")
3364 ((= tt js2-FALSE) "false")
3365 ((= tt js2-DEBUGGER) "debugger")
3366 (t (error "Invalid keyword literal type: %d" tt))))))
3368 (defsubst js2-this-node-p (node)
3369 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3370 (eq (js2-node-type node) js2-THIS))
3372 (defstruct (js2-new-node
3375 (:constructor make-js2-new-node (&key (type js2-NEW)
3383 "AST node for new-expression such as new Foo()."
3384 target ; an identifier or reference
3385 args ; a lisp list of argument nodes
3386 lp ; position of left-paren, nil if omitted
3387 rp ; position of right-paren, nil if omitted
3388 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3390 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3391 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3393 (defun js2-visit-new-node (n v)
3394 (js2-visit-ast (js2-new-node-target n) v)
3395 (dolist (arg (js2-new-node-args n))
3396 (js2-visit-ast arg v))
3397 (js2-visit-ast (js2-new-node-initializer n) v))
3399 (defun js2-print-new-node (n i)
3400 (insert (js2-make-pad i) "new ")
3401 (js2-print-ast (js2-new-node-target n))
3403 (js2-print-list (js2-new-node-args n))
3405 (when (js2-new-node-initializer n)
3407 (js2-print-ast (js2-new-node-initializer n))))
3409 (defstruct (js2-name-node
3412 (:constructor make-js2-name-node (&key (type js2-NAME)
3414 (len (- js2-ts-cursor
3416 (name js2-ts-string))))
3417 "AST node for a JavaScript identifier"
3419 scope) ; a `js2-scope' (optional, used for codegen)
3421 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3422 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3424 (defun js2-print-name-node (n i)
3425 (insert (js2-make-pad i)
3426 (js2-name-node-name n)))
3428 (defsubst js2-name-node-length (node)
3429 "Return identifier length of NODE, a `js2-name-node'.
3430 Returns 0 if NODE is nil or its identifier field is nil."
3432 (length (js2-name-node-name node))
3435 (defstruct (js2-number-node
3438 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3440 (len (- js2-ts-cursor
3442 (value js2-ts-string)
3443 (num-value js2-ts-number))))
3444 "AST node for a number literal."
3445 value ; the original string, e.g. "6.02e23"
3446 num-value) ; the parsed number value
3448 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3449 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3451 (defun js2-print-number-node (n i)
3452 (insert (js2-make-pad i)
3453 (number-to-string (js2-number-node-num-value n))))
3455 (defstruct (js2-regexp-node
3458 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3460 (len (- js2-ts-cursor
3464 "AST node for a regular expression literal."
3465 value ; the regexp string, without // delimiters
3466 flags) ; a string of flags, e.g. `mi'.
3468 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3469 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3471 (defun js2-print-regexp (n i)
3472 (insert (js2-make-pad i)
3474 (js2-regexp-node-value n)
3476 (if (js2-regexp-node-flags n)
3477 (insert (js2-regexp-node-flags n))))
3479 (defstruct (js2-string-node
3482 (:constructor make-js2-string-node (&key (type js2-STRING)
3484 (len (- js2-ts-cursor
3486 (value js2-ts-string))))
3488 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3489 You can tell the quote type by looking at the first character."
3490 value) ; the characters of the string, including the quotes
3492 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3493 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3495 (defun js2-print-string-node (n i)
3496 (insert (js2-make-pad i)
3497 (js2-node-string n)))
3499 (defstruct (js2-array-node
3502 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3506 "AST node for an array literal."
3507 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3509 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3510 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3512 (defun js2-visit-array-node (n v)
3513 (dolist (e (js2-array-node-elems n))
3514 (js2-visit-ast e v)))
3516 (defun js2-print-array-node (n i)
3517 (insert (js2-make-pad i) "[")
3518 (js2-print-list (js2-array-node-elems n))
3521 (defstruct (js2-object-node
3524 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3528 "AST node for an object literal expression.
3529 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3530 the latter represents abbreviation in destructuring expressions."
3533 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3534 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3536 (defun js2-visit-object-node (n v)
3537 (dolist (e (js2-object-node-elems n))
3538 (js2-visit-ast e v)))
3540 (defun js2-print-object-node (n i)
3541 (insert (js2-make-pad i) "{")
3542 (js2-print-list (js2-object-node-elems n))
3545 (defstruct (js2-object-prop-node
3546 (:include js2-infix-node)
3548 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3554 "AST node for an object literal prop:value entry.
3555 The `left' field is the property: a name node, string node or number node.
3556 The `right' field is a `js2-node' representing the initializer value.")
3558 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3559 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3561 (defun js2-print-object-prop-node (n i)
3562 (insert (js2-make-pad i))
3563 (js2-print-ast (js2-object-prop-node-left n) 0)
3565 (js2-print-ast (js2-object-prop-node-right n) 0))
3567 (defstruct (js2-getter-setter-node
3568 (:include js2-infix-node)
3570 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3575 "AST node for a getter/setter property in an object literal.
3576 The `left' field is the `js2-name-node' naming the getter/setter prop.
3577 The `right' field is always an anonymous `js2-function-node' with a node
3578 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3580 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3581 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3583 (defun js2-print-getter-setter (n i)
3584 (let ((pad (js2-make-pad i))
3585 (left (js2-getter-setter-node-left n))
3586 (right (js2-getter-setter-node-right n)))
3588 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3589 (js2-print-ast left 0)
3590 (js2-print-ast right 0)))
3592 (defstruct (js2-prop-get-node
3593 (:include js2-infix-node)
3595 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3600 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3602 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3603 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3605 (defun js2-visit-prop-get-node (n v)
3606 (js2-visit-ast (js2-prop-get-node-left n) v)
3607 (js2-visit-ast (js2-prop-get-node-right n) v))
3609 (defun js2-print-prop-get-node (n i)
3610 (insert (js2-make-pad i))
3611 (js2-print-ast (js2-prop-get-node-left n) 0)
3613 (js2-print-ast (js2-prop-get-node-right n) 0))
3615 (defstruct (js2-elem-get-node
3618 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3625 "AST node for an array index expression such as foo[bar]."
3626 target ; a `js2-node' - the expression preceding the "."
3627 element ; a `js2-node' - the expression in brackets
3628 lb ; position of left-bracket, nil if omitted
3629 rb) ; position of right-bracket, nil if omitted
3631 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3632 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3634 (defun js2-visit-elem-get-node (n v)
3635 (js2-visit-ast (js2-elem-get-node-target n) v)
3636 (js2-visit-ast (js2-elem-get-node-element n) v))
3638 (defun js2-print-elem-get-node (n i)
3639 (insert (js2-make-pad i))
3640 (js2-print-ast (js2-elem-get-node-target n) 0)
3642 (js2-print-ast (js2-elem-get-node-element n) 0)
3645 (defstruct (js2-call-node
3648 (:constructor make-js2-call-node (&key (type js2-CALL)
3655 "AST node for a JavaScript function call."
3656 target ; a `js2-node' evaluating to the function to call
3657 args ; a lisp list of `js2-node' arguments
3658 lp ; position of open-paren, or nil if missing
3659 rp) ; position of close-paren, or nil if missing
3661 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3662 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3664 (defun js2-visit-call-node (n v)
3665 (js2-visit-ast (js2-call-node-target n) v)
3666 (dolist (arg (js2-call-node-args n))
3667 (js2-visit-ast arg v)))
3669 (defun js2-print-call-node (n i)
3670 (insert (js2-make-pad i))
3671 (js2-print-ast (js2-call-node-target n) 0)
3673 (js2-print-list (js2-call-node-args n))
3676 (defstruct (js2-yield-node
3679 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3683 "AST node for yield statement or expression."
3684 value) ; optional: value to be yielded
3686 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3687 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3689 (defun js2-visit-yield-node (n v)
3690 (js2-visit-ast (js2-yield-node-value n) v))
3692 (defun js2-print-yield-node (n i)
3693 (insert (js2-make-pad i))
3695 (when (js2-yield-node-value n)
3697 (js2-print-ast (js2-yield-node-value n) 0)))
3699 (defstruct (js2-paren-node
3702 (:constructor make-js2-paren-node (&key (type js2-LP)
3706 "AST node for a parenthesized expression.
3707 In particular, used when the parens are syntactically optional,
3708 as opposed to required parens such as those enclosing an if-conditional."
3711 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3712 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3714 (defun js2-visit-paren-node (n v)
3715 (js2-visit-ast (js2-paren-node-expr n) v))
3717 (defun js2-print-paren-node (n i)
3718 (insert (js2-make-pad i))
3720 (js2-print-ast (js2-paren-node-expr n) 0)
3723 (defstruct (js2-array-comp-node
3724 (:include js2-scope)
3726 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3735 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3736 result ; result expression (just after left-bracket)
3737 loops ; a lisp list of `js2-array-comp-loop-node'
3738 filter ; guard/filter expression
3739 if-pos ; buffer pos of 'if' keyword, if present, else nil
3740 lp ; buffer position of if-guard left-paren, or nil if not present
3741 rp) ; buffer position of if-guard right-paren, or nil if not present
3743 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3744 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3746 (defun js2-visit-array-comp-node (n v)
3747 (js2-visit-ast (js2-array-comp-node-result n) v)
3748 (dolist (l (js2-array-comp-node-loops n))
3749 (js2-visit-ast l v))
3750 (js2-visit-ast (js2-array-comp-node-filter n) v))
3752 (defun js2-print-array-comp-node (n i)
3753 (let ((pad (js2-make-pad i))
3754 (result (js2-array-comp-node-result n))
3755 (loops (js2-array-comp-node-loops n))
3756 (filter (js2-array-comp-node-filter n)))
3758 (js2-print-ast result 0)
3761 (js2-print-ast l 0))
3764 (js2-print-ast filter 0))
3767 (defstruct (js2-array-comp-loop-node
3768 (:include js2-for-in-node)
3770 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3780 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3782 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3783 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3785 (defun js2-visit-array-comp-loop (n v)
3786 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3787 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3789 (defun js2-print-array-comp-loop (n i)
3791 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3793 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3796 (defstruct (js2-empty-expr-node
3799 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3802 "AST node for an empty expression.")
3804 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3805 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3807 (defstruct (js2-xml-node
3808 (:include js2-block-node)
3810 (:constructor make-js2-xml-node (&key (type js2-XML)
3814 "AST node for initial parse of E4X literals.
3815 The kids field is a list of XML fragments, each a `js2-string-node' or
3816 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3818 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3819 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3821 (defun js2-print-xml-node (n i)
3822 (dolist (kid (js2-xml-node-kids n))
3823 (js2-print-ast kid i)))
3825 (defstruct (js2-xml-js-expr-node
3826 (:include js2-xml-node)
3828 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3832 "AST node for an embedded JavaScript {expression} in an E4X literal.
3833 The start and end fields correspond to the curly-braces."
3834 expr) ; a `js2-expr-node' of some sort
3836 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3837 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3839 (defun js2-visit-xml-js-expr (n v)
3840 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3842 (defun js2-print-xml-js-expr (n i)
3843 (insert (js2-make-pad i))
3845 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3848 (defstruct (js2-xml-dot-query-node
3849 (:include js2-infix-node)
3851 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3858 "AST node for an E4X foo.(bar) filter expression.
3859 Note that the left-paren is automatically the character immediately
3860 following the dot (.) in the operator. No whitespace is permitted
3861 between the dot and the lp by the scanner."
3864 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3865 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3867 (defun js2-print-xml-dot-query (n i)
3868 (insert (js2-make-pad i))
3869 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3871 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3874 (defstruct (js2-xml-ref-node
3876 (:constructor nil)) ; abstract
3877 "Base type for E4X XML attribute-access or property-get expressions.
3878 Such expressions can take a variety of forms. The general syntax has
3881 - (optional) an @ (specifying an attribute access)
3882 - (optional) a namespace (a `js2-name-node') and double-colon
3883 - (required) either a `js2-name-node' or a bracketed [expression]
3885 The property-name expressions (examples: ns::name, @name) are
3886 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3887 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3889 This node type (or more specifically, its subclasses) will sometimes
3890 be the right-hand child of a `js2-prop-get-node' or a
3891 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3892 The `js2-xml-ref-node' may also be a standalone primary expression with
3893 no explicit target, which is valid in certain expression contexts such as
3895 company..employee.(@id < 100)
3897 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3898 expression whose parent is a `js2-xml-dot-query-node'."
3903 (defsubst js2-xml-ref-node-attr-access-p (node)
3904 "Return non-nil if this expression began with an @-token."
3905 (and (numberp (js2-xml-ref-node-at-pos node))
3906 (plusp (js2-xml-ref-node-at-pos node))))
3908 (defstruct (js2-xml-prop-ref-node
3909 (:include js2-xml-ref-node)
3911 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3918 "AST node for an E4X XML [expr] property-ref expression.
3919 The JavaScript syntax is an optional @, an optional ns::, and a name.
3921 [ '@' ] [ name '::' ] name
3923 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3924 @ns::*, @*::attr, @*::*, and @*.
3926 The node starts at the @ token, if present. Otherwise it starts at the
3927 namespace name. The node bounds extend through the closing right-bracket,
3928 or if it is missing due to a syntax error, through the end of the index
3932 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3933 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3935 (defun js2-visit-xml-prop-ref-node (n v)
3936 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3937 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3939 (defun js2-print-xml-prop-ref-node (n i)
3940 (insert (js2-make-pad i))
3941 (if (js2-xml-ref-node-attr-access-p n)
3943 (when (js2-xml-prop-ref-node-namespace n)
3944 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3946 (if (js2-xml-prop-ref-node-propname n)
3947 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3949 (defstruct (js2-xml-elem-ref-node
3950 (:include js2-xml-ref-node)
3952 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3961 "AST node for an E4X XML [expr] member-ref expression.
3964 [ '@' ] [ name '::' ] '[' expr ']'
3966 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3968 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3969 is not a legal E4X XML element-ref expression, since it's already used
3970 for standard JavaScript element-get array indexing. Hence, a
3971 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3972 non-nil namespace node, or both.
3974 The node starts at the @ token, if present. Otherwise it starts
3975 at the namespace name. The node bounds extend through the closing
3976 right-bracket, or if it is missing due to a syntax error, through the
3977 end of the index expression."
3978 expr ; the bracketed index expression
3982 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3983 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3985 (defun js2-visit-xml-elem-ref-node (n v)
3986 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3987 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3989 (defun js2-print-xml-elem-ref-node (n i)
3990 (insert (js2-make-pad i))
3991 (if (js2-xml-ref-node-attr-access-p n)
3993 (when (js2-xml-elem-ref-node-namespace n)
3994 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3997 (if (js2-xml-elem-ref-node-expr n)
3998 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4001 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4003 (defstruct (js2-xml-start-tag-node
4004 (:include js2-xml-node)
4006 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4013 "AST node for an XML start-tag. Not currently used.
4014 The `kids' field is a lisp list of child content nodes."
4015 name ; a `js2-xml-name-node'
4016 attrs ; a lisp list of `js2-xml-attr-node'
4017 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4019 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4020 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4022 (defun js2-visit-xml-start-tag (n v)
4023 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4024 (dolist (attr (js2-xml-start-tag-node-attrs n))
4025 (js2-visit-ast attr v))
4026 (js2-visit-block n v))
4028 (defun js2-print-xml-start-tag (n i)
4029 (insert (js2-make-pad i) "<")
4030 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4031 (when (js2-xml-start-tag-node-attrs n)
4033 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4036 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4037 ;; and add the end-tag to the kids list of the parent as well.
4038 (defstruct (js2-xml-end-tag-node
4039 (:include js2-xml-node)
4041 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4045 "AST node for an XML end-tag. Not currently used."
4046 name) ; a `js2-xml-name-node'
4048 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4049 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4051 (defun js2-visit-xml-end-tag (n v)
4052 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4054 (defun js2-print-xml-end-tag (n i)
4055 (insert (js2-make-pad i))
4057 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4060 (defstruct (js2-xml-name-node
4061 (:include js2-xml-node)
4063 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4068 "AST node for an E4X XML name. Not currently used.
4069 Any XML name can be qualified with a namespace, hence the namespace field.
4070 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4071 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4072 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4073 namespace) ; a `js2-string-node'
4075 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4076 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4078 (defun js2-visit-xml-name-node (n v)
4079 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4081 (defun js2-print-xml-name-node (n i)
4082 (insert (js2-make-pad i))
4083 (when (js2-xml-name-node-namespace n)
4084 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4086 (dolist (kid (js2-xml-name-node-kids n))
4087 (js2-print-ast kid 0)))
4089 (defstruct (js2-xml-pi-node
4090 (:include js2-xml-node)
4092 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4097 "AST node for an E4X XML processing instruction. Not currently used."
4098 name ; a `js2-xml-name-node'
4099 attrs) ; a list of `js2-xml-attr-node'
4101 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4102 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4104 (defun js2-visit-xml-pi-node (n v)
4105 (js2-visit-ast (js2-xml-pi-node-name n) v)
4106 (dolist (attr (js2-xml-pi-node-attrs n))
4107 (js2-visit-ast attr v)))
4109 (defun js2-print-xml-pi-node (n i)
4110 (insert (js2-make-pad i) "<?")
4111 (js2-print-ast (js2-xml-pi-node-name n))
4112 (when (js2-xml-pi-node-attrs n)
4114 (js2-print-list (js2-xml-pi-node-attrs n)))
4117 (defstruct (js2-xml-cdata-node
4118 (:include js2-xml-node)
4120 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4124 "AST node for a CDATA escape section. Not currently used."
4125 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4127 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4128 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4130 (defun js2-visit-xml-cdata-node (n v)
4131 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4133 (defun js2-print-xml-cdata-node (n i)
4134 (insert (js2-make-pad i))
4135 (js2-print-ast (js2-xml-cdata-node-content n)))
4137 (defstruct (js2-xml-attr-node
4138 (:include js2-xml-node)
4140 (:constructor make-js2-attr-node (&key (type js2-XML)
4147 "AST node representing a foo='bar' XML attribute value. Not yet used."
4148 name ; a `js2-xml-name-node'
4149 value ; a `js2-xml-name-node'
4150 eq-pos ; buffer position of "=" sign
4151 quote-type) ; 'single or 'double
4153 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4154 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4156 (defun js2-visit-xml-attr-node (n v)
4157 (js2-visit-ast (js2-xml-attr-node-name n) v)
4158 (js2-visit-ast (js2-xml-attr-node-value n) v))
4160 (defun js2-print-xml-attr-node (n i)
4161 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4164 (insert (js2-make-pad i))
4165 (js2-print-ast (js2-xml-attr-node-name n) 0)
4167 (js2-print-ast (js2-xml-attr-node-value n) 0)
4170 (defstruct (js2-xml-text-node
4171 (:include js2-xml-node)
4173 (:constructor make-js2-text-node (&key (type js2-XML)
4177 "AST node for an E4X XML text node. Not currently used."
4178 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4180 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4181 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4183 (defun js2-visit-xml-text-node (n v)
4184 (js2-visit-ast (js2-xml-text-node-content n) v))
4186 (defun js2-print-xml-text-node (n i)
4187 (insert (js2-make-pad i))
4188 (dolist (kid (js2-xml-text-node-content n))
4189 (js2-print-ast kid)))
4191 (defstruct (js2-xml-comment-node
4192 (:include js2-xml-node)
4194 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4197 "AST node for E4X XML comment. Not currently used.")
4199 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4200 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4202 (defun js2-print-xml-comment (n i)
4203 (insert (js2-make-pad i)
4204 (js2-node-string n)))
4208 (defsubst js2-node-line (n)
4209 "Fetch the source line number at the start of node N.
4210 This is O(n) in the length of the source buffer; use prudently."
4211 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4213 (defsubst js2-block-node-kid (n i)
4214 "Return child I of node N, or nil if there aren't that many."
4215 (nth i (js2-block-node-kids n)))
4217 (defsubst js2-block-node-first (n)
4218 "Return first child of block node N, or nil if there is none."
4219 (first (js2-block-node-kids n)))
4221 (defun js2-node-root (n)
4222 "Return the root of the AST containing N.
4223 If N has no parent pointer, returns N."
4224 (let ((parent (js2-node-parent n)))
4226 (js2-node-root parent)
4229 (defun js2-node-position-in-parent (node &optional parent)
4230 "Return the position of NODE in parent's block-kids list.
4231 PARENT can be supplied if known. Positioned returned is zero-indexed.
4232 Returns 0 if NODE is not a child of a block statement, or if NODE
4233 is not a statement node."
4234 (let ((p (or parent (js2-node-parent node)))
4236 (if (not (js2-block-node-p p))
4238 (or (js2-position node (js2-block-node-kids p))
4241 (defsubst js2-node-short-name (n)
4242 "Return the short name of node N as a string, e.g. `js2-if-node'."
4243 (substring (symbol-name (aref n 0))
4244 (length "cl-struct-")))
4246 (defsubst js2-node-child-list (node)
4247 "Return the child list for NODE, a lisp list of nodes.
4248 Works for block nodes, array nodes, obj literals, funarg lists,
4249 var decls and try nodes (for catch clauses). Note that you should call
4250 `js2-block-node-kids' on the function body for the body statements.
4251 Returns nil for zero-length child lists or unsupported nodes."
4253 ((js2-function-node-p node)
4254 (js2-function-node-params node))
4255 ((js2-block-node-p node)
4256 (js2-block-node-kids node))
4257 ((js2-try-node-p node)
4258 (js2-try-node-catch-clauses node))
4259 ((js2-array-node-p node)
4260 (js2-array-node-elems node))
4261 ((js2-object-node-p node)
4262 (js2-object-node-elems node))
4263 ((js2-call-node-p node)
4264 (js2-call-node-args node))
4265 ((js2-new-node-p node)
4266 (js2-new-node-args node))
4267 ((js2-var-decl-node-p node)
4268 (js2-var-decl-node-kids node))
4272 (defsubst js2-node-set-child-list (node kids)
4273 "Set the child list for NODE to KIDS."
4275 ((js2-function-node-p node)
4276 (setf (js2-function-node-params node) kids))
4277 ((js2-block-node-p node)
4278 (setf (js2-block-node-kids node) kids))
4279 ((js2-try-node-p node)
4280 (setf (js2-try-node-catch-clauses node) kids))
4281 ((js2-array-node-p node)
4282 (setf (js2-array-node-elems node) kids))
4283 ((js2-object-node-p node)
4284 (setf (js2-object-node-elems node) kids))
4285 ((js2-call-node-p node)
4286 (setf (js2-call-node-args node) kids))
4287 ((js2-new-node-p node)
4288 (setf (js2-new-node-args node) kids))
4289 ((js2-var-decl-node-p node)
4290 (setf (js2-var-decl-node-kids node) kids))
4292 (error "Unsupported node type: %s" (js2-node-short-name node))))
4295 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4296 (defconst js2-paren-expr-nodes
4297 '(cl-struct-js2-array-comp-loop-node
4298 cl-struct-js2-array-comp-node
4299 cl-struct-js2-call-node
4300 cl-struct-js2-catch-node
4301 cl-struct-js2-do-node
4302 cl-struct-js2-elem-get-node
4303 cl-struct-js2-for-in-node
4304 cl-struct-js2-for-node
4305 cl-struct-js2-function-node
4306 cl-struct-js2-if-node
4307 cl-struct-js2-let-node
4308 cl-struct-js2-new-node
4309 cl-struct-js2-paren-node
4310 cl-struct-js2-switch-node
4311 cl-struct-js2-while-node
4312 cl-struct-js2-with-node
4313 cl-struct-js2-xml-dot-query-node)
4314 "Node types that can have a parenthesized child expression.
4315 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4317 (defsubst js2-paren-expr-node-p (node)
4318 "Return t for nodes that typically have a parenthesized child expression.
4319 Useful for computing the indentation anchors for arg-lists and conditions.
4320 Note that it may return a false positive, for instance when NODE is
4321 a `js2-new-node' and there are no arguments or parentheses."
4322 (memq (aref node 0) js2-paren-expr-nodes))
4324 ;; Fake polymorphism... yech.
4325 (defsubst js2-node-lp (node)
4326 "Return relative left-paren position for NODE, if applicable.
4327 For `js2-elem-get-node' structs, returns left-bracket position.
4328 Note that the position may be nil in the case of a parse error."
4330 ((js2-elem-get-node-p node)
4331 (js2-elem-get-node-lb node))
4332 ((js2-loop-node-p node)
4333 (js2-loop-node-lp node))
4334 ((js2-function-node-p node)
4335 (js2-function-node-lp node))
4336 ((js2-if-node-p node)
4337 (js2-if-node-lp node))
4338 ((js2-new-node-p node)
4339 (js2-new-node-lp node))
4340 ((js2-call-node-p node)
4341 (js2-call-node-lp node))
4342 ((js2-paren-node-p node)
4343 (js2-node-pos node))
4344 ((js2-switch-node-p node)
4345 (js2-switch-node-lp node))
4346 ((js2-catch-node-p node)
4347 (js2-catch-node-lp node))
4348 ((js2-let-node-p node)
4349 (js2-let-node-lp node))
4350 ((js2-array-comp-node-p node)
4351 (js2-array-comp-node-lp node))
4352 ((js2-with-node-p node)
4353 (js2-with-node-lp node))
4354 ((js2-xml-dot-query-node-p node)
4355 (1+ (js2-infix-node-op-pos node)))
4357 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4359 ;; Fake polymorphism... blech.
4360 (defsubst js2-node-rp (node)
4361 "Return relative right-paren position for NODE, if applicable.
4362 For `js2-elem-get-node' structs, returns right-bracket position.
4363 Note that the position may be nil in the case of a parse error."
4365 ((js2-elem-get-node-p node)
4366 (js2-elem-get-node-lb node))
4367 ((js2-loop-node-p node)
4368 (js2-loop-node-rp node))
4369 ((js2-function-node-p node)
4370 (js2-function-node-rp node))
4371 ((js2-if-node-p node)
4372 (js2-if-node-rp node))
4373 ((js2-new-node-p node)
4374 (js2-new-node-rp node))
4375 ((js2-call-node-p node)
4376 (js2-call-node-rp node))
4377 ((js2-paren-node-p node)
4378 (+ (js2-node-pos node) (js2-node-len node)))
4379 ((js2-switch-node-p node)
4380 (js2-switch-node-rp node))
4381 ((js2-catch-node-p node)
4382 (js2-catch-node-rp node))
4383 ((js2-let-node-p node)
4384 (js2-let-node-rp node))
4385 ((js2-array-comp-node-p node)
4386 (js2-array-comp-node-rp node))
4387 ((js2-with-node-p node)
4388 (js2-with-node-rp node))
4389 ((js2-xml-dot-query-node-p node)
4390 (1+ (js2-xml-dot-query-node-rp node)))
4392 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4394 (defsubst js2-node-first-child (node)
4395 "Returns the first element of `js2-node-child-list' for NODE."
4396 (car (js2-node-child-list node)))
4398 (defsubst js2-node-last-child (node)
4399 "Returns the last element of `js2-node-last-child' for NODE."
4400 (car (last (js2-node-child-list node))))
4402 (defun js2-node-prev-sibling (node)
4403 "Return the previous statement in parent.
4404 Works for parents supported by `js2-node-child-list'.
4405 Returns nil if NODE is not in the parent, or PARENT is
4406 not a supported node, or if NODE is the first child."
4407 (let* ((p (js2-node-parent node))
4408 (kids (js2-node-child-list p))
4411 (not (eq node (cadr kids))))
4412 (setq kids (cdr kids)
4416 (defun js2-node-next-sibling (node)
4417 "Return the next statement in parent block.
4418 Returns nil if NODE is not in the block, or PARENT is not
4419 a block node, or if NODE is the last statement."
4420 (let* ((p (js2-node-parent node))
4421 (kids (js2-node-child-list p)))
4423 (not (eq node (car kids))))
4424 (setq kids (cdr kids)))
4427 (defun js2-node-find-child-before (pos parent &optional after)
4428 "Find the last child that starts before POS in parent.
4429 If AFTER is non-nil, returns first child starting after POS.
4430 POS is an absolute buffer position. PARENT is any node
4431 supported by `js2-node-child-list'.
4432 Returns nil if no applicable child is found."
4433 (let ((kids (if (js2-function-node-p parent)
4434 (js2-block-node-kids (js2-function-node-body parent))
4435 (js2-node-child-list parent)))
4436 (beg (if (js2-function-node-p parent)
4437 (js2-node-abs-pos (js2-function-node-body parent))
4438 (js2-node-abs-pos parent)))
4443 (setq fn (if after '> '<))
4444 (while (and kids continue)
4445 (setq kid (car kids))
4446 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4448 continue (if after nil t))
4449 (setq continue (if after t nil)))
4450 (setq kids (cdr kids)))
4453 (defun js2-node-find-child-after (pos parent)
4454 "Find first child that starts after POS in parent.
4455 POS is an absolute buffer position. PARENT is any node
4456 supported by `js2-node-child-list'.
4457 Returns nil if no applicable child is found."
4458 (js2-node-find-child-before pos parent 'after))
4460 (defun js2-node-replace-child (pos parent new-node)
4461 "Replace node at index POS in PARENT with NEW-NODE.
4462 Only works for parents supported by `js2-node-child-list'."
4463 (let ((kids (js2-node-child-list parent))
4466 (setq kids (cdr kids)
4468 (setcar kids new-node)
4469 (js2-node-add-children parent new-node)))
4471 (defun js2-node-buffer (n)
4472 "Return the buffer associated with AST N.
4473 Returns nil if the buffer is not set as a property on the root
4474 node, or if parent links were not recorded during parsing."
4475 (let ((root (js2-node-root n)))
4477 (js2-ast-root-p root)
4478 (js2-ast-root-buffer root))))
4480 (defsubst js2-block-node-push (n kid)
4481 "Push js2-node KID onto the end of js2-block-node N's child list.
4482 KID is always added to the -end- of the kids list.
4483 Function also calls `js2-node-add-children' to add the parent link."
4484 (let ((kids (js2-node-child-list n)))
4486 (setcdr kids (nconc (cdr kids) (list kid)))
4487 (js2-node-set-child-list n (list kid)))
4488 (js2-node-add-children n kid)))
4490 (defun js2-node-string (node)
4491 (let ((buf (js2-node-buffer node))
4494 (error "No buffer available for node %s" node))
4497 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4498 (+ pos (js2-node-len node))))))
4500 ;; Container for storing the node we're looking for in a traversal.
4501 (js2-deflocal js2-discovered-node nil)
4503 ;; Keep track of absolute node position during traversals.
4504 (js2-deflocal js2-visitor-offset nil)
4506 (js2-deflocal js2-node-search-point nil)
4508 (when js2-mode-dev-mode-p
4509 (defun js2-find-node-at-point ()
4511 (let ((node (js2-node-at-point)))
4512 (message "%s" (or node "No node found at point"))))
4513 (defun js2-node-name-at-point ()
4515 (let ((node (js2-node-at-point)))
4516 (message "%s" (if node
4517 (js2-node-short-name node)
4518 "No node found at point.")))))
4520 (defun js2-node-at-point (&optional pos skip-comments)
4521 "Return AST node at POS, a buffer position, defaulting to current point.
4522 The `js2-mode-ast' variable must be set to the current parse tree.
4523 Signals an error if the AST (`js2-mode-ast') is nil.
4524 Always returns a node - if it can't find one, it returns the root.
4525 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4526 (let ((ast js2-mode-ast)
4529 (error "No JavaScript AST available"))
4530 ;; Look through comments first, since they may be inside nodes that
4531 ;; would otherwise report a match.
4532 (setq pos (or pos (point))
4533 result (if (> pos (js2-node-abs-end ast))
4535 (if (not skip-comments)
4536 (js2-comment-at-point pos))))
4538 (setq js2-discovered-node nil
4539 js2-visitor-offset 0
4540 js2-node-search-point pos)
4542 (catch 'js2-visit-done
4543 (js2-visit-ast ast #'js2-node-at-point-visitor))
4544 (setq js2-visitor-offset nil
4545 js2-node-search-point nil))
4546 (setq result js2-discovered-node))
4547 ;; may have found a comment beyond end of last child node,
4548 ;; since visiting the ast-root looks at the comment-list last.
4549 (if (and skip-comments
4550 (js2-comment-node-p result))
4552 (or result js2-mode-ast)))
4554 (defun js2-node-at-point-visitor (node end-p)
4555 (let ((rel-pos (js2-node-pos node))
4558 (point js2-node-search-point))
4561 ;; this evaluates to a non-nil return value, even if it's zero
4562 (decf js2-visitor-offset rel-pos))
4563 ;; we already looked for comments before visiting, and don't want them now
4564 ((js2-comment-node-p node)
4567 (setq abs-pos (incf js2-visitor-offset rel-pos)
4568 ;; we only want to use the node if the point is before
4569 ;; the last character position in the node, so we decrement
4570 ;; the absolute end by 1.
4571 abs-end (+ abs-pos (js2-node-len node) -1))
4573 ;; If this node starts after search-point, stop the search.
4575 (throw 'js2-visit-done nil))
4576 ;; If this node ends before the search-point, don't check kids.
4580 ;; Otherwise point is within this node, possibly in a child.
4581 (setq js2-discovered-node node)
4582 t)))))) ; keep processing kids to look for more specific match
4584 (defsubst js2-block-comment-p (node)
4585 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4586 (and (js2-comment-node-p node)
4587 (memq (js2-comment-node-format node) '(jsdoc block))))
4589 ;; TODO: put the comments in a vector and binary-search them instead
4590 (defun js2-comment-at-point (&optional pos)
4591 "Look through scanned comment nodes for one containing POS.
4592 POS is a buffer position that defaults to current point.
4593 Function returns nil if POS was not in any comment node."
4594 (let ((ast js2-mode-ast)
4595 (x (or pos (point)))
4599 (error "No JavaScript AST available"))
4601 ;; Comments are stored in lexical order.
4602 (dolist (comment (js2-ast-root-comments ast) nil)
4603 (setq beg (js2-node-abs-pos comment)
4604 end (+ beg (js2-node-len comment)))
4607 (throw 'done comment))))))
4609 (defun js2-mode-find-parent-fn (node)
4610 "Find function enclosing NODE.
4611 Returns nil if NODE is not inside a function."
4612 (setq node (js2-node-parent node))
4613 (while (and node (not (js2-function-node-p node)))
4614 (setq node (js2-node-parent node)))
4615 (and (js2-function-node-p node) node))
4617 (defun js2-mode-find-enclosing-fn (node)
4618 "Find function or root enclosing NODE."
4619 (if (js2-ast-root-p node)
4621 (setq node (js2-node-parent node))
4622 (while (not (or (js2-ast-root-p node)
4623 (js2-function-node-p node)))
4624 (setq node (js2-node-parent node)))
4627 (defun js2-mode-find-enclosing-node (beg end)
4628 "Find script or function fully enclosing BEG and END."
4629 (let ((node (js2-node-at-point beg))
4633 (if (or (js2-ast-root-p node)
4634 (and (js2-function-node-p node)
4635 (<= (setq pos (js2-node-abs-pos node)) beg)
4636 (>= (+ pos (js2-node-len node)) end)))
4638 (setq node (js2-node-parent node))))
4641 (defun js2-node-parent-script-or-fn (node)
4642 "Find script or function immediately enclosing NODE.
4643 If NODE is the ast-root, returns nil."
4644 (if (js2-ast-root-p node)
4646 (setq node (js2-node-parent node))
4647 (while (and node (not (or (js2-function-node-p node)
4648 (js2-script-node-p node))))
4649 (setq node (js2-node-parent node)))
4652 (defsubst js2-nested-function-p (node)
4653 "Return t if NODE is a nested function, or is inside a nested function."
4654 (unless (js2-ast-root-p node)
4655 (js2-function-node-p (if (js2-function-node-p node)
4656 (js2-node-parent-script-or-fn node)
4657 (js2-node-parent-script-or-fn
4658 (js2-node-parent-script-or-fn node))))))
4660 (defsubst js2-function-param-node-p (node)
4661 "Return non-nil if NODE is a param node of a `js2-function-node'."
4662 (let ((parent (js2-node-parent node)))
4664 (js2-function-node-p parent)
4665 (memq node (js2-function-node-params parent)))))
4667 (defsubst js2-mode-shift-kids (kids start offset)
4669 (if (> (js2-node-pos kid) start)
4670 (incf (js2-node-pos kid) offset))))
4672 (defsubst js2-mode-shift-children (parent start offset)
4673 "Update start-positions of all children of PARENT beyond START."
4674 (let ((root (js2-node-root parent)))
4675 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4676 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4678 (defsubst js2-node-is-descendant (node ancestor)
4679 "Return t if NODE is a descendant of ANCESTOR."
4681 (not (eq node ancestor)))
4682 (setq node (js2-node-parent node)))
4685 ;;; visitor infrastructure
4687 (defun js2-visit-none (node callback)
4688 "Visitor for AST node that have no node children."
4691 (defun js2-print-none (node indent)
4692 "Visitor for AST node with no printed representation.")
4694 (defun js2-print-body (node indent)
4695 "Print a statement, or a block without braces."
4696 (if (js2-block-node-p node)
4697 (dolist (kid (js2-block-node-kids node))
4698 (js2-print-ast kid indent))
4699 (js2-print-ast node indent)))
4701 (defun js2-print-list (args &optional delimiter)
4702 (loop with len = (length args)
4706 (js2-print-ast arg 0)
4708 (insert (or delimiter ", ")))))
4710 (defun js2-print-tree (ast)
4711 "Prints an AST to the current buffer.
4712 Makes `js2-ast-parent-nodes' available to the printer functions."
4713 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4714 (js2-print-ast ast)))
4716 (defun js2-print-ast (node &optional indent)
4717 "Helper function for printing AST nodes.
4718 Requires `js2-ast-parent-nodes' to be non-nil.
4719 You should use `js2-print-tree' instead of this function."
4720 (let ((printer (get (aref node 0) 'js2-printer))
4722 (pos (js2-node-abs-pos node)))
4723 ;; TODO: wedge comments in here somewhere
4725 (funcall printer node i))))
4727 (defconst js2-side-effecting-tokens
4728 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4729 (dolist (tt (list js2-ASSIGN
4798 (if js2-instanceof-has-side-effects
4799 (aset tokens js2-INSTANCEOF t))
4802 (defun js2-node-has-side-effects (node)
4803 "Return t if NODE has side effects."
4804 (when node ; makes it easier to handle malformed expressions
4805 (let ((tt (js2-node-type node)))
4807 ;; This doubtless needs some work, since EXPR_VOID is used
4808 ;; in several ways in Rhino, and I may not have caught them all.
4809 ;; I'll wait for people to notice incorrect warnings.
4810 ((and (= tt js2-EXPR_VOID)
4811 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4812 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4814 (js2-node-has-side-effects (js2-infix-node-right node)))
4817 (or (js2-node-has-side-effects (js2-infix-node-right node))
4818 (js2-node-has-side-effects (js2-infix-node-left node))))
4820 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4821 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4822 ((js2-paren-node-p node)
4823 (js2-node-has-side-effects (js2-paren-node-expr node)))
4824 ((= tt js2-ERROR) ; avoid cascaded error messages
4827 (aref js2-side-effecting-tokens tt))))))
4829 (defun js2-member-expr-leftmost-name (node)
4830 "For an expr such as foo.bar.baz, return leftmost node foo.
4831 NODE is any `js2-node' object. If it represents a member expression,
4832 which is any sequence of property gets, element-gets, function calls,
4833 or xml descendants/filter operators, then we look at the lexically
4834 leftmost (first) node in the chain. If it is a name-node we return it.
4835 Note that NODE can be a raw name-node and it will be returned as well.
4836 If NODE is not a name-node or member expression, or if it is a member
4837 expression whose leftmost target is not a name node, returns nil."
4840 (while (and continue (not result))
4842 ((js2-name-node-p node)
4844 ((js2-prop-get-node-p node)
4845 (setq node (js2-prop-get-node-left node)))
4846 ;; TODO: handle call-nodes, xml-nodes, others?
4848 (setq continue nil))))
4851 (defconst js2-stmt-node-types
4855 js2-DEFAULT ; e4x "default xml namespace" statement
4867 "Node types that only appear in statement contexts.
4868 The list does not include nodes that always appear as the child
4869 of another specific statement type, such as switch-cases,
4870 catch and finally blocks, and else-clauses. The list also excludes
4871 nodes like yield, let and var, which may appear in either expression
4872 or statement context, and in the latter context always have a
4873 `js2-expr-stmt-node' parent. Finally, the list does not include
4874 functions or scripts, which are treated separately from statements
4875 by the JavaScript parser and runtime.")
4877 (defun js2-stmt-node-p (node)
4878 "Heuristic for figuring out if NODE is a statement.
4879 Some node types can appear in either an expression context or a
4880 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4881 For these node types in a statement context, the parent will be a
4882 `js2-expr-stmt-node'.
4883 Functions aren't included in the check."
4884 (memq (js2-node-type node) js2-stmt-node-types))
4886 (defsubst js2-mode-find-first-stmt (node)
4887 "Search upward starting from NODE looking for a statement.
4888 For purposes of this function, a `js2-function-node' counts."
4889 (while (not (or (js2-stmt-node-p node)
4890 (js2-function-node-p node)))
4891 (setq node (js2-node-parent node)))
4894 (defun js2-node-parent-stmt (node)
4895 "Return the node's first ancestor that is a statement.
4896 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4897 appearing in a statement context will have a parent that is a
4898 `js2-expr-stmt-node' that will be returned by this function."
4899 (let ((parent (js2-node-parent node)))
4900 (if (or (null parent)
4901 (js2-stmt-node-p parent)
4902 (and (js2-function-node-p parent)
4903 (not (eq (js2-function-node-form parent)
4904 'FUNCTION_EXPRESSION))))
4906 (js2-node-parent-stmt parent))))
4908 ;; In the Mozilla Rhino sources, Roshan James writes:
4909 ;; Does consistent-return analysis on the function body when strict mode is
4912 ;; function (x) { return (x+1) }
4916 ;; function (x) { if (x < 0) return (x+1); }
4918 ;; is not because the function can potentially return a value when the
4919 ;; condition is satisfied and if not, the function does not explicitly
4922 ;; This extends to checking mismatches such as "return" and "return <value>"
4923 ;; used in the same function. Warnings are not emitted if inconsistent
4924 ;; returns exist in code that can be statically shown to be unreachable.
4926 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4928 ;; emits no warning. However if the loop had a break statement, then a
4929 ;; warning would be emitted.
4931 ;; The consistency analysis looks at control structures such as loops, ifs,
4932 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4933 ;; warns the user about an inconsistent set of termination possibilities.
4935 ;; These flags enumerate the possible ways a statement/function can
4936 ;; terminate. These flags are used by endCheck() and by the Parser to
4937 ;; detect inconsistent return usage.
4939 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4940 ;; able to execute (example: throw, continue)
4942 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4943 ;; next one. Statement such as return dont. A compound statement may have
4944 ;; some branch that drops off control to the next statement.
4946 ;; END_RETURNS indicates that the statement can return with no value.
4947 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4949 ;; A compound statement such as
4953 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4955 (defconst js2-END_UNREACHED 0)
4956 (defconst js2-END_DROPS_OFF 1)
4957 (defconst js2-END_RETURNS 2)
4958 (defconst js2-END_RETURNS_VALUE 4)
4959 (defconst js2-END_YIELDS 8)
4961 (defun js2-has-consistent-return-usage (node)
4962 "Check that every return usage in a function body is consistent.
4963 Returns t if the function satisfies strict mode requirement."
4964 (let ((n (js2-end-check node)))
4965 ;; either it doesn't return a value in any branch...
4966 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4967 ;; or it returns a value (or is unreached) at every branch
4968 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4972 (defun js2-end-check-if (node)
4973 "Returns in the then and else blocks must be consistent with each other.
4974 If there is no else block, then the return statement can fall through.
4975 Returns logical OR of END_* flags"
4976 (let ((th (js2-if-node-then-part node))
4977 (el (js2-if-node-else-part node)))
4980 (logior (js2-end-check th) (if el
4982 js2-END_DROPS_OFF)))))
4984 (defun js2-end-check-switch (node)
4985 "Consistency of return statements is checked between the case statements.
4986 If there is no default, then the switch can fall through. If there is a
4987 default, we check to see if all code paths in the default return or if
4988 there is a code path that can fall through.
4989 Returns logical OR of END_* flags."
4990 (let ((rv js2-END_UNREACHED)
4992 ;; examine the cases
4994 (dolist (c (js2-switch-node-cases node))
4995 (if (js2-case-node-expr c)
4996 (js2-set-flag rv (js2-end-check-block c))
4997 (setq default-case c)
4998 (throw 'break nil))))
4999 ;; we don't care how the cases drop into each other
5000 (js2-clear-flag rv js2-END_DROPS_OFF)
5001 ;; examine the default
5002 (js2-set-flag rv (if default-case
5003 (js2-end-check default-case)
5007 (defun js2-end-check-try (node)
5008 "If the block has a finally, return consistency is checked in the
5009 finally block. If all code paths in the finally return, then the
5010 returns in the try-catch blocks don't matter. If there is a code path
5011 that does not return or if there is no finally block, the returns
5012 of the try and catch blocks are checked for mismatch.
5013 Returns logical OR of END_* flags."
5014 (let ((finally (js2-try-node-finally-block node))
5016 ;; check the finally if it exists
5017 (setq rv (if finally
5018 (js2-end-check (js2-finally-node-body finally))
5020 ;; If the finally block always returns, then none of the returns
5021 ;; in the try or catch blocks matter.
5022 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5023 (js2-clear-flag rv js2-END_DROPS_OFF)
5024 ;; examine the try block
5025 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5026 ;; check each catch block
5027 (dolist (cb (js2-try-node-catch-clauses node))
5028 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5031 (defun js2-end-check-loop (node)
5032 "Return statement in the loop body must be consistent. The default
5033 assumption for any kind of a loop is that it will eventually terminate.
5034 The only exception is a loop with a constant true condition. Code that
5035 follows such a loop is examined only if one can statically determine
5036 that there is a break out of the loop.
5038 for(... ; ... ; ...) {}
5043 Returns logical OR of END_* flags."
5044 (let ((rv (js2-end-check (js2-loop-node-body node)))
5046 ((js2-while-node-p node)
5047 (js2-while-node-condition node))
5048 ((js2-do-node-p node)
5049 (js2-do-node-condition node))
5050 ((js2-for-node-p node)
5051 (js2-for-node-condition node)))))
5053 ;; check to see if the loop condition is always true
5055 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5056 (js2-clear-flag rv js2-END_DROPS_OFF))
5058 ;; look for effect of breaks
5059 (js2-set-flag rv (js2-node-get-prop node
5064 (defun js2-end-check-block (node)
5065 "A general block of code is examined statement by statement.
5066 If any statement (even a compound one) returns in all branches, then
5067 subsequent statements are not examined.
5068 Returns logical OR of END_* flags."
5069 (let* ((rv js2-END_DROPS_OFF)
5070 (kids (js2-block-node-kids node))
5072 ;; Check each statment. If the statement can continue onto the next
5073 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5074 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5075 (js2-clear-flag rv js2-END_DROPS_OFF)
5076 (js2-set-flag rv (js2-end-check n))
5077 (setq kids (cdr kids)
5081 (defun js2-end-check-label (node)
5082 "A labeled statement implies that there may be a break to the label.
5083 The function processes the labeled statement and then checks the
5084 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5086 Returns logical OR of END_* flags."
5087 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5088 (logior rv (js2-node-get-prop node
5090 js2-END_UNREACHED))))
5092 (defun js2-end-check-break (node)
5093 "When a break is encountered annotate the statement being broken
5094 out of by setting its CONTROL_BLOCK_PROP property.
5095 Returns logical OR of END_* flags."
5096 (and (js2-break-node-target node)
5097 (js2-node-set-prop (js2-break-node-target node)
5102 (defun js2-end-check (node)
5103 "Examine the body of a function, doing a basic reachability analysis.
5104 Returns a combination of flags END_* flags that indicate
5105 how the function execution can terminate. These constitute only the
5106 pessimistic set of termination conditions. It is possible that at
5107 runtime certain code paths will never be actually taken. Hence this
5108 analysis will flag errors in cases where there may not be errors.
5109 Returns logical OR of END_* flags"
5112 ((js2-break-node-p node)
5113 (js2-end-check-break node))
5114 ((js2-expr-stmt-node-p node)
5115 (if (setq kid (js2-expr-stmt-node-expr node))
5118 ((or (js2-continue-node-p node)
5119 (js2-throw-node-p node))
5121 ((js2-return-node-p node)
5122 (if (setq kid (js2-return-node-retval node))
5123 js2-END_RETURNS_VALUE
5125 ((js2-loop-node-p node)
5126 (js2-end-check-loop node))
5127 ((js2-switch-node-p node)
5128 (js2-end-check-switch node))
5129 ((js2-labeled-stmt-node-p node)
5130 (js2-end-check-label node))
5131 ((js2-if-node-p node)
5132 (js2-end-check-if node))
5133 ((js2-try-node-p node)
5134 (js2-end-check-try node))
5135 ((js2-block-node-p node)
5136 (if (null (js2-block-node-kids node))
5138 (js2-end-check-block node)))
5139 ((js2-yield-node-p node)
5142 js2-END_DROPS_OFF))))
5144 (defun js2-always-defined-boolean-p (node)
5145 "Check if NODE always evaluates to true or false in boolean context.
5146 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5148 (let ((tt (js2-node-type node))
5151 ((or (= tt js2-FALSE) (= tt js2-NULL))
5156 (setq num (js2-number-node-num-value node))
5157 (if (and (not (eq num 0.0e+NaN))
5164 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5165 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5167 (defvar js2-tokens nil
5168 "List of all defined token names.") ; initialized in `js2-token-names'
5170 (defconst js2-token-names
5171 (let* ((names (make-vector js2-num-tokens -1))
5172 (case-fold-search nil) ; only match js2-UPPER_CASE
5173 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5174 (loop for sym in syms
5177 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5179 (aset names (symbol-value sym) ; code, e.g. 152
5180 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5181 (push sym js2-tokens)))
5183 "Vector mapping int values to token string names, sans `js2-' prefix.")
5185 (defun js2-token-name (tok)
5186 "Return a string name for TOK, a token symbol or code.
5187 Signals an error if it's not a recognized token."
5190 (setq code (symbol-value tok)))
5193 (if (and (numberp code)
5195 (< code js2-num-tokens))
5196 (aref js2-token-names code)
5197 (error "Invalid token: %s" code)))))
5199 (defsubst js2-token-sym (tok)
5200 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5201 (intern (js2-token-name tok)))
5203 (defconst js2-token-codes
5204 (let ((table (make-hash-table :test 'eq :size 256)))
5205 (loop for name across js2-token-names
5206 for sym = (intern (concat "js2-" name))
5208 (puthash sym (symbol-value sym) table))
5209 ;; clean up a few that are "wrong" in Rhino's token codes
5210 (puthash 'js2-DELETE js2-DELPROP table)
5212 "Hashtable mapping token symbols to their bytecodes.")
5214 (defsubst js2-token-code (sym)
5215 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5216 (or (gethash sym js2-token-codes)
5217 (error "Invalid token symbol: %s " sym))) ; signal code bug
5219 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5220 (setq js2-token-end js2-ts-cursor)
5221 (js2-report-error msg nil
5222 (or beg js2-token-beg)
5223 (or len (- js2-token-end js2-token-beg)))
5225 (throw 'return js2-ERROR)))
5227 (defsubst js2-get-string-from-buffer ()
5228 "Reverse the char accumulator and return it as a string."
5229 (setq js2-token-end js2-ts-cursor)
5230 (if js2-ts-string-buffer
5231 (apply #'string (nreverse js2-ts-string-buffer))
5234 ;; TODO: could potentially avoid a lot of consing by allocating a
5235 ;; char buffer the way Rhino does.
5236 (defsubst js2-add-to-string (c)
5237 (push c js2-ts-string-buffer))
5239 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5240 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5241 ;; any other character: when it's not part of the current token, we
5242 ;; unget it, allowing it to be read again by the following call.
5243 (defsubst js2-unget-char ()
5244 (decf js2-ts-cursor))
5246 ;; Rhino distinguishes \r and \n line endings. We don't need to
5247 ;; because we only scan from Emacs buffers, which always use \n.
5248 (defsubst js2-get-char ()
5249 "Read and return the next character from the input buffer.
5250 Increments `js2-ts-lineno' if the return value is a newline char.
5251 Updates `js2-ts-cursor' to the point after the returned char.
5252 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5253 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5255 ;; check for end of buffer
5256 (if (>= js2-ts-cursor (point-max))
5257 (setq js2-ts-hit-eof t
5258 js2-ts-cursor (1+ js2-ts-cursor)
5259 c js2-EOF_CHAR) ; return value
5260 ;; otherwise read next char
5261 (setq c (char-before (incf js2-ts-cursor)))
5262 ;; if we read a newline, update counters
5264 (setq js2-ts-line-start js2-ts-cursor
5265 js2-ts-lineno (1+ js2-ts-lineno)))
5266 ;; TODO: skip over format characters
5269 (defsubst js2-read-unicode-escape ()
5270 "Read a \\uNNNN sequence from the input.
5271 Assumes the ?\ and ?u have already been read.
5272 Returns the unicode character, or nil if it wasn't a valid character.
5273 Doesn't change the values of any scanner variables."
5274 ;; I really wish I knew a better way to do this, but I can't
5275 ;; find the Emacs function that takes a 16-bit int and converts
5276 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5277 ;; Have to first check that it's 4 hex characters or it may stop
5280 (let ((s (buffer-substring-no-properties js2-ts-cursor
5281 (+ 4 js2-ts-cursor))))
5282 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5283 (read (concat "?\\u" s))))))
5285 (defsubst js2-match-char (test)
5286 "Consume and return next character if it matches TEST, a character.
5287 Returns nil and consumes nothing if TEST is not the next character."
5288 (let ((c (js2-get-char)))
5294 (defsubst js2-peek-char ()
5299 (defsubst js2-java-identifier-start-p (c)
5302 (js2-char-uppercase-p c)
5303 (js2-char-lowercase-p c)))
5305 (defsubst js2-java-identifier-part-p (c)
5306 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5307 ;; TODO: make me Unicode-friendly. See comments above.
5310 (js2-char-uppercase-p c)
5311 (js2-char-lowercase-p c)
5312 (and (>= c ?0) (<= c ?9))))
5314 (defsubst js2-alpha-p (c)
5315 (cond ((and (<= ?A c) (<= c ?Z)) t)
5316 ((and (<= ?a c) (<= c ?z)) t)
5319 (defsubst js2-digit-p (c)
5320 (and (<= ?0 c) (<= c ?9)))
5322 (defsubst js2-js-space-p (c)
5324 (memq c '(#x20 #x9 #xB #xC #xD))
5327 ;; TODO: change this nil to check for Unicode space character
5330 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5332 (defsubst js2-skip-line ()
5333 "Skip to end of line"
5335 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5337 (setq js2-token-end js2-ts-cursor)))
5339 (defun js2-init-scanner (&optional buf line)
5340 "Create token stream for BUF starting on LINE.
5341 BUF defaults to current-buffer and line defaults to 1.
5343 A buffer can only have one scanner active at a time, which yields
5344 dramatically simpler code than using a defstruct. If you need to
5345 have simultaneous scanners in a buffer, copy the regions to scan
5350 (setq js2-ts-dirty-line nil
5351 js2-ts-regexp-flags nil
5356 js2-ts-lineno (or line 1)
5357 js2-ts-line-end-char -1
5358 js2-ts-cursor (point-min)
5359 js2-ts-is-xml-attribute nil
5360 js2-ts-xml-is-tag-content nil
5361 js2-ts-xml-open-tags-count 0
5362 js2-ts-string-buffer nil)))
5364 ;; This function uses the cached op, string and number fields in
5365 ;; TokenStream; if getToken has been called since the passed token
5366 ;; was scanned, the op or string printed may be incorrect.
5367 (defun js2-token-to-string (token)
5368 ;; Not sure where this function is used in Rhino. Not tested.
5369 (if (not js2-debug-print-trees)
5371 (let ((name (js2-token-name token)))
5373 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5374 (concat name " `" js2-ts-string "'"))
5375 ((eq token js2-NUMBER)
5376 (format "NUMBER %g" js2-ts-number))
5380 (defconst js2-keywords
5382 case catch const continue
5383 debugger default delete do
5385 false finally for function
5386 if in instanceof import
5391 this throw true try typeof
5396 ;; Token names aren't exactly the same as the keywords, unfortunately.
5397 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5398 (defconst js2-kwd-tokens
5399 (let ((table (make-vector js2-num-tokens nil))
5402 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5403 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5405 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5406 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5411 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5416 (aset table i 'font-lock-keyword-face))
5417 (aset table js2-STRING 'font-lock-string-face)
5418 (aset table js2-REGEXP 'font-lock-string-face)
5419 (aset table js2-COMMENT 'font-lock-comment-face)
5420 (aset table js2-THIS 'font-lock-builtin-face)
5421 (aset table js2-VOID 'font-lock-constant-face)
5422 (aset table js2-NULL 'font-lock-constant-face)
5423 (aset table js2-TRUE 'font-lock-constant-face)
5424 (aset table js2-FALSE 'font-lock-constant-face)
5426 "Vector whose values are non-nil for tokens that are keywords.
5427 The values are default faces to use for highlighting the keywords.")
5429 (defconst js2-reserved-words
5437 implements import int interface
5440 package private protected public
5441 short static super synchronized
5445 (defconst js2-keyword-names
5446 (let ((table (make-hash-table :test 'equal)))
5447 (loop for k in js2-keywords
5449 (symbol-name k) ; instanceof
5450 (intern (concat "js2-"
5451 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5454 "JavaScript keywords by name, mapped to their symbols.")
5456 (defconst js2-reserved-word-names
5457 (let ((table (make-hash-table :test 'equal)))
5458 (loop for k in js2-reserved-words
5460 (puthash (symbol-name k) 'js2-RESERVED table))
5462 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5464 (defsubst js2-collect-string (buf)
5465 "Convert BUF, a list of chars, to a string.
5466 Reverses BUF before converting."
5470 ((null buf) ; for emacs21 compat
5474 (apply #'string (nreverse buf))
5477 (defun js2-string-to-keyword (s)
5478 "Return token for S, a string, if S is a keyword or reserved word.
5479 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5480 (or (gethash s js2-keyword-names)
5481 (gethash s js2-reserved-word-names)))
5483 (defsubst js2-ts-set-char-token-bounds ()
5484 "Used when next token is one character."
5485 (setq js2-token-beg (1- js2-ts-cursor)
5486 js2-token-end js2-ts-cursor))
5488 (defsubst js2-ts-return (token)
5489 "Return an N-character TOKEN from `js2-get-token'.
5490 Updates `js2-token-end' accordingly."
5491 (setq js2-token-end js2-ts-cursor)
5492 (throw 'return token))
5494 (defsubst js2-x-digit-to-int (c accumulator)
5495 "Build up a hex number.
5496 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5497 corresponding number. Otherwise return -1."
5500 ;; Use 0..9 < A..Z < a..z
5505 (throw 'check nil)))
5509 (throw 'check nil)))
5513 (throw 'check nil))))
5515 (logior c (lsh accumulator 4))))
5517 (defun js2-get-token ()
5518 "Return next JavaScript token, an int such as js2-RETURN."
5522 is-unicode-escape-start
5536 ;; Eat whitespace, possibly sensitive to newlines.
5539 (setq c (js2-get-char))
5541 ((eq c js2-EOF_CHAR)
5542 (js2-ts-set-char-token-bounds)
5543 (throw 'return js2-EOF))
5545 (js2-ts-set-char-token-bounds)
5546 (setq js2-ts-dirty-line nil)
5547 (throw 'return js2-EOL))
5548 ((not (js2-js-space-p c))
5549 (if (/= c ?-) ; in case end of HTML comment
5550 (setq js2-ts-dirty-line t))
5551 (setq continue nil))))
5552 ;; Assume the token will be 1 char - fixed up below.
5553 (js2-ts-set-char-token-bounds)
5555 (throw 'return js2-XMLATTR))
5556 ;; identifier/keyword/instanceof?
5557 ;; watch out for starting with a <backslash>
5560 (setq c (js2-get-char))
5562 (setq identifier-start t
5563 is-unicode-escape-start t
5564 js2-ts-string-buffer nil)
5565 (setq identifier-start nil)
5569 (when (setq identifier-start (js2-java-identifier-start-p c))
5570 (setq js2-ts-string-buffer nil)
5571 (js2-add-to-string c))))
5572 (when identifier-start
5573 (setq contains-escape is-unicode-escape-start)
5576 (if is-unicode-escape-start
5577 ;; strictly speaking we should probably push-back
5578 ;; all the bad characters if the <backslash>uXXXX
5579 ;; sequence is malformed. But since there isn't a
5580 ;; correct context(is there?) for a bad Unicode
5581 ;; escape sequence in an identifier, we can report
5586 (setq c (js2-get-char)
5587 escape-val (js2-x-digit-to-int c escape-val))
5588 ;; Next check takes care of c < 0 and bad escape
5589 (if (minusp escape-val)
5590 (throw 'break nil)))
5591 (if (minusp escape-val)
5592 (js2-report-scan-error "msg.invalid.escape" t))
5593 (js2-add-to-string escape-val)
5594 (setq is-unicode-escape-start nil))
5595 (setq c (js2-get-char))
5598 (setq c (js2-get-char))
5600 (setq is-unicode-escape-start t
5602 (js2-report-scan-error "msg.illegal.character" t)))
5604 (if (or (eq c js2-EOF_CHAR)
5605 (not (js2-java-identifier-part-p c)))
5607 (js2-add-to-string c))))))
5609 (setq str (js2-get-string-from-buffer))
5610 (unless contains-escape
5611 ;; OPT we shouldn't have to make a string (object!) to
5612 ;; check if it's a keyword.
5613 ;; Return the corresponding token if it's a keyword
5614 (when (setq result (js2-string-to-keyword str))
5615 (if (and (< js2-language-version 170)
5616 (memq result '(js2-LET js2-YIELD)))
5617 ;; LET and YIELD are tokens only in 1.7 and later
5618 (setq result 'js2-NAME))
5619 (if (not (eq result 'js2-RESERVED))
5620 (throw 'return (js2-token-code result)))
5621 (js2-report-warning "msg.reserved.keyword" str)))
5622 ;; If we want to intern these as Rhino does, just use (intern str)
5623 (setq js2-ts-string str)
5624 (throw 'return js2-NAME)) ; end identifier/kwd check
5626 (when (or (js2-digit-p c)
5627 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5628 (setq js2-ts-string-buffer nil
5631 (setq c (js2-get-char))
5633 ((or (eq c ?x) (eq c ?X))
5635 (setq c (js2-get-char)))
5639 (js2-add-to-string ?0))))
5641 (while (<= 0 (js2-x-digit-to-int c 0))
5642 (js2-add-to-string c)
5643 (setq c (js2-get-char)))
5644 (while (and (<= ?0 c) (<= c ?9))
5645 ;; We permit 08 and 09 as decimal numbers, which
5646 ;; makes our behavior a superset of the ECMA
5647 ;; numeric grammar. We might not always be so
5648 ;; permissive, so we warn about it.
5649 (when (and (eq base 8) (>= c ?8))
5650 (js2-report-warning "msg.bad.octal.literal"
5651 (if (eq c ?8) "8" "9"))
5653 (js2-add-to-string c)
5654 (setq c (js2-get-char))))
5656 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5657 (setq is-integer nil)
5660 (js2-add-to-string c)
5661 (setq c (js2-get-char))
5662 while (js2-digit-p c)))
5663 (when (memq c '(?e ?E))
5664 (js2-add-to-string c)
5665 (setq c (js2-get-char))
5666 (when (memq c '(?+ ?-))
5667 (js2-add-to-string c)
5668 (setq c (js2-get-char)))
5669 (unless (js2-digit-p c)
5670 (js2-report-scan-error "msg.missing.exponent" t))
5672 (js2-add-to-string c)
5673 (setq c (js2-get-char))
5674 while (js2-digit-p c))))
5676 (setq js2-ts-string (js2-get-string-from-buffer)
5678 (if (and (eq base 10) (not is-integer))
5679 (string-to-number js2-ts-string)
5680 ;; TODO: call runtime number-parser. Some of it is in
5681 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5682 (string-to-number js2-ts-string)))
5683 (throw 'return js2-NUMBER))
5685 (when (memq c '(?\" ?\'))
5686 ;; We attempt to accumulate a string the fast way, by
5687 ;; building it directly out of the reader. But if there
5688 ;; are any escaped characters in the string, we revert to
5689 ;; building it out of a string buffer.
5691 js2-ts-string-buffer nil
5694 (while (/= c quote-char)
5696 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5698 (setq js2-token-end js2-ts-cursor)
5699 (js2-report-error "msg.unterminated.string.lit")
5700 (throw 'return js2-STRING))
5702 ;; We've hit an escaped character
5703 (setq c (js2-get-char))
5712 (setq c1 (js2-read-unicode-escape))
5713 (if js2-parse-ide-mode
5716 ;; just copy the string in IDE-mode
5717 (js2-add-to-string ?\\)
5718 (js2-add-to-string ?u)
5720 (js2-add-to-string (js2-get-char)))
5721 (setq c (js2-get-char))) ; added at end of loop
5722 ;; flag it as an invalid escape
5723 (js2-report-warning "msg.invalid.escape"
5724 nil (- js2-ts-cursor 2) 6))
5725 ;; Get 4 hex digits; if the u escape is not
5726 ;; followed by 4 hex digits, use 'u' + the
5727 ;; literal character sequence that follows.
5728 (js2-add-to-string ?u)
5731 (setq c (js2-get-char)
5732 escape-val (js2-x-digit-to-int c escape-val))
5733 (if (minusp escape-val)
5734 (throw 'continue nil))
5735 (js2-add-to-string c))
5736 ;; prepare for replace of stored 'u' sequence by escape value
5737 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5740 ;; Get 2 hex digits, defaulting to 'x'+literal
5741 ;; sequence, as above.
5742 (setq c (js2-get-char)
5743 escape-val (js2-x-digit-to-int c 0))
5744 (if (minusp escape-val)
5746 (js2-add-to-string ?x)
5747 (throw 'continue nil))
5750 escape-val (js2-x-digit-to-int c escape-val))
5751 (if (minusp escape-val)
5753 (js2-add-to-string ?x)
5754 (js2-add-to-string c1)
5755 (throw 'continue nil))
5757 (setq c escape-val))))
5759 ;; Remove line terminator after escape to follow
5760 ;; SpiderMonkey and C/C++
5761 (setq c (js2-get-char))
5762 (throw 'continue nil))
5764 (when (and (<= ?0 c) (< c ?8))
5767 (when (and (<= ?0 c) (< c ?8))
5768 (setq val (- (+ (* 8 val) c) ?0)
5770 (when (and (<= ?0 c)
5773 ;; c is 3rd char of octal sequence only
5774 ;; if the resulting val <= 0377
5775 (setq val (- (+ (* 8 val) c) ?0)
5779 (js2-add-to-string c)
5780 (setq c (js2-get-char)))))
5781 (setq js2-ts-string (js2-get-string-from-buffer))
5782 (throw 'return js2-STRING))
5785 (throw 'return js2-SEMI))
5787 (throw 'return js2-LB))
5789 (throw 'return js2-RB))
5791 (throw 'return js2-LC))
5793 (throw 'return js2-RC))
5795 (throw 'return js2-LP))
5797 (throw 'return js2-RP))
5799 (throw 'return js2-COMMA))
5801 (throw 'return js2-HOOK))
5803 (if (js2-match-char ?:)
5804 (js2-ts-return js2-COLONCOLON)
5805 (throw 'return js2-COLON)))
5807 (if (js2-match-char ?.)
5808 (js2-ts-return js2-DOTDOT)
5809 (if (js2-match-char ?\()
5810 (js2-ts-return js2-DOTQUERY)
5811 (throw 'return js2-DOT))))
5813 (if (js2-match-char ?|)
5814 (throw 'return js2-OR)
5815 (if (js2-match-char ?=)
5816 (js2-ts-return js2-ASSIGN_BITOR)
5817 (throw 'return js2-BITOR))))
5819 (if (js2-match-char ?=)
5820 (js2-ts-return js2-ASSIGN_BITOR)
5821 (throw 'return js2-BITXOR)))
5823 (if (js2-match-char ?&)
5824 (throw 'return js2-AND)
5825 (if (js2-match-char ?=)
5826 (js2-ts-return js2-ASSIGN_BITAND)
5827 (throw 'return js2-BITAND))))
5829 (if (js2-match-char ?=)
5830 (if (js2-match-char ?=)
5831 (js2-ts-return js2-SHEQ)
5832 (throw 'return js2-EQ))
5833 (throw 'return js2-ASSIGN)))
5835 (if (js2-match-char ?=)
5836 (if (js2-match-char ?=)
5837 (js2-ts-return js2-SHNE)
5838 (js2-ts-return js2-NE))
5839 (throw 'return js2-NOT)))
5841 ;; NB:treat HTML begin-comment as comment-till-eol
5842 (when (js2-match-char ?!)
5843 (when (js2-match-char ?-)
5844 (when (js2-match-char ?-)
5846 (setq js2-ts-comment-type 'html)
5847 (throw 'return js2-COMMENT)))
5849 (if (js2-match-char ?<)
5850 (if (js2-match-char ?=)
5851 (js2-ts-return js2-ASSIGN_LSH)
5852 (js2-ts-return js2-LSH))
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-LE)
5855 (throw 'return js2-LT))))
5857 (if (js2-match-char ?>)
5858 (if (js2-match-char ?>)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-ASSIGN_URSH)
5861 (js2-ts-return js2-URSH))
5862 (if (js2-match-char ?=)
5863 (js2-ts-return js2-ASSIGN_RSH)
5864 (js2-ts-return js2-RSH)))
5865 (if (js2-match-char ?=)
5866 (js2-ts-return js2-GE)
5867 (throw 'return js2-GT))))
5869 (if (js2-match-char ?=)
5870 (js2-ts-return js2-ASSIGN_MUL)
5871 (throw 'return js2-MUL)))
5873 ;; is it a // comment?
5874 (when (js2-match-char ?/)
5875 (setq js2-token-beg (- js2-ts-cursor 2))
5877 (setq js2-ts-comment-type 'line)
5878 ;; include newline so highlighting goes to end of window
5879 (incf js2-token-end)
5880 (throw 'return js2-COMMENT))
5881 ;; is it a /* comment?
5882 (when (js2-match-char ?*)
5883 (setq look-for-slash nil
5884 js2-token-beg (- js2-ts-cursor 2)
5886 (if (js2-match-char ?*)
5888 (setq look-for-slash t)
5892 (setq c (js2-get-char))
5894 ((eq c js2-EOF_CHAR)
5895 (setq js2-token-end (1- js2-ts-cursor))
5896 (js2-report-error "msg.unterminated.comment")
5897 (throw 'return js2-COMMENT))
5899 (setq look-for-slash t))
5902 (js2-ts-return js2-COMMENT)))
5904 (setq look-for-slash nil
5905 js2-token-end js2-ts-cursor)))))
5906 (if (js2-match-char ?=)
5907 (js2-ts-return js2-ASSIGN_DIV)
5908 (throw 'return js2-DIV)))
5910 (when js2-skip-preprocessor-directives
5912 (setq js2-ts-comment-type 'preprocessor
5913 js2-token-end js2-ts-cursor)
5914 (throw 'return js2-COMMENT))
5915 (throw 'return js2-ERROR))
5917 (if (js2-match-char ?=)
5918 (js2-ts-return js2-ASSIGN_MOD)
5919 (throw 'return js2-MOD)))
5921 (throw 'return js2-BITNOT))
5923 (if (js2-match-char ?=)
5924 (js2-ts-return js2-ASSIGN_ADD)
5925 (if (js2-match-char ?+)
5926 (js2-ts-return js2-INC)
5927 (throw 'return js2-ADD))))
5930 ((js2-match-char ?=)
5931 (setq c js2-ASSIGN_SUB))
5932 ((js2-match-char ?-)
5933 (unless js2-ts-dirty-line
5934 ;; treat HTML end-comment after possible whitespace
5935 ;; after line start as comment-until-eol
5936 (when (js2-match-char ?>)
5938 (setq js2-ts-comment-type 'html)
5939 (throw 'return js2-COMMENT)))
5943 (setq js2-ts-dirty-line t)
5946 (js2-report-scan-error "msg.illegal.character")))))))
5948 (defun js2-read-regexp (start-token)
5949 "Called by parser when it gets / or /= in literal context."
5952 in-class ; inside a '[' .. ']' character-class
5955 (setq js2-token-beg js2-ts-cursor
5956 js2-ts-string-buffer nil
5957 js2-ts-regexp-flags nil)
5958 (if (eq start-token js2-ASSIGN_DIV)
5960 (js2-add-to-string ?=)
5961 (if (not (eq start-token js2-DIV))
5962 (error "failed assertion")))
5963 (while (and (not err)
5964 (or (/= (setq c (js2-get-char)) ?/)
5969 (setq js2-token-end (1- js2-ts-cursor)
5971 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5972 (js2-report-error "msg.unterminated.re.lit"))
5975 (js2-add-to-string c)
5976 (setq c (js2-get-char)))
5980 (setq in-class nil)))
5981 (js2-add-to-string c))))
5985 ((js2-match-char ?g)
5987 ((js2-match-char ?i)
5989 ((js2-match-char ?m)
5992 (setq continue nil))))
5993 (if (js2-alpha-p (js2-peek-char))
5994 (js2-report-scan-error "msg.invalid.re.flag" t
5996 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5997 js2-ts-regexp-flags (js2-collect-string flags)
5998 js2-token-end js2-ts-cursor)
5999 ;; tell `parse-partial-sexp' to ignore this range of chars
6000 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6002 (defun js2-get-first-xml-token ()
6003 (setq js2-ts-xml-open-tags-count 0
6004 js2-ts-is-xml-attribute nil
6005 js2-ts-xml-is-tag-content nil)
6007 (js2-get-next-xml-token))
6009 (defsubst js2-xml-discard-string ()
6010 "Throw away the string in progress and flag an XML parse error."
6011 (setq js2-ts-string-buffer nil
6013 (js2-report-scan-error "msg.XML.bad.form" t))
6015 (defun js2-get-next-xml-token ()
6016 (setq js2-ts-string-buffer nil ; for recording the XML
6017 js2-token-beg js2-ts-cursor)
6022 (setq c (js2-get-char))
6025 (throw 'return js2-ERROR))
6026 (js2-ts-xml-is-tag-content
6029 (js2-add-to-string c)
6030 (setq js2-ts-xml-is-tag-content nil
6031 js2-ts-is-xml-attribute nil))
6033 (js2-add-to-string c)
6034 (when (eq ?> (js2-peek-char))
6035 (setq c (js2-get-char))
6036 (js2-add-to-string c)
6037 (setq js2-ts-xml-is-tag-content nil)
6038 (decf js2-ts-xml-open-tags-count)))
6041 (setq js2-ts-string (js2-get-string-from-buffer))
6042 (throw 'return js2-XML))
6044 (js2-add-to-string c)
6045 (unless (js2-read-quoted-string c)
6046 (throw 'return js2-ERROR)))
6048 (js2-add-to-string c)
6049 (setq js2-ts-is-xml-attribute t))
6051 (js2-add-to-string c))
6053 (js2-add-to-string c)
6054 (setq js2-ts-is-xml-attribute nil)))
6055 (when (and (not js2-ts-xml-is-tag-content)
6056 (zerop js2-ts-xml-open-tags-count))
6057 (setq js2-ts-string (js2-get-string-from-buffer))
6058 (throw 'return js2-XMLEND)))
6060 ;; else not tag content
6063 (js2-add-to-string c)
6064 (setq c (js2-peek-char))
6067 (setq c (js2-get-char)) ;; skip !
6068 (js2-add-to-string c)
6069 (setq c (js2-peek-char))
6072 (setq c (js2-get-char)) ;; skip -
6073 (js2-add-to-string c)
6076 (js2-add-to-string c)
6077 (unless (js2-read-xml-comment)
6078 (throw 'return js2-ERROR)))
6079 (js2-xml-discard-string)
6080 (throw 'return js2-ERROR)))
6082 (setq c (js2-get-char)) ;; skip [
6083 (js2-add-to-string c)
6084 (if (and (= (js2-get-char) ?C)
6085 (= (js2-get-char) ?D)
6086 (= (js2-get-char) ?A)
6087 (= (js2-get-char) ?T)
6088 (= (js2-get-char) ?A)
6089 (= (js2-get-char) ?\[))
6091 (js2-add-to-string ?C)
6092 (js2-add-to-string ?D)
6093 (js2-add-to-string ?A)
6094 (js2-add-to-string ?T)
6095 (js2-add-to-string ?A)
6096 (js2-add-to-string ?\[)
6097 (unless (js2-read-cdata)
6098 (throw 'return js2-ERROR)))
6099 (js2-xml-discard-string)
6100 (throw 'return js2-ERROR)))
6102 (unless (js2-read-entity)
6103 (throw 'return js2-ERROR)))))
6105 (setq c (js2-get-char)) ;; skip ?
6106 (js2-add-to-string c)
6107 (unless (js2-read-PI)
6108 (throw 'return js2-ERROR)))
6111 (setq c (js2-get-char)) ;; skip /
6112 (js2-add-to-string c)
6113 (when (zerop js2-ts-xml-open-tags-count)
6114 (js2-xml-discard-string)
6115 (throw 'return js2-ERROR))
6116 (setq js2-ts-xml-is-tag-content t)
6117 (decf js2-ts-xml-open-tags-count))
6120 (setq js2-ts-xml-is-tag-content t)
6121 (incf js2-ts-xml-open-tags-count))))
6124 (setq js2-ts-string (js2-get-string-from-buffer))
6125 (throw 'return js2-XML))
6127 (js2-add-to-string c))))))))
6128 (setq js2-token-end js2-ts-cursor)
6131 (defun js2-read-quoted-string (quote)
6134 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6135 (js2-add-to-string c)
6138 (js2-xml-discard-string) ;; throw away string in progress
6141 (defun js2-read-xml-comment ()
6142 (let ((c (js2-get-char)))
6144 (while (/= c js2-EOF_CHAR)
6146 (js2-add-to-string c)
6147 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6148 (setq c (js2-get-char))
6149 (js2-add-to-string c)
6150 (if (eq (js2-peek-char) ?>)
6152 (setq c (js2-get-char)) ;; skip >
6153 (js2-add-to-string c)
6155 (throw 'continue nil)))
6156 (setq c (js2-get-char))))
6157 (js2-xml-discard-string)
6160 (defun js2-read-cdata ()
6161 (let ((c (js2-get-char)))
6163 (while (/= c js2-EOF_CHAR)
6165 (js2-add-to-string c)
6166 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6167 (setq c (js2-get-char))
6168 (js2-add-to-string c)
6169 (if (eq (js2-peek-char) ?>)
6171 (setq c (js2-get-char)) ;; Skip >
6172 (js2-add-to-string c)
6174 (throw 'continue nil)))
6175 (setq c (js2-get-char))))
6176 (js2-xml-discard-string)
6179 (defun js2-read-entity ()
6183 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6184 (js2-add-to-string c)
6190 (if (zerop decl-tags)
6191 (throw 'return t)))))
6192 (js2-xml-discard-string)
6195 (defun js2-read-PI ()
6196 "Scan an XML processing instruction."
6199 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6200 (js2-add-to-string c)
6201 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6202 (setq c (js2-get-char)) ;; Skip >
6203 (js2-add-to-string c)
6205 (js2-xml-discard-string)
6208 (defun js2-scanner-get-line ()
6209 "Return the text of the current scan line."
6210 (buffer-substring (point-at-bol) (point-at-eol)))
6214 (defsubst js2-set-face (beg end face &optional record)
6215 "Fontify a region. If RECORD is non-nil, record for later."
6216 (when (plusp js2-highlight-level)
6217 (setq beg (min (point-max) beg)
6218 beg (max (point-min) beg)
6219 end (min (point-max) end)
6220 end (max (point-min) end))
6222 (push (list beg end face) js2-mode-fontifications)
6223 (put-text-property beg end 'face face))))
6225 (defsubst js2-set-kid-face (pos kid len face)
6226 "Set-face on a child node.
6227 POS is absolute buffer position of parent.
6228 KID is the child node.
6229 LEN is the length to fontify.
6230 FACE is the face to fontify with."
6231 (js2-set-face (+ pos (js2-node-pos kid))
6232 (+ pos (js2-node-pos kid) (js2-node-len kid))
6235 (defsubst js2-fontify-kwd (start length)
6236 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6238 (defsubst js2-clear-face (beg end)
6239 (remove-text-properties beg end '(face nil
6244 (defconst js2-ecma-global-props
6247 '("Infinity" "NaN" "undefined" "arguments") t)
6249 "Value properties of the Ecma-262 Global Object.
6250 Shown at or above `js2-highlight-level' 2.")
6252 ;; might want to add the name "arguments" to this list?
6253 (defconst js2-ecma-object-props
6256 '("prototype" "__proto__" "__parent__") t)
6258 "Value properties of the Ecma-262 Object constructor.
6259 Shown at or above `js2-highlight-level' 2.")
6261 (defconst js2-ecma-global-funcs
6265 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6266 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6268 "Function properties of the Ecma-262 Global object.
6269 Shown at or above `js2-highlight-level' 2.")
6271 (defconst js2-ecma-number-props
6273 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6275 "POSITIVE_INFINITY") t)
6277 "Properties of the Ecma-262 Number constructor.
6278 Shown at or above `js2-highlight-level' 2.")
6280 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6281 "Properties of the Ecma-262 Date constructor.
6282 Shown at or above `js2-highlight-level' 2.")
6284 (defconst js2-ecma-math-props
6287 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6290 "Properties of the Ecma-262 Math object.
6291 Shown at or above `js2-highlight-level' 2.")
6293 (defconst js2-ecma-math-funcs
6296 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6297 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6299 "Function properties of the Ecma-262 Math object.
6300 Shown at or above `js2-highlight-level' 2.")
6302 (defconst js2-ecma-function-props
6306 '(;; properties of the Object prototype object
6307 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6308 "toLocaleString" "toString" "valueOf"
6309 ;; properties of the Function prototype object
6311 ;; properties of the Array prototype object
6312 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6314 ;; properties of the String prototype object
6315 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6316 "localeCompare" "match" "replace" "search" "split" "substring"
6317 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6319 ;; properties of the Number prototype object
6320 "toExponential" "toFixed" "toPrecision"
6321 ;; properties of the Date prototype object
6322 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6323 "getMinutes" "getMonth" "getSeconds" "getTime"
6324 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6325 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6326 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6327 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6328 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6329 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6330 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6331 "toTimeString" "toUTCString"
6332 ;; properties of the RegExp prototype object
6334 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6335 "toSource" "__defineGetter__" "__defineSetter__"
6336 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6337 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6340 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6341 Shown at or above `js2-highlight-level' 3.")
6343 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6344 (let ((target-name (and target
6345 (js2-name-node-p target)
6346 (js2-name-node-name target)))
6347 (prop-name (if prop (js2-name-node-name prop)))
6348 (level1 (>= js2-highlight-level 1))
6349 (level2 (>= js2-highlight-level 2))
6350 (level3 (>= js2-highlight-level 3))
6358 ((and level3 (string-match js2-ecma-function-props prop-name))
6359 (setq face 'font-lock-builtin-face))
6360 ((and target-name prop)
6362 ((string= target-name "Date")
6363 (if (string-match js2-ecma-date-props prop-name)
6364 (setq face 'font-lock-builtin-face)))
6365 ((string= target-name "Math")
6366 (if (string-match js2-ecma-math-funcs prop-name)
6367 (setq face 'font-lock-builtin-face)))))))
6369 (if (string-match js2-ecma-global-funcs prop-name)
6370 (setq face 'font-lock-builtin-face))))
6374 ((string= target-name "Number")
6375 (if (string-match js2-ecma-number-props prop-name)
6376 (setq face 'font-lock-constant-face)))
6377 ((string= target-name "Math")
6378 (if (string-match js2-ecma-math-props prop-name)
6379 (setq face 'font-lock-constant-face)))))
6381 (if (string-match js2-ecma-object-props prop-name)
6382 (setq face 'font-lock-constant-face)))))
6384 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6385 (js2-node-pos prop))) ; relative
6386 (+ pos (js2-node-len prop))
6389 (defun js2-parse-highlight-member-expr-node (node)
6390 "Perform syntax highlighting of EcmaScript built-in properties.
6391 The variable `js2-highlight-level' governs this highighting."
6392 (let (face target prop name pos end parent call-p callee)
6394 ;; case 1: simple name, e.g. foo
6395 ((js2-name-node-p node)
6396 (setq name (js2-name-node-name node))
6397 ;; possible for name to be nil in rare cases - saw it when
6398 ;; running js2-mode on an elisp buffer. Might as well try to
6399 ;; make it so js2-mode never barfs.
6401 (setq face (if (string-match js2-ecma-global-props name)
6402 'font-lock-constant-face))
6404 (setq pos (js2-node-pos node)
6405 end (+ pos (js2-node-len node)))
6406 (js2-set-face pos end face))))
6407 ;; case 2: property access or function call
6408 ((or (js2-prop-get-node-p node)
6409 ;; highlight function call if expr is a prop-get node
6410 ;; or a plain name (i.e. unqualified function call)
6411 (and (setq call-p (js2-call-node-p node))
6412 (setq callee (js2-call-node-target node)) ; separate setq!
6413 (or (js2-prop-get-node-p callee)
6414 (js2-name-node-p callee))))
6416 node (if call-p callee node))
6417 (if (and call-p (js2-name-node-p callee))
6419 (setq target (js2-prop-get-node-left node)
6420 prop (js2-prop-get-node-right node)))
6422 ((js2-name-node-p target)
6423 (if (js2-name-node-p prop)
6424 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6425 (js2-parse-highlight-prop-get parent target prop call-p)
6426 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6427 (js2-parse-highlight-prop-get parent target nil call-p)))
6428 ((js2-name-node-p prop)
6429 ;; case 2c: complex target, simple name, e.g. x[y].bar
6430 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6432 (defun js2-parse-highlight-member-expr-fn-name (expr)
6433 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6434 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6435 We currently only handle the case where the last component is a prop-get
6436 of a simple name. Called before EXPR has a parent node."
6438 (name (and (js2-prop-get-node-p expr)
6439 (js2-prop-get-node-right expr))))
6440 (when (js2-name-node-p name)
6441 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6442 (js2-node-pos name)))
6443 (+ pos (js2-node-len name))
6444 'font-lock-function-name-face
6447 ;; source: http://jsdoc.sourceforge.net/
6448 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6449 ;; allows type specifications, and needs work before entering the wild.
6451 (defconst js2-jsdoc-param-tag-regexp
6452 (concat "^\\s-*\\*+\\s-*\\(@"
6453 "\\(?:param\\|argument\\)"
6455 "\\s-*\\({[^}]+}\\)?" ; optional type
6456 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6458 "Matches jsdoc tags with optional type and optional param name.")
6460 (defconst js2-jsdoc-typed-tag-regexp
6461 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6475 "\\)\\)\\s-*\\({[^}]+}\\)?")
6476 "Matches jsdoc tags with optional type.")
6478 (defconst js2-jsdoc-arg-tag-regexp
6479 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6502 "\\)\\)\\s-+\\([^ \t]+\\)")
6503 "Matches jsdoc tags with a single argument.")
6505 (defconst js2-jsdoc-empty-tag-regexp
6506 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6546 "Matches empty jsdoc tags.")
6548 (defconst js2-jsdoc-link-tag-regexp
6549 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6550 "Matches a jsdoc link or code tag.")
6552 (defconst js2-jsdoc-see-tag-regexp
6553 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6554 "Matches a jsdoc @see tag.")
6556 (defconst js2-jsdoc-html-tag-regexp
6557 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6558 "Matches a simple (no attributes) html start- or end-tag.")
6560 (defsubst js2-jsdoc-highlight-helper ()
6561 (js2-set-face (match-beginning 1)
6563 'js2-jsdoc-tag-face)
6564 (if (match-beginning 2)
6566 (goto-char (match-beginning 2))
6567 (= (char-after) ?{))
6568 (js2-set-face (1+ (match-beginning 2))
6570 'js2-jsdoc-type-face)
6571 (js2-set-face (match-beginning 2)
6573 'js2-jsdoc-value-face)))
6574 (if (match-beginning 3)
6575 (js2-set-face (match-beginning 3)
6577 'js2-jsdoc-value-face)))
6579 (defun js2-highlight-jsdoc (ast)
6580 "Highlight doc comment tags."
6581 (let ((comments (js2-ast-root-comments ast))
6584 (dolist (node comments)
6585 (when (eq (js2-comment-node-format node) 'jsdoc)
6586 (setq beg (js2-node-abs-pos node)
6587 end (+ beg (js2-node-len node)))
6589 (narrow-to-region beg end)
6590 (dolist (re (list js2-jsdoc-param-tag-regexp
6591 js2-jsdoc-typed-tag-regexp
6592 js2-jsdoc-arg-tag-regexp
6593 js2-jsdoc-link-tag-regexp
6594 js2-jsdoc-see-tag-regexp
6595 js2-jsdoc-empty-tag-regexp))
6597 (while (re-search-forward re nil t)
6598 (js2-jsdoc-highlight-helper)))
6599 ;; simple highlighting for html tags
6601 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6602 (js2-set-face (match-beginning 1)
6604 'js2-jsdoc-html-tag-delimiter-face)
6605 (js2-set-face (match-beginning 2)
6607 'js2-jsdoc-html-tag-name-face)
6608 (js2-set-face (match-beginning 3)
6610 'js2-jsdoc-html-tag-delimiter-face))))))))
6612 (defun js2-highlight-assign-targets (node left right)
6613 "Highlight function properties and external variables."
6614 (let (leftpos end name)
6615 ;; highlight vars and props assigned function values
6616 (when (js2-function-node-p right)
6618 ;; var foo = function() {...}
6619 ((js2-name-node-p left)
6621 ;; foo.bar.baz = function() {...}
6622 ((and (js2-prop-get-node-p left)
6623 (js2-name-node-p (js2-prop-get-node-right left)))
6624 (setq name (js2-prop-get-node-right left))))
6626 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6627 (+ leftpos (js2-node-len name))
6628 'font-lock-function-name-face
6631 (defun js2-record-name-node (node)
6632 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6633 later. NODE must be a name node."
6635 (push (list node js2-current-scope
6636 (setq leftpos (js2-node-abs-pos node))
6637 (setq end (+ leftpos (js2-node-len node))))
6638 js2-recorded-identifiers)))
6640 (defun js2-highlight-undeclared-vars ()
6641 "After entire parse is finished, look for undeclared variable references.
6642 We have to wait until entire buffer is parsed, since JavaScript permits var
6643 decls to occur after they're used.
6645 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6646 it is considered declared."
6648 (dolist (entry js2-recorded-identifiers)
6649 (destructuring-bind (name-node scope pos end) entry
6650 (setq name (js2-name-node-name name-node))
6651 (unless (or (member name js2-global-externs)
6652 (member name js2-default-externs)
6653 (member name js2-additional-externs)
6654 (js2-get-defining-scope scope name))
6655 (js2-set-face pos end 'js2-external-variable-face 'record)
6656 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6657 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6658 (setq js2-recorded-identifiers nil)))
6662 ;; We currently only support imenu, but eventually should support speedbar and
6663 ;; possibly other browsing mechanisms.
6665 ;; The basic strategy is to identify function assignment targets of the form
6666 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6667 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6668 ;; for imenu after parsing is finished.
6670 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6671 ;; JavaScript, and the general problem is undecidable. However, several forms
6672 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6675 ;; function foo() -- function declaration
6676 ;; foo = function() -- function expression assigned to variable
6677 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6678 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6679 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6680 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6681 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6682 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6683 ;; function foo() {function bar() {...}} -- nested function
6684 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6686 ;; This list boils down to a few forms that can be combined recursively.
6687 ;; Top-level named function declarations include both the left-hand (name)
6688 ;; and the right-hand (function value) expressions needed to produce an imenu
6689 ;; entry. The other "right-hand" forms we need to look for are:
6690 ;; - functions declared as props/getters/setters in object literals
6691 ;; - nested named function declarations
6692 ;; The "left-hand" expressions that functions can be assigned to include:
6693 ;; - local/global variables
6694 ;; - nested property-get expressions like a.b.c.d
6695 ;; - element gets like foo[10] or foo['bar'] where the index
6696 ;; expression can be trivially converted to a property name. They
6697 ;; effectively then become property gets.
6699 ;; All the different definition types are canonicalized into the form
6700 ;; foo.bar.baz = position-of-function-keyword
6702 ;; We need to build a trie-like structure for imenu. As an example,
6703 ;; consider the following JavaScript code:
6705 ;; a = function() {...} // function at position 5
6706 ;; b = function() {...} // function at position 25
6707 ;; foo = function() {...} // function at position 100
6708 ;; foo.bar = function() {...} // function at position 200
6709 ;; foo.bar.baz = function() {...} // function at position 300
6710 ;; foo.bar.zab = function() {...} // function at position 400
6712 ;; During parsing we accumulate an entry for each definition in
6713 ;; the variable `js2-imenu-recorder', like so:
6719 ;; (foo bar baz 300)
6720 ;; (foo bar zab 400))
6722 ;; After parsing these entries are merged into this alist-trie:
6726 ;; (foo (<definition> . 3)
6727 ;; (bar (<definition> . 6)
6731 ;; Note the wacky need for a <definition> name. The token can be anything
6732 ;; that isn't a valid JavaScript identifier, because you might make foo
6733 ;; a function and then start setting properties on it that are also functions.
6735 (defsubst js2-prop-node-name (node)
6736 "Return the name of a node that may be a property-get/property-name.
6737 If NODE is not a valid name-node, string-node or integral number-node,
6738 returns nil. Otherwise returns the string name/value of the node."
6740 ((js2-name-node-p node)
6741 (js2-name-node-name node))
6742 ((js2-string-node-p node)
6743 (js2-string-node-value node))
6744 ((and (js2-number-node-p node)
6745 (string-match "^[0-9]+$" (js2-number-node-value node)))
6746 (js2-number-node-value node))
6747 ((js2-this-node-p node)
6750 (defsubst js2-node-qname-component (node)
6751 "Test function: return the name of this node, if it contributes to a qname.
6752 Returns nil if the node doesn't contribute."
6754 (or (js2-prop-node-name node)
6755 (if (and (js2-function-node-p node)
6756 (js2-function-node-name node))
6757 (js2-name-node-name (js2-function-node-name node))))))
6759 (defsubst js2-record-function-qname (fn-node qname)
6760 "Associate FN-NODE with its QNAME for later lookup.
6761 This is used in postprocessing the chain list. When we find a chain
6762 whose first element is a js2-THIS keyword node, we look up the parent
6763 function and see (using this map) whether it is the tail of a chain.
6764 If so, we replace the this-node with a copy of the parent's qname."
6765 (unless js2-imenu-function-map
6766 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6767 (puthash fn-node qname js2-imenu-function-map))
6769 (defun js2-record-imenu-functions (node &optional var)
6770 "Record function definitions for imenu.
6771 NODE is a function node or an object literal.
6772 VAR, if non-nil, is the expression that NODE is being assigned to."
6773 (when js2-parse-ide-mode
6774 (let ((fun-p (js2-function-node-p node))
6775 qname left fname-node pos)
6777 ;; non-anonymous function declaration?
6780 (setq fname-node (js2-function-node-name node)))
6781 (push (setq qname (list fname-node (js2-node-pos node)))
6783 (js2-record-function-qname node qname))
6784 ;; for remaining forms, compute left-side tree branch first
6785 ((and var (setq qname (js2-compute-nested-prop-get var)))
6787 ;; foo.bar.baz = function
6789 (push (nconc qname (list (js2-node-pos node)))
6791 (js2-record-function-qname node qname))
6792 ;; foo.bar.baz = object-literal
6793 ;; look for nested functions: {a: {b: function() {...} }}
6794 ((js2-object-node-p node)
6795 ;; Node position here is still absolute, since the parser
6796 ;; passes the assignment target and value expressions
6797 ;; to us before they are added as children of the assignment node.
6798 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6800 (defun js2-compute-nested-prop-get (node)
6801 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6802 component nodes as a list. Otherwise return nil. Element-gets are treated
6803 as property-gets if the index expression is a string, or a positive integer."
6804 (let (left right head)
6806 ((or (js2-name-node-p node)
6807 (js2-this-node-p node))
6809 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6810 ((js2-prop-get-node-p node) ; foo.bar
6811 (setq left (js2-prop-get-node-left node)
6812 right (js2-prop-get-node-right node))
6813 (if (setq head (js2-compute-nested-prop-get left))
6814 (nconc head (list right))))
6815 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6816 (setq left (js2-elem-get-node-target node)
6817 right (js2-elem-get-node-element node))
6818 (if (or (js2-string-node-p right) ; ['bar']
6819 (and (js2-number-node-p right) ; [10]
6820 (string-match "^[0-9]+$"
6821 (js2-number-node-value right))))
6822 (if (setq head (js2-compute-nested-prop-get left))
6823 (nconc head (list right))))))))
6825 (defun js2-record-object-literal (node qname pos)
6826 "Recursively process an object literal looking for functions.
6827 NODE is an object literal that is the right-hand child of an assignment
6828 expression. QNAME is a list of nodes representing the assignment target,
6829 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6830 POS is the absolute position of the node.
6831 We do a depth-first traversal of NODE. Any functions we find are prefixed
6832 with QNAME plus the property name of the function and appended to the
6833 variable `js2-imenu-recorder'."
6835 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6836 (let ((left (js2-infix-node-left e))
6837 ;; Element positions are relative to the parent position.
6838 (pos (+ pos (js2-node-pos e))))
6840 ;; foo: function() {...}
6841 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6842 (when (js2-prop-node-name left)
6843 ;; As a policy decision, we record the position of the property,
6844 ;; not the position of the `function' keyword, since the property
6845 ;; is effectively the name of the function.
6846 (push (append qname (list left pos))
6848 (js2-record-function-qname right qname)))
6849 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6850 ((js2-object-node-p right)
6851 (js2-record-object-literal right
6852 (append qname (list (js2-infix-node-left e)))
6853 (+ pos (js2-node-pos right)))))))))
6855 (defsubst js2-node-top-level-decl-p (node)
6856 "Return t if NODE's name is defined in the top-level scope.
6857 Also returns t if NODE's name is not defined in any scope, since it implies
6858 that it's an external variable, which must also be in the top-level scope."
6859 (let* ((name (js2-prop-node-name node))
6860 (this-scope (js2-node-get-enclosing-scope node))
6863 ((js2-this-node-p node)
6867 ((setq defining-scope (js2-get-defining-scope this-scope name))
6868 (js2-ast-root-p defining-scope))
6871 (defsubst js2-anonymous-wrapper-fn-p (node)
6872 "Returns t if NODE is an anonymous function that's invoked immediately.
6873 NODE must be `js2-function-node'."
6874 (let ((parent (js2-node-parent node)))
6875 (and (js2-paren-node-p parent)
6876 ;; (function(){...})();
6877 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6878 ;; (function(){...}).call(this);
6879 (and (js2-prop-get-node-p parent)
6880 (member (js2-name-node-name (js2-prop-get-node-right parent))
6882 (js2-call-node-p (js2-node-parent parent)))))))
6884 (defun js2-browse-postprocess-chains (chains)
6885 "Modify function-declaration name chains after parsing finishes.
6886 Some of the information is only available after the parse tree is complete.
6887 For instance, following a 'this' reference requires a parent function node."
6888 (let ((js2-imenu-fn-type-map (make-hash-table :test 'eq))
6889 result head fn fn-type parent-chain p elem parent)
6890 (dolist (chain chains)
6891 ;; examine the head of each node to get its defining scope
6892 (setq head (car chain))
6893 ;; if top-level/external, keep as-is
6894 (if (js2-node-top-level-decl-p head)
6897 ;; starts with this-reference
6898 ((js2-this-node-p head)
6899 (setq fn (js2-node-parent-script-or-fn head)
6900 chain (cdr chain))) ; discard this-node
6901 ;; nested named function
6902 ((js2-function-node-p (setq parent (js2-node-parent head)))
6903 (setq fn (js2-node-parent-script-or-fn parent)))
6904 ;; variable assigned a function expression
6905 (t (setq fn (js2-node-parent-script-or-fn head))))
6907 (setq fn-type (gethash fn js2-imenu-fn-type-map))
6910 (cond ((js2-nested-function-p fn) 'skip)
6912 (gethash fn js2-imenu-function-map))
6914 ((js2-anonymous-wrapper-fn-p fn) 'anon)
6916 (puthash fn fn-type js2-imenu-fn-type-map))
6918 ('anon (push chain result)) ; anonymous top-level wrapper
6919 ('named ; top-level named function
6920 ;; prefix parent fn qname, which is
6921 ;; parent-chain sans last elem, to this chain.
6922 (push (append (butlast parent-chain) chain) result))))))
6923 ;; finally replace each node in each chain with its name.
6924 (dolist (chain result)
6927 (if (js2-node-p (setq elem (car p)))
6928 (setcar p (js2-node-qname-component elem)))
6932 ;; Merge name chains into a trie-like tree structure of nested lists.
6933 ;; To simplify construction of the trie, we first build it out using the rule
6934 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6935 ;; [key, num-or-list]. The second element can be a number; if so, this key
6936 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6937 ;; associated with the key at this level.) Otherwise the second element is
6938 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6939 ;; a simple recursive formulation.
6941 ;; js2-mode is building the data structure for imenu. The imenu documentation
6942 ;; claims that it's the structure above, but in practice it wants the children
6943 ;; at the same list level as the key for that level, which is how I've drawn
6944 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6945 ;; list wrapper around the children at each level.
6947 ;; A completed nested imenu-alist entry looks like this:
6949 ;; ("<definition>" . 7)
6954 ;; In particular, the documentation for `imenu--index-alist' says that
6955 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6956 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6958 (defsubst js2-treeify (lst)
6959 "Convert (a b c d) to (a ((b ((c d)))))"
6960 (if (null (cddr lst)) ; list length <= 2
6962 (list (car lst) (list (js2-treeify (cdr lst))))))
6964 (defun js2-build-alist-trie (chains trie)
6965 "Merge declaration name chains into a trie-like alist structure for imenu.
6966 CHAINS is the qname chain list produced during parsing. TRIE is a
6967 list of elements built up so far."
6968 (let (head tail pos branch kids)
6969 (dolist (chain chains)
6970 (setq head (car chain)
6972 pos (if (numberp (car tail)) (car tail))
6973 branch (js2-find-if (lambda (n)
6974 (string= (car n) head))
6976 kids (second branch))
6978 ;; case 1: this key isn't in the trie yet
6981 (setcdr (last trie) (list (js2-treeify chain)))
6982 (setq trie (list (js2-treeify chain)))))
6983 ;; case 2: key is present with a single number entry: replace w/ list
6984 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6985 ;; ("<definition>" 20)))
6987 (setcar (cdr branch)
6988 (list (list "<definition-1>" kids)
6990 (list "<definition-2>" pos)
6991 (js2-treeify tail)))))
6992 ;; case 3: key is there (with kids), and we're a number entry
6996 (list (format "<definition-%d>"
6997 (1+ (loop for kid in kids
6998 count (eq ?< (aref (car kid) 0)))))
7000 ;; case 4: key is there with kids, need to merge in our chain
7002 (js2-build-alist-trie (list tail) kids))))
7005 (defun js2-flatten-trie (trie)
7006 "Convert TRIE to imenu-format.
7007 Recurses through nodes, and for each one whose second element is a list,
7008 appends the list's flattened elements to the current element. Also
7009 changes the tails into conses. For instance, this pre-flattened trie
7021 Note that the root of the trie has no key, just a list of chains.
7022 This is also true for the value of any key with multiple children,
7023 e.g. key 'c' in the example above."
7026 (mapcar #'js2-flatten-trie trie))
7028 (if (numberp (second trie))
7029 (cons (car trie) (second trie))
7030 ;; else pop list and append its kids
7031 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7033 (defun js2-build-imenu-index ()
7034 "Turn `js2-imenu-recorder' into an imenu data structure."
7035 (unless (eq js2-imenu-recorder 'empty)
7036 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7037 (result (js2-build-alist-trie chains nil)))
7038 (js2-flatten-trie result))))
7040 (defun js2-test-print-chains (chains)
7041 "Print a list of qname chains.
7042 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7043 i.e. one or more nodes, and an integer position as the list tail."
7044 (mapconcat (lambda (chain)
7046 (mapconcat (lambda (elem)
7047 (if (js2-node-p elem)
7048 (or (js2-node-qname-component elem)
7050 (number-to-string elem)))
7059 (defconst js2-version "1.8.0"
7060 "Version of JavaScript supported, plus minor js2 version.")
7062 (defmacro js2-record-face (face)
7063 "Record a style run of FACE for the current token."
7064 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7066 (defsubst js2-node-end (n)
7067 "Computes the absolute end of node N.
7068 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7069 is only true until the node is added to its parent; i.e., while parsing."
7073 (defsubst js2-record-comment ()
7074 "Record a comment in `js2-scanned-comments'."
7075 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7076 :format js2-ts-comment-type)
7077 js2-scanned-comments)
7078 (when js2-parse-ide-mode
7079 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7081 'font-lock-comment-face))
7082 (when (memq js2-ts-comment-type '(html preprocessor))
7083 ;; Tell cc-engine the bounds of the comment.
7084 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7086 ;; This function is called depressingly often, so it should be fast.
7087 ;; Most of the time it's looking at the same token it peeked before.
7088 (defsubst js2-peek-token ()
7089 "Returns the next token without consuming it.
7090 If previous token was consumed, calls scanner to get new token.
7091 If previous token was -not- consumed, returns it (idempotent).
7093 This function will not return a newline (js2-EOL) - instead, it
7094 gobbles newlines until it finds a non-newline token, and flags
7095 that token as appearing just after a newline.
7097 This function will also not return a js2-COMMENT. Instead, it
7098 records comments found in `js2-scanned-comments'. If the token
7099 returned by this function immediately follows a jsdoc comment,
7100 the token is flagged as such.
7102 Note that this function always returned the un-flagged token!
7103 The flags, if any, are saved in `js2-current-flagged-token'."
7104 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7105 js2-current-token ; most common case - return already-peeked token
7106 (let ((tt (js2-get-token)) ; call scanner
7109 ;; process comments and whitespace
7110 (while (or (= tt js2-EOL)
7115 (if js2-record-comments
7116 (js2-record-comment)))
7117 (setq tt (js2-get-token))) ; call scanner
7118 (setq js2-current-token tt
7119 js2-current-flagged-token (if saw-eol
7120 (logior tt js2-ti-after-eol)
7122 ;; perform lexical fontification as soon as token is scanned
7123 (when js2-parse-ide-mode
7126 (js2-record-face 'js2-error-face))
7127 ((setq face (aref js2-kwd-tokens tt))
7128 (js2-record-face face))
7129 ((and (= tt js2-NAME)
7130 (equal js2-ts-string "undefined"))
7131 (js2-record-face 'font-lock-constant-face))))
7132 tt))) ; return unflagged token
7134 (defsubst js2-peek-flagged-token ()
7135 "Returns the current token along with any flags set for it."
7137 js2-current-flagged-token)
7139 (defsubst js2-consume-token ()
7140 (setq js2-current-flagged-token js2-EOF))
7142 (defsubst js2-next-token ()
7145 (js2-consume-token)))
7147 (defsubst js2-next-flagged-token ()
7149 (prog1 js2-current-flagged-token
7150 (js2-consume-token)))
7152 (defsubst js2-match-token (match)
7153 "Consume and return t if next token matches MATCH, a bytecode.
7154 Returns nil and consumes nothing if MATCH is not the next token."
7155 (if (/= (js2-peek-token) match)
7160 (defsubst js2-valid-prop-name-token (tt)
7162 (and js2-allow-keywords-as-property-names
7164 (aref js2-kwd-tokens tt))))
7166 (defsubst js2-match-prop-name ()
7167 "Consume token and return t if next token is a valid property name.
7168 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7169 is non-nil and it's a keyword token."
7170 (if (js2-valid-prop-name-token (js2-peek-token))
7176 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7177 (if (js2-match-prop-name)
7179 (js2-report-error msg-id nil pos len)
7182 (defsubst js2-peek-token-or-eol ()
7183 "Return js2-EOL if the current token immediately follows a newline.
7184 Else returns the current token. Used in situations where we don't
7185 consider certain token types valid if they are preceded by a newline.
7186 One example is the postfix ++ or -- operator, which has to be on the
7187 same line as its operand."
7188 (let ((tt (js2-peek-token)))
7189 ;; Check for last peeked token flags
7190 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7194 (defsubst js2-set-check-for-label ()
7195 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7196 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7198 (defsubst js2-must-match (token msg-id &optional pos len)
7199 "Match next token to token code TOKEN, or record a syntax error.
7200 MSG-ID is the error message to report if the match fails.
7201 Returns t on match, nil if no match."
7202 (if (js2-match-token token)
7204 (js2-report-error msg-id nil pos len)
7207 (defsubst js2-inside-function ()
7208 (plusp js2-nesting-of-function))
7210 (defsubst js2-set-requires-activation ()
7211 (if (js2-function-node-p js2-current-script-or-fn)
7212 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7214 (defsubst js2-check-activation-name (name token)
7215 (when (js2-inside-function)
7216 ;; skip language-version 1.2 check from Rhino
7217 (if (or (string= "arguments" name)
7218 (and js2-compiler-activation-names ; only used in codegen
7219 (gethash name js2-compiler-activation-names)))
7220 (js2-set-requires-activation))))
7222 (defsubst js2-set-is-generator ()
7223 (if (js2-function-node-p js2-current-script-or-fn)
7224 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7226 (defsubst js2-must-have-xml ()
7227 (unless js2-compiler-xml-available
7228 (js2-report-error "msg.XML.not.available")))
7230 (defsubst js2-push-scope (scope)
7231 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7232 (assert (js2-scope-p scope))
7233 (assert (null (js2-scope-parent-scope scope)))
7234 (assert (not (eq js2-current-scope scope)))
7235 (setf (js2-scope-parent-scope scope) js2-current-scope
7236 js2-current-scope scope))
7238 (defsubst js2-pop-scope ()
7239 (setq js2-current-scope
7240 (js2-scope-parent-scope js2-current-scope)))
7242 (defsubst js2-enter-loop (loop-node)
7243 (push loop-node js2-loop-set)
7244 (push loop-node js2-loop-and-switch-set)
7245 (js2-push-scope loop-node)
7246 ;; Tell the current labeled statement (if any) its statement,
7247 ;; and set the jump target of the first label to the loop.
7248 ;; These are used in `js2-parse-continue' to verify that the
7249 ;; continue target is an actual labeled loop. (And for codegen.)
7250 (when js2-labeled-stmt
7251 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7252 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7253 js2-labeled-stmt))) loop-node)))
7255 (defsubst js2-exit-loop ()
7257 (pop js2-loop-and-switch-set)
7260 (defsubst js2-enter-switch (switch-node)
7261 (push switch-node js2-loop-and-switch-set))
7263 (defsubst js2-exit-switch ()
7264 (pop js2-loop-and-switch-set))
7266 (defun js2-parse (&optional buf cb)
7267 "Tells the js2 parser to parse a region of JavaScript.
7269 BUF is a buffer or buffer name containing the code to parse.
7270 Call `narrow-to-region' first to parse only part of the buffer.
7272 The returned AST root node is given some additional properties:
7273 `node-count' - total number of nodes in the AST
7274 `buffer' - BUF. The buffer it refers to may change or be killed,
7275 so the value is not necessarily reliable.
7277 An optional callback CB can be specified to report parsing
7278 progress. If `(functionp CB)' returns t, it will be called with
7279 the current line number once before parsing begins, then again
7280 each time the lexer reaches a new line number.
7282 CB can also be a list of the form `(symbol cb ...)' to specify
7283 multiple callbacks with different criteria. Each symbol is a
7284 criterion keyword, and the following element is the callback to
7287 :line - called whenever the line number changes
7288 :token - called for each new token consumed
7290 The list of criteria could be extended to include entering or
7291 leaving a statement, an expression, or a function definition."
7292 (if (and cb (not (functionp cb)))
7293 (error "criteria callbacks not yet implemented"))
7294 (let ((inhibit-point-motion-hooks t)
7295 (js2-compiler-xml-available (>= js2-language-version 160))
7296 ;; This is a recursive-descent parser, so give it a big stack.
7297 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7298 (max-specpdl-size (max max-specpdl-size 3000))
7299 (case-fold-search nil)
7301 (or buf (setq buf (current-buffer)))
7302 (message nil) ; clear any error message from previous parse
7305 (setq js2-scanned-comments nil
7306 js2-parsed-errors nil
7307 js2-parsed-warnings nil
7308 js2-imenu-recorder nil
7309 js2-imenu-function-map nil
7312 (setq ast (js2-with-unmodifying-text-property-changes
7314 (unless js2-ts-hit-eof
7315 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7316 (setf (js2-ast-root-errors ast) js2-parsed-errors
7317 (js2-ast-root-warnings ast) js2-parsed-warnings)
7318 ;; if we didn't find any declarations, put a dummy in this list so we
7319 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7320 (unless js2-imenu-recorder
7321 (setq js2-imenu-recorder 'empty))
7322 (run-hooks 'js2-parse-finished-hook)
7325 ;; Corresponds to Rhino's Parser.parse() method.
7326 (defun js2-do-parse ()
7327 "Parse current buffer starting from current point.
7328 Scanner should be initialized."
7329 (let ((pos js2-ts-cursor)
7330 (end js2-ts-cursor) ; in case file is empty
7332 ;; initialize buffer-local parsing vars
7333 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7334 js2-current-script-or-fn root
7335 js2-current-scope root
7336 js2-current-flagged-token js2-EOF
7337 js2-nesting-of-function 0
7338 js2-labeled-stmt nil
7339 js2-recorded-identifiers nil) ; for js2-highlight
7340 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7341 (if (= tt js2-FUNCTION)
7344 (setq n (js2-parse-function (if js2-called-by-compile-function
7345 'FUNCTION_EXPRESSION
7346 'FUNCTION_STATEMENT))))
7347 ;; not a function - parse a statement
7348 (setq n (js2-parse-statement)))
7349 ;; add function or statement to script
7350 (setq end (js2-node-end n))
7351 (js2-block-node-push root n))
7352 ;; add comments to root in lexical order
7353 (when js2-scanned-comments
7354 ;; if we find a comment beyond end of normal kids, use its end
7355 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7356 (dolist (comment js2-scanned-comments)
7357 (push comment (js2-ast-root-comments root))
7358 (js2-node-add-children root comment)))
7359 (setf (js2-node-len root) (- end pos))
7360 ;; Give extensions a chance to muck with things before highlighting starts.
7361 (dolist (callback js2-post-parse-callbacks)
7363 (js2-highlight-undeclared-vars)
7366 (defun js2-function-parser ()
7368 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7370 (defun js2-parse-function-closure-body (fn-node)
7371 "Parse a JavaScript 1.8 function closure body."
7372 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7374 (js2-report-error "msg.no.brace.body" nil
7375 (js2-node-pos fn-node)
7376 (- js2-ts-cursor (js2-node-pos fn-node)))
7377 (js2-node-add-children fn-node
7378 (setf (js2-function-node-body fn-node)
7379 (js2-parse-expr t))))))
7381 (defun js2-parse-function-body (fn-node)
7382 (js2-must-match js2-LC "msg.no.brace.body"
7383 (js2-node-pos fn-node)
7384 (- js2-ts-cursor (js2-node-pos fn-node)))
7385 (let ((pos js2-token-beg) ; LC position
7386 (pn (make-js2-block-node)) ; starts at LC position
7389 (incf js2-nesting-of-function)
7391 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7394 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7395 (js2-parse-statement)
7397 (js2-parse-function 'FUNCTION_STATEMENT))))
7398 (decf js2-nesting-of-function))
7399 (setq end js2-token-end) ; assume no curly and leave at current token
7400 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7401 (setq end js2-token-end))
7402 (setf (js2-node-pos pn) pos
7403 (js2-node-len pn) (- end pos))
7404 (setf (js2-function-node-body fn-node) pn)
7405 (js2-node-add-children fn-node pn)
7408 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7409 "Declare and fontify destructuring parameters inside NODE.
7410 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7412 ((js2-name-node-p node)
7414 (js2-define-symbol decl-type (js2-name-node-name node)
7415 node ignore-not-in-block)
7417 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7418 (+ leftpos (js2-node-len node))
7420 ((js2-object-node-p node)
7421 (dolist (elem (js2-object-node-elems node))
7422 (js2-define-destruct-symbols
7423 (if (js2-object-prop-node-p elem)
7424 (js2-object-prop-node-right elem)
7425 ;; abbreviated destructuring {a, b}
7427 decl-type face ignore-not-in-block)))
7428 ((js2-array-node-p node)
7429 (dolist (elem (js2-array-node-elems node))
7431 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7432 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7433 (js2-node-len node)))))
7435 (defun js2-parse-function-params (fn-node pos)
7436 (if (js2-match-token js2-RP)
7437 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7438 (let (params len param)
7439 (loop for tt = (js2-peek-token)
7442 ;; destructuring param
7443 ((or (= tt js2-LB) (= tt js2-LC))
7444 (setq param (js2-parse-primary-expr-lhs))
7445 (js2-define-destruct-symbols param
7447 'js2-function-param-face)
7448 (push param params))
7451 (js2-must-match js2-NAME "msg.no.parm")
7452 (js2-record-face 'js2-function-param-face)
7453 (setq param (js2-create-name-node))
7454 (js2-define-symbol js2-LP js2-ts-string param)
7455 (push param params)))
7457 (js2-match-token js2-COMMA))
7458 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7459 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7461 (js2-node-add-children fn-node p)
7462 (push p (js2-function-node-params fn-node))))))
7464 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7465 "Possibly show inconsistent-return warning.
7466 Last token scanned is the close-curly for the function body."
7467 (when (and js2-mode-show-strict-warnings
7468 js2-strict-inconsistent-return-warning
7469 (not (js2-has-consistent-return-usage
7470 (js2-function-node-body fn-node))))
7471 ;; Have it extend from close-curly to bol or beginning of block.
7472 (let ((pos (save-excursion
7473 (goto-char js2-token-end)
7474 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7476 (end js2-token-end))
7477 (if (plusp (js2-name-node-length name))
7478 (js2-add-strict-warning "msg.no.return.value"
7479 (js2-name-node-name name) pos end)
7480 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7482 (defun js2-parse-function (function-type)
7483 "Function parser. FUNCTION-TYPE is a symbol."
7484 (let ((pos js2-token-beg) ; start of 'function' keyword
7490 (synthetic-type function-type)
7492 ;; parse function name, expression, or non-name (anonymous)
7494 ;; function foo(...)
7495 ((js2-match-token js2-NAME)
7496 (setq name (js2-create-name-node t)
7497 name-beg js2-token-beg
7498 name-end js2-token-end)
7499 (unless (js2-match-token js2-LP)
7500 (when js2-allow-member-expr-as-function-name
7501 ;; function foo.bar(...)
7502 (setq member-expr-node name
7504 member-expr-node (js2-parse-member-expr-tail
7505 nil member-expr-node)))
7506 (js2-must-match js2-LP "msg.no.paren.parms")))
7507 ((js2-match-token js2-LP)
7508 nil) ; anonymous function: leave name as null
7510 ;; function random-member-expr(...)
7511 (when js2-allow-member-expr-as-function-name
7512 ;; Note that memberExpr can not start with '(' like
7513 ;; in function (1+2).toString(), because 'function (' already
7514 ;; processed as anonymous function
7515 (setq member-expr-node (js2-parse-member-expr)))
7516 (js2-must-match js2-LP "msg.no.paren.parms")))
7517 (if (= js2-current-token js2-LP) ; eventually matched LP?
7518 (setq lp js2-token-beg))
7519 (if member-expr-node
7521 (setq synthetic-type 'FUNCTION_EXPRESSION)
7522 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7524 (js2-set-face name-beg name-end
7525 'font-lock-function-name-face 'record)))
7526 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7527 (plusp (js2-name-node-length name)))
7528 ;; Function statements define a symbol in the enclosing scope
7529 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7530 (setf fn-node (make-js2-function-node :pos pos
7533 :lp (if lp (- lp pos))))
7534 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7535 ;; 1. Nested functions are not affected by the dynamic scope flag
7536 ;; as dynamic scope is already a parent of their scope.
7537 ;; 2. Functions defined under the with statement also immune to
7538 ;; this setup, in which case dynamic scope is ignored in favor
7539 ;; of the with object.
7540 (setf (js2-function-node-ignore-dynamic fn-node) t))
7541 ;; dynamically bind all the per-function variables
7542 (let ((js2-current-script-or-fn fn-node)
7543 (js2-current-scope fn-node)
7544 (js2-nesting-of-with 0)
7548 js2-loop-and-switch-set)
7549 (js2-parse-function-params fn-node pos)
7550 (if (and (>= js2-language-version 180)
7551 (/= (js2-peek-token) js2-LC))
7552 (js2-parse-function-closure-body fn-node)
7553 (js2-parse-function-body fn-node))
7555 (js2-node-add-children fn-node name))
7556 (js2-check-inconsistent-return-warning fn-node name)
7557 ;; Function expressions define a name only in the body of the
7558 ;; function, and only if not hidden by a parameter name
7560 (eq synthetic-type 'FUNCTION_EXPRESSION)
7561 (null (js2-scope-get-symbol js2-current-scope
7562 (js2-name-node-name name))))
7563 (js2-define-symbol js2-FUNCTION
7564 (js2-name-node-name name)
7567 (not (eq function-type 'FUNCTION_EXPRESSION)))
7568 (js2-record-imenu-functions fn-node)))
7569 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7570 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7571 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7572 ;; We wait until after parsing the function to set its parent scope,
7573 ;; since `js2-define-symbol' needs the defining-scope check to stop
7574 ;; at the function boundary when checking for redeclarations.
7575 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7578 (defun js2-parse-statements (&optional parent)
7579 "Parse a statement list. Last token consumed must be js2-LC.
7581 PARENT can be a `js2-block-node', in which case the statements are
7582 appended to PARENT. Otherwise a new `js2-block-node' is created
7585 This function does not match the closing js2-RC: the caller
7586 matches the RC so it can provide a suitable error message if not
7587 matched. This means it's up to the caller to set the length of
7588 the node to include the closing RC. The node start pos is set to
7589 the absolute buffer start position, and the caller should fix it
7590 up to be relative to the parent node. All children of this block
7591 node are given relative start positions and correct lengths."
7592 (let ((pn (or parent (make-js2-block-node)))
7594 (setf (js2-node-pos pn) js2-token-beg)
7595 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7597 (js2-block-node-push pn (js2-parse-statement)))
7600 (defun js2-parse-statement ()
7601 (let (tt pn beg end)
7602 ;; coarse-grained user-interrupt check - needs work
7603 (and js2-parse-interruptable-p
7604 (zerop (% (incf js2-parse-stmt-count)
7605 js2-statements-per-pause))
7607 (throw 'interrupted t))
7608 (setq pn (js2-statement-helper))
7609 ;; no-side-effects warning check
7610 (unless (js2-node-has-side-effects pn)
7611 (setq end (js2-node-end pn))
7614 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7615 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7618 ;; These correspond to the switch cases in Parser.statementHelper
7619 (defconst js2-parsers
7620 (let ((parsers (make-vector js2-num-tokens
7621 #'js2-parse-expr-stmt)))
7622 (aset parsers js2-BREAK #'js2-parse-break)
7623 (aset parsers js2-CONST #'js2-parse-const-var)
7624 (aset parsers js2-CONTINUE #'js2-parse-continue)
7625 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7626 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7627 (aset parsers js2-DO #'js2-parse-do)
7628 (aset parsers js2-FOR #'js2-parse-for)
7629 (aset parsers js2-FUNCTION #'js2-function-parser)
7630 (aset parsers js2-IF #'js2-parse-if)
7631 (aset parsers js2-LC #'js2-parse-block)
7632 (aset parsers js2-LET #'js2-parse-let-stmt)
7633 (aset parsers js2-NAME #'js2-parse-name-or-label)
7634 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7635 (aset parsers js2-SEMI #'js2-parse-semi)
7636 (aset parsers js2-SWITCH #'js2-parse-switch)
7637 (aset parsers js2-THROW #'js2-parse-throw)
7638 (aset parsers js2-TRY #'js2-parse-try)
7639 (aset parsers js2-VAR #'js2-parse-const-var)
7640 (aset parsers js2-WHILE #'js2-parse-while)
7641 (aset parsers js2-WITH #'js2-parse-with)
7642 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7644 "A vector mapping token types to parser functions.")
7646 (defsubst js2-parse-warn-missing-semi (beg end)
7647 (and js2-mode-show-strict-warnings
7648 js2-strict-missing-semi-warning
7649 (js2-add-strict-warning
7650 "msg.missing.semi" nil
7651 ;; back up to beginning of statement or line
7652 (max beg (save-excursion
7657 (defconst js2-no-semi-insertion
7669 "List of tokens that don't do automatic semicolon insertion.")
7671 (defconst js2-autoinsert-semi-and-warn
7672 (list js2-ERROR js2-EOF js2-RC))
7674 (defun js2-statement-helper ()
7675 (let* ((tt (js2-peek-token))
7678 (parser (if (= tt js2-ERROR)
7680 (aref js2-parsers tt)))
7683 ;; If the statement is set, then it's been told its label by now.
7684 (and js2-labeled-stmt
7685 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7686 (setq js2-labeled-stmt nil))
7687 (setq pn (funcall parser))
7688 ;; Don't do auto semi insertion for certain statement types.
7689 (unless (or (memq first-tt js2-no-semi-insertion)
7690 (js2-labeled-stmt-node-p pn))
7691 (js2-auto-insert-semicolon pn))
7694 (defun js2-auto-insert-semicolon (pn)
7695 (let* ((tt-flagged (js2-peek-flagged-token))
7696 (tt (logand tt-flagged js2-clear-ti-mask))
7697 (pos (js2-node-pos pn)))
7700 ;; Consume ';' as a part of expression
7702 ;; extend the node bounds to include the semicolon.
7703 (setf (js2-node-len pn) (- js2-token-end pos)))
7704 ((memq tt js2-autoinsert-semi-and-warn)
7706 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7708 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7709 ;; Report error if no EOL or autoinsert ';' otherwise
7710 (js2-report-error "msg.no.semi.stmt")
7711 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7713 (defun js2-parse-condition ()
7714 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7715 The parens are discarded and the expression node is returned.
7716 The `pos' field of the return value is set to an absolute position
7717 that must be fixed up by the caller.
7718 Return value is a list (EXPR LP RP), with absolute paren positions."
7720 (if (js2-must-match js2-LP "msg.no.paren.cond")
7721 (setq lp js2-token-beg))
7722 (setq pn (js2-parse-expr))
7723 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7724 (setq rp js2-token-beg))
7725 ;; Report strict warning on code like "if (a = 7) ..."
7726 (if (and js2-strict-cond-assign-warning
7727 (js2-assign-node-p pn))
7728 (js2-add-strict-warning "msg.equal.as.assign" nil
7730 (+ (js2-node-pos pn)
7731 (js2-node-len pn))))
7734 (defun js2-parse-if ()
7735 "Parser for if-statement. Last matched token must be js2-IF."
7736 (let ((pos js2-token-beg)
7744 (setq cond (js2-parse-condition)
7745 if-true (js2-parse-statement)
7746 if-false (if (js2-match-token js2-ELSE)
7748 (setq else-pos (- js2-token-beg pos))
7749 (js2-parse-statement)))
7750 end (js2-node-end (or if-false if-true))
7751 pn (make-js2-if-node :pos pos
7753 :condition (car cond)
7757 :lp (js2-relpos (second cond) pos)
7758 :rp (js2-relpos (third cond) pos)))
7759 (js2-node-add-children pn (car cond) if-true if-false)
7762 (defun js2-parse-switch ()
7763 "Parser for if-statement. Last matched token must be js2-SWITCH."
7764 (let ((pos js2-token-beg)
7777 (if (js2-must-match js2-LP "msg.no.paren.switch")
7778 (setq lp js2-token-beg))
7779 (setq discriminant (js2-parse-expr)
7780 pn (make-js2-switch-node :discriminant discriminant
7782 :lp (js2-relpos lp pos)))
7783 (js2-node-add-children pn discriminant)
7784 (js2-enter-switch pn)
7787 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7788 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7789 (js2-must-match js2-LC "msg.no.brace.switch")
7792 (setq tt (js2-next-token)
7793 case-pos js2-token-beg)
7796 (setf (js2-node-len pn) (- js2-token-end pos))
7797 (throw 'break nil)) ; done
7799 (setq case-expr (js2-parse-expr))
7800 (js2-must-match js2-COLON "msg.no.colon.case"))
7803 (js2-report-error "msg.double.switch.default"))
7806 (js2-must-match js2-COLON "msg.no.colon.case"))
7808 (js2-report-error "msg.bad.switch")
7809 (throw 'break nil)))
7810 (setq case-node (make-js2-case-node :pos case-pos
7811 :len (- js2-token-end case-pos)
7813 (js2-node-add-children case-node case-expr)
7814 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7818 (setf stmt (js2-parse-statement)
7819 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7820 (js2-block-node-push case-node stmt))
7821 (push case-node cases)))
7822 ;; add cases last, as pushing reverses the order to be correct
7824 (js2-node-add-children pn kid)
7825 (push kid (js2-switch-node-cases pn)))
7827 (js2-exit-switch))))
7829 (defun js2-parse-while ()
7830 "Parser for while-statement. Last matched token must be js2-WHILE."
7831 (let ((pos js2-token-beg)
7832 (pn (make-js2-while-node))
7839 (setf cond (js2-parse-condition)
7840 (js2-while-node-condition pn) (car cond)
7841 body (js2-parse-statement)
7842 (js2-while-node-body pn) body
7843 (js2-node-len pn) (- (js2-node-end body) pos)
7844 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7845 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7846 (js2-node-add-children pn body (car cond)))
7850 (defun js2-parse-do ()
7851 "Parser for do-statement. Last matched token must be js2-DO."
7852 (let ((pos js2-token-beg)
7853 (pn (make-js2-do-node))
7861 (setq body (js2-parse-statement))
7862 (js2-must-match js2-WHILE "msg.no.while.do")
7863 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7864 cond (js2-parse-condition)
7865 (js2-do-node-condition pn) (car cond)
7866 (js2-do-node-body pn) body
7868 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7869 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7870 (js2-node-add-children pn (car cond) body))
7872 ;; Always auto-insert semicolon to follow SpiderMonkey:
7873 ;; It is required by ECMAScript but is ignored by the rest of
7874 ;; world; see bug 238945
7875 (if (js2-match-token js2-SEMI)
7876 (setq end js2-ts-cursor))
7877 (setf (js2-node-len pn) (- end pos))
7880 (defun js2-parse-for ()
7881 "Parser for for-statement. Last matched token must be js2-FOR.
7882 Parses for, for-in, and for each-in statements."
7883 (let ((for-pos js2-token-beg)
7890 init ; Node init is also foo in 'foo in object'
7891 cond ; Node cond is also object in 'foo in object'
7892 incr ; 3rd section of for-loop initializer
7898 ;; See if this is a for each () instead of just a for ()
7899 (when (js2-match-token js2-NAME)
7900 (if (string= "each" js2-ts-string)
7903 each-pos (- js2-token-beg for-pos)) ; relative
7904 (js2-record-face 'font-lock-keyword-face))
7905 (js2-report-error "msg.no.paren.for")))
7906 (if (js2-must-match js2-LP "msg.no.paren.for")
7907 (setq lp (- js2-token-beg for-pos)))
7908 (setq tt (js2-peek-token))
7909 ;; parse init clause
7910 (let ((js2-in-for-init t)) ; set as dynamic variable
7913 (setq init (make-js2-empty-expr-node)))
7914 ((or (= tt js2-VAR) (= tt js2-LET))
7916 (setq init (js2-parse-variables tt js2-token-beg)))
7918 (setq init (js2-parse-expr)))))
7919 (if (js2-match-token js2-IN)
7921 in-pos (- js2-token-beg for-pos)
7922 cond (js2-parse-expr)) ; object over which we're iterating
7923 ;; else ordinary for loop - parse cond and incr
7924 (js2-must-match js2-SEMI "msg.no.semi.for")
7925 (setq cond (if (= (js2-peek-token) js2-SEMI)
7926 (make-js2-empty-expr-node) ; no loop condition
7928 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7929 (setq tmp-pos js2-token-end
7930 incr (if (= (js2-peek-token) js2-RP)
7931 (make-js2-empty-expr-node :pos tmp-pos)
7933 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7934 (setq rp (- js2-token-beg for-pos)))
7936 (setq pn (make-js2-for-node :init init
7941 ;; cond could be null if 'in obj' got eaten by the init node.
7942 (if (js2-infix-node-p init)
7943 ;; it was (foo in bar) instead of (var foo in bar)
7944 (setq cond (js2-infix-node-right init)
7945 init (js2-infix-node-left init))
7946 (if (and (js2-var-decl-node-p init)
7947 (> (length (js2-var-decl-node-kids init)) 1))
7948 (js2-report-error "msg.mult.index")))
7949 (setq pn (make-js2-for-in-node :iterator init
7952 :foreach-p is-for-each
7959 ;; We have to parse the body -after- creating the loop node,
7960 ;; so that the loop node appears in the js2-loop-set, allowing
7961 ;; break/continue statements to find the enclosing loop.
7962 (setf body (js2-parse-statement)
7963 (js2-loop-node-body pn) body
7964 (js2-node-pos pn) for-pos
7965 (js2-node-len pn) (- (js2-node-end body) for-pos))
7966 (js2-node-add-children pn init cond incr body))
7971 (defun js2-parse-try ()
7972 "Parser for try-statement. Last matched token must be js2-TRY."
7973 (let ((try-pos js2-token-beg)
7991 (if (/= (js2-peek-token) js2-LC)
7992 (js2-report-error "msg.no.brace.try"))
7993 (setq try-block (js2-parse-statement)
7994 try-end (js2-node-end try-block)
7995 peek (js2-peek-token))
7998 (while (js2-match-token js2-CATCH)
7999 (setq catch-pos js2-token-beg
8004 (if saw-default-catch
8005 (js2-report-error "msg.catch.unreachable"))
8006 (if (js2-must-match js2-LP "msg.no.paren.catch")
8007 (setq lp (- js2-token-beg catch-pos)))
8008 (js2-push-scope (make-js2-scope))
8009 (let ((tt (js2-peek-token)))
8011 ;; destructuring pattern
8012 ;; catch ({ message, file }) { ... }
8013 ((or (= tt js2-LB) (= tt js2-LC))
8015 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8019 (js2-must-match js2-NAME "msg.bad.catchcond")
8020 (setq param (js2-create-name-node))
8021 (js2-define-symbol js2-LET js2-ts-string param))))
8023 (if (js2-match-token js2-IF)
8024 (setq guard-kwd (- js2-token-beg catch-pos)
8025 catch-cond (js2-parse-expr))
8026 (setq saw-default-catch t))
8027 (if (js2-must-match js2-RP "msg.bad.catchcond")
8028 (setq rp (- js2-token-beg catch-pos)))
8029 (js2-must-match js2-LC "msg.no.brace.catchblock")
8030 (setq block (js2-parse-statements)
8031 try-end (js2-node-end block)
8032 catch-node (make-js2-catch-node :pos catch-pos
8034 :guard-expr catch-cond
8035 :guard-kwd guard-kwd
8040 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8041 (setq try-end js2-token-beg))
8042 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8043 (js2-node-len catch-node) (- try-end catch-pos))
8044 (js2-node-add-children catch-node param catch-cond block)
8045 (push catch-node catch-blocks)))
8046 ((/= peek js2-FINALLY)
8047 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8048 (js2-node-pos try-block)
8049 (- (setq try-end (js2-node-end try-block))
8050 (js2-node-pos try-block)))))
8051 (when (js2-match-token js2-FINALLY)
8052 (setq finally-pos js2-token-beg
8053 block (js2-parse-statement)
8054 try-end (js2-node-end block)
8055 finally-block (make-js2-finally-node :pos finally-pos
8056 :len (- try-end finally-pos)
8058 (js2-node-add-children finally-block block))
8059 (setq pn (make-js2-try-node :pos try-pos
8060 :len (- try-end try-pos)
8061 :try-block try-block
8062 :finally-block finally-block))
8063 (js2-node-add-children pn try-block finally-block)
8064 ;; push them onto the try-node, which reverses and corrects their order
8065 (dolist (cb catch-blocks)
8066 (js2-node-add-children pn cb)
8067 (push cb (js2-try-node-catch-clauses pn)))
8070 (defun js2-parse-throw ()
8071 "Parser for throw-statement. Last matched token must be js2-THROW."
8072 (let ((pos js2-token-beg)
8076 (if (= (js2-peek-token-or-eol) js2-EOL)
8077 ;; ECMAScript does not allow new lines before throw expression,
8079 (js2-report-error "msg.bad.throw.eol"))
8080 (setq expr (js2-parse-expr)
8081 pn (make-js2-throw-node :pos pos
8082 :len (- (js2-node-end expr) pos)
8084 (js2-node-add-children pn expr)
8087 (defsubst js2-match-jump-label-name (label-name)
8088 "If break/continue specified a label, return that label's labeled stmt.
8089 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8090 does not match an existing label, reports an error and returns nil."
8091 (let ((bundle (cdr (assoc label-name js2-label-set))))
8093 (js2-report-error "msg.undef.label"))
8096 (defun js2-parse-break ()
8097 "Parser for break-statement. Last matched token must be js2-BREAK."
8098 (let ((pos js2-token-beg)
8100 break-target ; statement to break from
8101 break-label ; in "break foo", name-node representing the foo
8102 labels ; matching labeled statement to break to
8104 (js2-consume-token) ; `break'
8105 (when (eq (js2-peek-token-or-eol) js2-NAME)
8107 (setq break-label (js2-create-name-node)
8108 end (js2-node-end break-label)
8109 ;; matchJumpLabelName only matches if there is one
8110 labels (js2-match-jump-label-name js2-ts-string)
8111 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8112 (unless (or break-target break-label)
8113 ;; no break target specified - try for innermost enclosing loop/switch
8114 (if (null js2-loop-and-switch-set)
8116 (js2-report-error "msg.bad.break" nil pos (length "break")))
8117 (setq break-target (car js2-loop-and-switch-set))))
8118 (setq pn (make-js2-break-node :pos pos
8121 :target break-target))
8122 (js2-node-add-children pn break-label) ; but not break-target
8125 (defun js2-parse-continue ()
8126 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8127 (let ((pos js2-token-beg)
8129 label ; optional user-specified label, a `js2-name-node'
8130 labels ; current matching labeled stmt, if any
8131 target ; the `js2-loop-node' target of this continue stmt
8133 (js2-consume-token) ; `continue'
8134 (when (= (js2-peek-token-or-eol) js2-NAME)
8136 (setq label (js2-create-name-node)
8137 end (js2-node-end label)
8138 ;; matchJumpLabelName only matches if there is one
8139 labels (js2-match-jump-label-name js2-ts-string)))
8141 ((null labels) ; no current label to go to
8142 (if (null js2-loop-set) ; no loop to continue to
8143 (js2-report-error "msg.continue.outside" nil pos
8144 (length "continue"))
8145 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8147 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8148 (setq target (js2-labeled-stmt-node-stmt labels))
8149 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8150 (setq pn (make-js2-continue-node :pos pos
8154 (js2-node-add-children pn label) ; but not target - it's not our child
8157 (defun js2-parse-with ()
8158 "Parser for with-statement. Last matched token must be js2-WITH."
8160 (let ((pos js2-token-beg)
8162 (if (js2-must-match js2-LP "msg.no.paren.with")
8163 (setq lp js2-token-beg))
8164 (setq obj (js2-parse-expr))
8165 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8166 (setq rp js2-token-beg))
8167 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8168 (setq body (js2-parse-statement)))
8169 (setq pn (make-js2-with-node :pos pos
8170 :len (- (js2-node-end body) pos)
8173 :lp (js2-relpos lp pos)
8174 :rp (js2-relpos rp pos)))
8175 (js2-node-add-children pn obj body)
8178 (defun js2-parse-const-var ()
8179 "Parser for var- or const-statement.
8180 Last matched token must be js2-CONST or js2-VAR."
8181 (let ((tt (js2-peek-token))
8186 (setq expr (js2-parse-variables tt js2-token-beg)
8187 pn (make-js2-expr-stmt-node :pos pos
8188 :len (- (js2-node-end expr) pos)
8190 (js2-node-add-children pn expr)
8193 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8194 (let ((pn (make-js2-expr-stmt-node :pos pos
8195 :len (js2-node-len expr)
8196 :type (if (js2-inside-function)
8201 (js2-node-add-children pn expr))
8204 (defun js2-parse-let-stmt ()
8205 "Parser for let-statement. Last matched token must be js2-LET."
8207 (let ((pos js2-token-beg)
8210 (if (= (js2-peek-token) js2-LP)
8211 ;; let expression in statement context
8212 (setq expr (js2-parse-let pos 'statement)
8213 pn (js2-wrap-with-expr-stmt pos expr t))
8214 ;; else we're looking at a statement like let x=6, y=7;
8215 (setf expr (js2-parse-variables js2-LET pos)
8216 pn (js2-wrap-with-expr-stmt pos expr t)
8217 (js2-node-type pn) js2-EXPR_RESULT))
8220 (defun js2-parse-ret-yield ()
8221 (js2-parse-return-or-yield (js2-peek-token) nil))
8223 (defconst js2-parse-return-stmt-enders
8224 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8226 (defsubst js2-now-all-set (before after mask)
8227 "Return whether or not the bits in the mask have changed to all set.
8228 BEFORE is bits before change, AFTER is bits after change, and MASK is
8229 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8231 (and (/= (logand before mask) mask)
8232 (= (logand after mask) mask)))
8234 (defun js2-parse-return-or-yield (tt expr-context)
8235 (let ((pos js2-token-beg)
8237 (before js2-end-flags)
8238 (inside-function (js2-inside-function))
8242 (unless inside-function
8243 (js2-report-error (if (eq tt js2-RETURN)
8247 ;; This is ugly, but we don't want to require a semicolon.
8248 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8249 (setq e (js2-parse-expr)
8250 end (js2-node-end e)))
8253 (js2-set-flag js2-end-flags (if (null e)
8255 js2-end-returns-value))
8256 (setq ret (make-js2-return-node :pos pos
8259 (js2-node-add-children ret e)
8260 ;; See if we need a strict mode warning.
8261 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8262 ;; more thorough and accurate than this before/after flag check.
8263 ;; E.g. if there's a finally-block that always returns, we shouldn't
8264 ;; show a warning generated by inconsistent returns in the catch blocks.
8265 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8266 ;; so we know which returns/yields to highlight, and we should get rid of
8267 ;; all the checking in `js2-parse-return-or-yield'.
8268 (if (and js2-strict-inconsistent-return-warning
8269 (js2-now-all-set before js2-end-flags
8270 (logior js2-end-returns js2-end-returns-value)))
8271 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8273 (unless (js2-inside-function)
8274 (js2-report-error "msg.bad.yield"))
8275 (js2-set-flag js2-end-flags js2-end-yields)
8276 (setq ret (make-js2-yield-node :pos pos
8279 (js2-node-add-children ret e)
8280 (unless expr-context
8282 ret (js2-wrap-with-expr-stmt pos e t))
8283 (js2-set-requires-activation)
8284 (js2-set-is-generator))))
8285 ;; see if we are mixing yields and value returns.
8286 (when (and inside-function
8287 (js2-now-all-set before js2-end-flags
8288 (logior js2-end-yields js2-end-returns-value)))
8289 (setq name (js2-function-name js2-current-script-or-fn))
8290 (if (zerop (length name))
8291 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8292 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8295 (defun js2-parse-debugger ()
8297 (make-js2-keyword-node :type js2-DEBUGGER))
8299 (defun js2-parse-block ()
8300 "Parser for a curly-delimited statement block.
8301 Last token matched must be js2-LC."
8302 (let ((pos js2-token-beg)
8303 (pn (make-js2-scope)))
8308 (js2-parse-statements pn)
8309 (js2-must-match js2-RC "msg.no.brace.block")
8310 (setf (js2-node-len pn) (- js2-token-end pos)))
8314 ;; for js2-ERROR too, to have a node for error recovery to work on
8315 (defun js2-parse-semi ()
8316 "Parse a statement or handle an error.
8317 Last matched token is js-SEMI or js-ERROR."
8318 (let ((tt (js2-peek-token)) pos len)
8320 (if (eq tt js2-SEMI)
8321 (make-js2-empty-expr-node :len 1)
8322 (setq pos js2-token-beg
8323 len (- js2-token-beg pos))
8324 (js2-report-error "msg.syntax" nil pos len)
8325 (make-js2-error-node :pos pos :len len))))
8327 (defun js2-parse-default-xml-namespace ()
8328 "Parse a `default xml namespace = <expr>' e4x statement."
8329 (let ((pos js2-token-beg)
8330 end len expr unary es)
8333 (js2-set-requires-activation)
8334 (setq len (- js2-ts-cursor pos))
8335 (unless (and (js2-match-token js2-NAME)
8336 (string= js2-ts-string "xml"))
8337 (js2-report-error "msg.bad.namespace" nil pos len))
8338 (unless (and (js2-match-token js2-NAME)
8339 (string= js2-ts-string "namespace"))
8340 (js2-report-error "msg.bad.namespace" nil pos len))
8341 (unless (js2-match-token js2-ASSIGN)
8342 (js2-report-error "msg.bad.namespace" nil pos len))
8343 (setq expr (js2-parse-expr)
8344 end (js2-node-end expr)
8345 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8349 (js2-node-add-children unary expr)
8350 (make-js2-expr-stmt-node :pos pos
8354 (defun js2-record-label (label bundle)
8355 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8357 (let ((name (js2-label-node-name label))
8360 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8361 ;; flag both labels if possible when used in editing mode
8362 (if (and js2-parse-ide-mode
8363 (setq dup (js2-get-label-by-name labeled-stmt name)))
8364 (js2-report-error "msg.dup.label" nil
8365 (js2-node-abs-pos dup) (js2-node-len dup)))
8366 (js2-report-error "msg.dup.label" nil
8367 (js2-node-pos label) (js2-node-len label)))
8368 (js2-labeled-stmt-node-add-label bundle label)
8369 (js2-node-add-children bundle label)
8370 ;; Add one reference to the bundle per label in `js2-label-set'
8371 (push (cons name bundle) js2-label-set)))
8373 (defun js2-parse-name-or-label ()
8374 "Parser for identifier or label. Last token matched must be js2-NAME.
8375 Called when we found a name in a statement context. If it's a label, we gather
8376 up any following labels and the next non-label statement into a
8377 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8378 expression and return it wrapped in a `js2-expr-stmt-node'."
8379 (let ((pos js2-token-beg)
8386 ;; set check for label and call down to `js2-parse-primary-expr'
8387 (js2-set-check-for-label)
8388 (setq expr (js2-parse-expr))
8389 (if (/= (js2-node-type expr) js2-LABEL)
8390 ;; Parsed non-label expression - wrap with expression stmt.
8391 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8392 ;; else parsed a label
8393 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8394 (js2-record-label expr bundle)
8395 ;; look for more labels
8396 (while (and continue (= (js2-peek-token) js2-NAME))
8397 (js2-set-check-for-label)
8398 (setq expr (js2-parse-expr))
8399 (if (/= (js2-node-type expr) js2-LABEL)
8401 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8403 (js2-auto-insert-semicolon stmt))
8404 (js2-record-label expr bundle)))
8405 ;; no more labels; now parse the labeled statement
8408 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8409 (setq stmt (js2-statement-helper))))
8410 ;; remove the labels for this statement from the global set
8411 (dolist (label (js2-labeled-stmt-node-labels bundle))
8412 (setq js2-label-set (remove label js2-label-set))))
8413 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8414 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8415 (js2-node-add-children bundle stmt)
8418 (defun js2-parse-expr-stmt ()
8419 "Default parser in statement context, if no recognized statement found."
8420 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8422 (defun js2-parse-variables (decl-type pos)
8423 "Parse a comma-separated list of variable declarations.
8424 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8426 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8427 For 'var' or 'const', the keyword should be the token last scanned.
8429 POS is the position where the node should start. It's sometimes the
8430 var/const/let keyword, and other times the beginning of the first token
8431 in the first variable declaration.
8433 Returns the parsed `js2-var-decl-node' expression node."
8434 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8446 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8447 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8448 ;; var {a, b} = baz;
8450 (setq destructuring nil
8453 kid-pos js2-token-beg
8456 (if (or (= tt js2-LB) (= tt js2-LC))
8457 ;; Destructuring assignment, e.g., var [a, b] = ...
8458 (setq destructuring (js2-parse-primary-expr-lhs)
8459 end (js2-node-end destructuring))
8460 ;; Simple variable name
8461 (when (js2-must-match js2-NAME "msg.bad.var")
8462 (setq name (js2-create-name-node)
8466 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8467 (when (js2-match-token js2-ASSIGN)
8468 (setq init (js2-parse-assign-expr)
8469 end (js2-node-end init))
8470 (if (and js2-parse-ide-mode
8471 (or (js2-object-node-p init)
8472 (js2-function-node-p init)))
8473 (js2-record-imenu-functions init name)))
8475 (js2-set-face nbeg nend (if (js2-function-node-p init)
8476 'font-lock-function-name-face
8477 'font-lock-variable-name-face)
8479 (setq vi (make-js2-var-init-node :pos kid-pos
8480 :len (- end kid-pos)
8484 (if (and (null init) (not js2-in-for-init))
8485 (js2-report-error "msg.destruct.assign.no.init"))
8486 (js2-define-destruct-symbols destructuring
8488 'font-lock-variable-name-face)
8489 (setf (js2-var-init-node-target vi) destructuring))
8490 (setf (js2-var-init-node-target vi) name))
8491 (setf (js2-var-init-node-initializer vi) init)
8492 (js2-node-add-children vi name destructuring init)
8493 (js2-block-node-push result vi)
8494 (unless (js2-match-token js2-COMMA)
8495 (setq continue nil)))
8496 (setf (js2-node-len result) (- end pos))
8499 (defun js2-parse-let (pos &optional stmt-p)
8500 "Parse a let expression or statement.
8501 A let-expression is of the form `let (vars) expr'.
8502 A let-statment is of the form `let (vars) {statements}'.
8503 The third form of let is a variable declaration list, handled
8504 by `js2-parse-variables'."
8505 (let ((pn (make-js2-let-node :pos pos))
8507 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8508 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8512 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8513 (if (js2-must-match js2-RP "msg.no.paren.let")
8514 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8515 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8519 (setf beg js2-token-beg ; position stmt at LC
8520 body (js2-parse-statements))
8521 (js2-must-match js2-RC "msg.no.curly.let")
8522 (setf (js2-node-len body) (- js2-token-end beg)
8523 (js2-node-len pn) (- js2-token-end pos)
8524 (js2-let-node-body pn) body
8525 (js2-node-type pn) js2-LET))
8527 (setf body (js2-parse-expr)
8528 (js2-node-len pn) (- (js2-node-end body) pos)
8529 (js2-let-node-body pn) body))
8530 (js2-node-add-children pn vars body))
8534 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8535 (js2-scope-put-symbol (or scope js2-current-scope)
8537 (make-js2-symbol decl-type name node)))
8539 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8540 "Define a symbol in the current scope.
8541 If NODE is non-nil, it is the AST node associated with the symbol."
8542 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8543 (symbol (if defining-scope
8544 (js2-scope-get-symbol defining-scope name)))
8545 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8547 ((and symbol ; already defined
8548 (or (= sdt js2-CONST) ; old version is const
8549 (= decl-type js2-CONST) ; new version is const
8550 ;; two let-bound vars in this block have same name
8551 (and (= sdt js2-LET)
8552 (eq defining-scope js2-current-scope))))
8555 ((= sdt js2-CONST) "msg.const.redecl")
8556 ((= sdt js2-LET) "msg.let.redecl")
8557 ((= sdt js2-VAR) "msg.var.redecl")
8558 ((= sdt js2-FUNCTION) "msg.function.redecl")
8559 (t "msg.parm.redecl"))
8561 ((= decl-type js2-LET)
8562 (if (and (not ignore-not-in-block)
8563 (or (= (js2-node-type js2-current-scope) js2-IF)
8564 (js2-loop-node-p js2-current-scope)))
8565 (js2-report-error "msg.let.decl.not.in.block")
8566 (js2-define-new-symbol decl-type name node)))
8567 ((or (= decl-type js2-VAR)
8568 (= decl-type js2-CONST)
8569 (= decl-type js2-FUNCTION))
8571 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8572 (js2-add-strict-warning "msg.var.redecl" name)
8573 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8574 (js2-add-strict-warning "msg.var.hides.arg" name)))
8575 (js2-define-new-symbol decl-type name node
8576 js2-current-script-or-fn)))
8577 ((= decl-type js2-LP)
8579 ;; must be duplicate parameter. Second parameter hides the
8580 ;; first, so go ahead and add the second pararameter
8581 (js2-report-warning "msg.dup.parms" name))
8582 (js2-define-new-symbol decl-type name node))
8583 (t (js2-code-bug)))))
8585 (defun js2-parse-expr (&optional oneshot)
8586 (let* ((pn (js2-parse-assign-expr))
8587 (pos (js2-node-pos pn))
8591 (while (and (not oneshot)
8592 (js2-match-token js2-COMMA))
8593 (setq op-pos (- js2-token-beg pos)) ; relative
8594 (if (= (js2-peek-token) js2-YIELD)
8595 (js2-report-error "msg.yield.parenthesized"))
8596 (setq right (js2-parse-assign-expr)
8598 pn (make-js2-infix-node :type js2-COMMA
8600 :len (- js2-ts-cursor pos)
8604 (js2-node-add-children pn left right))
8607 (defun js2-parse-assign-expr ()
8608 (let ((tt (js2-peek-token))
8614 (if (= tt js2-YIELD)
8615 (js2-parse-return-or-yield tt t)
8616 ;; not yield - parse assignment expression
8617 (setq pn (js2-parse-cond-expr)
8618 tt (js2-peek-token))
8619 (when (and (<= js2-first-assign tt)
8620 (<= tt js2-last-assign))
8621 ;; tt express assignment (=, |=, ^=, ..., %=)
8623 (setq op-pos (- js2-token-beg pos) ; relative
8625 right (js2-parse-assign-expr)
8626 pn (make-js2-assign-node :type tt
8628 :len (- (js2-node-end right) pos)
8632 (when js2-parse-ide-mode
8633 (js2-highlight-assign-targets pn left right)
8634 (if (or (js2-function-node-p right)
8635 (js2-object-node-p right))
8636 (js2-record-imenu-functions right left)))
8637 ;; do this last so ide checks above can use absolute positions
8638 (js2-node-add-children pn left right))
8641 (defun js2-parse-cond-expr ()
8642 (let ((pos js2-token-beg)
8643 (pn (js2-parse-or-expr))
8649 (when (js2-match-token js2-HOOK)
8650 (setq q-pos (- js2-token-beg pos)
8651 if-true (js2-parse-assign-expr))
8652 (js2-must-match js2-COLON "msg.no.colon.cond")
8653 (setq c-pos (- js2-token-beg pos)
8654 if-false (js2-parse-assign-expr)
8656 pn (make-js2-cond-node :pos pos
8657 :len (- (js2-node-end if-false) pos)
8658 :test-expr test-expr
8660 :false-expr if-false
8663 (js2-node-add-children pn test-expr if-true if-false))
8666 (defun js2-make-binary (type left parser)
8667 "Helper for constructing a binary-operator AST node.
8668 LEFT is the left-side-expression, already parsed, and the
8669 binary operator should have just been matched.
8670 PARSER is a function to call to parse the right operand,
8671 or a `js2-node' struct if it has already been parsed."
8672 (let* ((pos (js2-node-pos left))
8673 (op-pos (- js2-token-beg pos))
8674 (right (if (js2-node-p parser)
8677 (pn (make-js2-infix-node :type type
8679 :len (- (js2-node-end right) pos)
8683 (js2-node-add-children pn left right)
8686 (defun js2-parse-or-expr ()
8687 (let ((pn (js2-parse-and-expr)))
8688 (when (js2-match-token js2-OR)
8689 (setq pn (js2-make-binary js2-OR
8691 'js2-parse-or-expr)))
8694 (defun js2-parse-and-expr ()
8695 (let ((pn (js2-parse-bit-or-expr)))
8696 (when (js2-match-token js2-AND)
8697 (setq pn (js2-make-binary js2-AND
8699 'js2-parse-and-expr)))
8702 (defun js2-parse-bit-or-expr ()
8703 (let ((pn (js2-parse-bit-xor-expr)))
8704 (while (js2-match-token js2-BITOR)
8705 (setq pn (js2-make-binary js2-BITOR
8707 'js2-parse-bit-xor-expr)))
8710 (defun js2-parse-bit-xor-expr ()
8711 (let ((pn (js2-parse-bit-and-expr)))
8712 (while (js2-match-token js2-BITXOR)
8713 (setq pn (js2-make-binary js2-BITXOR
8715 'js2-parse-bit-and-expr)))
8718 (defun js2-parse-bit-and-expr ()
8719 (let ((pn (js2-parse-eq-expr)))
8720 (while (js2-match-token js2-BITAND)
8721 (setq pn (js2-make-binary js2-BITAND
8723 'js2-parse-eq-expr)))
8726 (defconst js2-parse-eq-ops
8727 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8729 (defun js2-parse-eq-expr ()
8730 (let ((pn (js2-parse-rel-expr))
8732 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8734 (setq pn (js2-make-binary tt
8736 'js2-parse-rel-expr)))
8739 (defconst js2-parse-rel-ops
8740 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8742 (defun js2-parse-rel-expr ()
8743 (let ((pn (js2-parse-shift-expr))
8747 (setq tt (js2-peek-token))
8749 ((and js2-in-for-init (= tt js2-IN))
8750 (setq continue nil))
8751 ((memq tt js2-parse-rel-ops)
8753 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8755 (setq continue nil))))
8758 (defconst js2-parse-shift-ops
8759 (list js2-LSH js2-URSH js2-RSH))
8761 (defun js2-parse-shift-expr ()
8762 (let ((pn (js2-parse-add-expr))
8766 (setq tt (js2-peek-token))
8767 (if (memq tt js2-parse-shift-ops)
8770 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8771 (setq continue nil)))
8774 (defun js2-parse-add-expr ()
8775 (let ((pn (js2-parse-mul-expr))
8779 (setq tt (js2-peek-token))
8780 (if (or (= tt js2-ADD) (= tt js2-SUB))
8783 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8784 (setq continue nil)))
8787 (defconst js2-parse-mul-ops
8788 (list js2-MUL js2-DIV js2-MOD))
8790 (defun js2-parse-mul-expr ()
8791 (let ((pn (js2-parse-unary-expr))
8795 (setq tt (js2-peek-token))
8796 (if (memq tt js2-parse-mul-ops)
8799 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8800 (setq continue nil)))
8803 (defsubst js2-make-unary (type parser &rest args)
8804 "Make a unary node of type TYPE.
8805 PARSER is either a node (for postfix operators) or a function to call
8806 to parse the operand (for prefix operators)."
8807 (let* ((pos js2-token-beg)
8808 (postfix (js2-node-p parser))
8811 (apply parser args)))
8814 (if postfix ; e.g. i++
8815 (setq pos (js2-node-pos expr)
8817 (setq end (js2-node-end expr)))
8818 (setq pn (make-js2-unary-node :type type
8822 (js2-node-add-children pn expr)
8825 (defconst js2-incrementable-node-types
8826 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8827 "Node types that can be the operand of a ++ or -- operator.")
8829 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8830 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8831 js2-incrementable-node-types)
8832 (js2-report-error (if (= tt js2-INC)
8835 nil beg (- end beg))))
8837 (defun js2-parse-unary-expr ()
8838 (let ((tt (js2-peek-token))
8841 ((or (= tt js2-VOID)
8846 (js2-make-unary tt 'js2-parse-unary-expr))
8849 ;; Convert to special POS token in decompiler and parse tree
8850 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8853 ;; Convert to special NEG token in decompiler and parse tree
8854 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8859 (setq beg js2-token-beg
8861 expr (js2-make-unary tt 'js2-parse-member-expr t))
8862 (js2-check-bad-inc-dec tt beg end expr)))
8865 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8868 (make-js2-error-node)) ; try to continue
8870 js2-compiler-xml-available)
8871 ;; XML stream encountered in expression.
8873 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8875 (setq pn (js2-parse-member-expr t)
8876 ;; Don't look across a newline boundary for a postfix incop.
8877 tt (js2-peek-token-or-eol))
8878 (when (or (= tt js2-INC) (= tt js2-DEC))
8881 pn (js2-make-unary tt expr))
8882 (js2-node-set-prop pn 'postfix t)
8883 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8886 (defun js2-parse-xml-initializer ()
8887 "Parse an E4X XML initializer.
8888 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8889 Then I'll postprocess the result, depending on whether we're in IDE
8890 mode or codegen mode, and generate the appropriate rewritten AST.
8891 IDE mode uses a rich AST that models the XML structure. Codegen mode
8892 just concatenates everything and makes a new XML or XMLList out of it."
8893 (let ((tt (js2-get-first-xml-token))
8901 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8902 (js2-report-error "msg.syntax"))
8903 (setq pn-xml (make-js2-xml-node))
8906 (setq first-token nil)
8907 (setq tt (js2-get-next-xml-token)))
8909 ;; js2-XML means we found a {expr} in the XML stream.
8910 ;; The js2-ts-string is the XML up to the left-curly.
8912 (push (make-js2-string-node :pos js2-token-beg
8913 :len (- js2-ts-cursor js2-token-beg))
8915 (js2-must-match js2-LC "msg.syntax")
8916 (setq expr-pos js2-ts-cursor
8917 expr (if (eq (js2-peek-token) js2-RC)
8918 (make-js2-empty-expr-node :pos expr-pos)
8920 (js2-must-match js2-RC "msg.syntax")
8921 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8922 :len (js2-node-len expr)
8924 (js2-node-add-children pn expr)
8926 ;; a js2-XMLEND token means we hit the final close-tag.
8928 (push (make-js2-string-node :pos js2-token-beg
8929 :len (- js2-ts-cursor js2-token-beg))
8931 (dolist (kid (nreverse kids))
8932 (js2-block-node-push pn-xml kid))
8933 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8934 (js2-node-pos pn-xml))
8937 (js2-report-error "msg.syntax")
8938 (setq continue nil))))
8942 (defun js2-parse-argument-list ()
8943 "Parse an argument list and return it as a lisp list of nodes.
8944 Returns the list in reverse order. Consumes the right-paren token."
8946 (unless (js2-match-token js2-RP)
8948 (if (= (js2-peek-token) js2-YIELD)
8949 (js2-report-error "msg.yield.parenthesized"))
8950 (push (js2-parse-assign-expr) result)
8952 (js2-match-token js2-COMMA))
8953 (js2-must-match js2-RP "msg.no.paren.arg")
8956 (defun js2-parse-member-expr (&optional allow-call-syntax)
8957 (let ((tt (js2-peek-token))
8967 (setq pn (js2-parse-primary-expr))
8968 ;; parse a 'new' expression
8970 (setq pos js2-token-beg
8972 target (js2-parse-member-expr)
8973 end (js2-node-end target)
8974 pn (make-js2-new-node :pos pos
8977 (js2-node-add-children pn target)
8978 (when (js2-match-token js2-LP)
8979 ;; Add the arguments to pn, if any are supplied.
8980 (setf beg pos ; start of "new" keyword
8982 args (nreverse (js2-parse-argument-list))
8983 (js2-new-node-args pn) args
8985 (js2-new-node-lp pn) (- pos beg)
8986 (js2-new-node-rp pn) (- end 1 beg))
8987 (apply #'js2-node-add-children pn args))
8988 (when (and js2-allow-rhino-new-expr-initializer
8989 (js2-match-token js2-LC))
8990 (setf init (js2-parse-object-literal)
8991 end (js2-node-end init)
8992 (js2-new-node-initializer pn) init)
8993 (js2-node-add-children pn init))
8994 (setf (js2-node-len pn) (- end beg))) ; end outer if
8995 (js2-parse-member-expr-tail allow-call-syntax pn)))
8997 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8998 "Parse a chain of property/array accesses or function calls.
8999 Includes parsing for E4X operators like `..' and `.@'.
9000 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9001 Returns an expression tree that includes PN, the parent node."
9002 (let ((beg (js2-node-pos pn))
9006 (setq tt (js2-peek-token))
9008 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9009 (setq pn (js2-parse-property-access tt pn)))
9010 ((= tt js2-DOTQUERY)
9011 (setq pn (js2-parse-dot-query pn)))
9013 (setq pn (js2-parse-element-get pn)))
9015 (if allow-call-syntax
9016 (setq pn (js2-parse-function-call pn))
9017 (setq continue nil)))
9019 (setq continue nil))))
9020 (if (>= js2-highlight-level 2)
9021 (js2-parse-highlight-member-expr-node pn))
9024 (defun js2-parse-dot-query (pn)
9025 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9026 Last token parsed must be `js2-DOTQUERY'."
9027 (let ((pos (js2-node-pos pn))
9033 (js2-set-requires-activation)
9034 (setq op-pos js2-token-beg
9035 expr (js2-parse-expr)
9036 end (js2-node-end expr)
9037 pn (make-js2-xml-dot-query-node :left pn
9041 (js2-node-add-children pn
9042 (js2-xml-dot-query-node-left pn)
9043 (js2-xml-dot-query-node-right pn))
9044 (if (js2-must-match js2-RP "msg.no.paren")
9045 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9047 (setf (js2-node-len pn) (- end pos))
9050 (defun js2-parse-element-get (pn)
9051 "Parse an element-get expression, e.g. foo[bar].
9052 Last token parsed must be `js2-RB'."
9053 (let ((lb js2-token-beg)
9054 (pos (js2-node-pos pn))
9058 (setq expr (js2-parse-expr))
9059 (if (js2-must-match js2-RB "msg.no.bracket.index")
9060 (setq rb js2-token-beg))
9061 (setq pn (make-js2-elem-get-node :target pn
9064 :lb (js2-relpos lb pos)
9065 :rb (js2-relpos rb pos)
9066 :len (- js2-token-end pos)))
9067 (js2-node-add-children pn
9068 (js2-elem-get-node-target pn)
9069 (js2-elem-get-node-element pn))
9072 (defun js2-parse-function-call (pn)
9074 (pos (js2-node-pos pn)))
9076 (setq pn (make-js2-call-node :pos pos
9078 :lp (- js2-token-beg pos)))
9079 (js2-node-add-children pn (js2-call-node-target pn))
9080 ;; Add the arguments to pn, if any are supplied.
9081 (setf args (nreverse (js2-parse-argument-list))
9082 (js2-call-node-rp pn) (- js2-token-beg pos)
9083 (js2-call-node-args pn) args)
9084 (apply #'js2-node-add-children pn args)
9085 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9088 (defun js2-parse-property-access (tt pn)
9089 "Parse a property access, XML descendants access, or XML attr access."
9090 (let ((member-type-flags 0)
9091 (dot-pos js2-token-beg)
9092 (dot-len (if (= tt js2-DOTDOT) 2 1))
9094 ref ; right side of . or .. operator
9097 (when (= tt js2-DOTDOT)
9099 (setq member-type-flags js2-descendants-flag))
9100 (if (not js2-compiler-xml-available)
9102 (js2-must-match-prop-name "msg.no.name.after.dot")
9103 (setq name (js2-create-name-node t js2-GETPROP)
9104 result (make-js2-prop-get-node :left pn
9107 :len (- js2-token-end
9109 (js2-node-add-children result pn name)
9111 ;; otherwise look for XML operators
9112 (setf result (if (= tt js2-DOT)
9113 (make-js2-prop-get-node)
9114 (make-js2-infix-node :type js2-DOTDOT))
9115 (js2-node-pos result) (js2-node-pos pn)
9116 (js2-infix-node-op-pos result) dot-pos
9117 (js2-infix-node-left result) pn ; do this after setting position
9118 tt (js2-next-token))
9120 ;; needed for generator.throw()
9122 (js2-save-name-token-data js2-token-beg "throw")
9123 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9124 ;; handles: name, ns::name, ns::*, ns::[expr]
9125 ((js2-valid-prop-name-token tt)
9126 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9127 ;; handles: *, *::name, *::*, *::[expr]
9129 (js2-save-name-token-data js2-token-beg "*")
9130 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9131 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9133 (setq result (js2-parse-attribute-access)))
9135 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9137 (setf (js2-node-len result) (- (js2-node-end ref)
9138 (js2-node-pos result))
9139 (js2-infix-node-right result) ref))
9140 (if (js2-infix-node-p result)
9141 (js2-node-add-children result
9142 (js2-infix-node-left result)
9143 (js2-infix-node-right result)))
9146 (defun js2-parse-attribute-access ()
9147 "Parse an E4X XML attribute expression.
9148 This includes expressions of the forms:
9150 @attr @ns::attr @ns::*
9152 @[expr] @*::[expr] @ns::[expr]
9154 Called if we peeked an '@' token."
9155 (let ((tt (js2-next-token))
9156 (at-pos js2-token-beg))
9158 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9159 ((js2-valid-prop-name-token tt)
9160 (js2-parse-property-name at-pos js2-ts-string 0))
9161 ;; handles: @*, @*::name, @*::*, @*::[expr]
9163 (js2-save-name-token-data js2-token-beg "*")
9164 (js2-parse-property-name js2-token-beg "*" 0))
9167 (js2-parse-xml-elem-ref at-pos))
9169 (js2-report-error "msg.no.name.after.xmlAttr")
9170 ;; Avoid cascaded errors that happen if we make an error node here.
9171 (js2-save-name-token-data js2-token-beg "")
9172 (js2-parse-property-name js2-token-beg "" 0)))))
9174 (defun js2-parse-property-name (at-pos s member-type-flags)
9175 "Check if :: follows name in which case it becomes qualified name.
9177 AT-POS is a natural number if we just read an '@' token, else nil.
9178 S is the name or string that was matched: an identifier, 'throw' or '*'.
9179 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9181 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9182 operator, or the name is followed by ::. For a plain name, returns a
9183 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9184 (let ((pos (or at-pos js2-token-beg))
9186 (name (js2-create-name-node t js2-current-token))
9192 (when (js2-match-token js2-COLONCOLON)
9194 colon-pos js2-token-beg
9195 tt (js2-next-token))
9197 ;; handles name::name
9198 ((js2-valid-prop-name-token tt)
9199 (setq name (js2-create-name-node)))
9202 (js2-save-name-token-data js2-token-beg "*")
9203 (setq name (js2-create-name-node)))
9204 ;; handles name::[expr]
9206 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9208 (js2-report-error "msg.no.name.after.coloncolon"))))
9209 (if (and (null ns) (zerop member-type-flags))
9213 (make-js2-xml-prop-ref-node :pos pos
9214 :len (- (js2-node-end name) pos)
9216 :colon-pos colon-pos
9218 (js2-node-add-children pn name))))))
9220 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9221 "Parse the [expr] portion of an xml element reference.
9222 For instance, @[expr], @*::[expr], or ns::[expr]."
9223 (let* ((lb js2-token-beg)
9224 (pos (or at-pos lb))
9226 (expr (js2-parse-expr))
9227 (end (js2-node-end expr))
9229 (if (js2-must-match js2-RB "msg.no.bracket.index")
9230 (setq rb js2-token-beg
9234 (make-js2-xml-elem-ref-node :pos pos
9236 :namespace namespace
9237 :colon-pos colon-pos
9240 :lb (js2-relpos lb pos)
9241 :rb (js2-relpos rb pos)))
9242 (js2-node-add-children pn namespace expr))))
9244 (defsubst js2-parse-primary-expr-lhs ()
9245 (let ((js2-is-in-lhs t))
9246 (js2-parse-primary-expr)))
9248 (defun js2-parse-primary-expr ()
9249 "Parses a literal (leaf) expression of some sort.
9250 Includes complex literals such as functions, object-literals,
9251 array-literals, array comprehensions and regular expressions."
9252 (let ((tt-flagged (js2-next-flagged-token))
9253 pn ; parent node (usually return value)
9255 px-pos ; paren-expr pos
9257 flags ; regexp flags
9259 (setq tt js2-current-token)
9261 ((= tt js2-FUNCTION)
9262 (js2-parse-function 'FUNCTION_EXPRESSION))
9264 (js2-parse-array-literal))
9266 (js2-parse-object-literal))
9268 (js2-parse-let js2-token-beg))
9270 (setq px-pos js2-token-beg
9271 expr (js2-parse-expr))
9272 (js2-must-match js2-RP "msg.no.paren")
9273 (setq pn (make-js2-paren-node :pos px-pos
9275 :len (- js2-token-end px-pos)))
9276 (js2-node-add-children pn (js2-paren-node-expr pn))
9280 (js2-parse-attribute-access))
9282 (js2-parse-name tt-flagged tt))
9284 (make-js2-number-node))
9287 (make-js2-string-node)
9288 (js2-record-face 'font-lock-string-face)))
9289 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9290 ;; Got / or /= which in this context means a regexp literal
9291 (setq px-pos js2-token-beg)
9292 (js2-read-regexp tt)
9293 (setq flags js2-ts-regexp-flags
9294 js2-ts-regexp-flags nil)
9296 (make-js2-regexp-node :pos px-pos
9297 :len (- js2-ts-cursor px-pos)
9298 :value js2-ts-string
9300 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9301 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9302 ((or (= tt js2-NULL)
9306 (make-js2-keyword-node :type tt))
9307 ((= tt js2-RESERVED)
9308 (js2-report-error "msg.reserved.id")
9309 (make-js2-name-node))
9311 ;; the scanner or one of its subroutines reported the error.
9312 (make-js2-error-node))
9314 (setq px-pos (point-at-bol)
9315 len (- js2-ts-cursor px-pos))
9316 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9317 (make-js2-error-node :pos px-pos :len len))
9319 (js2-report-error "msg.syntax")
9320 (make-js2-error-node)))))
9322 (defun js2-parse-name (tt-flagged tt)
9323 (let ((name js2-ts-string)
9324 (name-pos js2-token-beg)
9326 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9327 (= (js2-peek-token) js2-COLON))
9329 ;; Do not consume colon, it is used as unwind indicator
9330 ;; to return to statementHelper.
9331 (make-js2-label-node :pos name-pos
9332 :len (- js2-token-end name-pos)
9334 (js2-set-face name-pos
9336 'font-lock-variable-name-face 'record))
9337 ;; Otherwise not a label, just a name. Unfortunately peeking
9338 ;; the next token to check for a colon has biffed js2-token-beg
9339 ;; and js2-token-end. We store the name's bounds in buffer vars
9340 ;; and `js2-create-name-node' uses them.
9341 (js2-save-name-token-data name-pos name)
9342 (setq node (if js2-compiler-xml-available
9343 (js2-parse-property-name nil name 0)
9344 (js2-create-name-node 'check-activation)))
9345 (if js2-highlight-external-variables
9346 (js2-record-name-node node))
9349 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9350 (js2-add-strict-warning
9352 ;; back up from comma to beginning of line or array/objlit
9354 (js2-node-pos (car elems))
9357 (goto-char comma-pos)
9358 (back-to-indentation)
9362 (defun js2-parse-array-literal ()
9363 (let ((pos js2-token-beg)
9365 (after-lb-or-comma t)
9371 (unless js2-is-in-lhs
9372 (js2-push-scope (make-js2-scope))) ; for array comp
9374 (setq tt (js2-peek-token))
9379 (setq after-comma js2-token-end)
9380 (if (not after-lb-or-comma)
9381 (setq after-lb-or-comma t)
9385 (= tt js2-EOF)) ; prevent infinite loop
9387 (js2-report-error "msg.no.bracket.arg" nil pos)
9388 (js2-consume-token))
9391 pn (make-js2-array-node :pos pos
9392 :len (- js2-ts-cursor pos)
9393 :elems (nreverse elems)))
9394 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9396 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9397 pos elems after-comma)))
9398 ;; destructuring binding
9400 (push (if (or (= tt js2-LC)
9403 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9404 (js2-parse-primary-expr-lhs)
9407 (js2-report-error "msg.bad.var")
9408 (make-js2-error-node))
9410 (setq after-lb-or-comma nil
9413 ((and (>= js2-language-version 170)
9414 (= tt js2-FOR) ; check for array comprehension
9415 (not after-lb-or-comma) ; "for" can't follow a comma
9416 elems ; must have at least 1 element
9417 (not (cdr elems))) ; but no 2nd element
9419 pn (js2-parse-array-comprehension (car elems) pos)))
9423 (unless after-lb-or-comma
9424 (js2-report-error "msg.no.bracket.arg"))
9425 (push (js2-parse-assign-expr) elems)
9426 (setq after-lb-or-comma nil
9428 (unless js2-is-in-lhs
9432 (defun js2-parse-array-comprehension (expr pos)
9433 "Parse a JavaScript 1.7 Array Comprehension.
9434 EXPR is the first expression after the opening left-bracket.
9435 POS is the beginning of the LB token preceding EXPR.
9436 We should have just parsed the 'for' keyword before calling this function."
9444 (while (= (js2-peek-token) js2-FOR)
9445 (let ((prev (car loops))) ; rearrange scope chain
9446 (push (setq loop (js2-parse-array-comp-loop)) loops)
9447 (if prev ; each loop is parent scope to the next one
9448 (setf (js2-scope-parent-scope loop) prev)
9449 ; first loop takes expr scope's parent
9450 (setf (js2-scope-parent-scope (setq first loop))
9451 (js2-scope-parent-scope js2-current-scope)))))
9452 ;; set expr scope's parent to the last loop
9453 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9454 (when (= (js2-peek-token) js2-IF)
9456 (setq if-pos (- js2-token-beg pos) ; relative
9457 filter (js2-parse-condition)))
9458 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9459 (setq result (make-js2-array-comp-node :pos pos
9460 :len (- js2-ts-cursor pos)
9462 :loops (nreverse loops)
9463 :filter (car filter)
9464 :lp (js2-relpos (second filter) pos)
9465 :rp (js2-relpos (third filter) pos)
9467 (apply #'js2-node-add-children result expr (car filter)
9468 (js2-array-comp-node-loops result))
9469 (setq js2-current-scope first) ; pop to the first loop
9472 (defun js2-parse-array-comp-loop ()
9473 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9474 Last token peeked should be the initial FOR."
9475 (let ((pos js2-token-beg)
9476 (pn (make-js2-array-comp-loop-node))
9485 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9489 (when (js2-match-token js2-NAME)
9490 (if (string= js2-ts-string "each")
9493 each-pos (- js2-token-beg pos)) ; relative
9494 (js2-record-face 'font-lock-keyword-face))
9495 (js2-report-error "msg.no.paren.for")))
9496 (if (js2-must-match js2-LP "msg.no.paren.for")
9497 (setq lp (- js2-token-beg pos)))
9498 (setq tt (js2-peek-token))
9502 ;; handle destructuring assignment
9503 (setq iter (js2-parse-primary-expr-lhs))
9504 (js2-define-destruct-symbols iter js2-LET
9505 'font-lock-variable-name-face t))
9506 ((js2-valid-prop-name-token tt)
9508 (setq iter (js2-create-name-node)))
9510 (js2-report-error "msg.bad.var")))
9511 ;; Define as a let since we want the scope of the variable to
9512 ;; be restricted to the array comprehension
9513 (if (js2-name-node-p iter)
9514 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9515 (if (js2-must-match js2-IN "msg.in.after.for.name")
9516 (setq in-pos (- js2-token-beg pos)))
9517 (setq obj (js2-parse-expr))
9518 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9519 (setq rp (- js2-token-beg pos)))
9520 (setf (js2-node-pos pn) pos
9521 (js2-node-len pn) (- js2-ts-cursor pos)
9522 (js2-array-comp-loop-node-iterator pn) iter
9523 (js2-array-comp-loop-node-object pn) obj
9524 (js2-array-comp-loop-node-in-pos pn) in-pos
9525 (js2-array-comp-loop-node-each-pos pn) each-pos
9526 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9527 (js2-array-comp-loop-node-lp pn) lp
9528 (js2-array-comp-loop-node-rp pn) rp)
9529 (js2-node-add-children pn iter obj))
9533 (defun js2-parse-object-literal ()
9534 (let ((pos js2-token-beg)
9541 (setq tt (js2-peek-token))
9543 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9544 ((or (js2-valid-prop-name-token tt)
9546 (setq after-comma nil
9547 result (js2-parse-named-prop tt))
9548 (if (and (null result)
9549 (not js2-recover-from-parse-errors))
9551 (push result elems)))
9552 ;; {12: x} or {10.7: x}
9555 (setq after-comma nil)
9556 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9561 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9562 pos elems after-comma)))
9564 (js2-report-error "msg.bad.prop")
9565 (unless js2-recover-from-parse-errors
9566 (setq continue nil)))) ; end switch
9567 (if (js2-match-token js2-COMMA)
9568 (setq after-comma js2-token-end)
9569 (setq continue nil))) ; end loop
9570 (js2-must-match js2-RC "msg.no.brace.prop")
9571 (setq result (make-js2-object-node :pos pos
9572 :len (- js2-ts-cursor pos)
9573 :elems (nreverse elems)))
9574 (apply #'js2-node-add-children result (js2-object-node-elems result))
9577 (defun js2-parse-named-prop (tt)
9578 "Parse a name, string, or getter/setter object property.
9579 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9581 (let ((string-prop (and (= tt js2-STRING)
9582 (make-js2-string-node)))
9584 (ppos js2-token-beg)
9585 (pend js2-token-end)
9586 (name (js2-create-name-node))
9587 (prop js2-ts-string))
9589 ;; getter/setter prop
9590 ((and (= tt js2-NAME)
9591 (= (js2-peek-token) js2-NAME)
9592 (or (string= prop "get")
9593 (string= prop "set")))
9595 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9596 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9597 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9598 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9599 ;; abbreviated destructuring bind e.g., {a, b} = c;
9600 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9601 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9602 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9603 ;; assignment but it's difficult because it requires looking ahead of expression.
9606 (let ((ctk (js2-peek-token)))
9607 (or (= ctk js2-COMMA)
9609 (js2-valid-prop-name-token ctk))))
9614 (setq expr (js2-parse-plain-property (or string-prop name)))
9615 (js2-set-face ppos pend
9616 (if (js2-function-node-p
9617 (js2-object-prop-node-right expr))
9618 'font-lock-function-name-face
9619 'font-lock-variable-name-face)
9622 (defun js2-parse-plain-property (prop)
9623 "Parse a non-getter/setter property in an object literal.
9624 PROP is the node representing the property: a number, name or string."
9625 (js2-must-match js2-COLON "msg.no.colon.prop")
9626 (let* ((pos (js2-node-pos prop))
9627 (colon (- js2-token-beg pos))
9628 (expr (js2-parse-assign-expr))
9629 (result (make-js2-object-prop-node
9631 ;; don't include last consumed token in length
9632 :len (- (+ (js2-node-pos expr)
9633 (js2-node-len expr))
9638 (js2-node-add-children result prop expr)
9641 (defun js2-parse-getter-setter-prop (pos prop get-p)
9642 "Parse getter or setter property in an object literal.
9643 JavaScript syntax is:
9645 { get foo() {...}, set foo(x) {...} }
9647 and expression closure style is also supported
9649 { get foo() x, set foo(x) _x = x }
9651 POS is the start position of the `get' or `set' keyword.
9652 PROP is the `js2-name-node' representing the property name.
9653 GET-P is non-nil if the keyword was `get'."
9654 (let ((type (if get-p js2-GET js2-SET))
9657 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9658 ;; it has to be an anonymous function, as we already parsed the name
9659 (if (/= (js2-node-type fn) js2-FUNCTION)
9660 (js2-report-error "msg.bad.prop")
9661 (if (plusp (length (js2-function-name fn)))
9662 (js2-report-error "msg.bad.prop")))
9663 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9664 (setq end (js2-node-end fn)
9665 result (make-js2-getter-setter-node :type type
9670 (js2-node-add-children result prop fn)
9673 (defun js2-create-name-node (&optional check-activation-p token)
9674 "Create a name node using the token info from last scanned name.
9675 In some cases we need to either synthesize a name node, or we lost
9676 the name token information by peeking. If the TOKEN parameter is
9677 not `js2-NAME', then we use the token info saved in instance vars."
9678 (let ((beg js2-token-beg)
9681 (when (/= js2-current-token js2-NAME)
9682 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9683 s js2-prev-name-token-string
9684 js2-prev-name-token-start nil
9685 js2-prev-name-token-string nil))
9686 (setq name (make-js2-name-node :pos beg
9689 (if check-activation-p
9690 (js2-check-activation-name s (or token js2-NAME)))
9693 ;;; Indentation support
9695 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9696 ;; Karl cleverly deduces that the desired indentation level is often a
9697 ;; function of paren/bracket/brace nesting depth, which can be determined
9698 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9699 ;; then does some equally clever checks to see if we're in the context of a
9700 ;; substatement of a possibly braceless statement keyword such as if, while,
9701 ;; or finally. This approach yields pretty good results.
9703 ;; The indenter is often "wrong", however, and needs to be overridden.
9704 ;; The right long-term solution is probably to emulate (or integrate
9705 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9706 ;; parse tree from `js2-parse' is present, which is not true at the
9707 ;; moment the user is typing, computing indentation is still thousands
9708 ;; of lines of code to handle every possible syntactic edge case.
9710 ;; In the meantime, the compromise solution is that we offer a "bounce
9711 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9712 ;; current line indent among various likely guess points. This approach
9713 ;; is far from perfect, but should at least make it slightly easier to
9714 ;; move the line towards its desired indentation when manually
9715 ;; overriding Karl's heuristic nesting guesser.
9717 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9718 ;; extensions such as `let' and Array comprehensions. Major kudos to
9719 ;; Karl for coming up with the initial approach, which packs a lot of
9720 ;; punch for so little code.
9722 (defconst js-possibly-braceless-keyword-re
9724 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9726 "Regular expression matching keywords that are optionally
9727 followed by an opening brace.")
9729 (defconst js-possibly-braceless-keywords-re
9730 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9731 "Regular expression which matches the keywords which are consist of more than 2 words
9732 like 'if else' and 'for each', and optionally followed by an opening brace.")
9734 (defconst js-indent-operator-re
9735 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9736 (regexp-opt '("in" "instanceof") 'words))
9737 "Regular expression matching operators that affect indentation
9738 of continued expressions.")
9740 ;; This function has horrible results if you're typing an array
9741 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9742 ;; in conjunction with electric-indent, so just disabling it.
9743 (defsubst js2-code-at-bol-p ()
9744 "Return t if the first character on line is non-whitespace."
9747 (defun js2-insert-and-indent (key)
9748 "Run command bound to key and indent current line. Runs the command
9749 bound to KEY in the global keymap and indents the current line."
9750 (interactive (list (this-command-keys)))
9751 (let ((cmd (lookup-key (current-global-map) key)))
9753 (call-interactively cmd)))
9754 ;; don't do the electric keys inside comments or strings,
9755 ;; and don't do bounce-indent with them.
9756 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9757 (js2-bounce-indent-p (js2-code-at-bol-p)))
9758 (unless (or (nth 3 parse-state)
9759 (nth 4 parse-state))
9760 (indent-according-to-mode))))
9762 (defun js-re-search-forward-inner (regexp &optional bound count)
9763 "Auxiliary function for `js-re-search-forward'."
9765 (saved-point (point-min)))
9767 (re-search-forward regexp bound)
9768 (setq parse (parse-partial-sexp saved-point (point)))
9769 (cond ((nth 3 parse)
9771 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9772 (save-excursion (end-of-line) (point)) t))
9776 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9777 (re-search-forward "\\*/"))
9779 (setq count (1- count))))
9780 (setq saved-point (point))))
9783 (defun js-re-search-forward (regexp &optional bound noerror count)
9784 "Search forward but ignore strings and comments. Invokes
9785 `re-search-forward' but treats the buffer as if strings and
9786 comments have been removed."
9787 (let ((saved-point (point))
9790 '(js-re-search-forward-inner regexp bound 1))
9792 '(js-re-search-backward-inner regexp bound (- count)))
9794 '(js-re-search-forward-inner regexp bound count)))))
9798 (goto-char saved-point)
9800 (error (error-message-string err)))))))
9802 (defun js-re-search-backward-inner (regexp &optional bound count)
9803 "Auxiliary function for `js-re-search-backward'."
9805 (saved-point (point-min)))
9807 (re-search-backward regexp bound)
9808 (setq parse (parse-partial-sexp saved-point (point)))
9809 (cond ((nth 3 parse)
9811 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9812 (save-excursion (beginning-of-line) (point)) t))
9814 (goto-char (nth 8 parse)))
9816 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9817 (re-search-backward "/\\*"))
9819 (setq count (1- count))))))
9822 (defun js-re-search-backward (regexp &optional bound noerror count)
9823 "Search backward but ignore strings and comments. Invokes
9824 `re-search-backward' but treats the buffer as if strings and
9825 comments have been removed."
9826 (let ((saved-point (point))
9829 '(js-re-search-backward-inner regexp bound 1))
9831 '(js-re-search-forward-inner regexp bound (- count)))
9833 '(js-re-search-backward-inner regexp bound count)))))
9837 (goto-char saved-point)
9839 (error (error-message-string err)))))))
9841 (defun js-looking-at-operator-p ()
9842 "Return non-nil if text after point is an operator (that is not
9845 (and (looking-at js-indent-operator-re)
9846 (or (not (looking-at ":"))
9848 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9849 (looking-at "?")))))))
9851 (defun js-continued-expression-p ()
9852 "Returns non-nil if the current line continues an expression."
9854 (back-to-indentation)
9855 (or (js-looking-at-operator-p)
9857 (and (js-re-search-backward "\n" nil t)
9859 (skip-chars-backward " \t")
9861 (and (js-looking-at-operator-p)
9862 (and (progn (backward-char)
9863 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9865 (defun js-end-of-do-while-loop-p ()
9866 "Returns non-nil if word after point is `while' of a do-while
9867 statement, else returns nil. A braceless do-while statement
9868 spanning several lines requires that the start of the loop is
9869 indented to the same column as the current line."
9873 (when (looking-at "\\s-*\\<while\\>")
9875 (skip-chars-backward "[ \t\n]*}")
9876 (looking-at "[ \t\n]*}"))
9878 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9879 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9880 (or (looking-at "\\<do\\>")
9881 (let ((saved-indent (current-indentation)))
9882 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9883 (/= (current-indentation) saved-indent)))
9884 (and (looking-at "[ \t]*\\<do\\>")
9885 (not (js-re-search-forward
9886 "\\<while\\>" (point-at-eol) t))
9887 (= (current-indentation) saved-indent)))))))))
9889 (defun js-get-multiline-declaration-offset ()
9890 "Returns offset (> 0) if the current line is part of
9891 multi-line variable declaration like below example, and
9892 returns 0 otherwise.
9899 (let* ((node (js2-node-at-point))
9900 (pnode (and node (js2-node-parent node)))
9901 (pnode-type (and pnode (js2-node-type pnode))))
9903 (= js2-NAME (js2-node-type node))
9905 (= js2-VAR pnode-type)
9906 (= js2-LET pnode-type)
9907 (= js2-CONST pnode-type)))
9908 (if (= js2-CONST pnode-type)
9913 (defun js-ctrl-statement-indentation ()
9914 "Returns the proper indentation of the current line if it
9915 starts the body of a control statement without braces, else
9917 (let (forward-sexp-function) ; temporarily unbind it
9919 (back-to-indentation)
9920 (when (save-excursion
9921 (and (not (js2-same-line (point-min)))
9922 (not (looking-at "{"))
9923 (js-re-search-backward "[[:graph:]]" nil t)
9924 (not (looking-at "[{([]"))
9927 ;; scan-sexps sometimes throws an error
9928 (ignore-errors (backward-sexp))
9929 (when (looking-at "(") (backward-word 1))
9930 (and (save-excursion
9931 (skip-chars-backward " \t}" (point-at-bol))
9933 (and (backward-word 1)
9934 (skip-chars-backward " \t}" (point-at-bol))
9936 (looking-at js-possibly-braceless-keywords-re))))
9937 (looking-at js-possibly-braceless-keyword-re)
9938 (not (js-end-of-do-while-loop-p))))))
9940 (goto-char (match-beginning 0))
9941 (+ (current-indentation) js2-basic-offset))))))
9943 (defun js2-indent-in-array-comp (parse-status)
9944 "Return non-nil if we think we're in an array comprehension.
9945 In particular, return the buffer position of the first `for' kwd."
9946 (let ((end (point)))
9947 (when (nth 1 parse-status)
9949 (goto-char (nth 1 parse-status))
9950 (when (looking-at "\\[")
9953 (if (looking-at "[[{]")
9954 (let (forward-sexp-function) ; use lisp version
9955 (forward-sexp) ; skip destructuring form
9957 (if (and (/= (char-after) ?,) ; regular array
9959 (match-beginning 0)))
9960 ;; to skip arbitrary expressions we need the parser,
9961 ;; so we'll just guess at it.
9962 (if (re-search-forward "[^,]* \\(for\\) " end t)
9963 (match-beginning 1))))))))
9965 (defun js2-array-comp-indentation (parse-status for-kwd)
9966 (if (js2-same-line for-kwd)
9967 ;; first continuation line
9969 (goto-char (nth 1 parse-status))
9971 (skip-chars-forward " \t")
9977 (defun js-proper-indentation (parse-status)
9978 "Return the proper indentation for the current line."
9980 (back-to-indentation)
9981 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9982 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9983 (continued-expr-p (js-continued-expression-p))
9984 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9985 (js-get-multiline-declaration-offset))
9987 (bracket (nth 1 parse-status))
9990 ;; indent array comprehension continuation lines specially
9992 (not (js2-same-line bracket))
9993 (setq beg (js2-indent-in-array-comp parse-status))
9994 (>= (point) (save-excursion
9996 (point-at-bol)))) ; at or after first loop?
9997 (js2-array-comp-indentation parse-status beg))
10002 (goto-char bracket)
10004 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10005 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10006 (when (save-excursion (skip-chars-backward " \t)")
10010 (not js2-consistent-level-indent-inner-bracket-p))
10011 (progn (goto-char (1+ (nth 1 p)))
10012 (skip-chars-forward " \t"))
10013 (back-to-indentation))
10014 (cond (same-indent-p
10017 (+ (current-column) (* 2 js2-basic-offset)))
10018 ((> multiline-declaration-offset 0)
10019 (+ (current-column) js2-basic-offset multiline-declaration-offset))
10021 (+ (current-column) js2-basic-offset)))))
10023 (unless same-indent-p
10025 (skip-chars-forward " \t"))
10026 (current-column))))
10028 (continued-expr-p js2-basic-offset)
10030 ((> multiline-declaration-offset 0)
10031 (+ multiline-declaration-offset))
10035 (defun js2-lineup-comment (parse-status)
10036 "Indent a multi-line block comment continuation line."
10037 (let* ((beg (nth 8 parse-status))
10038 (first-line (js2-same-line beg))
10039 (offset (save-excursion
10041 (if (looking-at "/\\*")
10042 (+ 1 (current-column))
10045 (indent-line-to offset))))
10047 (defun js2-backward-sws ()
10048 "Move backward through whitespace and comments."
10050 (while (forward-comment -1)))
10052 (defun js2-forward-sws ()
10053 "Move forward through whitespace and comments."
10055 (while (forward-comment 1)))
10057 (defsubst js2-current-indent (&optional pos)
10058 "Return column of indentation on current line.
10059 If POS is non-nil, go to that point and return indentation for that line."
10063 (back-to-indentation)
10066 (defsubst js2-arglist-close ()
10067 "Return non-nil if we're on a line beginning with a close-paren/brace."
10070 (goto-char (point-at-bol))
10072 (looking-at "[])}]"))))
10074 (defsubst js2-indent-looks-like-label-p ()
10075 (goto-char (point-at-bol))
10077 (looking-at (concat js2-mode-identifier-re ":")))
10079 (defun js2-indent-in-objlit-p (parse-status)
10080 "Return non-nil if this looks like an object-literal entry."
10081 (let ((start (nth 1 parse-status)))
10085 (and (zerop (forward-line -1))
10086 (not (< (point) start)) ; crossed a {} boundary
10087 (js2-indent-looks-like-label-p)))
10089 (js2-indent-looks-like-label-p)))))
10091 ;; if prev line looks like foobar({ then we're passing an object
10092 ;; literal to a function call, and people pretty much always want to
10093 ;; de-dent back to the previous line, so move the 'basic-offset'
10094 ;; position to the front.
10095 (defsubst js2-indent-objlit-arg-p (parse-status)
10097 (back-to-indentation)
10099 (and (eq (1- (point)) (nth 1 parse-status))
10100 (eq (char-before) ?{)
10103 (skip-chars-backward " \t")
10104 (eq (char-before) ?\()))))
10106 (defsubst js2-indent-case-block-p ()
10108 (back-to-indentation)
10110 (goto-char (point-at-bol))
10111 (skip-chars-forward " \t")
10113 (looking-at "case\\s-.+:"))))
10115 (defsubst js2-syntax-bol ()
10116 "Return the point at the first non-whitespace char on the line.
10117 Returns `point-at-bol' if the line is empty."
10119 (beginning-of-line)
10120 (skip-chars-forward " \t")
10123 (defun js2-bounce-indent (normal-col parse-status)
10124 "Cycle among alternate computed indentation positions.
10125 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10126 of the buffer to the current point. NORMAL-COL is the indentation
10127 column computed by the heuristic guesser based on current paren,
10128 bracket, brace and statement nesting."
10129 (let ((cur-indent (js2-current-indent))
10130 (old-buffer-undo-list buffer-undo-list)
10131 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10132 (current-line (save-excursion
10133 (forward-line 0) ; move to bol
10134 (1+ (count-lines (point-min) (point)))))
10143 ;; temporarily don't record undo info, if user requested this
10144 (if js2-mode-indent-inhibit-undo
10145 (setq buffer-undo-list t))
10148 ;; first likely point: indent from beginning of previous code line
10149 (push (setq basic-offset
10151 (back-to-indentation)
10153 (back-to-indentation)
10154 (setq prev-line-col (current-column)))
10158 ;; (first + epsilon) likely point: indent 2x from beginning of
10159 ;; previous code line. Some companies like this approach. Ahem.
10160 ;; Seriously, though -- 4-space indent for expression continuation
10161 ;; lines isn't a bad idea. We should eventually implement it
10163 (push (setq basic-offset
10165 (back-to-indentation)
10167 (back-to-indentation)
10168 (setq prev-line-col (current-column)))
10169 (* 2 js2-basic-offset)))
10172 ;; second likely point: indent from assign-expr RHS. This
10173 ;; is just a crude guess based on finding " = " on the previous
10174 ;; line containing actual code.
10175 (setq pos (save-excursion
10178 (goto-char (point-at-bol))
10179 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10181 (goto-char (match-end 1))
10182 (skip-chars-forward " \t\r\n")
10183 (current-column)))))
10185 (incf pos js2-basic-offset)
10186 (unless (member pos positions)
10187 (push pos positions)))
10189 ;; third likely point: same indent as previous line of code.
10190 ;; Make it the first likely point if we're not on an
10191 ;; arglist-close line and previous line ends in a comma, or
10192 ;; both this line and prev line look like object-literal
10194 (setq pos (save-excursion
10195 (goto-char (point-at-bol))
10197 (back-to-indentation)
10200 ;; while we're here, look for trailing comma
10201 (if (save-excursion
10202 (goto-char (point-at-eol))
10204 (eq (char-before) ?,))
10205 (setq arglist-cont (1- (point)))))))
10207 (if (and (or arglist-cont
10208 (js2-indent-in-objlit-p parse-status))
10209 (not (js2-arglist-close)))
10210 (setq same-indent pos))
10211 (unless (member pos positions)
10212 (push pos positions)))
10214 ;; fourth likely point: first preceding code with less indentation
10215 ;; than the immediately preceding code line.
10216 (setq pos (save-excursion
10218 (back-to-indentation)
10219 (setq anchor (current-column))
10220 (while (and (zerop (forward-line -1))
10222 (back-to-indentation)
10225 (setq pos (current-column))))
10226 (unless (member pos positions)
10227 (push pos positions))
10229 ;; put nesting-heuristic position first in list, sort rest
10230 (setq positions (nreverse (sort positions '<)))
10231 (setq positions (cons normal-col (delete normal-col positions)))
10233 ;; comma-list continuation lines: prev line indent takes precedence
10237 (sort (delete same-indent positions) '<))))
10239 ;; common special cases where we want to indent in from previous line
10240 (if (or (js2-indent-case-block-p)
10241 (js2-indent-objlit-arg-p parse-status))
10244 (delete basic-offset positions))))
10246 ;; record whether we're already sitting on one of the alternatives
10247 (setq pos (member cur-indent positions))
10249 ;; case 0: we're one one of the alternatives and this is the
10250 ;; first time they've pressed TAB on this line (best-guess).
10251 ((and js2-mode-indent-ignore-first-tab
10253 ;; first time pressing TAB on this line?
10254 (not (eq js2-mode-last-indented-line current-line)))
10256 (setq computed-pos nil))
10257 ;; case 1: only one computed position => use it
10258 ((null (cdr positions))
10259 (setq computed-pos 0))
10260 ;; case 2: not on any of the computed spots => use main spot
10262 (setq computed-pos 0))
10263 ;; case 3: on last position: cycle to first position
10265 (setq computed-pos 0))
10266 ;; case 4: on intermediate position: cycle to next position
10268 (setq computed-pos (js2-position (second pos) positions))))
10270 ;; see if any hooks want to indent; otherwise we do it
10271 (loop with result = nil
10272 for hook in js2-indent-hook
10273 while (null result)
10275 (setq result (funcall hook positions computed-pos))
10277 (unless (or result (null computed-pos))
10278 (indent-line-to (nth computed-pos positions)))))
10281 (if js2-mode-indent-inhibit-undo
10282 (setq buffer-undo-list old-buffer-undo-list))
10283 ;; see commentary for `js2-mode-last-indented-line'
10284 (setq js2-mode-last-indented-line current-line))))
10286 (defsubst js2-1-line-comment-continuation-p ()
10287 "Return t if we're in a 1-line comment continuation.
10288 If so, we don't ever want to use bounce-indent."
10293 (looking-at "\\s-*//"))
10297 (when (looking-at "\\s-*$")
10300 (looking-at "\\s-*//"))))))
10302 (defun js2-indent-line ()
10303 "Indent the current line as JavaScript source text."
10305 (when js2-use-ast-for-indentation-p
10312 ;; don't whine about errors/warnings when we're indenting.
10313 ;; This has to be set before calling parse-partial-sexp below.
10314 (inhibit-point-motion-hooks t))
10315 (setq parse-status (save-excursion
10316 (parse-partial-sexp (point-min)
10318 offset (- (point) (save-excursion
10319 (back-to-indentation)
10320 (setq current-indent (current-column))
10322 (js2-with-underscore-as-word-syntax
10323 (if (nth 4 parse-status)
10324 (js2-lineup-comment parse-status)
10325 (setq indent-col (js-proper-indentation parse-status))
10326 ;; see comments below about js2-mode-last-indented-line
10329 ;; bounce-indenting is disabled during electric-key indent.
10330 ;; It doesn't work well on first line of buffer.
10331 ((and js2-bounce-indent-p
10332 (not (js2-same-line (point-min)))
10333 (not (js2-1-line-comment-continuation-p)))
10334 (js2-bounce-indent indent-col parse-status)
10336 ;; just indent to the guesser's likely spot
10337 ((/= current-indent indent-col)
10338 (indent-line-to indent-col)
10340 (when (and moved (plusp offset))
10341 (forward-char offset)))))))
10343 (defun js2-indent-region (start end)
10344 "Indent the region, but don't use bounce indenting."
10345 (let ((js2-bounce-indent-p nil)
10346 (indent-region-function nil))
10347 (indent-region start end nil))) ; nil for byte-compiler
10349 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10353 "Major mode for editing JavaScript code."
10355 (kill-all-local-variables)
10356 (set-syntax-table js2-mode-syntax-table)
10357 (use-local-map js2-mode-map)
10358 (make-local-variable 'comment-start)
10359 (make-local-variable 'comment-end)
10360 (make-local-variable 'comment-start-skip)
10361 (setq major-mode 'js2-mode
10362 mode-name "JavaScript-IDE"
10363 comment-start "//" ; used by comment-region; don't change it
10365 (setq local-abbrev-table js2-mode-abbrev-table)
10366 (set (make-local-variable 'max-lisp-eval-depth)
10367 (max max-lisp-eval-depth 3000))
10368 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10369 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10371 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10372 ;; on most platforms other than the one I originally wrote it on. So it's
10373 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10374 ;; with our binding of the RET key inside comments: short lines stay short.
10375 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10377 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10378 (set (make-local-variable 'next-error-function) #'js2-next-error)
10379 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10380 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10381 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10382 ;; for characters inside regexp literals.
10383 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10384 ;; this is necessary to make `show-paren-function' work properly
10385 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10386 ;; needed for M-x rgrep, among other things
10387 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10389 ;; some variables needed by cc-engine for paragraph-fill, etc.
10390 (setq c-buffer-is-cc-mode t
10391 c-comment-prefix-regexp js2-comment-prefix-regexp
10392 c-comment-start-regexp "/[*/]\\|\\s|"
10393 c-paragraph-start js2-paragraph-start
10394 c-paragraph-separate "$"
10395 comment-start-skip js2-comment-start-skip
10396 c-syntactic-ws-start js2-syntactic-ws-start
10397 c-syntactic-ws-end js2-syntactic-ws-end
10398 c-syntactic-eol js2-syntactic-eol)
10400 (setq js2-default-externs
10401 (append js2-ecma-262-externs
10402 (if js2-include-browser-externs
10403 js2-browser-externs)
10404 (if js2-include-gears-externs
10406 (if js2-include-rhino-externs
10407 js2-rhino-externs)))
10409 ;; We do our own syntax highlighting based on the parse tree.
10410 ;; However, we want minor modes that add keywords to highlight properly
10411 ;; (examples: doxymacs, column-marker). We do this by not letting
10412 ;; font-lock unfontify anything, and telling it to fontify after we
10413 ;; re-parse and re-highlight the buffer. (We currently don't do any
10414 ;; work with regions other than the whole buffer.)
10415 (dolist (var '(font-lock-unfontify-buffer-function
10416 font-lock-unfontify-region-function))
10417 (set (make-local-variable var) (lambda (&rest args) t)))
10419 ;; Don't let font-lock do syntactic (string/comment) fontification.
10420 (set (make-local-variable #'font-lock-syntactic-face-function)
10421 (lambda (state) nil))
10423 ;; Experiment: make reparse-delay longer for longer files.
10424 (if (plusp js2-dynamic-idle-timer-adjust)
10425 (setq js2-idle-timer-delay
10426 (* js2-idle-timer-delay
10427 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10429 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10430 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10431 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10432 (imenu-add-to-menubar (concat "IM-" mode-name))
10433 (when js2-mirror-mode
10434 (js2-enter-mirror-mode))
10435 (add-to-invisibility-spec '(js2-outline . t))
10436 (set (make-local-variable 'line-move-ignore-invisible) t)
10437 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10438 (setq js2-mode-functions-hidden nil
10439 js2-mode-comments-hidden nil
10440 js2-mode-buffer-dirty-p t
10441 js2-mode-parsing nil)
10443 (run-hooks 'js2-mode-hook))
10445 (defun js2-mode-exit ()
10446 "Exit `js2-mode' and clean up."
10448 (when js2-mode-node-overlay
10449 (delete-overlay js2-mode-node-overlay)
10450 (setq js2-mode-node-overlay nil))
10451 (js2-remove-overlays)
10452 (setq js2-mode-ast nil)
10453 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10454 (remove-from-invisibility-spec '(js2-outline . t))
10455 (js2-mode-show-all)
10456 (js2-with-unmodifying-text-property-changes
10457 (js2-clear-face (point-min) (point-max))))
10459 (defun js2-before-save ()
10460 "Clean up whitespace before saving file.
10461 You can disable this by customizing `js2-cleanup-whitespace'."
10462 (when js2-cleanup-whitespace
10463 (let ((col (current-column)))
10464 (delete-trailing-whitespace)
10465 ;; don't change trailing whitespace on current line
10466 (unless (eq (current-column) col)
10467 (indent-to col)))))
10469 (defsubst js2-mode-reset-timer ()
10470 "Cancel any existing parse timer and schedule a new one."
10471 (if js2-mode-parse-timer
10472 (cancel-timer js2-mode-parse-timer))
10473 (setq js2-mode-parsing nil)
10474 (setq js2-mode-parse-timer
10475 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10477 (defun js2-mode-edit (beg end len)
10478 "Schedule a new parse after buffer is edited.
10479 Buffer edit spans from BEG to END and is of length LEN.
10480 Also clears the `js2-magic' bit on autoinserted parens/brackets
10481 if the edit occurred on a line different from the magic paren."
10482 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10483 (line (if magic-pos (line-number-at-pos magic-pos))))
10485 (or (/= (line-number-at-pos beg) line)
10487 (/= (line-number-at-pos end) line)))
10488 (js2-mode-mundanify-parens)))
10489 (setq js2-mode-buffer-dirty-p t)
10490 (js2-mode-hide-overlay)
10491 (js2-mode-reset-timer))
10493 (defun js2-mode-run-font-lock ()
10494 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10495 This is intended to allow modes that install their own font-lock keywords
10496 to work with js2-mode. In practice it never seems to work for long.
10497 Hopefully the Emacs maintainers can help figure out a way to make it work."
10498 (when (and (boundp 'font-lock-keywords)
10500 (boundp 'font-lock-mode)
10502 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10503 ;; play nicely with js2-mode. They go out of their way to fail to
10504 ;; provide any option for saying "look, fontify the farging buffer
10505 ;; with just the keywords already". Argh.
10506 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10507 (let (font-lock-verbose)
10508 (font-lock-fontify-buffer))))
10510 (defun js2-reparse (&optional force)
10511 "Re-parse current buffer after user finishes some data entry.
10512 If we get any user input while parsing, including cursor motion,
10513 we discard the parse and reschedule it. If FORCE is nil, then the
10514 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10517 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10518 (unless js2-mode-parsing
10519 (setq js2-mode-parsing t)
10521 (when (or js2-mode-buffer-dirty-p force)
10522 (js2-remove-overlays)
10523 (js2-with-unmodifying-text-property-changes
10524 (setq js2-mode-buffer-dirty-p nil
10525 js2-mode-fontifications nil
10526 js2-mode-deferred-properties nil
10527 js2-additional-externs nil)
10528 (if js2-mode-verbose-parse-p
10529 (message "parsing..."))
10532 (setq interrupted-p
10533 (catch 'interrupted
10534 (setq js2-mode-ast (js2-parse))
10535 ;; if parsing is interrupted, comments and regex
10536 ;; literals stay ignored by `parse-partial-sexp'
10537 (remove-text-properties (point-min) (point-max)
10539 (js2-mode-apply-deferred-properties)
10540 (js2-mode-remove-suppressed-warnings)
10541 (js2-mode-show-warnings)
10542 (js2-mode-show-errors)
10543 (js2-mode-run-font-lock) ; note: doesn't work
10544 (js2-mode-highlight-magic-parens)
10545 (if (>= js2-highlight-level 1)
10546 (js2-highlight-jsdoc js2-mode-ast))
10550 ;; unfinished parse => try again
10551 (setq js2-mode-buffer-dirty-p t)
10552 (js2-mode-reset-timer))
10553 (if js2-mode-verbose-parse-p
10554 (message "Parse time: %s" time)))))
10555 (setq js2-mode-parsing nil)
10556 (unless interrupted-p
10557 (setq js2-mode-parse-timer nil))))))
10559 (defun js2-mode-show-node ()
10560 "Debugging aid: highlight selected AST node on mouse click."
10562 (let ((node (js2-node-at-point))
10565 (when js2-mode-show-overlay
10567 (message "No node found at location %s" (point))
10568 (setq beg (js2-node-abs-pos node)
10569 end (+ beg (js2-node-len node)))
10570 (if js2-mode-node-overlay
10571 (move-overlay js2-mode-node-overlay beg end)
10572 (setq js2-mode-node-overlay (make-overlay beg end))
10573 (overlay-put js2-mode-node-overlay 'face 'highlight))
10574 (js2-with-unmodifying-text-property-changes
10575 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10576 (message "%s, parent: %s"
10577 (js2-node-short-name node)
10578 (if (js2-node-parent node)
10579 (js2-node-short-name (js2-node-parent node))
10582 (defun js2-mode-hide-overlay (&optional p1 p2)
10583 "Remove the debugging overlay when the point moves.
10584 P1 and P2 are the old and new values of point, respectively."
10585 (when js2-mode-node-overlay
10586 (let ((beg (overlay-start js2-mode-node-overlay))
10587 (end (overlay-end js2-mode-node-overlay)))
10588 ;; Sometimes we're called spuriously.
10592 (js2-with-unmodifying-text-property-changes
10593 (remove-text-properties beg end '(point-left nil)))
10594 (delete-overlay js2-mode-node-overlay)
10595 (setq js2-mode-node-overlay nil)))))
10597 (defun js2-mode-reset ()
10598 "Debugging helper: reset everything."
10603 (defsubst js2-mode-show-warn-or-err (e face)
10604 "Highlight a warning or error E with FACE.
10605 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10606 (let* ((key (first e))
10608 (end (+ beg (third e)))
10609 ;; Don't inadvertently go out of bounds.
10610 (beg (max (point-min) (min beg (point-max))))
10611 (end (max (point-min) (min end (point-max))))
10612 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10613 (ovl (make-overlay beg end)))
10614 (overlay-put ovl 'face face)
10615 (overlay-put ovl 'js2-error t)
10616 (put-text-property beg end 'help-echo (js2-get-msg key))
10617 (put-text-property beg end 'point-entered #'js2-echo-error)))
10619 (defun js2-remove-overlays ()
10620 "Remove overlays from buffer that have a `js2-error' property."
10621 (let ((beg (point-min))
10624 (dolist (o (overlays-in beg end))
10625 (when (overlay-get o 'js2-error)
10626 (delete-overlay o))))))
10628 (defun js2-error-at-point (&optional pos)
10629 "Return non-nil if there's an error overlay at POS.
10630 Defaults to point."
10631 (loop with pos = (or pos (point))
10632 for o in (overlays-at pos)
10633 thereis (overlay-get o 'js2-error)))
10635 (defun js2-mode-apply-deferred-properties ()
10636 "Apply fontifications and other text properties recorded during parsing."
10637 (when (plusp js2-highlight-level)
10638 ;; We defer clearing faces as long as possible to eliminate flashing.
10639 (js2-clear-face (point-min) (point-max))
10640 ;; Have to reverse the recorded fontifications list so that errors
10641 ;; and warnings overwrite the normal fontifications.
10642 (dolist (f (nreverse js2-mode-fontifications))
10643 (put-text-property (first f) (second f) 'face (third f)))
10644 (setq js2-mode-fontifications nil))
10645 (dolist (p js2-mode-deferred-properties)
10646 (apply #'put-text-property p))
10647 (setq js2-mode-deferred-properties nil))
10649 (defun js2-mode-show-errors ()
10650 "Highlight syntax errors."
10651 (when js2-mode-show-parse-errors
10652 (dolist (e (js2-ast-root-errors js2-mode-ast))
10653 (js2-mode-show-warn-or-err e 'js2-error-face))))
10655 (defun js2-mode-remove-suppressed-warnings ()
10656 "Take suppressed warnings out of the AST warnings list.
10657 This ensures that the counts and `next-error' are correct."
10658 (setf (js2-ast-root-warnings js2-mode-ast)
10661 (let ((key (caar e)))
10663 (and (not js2-strict-trailing-comma-warning)
10664 (string-match "trailing\\.comma" key))
10665 (and (not js2-strict-cond-assign-warning)
10666 (string= key "msg.equal.as.assign"))
10667 (and js2-missing-semi-one-line-override
10668 (string= key "msg.missing.semi")
10669 (let* ((beg (second e))
10670 (node (js2-node-at-point beg))
10671 (fn (js2-mode-find-parent-fn node))
10672 (body (and fn (js2-function-node-body fn)))
10673 (lc (and body (js2-node-abs-pos body)))
10674 (rc (and lc (+ lc (js2-node-len body)))))
10679 (and (js2-same-line lc)
10680 (js2-same-line rc))))))))))
10681 (js2-ast-root-warnings js2-mode-ast))))
10683 (defun js2-mode-show-warnings ()
10684 "Highlight strict-mode warnings."
10685 (when js2-mode-show-strict-warnings
10686 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10687 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10689 (defun js2-echo-error (old-point new-point)
10690 "Called by point-motion hooks."
10691 (let ((msg (get-text-property new-point 'help-echo)))
10695 (defalias #'js2-echo-help #'js2-echo-error)
10697 (defun js2-enter-key ()
10698 "Handle user pressing the Enter key."
10700 (let ((parse-status (save-excursion
10701 (parse-partial-sexp (point-min) (point)))))
10703 ;; check if we're inside a string
10704 ((nth 3 parse-status)
10705 (js2-mode-split-string parse-status))
10706 ;; check if inside a block comment
10707 ((nth 4 parse-status)
10708 (js2-mode-extend-comment))
10710 ;; should probably figure out what the mode-map says we should do
10711 (if js2-indent-on-enter-key
10712 (let ((js2-bounce-indent-p nil))
10713 (js2-indent-line)))
10715 (if js2-enter-indents-newline
10716 (let ((js2-bounce-indent-p nil))
10717 (js2-indent-line)))))))
10719 (defun js2-mode-split-string (parse-status)
10720 "Turn a newline in mid-string into a string concatenation.
10721 PARSE-STATUS is as documented in `parse-partial-sexp'."
10722 (let* ((col (current-column))
10723 (quote-char (nth 3 parse-status))
10724 (quote-string (string quote-char))
10725 (string-beg (nth 8 parse-status))
10726 (indent (save-match-data
10729 (back-to-indentation)
10730 (if (looking-at "\\+")
10733 (goto-char string-beg)
10734 (if (looking-back "\\+\\s-+")
10735 (goto-char (match-beginning 0)))
10736 (current-column))))))
10737 (insert quote-char "\n")
10739 (insert "+ " quote-string)
10741 (insert quote-string)
10742 (backward-char 1))))
10744 (defun js2-mode-extend-comment ()
10745 "When inside a comment block, add comment prefix."
10746 (let (star single col first-line needs-close)
10748 (back-to-indentation)
10750 ((looking-at "\\*[^/]")
10752 col (current-column)))
10753 ((looking-at "/\\*")
10756 col (1+ (current-column))))
10759 col (current-column)))))
10760 ;; Heuristic for whether we need to close the comment:
10761 ;; if we've got a parse error here, assume it's an unterminated
10765 (eq (get-text-property (1- (point)) 'point-entered)
10767 ;; The heuristic above doesn't work well when we're
10768 ;; creating a comment and there's another one downstream,
10769 ;; as our parser thinks this one ends at the end of the
10770 ;; next one. (You can have a /* inside a js block comment.)
10771 ;; So just close it if the next non-ws char isn't a *.
10775 (skip-chars-forward " \t\r\n")
10776 (not (eq (char-after) ?*))))))
10782 (if (and first-line needs-close)
10788 (when (save-excursion
10789 (and (zerop (forward-line 1))
10790 (looking-at "\\s-*//")))
10792 (insert "// "))))))
10794 (defun js2-beginning-of-line ()
10795 "Toggles point between bol and first non-whitespace char in line.
10796 Also moves past comment delimiters when inside comments."
10801 (back-to-indentation))
10803 (skip-chars-forward "/ \t"))
10804 ((and (eq (char-after) ?*)
10805 (setq node (js2-comment-at-point))
10806 (memq (js2-comment-node-format node) '(jsdoc block))
10808 (skip-chars-backward " \t")
10810 (skip-chars-forward "\* \t"))
10812 (goto-char (point-at-bol))))))
10814 (defun js2-end-of-line ()
10815 "Toggles point between eol and last non-whitespace char in line."
10818 (skip-chars-backward " \t")
10819 (goto-char (point-at-eol))))
10821 (defun js2-enter-mirror-mode()
10822 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10825 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10826 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10827 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10828 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10829 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10830 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10831 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10832 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10834 (defun js2-leave-mirror-mode()
10835 "Turns off mirror mode."
10837 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10838 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10840 (defsubst js2-mode-inside-string ()
10841 "Return non-nil if inside a string.
10842 Actually returns the quote character that begins the string."
10843 (let ((parse-state (save-excursion
10844 (parse-partial-sexp (point-min) (point)))))
10845 (nth 3 parse-state)))
10847 (defsubst js2-mode-inside-comment-or-string ()
10848 "Return non-nil if inside a comment or string."
10850 (let ((comment-start
10852 (goto-char (point-at-bol))
10853 (if (re-search-forward "//" (point-at-eol) t)
10854 (match-beginning 0)))))
10856 (<= comment-start (point))))
10857 (let ((parse-state (save-excursion
10858 (parse-partial-sexp (point-min) (point)))))
10859 (or (nth 3 parse-state)
10860 (nth 4 parse-state)))))
10862 (defsubst js2-make-magic-delimiter (delim &optional pos)
10863 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10864 Sets value of `js2-magic' text property to line number at POS."
10866 'js2-magic (line-number-at-pos pos)
10867 'face 'js2-magic-paren-face))
10869 (defun js2-mode-match-delimiter (open close)
10870 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10871 The rule we use, which as far as we can tell is how Eclipse works,
10872 is that we insert the match if we're not in a comment or string,
10873 and the next non-whitespace character is either punctuation or
10874 occurs on another line."
10876 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10877 (not (js2-mode-inside-comment-or-string)))
10879 (insert (js2-make-magic-delimiter close)))
10880 (when js2-auto-indent-p
10881 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10882 (js2-indent-line)))))
10884 (defun js2-mode-match-bracket ()
10885 "Insert matching bracket."
10887 (js2-mode-match-delimiter "[" "]"))
10889 (defun js2-mode-match-paren ()
10890 "Insert matching paren unless already inserted."
10892 (js2-mode-match-delimiter "(" ")"))
10894 (defun js2-mode-match-curly (arg)
10895 "Insert matching curly-brace.
10896 With prefix arg, no formatting or indentation will occur -- the close-brace
10897 is simply inserted directly at the point."
10901 (current-prefix-arg
10902 (js2-mode-match-delimiter "{" "}"))
10903 ((and js2-auto-insert-catch-block
10904 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10906 (match-beginning 1))))
10907 (js2-insert-catch-skel try-pos))
10909 ;; Otherwise try to do something smarter.
10911 (unless (or (not (looking-at "\\s-*$"))
10913 (skip-chars-forward " \t\r\n")
10914 (and (looking-at "}")
10915 (js2-error-at-point)))
10916 (js2-mode-inside-comment-or-string))
10918 ;; absolutely mystifying bug: when inserting the next "\n",
10919 ;; the buffer-undo-list is given two new entries: the inserted range,
10920 ;; and the incorrect position of the point. It's recorded incorrectly
10921 ;; as being before the opening "{", not after it. But it's recorded
10922 ;; as the correct value if you're debugging `js2-mode-match-curly'
10923 ;; in edebug. I have no idea why it's doing this, but incrementing
10924 ;; the inserted position fixes the problem, so that the undo takes us
10925 ;; back to just after the user-inserted "{".
10928 (incf (cadr buffer-undo-list)))
10932 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10933 (js2-indent-line))))))))
10935 (defun js2-insert-catch-skel (try-pos)
10936 "Complete a try/catch block after inserting a { following a try keyword.
10937 Rationale is that a try always needs a catch or a finally, and the catch is
10938 the more likely of the two.
10940 TRY-POS is the buffer position of the try keyword. The open-curly should
10941 already have been inserted."
10943 (let ((try-col (save-excursion
10944 (goto-char try-pos)
10945 (current-column))))
10948 (js2-indent-line) ;; indent the blank line where cursor will end up
10951 (indent-to try-col)
10952 (insert "} catch (x) {\n\n")
10953 (indent-to try-col)
10956 (defun js2-mode-highlight-magic-parens ()
10957 "Re-highlight magic parens after parsing nukes the 'face prop."
10958 (let ((beg (point-min))
10960 (while (setq beg (next-single-property-change beg 'js2-magic))
10961 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10962 (if (get-text-property beg 'js2-magic)
10963 (js2-with-unmodifying-text-property-changes
10964 (put-text-property beg (or end (1+ beg))
10965 'face 'js2-magic-paren-face))))))
10967 (defun js2-mode-mundanify-parens ()
10968 "Clear all magic parens and brackets."
10969 (let ((beg (point-min))
10971 (while (setq beg (next-single-property-change beg 'js2-magic))
10972 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10973 (remove-text-properties beg (or end (1+ beg))
10974 '(js2-magic face)))))
10976 (defsubst js2-match-quote (quote-string)
10977 (let ((start-quote (js2-mode-inside-string)))
10979 ;; inside a comment - don't do quote-matching, since we can't
10980 ;; reliably figure out if we're in a string inside the comment
10981 ((js2-comment-at-point)
10982 (insert quote-string))
10984 ;; not in string => insert matched quotes
10985 (insert quote-string)
10986 ;; exception: if we're just before a word, don't double it.
10987 (unless (looking-at "[^ \t\r\n]")
10989 (insert quote-string))))
10990 ((looking-at quote-string)
10991 (if (looking-back "[^\\]\\\\")
10992 (insert quote-string)
10994 ((and js2-mode-escape-quotes
10997 (re-search-forward quote-string (point-at-eol) t))))
10998 ;; inside terminated string, escape quote (unless already escaped)
10999 (insert (if (looking-back "[^\\]\\\\")
11001 (concat "\\" quote-string))))
11003 (insert quote-string))))) ; else terminate the string
11005 (defun js2-mode-match-single-quote ()
11006 "Insert matching single-quote."
11008 (let ((parse-status (parse-partial-sexp (point-min) (point))))
11009 ;; don't match inside comments, since apostrophe is more common
11010 (if (nth 4 parse-status)
11012 (js2-match-quote "'"))))
11014 (defun js2-mode-match-double-quote ()
11015 "Insert matching double-quote."
11017 (js2-match-quote "\""))
11019 ;; Eclipse works as follows:
11020 ;; * type an open-paren and it auto-inserts close-paren
11021 ;; - auto-inserted paren gets a green bracket
11022 ;; - green bracket means typing close-paren there will skip it
11023 ;; * if you insert any text on a different line, it turns off
11024 (defun js2-mode-magic-close-paren ()
11025 "Skip over close-paren rather than inserting, where appropriate."
11027 (let* ((here (point))
11028 (parse-status (parse-partial-sexp (point-min) here))
11029 (open-pos (nth 1 parse-status))
11030 (close last-input-event)
11039 (if (and (eq (char-after) close)
11040 (eq open (char-after open-pos))
11041 (js2-same-line open-pos)
11042 (get-text-property here 'js2-magic))
11044 (remove-text-properties here (1+ here) '(js2-magic face))
11046 (insert-char close 1))
11047 (blink-matching-open)))
11049 (defun js2-mode-wait-for-parse (callback)
11050 "Invoke CALLBACK when parsing is finished.
11051 If parsing is already finished, calls CALLBACK immediately."
11052 (if (not js2-mode-buffer-dirty-p)
11054 (push callback js2-mode-pending-parse-callbacks)
11055 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11057 (defun js2-mode-parse-finished ()
11058 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11059 ;; We can't let errors propagate up, since it prevents the
11060 ;; `js2-parse' method from completing normally and returning
11061 ;; the ast, which makes things mysteriously not work right.
11063 (dolist (cb js2-mode-pending-parse-callbacks)
11064 (condition-case err
11066 (error (message "%s" err))))
11067 (setq js2-mode-pending-parse-callbacks nil)))
11069 (defun js2-mode-flag-region (from to flag)
11070 "Hide or show text from FROM to TO, according to FLAG.
11071 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11072 Returns the created overlay if FLAG is non-nil."
11073 (remove-overlays from to 'invisible 'js2-outline)
11075 (let ((o (make-overlay from to)))
11076 (overlay-put o 'invisible 'js2-outline)
11077 (overlay-put o 'isearch-open-invisible
11078 'js2-isearch-open-invisible)
11081 ;; Function to be set as an outline-isearch-open-invisible' property
11082 ;; to the overlay that makes the outline invisible (see
11083 ;; `js2-mode-flag-region').
11084 (defun js2-isearch-open-invisible (overlay)
11085 ;; We rely on the fact that isearch places point on the matched text.
11086 (js2-mode-show-element))
11088 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11089 "Return cons cell of bounds of folding overlay at POS.
11090 Returns nil if not found."
11091 (let ((overlays (overlays-at (or pos (point))))
11093 (while (and overlays
11095 (if (overlay-get (car overlays) 'invisible)
11096 (setq o (car overlays))
11097 (setq overlays (cdr overlays))))
11099 (cons (overlay-start o) (overlay-end o)))))
11101 (defun js2-mode-function-at-point (&optional pos)
11102 "Return the innermost function node enclosing current point.
11103 Returns nil if point is not in a function."
11104 (let ((node (js2-node-at-point pos)))
11105 (while (and node (not (js2-function-node-p node)))
11106 (setq node (js2-node-parent node)))
11107 (if (js2-function-node-p node)
11110 (defun js2-mode-toggle-element ()
11111 "Hide or show the foldable element at the point."
11113 (let (comment fn pos)
11117 ;; /* ... */ comment?
11118 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11119 (if (js2-mode-invisible-overlay-bounds
11120 (setq pos (+ 3 (js2-node-abs-pos comment))))
11123 (js2-mode-show-element))
11124 (js2-mode-hide-element)))
11127 (back-to-indentation)
11128 (looking-at js2-mode-//-comment-re))
11129 (js2-mode-toggle-//-comment))
11131 ((setq fn (js2-mode-function-at-point))
11132 (setq pos (and (js2-function-node-body fn)
11133 (js2-node-abs-pos (js2-function-node-body fn))))
11134 (goto-char (1+ pos))
11135 (if (js2-mode-invisible-overlay-bounds)
11136 (js2-mode-show-element)
11137 (js2-mode-hide-element)))
11139 (message "Nothing at point to hide or show")))))))
11141 (defun js2-mode-hide-element ()
11142 "Fold/hide contents of a block, showing ellipses.
11143 Show the hidden text with \\[js2-mode-show-element]."
11145 (if js2-mode-buffer-dirty-p
11146 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11147 (let (node body beg end)
11149 ((js2-mode-invisible-overlay-bounds)
11150 (message "already hidden"))
11152 (setq node (js2-node-at-point))
11154 ((js2-block-comment-p node)
11155 (js2-mode-hide-comment node))
11157 (while (and node (not (js2-function-node-p node)))
11158 (setq node (js2-node-parent node)))
11160 (setq body (js2-function-node-body node)))
11162 (setq beg (js2-node-abs-pos body)
11163 end (+ beg (js2-node-len body)))
11164 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11165 (message "No collapsable element found at point"))))))))
11167 (defun js2-mode-show-element ()
11168 "Show the hidden element at current point."
11170 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11172 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11173 (message "Nothing to un-hide"))))
11175 (defun js2-mode-show-all ()
11176 "Show all of the text in the buffer."
11178 (js2-mode-flag-region (point-min) (point-max) nil))
11180 (defun js2-mode-toggle-hide-functions ()
11182 (if js2-mode-functions-hidden
11183 (js2-mode-show-functions)
11184 (js2-mode-hide-functions)))
11186 (defun js2-mode-hide-functions ()
11187 "Hides all non-nested function bodies in the buffer.
11188 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11189 to open an individual entry."
11191 (if js2-mode-buffer-dirty-p
11192 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11193 (if (null js2-mode-ast)
11194 (message "Oops - parsing failed")
11195 (setq js2-mode-functions-hidden t)
11196 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11198 (defun js2-mode-function-hider (n endp)
11200 (let ((tt (js2-node-type n))
11203 ((and (= tt js2-FUNCTION)
11204 (setq body (js2-function-node-body n)))
11205 (setq beg (js2-node-abs-pos body)
11206 end (+ beg (js2-node-len body)))
11207 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11208 nil) ; don't process children of function
11210 t))))) ; keep processing other AST nodes
11212 (defun js2-mode-show-functions ()
11213 "Un-hide any folded function bodies in the buffer."
11215 (setq js2-mode-functions-hidden nil)
11217 (goto-char (point-min))
11218 (while (/= (goto-char (next-overlay-change (point)))
11220 (dolist (o (overlays-at (point)))
11221 (when (and (overlay-get o 'invisible)
11222 (not (overlay-get o 'comment)))
11223 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11225 (defun js2-mode-hide-comment (n)
11226 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11229 (beg (+ (js2-node-abs-pos n) head))
11230 (end (- (+ beg (js2-node-len n)) head 2))
11231 (o (js2-mode-flag-region beg end 'hide)))
11232 (overlay-put o 'comment t)))
11234 (defun js2-mode-toggle-hide-comments ()
11235 "Folds all block comments in the buffer.
11236 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11237 to open an individual entry."
11239 (if js2-mode-comments-hidden
11240 (js2-mode-show-comments)
11241 (js2-mode-hide-comments)))
11243 (defun js2-mode-hide-comments ()
11245 (if js2-mode-buffer-dirty-p
11246 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11247 (if (null js2-mode-ast)
11248 (message "Oops - parsing failed")
11249 (setq js2-mode-comments-hidden t)
11250 (dolist (n (js2-ast-root-comments js2-mode-ast))
11251 (let ((format (js2-comment-node-format n)))
11252 (when (js2-block-comment-p n)
11253 (js2-mode-hide-comment n))))
11254 (js2-mode-hide-//-comments)))
11256 (defsubst js2-mode-extend-//-comment (direction)
11257 "Find start or end of a block of similar //-comment lines.
11258 DIRECTION is -1 to look back, 1 to look forward.
11259 INDENT is the indentation level to match.
11260 Returns the end-of-line position of the furthest adjacent
11261 //-comment line with the same indentation as the current line.
11262 If there is no such matching line, returns current end of line."
11263 (let ((pos (point-at-eol))
11264 (indent (current-indentation)))
11267 (while (and (zerop (forward-line direction))
11268 (looking-at js2-mode-//-comment-re)
11269 (eq indent (length (match-string 1))))
11270 (setq pos (point-at-eol)))
11273 (defun js2-mode-hide-//-comments ()
11274 "Fold adjacent 1-line comments, showing only snippet of first one."
11278 (goto-char (point-min))
11279 (while (re-search-forward js2-mode-//-comment-re nil t)
11281 end (js2-mode-extend-//-comment 1))
11282 (unless (eq beg end)
11283 (overlay-put (js2-mode-flag-region beg end 'hide)
11286 (forward-char 1))))))
11288 (defun js2-mode-toggle-//-comment ()
11289 "Fold or un-fold any multi-line //-comment at point.
11290 Caller should have determined that this line starts with a //-comment."
11291 (let* ((beg (point-at-eol))
11295 (if (js2-mode-invisible-overlay-bounds)
11296 (js2-mode-show-element)
11297 ;; else hide the comment
11298 (setq beg (js2-mode-extend-//-comment -1)
11299 end (js2-mode-extend-//-comment 1))
11300 (unless (eq beg end)
11301 (overlay-put (js2-mode-flag-region beg end 'hide)
11304 (defun js2-mode-show-comments ()
11305 "Un-hide any hidden comments, leaving other hidden elements alone."
11307 (setq js2-mode-comments-hidden nil)
11309 (goto-char (point-min))
11310 (while (/= (goto-char (next-overlay-change (point)))
11312 (dolist (o (overlays-at (point)))
11313 (when (overlay-get o 'comment)
11314 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11316 (defun js2-mode-display-warnings-and-errors ()
11317 "Turn on display of warnings and errors."
11319 (setq js2-mode-show-parse-errors t
11320 js2-mode-show-strict-warnings t)
11321 (js2-reparse 'force))
11323 (defun js2-mode-hide-warnings-and-errors ()
11324 "Turn off display of warnings and errors."
11326 (setq js2-mode-show-parse-errors nil
11327 js2-mode-show-strict-warnings nil)
11328 (js2-reparse 'force))
11330 (defun js2-mode-toggle-warnings-and-errors ()
11331 "Toggle the display of warnings and errors.
11332 Some users don't like having warnings/errors reported while they type."
11334 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11335 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11336 (if (interactive-p)
11337 (message "warnings and errors %s"
11338 (if js2-mode-show-parse-errors
11341 (js2-reparse 'force))
11343 (defun js2-mode-customize ()
11345 (customize-group 'js2-mode))
11347 (defun js2-mode-forward-sexp (&optional arg)
11348 "Move forward across one statement or balanced expression.
11349 With ARG, do it that many times. Negative arg -N means
11350 move backward across N balanced expressions."
11352 (setq arg (or arg 1))
11353 (if js2-mode-buffer-dirty-p
11354 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11355 (let (node end (start (point)))
11358 ;; could probably make this better for some cases:
11359 ;; - if in statement block (e.g. function body), go to parent
11360 ;; - infix exprs like (foo in bar) - maybe go to beginning
11361 ;; of infix expr if in the right-side expression?
11362 ((and arg (minusp arg))
11363 (dotimes (i (- arg))
11365 (forward-char -1) ; enter the node we backed up to
11366 (setq node (js2-node-at-point (point) t))
11367 (goto-char (if node
11368 (js2-node-abs-pos node)
11375 (setq node (js2-node-at-point (point) t)
11376 end (if node (+ (js2-node-abs-pos node)
11377 (js2-node-len node))))
11378 (goto-char (or end (point-max))))))))
11380 (defun js2-next-error (&optional arg reset)
11381 "Move to next parse error.
11382 Typically invoked via \\[next-error].
11383 ARG is the number of errors, forward or backward, to move.
11384 RESET means start over from the beginning."
11386 (if (or (null js2-mode-ast)
11387 (and (null (js2-ast-root-errors js2-mode-ast))
11388 (null (js2-ast-root-warnings js2-mode-ast))))
11389 (message "No errors")
11391 (goto-char (point-min)))
11392 (let* ((errs (copy-sequence
11393 (append (js2-ast-root-errors js2-mode-ast)
11394 (js2-ast-root-warnings js2-mode-ast))))
11398 (backward (minusp count))
11399 (sorter (if backward '> '<))
11400 (stopper (if backward '< '>))
11401 (count (abs count))
11404 ;; sort by start position
11405 (setq errs (sort errs (lambda (e1 e2)
11406 (funcall sorter (second e1) (second e2))))
11408 ;; find nth error with pos > start
11409 (while (and errs continue)
11410 (when (funcall stopper (cadar errs) start)
11411 (setq err (car errs))
11412 (if (zerop (decf count))
11413 (setq continue nil)))
11414 (setq errs (cdr errs)))
11416 (goto-char (second err))
11417 ;; wrap around to first error
11418 (goto-char (second (car all-errs)))
11419 ;; if we were already on it, echo msg again
11420 (if (= (point) start)
11421 (js2-echo-error (point) (point)))))))
11423 (defun js2-down-mouse-3 ()
11424 "Make right-click move the point to the click location.
11425 This makes right-click context menu operations a bit more intuitive.
11426 The point will not move if the region is active, however, to avoid
11427 destroying the region selection."
11429 (when (and js2-move-point-on-right-click
11431 (let ((e last-input-event))
11433 (goto-char (cadadr e))))))
11435 (defun js2-mode-create-imenu-index ()
11436 "Return an alist for `imenu--index-alist'."
11437 ;; This is built up in `js2-parse-record-imenu' during parsing.
11439 ;; if we have an ast but no recorder, they're requesting a rescan
11440 (unless js2-imenu-recorder
11441 (js2-reparse 'force))
11443 (js2-build-imenu-index)
11444 (setq js2-imenu-recorder nil
11445 js2-imenu-function-map nil))))
11447 (defun js2-mode-find-tag ()
11448 "Replacement for `find-tag-default'.
11449 `find-tag-default' returns a ridiculous answer inside comments."
11451 (js2-with-underscore-as-word-syntax
11453 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11454 (looking-back "[A-Za-z0-9_$]"))
11455 (setq beg (progn (forward-word -1) (point))
11456 end (progn (forward-word 1) (point)))
11457 (setq beg (progn (forward-word 1) (point))
11458 end (progn (forward-word -1) (point))))
11459 (replace-regexp-in-string
11461 (buffer-substring-no-properties beg end))))))
11463 (defun js2-mode-forward-sibling ()
11464 "Move to the end of the sibling following point in parent.
11465 Returns non-nil if successful, or nil if there was no following sibling."
11466 (let* ((node (js2-node-at-point))
11467 (parent (js2-mode-find-enclosing-fn node))
11469 (when (setq sib (js2-node-find-child-after (point) parent))
11470 (goto-char (+ (js2-node-abs-pos sib)
11471 (js2-node-len sib))))))
11473 (defun js2-mode-backward-sibling ()
11474 "Move to the beginning of the sibling node preceding point in parent.
11475 Parent is defined as the enclosing script or function."
11476 (let* ((node (js2-node-at-point))
11477 (parent (js2-mode-find-enclosing-fn node))
11479 (when (setq sib (js2-node-find-child-before (point) parent))
11480 (goto-char (js2-node-abs-pos sib)))))
11482 (defun js2-beginning-of-defun ()
11483 "Go to line on which current function starts, and return non-nil.
11484 If we're not in a function, go to beginning of previous script-level element."
11486 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11489 ((and (js2-function-node-p parent)
11490 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11493 (js2-mode-backward-sibling)))))
11495 (defun js2-end-of-defun ()
11496 "Go to the char after the last position of the current function.
11497 If we're not in a function, skips over the next script-level element."
11499 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11500 (if (not (js2-function-node-p parent))
11501 ;; punt: skip over next script-level element beyond point
11502 (js2-mode-forward-sibling)
11503 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11504 (js2-node-len parent)))))))
11506 (defun js2-mark-defun (&optional allow-extend)
11507 "Put mark at end of this function, point at beginning.
11508 The function marked is the one that contains point.
11510 Interactively, if this command is repeated,
11511 or (in Transient Mark mode) if the mark is active,
11512 it marks the next defun after the ones already marked."
11515 (when (and allow-extend
11516 (or (and (eq last-command this-command) (mark t))
11517 (and transient-mark-mode mark-active)))
11518 (let ((sib (save-excursion
11520 (if (js2-mode-forward-sibling)
11527 ;; no more siblings - try extending to enclosing node
11528 (goto-char (mark t)))))
11529 (when (not extended)
11530 (let ((node (js2-node-at-point (point) t)) ; skip comments
11531 ast fn stmt parent beg end)
11532 (when (js2-ast-root-p node)
11534 node (or (js2-node-find-child-after (point) node)
11535 (js2-node-find-child-before (point) node))))
11536 ;; only mark whole buffer if we can't find any children
11539 (if (js2-function-node-p node)
11541 (setq fn (js2-mode-find-enclosing-fn node)
11542 stmt (if (or (null fn)
11543 (js2-ast-root-p fn))
11544 (js2-mode-find-first-stmt node))
11545 parent (or stmt fn)))
11546 (setq beg (js2-node-abs-pos parent)
11547 end (+ beg (js2-node-len parent)))
11550 (exchange-point-and-mark)))))
11552 (defun js2-narrow-to-defun ()
11553 "Narrow to the function enclosing point."
11555 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11556 (fn (if (js2-script-node-p node)
11558 (js2-mode-find-enclosing-fn node)))
11559 (beg (js2-node-abs-pos fn)))
11560 (unless (js2-ast-root-p fn)
11561 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11563 (provide 'js2-mode)
11565 ;;; js2-mode.el ends here