1 ;;; js2-mode.el --- Improved JavaScript editing mode
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
14 ;; This file is part of GNU Emacs.
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 ;; This JavaScript editing mode supports:
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
50 ;; To install it as your major mode for JavaScript editing:
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
59 ;; You may also want to hook it in for shell scripts running via node.js:
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
63 ;; Support for JSX is available via the derived mode `js2-jsx-mode'. If you
64 ;; also want JSX support, use that mode instead:
66 ;; (add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
67 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-jsx-mode))
69 ;; To customize how it works:
70 ;; M-x customize-group RET js2-mode RET
74 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
75 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
76 ;; `js2-mode' current as the EcmaScript language standard evolves.
78 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
79 ;; customizable. It is a surprising amount of work to support customizable
80 ;; indentation. The current compromise is that the tab key lets you cycle among
81 ;; various likely indentation points, similar to the behavior of python-mode.
83 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
84 ;; and `mumamo', although it could be made to do so with some effort.
85 ;; This means that `js2-mode' is currently only useful for editing JavaScript
86 ;; files, and not for editing JavaScript within <script> tags or templates.
88 ;; The project page on GitHub is used for development and issue tracking.
89 ;; The original homepage at Google Code has outdated information and is mostly
100 (if (version< emacs-version "25.0")
101 (require 'js2-old-indent)
102 (defvaralias 'js2-basic-offset 'js-indent-level nil)
103 (defalias 'js2-proper-indentation 'js--proper-indentation)
104 (defalias 'js2-jsx-indent-line 'js-jsx-indent-line)
105 (defalias 'js2-indent-line 'js-indent-line)
106 (defalias 'js2-re-search-forward 'js--re-search-forward)))
108 ;;; Externs (variables presumed to be defined by the host system)
110 (defvar js2-ecma-262-externs
112 '(Array Boolean Date Error EvalError Function Infinity JSON
113 Math NaN Number Object RangeError ReferenceError RegExp
114 String SyntaxError TypeError URIError
115 decodeURI decodeURIComponent encodeURI
116 encodeURIComponent escape eval isFinite isNaN
117 parseFloat parseInt undefined unescape))
118 "Ecma-262 externs. Included in `js2-externs' by default.")
120 (defvar js2-browser-externs
123 Attr CDATASection CharacterData Comment DOMException
124 DOMImplementation Document DocumentFragment
125 DocumentType Element Entity EntityReference
126 ExceptionCode NamedNodeMap Node NodeList Notation
127 ProcessingInstruction Text
130 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
131 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
132 HTMLBodyElement HTMLButtonElement HTMLCollection
133 HTMLDListElement HTMLDirectoryElement HTMLDivElement
134 HTMLDocument HTMLElement HTMLFieldSetElement
135 HTMLFontElement HTMLFormElement HTMLFrameElement
136 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
137 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
138 HTMLImageElement HTMLInputElement HTMLIsIndexElement
139 HTMLLIElement HTMLLabelElement HTMLLegendElement
140 HTMLLinkElement HTMLMapElement HTMLMenuElement
141 HTMLMetaElement HTMLModElement HTMLOListElement
142 HTMLObjectElement HTMLOptGroupElement
143 HTMLOptionElement HTMLOptionsCollection
144 HTMLParagraphElement HTMLParamElement HTMLPreElement
145 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
146 HTMLStyleElement HTMLTableCaptionElement
147 HTMLTableCellElement HTMLTableColElement
148 HTMLTableElement HTMLTableRowElement
149 HTMLTableSectionElement HTMLTextAreaElement
150 HTMLTitleElement HTMLUListElement
153 DOMConfiguration DOMError DOMException
154 DOMImplementationList DOMImplementationSource
155 DOMLocator DOMStringList NameList TypeInfo
159 window alert confirm document java navigator prompt screen
160 self top requestAnimationFrame cancelAnimationFrame
163 CSSCharsetRule CSSFontFace CSSFontFaceRule
164 CSSImportRule CSSMediaRule CSSPageRule
165 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
166 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
167 CSSValue CSSValueList Counter DOMImplementationCSS
168 DocumentCSS DocumentStyle ElementCSSInlineStyle
169 LinkStyle MediaList RGBColor Rect StyleSheet
170 StyleSheetList ViewCSS
173 EventListener EventTarget Event DocumentEvent UIEvent
174 MouseEvent MutationEvent KeyboardEvent
177 DocumentRange Range RangeException
180 XPathResult XMLHttpRequest
182 ;; console object. Provided by at least Chrome and Firefox.
185 You can cause these to be included or excluded with the custom
186 variable `js2-include-browser-externs'.")
188 (defvar js2-rhino-externs
190 '(Packages importClass importPackage com org java
191 ;; Global object (shell) externs.
192 defineClass deserialize doctest gc help load
193 loadClass print quit readFile readUrl runCommand seal
194 serialize spawn sync toint32 version))
195 "Mozilla Rhino externs.
196 Set `js2-include-rhino-externs' to t to include them.")
198 (defvar js2-node-externs
200 '(__dirname __filename Buffer clearInterval clearTimeout require
201 console exports global module process setInterval setTimeout
204 Set `js2-include-node-externs' to t to include them.")
206 (defvar js2-typed-array-externs
208 '(ArrayBuffer Uint8ClampedArray DataView
209 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
210 Float32Array Float64Array))
211 "Khronos typed array externs. Available in most modern browsers and
212 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
213 are enabled, these will also be included.")
215 (defvar js2-harmony-externs
217 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
218 "ES6 externs. If `js2-include-browser-externs' is enabled and
219 `js2-language-version' is sufficiently high, these will be included.")
223 (defun js2-mark-safe-local (name pred)
224 "Make the variable NAME buffer-local and mark it as safe file-local
225 variable with predicate PRED."
226 (make-variable-buffer-local name)
227 (put name 'safe-local-variable pred))
229 (defcustom js2-highlight-level 2
230 "Amount of syntax highlighting to perform.
231 0 or a negative value means none.
232 1 adds basic syntax highlighting.
233 2 adds highlighting of some Ecma built-in properties.
234 3 adds highlighting of many Ecma built-in functions."
236 :type '(choice (const :tag "None" 0)
237 (const :tag "Basic" 1)
238 (const :tag "Include Properties" 2)
239 (const :tag "Include Functions" 3)))
241 (defvar js2-mode-dev-mode-p nil
242 "Non-nil if running in development mode. Normally nil.")
244 (defgroup js2-mode nil
245 "An improved JavaScript mode."
248 (defcustom js2-idle-timer-delay 0.2
249 "Delay in secs before re-parsing after user makes changes.
250 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
253 (make-variable-buffer-local 'js2-idle-timer-delay)
255 (defcustom js2-dynamic-idle-timer-adjust 0
256 "Positive to adjust `js2-idle-timer-delay' based on file size.
257 The idea is that for short files, parsing is faster so we can be
258 more responsive to user edits without interfering with editing.
259 The buffer length in characters (typically bytes) is divided by
260 this value and used to multiply `js2-idle-timer-delay' for the
261 buffer. For example, a 21k file and 10k adjust yields 21k/10k
262 == 2, so js2-idle-timer-delay is multiplied by 2.
263 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
264 `js2-idle-timer-delay' is not dependent on the file size."
268 (defcustom js2-concat-multiline-strings t
269 "When non-nil, `js2-line-break' in mid-string will make it a
270 string concatenation. When `eol', the '+' will be inserted at the
271 end of the line, otherwise, at the beginning of the next line."
272 :type '(choice (const t) (const eol) (const nil))
275 (defcustom js2-mode-show-parse-errors t
276 "True to highlight parse errors."
280 (defcustom js2-mode-show-strict-warnings t
281 "Non-nil to emit Ecma strict-mode warnings.
282 Some of the warnings can be individually disabled by other flags,
283 even if this flag is non-nil."
287 (defcustom js2-strict-trailing-comma-warning t
288 "Non-nil to warn about trailing commas in array literals.
289 Ecma-262-5.1 allows them, but older versions of IE raise an error."
293 (defcustom js2-strict-missing-semi-warning t
294 "Non-nil to warn about semicolon auto-insertion after statement.
295 Technically this is legal per Ecma-262, but some style guides disallow
300 (defcustom js2-missing-semi-one-line-override nil
301 "Non-nil to permit missing semicolons in one-line functions.
302 In one-liner functions such as `function identity(x) {return x}'
303 people often omit the semicolon for a cleaner look. If you are
304 such a person, you can suppress the missing-semicolon warning
305 by setting this variable to t."
309 (defcustom js2-strict-inconsistent-return-warning t
310 "Non-nil to warn about mixing returns with value-returns.
311 It's perfectly legal to have a `return' and a `return foo' in the
312 same function, but it's often an indicator of a bug, and it also
313 interferes with type inference (in systems that support it.)"
317 (defcustom js2-strict-cond-assign-warning t
318 "Non-nil to warn about expressions like if (a = b).
319 This often should have been '==' instead of '='. If the warning
320 is enabled, you can suppress it on a per-expression basis by
321 parenthesizing the expression, e.g. if ((a = b)) ..."
325 (defcustom js2-strict-var-redeclaration-warning t
326 "Non-nil to warn about redeclaring variables in a script or function."
330 (defcustom js2-strict-var-hides-function-arg-warning t
331 "Non-nil to warn about a var decl hiding a function argument."
335 (defcustom js2-skip-preprocessor-directives nil
336 "Non-nil to treat lines beginning with # as comments.
337 Useful for viewing Mozilla JavaScript source code."
341 (defcustom js2-language-version 200
342 "Configures what JavaScript language version to recognize.
343 Currently versions 150, 160, 170, 180 and 200 are supported,
344 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
345 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
346 yield, and Array comprehensions, and 1.8 adds function closures."
350 (defcustom js2-instanceof-has-side-effects nil
351 "If non-nil, treats the instanceof operator as having side effects.
352 This is useful for xulrunner apps."
356 (defcustom js2-move-point-on-right-click t
357 "Non-nil to move insertion point when you right-click.
358 This makes right-click context menu behavior a bit more intuitive,
359 since menu operations generally apply to the point. The exception
360 is if there is a region selection, in which case the point does -not-
361 move, so cut/copy/paste can work properly.
363 Note that IntelliJ moves the point, and Eclipse leaves it alone,
364 so this behavior is customizable."
368 (defcustom js2-allow-rhino-new-expr-initializer t
369 "Non-nil to support a Rhino's experimental syntactic construct.
371 Rhino supports the ability to follow a `new' expression with an object
372 literal, which is used to set additional properties on the new object
373 after calling its constructor. Syntax:
375 new <expr> [ ( arglist ) ] [initializer]
377 Hence, this expression:
379 new Object {a: 1, b: 2}
381 results in an Object with properties a=1 and b=2. This syntax is
382 apparently not configurable in Rhino - it's currently always enabled,
383 as of Rhino version 1.7R2."
387 (defcustom js2-allow-member-expr-as-function-name nil
388 "Non-nil to support experimental Rhino syntax for function names.
390 Rhino supports an experimental syntax configured via the Rhino Context
391 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
393 function <member-expr> ( [ arg-list ] ) { <body> }
395 Where member-expr is a non-parenthesized 'member expression', which
396 is anything at the grammar level of a new-expression or lower, meaning
397 any expression that does not involve infix or unary operators.
399 When <member-expr> is not a simple identifier, then it is syntactic
400 sugar for assigning the anonymous function to the <member-expr>. Hence,
403 function a.b().c[2] (x, y) { ... }
407 a.b().c[2] = function(x, y) {...}
409 which doesn't seem particularly useful, but Rhino permits it."
415 (defmacro js2-deflocal (name value &optional comment)
416 "Define a buffer-local variable NAME with VALUE and COMMENT."
417 (declare (debug defvar) (doc-string 3))
419 (defvar ,name ,value ,comment)
420 (make-variable-buffer-local ',name)))
422 (defvar js2-EOF_CHAR -1
423 "Represents end of stream. Distinct from js2-EOF token type.")
425 ;; I originally used symbols to represent tokens, but Rhino uses
426 ;; ints and then sets various flag bits in them, so ints it is.
427 ;; The upshot is that we need a `js2-' prefix in front of each name.
428 (defvar js2-ERROR -1)
431 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
432 (defvar js2-LEAVEWITH 3)
433 (defvar js2-RETURN 4)
437 (defvar js2-SETNAME 8)
439 (defvar js2-BITXOR 10)
440 (defvar js2-BITAND 11)
450 (defvar js2-ADD 21) ; infix plus
451 (defvar js2-SUB 22) ; infix minus
456 (defvar js2-BITNOT 27)
457 (defvar js2-POS 28) ; unary plus
458 (defvar js2-NEG 29) ; unary minus
460 (defvar js2-DELPROP 31)
461 (defvar js2-TYPEOF 32)
462 (defvar js2-GETPROP 33)
463 (defvar js2-GETPROPNOWARN 34)
464 (defvar js2-SETPROP 35)
465 (defvar js2-GETELEM 36)
466 (defvar js2-SETELEM 37)
468 (defvar js2-NAME 39) ; an identifier
469 (defvar js2-NUMBER 40)
470 (defvar js2-STRING 41)
473 (defvar js2-FALSE 44)
475 (defvar js2-SHEQ 46) ; shallow equality (===)
476 (defvar js2-SHNE 47) ; shallow inequality (!==)
477 (defvar js2-REGEXP 48)
478 (defvar js2-BINDNAME 49)
479 (defvar js2-THROW 50)
480 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
482 (defvar js2-INSTANCEOF 53)
483 (defvar js2-LOCAL_LOAD 54)
484 (defvar js2-GETVAR 55)
485 (defvar js2-SETVAR 56)
486 (defvar js2-CATCH_SCOPE 57)
487 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
488 (defvar js2-ENUM_INIT_VALUES 59)
489 (defvar js2-ENUM_INIT_ARRAY 60)
490 (defvar js2-ENUM_NEXT 61)
491 (defvar js2-ENUM_ID 62)
492 (defvar js2-THISFN 63)
493 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
494 (defvar js2-ARRAYLIT 65) ; array literal
495 (defvar js2-OBJECTLIT 66) ; object literal
496 (defvar js2-GET_REF 67) ; *reference
497 (defvar js2-SET_REF 68) ; *reference = something
498 (defvar js2-DEL_REF 69) ; delete reference
499 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
500 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
501 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
504 (defvar js2-DEFAULTNAMESPACE 73)
505 (defvar js2-ESCXMLATTR 74)
506 (defvar js2-ESCXMLTEXT 75)
507 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
508 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
509 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
510 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
512 (defvar js2-first-bytecode js2-ENTERWITH)
513 (defvar js2-last-bytecode js2-REF_NS_NAME)
516 (defvar js2-SEMI 81) ; semicolon
517 (defvar js2-LB 82) ; left and right brackets
519 (defvar js2-LC 84) ; left and right curly-braces
521 (defvar js2-LP 86) ; left and right parens
523 (defvar js2-COMMA 88) ; comma operator
525 (defvar js2-ASSIGN 89) ; simple assignment (=)
526 (defvar js2-ASSIGN_BITOR 90) ; |=
527 (defvar js2-ASSIGN_BITXOR 91) ; ^=
528 (defvar js2-ASSIGN_BITAND 92) ; &=
529 (defvar js2-ASSIGN_LSH 93) ; <<=
530 (defvar js2-ASSIGN_RSH 94) ; >>=
531 (defvar js2-ASSIGN_URSH 95) ; >>>=
532 (defvar js2-ASSIGN_ADD 96) ; +=
533 (defvar js2-ASSIGN_SUB 97) ; -=
534 (defvar js2-ASSIGN_MUL 98) ; *=
535 (defvar js2-ASSIGN_DIV 99) ; /=
536 (defvar js2-ASSIGN_MOD 100) ; %=
538 (defvar js2-first-assign js2-ASSIGN)
539 (defvar js2-last-assign js2-ASSIGN_MOD)
541 (defvar js2-HOOK 101) ; conditional (?:)
542 (defvar js2-COLON 102)
543 (defvar js2-OR 103) ; logical or (||)
544 (defvar js2-AND 104) ; logical and (&&)
545 (defvar js2-INC 105) ; increment/decrement (++ --)
547 (defvar js2-DOT 107) ; member operator (.)
548 (defvar js2-FUNCTION 108) ; function keyword
549 (defvar js2-EXPORT 109) ; export keyword
550 (defvar js2-IMPORT 110) ; import keyword
551 (defvar js2-IF 111) ; if keyword
552 (defvar js2-ELSE 112) ; else keyword
553 (defvar js2-SWITCH 113) ; switch keyword
554 (defvar js2-CASE 114) ; case keyword
555 (defvar js2-DEFAULT 115) ; default keyword
556 (defvar js2-WHILE 116) ; while keyword
557 (defvar js2-DO 117) ; do keyword
558 (defvar js2-FOR 118) ; for keyword
559 (defvar js2-BREAK 119) ; break keyword
560 (defvar js2-CONTINUE 120) ; continue keyword
561 (defvar js2-VAR 121) ; var keyword
562 (defvar js2-WITH 122) ; with keyword
563 (defvar js2-CATCH 123) ; catch keyword
564 (defvar js2-FINALLY 124) ; finally keyword
565 (defvar js2-VOID 125) ; void keyword
566 (defvar js2-RESERVED 126) ; reserved keywords
568 (defvar js2-EMPTY 127)
570 ;; Types used for the parse tree - never returned by scanner.
572 (defvar js2-BLOCK 128) ; statement block
573 (defvar js2-LABEL 129) ; label
574 (defvar js2-TARGET 130)
575 (defvar js2-LOOP 131)
576 (defvar js2-EXPR_VOID 132) ; expression statement in functions
577 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
579 (defvar js2-SCRIPT 135) ; top-level node for entire script
580 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
581 (defvar js2-USE_STACK 137)
582 (defvar js2-SETPROP_OP 138) ; x.y op= something
583 (defvar js2-SETELEM_OP 139) ; x[y] op= something
584 (defvar js2-LOCAL_BLOCK 140)
585 (defvar js2-SET_REF_OP 141) ; *reference op= something
588 (defvar js2-DOTDOT 142) ; member operator (..)
589 (defvar js2-COLONCOLON 143) ; namespace::name
590 (defvar js2-XML 144) ; XML type
591 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
592 (defvar js2-XMLATTR 146) ; @
593 (defvar js2-XMLEND 147)
595 ;; Optimizer-only tokens
596 (defvar js2-TO_OBJECT 148)
597 (defvar js2-TO_DOUBLE 149)
599 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
600 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
601 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
602 (defvar js2-CONST 153)
603 (defvar js2-SETCONST 154)
604 (defvar js2-SETCONSTVAR 155)
605 (defvar js2-ARRAYCOMP 156)
606 (defvar js2-LETEXPR 157)
607 (defvar js2-WITHEXPR 158)
608 (defvar js2-DEBUGGER 159)
610 (defvar js2-COMMENT 160)
611 (defvar js2-TRIPLEDOT 161) ; for rest parameter
612 (defvar js2-ARROW 162) ; function arrow (=>)
613 (defvar js2-CLASS 163)
614 (defvar js2-EXTENDS 164)
615 (defvar js2-SUPER 165)
616 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
617 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
618 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
620 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
622 (defconst js2-debug-print-trees nil)
624 ;; Rhino accepts any string or stream as input. Emacs character
625 ;; processing works best in buffers, so we'll assume the input is a
626 ;; buffer. JavaScript strings can be copied into temp buffers before
629 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
630 ;; They're the Emacs equivalent of instance variables, more or less.
632 (js2-deflocal js2-ts-dirty-line nil
633 "Token stream buffer-local variable.
634 Indicates stuff other than whitespace since start of line.")
636 (js2-deflocal js2-ts-hit-eof nil
637 "Token stream buffer-local variable.")
640 (js2-deflocal js2-ts-line-start 0
641 "Token stream buffer-local variable.")
643 (js2-deflocal js2-ts-lineno 1
644 "Token stream buffer-local variable.")
647 (js2-deflocal js2-ts-line-end-char -1
648 "Token stream buffer-local variable.")
650 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
651 "Token stream buffer-local variable.
652 Current scan position.")
655 (js2-deflocal js2-ts-is-xml-attribute nil
656 "Token stream buffer-local variable.")
658 (js2-deflocal js2-ts-xml-is-tag-content nil
659 "Token stream buffer-local variable.")
661 (js2-deflocal js2-ts-xml-open-tags-count 0
662 "Token stream buffer-local variable.")
664 (js2-deflocal js2-ts-string-buffer nil
665 "Token stream buffer-local variable.
666 List of chars built up while scanning various tokens.")
668 (cl-defstruct (js2-token
670 (:constructor make-js2-token (beg)))
671 "Value returned from the token stream."
678 number-legacy-octal-p
683 ;; Have to call `js2-init-scanner' to initialize the values.
684 (js2-deflocal js2-ti-tokens nil)
685 (js2-deflocal js2-ti-tokens-cursor nil)
686 (js2-deflocal js2-ti-lookahead nil)
688 (cl-defstruct (js2-ts-state
689 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
690 (cursor js2-ts-cursor)
691 (tokens (copy-sequence js2-ti-tokens))
692 (tokens-cursor js2-ti-tokens-cursor)
693 (lookahead js2-ti-lookahead))))
702 (js2-deflocal js2-parsed-errors nil
703 "List of errors produced during scanning/parsing.")
705 (js2-deflocal js2-parsed-warnings nil
706 "List of warnings produced during scanning/parsing.")
708 (js2-deflocal js2-recover-from-parse-errors t
709 "Non-nil to continue parsing after a syntax error.
711 In recovery mode, the AST will be built in full, and any error
712 nodes will be flagged with appropriate error information. If
713 this flag is nil, a syntax error will result in an error being
716 The variable is automatically buffer-local, because different
717 modes that use the parser will need different settings.")
719 (js2-deflocal js2-parse-hook nil
720 "List of callbacks for receiving parsing progress.")
722 (defvar js2-parse-finished-hook nil
723 "List of callbacks to notify when parsing finishes.
724 Not called if parsing was interrupted.")
726 (js2-deflocal js2-is-eval-code nil
727 "True if we're evaluating code in a string.
728 If non-nil, the tokenizer will record the token text, and the AST nodes
729 will record their source text. Off by default for IDE modes, since the
730 text is available in the buffer.")
732 (defvar js2-parse-ide-mode t
733 "Non-nil if the parser is being used for `js2-mode'.
734 If non-nil, the parser will set text properties for fontification
735 and the syntax table. The value should be nil when using the
736 parser as a frontend to an interpreter or byte compiler.")
738 ;;; Parser instance variables (buffer-local vars for js2-parse)
740 (defconst js2-ti-after-eol (lsh 1 16)
741 "Flag: first token of the source line.")
743 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
745 (js2-deflocal js2-compiler-generate-debug-info t)
746 (js2-deflocal js2-compiler-use-dynamic-scope nil)
747 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
748 (js2-deflocal js2-compiler-xml-available t)
749 (js2-deflocal js2-compiler-optimization-level 0)
750 (js2-deflocal js2-compiler-generating-source t)
751 (js2-deflocal js2-compiler-strict-mode nil)
752 (js2-deflocal js2-compiler-report-warning-as-error nil)
753 (js2-deflocal js2-compiler-generate-observer-count nil)
754 (js2-deflocal js2-compiler-activation-names nil)
758 ;; There's a compileFunction method in Context.java - may need it.
759 (js2-deflocal js2-called-by-compile-function nil
760 "True if `js2-parse' was called by `js2-compile-function'.
761 Will only be used when we finish implementing the interpreter.")
763 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
765 ;; SKIP: node factory - we're going to just call functions directly,
766 ;; and eventually go to a unified AST format.
768 (js2-deflocal js2-nesting-of-function 0)
770 (js2-deflocal js2-recorded-identifiers nil
771 "Tracks identifiers found during parsing.")
773 (js2-deflocal js2-is-in-destructuring nil
774 "True while parsing destructuring expression.")
776 (js2-deflocal js2-in-use-strict-directive nil
777 "True while inside a script or function under strict mode.")
779 (defcustom js2-global-externs nil
780 "A list of any extern names you'd like to consider always declared.
781 This list is global and is used by all `js2-mode' files.
782 You can create buffer-local externs list using `js2-additional-externs'.
784 There is also a buffer-local variable `js2-default-externs',
785 which is initialized by default to include the Ecma-262 externs
786 and the standard browser externs. The three lists are all
787 checked during highlighting."
791 (js2-deflocal js2-default-externs nil
792 "Default external declarations.
794 These are currently only used for highlighting undeclared variables,
795 which only worries about top-level (unqualified) references.
796 As js2-mode's processing improves, we will flesh out this list.
798 The initial value is set to `js2-ecma-262-externs', unless some
799 of the `js2-include-?-externs' variables are set to t, in which
800 case the browser, Rhino and/or Node.js externs are also included.
802 See `js2-additional-externs' for more information.")
804 (defcustom js2-include-browser-externs t
805 "Non-nil to include browser externs in the master externs list.
806 If you work on JavaScript files that are not intended for browsers,
807 such as Mozilla Rhino server-side JavaScript, set this to nil.
808 See `js2-additional-externs' for more information about externs."
812 (defcustom js2-include-rhino-externs nil
813 "Non-nil to include Mozilla Rhino externs in the master externs list.
814 See `js2-additional-externs' for more information about externs."
818 (defcustom js2-include-node-externs nil
819 "Non-nil to include Node.js externs in the master externs list.
820 See `js2-additional-externs' for more information about externs."
824 (js2-deflocal js2-additional-externs nil
825 "A buffer-local list of additional external declarations.
826 It is used to decide whether variables are considered undeclared
827 for purposes of highlighting.
829 Each entry is a Lisp string. The string should be the fully qualified
830 name of an external entity. All externs should be added to this list,
831 so that as js2-mode's processing improves it can take advantage of them.
833 You may want to declare your externs in three ways.
834 First, you can add externs that are valid for all your JavaScript files.
835 You should probably do this by adding them to `js2-global-externs', which
836 is a global list used for all js2-mode files.
838 Next, you can add a function to `js2-init-hook' that adds additional
839 externs appropriate for the specific file, perhaps based on its path.
840 These should go in `js2-additional-externs', which is buffer-local.
842 Third, you can use JSLint's global declaration, as long as
843 `js2-include-jslint-globals' is non-nil, which see.
845 Finally, you can add a function to `js2-post-parse-callbacks',
846 which is called after parsing completes, and `js2-mode-ast' is bound to
847 the root of the parse tree. At this stage you can set up an AST
848 node visitor using `js2-visit-ast' and examine the parse tree
849 for specific import patterns that may imply the existence of
850 other externs, possibly tied to your build system. These should also
851 be added to `js2-additional-externs'.
853 Your post-parse callback may of course also use the simpler and
854 faster (but perhaps less robust) approach of simply scanning the
855 buffer text for your imports, using regular expressions.")
858 ;; SKIP: encoded-source
860 ;;; The following variables are per-function and should be saved/restored
861 ;;; during function parsing...
863 (js2-deflocal js2-current-script-or-fn nil)
864 (js2-deflocal js2-current-scope nil)
865 (js2-deflocal js2-nesting-of-with 0)
866 (js2-deflocal js2-label-set nil
867 "An alist mapping label names to nodes.")
869 (js2-deflocal js2-loop-set nil)
870 (js2-deflocal js2-loop-and-switch-set nil)
871 (js2-deflocal js2-has-return-value nil)
872 (js2-deflocal js2-end-flags 0)
874 ;;; ...end of per function variables
876 ;; These flags enumerate the possible ways a statement/function can
877 ;; terminate. These flags are used by endCheck() and by the Parser to
878 ;; detect inconsistent return usage.
880 ;; END_UNREACHED is reserved for code paths that are assumed to always be
881 ;; able to execute (example: throw, continue)
883 ;; END_DROPS_OFF indicates if the statement can transfer control to the
884 ;; next one. Statement such as return dont. A compound statement may have
885 ;; some branch that drops off control to the next statement.
887 ;; END_RETURNS indicates that the statement can return (without arguments)
888 ;; END_RETURNS_VALUE indicates that the statement can return a value.
890 ;; A compound statement such as
894 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
896 (defconst js2-end-unreached #x0)
897 (defconst js2-end-drops-off #x1)
898 (defconst js2-end-returns #x2)
899 (defconst js2-end-returns-value #x4)
901 ;; Rhino awkwardly passes a statementLabel parameter to the
902 ;; statementHelper() function, the main statement parser, which
903 ;; is then used by quite a few of the sub-parsers. We just make
904 ;; it a buffer-local variable and make sure it's cleaned up properly.
905 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
907 ;; Similarly, Rhino passes an inForInit boolean through about half
908 ;; the expression parsers. We use a dynamically-scoped variable,
909 ;; which makes it easier to funcall the parsers individually without
910 ;; worrying about whether they take the parameter or not.
911 (js2-deflocal js2-in-for-init nil)
912 (js2-deflocal js2-temp-name-counter 0)
913 (js2-deflocal js2-parse-stmt-count 0)
915 (defsubst js2-get-next-temp-name ()
916 (format "$%d" (cl-incf js2-temp-name-counter)))
918 (defvar js2-parse-interruptable-p t
919 "Set this to nil to force parse to continue until finished.
920 This will mostly be useful for interpreters.")
922 (defvar js2-statements-per-pause 50
923 "Pause after this many statements to check for user input.
924 If user input is pending, stop the parse and discard the tree.
925 This makes for a smoother user experience for large files.
926 You may have to wait a second or two before the highlighting
927 and error-reporting appear, but you can always type ahead if
928 you wish. This appears to be more or less how Eclipse, IntelliJ
929 and other editors work.")
931 (js2-deflocal js2-record-comments t
932 "Instructs the scanner to record comments in `js2-scanned-comments'.")
934 (js2-deflocal js2-scanned-comments nil
935 "List of all comments from the current parse.")
937 (defcustom js2-mode-indent-inhibit-undo nil
938 "Non-nil to disable collection of Undo information when indenting lines.
939 Some users have requested this behavior. It's nil by default because
940 other Emacs modes don't work this way."
944 (defcustom js2-mode-indent-ignore-first-tab nil
945 "If non-nil, ignore first TAB keypress if we look indented properly.
946 It's fairly common for users to navigate to an already-indented line
947 and press TAB for reassurance that it's been indented. For this class
948 of users, we want the first TAB press on a line to be ignored if the
949 line is already indented to one of the precomputed alternatives.
951 This behavior is only partly implemented. If you TAB-indent a line,
952 navigate to another line, and then navigate back, it fails to clear
953 the last-indented variable, so it thinks you've already hit TAB once,
954 and performs the indent. A full solution would involve getting on the
955 point-motion hooks for the entire buffer. If we come across another
956 use cases that requires watching point motion, I'll consider doing it.
958 If you set this variable to nil, then the TAB key will always change
959 the indentation of the current line, if more than one alternative
960 indentation spot exists."
964 (defvar js2-indent-hook nil
965 "A hook for user-defined indentation rules.
967 Functions on this hook should expect two arguments: (LIST INDEX)
968 The LIST argument is the list of computed indentation points for
969 the current line. INDEX is the list index of the indentation point
970 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
971 indent function is not going to change the current line indentation.
973 If a hook function on this list returns a non-nil value, then
974 `js2-bounce-indent' assumes the hook function has performed its own
975 indentation, and will do nothing. If all hook functions on the list
976 return nil, then `js2-bounce-indent' will use its computed indentation
977 and reindent the line.
979 When hook functions on this hook list are called, the variable
980 `js2-mode-ast' may or may not be set, depending on whether the
981 parse tree is available. If the variable is nil, you can pass a
982 callback to `js2-mode-wait-for-parse', and your callback will be
983 called after the new parse tree is built. This can take some time
987 `((((class color) (background light))
988 (:underline "orange"))
989 (((class color) (background dark))
990 (:underline "orange"))
992 "Face for JavaScript warnings."
996 `((((class color) (background light))
998 (((class color) (background dark))
1000 (t (:foreground "red")))
1001 "Face for JavaScript errors."
1004 (defface js2-jsdoc-tag
1005 '((t :foreground "SlateGray"))
1006 "Face used to highlight @whatever tags in jsdoc comments."
1009 (defface js2-jsdoc-type
1010 '((t :foreground "SteelBlue"))
1011 "Face used to highlight {FooBar} types in jsdoc comments."
1014 (defface js2-jsdoc-value
1015 '((t :foreground "PeachPuff3"))
1016 "Face used to highlight tag values in jsdoc comments."
1019 (defface js2-function-param
1020 '((t :foreground "SeaGreen"))
1021 "Face used to highlight function parameters in javascript."
1024 (defface js2-function-call
1025 '((t :inherit default))
1026 "Face used to highlight function name in calls."
1029 (defface js2-object-property
1030 '((t :inherit default))
1031 "Face used to highlight named property in object literal."
1034 (defface js2-instance-member
1035 '((t :foreground "DarkOrchid"))
1036 "Face used to highlight instance variables in javascript.
1037 Not currently used."
1040 (defface js2-private-member
1041 '((t :foreground "PeachPuff3"))
1042 "Face used to highlight calls to private methods in javascript.
1043 Not currently used."
1046 (defface js2-private-function-call
1047 '((t :foreground "goldenrod"))
1048 "Face used to highlight calls to private functions in javascript.
1049 Not currently used."
1052 (defface js2-jsdoc-html-tag-name
1053 '((((class color) (min-colors 88) (background light))
1054 (:foreground "rosybrown"))
1055 (((class color) (min-colors 8) (background dark))
1056 (:foreground "yellow"))
1057 (((class color) (min-colors 8) (background light))
1058 (:foreground "magenta")))
1059 "Face used to highlight jsdoc html tag names"
1062 (defface js2-jsdoc-html-tag-delimiter
1063 '((((class color) (min-colors 88) (background light))
1064 (:foreground "dark khaki"))
1065 (((class color) (min-colors 8) (background dark))
1066 (:foreground "green"))
1067 (((class color) (min-colors 8) (background light))
1068 (:foreground "green")))
1069 "Face used to highlight brackets in jsdoc html tags."
1072 (defface js2-external-variable
1073 '((t :foreground "orange"))
1074 "Face used to highlight undeclared variable identifiers.")
1076 (defcustom js2-init-hook nil
1077 "List of functions to be called after `js2-mode' or
1078 `js2-minor-mode' has initialized all variables, before parsing
1079 the buffer for the first time."
1082 :version "20130608")
1084 (defcustom js2-post-parse-callbacks nil
1085 "List of callback functions invoked after parsing finishes.
1086 Currently, the main use for this function is to add synthetic
1087 declarations to `js2-recorded-identifiers', which see."
1091 (defcustom js2-build-imenu-callbacks nil
1092 "List of functions called during Imenu index generation.
1093 It's a good place to add additional entries to it, using
1094 `js2-record-imenu-entry'."
1098 (defcustom js2-highlight-external-variables t
1099 "Non-nil to highlight undeclared variable identifiers.
1100 An undeclared variable is any variable not declared with var or let
1101 in the current scope or any lexically enclosing scope. If you use
1102 such a variable, then you are either expecting it to originate from
1103 another file, or you've got a potential bug."
1107 (defcustom js2-warn-about-unused-function-arguments nil
1108 "Non-nil to treat function arguments like declared-but-unused variables."
1112 (defcustom js2-include-jslint-globals t
1113 "Non-nil to include the identifiers from JSLint global
1114 declaration (see http://www.jslint.com/lint.html#global) in the
1115 buffer-local externs list. See `js2-additional-externs' for more
1120 (defvar js2-mode-map
1121 (let ((map (make-sparse-keymap)))
1122 (define-key map [mouse-1] #'js2-mode-show-node)
1123 (define-key map (kbd "M-j") #'js2-line-break)
1124 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1125 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1126 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1127 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1128 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1129 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1130 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1131 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1132 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1134 (define-key map [menu-bar javascript]
1135 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1137 (define-key map [menu-bar javascript customize-js2-mode]
1138 '(menu-item "Customize js2-mode" js2-mode-customize
1139 :help "Customize the behavior of this mode"))
1141 (define-key map [menu-bar javascript js2-force-refresh]
1142 '(menu-item "Force buffer refresh" js2-mode-reset
1143 :help "Re-parse the buffer from scratch"))
1145 (define-key map [menu-bar javascript separator-2]
1148 (define-key map [menu-bar javascript next-error]
1149 '(menu-item "Next warning or error" next-error
1150 :enabled (and js2-mode-ast
1151 (or (js2-ast-root-errors js2-mode-ast)
1152 (js2-ast-root-warnings js2-mode-ast)))
1153 :help "Move to next warning or error"))
1155 (define-key map [menu-bar javascript display-errors]
1156 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1157 :visible (not js2-mode-show-parse-errors)
1158 :help "Turn on display of warnings and errors"))
1160 (define-key map [menu-bar javascript hide-errors]
1161 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1162 :visible js2-mode-show-parse-errors
1163 :help "Turn off display of warnings and errors"))
1165 (define-key map [menu-bar javascript separator-1]
1168 (define-key map [menu-bar javascript js2-toggle-function]
1169 '(menu-item "Show/collapse element" js2-mode-toggle-element
1170 :help "Hide or show function body or comment"))
1172 (define-key map [menu-bar javascript show-comments]
1173 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1174 :visible js2-mode-comments-hidden
1175 :help "Expand all hidden block comments"))
1177 (define-key map [menu-bar javascript hide-comments]
1178 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1179 :visible (not js2-mode-comments-hidden)
1180 :help "Show block comments as /*...*/"))
1182 (define-key map [menu-bar javascript show-all-functions]
1183 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1184 :visible js2-mode-functions-hidden
1185 :help "Expand all hidden function bodies"))
1187 (define-key map [menu-bar javascript hide-all-functions]
1188 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1189 :visible (not js2-mode-functions-hidden)
1190 :help "Show {...} for all top-level function bodies"))
1193 "Keymap used in `js2-mode' buffers.")
1195 (defcustom js2-bounce-indent-p nil
1196 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1197 They will augment the default indent-line behavior with cycling
1198 among several computed alternatives. See the function
1199 `js2-bounce-indent' for details. The above commands will be
1200 bound to TAB and backtab."
1203 :set (lambda (sym value)
1204 (set-default sym value)
1205 (let ((map js2-mode-map))
1208 (define-key map "\t" nil)
1209 (define-key map (kbd "<backtab>") nil))
1210 (define-key map "\t" #'js2-indent-bounce)
1211 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1213 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1215 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1216 "Matches a //-comment line. Must be first non-whitespace on line.
1217 First match-group is the leading whitespace.")
1219 (defvar js2-mode-hook nil)
1221 (js2-deflocal js2-mode-ast nil "Private variable.")
1222 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1223 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1224 (js2-deflocal js2-mode-parsing nil "Private variable.")
1225 (js2-deflocal js2-mode-node-overlay nil)
1227 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1228 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1230 (js2-deflocal js2-mode-fontifications nil "Private variable")
1231 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1232 (js2-deflocal js2-imenu-recorder nil "Private variable")
1233 (js2-deflocal js2-imenu-function-map nil "Private variable")
1235 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1236 "Non-nil to emit status messages during parsing.")
1238 (defvar js2-mode-functions-hidden nil "Private variable.")
1239 (defvar js2-mode-comments-hidden nil "Private variable.")
1241 (defvar js2-mode-syntax-table
1242 (let ((table (make-syntax-table)))
1243 (c-populate-syntax-table table)
1244 (modify-syntax-entry ?` "\"" table)
1246 "Syntax table used in `js2-mode' buffers.")
1248 (defvar js2-mode-abbrev-table nil
1249 "Abbrev table in use in `js2-mode' buffers.")
1250 (define-abbrev-table 'js2-mode-abbrev-table ())
1252 (defvar js2-mode-pending-parse-callbacks nil
1253 "List of functions waiting to be notified that parse is finished.")
1255 (defvar js2-mode-last-indented-line -1)
1257 ;;; Localizable error and warning messages
1259 ;; Messages are copied from Rhino's Messages.properties.
1260 ;; Many of the Java-specific messages have been elided.
1261 ;; Add any js2-specific ones at the end, so we can keep
1262 ;; this file synced with changes to Rhino's.
1264 (defvar js2-message-table
1265 (make-hash-table :test 'equal :size 250)
1266 "Contains localized messages for `js2-mode'.")
1268 ;; TODO(stevey): construct this table at compile-time.
1269 (defmacro js2-msg (key &rest strings)
1270 `(puthash ,key (concat ,@strings)
1273 (defun js2-get-msg (msg-key)
1274 "Look up a localized message.
1275 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1276 the correct number of ARGS must be provided."
1277 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1278 (args (if (listp msg-key) (cdr msg-key)))
1279 (msg (gethash key js2-message-table)))
1281 (apply #'format msg args)
1282 key))) ; default to showing the key
1284 (js2-msg "msg.dup.parms"
1285 "Duplicate parameter name '%s'.")
1287 (js2-msg "msg.too.big.jump"
1288 "Program too complex: jump offset too big.")
1290 (js2-msg "msg.too.big.index"
1291 "Program too complex: internal index exceeds 64K limit.")
1293 (js2-msg "msg.while.compiling.fn"
1294 "Encountered code generation error while compiling function '%s': %s")
1296 (js2-msg "msg.while.compiling.script"
1297 "Encountered code generation error while compiling script: %s")
1300 (js2-msg "msg.ctor.not.found"
1301 "Constructor for '%s' not found.")
1303 (js2-msg "msg.not.ctor"
1304 "'%s' is not a constructor.")
1307 (js2-msg "msg.varargs.ctor"
1308 "Method or constructor '%s' must be static "
1309 "with the signature (Context cx, Object[] args, "
1310 "Function ctorObj, boolean inNewExpr) "
1311 "to define a variable arguments constructor.")
1313 (js2-msg "msg.varargs.fun"
1314 "Method '%s' must be static with the signature "
1315 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1316 "to define a variable arguments function.")
1318 (js2-msg "msg.incompat.call"
1319 "Method '%s' called on incompatible object.")
1321 (js2-msg "msg.bad.parms"
1322 "Unsupported parameter type '%s' in method '%s'.")
1324 (js2-msg "msg.bad.method.return"
1325 "Unsupported return type '%s' in method '%s'.")
1327 (js2-msg "msg.bad.ctor.return"
1328 "Construction of objects of type '%s' is not supported.")
1330 (js2-msg "msg.no.overload"
1331 "Method '%s' occurs multiple times in class '%s'.")
1333 (js2-msg "msg.method.not.found"
1334 "Method '%s' not found in '%s'.")
1338 (js2-msg "msg.bad.for.in.lhs"
1339 "Invalid left-hand side of for..in loop.")
1341 (js2-msg "msg.mult.index"
1342 "Only one variable allowed in for..in loop.")
1344 (js2-msg "msg.bad.for.in.destruct"
1345 "Left hand side of for..in loop must be an array of "
1346 "length 2 to accept key/value pair.")
1348 (js2-msg "msg.cant.convert"
1349 "Can't convert to type '%s'.")
1351 (js2-msg "msg.bad.assign.left"
1352 "Invalid assignment left-hand side.")
1354 (js2-msg "msg.bad.decr"
1355 "Invalid decrement operand.")
1357 (js2-msg "msg.bad.incr"
1358 "Invalid increment operand.")
1360 (js2-msg "msg.bad.yield"
1361 "yield must be in a function.")
1363 (js2-msg "msg.yield.parenthesized"
1364 "yield expression must be parenthesized.")
1367 (js2-msg "msg.cant.call.indirect"
1368 "Function '%s' must be called directly, and not by way of a "
1369 "function of another name.")
1371 (js2-msg "msg.eval.nonstring"
1372 "Calling eval() with anything other than a primitive "
1373 "string value will simply return the value. "
1374 "Is this what you intended?")
1376 (js2-msg "msg.eval.nonstring.strict"
1377 "Calling eval() with anything other than a primitive "
1378 "string value is not allowed in strict mode.")
1380 (js2-msg "msg.bad.destruct.op"
1381 "Invalid destructuring assignment operator")
1384 (js2-msg "msg.only.from.new"
1385 "'%s' may only be invoked from a `new' expression.")
1387 (js2-msg "msg.deprec.ctor"
1388 "The '%s' constructor is deprecated.")
1391 (js2-msg "msg.no.function.ref.found"
1392 "no source found to decompile function reference %s")
1394 (js2-msg "msg.arg.isnt.array"
1395 "second argument to Function.prototype.apply must be an array")
1398 (js2-msg "msg.bad.esc.mask"
1399 "invalid string escape mask")
1402 (js2-msg "msg.bad.quant"
1403 "Invalid quantifier %s")
1405 (js2-msg "msg.overlarge.backref"
1406 "Overly large back reference %s")
1408 (js2-msg "msg.overlarge.min"
1409 "Overly large minimum %s")
1411 (js2-msg "msg.overlarge.max"
1412 "Overly large maximum %s")
1414 (js2-msg "msg.zero.quant"
1415 "Zero quantifier %s")
1417 (js2-msg "msg.max.lt.min"
1418 "Maximum %s less than minimum")
1420 (js2-msg "msg.unterm.quant"
1421 "Unterminated quantifier %s")
1423 (js2-msg "msg.unterm.paren"
1424 "Unterminated parenthetical %s")
1426 (js2-msg "msg.unterm.class"
1427 "Unterminated character class %s")
1429 (js2-msg "msg.bad.range"
1430 "Invalid range in character class.")
1432 (js2-msg "msg.trail.backslash"
1433 "Trailing \\ in regular expression.")
1435 (js2-msg "msg.re.unmatched.right.paren"
1436 "unmatched ) in regular expression.")
1438 (js2-msg "msg.no.regexp"
1439 "Regular expressions are not available.")
1441 (js2-msg "msg.bad.backref"
1442 "back-reference exceeds number of capturing parentheses.")
1444 (js2-msg "msg.bad.regexp.compile"
1445 "Only one argument may be specified if the first "
1446 "argument to RegExp.prototype.compile is a RegExp object.")
1449 (js2-msg "msg.got.syntax.errors"
1450 "Compilation produced %s syntax errors.")
1452 (js2-msg "msg.var.redecl"
1453 "TypeError: redeclaration of var %s.")
1455 (js2-msg "msg.const.redecl"
1456 "TypeError: redeclaration of const %s.")
1458 (js2-msg "msg.let.redecl"
1459 "TypeError: redeclaration of variable %s.")
1461 (js2-msg "msg.parm.redecl"
1462 "TypeError: redeclaration of formal parameter %s.")
1464 (js2-msg "msg.fn.redecl"
1465 "TypeError: redeclaration of function %s.")
1467 (js2-msg "msg.let.decl.not.in.block"
1468 "SyntaxError: let declaration not directly within block")
1470 (js2-msg "msg.mod.import.decl.at.top.level"
1471 "SyntaxError: import declarations may only appear at the top level")
1473 (js2-msg "msg.mod.as.after.reserved.word"
1474 "SyntaxError: missing keyword 'as' after reserved word %s")
1476 (js2-msg "msg.mod.rc.after.import.spec.list"
1477 "SyntaxError: missing '}' after module specifier list")
1479 (js2-msg "msg.mod.from.after.import.spec.set"
1480 "SyntaxError: missing keyword 'from' after import specifier set")
1482 (js2-msg "msg.mod.declaration.after.import"
1483 "SyntaxError: missing declaration after 'import' keyword")
1485 (js2-msg "msg.mod.spec.after.from"
1486 "SyntaxError: missing module specifier after 'from' keyword")
1488 (js2-msg "msg.mod.export.decl.at.top.level"
1489 "SyntaxError: export declarations may only appear at top level")
1491 (js2-msg "msg.mod.rc.after.export.spec.list"
1492 "SyntaxError: missing '}' after export specifier list")
1495 (js2-msg "msg.dup.label"
1498 (js2-msg "msg.undef.label"
1501 (js2-msg "msg.bad.break"
1502 "unlabelled break must be inside loop or switch")
1504 (js2-msg "msg.continue.outside"
1505 "continue must be inside loop")
1507 (js2-msg "msg.continue.nonloop"
1508 "continue can only use labels of iteration statements")
1510 (js2-msg "msg.bad.throw.eol"
1511 "Line terminator is not allowed between the throw "
1512 "keyword and throw expression.")
1514 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1515 "function statement requires a name")
1517 (js2-msg "msg.no.paren.parms"
1518 "missing ( before function parameters.")
1520 (js2-msg "msg.no.parm"
1521 "missing formal parameter")
1523 (js2-msg "msg.no.paren.after.parms"
1524 "missing ) after formal parameters")
1526 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1527 "parameter without default follows parameter with default")
1529 (js2-msg "msg.param.after.rest" ; added by js2-mode
1530 "parameter after rest parameter")
1532 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1533 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1535 (js2-msg "msg.no.brace.body"
1536 "missing '{' before function body")
1538 (js2-msg "msg.no.brace.after.body"
1539 "missing } after function body")
1541 (js2-msg "msg.no.paren.cond"
1542 "missing ( before condition")
1544 (js2-msg "msg.no.paren.after.cond"
1545 "missing ) after condition")
1547 (js2-msg "msg.no.semi.stmt"
1548 "missing ; before statement")
1550 (js2-msg "msg.missing.semi"
1551 "missing ; after statement")
1553 (js2-msg "msg.no.name.after.dot"
1554 "missing name after . operator")
1556 (js2-msg "msg.no.name.after.coloncolon"
1557 "missing name after :: operator")
1559 (js2-msg "msg.no.name.after.dotdot"
1560 "missing name after .. operator")
1562 (js2-msg "msg.no.name.after.xmlAttr"
1563 "missing name after .@")
1565 (js2-msg "msg.no.bracket.index"
1566 "missing ] in index expression")
1568 (js2-msg "msg.no.paren.switch"
1569 "missing ( before switch expression")
1571 (js2-msg "msg.no.paren.after.switch"
1572 "missing ) after switch expression")
1574 (js2-msg "msg.no.brace.switch"
1575 "missing '{' before switch body")
1577 (js2-msg "msg.bad.switch"
1578 "invalid switch statement")
1580 (js2-msg "msg.no.colon.case"
1581 "missing : after case expression")
1583 (js2-msg "msg.double.switch.default"
1584 "double default label in the switch statement")
1586 (js2-msg "msg.no.while.do"
1587 "missing while after do-loop body")
1589 (js2-msg "msg.no.paren.for"
1590 "missing ( after for")
1592 (js2-msg "msg.no.semi.for"
1593 "missing ; after for-loop initializer")
1595 (js2-msg "msg.no.semi.for.cond"
1596 "missing ; after for-loop condition")
1598 (js2-msg "msg.in.after.for.name"
1599 "missing in or of after for")
1601 (js2-msg "msg.no.paren.for.ctrl"
1602 "missing ) after for-loop control")
1604 (js2-msg "msg.no.paren.with"
1605 "missing ( before with-statement object")
1607 (js2-msg "msg.no.paren.after.with"
1608 "missing ) after with-statement object")
1610 (js2-msg "msg.no.with.strict"
1611 "with statements not allowed in strict mode")
1613 (js2-msg "msg.no.paren.after.let"
1614 "missing ( after let")
1616 (js2-msg "msg.no.paren.let"
1617 "missing ) after variable list")
1619 (js2-msg "msg.no.curly.let"
1620 "missing } after let statement")
1622 (js2-msg "msg.bad.return"
1625 (js2-msg "msg.no.brace.block"
1626 "missing } in compound statement")
1628 (js2-msg "msg.bad.label"
1631 (js2-msg "msg.bad.var"
1632 "missing variable name")
1634 (js2-msg "msg.bad.var.init"
1635 "invalid variable initialization")
1637 (js2-msg "msg.no.colon.cond"
1638 "missing : in conditional expression")
1640 (js2-msg "msg.no.paren.arg"
1641 "missing ) after argument list")
1643 (js2-msg "msg.no.bracket.arg"
1644 "missing ] after element list")
1646 (js2-msg "msg.bad.prop"
1647 "invalid property id")
1649 (js2-msg "msg.no.colon.prop"
1650 "missing : after property id")
1652 (js2-msg "msg.no.brace.prop"
1653 "missing } after property list")
1655 (js2-msg "msg.no.paren"
1656 "missing ) in parenthetical")
1658 (js2-msg "msg.reserved.id"
1659 "'%s' is a reserved identifier")
1661 (js2-msg "msg.no.paren.catch"
1662 "missing ( before catch-block condition")
1664 (js2-msg "msg.bad.catchcond"
1665 "invalid catch block condition")
1667 (js2-msg "msg.catch.unreachable"
1668 "any catch clauses following an unqualified catch are unreachable")
1670 (js2-msg "msg.no.brace.try"
1671 "missing '{' before try block")
1673 (js2-msg "msg.no.brace.catchblock"
1674 "missing '{' before catch-block body")
1676 (js2-msg "msg.try.no.catchfinally"
1677 "'try' without 'catch' or 'finally'")
1679 (js2-msg "msg.no.return.value"
1680 "function %s does not always return a value")
1682 (js2-msg "msg.anon.no.return.value"
1683 "anonymous function does not always return a value")
1685 (js2-msg "msg.return.inconsistent"
1686 "return statement is inconsistent with previous usage")
1688 (js2-msg "msg.generator.returns"
1689 "TypeError: legacy generator function '%s' returns a value")
1691 (js2-msg "msg.anon.generator.returns"
1692 "TypeError: anonymous legacy generator function returns a value")
1694 (js2-msg "msg.syntax"
1697 (js2-msg "msg.unexpected.eof"
1698 "Unexpected end of file")
1700 (js2-msg "msg.XML.bad.form"
1701 "illegally formed XML syntax")
1703 (js2-msg "msg.XML.not.available"
1704 "XML runtime not available")
1706 (js2-msg "msg.too.deep.parser.recursion"
1707 "Too deep recursion while parsing")
1709 (js2-msg "msg.no.side.effects"
1710 "Code has no side effects")
1712 (js2-msg "msg.extra.trailing.comma"
1713 "Trailing comma is not supported in some browsers")
1715 (js2-msg "msg.array.trailing.comma"
1716 "Trailing comma yields different behavior across browsers")
1718 (js2-msg "msg.equal.as.assign"
1719 (concat "Test for equality (==) mistyped as assignment (=)?"
1720 " (parenthesize to suppress warning)"))
1722 (js2-msg "msg.var.hides.arg"
1723 "Variable %s hides argument")
1725 (js2-msg "msg.destruct.assign.no.init"
1726 "Missing = in destructuring declaration")
1728 (js2-msg "msg.init.no.destruct"
1729 "Binding initializer not in destructuring assignment")
1731 (js2-msg "msg.no.octal.strict"
1732 "Octal numbers prohibited in strict mode.")
1734 (js2-msg "msg.dup.obj.lit.prop.strict"
1735 "Property '%s' already defined in this object literal.")
1737 (js2-msg "msg.dup.param.strict"
1738 "Parameter '%s' already declared in this function.")
1740 (js2-msg "msg.bad.id.strict"
1741 "'%s' is not a valid identifier for this use in strict mode.")
1744 (js2-msg "msg.no.properties"
1745 "%s has no properties.")
1747 (js2-msg "msg.invalid.iterator"
1748 "Invalid iterator value")
1750 (js2-msg "msg.iterator.primitive"
1751 "__iterator__ returned a primitive value")
1753 (js2-msg "msg.assn.create.strict"
1754 "Assignment to undeclared variable %s")
1756 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1757 "Undeclared variable or function '%s'")
1759 (js2-msg "msg.unused.variable" ; added by js2-mode
1760 "Unused variable or function '%s'")
1762 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1763 "Variable '%s' referenced but never initialized")
1765 (js2-msg "msg.ref.undefined.prop"
1766 "Reference to undefined property '%s'")
1768 (js2-msg "msg.prop.not.found"
1769 "Property %s not found.")
1771 (js2-msg "msg.invalid.type"
1772 "Invalid JavaScript value of type %s")
1774 (js2-msg "msg.primitive.expected"
1775 "Primitive type expected (had %s instead)")
1777 (js2-msg "msg.namespace.expected"
1778 "Namespace object expected to left of :: (found %s instead)")
1780 (js2-msg "msg.null.to.object"
1781 "Cannot convert null to an object.")
1783 (js2-msg "msg.undef.to.object"
1784 "Cannot convert undefined to an object.")
1786 (js2-msg "msg.cyclic.value"
1787 "Cyclic %s value not allowed.")
1789 (js2-msg "msg.is.not.defined"
1790 "'%s' is not defined.")
1792 (js2-msg "msg.undef.prop.read"
1793 "Cannot read property '%s' from %s")
1795 (js2-msg "msg.undef.prop.write"
1796 "Cannot set property '%s' of %s to '%s'")
1798 (js2-msg "msg.undef.prop.delete"
1799 "Cannot delete property '%s' of %s")
1801 (js2-msg "msg.undef.method.call"
1802 "Cannot call method '%s' of %s")
1804 (js2-msg "msg.undef.with"
1805 "Cannot apply 'with' to %s")
1807 (js2-msg "msg.isnt.function"
1808 "%s is not a function, it is %s.")
1810 (js2-msg "msg.isnt.function.in"
1811 "Cannot call property %s in object %s. "
1812 "It is not a function, it is '%s'.")
1814 (js2-msg "msg.function.not.found"
1815 "Cannot find function %s.")
1817 (js2-msg "msg.function.not.found.in"
1818 "Cannot find function %s in object %s.")
1820 (js2-msg "msg.isnt.xml.object"
1821 "%s is not an xml object.")
1823 (js2-msg "msg.no.ref.to.get"
1824 "%s is not a reference to read reference value.")
1826 (js2-msg "msg.no.ref.to.set"
1827 "%s is not a reference to set reference value to %s.")
1829 (js2-msg "msg.no.ref.from.function"
1830 "Function %s can not be used as the left-hand "
1831 "side of assignment or as an operand of ++ or -- operator.")
1833 (js2-msg "msg.bad.default.value"
1834 "Object's getDefaultValue() method returned an object.")
1836 (js2-msg "msg.instanceof.not.object"
1837 "Can't use instanceof on a non-object.")
1839 (js2-msg "msg.instanceof.bad.prototype"
1840 "'prototype' property of %s is not an object.")
1842 (js2-msg "msg.bad.radix"
1843 "illegal radix %s.")
1846 (js2-msg "msg.default.value"
1847 "Cannot find default value for object.")
1849 (js2-msg "msg.zero.arg.ctor"
1850 "Cannot load class '%s' which has no zero-parameter constructor.")
1852 (js2-msg "msg.ctor.multiple.parms"
1853 "Can't define constructor or class %s since more than "
1854 "one constructor has multiple parameters.")
1856 (js2-msg "msg.extend.scriptable"
1857 "%s must extend ScriptableObject in order to define property %s.")
1859 (js2-msg "msg.bad.getter.parms"
1860 "In order to define a property, getter %s must have zero "
1861 "parameters or a single ScriptableObject parameter.")
1863 (js2-msg "msg.obj.getter.parms"
1864 "Expected static or delegated getter %s to take "
1865 "a ScriptableObject parameter.")
1867 (js2-msg "msg.getter.static"
1868 "Getter and setter must both be static or neither be static.")
1870 (js2-msg "msg.setter.return"
1871 "Setter must have void return type: %s")
1873 (js2-msg "msg.setter2.parms"
1874 "Two-parameter setter must take a ScriptableObject as "
1875 "its first parameter.")
1877 (js2-msg "msg.setter1.parms"
1878 "Expected single parameter setter for %s")
1880 (js2-msg "msg.setter2.expected"
1881 "Expected static or delegated setter %s to take two parameters.")
1883 (js2-msg "msg.setter.parms"
1884 "Expected either one or two parameters for setter.")
1886 (js2-msg "msg.setter.bad.type"
1887 "Unsupported parameter type '%s' in setter '%s'.")
1889 (js2-msg "msg.add.sealed"
1890 "Cannot add a property to a sealed object: %s.")
1892 (js2-msg "msg.remove.sealed"
1893 "Cannot remove a property from a sealed object: %s.")
1895 (js2-msg "msg.modify.sealed"
1896 "Cannot modify a property of a sealed object: %s.")
1898 (js2-msg "msg.modify.readonly"
1899 "Cannot modify readonly property: %s.")
1902 (js2-msg "msg.missing.exponent"
1905 (js2-msg "msg.caught.nfe"
1906 "number format error")
1908 (js2-msg "msg.unterminated.string.lit"
1909 "unterminated string literal")
1911 (js2-msg "msg.unterminated.comment"
1912 "unterminated comment")
1914 (js2-msg "msg.unterminated.re.lit"
1915 "unterminated regular expression literal")
1917 (js2-msg "msg.invalid.re.flag"
1918 "invalid flag after regular expression")
1920 (js2-msg "msg.no.re.input.for"
1923 (js2-msg "msg.illegal.character"
1924 "illegal character")
1926 (js2-msg "msg.invalid.escape"
1927 "invalid Unicode escape sequence")
1929 (js2-msg "msg.bad.namespace"
1930 "not a valid default namespace statement. "
1931 "Syntax is: default xml namespace = EXPRESSION;")
1933 ;; TokensStream warnings
1934 (js2-msg "msg.bad.octal.literal"
1935 "illegal octal literal digit %s; "
1936 "interpreting it as a decimal digit")
1938 (js2-msg "msg.missing.hex.digits"
1939 "missing hexadecimal digits after '0x'")
1941 (js2-msg "msg.missing.binary.digits"
1942 "missing binary digits after '0b'")
1944 (js2-msg "msg.missing.octal.digits"
1945 "missing octal digits after '0o'")
1947 (js2-msg "msg.script.is.not.constructor"
1948 "Script objects are not constructors.")
1951 (js2-msg "msg.arraylength.bad"
1952 "Inappropriate array length.")
1955 (js2-msg "msg.arraylength.too.big"
1956 "Array length %s exceeds supported capacity limit.")
1959 (js2-msg "msg.bad.uri"
1960 "Malformed URI sequence.")
1963 (js2-msg "msg.bad.precision"
1964 "Precision %s out of range.")
1967 (js2-msg "msg.send.newborn"
1968 "Attempt to send value to newborn generator")
1970 (js2-msg "msg.already.exec.gen"
1971 "Already executing generator")
1973 (js2-msg "msg.StopIteration.invalid"
1974 "StopIteration may not be changed to an arbitrary object.")
1977 (js2-msg "msg.yield.closing"
1978 "Yield from closing generator")
1981 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1982 "class statement requires a name")
1984 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1985 "unexpected ',' between class properties")
1987 (js2-msg "msg.unexpected.static" ; added by js2-mode
1988 "unexpected 'static'")
1990 (js2-msg "msg.missing.extends" ; added by js2-mode
1991 "name is required after extends")
1993 (js2-msg "msg.no.brace.class" ; added by js2-mode
1994 "missing '{' before class body")
1996 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1997 "missing ']' after computed property expression")
2001 (defconst js2-ti-max-lookahead 2)
2002 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2004 (defun js2-new-token (offset)
2005 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2006 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2007 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2010 (defsubst js2-current-token ()
2011 (aref js2-ti-tokens js2-ti-tokens-cursor))
2013 (defsubst js2-current-token-string ()
2014 (js2-token-string (js2-current-token)))
2016 (defsubst js2-current-token-type ()
2017 (js2-token-type (js2-current-token)))
2019 (defsubst js2-current-token-beg ()
2020 (js2-token-beg (js2-current-token)))
2022 (defsubst js2-current-token-end ()
2023 (js2-token-end (js2-current-token)))
2025 (defun js2-current-token-len ()
2026 (let ((token (js2-current-token)))
2027 (- (js2-token-end token)
2028 (js2-token-beg token))))
2030 (defun js2-ts-seek (state)
2031 (setq js2-ts-lineno (js2-ts-state-lineno state)
2032 js2-ts-cursor (js2-ts-state-cursor state)
2033 js2-ti-tokens (js2-ts-state-tokens state)
2034 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2035 js2-ti-lookahead (js2-ts-state-lookahead state)))
2039 (defun js2-delete-if (predicate list)
2040 "Remove all items satisfying PREDICATE in LIST."
2041 (cl-loop for item in list
2042 if (not (funcall predicate item))
2045 (defun js2-position (element list)
2046 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2047 Returns nil if element is not found in the list."
2050 (while (and list (not found))
2051 (if (eq element (car list))
2053 (setq count (1+ count)
2057 (defun js2-find-if (predicate list)
2058 "Find first item satisfying PREDICATE in LIST."
2060 (while (and list (not result))
2061 (if (funcall predicate (car list))
2062 (setq result (car list)))
2063 (setq list (cdr list)))
2066 (defmacro js2-time (form)
2067 "Evaluate FORM, discard result, and return elapsed time in sec."
2069 (let ((beg (make-symbol "--js2-time-beg--")))
2070 `(let ((,beg (current-time)))
2072 (/ (truncate (* (- (float-time (current-time))
2077 (defsubst js2-same-line (pos)
2078 "Return t if POS is on the same line as current point."
2079 (and (>= pos (point-at-bol))
2080 (<= pos (point-at-eol))))
2082 (defun js2-code-bug ()
2083 "Signal an error when we encounter an unexpected code path."
2084 (error "failed assertion"))
2086 (defsubst js2-record-text-property (beg end prop value)
2087 "Record a text property to set when parsing finishes."
2088 (push (list beg end prop value) js2-mode-deferred-properties))
2090 ;; I'd like to associate errors with nodes, but for now the
2091 ;; easiest thing to do is get the context info from the last token.
2092 (defun js2-record-parse-error (msg &optional arg pos len)
2093 (push (list (list msg arg)
2094 (or pos (js2-current-token-beg))
2095 (or len (js2-current-token-len)))
2098 (defun js2-report-error (msg &optional msg-arg pos len)
2099 "Signal a syntax error or record a parse error."
2100 (if js2-recover-from-parse-errors
2101 (js2-record-parse-error msg msg-arg pos len)
2102 (signal 'js2-syntax-error
2106 (goto-char js2-ts-cursor)
2110 (defun js2-report-warning (msg &optional msg-arg pos len face)
2111 (if js2-compiler-report-warning-as-error
2112 (js2-report-error msg msg-arg pos len)
2113 (push (list (list msg msg-arg)
2114 (or pos (js2-current-token-beg))
2115 (or len (js2-current-token-len))
2117 js2-parsed-warnings)))
2119 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2120 (if js2-compiler-strict-mode
2121 (js2-report-warning msg-id msg-arg beg
2122 (and beg end (- end beg)))))
2124 (put 'js2-syntax-error 'error-conditions
2125 '(error syntax-error js2-syntax-error))
2126 (put 'js2-syntax-error 'error-message "Syntax error")
2128 (put 'js2-parse-error 'error-conditions
2129 '(error parse-error js2-parse-error))
2130 (put 'js2-parse-error 'error-message "Parse error")
2132 (defmacro js2-clear-flag (flags flag)
2133 `(setq ,flags (logand ,flags (lognot ,flag))))
2135 (defmacro js2-set-flag (flags flag)
2136 "Logical-or FLAG into FLAGS."
2137 `(setq ,flags (logior ,flags ,flag)))
2139 (defsubst js2-flag-set-p (flags flag)
2140 (/= 0 (logand flags flag)))
2142 (defsubst js2-flag-not-set-p (flags flag)
2143 (zerop (logand flags flag)))
2145 ;;; AST struct and function definitions
2147 ;; flags for ast node property 'member-type (used for e4x operators)
2148 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2149 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2150 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2152 (defsubst js2-relpos (pos anchor)
2153 "Convert POS to be relative to ANCHOR.
2154 If POS is nil, returns nil."
2155 (and pos (- pos anchor)))
2157 (defun js2-make-pad (indent)
2160 (make-string (* indent js2-basic-offset) ? )))
2162 (defun js2-visit-ast (node callback)
2163 "Visit every node in ast NODE with visitor CALLBACK.
2165 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2166 called twice: once to visit the node, and again after all the node's
2167 children have been processed. The END-P argument is nil on the first
2168 call and non-nil on the second call. The return value of the callback
2169 affects the traversal: if non-nil, the children of NODE are processed.
2170 If the callback returns nil, or if the node has no children, then the
2171 callback is called immediately with a non-nil END-P argument.
2173 The node traversal is approximately lexical-order, although there
2174 are currently no guarantees around this."
2176 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2178 (when (funcall callback node nil)
2181 ((eq vfunc 'js2-visit-none)
2182 nil) ; don't even bother calling it
2183 ;; Each AST node type has to define a `js2-visitor' function
2184 ;; that takes a node and a callback, and calls `js2-visit-ast'
2185 ;; on each child of the node.
2187 (funcall vfunc node callback))
2189 (error "%s does not define a visitor-traversal function"
2191 ;; call the end-visit
2192 (funcall callback node t))))
2194 (cl-defstruct (js2-node
2195 (:constructor nil)) ; abstract
2196 "Base AST node type."
2197 (type -1) ; token type
2198 (pos -1) ; start position of this AST node in parsed input
2199 (len 1) ; num characters spanned by the node
2200 props ; optional node property list (an alist)
2201 parent) ; link to parent node; null for root
2203 (defsubst js2-node-get-prop (node prop &optional default)
2204 (or (cadr (assoc prop (js2-node-props node))) default))
2206 (defsubst js2-node-set-prop (node prop value)
2207 (setf (js2-node-props node)
2208 (cons (list prop value) (js2-node-props node))))
2210 (defun js2-fixup-starts (n nodes)
2211 "Adjust the start positions of NODES to be relative to N.
2212 Any node in the list may be nil, for convenience."
2213 (dolist (node nodes)
2215 (setf (js2-node-pos node) (- (js2-node-pos node)
2216 (js2-node-pos n))))))
2218 (defun js2-node-add-children (parent &rest nodes)
2219 "Set parent node of NODES to PARENT, and return PARENT.
2220 Does nothing if we're not recording parent links.
2221 If any given node in NODES is nil, doesn't record that link."
2222 (js2-fixup-starts parent nodes)
2223 (dolist (node nodes)
2225 (setf (js2-node-parent node) parent))))
2227 ;; Non-recursive since it's called a frightening number of times.
2228 (defun js2-node-abs-pos (n)
2229 (let ((pos (js2-node-pos n)))
2230 (while (setq n (js2-node-parent n))
2231 (setq pos (+ pos (js2-node-pos n))))
2234 (defsubst js2-node-abs-end (n)
2235 "Return absolute buffer position of end of N."
2236 (+ (js2-node-abs-pos n) (js2-node-len n)))
2238 ;; It's important to make sure block nodes have a Lisp list for the
2239 ;; child nodes, to limit printing recursion depth in an AST that
2240 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2241 ;; a sufficiently large vector tree.
2243 (cl-defstruct (js2-block-node
2246 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2247 (pos (js2-current-token-beg))
2251 "A block of statements."
2252 kids) ; a Lisp list of the child statement nodes
2254 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2255 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2257 (defun js2-visit-block (ast callback)
2258 "Visit the `js2-block-node' children of AST."
2259 (dolist (kid (js2-block-node-kids ast))
2260 (js2-visit-ast kid callback)))
2262 (defun js2-print-block (n i)
2263 (let ((pad (js2-make-pad i)))
2265 (dolist (kid (js2-block-node-kids n))
2266 (js2-print-ast kid (1+ i)))
2269 (cl-defstruct (js2-scope
2270 (:include js2-block-node)
2272 (:constructor make-js2-scope (&key (type js2-BLOCK)
2273 (pos (js2-current-token-beg))
2276 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2277 ;; I don't have one of those handy, so I'll use an alist for now.
2278 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2279 ;; and is much lighter-weight to construct (both CPU and mem).
2280 ;; The keys are interned strings (symbols) for faster lookup.
2281 ;; Should switch to hybrid alist/hashtable eventually.
2282 symbol-table ; an alist of (symbol . js2-symbol)
2283 parent-scope ; a `js2-scope'
2284 top) ; top-level `js2-scope' (script/function)
2286 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2287 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2289 (defun js2-node-get-enclosing-scope (node)
2290 "Return the innermost `js2-scope' node surrounding NODE.
2291 Returns nil if there is no enclosing scope node."
2292 (while (and (setq node (js2-node-parent node))
2293 (not (js2-scope-p node))))
2296 (defun js2-get-defining-scope (scope name &optional point)
2297 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2298 Returns `js2-scope' in which NAME is defined, or nil if not found.
2300 If POINT is non-nil, and if the found declaration type is
2301 `js2-LET', also check that the declaration node is before POINT."
2302 (let ((sym (if (symbolp name)
2307 (while (and scope continue)
2309 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2312 (not (eq js2-LET (js2-symbol-decl-type entry)))
2314 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2315 (and (eq sym 'arguments)
2316 (js2-function-node-p scope)))
2319 (setq scope (js2-scope-parent-scope scope))))
2322 (defun js2-scope-get-symbol (scope name)
2323 "Return symbol table entry for NAME in SCOPE.
2324 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2325 (and (js2-scope-symbol-table scope)
2326 (cdr (assq (if (symbolp name)
2329 (js2-scope-symbol-table scope)))))
2331 (defun js2-scope-put-symbol (scope name symbol)
2332 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2333 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2334 (let* ((table (js2-scope-symbol-table scope))
2335 (sym (if (symbolp name) name (intern name)))
2336 (entry (assq sym table)))
2338 (setcdr entry symbol)
2339 (push (cons sym symbol)
2340 (js2-scope-symbol-table scope)))))
2342 (cl-defstruct (js2-symbol
2344 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2345 "A symbol table entry."
2346 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2347 ;; js2-LET, or js2-CONST
2350 ast-node) ; a `js2-node'
2352 (cl-defstruct (js2-error-node
2354 (:constructor nil) ; silence emacs21 byte-compiler
2355 (:constructor make-js2-error-node (&key (type js2-ERROR)
2356 (pos (js2-current-token-beg))
2358 "AST node representing a parse error.")
2360 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2361 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2363 (cl-defstruct (js2-script-node
2364 (:include js2-scope)
2366 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2367 (pos (js2-current-token-beg))
2369 ;; FIXME: What are those?
2372 functions ; Lisp list of nested functions
2373 regexps ; Lisp list of (string . flags)
2374 symbols ; alist (every symbol gets unique index)
2376 var-names ; vector of string names
2377 consts ; bool-vector matching var-decls
2378 (temp-number 0)) ; for generating temp variables
2380 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2381 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2383 (defun js2-print-script (node indent)
2384 (dolist (kid (js2-block-node-kids node))
2385 (js2-print-ast kid indent)))
2387 (cl-defstruct (js2-ast-root
2388 (:include js2-script-node)
2390 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2391 (pos (js2-current-token-beg))
2394 "The root node of a js2 AST."
2395 buffer ; the source buffer from which the code was parsed
2396 comments ; a Lisp list of comments, ordered by start position
2397 errors ; a Lisp list of errors found during parsing
2398 warnings ; a Lisp list of warnings found during parsing
2399 node-count) ; number of nodes in the tree, including the root
2401 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2402 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2404 (defun js2-visit-ast-root (ast callback)
2405 (dolist (kid (js2-ast-root-kids ast))
2406 (js2-visit-ast kid callback))
2407 (dolist (comment (js2-ast-root-comments ast))
2408 (js2-visit-ast comment callback)))
2410 (cl-defstruct (js2-comment-node
2413 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2414 (pos (js2-current-token-beg))
2417 format) ; 'line, 'block, 'jsdoc or 'html
2419 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2420 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2422 (defun js2-print-comment (n i)
2423 ;; We really ought to link end-of-line comments to their nodes.
2424 ;; Or maybe we could add a new comment type, 'endline.
2425 (insert (js2-make-pad i)
2426 (js2-node-string n)))
2428 (cl-defstruct (js2-expr-stmt-node
2431 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2435 "An expression statement."
2438 (defsubst js2-expr-stmt-node-set-has-result (node)
2439 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2440 (setf (js2-node-type node) js2-EXPR_RESULT))
2442 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2443 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2445 (defun js2-visit-expr-stmt-node (n v)
2446 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2448 (defun js2-print-expr-stmt-node (n indent)
2449 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2452 (cl-defstruct (js2-loop-node
2453 (:include js2-scope)
2455 "Abstract supertype of loop nodes."
2456 body ; a `js2-block-node'
2457 lp ; position of left-paren, nil if omitted
2458 rp) ; position of right-paren, nil if omitted
2460 (cl-defstruct (js2-do-node
2461 (:include js2-loop-node)
2463 (:constructor make-js2-do-node (&key (type js2-DO)
2464 (pos (js2-current-token-beg))
2471 "AST node for do-loop."
2472 condition ; while (expression)
2473 while-pos) ; buffer position of 'while' keyword
2475 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2476 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2478 (defun js2-visit-do-node (n v)
2479 (js2-visit-ast (js2-do-node-body n) v)
2480 (js2-visit-ast (js2-do-node-condition n) v))
2482 (defun js2-print-do-node (n i)
2483 (let ((pad (js2-make-pad i)))
2484 (insert pad "do {\n")
2485 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2486 (js2-print-ast kid (1+ i)))
2487 (insert pad "} while (")
2488 (js2-print-ast (js2-do-node-condition n) 0)
2491 (cl-defstruct (js2-export-node
2494 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2495 (pos (js2-current-token-beg))
2501 "AST node for an export statement. There are many things that can be exported,
2502 so many of its properties will be nil.
2504 exports-list ; lisp list of js2-export-binding-node to export
2505 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2506 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2507 default) ; js2-function-node or js2-assign-node
2509 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2510 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2512 (defun js2-visit-export-node (n v)
2513 (let ((exports-list (js2-export-node-exports-list n))
2514 (from (js2-export-node-from-clause n))
2515 (declaration (js2-export-node-declaration n))
2516 (default (js2-export-node-default n)))
2518 (dolist (export exports-list)
2519 (js2-visit-ast export v)))
2521 (js2-visit-ast from v))
2523 (js2-visit-ast declaration v))
2525 (js2-visit-ast default v))))
2527 (defun js2-print-export-node (n i)
2528 (let ((pad (js2-make-pad i))
2529 (exports-list (js2-export-node-exports-list n))
2530 (from (js2-export-node-from-clause n))
2531 (declaration (js2-export-node-declaration n))
2532 (default (js2-export-node-default n)))
2533 (insert pad "export ")
2537 (js2-print-ast default i))
2539 (js2-print-ast declaration i))
2540 ((and exports-list from)
2541 (js2-print-named-imports exports-list)
2543 (js2-print-from-clause from))
2546 (js2-print-from-clause from))
2548 (js2-print-named-imports exports-list)))
2551 (cl-defstruct (js2-while-node
2552 (:include js2-loop-node)
2554 (:constructor make-js2-while-node (&key (type js2-WHILE)
2555 (pos (js2-current-token-beg))
2559 "AST node for while-loop."
2560 condition) ; while-condition
2562 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2563 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2565 (defun js2-visit-while-node (n v)
2566 (js2-visit-ast (js2-while-node-condition n) v)
2567 (js2-visit-ast (js2-while-node-body n) v))
2569 (defun js2-print-while-node (n i)
2570 (let ((pad (js2-make-pad i)))
2571 (insert pad "while (")
2572 (js2-print-ast (js2-while-node-condition n) 0)
2574 (js2-print-body (js2-while-node-body n) (1+ i))
2575 (insert pad "}\n")))
2577 (cl-defstruct (js2-for-node
2578 (:include js2-loop-node)
2580 (:constructor make-js2-for-node (&key (type js2-FOR)
2585 "AST node for a C-style for-loop."
2586 init ; initialization expression
2587 condition ; loop condition
2588 update) ; update clause
2590 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2591 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2593 (defun js2-visit-for-node (n v)
2594 (js2-visit-ast (js2-for-node-init n) v)
2595 (js2-visit-ast (js2-for-node-condition n) v)
2596 (js2-visit-ast (js2-for-node-update n) v)
2597 (js2-visit-ast (js2-for-node-body n) v))
2599 (defun js2-print-for-node (n i)
2600 (let ((pad (js2-make-pad i)))
2601 (insert pad "for (")
2602 (js2-print-ast (js2-for-node-init n) 0)
2604 (js2-print-ast (js2-for-node-condition n) 0)
2606 (js2-print-ast (js2-for-node-update n) 0)
2608 (js2-print-body (js2-for-node-body n) (1+ i))
2609 (insert pad "}\n")))
2611 (cl-defstruct (js2-for-in-node
2612 (:include js2-loop-node)
2614 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2623 "AST node for a for..in loop."
2624 iterator ; [var] foo in ...
2625 object ; object over which we're iterating
2626 in-pos ; buffer position of 'in' keyword
2627 each-pos ; buffer position of 'each' keyword, if foreach-p
2628 foreach-p ; t if it's a for-each loop
2629 forof-p) ; t if it's a for-of loop
2631 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2632 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2634 (defun js2-visit-for-in-node (n v)
2635 (js2-visit-ast (js2-for-in-node-iterator n) v)
2636 (js2-visit-ast (js2-for-in-node-object n) v)
2637 (js2-visit-ast (js2-for-in-node-body n) v))
2639 (defun js2-print-for-in-node (n i)
2640 (let ((pad (js2-make-pad i))
2641 (foreach (js2-for-in-node-foreach-p n))
2642 (forof (js2-for-in-node-forof-p n)))
2647 (js2-print-ast (js2-for-in-node-iterator n) 0)
2648 (insert (if forof " of " " in "))
2649 (js2-print-ast (js2-for-in-node-object n) 0)
2651 (js2-print-body (js2-for-in-node-body n) (1+ i))
2652 (insert pad "}\n")))
2654 (cl-defstruct (js2-return-node
2657 (:constructor make-js2-return-node (&key (type js2-RETURN)
2661 "AST node for a return statement."
2662 retval) ; expression to return, or 'undefined
2664 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2665 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2667 (defun js2-visit-return-node (n v)
2668 (js2-visit-ast (js2-return-node-retval n) v))
2670 (defun js2-print-return-node (n i)
2671 (insert (js2-make-pad i) "return")
2672 (when (js2-return-node-retval n)
2674 (js2-print-ast (js2-return-node-retval n) 0))
2677 (cl-defstruct (js2-if-node
2680 (:constructor make-js2-if-node (&key (type js2-IF)
2687 "AST node for an if-statement."
2688 condition ; expression
2689 then-part ; statement or block
2690 else-pos ; optional buffer position of 'else' keyword
2691 else-part ; optional statement or block
2692 lp ; position of left-paren, nil if omitted
2693 rp) ; position of right-paren, nil if omitted
2695 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2696 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2698 (defun js2-visit-if-node (n v)
2699 (js2-visit-ast (js2-if-node-condition n) v)
2700 (js2-visit-ast (js2-if-node-then-part n) v)
2701 (js2-visit-ast (js2-if-node-else-part n) v))
2703 (defun js2-print-if-node (n i)
2704 (let ((pad (js2-make-pad i))
2705 (then-part (js2-if-node-then-part n))
2706 (else-part (js2-if-node-else-part n)))
2708 (js2-print-ast (js2-if-node-condition n) 0)
2710 (js2-print-body then-part (1+ i))
2715 ((js2-if-node-p else-part)
2717 (js2-print-body else-part i))
2719 (insert " else {\n")
2720 (js2-print-body else-part (1+ i))
2721 (insert pad "}\n")))))
2723 (cl-defstruct (js2-export-binding-node
2726 (:constructor make-js2-export-binding-node (&key (type -1)
2731 "AST node for an external symbol binding.
2732 It contains a local-name node which is the name of the value in the
2733 current scope, and extern-name which is the name of the value in the
2734 imported or exported scope. By default these are the same, but if the
2735 name is aliased as in {foo as bar}, it would have an extern-name node
2736 containing 'foo' and a local-name node containing 'bar'."
2737 local-name ; js2-name-node with the variable name in this scope
2738 extern-name) ; js2-name-node with the value name in the exporting module
2740 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2741 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2743 (defun js2-visit-extern-binding (n v)
2744 "Visit an extern binding node. First visit the local-name, and, if
2745 different, visit the extern-name."
2746 (let ((local-name (js2-export-binding-node-local-name n))
2747 (extern-name (js2-export-binding-node-extern-name n)))
2749 (js2-visit-ast local-name v))
2750 (when (not (equal local-name extern-name))
2751 (js2-visit-ast extern-name v))))
2753 (defun js2-print-extern-binding (n _i)
2754 "Print a representation of a single extern binding. E.g. 'foo' or
2756 (let ((local-name (js2-export-binding-node-local-name n))
2757 (extern-name (js2-export-binding-node-extern-name n)))
2758 (insert (js2-name-node-name extern-name))
2759 (when (not (equal local-name extern-name))
2761 (insert (js2-name-node-name local-name)))))
2764 (cl-defstruct (js2-import-node
2767 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2768 (pos (js2-current-token-beg))
2773 "AST node for an import statement. It follows the form
2775 import ModuleSpecifier;
2776 import ImportClause FromClause;"
2777 import ; js2-import-clause-node specifying which names are to imported.
2778 from ; js2-from-clause-node indicating the module from which to import.
2779 module-id) ; module-id of the import. E.g. 'src/mylib'.
2781 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2782 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2784 (defun js2-visit-import (n v)
2785 (let ((import-clause (js2-import-node-import n))
2786 (from-clause (js2-import-node-from n)))
2788 (js2-visit-ast import-clause v))
2790 (js2-visit-ast from-clause v))))
2792 (defun js2-print-import (n i)
2793 "Prints a representation of the import node"
2794 (let ((pad (js2-make-pad i))
2795 (import-clause (js2-import-node-import n))
2796 (from-clause (js2-import-node-from n))
2797 (module-id (js2-import-node-module-id n)))
2798 (insert pad "import ")
2801 (js2-print-import-clause import-clause)
2803 (js2-print-from-clause from-clause))
2809 (cl-defstruct (js2-import-clause-node
2812 (:constructor make-js2-import-clause-node (&key (type -1)
2818 "AST node corresponding to the import clause of an import statement. This is
2819 the portion of the import that bindings names from the external context to the
2821 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2822 named-imports ; lisp list of js2-export-binding-node for all named imports.
2823 default-binding) ; js2-export-binding-node for the default import binding
2825 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2826 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2828 (defun js2-visit-import-clause (n v)
2829 (let ((ns-import (js2-import-clause-node-namespace-import n))
2830 (named-imports (js2-import-clause-node-named-imports n))
2831 (default (js2-import-clause-node-default-binding n)))
2833 (js2-visit-ast ns-import v))
2835 (dolist (import named-imports)
2836 (js2-visit-ast import v)))
2838 (js2-visit-ast default v))))
2840 (defun js2-print-import-clause (n)
2841 (let ((ns-import (js2-import-clause-node-namespace-import n))
2842 (named-imports (js2-import-clause-node-named-imports n))
2843 (default (js2-import-clause-node-default-binding n)))
2845 ((and default ns-import)
2846 (js2-print-ast default)
2848 (js2-print-namespace-import ns-import))
2849 ((and default named-imports)
2850 (js2-print-ast default)
2852 (js2-print-named-imports named-imports))
2854 (js2-print-ast default))
2856 (js2-print-namespace-import ns-import))
2858 (js2-print-named-imports named-imports)))))
2860 (defun js2-print-namespace-import (node)
2862 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2864 (defun js2-print-named-imports (imports)
2866 (let ((len (length imports))
2869 (js2-print-extern-binding (nth n imports) 0)
2870 (unless (= n (- len 1))
2875 (cl-defstruct (js2-namespace-import-node
2878 (:constructor make-js2-namespace-import-node (&key (type -1)
2882 "AST node for a complete namespace import.
2883 E.g. the '* as lib' expression in:
2885 import * as lib from 'src/lib'
2887 It contains a single name node referring to the bound name."
2888 name) ; js2-name-node of the bound name.
2890 (defun js2-visit-namespace-import (n v)
2891 (js2-visit-ast (js2-namespace-import-node-name n) v))
2893 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2894 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2896 (cl-defstruct (js2-from-clause-node
2899 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2904 "AST node for the from clause in an import or export statement.
2905 E.g. from 'my/module'. It can refere to either an external module, or to the
2906 modules metadata itself."
2907 module-id ; string containing the module specifier.
2908 metadata-p) ; true if this clause refers to the module's metadata
2910 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2911 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2913 (defun js2-print-from-clause (n)
2915 (if (js2-from-clause-node-metadata-p n)
2916 (insert "this module")
2918 (insert (js2-from-clause-node-module-id n))
2921 (cl-defstruct (js2-try-node
2924 (:constructor make-js2-try-node (&key (type js2-TRY)
2930 "AST node for a try-statement."
2932 catch-clauses ; a Lisp list of `js2-catch-node'
2933 finally-block) ; a `js2-finally-node'
2935 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2936 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2938 (defun js2-visit-try-node (n v)
2939 (js2-visit-ast (js2-try-node-try-block n) v)
2940 (dolist (clause (js2-try-node-catch-clauses n))
2941 (js2-visit-ast clause v))
2942 (js2-visit-ast (js2-try-node-finally-block n) v))
2944 (defun js2-print-try-node (n i)
2945 (let ((pad (js2-make-pad i))
2946 (catches (js2-try-node-catch-clauses n))
2947 (finally (js2-try-node-finally-block n)))
2948 (insert pad "try {\n")
2949 (js2-print-body (js2-try-node-try-block n) (1+ i))
2952 (dolist (catch catches)
2953 (js2-print-ast catch i)))
2955 (js2-print-ast finally i)
2958 (cl-defstruct (js2-catch-node
2959 (:include js2-scope)
2961 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2968 "AST node for a catch clause."
2969 param ; destructuring form or simple name node
2970 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2971 guard-expr ; catch condition, a `js2-node'
2972 lp ; buffer position of left-paren, nil if omitted
2973 rp) ; buffer position of right-paren, nil if omitted
2975 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2976 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2978 (defun js2-visit-catch-node (n v)
2979 (js2-visit-ast (js2-catch-node-param n) v)
2980 (when (js2-catch-node-guard-kwd n)
2981 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2982 (js2-visit-block n v))
2984 (defun js2-print-catch-node (n i)
2985 (let ((pad (js2-make-pad i))
2986 (guard-kwd (js2-catch-node-guard-kwd n))
2987 (guard-expr (js2-catch-node-guard-expr n)))
2989 (js2-print-ast (js2-catch-node-param n) 0)
2992 (js2-print-ast guard-expr 0))
2994 (js2-print-body n (1+ i))
2997 (cl-defstruct (js2-finally-node
3000 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3003 "AST node for a finally clause."
3004 body) ; a `js2-node', often but not always a block node
3006 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3007 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3009 (defun js2-visit-finally-node (n v)
3010 (js2-visit-ast (js2-finally-node-body n) v))
3012 (defun js2-print-finally-node (n i)
3013 (let ((pad (js2-make-pad i)))
3014 (insert " finally {\n")
3015 (js2-print-body (js2-finally-node-body n) (1+ i))
3016 (insert pad "}\n")))
3018 (cl-defstruct (js2-switch-node
3021 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3027 "AST node for a switch statement."
3028 discriminant ; a `js2-node' (switch expression)
3029 cases ; a Lisp list of `js2-case-node'
3030 lp ; position of open-paren for discriminant, nil if omitted
3031 rp) ; position of close-paren for discriminant, nil if omitted
3033 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3034 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3036 (defun js2-visit-switch-node (n v)
3037 (js2-visit-ast (js2-switch-node-discriminant n) v)
3038 (dolist (c (js2-switch-node-cases n))
3039 (js2-visit-ast c v)))
3041 (defun js2-print-switch-node (n i)
3042 (let ((pad (js2-make-pad i))
3043 (cases (js2-switch-node-cases n)))
3044 (insert pad "switch (")
3045 (js2-print-ast (js2-switch-node-discriminant n) 0)
3047 (dolist (case cases)
3048 (js2-print-ast case i))
3049 (insert pad "}\n")))
3051 (cl-defstruct (js2-case-node
3052 (:include js2-block-node)
3054 (:constructor make-js2-case-node (&key (type js2-CASE)
3057 "AST node for a case clause of a switch statement."
3058 expr) ; the case expression (nil for default)
3060 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3061 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3063 (defun js2-visit-case-node (n v)
3064 (js2-visit-ast (js2-case-node-expr n) v)
3065 (js2-visit-block n v))
3067 (defun js2-print-case-node (n i)
3068 (let ((pad (js2-make-pad i))
3069 (expr (js2-case-node-expr n)))
3072 (insert "default:\n")
3074 (js2-print-ast expr 0)
3076 (dolist (kid (js2-case-node-kids n))
3077 (js2-print-ast kid (1+ i)))))
3079 (cl-defstruct (js2-throw-node
3082 (:constructor make-js2-throw-node (&key (type js2-THROW)
3085 "AST node for a throw statement."
3086 expr) ; the expression to throw
3088 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3089 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3091 (defun js2-visit-throw-node (n v)
3092 (js2-visit-ast (js2-throw-node-expr n) v))
3094 (defun js2-print-throw-node (n i)
3095 (insert (js2-make-pad i) "throw ")
3096 (js2-print-ast (js2-throw-node-expr n) 0)
3099 (cl-defstruct (js2-with-node
3102 (:constructor make-js2-with-node (&key (type js2-WITH)
3106 "AST node for a with-statement."
3109 lp ; buffer position of left-paren around object, nil if omitted
3110 rp) ; buffer position of right-paren around object, nil if omitted
3112 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3113 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3115 (defun js2-visit-with-node (n v)
3116 (js2-visit-ast (js2-with-node-object n) v)
3117 (js2-visit-ast (js2-with-node-body n) v))
3119 (defun js2-print-with-node (n i)
3120 (let ((pad (js2-make-pad i)))
3121 (insert pad "with (")
3122 (js2-print-ast (js2-with-node-object n) 0)
3124 (js2-print-body (js2-with-node-body n) (1+ i))
3125 (insert pad "}\n")))
3127 (cl-defstruct (js2-label-node
3130 (:constructor make-js2-label-node (&key (type js2-LABEL)
3133 "AST node for a statement label or case label."
3135 loop) ; for validating and code-generating continue-to-label
3137 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3138 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3140 (defun js2-print-label (n i)
3141 (insert (js2-make-pad i)
3142 (js2-label-node-name n)
3145 (cl-defstruct (js2-labeled-stmt-node
3148 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3149 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3150 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3153 "AST node for a statement with one or more labels.
3154 Multiple labels for a statement are collapsed into the labels field."
3155 labels ; Lisp list of `js2-label-node'
3156 stmt) ; the statement these labels are for
3158 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3159 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3161 (defun js2-get-label-by-name (lbl-stmt name)
3162 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3163 Returns nil if no such label is in the list."
3164 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3166 (while (and label-list (not result))
3167 (if (string= (js2-label-node-name (car label-list)) name)
3168 (setq result (car label-list))
3169 (setq label-list (cdr label-list))))
3172 (defun js2-visit-labeled-stmt (n v)
3173 (dolist (label (js2-labeled-stmt-node-labels n))
3174 (js2-visit-ast label v))
3175 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3177 (defun js2-print-labeled-stmt (n i)
3178 (dolist (label (js2-labeled-stmt-node-labels n))
3179 (js2-print-ast label i))
3180 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3182 (defun js2-labeled-stmt-node-contains (node label)
3183 "Return t if NODE contains LABEL in its label set.
3184 NODE is a `js2-labels-node'. LABEL is an identifier."
3185 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3186 if (string= label (js2-label-node-name nl))
3188 finally return nil))
3190 (defsubst js2-labeled-stmt-node-add-label (node label)
3191 "Add a `js2-label-node' to the label set for this statement."
3192 (setf (js2-labeled-stmt-node-labels node)
3193 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3195 (cl-defstruct (js2-jump-node
3198 "Abstract supertype of break and continue nodes."
3199 label ; `js2-name-node' for location of label identifier, if present
3200 target) ; target js2-labels-node or loop/switch statement
3202 (defun js2-visit-jump-node (n v)
3203 ;; We don't visit the target, since it's a back-link.
3204 (js2-visit-ast (js2-jump-node-label n) v))
3206 (cl-defstruct (js2-break-node
3207 (:include js2-jump-node)
3209 (:constructor make-js2-break-node (&key (type js2-BREAK)
3212 "AST node for a break statement.
3213 The label field is a `js2-name-node', possibly nil, for the named label
3214 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3215 is the target of the break - a label node or enclosing loop/switch statement.")
3217 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3218 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3220 (defun js2-print-break-node (n i)
3221 (insert (js2-make-pad i) "break")
3222 (when (js2-break-node-label n)
3224 (js2-print-ast (js2-break-node-label n) 0))
3227 (cl-defstruct (js2-continue-node
3228 (:include js2-jump-node)
3230 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3233 "AST node for a continue statement.
3234 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3235 It is nil if continue specifies no label. The target field is the jump target:
3236 a `js2-label-node' or the innermost enclosing loop.")
3238 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3239 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3241 (defun js2-print-continue-node (n i)
3242 (insert (js2-make-pad i) "continue")
3243 (when (js2-continue-node-label n)
3245 (js2-print-ast (js2-continue-node-label n) 0))
3248 (cl-defstruct (js2-function-node
3249 (:include js2-script-node)
3251 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3255 (form 'FUNCTION_STATEMENT)
3261 "AST node for a function declaration.
3262 The `params' field is a Lisp list of nodes. Each node is either a simple
3263 `js2-name-node', or if it's a destructuring-assignment parameter, a
3264 `js2-array-node' or `js2-object-node'."
3265 ftype ; FUNCTION, GETTER or SETTER
3266 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3267 name ; function name (a `js2-name-node', or nil if anonymous)
3268 params ; a Lisp list of destructuring forms or simple name nodes
3269 rest-p ; if t, the last parameter is rest parameter
3270 body ; a `js2-block-node' or expression node (1.8 only)
3271 lp ; position of arg-list open-paren, or nil if omitted
3272 rp ; position of arg-list close-paren, or nil if omitted
3273 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3274 needs-activation ; t if we need an activation object for this frame
3275 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3276 member-expr) ; nonstandard Ecma extension from Rhino
3278 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3279 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3281 (defun js2-visit-function-node (n v)
3282 (js2-visit-ast (js2-function-node-name n) v)
3283 (dolist (p (js2-function-node-params n))
3284 (js2-visit-ast p v))
3285 (js2-visit-ast (js2-function-node-body n) v))
3287 (defun js2-print-function-node (n i)
3288 (let* ((pad (js2-make-pad i))
3289 (method (js2-node-get-prop n 'METHOD_TYPE))
3290 (name (or (js2-function-node-name n)
3291 (js2-function-node-member-expr n)))
3292 (params (js2-function-node-params n))
3293 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3294 (rest-p (js2-function-node-rest-p n))
3295 (body (js2-function-node-body n))
3296 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3297 (unless (or method arrow)
3298 (insert pad "function")
3299 (when (eq (js2-function-node-generator-type n) 'STAR)
3303 (js2-print-ast name 0))
3305 (cl-loop with len = (length params)
3309 (when (and rest-p (= count len))
3311 (js2-print-ast param 0)
3318 ;; TODO: fix this to be smarter about indenting, etc.
3321 (if (js2-block-node-p body)
3322 (js2-print-body body (1+ i))
3323 (js2-print-ast body 0))
3328 (defun js2-function-name (node)
3329 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3330 (and (js2-function-node-name node)
3331 (js2-name-node-name (js2-function-node-name node))))
3333 ;; Having this be an expression node makes it more flexible.
3334 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3335 ;; that work better if you assume it's an expression. Whenever we have
3336 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3337 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3338 (cl-defstruct (js2-var-decl-node
3341 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3342 (pos (js2-current-token-beg))
3345 "AST node for a variable declaration list (VAR, CONST or LET).
3346 The node bounds differ depending on the declaration type. For VAR or
3347 CONST declarations, the bounds include the var/const keyword. For LET
3348 declarations, the node begins at the position of the first child."
3349 kids ; a Lisp list of `js2-var-init-node' structs.
3350 decl-type) ; js2-VAR, js2-CONST or js2-LET
3352 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3353 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3355 (defun js2-visit-var-decl (n v)
3356 (dolist (kid (js2-var-decl-node-kids n))
3357 (js2-visit-ast kid v)))
3359 (defun js2-print-var-decl (n i)
3360 (let ((pad (js2-make-pad i))
3361 (tt (js2-var-decl-node-decl-type n)))
3364 ((= tt js2-VAR) "var ")
3365 ((= tt js2-LET) "let ")
3366 ((= tt js2-CONST) "const ")
3368 (error "malformed var-decl node"))))
3369 (cl-loop with kids = (js2-var-decl-node-kids n)
3370 with len = (length kids)
3374 (js2-print-ast kid 0)
3378 (cl-defstruct (js2-var-init-node
3381 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3385 "AST node for a variable declaration.
3386 The type field will be js2-CONST for a const decl."
3387 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3388 initializer) ; initializer expression, a `js2-node'
3390 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3391 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3393 (defun js2-visit-var-init-node (n v)
3394 (js2-visit-ast (js2-var-init-node-target n) v)
3395 (js2-visit-ast (js2-var-init-node-initializer n) v))
3397 (defun js2-print-var-init-node (n i)
3398 (let ((pad (js2-make-pad i))
3399 (name (js2-var-init-node-target n))
3400 (init (js2-var-init-node-initializer n)))
3402 (js2-print-ast name 0)
3405 (js2-print-ast init 0))))
3407 (cl-defstruct (js2-cond-node
3410 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3417 "AST node for the ternary operator"
3421 q-pos ; buffer position of ?
3422 c-pos) ; buffer position of :
3424 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3425 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3427 (defun js2-visit-cond-node (n v)
3428 (js2-visit-ast (js2-cond-node-test-expr n) v)
3429 (js2-visit-ast (js2-cond-node-true-expr n) v)
3430 (js2-visit-ast (js2-cond-node-false-expr n) v))
3432 (defun js2-print-cond-node (n i)
3433 (let ((pad (js2-make-pad i)))
3435 (js2-print-ast (js2-cond-node-test-expr n) 0)
3437 (js2-print-ast (js2-cond-node-true-expr n) 0)
3439 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3441 (cl-defstruct (js2-infix-node
3444 (:constructor make-js2-infix-node (&key type
3448 "Represents infix expressions.
3449 Includes assignment ops like `|=', and the comma operator.
3450 The type field inherited from `js2-node' holds the operator."
3451 op-pos ; buffer position where operator begins
3452 left ; any `js2-node'
3453 right) ; any `js2-node'
3455 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3456 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3458 (defun js2-visit-infix-node (n v)
3459 (js2-visit-ast (js2-infix-node-left n) v)
3460 (js2-visit-ast (js2-infix-node-right n) v))
3462 (defconst js2-operator-tokens
3463 (let ((table (make-hash-table :test 'eq))
3465 (list (cons js2-IN "in")
3466 (cons js2-TYPEOF "typeof")
3467 (cons js2-INSTANCEOF "instanceof")
3468 (cons js2-DELPROP "delete")
3469 (cons js2-COMMA ",")
3470 (cons js2-COLON ":")
3475 (cons js2-BITOR "|")
3476 (cons js2-BITXOR "^")
3477 (cons js2-BITAND "&")
3486 (cons js2-URSH ">>>")
3487 (cons js2-ADD "+") ; infix plus
3488 (cons js2-SUB "-") ; infix minus
3493 (cons js2-BITNOT "~")
3494 (cons js2-POS "+") ; unary plus
3495 (cons js2-NEG "-") ; unary minus
3496 (cons js2-TRIPLEDOT "...")
3497 (cons js2-SHEQ "===") ; shallow equality
3498 (cons js2-SHNE "!==") ; shallow inequality
3499 (cons js2-ASSIGN "=")
3500 (cons js2-ASSIGN_BITOR "|=")
3501 (cons js2-ASSIGN_BITXOR "^=")
3502 (cons js2-ASSIGN_BITAND "&=")
3503 (cons js2-ASSIGN_LSH "<<=")
3504 (cons js2-ASSIGN_RSH ">>=")
3505 (cons js2-ASSIGN_URSH ">>>=")
3506 (cons js2-ASSIGN_ADD "+=")
3507 (cons js2-ASSIGN_SUB "-=")
3508 (cons js2-ASSIGN_MUL "*=")
3509 (cons js2-ASSIGN_DIV "/=")
3510 (cons js2-ASSIGN_MOD "%="))))
3511 (cl-loop for (k . v) in tokens do
3512 (puthash k v table))
3515 (defun js2-print-infix-node (n i)
3516 (let* ((tt (js2-node-type n))
3517 (op (gethash tt js2-operator-tokens)))
3519 (error "unrecognized infix operator %s" (js2-node-type n)))
3520 (insert (js2-make-pad i))
3521 (js2-print-ast (js2-infix-node-left n) 0)
3522 (unless (= tt js2-COMMA)
3526 (js2-print-ast (js2-infix-node-right n) 0)))
3528 (cl-defstruct (js2-assign-node
3529 (:include js2-infix-node)
3531 (:constructor make-js2-assign-node (&key type
3535 "Represents any assignment.
3536 The type field holds the actual assignment operator.")
3538 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3539 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3541 (cl-defstruct (js2-unary-node
3544 (:constructor make-js2-unary-node (&key type ; required
3547 "AST node type for unary operator nodes.
3548 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3549 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3550 property is added if the operator follows the operand."
3551 operand) ; a `js2-node' expression
3553 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3554 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3556 (defun js2-visit-unary-node (n v)
3557 (js2-visit-ast (js2-unary-node-operand n) v))
3559 (defun js2-print-unary-node (n i)
3560 (let* ((tt (js2-node-type n))
3561 (op (gethash tt js2-operator-tokens))
3562 (postfix (js2-node-get-prop n 'postfix)))
3564 (error "unrecognized unary operator %s" tt))
3565 (insert (js2-make-pad i))
3568 (if (or (= tt js2-TYPEOF)
3571 (js2-print-ast (js2-unary-node-operand n) 0)
3575 (cl-defstruct (js2-let-node
3576 (:include js2-scope)
3578 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3579 (pos (js2-current-token-beg))
3582 "AST node for a let expression or a let statement.
3583 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3584 vars ; a `js2-var-decl-node'
3585 body ; a `js2-node' representing the expression or body block
3589 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3590 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3592 (defun js2-visit-let-node (n v)
3593 (js2-visit-ast (js2-let-node-vars n) v)
3594 (js2-visit-ast (js2-let-node-body n) v))
3596 (defun js2-print-let-node (n i)
3597 (insert (js2-make-pad i) "let (")
3599 (js2-print-ast (js2-let-node-vars n) 0)
3600 (delete-region p (+ p 4)))
3602 (js2-print-ast (js2-let-node-body n) i))
3604 (cl-defstruct (js2-keyword-node
3607 (:constructor make-js2-keyword-node (&key type
3608 (pos (js2-current-token-beg))
3609 (len (- js2-ts-cursor pos)))))
3610 "AST node representing a literal keyword such as `null'.
3611 Used for `null', `this', `true', `false' and `debugger'.
3612 The node type is set to js2-NULL, js2-THIS, etc.")
3614 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3615 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3617 (defun js2-print-keyword-node (n i)
3618 (insert (js2-make-pad i)
3619 (let ((tt (js2-node-type n)))
3621 ((= tt js2-THIS) "this")
3622 ((= tt js2-SUPER) "super")
3623 ((= tt js2-NULL) "null")
3624 ((= tt js2-TRUE) "true")
3625 ((= tt js2-FALSE) "false")
3626 ((= tt js2-DEBUGGER) "debugger")
3627 (t (error "Invalid keyword literal type: %d" tt))))))
3629 (defsubst js2-this-or-super-node-p (node)
3630 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3631 (let ((type (js2-node-type node)))
3632 (or (eq type js2-THIS) (eq type js2-SUPER))))
3634 (cl-defstruct (js2-new-node
3637 (:constructor make-js2-new-node (&key (type js2-NEW)
3638 (pos (js2-current-token-beg))
3642 "AST node for new-expression such as new Foo()."
3643 target ; an identifier or reference
3644 args ; a Lisp list of argument nodes
3645 lp ; position of left-paren, nil if omitted
3646 rp ; position of right-paren, nil if omitted
3647 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3649 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3650 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3652 (defun js2-visit-new-node (n v)
3653 (js2-visit-ast (js2-new-node-target n) v)
3654 (dolist (arg (js2-new-node-args n))
3655 (js2-visit-ast arg v))
3656 (js2-visit-ast (js2-new-node-initializer n) v))
3658 (defun js2-print-new-node (n i)
3659 (insert (js2-make-pad i) "new ")
3660 (js2-print-ast (js2-new-node-target n))
3662 (js2-print-list (js2-new-node-args n))
3664 (when (js2-new-node-initializer n)
3666 (js2-print-ast (js2-new-node-initializer n))))
3668 (cl-defstruct (js2-name-node
3671 (:constructor make-js2-name-node (&key (type js2-NAME)
3672 (pos (js2-current-token-beg))
3673 (len (- js2-ts-cursor
3674 (js2-current-token-beg)))
3675 (name (js2-current-token-string)))))
3676 "AST node for a JavaScript identifier"
3678 scope) ; a `js2-scope' (optional, used for codegen)
3680 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3681 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3683 (defun js2-print-name-node (n i)
3684 (insert (js2-make-pad i)
3685 (js2-name-node-name n)))
3687 (defsubst js2-name-node-length (node)
3688 "Return identifier length of NODE, a `js2-name-node'.
3689 Returns 0 if NODE is nil or its identifier field is nil."
3691 (length (js2-name-node-name node))
3694 (cl-defstruct (js2-number-node
3697 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3698 (pos (js2-current-token-beg))
3699 (len (- js2-ts-cursor
3700 (js2-current-token-beg)))
3701 (value (js2-current-token-string))
3702 (num-value (js2-token-number
3703 (js2-current-token)))
3704 (num-base (js2-token-number-base
3705 (js2-current-token)))
3706 (legacy-octal-p (js2-token-number-legacy-octal-p
3707 (js2-current-token))))))
3708 "AST node for a number literal."
3709 value ; the original string, e.g. "6.02e23"
3710 num-value ; the parsed number value
3711 num-base ; the number's base
3712 legacy-octal-p) ; whether the number is a legacy octal (0123 instead of 0o123)
3714 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3715 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3717 (defun js2-print-number-node (n i)
3718 (insert (js2-make-pad i)
3719 (number-to-string (js2-number-node-num-value n))))
3721 (cl-defstruct (js2-regexp-node
3724 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3725 (pos (js2-current-token-beg))
3726 (len (- js2-ts-cursor
3727 (js2-current-token-beg)))
3729 "AST node for a regular expression literal."
3730 value ; the regexp string, without // delimiters
3731 flags) ; a string of flags, e.g. `mi'.
3733 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3734 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3736 (defun js2-print-regexp (n i)
3737 (insert (js2-make-pad i)
3739 (js2-regexp-node-value n)
3741 (if (js2-regexp-node-flags n)
3742 (insert (js2-regexp-node-flags n))))
3744 (cl-defstruct (js2-string-node
3747 (:constructor make-js2-string-node (&key (type js2-STRING)
3748 (pos (js2-current-token-beg))
3749 (len (- js2-ts-cursor
3750 (js2-current-token-beg)))
3751 (value (js2-current-token-string)))))
3753 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3754 You can tell the quote type by looking at the first character."
3755 value) ; the characters of the string, including the quotes
3757 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3758 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3760 (defun js2-print-string-node (n i)
3761 (insert (js2-make-pad i)
3762 (js2-node-string n)))
3764 (cl-defstruct (js2-template-node
3767 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3770 kids) ; `js2-string-node' is used for string segments, other nodes
3771 ; for substitutions inside.
3773 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3774 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3776 (defun js2-visit-template (n callback)
3777 (dolist (kid (js2-template-node-kids n))
3778 (js2-visit-ast kid callback)))
3780 (defun js2-print-template (n i)
3781 (insert (js2-make-pad i))
3782 (dolist (kid (js2-template-node-kids n))
3783 (if (js2-string-node-p kid)
3784 (insert (js2-node-string kid))
3785 (js2-print-ast kid))))
3787 (cl-defstruct (js2-tagged-template-node
3790 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3791 beg len tag template)))
3792 "Tagged template literal."
3793 tag ; `js2-node' with the tag expression.
3794 template) ; `js2-template-node' with the template.
3796 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3797 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3799 (defun js2-visit-tagged-template (n callback)
3800 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3801 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3803 (defun js2-print-tagged-template (n i)
3804 (insert (js2-make-pad i))
3805 (js2-print-ast (js2-tagged-template-node-tag n))
3806 (js2-print-ast (js2-tagged-template-node-template n)))
3808 (cl-defstruct (js2-array-node
3811 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3814 "AST node for an array literal."
3815 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3817 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3818 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3820 (defun js2-visit-array-node (n v)
3821 (dolist (e (js2-array-node-elems n))
3822 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3824 (defun js2-print-array-node (n i)
3825 (insert (js2-make-pad i) "[")
3826 (let ((elems (js2-array-node-elems n)))
3827 (js2-print-list elems)
3828 (when (and elems (null (car (last elems))))
3832 (cl-defstruct (js2-class-node
3835 (:constructor make-js2-class-node (&key (type js2-CLASS)
3837 (form 'CLASS_STATEMENT)
3839 extends len elems)))
3840 "AST node for an class expression.
3841 `elems' is a list of `js2-object-prop-node', and `extends' is an
3842 optional `js2-expr-node'"
3843 form ; CLASS_{STATEMENT|EXPRESSION}
3844 name ; class name (a `js2-node-name', or nil if anonymous)
3845 extends ; class heritage (a `js2-expr-node', or nil if none)
3848 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3849 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3851 (defun js2-visit-class-node (n v)
3852 (js2-visit-ast (js2-class-node-name n) v)
3853 (js2-visit-ast (js2-class-node-extends n) v)
3854 (dolist (e (js2-class-node-elems n))
3855 (js2-visit-ast e v)))
3857 (defun js2-print-class-node (n i)
3858 (let* ((pad (js2-make-pad i))
3859 (name (js2-class-node-name n))
3860 (extends (js2-class-node-extends n))
3861 (elems (js2-class-node-elems n)))
3862 (insert pad "class")
3865 (js2-print-ast name 0))
3867 (insert " extends ")
3868 (js2-print-ast extends))
3870 (dolist (elem elems)
3872 (if (js2-node-get-prop elem 'STATIC)
3873 (progn (insert (js2-make-pad (1+ i)) "static ")
3874 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3875 (js2-print-ast elem (1+ i))))
3876 (insert "\n" pad "}")))
3878 (cl-defstruct (js2-object-node
3881 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3885 "AST node for an object literal expression.
3886 `elems' is a list of `js2-object-prop-node'."
3889 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3890 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3892 (defun js2-visit-object-node (n v)
3893 (dolist (e (js2-object-node-elems n))
3894 (js2-visit-ast e v)))
3896 (defun js2-print-object-node (n i)
3897 (insert (js2-make-pad i) "{")
3898 (js2-print-list (js2-object-node-elems n))
3901 (cl-defstruct (js2-computed-prop-name-node
3904 (:constructor make-js2-computed-prop-name-node
3908 (pos (js2-current-token-beg))
3909 (len (- js2-ts-cursor
3910 (js2-current-token-beg))))))
3911 "AST node for a `ComputedPropertyName'."
3914 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3915 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3917 (defun js2-visit-computed-prop-name-node (n v)
3918 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3920 (defun js2-print-computed-prop-name-node (n i)
3921 (insert (js2-make-pad i) "[")
3922 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3925 (cl-defstruct (js2-object-prop-node
3926 (:include js2-infix-node)
3928 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3932 "AST node for an object literal prop:value entry.
3933 The `left' field is the property: a name node, string node,
3934 number node or expression node. The `right' field is a
3935 `js2-node' representing the initializer value. If the property
3936 is abbreviated, the node's `SHORTHAND' property is non-nil and
3937 both fields have the same value.")
3939 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3940 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3942 (defun js2-print-object-prop-node (n i)
3943 (let* ((left (js2-object-prop-node-left n))
3944 (right (js2-object-prop-node-right n)))
3945 (js2-print-ast left i)
3946 (if (not (js2-node-get-prop n 'SHORTHAND))
3949 (js2-print-ast right 0)))))
3951 (cl-defstruct (js2-method-node
3952 (:include js2-infix-node)
3954 (:constructor make-js2-method-node (&key type ; GET, SET, or FUNCTION
3957 "AST node for a method in an object literal or a class body.
3958 The `left' field is the `js2-name-node' naming the method.
3959 The `right' field is always an anonymous `js2-function-node' with a node
3960 property `METHOD_TYPE' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3962 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3963 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3965 (defun js2-print-method (n i)
3966 (let* ((pad (js2-make-pad i))
3967 (left (js2-method-node-left n))
3968 (right (js2-method-node-right n)))
3970 (if (/= (js2-node-type n) js2-FUNCTION)
3971 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3972 (when (and (js2-function-node-p right)
3973 (eq 'STAR (js2-function-node-generator-type right)))
3975 (js2-print-ast left 0)
3976 (js2-print-ast right 0)))
3978 (cl-defstruct (js2-prop-get-node
3979 (:include js2-infix-node)
3981 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3984 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3986 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3987 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3989 (defun js2-visit-prop-get-node (n v)
3990 (js2-visit-ast (js2-prop-get-node-left n) v)
3991 (js2-visit-ast (js2-prop-get-node-right n) v))
3993 (defun js2-print-prop-get-node (n i)
3994 (insert (js2-make-pad i))
3995 (js2-print-ast (js2-prop-get-node-left n) 0)
3997 (js2-print-ast (js2-prop-get-node-right n) 0))
3999 (cl-defstruct (js2-elem-get-node
4002 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4006 "AST node for an array index expression such as foo[bar]."
4007 target ; a `js2-node' - the expression preceding the "."
4008 element ; a `js2-node' - the expression in brackets
4009 lb ; position of left-bracket, nil if omitted
4010 rb) ; position of right-bracket, nil if omitted
4012 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4013 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4015 (defun js2-visit-elem-get-node (n v)
4016 (js2-visit-ast (js2-elem-get-node-target n) v)
4017 (js2-visit-ast (js2-elem-get-node-element n) v))
4019 (defun js2-print-elem-get-node (n i)
4020 (insert (js2-make-pad i))
4021 (js2-print-ast (js2-elem-get-node-target n) 0)
4023 (js2-print-ast (js2-elem-get-node-element n) 0)
4026 (cl-defstruct (js2-call-node
4029 (:constructor make-js2-call-node (&key (type js2-CALL)
4033 "AST node for a JavaScript function call."
4034 target ; a `js2-node' evaluating to the function to call
4035 args ; a Lisp list of `js2-node' arguments
4036 lp ; position of open-paren, or nil if missing
4037 rp) ; position of close-paren, or nil if missing
4039 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4040 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4042 (defun js2-visit-call-node (n v)
4043 (js2-visit-ast (js2-call-node-target n) v)
4044 (dolist (arg (js2-call-node-args n))
4045 (js2-visit-ast arg v)))
4047 (defun js2-print-call-node (n i)
4048 (insert (js2-make-pad i))
4049 (js2-print-ast (js2-call-node-target n) 0)
4051 (js2-print-list (js2-call-node-args n))
4054 (cl-defstruct (js2-yield-node
4057 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4060 "AST node for yield statement or expression."
4061 star-p ; whether it's yield*
4062 value) ; optional: value to be yielded
4064 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4065 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4067 (defun js2-visit-yield-node (n v)
4068 (js2-visit-ast (js2-yield-node-value n) v))
4070 (defun js2-print-yield-node (n i)
4071 (insert (js2-make-pad i))
4073 (when (js2-yield-node-star-p n)
4075 (when (js2-yield-node-value n)
4077 (js2-print-ast (js2-yield-node-value n) 0)))
4079 (cl-defstruct (js2-paren-node
4082 (:constructor make-js2-paren-node (&key (type js2-LP)
4085 "AST node for a parenthesized expression.
4086 In particular, used when the parens are syntactically optional,
4087 as opposed to required parens such as those enclosing an if-conditional."
4090 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4091 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4093 (defun js2-visit-paren-node (n v)
4094 (js2-visit-ast (js2-paren-node-expr n) v))
4096 (defun js2-print-paren-node (n i)
4097 (insert (js2-make-pad i))
4099 (js2-print-ast (js2-paren-node-expr n) 0)
4102 (cl-defstruct (js2-comp-node
4103 (:include js2-scope)
4105 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4110 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4111 result ; result expression (just after left-bracket)
4112 loops ; a Lisp list of `js2-comp-loop-node'
4113 filters ; a Lisp list of guard/filter expressions
4114 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4115 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4118 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4119 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4121 (defun js2-visit-comp-node (n v)
4122 (js2-visit-ast (js2-comp-node-result n) v)
4123 (dolist (l (js2-comp-node-loops n))
4124 (js2-visit-ast l v))
4125 (dolist (f (js2-comp-node-filters n))
4126 (js2-visit-ast f v)))
4128 (defun js2-print-comp-node (n i)
4129 (let ((pad (js2-make-pad i))
4130 (result (js2-comp-node-result n))
4131 (loops (js2-comp-node-loops n))
4132 (filters (js2-comp-node-filters n))
4133 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4134 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4135 (insert pad (if gen-p "(" "["))
4137 (js2-print-ast result 0))
4153 (js2-print-ast result 0))
4154 (insert (if gen-p ")" "]"))))
4156 (cl-defstruct (js2-comp-loop-node
4157 (:include js2-for-in-node)
4159 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4167 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4169 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4170 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4172 (defun js2-visit-comp-loop (n v)
4173 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4174 (js2-visit-ast (js2-comp-loop-node-object n) v))
4176 (defun js2-print-comp-loop (n _i)
4178 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4180 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4181 (insert (if (js2-comp-loop-node-forof-p n)
4183 (js2-print-ast (js2-comp-loop-node-object n) 0)
4186 (cl-defstruct (js2-empty-expr-node
4189 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4190 (pos (js2-current-token-beg))
4192 "AST node for an empty expression.")
4194 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4195 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4197 (cl-defstruct (js2-xml-node
4198 (:include js2-block-node)
4200 (:constructor make-js2-xml-node (&key (type js2-XML)
4201 (pos (js2-current-token-beg))
4203 "AST node for initial parse of E4X literals.
4204 The kids field is a list of XML fragments, each a `js2-string-node' or
4205 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4207 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4208 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4210 (defun js2-print-xml-node (n i)
4211 (dolist (kid (js2-xml-node-kids n))
4212 (js2-print-ast kid i)))
4214 (cl-defstruct (js2-xml-js-expr-node
4215 (:include js2-xml-node)
4217 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4220 "AST node for an embedded JavaScript {expression} in an E4X literal.
4221 The start and end fields correspond to the curly-braces."
4222 expr) ; a `js2-expr-node' of some sort
4224 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4225 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4227 (defun js2-visit-xml-js-expr (n v)
4228 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4230 (defun js2-print-xml-js-expr (n i)
4231 (insert (js2-make-pad i))
4233 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4236 (cl-defstruct (js2-xml-dot-query-node
4237 (:include js2-infix-node)
4239 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4243 "AST node for an E4X foo.(bar) filter expression.
4244 Note that the left-paren is automatically the character immediately
4245 following the dot (.) in the operator. No whitespace is permitted
4246 between the dot and the lp by the scanner."
4249 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4250 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4252 (defun js2-print-xml-dot-query (n i)
4253 (insert (js2-make-pad i))
4254 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4256 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4259 (cl-defstruct (js2-xml-ref-node
4261 (:constructor nil)) ; abstract
4262 "Base type for E4X XML attribute-access or property-get expressions.
4263 Such expressions can take a variety of forms. The general syntax has
4266 - (optional) an @ (specifying an attribute access)
4267 - (optional) a namespace (a `js2-name-node') and double-colon
4268 - (required) either a `js2-name-node' or a bracketed [expression]
4270 The property-name expressions (examples: ns::name, @name) are
4271 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4272 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4274 This node type (or more specifically, its subclasses) will sometimes
4275 be the right-hand child of a `js2-prop-get-node' or a
4276 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4277 The `js2-xml-ref-node' may also be a standalone primary expression with
4278 no explicit target, which is valid in certain expression contexts such as
4280 company..employee.(@id < 100)
4282 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4283 expression whose parent is a `js2-xml-dot-query-node'."
4288 (defsubst js2-xml-ref-node-attr-access-p (node)
4289 "Return non-nil if this expression began with an @-token."
4290 (and (numberp (js2-xml-ref-node-at-pos node))
4291 (cl-plusp (js2-xml-ref-node-at-pos node))))
4293 (cl-defstruct (js2-xml-prop-ref-node
4294 (:include js2-xml-ref-node)
4296 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4297 (pos (js2-current-token-beg))
4301 "AST node for an E4X XML [expr] property-ref expression.
4302 The JavaScript syntax is an optional @, an optional ns::, and a name.
4304 [ '@' ] [ name '::' ] name
4306 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4307 @ns::*, @*::attr, @*::*, and @*.
4309 The node starts at the @ token, if present. Otherwise it starts at the
4310 namespace name. The node bounds extend through the closing right-bracket,
4311 or if it is missing due to a syntax error, through the end of the index
4315 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4316 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4318 (defun js2-visit-xml-prop-ref-node (n v)
4319 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4320 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4322 (defun js2-print-xml-prop-ref-node (n i)
4323 (insert (js2-make-pad i))
4324 (if (js2-xml-ref-node-attr-access-p n)
4326 (when (js2-xml-prop-ref-node-namespace n)
4327 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4329 (if (js2-xml-prop-ref-node-propname n)
4330 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4332 (cl-defstruct (js2-xml-elem-ref-node
4333 (:include js2-xml-ref-node)
4335 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4336 (pos (js2-current-token-beg))
4340 "AST node for an E4X XML [expr] member-ref expression.
4343 [ '@' ] [ name '::' ] '[' expr ']'
4345 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4347 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4348 is not a legal E4X XML element-ref expression, since it's already used
4349 for standard JavaScript element-get array indexing. Hence, a
4350 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4351 non-nil namespace node, or both.
4353 The node starts at the @ token, if present. Otherwise it starts
4354 at the namespace name. The node bounds extend through the closing
4355 right-bracket, or if it is missing due to a syntax error, through the
4356 end of the index expression."
4357 expr ; the bracketed index expression
4361 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4362 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4364 (defun js2-visit-xml-elem-ref-node (n v)
4365 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4366 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4368 (defun js2-print-xml-elem-ref-node (n i)
4369 (insert (js2-make-pad i))
4370 (if (js2-xml-ref-node-attr-access-p n)
4372 (when (js2-xml-elem-ref-node-namespace n)
4373 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4376 (if (js2-xml-elem-ref-node-expr n)
4377 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4380 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4382 (cl-defstruct (js2-xml-start-tag-node
4383 (:include js2-xml-node)
4385 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4389 "AST node for an XML start-tag. Not currently used.
4390 The `kids' field is a Lisp list of child content nodes."
4391 name ; a `js2-xml-name-node'
4392 attrs ; a Lisp list of `js2-xml-attr-node'
4393 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4395 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4396 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4398 (defun js2-visit-xml-start-tag (n v)
4399 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4400 (dolist (attr (js2-xml-start-tag-node-attrs n))
4401 (js2-visit-ast attr v))
4402 (js2-visit-block n v))
4404 (defun js2-print-xml-start-tag (n i)
4405 (insert (js2-make-pad i) "<")
4406 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4407 (when (js2-xml-start-tag-node-attrs n)
4409 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4412 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4413 ;; and add the end-tag to the kids list of the parent as well.
4414 (cl-defstruct (js2-xml-end-tag-node
4415 (:include js2-xml-node)
4417 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4420 "AST node for an XML end-tag. Not currently used."
4421 name) ; a `js2-xml-name-node'
4423 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4424 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4426 (defun js2-visit-xml-end-tag (n v)
4427 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4429 (defun js2-print-xml-end-tag (n i)
4430 (insert (js2-make-pad i))
4432 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4435 (cl-defstruct (js2-xml-name-node
4436 (:include js2-xml-node)
4438 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4440 len namespace kids)))
4441 "AST node for an E4X XML name. Not currently used.
4442 Any XML name can be qualified with a namespace, hence the namespace field.
4443 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4444 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4445 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4446 namespace) ; a `js2-string-node'
4448 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4449 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4451 (defun js2-visit-xml-name-node (n v)
4452 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4454 (defun js2-print-xml-name-node (n i)
4455 (insert (js2-make-pad i))
4456 (when (js2-xml-name-node-namespace n)
4457 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4459 (dolist (kid (js2-xml-name-node-kids n))
4460 (js2-print-ast kid 0)))
4462 (cl-defstruct (js2-xml-pi-node
4463 (:include js2-xml-node)
4465 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4468 "AST node for an E4X XML processing instruction. Not currently used."
4469 name ; a `js2-xml-name-node'
4470 attrs) ; a list of `js2-xml-attr-node'
4472 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4473 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4475 (defun js2-visit-xml-pi-node (n v)
4476 (js2-visit-ast (js2-xml-pi-node-name n) v)
4477 (dolist (attr (js2-xml-pi-node-attrs n))
4478 (js2-visit-ast attr v)))
4480 (defun js2-print-xml-pi-node (n i)
4481 (insert (js2-make-pad i) "<?")
4482 (js2-print-ast (js2-xml-pi-node-name n))
4483 (when (js2-xml-pi-node-attrs n)
4485 (js2-print-list (js2-xml-pi-node-attrs n)))
4488 (cl-defstruct (js2-xml-cdata-node
4489 (:include js2-xml-node)
4491 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4494 "AST node for a CDATA escape section. Not currently used."
4495 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4497 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4498 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4500 (defun js2-visit-xml-cdata-node (n v)
4501 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4503 (defun js2-print-xml-cdata-node (n i)
4504 (insert (js2-make-pad i))
4505 (js2-print-ast (js2-xml-cdata-node-content n)))
4507 (cl-defstruct (js2-xml-attr-node
4508 (:include js2-xml-node)
4510 (:constructor make-js2-attr-node (&key (type js2-XML)
4513 eq-pos quote-type)))
4514 "AST node representing a foo='bar' XML attribute value. Not yet used."
4515 name ; a `js2-xml-name-node'
4516 value ; a `js2-xml-name-node'
4517 eq-pos ; buffer position of "=" sign
4518 quote-type) ; 'single or 'double
4520 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4521 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4523 (defun js2-visit-xml-attr-node (n v)
4524 (js2-visit-ast (js2-xml-attr-node-name n) v)
4525 (js2-visit-ast (js2-xml-attr-node-value n) v))
4527 (defun js2-print-xml-attr-node (n i)
4528 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4531 (insert (js2-make-pad i))
4532 (js2-print-ast (js2-xml-attr-node-name n) 0)
4534 (js2-print-ast (js2-xml-attr-node-value n) 0)
4537 (cl-defstruct (js2-xml-text-node
4538 (:include js2-xml-node)
4540 (:constructor make-js2-text-node (&key (type js2-XML)
4543 "AST node for an E4X XML text node. Not currently used."
4544 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4546 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4547 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4549 (defun js2-visit-xml-text-node (n v)
4550 (js2-visit-ast (js2-xml-text-node-content n) v))
4552 (defun js2-print-xml-text-node (n i)
4553 (insert (js2-make-pad i))
4554 (dolist (kid (js2-xml-text-node-content n))
4555 (js2-print-ast kid)))
4557 (cl-defstruct (js2-xml-comment-node
4558 (:include js2-xml-node)
4560 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4563 "AST node for E4X XML comment. Not currently used.")
4565 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4566 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4568 (defun js2-print-xml-comment (n i)
4569 (insert (js2-make-pad i)
4570 (js2-node-string n)))
4574 (defsubst js2-node-line (n)
4575 "Fetch the source line number at the start of node N.
4576 This is O(n) in the length of the source buffer; use prudently."
4577 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4579 (defsubst js2-block-node-kid (n i)
4580 "Return child I of node N, or nil if there aren't that many."
4581 (nth i (js2-block-node-kids n)))
4583 (defsubst js2-block-node-first (n)
4584 "Return first child of block node N, or nil if there is none."
4585 (cl-first (js2-block-node-kids n)))
4587 (defun js2-node-root (n)
4588 "Return the root of the AST containing N.
4589 If N has no parent pointer, returns N."
4590 (let ((parent (js2-node-parent n)))
4592 (js2-node-root parent)
4595 (defsubst js2-node-short-name (n)
4596 "Return the short name of node N as a string, e.g. `js2-if-node'."
4597 (substring (symbol-name (aref n 0))
4598 (length "cl-struct-")))
4600 (defun js2-node-child-list (node)
4601 "Return the child list for NODE, a Lisp list of nodes.
4602 Works for block nodes, array nodes, obj literals, funarg lists,
4603 var decls and try nodes (for catch clauses). Note that you should call
4604 `js2-block-node-kids' on the function body for the body statements.
4605 Returns nil for zero-length child lists or unsupported nodes."
4607 ((js2-function-node-p node)
4608 (js2-function-node-params node))
4609 ((js2-block-node-p node)
4610 (js2-block-node-kids node))
4611 ((js2-try-node-p node)
4612 (js2-try-node-catch-clauses node))
4613 ((js2-array-node-p node)
4614 (js2-array-node-elems node))
4615 ((js2-object-node-p node)
4616 (js2-object-node-elems node))
4617 ((js2-call-node-p node)
4618 (js2-call-node-args node))
4619 ((js2-new-node-p node)
4620 (js2-new-node-args node))
4621 ((js2-var-decl-node-p node)
4622 (js2-var-decl-node-kids node))
4626 (defun js2-node-set-child-list (node kids)
4627 "Set the child list for NODE to KIDS."
4629 ((js2-function-node-p node)
4630 (setf (js2-function-node-params node) kids))
4631 ((js2-block-node-p node)
4632 (setf (js2-block-node-kids node) kids))
4633 ((js2-try-node-p node)
4634 (setf (js2-try-node-catch-clauses node) kids))
4635 ((js2-array-node-p node)
4636 (setf (js2-array-node-elems node) kids))
4637 ((js2-object-node-p node)
4638 (setf (js2-object-node-elems node) kids))
4639 ((js2-call-node-p node)
4640 (setf (js2-call-node-args node) kids))
4641 ((js2-new-node-p node)
4642 (setf (js2-new-node-args node) kids))
4643 ((js2-var-decl-node-p node)
4644 (setf (js2-var-decl-node-kids node) kids))
4646 (error "Unsupported node type: %s" (js2-node-short-name node))))
4649 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4650 (defconst js2-paren-expr-nodes
4651 '(cl-struct-js2-comp-loop-node
4652 cl-struct-js2-comp-node
4653 cl-struct-js2-call-node
4654 cl-struct-js2-catch-node
4655 cl-struct-js2-do-node
4656 cl-struct-js2-elem-get-node
4657 cl-struct-js2-for-in-node
4658 cl-struct-js2-for-node
4659 cl-struct-js2-function-node
4660 cl-struct-js2-if-node
4661 cl-struct-js2-let-node
4662 cl-struct-js2-new-node
4663 cl-struct-js2-paren-node
4664 cl-struct-js2-switch-node
4665 cl-struct-js2-while-node
4666 cl-struct-js2-with-node
4667 cl-struct-js2-xml-dot-query-node)
4668 "Node types that can have a parenthesized child expression.
4669 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4671 (defsubst js2-paren-expr-node-p (node)
4672 "Return t for nodes that typically have a parenthesized child expression.
4673 Useful for computing the indentation anchors for arg-lists and conditions.
4674 Note that it may return a false positive, for instance when NODE is
4675 a `js2-new-node' and there are no arguments or parentheses."
4676 (memq (aref node 0) js2-paren-expr-nodes))
4678 ;; Fake polymorphism... yech.
4679 (defun js2-node-lp (node)
4680 "Return relative left-paren position for NODE, if applicable.
4681 For `js2-elem-get-node' structs, returns left-bracket position.
4682 Note that the position may be nil in the case of a parse error."
4684 ((js2-elem-get-node-p node)
4685 (js2-elem-get-node-lb node))
4686 ((js2-loop-node-p node)
4687 (js2-loop-node-lp node))
4688 ((js2-function-node-p node)
4689 (js2-function-node-lp node))
4690 ((js2-if-node-p node)
4691 (js2-if-node-lp node))
4692 ((js2-new-node-p node)
4693 (js2-new-node-lp node))
4694 ((js2-call-node-p node)
4695 (js2-call-node-lp node))
4696 ((js2-paren-node-p node)
4698 ((js2-switch-node-p node)
4699 (js2-switch-node-lp node))
4700 ((js2-catch-node-p node)
4701 (js2-catch-node-lp node))
4702 ((js2-let-node-p node)
4703 (js2-let-node-lp node))
4704 ((js2-comp-node-p node)
4706 ((js2-with-node-p node)
4707 (js2-with-node-lp node))
4708 ((js2-xml-dot-query-node-p node)
4709 (1+ (js2-infix-node-op-pos node)))
4711 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4713 ;; Fake polymorphism... blech.
4714 (defun js2-node-rp (node)
4715 "Return relative right-paren position for NODE, if applicable.
4716 For `js2-elem-get-node' structs, returns right-bracket position.
4717 Note that the position may be nil in the case of a parse error."
4719 ((js2-elem-get-node-p node)
4720 (js2-elem-get-node-rb node))
4721 ((js2-loop-node-p node)
4722 (js2-loop-node-rp node))
4723 ((js2-function-node-p node)
4724 (js2-function-node-rp node))
4725 ((js2-if-node-p node)
4726 (js2-if-node-rp node))
4727 ((js2-new-node-p node)
4728 (js2-new-node-rp node))
4729 ((js2-call-node-p node)
4730 (js2-call-node-rp node))
4731 ((js2-paren-node-p node)
4732 (1- (js2-node-len node)))
4733 ((js2-switch-node-p node)
4734 (js2-switch-node-rp node))
4735 ((js2-catch-node-p node)
4736 (js2-catch-node-rp node))
4737 ((js2-let-node-p node)
4738 (js2-let-node-rp node))
4739 ((js2-comp-node-p node)
4740 (1- (js2-node-len node)))
4741 ((js2-with-node-p node)
4742 (js2-with-node-rp node))
4743 ((js2-xml-dot-query-node-p node)
4744 (1+ (js2-xml-dot-query-node-rp node)))
4746 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4748 (defsubst js2-node-first-child (node)
4749 "Return the first element of `js2-node-child-list' for NODE."
4750 (car (js2-node-child-list node)))
4752 (defsubst js2-node-last-child (node)
4753 "Return the last element of `js2-node-last-child' for NODE."
4754 (car (last (js2-node-child-list node))))
4756 (defun js2-node-prev-sibling (node)
4757 "Return the previous statement in parent.
4758 Works for parents supported by `js2-node-child-list'.
4759 Returns nil if NODE is not in the parent, or PARENT is
4760 not a supported node, or if NODE is the first child."
4761 (let* ((p (js2-node-parent node))
4762 (kids (js2-node-child-list p))
4765 (not (eq node (cadr kids))))
4766 (setq kids (cdr kids)
4770 (defun js2-node-next-sibling (node)
4771 "Return the next statement in parent block.
4772 Returns nil if NODE is not in the block, or PARENT is not
4773 a block node, or if NODE is the last statement."
4774 (let* ((p (js2-node-parent node))
4775 (kids (js2-node-child-list p)))
4777 (not (eq node (car kids))))
4778 (setq kids (cdr kids)))
4781 (defun js2-node-find-child-before (pos parent &optional after)
4782 "Find the last child that starts before POS in parent.
4783 If AFTER is non-nil, returns first child starting after POS.
4784 POS is an absolute buffer position. PARENT is any node
4785 supported by `js2-node-child-list'.
4786 Returns nil if no applicable child is found."
4787 (let ((kids (if (js2-function-node-p parent)
4788 (js2-block-node-kids (js2-function-node-body parent))
4789 (js2-node-child-list parent)))
4790 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4791 (js2-function-node-body parent)
4795 (setq fn (if after '>= '<))
4796 (while (and kids continue)
4797 (setq kid (car kids))
4798 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4800 continue (not after))
4801 (setq continue after))
4802 (setq kids (cdr kids)))
4805 (defun js2-node-find-child-after (pos parent)
4806 "Find first child that starts after POS in parent.
4807 POS is an absolute buffer position. PARENT is any node
4808 supported by `js2-node-child-list'.
4809 Returns nil if no applicable child is found."
4810 (js2-node-find-child-before pos parent 'after))
4812 (defun js2-node-replace-child (pos parent new-node)
4813 "Replace node at index POS in PARENT with NEW-NODE.
4814 Only works for parents supported by `js2-node-child-list'."
4815 (let ((kids (js2-node-child-list parent))
4818 (setq kids (cdr kids)
4820 (setcar kids new-node)
4821 (js2-node-add-children parent new-node)))
4823 (defun js2-node-buffer (n)
4824 "Return the buffer associated with AST N.
4825 Returns nil if the buffer is not set as a property on the root
4826 node, or if parent links were not recorded during parsing."
4827 (let ((root (js2-node-root n)))
4829 (js2-ast-root-p root)
4830 (js2-ast-root-buffer root))))
4832 (defun js2-block-node-push (n kid)
4833 "Push js2-node KID onto the end of js2-block-node N's child list.
4834 KID is always added to the -end- of the kids list.
4835 Function also calls `js2-node-add-children' to add the parent link."
4836 (let ((kids (js2-node-child-list n)))
4838 (setcdr kids (nconc (cdr kids) (list kid)))
4839 (js2-node-set-child-list n (list kid)))
4840 (js2-node-add-children n kid)))
4842 (defun js2-node-string (node)
4843 (with-current-buffer (or (js2-node-buffer node)
4844 (error "No buffer available for node %s" node))
4845 (let ((pos (js2-node-abs-pos node)))
4846 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4848 ;; Container for storing the node we're looking for in a traversal.
4849 (js2-deflocal js2-discovered-node nil)
4851 ;; Keep track of absolute node position during traversals.
4852 (js2-deflocal js2-visitor-offset nil)
4854 (js2-deflocal js2-node-search-point nil)
4856 (when js2-mode-dev-mode-p
4857 (defun js2-find-node-at-point ()
4859 (let ((node (js2-node-at-point)))
4860 (message "%s" (or node "No node found at point"))))
4861 (defun js2-node-name-at-point ()
4863 (let ((node (js2-node-at-point)))
4864 (message "%s" (if node
4865 (js2-node-short-name node)
4866 "No node found at point.")))))
4868 (defun js2-node-at-point (&optional pos skip-comments)
4869 "Return AST node at POS, a buffer position, defaulting to current point.
4870 The `js2-mode-ast' variable must be set to the current parse tree.
4871 Signals an error if the AST (`js2-mode-ast') is nil.
4872 Always returns a node - if it can't find one, it returns the root.
4873 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4874 (let ((ast js2-mode-ast)
4877 (error "No JavaScript AST available"))
4878 ;; Look through comments first, since they may be inside nodes that
4879 ;; would otherwise report a match.
4880 (setq pos (or pos (point))
4881 result (if (> pos (js2-node-abs-end ast))
4883 (if (not skip-comments)
4884 (js2-comment-at-point pos))))
4886 (setq js2-discovered-node nil
4887 js2-visitor-offset 0
4888 js2-node-search-point pos)
4890 (catch 'js2-visit-done
4891 (js2-visit-ast ast #'js2-node-at-point-visitor))
4892 (setq js2-visitor-offset nil
4893 js2-node-search-point nil))
4894 (setq result js2-discovered-node))
4895 ;; may have found a comment beyond end of last child node,
4896 ;; since visiting the ast-root looks at the comment-list last.
4897 (if (and skip-comments
4898 (js2-comment-node-p result))
4900 (or result js2-mode-ast)))
4902 (defun js2-node-at-point-visitor (node end-p)
4903 (let ((rel-pos (js2-node-pos node))
4906 (point js2-node-search-point))
4909 ;; this evaluates to a non-nil return value, even if it's zero
4910 (cl-decf js2-visitor-offset rel-pos))
4911 ;; we already looked for comments before visiting, and don't want them now
4912 ((js2-comment-node-p node)
4915 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4916 ;; we only want to use the node if the point is before
4917 ;; the last character position in the node, so we decrement
4918 ;; the absolute end by 1.
4919 abs-end (+ abs-pos (js2-node-len node) -1))
4921 ;; If this node starts after search-point, stop the search.
4923 (throw 'js2-visit-done nil))
4924 ;; If this node ends before the search-point, don't check kids.
4928 ;; Otherwise point is within this node, possibly in a child.
4929 (setq js2-discovered-node node)
4930 t)))))) ; keep processing kids to look for more specific match
4932 (defsubst js2-block-comment-p (node)
4933 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4934 (and (js2-comment-node-p node)
4935 (memq (js2-comment-node-format node) '(jsdoc block))))
4937 ;; TODO: put the comments in a vector and binary-search them instead
4938 (defun js2-comment-at-point (&optional pos)
4939 "Look through scanned comment nodes for one containing POS.
4940 POS is a buffer position that defaults to current point.
4941 Function returns nil if POS was not in any comment node."
4942 (let ((ast js2-mode-ast)
4943 (x (or pos (point)))
4946 (error "No JavaScript AST available"))
4948 ;; Comments are stored in lexical order.
4949 (dolist (comment (js2-ast-root-comments ast) nil)
4950 (setq beg (js2-node-abs-pos comment)
4951 end (+ beg (js2-node-len comment)))
4954 (throw 'done comment))))))
4956 (defun js2-mode-find-parent-fn (node)
4957 "Find function enclosing NODE.
4958 Returns nil if NODE is not inside a function."
4959 (setq node (js2-node-parent node))
4960 (while (and node (not (js2-function-node-p node)))
4961 (setq node (js2-node-parent node)))
4962 (and (js2-function-node-p node) node))
4964 (defun js2-mode-find-enclosing-fn (node)
4965 "Find function or root enclosing NODE."
4966 (if (js2-ast-root-p node)
4968 (setq node (js2-node-parent node))
4969 (while (not (or (js2-ast-root-p node)
4970 (js2-function-node-p node)))
4971 (setq node (js2-node-parent node)))
4974 (defun js2-mode-find-enclosing-node (beg end)
4975 "Find node fully enclosing BEG and END."
4976 (let ((node (js2-node-at-point beg))
4980 (if (or (js2-ast-root-p node)
4982 (<= (setq pos (js2-node-abs-pos node)) beg)
4983 (>= (+ pos (js2-node-len node)) end)))
4985 (setq node (js2-node-parent node))))
4988 (defun js2-node-parent-script-or-fn (node)
4989 "Find script or function immediately enclosing NODE.
4990 If NODE is the ast-root, returns nil."
4991 (if (js2-ast-root-p node)
4993 (setq node (js2-node-parent node))
4994 (while (and node (not (or (js2-function-node-p node)
4995 (js2-script-node-p node))))
4996 (setq node (js2-node-parent node)))
4999 (defun js2-node-is-descendant (node ancestor)
5000 "Return t if NODE is a descendant of ANCESTOR."
5002 (not (eq node ancestor)))
5003 (setq node (js2-node-parent node)))
5006 ;;; visitor infrastructure
5008 (defun js2-visit-none (_node _callback)
5009 "Visitor for AST node that have no node children."
5012 (defun js2-print-none (_node _indent)
5013 "Visitor for AST node with no printed representation.")
5015 (defun js2-print-body (node indent)
5016 "Print a statement, or a block without braces."
5017 (if (js2-block-node-p node)
5018 (dolist (kid (js2-block-node-kids node))
5019 (js2-print-ast kid indent))
5020 (js2-print-ast node indent)))
5022 (defun js2-print-list (args &optional delimiter)
5023 (cl-loop with len = (length args)
5027 (when arg (js2-print-ast arg 0))
5029 (insert (or delimiter ", ")))))
5031 (defun js2-print-tree (ast)
5032 "Prints an AST to the current buffer.
5033 Makes `js2-ast-parent-nodes' available to the printer functions."
5034 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5035 (js2-print-ast ast)))
5037 (defun js2-print-ast (node &optional indent)
5038 "Helper function for printing AST nodes.
5039 Requires `js2-ast-parent-nodes' to be non-nil.
5040 You should use `js2-print-tree' instead of this function."
5041 (let ((printer (get (aref node 0) 'js2-printer))
5043 ;; TODO: wedge comments in here somewhere
5045 (funcall printer node i))))
5047 (defconst js2-side-effecting-tokens
5048 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5049 (dolist (tt (list js2-ASSIGN
5119 (if js2-instanceof-has-side-effects
5120 (aset tokens js2-INSTANCEOF t))
5123 (defun js2-node-has-side-effects (node)
5124 "Return t if NODE has side effects."
5125 (when node ; makes it easier to handle malformed expressions
5126 (let ((tt (js2-node-type node)))
5128 ;; This doubtless needs some work, since EXPR_VOID is used
5129 ;; in several ways in Rhino and I may not have caught them all.
5130 ;; I'll wait for people to notice incorrect warnings.
5131 ((and (= tt js2-EXPR_VOID)
5132 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5133 (let ((expr (js2-expr-stmt-node-expr node)))
5134 (or (js2-node-has-side-effects expr)
5135 (when (js2-string-node-p expr)
5136 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5138 (js2-node-has-side-effects (js2-infix-node-right node)))
5141 (or (js2-node-has-side-effects (js2-infix-node-right node))
5142 (js2-node-has-side-effects (js2-infix-node-left node))))
5144 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5145 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5146 ((js2-paren-node-p node)
5147 (js2-node-has-side-effects (js2-paren-node-expr node)))
5148 ((= tt js2-ERROR) ; avoid cascaded error messages
5151 (aref js2-side-effecting-tokens tt))))))
5153 (defconst js2-stmt-node-types
5157 js2-DEFAULT ; e4x "default xml namespace" statement
5171 "Node types that only appear in statement contexts.
5172 The list does not include nodes that always appear as the child
5173 of another specific statement type, such as switch-cases,
5174 catch and finally blocks, and else-clauses. The list also excludes
5175 nodes like yield, let and var, which may appear in either expression
5176 or statement context, and in the latter context always have a
5177 `js2-expr-stmt-node' parent. Finally, the list does not include
5178 functions or scripts, which are treated separately from statements
5179 by the JavaScript parser and runtime.")
5181 (defun js2-stmt-node-p (node)
5182 "Heuristic for figuring out if NODE is a statement.
5183 Some node types can appear in either an expression context or a
5184 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5185 For these node types in a statement context, the parent will be a
5186 `js2-expr-stmt-node'.
5187 Functions aren't included in the check."
5188 (memq (js2-node-type node) js2-stmt-node-types))
5190 (defun js2-mode-find-first-stmt (node)
5191 "Search upward starting from NODE looking for a statement.
5192 For purposes of this function, a `js2-function-node' counts."
5193 (while (not (or (js2-stmt-node-p node)
5194 (js2-function-node-p node)))
5195 (setq node (js2-node-parent node)))
5198 (defun js2-node-parent-stmt (node)
5199 "Return the node's first ancestor that is a statement.
5200 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5201 appearing in a statement context will have a parent that is a
5202 `js2-expr-stmt-node' that will be returned by this function."
5203 (let ((parent (js2-node-parent node)))
5204 (if (or (null parent)
5205 (js2-stmt-node-p parent)
5206 (and (js2-function-node-p parent)
5207 (not (eq (js2-function-node-form parent)
5208 'FUNCTION_EXPRESSION))))
5210 (js2-node-parent-stmt parent))))
5212 ;; In the Mozilla Rhino sources, Roshan James writes:
5213 ;; Does consistent-return analysis on the function body when strict mode is
5216 ;; function (x) { return (x+1) }
5220 ;; function (x) { if (x < 0) return (x+1); }
5222 ;; is not because the function can potentially return a value when the
5223 ;; condition is satisfied and if not, the function does not explicitly
5226 ;; This extends to checking mismatches such as "return" and "return <value>"
5227 ;; used in the same function. Warnings are not emitted if inconsistent
5228 ;; returns exist in code that can be statically shown to be unreachable.
5230 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5232 ;; emits no warning. However if the loop had a break statement, then a
5233 ;; warning would be emitted.
5235 ;; The consistency analysis looks at control structures such as loops, ifs,
5236 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5237 ;; warns the user about an inconsistent set of termination possibilities.
5239 ;; These flags enumerate the possible ways a statement/function can
5240 ;; terminate. These flags are used by endCheck() and by the Parser to
5241 ;; detect inconsistent return usage.
5243 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5244 ;; able to execute (example: throw, continue)
5246 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5247 ;; next one. Statement such as return dont. A compound statement may have
5248 ;; some branch that drops off control to the next statement.
5250 ;; END_RETURNS indicates that the statement can return with no value.
5251 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5253 ;; A compound statement such as
5257 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5259 (defconst js2-END_UNREACHED 0)
5260 (defconst js2-END_DROPS_OFF 1)
5261 (defconst js2-END_RETURNS 2)
5262 (defconst js2-END_RETURNS_VALUE 4)
5263 (defconst js2-END_YIELDS 8)
5265 (defun js2-has-consistent-return-usage (node)
5266 "Check that every return usage in a function body is consistent.
5267 Returns t if the function satisfies strict mode requirement."
5268 (let ((n (js2-end-check node)))
5269 ;; either it doesn't return a value in any branch...
5270 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5271 ;; or it returns a value (or is unreached) at every branch
5272 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5276 (defun js2-end-check-if (node)
5277 "Ensure that return usage in then/else blocks is consistent.
5278 If there is no else block, then the return statement can fall through.
5279 Returns logical OR of END_* flags"
5280 (let ((th (js2-if-node-then-part node))
5281 (el (js2-if-node-else-part node)))
5284 (logior (js2-end-check th) (if el
5286 js2-END_DROPS_OFF)))))
5288 (defun js2-end-check-switch (node)
5289 "Consistency of return statements is checked between the case statements.
5290 If there is no default, then the switch can fall through. If there is a
5291 default, we check to see if all code paths in the default return or if
5292 there is a code path that can fall through.
5293 Returns logical OR of END_* flags."
5294 (let ((rv js2-END_UNREACHED)
5296 ;; examine the cases
5298 (dolist (c (js2-switch-node-cases node))
5299 (if (js2-case-node-expr c)
5300 (js2-set-flag rv (js2-end-check-block c))
5301 (setq default-case c)
5302 (throw 'break nil))))
5303 ;; we don't care how the cases drop into each other
5304 (js2-clear-flag rv js2-END_DROPS_OFF)
5305 ;; examine the default
5306 (js2-set-flag rv (if default-case
5307 (js2-end-check default-case)
5311 (defun js2-end-check-try (node)
5312 "If the block has a finally, return consistency is checked in the
5313 finally block. If all code paths in the finally return, then the
5314 returns in the try-catch blocks don't matter. If there is a code path
5315 that does not return or if there is no finally block, the returns
5316 of the try and catch blocks are checked for mismatch.
5317 Returns logical OR of END_* flags."
5318 (let ((finally (js2-try-node-finally-block node))
5320 ;; check the finally if it exists
5321 (setq rv (if finally
5322 (js2-end-check (js2-finally-node-body finally))
5324 ;; If the finally block always returns, then none of the returns
5325 ;; in the try or catch blocks matter.
5326 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5327 (js2-clear-flag rv js2-END_DROPS_OFF)
5328 ;; examine the try block
5329 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5330 ;; check each catch block
5331 (dolist (cb (js2-try-node-catch-clauses node))
5332 (js2-set-flag rv (js2-end-check cb))))
5335 (defun js2-end-check-loop (node)
5336 "Return statement in the loop body must be consistent.
5337 The default assumption for any kind of a loop is that it will eventually
5338 terminate. The only exception is a loop with a constant true condition.
5339 Code that follows such a loop is examined only if one can determine
5340 statically that there is a break out of the loop.
5342 for(... ; ... ; ...) {}
5347 Returns logical OR of END_* flags."
5348 (let ((rv (js2-end-check (js2-loop-node-body node)))
5350 ((js2-while-node-p node)
5351 (js2-while-node-condition node))
5352 ((js2-do-node-p node)
5353 (js2-do-node-condition node))
5354 ((js2-for-node-p node)
5355 (js2-for-node-condition node)))))
5357 ;; check to see if the loop condition is always true
5359 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5360 (js2-clear-flag rv js2-END_DROPS_OFF))
5362 ;; look for effect of breaks
5363 (js2-set-flag rv (js2-node-get-prop node
5368 (defun js2-end-check-block (node)
5369 "A general block of code is examined statement by statement.
5370 If any statement (even a compound one) returns in all branches, then
5371 subsequent statements are not examined.
5372 Returns logical OR of END_* flags."
5373 (let* ((rv js2-END_DROPS_OFF)
5374 (kids (js2-block-node-kids node))
5376 ;; Check each statement. If the statement can continue onto the next
5377 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5378 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5379 (js2-clear-flag rv js2-END_DROPS_OFF)
5380 (js2-set-flag rv (js2-end-check n))
5381 (setq kids (cdr kids)
5385 (defun js2-end-check-label (node)
5386 "A labeled statement implies that there may be a break to the label.
5387 The function processes the labeled statement and then checks the
5388 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5390 Returns logical OR of END_* flags."
5391 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5392 (logior rv (js2-node-get-prop node
5394 js2-END_UNREACHED))))
5396 (defun js2-end-check-break (node)
5397 "When a break is encountered annotate the statement being broken
5398 out of by setting its CONTROL_BLOCK_PROP property.
5399 Returns logical OR of END_* flags."
5400 (and (js2-break-node-target node)
5401 (js2-node-set-prop (js2-break-node-target node)
5406 (defun js2-end-check (node)
5407 "Examine the body of a function, doing a basic reachability analysis.
5408 Returns a combination of flags END_* flags that indicate
5409 how the function execution can terminate. These constitute only the
5410 pessimistic set of termination conditions. It is possible that at
5411 runtime certain code paths will never be actually taken. Hence this
5412 analysis will flag errors in cases where there may not be errors.
5413 Returns logical OR of END_* flags"
5416 ((js2-break-node-p node)
5417 (js2-end-check-break node))
5418 ((js2-expr-stmt-node-p node)
5419 (if (setq kid (js2-expr-stmt-node-expr node))
5422 ((or (js2-continue-node-p node)
5423 (js2-throw-node-p node))
5425 ((js2-return-node-p node)
5426 (if (setq kid (js2-return-node-retval node))
5427 js2-END_RETURNS_VALUE
5429 ((js2-loop-node-p node)
5430 (js2-end-check-loop node))
5431 ((js2-switch-node-p node)
5432 (js2-end-check-switch node))
5433 ((js2-labeled-stmt-node-p node)
5434 (js2-end-check-label node))
5435 ((js2-if-node-p node)
5436 (js2-end-check-if node))
5437 ((js2-try-node-p node)
5438 (js2-end-check-try node))
5439 ((js2-block-node-p node)
5440 (if (null (js2-block-node-kids node))
5442 (js2-end-check-block node)))
5443 ((js2-yield-node-p node)
5446 js2-END_DROPS_OFF))))
5448 (defun js2-always-defined-boolean-p (node)
5449 "Check if NODE always evaluates to true or false in boolean context.
5450 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5452 (let ((tt (js2-node-type node))
5455 ((or (= tt js2-FALSE) (= tt js2-NULL))
5460 (setq num (js2-number-node-num-value node))
5461 (if (and (not (eq num 0.0e+NaN))
5468 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5469 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5471 (defvar js2-tokens nil
5472 "List of all defined token names.") ; initialized in `js2-token-names'
5474 (defconst js2-token-names
5475 (let* ((names (make-vector js2-num-tokens -1))
5476 (case-fold-search nil) ; only match js2-UPPER_CASE
5477 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5478 (cl-loop for sym in syms
5481 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5483 (aset names (symbol-value sym) ; code, e.g. 152
5485 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5486 (push sym js2-tokens)))
5488 "Vector mapping int values to token string names, sans `js2-' prefix.")
5490 (defun js2-tt-name (tok)
5491 "Return a string name for TOK, a token symbol or code.
5492 Signals an error if it's not a recognized token."
5495 (setq code (symbol-value tok)))
5498 (if (and (numberp code)
5499 (not (cl-minusp code))
5500 (< code js2-num-tokens))
5501 (aref js2-token-names code)
5502 (error "Invalid token: %s" code)))))
5504 (defsubst js2-tt-sym (tok)
5505 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5506 (intern (js2-tt-name tok)))
5508 (defconst js2-token-codes
5509 (let ((table (make-hash-table :test 'eq :size 256)))
5510 (cl-loop for name across js2-token-names
5511 for sym = (intern (concat "js2-" (upcase name)))
5513 (puthash sym (symbol-value sym) table))
5514 ;; clean up a few that are "wrong" in Rhino's token codes
5515 (puthash 'js2-DELETE js2-DELPROP table)
5517 "Hashtable mapping token type symbols to their bytecodes.")
5519 (defsubst js2-tt-code (sym)
5520 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5521 (or (gethash sym js2-token-codes)
5522 (error "Invalid token symbol: %s " sym))) ; signal code bug
5524 (defun js2-report-scan-error (msg &optional no-throw beg len)
5525 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5526 (js2-report-error msg nil
5527 (or beg (js2-current-token-beg))
5528 (or len (js2-current-token-len)))
5530 (throw 'return js2-ERROR)))
5532 (defun js2-set-string-from-buffer (token)
5533 "Set `string' and `end' slots for TOKEN, return the string."
5534 (setf (js2-token-end token) js2-ts-cursor
5535 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5537 ;; TODO: could potentially avoid a lot of consing by allocating a
5538 ;; char buffer the way Rhino does.
5539 (defsubst js2-add-to-string (c)
5540 (push c js2-ts-string-buffer))
5542 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5543 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5544 ;; any other character: when it's not part of the current token, we
5545 ;; unget it, allowing it to be read again by the following call.
5546 (defsubst js2-unget-char ()
5547 (cl-decf js2-ts-cursor))
5549 ;; Rhino distinguishes \r and \n line endings. We don't need to
5550 ;; because we only scan from Emacs buffers, which always use \n.
5551 (defun js2-get-char ()
5552 "Read and return the next character from the input buffer.
5553 Increments `js2-ts-lineno' if the return value is a newline char.
5554 Updates `js2-ts-cursor' to the point after the returned char.
5555 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5556 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5558 ;; check for end of buffer
5559 (if (>= js2-ts-cursor (point-max))
5560 (setq js2-ts-hit-eof t
5561 js2-ts-cursor (1+ js2-ts-cursor)
5562 c js2-EOF_CHAR) ; return value
5563 ;; otherwise read next char
5564 (setq c (char-before (cl-incf js2-ts-cursor)))
5565 ;; if we read a newline, update counters
5567 (setq js2-ts-line-start js2-ts-cursor
5568 js2-ts-lineno (1+ js2-ts-lineno)))
5569 ;; TODO: skip over format characters
5572 (defun js2-read-unicode-escape ()
5573 "Read a \\uNNNN sequence from the input.
5574 Assumes the ?\ and ?u have already been read.
5575 Returns the unicode character, or nil if it wasn't a valid character.
5576 Doesn't change the values of any scanner variables."
5577 ;; I really wish I knew a better way to do this, but I can't
5578 ;; find the Emacs function that takes a 16-bit int and converts
5579 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5580 ;; Have to first check that it's 4 hex characters or it may stop
5583 (let ((s (buffer-substring-no-properties js2-ts-cursor
5584 (+ 4 js2-ts-cursor))))
5585 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5586 (read (concat "?\\u" s))))))
5588 (defun js2-match-char (test)
5589 "Consume and return next character if it matches TEST, a character.
5590 Returns nil and consumes nothing if TEST is not the next character."
5591 (let ((c (js2-get-char)))
5597 (defun js2-peek-char ()
5602 (defun js2-identifier-start-p (c)
5603 "Is C a valid start to an ES5 Identifier?
5604 See http://es5.github.io/#x7.6"
5607 (memq (get-char-code-property c 'general-category)
5609 '(Lu Ll Lt Lm Lo Nl))))
5611 (defun js2-identifier-part-p (c)
5612 "Is C a valid part of an ES5 Identifier?
5613 See http://es5.github.io/#x7.6"
5615 (memq c '(?$ ?_ ?\u200c ?\u200d))
5616 (memq (get-char-code-property c 'general-category)
5623 ;; Connector Punctuation
5626 (defun js2-alpha-p (c)
5627 (cond ((and (<= ?A c) (<= c ?Z)) t)
5628 ((and (<= ?a c) (<= c ?z)) t)
5631 (defsubst js2-digit-p (c)
5632 (and (<= ?0 c) (<= c ?9)))
5634 (defun js2-js-space-p (c)
5636 (memq c '(#x20 #x9 #xB #xC #xD))
5639 ;; TODO: change this nil to check for Unicode space character
5642 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5644 (defun js2-skip-line ()
5645 "Skip to end of line."
5646 (while (not (memq (js2-get-char) js2-eol-chars)))
5648 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5650 (defun js2-init-scanner (&optional buf line)
5651 "Create token stream for BUF starting on LINE.
5652 BUF defaults to `current-buffer' and LINE defaults to 1.
5654 A buffer can only have one scanner active at a time, which yields
5655 dramatically simpler code than using a defstruct. If you need to
5656 have simultaneous scanners in a buffer, copy the regions to scan
5658 (with-current-buffer (or buf (current-buffer))
5659 (setq js2-ts-dirty-line nil
5662 js2-ts-lineno (or line 1)
5663 js2-ts-line-end-char -1
5664 js2-ts-cursor (point-min)
5665 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5666 js2-ti-tokens-cursor 0
5668 js2-ts-is-xml-attribute nil
5669 js2-ts-xml-is-tag-content nil
5670 js2-ts-xml-open-tags-count 0
5671 js2-ts-string-buffer nil)))
5673 ;; This function uses the cached op, string and number fields in
5674 ;; TokenStream; if getToken has been called since the passed token
5675 ;; was scanned, the op or string printed may be incorrect.
5676 (defun js2-token-to-string (token)
5677 ;; Not sure where this function is used in Rhino. Not tested.
5678 (if (not js2-debug-print-trees)
5680 (let ((name (js2-tt-name token)))
5682 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5683 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5684 (concat name " `" (js2-current-token-string) "'"))
5685 ((eq token js2-NUMBER)
5686 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5690 (defconst js2-keywords
5692 case catch class const continue
5693 debugger default delete do
5695 false finally for function
5696 if in instanceof import
5701 this throw true try typeof
5706 ;; Token names aren't exactly the same as the keywords, unfortunately.
5707 ;; E.g. delete is js2-DELPROP.
5708 (defconst js2-kwd-tokens
5709 (let ((table (make-vector js2-num-tokens nil))
5712 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5713 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5715 js2-ELSE js2-EXTENDS js2-EXPORT
5716 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5717 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5721 js2-SUPER js2-SWITCH
5722 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5727 (aset table i 'font-lock-keyword-face))
5728 (aset table js2-STRING 'font-lock-string-face)
5729 (aset table js2-REGEXP 'font-lock-string-face)
5730 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5731 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5732 (aset table js2-COMMENT 'font-lock-comment-face)
5733 (aset table js2-THIS 'font-lock-builtin-face)
5734 (aset table js2-SUPER 'font-lock-builtin-face)
5735 (aset table js2-VOID 'font-lock-constant-face)
5736 (aset table js2-NULL 'font-lock-constant-face)
5737 (aset table js2-TRUE 'font-lock-constant-face)
5738 (aset table js2-FALSE 'font-lock-constant-face)
5739 (aset table js2-NOT 'font-lock-negation-char-face)
5741 "Vector whose values are non-nil for tokens that are keywords.
5742 The values are default faces to use for highlighting the keywords.")
5744 ;; FIXME: Support strict mode-only future reserved words, after we know
5745 ;; which parts scopes are in strict mode, and which are not.
5746 (defconst js2-reserved-words '(class enum export extends import static super)
5747 "Future reserved keywords in ECMAScript 5.1.")
5749 (defconst js2-keyword-names
5750 (let ((table (make-hash-table :test 'equal)))
5751 (cl-loop for k in js2-keywords
5753 (symbol-name k) ; instanceof
5754 (intern (concat "js2-"
5755 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5758 "JavaScript keywords by name, mapped to their symbols.")
5760 (defconst js2-reserved-word-names
5761 (let ((table (make-hash-table :test 'equal)))
5762 (cl-loop for k in js2-reserved-words
5764 (puthash (symbol-name k) 'js2-RESERVED table))
5766 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5768 (defun js2-collect-string (buf)
5769 "Convert BUF, a list of chars, to a string.
5770 Reverses BUF before converting."
5772 (apply #'string (nreverse buf))
5775 (defun js2-string-to-keyword (s)
5776 "Return token for S, a string, if S is a keyword or reserved word.
5777 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5778 (or (gethash s js2-keyword-names)
5779 (gethash s js2-reserved-word-names)))
5781 (defsubst js2-ts-set-char-token-bounds (token)
5782 "Used when next token is one character."
5783 (setf (js2-token-beg token) (1- js2-ts-cursor)
5784 (js2-token-end token) js2-ts-cursor))
5786 (defsubst js2-ts-return (token type)
5787 "Update the `end' and `type' slots of TOKEN,
5788 then throw `return' with value TYPE."
5789 (setf (js2-token-end token) js2-ts-cursor
5790 (js2-token-type token) type)
5791 (throw 'return type))
5793 (defun js2-x-digit-to-int (c accumulator)
5794 "Build up a hex number.
5795 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5796 corresponding number. Otherwise return -1."
5799 ;; Use 0..9 < A..Z < a..z
5804 (throw 'check nil)))
5807 (cl-decf c (- ?A 10))
5808 (throw 'check nil)))
5811 (cl-decf c (- ?a 10))
5812 (throw 'check nil))))
5814 (logior c (lsh accumulator 4))))
5816 (defun js2-get-token (&optional modifier)
5817 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5818 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5821 This function will not return a newline (js2-EOL) - instead, it
5822 gobbles newlines until it finds a non-newline token. Call
5823 `js2-peek-token-or-eol' when you care about newlines.
5825 This function will also not return a js2-COMMENT. Instead, it
5826 records comments found in `js2-scanned-comments'. If the token
5827 returned by this function immediately follows a jsdoc comment,
5828 the token is flagged as such."
5829 (if (zerop js2-ti-lookahead)
5830 (js2-get-token-internal modifier)
5831 (cl-decf js2-ti-lookahead)
5832 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5833 (let ((tt (js2-current-token-type)))
5834 (cl-assert (not (= tt js2-EOL)))
5837 (defun js2-unget-token ()
5838 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5839 (cl-incf js2-ti-lookahead)
5840 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5842 (defun js2-get-token-internal (modifier)
5843 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5844 (tt (js2-token-type token))
5848 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5852 (when js2-record-comments
5853 (js2-record-comment token)))
5854 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5855 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5856 tt (js2-token-type token)))
5859 (setf (js2-token-follows-eol-p token) t))
5861 ;; perform lexical fontification as soon as token is scanned
5862 (when js2-parse-ide-mode
5865 (js2-record-face 'js2-error token))
5866 ((setq face (aref js2-kwd-tokens tt))
5867 (js2-record-face face token))
5868 ((and (= tt js2-NAME)
5869 (equal (js2-token-string token) "undefined"))
5870 (js2-record-face 'font-lock-constant-face token))))
5873 (defsubst js2-string-to-number (str base)
5874 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5876 (string-to-number str base)
5877 (overflow-error -1)))
5879 (defun js2-get-token-internal-1 (modifier)
5880 "Return next JavaScript token type, an int such as js2-RETURN.
5881 During operation, creates an instance of `js2-token' struct, sets
5882 its relevant fields and puts it into `js2-ti-tokens'."
5883 (let (identifier-start
5884 is-unicode-escape-start c
5885 contains-escape escape-val str result base
5886 look-for-slash continue tt legacy-octal
5887 (token (js2-new-token 0)))
5891 (when (eq modifier 'TEMPLATE_TAIL)
5892 (setf (js2-token-beg token) (1- js2-ts-cursor))
5893 (throw 'return (js2-get-string-or-template-token ?` token)))
5895 ;; Eat whitespace, possibly sensitive to newlines.
5898 (setq c (js2-get-char))
5900 ((eq c js2-EOF_CHAR)
5902 (js2-ts-set-char-token-bounds token)
5903 (throw 'return js2-EOF))
5905 (js2-ts-set-char-token-bounds token)
5906 (setq js2-ts-dirty-line nil)
5907 (throw 'return js2-EOL))
5908 ((not (js2-js-space-p c))
5909 (if (/= c ?-) ; in case end of HTML comment
5910 (setq js2-ts-dirty-line t))
5911 (setq continue nil))))
5912 ;; Assume the token will be 1 char - fixed up below.
5913 (js2-ts-set-char-token-bounds token)
5915 (throw 'return js2-XMLATTR))
5916 ;; identifier/keyword/instanceof?
5917 ;; watch out for starting with a <backslash>
5920 (setq c (js2-get-char))
5922 (setq identifier-start t
5923 is-unicode-escape-start t
5924 js2-ts-string-buffer nil)
5925 (setq identifier-start nil)
5929 (when (setq identifier-start (js2-identifier-start-p c))
5930 (setq js2-ts-string-buffer nil)
5931 (js2-add-to-string c))))
5932 (when identifier-start
5933 (setq contains-escape is-unicode-escape-start)
5936 (if is-unicode-escape-start
5937 ;; strictly speaking we should probably push-back
5938 ;; all the bad characters if the <backslash>uXXXX
5939 ;; sequence is malformed. But since there isn't a
5940 ;; correct context(is there?) for a bad Unicode
5941 ;; escape sequence in an identifier, we can report
5946 (setq c (js2-get-char)
5947 escape-val (js2-x-digit-to-int c escape-val))
5948 ;; Next check takes care of c < 0 and bad escape
5949 (if (cl-minusp escape-val)
5950 (throw 'break nil)))
5951 (if (cl-minusp escape-val)
5952 (js2-report-scan-error "msg.invalid.escape" t))
5953 (js2-add-to-string escape-val)
5954 (setq is-unicode-escape-start nil))
5955 (setq c (js2-get-char))
5958 (setq c (js2-get-char))
5960 (setq is-unicode-escape-start t
5962 (js2-report-scan-error "msg.illegal.character" t)))
5964 (if (or (eq c js2-EOF_CHAR)
5965 (not (js2-identifier-part-p c)))
5967 (js2-add-to-string c))))))
5969 (setf str (js2-collect-string js2-ts-string-buffer)
5970 (js2-token-end token) js2-ts-cursor)
5971 ;; FIXME: Invalid in ES5 and ES6, see
5972 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5973 ;; Probably should just drop this conditional.
5974 (unless contains-escape
5975 ;; OPT we shouldn't have to make a string (object!) to
5976 ;; check if it's a keyword.
5977 ;; Return the corresponding token if it's a keyword
5978 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5979 (setq result (js2-string-to-keyword str)))
5980 (if (and (< js2-language-version 170)
5981 (memq result '(js2-LET js2-YIELD)))
5982 ;; LET and YIELD are tokens only in 1.7 and later
5983 (setq result 'js2-NAME))
5984 (when (eq result 'js2-RESERVED)
5985 (setf (js2-token-string token) str))
5986 (throw 'return (js2-tt-code result))))
5987 ;; If we want to intern these as Rhino does, just use (intern str)
5988 (setf (js2-token-string token) str)
5989 (throw 'return js2-NAME)) ; end identifier/kwd check
5991 (when (or (js2-digit-p c)
5992 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5993 (setq js2-ts-string-buffer nil
5996 (setq c (js2-get-char))
5998 ((or (eq c ?x) (eq c ?X))
6000 (setq c (js2-get-char)))
6001 ((and (or (eq c ?b) (eq c ?B))
6002 (>= js2-language-version 200))
6004 (setq c (js2-get-char)))
6005 ((and (or (eq c ?o) (eq c ?O))
6006 (>= js2-language-version 200))
6008 (setq legacy-octal nil)
6009 (setq c (js2-get-char)))
6011 (setq base 'maybe-8))
6013 (js2-add-to-string ?0))))
6016 (if (> 0 (js2-x-digit-to-int c 0))
6017 (js2-report-scan-error "msg.missing.hex.digits")
6018 (while (<= 0 (js2-x-digit-to-int c 0))
6019 (js2-add-to-string c)
6020 (setq c (js2-get-char)))))
6022 (if (not (memq c '(?0 ?1)))
6023 (js2-report-scan-error "msg.missing.binary.digits")
6024 (while (memq c '(?0 ?1))
6025 (js2-add-to-string c)
6026 (setq c (js2-get-char)))))
6028 (if (or (> ?0 c) (< ?7 c))
6029 (js2-report-scan-error "msg.missing.octal.digits")
6030 (while (and (<= ?0 c) (>= ?7 c))
6031 (js2-add-to-string c)
6032 (setq c (js2-get-char)))))
6034 (while (and (<= ?0 c) (<= c ?9))
6035 ;; We permit 08 and 09 as decimal numbers, which
6036 ;; makes our behavior a superset of the ECMA
6037 ;; numeric grammar. We might not always be so
6038 ;; permissive, so we warn about it.
6039 (when (and (eq base 'maybe-8) (>= c ?8))
6040 (js2-report-warning "msg.bad.octal.literal"
6041 (if (eq c ?8) "8" "9"))
6043 (js2-add-to-string c)
6044 (setq c (js2-get-char)))
6045 (when (eq base 'maybe-8)
6048 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6051 (js2-add-to-string c)
6052 (setq c (js2-get-char))
6053 while (js2-digit-p c)))
6054 (when (memq c '(?e ?E))
6055 (js2-add-to-string c)
6056 (setq c (js2-get-char))
6057 (when (memq c '(?+ ?-))
6058 (js2-add-to-string c)
6059 (setq c (js2-get-char)))
6060 (unless (js2-digit-p c)
6061 (js2-report-scan-error "msg.missing.exponent" t))
6063 (js2-add-to-string c)
6064 (setq c (js2-get-char))
6065 while (js2-digit-p c))))
6067 (let ((str (js2-set-string-from-buffer token)))
6068 (setf (js2-token-number token) (js2-string-to-number str base)
6069 (js2-token-number-base token) base
6070 (js2-token-number-legacy-octal-p token) (and (= base 8) legacy-octal)))
6071 (throw 'return js2-NUMBER))
6073 (when (or (memq c '(?\" ?\'))
6074 (and (>= js2-language-version 200)
6077 (js2-get-string-or-template-token c token)))
6078 (js2-ts-return token
6081 (throw 'return js2-SEMI))
6083 (throw 'return js2-LB))
6085 (throw 'return js2-RB))
6087 (throw 'return js2-LC))
6089 (throw 'return js2-RC))
6091 (throw 'return js2-LP))
6093 (throw 'return js2-RP))
6095 (throw 'return js2-COMMA))
6097 (throw 'return js2-HOOK))
6099 (if (js2-match-char ?:)
6101 (throw 'return js2-COLON)))
6103 (if (js2-match-char ?.)
6104 (if (js2-match-char ?.)
6105 js2-TRIPLEDOT js2-DOTDOT)
6106 (if (js2-match-char ?\()
6108 (throw 'return js2-DOT))))
6110 (if (js2-match-char ?|)
6111 (throw 'return js2-OR)
6112 (if (js2-match-char ?=)
6114 (throw 'return js2-BITOR))))
6116 (if (js2-match-char ?=)
6118 (throw 'return js2-BITXOR)))
6120 (if (js2-match-char ?&)
6121 (throw 'return js2-AND)
6122 (if (js2-match-char ?=)
6124 (throw 'return js2-BITAND))))
6126 (if (js2-match-char ?=)
6127 (if (js2-match-char ?=)
6129 (throw 'return js2-EQ))
6130 (if (js2-match-char ?>)
6131 (js2-ts-return token js2-ARROW)
6132 (throw 'return js2-ASSIGN))))
6134 (if (js2-match-char ?=)
6135 (if (js2-match-char ?=)
6138 (throw 'return js2-NOT)))
6140 ;; NB:treat HTML begin-comment as comment-till-eol
6141 (when (js2-match-char ?!)
6142 (when (js2-match-char ?-)
6143 (when (js2-match-char ?-)
6145 (setf (js2-token-comment-type (js2-current-token)) 'html)
6146 (throw 'return js2-COMMENT)))
6148 (if (js2-match-char ?<)
6149 (if (js2-match-char ?=)
6152 (if (js2-match-char ?=)
6154 (throw 'return js2-LT))))
6156 (if (js2-match-char ?>)
6157 (if (js2-match-char ?>)
6158 (if (js2-match-char ?=)
6161 (if (js2-match-char ?=)
6164 (if (js2-match-char ?=)
6166 (throw 'return js2-GT))))
6168 (if (js2-match-char ?=)
6170 (throw 'return js2-MUL)))
6172 ;; is it a // comment?
6173 (when (js2-match-char ?/)
6174 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6176 (setf (js2-token-comment-type token) 'line)
6177 ;; include newline so highlighting goes to end of
6178 ;; window, if there actually is a newline; if we
6179 ;; hit eof, then implicitly there isn't
6180 (unless js2-ts-hit-eof
6181 (cl-incf (js2-token-end token)))
6182 (throw 'return js2-COMMENT))
6183 ;; is it a /* comment?
6184 (when (js2-match-char ?*)
6185 (setf look-for-slash nil
6186 (js2-token-beg token) (- js2-ts-cursor 2)
6187 (js2-token-comment-type token)
6188 (if (js2-match-char ?*)
6190 (setq look-for-slash t)
6194 (setq c (js2-get-char))
6196 ((eq c js2-EOF_CHAR)
6197 (setf (js2-token-end token) (1- js2-ts-cursor))
6198 (js2-report-error "msg.unterminated.comment")
6199 (throw 'return js2-COMMENT))
6201 (setq look-for-slash t))
6204 (js2-ts-return token js2-COMMENT)))
6206 (setf look-for-slash nil
6207 (js2-token-end token) js2-ts-cursor)))))
6208 (if (js2-match-char ?=)
6210 (throw 'return js2-DIV)))
6212 (when js2-skip-preprocessor-directives
6214 (setf (js2-token-comment-type token) 'preprocessor
6215 (js2-token-end token) js2-ts-cursor)
6216 (throw 'return js2-COMMENT))
6217 (throw 'return js2-ERROR))
6219 (if (js2-match-char ?=)
6221 (throw 'return js2-MOD)))
6223 (throw 'return js2-BITNOT))
6225 (if (js2-match-char ?=)
6227 (if (js2-match-char ?+)
6229 (throw 'return js2-ADD))))
6232 ((js2-match-char ?=)
6233 (setq c js2-ASSIGN_SUB))
6234 ((js2-match-char ?-)
6235 (unless js2-ts-dirty-line
6236 ;; treat HTML end-comment after possible whitespace
6237 ;; after line start as comment-until-eol
6238 (when (js2-match-char ?>)
6240 (setf (js2-token-comment-type (js2-current-token)) 'html)
6241 (throw 'return js2-COMMENT)))
6245 (setq js2-ts-dirty-line t)
6248 (js2-report-scan-error "msg.illegal.character")))))))
6249 (setf (js2-token-type token) tt)
6252 (defun js2-get-string-or-template-token (quote-char token)
6253 ;; We attempt to accumulate a string the fast way, by
6254 ;; building it directly out of the reader. But if there
6255 ;; are any escaped characters in the string, we revert to
6256 ;; building it out of a string buffer.
6257 (let ((c (js2-get-char))
6258 js2-ts-string-buffer
6259 nc c1 val escape-val)
6261 (while (/= c quote-char)
6263 (when (eq c js2-EOF_CHAR)
6265 (js2-report-error "msg.unterminated.string.lit")
6267 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6269 (js2-report-error "msg.unterminated.string.lit")
6272 ;; We've hit an escaped character
6273 (setq c (js2-get-char))
6282 (setq c1 (js2-read-unicode-escape))
6283 (if js2-parse-ide-mode
6286 ;; just copy the string in IDE-mode
6287 (js2-add-to-string ?\\)
6288 (js2-add-to-string ?u)
6290 (js2-add-to-string (js2-get-char)))
6291 (setq c (js2-get-char))) ; added at end of loop
6292 ;; flag it as an invalid escape
6293 (js2-report-warning "msg.invalid.escape"
6294 nil (- js2-ts-cursor 2) 6))
6295 ;; Get 4 hex digits; if the u escape is not
6296 ;; followed by 4 hex digits, use 'u' + the
6297 ;; literal character sequence that follows.
6298 (js2-add-to-string ?u)
6301 (setq c (js2-get-char)
6302 escape-val (js2-x-digit-to-int c escape-val))
6303 (if (cl-minusp escape-val)
6304 (throw 'continue nil))
6305 (js2-add-to-string c))
6306 ;; prepare for replace of stored 'u' sequence by escape value
6307 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6310 ;; Get 2 hex digits, defaulting to 'x'+literal
6311 ;; sequence, as above.
6312 (setq c (js2-get-char)
6313 escape-val (js2-x-digit-to-int c 0))
6314 (if (cl-minusp escape-val)
6316 (js2-add-to-string ?x)
6317 (throw 'continue nil))
6320 escape-val (js2-x-digit-to-int c escape-val))
6321 (if (cl-minusp escape-val)
6323 (js2-add-to-string ?x)
6324 (js2-add-to-string c1)
6325 (throw 'continue nil))
6327 (setq c escape-val))))
6329 ;; Remove line terminator after escape to follow
6330 ;; SpiderMonkey and C/C++
6331 (setq c (js2-get-char))
6332 (throw 'continue nil))
6334 (when (and (<= ?0 c) (< c ?8))
6337 (when (and (<= ?0 c) (< c ?8))
6338 (setq val (- (+ (* 8 val) c) ?0)
6340 (when (and (<= ?0 c)
6343 ;; c is 3rd char of octal sequence only
6344 ;; if the resulting val <= 0377
6345 (setq val (- (+ (* 8 val) c) ?0)
6349 (when (and (eq quote-char ?`) (eq c ?$))
6350 (when (eq (setq nc (js2-get-char)) ?\{)
6353 (js2-add-to-string c)
6354 (setq c (js2-get-char)))))
6355 (js2-set-string-from-buffer token)
6356 (if (not (eq quote-char ?`))
6358 (if (and (eq c ?$) (eq nc ?\{))
6360 js2-NO_SUBS_TEMPLATE))))
6362 (defun js2-read-regexp (start-tt)
6363 "Called by parser when it gets / or /= in literal context."
6365 in-class ; inside a '[' .. ']' character-class
6368 (token (js2-new-token 0)))
6369 (setq js2-ts-string-buffer nil)
6370 (if (eq start-tt js2-ASSIGN_DIV)
6372 (js2-add-to-string ?=)
6373 (if (not (eq start-tt js2-DIV))
6374 (error "failed assertion")))
6375 (while (and (not err)
6376 (or (/= (setq c (js2-get-char)) ?/)
6381 (setf (js2-token-end token) (1- js2-ts-cursor)
6383 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6384 (js2-report-error "msg.unterminated.re.lit"))
6387 (js2-add-to-string c)
6388 (setq c (js2-get-char)))
6392 (setq in-class nil)))
6393 (js2-add-to-string c))))
6397 ((js2-match-char ?g)
6399 ((js2-match-char ?i)
6401 ((js2-match-char ?m)
6403 ((and (js2-match-char ?u)
6404 (>= js2-language-version 200))
6406 ((and (js2-match-char ?y)
6407 (>= js2-language-version 200))
6410 (setq continue nil))))
6411 (if (js2-alpha-p (js2-peek-char))
6412 (js2-report-scan-error "msg.invalid.re.flag" t
6414 (js2-set-string-from-buffer token))
6415 (js2-collect-string flags)))
6417 (defun js2-get-first-xml-token ()
6418 (setq js2-ts-xml-open-tags-count 0
6419 js2-ts-is-xml-attribute nil
6420 js2-ts-xml-is-tag-content nil)
6422 (js2-get-next-xml-token))
6424 (defun js2-xml-discard-string (token)
6425 "Throw away the string in progress and flag an XML parse error."
6426 (setf js2-ts-string-buffer nil
6427 (js2-token-string token) nil)
6428 (js2-report-scan-error "msg.XML.bad.form" t))
6430 (defun js2-get-next-xml-token ()
6431 (setq js2-ts-string-buffer nil) ; for recording the XML
6432 (let ((token (js2-new-token 0))
6437 (setq c (js2-get-char))
6440 (throw 'return js2-ERROR))
6441 (js2-ts-xml-is-tag-content
6444 (js2-add-to-string c)
6445 (setq js2-ts-xml-is-tag-content nil
6446 js2-ts-is-xml-attribute nil))
6448 (js2-add-to-string c)
6449 (when (eq ?> (js2-peek-char))
6450 (setq c (js2-get-char))
6451 (js2-add-to-string c)
6452 (setq js2-ts-xml-is-tag-content nil)
6453 (cl-decf js2-ts-xml-open-tags-count)))
6456 (js2-set-string-from-buffer token)
6457 (throw 'return js2-XML))
6459 (js2-add-to-string c)
6460 (unless (js2-read-quoted-string c token)
6461 (throw 'return js2-ERROR)))
6463 (js2-add-to-string c)
6464 (setq js2-ts-is-xml-attribute t))
6466 (js2-add-to-string c))
6468 (js2-add-to-string c)
6469 (setq js2-ts-is-xml-attribute nil)))
6470 (when (and (not js2-ts-xml-is-tag-content)
6471 (zerop js2-ts-xml-open-tags-count))
6472 (js2-set-string-from-buffer token)
6473 (throw 'return js2-XMLEND)))
6475 ;; else not tag content
6478 (js2-add-to-string c)
6479 (setq c (js2-peek-char))
6482 (setq c (js2-get-char)) ;; skip !
6483 (js2-add-to-string c)
6484 (setq c (js2-peek-char))
6487 (setq c (js2-get-char)) ;; skip -
6488 (js2-add-to-string c)
6491 (js2-add-to-string c)
6492 (unless (js2-read-xml-comment token)
6493 (throw 'return js2-ERROR)))
6494 (js2-xml-discard-string token)
6495 (throw 'return js2-ERROR)))
6497 (setq c (js2-get-char)) ;; skip [
6498 (js2-add-to-string c)
6499 (if (and (= (js2-get-char) ?C)
6500 (= (js2-get-char) ?D)
6501 (= (js2-get-char) ?A)
6502 (= (js2-get-char) ?T)
6503 (= (js2-get-char) ?A)
6504 (= (js2-get-char) ?\[))
6506 (js2-add-to-string ?C)
6507 (js2-add-to-string ?D)
6508 (js2-add-to-string ?A)
6509 (js2-add-to-string ?T)
6510 (js2-add-to-string ?A)
6511 (js2-add-to-string ?\[)
6512 (unless (js2-read-cdata token)
6513 (throw 'return js2-ERROR)))
6514 (js2-xml-discard-string token)
6515 (throw 'return js2-ERROR)))
6517 (unless (js2-read-entity token)
6518 (throw 'return js2-ERROR))))
6519 ;; Allow bare CDATA section, e.g.:
6520 ;; let xml = <![CDATA[ foo bar baz ]]>;
6521 (when (zerop js2-ts-xml-open-tags-count)
6522 (throw 'return js2-XMLEND)))
6524 (setq c (js2-get-char)) ;; skip ?
6525 (js2-add-to-string c)
6526 (unless (js2-read-PI token)
6527 (throw 'return js2-ERROR)))
6530 (setq c (js2-get-char)) ;; skip /
6531 (js2-add-to-string c)
6532 (when (zerop js2-ts-xml-open-tags-count)
6533 (js2-xml-discard-string token)
6534 (throw 'return js2-ERROR))
6535 (setq js2-ts-xml-is-tag-content t)
6536 (cl-decf js2-ts-xml-open-tags-count))
6539 (setq js2-ts-xml-is-tag-content t)
6540 (cl-incf js2-ts-xml-open-tags-count))))
6543 (js2-set-string-from-buffer token)
6544 (throw 'return js2-XML))
6546 (js2-add-to-string c))))))))
6547 (setf (js2-token-end token) js2-ts-cursor)
6548 (setf (js2-token-type token) result)
6551 (defun js2-read-quoted-string (quote token)
6554 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6555 (js2-add-to-string c)
6558 (js2-xml-discard-string token) ;; throw away string in progress
6561 (defun js2-read-xml-comment (token)
6562 (let ((c (js2-get-char)))
6564 (while (/= c js2-EOF_CHAR)
6566 (js2-add-to-string c)
6567 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6568 (setq c (js2-get-char))
6569 (js2-add-to-string c)
6570 (if (eq (js2-peek-char) ?>)
6572 (setq c (js2-get-char)) ;; skip >
6573 (js2-add-to-string c)
6575 (throw 'continue nil)))
6576 (setq c (js2-get-char))))
6577 (js2-xml-discard-string token)
6580 (defun js2-read-cdata (token)
6581 (let ((c (js2-get-char)))
6583 (while (/= c js2-EOF_CHAR)
6585 (js2-add-to-string c)
6586 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6587 (setq c (js2-get-char))
6588 (js2-add-to-string c)
6589 (if (eq (js2-peek-char) ?>)
6591 (setq c (js2-get-char)) ;; Skip >
6592 (js2-add-to-string c)
6594 (throw 'continue nil)))
6595 (setq c (js2-get-char))))
6596 (js2-xml-discard-string token)
6599 (defun js2-read-entity (token)
6603 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6604 (js2-add-to-string c)
6607 (cl-incf decl-tags))
6610 (if (zerop decl-tags)
6611 (throw 'return t)))))
6612 (js2-xml-discard-string token)
6615 (defun js2-read-PI (token)
6616 "Scan an XML processing instruction."
6619 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6620 (js2-add-to-string c)
6621 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6622 (setq c (js2-get-char)) ;; Skip >
6623 (js2-add-to-string c)
6625 (js2-xml-discard-string token)
6630 (defun js2-set-face (beg end face &optional record)
6631 "Fontify a region. If RECORD is non-nil, record for later."
6632 (when (cl-plusp js2-highlight-level)
6633 (setq beg (min (point-max) beg)
6634 beg (max (point-min) beg)
6635 end (min (point-max) end)
6636 end (max (point-min) end))
6638 (push (list beg end face) js2-mode-fontifications)
6639 (put-text-property beg end 'font-lock-face face))))
6641 (defsubst js2-clear-face (beg end)
6642 (remove-text-properties beg end '(font-lock-face nil
6645 cursor-sensor-functions nil
6648 (defconst js2-ecma-global-props
6651 '("Infinity" "NaN" "undefined" "arguments") t)
6653 "Value properties of the Ecma-262 Global Object.
6654 Shown at or above `js2-highlight-level' 2.")
6656 ;; might want to add the name "arguments" to this list?
6657 (defconst js2-ecma-object-props
6660 '("prototype" "__proto__" "__parent__") t)
6662 "Value properties of the Ecma-262 Object constructor.
6663 Shown at or above `js2-highlight-level' 2.")
6665 (defconst js2-ecma-global-funcs
6669 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6670 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6672 "Function properties of the Ecma-262 Global object.
6673 Shown at or above `js2-highlight-level' 2.")
6675 (defconst js2-ecma-number-props
6677 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6679 "POSITIVE_INFINITY") t)
6681 "Properties of the Ecma-262 Number constructor.
6682 Shown at or above `js2-highlight-level' 2.")
6684 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6685 "Properties of the Ecma-262 Date constructor.
6686 Shown at or above `js2-highlight-level' 2.")
6688 (defconst js2-ecma-math-props
6691 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6694 "Properties of the Ecma-262 Math object.
6695 Shown at or above `js2-highlight-level' 2.")
6697 (defconst js2-ecma-math-funcs
6700 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6701 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6703 "Function properties of the Ecma-262 Math object.
6704 Shown at or above `js2-highlight-level' 2.")
6706 (defconst js2-ecma-function-props
6710 '(;; properties of the Object prototype object
6711 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6712 "toLocaleString" "toString" "valueOf"
6713 ;; properties of the Function prototype object
6715 ;; properties of the Array prototype object
6716 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6718 ;; properties of the String prototype object
6719 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6720 "localeCompare" "match" "replace" "search" "split" "substring"
6721 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6723 ;; properties of the Number prototype object
6724 "toExponential" "toFixed" "toPrecision"
6725 ;; properties of the Date prototype object
6726 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6727 "getMinutes" "getMonth" "getSeconds" "getTime"
6728 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6729 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6730 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6731 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6732 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6733 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6734 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6735 "toTimeString" "toUTCString"
6736 ;; properties of the RegExp prototype object
6738 ;; properties of the JSON prototype object
6740 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6741 "toSource" "__defineGetter__" "__defineSetter__"
6742 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6743 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6746 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6747 Shown at or above `js2-highlight-level' 3.")
6749 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6750 (let ((target-name (and target
6751 (js2-name-node-p target)
6752 (js2-name-node-name target)))
6753 (prop-name (if prop (js2-name-node-name prop)))
6754 (level2 (>= js2-highlight-level 2))
6755 (level3 (>= js2-highlight-level 3)))
6762 ((and level3 (string-match js2-ecma-function-props prop-name))
6763 'font-lock-builtin-face)
6764 ((and target-name prop)
6766 ((string= target-name "Date")
6767 (if (string-match js2-ecma-date-props prop-name)
6768 'font-lock-builtin-face))
6769 ((string= target-name "Math")
6770 (if (string-match js2-ecma-math-funcs prop-name)
6771 'font-lock-builtin-face))))))
6773 (if (string-match js2-ecma-global-funcs prop-name)
6774 'font-lock-builtin-face)))
6778 ((string= target-name "Number")
6779 (if (string-match js2-ecma-number-props prop-name)
6780 'font-lock-constant-face))
6781 ((string= target-name "Math")
6782 (if (string-match js2-ecma-math-props prop-name)
6783 'font-lock-constant-face))))
6785 (if (string-match js2-ecma-object-props prop-name)
6786 'font-lock-constant-face))))))
6787 (when (and (not face) target (not call-p) prop-name)
6788 (setq face 'js2-object-property))
6790 (let ((pos (+ (js2-node-pos parent) ; absolute
6791 (js2-node-pos prop)))) ; relative
6793 (+ pos (js2-node-len prop))
6796 (defun js2-parse-highlight-member-expr-node (node)
6797 "Perform syntax highlighting of EcmaScript built-in properties.
6798 The variable `js2-highlight-level' governs this highlighting."
6799 (let (face target prop name pos end parent call-p callee)
6801 ;; case 1: simple name, e.g. foo
6802 ((js2-name-node-p node)
6803 (setq name (js2-name-node-name node))
6804 ;; possible for name to be nil in rare cases - saw it when
6805 ;; running js2-mode on an elisp buffer. Might as well try to
6806 ;; make it so js2-mode never barfs.
6808 (setq face (if (string-match js2-ecma-global-props name)
6809 'font-lock-constant-face))
6811 (setq pos (js2-node-pos node)
6812 end (+ pos (js2-node-len node)))
6813 (js2-set-face pos end face 'record))))
6814 ;; case 2: property access or function call
6815 ((or (js2-prop-get-node-p node)
6816 ;; highlight function call if expr is a prop-get node
6817 ;; or a plain name (i.e. unqualified function call)
6818 (and (setq call-p (js2-call-node-p node))
6819 (setq callee (js2-call-node-target node)) ; separate setq!
6820 (or (js2-prop-get-node-p callee)
6821 (js2-name-node-p callee))))
6823 node (if call-p callee node))
6824 (if (and call-p (js2-name-node-p callee))
6826 (setq target (js2-prop-get-node-left node)
6827 prop (js2-prop-get-node-right node)))
6829 ((js2-name-node-p prop)
6830 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6831 (js2-parse-highlight-prop-get parent target prop call-p))
6832 ((js2-name-node-p target)
6833 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6834 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6836 (defun js2-parse-highlight-member-expr-fn-name (expr)
6837 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6838 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6839 We currently only handle the case where the last component is a prop-get
6840 of a simple name. Called before EXPR has a parent node."
6842 (name (and (js2-prop-get-node-p expr)
6843 (js2-prop-get-node-right expr))))
6844 (when (js2-name-node-p name)
6845 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6846 (js2-node-pos name)))
6847 (+ pos (js2-node-len name))
6848 'font-lock-function-name-face
6851 ;; source: http://jsdoc.sourceforge.net/
6852 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6853 ;; allows type specifications, and needs work before entering the wild.
6855 (defconst js2-jsdoc-param-tag-regexp
6856 (concat "^\\s-*\\*+\\s-*\\(@"
6857 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6859 "\\s-*\\({[^}]+}\\)?" ; optional type
6860 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6862 "Matches jsdoc tags with optional type and optional param name.")
6864 (defconst js2-jsdoc-typed-tag-regexp
6865 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6879 "\\)\\)\\s-*\\({[^}]+}\\)?")
6880 "Matches jsdoc tags with optional type.")
6882 (defconst js2-jsdoc-arg-tag-regexp
6883 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6905 "\\)\\)\\s-+\\([^ \t]+\\)")
6906 "Matches jsdoc tags with a single argument.")
6908 (defconst js2-jsdoc-empty-tag-regexp
6909 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6949 "Matches empty jsdoc tags.")
6951 (defconst js2-jsdoc-link-tag-regexp
6952 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6953 "Matches a jsdoc link or code tag.")
6955 (defconst js2-jsdoc-see-tag-regexp
6956 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6957 "Matches a jsdoc @see tag.")
6959 (defconst js2-jsdoc-html-tag-regexp
6960 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6961 "Matches a simple (no attributes) html start- or end-tag.")
6963 (defun js2-jsdoc-highlight-helper ()
6964 (js2-set-face (match-beginning 1)
6967 (if (match-beginning 2)
6969 (goto-char (match-beginning 2))
6970 (= (char-after) ?{))
6971 (js2-set-face (1+ (match-beginning 2))
6974 (js2-set-face (match-beginning 2)
6977 (if (match-beginning 3)
6978 (js2-set-face (match-beginning 3)
6982 (defun js2-highlight-jsdoc (ast)
6983 "Highlight doc comment tags."
6984 (let ((comments (js2-ast-root-comments ast))
6987 (dolist (node comments)
6988 (when (eq (js2-comment-node-format node) 'jsdoc)
6989 (setq beg (js2-node-abs-pos node)
6990 end (+ beg (js2-node-len node)))
6992 (narrow-to-region beg end)
6993 (dolist (re (list js2-jsdoc-param-tag-regexp
6994 js2-jsdoc-typed-tag-regexp
6995 js2-jsdoc-arg-tag-regexp
6996 js2-jsdoc-link-tag-regexp
6997 js2-jsdoc-see-tag-regexp
6998 js2-jsdoc-empty-tag-regexp))
7000 (while (re-search-forward re nil t)
7001 (js2-jsdoc-highlight-helper)))
7002 ;; simple highlighting for html tags
7004 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7005 (js2-set-face (match-beginning 1)
7007 'js2-jsdoc-html-tag-delimiter)
7008 (js2-set-face (match-beginning 2)
7010 'js2-jsdoc-html-tag-name)
7011 (js2-set-face (match-beginning 3)
7013 'js2-jsdoc-html-tag-delimiter))))))))
7015 (defun js2-highlight-assign-targets (_node left right)
7016 "Highlight function properties and external variables."
7018 ;; highlight vars and props assigned function values
7019 (when (or (js2-function-node-p right)
7020 (js2-class-node-p right))
7022 ;; var foo = function() {...}
7023 ((js2-name-node-p left)
7025 ;; foo.bar.baz = function() {...}
7026 ((and (js2-prop-get-node-p left)
7027 (js2-name-node-p (js2-prop-get-node-right left)))
7028 (setq name (js2-prop-get-node-right left))))
7030 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7031 (+ leftpos (js2-node-len name))
7032 'font-lock-function-name-face
7035 (defun js2-record-name-node (node)
7036 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7037 later. NODE must be a name node."
7038 (let ((leftpos (js2-node-abs-pos node)))
7039 (push (list node js2-current-scope
7041 (+ leftpos (js2-node-len node)))
7042 js2-recorded-identifiers)))
7044 (defun js2-highlight-undeclared-vars ()
7045 "After entire parse is finished, look for undeclared variable references.
7046 We have to wait until entire buffer is parsed, since JavaScript permits var
7047 decls to occur after they're used.
7049 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7050 it is considered declared."
7052 (dolist (entry js2-recorded-identifiers)
7053 (cl-destructuring-bind (name-node scope pos end) entry
7054 (setq name (js2-name-node-name name-node))
7055 (unless (or (member name js2-global-externs)
7056 (member name js2-default-externs)
7057 (member name js2-additional-externs)
7058 (js2-get-defining-scope scope name pos))
7059 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7060 'js2-external-variable))))))
7062 (defun js2--add-or-update-symbol (symbol inition used vars)
7063 "Add or update SYMBOL entry in VARS, an hash table.
7064 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7065 respectively meaning that SYMBOL is a mere declaration, an
7066 assignment or a function parameter; when USED is t, the symbol
7067 node is assumed to be an usage and thus added to the list stored
7068 in the cdr of the entry.
7070 (let* ((nm (js2-name-node-name symbol))
7071 (es (js2-node-get-enclosing-scope symbol))
7072 (ds (js2-get-defining-scope es nm)))
7073 (when (and ds (not (equal nm "arguments")))
7074 (let* ((sym (js2-scope-get-symbol ds nm))
7075 (var (gethash sym vars))
7076 (err-var-p (js2-catch-node-p ds)))
7078 (setq inition err-var-p))
7081 (when (and inition (not (equal (car var) ?P)))
7082 (setcar var inition))
7084 (push symbol (cdr var))))
7085 ;; do not consider the declaration of catch parameter as an usage
7086 (when (and err-var-p used)
7088 (puthash sym (cons inition (if used (list symbol))) vars))))))
7090 (defun js2--classify-variables ()
7091 "Collect and classify variables declared or used within js2-mode-ast.
7092 Traverse the whole ast tree returning a summary of the variables
7093 usage as an hash-table, keyed by their corresponding symbol table
7095 Each variable is described by a tuple where the car is a flag
7096 indicating whether the variable has been initialized and the cdr
7097 is a possibly empty list of name nodes where it is used. External
7098 symbols, i.e. those not present in the whole scopes hierarchy,
7100 (let ((vars (make-hash-table :test #'eq :size 100)))
7103 (lambda (node end-p)
7106 ((js2-var-init-node-p node)
7107 ;; take note about possibly initialized declarations
7108 (let ((target (js2-var-init-node-target node))
7109 (initializer (js2-var-init-node-initializer node)))
7111 (let* ((parent (js2-node-parent node))
7112 (grandparent (if parent (js2-node-parent parent)))
7113 (inited (not (null initializer))))
7117 (js2-for-in-node-p grandparent)
7119 (mapcar #'js2-var-init-node-target
7120 (js2-var-decl-node-kids
7121 (js2-for-in-node-iterator grandparent)))))))
7122 (js2--add-or-update-symbol target inited nil vars)))))
7124 ((js2-assign-node-p node)
7125 ;; take note about assignments
7126 (let ((left (js2-assign-node-left node)))
7127 (when (js2-name-node-p left)
7128 (js2--add-or-update-symbol left t nil vars))))
7130 ((js2-prop-get-node-p node)
7131 ;; handle x.y.z nodes, considering only x
7132 (let ((left (js2-prop-get-node-left node)))
7133 (when (js2-name-node-p left)
7134 (js2--add-or-update-symbol left nil t vars))))
7136 ((js2-name-node-p node)
7137 ;; take note about used variables
7138 (let ((parent (js2-node-parent node)))
7140 (unless (or (and (js2-var-init-node-p parent) ; handled above
7141 (eq node (js2-var-init-node-target parent)))
7142 (and (js2-assign-node-p parent)
7143 (eq node (js2-assign-node-left parent)))
7144 (js2-prop-get-node-p parent))
7145 (let ((used t) inited)
7147 ((and (js2-function-node-p parent)
7148 (js2-wrapper-function-p parent))
7149 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7151 ((js2-for-in-node-p parent)
7152 (if (eq node (js2-for-in-node-iterator parent))
7153 (setq inited t used nil)))
7155 ((js2-function-node-p parent)
7156 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7160 (let ((grandparent (js2-node-parent parent)))
7162 (setq used (js2-return-node-p grandparent)))))
7164 (js2--add-or-update-symbol node inited used vars))))))))
7168 (defun js2--get-name-node (node)
7170 ((js2-name-node-p node) node)
7171 ((js2-function-node-p node)
7172 (js2-function-node-name node))
7173 ((js2-class-node-p node)
7174 (js2-class-node-name node))
7175 ((js2-comp-loop-node-p node)
7176 (js2-comp-loop-node-iterator node))
7179 (defun js2--highlight-unused-variable (symbol info)
7180 (let ((name (js2-symbol-name symbol))
7184 (unless (and inited refs)
7187 (setq pos (js2-node-abs-pos ref))
7188 (setq len (js2-name-node-len ref))
7189 (js2-report-warning "msg.uninitialized.variable" name pos len
7191 (when (or js2-warn-about-unused-function-arguments
7192 (not (eq inited ?P)))
7193 (let* ((symn (js2-symbol-ast-node symbol))
7194 (namen (js2--get-name-node symn)))
7195 (unless (js2-node-top-level-decl-p namen)
7196 (setq pos (js2-node-abs-pos namen))
7197 (setq len (js2-name-node-len namen))
7198 (js2-report-warning "msg.unused.variable" name pos len
7199 'js2-warning))))))))
7201 (defun js2-highlight-unused-variables ()
7202 "Highlight unused variables."
7203 (let ((vars (js2--classify-variables)))
7204 (maphash #'js2--highlight-unused-variable vars)))
7207 (define-minor-mode js2-highlight-unused-variables-mode
7208 "Toggle highlight of unused variables."
7210 (if js2-highlight-unused-variables-mode
7211 (add-hook 'js2-post-parse-callbacks
7212 #'js2-highlight-unused-variables nil t)
7213 (remove-hook 'js2-post-parse-callbacks
7214 #'js2-highlight-unused-variables t)))
7216 (defun js2-set-default-externs ()
7217 "Set the value of `js2-default-externs' based on the various
7218 `js2-include-?-externs' variables."
7219 (setq js2-default-externs
7220 (append js2-ecma-262-externs
7221 (if js2-include-browser-externs js2-browser-externs)
7222 (if (and js2-include-browser-externs
7223 (>= js2-language-version 200)) js2-harmony-externs)
7224 (if js2-include-rhino-externs js2-rhino-externs)
7225 (if js2-include-node-externs js2-node-externs)
7226 (if (or js2-include-browser-externs js2-include-node-externs)
7227 js2-typed-array-externs))))
7229 (defun js2-apply-jslint-globals ()
7230 (setq js2-additional-externs
7231 (nconc (js2-get-jslint-globals)
7232 js2-additional-externs)))
7234 (defun js2-get-jslint-globals ()
7235 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7236 when (and (eq 'block (js2-comment-node-format node))
7238 (goto-char (js2-node-abs-pos node))
7239 (looking-at "/\\*global ")))
7240 append (js2-get-jslint-globals-in
7242 (js2-node-abs-end node))))
7244 (defun js2-get-jslint-globals-in (beg end)
7248 (while (re-search-forward js2-mode-identifier-re end t)
7249 (let ((match (match-string 0)))
7250 (unless (member match '("true" "false"))
7251 (push match res)))))
7256 ;; We currently only support imenu, but eventually should support speedbar and
7257 ;; possibly other browsing mechanisms.
7259 ;; The basic strategy is to identify function assignment targets of the form
7260 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7261 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7262 ;; for imenu after parsing is finished.
7264 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7265 ;; JavaScript, and the general problem is undecidable. However, several forms
7266 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7269 ;; function foo() -- function declaration
7270 ;; foo = function() -- function expression assigned to variable
7271 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7272 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7273 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7274 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7275 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7276 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7277 ;; function foo() {function bar() {...}} -- nested function
7278 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7280 ;; This list boils down to a few forms that can be combined recursively.
7281 ;; Top-level named function declarations include both the left-hand (name)
7282 ;; and the right-hand (function value) expressions needed to produce an imenu
7283 ;; entry. The other "right-hand" forms we need to look for are:
7284 ;; - functions declared as props/getters/setters in object literals
7285 ;; - nested named function declarations
7286 ;; The "left-hand" expressions that functions can be assigned to include:
7287 ;; - local/global variables
7288 ;; - nested property-get expressions like a.b.c.d
7289 ;; - element gets like foo[10] or foo['bar'] where the index
7290 ;; expression can be trivially converted to a property name. They
7291 ;; effectively then become property gets.
7293 ;; All the different definition types are canonicalized into the form
7294 ;; foo.bar.baz = position-of-function-keyword
7296 ;; We need to build a trie-like structure for imenu. As an example,
7297 ;; consider the following JavaScript code:
7299 ;; a = function() {...} // function at position 5
7300 ;; b = function() {...} // function at position 25
7301 ;; foo = function() {...} // function at position 100
7302 ;; foo.bar = function() {...} // function at position 200
7303 ;; foo.bar.baz = function() {...} // function at position 300
7304 ;; foo.bar.zab = function() {...} // function at position 400
7306 ;; During parsing we accumulate an entry for each definition in
7307 ;; the variable `js2-imenu-recorder', like so:
7313 ;; (fn foo bar baz 300)
7314 ;; (fn foo bar zab 400))
7316 ;; Where 'fn' is the respective function node.
7317 ;; After parsing these entries are merged into this alist-trie:
7321 ;; (foo (<definition> . 3)
7322 ;; (bar (<definition> . 6)
7326 ;; Note the wacky need for a <definition> name. The token can be anything
7327 ;; that isn't a valid JavaScript identifier, because you might make foo
7328 ;; a function and then start setting properties on it that are also functions.
7330 (defun js2-prop-node-name (node)
7331 "Return the name of a node that may be a property-get/property-name.
7332 If NODE is not a valid name-node, string-node or integral number-node,
7333 returns nil. Otherwise returns the string name/value of the node."
7335 ((js2-name-node-p node)
7336 (js2-name-node-name node))
7337 ((js2-string-node-p node)
7338 (js2-string-node-value node))
7339 ((and (js2-number-node-p node)
7340 (string-match "^[0-9]+$" (js2-number-node-value node)))
7341 (js2-number-node-value node))
7342 ((eq (js2-node-type node) js2-THIS)
7344 ((eq (js2-node-type node) js2-SUPER)
7347 (defun js2-node-qname-component (node)
7348 "Return the name of this node, if it contributes to a qname.
7349 Returns nil if the node doesn't contribute."
7351 (or (js2-prop-node-name node)
7352 (if (and (js2-function-node-p node)
7353 (js2-function-node-name node))
7354 (js2-name-node-name (js2-function-node-name node))))))
7356 (defun js2-record-imenu-entry (fn-node qname pos)
7357 "Add an entry to `js2-imenu-recorder'.
7358 FN-NODE should be the current item's function node.
7360 Associate FN-NODE with its QNAME for later lookup.
7361 This is used in postprocessing the chain list. For each chain, we find
7362 the parent function, look up its qname, then prepend a copy of it to the chain."
7363 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7364 (unless js2-imenu-function-map
7365 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7366 (puthash fn-node qname js2-imenu-function-map))
7368 (defun js2-record-imenu-functions (node &optional var)
7369 "Record function definitions for imenu.
7370 NODE is a function node or an object literal.
7371 VAR, if non-nil, is the expression that NODE is being assigned to.
7372 When passed arguments of wrong type, does nothing."
7373 (when js2-parse-ide-mode
7374 (let ((fun-p (js2-function-node-p node))
7377 ;; non-anonymous function declaration?
7380 (setq fname-node (js2-function-node-name node)))
7381 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7382 ;; for remaining forms, compute left-side tree branch first
7383 ((and var (setq qname (js2-compute-nested-prop-get var)))
7385 ;; foo.bar.baz = function
7387 (js2-record-imenu-entry node qname (js2-node-pos node)))
7388 ;; foo.bar.baz = object-literal
7389 ;; look for nested functions: {a: {b: function() {...} }}
7390 ((js2-object-node-p node)
7391 ;; Node position here is still absolute, since the parser
7392 ;; passes the assignment target and value expressions
7393 ;; to us before they are added as children of the assignment node.
7394 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7396 (defun js2-compute-nested-prop-get (node)
7397 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7398 component nodes as a list. Otherwise return nil. Element-gets are treated
7399 as property-gets if the index expression is a string, or a positive integer."
7400 (let (left right head)
7402 ((or (js2-name-node-p node)
7403 (js2-this-or-super-node-p node))
7405 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7406 ((js2-prop-get-node-p node) ; foo.bar
7407 (setq left (js2-prop-get-node-left node)
7408 right (js2-prop-get-node-right node))
7409 (if (setq head (js2-compute-nested-prop-get left))
7410 (nconc head (list right))))
7411 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7412 (setq left (js2-elem-get-node-target node)
7413 right (js2-elem-get-node-element node))
7414 (if (or (js2-string-node-p right) ; ['bar']
7415 (and (js2-number-node-p right) ; [10]
7416 (string-match "^[0-9]+$"
7417 (js2-number-node-value right))))
7418 (if (setq head (js2-compute-nested-prop-get left))
7419 (nconc head (list right))))))))
7421 (defun js2-record-object-literal (node qname pos)
7422 "Recursively process an object literal looking for functions.
7423 NODE is an object literal that is the right-hand child of an assignment
7424 expression. QNAME is a list of nodes representing the assignment target,
7425 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7426 POS is the absolute position of the node.
7427 We do a depth-first traversal of NODE. For any functions we find,
7428 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7430 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7431 (let ((left (js2-infix-node-left e))
7432 ;; Element positions are relative to the parent position.
7433 (pos (+ pos (js2-node-pos e))))
7435 ;; foo: function() {...}
7436 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7437 (when (js2-prop-node-name left)
7438 ;; As a policy decision, we record the position of the property,
7439 ;; not the position of the `function' keyword, since the property
7440 ;; is effectively the name of the function.
7441 (js2-record-imenu-entry right (append qname (list left)) pos)))
7442 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7443 ((js2-object-node-p right)
7444 (js2-record-object-literal right
7445 (append qname (list (js2-infix-node-left e)))
7446 (+ pos (js2-node-pos right)))))))))
7448 (defun js2-node-top-level-decl-p (node)
7449 "Return t if NODE's name is defined in the top-level scope.
7450 Also returns t if NODE's name is not defined in any scope, since it implies
7451 that it's an external variable, which must also be in the top-level scope."
7452 (let* ((name (js2-prop-node-name node))
7453 (this-scope (js2-node-get-enclosing-scope node))
7456 ((js2-this-or-super-node-p node)
7460 ((setq defining-scope (js2-get-defining-scope this-scope name))
7461 (js2-ast-root-p defining-scope))
7464 (defun js2-wrapper-function-p (node)
7465 "Return t if NODE is a function expression that's immediately invoked.
7466 NODE must be `js2-function-node'."
7467 (let ((parent (js2-node-parent node)))
7469 ;; function(){...}();
7470 (and (js2-call-node-p parent)
7471 (eq node (js2-call-node-target parent)))
7472 (and (js2-paren-node-p parent)
7473 ;; (function(){...})();
7474 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7475 ;; (function(){...}).call(this);
7476 (and (js2-prop-get-node-p parent)
7477 (member (js2-name-node-name (js2-prop-get-node-right parent))
7479 (js2-call-node-p (js2-node-parent parent))))))))
7481 (defun js2-browse-postprocess-chains ()
7482 "Modify function-declaration name chains after parsing finishes.
7483 Some of the information is only available after the parse tree is complete.
7484 For instance, processing a nested scope requires a parent function node."
7485 (let (result fn parent-qname p elem)
7486 (dolist (entry js2-imenu-recorder)
7487 ;; function node goes first
7488 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7489 ;; Examine head's defining scope:
7490 ;; Pre-processed chain, or top-level/external, keep as-is.
7491 (if (or (stringp head) (js2-node-top-level-decl-p head))
7493 (when (js2-this-or-super-node-p head)
7494 (setq chain (cdr chain))) ; discard this-node
7495 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7496 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7497 (when (eq parent-qname 'not-found)
7498 ;; anonymous function expressions are not recorded
7499 ;; during the parse, so we need to handle this case here
7501 (if (js2-wrapper-function-p fn)
7502 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7503 (if (js2-ast-root-p grandparent)
7505 (gethash grandparent js2-imenu-function-map 'skip)))
7507 (puthash fn parent-qname js2-imenu-function-map))
7508 (if (eq parent-qname 'skip)
7509 ;; We don't show it, let's record that fact.
7510 (remhash current-fn js2-imenu-function-map)
7511 ;; Prepend parent fn qname to this chain.
7512 (let ((qname (append parent-qname chain)))
7513 (puthash current-fn (butlast qname) js2-imenu-function-map)
7514 (push qname result)))))))
7515 ;; Collect chains obtained by third-party code.
7516 (let (js2-imenu-recorder)
7517 (run-hooks 'js2-build-imenu-callbacks)
7518 (dolist (entry js2-imenu-recorder)
7519 (push (cdr entry) result)))
7520 ;; Finally replace each node in each chain with its name.
7521 (dolist (chain result)
7524 (if (js2-node-p (setq elem (car p)))
7525 (setcar p (js2-node-qname-component elem)))
7529 ;; Merge name chains into a trie-like tree structure of nested lists.
7530 ;; To simplify construction of the trie, we first build it out using the rule
7531 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7532 ;; [key, num-or-list]. The second element can be a number; if so, this key
7533 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7534 ;; associated with the key at this level.) Otherwise the second element is
7535 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7536 ;; a simple recursive formulation.
7538 ;; js2-mode is building the data structure for imenu. The imenu documentation
7539 ;; claims that it's the structure above, but in practice it wants the children
7540 ;; at the same list level as the key for that level, which is how I've drawn
7541 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7542 ;; list wrapper around the children at each level.
7544 ;; A completed nested imenu-alist entry looks like this:
7546 ;; ("<definition>" . 7)
7551 ;; In particular, the documentation for `imenu--index-alist' says that
7552 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7553 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7555 (defun js2-treeify (lst)
7556 "Convert (a b c d) to (a ((b ((c d)))))."
7557 (if (null (cddr lst)) ; list length <= 2
7559 (list (car lst) (list (js2-treeify (cdr lst))))))
7561 (defun js2-build-alist-trie (chains trie)
7562 "Merge declaration name chains into a trie-like alist structure for imenu.
7563 CHAINS is the qname chain list produced during parsing. TRIE is a
7564 list of elements built up so far."
7565 (let (head tail pos branch kids)
7566 (dolist (chain chains)
7567 (setq head (car chain)
7569 pos (if (numberp (car tail)) (car tail))
7570 branch (js2-find-if (lambda (n)
7571 (string= (car n) head))
7573 kids (cl-second branch))
7575 ;; case 1: this key isn't in the trie yet
7578 (setcdr (last trie) (list (js2-treeify chain)))
7579 (setq trie (list (js2-treeify chain)))))
7580 ;; case 2: key is present with a single number entry: replace w/ list
7581 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7582 ;; ("<definition>" 20)))
7584 (setcar (cdr branch)
7585 (list (list "<definition-1>" kids)
7587 (list "<definition-2>" pos)
7588 (js2-treeify tail)))))
7589 ;; case 3: key is there (with kids), and we're a number entry
7593 (list (format "<definition-%d>"
7594 (1+ (cl-loop for kid in kids
7595 count (eq ?< (aref (car kid) 0)))))
7597 ;; case 4: key is there with kids, need to merge in our chain
7599 (js2-build-alist-trie (list tail) kids))))
7602 (defun js2-flatten-trie (trie)
7603 "Convert TRIE to imenu-format.
7604 Recurses through nodes, and for each one whose second element is a list,
7605 appends the list's flattened elements to the current element. Also
7606 changes the tails into conses. For instance, this pre-flattened trie
7618 Note that the root of the trie has no key, just a list of chains.
7619 This is also true for the value of any key with multiple children,
7620 e.g. key 'c' in the example above."
7623 (mapcar #'js2-flatten-trie trie))
7625 (if (numberp (cl-second trie))
7626 (cons (car trie) (cl-second trie))
7627 ;; else pop list and append its kids
7628 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7630 (defun js2-build-imenu-index ()
7631 "Turn `js2-imenu-recorder' into an imenu data structure."
7632 (when (eq js2-imenu-recorder 'empty)
7633 (setq js2-imenu-recorder nil))
7634 (let* ((chains (js2-browse-postprocess-chains))
7635 (result (js2-build-alist-trie chains nil)))
7636 (js2-flatten-trie result)))
7638 (defun js2-test-print-chains (chains)
7639 "Print a list of qname chains.
7640 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7641 i.e. one or more nodes, and an integer position as the list tail."
7642 (mapconcat (lambda (chain)
7644 (mapconcat (lambda (elem)
7645 (if (js2-node-p elem)
7646 (or (js2-node-qname-component elem)
7648 (number-to-string elem)))
7657 (defconst js2-version "1.8.5"
7658 "Version of JavaScript supported.")
7660 (defun js2-record-face (face &optional token)
7661 "Record a style run of FACE for TOKEN or the current token."
7662 (unless token (setq token (js2-current-token)))
7663 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7665 (defsubst js2-node-end (n)
7666 "Computes the absolute end of node N.
7667 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7668 is only true until the node is added to its parent; i.e., while parsing."
7672 (defun js2-record-comment (token)
7673 "Record a comment in `js2-scanned-comments'."
7674 (let ((ct (js2-token-comment-type token))
7675 (beg (js2-token-beg token))
7676 (end (js2-token-end token)))
7677 (push (make-js2-comment-node :len (- end beg)
7679 js2-scanned-comments)
7680 (when js2-parse-ide-mode
7681 (js2-record-face (if (eq ct 'jsdoc)
7683 'font-lock-comment-face)
7685 (when (memq ct '(html preprocessor))
7686 ;; Tell cc-engine the bounds of the comment.
7687 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7689 (defun js2-peek-token ()
7690 "Return the next token type without consuming it.
7691 If `js2-ti-lookahead' is positive, return the type of next token
7692 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7693 (if (not (zerop js2-ti-lookahead))
7695 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7696 (let ((tt (js2-get-token-internal nil)))
7700 (defalias 'js2-next-token 'js2-get-token)
7702 (defun js2-match-token (match &optional dont-unget)
7703 "Get next token and return t if it matches MATCH, a bytecode.
7704 Returns nil and consumes nothing if MATCH is not the next token."
7705 (if (/= (js2-get-token) match)
7706 (ignore (unless dont-unget (js2-unget-token)))
7709 (defun js2-match-contextual-kwd (name)
7710 "Consume and return t if next token is `js2-NAME', and its
7711 string is NAME. Returns nil and keeps current token otherwise."
7712 (if (or (/= (js2-get-token) js2-NAME)
7713 (not (string= (js2-current-token-string) name)))
7717 (js2-record-face 'font-lock-keyword-face)
7720 (defun js2-get-prop-name-token ()
7721 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7723 (defun js2-match-prop-name ()
7724 "Consume token and return t if next token is a valid property name.
7725 If `js2-language-version' is >= 180, a keyword or reserved word
7726 is considered valid name as well."
7727 (if (eq js2-NAME (js2-get-prop-name-token))
7732 (defun js2-must-match-prop-name (msg-id &optional pos len)
7733 (if (js2-match-prop-name)
7735 (js2-report-error msg-id nil pos len)
7738 (defun js2-peek-token-or-eol ()
7739 "Return js2-EOL if the next token immediately follows a newline.
7740 Else returns the next token. Used in situations where we don't
7741 consider certain token types valid if they are preceded by a newline.
7742 One example is the postfix ++ or -- operator, which has to be on the
7743 same line as its operand."
7744 (let ((tt (js2-get-token))
7745 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7751 (defun js2-must-match (token msg-id &optional pos len)
7752 "Match next token to token code TOKEN, or record a syntax error.
7753 MSG-ID is the error message to report if the match fails.
7754 Returns t on match, nil if no match."
7755 (if (js2-match-token token t)
7757 (js2-report-error msg-id nil pos len)
7761 (defun js2-must-match-name (msg-id)
7762 (if (js2-match-token js2-NAME t)
7764 (if (eq (js2-current-token-type) js2-RESERVED)
7765 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7766 (js2-report-error msg-id)
7770 (defsubst js2-inside-function ()
7771 (cl-plusp js2-nesting-of-function))
7773 (defun js2-set-requires-activation ()
7774 (if (js2-function-node-p js2-current-script-or-fn)
7775 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7777 (defun js2-check-activation-name (name _token)
7778 (when (js2-inside-function)
7779 ;; skip language-version 1.2 check from Rhino
7780 (if (or (string= "arguments" name)
7781 (and js2-compiler-activation-names ; only used in codegen
7782 (gethash name js2-compiler-activation-names)))
7783 (js2-set-requires-activation))))
7785 (defun js2-set-is-generator ()
7786 (let ((fn-node js2-current-script-or-fn))
7787 (when (and (js2-function-node-p fn-node)
7788 (not (js2-function-node-generator-type fn-node)))
7789 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7791 (defun js2-must-have-xml ()
7792 (unless js2-compiler-xml-available
7793 (js2-report-error "msg.XML.not.available")))
7795 (defun js2-push-scope (scope)
7796 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7797 (cl-assert (js2-scope-p scope))
7798 (cl-assert (null (js2-scope-parent-scope scope)))
7799 (cl-assert (not (eq js2-current-scope scope)))
7800 (setf (js2-scope-parent-scope scope) js2-current-scope
7801 js2-current-scope scope))
7803 (defsubst js2-pop-scope ()
7804 (setq js2-current-scope
7805 (js2-scope-parent-scope js2-current-scope)))
7807 (defun js2-enter-loop (loop-node)
7808 (push loop-node js2-loop-set)
7809 (push loop-node js2-loop-and-switch-set)
7810 (js2-push-scope loop-node)
7811 ;; Tell the current labeled statement (if any) its statement,
7812 ;; and set the jump target of the first label to the loop.
7813 ;; These are used in `js2-parse-continue' to verify that the
7814 ;; continue target is an actual labeled loop. (And for codegen.)
7815 (when js2-labeled-stmt
7816 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7817 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7818 js2-labeled-stmt))) loop-node)))
7820 (defun js2-exit-loop ()
7822 (pop js2-loop-and-switch-set)
7825 (defsubst js2-enter-switch (switch-node)
7826 (push switch-node js2-loop-and-switch-set))
7828 (defsubst js2-exit-switch ()
7829 (pop js2-loop-and-switch-set))
7831 (defsubst js2-get-directive (node)
7832 "Return NODE's value if it is a directive, nil otherwise.
7834 A directive is an otherwise-meaningless expression statement
7835 consisting of a string literal, such as \"use strict\"."
7836 (and (js2-expr-stmt-node-p node)
7837 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7838 (js2-string-node-value node)))
7840 (defun js2-parse (&optional buf cb)
7841 "Tell the js2 parser to parse a region of JavaScript.
7843 BUF is a buffer or buffer name containing the code to parse.
7844 Call `narrow-to-region' first to parse only part of the buffer.
7846 The returned AST root node is given some additional properties:
7847 `node-count' - total number of nodes in the AST
7848 `buffer' - BUF. The buffer it refers to may change or be killed,
7849 so the value is not necessarily reliable.
7851 An optional callback CB can be specified to report parsing
7852 progress. If `(functionp CB)' returns t, it will be called with
7853 the current line number once before parsing begins, then again
7854 each time the lexer reaches a new line number.
7856 CB can also be a list of the form `(symbol cb ...)' to specify
7857 multiple callbacks with different criteria. Each symbol is a
7858 criterion keyword, and the following element is the callback to
7861 :line - called whenever the line number changes
7862 :token - called for each new token consumed
7864 The list of criteria could be extended to include entering or
7865 leaving a statement, an expression, or a function definition."
7866 (if (and cb (not (functionp cb)))
7867 (error "criteria callbacks not yet implemented"))
7868 (let ((inhibit-point-motion-hooks t)
7869 (js2-compiler-xml-available (>= js2-language-version 160))
7870 ;; This is a recursive-descent parser, so give it a big stack.
7871 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7872 (max-specpdl-size (max max-specpdl-size 3000))
7873 (case-fold-search nil)
7875 (with-current-buffer (or buf (current-buffer))
7876 (setq js2-scanned-comments nil
7877 js2-parsed-errors nil
7878 js2-parsed-warnings nil
7879 js2-imenu-recorder nil
7880 js2-imenu-function-map nil
7883 (setq ast (js2-do-parse))
7884 (unless js2-ts-hit-eof
7885 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7886 (setf (js2-ast-root-errors ast) js2-parsed-errors
7887 (js2-ast-root-warnings ast) js2-parsed-warnings)
7888 ;; if we didn't find any declarations, put a dummy in this list so we
7889 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7890 (unless js2-imenu-recorder
7891 (setq js2-imenu-recorder 'empty))
7892 (run-hooks 'js2-parse-finished-hook)
7895 ;; Corresponds to Rhino's Parser.parse() method.
7896 (defun js2-do-parse ()
7897 "Parse current buffer starting from current point.
7898 Scanner should be initialized."
7899 (let ((pos js2-ts-cursor)
7900 (end js2-ts-cursor) ; in case file is empty
7902 (in-directive-prologue t)
7903 (js2-in-use-strict-directive js2-in-use-strict-directive)
7905 ;; initialize buffer-local parsing vars
7906 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7907 js2-current-script-or-fn root
7908 js2-current-scope root
7909 js2-nesting-of-function 0
7910 js2-labeled-stmt nil
7911 js2-recorded-identifiers nil ; for js2-highlight
7912 js2-in-use-strict-directive nil)
7913 (while (/= (setq tt (js2-get-token)) js2-EOF)
7914 (if (= tt js2-FUNCTION)
7916 (setq n (if js2-called-by-compile-function
7917 (js2-parse-function-expr)
7918 (js2-parse-function-stmt))))
7919 ;; not a function - parse a statement
7921 (setq n (js2-parse-statement))
7922 (when in-directive-prologue
7923 (setq directive (js2-get-directive n))
7926 (setq in-directive-prologue nil))
7927 ((string= directive "use strict")
7928 (setq js2-in-use-strict-directive t)))))
7929 ;; add function or statement to script
7930 (setq end (js2-node-end n))
7931 (js2-block-node-push root n))
7932 ;; add comments to root in lexical order
7933 (when js2-scanned-comments
7934 ;; if we find a comment beyond end of normal kids, use its end
7935 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7936 (dolist (comment js2-scanned-comments)
7937 (push comment (js2-ast-root-comments root))
7938 (js2-node-add-children root comment)))
7939 (setf (js2-node-len root) (- end pos))
7940 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7941 ;; Give extensions a chance to muck with things before highlighting starts.
7942 (let ((js2-additional-externs js2-additional-externs))
7944 (run-hooks 'js2-post-parse-callbacks))
7945 (js2-highlight-undeclared-vars))
7948 (defun js2-parse-function-closure-body (fn-node)
7949 "Parse a JavaScript 1.8 function closure body."
7950 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7952 (js2-report-error "msg.no.brace.body" nil
7953 (js2-node-pos fn-node)
7954 (- js2-ts-cursor (js2-node-pos fn-node)))
7955 (js2-node-add-children fn-node
7956 (setf (js2-function-node-body fn-node)
7957 (js2-parse-expr t))))))
7959 (defun js2-parse-function-body (fn-node)
7960 (js2-must-match js2-LC "msg.no.brace.body"
7961 (js2-node-pos fn-node)
7962 (- js2-ts-cursor (js2-node-pos fn-node)))
7963 (let ((pos (js2-current-token-beg)) ; LC position
7964 (pn (make-js2-block-node)) ; starts at LC position
7967 not-in-directive-prologue
7970 (cl-incf js2-nesting-of-function)
7972 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7975 (js2-block-node-push
7977 (if (/= tt js2-FUNCTION)
7978 (if not-in-directive-prologue
7979 (js2-parse-statement)
7980 (setq node (js2-parse-statement)
7981 directive (js2-get-directive node))
7984 (setq not-in-directive-prologue t))
7985 ((string= directive "use strict")
7986 ;; Back up and reparse the function, because new rules apply
7987 ;; to the function name and parameters.
7988 (when (not js2-in-use-strict-directive)
7989 (setq js2-in-use-strict-directive t)
7990 (throw 'reparse t))))
7993 (js2-parse-function-stmt))))
7994 (cl-decf js2-nesting-of-function))
7995 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7996 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7997 (setq end (js2-current-token-end)))
7998 (setf (js2-node-pos pn) pos
7999 (js2-node-len pn) (- end pos))
8000 (setf (js2-function-node-body fn-node) pn)
8001 (js2-node-add-children fn-node pn)
8004 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8005 "Declare and fontify destructuring parameters inside NODE.
8006 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8008 Return a list of `js2-name-node' nodes representing the symbols
8009 declared; probably to check them for errors."
8012 ((js2-name-node-p node)
8014 (js2-define-symbol decl-type (js2-name-node-name node)
8015 node ignore-not-in-block)
8017 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8018 (+ leftpos (js2-node-len node))
8021 ((js2-object-node-p node)
8022 (dolist (elem (js2-object-node-elems node))
8023 ;; js2-infix-node-p catches both object prop node and initialized
8024 ;; binding element (which is directly an infix node).
8025 (when (js2-infix-node-p elem)
8026 (push (js2-define-destruct-symbols
8027 (js2-infix-node-left elem)
8028 decl-type face ignore-not-in-block)
8030 (apply #'append (nreverse name-nodes)))
8031 ((js2-array-node-p node)
8032 (dolist (elem (js2-array-node-elems node))
8034 (if (js2-infix-node-p elem) (setq elem (js2-infix-node-left elem)))
8035 (push (js2-define-destruct-symbols
8036 elem decl-type face ignore-not-in-block)
8038 (apply #'append (nreverse name-nodes)))
8039 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8040 (js2-node-len node))
8043 (defvar js2-illegal-strict-identifiers
8044 '("eval" "arguments")
8045 "Identifiers not allowed as variables in strict mode.")
8047 (defun js2-check-strict-identifier (name-node)
8048 "Check that NAME-NODE makes a legal strict mode identifier."
8049 (when js2-in-use-strict-directive
8050 (let ((param-name (js2-name-node-name name-node)))
8051 (when (member param-name js2-illegal-strict-identifiers)
8052 (js2-report-error "msg.bad.id.strict" param-name
8053 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8055 (defun js2-check-strict-function-params (preceding-params params)
8056 "Given PRECEDING-PARAMS in a function's parameter list, check
8057 for strict mode errors caused by PARAMS."
8058 (when js2-in-use-strict-directive
8059 (dolist (param params)
8060 (let ((param-name (js2-name-node-name param)))
8061 (js2-check-strict-identifier param)
8062 (when (cl-some (lambda (param)
8063 (string= (js2-name-node-name param) param-name))
8065 (js2-report-error "msg.dup.param.strict" param-name
8066 (js2-node-abs-pos param) (js2-node-len param)))))))
8068 (defun js2-parse-function-params (function-type fn-node pos)
8069 "Parse the parameters of a function of FUNCTION-TYPE
8070 represented by FN-NODE at POS."
8071 (if (js2-match-token js2-RP)
8072 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8073 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8074 (eq (js2-current-token-type) js2-NAME)))
8076 param-name-nodes new-param-name-nodes
8078 (when paren-free-arrow
8080 (cl-loop for tt = (js2-peek-token)
8083 ;; destructuring param
8084 ((and (not paren-free-arrow)
8085 (or (= tt js2-LB) (= tt js2-LC)))
8087 (setq param (js2-parse-destruct-primary-expr)
8088 new-param-name-nodes (js2-define-destruct-symbols
8089 param js2-LP 'js2-function-param))
8090 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8091 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8092 (push param params))
8095 (when (and (>= js2-language-version 200)
8096 (not paren-free-arrow)
8097 (js2-match-token js2-TRIPLEDOT)
8098 (not rest-param-at))
8099 ;; to report errors if there are more parameters
8100 (setq rest-param-at (length params)))
8101 (js2-must-match-name "msg.no.parm")
8102 (js2-record-face 'js2-function-param)
8103 (setq param (js2-create-name-node))
8104 (js2-define-symbol js2-LP (js2-current-token-string) param)
8105 (js2-check-strict-function-params param-name-nodes (list param))
8106 (setq param-name-nodes (append param-name-nodes (list param)))
8107 ;; default parameter value
8108 (when (and (>= js2-language-version 200)
8109 (js2-match-token js2-ASSIGN))
8110 (cl-assert (not paren-free-arrow))
8111 (let* ((pos (js2-node-pos param))
8112 (tt (js2-current-token-type))
8113 (op-pos (- (js2-current-token-beg) pos))
8115 (right (js2-parse-assign-expr))
8116 (len (- (js2-node-end right) pos)))
8117 (setq param (make-js2-assign-node
8118 :type tt :pos pos :len len :op-pos op-pos
8119 :left left :right right))
8120 (js2-node-add-children param left right)))
8121 (push param params)))
8122 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8123 (js2-report-error "msg.param.after.rest" nil
8124 (js2-node-pos param) (js2-node-len param)))
8126 (js2-match-token js2-COMMA))
8127 (when (and (not paren-free-arrow)
8128 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8129 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8131 (setf (js2-function-node-rest-p fn-node) t))
8133 (js2-node-add-children fn-node p)
8134 (push p (js2-function-node-params fn-node))))))
8136 (defun js2-check-inconsistent-return-warning (fn-node name)
8137 "Possibly show inconsistent-return warning.
8138 Last token scanned is the close-curly for the function body."
8139 (when (and js2-mode-show-strict-warnings
8140 js2-strict-inconsistent-return-warning
8141 (not (js2-has-consistent-return-usage
8142 (js2-function-node-body fn-node))))
8143 ;; Have it extend from close-curly to bol or beginning of block.
8144 (let ((pos (save-excursion
8145 (goto-char (js2-current-token-end))
8146 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8148 (end (js2-current-token-end)))
8149 (if (cl-plusp (js2-name-node-length name))
8150 (js2-add-strict-warning "msg.no.return.value"
8151 (js2-name-node-name name) pos end)
8152 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8154 (defun js2-parse-function-stmt ()
8155 (let ((pos (js2-current-token-beg))
8156 (star-p (js2-match-token js2-MUL)))
8157 (js2-must-match-name "msg.unnamed.function.stmt")
8158 (let ((name (js2-create-name-node t))
8161 ((js2-match-token js2-LP)
8162 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8163 (js2-allow-member-expr-as-function-name
8164 (setq member-expr (js2-parse-member-expr-tail nil name))
8165 (js2-parse-highlight-member-expr-fn-name member-expr)
8166 (js2-must-match js2-LP "msg.no.paren.parms")
8167 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8168 (js2-function-node-member-expr pn) member-expr)
8171 (js2-report-error "msg.no.paren.parms")
8172 (make-js2-error-node))))))
8174 (defun js2-parse-function-expr ()
8175 (let ((pos (js2-current-token-beg))
8176 (star-p (js2-match-token js2-MUL))
8178 (when (js2-match-token js2-NAME)
8179 (setq name (js2-create-name-node t)))
8180 (js2-must-match js2-LP "msg.no.paren.parms")
8181 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8183 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8185 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8186 (setq lp (js2-current-token-beg)))
8187 (setf fn-node (make-js2-function-node :pos pos
8190 :lp (if lp (- lp pos))
8191 :generator-type (and star-p 'STAR)))
8193 (js2-set-face (js2-node-pos name) (js2-node-end name)
8194 'font-lock-function-name-face 'record)
8195 (when (and (eq function-type 'FUNCTION_STATEMENT)
8196 (cl-plusp (js2-name-node-length name)))
8197 ;; Function statements define a symbol in the enclosing scope
8198 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8199 (when js2-in-use-strict-directive
8200 (js2-check-strict-identifier name)))
8201 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8202 ;; 1. Nested functions are not affected by the dynamic scope flag
8203 ;; as dynamic scope is already a parent of their scope.
8204 ;; 2. Functions defined under the with statement also immune to
8205 ;; this setup, in which case dynamic scope is ignored in favor
8206 ;; of the with object.
8207 (setf (js2-function-node-ignore-dynamic fn-node) t))
8208 ;; dynamically bind all the per-function variables
8209 (let ((js2-current-script-or-fn fn-node)
8210 (js2-current-scope fn-node)
8211 (js2-nesting-of-with 0)
8215 js2-loop-and-switch-set)
8216 (js2-parse-function-params function-type fn-node pos)
8217 (when (eq function-type 'FUNCTION_ARROW)
8218 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8219 (if (and (>= js2-language-version 180)
8220 (/= (js2-peek-token) js2-LC))
8221 (js2-parse-function-closure-body fn-node)
8222 (js2-parse-function-body fn-node))
8223 (js2-check-inconsistent-return-warning fn-node name)
8226 (js2-node-add-children fn-node name)
8227 ;; Function expressions define a name only in the body of the
8228 ;; function, and only if not hidden by a parameter name
8229 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8230 (null (js2-scope-get-symbol js2-current-scope
8231 (js2-name-node-name name))))
8232 (js2-define-symbol js2-FUNCTION
8233 (js2-name-node-name name)
8235 (when (eq function-type 'FUNCTION_STATEMENT)
8236 (js2-record-imenu-functions fn-node))))
8238 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8239 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8240 ;; We wait until after parsing the function to set its parent scope,
8241 ;; since `js2-define-symbol' needs the defining-scope check to stop
8242 ;; at the function boundary when checking for redeclarations.
8243 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8246 (defun js2-parse-function (function-type pos star-p &optional name)
8247 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8248 beginning of the first token (function keyword, unless it's an
8249 arrow function), NAME is js2-name-node."
8253 ;; Preserve strict state outside this function.
8254 (js2-in-use-strict-directive js2-in-use-strict-directive))
8255 ;; Parse multiple times if a new strict mode directive is discovered in the
8256 ;; function body, as new rules will be retroactively applied to the legality
8257 ;; of function names and parameters.
8259 (setq ts-state (make-js2-ts-state))
8260 (setq continue (catch 'reparse
8261 (setq fn-node (js2-parse-function-internal
8262 function-type pos star-p name))
8266 (js2-ts-seek ts-state)))
8269 (defun js2-parse-statements (&optional parent)
8270 "Parse a statement list. Last token consumed must be js2-LC.
8272 PARENT can be a `js2-block-node', in which case the statements are
8273 appended to PARENT. Otherwise a new `js2-block-node' is created
8276 This function does not match the closing js2-RC: the caller
8277 matches the RC so it can provide a suitable error message if not
8278 matched. This means it's up to the caller to set the length of
8279 the node to include the closing RC. The node start pos is set to
8280 the absolute buffer start position, and the caller should fix it
8281 up to be relative to the parent node. All children of this block
8282 node are given relative start positions and correct lengths."
8283 (let ((pn (or parent (make-js2-block-node)))
8285 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8287 (js2-block-node-push pn (js2-parse-statement)))
8290 (defun js2-parse-statement ()
8292 ;; coarse-grained user-interrupt check - needs work
8293 (and js2-parse-interruptable-p
8294 (zerop (% (cl-incf js2-parse-stmt-count)
8295 js2-statements-per-pause))
8297 (throw 'interrupted t))
8298 (setq pn (js2-statement-helper))
8299 ;; no-side-effects warning check
8300 (unless (js2-node-has-side-effects pn)
8301 (setq end (js2-node-end pn))
8304 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8305 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8308 ;; These correspond to the switch cases in Parser.statementHelper
8309 (defconst js2-parsers
8310 (let ((parsers (make-vector js2-num-tokens
8311 #'js2-parse-expr-stmt)))
8312 (aset parsers js2-BREAK #'js2-parse-break)
8313 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8314 (aset parsers js2-CONST #'js2-parse-const-var)
8315 (aset parsers js2-CONTINUE #'js2-parse-continue)
8316 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8317 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8318 (aset parsers js2-DO #'js2-parse-do)
8319 (aset parsers js2-EXPORT #'js2-parse-export)
8320 (aset parsers js2-FOR #'js2-parse-for)
8321 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8322 (aset parsers js2-IF #'js2-parse-if)
8323 (aset parsers js2-IMPORT #'js2-parse-import)
8324 (aset parsers js2-LC #'js2-parse-block)
8325 (aset parsers js2-LET #'js2-parse-let-stmt)
8326 (aset parsers js2-NAME #'js2-parse-name-or-label)
8327 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8328 (aset parsers js2-SEMI #'js2-parse-semi)
8329 (aset parsers js2-SWITCH #'js2-parse-switch)
8330 (aset parsers js2-THROW #'js2-parse-throw)
8331 (aset parsers js2-TRY #'js2-parse-try)
8332 (aset parsers js2-VAR #'js2-parse-const-var)
8333 (aset parsers js2-WHILE #'js2-parse-while)
8334 (aset parsers js2-WITH #'js2-parse-with)
8335 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8337 "A vector mapping token types to parser functions.")
8339 (defun js2-parse-warn-missing-semi (beg end)
8340 (and js2-mode-show-strict-warnings
8341 js2-strict-missing-semi-warning
8342 (js2-add-strict-warning
8343 "msg.missing.semi" nil
8344 ;; back up to beginning of statement or line
8345 (max beg (save-excursion
8350 (defconst js2-no-semi-insertion
8364 "List of tokens that don't do automatic semicolon insertion.")
8366 (defconst js2-autoinsert-semi-and-warn
8367 (list js2-ERROR js2-EOF js2-RC))
8369 (defun js2-statement-helper ()
8370 (let* ((tt (js2-get-token))
8372 (parser (if (= tt js2-ERROR)
8374 (aref js2-parsers tt)))
8376 ;; If the statement is set, then it's been told its label by now.
8377 (and js2-labeled-stmt
8378 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8379 (setq js2-labeled-stmt nil))
8380 (setq pn (funcall parser))
8381 ;; Don't do auto semi insertion for certain statement types.
8382 (unless (or (memq first-tt js2-no-semi-insertion)
8383 (js2-labeled-stmt-node-p pn))
8384 (js2-auto-insert-semicolon pn))
8387 (defun js2-auto-insert-semicolon (pn)
8388 (let* ((tt (js2-get-token))
8389 (pos (js2-node-pos pn)))
8392 ;; extend the node bounds to include the semicolon.
8393 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8394 ((memq tt js2-autoinsert-semi-and-warn)
8395 (js2-unget-token) ; Not ';', do not consume.
8397 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8399 (if (not (js2-token-follows-eol-p (js2-current-token)))
8400 ;; Report error if no EOL or autoinsert ';' otherwise
8401 (js2-report-error "msg.no.semi.stmt")
8402 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8403 (js2-unget-token) ; Not ';', do not consume.
8406 (defun js2-parse-condition ()
8407 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8408 The parens are discarded and the expression node is returned.
8409 The `pos' field of the return value is set to an absolute position
8410 that must be fixed up by the caller.
8411 Return value is a list (EXPR LP RP), with absolute paren positions."
8413 (if (js2-must-match js2-LP "msg.no.paren.cond")
8414 (setq lp (js2-current-token-beg)))
8415 (setq pn (js2-parse-expr))
8416 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8417 (setq rp (js2-current-token-beg)))
8418 ;; Report strict warning on code like "if (a = 7) ..."
8419 (if (and js2-strict-cond-assign-warning
8420 (js2-assign-node-p pn))
8421 (js2-add-strict-warning "msg.equal.as.assign" nil
8423 (+ (js2-node-pos pn)
8424 (js2-node-len pn))))
8427 (defun js2-parse-if ()
8428 "Parser for if-statement. Last matched token must be js2-IF."
8429 (let ((pos (js2-current-token-beg))
8430 cond if-true if-false else-pos end pn)
8431 (setq cond (js2-parse-condition)
8432 if-true (js2-parse-statement)
8433 if-false (if (js2-match-token js2-ELSE)
8435 (setq else-pos (- (js2-current-token-beg) pos))
8436 (js2-parse-statement)))
8437 end (js2-node-end (or if-false if-true))
8438 pn (make-js2-if-node :pos pos
8440 :condition (car cond)
8444 :lp (js2-relpos (cl-second cond) pos)
8445 :rp (js2-relpos (cl-third cond) pos)))
8446 (js2-node-add-children pn (car cond) if-true if-false)
8449 (defun js2-parse-import ()
8450 "Parse import statement. The current token must be js2-IMPORT."
8451 (unless (js2-ast-root-p js2-current-scope)
8452 (js2-report-error "msg.mod.import.decl.at.top.level"))
8453 (let ((beg (js2-current-token-beg)))
8454 (cond ((js2-match-token js2-STRING)
8455 (make-js2-import-node
8457 :len (- (js2-current-token-end) beg)
8458 :module-id (js2-current-token-string)))
8460 (let* ((import-clause (js2-parse-import-clause))
8461 (from-clause (and import-clause (js2-parse-from-clause)))
8462 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8463 (node (make-js2-import-node
8465 :len (- (js2-current-token-end) beg)
8466 :import import-clause
8468 :module-id module-id)))
8470 (js2-node-add-children node import-clause))
8472 (js2-node-add-children node from-clause))
8475 (defun js2-parse-import-clause ()
8476 "Parse the bindings in an import statement.
8477 This can take many forms:
8479 ImportedDefaultBinding -> 'foo'
8480 NameSpaceImport -> '* as lib'
8481 NamedImports -> '{foo as bar, bang}'
8482 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8483 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8485 Try to match namespace imports and named imports first because nothing can
8486 come after them. If it is an imported default binding, then it could have named
8487 imports or a namespace import that follows it.
8489 (let* ((beg (js2-current-token-beg))
8490 (clause (make-js2-import-clause-node
8494 ((js2-match-token js2-MUL)
8495 (let ((ns-import (js2-parse-namespace-import)))
8497 (let ((name-node (js2-namespace-import-node-name ns-import)))
8499 js2-LET (js2-name-node-name name-node) name-node t)))
8500 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8501 (push ns-import children)))
8502 ((js2-match-token js2-LC)
8503 (let ((imports (js2-parse-export-bindings t)))
8504 (setf (js2-import-clause-node-named-imports clause) imports)
8505 (dolist (import imports)
8506 (push import children)
8507 (let ((name-node (js2-export-binding-node-local-name import)))
8510 js2-LET (js2-name-node-name name-node) name-node t))))))
8511 ((= (js2-peek-token) js2-NAME)
8512 (let ((binding (js2-maybe-parse-export-binding)))
8513 (let ((node-name (js2-export-binding-node-local-name binding)))
8514 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8515 (setf (js2-import-clause-node-default-binding clause) binding)
8516 (push binding children))
8517 (when (js2-match-token js2-COMMA)
8519 ((js2-match-token js2-MUL)
8520 (let ((ns-import (js2-parse-namespace-import)))
8521 (let ((name-node (js2-namespace-import-node-name ns-import)))
8523 js2-LET (js2-name-node-name name-node) name-node t))
8524 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8525 (push ns-import children)))
8526 ((js2-match-token js2-LC)
8527 (let ((imports (js2-parse-export-bindings t)))
8528 (setf (js2-import-clause-node-named-imports clause) imports)
8529 (dolist (import imports)
8530 (push import children)
8531 (let ((name-node (js2-export-binding-node-local-name import)))
8534 js2-LET (js2-name-node-name name-node) name-node t))))))
8535 (t (js2-report-error "msg.syntax")))))
8536 (t (js2-report-error "msg.mod.declaration.after.import")))
8537 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8538 (apply #'js2-node-add-children clause children)
8541 (defun js2-parse-namespace-import ()
8542 "Parse a namespace import expression such as '* as bar'.
8543 The current token must be js2-MUL."
8544 (let ((beg (js2-current-token-beg)))
8545 (when (js2-must-match js2-NAME "msg.syntax")
8546 (if (equal "as" (js2-current-token-string))
8547 (when (js2-must-match-prop-name "msg.syntax")
8548 (let ((node (make-js2-namespace-import-node
8550 :len (- (js2-current-token-end) beg)
8551 :name (make-js2-name-node
8552 :pos (js2-current-token-beg)
8553 :len (js2-current-token-end)
8554 :name (js2-current-token-string)))))
8555 (js2-node-add-children node (js2-namespace-import-node-name node))
8558 (js2-report-error "msg.syntax")))))
8561 (defun js2-parse-from-clause ()
8562 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8563 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8564 (let ((beg (js2-current-token-beg)))
8565 (if (equal "from" (js2-current-token-string))
8567 ((js2-match-token js2-STRING)
8568 (make-js2-from-clause-node
8570 :len (- (js2-current-token-end) beg)
8571 :module-id (js2-current-token-string)
8573 ((js2-match-token js2-THIS)
8574 (when (js2-must-match-name "msg.mod.spec.after.from")
8575 (if (equal "module" (js2-current-token-string))
8576 (make-js2-from-clause-node
8578 :len (- (js2-current-token-end) beg)
8583 (js2-report-error "msg.mod.spec.after.from")
8585 (t (js2-report-error "msg.mod.spec.after.from") nil))
8587 (js2-report-error "msg.mod.from.after.import.spec.set")
8590 (defun js2-parse-export-bindings (&optional import-p)
8591 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8592 {foo as bar, baz as bang}. The current token must be
8593 js2-LC. Return a lisp list of js2-export-binding-node"
8594 (let ((bindings (list)))
8596 (let ((binding (js2-maybe-parse-export-binding)))
8598 (push binding bindings))
8599 (js2-match-token js2-COMMA)))
8600 (when (js2-must-match js2-RC (if import-p
8601 "msg.mod.rc.after.import.spec.list"
8602 "msg.mod.rc.after.export.spec.list"))
8603 (reverse bindings))))
8605 (defun js2-maybe-parse-export-binding ()
8606 "Attempt to parse a binding expression found inside an import/export statement.
8607 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8608 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8609 js2-export-binding-node and consume all the tokens. If it does not match, it
8610 consumes no tokens."
8611 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8612 (beg (js2-current-token-beg))
8613 (extern-name-len (js2-current-token-len))
8614 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8615 (aref js2-kwd-tokens (js2-current-token-type)))))
8617 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8618 (if (and as (equal "as" (js2-current-token-string)))
8621 (and (js2-match-token js2-DEFAULT) "default")
8622 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8624 (let ((node (make-js2-export-binding-node
8626 :len (- (js2-current-token-end) beg)
8627 :local-name (make-js2-name-node
8629 :pos (js2-current-token-beg)
8630 :len (js2-current-token-len))
8631 :extern-name (make-js2-name-node
8634 :len extern-name-len))))
8635 (js2-node-add-children
8637 (js2-export-binding-node-local-name node)
8638 (js2-export-binding-node-extern-name node))
8642 (when as (js2-unget-token))
8643 (let* ((name-node (make-js2-name-node
8644 :name (js2-current-token-string)
8645 :pos (js2-current-token-beg)
8646 :len (js2-current-token-len)))
8647 (node (make-js2-export-binding-node
8648 :pos (js2-current-token-beg)
8649 :len (js2-current-token-len)
8650 :local-name name-node
8651 :extern-name name-node)))
8652 (when is-reserved-name
8653 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8654 (js2-node-add-children node name-node)
8658 (defun js2-parse-switch ()
8659 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8660 (let ((pos (js2-current-token-beg))
8661 tt pn discriminant has-default case-expr case-node
8662 case-pos cases stmt lp)
8663 (if (js2-must-match js2-LP "msg.no.paren.switch")
8664 (setq lp (js2-current-token-beg)))
8665 (setq discriminant (js2-parse-expr)
8666 pn (make-js2-switch-node :discriminant discriminant
8668 :lp (js2-relpos lp pos)))
8669 (js2-node-add-children pn discriminant)
8670 (js2-enter-switch pn)
8673 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8674 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8675 (js2-must-match js2-LC "msg.no.brace.switch")
8678 (setq tt (js2-next-token)
8679 case-pos (js2-current-token-beg))
8682 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8683 (throw 'break nil)) ; done
8685 (setq case-expr (js2-parse-expr))
8686 (js2-must-match js2-COLON "msg.no.colon.case"))
8689 (js2-report-error "msg.double.switch.default"))
8692 (js2-must-match js2-COLON "msg.no.colon.case"))
8694 (js2-report-error "msg.bad.switch")
8695 (throw 'break nil)))
8696 (setq case-node (make-js2-case-node :pos case-pos
8697 :len (- (js2-current-token-end) case-pos)
8699 (js2-node-add-children case-node case-expr)
8700 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8704 (setf stmt (js2-parse-statement)
8705 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8706 (js2-block-node-push case-node stmt))
8707 (push case-node cases)))
8708 ;; add cases last, as pushing reverses the order to be correct
8710 (js2-node-add-children pn kid)
8711 (push kid (js2-switch-node-cases pn)))
8713 (js2-exit-switch))))
8715 (defun js2-parse-while ()
8716 "Parser for while-statement. Last matched token must be js2-WHILE."
8717 (let ((pos (js2-current-token-beg))
8718 (pn (make-js2-while-node))
8723 (setf cond (js2-parse-condition)
8724 (js2-while-node-condition pn) (car cond)
8725 body (js2-parse-statement)
8726 (js2-while-node-body pn) body
8727 (js2-node-len pn) (- (js2-node-end body) pos)
8728 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8729 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8730 (js2-node-add-children pn body (car cond)))
8734 (defun js2-parse-do ()
8735 "Parser for do-statement. Last matched token must be js2-DO."
8736 (let ((pos (js2-current-token-beg))
8737 (pn (make-js2-do-node))
8742 (setq body (js2-parse-statement))
8743 (js2-must-match js2-WHILE "msg.no.while.do")
8744 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8745 cond (js2-parse-condition)
8746 (js2-do-node-condition pn) (car cond)
8747 (js2-do-node-body pn) body
8749 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8750 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8751 (js2-node-add-children pn (car cond) body))
8753 ;; Always auto-insert semicolon to follow SpiderMonkey:
8754 ;; It is required by ECMAScript but is ignored by the rest of
8755 ;; world; see bug 238945
8756 (if (js2-match-token js2-SEMI)
8757 (setq end js2-ts-cursor))
8758 (setf (js2-node-len pn) (- end pos))
8761 (defun js2-parse-export ()
8762 "Parse an export statement.
8763 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8764 expressions should only be either hoistable expressions (function or generator)
8765 or assignment expressions, but there is no checking to enforce that and so it
8766 will parse without error a small subset of
8767 invalid export statements."
8768 (unless (js2-ast-root-p js2-current-scope)
8769 (js2-report-error "msg.mod.export.decl.at.top.level"))
8770 (let ((beg (js2-current-token-beg))
8772 exports-list from-clause declaration default)
8774 ((js2-match-token js2-MUL)
8775 (setq from-clause (js2-parse-from-clause))
8777 (push from-clause children)))
8778 ((js2-match-token js2-LC)
8779 (setq exports-list (js2-parse-export-bindings))
8781 (dolist (export exports-list)
8782 (push export children)))
8783 (when (js2-match-token js2-NAME)
8784 (if (equal "from" (js2-current-token-string))
8787 (setq from-clause (js2-parse-from-clause)))
8788 (js2-unget-token))))
8789 ((js2-match-token js2-DEFAULT)
8790 (setq default (js2-parse-expr)))
8791 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8792 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8794 (setq declaration (js2-parse-expr))))
8796 (push from-clause children))
8798 (push declaration children)
8799 (when (not (js2-function-node-p declaration))
8800 (js2-auto-insert-semicolon declaration)))
8802 (push default children)
8803 (when (not (js2-function-node-p default))
8804 (js2-auto-insert-semicolon default)))
8805 (let ((node (make-js2-export-node
8807 :len (- (js2-current-token-end) beg)
8808 :exports-list exports-list
8809 :from-clause from-clause
8810 :declaration declaration
8812 (apply #'js2-node-add-children node children)
8815 (defun js2-parse-for ()
8816 "Parse a for, for-in or for each-in statement.
8817 Last matched token must be js2-FOR."
8818 (let ((for-pos (js2-current-token-beg))
8819 (tmp-scope (make-js2-scope))
8820 pn is-for-each is-for-in-or-of is-for-of
8821 in-pos each-pos tmp-pos
8822 init ; Node init is also foo in 'foo in object'.
8823 cond ; Node cond is also object in 'foo in object'.
8824 incr ; 3rd section of for-loop initializer.
8826 ;; See if this is a for each () instead of just a for ()
8827 (when (js2-match-token js2-NAME)
8828 (if (string= "each" (js2-current-token-string))
8831 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8832 (js2-record-face 'font-lock-keyword-face))
8833 (js2-report-error "msg.no.paren.for")))
8834 (if (js2-must-match js2-LP "msg.no.paren.for")
8835 (setq lp (- (js2-current-token-beg) for-pos)))
8836 (setq tt (js2-get-token))
8837 ;; Capture identifiers inside parens. We can't create the node
8838 ;; (and use it as the current scope) until we know its type.
8839 (js2-push-scope tmp-scope)
8842 ;; parse init clause
8843 (let ((js2-in-for-init t)) ; set as dynamic variable
8847 (setq init (make-js2-empty-expr-node)))
8848 ((or (= tt js2-VAR) (= tt js2-LET))
8849 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8852 (setq init (js2-parse-expr)))))
8853 (if (or (js2-match-token js2-IN)
8854 (and (>= js2-language-version 200)
8855 (js2-match-contextual-kwd "of")
8856 (setq is-for-of t)))
8857 (setq is-for-in-or-of t
8858 in-pos (- (js2-current-token-beg) for-pos)
8859 ;; scope of iteration target object is not the scope we've created above.
8860 ;; stash current scope temporary.
8861 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8862 (js2-parse-expr))) ; object over which we're iterating
8863 ;; else ordinary for loop - parse cond and incr
8864 (js2-must-match js2-SEMI "msg.no.semi.for")
8865 (setq cond (if (= (js2-peek-token) js2-SEMI)
8866 (make-js2-empty-expr-node) ; no loop condition
8868 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8869 (setq tmp-pos (js2-current-token-end)
8870 incr (if (= (js2-peek-token) js2-RP)
8871 (make-js2-empty-expr-node :pos tmp-pos)
8872 (js2-parse-expr)))))
8874 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8875 (setq rp (- (js2-current-token-beg) for-pos)))
8876 (if (not is-for-in-or-of)
8877 (setq pn (make-js2-for-node :init init
8882 ;; cond could be null if 'in obj' got eaten by the init node.
8883 (if (js2-infix-node-p init)
8884 ;; it was (foo in bar) instead of (var foo in bar)
8885 (setq cond (js2-infix-node-right init)
8886 init (js2-infix-node-left init))
8887 (if (and (js2-var-decl-node-p init)
8888 (> (length (js2-var-decl-node-kids init)) 1))
8889 (js2-report-error "msg.mult.index")))
8890 (setq pn (make-js2-for-in-node :iterator init
8893 :foreach-p is-for-each
8898 ;; Transplant the declarations.
8899 (setf (js2-scope-symbol-table pn)
8900 (js2-scope-symbol-table tmp-scope))
8904 ;; We have to parse the body -after- creating the loop node,
8905 ;; so that the loop node appears in the js2-loop-set, allowing
8906 ;; break/continue statements to find the enclosing loop.
8907 (setf body (js2-parse-statement)
8908 (js2-loop-node-body pn) body
8909 (js2-node-pos pn) for-pos
8910 (js2-node-len pn) (- (js2-node-end body) for-pos))
8911 (js2-node-add-children pn init cond incr body))
8916 (defun js2-parse-try ()
8917 "Parse a try statement. Last matched token must be js2-TRY."
8918 (let ((try-pos (js2-current-token-beg))
8925 (if (/= (js2-peek-token) js2-LC)
8926 (js2-report-error "msg.no.brace.try"))
8927 (setq try-block (js2-parse-statement)
8928 try-end (js2-node-end try-block)
8929 peek (js2-peek-token))
8932 (while (js2-match-token js2-CATCH)
8933 (let* ((catch-pos (js2-current-token-beg))
8934 (catch-node (make-js2-catch-node :pos catch-pos))
8939 (if saw-default-catch
8940 (js2-report-error "msg.catch.unreachable"))
8941 (if (js2-must-match js2-LP "msg.no.paren.catch")
8942 (setq lp (- (js2-current-token-beg) catch-pos)))
8943 (js2-push-scope catch-node)
8944 (let ((tt (js2-peek-token)))
8946 ;; Destructuring pattern:
8947 ;; catch ({ message, file }) { ... }
8948 ((or (= tt js2-LB) (= tt js2-LC))
8950 (setq param (js2-parse-destruct-primary-expr))
8951 (js2-define-destruct-symbols param js2-LET nil))
8954 (js2-must-match-name "msg.bad.catchcond")
8955 (setq param (js2-create-name-node))
8956 (js2-define-symbol js2-LET (js2-current-token-string) param)
8957 (js2-check-strict-identifier param))))
8959 (if (js2-match-token js2-IF)
8960 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8961 catch-cond (js2-parse-expr))
8962 (setq saw-default-catch t))
8963 (if (js2-must-match js2-RP "msg.bad.catchcond")
8964 (setq rp (- (js2-current-token-beg) catch-pos)))
8965 (js2-must-match js2-LC "msg.no.brace.catchblock")
8966 (js2-parse-statements catch-node)
8967 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8968 (setq try-end (js2-current-token-end)))
8970 (setf (js2-node-len catch-node) (- try-end catch-pos)
8971 (js2-catch-node-param catch-node) param
8972 (js2-catch-node-guard-expr catch-node) catch-cond
8973 (js2-catch-node-guard-kwd catch-node) guard-kwd
8974 (js2-catch-node-lp catch-node) lp
8975 (js2-catch-node-rp catch-node) rp)
8976 (js2-node-add-children catch-node param catch-cond)
8977 (push catch-node catch-blocks))))
8978 ((/= peek js2-FINALLY)
8979 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8980 (js2-node-pos try-block)
8981 (- (setq try-end (js2-node-end try-block))
8982 (js2-node-pos try-block)))))
8983 (when (js2-match-token js2-FINALLY)
8984 (let ((finally-pos (js2-current-token-beg))
8985 (block (js2-parse-statement)))
8986 (setq try-end (js2-node-end block)
8987 finally-block (make-js2-finally-node :pos finally-pos
8988 :len (- try-end finally-pos)
8990 (js2-node-add-children finally-block block)))
8991 (let ((pn (make-js2-try-node :pos try-pos
8992 :len (- try-end try-pos)
8993 :try-block try-block
8994 :finally-block finally-block)))
8995 (js2-node-add-children pn try-block finally-block)
8996 ;; Push them onto the try-node, which reverses and corrects their order.
8997 (dolist (cb catch-blocks)
8998 (js2-node-add-children pn cb)
8999 (push cb (js2-try-node-catch-clauses pn)))
9002 (defun js2-parse-throw ()
9003 "Parser for throw-statement. Last matched token must be js2-THROW."
9004 (let ((pos (js2-current-token-beg))
9006 (if (= (js2-peek-token-or-eol) js2-EOL)
9007 ;; ECMAScript does not allow new lines before throw expression,
9009 (js2-report-error "msg.bad.throw.eol"))
9010 (setq expr (js2-parse-expr)
9011 pn (make-js2-throw-node :pos pos
9012 :len (- (js2-node-end expr) pos)
9014 (js2-node-add-children pn expr)
9017 (defun js2-match-jump-label-name (label-name)
9018 "If break/continue specified a label, return that label's labeled stmt.
9019 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9020 does not match an existing label, reports an error and returns nil."
9021 (let ((bundle (cdr (assoc label-name js2-label-set))))
9023 (js2-report-error "msg.undef.label"))
9026 (defun js2-parse-break ()
9027 "Parser for break-statement. Last matched token must be js2-BREAK."
9028 (let ((pos (js2-current-token-beg))
9029 (end (js2-current-token-end))
9030 break-target ; statement to break from
9031 break-label ; in "break foo", name-node representing the foo
9032 labels ; matching labeled statement to break to
9034 (when (eq (js2-peek-token-or-eol) js2-NAME)
9036 (setq break-label (js2-create-name-node)
9037 end (js2-node-end break-label)
9038 ;; matchJumpLabelName only matches if there is one
9039 labels (js2-match-jump-label-name (js2-current-token-string))
9040 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9041 (unless (or break-target break-label)
9042 ;; no break target specified - try for innermost enclosing loop/switch
9043 (if (null js2-loop-and-switch-set)
9045 (js2-report-error "msg.bad.break" nil pos (length "break")))
9046 (setq break-target (car js2-loop-and-switch-set))))
9047 (setq pn (make-js2-break-node :pos pos
9050 :target break-target))
9051 (js2-node-add-children pn break-label) ; but not break-target
9054 (defun js2-parse-continue ()
9055 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9056 (let ((pos (js2-current-token-beg))
9057 (end (js2-current-token-end))
9058 label ; optional user-specified label, a `js2-name-node'
9059 labels ; current matching labeled stmt, if any
9060 target ; the `js2-loop-node' target of this continue stmt
9062 (when (= (js2-peek-token-or-eol) js2-NAME)
9064 (setq label (js2-create-name-node)
9065 end (js2-node-end label)
9066 ;; matchJumpLabelName only matches if there is one
9067 labels (js2-match-jump-label-name (js2-current-token-string))))
9069 ((null labels) ; no current label to go to
9070 (if (null js2-loop-set) ; no loop to continue to
9071 (js2-report-error "msg.continue.outside" nil pos
9072 (length "continue"))
9073 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9075 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9076 (setq target (js2-labeled-stmt-node-stmt labels))
9077 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9078 (setq pn (make-js2-continue-node :pos pos
9082 (js2-node-add-children pn label) ; but not target - it's not our child
9085 (defun js2-parse-with ()
9086 "Parser for with-statement. Last matched token must be js2-WITH."
9087 (when js2-in-use-strict-directive
9088 (js2-report-error "msg.no.with.strict"))
9089 (let ((pos (js2-current-token-beg))
9091 (if (js2-must-match js2-LP "msg.no.paren.with")
9092 (setq lp (js2-current-token-beg)))
9093 (setq obj (js2-parse-expr))
9094 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9095 (setq rp (js2-current-token-beg)))
9096 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9097 (setq body (js2-parse-statement)))
9098 (setq pn (make-js2-with-node :pos pos
9099 :len (- (js2-node-end body) pos)
9102 :lp (js2-relpos lp pos)
9103 :rp (js2-relpos rp pos)))
9104 (js2-node-add-children pn obj body)
9107 (defun js2-parse-const-var ()
9108 "Parser for var- or const-statement.
9109 Last matched token must be js2-CONST or js2-VAR."
9110 (let ((tt (js2-current-token-type))
9111 (pos (js2-current-token-beg))
9113 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9114 pn (make-js2-expr-stmt-node :pos pos
9115 :len (- (js2-node-end expr) pos)
9117 (js2-node-add-children pn expr)
9120 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9121 (let ((pn (make-js2-expr-stmt-node :pos pos
9122 :len (js2-node-len expr)
9123 :type (if (js2-inside-function)
9128 (js2-node-add-children pn expr))
9131 (defun js2-parse-let-stmt ()
9132 "Parser for let-statement. Last matched token must be js2-LET."
9133 (let ((pos (js2-current-token-beg))
9135 (if (= (js2-peek-token) js2-LP)
9136 ;; let expression in statement context
9137 (setq expr (js2-parse-let pos 'statement)
9138 pn (js2-wrap-with-expr-stmt pos expr t))
9139 ;; else we're looking at a statement like let x=6, y=7;
9140 (setf expr (js2-parse-variables js2-LET pos)
9141 pn (js2-wrap-with-expr-stmt pos expr t)
9142 (js2-node-type pn) js2-EXPR_RESULT))
9145 (defun js2-parse-ret-yield ()
9146 (js2-parse-return-or-yield (js2-current-token-type) nil))
9148 (defconst js2-parse-return-stmt-enders
9149 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9151 (defsubst js2-now-all-set (before after mask)
9152 "Return whether or not the bits in the mask have changed to all set.
9153 BEFORE is bits before change, AFTER is bits after change, and MASK is
9154 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9156 (and (/= (logand before mask) mask)
9157 (= (logand after mask) mask)))
9159 (defun js2-parse-return-or-yield (tt expr-context)
9160 (let* ((pos (js2-current-token-beg))
9161 (end (js2-current-token-end))
9162 (before js2-end-flags)
9163 (inside-function (js2-inside-function))
9164 (gen-type (and inside-function (js2-function-node-generator-type
9165 js2-current-script-or-fn)))
9166 e ret name yield-star-p)
9167 (unless inside-function
9168 (js2-report-error (if (eq tt js2-RETURN)
9171 (when (and inside-function
9173 (js2-match-token js2-MUL))
9174 (setq yield-star-p t))
9175 ;; This is ugly, but we don't want to require a semicolon.
9176 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9177 (setq e (js2-parse-expr)
9178 end (js2-node-end e)))
9181 (js2-set-flag js2-end-flags (if (null e)
9183 js2-end-returns-value))
9184 (setq ret (make-js2-return-node :pos pos
9187 (js2-node-add-children ret e)
9188 ;; See if we need a strict mode warning.
9189 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9190 ;; more thorough and accurate than this before/after flag check.
9191 ;; E.g. if there's a finally-block that always returns, we shouldn't
9192 ;; show a warning generated by inconsistent returns in the catch blocks.
9193 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9194 ;; so we know which returns/yields to highlight, and we should get rid of
9195 ;; all the checking in `js2-parse-return-or-yield'.
9196 (if (and js2-strict-inconsistent-return-warning
9197 (js2-now-all-set before js2-end-flags
9198 (logior js2-end-returns js2-end-returns-value)))
9199 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9200 ((eq gen-type 'COMPREHENSION)
9201 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9202 ;; like SpiderMonkey does.
9203 (js2-report-error "msg.syntax" nil pos 5))
9205 (setq ret (make-js2-yield-node :pos pos
9208 :star-p yield-star-p))
9209 (js2-node-add-children ret e)
9210 (unless expr-context
9212 ret (js2-wrap-with-expr-stmt pos e t))
9213 (js2-set-requires-activation)
9214 (js2-set-is-generator))))
9215 ;; see if we are mixing yields and value returns.
9216 (when (and inside-function
9217 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9218 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9220 (setq name (js2-function-name js2-current-script-or-fn))
9221 (if (zerop (length name))
9222 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9223 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9226 (defun js2-parse-debugger ()
9227 (make-js2-keyword-node :type js2-DEBUGGER))
9229 (defun js2-parse-block ()
9230 "Parser for a curly-delimited statement block.
9231 Last token matched must be `js2-LC'."
9232 (let ((pos (js2-current-token-beg))
9233 (pn (make-js2-scope)))
9237 (js2-parse-statements pn)
9238 (js2-must-match js2-RC "msg.no.brace.block")
9239 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9243 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9244 (defun js2-parse-semi ()
9245 "Parse a statement or handle an error.
9246 Current token type is `js2-SEMI' or `js2-ERROR'."
9247 (let ((tt (js2-current-token-type)) pos len)
9248 (if (eq tt js2-SEMI)
9249 (make-js2-empty-expr-node :len 1)
9250 (setq pos (js2-current-token-beg)
9251 len (- (js2-current-token-end) pos))
9252 (js2-report-error "msg.syntax" nil pos len)
9253 (make-js2-error-node :pos pos :len len))))
9255 (defun js2-parse-default-xml-namespace ()
9256 "Parse a `default xml namespace = <expr>' e4x statement."
9257 (let ((pos (js2-current-token-beg))
9260 (js2-set-requires-activation)
9261 (setq len (- js2-ts-cursor pos))
9262 (unless (and (js2-match-token js2-NAME)
9263 (string= (js2-current-token-string) "xml"))
9264 (js2-report-error "msg.bad.namespace" nil pos len))
9265 (unless (and (js2-match-token js2-NAME)
9266 (string= (js2-current-token-string) "namespace"))
9267 (js2-report-error "msg.bad.namespace" nil pos len))
9268 (unless (js2-match-token js2-ASSIGN)
9269 (js2-report-error "msg.bad.namespace" nil pos len))
9270 (setq expr (js2-parse-expr)
9271 end (js2-node-end expr)
9272 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9276 (js2-node-add-children unary expr)
9277 (make-js2-expr-stmt-node :pos pos
9281 (defun js2-record-label (label bundle)
9282 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9284 (let ((name (js2-label-node-name label))
9287 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9288 ;; flag both labels if possible when used in editing mode
9289 (if (and js2-parse-ide-mode
9290 (setq dup (js2-get-label-by-name labeled-stmt name)))
9291 (js2-report-error "msg.dup.label" nil
9292 (js2-node-abs-pos dup) (js2-node-len dup)))
9293 (js2-report-error "msg.dup.label" nil
9294 (js2-node-pos label) (js2-node-len label)))
9295 (js2-labeled-stmt-node-add-label bundle label)
9296 (js2-node-add-children bundle label)
9297 ;; Add one reference to the bundle per label in `js2-label-set'
9298 (push (cons name bundle) js2-label-set)))
9300 (defun js2-parse-name-or-label ()
9301 "Parser for identifier or label. Last token matched must be js2-NAME.
9302 Called when we found a name in a statement context. If it's a label, we gather
9303 up any following labels and the next non-label statement into a
9304 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9305 expression and return it wrapped in a `js2-expr-stmt-node'."
9306 (let ((pos (js2-current-token-beg))
9309 ;; set check for label and call down to `js2-parse-primary-expr'
9310 (setq expr (js2-maybe-parse-label))
9312 ;; Parse the non-label expression and wrap with expression stmt.
9313 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9314 ;; else parsed a label
9315 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9316 (js2-record-label expr bundle)
9317 ;; look for more labels
9318 (while (and continue (= (js2-get-token) js2-NAME))
9319 (if (setq expr (js2-maybe-parse-label))
9320 (js2-record-label expr bundle)
9321 (setq expr (js2-parse-expr)
9322 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9324 (js2-auto-insert-semicolon stmt)))
9325 ;; no more labels; now parse the labeled statement
9328 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9330 (setq stmt (js2-statement-helper))))
9331 ;; remove the labels for this statement from the global set
9332 (dolist (label (js2-labeled-stmt-node-labels bundle))
9333 (setq js2-label-set (remove label js2-label-set))))
9334 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9335 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9336 (js2-node-add-children bundle stmt)
9339 (defun js2-maybe-parse-label ()
9340 (cl-assert (= (js2-current-token-type) js2-NAME))
9342 (next-tt (js2-get-token))
9343 (label-end (js2-current-token-end)))
9344 ;; Do not consume colon, it is used as unwind indicator
9345 ;; to return to statementHelper.
9347 (if (= next-tt js2-COLON)
9349 (setq label-pos (js2-current-token-beg))
9350 (make-js2-label-node :pos label-pos
9351 :len (- label-end label-pos)
9352 :name (js2-current-token-string))
9353 (js2-set-face label-pos
9355 'font-lock-variable-name-face 'record))
9356 ;; Backtrack from the name token, too.
9360 (defun js2-parse-expr-stmt ()
9361 "Default parser in statement context, if no recognized statement found."
9362 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9365 (js2-parse-expr)) t))
9367 (defun js2-parse-variables (decl-type pos)
9368 "Parse a comma-separated list of variable declarations.
9369 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9371 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9372 For 'var' or 'const', the keyword should be the token last scanned.
9374 POS is the position where the node should start. It's sometimes the
9375 var/const/let keyword, and other times the beginning of the first token
9376 in the first variable declaration.
9378 Returns the parsed `js2-var-decl-node' expression node."
9379 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9381 destructuring kid-pos tt init name end nbeg nend vi
9384 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9385 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9386 ;; var {a, b} = baz;
9388 (setq destructuring nil
9391 kid-pos (js2-current-token-beg)
9392 end (js2-current-token-end)
9394 (if (or (= tt js2-LB) (= tt js2-LC))
9395 ;; Destructuring assignment, e.g., var [a, b] = ...
9396 (setq destructuring (js2-parse-destruct-primary-expr)
9397 end (js2-node-end destructuring))
9398 ;; Simple variable name
9400 (when (js2-must-match-name "msg.bad.var")
9401 (setq name (js2-create-name-node)
9402 nbeg (js2-current-token-beg)
9403 nend (js2-current-token-end)
9405 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9406 (js2-check-strict-identifier name)))
9407 (when (js2-match-token js2-ASSIGN)
9408 (setq init (js2-parse-assign-expr)
9409 end (js2-node-end init))
9410 (js2-record-imenu-functions init name))
9412 (js2-set-face nbeg nend (if (js2-function-node-p init)
9413 'font-lock-function-name-face
9414 'font-lock-variable-name-face)
9416 (setq vi (make-js2-var-init-node :pos kid-pos
9417 :len (- end kid-pos)
9421 (if (and (null init) (not js2-in-for-init))
9422 (js2-report-error "msg.destruct.assign.no.init"))
9423 (js2-define-destruct-symbols destructuring
9425 'font-lock-variable-name-face)
9426 (setf (js2-var-init-node-target vi) destructuring))
9427 (setf (js2-var-init-node-target vi) name))
9428 (setf (js2-var-init-node-initializer vi) init)
9429 (js2-node-add-children vi name destructuring init)
9430 (js2-block-node-push result vi)
9431 (unless (js2-match-token js2-COMMA)
9432 (setq continue nil)))
9433 (setf (js2-node-len result) (- end pos))
9436 (defun js2-parse-let (pos &optional stmt-p)
9437 "Parse a let expression or statement.
9438 A let-expression is of the form `let (vars) expr'.
9439 A let-statement is of the form `let (vars) {statements}'.
9440 The third form of let is a variable declaration list, handled
9441 by `js2-parse-variables'."
9442 (let ((pn (make-js2-let-node :pos pos))
9444 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9445 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9449 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9450 (if (js2-must-match js2-RP "msg.no.paren.let")
9451 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9452 (if (and stmt-p (js2-match-token js2-LC))
9455 (setf beg (js2-current-token-beg) ; position stmt at LC
9456 body (js2-parse-statements))
9457 (js2-must-match js2-RC "msg.no.curly.let")
9458 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9459 (js2-node-len pn) (- (js2-current-token-end) pos)
9460 (js2-let-node-body pn) body
9461 (js2-node-type pn) js2-LET))
9463 (setf body (js2-parse-expr)
9464 (js2-node-len pn) (- (js2-node-end body) pos)
9465 (js2-let-node-body pn) body))
9466 (setf (js2-let-node-vars pn) vars)
9467 (js2-node-add-children pn vars body))
9471 (defun js2-define-new-symbol (decl-type name node &optional scope)
9472 (js2-scope-put-symbol (or scope js2-current-scope)
9474 (make-js2-symbol decl-type name node)))
9476 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9477 "Define a symbol in the current scope.
9478 If NODE is non-nil, it is the AST node associated with the symbol."
9479 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9480 (symbol (if defining-scope
9481 (js2-scope-get-symbol defining-scope name)))
9482 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9483 (pos (if node (js2-node-abs-pos node)))
9484 (len (if node (js2-node-len node))))
9486 ((and symbol ; already defined
9487 (or (if js2-in-use-strict-directive
9488 ;; two const-bound vars in this block have same name
9489 (and (= sdt js2-CONST)
9490 (eq defining-scope js2-current-scope))
9491 (or (= sdt js2-CONST) ; old version is const
9492 (= decl-type js2-CONST))) ; new version is const
9493 ;; two let-bound vars in this block have same name
9494 (and (= sdt js2-LET)
9495 (eq defining-scope js2-current-scope))))
9498 ((= sdt js2-CONST) "msg.const.redecl")
9499 ((= sdt js2-LET) "msg.let.redecl")
9500 ((= sdt js2-VAR) "msg.var.redecl")
9501 ((= sdt js2-FUNCTION) "msg.function.redecl")
9502 (t "msg.parm.redecl"))
9504 ((or (= decl-type js2-LET)
9505 ;; strict mode const is scoped to the current LexicalEnvironment
9506 (and js2-in-use-strict-directive
9507 (= decl-type js2-CONST)))
9508 (if (and (= decl-type js2-LET)
9509 (not ignore-not-in-block)
9510 (or (= (js2-node-type js2-current-scope) js2-IF)
9511 (js2-loop-node-p js2-current-scope)))
9512 (js2-report-error "msg.let.decl.not.in.block")
9513 (js2-define-new-symbol decl-type name node)))
9514 ((or (= decl-type js2-VAR)
9515 (= decl-type js2-FUNCTION)
9516 ;; sloppy mode const is scoped to the current VariableEnvironment
9517 (and (not js2-in-use-strict-directive)
9518 (= decl-type js2-CONST)))
9520 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9521 (js2-add-strict-warning "msg.var.redecl" name)
9522 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9523 (js2-add-strict-warning "msg.var.hides.arg" name)))
9524 (js2-define-new-symbol decl-type name node
9525 js2-current-script-or-fn)))
9526 ((= decl-type js2-LP)
9528 ;; must be duplicate parameter. Second parameter hides the
9529 ;; first, so go ahead and add the second pararameter
9530 (js2-report-warning "msg.dup.parms" name))
9531 (js2-define-new-symbol decl-type name node))
9532 (t (js2-code-bug)))))
9534 (defun js2-parse-paren-expr-or-generator-comp ()
9535 (let ((px-pos (js2-current-token-beg)))
9537 ((and (>= js2-language-version 200)
9538 (js2-match-token js2-FOR))
9539 (js2-parse-generator-comp px-pos))
9540 ((and (>= js2-language-version 200)
9541 (js2-match-token js2-RP))
9542 ;; Not valid expression syntax, but this is valid in an arrow
9543 ;; function with no params: () => body.
9544 (if (eq (js2-peek-token) js2-ARROW)
9545 ;; Return whatever, it will hopefully be rewinded and
9546 ;; reparsed when we reach the =>.
9547 (make-js2-keyword-node :type js2-NULL)
9548 (js2-report-error "msg.syntax")
9549 (make-js2-error-node)))
9551 (let* ((js2-in-for-init nil)
9552 (expr (js2-parse-expr))
9553 (pn (make-js2-paren-node :pos px-pos
9555 (js2-node-add-children pn (js2-paren-node-expr pn))
9556 (js2-must-match js2-RP "msg.no.paren")
9557 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9560 (defun js2-parse-expr (&optional oneshot)
9561 (let* ((pn (js2-parse-assign-expr))
9562 (pos (js2-node-pos pn))
9566 (while (and (not oneshot)
9567 (js2-match-token js2-COMMA))
9568 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9569 (if (= (js2-peek-token) js2-YIELD)
9570 (js2-report-error "msg.yield.parenthesized"))
9571 (setq right (js2-parse-assign-expr)
9573 pn (make-js2-infix-node :type js2-COMMA
9575 :len (- js2-ts-cursor pos)
9579 (js2-node-add-children pn left right))
9582 (defun js2-parse-assign-expr ()
9583 (let ((tt (js2-get-token))
9584 (pos (js2-current-token-beg))
9585 pn left right op-pos
9586 ts-state recorded-identifiers parsed-errors)
9587 (if (= tt js2-YIELD)
9588 (js2-parse-return-or-yield tt t)
9589 ;; Save the tokenizer state in case we find an arrow function
9590 ;; and have to rewind.
9591 (setq ts-state (make-js2-ts-state)
9592 recorded-identifiers js2-recorded-identifiers
9593 parsed-errors js2-parsed-errors)
9594 ;; not yield - parse assignment expression
9595 (setq pn (js2-parse-cond-expr)
9598 ((and (<= js2-first-assign tt)
9599 (<= tt js2-last-assign))
9600 ;; tt express assignment (=, |=, ^=, ..., %=)
9601 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9603 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9604 ;; care about assignment to strict variable names.
9605 (when (js2-name-node-p left)
9606 (js2-check-strict-identifier left))
9607 (setq right (js2-parse-assign-expr)
9608 pn (make-js2-assign-node :type tt
9610 :len (- (js2-node-end right) pos)
9614 (when js2-parse-ide-mode
9615 (js2-highlight-assign-targets pn left right)
9616 (js2-record-imenu-functions right left))
9617 ;; do this last so ide checks above can use absolute positions
9618 (js2-node-add-children pn left right))
9619 ((and (= tt js2-ARROW)
9620 (>= js2-language-version 200))
9621 (js2-ts-seek ts-state)
9622 (setq js2-recorded-identifiers recorded-identifiers
9623 js2-parsed-errors parsed-errors)
9624 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9629 (defun js2-parse-cond-expr ()
9630 (let ((pos (js2-current-token-beg))
9631 (pn (js2-parse-or-expr))
9637 (when (js2-match-token js2-HOOK)
9638 (setq q-pos (- (js2-current-token-beg) pos)
9639 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9640 (js2-must-match js2-COLON "msg.no.colon.cond")
9641 (setq c-pos (- (js2-current-token-beg) pos)
9642 if-false (js2-parse-assign-expr)
9644 pn (make-js2-cond-node :pos pos
9645 :len (- (js2-node-end if-false) pos)
9646 :test-expr test-expr
9648 :false-expr if-false
9651 (js2-node-add-children pn test-expr if-true if-false))
9654 (defun js2-make-binary (type left parser &optional no-get)
9655 "Helper for constructing a binary-operator AST node.
9656 LEFT is the left-side-expression, already parsed, and the
9657 binary operator should have just been matched.
9658 PARSER is a function to call to parse the right operand,
9659 or a `js2-node' struct if it has already been parsed.
9660 FIXME: The latter option is unused?"
9661 (let* ((pos (js2-node-pos left))
9662 (op-pos (- (js2-current-token-beg) pos))
9663 (right (if (js2-node-p parser)
9665 (unless no-get (js2-get-token))
9667 (pn (make-js2-infix-node :type type
9669 :len (- (js2-node-end right) pos)
9673 (js2-node-add-children pn left right)
9676 (defun js2-parse-or-expr ()
9677 (let ((pn (js2-parse-and-expr)))
9678 (when (js2-match-token js2-OR)
9679 (setq pn (js2-make-binary js2-OR
9681 'js2-parse-or-expr)))
9684 (defun js2-parse-and-expr ()
9685 (let ((pn (js2-parse-bit-or-expr)))
9686 (when (js2-match-token js2-AND)
9687 (setq pn (js2-make-binary js2-AND
9689 'js2-parse-and-expr)))
9692 (defun js2-parse-bit-or-expr ()
9693 (let ((pn (js2-parse-bit-xor-expr)))
9694 (while (js2-match-token js2-BITOR)
9695 (setq pn (js2-make-binary js2-BITOR
9697 'js2-parse-bit-xor-expr)))
9700 (defun js2-parse-bit-xor-expr ()
9701 (let ((pn (js2-parse-bit-and-expr)))
9702 (while (js2-match-token js2-BITXOR)
9703 (setq pn (js2-make-binary js2-BITXOR
9705 'js2-parse-bit-and-expr)))
9708 (defun js2-parse-bit-and-expr ()
9709 (let ((pn (js2-parse-eq-expr)))
9710 (while (js2-match-token js2-BITAND)
9711 (setq pn (js2-make-binary js2-BITAND
9713 'js2-parse-eq-expr)))
9716 (defconst js2-parse-eq-ops
9717 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9719 (defun js2-parse-eq-expr ()
9720 (let ((pn (js2-parse-rel-expr))
9722 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9723 (setq pn (js2-make-binary tt
9725 'js2-parse-rel-expr)))
9729 (defconst js2-parse-rel-ops
9730 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9732 (defun js2-parse-rel-expr ()
9733 (let ((pn (js2-parse-shift-expr))
9737 (setq tt (js2-get-token))
9739 ((and js2-in-for-init (= tt js2-IN))
9741 (setq continue nil))
9742 ((memq tt js2-parse-rel-ops)
9743 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9746 (setq continue nil))))
9749 (defconst js2-parse-shift-ops
9750 (list js2-LSH js2-URSH js2-RSH))
9752 (defun js2-parse-shift-expr ()
9753 (let ((pn (js2-parse-add-expr))
9757 (setq tt (js2-get-token))
9758 (if (memq tt js2-parse-shift-ops)
9759 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9761 (setq continue nil)))
9764 (defun js2-parse-add-expr ()
9765 (let ((pn (js2-parse-mul-expr))
9769 (setq tt (js2-get-token))
9770 (if (or (= tt js2-ADD) (= tt js2-SUB))
9771 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9773 (setq continue nil)))
9776 (defconst js2-parse-mul-ops
9777 (list js2-MUL js2-DIV js2-MOD))
9779 (defun js2-parse-mul-expr ()
9780 (let ((pn (js2-parse-unary-expr))
9784 (setq tt (js2-get-token))
9785 (if (memq tt js2-parse-mul-ops)
9786 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9788 (setq continue nil)))
9791 (defun js2-make-unary (type parser &rest args)
9792 "Make a unary node of type TYPE.
9793 PARSER is either a node (for postfix operators) or a function to call
9794 to parse the operand (for prefix operators)."
9795 (let* ((pos (js2-current-token-beg))
9796 (postfix (js2-node-p parser))
9799 (apply parser args)))
9802 (if postfix ; e.g. i++
9803 (setq pos (js2-node-pos expr)
9804 end (js2-current-token-end))
9805 (setq end (js2-node-end expr)))
9806 (setq pn (make-js2-unary-node :type type
9810 (js2-node-add-children pn expr)
9813 (defconst js2-incrementable-node-types
9814 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9815 "Node types that can be the operand of a ++ or -- operator.")
9817 (defun js2-check-bad-inc-dec (tt beg end unary)
9818 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9819 js2-incrementable-node-types)
9820 (js2-report-error (if (= tt js2-INC)
9823 nil beg (- end beg))))
9825 (defun js2-parse-unary-expr ()
9826 (let ((tt (js2-current-token-type))
9829 ((or (= tt js2-VOID)
9834 (js2-make-unary tt 'js2-parse-unary-expr))
9837 ;; Convert to special POS token in decompiler and parse tree
9838 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9841 ;; Convert to special NEG token in decompiler and parse tree
9842 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9847 (setq beg (js2-current-token-beg)
9848 end (js2-current-token-end)
9849 expr (js2-make-unary tt 'js2-parse-member-expr t))
9850 (js2-check-bad-inc-dec tt beg end expr)))
9853 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9856 (make-js2-error-node)) ; try to continue
9858 js2-compiler-xml-available)
9859 ;; XML stream encountered in expression.
9860 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9862 (setq pn (js2-parse-member-expr t)
9863 ;; Don't look across a newline boundary for a postfix incop.
9864 tt (js2-peek-token-or-eol))
9865 (when (or (= tt js2-INC) (= tt js2-DEC))
9868 pn (js2-make-unary tt expr))
9869 (js2-node-set-prop pn 'postfix t)
9870 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9873 (defun js2-parse-xml-initializer ()
9874 "Parse an E4X XML initializer.
9875 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9876 Then I'll postprocess the result, depending on whether we're in IDE
9877 mode or codegen mode, and generate the appropriate rewritten AST.
9878 IDE mode uses a rich AST that models the XML structure. Codegen mode
9879 just concatenates everything and makes a new XML or XMLList out of it."
9880 (let ((tt (js2-get-first-xml-token))
9881 pn-xml pn expr kids expr-pos
9884 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9885 (js2-report-error "msg.syntax"))
9886 (setq pn-xml (make-js2-xml-node))
9889 (setq first-token nil)
9890 (setq tt (js2-get-next-xml-token)))
9892 ;; js2-XML means we found a {expr} in the XML stream.
9893 ;; The token string is the XML up to the left-curly.
9895 (push (make-js2-string-node :pos (js2-current-token-beg)
9896 :len (- js2-ts-cursor (js2-current-token-beg)))
9898 (js2-must-match js2-LC "msg.syntax")
9899 (setq expr-pos js2-ts-cursor
9900 expr (if (eq (js2-peek-token) js2-RC)
9901 (make-js2-empty-expr-node :pos expr-pos)
9903 (js2-must-match js2-RC "msg.syntax")
9904 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9905 :len (js2-node-len expr)
9907 (js2-node-add-children pn expr)
9909 ;; a js2-XMLEND token means we hit the final close-tag.
9911 (push (make-js2-string-node :pos (js2-current-token-beg)
9912 :len (- js2-ts-cursor (js2-current-token-beg)))
9914 (dolist (kid (nreverse kids))
9915 (js2-block-node-push pn-xml kid))
9916 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9917 (js2-node-pos pn-xml))
9920 (js2-report-error "msg.syntax")
9921 (setq continue nil))))
9925 (defun js2-parse-argument-list ()
9926 "Parse an argument list and return it as a Lisp list of nodes.
9927 Returns the list in reverse order. Consumes the right-paren token."
9929 (unless (js2-match-token js2-RP)
9931 (let ((tt (js2-get-token)))
9932 (if (= tt js2-YIELD)
9933 (js2-report-error "msg.yield.parenthesized"))
9934 (if (and (= tt js2-TRIPLEDOT)
9935 (>= js2-language-version 200))
9936 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9938 (push (js2-parse-assign-expr) result)))
9940 (js2-match-token js2-COMMA))
9941 (js2-must-match js2-RP "msg.no.paren.arg")
9944 (defun js2-parse-member-expr (&optional allow-call-syntax)
9945 (let ((tt (js2-current-token-type))
9946 pn pos target args beg end init)
9948 (setq pn (js2-parse-primary-expr))
9949 ;; parse a 'new' expression
9951 (setq pos (js2-current-token-beg)
9953 target (js2-parse-member-expr)
9954 end (js2-node-end target)
9955 pn (make-js2-new-node :pos pos
9958 (js2-highlight-function-call (js2-current-token))
9959 (js2-node-add-children pn target)
9960 (when (js2-match-token js2-LP)
9961 ;; Add the arguments to pn, if any are supplied.
9962 (setf beg pos ; start of "new" keyword
9963 pos (js2-current-token-beg)
9964 args (nreverse (js2-parse-argument-list))
9965 (js2-new-node-args pn) args
9966 end (js2-current-token-end)
9967 (js2-new-node-lp pn) (- pos beg)
9968 (js2-new-node-rp pn) (- end 1 beg))
9969 (apply #'js2-node-add-children pn args))
9970 (when (and js2-allow-rhino-new-expr-initializer
9971 (js2-match-token js2-LC))
9972 (setf init (js2-parse-object-literal)
9973 end (js2-node-end init)
9974 (js2-new-node-initializer pn) init)
9975 (js2-node-add-children pn init))
9976 (setf (js2-node-len pn) (- end beg))) ; end outer if
9977 (js2-parse-member-expr-tail allow-call-syntax pn)))
9979 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9980 "Parse a chain of property/array accesses or function calls.
9981 Includes parsing for E4X operators like `..' and `.@'.
9982 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9983 Returns an expression tree that includes PN, the parent node."
9987 (setq tt (js2-get-token))
9989 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9990 (setq pn (js2-parse-property-access tt pn)))
9991 ((= tt js2-DOTQUERY)
9992 (setq pn (js2-parse-dot-query pn)))
9994 (setq pn (js2-parse-element-get pn)))
9997 (if allow-call-syntax
9998 (setq pn (js2-parse-function-call pn))
9999 (setq continue nil)))
10000 ((= tt js2-TEMPLATE_HEAD)
10001 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10002 ((= tt js2-NO_SUBS_TEMPLATE)
10003 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10006 (setq continue nil)))
10007 (if (>= js2-highlight-level 2)
10008 (js2-parse-highlight-member-expr-node pn)))
10011 (defun js2-parse-tagged-template (tag-node tpl-node)
10012 "Parse tagged template expression."
10013 (let* ((beg (js2-node-pos tag-node))
10014 (pn (make-js2-tagged-template-node :beg beg
10015 :len (- (js2-current-token-end) beg)
10017 :template tpl-node)))
10018 (js2-node-add-children pn tag-node tpl-node)
10021 (defun js2-parse-dot-query (pn)
10022 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10023 Last token parsed must be `js2-DOTQUERY'."
10024 (let ((pos (js2-node-pos pn))
10026 (js2-must-have-xml)
10027 (js2-set-requires-activation)
10028 (setq op-pos (js2-current-token-beg)
10029 expr (js2-parse-expr)
10030 end (js2-node-end expr)
10031 pn (make-js2-xml-dot-query-node :left pn
10035 (js2-node-add-children pn
10036 (js2-xml-dot-query-node-left pn)
10037 (js2-xml-dot-query-node-right pn))
10038 (if (js2-must-match js2-RP "msg.no.paren")
10039 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10040 end (js2-current-token-end)))
10041 (setf (js2-node-len pn) (- end pos))
10044 (defun js2-parse-element-get (pn)
10045 "Parse an element-get expression, e.g. foo[bar].
10046 Last token parsed must be `js2-RB'."
10047 (let ((lb (js2-current-token-beg))
10048 (pos (js2-node-pos pn))
10050 (setq expr (js2-parse-expr))
10051 (if (js2-must-match js2-RB "msg.no.bracket.index")
10052 (setq rb (js2-current-token-beg)))
10053 (setq pn (make-js2-elem-get-node :target pn
10056 :lb (js2-relpos lb pos)
10057 :rb (js2-relpos rb pos)
10058 :len (- (js2-current-token-end) pos)))
10059 (js2-node-add-children pn
10060 (js2-elem-get-node-target pn)
10061 (js2-elem-get-node-element pn))
10064 (defun js2-highlight-function-call (token)
10065 (when (eq (js2-token-type token) js2-NAME)
10066 (js2-record-face 'js2-function-call token)))
10068 (defun js2-parse-function-call (pn)
10069 (js2-highlight-function-call (js2-current-token))
10072 (pos (js2-node-pos pn)))
10073 (setq pn (make-js2-call-node :pos pos
10075 :lp (- (js2-current-token-beg) pos)))
10076 (js2-node-add-children pn (js2-call-node-target pn))
10077 ;; Add the arguments to pn, if any are supplied.
10078 (setf args (nreverse (js2-parse-argument-list))
10079 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10080 (js2-call-node-args pn) args)
10081 (apply #'js2-node-add-children pn args)
10082 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10085 (defun js2-parse-property-access (tt pn)
10086 "Parse a property access, XML descendants access, or XML attr access."
10087 (let ((member-type-flags 0)
10088 (dot-pos (js2-current-token-beg))
10089 (dot-len (if (= tt js2-DOTDOT) 2 1))
10091 ref ; right side of . or .. operator
10093 (when (= tt js2-DOTDOT)
10094 (js2-must-have-xml)
10095 (setq member-type-flags js2-descendants-flag))
10096 (if (not js2-compiler-xml-available)
10098 (js2-must-match-prop-name "msg.no.name.after.dot")
10099 (setq name (js2-create-name-node t js2-GETPROP)
10100 result (make-js2-prop-get-node :left pn
10101 :pos (js2-current-token-beg)
10103 :len (js2-current-token-len)))
10104 (js2-node-add-children result pn name)
10106 ;; otherwise look for XML operators
10107 (setf result (if (= tt js2-DOT)
10108 (make-js2-prop-get-node)
10109 (make-js2-infix-node :type js2-DOTDOT))
10110 (js2-node-pos result) (js2-node-pos pn)
10111 (js2-infix-node-op-pos result) dot-pos
10112 (js2-infix-node-left result) pn ; do this after setting position
10113 tt (js2-get-prop-name-token))
10115 ;; handles: name, ns::name, ns::*, ns::[expr]
10117 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10118 ;; handles: *, *::name, *::*, *::[expr]
10120 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10121 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10122 ((= tt js2-XMLATTR)
10123 (setq result (js2-parse-attribute-access)))
10125 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10127 (setf (js2-node-len result) (- (js2-node-end ref)
10128 (js2-node-pos result))
10129 (js2-infix-node-right result) ref))
10130 (if (js2-infix-node-p result)
10131 (js2-node-add-children result
10132 (js2-infix-node-left result)
10133 (js2-infix-node-right result)))
10136 (defun js2-parse-attribute-access ()
10137 "Parse an E4X XML attribute expression.
10138 This includes expressions of the forms:
10140 @attr @ns::attr @ns::*
10142 @[expr] @*::[expr] @ns::[expr]
10144 Called if we peeked an '@' token."
10145 (let ((tt (js2-get-prop-name-token))
10146 (at-pos (js2-current-token-beg)))
10148 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10150 (js2-parse-property-name at-pos nil 0))
10151 ;; handles: @*, @*::name, @*::*, @*::[expr]
10153 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10156 (js2-parse-xml-elem-ref at-pos))
10158 (js2-report-error "msg.no.name.after.xmlAttr")
10159 ;; Avoid cascaded errors that happen if we make an error node here.
10160 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10162 (defun js2-parse-property-name (at-pos s member-type-flags)
10163 "Check if :: follows name in which case it becomes qualified name.
10165 AT-POS is a natural number if we just read an '@' token, else nil.
10166 S is the name or string that was matched: an identifier, 'throw' or '*'.
10167 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10169 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10170 operator, or the name is followed by ::. For a plain name, returns a
10171 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10172 (let ((pos (or at-pos (js2-current-token-beg)))
10174 (name (js2-create-name-node t (js2-current-token-type) s))
10177 (when (js2-match-token js2-COLONCOLON)
10179 colon-pos (js2-current-token-beg)
10180 tt (js2-get-prop-name-token))
10182 ;; handles name::name
10184 (setq name (js2-create-name-node)))
10187 (setq name (js2-create-name-node nil nil "*")))
10188 ;; handles name::[expr]
10190 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10192 (js2-report-error "msg.no.name.after.coloncolon"))))
10193 (if (and (null ns) (zerop member-type-flags))
10197 (make-js2-xml-prop-ref-node :pos pos
10198 :len (- (js2-node-end name) pos)
10200 :colon-pos colon-pos
10202 (js2-node-add-children pn name))))))
10204 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10205 "Parse the [expr] portion of an xml element reference.
10206 For instance, @[expr], @*::[expr], or ns::[expr]."
10207 (let* ((lb (js2-current-token-beg))
10208 (pos (or at-pos lb))
10210 (expr (js2-parse-expr))
10211 (end (js2-node-end expr))
10213 (if (js2-must-match js2-RB "msg.no.bracket.index")
10214 (setq rb (js2-current-token-beg)
10215 end (js2-current-token-end)))
10218 (make-js2-xml-elem-ref-node :pos pos
10220 :namespace namespace
10221 :colon-pos colon-pos
10224 :lb (js2-relpos lb pos)
10225 :rb (js2-relpos rb pos)))
10226 (js2-node-add-children pn namespace expr))))
10228 (defun js2-parse-destruct-primary-expr ()
10229 (let ((js2-is-in-destructuring t))
10230 (js2-parse-primary-expr)))
10232 (defun js2-parse-primary-expr ()
10233 "Parse a literal (leaf) expression of some sort.
10234 Includes complex literals such as functions, object-literals,
10235 array-literals, array comprehensions and regular expressions."
10237 (setq tt (js2-current-token-type))
10240 (js2-parse-class-expr))
10241 ((= tt js2-FUNCTION)
10242 (js2-parse-function-expr))
10244 (js2-parse-array-comp-or-literal))
10246 (js2-parse-object-literal))
10248 (js2-parse-let (js2-current-token-beg)))
10250 (js2-parse-paren-expr-or-generator-comp))
10251 ((= tt js2-XMLATTR)
10252 (js2-must-have-xml)
10253 (js2-parse-attribute-access))
10255 (js2-parse-name tt))
10257 (setq node (make-js2-number-node))
10258 (when (and js2-in-use-strict-directive
10259 (= (js2-number-node-num-base node) 8)
10260 (js2-number-node-legacy-octal-p node))
10261 (js2-report-error "msg.no.octal.strict"))
10263 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10264 (make-js2-string-node :type tt))
10265 ((= tt js2-TEMPLATE_HEAD)
10266 (js2-parse-template-literal))
10267 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10268 ;; Got / or /= which in this context means a regexp literal
10269 (let ((px-pos (js2-current-token-beg))
10270 (flags (js2-read-regexp tt))
10271 (end (js2-current-token-end)))
10273 (make-js2-regexp-node :pos px-pos
10274 :len (- end px-pos)
10275 :value (js2-current-token-string)
10277 (js2-set-face px-pos end 'font-lock-string-face 'record)
10278 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10279 ((or (= tt js2-NULL)
10284 (make-js2-keyword-node :type tt))
10285 ((= tt js2-TRIPLEDOT)
10286 ;; Likewise, only valid in an arrow function with a rest param.
10287 (if (and (js2-match-token js2-NAME)
10288 (js2-match-token js2-RP)
10289 (eq (js2-peek-token) js2-ARROW))
10291 (js2-unget-token) ; Put back the right paren.
10292 ;; See the previous case.
10293 (make-js2-keyword-node :type js2-NULL))
10294 (js2-report-error "msg.syntax")
10295 (make-js2-error-node)))
10296 ((= tt js2-RESERVED)
10297 (js2-report-error "msg.reserved.id")
10298 (make-js2-name-node))
10300 ;; the scanner or one of its subroutines reported the error.
10301 (make-js2-error-node))
10303 (let* ((px-pos (point-at-bol))
10304 (len (- js2-ts-cursor px-pos)))
10305 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10306 (make-js2-error-node :pos (1- js2-ts-cursor)))
10308 (js2-report-error "msg.syntax")
10309 (make-js2-error-node)))))
10311 (defun js2-parse-template-literal ()
10312 (let ((beg (js2-current-token-beg))
10313 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10314 (tt js2-TEMPLATE_HEAD))
10315 (while (eq tt js2-TEMPLATE_HEAD)
10316 (push (js2-parse-expr) kids)
10317 (js2-must-match js2-RC "msg.syntax")
10318 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10319 (push (make-js2-string-node :type tt) kids))
10320 (setq kids (nreverse kids))
10321 (let ((tpl (make-js2-template-node :beg beg
10322 :len (- (js2-current-token-end) beg)
10324 (apply #'js2-node-add-children tpl kids)
10327 (defun js2-parse-name (_tt)
10328 (let ((name (js2-current-token-string))
10330 (setq node (if js2-compiler-xml-available
10331 (js2-parse-property-name nil name 0)
10332 (js2-create-name-node 'check-activation nil name)))
10333 (if js2-highlight-external-variables
10334 (js2-record-name-node node))
10337 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10338 (js2-add-strict-warning
10340 ;; back up from comma to beginning of line or array/objlit
10342 (js2-node-pos (car elems))
10345 (goto-char comma-pos)
10346 (back-to-indentation)
10350 (defun js2-parse-array-comp-or-literal ()
10351 (let ((pos (js2-current-token-beg)))
10352 (if (and (>= js2-language-version 200)
10353 (js2-match-token js2-FOR))
10354 (js2-parse-array-comp pos)
10355 (js2-parse-array-literal pos))))
10357 (defun js2-parse-array-literal (pos)
10358 (let ((after-lb-or-comma t)
10359 after-comma tt elems pn
10361 (unless js2-is-in-destructuring
10362 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10364 (setq tt (js2-get-token))
10368 (setq after-comma (js2-current-token-end))
10369 (if (not after-lb-or-comma)
10370 (setq after-lb-or-comma t)
10374 (= tt js2-EOF)) ; prevent infinite loop
10376 (js2-report-error "msg.no.bracket.arg" nil pos))
10377 (when (and after-comma (< js2-language-version 170))
10378 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10379 pos (remove nil elems) after-comma))
10381 pn (make-js2-array-node :pos pos
10382 :len (- js2-ts-cursor pos)
10383 :elems (nreverse elems)))
10384 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10385 ;; destructuring binding
10386 (js2-is-in-destructuring
10388 ((and (= tt js2-NAME)
10389 (= js2-ASSIGN (js2-peek-token)))
10391 (js2-parse-initialized-binding (js2-parse-name js2-NAME)))
10395 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10396 (js2-parse-destruct-primary-expr))
10399 (js2-report-error "msg.bad.var")
10400 (make-js2-error-node)))
10402 (setq after-lb-or-comma nil
10405 ((and (>= js2-language-version 170)
10406 (= tt js2-FOR) ; check for array comprehension
10407 (not after-lb-or-comma) ; "for" can't follow a comma
10408 elems ; must have at least 1 element
10409 (not (cdr elems))) ; but no 2nd element
10412 pn (js2-parse-legacy-array-comp (car elems) pos)))
10415 (unless after-lb-or-comma
10416 (js2-report-error "msg.no.bracket.arg"))
10417 (if (and (= tt js2-TRIPLEDOT)
10418 (>= js2-language-version 200))
10420 (push (js2-make-unary tt 'js2-parse-assign-expr)
10423 (push (js2-parse-assign-expr) elems))
10424 (setq after-lb-or-comma nil
10425 after-comma nil))))
10426 (unless js2-is-in-destructuring
10430 (defun js2-parse-legacy-array-comp (expr pos)
10431 "Parse a legacy array comprehension (JavaScript 1.7).
10432 EXPR is the first expression after the opening left-bracket.
10433 POS is the beginning of the LB token preceding EXPR.
10434 We should have just parsed the 'for' keyword before calling this function."
10435 (let ((current-scope js2-current-scope)
10436 loops first filter result)
10439 (while (js2-match-token js2-FOR)
10440 (let ((loop (make-js2-comp-loop-node)))
10441 (js2-push-scope loop)
10443 (js2-parse-comp-loop loop)))
10444 ;; First loop takes expr scope's parent.
10445 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10446 (js2-scope-parent-scope current-scope))
10447 ;; Set expr scope's parent to the last loop.
10448 (setf (js2-scope-parent-scope current-scope) (car loops))
10449 (if (/= (js2-get-token) js2-IF)
10451 (setq filter (js2-parse-condition))))
10452 (dotimes (_ (1- (length loops)))
10454 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10455 (setq result (make-js2-comp-node :pos pos
10456 :len (- js2-ts-cursor pos)
10458 :loops (nreverse loops)
10459 :filters (and filter (list (car filter)))
10460 :form 'LEGACY_ARRAY))
10461 ;; Set comp loop's parent to the last loop.
10462 ;; TODO: Get rid of the bogus expr scope.
10463 (setf (js2-scope-parent-scope result) first)
10464 (apply #'js2-node-add-children result expr (car filter)
10465 (js2-comp-node-loops result))
10468 (defun js2-parse-array-comp (pos)
10469 "Parse an ES6 array comprehension.
10470 POS is the beginning of the LB token.
10471 We should have just parsed the 'for' keyword before calling this function."
10472 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10473 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10476 (defun js2-parse-generator-comp (pos)
10477 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10478 (js2-current-script-or-fn
10479 (make-js2-function-node :generator-type 'COMPREHENSION))
10480 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10481 (js2-must-match js2-RP "msg.no.paren" pos)
10484 (defun js2-parse-comprehension (pos form)
10485 (let (loops filters expr result last)
10489 (while (js2-match-token js2-FOR)
10490 (let ((loop (make-js2-comp-loop-node)))
10491 (js2-push-scope loop)
10493 (js2-parse-comp-loop loop)))
10494 (while (js2-match-token js2-IF)
10495 (push (car (js2-parse-condition)) filters))
10496 (setq expr (js2-parse-assign-expr))
10497 (setq last (car loops)))
10500 (setq result (make-js2-comp-node :pos pos
10501 :len (- js2-ts-cursor pos)
10503 :loops (nreverse loops)
10504 :filters (nreverse filters)
10506 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10507 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10508 (setf (js2-scope-parent-scope result) last)
10511 (defun js2-parse-comp-loop (pn &optional only-of-p)
10512 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10513 The current token should be the initial FOR.
10514 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10515 (let ((pos (js2-comp-loop-node-pos pn))
10516 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10517 (when (and (not only-of-p) (js2-match-token js2-NAME))
10518 (if (string= (js2-current-token-string) "each")
10521 each-pos (- (js2-current-token-beg) pos)) ; relative
10522 (js2-record-face 'font-lock-keyword-face))
10523 (js2-report-error "msg.no.paren.for")))
10524 (if (js2-must-match js2-LP "msg.no.paren.for")
10525 (setq lp (- (js2-current-token-beg) pos)))
10526 (setq tt (js2-peek-token))
10531 (setq iter (js2-parse-destruct-primary-expr))
10532 (js2-define-destruct-symbols iter js2-LET
10533 'font-lock-variable-name-face t))
10534 ((js2-match-token js2-NAME)
10535 (setq iter (js2-create-name-node)))
10537 (js2-report-error "msg.bad.var")))
10538 ;; Define as a let since we want the scope of the variable to
10539 ;; be restricted to the array comprehension
10540 (if (js2-name-node-p iter)
10541 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10542 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10543 (and (>= js2-language-version 200)
10544 (js2-match-contextual-kwd "of")
10546 (setq in-pos (- (js2-current-token-beg) pos))
10547 (js2-report-error "msg.in.after.for.name"))
10548 (setq obj (js2-parse-expr))
10549 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10550 (setq rp (- (js2-current-token-beg) pos)))
10551 (setf (js2-node-pos pn) pos
10552 (js2-node-len pn) (- js2-ts-cursor pos)
10553 (js2-comp-loop-node-iterator pn) iter
10554 (js2-comp-loop-node-object pn) obj
10555 (js2-comp-loop-node-in-pos pn) in-pos
10556 (js2-comp-loop-node-each-pos pn) each-pos
10557 (js2-comp-loop-node-foreach-p pn) foreach-p
10558 (js2-comp-loop-node-forof-p pn) forof-p
10559 (js2-comp-loop-node-lp pn) lp
10560 (js2-comp-loop-node-rp pn) rp)
10561 (js2-node-add-children pn iter obj)
10564 (defun js2-parse-class-stmt ()
10565 (let ((pos (js2-current-token-beg))
10566 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10567 (name (js2-create-name-node t)))
10568 (js2-set-face (js2-node-pos name) (js2-node-end name)
10569 'font-lock-function-name-face 'record)
10570 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10571 (js2-define-symbol js2-FUNCTION
10572 (js2-name-node-name name)
10576 (defun js2-parse-class-expr ()
10577 (let ((pos (js2-current-token-beg))
10579 (when (js2-match-token js2-NAME)
10580 (setq name (js2-create-name-node t)))
10581 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10583 (defun js2-parse-class (pos form name)
10584 ;; class X [extends ...] {
10585 (let (pn elems extends)
10586 (if (js2-match-token js2-EXTENDS)
10587 (if (= (js2-peek-token) js2-LC)
10588 (js2-report-error "msg.missing.extends")
10589 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10590 (setq extends (js2-parse-assign-expr))
10592 (js2-report-error "msg.bad.extends"))))
10593 (js2-must-match js2-LC "msg.no.brace.class")
10594 (setq elems (js2-parse-object-literal-elems t)
10595 pn (make-js2-class-node :pos pos
10596 :len (- js2-ts-cursor pos)
10601 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10604 (defun js2-parse-object-literal ()
10605 (let* ((pos (js2-current-token-beg))
10606 (elems (js2-parse-object-literal-elems))
10607 (result (make-js2-object-node :pos pos
10608 :len (- js2-ts-cursor pos)
10610 (apply #'js2-node-add-children result (js2-object-node-elems result))
10613 (defun js2-property-key-string (property-node)
10614 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10615 `js2-method-node') as a string, or nil if it can't be
10616 represented as a string (e.g., the key is computed by an
10618 (let ((key (js2-infix-node-left property-node)))
10619 (when (js2-computed-prop-name-node-p key)
10620 (setq key (js2-computed-prop-name-node-expr key)))
10622 ((js2-name-node-p key)
10623 (js2-name-node-name key))
10624 ((js2-string-node-p key)
10625 (js2-string-node-value key))
10626 ((js2-number-node-p key)
10627 (js2-number-node-value key)))))
10629 (defun js2-parse-object-literal-elems (&optional class-p)
10630 (let ((pos (js2-current-token-beg))
10634 elem-key-string previous-elem-key-string
10635 after-comma previous-token)
10637 (setq tt (js2-get-prop-name-token)
10640 previous-token nil)
10641 ;; Handle 'static' keyword only if we're in a class
10642 (when (and class-p (= js2-NAME tt)
10643 (string= "static" (js2-current-token-string)))
10644 (js2-record-face 'font-lock-keyword-face)
10646 tt (js2-get-prop-name-token)))
10647 ;; Handle generator * before the property name for in-line functions
10648 (when (and (>= js2-language-version 200)
10650 (setq previous-token (js2-current-token)
10651 tt (js2-get-prop-name-token)))
10652 ;; Handle 'get' or 'set' keywords
10653 (let ((prop (js2-current-token-string)))
10654 (when (and (>= js2-language-version 200)
10656 (or (string= prop "get")
10657 (string= prop "set"))
10658 (member (js2-peek-token)
10659 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10660 (setq previous-token (js2-current-token)
10661 tt (js2-get-prop-name-token))))
10663 ;; Found a property (of any sort)
10664 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10665 (setq after-comma nil
10666 elem (js2-parse-named-prop tt pos previous-token))
10667 (if (and (null elem)
10668 (not js2-recover-from-parse-errors))
10669 (setq continue nil)))
10670 ;; Break out of loop, and handle trailing commas.
10674 (setq continue nil)
10676 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10677 pos elems after-comma)))
10678 ;; Skip semicolons in a class body
10683 (js2-report-error "msg.bad.prop")
10684 (unless js2-recover-from-parse-errors
10685 (setq continue nil)))) ; end switch
10686 ;; Handle static for classes' codegen.
10688 (if elem (js2-node-set-prop elem 'STATIC t)
10689 (js2-report-error "msg.unexpected.static")))
10690 ;; Handle commas, depending on class-p.
10691 (let ((tok (js2-get-prop-name-token)))
10692 (if (eq tok js2-COMMA)
10694 (js2-report-error "msg.class.unexpected.comma")
10695 (setq after-comma (js2-current-token-end)))
10697 (unless class-p (setq continue nil))))
10699 (when (and js2-in-use-strict-directive
10700 (setq elem-key-string (js2-property-key-string elem))
10702 (lambda (previous-elem)
10703 (and (setq previous-elem-key-string
10704 (js2-property-key-string previous-elem))
10705 ;; Check if the property is a duplicate.
10706 (string= previous-elem-key-string elem-key-string)
10707 ;; But make an exception for getter / setter pairs.
10708 (not (and (js2-method-node-p elem)
10709 (js2-method-node-p previous-elem)
10710 (/= (js2-method-node-type elem)
10711 (js2-method-node-type previous-elem))))))
10713 (js2-report-error "msg.dup.obj.lit.prop.strict"
10715 (js2-node-abs-pos (js2-infix-node-left elem))
10716 (js2-node-len (js2-infix-node-left elem))))
10717 ;; Append any parsed element.
10718 (push elem elems))) ; end loop
10719 (js2-must-match js2-RC "msg.no.brace.prop")
10722 (defun js2-parse-named-prop (tt pos previous-token)
10723 "Parse a name, string, or getter/setter object property.
10724 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10725 (let ((key (js2-parse-prop-name tt))
10726 (prop (and previous-token (js2-token-string previous-token)))
10727 (property-type (when previous-token
10728 (if (= (js2-token-type previous-token) js2-MUL)
10730 (js2-token-string previous-token)))))
10731 (when (or (string= prop "get")
10732 (string= prop "set"))
10733 (js2-set-face (js2-token-beg previous-token)
10734 (js2-token-end previous-token)
10735 'font-lock-keyword-face 'record)) ; get/set
10737 ;; method definition: {f() {...}}
10738 ((and (= (js2-peek-token) js2-LP)
10739 (>= js2-language-version 200))
10740 (when (js2-name-node-p key) ; highlight function name properties
10741 (js2-record-face 'font-lock-function-name-face))
10742 (js2-parse-method-prop pos key property-type))
10743 ;; binding element with initializer
10744 ((and (= (js2-peek-token) js2-ASSIGN)
10745 (>= js2-language-version 200))
10746 (if (not js2-is-in-destructuring)
10747 (js2-report-error "msg.init.no.destruct"))
10748 (js2-parse-initialized-binding key))
10751 (let ((beg (js2-current-token-beg))
10752 (end (js2-current-token-end))
10753 (expr (js2-parse-plain-property key)))
10754 (when (and (= tt js2-NAME)
10755 (not js2-is-in-destructuring)
10756 js2-highlight-external-variables
10757 (js2-node-get-prop expr 'SHORTHAND))
10758 (js2-record-name-node key))
10759 (js2-set-face beg end
10760 (if (js2-function-node-p
10761 (js2-object-prop-node-right expr))
10762 'font-lock-function-name-face
10763 'js2-object-property)
10767 (defun js2-parse-initialized-binding (name)
10768 "Parse a `SingleNameBinding' with initializer.
10770 `name' is the `BindingIdentifier'."
10771 (when (js2-match-token js2-ASSIGN)
10772 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10774 (defun js2-parse-prop-name (tt)
10776 ;; Literal string keys: {'foo': 'bar'}
10778 (make-js2-string-node))
10779 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10780 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10781 ((and (= tt js2-LB)
10782 (>= js2-language-version 200))
10783 (make-js2-computed-prop-name-node
10784 :expr (prog1 (js2-parse-assign-expr)
10785 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10786 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10788 (make-js2-number-node))
10789 ;; Unquoted names: {foo: 12}
10791 (js2-create-name-node))
10792 ;; Anything else is an error
10793 (t (js2-report-error "msg.bad.prop"))))
10795 (defun js2-parse-plain-property (prop)
10796 "Parse a non-getter/setter property in an object literal.
10797 PROP is the node representing the property: a number, name,
10798 string or expression."
10799 (let* ((tt (js2-get-token))
10800 (pos (js2-node-pos prop))
10803 ;; Abbreviated property, as in {foo, bar}
10804 ((and (>= js2-language-version 200)
10805 (or (= tt js2-COMMA)
10807 (not (js2-number-node-p prop)))
10809 (setq result (make-js2-object-prop-node
10813 :op-pos (js2-current-token-len)))
10814 (js2-node-add-children result prop)
10815 (js2-node-set-prop result 'SHORTHAND t)
10819 (if (= tt js2-COLON)
10820 (setq colon (- (js2-current-token-beg) pos)
10821 expr (js2-parse-assign-expr))
10822 (js2-report-error "msg.no.colon.prop")
10823 (setq expr (make-js2-error-node)))
10824 (setq result (make-js2-object-prop-node
10826 ;; don't include last consumed token in length
10827 :len (- (+ (js2-node-pos expr)
10828 (js2-node-len expr))
10833 (js2-node-add-children result prop expr)
10836 (defun js2-parse-method-prop (pos prop type-string)
10837 "Parse method property in an object literal or a class body.
10838 JavaScript syntax is:
10840 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...} }
10842 and expression closure style is also supported
10844 { get foo() x, set foo(x) _x = x }
10846 POS is the start position of the `get' or `set' keyword.
10847 PROP is the `js2-name-node' representing the property name.
10848 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10850 ((string= "get" type-string) js2-GET)
10851 ((string= "set" type-string) js2-SET)
10854 (fn (js2-parse-function-expr)))
10855 ;; it has to be an anonymous function, as we already parsed the name
10856 (if (/= (js2-node-type fn) js2-FUNCTION)
10857 (js2-report-error "msg.bad.prop")
10858 (if (cl-plusp (length (js2-function-name fn)))
10859 (js2-report-error "msg.bad.prop")))
10860 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10861 (when (string= type-string "*")
10862 (setf (js2-function-node-generator-type fn) 'STAR))
10863 (setq end (js2-node-end fn)
10864 result (make-js2-method-node :type type
10869 (js2-node-add-children result prop fn)
10872 (defun js2-create-name-node (&optional check-activation-p token string)
10873 "Create a name node using the current token and, optionally, STRING.
10874 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10875 (let* ((beg (js2-current-token-beg))
10876 (tt (js2-current-token-type))
10878 (if (= js2-NAME tt)
10879 (js2-current-token-string)
10880 (js2-tt-name tt))))
10882 (setq name (make-js2-name-node :pos beg
10885 (if check-activation-p
10886 (js2-check-activation-name s (or token js2-NAME)))
10889 ;;; Use AST to extract semantic information
10891 (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
10892 "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
10893 (let ((idx 0) elems (rlt hardcoded-array-index))
10894 (setq elems (js2-array-node-elems array-node))
10895 (if (and elem (not hardcoded-array-index))
10896 (setq rlt (catch 'nth-elt
10898 ;; We know the ELEM does belong to ARRAY-NODE,
10899 (if (eq elem x) (throw 'nth-elt idx))
10900 (setq idx (1+ idx)))
10902 (format "[%s]" rlt)))
10904 (defun js2-print-json-path (&optional hardcoded-array-index)
10905 "Print the path to the JSON value under point, and save it in the kill ring.
10906 If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
10908 (let (previous-node current-node
10912 ;; The `js2-node-at-point' starts scanning from AST root node.
10913 ;; So there is no way to optimize it.
10914 (setq current-node (js2-node-at-point))
10916 (while (not (js2-ast-root-p current-node))
10918 ;; JSON property node
10919 ((js2-object-prop-node-p current-node)
10920 (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
10921 (if rlt (setq rlt (concat "." key-name rlt))
10922 (setq rlt (concat "." key-name))))
10925 ((or (js2-array-node-p current-node))
10926 (setq rlt (concat (js2-get-element-index-from-array-node previous-node
10928 hardcoded-array-index)
10931 ;; Other nodes are ignored
10934 ;; current node is archived
10935 (setq previous-node current-node)
10936 ;; Get parent node and continue the loop
10937 (setq current-node (js2-node-parent current-node)))
10941 ;; Clean the final result
10942 (setq rlt (replace-regexp-in-string "^\\." "" rlt))
10944 (message "%s => kill-ring" rlt))
10946 (message "No JSON path found!")))
10950 ;;; Indentation support (bouncing)
10952 ;; In recent-enough Emacs, we reuse the indentation code from
10953 ;; `js-mode'. To continue support for the older versions, some code
10954 ;; that was here previously was moved to `js2-old-indent.el'.
10956 ;; Whichever indenter is used, it's often "wrong", however, and needs
10957 ;; to be overridden. The right long-term solution is probably to
10958 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
10959 ;; of coding. Even when a parse tree from `js2-parse' is present,
10960 ;; which is not true at the moment the user is typing, computing
10961 ;; indentation is still thousands of lines of code to handle every
10962 ;; possible syntactic edge case.
10964 ;; In the meantime, the compromise solution is that we offer a "bounce
10965 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10966 ;; current line indent among various likely guess points. This approach
10967 ;; is far from perfect, but should at least make it slightly easier to
10968 ;; move the line towards its desired indentation when manually
10969 ;; overriding Karl's heuristic nesting guesser.
10971 (defun js2-backward-sws ()
10972 "Move backward through whitespace and comments."
10974 (while (forward-comment -1)))
10976 (defun js2-forward-sws ()
10977 "Move forward through whitespace and comments."
10979 (while (forward-comment 1)))
10981 (defun js2-arglist-close ()
10982 "Return non-nil if we're on a line beginning with a close-paren/brace."
10984 (goto-char (point-at-bol))
10986 (looking-at "[])}]")))
10988 (defun js2-indent-looks-like-label-p ()
10989 (goto-char (point-at-bol))
10991 (looking-at (concat js2-mode-identifier-re ":")))
10993 (defun js2-indent-in-objlit-p (parse-status)
10994 "Return non-nil if this looks like an object-literal entry."
10995 (let ((start (nth 1 parse-status)))
10999 (and (zerop (forward-line -1))
11000 (not (< (point) start)) ; crossed a {} boundary
11001 (js2-indent-looks-like-label-p)))
11003 (js2-indent-looks-like-label-p)))))
11005 ;; If prev line looks like foobar({ then we're passing an object
11006 ;; literal to a function call, and people pretty much always want to
11007 ;; de-dent back to the previous line, so move the 'basic-offset'
11008 ;; position to the front.
11009 (defun js2-indent-objlit-arg-p (parse-status)
11011 (back-to-indentation)
11013 (and (eq (1- (point)) (nth 1 parse-status))
11014 (eq (char-before) ?{)
11017 (skip-chars-backward " \t")
11018 (eq (char-before) ?\()))))
11020 (defun js2-indent-case-block-p ()
11022 (back-to-indentation)
11024 (goto-char (point-at-bol))
11025 (skip-chars-forward " \t")
11026 (looking-at "case\\s-.+:")))
11028 (defun js2-bounce-indent (normal-col parse-status &optional backward)
11029 "Cycle among alternate computed indentation positions.
11030 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11031 of the buffer to the current point. NORMAL-COL is the indentation
11032 column computed by the heuristic guesser based on current paren,
11033 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11035 (let ((cur-indent (current-indentation))
11036 (old-buffer-undo-list buffer-undo-list)
11037 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11038 (current-line (save-excursion
11039 (forward-line 0) ; move to bol
11040 (1+ (count-lines (point-min) (point)))))
11041 positions pos main-pos anchor arglist-cont same-indent
11042 basic-offset computed-pos)
11043 ;; temporarily don't record undo info, if user requested this
11044 (when js2-mode-indent-inhibit-undo
11045 (setq buffer-undo-list t))
11048 ;; First likely point: indent from beginning of previous code line
11049 (push (setq basic-offset
11051 (back-to-indentation)
11053 (back-to-indentation)
11058 ;; (First + epsilon) likely point: indent 2x from beginning of
11059 ;; previous code line. Google does it this way.
11060 (push (setq basic-offset
11062 (back-to-indentation)
11064 (back-to-indentation)
11066 (* 2 js2-basic-offset)))
11069 ;; Second likely point: indent from assign-expr RHS. This
11070 ;; is just a crude guess based on finding " = " on the previous
11071 ;; line containing actual code.
11072 (setq pos (save-excursion
11074 (goto-char (point-at-bol))
11075 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11077 (goto-char (match-end 1))
11078 (skip-chars-forward " \t\r\n")
11079 (current-column))))
11081 (cl-incf pos js2-basic-offset)
11082 (push pos positions))
11084 ;; Third likely point: same indent as previous line of code.
11085 ;; Make it the first likely point if we're not on an
11086 ;; arglist-close line and previous line ends in a comma, or
11087 ;; both this line and prev line look like object-literal
11089 (setq pos (save-excursion
11090 (goto-char (point-at-bol))
11092 (back-to-indentation)
11095 ;; while we're here, look for trailing comma
11096 (if (save-excursion
11097 (goto-char (point-at-eol))
11099 (eq (char-before) ?,))
11100 (setq arglist-cont (1- (point)))))))
11102 (if (and (or arglist-cont
11103 (js2-indent-in-objlit-p parse-status))
11104 (not (js2-arglist-close)))
11105 (setq same-indent pos))
11106 (push pos positions))
11108 ;; Fourth likely point: first preceding code with less indentation.
11109 ;; than the immediately preceding code line.
11110 (setq pos (save-excursion
11111 (back-to-indentation)
11113 (back-to-indentation)
11114 (setq anchor (current-column))
11115 (while (and (zerop (forward-line -1))
11117 (back-to-indentation)
11120 (setq pos (current-column))))
11121 (push pos positions)
11123 ;; nesting-heuristic position, main by default
11124 (push (setq main-pos normal-col) positions)
11126 ;; delete duplicates and sort positions list
11127 (setq positions (sort (delete-dups positions) '<))
11129 ;; comma-list continuation lines: prev line indent takes precedence
11131 (setq main-pos same-indent))
11133 ;; common special cases where we want to indent in from previous line
11134 (if (or (js2-indent-case-block-p)
11135 (js2-indent-objlit-arg-p parse-status))
11136 (setq main-pos basic-offset))
11138 ;; if bouncing backward, reverse positions list
11140 (setq positions (reverse positions)))
11142 ;; record whether we're already sitting on one of the alternatives
11143 (setq pos (member cur-indent positions))
11146 ;; case 0: we're one one of the alternatives and this is the
11147 ;; first time they've pressed TAB on this line (best-guess).
11148 ((and js2-mode-indent-ignore-first-tab
11150 ;; first time pressing TAB on this line?
11151 (not (eq js2-mode-last-indented-line current-line)))
11153 (setq computed-pos nil))
11154 ;; case 1: only one computed position => use it
11155 ((null (cdr positions))
11156 (setq computed-pos 0))
11157 ;; case 2: not on any of the computed spots => use main spot
11159 (setq computed-pos (js2-position main-pos positions)))
11160 ;; case 3: on last position: cycle to first position
11162 (setq computed-pos 0))
11163 ;; case 4: on intermediate position: cycle to next position
11165 (setq computed-pos (js2-position (cl-second pos) positions))))
11167 ;; see if any hooks want to indent; otherwise we do it
11168 (cl-loop with result = nil
11169 for hook in js2-indent-hook
11170 while (null result)
11172 (setq result (funcall hook positions computed-pos))
11174 (unless (or result (null computed-pos))
11175 (indent-line-to (nth computed-pos positions)))))
11178 (if js2-mode-indent-inhibit-undo
11179 (setq buffer-undo-list old-buffer-undo-list))
11180 ;; see commentary for `js2-mode-last-indented-line'
11181 (setq js2-mode-last-indented-line current-line))))
11183 (defun js2-1-line-comment-continuation-p ()
11184 "Return t if we're in a 1-line comment continuation.
11185 If so, we don't ever want to use bounce-indent."
11189 (looking-at "\\s-*//"))
11193 (when (looking-at "\\s-*$")
11196 (looking-at "\\s-*//")))))
11198 (defun js2-indent-bounce (&optional backward)
11199 "Indent the current line, bouncing between several positions."
11201 (let (parse-status offset indent-col
11202 ;; Don't whine about errors/warnings when we're indenting.
11203 ;; This has to be set before calling parse-partial-sexp below.
11204 (inhibit-point-motion-hooks t))
11205 (setq parse-status (save-excursion
11206 (syntax-ppss (point-at-bol)))
11207 offset (- (point) (save-excursion
11208 (back-to-indentation)
11210 ;; Don't touch multiline strings.
11211 (unless (nth 3 parse-status)
11212 (setq indent-col (js2-proper-indentation parse-status))
11214 ;; It doesn't work well on first line of buffer.
11215 ((and (not (nth 4 parse-status))
11216 (not (js2-same-line (point-min)))
11217 (not (js2-1-line-comment-continuation-p)))
11218 (js2-bounce-indent indent-col parse-status backward))
11219 ;; just indent to the guesser's likely spot
11220 (t (indent-line-to indent-col)))
11221 (when (cl-plusp offset)
11222 (forward-char offset)))))
11224 (defun js2-indent-bounce-backward ()
11225 "Indent the current line, bouncing between positions in reverse."
11227 (js2-indent-bounce t))
11229 (defun js2-indent-region (start end)
11230 "Indent the region, but don't use bounce indenting."
11231 (let ((js2-bounce-indent-p nil)
11232 (indent-region-function nil)
11233 (after-change-functions (remq 'js2-mode-edit
11234 after-change-functions)))
11235 (indent-region start end nil) ; nil for byte-compiler
11236 (js2-mode-edit start end (- end start))))
11238 (defvar js2-minor-mode-map
11239 (let ((map (make-sparse-keymap)))
11240 (define-key map (kbd "C-c C-`") #'js2-next-error)
11241 (define-key map [mouse-1] #'js2-mode-show-node)
11243 "Keymap used when `js2-minor-mode' is active.")
11246 (define-minor-mode js2-minor-mode
11247 "Minor mode for running js2 as a background linter.
11248 This allows you to use a different major mode for JavaScript editing,
11249 such as `js-mode', while retaining the asynchronous error/warning
11250 highlighting features of `js2-mode'."
11252 :lighter " js-lint"
11253 (if (derived-mode-p 'js2-mode)
11254 (setq js2-minor-mode nil)
11256 (js2-minor-mode-enter)
11257 (js2-minor-mode-exit))))
11259 (defun js2-minor-mode-enter ()
11260 "Initialization for `js2-minor-mode'."
11261 (set (make-local-variable 'max-lisp-eval-depth)
11262 (max max-lisp-eval-depth 3000))
11263 (setq next-error-function #'js2-next-error)
11264 (js2-set-default-externs)
11265 ;; Experiment: make reparse-delay longer for longer files.
11266 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11267 (setq js2-idle-timer-delay
11268 (* js2-idle-timer-delay
11269 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11270 (setq js2-mode-buffer-dirty-p t
11271 js2-mode-parsing nil)
11272 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11273 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11274 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11275 (when js2-include-jslint-globals
11276 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11277 (run-hooks 'js2-init-hook)
11280 (defun js2-minor-mode-exit ()
11281 "Turn off `js2-minor-mode'."
11282 (setq next-error-function nil)
11283 (remove-hook 'after-change-functions #'js2-mode-edit t)
11284 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11285 (when js2-mode-node-overlay
11286 (delete-overlay js2-mode-node-overlay)
11287 (setq js2-mode-node-overlay nil))
11288 (js2-remove-overlays)
11289 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11290 (setq js2-mode-ast nil))
11292 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11293 (make-variable-buffer-local 'js2-source-buffer)
11295 (cl-defun js2-display-error-list ()
11296 "Display a navigable buffer listing parse errors/warnings."
11298 (unless (js2-have-errors-p)
11299 (message "No errors")
11300 (cl-return-from js2-display-error-list))
11301 (cl-labels ((annotate-list
11303 "Add diagnostic TYPE and line number to errs list"
11304 (mapcar (lambda (err)
11305 (list err type (line-number-at-pos (nth 1 err))))
11307 (let* ((srcbuf (current-buffer))
11308 (errbuf (get-buffer-create "*js-lint*"))
11309 (errors (annotate-list
11310 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11311 'js2-error)) ; must be a valid face name
11312 (warnings (annotate-list
11313 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11314 'js2-warning)) ; must be a valid face name
11315 (all-errs (sort (append errors warnings)
11316 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11317 (with-current-buffer errbuf
11318 (let ((inhibit-read-only t))
11320 (dolist (err all-errs)
11321 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11322 (insert-text-button
11323 (format "line %d: %s" line (js2-get-msg msg-key))
11325 'follow-link "\C-m"
11326 'action 'js2-error-buffer-jump
11327 'js2-msg (js2-get-msg msg-key)
11330 (js2-error-buffer-mode)
11331 (setq js2-source-buffer srcbuf)
11332 (pop-to-buffer errbuf)
11333 (goto-char (point-min))
11335 (js2-error-buffer-view))))))
11337 (defvar js2-error-buffer-mode-map
11338 (let ((map (make-sparse-keymap)))
11339 (define-key map "n" #'js2-error-buffer-next)
11340 (define-key map "p" #'js2-error-buffer-prev)
11341 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11342 (define-key map "o" #'js2-error-buffer-view)
11343 (define-key map "q" #'js2-error-buffer-quit)
11345 "Keymap used for js2 diagnostics buffers.")
11347 (defun js2-error-buffer-mode ()
11348 "Major mode for js2 diagnostics buffers.
11349 Selecting an error will jump it to the corresponding source-buffer error.
11350 \\{js2-error-buffer-mode-map}"
11352 (setq major-mode 'js2-error-buffer-mode
11353 mode-name "JS Lint Diagnostics")
11354 (use-local-map js2-error-buffer-mode-map)
11355 (setq truncate-lines t)
11356 (set-buffer-modified-p nil)
11357 (setq buffer-read-only t)
11358 (run-hooks 'js2-error-buffer-mode-hook))
11360 (defun js2-error-buffer-next ()
11361 "Move to next error and view it."
11363 (when (zerop (forward-line 1))
11364 (js2-error-buffer-view)))
11366 (defun js2-error-buffer-prev ()
11367 "Move to previous error and view it."
11369 (when (zerop (forward-line -1))
11370 (js2-error-buffer-view)))
11372 (defun js2-error-buffer-quit ()
11373 "Kill the current buffer."
11377 (defun js2-error-buffer-jump (&rest ignored)
11378 "Jump cursor to current error in source buffer."
11380 (when (js2-error-buffer-view)
11381 (pop-to-buffer js2-source-buffer)))
11383 (defun js2-error-buffer-view ()
11384 "Scroll source buffer to show error at current line."
11387 ((not (eq major-mode 'js2-error-buffer-mode))
11388 (message "Not in a js2 errors buffer"))
11389 ((not (buffer-live-p js2-source-buffer))
11390 (message "Source buffer has been killed"))
11391 ((not (wholenump (get-text-property (point) 'js2-pos)))
11392 (message "There does not seem to be an error here"))
11394 (let ((pos (get-text-property (point) 'js2-pos))
11395 (msg (get-text-property (point) 'js2-msg)))
11396 (save-selected-window
11397 (pop-to-buffer js2-source-buffer)
11402 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11403 "Major mode for editing JavaScript code."
11404 (set (make-local-variable 'max-lisp-eval-depth)
11405 (max max-lisp-eval-depth 3000))
11406 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11407 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11408 (set (make-local-variable 'syntax-propertize-function) nil)
11409 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11410 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11411 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11412 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11413 ;; for characters inside regexp literals.
11414 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11415 ;; this is necessary to make `show-paren-function' work properly
11416 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11417 ;; needed for M-x rgrep, among other things
11418 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11420 (setq font-lock-defaults '(nil t))
11422 ;; Experiment: make reparse-delay longer for longer files.
11423 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11424 (setq js2-idle-timer-delay
11425 (* js2-idle-timer-delay
11426 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11428 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11429 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11430 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11431 (setq next-error-function #'js2-next-error)
11432 (imenu-add-to-menubar (concat "IM-" mode-name))
11433 (add-to-invisibility-spec '(js2-outline . t))
11434 (set (make-local-variable 'line-move-ignore-invisible) t)
11435 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11436 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11438 (setq js2-mode-functions-hidden nil
11439 js2-mode-comments-hidden nil
11440 js2-mode-buffer-dirty-p t
11441 js2-mode-parsing nil)
11443 (js2-set-default-externs)
11445 (when js2-include-jslint-globals
11446 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11448 (run-hooks 'js2-init-hook)
11452 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11453 ;; a bit more complicated and it doesn't net us much yet.
11455 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11456 "Major mode for editing JSX code.
11458 To customize the indentation for this mode, set the SGML offset
11459 variables (`sgml-basic-offset' et al) locally, like so:
11461 (defun set-jsx-indentation ()
11462 (setq-local sgml-basic-offset js2-basic-offset))
11463 (add-hook 'js2-jsx-mode-hook #'set-jsx-indentation)"
11464 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11466 (defun js2-mode-exit ()
11467 "Exit `js2-mode' and clean up."
11469 (when js2-mode-node-overlay
11470 (delete-overlay js2-mode-node-overlay)
11471 (setq js2-mode-node-overlay nil))
11472 (js2-remove-overlays)
11473 (setq js2-mode-ast nil)
11474 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11475 (remove-from-invisibility-spec '(js2-outline . t))
11476 (js2-mode-show-all)
11477 (with-silent-modifications
11478 (js2-clear-face (point-min) (point-max))))
11480 (defun js2-mode-reset-timer ()
11481 "Cancel any existing parse timer and schedule a new one."
11482 (if js2-mode-parse-timer
11483 (cancel-timer js2-mode-parse-timer))
11484 (setq js2-mode-parsing nil)
11485 (let ((timer (timer-create)))
11486 (setq js2-mode-parse-timer timer)
11487 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11488 (timer-set-idle-time timer js2-idle-timer-delay)
11489 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11490 (timer-activate-when-idle timer nil)))
11492 (defun js2-mode-idle-reparse (buffer)
11493 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11494 it to be reparsed when the buffer is selected."
11495 (cond ((eq buffer (current-buffer))
11497 ((buffer-live-p buffer)
11498 ;; reparse when the buffer is selected again
11499 (with-current-buffer buffer
11500 (add-hook 'window-configuration-change-hook
11501 #'js2-mode-idle-reparse-inner
11504 (defun js2-mode-idle-reparse-inner ()
11505 (remove-hook 'window-configuration-change-hook
11506 #'js2-mode-idle-reparse-inner
11510 (defun js2-mode-edit (_beg _end _len)
11511 "Schedule a new parse after buffer is edited.
11512 Buffer edit spans from BEG to END and is of length LEN."
11513 (setq js2-mode-buffer-dirty-p t)
11514 (js2-mode-hide-overlay)
11515 (js2-mode-reset-timer))
11517 (defun js2-minor-mode-edit (_beg _end _len)
11518 "Callback for buffer edits in `js2-mode'.
11519 Schedules a new parse after buffer is edited.
11520 Buffer edit spans from BEG to END and is of length LEN."
11521 (setq js2-mode-buffer-dirty-p t)
11522 (js2-mode-hide-overlay)
11523 (js2-mode-reset-timer))
11525 (defun js2-reparse (&optional force)
11526 "Re-parse current buffer after user finishes some data entry.
11527 If we get any user input while parsing, including cursor motion,
11528 we discard the parse and reschedule it. If FORCE is nil, then the
11529 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11532 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11533 (unless js2-mode-parsing
11534 (setq js2-mode-parsing t)
11536 (when (or js2-mode-buffer-dirty-p force)
11537 (js2-remove-overlays)
11538 (setq js2-mode-buffer-dirty-p nil
11539 js2-mode-fontifications nil
11540 js2-mode-deferred-properties nil)
11541 (if js2-mode-verbose-parse-p
11542 (message "parsing..."))
11545 (setq interrupted-p
11546 (catch 'interrupted
11548 (with-silent-modifications
11549 ;; if parsing is interrupted, comments and regex
11550 ;; literals stay ignored by `parse-partial-sexp'
11551 (remove-text-properties (point-min) (point-max)
11553 (js2-mode-apply-deferred-properties)
11554 (js2-mode-remove-suppressed-warnings)
11555 (js2-mode-show-warnings)
11556 (js2-mode-show-errors)
11557 (if (>= js2-highlight-level 1)
11558 (js2-highlight-jsdoc js2-mode-ast)))
11562 ;; unfinished parse => try again
11563 (setq js2-mode-buffer-dirty-p t)
11564 (js2-mode-reset-timer))
11565 (if js2-mode-verbose-parse-p
11566 (message "Parse time: %s" time))))
11567 (setq js2-mode-parsing nil)
11568 (unless interrupted-p
11569 (setq js2-mode-parse-timer nil))))))
11571 (defun js2-mode-show-node (event)
11572 "Debugging aid: highlight selected AST node on mouse click."
11574 (mouse-set-point event)
11575 (setq deactivate-mark t)
11576 (when js2-mode-show-overlay
11577 (let ((node (js2-node-at-point))
11580 (message "No node found at location %s" (point))
11581 (setq beg (js2-node-abs-pos node)
11582 end (+ beg (js2-node-len node)))
11583 (if js2-mode-node-overlay
11584 (move-overlay js2-mode-node-overlay beg end)
11585 (setq js2-mode-node-overlay (make-overlay beg end))
11586 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11587 (with-silent-modifications
11588 (if (fboundp 'cursor-sensor-mode)
11589 (put-text-property beg end 'cursor-sensor-functions
11590 '(js2-mode-hide-overlay))
11591 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11592 (message "%s, parent: %s"
11593 (js2-node-short-name node)
11594 (if (js2-node-parent node)
11595 (js2-node-short-name (js2-node-parent node))
11598 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11599 "Remove the debugging overlay when point moves.
11600 ARG1, ARG2 and ARG3 have different values depending on whether this function
11601 was found on `point-left' or in `cursor-sensor-functions'."
11602 (when js2-mode-node-overlay
11603 (let ((beg (overlay-start js2-mode-node-overlay))
11604 (end (overlay-end js2-mode-node-overlay))
11605 (p2 (if (windowp arg1)
11606 ;; Called from cursor-sensor-functions.
11607 (window-point arg1)
11608 ;; Called from point-left.
11610 ;; Sometimes we're called spuriously.
11614 (with-silent-modifications
11615 (remove-text-properties beg end
11616 '(point-left nil cursor-sensor-functions)))
11617 (delete-overlay js2-mode-node-overlay)
11618 (setq js2-mode-node-overlay nil)))))
11620 (defun js2-mode-reset ()
11621 "Debugging helper: reset everything."
11626 (defun js2-mode-show-warn-or-err (e face)
11627 "Highlight a warning or error E with FACE.
11628 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11629 The last element is optional. When present, use instead of FACE."
11630 (let* ((key (cl-first e))
11631 (beg (cl-second e))
11632 (end (+ beg (cl-third e)))
11633 ;; Don't inadvertently go out of bounds.
11634 (beg (max (point-min) (min beg (point-max))))
11635 (end (max (point-min) (min end (point-max))))
11636 (ovl (make-overlay beg end)))
11637 ;; FIXME: Why a mix of overlays and text-properties?
11638 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11639 (overlay-put ovl 'js2-error t)
11640 (put-text-property beg end 'help-echo (js2-get-msg key))
11641 (if (fboundp 'cursor-sensor-mode)
11642 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11643 (put-text-property beg end 'point-entered #'js2-echo-error))))
11645 (defun js2-remove-overlays ()
11646 "Remove overlays from buffer that have a `js2-error' property."
11647 (let ((beg (point-min))
11650 (dolist (o (overlays-in beg end))
11651 (when (overlay-get o 'js2-error)
11652 (delete-overlay o))))))
11654 (defun js2-mode-apply-deferred-properties ()
11655 "Apply fontifications and other text properties recorded during parsing."
11656 (when (cl-plusp js2-highlight-level)
11657 ;; We defer clearing faces as long as possible to eliminate flashing.
11658 (js2-clear-face (point-min) (point-max))
11659 ;; Have to reverse the recorded fontifications list so that errors
11660 ;; and warnings overwrite the normal fontifications.
11661 (dolist (f (nreverse js2-mode-fontifications))
11662 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11663 (setq js2-mode-fontifications nil))
11664 (dolist (p js2-mode-deferred-properties)
11665 (apply #'put-text-property p))
11666 (setq js2-mode-deferred-properties nil))
11668 (defun js2-mode-show-errors ()
11669 "Highlight syntax errors."
11670 (when js2-mode-show-parse-errors
11671 (dolist (e (js2-ast-root-errors js2-mode-ast))
11672 (js2-mode-show-warn-or-err e 'js2-error))))
11674 (defun js2-mode-remove-suppressed-warnings ()
11675 "Take suppressed warnings out of the AST warnings list.
11676 This ensures that the counts and `next-error' are correct."
11677 (setf (js2-ast-root-warnings js2-mode-ast)
11680 (let ((key (caar e)))
11682 (and (not js2-strict-trailing-comma-warning)
11683 (string-match "trailing\\.comma" key))
11684 (and (not js2-strict-cond-assign-warning)
11685 (string= key "msg.equal.as.assign"))
11686 (and js2-missing-semi-one-line-override
11687 (string= key "msg.missing.semi")
11688 (let* ((beg (cl-second e))
11689 (node (js2-node-at-point beg))
11690 (fn (js2-mode-find-parent-fn node))
11691 (body (and fn (js2-function-node-body fn)))
11692 (lc (and body (js2-node-abs-pos body)))
11693 (rc (and lc (+ lc (js2-node-len body)))))
11698 (and (js2-same-line lc)
11699 (js2-same-line rc))))))))))
11700 (js2-ast-root-warnings js2-mode-ast))))
11702 (defun js2-mode-show-warnings ()
11703 "Highlight strict-mode warnings."
11704 (when js2-mode-show-strict-warnings
11705 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11706 (js2-mode-show-warn-or-err e 'js2-warning))))
11708 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11709 "Called by point-motion hooks.
11710 ARG1, ARG2 and ARG3 have different values depending on whether this function
11711 was found on `point-entered' or in `cursor-sensor-functions'."
11712 (let* ((new-point (if (windowp arg1)
11713 ;; Called from cursor-sensor-functions.
11714 (window-point arg1)
11715 ;; Called from point-left.
11717 (msg (get-text-property new-point 'help-echo)))
11718 (when (and (stringp msg)
11719 (not (active-minibuffer-window))
11720 (not (current-message)))
11723 (defun js2-line-break (&optional _soft)
11724 "Break line at point and indent, continuing comment if within one.
11725 If inside a string, and `js2-concat-multiline-strings' is not
11726 nil, turn it into concatenation."
11728 (let ((parse-status (syntax-ppss)))
11730 ;; Check if we're inside a string.
11731 ((nth 3 parse-status)
11732 (if js2-concat-multiline-strings
11733 (js2-mode-split-string parse-status)
11735 ;; Check if inside a block comment.
11736 ((nth 4 parse-status)
11737 (js2-mode-extend-comment (nth 8 parse-status)))
11739 (newline-and-indent)))))
11741 (defun js2-mode-split-string (parse-status)
11742 "Turn a newline in mid-string into a string concatenation.
11743 PARSE-STATUS is as documented in `parse-partial-sexp'."
11744 (let* ((quote-char (nth 3 parse-status))
11745 (at-eol (eq js2-concat-multiline-strings 'eol)))
11746 (insert quote-char)
11747 (insert (if at-eol " +\n" "\n"))
11751 (insert quote-char)
11753 (insert quote-char)
11754 (backward-char 1))))
11756 (defun js2-mode-extend-comment (start-pos)
11757 "Indent the line and, when inside a comment block, add comment prefix."
11758 (let (star single col first-line needs-close)
11760 (back-to-indentation)
11761 (when (< (point) start-pos)
11762 (goto-char start-pos))
11764 ((looking-at "\\*[^/]")
11766 col (current-column)))
11767 ((looking-at "/\\*")
11770 col (1+ (current-column))))
11773 col (current-column)))))
11774 ;; Heuristic for whether we need to close the comment:
11775 ;; if we've got a parse error here, assume it's an unterminated
11779 (get-char-property (1- (point)) 'js2-error)
11780 ;; The heuristic above doesn't work well when we're
11781 ;; creating a comment and there's another one downstream,
11782 ;; as our parser thinks this one ends at the end of the
11783 ;; next one. (You can have a /* inside a js block comment.)
11784 ;; So just close it if the next non-ws char isn't a *.
11788 (skip-chars-forward " \t\r\n")
11789 (not (eq (char-after) ?*))))))
11790 (delete-horizontal-space)
11796 (if (and first-line needs-close)
11803 (and (zerop (forward-line 1))
11804 (looking-at "\\s-*//"))))
11807 ;; Don't need to extend the comment after all.
11808 (js2-indent-line)))
11810 (defun js2-beginning-of-line ()
11811 "Toggle point between bol and first non-whitespace char in line.
11812 Also moves past comment delimiters when inside comments."
11817 (back-to-indentation))
11819 (skip-chars-forward "/ \t"))
11820 ((and (eq (char-after) ?*)
11821 (setq node (js2-comment-at-point))
11822 (memq (js2-comment-node-format node) '(jsdoc block))
11824 (skip-chars-backward " \t")
11826 (skip-chars-forward "\* \t"))
11828 (goto-char (point-at-bol))))))
11830 (defun js2-end-of-line ()
11831 "Toggle point between eol and last non-whitespace char in line."
11834 (skip-chars-backward " \t")
11835 (goto-char (point-at-eol))))
11837 (defun js2-mode-wait-for-parse (callback)
11838 "Invoke CALLBACK when parsing is finished.
11839 If parsing is already finished, calls CALLBACK immediately."
11840 (if (not js2-mode-buffer-dirty-p)
11842 (push callback js2-mode-pending-parse-callbacks)
11843 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11845 (defun js2-mode-parse-finished ()
11846 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11847 ;; We can't let errors propagate up, since it prevents the
11848 ;; `js2-parse' method from completing normally and returning
11849 ;; the ast, which makes things mysteriously not work right.
11851 (dolist (cb js2-mode-pending-parse-callbacks)
11852 (condition-case err
11854 (error (message "%s" err))))
11855 (setq js2-mode-pending-parse-callbacks nil)))
11857 (defun js2-mode-flag-region (from to flag)
11858 "Hide or show text from FROM to TO, according to FLAG.
11859 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11860 Returns the created overlay if FLAG is non-nil."
11861 (remove-overlays from to 'invisible 'js2-outline)
11863 (let ((o (make-overlay from to)))
11864 (overlay-put o 'invisible 'js2-outline)
11865 (overlay-put o 'isearch-open-invisible
11866 'js2-isearch-open-invisible)
11869 ;; Function to be set as an outline-isearch-open-invisible' property
11870 ;; to the overlay that makes the outline invisible (see
11871 ;; `js2-mode-flag-region').
11872 (defun js2-isearch-open-invisible (_overlay)
11873 ;; We rely on the fact that isearch places point on the matched text.
11874 (js2-mode-show-element))
11876 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11877 "Return cons cell of bounds of folding overlay at POS.
11878 Returns nil if not found."
11879 (let ((overlays (overlays-at (or pos (point))))
11881 (while (and overlays
11883 (if (overlay-get (car overlays) 'invisible)
11884 (setq o (car overlays))
11885 (setq overlays (cdr overlays))))
11887 (cons (overlay-start o) (overlay-end o)))))
11889 (defun js2-mode-function-at-point (&optional pos)
11890 "Return the innermost function node enclosing current point.
11891 Returns nil if point is not in a function."
11892 (let ((node (js2-node-at-point pos)))
11893 (while (and node (not (js2-function-node-p node)))
11894 (setq node (js2-node-parent node)))
11895 (if (js2-function-node-p node)
11898 (defun js2-mode-toggle-element ()
11899 "Hide or show the foldable element at the point."
11901 (let (comment fn pos)
11904 ;; /* ... */ comment?
11905 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11906 (if (js2-mode-invisible-overlay-bounds
11907 (setq pos (+ 3 (js2-node-abs-pos comment))))
11910 (js2-mode-show-element))
11911 (js2-mode-hide-element)))
11914 (back-to-indentation)
11915 (looking-at js2-mode-//-comment-re))
11916 (js2-mode-toggle-//-comment))
11918 ((setq fn (js2-mode-function-at-point))
11919 (setq pos (and (js2-function-node-body fn)
11920 (js2-node-abs-pos (js2-function-node-body fn))))
11921 (goto-char (1+ pos))
11922 (if (js2-mode-invisible-overlay-bounds)
11923 (js2-mode-show-element)
11924 (js2-mode-hide-element)))
11926 (message "Nothing at point to hide or show"))))))
11928 (defun js2-mode-hide-element ()
11929 "Fold/hide contents of a block, showing ellipses.
11930 Show the hidden text with \\[js2-mode-show-element]."
11932 (if js2-mode-buffer-dirty-p
11933 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11934 (let (node body beg end)
11936 ((js2-mode-invisible-overlay-bounds)
11937 (message "already hidden"))
11939 (setq node (js2-node-at-point))
11941 ((js2-block-comment-p node)
11942 (js2-mode-hide-comment node))
11944 (while (and node (not (js2-function-node-p node)))
11945 (setq node (js2-node-parent node)))
11947 (setq body (js2-function-node-body node)))
11949 (setq beg (js2-node-abs-pos body)
11950 end (+ beg (js2-node-len body)))
11951 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11952 (message "No collapsable element found at point"))))))))
11954 (defun js2-mode-show-element ()
11955 "Show the hidden element at current point."
11957 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11959 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11960 (message "Nothing to un-hide"))))
11962 (defun js2-mode-show-all ()
11963 "Show all of the text in the buffer."
11965 (js2-mode-flag-region (point-min) (point-max) nil))
11967 (defun js2-mode-toggle-hide-functions ()
11969 (if js2-mode-functions-hidden
11970 (js2-mode-show-functions)
11971 (js2-mode-hide-functions)))
11973 (defun js2-mode-hide-functions ()
11974 "Hides all non-nested function bodies in the buffer.
11975 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11976 to open an individual entry."
11978 (if js2-mode-buffer-dirty-p
11979 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11980 (if (null js2-mode-ast)
11981 (message "Oops - parsing failed")
11982 (setq js2-mode-functions-hidden t)
11983 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11985 (defun js2-mode-function-hider (n endp)
11987 (let ((tt (js2-node-type n))
11990 ((and (= tt js2-FUNCTION)
11991 (setq body (js2-function-node-body n)))
11992 (setq beg (js2-node-abs-pos body)
11993 end (+ beg (js2-node-len body)))
11994 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11995 nil) ; don't process children of function
11997 t))))) ; keep processing other AST nodes
11999 (defun js2-mode-show-functions ()
12000 "Un-hide any folded function bodies in the buffer."
12002 (setq js2-mode-functions-hidden nil)
12004 (goto-char (point-min))
12005 (while (/= (goto-char (next-overlay-change (point)))
12007 (dolist (o (overlays-at (point)))
12008 (when (and (overlay-get o 'invisible)
12009 (not (overlay-get o 'comment)))
12010 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12012 (defun js2-mode-hide-comment (n)
12013 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12016 (beg (+ (js2-node-abs-pos n) head))
12017 (end (- (+ beg (js2-node-len n)) head 2))
12018 (o (js2-mode-flag-region beg end 'hide)))
12019 (overlay-put o 'comment t)))
12021 (defun js2-mode-toggle-hide-comments ()
12022 "Folds all block comments in the buffer.
12023 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12024 to open an individual entry."
12026 (if js2-mode-comments-hidden
12027 (js2-mode-show-comments)
12028 (js2-mode-hide-comments)))
12030 (defun js2-mode-hide-comments ()
12032 (if js2-mode-buffer-dirty-p
12033 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12034 (if (null js2-mode-ast)
12035 (message "Oops - parsing failed")
12036 (setq js2-mode-comments-hidden t)
12037 (dolist (n (js2-ast-root-comments js2-mode-ast))
12038 (when (js2-block-comment-p n)
12039 (js2-mode-hide-comment n)))
12040 (js2-mode-hide-//-comments)))
12042 (defun js2-mode-extend-//-comment (direction)
12043 "Find start or end of a block of similar //-comment lines.
12044 DIRECTION is -1 to look back, 1 to look forward.
12045 INDENT is the indentation level to match.
12046 Returns the end-of-line position of the furthest adjacent
12047 //-comment line with the same indentation as the current line.
12048 If there is no such matching line, returns current end of line."
12049 (let ((pos (point-at-eol))
12050 (indent (current-indentation)))
12052 (while (and (zerop (forward-line direction))
12053 (looking-at js2-mode-//-comment-re)
12054 (eq indent (length (match-string 1))))
12055 (setq pos (point-at-eol)))
12058 (defun js2-mode-hide-//-comments ()
12059 "Fold adjacent 1-line comments, showing only snippet of first one."
12062 (goto-char (point-min))
12063 (while (re-search-forward js2-mode-//-comment-re nil t)
12065 end (js2-mode-extend-//-comment 1))
12066 (unless (eq beg end)
12067 (overlay-put (js2-mode-flag-region beg end 'hide)
12070 (forward-char 1)))))
12072 (defun js2-mode-toggle-//-comment ()
12073 "Fold or un-fold any multi-line //-comment at point.
12074 Caller should have determined that this line starts with a //-comment."
12075 (let* ((beg (point-at-eol))
12079 (if (js2-mode-invisible-overlay-bounds)
12080 (js2-mode-show-element)
12081 ;; else hide the comment
12082 (setq beg (js2-mode-extend-//-comment -1)
12083 end (js2-mode-extend-//-comment 1))
12084 (unless (eq beg end)
12085 (overlay-put (js2-mode-flag-region beg end 'hide)
12088 (defun js2-mode-show-comments ()
12089 "Un-hide any hidden comments, leaving other hidden elements alone."
12091 (setq js2-mode-comments-hidden nil)
12093 (goto-char (point-min))
12094 (while (/= (goto-char (next-overlay-change (point)))
12096 (dolist (o (overlays-at (point)))
12097 (when (overlay-get o 'comment)
12098 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12100 (defun js2-mode-display-warnings-and-errors ()
12101 "Turn on display of warnings and errors."
12103 (setq js2-mode-show-parse-errors t
12104 js2-mode-show-strict-warnings t)
12105 (js2-reparse 'force))
12107 (defun js2-mode-hide-warnings-and-errors ()
12108 "Turn off display of warnings and errors."
12110 (setq js2-mode-show-parse-errors nil
12111 js2-mode-show-strict-warnings nil)
12112 (js2-reparse 'force))
12114 (defun js2-mode-toggle-warnings-and-errors ()
12115 "Toggle the display of warnings and errors.
12116 Some users don't like having warnings/errors reported while they type."
12118 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12119 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12120 (if (called-interactively-p 'any)
12121 (message "warnings and errors %s"
12122 (if js2-mode-show-parse-errors
12125 (js2-reparse 'force))
12127 (defun js2-mode-customize ()
12129 (customize-group 'js2-mode))
12131 (defun js2-mode-forward-sexp (&optional arg)
12132 "Move forward across one statement or balanced expression.
12133 With ARG, do it that many times. Negative arg -N means
12134 move backward across N balanced expressions."
12136 (setq arg (or arg 1))
12138 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12140 (let (forward-sexp-function
12141 node (start (point)) pos lp rp child)
12144 ;; could probably make this better for some cases:
12145 ;; - if in statement block (e.g. function body), go to parent
12146 ;; - infix exprs like (foo in bar) - maybe go to beginning
12147 ;; of infix expr if in the right-side expression?
12148 ((and arg (cl-minusp arg))
12149 (dotimes (_ (- arg))
12151 (forward-char -1) ; Enter the node we backed up to.
12152 (when (setq node (js2-node-at-point (point) t))
12153 (setq pos (js2-node-abs-pos node))
12154 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12155 (setq lp (car parens)
12157 (when (and lp (> start lp))
12158 (if (and rp (<= start rp))
12159 ;; Between parens, check if there's a child node we can jump.
12160 (when (setq child (js2-node-closest-child node (point) lp t))
12161 (setq pos (js2-node-abs-pos child)))
12162 ;; Before both parens.
12164 (let ((state (parse-partial-sexp start pos)))
12165 (goto-char (if (not (zerop (car state)))
12166 ;; Stumble at the unbalanced paren if < 0, or
12167 ;; jump a bit further if > 0.
12168 (scan-sexps start -1)
12170 (unless pos (goto-char (point-min)))))
12175 (when (setq node (js2-node-at-point (point) t))
12176 (setq pos (js2-node-abs-pos node))
12177 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12178 (setq lp (car parens)
12181 (when (and rp (<= start rp))
12183 (when (setq child (js2-node-closest-child node (point) rp))
12184 (setq pos (js2-node-abs-end child)))
12185 (setq pos (1+ rp))))
12186 ;; No parens or child nodes, looks for the end of the current node.
12187 (cl-incf pos (js2-node-len
12188 (if (js2-expr-stmt-node-p (js2-node-parent node))
12189 ;; Stop after the semicolon.
12190 (js2-node-parent node)
12192 (let ((state (save-excursion (parse-partial-sexp start pos))))
12193 (goto-char (if (not (zerop (car state)))
12194 (scan-sexps start 1)
12196 (unless pos (goto-char (point-max)))))))))
12198 (defun js2-mode-forward-sexp-parens (node abs-pos)
12199 "Return a cons cell with positions of main parens in NODE."
12201 ((or (js2-array-node-p node)
12202 (js2-object-node-p node)
12203 (js2-comp-node-p node)
12204 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12205 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12206 ((js2-paren-expr-node-p node)
12207 (let ((lp (js2-node-lp node))
12208 (rp (js2-node-rp node)))
12209 (cons (when lp (+ abs-pos lp))
12210 (when rp (+ abs-pos rp)))))))
12212 (defun js2-node-closest-child (parent point limit &optional before)
12213 (let* ((parent-pos (js2-node-abs-pos parent))
12214 (rpoint (- point parent-pos))
12215 (rlimit (- limit parent-pos))
12216 (min (min rpoint rlimit))
12217 (max (max rpoint rlimit))
12222 (lambda (node _end-p)
12223 (if (eq node parent)
12225 (let ((pos (js2-node-pos node)) ;; Both relative values.
12226 (end (+ (js2-node-pos node) (js2-node-len node))))
12227 (when (and (>= pos min) (<= end max)
12228 (if before (< pos rpoint) (> end rpoint)))
12230 (when (> end rpoint)
12231 (throw 'done nil)))
12235 (defun js2-errors ()
12236 "Return a list of errors found."
12238 (js2-ast-root-errors js2-mode-ast)))
12240 (defun js2-warnings ()
12241 "Return a list of warnings found."
12243 (js2-ast-root-warnings js2-mode-ast)))
12245 (defun js2-have-errors-p ()
12246 "Return non-nil if any parse errors or warnings were found."
12247 (or (js2-errors) (js2-warnings)))
12249 (defun js2-errors-and-warnings ()
12250 "Return a copy of the concatenated errors and warnings lists.
12251 They are appended: first the errors, then the warnings.
12252 Entries are of the form (MSG BEG END)."
12254 (append (js2-ast-root-errors js2-mode-ast)
12255 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12257 (defun js2-next-error (&optional arg reset)
12258 "Move to next parse error.
12259 Typically invoked via \\[next-error].
12260 ARG is the number of errors, forward or backward, to move.
12261 RESET means start over from the beginning."
12263 (if (not (or (js2-errors) (js2-warnings)))
12264 (message "No errors")
12266 (goto-char (point-min)))
12267 (let* ((errs (js2-errors-and-warnings))
12271 (backward (cl-minusp count))
12272 (sorter (if backward '> '<))
12273 (stopper (if backward '< '>))
12274 (count (abs count))
12276 ;; Sort by start position.
12277 (setq errs (sort errs (lambda (e1 e2)
12278 (funcall sorter (cl-second e1) (cl-second e2))))
12280 ;; Find nth error with pos > start.
12281 (while (and errs continue)
12282 (when (funcall stopper (cl-cadar errs) start)
12283 (setq err (car errs))
12284 (if (zerop (cl-decf count))
12285 (setq continue nil)))
12286 (setq errs (cdr errs)))
12287 ;; Clear for `js2-echo-error'.
12290 (goto-char (cl-second err))
12291 ;; Wrap around to first error.
12292 (goto-char (cl-second (car all-errs)))
12293 ;; If we were already on it, echo msg again.
12294 (if (= (point) start)
12295 (js2-echo-error (point) (point)))))))
12297 (defun js2-down-mouse-3 ()
12298 "Make right-click move the point to the click location.
12299 This makes right-click context menu operations a bit more intuitive.
12300 The point will not move if the region is active, however, to avoid
12301 destroying the region selection."
12303 (when (and js2-move-point-on-right-click
12305 (let ((e last-input-event))
12307 (goto-char (cl-cadadr e))))))
12309 (defun js2-mode-create-imenu-index ()
12310 "Return an alist for `imenu--index-alist'."
12311 ;; This is built up in `js2-parse-record-imenu' during parsing.
12313 ;; if we have an ast but no recorder, they're requesting a rescan
12314 (unless js2-imenu-recorder
12315 (js2-reparse 'force))
12317 (js2-build-imenu-index)
12318 (setq js2-imenu-recorder nil
12319 js2-imenu-function-map nil))))
12321 (defun js2-mode-find-tag ()
12322 "Replacement for `find-tag-default'.
12323 `find-tag-default' returns a ridiculous answer inside comments."
12326 (if (looking-at "\\_>")
12327 (setq beg (progn (forward-symbol -1) (point))
12328 end (progn (forward-symbol 1) (point)))
12329 (setq beg (progn (forward-symbol 1) (point))
12330 end (progn (forward-symbol -1) (point))))
12331 (replace-regexp-in-string
12333 (buffer-substring-no-properties beg end)))))
12335 (defun js2-mode-forward-sibling ()
12336 "Move to the end of the sibling following point in parent.
12337 Returns non-nil if successful, or nil if there was no following sibling."
12338 (let* ((node (js2-node-at-point))
12339 (parent (js2-mode-find-enclosing-fn node))
12341 (when (setq sib (js2-node-find-child-after (point) parent))
12342 (goto-char (+ (js2-node-abs-pos sib)
12343 (js2-node-len sib))))))
12345 (defun js2-mode-backward-sibling ()
12346 "Move to the beginning of the sibling node preceding point in parent.
12347 Parent is defined as the enclosing script or function."
12348 (let* ((node (js2-node-at-point))
12349 (parent (js2-mode-find-enclosing-fn node))
12351 (when (setq sib (js2-node-find-child-before (point) parent))
12352 (goto-char (js2-node-abs-pos sib)))))
12354 (defun js2-beginning-of-defun (&optional arg)
12355 "Go to line on which current function starts, and return t on success.
12356 If we're not in a function or already at the beginning of one, go
12357 to beginning of previous script-level element.
12358 With ARG N, do that N times. If N is negative, move forward."
12359 (setq arg (or arg 1))
12361 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12363 ((js2-function-node-p parent)
12364 (goto-char (js2-node-abs-pos parent)))
12366 (js2-mode-backward-sibling)))
12368 (js2-beginning-of-defun (1- arg))
12370 (when (js2-end-of-defun)
12371 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12373 (defun js2-end-of-defun ()
12374 "Go to the char after the last position of the current function
12375 or script-level element."
12376 (let* ((node (js2-node-at-point))
12377 (parent (or (and (js2-function-node-p node) node)
12378 (js2-node-parent-script-or-fn node)))
12380 (unless (js2-function-node-p parent)
12381 ;; Use current script-level node, or, if none, the next one.
12382 (setq script (or parent node)
12383 parent (js2-node-find-child-before (point) script))
12384 (when (or (null parent)
12385 (>= (point) (+ (js2-node-abs-pos parent)
12386 (js2-node-len parent))))
12387 (setq parent (js2-node-find-child-after (point) script))))
12389 (goto-char (+ (js2-node-abs-pos parent)
12390 (js2-node-len parent))))))
12392 (defun js2-mark-defun (&optional allow-extend)
12393 "Put mark at end of this function, point at beginning.
12394 The function marked is the one that contains point.
12396 Interactively, if this command is repeated,
12397 or (in Transient Mark mode) if the mark is active,
12398 it marks the next defun after the ones already marked."
12401 (when (and allow-extend
12402 (or (and (eq last-command this-command) (mark t))
12403 (and transient-mark-mode mark-active)))
12404 (let ((sib (save-excursion
12406 (if (js2-mode-forward-sibling)
12412 ;; no more siblings - try extending to enclosing node
12413 (goto-char (mark t)))))
12414 (when (not extended)
12415 (let ((node (js2-node-at-point (point) t)) ; skip comments
12416 ast fn stmt parent beg end)
12417 (when (js2-ast-root-p node)
12419 node (or (js2-node-find-child-after (point) node)
12420 (js2-node-find-child-before (point) node))))
12421 ;; only mark whole buffer if we can't find any children
12424 (if (js2-function-node-p node)
12426 (setq fn (js2-mode-find-enclosing-fn node)
12427 stmt (if (or (null fn)
12428 (js2-ast-root-p fn))
12429 (js2-mode-find-first-stmt node))
12430 parent (or stmt fn)))
12431 (setq beg (js2-node-abs-pos parent)
12432 end (+ beg (js2-node-len parent)))
12435 (exchange-point-and-mark)))))
12437 (defun js2-narrow-to-defun ()
12438 "Narrow to the function enclosing point."
12440 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12441 (fn (if (js2-script-node-p node)
12443 (js2-mode-find-enclosing-fn node)))
12444 (beg (js2-node-abs-pos fn)))
12445 (unless (js2-ast-root-p fn)
12446 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12448 (defun js2-jump-to-definition (&optional arg)
12449 "Jump to the definition of an object's property, variable or function."
12451 (ring-insert find-tag-marker-ring (point-marker))
12452 (let* ((node (js2-node-at-point))
12453 (parent (js2-node-parent node))
12454 (names (if (js2-prop-get-node-p parent)
12455 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12456 (cl-loop for n in temp
12459 until (equal node n)
12460 finally return result)))))
12462 (unless (and (js2-name-node-p node)
12463 (not (js2-var-init-node-p parent))
12464 (not (js2-function-node-p parent)))
12465 (error "Node is not a supported jump node"))
12466 (push (or (and names (pop names))
12467 (unless (and (js2-object-prop-node-p parent)
12468 (eq node (js2-object-prop-node-left parent)))
12470 (setq node-init (js2-search-scope node names))
12472 ;; todo: display list of results in buffer
12473 ;; todo: group found references by buffer
12479 (with-current-buffer b
12480 (when (derived-mode-p 'js2-mode)
12481 (setq node-init (js2-search-scope js2-mode-ast names))
12483 (throw 'found b)))))
12486 (setq node-init (if (listp node-init) (car node-init) node-init))
12489 (error "No jump location found"))
12490 (goto-char (js2-node-abs-pos node-init))))
12492 (defun js2-search-object (node name-node)
12493 "Check if object NODE contains element with NAME-NODE."
12494 (cl-assert (js2-object-node-p node))
12495 ;; Only support name-node and nodes for the time being
12496 (cl-loop for elem in (js2-object-node-elems node)
12497 for left = (js2-object-prop-node-left elem)
12498 if (or (and (js2-name-node-p left)
12499 (equal (js2-name-node-name name-node)
12500 (js2-name-node-name left)))
12501 (and (js2-string-node-p left)
12502 (string= (js2-name-node-name name-node)
12503 (js2-string-node-value left))))
12506 (defun js2-search-object-for-prop (object prop-names)
12507 "Return node in OBJECT that matches PROP-NAMES or nil.
12508 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12509 i.e. ('name' 'value') = {name : { value: 3}}"
12511 (temp-object object)
12512 (temp t) ;temporay node
12513 (names prop-names))
12514 (while (and temp names (js2-object-node-p temp-object))
12515 (setq temp (js2-search-object temp-object (pop names)))
12516 (and (setq node temp)
12517 (setq temp-object (js2-object-prop-node-right temp))))
12518 (unless names node)))
12520 (defun js2-search-scope (node names)
12521 "Searches NODE scope for jump location matching NAMES.
12522 NAMES is a list of property values to search for. For functions
12523 and variables NAMES will contain one element."
12525 (val (js2-name-node-name (car names))))
12526 (setq node-init (js2-get-symbol-declaration node val))
12528 (when (> (length names) 1)
12530 ;; Check var declarations
12531 (when (and node-init (string= val (js2-name-node-name node-init)))
12532 (let ((parent (js2-node-parent node-init))
12533 (temp-names names))
12534 (pop temp-names) ;; First element is var name
12535 (setq node-init (when (js2-var-init-node-p parent)
12536 (js2-search-object-for-prop
12537 (js2-var-init-node-initializer parent)
12540 ;; Check all assign nodes
12543 (lambda (node endp)
12545 (if (js2-assign-node-p node)
12546 (let ((left (js2-assign-node-left node))
12547 (right (js2-assign-node-right node))
12548 (temp-names names))
12549 (when (js2-prop-get-node-p left)
12550 (let* ((prop-list (js2-compute-nested-prop-get left))
12551 (found (cl-loop for prop in prop-list
12552 until (not (string= (js2-name-node-name
12554 (js2-name-node-name prop)))
12555 if (not temp-names) return prop))
12556 (found-node (or found
12557 (when (js2-object-node-p right)
12558 (js2-search-object-for-prop right
12560 (if found-node (push found-node node-init))))))
12564 (defun js2-get-symbol-declaration (node name)
12565 "Find scope for NAME from NODE."
12566 (let ((scope (js2-get-defining-scope
12567 (or (js2-node-get-enclosing-scope node)
12569 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12571 (provide 'js2-mode)
12573 ;;; js2-mode.el ends here