]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Adapt async/await changes to latest master
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
4
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/
10 ;; Version: 20150909
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
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.
20
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.
25
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/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
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
41 ;; - code folding:
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
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
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:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; Support for JSX is available via the derived mode `js2-jsx-mode'. If you
64 ;; also want JSX support, use that mode instead:
65
66 ;; (add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
67 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-jsx-mode))
68
69 ;; To customize how it works:
70 ;; M-x customize-group RET js2-mode RET
71
72 ;; Notes:
73
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.
77
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.
82
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.
87
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
90 ;; unmaintained.
91
92 ;;; Code:
93
94 (require 'cl-lib)
95 (require 'imenu)
96 (require 'js)
97 (require 'etags)
98
99 (eval-and-compile
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)))
107
108 ;;; Externs (variables presumed to be defined by the host system)
109
110 (defvar js2-ecma-262-externs
111 (mapcar 'symbol-name
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.")
119
120 (defvar js2-browser-externs
121 (mapcar 'symbol-name
122 '(;; DOM level 1
123 Attr CDATASection CharacterData Comment DOMException
124 DOMImplementation Document DocumentFragment
125 DocumentType Element Entity EntityReference
126 ExceptionCode NamedNodeMap Node NodeList Notation
127 ProcessingInstruction Text
128
129 ;; DOM level 2
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
151
152 ;; DOM level 3
153 DOMConfiguration DOMError DOMException
154 DOMImplementationList DOMImplementationSource
155 DOMLocator DOMStringList NameList TypeInfo
156 UserDataHandler
157
158 ;; Window
159 window alert confirm document java navigator prompt screen
160 self top requestAnimationFrame cancelAnimationFrame
161
162 ;; W3C CSS
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
171
172 ;; W3C Event
173 EventListener EventTarget Event DocumentEvent UIEvent
174 MouseEvent MutationEvent KeyboardEvent
175
176 ;; W3C Range
177 DocumentRange Range RangeException
178
179 ;; W3C XML
180 XPathResult XMLHttpRequest
181
182 ;; console object. Provided by at least Chrome and Firefox.
183 console))
184 "Browser externs.
185 You can cause these to be included or excluded with the custom
186 variable `js2-include-browser-externs'.")
187
188 (defvar js2-rhino-externs
189 (mapcar 'symbol-name
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.")
197
198 (defvar js2-node-externs
199 (mapcar 'symbol-name
200 '(__dirname __filename Buffer clearInterval clearTimeout require
201 console exports global module process setInterval setTimeout
202 querystring))
203 "Node.js externs.
204 Set `js2-include-node-externs' to t to include them.")
205
206 (defvar js2-typed-array-externs
207 (mapcar 'symbol-name
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.")
214
215 (defvar js2-harmony-externs
216 (mapcar 'symbol-name
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.")
220
221 ;;; Variables
222
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))
228
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."
235 :group 'js2-mode
236 :type '(choice (const :tag "None" 0)
237 (const :tag "Basic" 1)
238 (const :tag "Include Properties" 2)
239 (const :tag "Include Functions" 3)))
240
241 (defvar js2-mode-dev-mode-p nil
242 "Non-nil if running in development mode. Normally nil.")
243
244 (defgroup js2-mode nil
245 "An improved JavaScript mode."
246 :group 'languages)
247
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."
251 :type 'number
252 :group 'js2-mode)
253 (make-variable-buffer-local 'js2-idle-timer-delay)
254
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."
265 :type 'number
266 :group 'js2-mode)
267
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))
273 :group 'js2-mode)
274
275 (defcustom js2-mode-show-parse-errors t
276 "True to highlight parse errors."
277 :type 'boolean
278 :group 'js2-mode)
279
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."
284 :type 'boolean
285 :group 'js2-mode)
286
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."
290 :type 'boolean
291 :group 'js2-mode)
292
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
296 depending on it."
297 :type 'boolean
298 :group 'js2-mode)
299
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."
306 :type 'boolean
307 :group 'js2-mode)
308
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.)"
314 :type 'boolean
315 :group 'js2-mode)
316
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)) ..."
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-strict-var-redeclaration-warning t
326 "Non-nil to warn about redeclaring variables in a script or function."
327 :type 'boolean
328 :group 'js2-mode)
329
330 (defcustom js2-strict-var-hides-function-arg-warning t
331 "Non-nil to warn about a var decl hiding a function argument."
332 :type 'boolean
333 :group 'js2-mode)
334
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."
338 :type 'boolean
339 :group 'js2-mode)
340
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."
347 :type 'integer
348 :group 'js2-mode)
349
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."
353 :type 'boolean
354 :group 'js2-mode)
355
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.
362
363 Note that IntelliJ moves the point, and Eclipse leaves it alone,
364 so this behavior is customizable."
365 :group 'js2-mode
366 :type 'boolean)
367
368 (defcustom js2-allow-rhino-new-expr-initializer t
369 "Non-nil to support a Rhino's experimental syntactic construct.
370
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:
374
375 new <expr> [ ( arglist ) ] [initializer]
376
377 Hence, this expression:
378
379 new Object {a: 1, b: 2}
380
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."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-allow-member-expr-as-function-name nil
388 "Non-nil to support experimental Rhino syntax for function names.
389
390 Rhino supports an experimental syntax configured via the Rhino Context
391 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
392
393 function <member-expr> ( [ arg-list ] ) { <body> }
394
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.
398
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,
401 this code:
402
403 function a.b().c[2] (x, y) { ... }
404
405 is rewritten as:
406
407 a.b().c[2] = function(x, y) {...}
408
409 which doesn't seem particularly useful, but Rhino permits it."
410 :type 'boolean
411 :group 'js2-mode)
412
413 ;; scanner variables
414
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))
418 `(progn
419 (defvar ,name ,value ,comment)
420 (make-variable-buffer-local ',name)))
421
422 (defvar js2-EOF_CHAR -1
423 "Represents end of stream. Distinct from js2-EOF token type.")
424
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)
429 (defvar js2-EOF 0)
430 (defvar js2-EOL 1)
431 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
432 (defvar js2-LEAVEWITH 3)
433 (defvar js2-RETURN 4)
434 (defvar js2-GOTO 5)
435 (defvar js2-IFEQ 6)
436 (defvar js2-IFNE 7)
437 (defvar js2-SETNAME 8)
438 (defvar js2-BITOR 9)
439 (defvar js2-BITXOR 10)
440 (defvar js2-BITAND 11)
441 (defvar js2-EQ 12)
442 (defvar js2-NE 13)
443 (defvar js2-LT 14)
444 (defvar js2-LE 15)
445 (defvar js2-GT 16)
446 (defvar js2-GE 17)
447 (defvar js2-LSH 18)
448 (defvar js2-RSH 19)
449 (defvar js2-URSH 20)
450 (defvar js2-ADD 21) ; infix plus
451 (defvar js2-SUB 22) ; infix minus
452 (defvar js2-MUL 23)
453 (defvar js2-DIV 24)
454 (defvar js2-MOD 25)
455 (defvar js2-NOT 26)
456 (defvar js2-BITNOT 27)
457 (defvar js2-POS 28) ; unary plus
458 (defvar js2-NEG 29) ; unary minus
459 (defvar js2-NEW 30)
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)
467 (defvar js2-CALL 38)
468 (defvar js2-NAME 39) ; an identifier
469 (defvar js2-NUMBER 40)
470 (defvar js2-STRING 41)
471 (defvar js2-NULL 42)
472 (defvar js2-THIS 43)
473 (defvar js2-FALSE 44)
474 (defvar js2-TRUE 45)
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
481 (defvar js2-IN 52)
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
502
503 ;; XML support
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.
511
512 (defvar js2-first-bytecode js2-ENTERWITH)
513 (defvar js2-last-bytecode js2-REF_NS_NAME)
514
515 (defvar js2-TRY 80)
516 (defvar js2-SEMI 81) ; semicolon
517 (defvar js2-LB 82) ; left and right brackets
518 (defvar js2-RB 83)
519 (defvar js2-LC 84) ; left and right curly-braces
520 (defvar js2-RC 85)
521 (defvar js2-LP 86) ; left and right parens
522 (defvar js2-RP 87)
523 (defvar js2-COMMA 88) ; comma operator
524
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) ; %=
537
538 (defvar js2-first-assign js2-ASSIGN)
539 (defvar js2-last-assign js2-ASSIGN_MOD)
540
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 (++ --)
546 (defvar js2-DEC 106)
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
567
568 (defvar js2-EMPTY 127)
569
570 ;; Types used for the parse tree - never returned by scanner.
571
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
578 (defvar js2-JSR 134)
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
586
587 ;; For XML support:
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)
594
595 ;; Optimizer-only tokens
596 (defvar js2-TO_OBJECT 148)
597 (defvar js2-TO_DOUBLE 149)
598
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)
609
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
619
620 (defvar js2-AWAIT 169) ; await (pseudo keyword)
621
622 (defconst js2-num-tokens (1+ js2-AWAIT))
623
624 (defconst js2-debug-print-trees nil)
625
626 ;; Rhino accepts any string or stream as input. Emacs character
627 ;; processing works best in buffers, so we'll assume the input is a
628 ;; buffer. JavaScript strings can be copied into temp buffers before
629 ;; scanning them.
630
631 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
632 ;; They're the Emacs equivalent of instance variables, more or less.
633
634 (js2-deflocal js2-ts-dirty-line nil
635 "Token stream buffer-local variable.
636 Indicates stuff other than whitespace since start of line.")
637
638 (js2-deflocal js2-ts-hit-eof nil
639 "Token stream buffer-local variable.")
640
641 ;; FIXME: Unused.
642 (js2-deflocal js2-ts-line-start 0
643 "Token stream buffer-local variable.")
644
645 (js2-deflocal js2-ts-lineno 1
646 "Token stream buffer-local variable.")
647
648 ;; FIXME: Unused.
649 (js2-deflocal js2-ts-line-end-char -1
650 "Token stream buffer-local variable.")
651
652 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
653 "Token stream buffer-local variable.
654 Current scan position.")
655
656 ;; FIXME: Unused.
657 (js2-deflocal js2-ts-is-xml-attribute nil
658 "Token stream buffer-local variable.")
659
660 (js2-deflocal js2-ts-xml-is-tag-content nil
661 "Token stream buffer-local variable.")
662
663 (js2-deflocal js2-ts-xml-open-tags-count 0
664 "Token stream buffer-local variable.")
665
666 (js2-deflocal js2-ts-string-buffer nil
667 "Token stream buffer-local variable.
668 List of chars built up while scanning various tokens.")
669
670 (cl-defstruct (js2-token
671 (:constructor nil)
672 (:constructor make-js2-token (beg)))
673 "Value returned from the token stream."
674 (type js2-EOF)
675 (beg 1)
676 (end -1)
677 (string "")
678 number
679 number-base
680 regexp-flags
681 comment-type
682 follows-eol-p)
683
684 ;; Have to call `js2-init-scanner' to initialize the values.
685 (js2-deflocal js2-ti-tokens nil)
686 (js2-deflocal js2-ti-tokens-cursor nil)
687 (js2-deflocal js2-ti-lookahead nil)
688
689 (cl-defstruct (js2-ts-state
690 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
691 (cursor js2-ts-cursor)
692 (tokens (copy-sequence js2-ti-tokens))
693 (tokens-cursor js2-ti-tokens-cursor)
694 (lookahead js2-ti-lookahead))))
695 lineno
696 cursor
697 tokens
698 tokens-cursor
699 lookahead)
700
701 ;;; Parser variables
702
703 (js2-deflocal js2-parsed-errors nil
704 "List of errors produced during scanning/parsing.")
705
706 (js2-deflocal js2-parsed-warnings nil
707 "List of warnings produced during scanning/parsing.")
708
709 (js2-deflocal js2-recover-from-parse-errors t
710 "Non-nil to continue parsing after a syntax error.
711
712 In recovery mode, the AST will be built in full, and any error
713 nodes will be flagged with appropriate error information. If
714 this flag is nil, a syntax error will result in an error being
715 signaled.
716
717 The variable is automatically buffer-local, because different
718 modes that use the parser will need different settings.")
719
720 (js2-deflocal js2-parse-hook nil
721 "List of callbacks for receiving parsing progress.")
722
723 (defvar js2-parse-finished-hook nil
724 "List of callbacks to notify when parsing finishes.
725 Not called if parsing was interrupted.")
726
727 (js2-deflocal js2-is-eval-code nil
728 "True if we're evaluating code in a string.
729 If non-nil, the tokenizer will record the token text, and the AST nodes
730 will record their source text. Off by default for IDE modes, since the
731 text is available in the buffer.")
732
733 (defvar js2-parse-ide-mode t
734 "Non-nil if the parser is being used for `js2-mode'.
735 If non-nil, the parser will set text properties for fontification
736 and the syntax table. The value should be nil when using the
737 parser as a frontend to an interpreter or byte compiler.")
738
739 ;;; Parser instance variables (buffer-local vars for js2-parse)
740
741 (defconst js2-ti-after-eol (lsh 1 16)
742 "Flag: first token of the source line.")
743
744 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
745
746 (js2-deflocal js2-compiler-generate-debug-info t)
747 (js2-deflocal js2-compiler-use-dynamic-scope nil)
748 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
749 (js2-deflocal js2-compiler-xml-available t)
750 (js2-deflocal js2-compiler-optimization-level 0)
751 (js2-deflocal js2-compiler-generating-source t)
752 (js2-deflocal js2-compiler-strict-mode nil)
753 (js2-deflocal js2-compiler-report-warning-as-error nil)
754 (js2-deflocal js2-compiler-generate-observer-count nil)
755 (js2-deflocal js2-compiler-activation-names nil)
756
757 ;; SKIP: sourceURI
758
759 ;; There's a compileFunction method in Context.java - may need it.
760 (js2-deflocal js2-called-by-compile-function nil
761 "True if `js2-parse' was called by `js2-compile-function'.
762 Will only be used when we finish implementing the interpreter.")
763
764 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
765
766 ;; SKIP: node factory - we're going to just call functions directly,
767 ;; and eventually go to a unified AST format.
768
769 (js2-deflocal js2-nesting-of-function 0)
770
771 (js2-deflocal js2-recorded-identifiers nil
772 "Tracks identifiers found during parsing.")
773
774 (js2-deflocal js2-is-in-destructuring nil
775 "True while parsing destructuring expression.")
776
777 (js2-deflocal js2-in-use-strict-directive nil
778 "True while inside a script or function under strict mode.")
779
780 (defcustom js2-global-externs nil
781 "A list of any extern names you'd like to consider always declared.
782 This list is global and is used by all `js2-mode' files.
783 You can create buffer-local externs list using `js2-additional-externs'.
784
785 There is also a buffer-local variable `js2-default-externs',
786 which is initialized by default to include the Ecma-262 externs
787 and the standard browser externs. The three lists are all
788 checked during highlighting."
789 :type 'list
790 :group 'js2-mode)
791
792 (js2-deflocal js2-default-externs nil
793 "Default external declarations.
794
795 These are currently only used for highlighting undeclared variables,
796 which only worries about top-level (unqualified) references.
797 As js2-mode's processing improves, we will flesh out this list.
798
799 The initial value is set to `js2-ecma-262-externs', unless some
800 of the `js2-include-?-externs' variables are set to t, in which
801 case the browser, Rhino and/or Node.js externs are also included.
802
803 See `js2-additional-externs' for more information.")
804
805 (defcustom js2-include-browser-externs t
806 "Non-nil to include browser externs in the master externs list.
807 If you work on JavaScript files that are not intended for browsers,
808 such as Mozilla Rhino server-side JavaScript, set this to nil.
809 See `js2-additional-externs' for more information about externs."
810 :type 'boolean
811 :group 'js2-mode)
812
813 (defcustom js2-include-rhino-externs nil
814 "Non-nil to include Mozilla Rhino externs in the master externs list.
815 See `js2-additional-externs' for more information about externs."
816 :type 'boolean
817 :group 'js2-mode)
818
819 (defcustom js2-include-node-externs nil
820 "Non-nil to include Node.js externs in the master externs list.
821 See `js2-additional-externs' for more information about externs."
822 :type 'boolean
823 :group 'js2-mode)
824
825 (js2-deflocal js2-additional-externs nil
826 "A buffer-local list of additional external declarations.
827 It is used to decide whether variables are considered undeclared
828 for purposes of highlighting.
829
830 Each entry is a Lisp string. The string should be the fully qualified
831 name of an external entity. All externs should be added to this list,
832 so that as js2-mode's processing improves it can take advantage of them.
833
834 You may want to declare your externs in three ways.
835 First, you can add externs that are valid for all your JavaScript files.
836 You should probably do this by adding them to `js2-global-externs', which
837 is a global list used for all js2-mode files.
838
839 Next, you can add a function to `js2-init-hook' that adds additional
840 externs appropriate for the specific file, perhaps based on its path.
841 These should go in `js2-additional-externs', which is buffer-local.
842
843 Third, you can use JSLint's global declaration, as long as
844 `js2-include-jslint-globals' is non-nil, which see.
845
846 Finally, you can add a function to `js2-post-parse-callbacks',
847 which is called after parsing completes, and `js2-mode-ast' is bound to
848 the root of the parse tree. At this stage you can set up an AST
849 node visitor using `js2-visit-ast' and examine the parse tree
850 for specific import patterns that may imply the existence of
851 other externs, possibly tied to your build system. These should also
852 be added to `js2-additional-externs'.
853
854 Your post-parse callback may of course also use the simpler and
855 faster (but perhaps less robust) approach of simply scanning the
856 buffer text for your imports, using regular expressions.")
857
858 ;; SKIP: decompiler
859 ;; SKIP: encoded-source
860
861 ;;; The following variables are per-function and should be saved/restored
862 ;;; during function parsing...
863
864 (js2-deflocal js2-current-script-or-fn nil)
865 (js2-deflocal js2-current-scope nil)
866 (js2-deflocal js2-nesting-of-with 0)
867 (js2-deflocal js2-label-set nil
868 "An alist mapping label names to nodes.")
869
870 (js2-deflocal js2-loop-set nil)
871 (js2-deflocal js2-loop-and-switch-set nil)
872 (js2-deflocal js2-has-return-value nil)
873 (js2-deflocal js2-end-flags 0)
874
875 ;;; ...end of per function variables
876
877 ;; These flags enumerate the possible ways a statement/function can
878 ;; terminate. These flags are used by endCheck() and by the Parser to
879 ;; detect inconsistent return usage.
880 ;;
881 ;; END_UNREACHED is reserved for code paths that are assumed to always be
882 ;; able to execute (example: throw, continue)
883 ;;
884 ;; END_DROPS_OFF indicates if the statement can transfer control to the
885 ;; next one. Statement such as return dont. A compound statement may have
886 ;; some branch that drops off control to the next statement.
887 ;;
888 ;; END_RETURNS indicates that the statement can return (without arguments)
889 ;; END_RETURNS_VALUE indicates that the statement can return a value.
890 ;;
891 ;; A compound statement such as
892 ;; if (condition) {
893 ;; return value;
894 ;; }
895 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
896
897 (defconst js2-end-unreached #x0)
898 (defconst js2-end-drops-off #x1)
899 (defconst js2-end-returns #x2)
900 (defconst js2-end-returns-value #x4)
901
902 ;; Rhino awkwardly passes a statementLabel parameter to the
903 ;; statementHelper() function, the main statement parser, which
904 ;; is then used by quite a few of the sub-parsers. We just make
905 ;; it a buffer-local variable and make sure it's cleaned up properly.
906 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
907
908 ;; Similarly, Rhino passes an inForInit boolean through about half
909 ;; the expression parsers. We use a dynamically-scoped variable,
910 ;; which makes it easier to funcall the parsers individually without
911 ;; worrying about whether they take the parameter or not.
912 (js2-deflocal js2-in-for-init nil)
913 (js2-deflocal js2-temp-name-counter 0)
914 (js2-deflocal js2-parse-stmt-count 0)
915
916 (defsubst js2-get-next-temp-name ()
917 (format "$%d" (cl-incf js2-temp-name-counter)))
918
919 (defvar js2-parse-interruptable-p t
920 "Set this to nil to force parse to continue until finished.
921 This will mostly be useful for interpreters.")
922
923 (defvar js2-statements-per-pause 50
924 "Pause after this many statements to check for user input.
925 If user input is pending, stop the parse and discard the tree.
926 This makes for a smoother user experience for large files.
927 You may have to wait a second or two before the highlighting
928 and error-reporting appear, but you can always type ahead if
929 you wish. This appears to be more or less how Eclipse, IntelliJ
930 and other editors work.")
931
932 (js2-deflocal js2-record-comments t
933 "Instructs the scanner to record comments in `js2-scanned-comments'.")
934
935 (js2-deflocal js2-scanned-comments nil
936 "List of all comments from the current parse.")
937
938 (defcustom js2-mode-indent-inhibit-undo nil
939 "Non-nil to disable collection of Undo information when indenting lines.
940 Some users have requested this behavior. It's nil by default because
941 other Emacs modes don't work this way."
942 :type 'boolean
943 :group 'js2-mode)
944
945 (defcustom js2-mode-indent-ignore-first-tab nil
946 "If non-nil, ignore first TAB keypress if we look indented properly.
947 It's fairly common for users to navigate to an already-indented line
948 and press TAB for reassurance that it's been indented. For this class
949 of users, we want the first TAB press on a line to be ignored if the
950 line is already indented to one of the precomputed alternatives.
951
952 This behavior is only partly implemented. If you TAB-indent a line,
953 navigate to another line, and then navigate back, it fails to clear
954 the last-indented variable, so it thinks you've already hit TAB once,
955 and performs the indent. A full solution would involve getting on the
956 point-motion hooks for the entire buffer. If we come across another
957 use cases that requires watching point motion, I'll consider doing it.
958
959 If you set this variable to nil, then the TAB key will always change
960 the indentation of the current line, if more than one alternative
961 indentation spot exists."
962 :type 'boolean
963 :group 'js2-mode)
964
965 (defvar js2-indent-hook nil
966 "A hook for user-defined indentation rules.
967
968 Functions on this hook should expect two arguments: (LIST INDEX)
969 The LIST argument is the list of computed indentation points for
970 the current line. INDEX is the list index of the indentation point
971 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
972 indent function is not going to change the current line indentation.
973
974 If a hook function on this list returns a non-nil value, then
975 `js2-bounce-indent' assumes the hook function has performed its own
976 indentation, and will do nothing. If all hook functions on the list
977 return nil, then `js2-bounce-indent' will use its computed indentation
978 and reindent the line.
979
980 When hook functions on this hook list are called, the variable
981 `js2-mode-ast' may or may not be set, depending on whether the
982 parse tree is available. If the variable is nil, you can pass a
983 callback to `js2-mode-wait-for-parse', and your callback will be
984 called after the new parse tree is built. This can take some time
985 in large files.")
986
987 (defface js2-warning
988 `((((class color) (background light))
989 (:underline "orange"))
990 (((class color) (background dark))
991 (:underline "orange"))
992 (t (:underline t)))
993 "Face for JavaScript warnings."
994 :group 'js2-mode)
995
996 (defface js2-error
997 `((((class color) (background light))
998 (:foreground "red"))
999 (((class color) (background dark))
1000 (:foreground "red"))
1001 (t (:foreground "red")))
1002 "Face for JavaScript errors."
1003 :group 'js2-mode)
1004
1005 (defface js2-jsdoc-tag
1006 '((t :foreground "SlateGray"))
1007 "Face used to highlight @whatever tags in jsdoc comments."
1008 :group 'js2-mode)
1009
1010 (defface js2-jsdoc-type
1011 '((t :foreground "SteelBlue"))
1012 "Face used to highlight {FooBar} types in jsdoc comments."
1013 :group 'js2-mode)
1014
1015 (defface js2-jsdoc-value
1016 '((t :foreground "PeachPuff3"))
1017 "Face used to highlight tag values in jsdoc comments."
1018 :group 'js2-mode)
1019
1020 (defface js2-function-param
1021 '((t :foreground "SeaGreen"))
1022 "Face used to highlight function parameters in javascript."
1023 :group 'js2-mode)
1024
1025 (defface js2-function-call
1026 '((t :inherit default))
1027 "Face used to highlight function name in calls."
1028 :group 'js2-mode)
1029
1030 (defface js2-object-property
1031 '((t :inherit default))
1032 "Face used to highlight named property in object literal."
1033 :group 'js2-mode)
1034
1035 (defface js2-instance-member
1036 '((t :foreground "DarkOrchid"))
1037 "Face used to highlight instance variables in javascript.
1038 Not currently used."
1039 :group 'js2-mode)
1040
1041 (defface js2-private-member
1042 '((t :foreground "PeachPuff3"))
1043 "Face used to highlight calls to private methods in javascript.
1044 Not currently used."
1045 :group 'js2-mode)
1046
1047 (defface js2-private-function-call
1048 '((t :foreground "goldenrod"))
1049 "Face used to highlight calls to private functions in javascript.
1050 Not currently used."
1051 :group 'js2-mode)
1052
1053 (defface js2-jsdoc-html-tag-name
1054 '((((class color) (min-colors 88) (background light))
1055 (:foreground "rosybrown"))
1056 (((class color) (min-colors 8) (background dark))
1057 (:foreground "yellow"))
1058 (((class color) (min-colors 8) (background light))
1059 (:foreground "magenta")))
1060 "Face used to highlight jsdoc html tag names"
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-html-tag-delimiter
1064 '((((class color) (min-colors 88) (background light))
1065 (:foreground "dark khaki"))
1066 (((class color) (min-colors 8) (background dark))
1067 (:foreground "green"))
1068 (((class color) (min-colors 8) (background light))
1069 (:foreground "green")))
1070 "Face used to highlight brackets in jsdoc html tags."
1071 :group 'js2-mode)
1072
1073 (defface js2-external-variable
1074 '((t :foreground "orange"))
1075 "Face used to highlight undeclared variable identifiers.")
1076
1077 (defcustom js2-init-hook nil
1078 "List of functions to be called after `js2-mode' or
1079 `js2-minor-mode' has initialized all variables, before parsing
1080 the buffer for the first time."
1081 :type 'hook
1082 :group 'js2-mode
1083 :version "20130608")
1084
1085 (defcustom js2-post-parse-callbacks nil
1086 "List of callback functions invoked after parsing finishes.
1087 Currently, the main use for this function is to add synthetic
1088 declarations to `js2-recorded-identifiers', which see."
1089 :type 'hook
1090 :group 'js2-mode)
1091
1092 (defcustom js2-build-imenu-callbacks nil
1093 "List of functions called during Imenu index generation.
1094 It's a good place to add additional entries to it, using
1095 `js2-record-imenu-entry'."
1096 :type 'hook
1097 :group 'js2-mode)
1098
1099 (defcustom js2-highlight-external-variables t
1100 "Non-nil to highlight undeclared variable identifiers.
1101 An undeclared variable is any variable not declared with var or let
1102 in the current scope or any lexically enclosing scope. If you use
1103 such a variable, then you are either expecting it to originate from
1104 another file, or you've got a potential bug."
1105 :type 'boolean
1106 :group 'js2-mode)
1107
1108 (defcustom js2-warn-about-unused-function-arguments nil
1109 "Non-nil to treat function arguments like declared-but-unused variables."
1110 :type 'booleanp
1111 :group 'js2-mode)
1112
1113 (defcustom js2-include-jslint-globals t
1114 "Non-nil to include the identifiers from JSLint global
1115 declaration (see http://www.jslint.com/lint.html#global) in the
1116 buffer-local externs list. See `js2-additional-externs' for more
1117 information."
1118 :type 'boolean
1119 :group 'js2-mode)
1120
1121 (defvar js2-mode-map
1122 (let ((map (make-sparse-keymap)))
1123 (define-key map [mouse-1] #'js2-mode-show-node)
1124 (define-key map (kbd "M-j") #'js2-line-break)
1125 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1126 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1127 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1128 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1129 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1130 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1131 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1132 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1133 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1134
1135 (define-key map [menu-bar javascript]
1136 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1137
1138 (define-key map [menu-bar javascript customize-js2-mode]
1139 '(menu-item "Customize js2-mode" js2-mode-customize
1140 :help "Customize the behavior of this mode"))
1141
1142 (define-key map [menu-bar javascript js2-force-refresh]
1143 '(menu-item "Force buffer refresh" js2-mode-reset
1144 :help "Re-parse the buffer from scratch"))
1145
1146 (define-key map [menu-bar javascript separator-2]
1147 '("--"))
1148
1149 (define-key map [menu-bar javascript next-error]
1150 '(menu-item "Next warning or error" next-error
1151 :enabled (and js2-mode-ast
1152 (or (js2-ast-root-errors js2-mode-ast)
1153 (js2-ast-root-warnings js2-mode-ast)))
1154 :help "Move to next warning or error"))
1155
1156 (define-key map [menu-bar javascript display-errors]
1157 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1158 :visible (not js2-mode-show-parse-errors)
1159 :help "Turn on display of warnings and errors"))
1160
1161 (define-key map [menu-bar javascript hide-errors]
1162 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1163 :visible js2-mode-show-parse-errors
1164 :help "Turn off display of warnings and errors"))
1165
1166 (define-key map [menu-bar javascript separator-1]
1167 '("--"))
1168
1169 (define-key map [menu-bar javascript js2-toggle-function]
1170 '(menu-item "Show/collapse element" js2-mode-toggle-element
1171 :help "Hide or show function body or comment"))
1172
1173 (define-key map [menu-bar javascript show-comments]
1174 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1175 :visible js2-mode-comments-hidden
1176 :help "Expand all hidden block comments"))
1177
1178 (define-key map [menu-bar javascript hide-comments]
1179 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1180 :visible (not js2-mode-comments-hidden)
1181 :help "Show block comments as /*...*/"))
1182
1183 (define-key map [menu-bar javascript show-all-functions]
1184 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1185 :visible js2-mode-functions-hidden
1186 :help "Expand all hidden function bodies"))
1187
1188 (define-key map [menu-bar javascript hide-all-functions]
1189 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1190 :visible (not js2-mode-functions-hidden)
1191 :help "Show {...} for all top-level function bodies"))
1192
1193 map)
1194 "Keymap used in `js2-mode' buffers.")
1195
1196 (defcustom js2-bounce-indent-p nil
1197 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1198 They will augment the default indent-line behavior with cycling
1199 among several computed alternatives. See the function
1200 `js2-bounce-indent' for details. The above commands will be
1201 bound to TAB and backtab."
1202 :type 'boolean
1203 :group 'js2-mode
1204 :set (lambda (sym value)
1205 (set-default sym value)
1206 (let ((map js2-mode-map))
1207 (if (not value)
1208 (progn
1209 (define-key map "\t" nil)
1210 (define-key map (kbd "<backtab>") nil))
1211 (define-key map "\t" #'js2-indent-bounce)
1212 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1213
1214 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1215
1216 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1217 "Matches a //-comment line. Must be first non-whitespace on line.
1218 First match-group is the leading whitespace.")
1219
1220 (defvar js2-mode-hook nil)
1221
1222 (js2-deflocal js2-mode-ast nil "Private variable.")
1223 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1224 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1225 (js2-deflocal js2-mode-parsing nil "Private variable.")
1226 (js2-deflocal js2-mode-node-overlay nil)
1227
1228 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1229 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1230
1231 (js2-deflocal js2-mode-fontifications nil "Private variable")
1232 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1233 (js2-deflocal js2-imenu-recorder nil "Private variable")
1234 (js2-deflocal js2-imenu-function-map nil "Private variable")
1235
1236 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1237 "Non-nil to emit status messages during parsing.")
1238
1239 (defvar js2-mode-functions-hidden nil "Private variable.")
1240 (defvar js2-mode-comments-hidden nil "Private variable.")
1241
1242 (defvar js2-mode-syntax-table
1243 (let ((table (make-syntax-table)))
1244 (c-populate-syntax-table table)
1245 (modify-syntax-entry ?` "\"" table)
1246 table)
1247 "Syntax table used in `js2-mode' buffers.")
1248
1249 (defvar js2-mode-abbrev-table nil
1250 "Abbrev table in use in `js2-mode' buffers.")
1251 (define-abbrev-table 'js2-mode-abbrev-table ())
1252
1253 (defvar js2-mode-pending-parse-callbacks nil
1254 "List of functions waiting to be notified that parse is finished.")
1255
1256 (defvar js2-mode-last-indented-line -1)
1257
1258 ;;; Localizable error and warning messages
1259
1260 ;; Messages are copied from Rhino's Messages.properties.
1261 ;; Many of the Java-specific messages have been elided.
1262 ;; Add any js2-specific ones at the end, so we can keep
1263 ;; this file synced with changes to Rhino's.
1264
1265 (defvar js2-message-table
1266 (make-hash-table :test 'equal :size 250)
1267 "Contains localized messages for `js2-mode'.")
1268
1269 ;; TODO(stevey): construct this table at compile-time.
1270 (defmacro js2-msg (key &rest strings)
1271 `(puthash ,key (concat ,@strings)
1272 js2-message-table))
1273
1274 (defun js2-get-msg (msg-key)
1275 "Look up a localized message.
1276 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1277 the correct number of ARGS must be provided."
1278 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1279 (args (if (listp msg-key) (cdr msg-key)))
1280 (msg (gethash key js2-message-table)))
1281 (if msg
1282 (apply #'format msg args)
1283 key))) ; default to showing the key
1284
1285 (js2-msg "msg.dup.parms"
1286 "Duplicate parameter name '%s'.")
1287
1288 (js2-msg "msg.too.big.jump"
1289 "Program too complex: jump offset too big.")
1290
1291 (js2-msg "msg.too.big.index"
1292 "Program too complex: internal index exceeds 64K limit.")
1293
1294 (js2-msg "msg.while.compiling.fn"
1295 "Encountered code generation error while compiling function '%s': %s")
1296
1297 (js2-msg "msg.while.compiling.script"
1298 "Encountered code generation error while compiling script: %s")
1299
1300 ;; Context
1301 (js2-msg "msg.ctor.not.found"
1302 "Constructor for '%s' not found.")
1303
1304 (js2-msg "msg.not.ctor"
1305 "'%s' is not a constructor.")
1306
1307 ;; FunctionObject
1308 (js2-msg "msg.varargs.ctor"
1309 "Method or constructor '%s' must be static "
1310 "with the signature (Context cx, Object[] args, "
1311 "Function ctorObj, boolean inNewExpr) "
1312 "to define a variable arguments constructor.")
1313
1314 (js2-msg "msg.varargs.fun"
1315 "Method '%s' must be static with the signature "
1316 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1317 "to define a variable arguments function.")
1318
1319 (js2-msg "msg.incompat.call"
1320 "Method '%s' called on incompatible object.")
1321
1322 (js2-msg "msg.bad.parms"
1323 "Unsupported parameter type '%s' in method '%s'.")
1324
1325 (js2-msg "msg.bad.method.return"
1326 "Unsupported return type '%s' in method '%s'.")
1327
1328 (js2-msg "msg.bad.ctor.return"
1329 "Construction of objects of type '%s' is not supported.")
1330
1331 (js2-msg "msg.no.overload"
1332 "Method '%s' occurs multiple times in class '%s'.")
1333
1334 (js2-msg "msg.method.not.found"
1335 "Method '%s' not found in '%s'.")
1336
1337 ;; IRFactory
1338
1339 (js2-msg "msg.bad.for.in.lhs"
1340 "Invalid left-hand side of for..in loop.")
1341
1342 (js2-msg "msg.mult.index"
1343 "Only one variable allowed in for..in loop.")
1344
1345 (js2-msg "msg.bad.for.in.destruct"
1346 "Left hand side of for..in loop must be an array of "
1347 "length 2 to accept key/value pair.")
1348
1349 (js2-msg "msg.cant.convert"
1350 "Can't convert to type '%s'.")
1351
1352 (js2-msg "msg.bad.assign.left"
1353 "Invalid assignment left-hand side.")
1354
1355 (js2-msg "msg.bad.decr"
1356 "Invalid decrement operand.")
1357
1358 (js2-msg "msg.bad.incr"
1359 "Invalid increment operand.")
1360
1361 (js2-msg "msg.bad.yield"
1362 "yield must be in a function.")
1363
1364 (js2-msg "msg.yield.parenthesized"
1365 "yield expression must be parenthesized.")
1366
1367 (js2-msg "msg.bad.await"
1368 "await must be in async functions.")
1369
1370 ;; NativeGlobal
1371 (js2-msg "msg.cant.call.indirect"
1372 "Function '%s' must be called directly, and not by way of a "
1373 "function of another name.")
1374
1375 (js2-msg "msg.eval.nonstring"
1376 "Calling eval() with anything other than a primitive "
1377 "string value will simply return the value. "
1378 "Is this what you intended?")
1379
1380 (js2-msg "msg.eval.nonstring.strict"
1381 "Calling eval() with anything other than a primitive "
1382 "string value is not allowed in strict mode.")
1383
1384 (js2-msg "msg.bad.destruct.op"
1385 "Invalid destructuring assignment operator")
1386
1387 ;; NativeCall
1388 (js2-msg "msg.only.from.new"
1389 "'%s' may only be invoked from a `new' expression.")
1390
1391 (js2-msg "msg.deprec.ctor"
1392 "The '%s' constructor is deprecated.")
1393
1394 ;; NativeFunction
1395 (js2-msg "msg.no.function.ref.found"
1396 "no source found to decompile function reference %s")
1397
1398 (js2-msg "msg.arg.isnt.array"
1399 "second argument to Function.prototype.apply must be an array")
1400
1401 ;; NativeGlobal
1402 (js2-msg "msg.bad.esc.mask"
1403 "invalid string escape mask")
1404
1405 ;; NativeRegExp
1406 (js2-msg "msg.bad.quant"
1407 "Invalid quantifier %s")
1408
1409 (js2-msg "msg.overlarge.backref"
1410 "Overly large back reference %s")
1411
1412 (js2-msg "msg.overlarge.min"
1413 "Overly large minimum %s")
1414
1415 (js2-msg "msg.overlarge.max"
1416 "Overly large maximum %s")
1417
1418 (js2-msg "msg.zero.quant"
1419 "Zero quantifier %s")
1420
1421 (js2-msg "msg.max.lt.min"
1422 "Maximum %s less than minimum")
1423
1424 (js2-msg "msg.unterm.quant"
1425 "Unterminated quantifier %s")
1426
1427 (js2-msg "msg.unterm.paren"
1428 "Unterminated parenthetical %s")
1429
1430 (js2-msg "msg.unterm.class"
1431 "Unterminated character class %s")
1432
1433 (js2-msg "msg.bad.range"
1434 "Invalid range in character class.")
1435
1436 (js2-msg "msg.trail.backslash"
1437 "Trailing \\ in regular expression.")
1438
1439 (js2-msg "msg.re.unmatched.right.paren"
1440 "unmatched ) in regular expression.")
1441
1442 (js2-msg "msg.no.regexp"
1443 "Regular expressions are not available.")
1444
1445 (js2-msg "msg.bad.backref"
1446 "back-reference exceeds number of capturing parentheses.")
1447
1448 (js2-msg "msg.bad.regexp.compile"
1449 "Only one argument may be specified if the first "
1450 "argument to RegExp.prototype.compile is a RegExp object.")
1451
1452 ;; Parser
1453 (js2-msg "msg.got.syntax.errors"
1454 "Compilation produced %s syntax errors.")
1455
1456 (js2-msg "msg.var.redecl"
1457 "TypeError: redeclaration of var %s.")
1458
1459 (js2-msg "msg.const.redecl"
1460 "TypeError: redeclaration of const %s.")
1461
1462 (js2-msg "msg.let.redecl"
1463 "TypeError: redeclaration of variable %s.")
1464
1465 (js2-msg "msg.parm.redecl"
1466 "TypeError: redeclaration of formal parameter %s.")
1467
1468 (js2-msg "msg.fn.redecl"
1469 "TypeError: redeclaration of function %s.")
1470
1471 (js2-msg "msg.let.decl.not.in.block"
1472 "SyntaxError: let declaration not directly within block")
1473
1474 (js2-msg "msg.mod.import.decl.at.top.level"
1475 "SyntaxError: import declarations may only appear at the top level")
1476
1477 (js2-msg "msg.mod.as.after.reserved.word"
1478 "SyntaxError: missing keyword 'as' after reserved word %s")
1479
1480 (js2-msg "msg.mod.rc.after.import.spec.list"
1481 "SyntaxError: missing '}' after module specifier list")
1482
1483 (js2-msg "msg.mod.from.after.import.spec.set"
1484 "SyntaxError: missing keyword 'from' after import specifier set")
1485
1486 (js2-msg "msg.mod.declaration.after.import"
1487 "SyntaxError: missing declaration after 'import' keyword")
1488
1489 (js2-msg "msg.mod.spec.after.from"
1490 "SyntaxError: missing module specifier after 'from' keyword")
1491
1492 (js2-msg "msg.mod.export.decl.at.top.level"
1493 "SyntaxError: export declarations may only appear at top level")
1494
1495 (js2-msg "msg.mod.rc.after.export.spec.list"
1496 "SyntaxError: missing '}' after export specifier list")
1497
1498 ;; NodeTransformer
1499 (js2-msg "msg.dup.label"
1500 "duplicated label")
1501
1502 (js2-msg "msg.undef.label"
1503 "undefined label")
1504
1505 (js2-msg "msg.bad.break"
1506 "unlabelled break must be inside loop or switch")
1507
1508 (js2-msg "msg.continue.outside"
1509 "continue must be inside loop")
1510
1511 (js2-msg "msg.continue.nonloop"
1512 "continue can only use labels of iteration statements")
1513
1514 (js2-msg "msg.bad.throw.eol"
1515 "Line terminator is not allowed between the throw "
1516 "keyword and throw expression.")
1517
1518 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1519 "function statement requires a name")
1520
1521 (js2-msg "msg.no.paren.parms"
1522 "missing ( before function parameters.")
1523
1524 (js2-msg "msg.no.parm"
1525 "missing formal parameter")
1526
1527 (js2-msg "msg.no.paren.after.parms"
1528 "missing ) after formal parameters")
1529
1530 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1531 "parameter without default follows parameter with default")
1532
1533 (js2-msg "msg.param.after.rest" ; added by js2-mode
1534 "parameter after rest parameter")
1535
1536 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1537 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1538
1539 (js2-msg "msg.no.brace.body"
1540 "missing '{' before function body")
1541
1542 (js2-msg "msg.no.brace.after.body"
1543 "missing } after function body")
1544
1545 (js2-msg "msg.no.paren.cond"
1546 "missing ( before condition")
1547
1548 (js2-msg "msg.no.paren.after.cond"
1549 "missing ) after condition")
1550
1551 (js2-msg "msg.no.semi.stmt"
1552 "missing ; before statement")
1553
1554 (js2-msg "msg.missing.semi"
1555 "missing ; after statement")
1556
1557 (js2-msg "msg.no.name.after.dot"
1558 "missing name after . operator")
1559
1560 (js2-msg "msg.no.name.after.coloncolon"
1561 "missing name after :: operator")
1562
1563 (js2-msg "msg.no.name.after.dotdot"
1564 "missing name after .. operator")
1565
1566 (js2-msg "msg.no.name.after.xmlAttr"
1567 "missing name after .@")
1568
1569 (js2-msg "msg.no.bracket.index"
1570 "missing ] in index expression")
1571
1572 (js2-msg "msg.no.paren.switch"
1573 "missing ( before switch expression")
1574
1575 (js2-msg "msg.no.paren.after.switch"
1576 "missing ) after switch expression")
1577
1578 (js2-msg "msg.no.brace.switch"
1579 "missing '{' before switch body")
1580
1581 (js2-msg "msg.bad.switch"
1582 "invalid switch statement")
1583
1584 (js2-msg "msg.no.colon.case"
1585 "missing : after case expression")
1586
1587 (js2-msg "msg.double.switch.default"
1588 "double default label in the switch statement")
1589
1590 (js2-msg "msg.no.while.do"
1591 "missing while after do-loop body")
1592
1593 (js2-msg "msg.no.paren.for"
1594 "missing ( after for")
1595
1596 (js2-msg "msg.no.semi.for"
1597 "missing ; after for-loop initializer")
1598
1599 (js2-msg "msg.no.semi.for.cond"
1600 "missing ; after for-loop condition")
1601
1602 (js2-msg "msg.in.after.for.name"
1603 "missing in or of after for")
1604
1605 (js2-msg "msg.no.paren.for.ctrl"
1606 "missing ) after for-loop control")
1607
1608 (js2-msg "msg.no.paren.with"
1609 "missing ( before with-statement object")
1610
1611 (js2-msg "msg.no.paren.after.with"
1612 "missing ) after with-statement object")
1613
1614 (js2-msg "msg.no.with.strict"
1615 "with statements not allowed in strict mode")
1616
1617 (js2-msg "msg.no.paren.after.let"
1618 "missing ( after let")
1619
1620 (js2-msg "msg.no.paren.let"
1621 "missing ) after variable list")
1622
1623 (js2-msg "msg.no.curly.let"
1624 "missing } after let statement")
1625
1626 (js2-msg "msg.bad.return"
1627 "invalid return")
1628
1629 (js2-msg "msg.no.brace.block"
1630 "missing } in compound statement")
1631
1632 (js2-msg "msg.bad.label"
1633 "invalid label")
1634
1635 (js2-msg "msg.bad.var"
1636 "missing variable name")
1637
1638 (js2-msg "msg.bad.var.init"
1639 "invalid variable initialization")
1640
1641 (js2-msg "msg.no.colon.cond"
1642 "missing : in conditional expression")
1643
1644 (js2-msg "msg.no.paren.arg"
1645 "missing ) after argument list")
1646
1647 (js2-msg "msg.no.bracket.arg"
1648 "missing ] after element list")
1649
1650 (js2-msg "msg.bad.prop"
1651 "invalid property id")
1652
1653 (js2-msg "msg.no.colon.prop"
1654 "missing : after property id")
1655
1656 (js2-msg "msg.no.brace.prop"
1657 "missing } after property list")
1658
1659 (js2-msg "msg.no.paren"
1660 "missing ) in parenthetical")
1661
1662 (js2-msg "msg.reserved.id"
1663 "'%s' is a reserved identifier")
1664
1665 (js2-msg "msg.no.paren.catch"
1666 "missing ( before catch-block condition")
1667
1668 (js2-msg "msg.bad.catchcond"
1669 "invalid catch block condition")
1670
1671 (js2-msg "msg.catch.unreachable"
1672 "any catch clauses following an unqualified catch are unreachable")
1673
1674 (js2-msg "msg.no.brace.try"
1675 "missing '{' before try block")
1676
1677 (js2-msg "msg.no.brace.catchblock"
1678 "missing '{' before catch-block body")
1679
1680 (js2-msg "msg.try.no.catchfinally"
1681 "'try' without 'catch' or 'finally'")
1682
1683 (js2-msg "msg.no.return.value"
1684 "function %s does not always return a value")
1685
1686 (js2-msg "msg.anon.no.return.value"
1687 "anonymous function does not always return a value")
1688
1689 (js2-msg "msg.return.inconsistent"
1690 "return statement is inconsistent with previous usage")
1691
1692 (js2-msg "msg.generator.returns"
1693 "TypeError: legacy generator function '%s' returns a value")
1694
1695 (js2-msg "msg.anon.generator.returns"
1696 "TypeError: anonymous legacy generator function returns a value")
1697
1698 (js2-msg "msg.syntax"
1699 "syntax error")
1700
1701 (js2-msg "msg.unexpected.eof"
1702 "Unexpected end of file")
1703
1704 (js2-msg "msg.XML.bad.form"
1705 "illegally formed XML syntax")
1706
1707 (js2-msg "msg.XML.not.available"
1708 "XML runtime not available")
1709
1710 (js2-msg "msg.too.deep.parser.recursion"
1711 "Too deep recursion while parsing")
1712
1713 (js2-msg "msg.no.side.effects"
1714 "Code has no side effects")
1715
1716 (js2-msg "msg.extra.trailing.comma"
1717 "Trailing comma is not supported in some browsers")
1718
1719 (js2-msg "msg.array.trailing.comma"
1720 "Trailing comma yields different behavior across browsers")
1721
1722 (js2-msg "msg.equal.as.assign"
1723 (concat "Test for equality (==) mistyped as assignment (=)?"
1724 " (parenthesize to suppress warning)"))
1725
1726 (js2-msg "msg.var.hides.arg"
1727 "Variable %s hides argument")
1728
1729 (js2-msg "msg.destruct.assign.no.init"
1730 "Missing = in destructuring declaration")
1731
1732 (js2-msg "msg.init.no.destruct"
1733 "Binding initializer not in destructuring assignment")
1734
1735 (js2-msg "msg.no.octal.strict"
1736 "Octal numbers prohibited in strict mode.")
1737
1738 (js2-msg "msg.dup.obj.lit.prop.strict"
1739 "Property '%s' already defined in this object literal.")
1740
1741 (js2-msg "msg.dup.param.strict"
1742 "Parameter '%s' already declared in this function.")
1743
1744 (js2-msg "msg.bad.id.strict"
1745 "'%s' is not a valid identifier for this use in strict mode.")
1746
1747 ;; ScriptRuntime
1748 (js2-msg "msg.no.properties"
1749 "%s has no properties.")
1750
1751 (js2-msg "msg.invalid.iterator"
1752 "Invalid iterator value")
1753
1754 (js2-msg "msg.iterator.primitive"
1755 "__iterator__ returned a primitive value")
1756
1757 (js2-msg "msg.assn.create.strict"
1758 "Assignment to undeclared variable %s")
1759
1760 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1761 "Undeclared variable or function '%s'")
1762
1763 (js2-msg "msg.unused.variable" ; added by js2-mode
1764 "Unused variable or function '%s'")
1765
1766 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1767 "Variable '%s' referenced but never initialized")
1768
1769 (js2-msg "msg.ref.undefined.prop"
1770 "Reference to undefined property '%s'")
1771
1772 (js2-msg "msg.prop.not.found"
1773 "Property %s not found.")
1774
1775 (js2-msg "msg.invalid.type"
1776 "Invalid JavaScript value of type %s")
1777
1778 (js2-msg "msg.primitive.expected"
1779 "Primitive type expected (had %s instead)")
1780
1781 (js2-msg "msg.namespace.expected"
1782 "Namespace object expected to left of :: (found %s instead)")
1783
1784 (js2-msg "msg.null.to.object"
1785 "Cannot convert null to an object.")
1786
1787 (js2-msg "msg.undef.to.object"
1788 "Cannot convert undefined to an object.")
1789
1790 (js2-msg "msg.cyclic.value"
1791 "Cyclic %s value not allowed.")
1792
1793 (js2-msg "msg.is.not.defined"
1794 "'%s' is not defined.")
1795
1796 (js2-msg "msg.undef.prop.read"
1797 "Cannot read property '%s' from %s")
1798
1799 (js2-msg "msg.undef.prop.write"
1800 "Cannot set property '%s' of %s to '%s'")
1801
1802 (js2-msg "msg.undef.prop.delete"
1803 "Cannot delete property '%s' of %s")
1804
1805 (js2-msg "msg.undef.method.call"
1806 "Cannot call method '%s' of %s")
1807
1808 (js2-msg "msg.undef.with"
1809 "Cannot apply 'with' to %s")
1810
1811 (js2-msg "msg.isnt.function"
1812 "%s is not a function, it is %s.")
1813
1814 (js2-msg "msg.isnt.function.in"
1815 "Cannot call property %s in object %s. "
1816 "It is not a function, it is '%s'.")
1817
1818 (js2-msg "msg.function.not.found"
1819 "Cannot find function %s.")
1820
1821 (js2-msg "msg.function.not.found.in"
1822 "Cannot find function %s in object %s.")
1823
1824 (js2-msg "msg.isnt.xml.object"
1825 "%s is not an xml object.")
1826
1827 (js2-msg "msg.no.ref.to.get"
1828 "%s is not a reference to read reference value.")
1829
1830 (js2-msg "msg.no.ref.to.set"
1831 "%s is not a reference to set reference value to %s.")
1832
1833 (js2-msg "msg.no.ref.from.function"
1834 "Function %s can not be used as the left-hand "
1835 "side of assignment or as an operand of ++ or -- operator.")
1836
1837 (js2-msg "msg.bad.default.value"
1838 "Object's getDefaultValue() method returned an object.")
1839
1840 (js2-msg "msg.instanceof.not.object"
1841 "Can't use instanceof on a non-object.")
1842
1843 (js2-msg "msg.instanceof.bad.prototype"
1844 "'prototype' property of %s is not an object.")
1845
1846 (js2-msg "msg.bad.radix"
1847 "illegal radix %s.")
1848
1849 ;; ScriptableObject
1850 (js2-msg "msg.default.value"
1851 "Cannot find default value for object.")
1852
1853 (js2-msg "msg.zero.arg.ctor"
1854 "Cannot load class '%s' which has no zero-parameter constructor.")
1855
1856 (js2-msg "msg.ctor.multiple.parms"
1857 "Can't define constructor or class %s since more than "
1858 "one constructor has multiple parameters.")
1859
1860 (js2-msg "msg.extend.scriptable"
1861 "%s must extend ScriptableObject in order to define property %s.")
1862
1863 (js2-msg "msg.bad.getter.parms"
1864 "In order to define a property, getter %s must have zero "
1865 "parameters or a single ScriptableObject parameter.")
1866
1867 (js2-msg "msg.obj.getter.parms"
1868 "Expected static or delegated getter %s to take "
1869 "a ScriptableObject parameter.")
1870
1871 (js2-msg "msg.getter.static"
1872 "Getter and setter must both be static or neither be static.")
1873
1874 (js2-msg "msg.setter.return"
1875 "Setter must have void return type: %s")
1876
1877 (js2-msg "msg.setter2.parms"
1878 "Two-parameter setter must take a ScriptableObject as "
1879 "its first parameter.")
1880
1881 (js2-msg "msg.setter1.parms"
1882 "Expected single parameter setter for %s")
1883
1884 (js2-msg "msg.setter2.expected"
1885 "Expected static or delegated setter %s to take two parameters.")
1886
1887 (js2-msg "msg.setter.parms"
1888 "Expected either one or two parameters for setter.")
1889
1890 (js2-msg "msg.setter.bad.type"
1891 "Unsupported parameter type '%s' in setter '%s'.")
1892
1893 (js2-msg "msg.add.sealed"
1894 "Cannot add a property to a sealed object: %s.")
1895
1896 (js2-msg "msg.remove.sealed"
1897 "Cannot remove a property from a sealed object: %s.")
1898
1899 (js2-msg "msg.modify.sealed"
1900 "Cannot modify a property of a sealed object: %s.")
1901
1902 (js2-msg "msg.modify.readonly"
1903 "Cannot modify readonly property: %s.")
1904
1905 ;; TokenStream
1906 (js2-msg "msg.missing.exponent"
1907 "missing exponent")
1908
1909 (js2-msg "msg.caught.nfe"
1910 "number format error")
1911
1912 (js2-msg "msg.unterminated.string.lit"
1913 "unterminated string literal")
1914
1915 (js2-msg "msg.unterminated.comment"
1916 "unterminated comment")
1917
1918 (js2-msg "msg.unterminated.re.lit"
1919 "unterminated regular expression literal")
1920
1921 (js2-msg "msg.invalid.re.flag"
1922 "invalid flag after regular expression")
1923
1924 (js2-msg "msg.no.re.input.for"
1925 "no input for %s")
1926
1927 (js2-msg "msg.illegal.character"
1928 "illegal character")
1929
1930 (js2-msg "msg.invalid.escape"
1931 "invalid Unicode escape sequence")
1932
1933 (js2-msg "msg.bad.namespace"
1934 "not a valid default namespace statement. "
1935 "Syntax is: default xml namespace = EXPRESSION;")
1936
1937 ;; TokensStream warnings
1938 (js2-msg "msg.bad.octal.literal"
1939 "illegal octal literal digit %s; "
1940 "interpreting it as a decimal digit")
1941
1942 (js2-msg "msg.missing.hex.digits"
1943 "missing hexadecimal digits after '0x'")
1944
1945 (js2-msg "msg.missing.binary.digits"
1946 "missing binary digits after '0b'")
1947
1948 (js2-msg "msg.missing.octal.digits"
1949 "missing octal digits after '0o'")
1950
1951 (js2-msg "msg.script.is.not.constructor"
1952 "Script objects are not constructors.")
1953
1954 ;; Arrays
1955 (js2-msg "msg.arraylength.bad"
1956 "Inappropriate array length.")
1957
1958 ;; Arrays
1959 (js2-msg "msg.arraylength.too.big"
1960 "Array length %s exceeds supported capacity limit.")
1961
1962 ;; URI
1963 (js2-msg "msg.bad.uri"
1964 "Malformed URI sequence.")
1965
1966 ;; Number
1967 (js2-msg "msg.bad.precision"
1968 "Precision %s out of range.")
1969
1970 ;; NativeGenerator
1971 (js2-msg "msg.send.newborn"
1972 "Attempt to send value to newborn generator")
1973
1974 (js2-msg "msg.already.exec.gen"
1975 "Already executing generator")
1976
1977 (js2-msg "msg.StopIteration.invalid"
1978 "StopIteration may not be changed to an arbitrary object.")
1979
1980 ;; Interpreter
1981 (js2-msg "msg.yield.closing"
1982 "Yield from closing generator")
1983
1984 ;; Classes
1985 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1986 "class statement requires a name")
1987
1988 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1989 "unexpected ',' between class properties")
1990
1991 (js2-msg "msg.unexpected.static" ; added by js2-mode
1992 "unexpected 'static'")
1993
1994 (js2-msg "msg.missing.extends" ; added by js2-mode
1995 "name is required after extends")
1996
1997 (js2-msg "msg.no.brace.class" ; added by js2-mode
1998 "missing '{' before class body")
1999
2000 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2001 "missing ']' after computed property expression")
2002
2003 ;;; Tokens Buffer
2004
2005 (defconst js2-ti-max-lookahead 2)
2006 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2007
2008 (defun js2-new-token (offset)
2009 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2010 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2011 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2012 token))
2013
2014 (defsubst js2-current-token ()
2015 (aref js2-ti-tokens js2-ti-tokens-cursor))
2016
2017 (defsubst js2-current-token-string ()
2018 (js2-token-string (js2-current-token)))
2019
2020 (defsubst js2-current-token-type ()
2021 (js2-token-type (js2-current-token)))
2022
2023 (defsubst js2-current-token-beg ()
2024 (js2-token-beg (js2-current-token)))
2025
2026 (defsubst js2-current-token-end ()
2027 (js2-token-end (js2-current-token)))
2028
2029 (defun js2-current-token-len ()
2030 (let ((token (js2-current-token)))
2031 (- (js2-token-end token)
2032 (js2-token-beg token))))
2033
2034 (defun js2-ts-seek (state)
2035 (setq js2-ts-lineno (js2-ts-state-lineno state)
2036 js2-ts-cursor (js2-ts-state-cursor state)
2037 js2-ti-tokens (js2-ts-state-tokens state)
2038 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2039 js2-ti-lookahead (js2-ts-state-lookahead state)))
2040
2041 ;;; Utilities
2042
2043 (defun js2-delete-if (predicate list)
2044 "Remove all items satisfying PREDICATE in LIST."
2045 (cl-loop for item in list
2046 if (not (funcall predicate item))
2047 collect item))
2048
2049 (defun js2-position (element list)
2050 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2051 Returns nil if element is not found in the list."
2052 (let ((count 0)
2053 found)
2054 (while (and list (not found))
2055 (if (eq element (car list))
2056 (setq found t)
2057 (setq count (1+ count)
2058 list (cdr list))))
2059 (if found count)))
2060
2061 (defun js2-find-if (predicate list)
2062 "Find first item satisfying PREDICATE in LIST."
2063 (let (result)
2064 (while (and list (not result))
2065 (if (funcall predicate (car list))
2066 (setq result (car list)))
2067 (setq list (cdr list)))
2068 result))
2069
2070 (defmacro js2-time (form)
2071 "Evaluate FORM, discard result, and return elapsed time in sec."
2072 (declare (debug t))
2073 (let ((beg (make-symbol "--js2-time-beg--")))
2074 `(let ((,beg (current-time)))
2075 ,form
2076 (/ (truncate (* (- (float-time (current-time))
2077 (float-time ,beg))
2078 10000))
2079 10000.0))))
2080
2081 (defsubst js2-same-line (pos)
2082 "Return t if POS is on the same line as current point."
2083 (and (>= pos (point-at-bol))
2084 (<= pos (point-at-eol))))
2085
2086 (defun js2-code-bug ()
2087 "Signal an error when we encounter an unexpected code path."
2088 (error "failed assertion"))
2089
2090 (defsubst js2-record-text-property (beg end prop value)
2091 "Record a text property to set when parsing finishes."
2092 (push (list beg end prop value) js2-mode-deferred-properties))
2093
2094 ;; I'd like to associate errors with nodes, but for now the
2095 ;; easiest thing to do is get the context info from the last token.
2096 (defun js2-record-parse-error (msg &optional arg pos len)
2097 (push (list (list msg arg)
2098 (or pos (js2-current-token-beg))
2099 (or len (js2-current-token-len)))
2100 js2-parsed-errors))
2101
2102 (defun js2-report-error (msg &optional msg-arg pos len)
2103 "Signal a syntax error or record a parse error."
2104 (if js2-recover-from-parse-errors
2105 (js2-record-parse-error msg msg-arg pos len)
2106 (signal 'js2-syntax-error
2107 (list msg
2108 js2-ts-lineno
2109 (save-excursion
2110 (goto-char js2-ts-cursor)
2111 (current-column))
2112 js2-ts-hit-eof))))
2113
2114 (defun js2-report-warning (msg &optional msg-arg pos len face)
2115 (if js2-compiler-report-warning-as-error
2116 (js2-report-error msg msg-arg pos len)
2117 (push (list (list msg msg-arg)
2118 (or pos (js2-current-token-beg))
2119 (or len (js2-current-token-len))
2120 face)
2121 js2-parsed-warnings)))
2122
2123 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2124 (if js2-compiler-strict-mode
2125 (js2-report-warning msg-id msg-arg beg
2126 (and beg end (- end beg)))))
2127
2128 (put 'js2-syntax-error 'error-conditions
2129 '(error syntax-error js2-syntax-error))
2130 (put 'js2-syntax-error 'error-message "Syntax error")
2131
2132 (put 'js2-parse-error 'error-conditions
2133 '(error parse-error js2-parse-error))
2134 (put 'js2-parse-error 'error-message "Parse error")
2135
2136 (defmacro js2-clear-flag (flags flag)
2137 `(setq ,flags (logand ,flags (lognot ,flag))))
2138
2139 (defmacro js2-set-flag (flags flag)
2140 "Logical-or FLAG into FLAGS."
2141 `(setq ,flags (logior ,flags ,flag)))
2142
2143 (defsubst js2-flag-set-p (flags flag)
2144 (/= 0 (logand flags flag)))
2145
2146 (defsubst js2-flag-not-set-p (flags flag)
2147 (zerop (logand flags flag)))
2148
2149 ;;; AST struct and function definitions
2150
2151 ;; flags for ast node property 'member-type (used for e4x operators)
2152 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2153 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2154 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2155
2156 (defsubst js2-relpos (pos anchor)
2157 "Convert POS to be relative to ANCHOR.
2158 If POS is nil, returns nil."
2159 (and pos (- pos anchor)))
2160
2161 (defun js2-make-pad (indent)
2162 (if (zerop indent)
2163 ""
2164 (make-string (* indent js2-basic-offset) ? )))
2165
2166 (defun js2-visit-ast (node callback)
2167 "Visit every node in ast NODE with visitor CALLBACK.
2168
2169 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2170 called twice: once to visit the node, and again after all the node's
2171 children have been processed. The END-P argument is nil on the first
2172 call and non-nil on the second call. The return value of the callback
2173 affects the traversal: if non-nil, the children of NODE are processed.
2174 If the callback returns nil, or if the node has no children, then the
2175 callback is called immediately with a non-nil END-P argument.
2176
2177 The node traversal is approximately lexical-order, although there
2178 are currently no guarantees around this."
2179 (when node
2180 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2181 ;; visit the node
2182 (when (funcall callback node nil)
2183 ;; visit the kids
2184 (cond
2185 ((eq vfunc 'js2-visit-none)
2186 nil) ; don't even bother calling it
2187 ;; Each AST node type has to define a `js2-visitor' function
2188 ;; that takes a node and a callback, and calls `js2-visit-ast'
2189 ;; on each child of the node.
2190 (vfunc
2191 (funcall vfunc node callback))
2192 (t
2193 (error "%s does not define a visitor-traversal function"
2194 (aref node 0)))))
2195 ;; call the end-visit
2196 (funcall callback node t))))
2197
2198 (cl-defstruct (js2-node
2199 (:constructor nil)) ; abstract
2200 "Base AST node type."
2201 (type -1) ; token type
2202 (pos -1) ; start position of this AST node in parsed input
2203 (len 1) ; num characters spanned by the node
2204 props ; optional node property list (an alist)
2205 parent) ; link to parent node; null for root
2206
2207 (defsubst js2-node-get-prop (node prop &optional default)
2208 (or (cadr (assoc prop (js2-node-props node))) default))
2209
2210 (defsubst js2-node-set-prop (node prop value)
2211 (setf (js2-node-props node)
2212 (cons (list prop value) (js2-node-props node))))
2213
2214 (defun js2-fixup-starts (n nodes)
2215 "Adjust the start positions of NODES to be relative to N.
2216 Any node in the list may be nil, for convenience."
2217 (dolist (node nodes)
2218 (when node
2219 (setf (js2-node-pos node) (- (js2-node-pos node)
2220 (js2-node-pos n))))))
2221
2222 (defun js2-node-add-children (parent &rest nodes)
2223 "Set parent node of NODES to PARENT, and return PARENT.
2224 Does nothing if we're not recording parent links.
2225 If any given node in NODES is nil, doesn't record that link."
2226 (js2-fixup-starts parent nodes)
2227 (dolist (node nodes)
2228 (and node
2229 (setf (js2-node-parent node) parent))))
2230
2231 ;; Non-recursive since it's called a frightening number of times.
2232 (defun js2-node-abs-pos (n)
2233 (let ((pos (js2-node-pos n)))
2234 (while (setq n (js2-node-parent n))
2235 (setq pos (+ pos (js2-node-pos n))))
2236 pos))
2237
2238 (defsubst js2-node-abs-end (n)
2239 "Return absolute buffer position of end of N."
2240 (+ (js2-node-abs-pos n) (js2-node-len n)))
2241
2242 ;; It's important to make sure block nodes have a Lisp list for the
2243 ;; child nodes, to limit printing recursion depth in an AST that
2244 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2245 ;; a sufficiently large vector tree.
2246
2247 (cl-defstruct (js2-block-node
2248 (:include js2-node)
2249 (:constructor nil)
2250 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2251 (pos (js2-current-token-beg))
2252 len
2253 props
2254 kids)))
2255 "A block of statements."
2256 kids) ; a Lisp list of the child statement nodes
2257
2258 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2259 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2260
2261 (defun js2-visit-block (ast callback)
2262 "Visit the `js2-block-node' children of AST."
2263 (dolist (kid (js2-block-node-kids ast))
2264 (js2-visit-ast kid callback)))
2265
2266 (defun js2-print-block (n i)
2267 (let ((pad (js2-make-pad i)))
2268 (insert pad "{\n")
2269 (dolist (kid (js2-block-node-kids n))
2270 (js2-print-ast kid (1+ i)))
2271 (insert pad "}")))
2272
2273 (cl-defstruct (js2-scope
2274 (:include js2-block-node)
2275 (:constructor nil)
2276 (:constructor make-js2-scope (&key (type js2-BLOCK)
2277 (pos (js2-current-token-beg))
2278 len
2279 kids)))
2280 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2281 ;; I don't have one of those handy, so I'll use an alist for now.
2282 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2283 ;; and is much lighter-weight to construct (both CPU and mem).
2284 ;; The keys are interned strings (symbols) for faster lookup.
2285 ;; Should switch to hybrid alist/hashtable eventually.
2286 symbol-table ; an alist of (symbol . js2-symbol)
2287 parent-scope ; a `js2-scope'
2288 top) ; top-level `js2-scope' (script/function)
2289
2290 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2291 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2292
2293 (defun js2-node-get-enclosing-scope (node)
2294 "Return the innermost `js2-scope' node surrounding NODE.
2295 Returns nil if there is no enclosing scope node."
2296 (while (and (setq node (js2-node-parent node))
2297 (not (js2-scope-p node))))
2298 node)
2299
2300 (defun js2-get-defining-scope (scope name &optional point)
2301 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2302 Returns `js2-scope' in which NAME is defined, or nil if not found.
2303
2304 If POINT is non-nil, and if the found declaration type is
2305 `js2-LET', also check that the declaration node is before POINT."
2306 (let ((sym (if (symbolp name)
2307 name
2308 (intern name)))
2309 result
2310 (continue t))
2311 (while (and scope continue)
2312 (if (or
2313 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2314 (and entry
2315 (or (not point)
2316 (not (eq js2-LET (js2-symbol-decl-type entry)))
2317 (>= point
2318 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2319 (and (eq sym 'arguments)
2320 (js2-function-node-p scope)))
2321 (setq continue nil
2322 result scope)
2323 (setq scope (js2-scope-parent-scope scope))))
2324 result))
2325
2326 (defun js2-scope-get-symbol (scope name)
2327 "Return symbol table entry for NAME in SCOPE.
2328 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2329 (and (js2-scope-symbol-table scope)
2330 (cdr (assq (if (symbolp name)
2331 name
2332 (intern name))
2333 (js2-scope-symbol-table scope)))))
2334
2335 (defun js2-scope-put-symbol (scope name symbol)
2336 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2337 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2338 (let* ((table (js2-scope-symbol-table scope))
2339 (sym (if (symbolp name) name (intern name)))
2340 (entry (assq sym table)))
2341 (if entry
2342 (setcdr entry symbol)
2343 (push (cons sym symbol)
2344 (js2-scope-symbol-table scope)))))
2345
2346 (cl-defstruct (js2-symbol
2347 (:constructor nil)
2348 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2349 "A symbol table entry."
2350 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2351 ;; js2-LET, or js2-CONST
2352 decl-type
2353 name ; string
2354 ast-node) ; a `js2-node'
2355
2356 (cl-defstruct (js2-error-node
2357 (:include js2-node)
2358 (:constructor nil) ; silence emacs21 byte-compiler
2359 (:constructor make-js2-error-node (&key (type js2-ERROR)
2360 (pos (js2-current-token-beg))
2361 len)))
2362 "AST node representing a parse error.")
2363
2364 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2365 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2366
2367 (cl-defstruct (js2-script-node
2368 (:include js2-scope)
2369 (:constructor nil)
2370 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2371 (pos (js2-current-token-beg))
2372 len
2373 ;; FIXME: What are those?
2374 var-decls
2375 fun-decls)))
2376 functions ; Lisp list of nested functions
2377 regexps ; Lisp list of (string . flags)
2378 symbols ; alist (every symbol gets unique index)
2379 (param-count 0)
2380 var-names ; vector of string names
2381 consts ; bool-vector matching var-decls
2382 (temp-number 0)) ; for generating temp variables
2383
2384 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2385 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2386
2387 (defun js2-print-script (node indent)
2388 (dolist (kid (js2-block-node-kids node))
2389 (js2-print-ast kid indent)))
2390
2391 (cl-defstruct (js2-ast-root
2392 (:include js2-script-node)
2393 (:constructor nil)
2394 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2395 (pos (js2-current-token-beg))
2396 len
2397 buffer)))
2398 "The root node of a js2 AST."
2399 buffer ; the source buffer from which the code was parsed
2400 comments ; a Lisp list of comments, ordered by start position
2401 errors ; a Lisp list of errors found during parsing
2402 warnings ; a Lisp list of warnings found during parsing
2403 node-count) ; number of nodes in the tree, including the root
2404
2405 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2406 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2407
2408 (defun js2-visit-ast-root (ast callback)
2409 (dolist (kid (js2-ast-root-kids ast))
2410 (js2-visit-ast kid callback))
2411 (dolist (comment (js2-ast-root-comments ast))
2412 (js2-visit-ast comment callback)))
2413
2414 (cl-defstruct (js2-comment-node
2415 (:include js2-node)
2416 (:constructor nil)
2417 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2418 (pos (js2-current-token-beg))
2419 len
2420 format)))
2421 format) ; 'line, 'block, 'jsdoc or 'html
2422
2423 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2424 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2425
2426 (defun js2-print-comment (n i)
2427 ;; We really ought to link end-of-line comments to their nodes.
2428 ;; Or maybe we could add a new comment type, 'endline.
2429 (insert (js2-make-pad i)
2430 (js2-node-string n)))
2431
2432 (cl-defstruct (js2-expr-stmt-node
2433 (:include js2-node)
2434 (:constructor nil)
2435 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2436 (pos js2-ts-cursor)
2437 len
2438 expr)))
2439 "An expression statement."
2440 expr)
2441
2442 (defsubst js2-expr-stmt-node-set-has-result (node)
2443 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2444 (setf (js2-node-type node) js2-EXPR_RESULT))
2445
2446 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2447 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2448
2449 (defun js2-visit-expr-stmt-node (n v)
2450 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2451
2452 (defun js2-print-expr-stmt-node (n indent)
2453 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2454 (insert ";\n"))
2455
2456 (cl-defstruct (js2-loop-node
2457 (:include js2-scope)
2458 (:constructor nil))
2459 "Abstract supertype of loop nodes."
2460 body ; a `js2-block-node'
2461 lp ; position of left-paren, nil if omitted
2462 rp) ; position of right-paren, nil if omitted
2463
2464 (cl-defstruct (js2-do-node
2465 (:include js2-loop-node)
2466 (:constructor nil)
2467 (:constructor make-js2-do-node (&key (type js2-DO)
2468 (pos (js2-current-token-beg))
2469 len
2470 body
2471 condition
2472 while-pos
2473 lp
2474 rp)))
2475 "AST node for do-loop."
2476 condition ; while (expression)
2477 while-pos) ; buffer position of 'while' keyword
2478
2479 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2480 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2481
2482 (defun js2-visit-do-node (n v)
2483 (js2-visit-ast (js2-do-node-body n) v)
2484 (js2-visit-ast (js2-do-node-condition n) v))
2485
2486 (defun js2-print-do-node (n i)
2487 (let ((pad (js2-make-pad i)))
2488 (insert pad "do {\n")
2489 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2490 (js2-print-ast kid (1+ i)))
2491 (insert pad "} while (")
2492 (js2-print-ast (js2-do-node-condition n) 0)
2493 (insert ");\n")))
2494
2495 (cl-defstruct (js2-export-node
2496 (:include js2-node)
2497 (:constructor nil)
2498 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2499 (pos (js2-current-token-beg))
2500 len
2501 exports-list
2502 from-clause
2503 declaration
2504 default)))
2505 "AST node for an export statement. There are many things that can be exported,
2506 so many of its properties will be nil.
2507 "
2508 exports-list ; lisp list of js2-export-binding-node to export
2509 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2510 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2511 default) ; js2-function-node or js2-assign-node
2512
2513 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2514 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2515
2516 (defun js2-visit-export-node (n v)
2517 (let ((exports-list (js2-export-node-exports-list n))
2518 (from (js2-export-node-from-clause n))
2519 (declaration (js2-export-node-declaration n))
2520 (default (js2-export-node-default n)))
2521 (when exports-list
2522 (dolist (export exports-list)
2523 (js2-visit-ast export v)))
2524 (when from
2525 (js2-visit-ast from v))
2526 (when declaration
2527 (js2-visit-ast declaration v))
2528 (when default
2529 (js2-visit-ast default v))))
2530
2531 (defun js2-print-export-node (n i)
2532 (let ((pad (js2-make-pad i))
2533 (exports-list (js2-export-node-exports-list n))
2534 (from (js2-export-node-from-clause n))
2535 (declaration (js2-export-node-declaration n))
2536 (default (js2-export-node-default n)))
2537 (insert pad "export ")
2538 (cond
2539 (default
2540 (insert "default ")
2541 (js2-print-ast default i))
2542 (declaration
2543 (js2-print-ast declaration i))
2544 ((and exports-list from)
2545 (js2-print-named-imports exports-list)
2546 (insert " ")
2547 (js2-print-from-clause from))
2548 (from
2549 (insert "* ")
2550 (js2-print-from-clause from))
2551 (exports-list
2552 (js2-print-named-imports exports-list)))
2553 (insert ";\n")))
2554
2555 (cl-defstruct (js2-while-node
2556 (:include js2-loop-node)
2557 (:constructor nil)
2558 (:constructor make-js2-while-node (&key (type js2-WHILE)
2559 (pos (js2-current-token-beg))
2560 len body
2561 condition lp
2562 rp)))
2563 "AST node for while-loop."
2564 condition) ; while-condition
2565
2566 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2567 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2568
2569 (defun js2-visit-while-node (n v)
2570 (js2-visit-ast (js2-while-node-condition n) v)
2571 (js2-visit-ast (js2-while-node-body n) v))
2572
2573 (defun js2-print-while-node (n i)
2574 (let ((pad (js2-make-pad i)))
2575 (insert pad "while (")
2576 (js2-print-ast (js2-while-node-condition n) 0)
2577 (insert ") {\n")
2578 (js2-print-body (js2-while-node-body n) (1+ i))
2579 (insert pad "}\n")))
2580
2581 (cl-defstruct (js2-for-node
2582 (:include js2-loop-node)
2583 (:constructor nil)
2584 (:constructor make-js2-for-node (&key (type js2-FOR)
2585 (pos js2-ts-cursor)
2586 len body init
2587 condition
2588 update lp rp)))
2589 "AST node for a C-style for-loop."
2590 init ; initialization expression
2591 condition ; loop condition
2592 update) ; update clause
2593
2594 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2595 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2596
2597 (defun js2-visit-for-node (n v)
2598 (js2-visit-ast (js2-for-node-init n) v)
2599 (js2-visit-ast (js2-for-node-condition n) v)
2600 (js2-visit-ast (js2-for-node-update n) v)
2601 (js2-visit-ast (js2-for-node-body n) v))
2602
2603 (defun js2-print-for-node (n i)
2604 (let ((pad (js2-make-pad i)))
2605 (insert pad "for (")
2606 (js2-print-ast (js2-for-node-init n) 0)
2607 (insert "; ")
2608 (js2-print-ast (js2-for-node-condition n) 0)
2609 (insert "; ")
2610 (js2-print-ast (js2-for-node-update n) 0)
2611 (insert ") {\n")
2612 (js2-print-body (js2-for-node-body n) (1+ i))
2613 (insert pad "}\n")))
2614
2615 (cl-defstruct (js2-for-in-node
2616 (:include js2-loop-node)
2617 (:constructor nil)
2618 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2619 (pos js2-ts-cursor)
2620 len body
2621 iterator
2622 object
2623 in-pos
2624 each-pos
2625 foreach-p forof-p
2626 lp rp)))
2627 "AST node for a for..in loop."
2628 iterator ; [var] foo in ...
2629 object ; object over which we're iterating
2630 in-pos ; buffer position of 'in' keyword
2631 each-pos ; buffer position of 'each' keyword, if foreach-p
2632 foreach-p ; t if it's a for-each loop
2633 forof-p) ; t if it's a for-of loop
2634
2635 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2636 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2637
2638 (defun js2-visit-for-in-node (n v)
2639 (js2-visit-ast (js2-for-in-node-iterator n) v)
2640 (js2-visit-ast (js2-for-in-node-object n) v)
2641 (js2-visit-ast (js2-for-in-node-body n) v))
2642
2643 (defun js2-print-for-in-node (n i)
2644 (let ((pad (js2-make-pad i))
2645 (foreach (js2-for-in-node-foreach-p n))
2646 (forof (js2-for-in-node-forof-p n)))
2647 (insert pad "for ")
2648 (if foreach
2649 (insert "each "))
2650 (insert "(")
2651 (js2-print-ast (js2-for-in-node-iterator n) 0)
2652 (insert (if forof " of " " in "))
2653 (js2-print-ast (js2-for-in-node-object n) 0)
2654 (insert ") {\n")
2655 (js2-print-body (js2-for-in-node-body n) (1+ i))
2656 (insert pad "}\n")))
2657
2658 (cl-defstruct (js2-return-node
2659 (:include js2-node)
2660 (:constructor nil)
2661 (:constructor make-js2-return-node (&key (type js2-RETURN)
2662 (pos js2-ts-cursor)
2663 len
2664 retval)))
2665 "AST node for a return statement."
2666 retval) ; expression to return, or 'undefined
2667
2668 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2669 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2670
2671 (defun js2-visit-return-node (n v)
2672 (js2-visit-ast (js2-return-node-retval n) v))
2673
2674 (defun js2-print-return-node (n i)
2675 (insert (js2-make-pad i) "return")
2676 (when (js2-return-node-retval n)
2677 (insert " ")
2678 (js2-print-ast (js2-return-node-retval n) 0))
2679 (insert ";\n"))
2680
2681 (cl-defstruct (js2-if-node
2682 (:include js2-node)
2683 (:constructor nil)
2684 (:constructor make-js2-if-node (&key (type js2-IF)
2685 (pos js2-ts-cursor)
2686 len condition
2687 then-part
2688 else-pos
2689 else-part lp
2690 rp)))
2691 "AST node for an if-statement."
2692 condition ; expression
2693 then-part ; statement or block
2694 else-pos ; optional buffer position of 'else' keyword
2695 else-part ; optional statement or block
2696 lp ; position of left-paren, nil if omitted
2697 rp) ; position of right-paren, nil if omitted
2698
2699 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2700 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2701
2702 (defun js2-visit-if-node (n v)
2703 (js2-visit-ast (js2-if-node-condition n) v)
2704 (js2-visit-ast (js2-if-node-then-part n) v)
2705 (js2-visit-ast (js2-if-node-else-part n) v))
2706
2707 (defun js2-print-if-node (n i)
2708 (let ((pad (js2-make-pad i))
2709 (then-part (js2-if-node-then-part n))
2710 (else-part (js2-if-node-else-part n)))
2711 (insert pad "if (")
2712 (js2-print-ast (js2-if-node-condition n) 0)
2713 (insert ") {\n")
2714 (js2-print-body then-part (1+ i))
2715 (insert pad "}")
2716 (cond
2717 ((not else-part)
2718 (insert "\n"))
2719 ((js2-if-node-p else-part)
2720 (insert " else ")
2721 (js2-print-body else-part i))
2722 (t
2723 (insert " else {\n")
2724 (js2-print-body else-part (1+ i))
2725 (insert pad "}\n")))))
2726
2727 (cl-defstruct (js2-export-binding-node
2728 (:include js2-node)
2729 (:constructor nil)
2730 (:constructor make-js2-export-binding-node (&key (type -1)
2731 pos
2732 len
2733 local-name
2734 extern-name)))
2735 "AST node for an external symbol binding.
2736 It contains a local-name node which is the name of the value in the
2737 current scope, and extern-name which is the name of the value in the
2738 imported or exported scope. By default these are the same, but if the
2739 name is aliased as in {foo as bar}, it would have an extern-name node
2740 containing 'foo' and a local-name node containing 'bar'."
2741 local-name ; js2-name-node with the variable name in this scope
2742 extern-name) ; js2-name-node with the value name in the exporting module
2743
2744 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2745 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2746
2747 (defun js2-visit-extern-binding (n v)
2748 "Visit an extern binding node. First visit the local-name, and, if
2749 different, visit the extern-name."
2750 (let ((local-name (js2-export-binding-node-local-name n))
2751 (extern-name (js2-export-binding-node-extern-name n)))
2752 (when local-name
2753 (js2-visit-ast local-name v))
2754 (when (not (equal local-name extern-name))
2755 (js2-visit-ast extern-name v))))
2756
2757 (defun js2-print-extern-binding (n _i)
2758 "Print a representation of a single extern binding. E.g. 'foo' or
2759 'foo as bar'."
2760 (let ((local-name (js2-export-binding-node-local-name n))
2761 (extern-name (js2-export-binding-node-extern-name n)))
2762 (insert (js2-name-node-name extern-name))
2763 (when (not (equal local-name extern-name))
2764 (insert " as ")
2765 (insert (js2-name-node-name local-name)))))
2766
2767
2768 (cl-defstruct (js2-import-node
2769 (:include js2-node)
2770 (:constructor nil)
2771 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2772 (pos (js2-current-token-beg))
2773 len
2774 import
2775 from
2776 module-id)))
2777 "AST node for an import statement. It follows the form
2778
2779 import ModuleSpecifier;
2780 import ImportClause FromClause;"
2781 import ; js2-import-clause-node specifying which names are to imported.
2782 from ; js2-from-clause-node indicating the module from which to import.
2783 module-id) ; module-id of the import. E.g. 'src/mylib'.
2784
2785 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2786 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2787
2788 (defun js2-visit-import (n v)
2789 (let ((import-clause (js2-import-node-import n))
2790 (from-clause (js2-import-node-from n)))
2791 (when import-clause
2792 (js2-visit-ast import-clause v))
2793 (when from-clause
2794 (js2-visit-ast from-clause v))))
2795
2796 (defun js2-print-import (n i)
2797 "Prints a representation of the import node"
2798 (let ((pad (js2-make-pad i))
2799 (import-clause (js2-import-node-import n))
2800 (from-clause (js2-import-node-from n))
2801 (module-id (js2-import-node-module-id n)))
2802 (insert pad "import ")
2803 (if import-clause
2804 (progn
2805 (js2-print-import-clause import-clause)
2806 (insert " ")
2807 (js2-print-from-clause from-clause))
2808 (insert "'")
2809 (insert module-id)
2810 (insert "'"))
2811 (insert ";\n")))
2812
2813 (cl-defstruct (js2-import-clause-node
2814 (:include js2-node)
2815 (:constructor nil)
2816 (:constructor make-js2-import-clause-node (&key (type -1)
2817 pos
2818 len
2819 namespace-import
2820 named-imports
2821 default-binding)))
2822 "AST node corresponding to the import clause of an import statement. This is
2823 the portion of the import that bindings names from the external context to the
2824 local context."
2825 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2826 named-imports ; lisp list of js2-export-binding-node for all named imports.
2827 default-binding) ; js2-export-binding-node for the default import binding
2828
2829 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2830 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2831
2832 (defun js2-visit-import-clause (n v)
2833 (let ((ns-import (js2-import-clause-node-namespace-import n))
2834 (named-imports (js2-import-clause-node-named-imports n))
2835 (default (js2-import-clause-node-default-binding n)))
2836 (when ns-import
2837 (js2-visit-ast ns-import v))
2838 (when named-imports
2839 (dolist (import named-imports)
2840 (js2-visit-ast import v)))
2841 (when default
2842 (js2-visit-ast default v))))
2843
2844 (defun js2-print-import-clause (n)
2845 (let ((ns-import (js2-import-clause-node-namespace-import n))
2846 (named-imports (js2-import-clause-node-named-imports n))
2847 (default (js2-import-clause-node-default-binding n)))
2848 (cond
2849 ((and default ns-import)
2850 (js2-print-ast default)
2851 (insert ", ")
2852 (js2-print-namespace-import ns-import))
2853 ((and default named-imports)
2854 (js2-print-ast default)
2855 (insert ", ")
2856 (js2-print-named-imports named-imports))
2857 (default
2858 (js2-print-ast default))
2859 (ns-import
2860 (js2-print-namespace-import ns-import))
2861 (named-imports
2862 (js2-print-named-imports named-imports)))))
2863
2864 (defun js2-print-namespace-import (node)
2865 (insert "* as ")
2866 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2867
2868 (defun js2-print-named-imports (imports)
2869 (insert "{")
2870 (let ((len (length imports))
2871 (n 0))
2872 (while (< n len)
2873 (js2-print-extern-binding (nth n imports) 0)
2874 (unless (= n (- len 1))
2875 (insert ", "))
2876 (setq n (+ n 1))))
2877 (insert "}"))
2878
2879 (cl-defstruct (js2-namespace-import-node
2880 (:include js2-node)
2881 (:constructor nil)
2882 (:constructor make-js2-namespace-import-node (&key (type -1)
2883 pos
2884 len
2885 name)))
2886 "AST node for a complete namespace import.
2887 E.g. the '* as lib' expression in:
2888
2889 import * as lib from 'src/lib'
2890
2891 It contains a single name node referring to the bound name."
2892 name) ; js2-name-node of the bound name.
2893
2894 (defun js2-visit-namespace-import (n v)
2895 (js2-visit-ast (js2-namespace-import-node-name n) v))
2896
2897 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2898 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2899
2900 (cl-defstruct (js2-from-clause-node
2901 (:include js2-node)
2902 (:constructor nil)
2903 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2904 pos
2905 len
2906 module-id
2907 metadata-p)))
2908 "AST node for the from clause in an import or export statement.
2909 E.g. from 'my/module'. It can refere to either an external module, or to the
2910 modules metadata itself."
2911 module-id ; string containing the module specifier.
2912 metadata-p) ; true if this clause refers to the module's metadata
2913
2914 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2915 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2916
2917 (defun js2-print-from-clause (n)
2918 (insert "from ")
2919 (if (js2-from-clause-node-metadata-p n)
2920 (insert "this module")
2921 (insert "'")
2922 (insert (js2-from-clause-node-module-id n))
2923 (insert "'")))
2924
2925 (cl-defstruct (js2-try-node
2926 (:include js2-node)
2927 (:constructor nil)
2928 (:constructor make-js2-try-node (&key (type js2-TRY)
2929 (pos js2-ts-cursor)
2930 len
2931 try-block
2932 catch-clauses
2933 finally-block)))
2934 "AST node for a try-statement."
2935 try-block
2936 catch-clauses ; a Lisp list of `js2-catch-node'
2937 finally-block) ; a `js2-finally-node'
2938
2939 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2940 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2941
2942 (defun js2-visit-try-node (n v)
2943 (js2-visit-ast (js2-try-node-try-block n) v)
2944 (dolist (clause (js2-try-node-catch-clauses n))
2945 (js2-visit-ast clause v))
2946 (js2-visit-ast (js2-try-node-finally-block n) v))
2947
2948 (defun js2-print-try-node (n i)
2949 (let ((pad (js2-make-pad i))
2950 (catches (js2-try-node-catch-clauses n))
2951 (finally (js2-try-node-finally-block n)))
2952 (insert pad "try {\n")
2953 (js2-print-body (js2-try-node-try-block n) (1+ i))
2954 (insert pad "}")
2955 (when catches
2956 (dolist (catch catches)
2957 (js2-print-ast catch i)))
2958 (if finally
2959 (js2-print-ast finally i)
2960 (insert "\n"))))
2961
2962 (cl-defstruct (js2-catch-node
2963 (:include js2-scope)
2964 (:constructor nil)
2965 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2966 (pos js2-ts-cursor)
2967 len
2968 param
2969 guard-kwd
2970 guard-expr
2971 lp rp)))
2972 "AST node for a catch clause."
2973 param ; destructuring form or simple name node
2974 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2975 guard-expr ; catch condition, a `js2-node'
2976 lp ; buffer position of left-paren, nil if omitted
2977 rp) ; buffer position of right-paren, nil if omitted
2978
2979 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2980 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2981
2982 (defun js2-visit-catch-node (n v)
2983 (js2-visit-ast (js2-catch-node-param n) v)
2984 (when (js2-catch-node-guard-kwd n)
2985 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2986 (js2-visit-block n v))
2987
2988 (defun js2-print-catch-node (n i)
2989 (let ((pad (js2-make-pad i))
2990 (guard-kwd (js2-catch-node-guard-kwd n))
2991 (guard-expr (js2-catch-node-guard-expr n)))
2992 (insert " catch (")
2993 (js2-print-ast (js2-catch-node-param n) 0)
2994 (when guard-kwd
2995 (insert " if ")
2996 (js2-print-ast guard-expr 0))
2997 (insert ") {\n")
2998 (js2-print-body n (1+ i))
2999 (insert pad "}")))
3000
3001 (cl-defstruct (js2-finally-node
3002 (:include js2-node)
3003 (:constructor nil)
3004 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3005 (pos js2-ts-cursor)
3006 len body)))
3007 "AST node for a finally clause."
3008 body) ; a `js2-node', often but not always a block node
3009
3010 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3011 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3012
3013 (defun js2-visit-finally-node (n v)
3014 (js2-visit-ast (js2-finally-node-body n) v))
3015
3016 (defun js2-print-finally-node (n i)
3017 (let ((pad (js2-make-pad i)))
3018 (insert " finally {\n")
3019 (js2-print-body (js2-finally-node-body n) (1+ i))
3020 (insert pad "}\n")))
3021
3022 (cl-defstruct (js2-switch-node
3023 (:include js2-node)
3024 (:constructor nil)
3025 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3026 (pos js2-ts-cursor)
3027 len
3028 discriminant
3029 cases lp
3030 rp)))
3031 "AST node for a switch statement."
3032 discriminant ; a `js2-node' (switch expression)
3033 cases ; a Lisp list of `js2-case-node'
3034 lp ; position of open-paren for discriminant, nil if omitted
3035 rp) ; position of close-paren for discriminant, nil if omitted
3036
3037 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3038 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3039
3040 (defun js2-visit-switch-node (n v)
3041 (js2-visit-ast (js2-switch-node-discriminant n) v)
3042 (dolist (c (js2-switch-node-cases n))
3043 (js2-visit-ast c v)))
3044
3045 (defun js2-print-switch-node (n i)
3046 (let ((pad (js2-make-pad i))
3047 (cases (js2-switch-node-cases n)))
3048 (insert pad "switch (")
3049 (js2-print-ast (js2-switch-node-discriminant n) 0)
3050 (insert ") {\n")
3051 (dolist (case cases)
3052 (js2-print-ast case i))
3053 (insert pad "}\n")))
3054
3055 (cl-defstruct (js2-case-node
3056 (:include js2-block-node)
3057 (:constructor nil)
3058 (:constructor make-js2-case-node (&key (type js2-CASE)
3059 (pos js2-ts-cursor)
3060 len kids expr)))
3061 "AST node for a case clause of a switch statement."
3062 expr) ; the case expression (nil for default)
3063
3064 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3065 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3066
3067 (defun js2-visit-case-node (n v)
3068 (js2-visit-ast (js2-case-node-expr n) v)
3069 (js2-visit-block n v))
3070
3071 (defun js2-print-case-node (n i)
3072 (let ((pad (js2-make-pad i))
3073 (expr (js2-case-node-expr n)))
3074 (insert pad)
3075 (if (null expr)
3076 (insert "default:\n")
3077 (insert "case ")
3078 (js2-print-ast expr 0)
3079 (insert ":\n"))
3080 (dolist (kid (js2-case-node-kids n))
3081 (js2-print-ast kid (1+ i)))))
3082
3083 (cl-defstruct (js2-throw-node
3084 (:include js2-node)
3085 (:constructor nil)
3086 (:constructor make-js2-throw-node (&key (type js2-THROW)
3087 (pos js2-ts-cursor)
3088 len expr)))
3089 "AST node for a throw statement."
3090 expr) ; the expression to throw
3091
3092 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3093 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3094
3095 (defun js2-visit-throw-node (n v)
3096 (js2-visit-ast (js2-throw-node-expr n) v))
3097
3098 (defun js2-print-throw-node (n i)
3099 (insert (js2-make-pad i) "throw ")
3100 (js2-print-ast (js2-throw-node-expr n) 0)
3101 (insert ";\n"))
3102
3103 (cl-defstruct (js2-with-node
3104 (:include js2-node)
3105 (:constructor nil)
3106 (:constructor make-js2-with-node (&key (type js2-WITH)
3107 (pos js2-ts-cursor)
3108 len object
3109 body lp rp)))
3110 "AST node for a with-statement."
3111 object
3112 body
3113 lp ; buffer position of left-paren around object, nil if omitted
3114 rp) ; buffer position of right-paren around object, nil if omitted
3115
3116 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3117 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3118
3119 (defun js2-visit-with-node (n v)
3120 (js2-visit-ast (js2-with-node-object n) v)
3121 (js2-visit-ast (js2-with-node-body n) v))
3122
3123 (defun js2-print-with-node (n i)
3124 (let ((pad (js2-make-pad i)))
3125 (insert pad "with (")
3126 (js2-print-ast (js2-with-node-object n) 0)
3127 (insert ") {\n")
3128 (js2-print-body (js2-with-node-body n) (1+ i))
3129 (insert pad "}\n")))
3130
3131 (cl-defstruct (js2-label-node
3132 (:include js2-node)
3133 (:constructor nil)
3134 (:constructor make-js2-label-node (&key (type js2-LABEL)
3135 (pos js2-ts-cursor)
3136 len name)))
3137 "AST node for a statement label or case label."
3138 name ; a string
3139 loop) ; for validating and code-generating continue-to-label
3140
3141 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3142 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3143
3144 (defun js2-print-label (n i)
3145 (insert (js2-make-pad i)
3146 (js2-label-node-name n)
3147 ":\n"))
3148
3149 (cl-defstruct (js2-labeled-stmt-node
3150 (:include js2-node)
3151 (:constructor nil)
3152 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3153 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3154 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3155 (pos js2-ts-cursor)
3156 len labels stmt)))
3157 "AST node for a statement with one or more labels.
3158 Multiple labels for a statement are collapsed into the labels field."
3159 labels ; Lisp list of `js2-label-node'
3160 stmt) ; the statement these labels are for
3161
3162 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3163 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3164
3165 (defun js2-get-label-by-name (lbl-stmt name)
3166 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3167 Returns nil if no such label is in the list."
3168 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3169 result)
3170 (while (and label-list (not result))
3171 (if (string= (js2-label-node-name (car label-list)) name)
3172 (setq result (car label-list))
3173 (setq label-list (cdr label-list))))
3174 result))
3175
3176 (defun js2-visit-labeled-stmt (n v)
3177 (dolist (label (js2-labeled-stmt-node-labels n))
3178 (js2-visit-ast label v))
3179 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3180
3181 (defun js2-print-labeled-stmt (n i)
3182 (dolist (label (js2-labeled-stmt-node-labels n))
3183 (js2-print-ast label i))
3184 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3185
3186 (defun js2-labeled-stmt-node-contains (node label)
3187 "Return t if NODE contains LABEL in its label set.
3188 NODE is a `js2-labels-node'. LABEL is an identifier."
3189 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3190 if (string= label (js2-label-node-name nl))
3191 return t
3192 finally return nil))
3193
3194 (defsubst js2-labeled-stmt-node-add-label (node label)
3195 "Add a `js2-label-node' to the label set for this statement."
3196 (setf (js2-labeled-stmt-node-labels node)
3197 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3198
3199 (cl-defstruct (js2-jump-node
3200 (:include js2-node)
3201 (:constructor nil))
3202 "Abstract supertype of break and continue nodes."
3203 label ; `js2-name-node' for location of label identifier, if present
3204 target) ; target js2-labels-node or loop/switch statement
3205
3206 (defun js2-visit-jump-node (n v)
3207 ;; We don't visit the target, since it's a back-link.
3208 (js2-visit-ast (js2-jump-node-label n) v))
3209
3210 (cl-defstruct (js2-break-node
3211 (:include js2-jump-node)
3212 (:constructor nil)
3213 (:constructor make-js2-break-node (&key (type js2-BREAK)
3214 (pos js2-ts-cursor)
3215 len label target)))
3216 "AST node for a break statement.
3217 The label field is a `js2-name-node', possibly nil, for the named label
3218 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3219 is the target of the break - a label node or enclosing loop/switch statement.")
3220
3221 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3222 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3223
3224 (defun js2-print-break-node (n i)
3225 (insert (js2-make-pad i) "break")
3226 (when (js2-break-node-label n)
3227 (insert " ")
3228 (js2-print-ast (js2-break-node-label n) 0))
3229 (insert ";\n"))
3230
3231 (cl-defstruct (js2-continue-node
3232 (:include js2-jump-node)
3233 (:constructor nil)
3234 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3235 (pos js2-ts-cursor)
3236 len label target)))
3237 "AST node for a continue statement.
3238 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3239 It is nil if continue specifies no label. The target field is the jump target:
3240 a `js2-label-node' or the innermost enclosing loop.")
3241
3242 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3243 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3244
3245 (defun js2-print-continue-node (n i)
3246 (insert (js2-make-pad i) "continue")
3247 (when (js2-continue-node-label n)
3248 (insert " ")
3249 (js2-print-ast (js2-continue-node-label n) 0))
3250 (insert ";\n"))
3251
3252 (cl-defstruct (js2-function-node
3253 (:include js2-script-node)
3254 (:constructor nil)
3255 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3256 (pos js2-ts-cursor)
3257 len
3258 (ftype 'FUNCTION)
3259 (form 'FUNCTION_STATEMENT)
3260 (name "")
3261 params rest-p
3262 body
3263 generator-type
3264 async
3265 lp rp)))
3266 "AST node for a function declaration.
3267 The `params' field is a Lisp list of nodes. Each node is either a simple
3268 `js2-name-node', or if it's a destructuring-assignment parameter, a
3269 `js2-array-node' or `js2-object-node'."
3270 ftype ; FUNCTION, GETTER or SETTER
3271 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3272 name ; function name (a `js2-name-node', or nil if anonymous)
3273 params ; a Lisp list of destructuring forms or simple name nodes
3274 rest-p ; if t, the last parameter is rest parameter
3275 body ; a `js2-block-node' or expression node (1.8 only)
3276 lp ; position of arg-list open-paren, or nil if omitted
3277 rp ; position of arg-list close-paren, or nil if omitted
3278 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3279 needs-activation ; t if we need an activation object for this frame
3280 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3281 async ; t if the function is defined as `async function`
3282 member-expr) ; nonstandard Ecma extension from Rhino
3283
3284 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3285 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3286
3287 (defun js2-visit-function-node (n v)
3288 (js2-visit-ast (js2-function-node-name n) v)
3289 (dolist (p (js2-function-node-params n))
3290 (js2-visit-ast p v))
3291 (js2-visit-ast (js2-function-node-body n) v))
3292
3293 (defun js2-print-function-node (n i)
3294 (let* ((pad (js2-make-pad i))
3295 (method (js2-node-get-prop n 'METHOD_TYPE))
3296 (name (or (js2-function-node-name n)
3297 (js2-function-node-member-expr n)))
3298 (params (js2-function-node-params n))
3299 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3300 (rest-p (js2-function-node-rest-p n))
3301 (body (js2-function-node-body n))
3302 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3303 (unless method
3304 (insert pad)
3305 (when (js2-function-node-async n) (insert "async "))
3306 (unless arrow (insert "function"))
3307 (when (eq (js2-function-node-generator-type n) 'STAR)
3308 (insert "*")))
3309 (when name
3310 (insert " ")
3311 (js2-print-ast name 0))
3312 (insert "(")
3313 (cl-loop with len = (length params)
3314 for param in params
3315 for count from 1
3316 do
3317 (when (and rest-p (= count len))
3318 (insert "..."))
3319 (js2-print-ast param 0)
3320 (when (< count len)
3321 (insert ", ")))
3322 (insert ") ")
3323 (when arrow
3324 (insert "=> "))
3325 (insert "{")
3326 ;; TODO: fix this to be smarter about indenting, etc.
3327 (unless expr
3328 (insert "\n"))
3329 (if (js2-block-node-p body)
3330 (js2-print-body body (1+ i))
3331 (js2-print-ast body 0))
3332 (insert pad "}")
3333 (unless expr
3334 (insert "\n"))))
3335
3336 (defun js2-function-name (node)
3337 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3338 (and (js2-function-node-name node)
3339 (js2-name-node-name (js2-function-node-name node))))
3340
3341 ;; Having this be an expression node makes it more flexible.
3342 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3343 ;; that work better if you assume it's an expression. Whenever we have
3344 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3345 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3346 (cl-defstruct (js2-var-decl-node
3347 (:include js2-node)
3348 (:constructor nil)
3349 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3350 (pos (js2-current-token-beg))
3351 len kids
3352 decl-type)))
3353 "AST node for a variable declaration list (VAR, CONST or LET).
3354 The node bounds differ depending on the declaration type. For VAR or
3355 CONST declarations, the bounds include the var/const keyword. For LET
3356 declarations, the node begins at the position of the first child."
3357 kids ; a Lisp list of `js2-var-init-node' structs.
3358 decl-type) ; js2-VAR, js2-CONST or js2-LET
3359
3360 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3361 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3362
3363 (defun js2-visit-var-decl (n v)
3364 (dolist (kid (js2-var-decl-node-kids n))
3365 (js2-visit-ast kid v)))
3366
3367 (defun js2-print-var-decl (n i)
3368 (let ((pad (js2-make-pad i))
3369 (tt (js2-var-decl-node-decl-type n)))
3370 (insert pad)
3371 (insert (cond
3372 ((= tt js2-VAR) "var ")
3373 ((= tt js2-LET) "let ")
3374 ((= tt js2-CONST) "const ")
3375 (t
3376 (error "malformed var-decl node"))))
3377 (cl-loop with kids = (js2-var-decl-node-kids n)
3378 with len = (length kids)
3379 for kid in kids
3380 for count from 1
3381 do
3382 (js2-print-ast kid 0)
3383 (if (< count len)
3384 (insert ", ")))))
3385
3386 (cl-defstruct (js2-var-init-node
3387 (:include js2-node)
3388 (:constructor nil)
3389 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3390 (pos js2-ts-cursor)
3391 len target
3392 initializer)))
3393 "AST node for a variable declaration.
3394 The type field will be js2-CONST for a const decl."
3395 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3396 initializer) ; initializer expression, a `js2-node'
3397
3398 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3399 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3400
3401 (defun js2-visit-var-init-node (n v)
3402 (js2-visit-ast (js2-var-init-node-target n) v)
3403 (js2-visit-ast (js2-var-init-node-initializer n) v))
3404
3405 (defun js2-print-var-init-node (n i)
3406 (let ((pad (js2-make-pad i))
3407 (name (js2-var-init-node-target n))
3408 (init (js2-var-init-node-initializer n)))
3409 (insert pad)
3410 (js2-print-ast name 0)
3411 (when init
3412 (insert " = ")
3413 (js2-print-ast init 0))))
3414
3415 (cl-defstruct (js2-cond-node
3416 (:include js2-node)
3417 (:constructor nil)
3418 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3419 (pos js2-ts-cursor)
3420 len
3421 test-expr
3422 true-expr
3423 false-expr
3424 q-pos c-pos)))
3425 "AST node for the ternary operator"
3426 test-expr
3427 true-expr
3428 false-expr
3429 q-pos ; buffer position of ?
3430 c-pos) ; buffer position of :
3431
3432 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3433 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3434
3435 (defun js2-visit-cond-node (n v)
3436 (js2-visit-ast (js2-cond-node-test-expr n) v)
3437 (js2-visit-ast (js2-cond-node-true-expr n) v)
3438 (js2-visit-ast (js2-cond-node-false-expr n) v))
3439
3440 (defun js2-print-cond-node (n i)
3441 (let ((pad (js2-make-pad i)))
3442 (insert pad)
3443 (js2-print-ast (js2-cond-node-test-expr n) 0)
3444 (insert " ? ")
3445 (js2-print-ast (js2-cond-node-true-expr n) 0)
3446 (insert " : ")
3447 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3448
3449 (cl-defstruct (js2-infix-node
3450 (:include js2-node)
3451 (:constructor nil)
3452 (:constructor make-js2-infix-node (&key type
3453 (pos js2-ts-cursor)
3454 len op-pos
3455 left right)))
3456 "Represents infix expressions.
3457 Includes assignment ops like `|=', and the comma operator.
3458 The type field inherited from `js2-node' holds the operator."
3459 op-pos ; buffer position where operator begins
3460 left ; any `js2-node'
3461 right) ; any `js2-node'
3462
3463 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3464 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3465
3466 (defun js2-visit-infix-node (n v)
3467 (js2-visit-ast (js2-infix-node-left n) v)
3468 (js2-visit-ast (js2-infix-node-right n) v))
3469
3470 (defconst js2-operator-tokens
3471 (let ((table (make-hash-table :test 'eq))
3472 (tokens
3473 (list (cons js2-IN "in")
3474 (cons js2-TYPEOF "typeof")
3475 (cons js2-INSTANCEOF "instanceof")
3476 (cons js2-DELPROP "delete")
3477 (cons js2-AWAIT "await")
3478 (cons js2-COMMA ",")
3479 (cons js2-COLON ":")
3480 (cons js2-OR "||")
3481 (cons js2-AND "&&")
3482 (cons js2-INC "++")
3483 (cons js2-DEC "--")
3484 (cons js2-BITOR "|")
3485 (cons js2-BITXOR "^")
3486 (cons js2-BITAND "&")
3487 (cons js2-EQ "==")
3488 (cons js2-NE "!=")
3489 (cons js2-LT "<")
3490 (cons js2-LE "<=")
3491 (cons js2-GT ">")
3492 (cons js2-GE ">=")
3493 (cons js2-LSH "<<")
3494 (cons js2-RSH ">>")
3495 (cons js2-URSH ">>>")
3496 (cons js2-ADD "+") ; infix plus
3497 (cons js2-SUB "-") ; infix minus
3498 (cons js2-MUL "*")
3499 (cons js2-DIV "/")
3500 (cons js2-MOD "%")
3501 (cons js2-NOT "!")
3502 (cons js2-BITNOT "~")
3503 (cons js2-POS "+") ; unary plus
3504 (cons js2-NEG "-") ; unary minus
3505 (cons js2-TRIPLEDOT "...")
3506 (cons js2-SHEQ "===") ; shallow equality
3507 (cons js2-SHNE "!==") ; shallow inequality
3508 (cons js2-ASSIGN "=")
3509 (cons js2-ASSIGN_BITOR "|=")
3510 (cons js2-ASSIGN_BITXOR "^=")
3511 (cons js2-ASSIGN_BITAND "&=")
3512 (cons js2-ASSIGN_LSH "<<=")
3513 (cons js2-ASSIGN_RSH ">>=")
3514 (cons js2-ASSIGN_URSH ">>>=")
3515 (cons js2-ASSIGN_ADD "+=")
3516 (cons js2-ASSIGN_SUB "-=")
3517 (cons js2-ASSIGN_MUL "*=")
3518 (cons js2-ASSIGN_DIV "/=")
3519 (cons js2-ASSIGN_MOD "%="))))
3520 (cl-loop for (k . v) in tokens do
3521 (puthash k v table))
3522 table))
3523
3524 (defun js2-print-infix-node (n i)
3525 (let* ((tt (js2-node-type n))
3526 (op (gethash tt js2-operator-tokens)))
3527 (unless op
3528 (error "unrecognized infix operator %s" (js2-node-type n)))
3529 (insert (js2-make-pad i))
3530 (js2-print-ast (js2-infix-node-left n) 0)
3531 (unless (= tt js2-COMMA)
3532 (insert " "))
3533 (insert op)
3534 (insert " ")
3535 (js2-print-ast (js2-infix-node-right n) 0)))
3536
3537 (cl-defstruct (js2-assign-node
3538 (:include js2-infix-node)
3539 (:constructor nil)
3540 (:constructor make-js2-assign-node (&key type
3541 (pos js2-ts-cursor)
3542 len op-pos
3543 left right)))
3544 "Represents any assignment.
3545 The type field holds the actual assignment operator.")
3546
3547 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3548 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3549
3550 (cl-defstruct (js2-unary-node
3551 (:include js2-node)
3552 (:constructor nil)
3553 (:constructor make-js2-unary-node (&key type ; required
3554 (pos js2-ts-cursor)
3555 len operand)))
3556 "AST node type for unary operator nodes.
3557 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3558 TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
3559 property is added if the operator follows the operand."
3560 operand) ; a `js2-node' expression
3561
3562 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3563 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3564
3565 (defun js2-visit-unary-node (n v)
3566 (js2-visit-ast (js2-unary-node-operand n) v))
3567
3568 (defun js2-print-unary-node (n i)
3569 (let* ((tt (js2-node-type n))
3570 (op (gethash tt js2-operator-tokens))
3571 (postfix (js2-node-get-prop n 'postfix)))
3572 (unless op
3573 (error "unrecognized unary operator %s" tt))
3574 (insert (js2-make-pad i))
3575 (unless postfix
3576 (insert op))
3577 (if (or (= tt js2-TYPEOF)
3578 (= tt js2-DELPROP)
3579 (= tt js2-AWAIT))
3580 (insert " "))
3581 (js2-print-ast (js2-unary-node-operand n) 0)
3582 (when postfix
3583 (insert op))))
3584
3585 (cl-defstruct (js2-let-node
3586 (:include js2-scope)
3587 (:constructor nil)
3588 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3589 (pos (js2-current-token-beg))
3590 len vars body
3591 lp rp)))
3592 "AST node for a let expression or a let statement.
3593 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3594 vars ; a `js2-var-decl-node'
3595 body ; a `js2-node' representing the expression or body block
3596 lp
3597 rp)
3598
3599 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3600 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3601
3602 (defun js2-visit-let-node (n v)
3603 (js2-visit-ast (js2-let-node-vars n) v)
3604 (js2-visit-ast (js2-let-node-body n) v))
3605
3606 (defun js2-print-let-node (n i)
3607 (insert (js2-make-pad i) "let (")
3608 (let ((p (point)))
3609 (js2-print-ast (js2-let-node-vars n) 0)
3610 (delete-region p (+ p 4)))
3611 (insert ") ")
3612 (js2-print-ast (js2-let-node-body n) i))
3613
3614 (cl-defstruct (js2-keyword-node
3615 (:include js2-node)
3616 (:constructor nil)
3617 (:constructor make-js2-keyword-node (&key type
3618 (pos (js2-current-token-beg))
3619 (len (- js2-ts-cursor pos)))))
3620 "AST node representing a literal keyword such as `null'.
3621 Used for `null', `this', `true', `false' and `debugger'.
3622 The node type is set to js2-NULL, js2-THIS, etc.")
3623
3624 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3625 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3626
3627 (defun js2-print-keyword-node (n i)
3628 (insert (js2-make-pad i)
3629 (let ((tt (js2-node-type n)))
3630 (cond
3631 ((= tt js2-THIS) "this")
3632 ((= tt js2-SUPER) "super")
3633 ((= tt js2-NULL) "null")
3634 ((= tt js2-TRUE) "true")
3635 ((= tt js2-FALSE) "false")
3636 ((= tt js2-DEBUGGER) "debugger")
3637 (t (error "Invalid keyword literal type: %d" tt))))))
3638
3639 (defsubst js2-this-or-super-node-p (node)
3640 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3641 (let ((type (js2-node-type node)))
3642 (or (eq type js2-THIS) (eq type js2-SUPER))))
3643
3644 (cl-defstruct (js2-new-node
3645 (:include js2-node)
3646 (:constructor nil)
3647 (:constructor make-js2-new-node (&key (type js2-NEW)
3648 (pos (js2-current-token-beg))
3649 len target
3650 args initializer
3651 lp rp)))
3652 "AST node for new-expression such as new Foo()."
3653 target ; an identifier or reference
3654 args ; a Lisp list of argument nodes
3655 lp ; position of left-paren, nil if omitted
3656 rp ; position of right-paren, nil if omitted
3657 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3658
3659 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3660 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3661
3662 (defun js2-visit-new-node (n v)
3663 (js2-visit-ast (js2-new-node-target n) v)
3664 (dolist (arg (js2-new-node-args n))
3665 (js2-visit-ast arg v))
3666 (js2-visit-ast (js2-new-node-initializer n) v))
3667
3668 (defun js2-print-new-node (n i)
3669 (insert (js2-make-pad i) "new ")
3670 (js2-print-ast (js2-new-node-target n))
3671 (insert "(")
3672 (js2-print-list (js2-new-node-args n))
3673 (insert ")")
3674 (when (js2-new-node-initializer n)
3675 (insert " ")
3676 (js2-print-ast (js2-new-node-initializer n))))
3677
3678 (cl-defstruct (js2-name-node
3679 (:include js2-node)
3680 (:constructor nil)
3681 (:constructor make-js2-name-node (&key (type js2-NAME)
3682 (pos (js2-current-token-beg))
3683 (len (- js2-ts-cursor
3684 (js2-current-token-beg)))
3685 (name (js2-current-token-string)))))
3686 "AST node for a JavaScript identifier"
3687 name ; a string
3688 scope) ; a `js2-scope' (optional, used for codegen)
3689
3690 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3691 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3692
3693 (defun js2-print-name-node (n i)
3694 (insert (js2-make-pad i)
3695 (js2-name-node-name n)))
3696
3697 (defsubst js2-name-node-length (node)
3698 "Return identifier length of NODE, a `js2-name-node'.
3699 Returns 0 if NODE is nil or its identifier field is nil."
3700 (if node
3701 (length (js2-name-node-name node))
3702 0))
3703
3704 (cl-defstruct (js2-number-node
3705 (:include js2-node)
3706 (:constructor nil)
3707 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3708 (pos (js2-current-token-beg))
3709 (len (- js2-ts-cursor
3710 (js2-current-token-beg)))
3711 (value (js2-current-token-string))
3712 (num-value (js2-token-number
3713 (js2-current-token)))
3714 (num-base (js2-token-number-base
3715 (js2-current-token))))))
3716 "AST node for a number literal."
3717 value ; the original string, e.g. "6.02e23"
3718 num-value ; the parsed number value
3719 num-base) ; the number's base
3720
3721 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3722 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3723
3724 (defun js2-print-number-node (n i)
3725 (insert (js2-make-pad i)
3726 (number-to-string (js2-number-node-num-value n))))
3727
3728 (cl-defstruct (js2-regexp-node
3729 (:include js2-node)
3730 (:constructor nil)
3731 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3732 (pos (js2-current-token-beg))
3733 (len (- js2-ts-cursor
3734 (js2-current-token-beg)))
3735 value flags)))
3736 "AST node for a regular expression literal."
3737 value ; the regexp string, without // delimiters
3738 flags) ; a string of flags, e.g. `mi'.
3739
3740 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3741 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3742
3743 (defun js2-print-regexp (n i)
3744 (insert (js2-make-pad i)
3745 "/"
3746 (js2-regexp-node-value n)
3747 "/")
3748 (if (js2-regexp-node-flags n)
3749 (insert (js2-regexp-node-flags n))))
3750
3751 (cl-defstruct (js2-string-node
3752 (:include js2-node)
3753 (:constructor nil)
3754 (:constructor make-js2-string-node (&key (type js2-STRING)
3755 (pos (js2-current-token-beg))
3756 (len (- js2-ts-cursor
3757 (js2-current-token-beg)))
3758 (value (js2-current-token-string)))))
3759 "String literal.
3760 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3761 You can tell the quote type by looking at the first character."
3762 value) ; the characters of the string, including the quotes
3763
3764 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3765 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3766
3767 (defun js2-print-string-node (n i)
3768 (insert (js2-make-pad i)
3769 (js2-node-string n)))
3770
3771 (cl-defstruct (js2-template-node
3772 (:include js2-node)
3773 (:constructor nil)
3774 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3775 beg len kids)))
3776 "Template literal."
3777 kids) ; `js2-string-node' is used for string segments, other nodes
3778 ; for substitutions inside.
3779
3780 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3781 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3782
3783 (defun js2-visit-template (n callback)
3784 (dolist (kid (js2-template-node-kids n))
3785 (js2-visit-ast kid callback)))
3786
3787 (defun js2-print-template (n i)
3788 (insert (js2-make-pad i))
3789 (dolist (kid (js2-template-node-kids n))
3790 (if (js2-string-node-p kid)
3791 (insert (js2-node-string kid))
3792 (js2-print-ast kid))))
3793
3794 (cl-defstruct (js2-tagged-template-node
3795 (:include js2-node)
3796 (:constructor nil)
3797 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3798 beg len tag template)))
3799 "Tagged template literal."
3800 tag ; `js2-node' with the tag expression.
3801 template) ; `js2-template-node' with the template.
3802
3803 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3804 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3805
3806 (defun js2-visit-tagged-template (n callback)
3807 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3808 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3809
3810 (defun js2-print-tagged-template (n i)
3811 (insert (js2-make-pad i))
3812 (js2-print-ast (js2-tagged-template-node-tag n))
3813 (js2-print-ast (js2-tagged-template-node-template n)))
3814
3815 (cl-defstruct (js2-array-node
3816 (:include js2-node)
3817 (:constructor nil)
3818 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3819 (pos js2-ts-cursor)
3820 len elems)))
3821 "AST node for an array literal."
3822 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3823
3824 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3825 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3826
3827 (defun js2-visit-array-node (n v)
3828 (dolist (e (js2-array-node-elems n))
3829 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3830
3831 (defun js2-print-array-node (n i)
3832 (insert (js2-make-pad i) "[")
3833 (let ((elems (js2-array-node-elems n)))
3834 (js2-print-list elems)
3835 (when (and elems (null (car (last elems))))
3836 (insert ",")))
3837 (insert "]"))
3838
3839 (cl-defstruct (js2-class-node
3840 (:include js2-node)
3841 (:constructor nil)
3842 (:constructor make-js2-class-node (&key (type js2-CLASS)
3843 (pos js2-ts-cursor)
3844 (form 'CLASS_STATEMENT)
3845 (name "")
3846 extends len elems)))
3847 "AST node for an class expression.
3848 `elems' is a list of `js2-object-prop-node', and `extends' is an
3849 optional `js2-expr-node'"
3850 form ; CLASS_{STATEMENT|EXPRESSION}
3851 name ; class name (a `js2-node-name', or nil if anonymous)
3852 extends ; class heritage (a `js2-expr-node', or nil if none)
3853 elems)
3854
3855 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3856 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3857
3858 (defun js2-visit-class-node (n v)
3859 (js2-visit-ast (js2-class-node-name n) v)
3860 (js2-visit-ast (js2-class-node-extends n) v)
3861 (dolist (e (js2-class-node-elems n))
3862 (js2-visit-ast e v)))
3863
3864 (defun js2-print-class-node (n i)
3865 (let* ((pad (js2-make-pad i))
3866 (name (js2-class-node-name n))
3867 (extends (js2-class-node-extends n))
3868 (elems (js2-class-node-elems n)))
3869 (insert pad "class")
3870 (when name
3871 (insert " ")
3872 (js2-print-ast name 0))
3873 (when extends
3874 (insert " extends ")
3875 (js2-print-ast extends))
3876 (insert " {")
3877 (dolist (elem elems)
3878 (insert "\n")
3879 (if (js2-node-get-prop elem 'STATIC)
3880 (progn (insert (js2-make-pad (1+ i)) "static ")
3881 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3882 (js2-print-ast elem (1+ i))))
3883 (insert "\n" pad "}")))
3884
3885 (cl-defstruct (js2-object-node
3886 (:include js2-node)
3887 (:constructor nil)
3888 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3889 (pos js2-ts-cursor)
3890 len
3891 elems)))
3892 "AST node for an object literal expression.
3893 `elems' is a list of `js2-object-prop-node'."
3894 elems)
3895
3896 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3897 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3898
3899 (defun js2-visit-object-node (n v)
3900 (dolist (e (js2-object-node-elems n))
3901 (js2-visit-ast e v)))
3902
3903 (defun js2-print-object-node (n i)
3904 (insert (js2-make-pad i) "{")
3905 (js2-print-list (js2-object-node-elems n))
3906 (insert "}"))
3907
3908 (cl-defstruct (js2-computed-prop-name-node
3909 (:include js2-node)
3910 (:constructor nil)
3911 (:constructor make-js2-computed-prop-name-node
3912 (&key
3913 (type js2-LB)
3914 expr
3915 (pos (js2-current-token-beg))
3916 (len (- js2-ts-cursor
3917 (js2-current-token-beg))))))
3918 "AST node for a `ComputedPropertyName'."
3919 expr)
3920
3921 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3922 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3923
3924 (defun js2-visit-computed-prop-name-node (n v)
3925 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3926
3927 (defun js2-print-computed-prop-name-node (n i)
3928 (insert (js2-make-pad i) "[")
3929 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3930 (insert "]"))
3931
3932 (cl-defstruct (js2-object-prop-node
3933 (:include js2-infix-node)
3934 (:constructor nil)
3935 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3936 (pos js2-ts-cursor)
3937 len left
3938 right op-pos)))
3939 "AST node for an object literal prop:value entry.
3940 The `left' field is the property: a name node, string node,
3941 number node or expression node. The `right' field is a
3942 `js2-node' representing the initializer value. If the property
3943 is abbreviated, the node's `SHORTHAND' property is non-nil and
3944 both fields have the same value.")
3945
3946 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3947 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3948
3949 (defun js2-print-object-prop-node (n i)
3950 (let* ((left (js2-object-prop-node-left n))
3951 (right (js2-object-prop-node-right n)))
3952 (js2-print-ast left i)
3953 (if (not (js2-node-get-prop n 'SHORTHAND))
3954 (progn
3955 (insert ": ")
3956 (js2-print-ast right 0)))))
3957
3958 (cl-defstruct (js2-method-node
3959 (:include js2-infix-node)
3960 (:constructor nil)
3961 (:constructor make-js2-method-node (&key type ; GET, SET, or FUNCTION
3962 (pos js2-ts-cursor)
3963 len left right)))
3964 "AST node for a method in an object literal or a class body.
3965 The `left' field is the `js2-name-node' naming the method.
3966 The `right' field is always an anonymous `js2-function-node' with a node
3967 property `METHOD_TYPE' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3968
3969 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3970 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3971
3972 (defun js2-print-method (n i)
3973 (let* ((pad (js2-make-pad i))
3974 (left (js2-method-node-left n))
3975 (right (js2-method-node-right n)))
3976 (insert pad)
3977 (if (/= (js2-node-type n) js2-FUNCTION)
3978 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3979 (when (and (js2-function-node-p right)
3980 (eq 'STAR (js2-function-node-generator-type right)))
3981 (insert "*"))
3982 (js2-print-ast left 0)
3983 (js2-print-ast right 0)))
3984
3985 (cl-defstruct (js2-prop-get-node
3986 (:include js2-infix-node)
3987 (:constructor nil)
3988 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3989 (pos js2-ts-cursor)
3990 len left right)))
3991 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3992
3993 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3994 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3995
3996 (defun js2-visit-prop-get-node (n v)
3997 (js2-visit-ast (js2-prop-get-node-left n) v)
3998 (js2-visit-ast (js2-prop-get-node-right n) v))
3999
4000 (defun js2-print-prop-get-node (n i)
4001 (insert (js2-make-pad i))
4002 (js2-print-ast (js2-prop-get-node-left n) 0)
4003 (insert ".")
4004 (js2-print-ast (js2-prop-get-node-right n) 0))
4005
4006 (cl-defstruct (js2-elem-get-node
4007 (:include js2-node)
4008 (:constructor nil)
4009 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4010 (pos js2-ts-cursor)
4011 len target element
4012 lb rb)))
4013 "AST node for an array index expression such as foo[bar]."
4014 target ; a `js2-node' - the expression preceding the "."
4015 element ; a `js2-node' - the expression in brackets
4016 lb ; position of left-bracket, nil if omitted
4017 rb) ; position of right-bracket, nil if omitted
4018
4019 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4020 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4021
4022 (defun js2-visit-elem-get-node (n v)
4023 (js2-visit-ast (js2-elem-get-node-target n) v)
4024 (js2-visit-ast (js2-elem-get-node-element n) v))
4025
4026 (defun js2-print-elem-get-node (n i)
4027 (insert (js2-make-pad i))
4028 (js2-print-ast (js2-elem-get-node-target n) 0)
4029 (insert "[")
4030 (js2-print-ast (js2-elem-get-node-element n) 0)
4031 (insert "]"))
4032
4033 (cl-defstruct (js2-call-node
4034 (:include js2-node)
4035 (:constructor nil)
4036 (:constructor make-js2-call-node (&key (type js2-CALL)
4037 (pos js2-ts-cursor)
4038 len target args
4039 lp rp)))
4040 "AST node for a JavaScript function call."
4041 target ; a `js2-node' evaluating to the function to call
4042 args ; a Lisp list of `js2-node' arguments
4043 lp ; position of open-paren, or nil if missing
4044 rp) ; position of close-paren, or nil if missing
4045
4046 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4047 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4048
4049 (defun js2-visit-call-node (n v)
4050 (js2-visit-ast (js2-call-node-target n) v)
4051 (dolist (arg (js2-call-node-args n))
4052 (js2-visit-ast arg v)))
4053
4054 (defun js2-print-call-node (n i)
4055 (insert (js2-make-pad i))
4056 (js2-print-ast (js2-call-node-target n) 0)
4057 (insert "(")
4058 (js2-print-list (js2-call-node-args n))
4059 (insert ")"))
4060
4061 (cl-defstruct (js2-yield-node
4062 (:include js2-node)
4063 (:constructor nil)
4064 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4065 (pos js2-ts-cursor)
4066 len value star-p)))
4067 "AST node for yield statement or expression."
4068 star-p ; whether it's yield*
4069 value) ; optional: value to be yielded
4070
4071 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4072 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4073
4074 (defun js2-visit-yield-node (n v)
4075 (js2-visit-ast (js2-yield-node-value n) v))
4076
4077 (defun js2-print-yield-node (n i)
4078 (insert (js2-make-pad i))
4079 (insert "yield")
4080 (when (js2-yield-node-star-p n)
4081 (insert "*"))
4082 (when (js2-yield-node-value n)
4083 (insert " ")
4084 (js2-print-ast (js2-yield-node-value n) 0)))
4085
4086 (cl-defstruct (js2-paren-node
4087 (:include js2-node)
4088 (:constructor nil)
4089 (:constructor make-js2-paren-node (&key (type js2-LP)
4090 (pos js2-ts-cursor)
4091 len expr)))
4092 "AST node for a parenthesized expression.
4093 In particular, used when the parens are syntactically optional,
4094 as opposed to required parens such as those enclosing an if-conditional."
4095 expr) ; `js2-node'
4096
4097 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4098 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4099
4100 (defun js2-visit-paren-node (n v)
4101 (js2-visit-ast (js2-paren-node-expr n) v))
4102
4103 (defun js2-print-paren-node (n i)
4104 (insert (js2-make-pad i))
4105 (insert "(")
4106 (js2-print-ast (js2-paren-node-expr n) 0)
4107 (insert ")"))
4108
4109 (cl-defstruct (js2-comp-node
4110 (:include js2-scope)
4111 (:constructor nil)
4112 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4113 (pos js2-ts-cursor)
4114 len result
4115 loops filters
4116 form)))
4117 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4118 result ; result expression (just after left-bracket)
4119 loops ; a Lisp list of `js2-comp-loop-node'
4120 filters ; a Lisp list of guard/filter expressions
4121 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4122 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4123 )
4124
4125 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4126 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4127
4128 (defun js2-visit-comp-node (n v)
4129 (js2-visit-ast (js2-comp-node-result n) v)
4130 (dolist (l (js2-comp-node-loops n))
4131 (js2-visit-ast l v))
4132 (dolist (f (js2-comp-node-filters n))
4133 (js2-visit-ast f v)))
4134
4135 (defun js2-print-comp-node (n i)
4136 (let ((pad (js2-make-pad i))
4137 (result (js2-comp-node-result n))
4138 (loops (js2-comp-node-loops n))
4139 (filters (js2-comp-node-filters n))
4140 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4141 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4142 (insert pad (if gen-p "(" "["))
4143 (when legacy-p
4144 (js2-print-ast result 0))
4145 (dolist (l loops)
4146 (when legacy-p
4147 (insert " "))
4148 (js2-print-ast l 0)
4149 (unless legacy-p
4150 (insert " ")))
4151 (dolist (f filters)
4152 (when legacy-p
4153 (insert " "))
4154 (insert "if (")
4155 (js2-print-ast f 0)
4156 (insert ")")
4157 (unless legacy-p
4158 (insert " ")))
4159 (unless legacy-p
4160 (js2-print-ast result 0))
4161 (insert (if gen-p ")" "]"))))
4162
4163 (cl-defstruct (js2-comp-loop-node
4164 (:include js2-for-in-node)
4165 (:constructor nil)
4166 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4167 (pos js2-ts-cursor)
4168 len iterator
4169 object in-pos
4170 foreach-p
4171 each-pos
4172 forof-p
4173 lp rp)))
4174 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4175
4176 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4177 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4178
4179 (defun js2-visit-comp-loop (n v)
4180 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4181 (js2-visit-ast (js2-comp-loop-node-object n) v))
4182
4183 (defun js2-print-comp-loop (n _i)
4184 (insert "for ")
4185 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4186 (insert "(")
4187 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4188 (insert (if (js2-comp-loop-node-forof-p n)
4189 " of " " in "))
4190 (js2-print-ast (js2-comp-loop-node-object n) 0)
4191 (insert ")"))
4192
4193 (cl-defstruct (js2-empty-expr-node
4194 (:include js2-node)
4195 (:constructor nil)
4196 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4197 (pos (js2-current-token-beg))
4198 len)))
4199 "AST node for an empty expression.")
4200
4201 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4202 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4203
4204 (cl-defstruct (js2-xml-node
4205 (:include js2-block-node)
4206 (:constructor nil)
4207 (:constructor make-js2-xml-node (&key (type js2-XML)
4208 (pos (js2-current-token-beg))
4209 len kids)))
4210 "AST node for initial parse of E4X literals.
4211 The kids field is a list of XML fragments, each a `js2-string-node' or
4212 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4213
4214 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4215 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4216
4217 (defun js2-print-xml-node (n i)
4218 (dolist (kid (js2-xml-node-kids n))
4219 (js2-print-ast kid i)))
4220
4221 (cl-defstruct (js2-xml-js-expr-node
4222 (:include js2-xml-node)
4223 (:constructor nil)
4224 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4225 (pos js2-ts-cursor)
4226 len expr)))
4227 "AST node for an embedded JavaScript {expression} in an E4X literal.
4228 The start and end fields correspond to the curly-braces."
4229 expr) ; a `js2-expr-node' of some sort
4230
4231 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4232 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4233
4234 (defun js2-visit-xml-js-expr (n v)
4235 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4236
4237 (defun js2-print-xml-js-expr (n i)
4238 (insert (js2-make-pad i))
4239 (insert "{")
4240 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4241 (insert "}"))
4242
4243 (cl-defstruct (js2-xml-dot-query-node
4244 (:include js2-infix-node)
4245 (:constructor nil)
4246 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4247 (pos js2-ts-cursor)
4248 op-pos len left
4249 right rp)))
4250 "AST node for an E4X foo.(bar) filter expression.
4251 Note that the left-paren is automatically the character immediately
4252 following the dot (.) in the operator. No whitespace is permitted
4253 between the dot and the lp by the scanner."
4254 rp)
4255
4256 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4257 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4258
4259 (defun js2-print-xml-dot-query (n i)
4260 (insert (js2-make-pad i))
4261 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4262 (insert ".(")
4263 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4264 (insert ")"))
4265
4266 (cl-defstruct (js2-xml-ref-node
4267 (:include js2-node)
4268 (:constructor nil)) ; abstract
4269 "Base type for E4X XML attribute-access or property-get expressions.
4270 Such expressions can take a variety of forms. The general syntax has
4271 three parts:
4272
4273 - (optional) an @ (specifying an attribute access)
4274 - (optional) a namespace (a `js2-name-node') and double-colon
4275 - (required) either a `js2-name-node' or a bracketed [expression]
4276
4277 The property-name expressions (examples: ns::name, @name) are
4278 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4279 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4280
4281 This node type (or more specifically, its subclasses) will sometimes
4282 be the right-hand child of a `js2-prop-get-node' or a
4283 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4284 The `js2-xml-ref-node' may also be a standalone primary expression with
4285 no explicit target, which is valid in certain expression contexts such as
4286
4287 company..employee.(@id < 100)
4288
4289 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4290 expression whose parent is a `js2-xml-dot-query-node'."
4291 namespace
4292 at-pos
4293 colon-pos)
4294
4295 (defsubst js2-xml-ref-node-attr-access-p (node)
4296 "Return non-nil if this expression began with an @-token."
4297 (and (numberp (js2-xml-ref-node-at-pos node))
4298 (cl-plusp (js2-xml-ref-node-at-pos node))))
4299
4300 (cl-defstruct (js2-xml-prop-ref-node
4301 (:include js2-xml-ref-node)
4302 (:constructor nil)
4303 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4304 (pos (js2-current-token-beg))
4305 len propname
4306 namespace at-pos
4307 colon-pos)))
4308 "AST node for an E4X XML [expr] property-ref expression.
4309 The JavaScript syntax is an optional @, an optional ns::, and a name.
4310
4311 [ '@' ] [ name '::' ] name
4312
4313 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4314 @ns::*, @*::attr, @*::*, and @*.
4315
4316 The node starts at the @ token, if present. Otherwise it starts at the
4317 namespace name. The node bounds extend through the closing right-bracket,
4318 or if it is missing due to a syntax error, through the end of the index
4319 expression."
4320 propname)
4321
4322 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4323 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4324
4325 (defun js2-visit-xml-prop-ref-node (n v)
4326 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4327 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4328
4329 (defun js2-print-xml-prop-ref-node (n i)
4330 (insert (js2-make-pad i))
4331 (if (js2-xml-ref-node-attr-access-p n)
4332 (insert "@"))
4333 (when (js2-xml-prop-ref-node-namespace n)
4334 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4335 (insert "::"))
4336 (if (js2-xml-prop-ref-node-propname n)
4337 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4338
4339 (cl-defstruct (js2-xml-elem-ref-node
4340 (:include js2-xml-ref-node)
4341 (:constructor nil)
4342 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4343 (pos (js2-current-token-beg))
4344 len expr lb rb
4345 namespace at-pos
4346 colon-pos)))
4347 "AST node for an E4X XML [expr] member-ref expression.
4348 Syntax:
4349
4350 [ '@' ] [ name '::' ] '[' expr ']'
4351
4352 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4353
4354 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4355 is not a legal E4X XML element-ref expression, since it's already used
4356 for standard JavaScript element-get array indexing. Hence, a
4357 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4358 non-nil namespace node, or both.
4359
4360 The node starts at the @ token, if present. Otherwise it starts
4361 at the namespace name. The node bounds extend through the closing
4362 right-bracket, or if it is missing due to a syntax error, through the
4363 end of the index expression."
4364 expr ; the bracketed index expression
4365 lb
4366 rb)
4367
4368 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4369 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4370
4371 (defun js2-visit-xml-elem-ref-node (n v)
4372 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4373 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4374
4375 (defun js2-print-xml-elem-ref-node (n i)
4376 (insert (js2-make-pad i))
4377 (if (js2-xml-ref-node-attr-access-p n)
4378 (insert "@"))
4379 (when (js2-xml-elem-ref-node-namespace n)
4380 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4381 (insert "::"))
4382 (insert "[")
4383 (if (js2-xml-elem-ref-node-expr n)
4384 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4385 (insert "]"))
4386
4387 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4388
4389 (cl-defstruct (js2-xml-start-tag-node
4390 (:include js2-xml-node)
4391 (:constructor nil)
4392 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4393 (pos js2-ts-cursor)
4394 len name attrs kids
4395 empty-p)))
4396 "AST node for an XML start-tag. Not currently used.
4397 The `kids' field is a Lisp list of child content nodes."
4398 name ; a `js2-xml-name-node'
4399 attrs ; a Lisp list of `js2-xml-attr-node'
4400 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4401
4402 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4403 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4404
4405 (defun js2-visit-xml-start-tag (n v)
4406 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4407 (dolist (attr (js2-xml-start-tag-node-attrs n))
4408 (js2-visit-ast attr v))
4409 (js2-visit-block n v))
4410
4411 (defun js2-print-xml-start-tag (n i)
4412 (insert (js2-make-pad i) "<")
4413 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4414 (when (js2-xml-start-tag-node-attrs n)
4415 (insert " ")
4416 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4417 (insert ">"))
4418
4419 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4420 ;; and add the end-tag to the kids list of the parent as well.
4421 (cl-defstruct (js2-xml-end-tag-node
4422 (:include js2-xml-node)
4423 (:constructor nil)
4424 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4425 (pos js2-ts-cursor)
4426 len name)))
4427 "AST node for an XML end-tag. Not currently used."
4428 name) ; a `js2-xml-name-node'
4429
4430 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4431 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4432
4433 (defun js2-visit-xml-end-tag (n v)
4434 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4435
4436 (defun js2-print-xml-end-tag (n i)
4437 (insert (js2-make-pad i))
4438 (insert "</")
4439 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4440 (insert ">"))
4441
4442 (cl-defstruct (js2-xml-name-node
4443 (:include js2-xml-node)
4444 (:constructor nil)
4445 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4446 (pos js2-ts-cursor)
4447 len namespace kids)))
4448 "AST node for an E4X XML name. Not currently used.
4449 Any XML name can be qualified with a namespace, hence the namespace field.
4450 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4451 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4452 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4453 namespace) ; a `js2-string-node'
4454
4455 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4456 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4457
4458 (defun js2-visit-xml-name-node (n v)
4459 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4460
4461 (defun js2-print-xml-name-node (n i)
4462 (insert (js2-make-pad i))
4463 (when (js2-xml-name-node-namespace n)
4464 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4465 (insert "::"))
4466 (dolist (kid (js2-xml-name-node-kids n))
4467 (js2-print-ast kid 0)))
4468
4469 (cl-defstruct (js2-xml-pi-node
4470 (:include js2-xml-node)
4471 (:constructor nil)
4472 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4473 (pos js2-ts-cursor)
4474 len name attrs)))
4475 "AST node for an E4X XML processing instruction. Not currently used."
4476 name ; a `js2-xml-name-node'
4477 attrs) ; a list of `js2-xml-attr-node'
4478
4479 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4480 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4481
4482 (defun js2-visit-xml-pi-node (n v)
4483 (js2-visit-ast (js2-xml-pi-node-name n) v)
4484 (dolist (attr (js2-xml-pi-node-attrs n))
4485 (js2-visit-ast attr v)))
4486
4487 (defun js2-print-xml-pi-node (n i)
4488 (insert (js2-make-pad i) "<?")
4489 (js2-print-ast (js2-xml-pi-node-name n))
4490 (when (js2-xml-pi-node-attrs n)
4491 (insert " ")
4492 (js2-print-list (js2-xml-pi-node-attrs n)))
4493 (insert "?>"))
4494
4495 (cl-defstruct (js2-xml-cdata-node
4496 (:include js2-xml-node)
4497 (:constructor nil)
4498 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4499 (pos js2-ts-cursor)
4500 len content)))
4501 "AST node for a CDATA escape section. Not currently used."
4502 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4503
4504 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4505 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4506
4507 (defun js2-visit-xml-cdata-node (n v)
4508 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4509
4510 (defun js2-print-xml-cdata-node (n i)
4511 (insert (js2-make-pad i))
4512 (js2-print-ast (js2-xml-cdata-node-content n)))
4513
4514 (cl-defstruct (js2-xml-attr-node
4515 (:include js2-xml-node)
4516 (:constructor nil)
4517 (:constructor make-js2-attr-node (&key (type js2-XML)
4518 (pos js2-ts-cursor)
4519 len name value
4520 eq-pos quote-type)))
4521 "AST node representing a foo='bar' XML attribute value. Not yet used."
4522 name ; a `js2-xml-name-node'
4523 value ; a `js2-xml-name-node'
4524 eq-pos ; buffer position of "=" sign
4525 quote-type) ; 'single or 'double
4526
4527 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4528 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4529
4530 (defun js2-visit-xml-attr-node (n v)
4531 (js2-visit-ast (js2-xml-attr-node-name n) v)
4532 (js2-visit-ast (js2-xml-attr-node-value n) v))
4533
4534 (defun js2-print-xml-attr-node (n i)
4535 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4536 "'"
4537 "\"")))
4538 (insert (js2-make-pad i))
4539 (js2-print-ast (js2-xml-attr-node-name n) 0)
4540 (insert "=" quote)
4541 (js2-print-ast (js2-xml-attr-node-value n) 0)
4542 (insert quote)))
4543
4544 (cl-defstruct (js2-xml-text-node
4545 (:include js2-xml-node)
4546 (:constructor nil)
4547 (:constructor make-js2-text-node (&key (type js2-XML)
4548 (pos js2-ts-cursor)
4549 len content)))
4550 "AST node for an E4X XML text node. Not currently used."
4551 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4552
4553 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4554 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4555
4556 (defun js2-visit-xml-text-node (n v)
4557 (js2-visit-ast (js2-xml-text-node-content n) v))
4558
4559 (defun js2-print-xml-text-node (n i)
4560 (insert (js2-make-pad i))
4561 (dolist (kid (js2-xml-text-node-content n))
4562 (js2-print-ast kid)))
4563
4564 (cl-defstruct (js2-xml-comment-node
4565 (:include js2-xml-node)
4566 (:constructor nil)
4567 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4568 (pos js2-ts-cursor)
4569 len)))
4570 "AST node for E4X XML comment. Not currently used.")
4571
4572 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4573 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4574
4575 (defun js2-print-xml-comment (n i)
4576 (insert (js2-make-pad i)
4577 (js2-node-string n)))
4578
4579 ;;; Node utilities
4580
4581 (defsubst js2-node-line (n)
4582 "Fetch the source line number at the start of node N.
4583 This is O(n) in the length of the source buffer; use prudently."
4584 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4585
4586 (defsubst js2-block-node-kid (n i)
4587 "Return child I of node N, or nil if there aren't that many."
4588 (nth i (js2-block-node-kids n)))
4589
4590 (defsubst js2-block-node-first (n)
4591 "Return first child of block node N, or nil if there is none."
4592 (cl-first (js2-block-node-kids n)))
4593
4594 (defun js2-node-root (n)
4595 "Return the root of the AST containing N.
4596 If N has no parent pointer, returns N."
4597 (let ((parent (js2-node-parent n)))
4598 (if parent
4599 (js2-node-root parent)
4600 n)))
4601
4602 (defsubst js2-node-short-name (n)
4603 "Return the short name of node N as a string, e.g. `js2-if-node'."
4604 (substring (symbol-name (aref n 0))
4605 (length "cl-struct-")))
4606
4607 (defun js2-node-child-list (node)
4608 "Return the child list for NODE, a Lisp list of nodes.
4609 Works for block nodes, array nodes, obj literals, funarg lists,
4610 var decls and try nodes (for catch clauses). Note that you should call
4611 `js2-block-node-kids' on the function body for the body statements.
4612 Returns nil for zero-length child lists or unsupported nodes."
4613 (cond
4614 ((js2-function-node-p node)
4615 (js2-function-node-params node))
4616 ((js2-block-node-p node)
4617 (js2-block-node-kids node))
4618 ((js2-try-node-p node)
4619 (js2-try-node-catch-clauses node))
4620 ((js2-array-node-p node)
4621 (js2-array-node-elems node))
4622 ((js2-object-node-p node)
4623 (js2-object-node-elems node))
4624 ((js2-call-node-p node)
4625 (js2-call-node-args node))
4626 ((js2-new-node-p node)
4627 (js2-new-node-args node))
4628 ((js2-var-decl-node-p node)
4629 (js2-var-decl-node-kids node))
4630 (t
4631 nil)))
4632
4633 (defun js2-node-set-child-list (node kids)
4634 "Set the child list for NODE to KIDS."
4635 (cond
4636 ((js2-function-node-p node)
4637 (setf (js2-function-node-params node) kids))
4638 ((js2-block-node-p node)
4639 (setf (js2-block-node-kids node) kids))
4640 ((js2-try-node-p node)
4641 (setf (js2-try-node-catch-clauses node) kids))
4642 ((js2-array-node-p node)
4643 (setf (js2-array-node-elems node) kids))
4644 ((js2-object-node-p node)
4645 (setf (js2-object-node-elems node) kids))
4646 ((js2-call-node-p node)
4647 (setf (js2-call-node-args node) kids))
4648 ((js2-new-node-p node)
4649 (setf (js2-new-node-args node) kids))
4650 ((js2-var-decl-node-p node)
4651 (setf (js2-var-decl-node-kids node) kids))
4652 (t
4653 (error "Unsupported node type: %s" (js2-node-short-name node))))
4654 kids)
4655
4656 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4657 (defconst js2-paren-expr-nodes
4658 '(cl-struct-js2-comp-loop-node
4659 cl-struct-js2-comp-node
4660 cl-struct-js2-call-node
4661 cl-struct-js2-catch-node
4662 cl-struct-js2-do-node
4663 cl-struct-js2-elem-get-node
4664 cl-struct-js2-for-in-node
4665 cl-struct-js2-for-node
4666 cl-struct-js2-function-node
4667 cl-struct-js2-if-node
4668 cl-struct-js2-let-node
4669 cl-struct-js2-new-node
4670 cl-struct-js2-paren-node
4671 cl-struct-js2-switch-node
4672 cl-struct-js2-while-node
4673 cl-struct-js2-with-node
4674 cl-struct-js2-xml-dot-query-node)
4675 "Node types that can have a parenthesized child expression.
4676 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4677
4678 (defsubst js2-paren-expr-node-p (node)
4679 "Return t for nodes that typically have a parenthesized child expression.
4680 Useful for computing the indentation anchors for arg-lists and conditions.
4681 Note that it may return a false positive, for instance when NODE is
4682 a `js2-new-node' and there are no arguments or parentheses."
4683 (memq (aref node 0) js2-paren-expr-nodes))
4684
4685 ;; Fake polymorphism... yech.
4686 (defun js2-node-lp (node)
4687 "Return relative left-paren position for NODE, if applicable.
4688 For `js2-elem-get-node' structs, returns left-bracket position.
4689 Note that the position may be nil in the case of a parse error."
4690 (cond
4691 ((js2-elem-get-node-p node)
4692 (js2-elem-get-node-lb node))
4693 ((js2-loop-node-p node)
4694 (js2-loop-node-lp node))
4695 ((js2-function-node-p node)
4696 (js2-function-node-lp node))
4697 ((js2-if-node-p node)
4698 (js2-if-node-lp node))
4699 ((js2-new-node-p node)
4700 (js2-new-node-lp node))
4701 ((js2-call-node-p node)
4702 (js2-call-node-lp node))
4703 ((js2-paren-node-p node)
4704 0)
4705 ((js2-switch-node-p node)
4706 (js2-switch-node-lp node))
4707 ((js2-catch-node-p node)
4708 (js2-catch-node-lp node))
4709 ((js2-let-node-p node)
4710 (js2-let-node-lp node))
4711 ((js2-comp-node-p node)
4712 0)
4713 ((js2-with-node-p node)
4714 (js2-with-node-lp node))
4715 ((js2-xml-dot-query-node-p node)
4716 (1+ (js2-infix-node-op-pos node)))
4717 (t
4718 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4719
4720 ;; Fake polymorphism... blech.
4721 (defun js2-node-rp (node)
4722 "Return relative right-paren position for NODE, if applicable.
4723 For `js2-elem-get-node' structs, returns right-bracket position.
4724 Note that the position may be nil in the case of a parse error."
4725 (cond
4726 ((js2-elem-get-node-p node)
4727 (js2-elem-get-node-rb node))
4728 ((js2-loop-node-p node)
4729 (js2-loop-node-rp node))
4730 ((js2-function-node-p node)
4731 (js2-function-node-rp node))
4732 ((js2-if-node-p node)
4733 (js2-if-node-rp node))
4734 ((js2-new-node-p node)
4735 (js2-new-node-rp node))
4736 ((js2-call-node-p node)
4737 (js2-call-node-rp node))
4738 ((js2-paren-node-p node)
4739 (1- (js2-node-len node)))
4740 ((js2-switch-node-p node)
4741 (js2-switch-node-rp node))
4742 ((js2-catch-node-p node)
4743 (js2-catch-node-rp node))
4744 ((js2-let-node-p node)
4745 (js2-let-node-rp node))
4746 ((js2-comp-node-p node)
4747 (1- (js2-node-len node)))
4748 ((js2-with-node-p node)
4749 (js2-with-node-rp node))
4750 ((js2-xml-dot-query-node-p node)
4751 (1+ (js2-xml-dot-query-node-rp node)))
4752 (t
4753 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4754
4755 (defsubst js2-node-first-child (node)
4756 "Return the first element of `js2-node-child-list' for NODE."
4757 (car (js2-node-child-list node)))
4758
4759 (defsubst js2-node-last-child (node)
4760 "Return the last element of `js2-node-last-child' for NODE."
4761 (car (last (js2-node-child-list node))))
4762
4763 (defun js2-node-prev-sibling (node)
4764 "Return the previous statement in parent.
4765 Works for parents supported by `js2-node-child-list'.
4766 Returns nil if NODE is not in the parent, or PARENT is
4767 not a supported node, or if NODE is the first child."
4768 (let* ((p (js2-node-parent node))
4769 (kids (js2-node-child-list p))
4770 (sib (car kids)))
4771 (while (and kids
4772 (not (eq node (cadr kids))))
4773 (setq kids (cdr kids)
4774 sib (car kids)))
4775 sib))
4776
4777 (defun js2-node-next-sibling (node)
4778 "Return the next statement in parent block.
4779 Returns nil if NODE is not in the block, or PARENT is not
4780 a block node, or if NODE is the last statement."
4781 (let* ((p (js2-node-parent node))
4782 (kids (js2-node-child-list p)))
4783 (while (and kids
4784 (not (eq node (car kids))))
4785 (setq kids (cdr kids)))
4786 (cadr kids)))
4787
4788 (defun js2-node-find-child-before (pos parent &optional after)
4789 "Find the last child that starts before POS in parent.
4790 If AFTER is non-nil, returns first child starting after POS.
4791 POS is an absolute buffer position. PARENT is any node
4792 supported by `js2-node-child-list'.
4793 Returns nil if no applicable child is found."
4794 (let ((kids (if (js2-function-node-p parent)
4795 (js2-block-node-kids (js2-function-node-body parent))
4796 (js2-node-child-list parent)))
4797 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4798 (js2-function-node-body parent)
4799 parent)))
4800 kid result fn
4801 (continue t))
4802 (setq fn (if after '>= '<))
4803 (while (and kids continue)
4804 (setq kid (car kids))
4805 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4806 (setq result kid
4807 continue (not after))
4808 (setq continue after))
4809 (setq kids (cdr kids)))
4810 result))
4811
4812 (defun js2-node-find-child-after (pos parent)
4813 "Find first child that starts after POS in parent.
4814 POS is an absolute buffer position. PARENT is any node
4815 supported by `js2-node-child-list'.
4816 Returns nil if no applicable child is found."
4817 (js2-node-find-child-before pos parent 'after))
4818
4819 (defun js2-node-replace-child (pos parent new-node)
4820 "Replace node at index POS in PARENT with NEW-NODE.
4821 Only works for parents supported by `js2-node-child-list'."
4822 (let ((kids (js2-node-child-list parent))
4823 (i 0))
4824 (while (< i pos)
4825 (setq kids (cdr kids)
4826 i (1+ i)))
4827 (setcar kids new-node)
4828 (js2-node-add-children parent new-node)))
4829
4830 (defun js2-node-buffer (n)
4831 "Return the buffer associated with AST N.
4832 Returns nil if the buffer is not set as a property on the root
4833 node, or if parent links were not recorded during parsing."
4834 (let ((root (js2-node-root n)))
4835 (and root
4836 (js2-ast-root-p root)
4837 (js2-ast-root-buffer root))))
4838
4839 (defun js2-block-node-push (n kid)
4840 "Push js2-node KID onto the end of js2-block-node N's child list.
4841 KID is always added to the -end- of the kids list.
4842 Function also calls `js2-node-add-children' to add the parent link."
4843 (let ((kids (js2-node-child-list n)))
4844 (if kids
4845 (setcdr kids (nconc (cdr kids) (list kid)))
4846 (js2-node-set-child-list n (list kid)))
4847 (js2-node-add-children n kid)))
4848
4849 (defun js2-node-string (node)
4850 (with-current-buffer (or (js2-node-buffer node)
4851 (error "No buffer available for node %s" node))
4852 (let ((pos (js2-node-abs-pos node)))
4853 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4854
4855 ;; Container for storing the node we're looking for in a traversal.
4856 (js2-deflocal js2-discovered-node nil)
4857
4858 ;; Keep track of absolute node position during traversals.
4859 (js2-deflocal js2-visitor-offset nil)
4860
4861 (js2-deflocal js2-node-search-point nil)
4862
4863 (when js2-mode-dev-mode-p
4864 (defun js2-find-node-at-point ()
4865 (interactive)
4866 (let ((node (js2-node-at-point)))
4867 (message "%s" (or node "No node found at point"))))
4868 (defun js2-node-name-at-point ()
4869 (interactive)
4870 (let ((node (js2-node-at-point)))
4871 (message "%s" (if node
4872 (js2-node-short-name node)
4873 "No node found at point.")))))
4874
4875 (defun js2-node-at-point (&optional pos skip-comments)
4876 "Return AST node at POS, a buffer position, defaulting to current point.
4877 The `js2-mode-ast' variable must be set to the current parse tree.
4878 Signals an error if the AST (`js2-mode-ast') is nil.
4879 Always returns a node - if it can't find one, it returns the root.
4880 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4881 (let ((ast js2-mode-ast)
4882 result)
4883 (unless ast
4884 (error "No JavaScript AST available"))
4885 ;; Look through comments first, since they may be inside nodes that
4886 ;; would otherwise report a match.
4887 (setq pos (or pos (point))
4888 result (if (> pos (js2-node-abs-end ast))
4889 ast
4890 (if (not skip-comments)
4891 (js2-comment-at-point pos))))
4892 (unless result
4893 (setq js2-discovered-node nil
4894 js2-visitor-offset 0
4895 js2-node-search-point pos)
4896 (unwind-protect
4897 (catch 'js2-visit-done
4898 (js2-visit-ast ast #'js2-node-at-point-visitor))
4899 (setq js2-visitor-offset nil
4900 js2-node-search-point nil))
4901 (setq result js2-discovered-node))
4902 ;; may have found a comment beyond end of last child node,
4903 ;; since visiting the ast-root looks at the comment-list last.
4904 (if (and skip-comments
4905 (js2-comment-node-p result))
4906 (setq result nil))
4907 (or result js2-mode-ast)))
4908
4909 (defun js2-node-at-point-visitor (node end-p)
4910 (let ((rel-pos (js2-node-pos node))
4911 abs-pos
4912 abs-end
4913 (point js2-node-search-point))
4914 (cond
4915 (end-p
4916 ;; this evaluates to a non-nil return value, even if it's zero
4917 (cl-decf js2-visitor-offset rel-pos))
4918 ;; we already looked for comments before visiting, and don't want them now
4919 ((js2-comment-node-p node)
4920 nil)
4921 (t
4922 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4923 ;; we only want to use the node if the point is before
4924 ;; the last character position in the node, so we decrement
4925 ;; the absolute end by 1.
4926 abs-end (+ abs-pos (js2-node-len node) -1))
4927 (cond
4928 ;; If this node starts after search-point, stop the search.
4929 ((> abs-pos point)
4930 (throw 'js2-visit-done nil))
4931 ;; If this node ends before the search-point, don't check kids.
4932 ((> point abs-end)
4933 nil)
4934 (t
4935 ;; Otherwise point is within this node, possibly in a child.
4936 (setq js2-discovered-node node)
4937 t)))))) ; keep processing kids to look for more specific match
4938
4939 (defsubst js2-block-comment-p (node)
4940 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4941 (and (js2-comment-node-p node)
4942 (memq (js2-comment-node-format node) '(jsdoc block))))
4943
4944 ;; TODO: put the comments in a vector and binary-search them instead
4945 (defun js2-comment-at-point (&optional pos)
4946 "Look through scanned comment nodes for one containing POS.
4947 POS is a buffer position that defaults to current point.
4948 Function returns nil if POS was not in any comment node."
4949 (let ((ast js2-mode-ast)
4950 (x (or pos (point)))
4951 beg end)
4952 (unless ast
4953 (error "No JavaScript AST available"))
4954 (catch 'done
4955 ;; Comments are stored in lexical order.
4956 (dolist (comment (js2-ast-root-comments ast) nil)
4957 (setq beg (js2-node-abs-pos comment)
4958 end (+ beg (js2-node-len comment)))
4959 (if (and (>= x beg)
4960 (<= x end))
4961 (throw 'done comment))))))
4962
4963 (defun js2-mode-find-parent-fn (node)
4964 "Find function enclosing NODE.
4965 Returns nil if NODE is not inside a function."
4966 (setq node (js2-node-parent node))
4967 (while (and node (not (js2-function-node-p node)))
4968 (setq node (js2-node-parent node)))
4969 (and (js2-function-node-p node) node))
4970
4971 (defun js2-mode-find-enclosing-fn (node)
4972 "Find function or root enclosing NODE."
4973 (if (js2-ast-root-p node)
4974 node
4975 (setq node (js2-node-parent node))
4976 (while (not (or (js2-ast-root-p node)
4977 (js2-function-node-p node)))
4978 (setq node (js2-node-parent node)))
4979 node))
4980
4981 (defun js2-mode-find-enclosing-node (beg end)
4982 "Find node fully enclosing BEG and END."
4983 (let ((node (js2-node-at-point beg))
4984 pos
4985 (continue t))
4986 (while continue
4987 (if (or (js2-ast-root-p node)
4988 (and
4989 (<= (setq pos (js2-node-abs-pos node)) beg)
4990 (>= (+ pos (js2-node-len node)) end)))
4991 (setq continue nil)
4992 (setq node (js2-node-parent node))))
4993 node))
4994
4995 (defun js2-node-parent-script-or-fn (node)
4996 "Find script or function immediately enclosing NODE.
4997 If NODE is the ast-root, returns nil."
4998 (if (js2-ast-root-p node)
4999 nil
5000 (setq node (js2-node-parent node))
5001 (while (and node (not (or (js2-function-node-p node)
5002 (js2-script-node-p node))))
5003 (setq node (js2-node-parent node)))
5004 node))
5005
5006 (defun js2-node-is-descendant (node ancestor)
5007 "Return t if NODE is a descendant of ANCESTOR."
5008 (while (and node
5009 (not (eq node ancestor)))
5010 (setq node (js2-node-parent node)))
5011 node)
5012
5013 ;;; visitor infrastructure
5014
5015 (defun js2-visit-none (_node _callback)
5016 "Visitor for AST node that have no node children."
5017 nil)
5018
5019 (defun js2-print-none (_node _indent)
5020 "Visitor for AST node with no printed representation.")
5021
5022 (defun js2-print-body (node indent)
5023 "Print a statement, or a block without braces."
5024 (if (js2-block-node-p node)
5025 (dolist (kid (js2-block-node-kids node))
5026 (js2-print-ast kid indent))
5027 (js2-print-ast node indent)))
5028
5029 (defun js2-print-list (args &optional delimiter)
5030 (cl-loop with len = (length args)
5031 for arg in args
5032 for count from 1
5033 do
5034 (when arg (js2-print-ast arg 0))
5035 (if (< count len)
5036 (insert (or delimiter ", ")))))
5037
5038 (defun js2-print-tree (ast)
5039 "Prints an AST to the current buffer.
5040 Makes `js2-ast-parent-nodes' available to the printer functions."
5041 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5042 (js2-print-ast ast)))
5043
5044 (defun js2-print-ast (node &optional indent)
5045 "Helper function for printing AST nodes.
5046 Requires `js2-ast-parent-nodes' to be non-nil.
5047 You should use `js2-print-tree' instead of this function."
5048 (let ((printer (get (aref node 0) 'js2-printer))
5049 (i (or indent 0)))
5050 ;; TODO: wedge comments in here somewhere
5051 (if printer
5052 (funcall printer node i))))
5053
5054 (defconst js2-side-effecting-tokens
5055 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5056 (dolist (tt (list js2-ASSIGN
5057 js2-ASSIGN_ADD
5058 js2-ASSIGN_BITAND
5059 js2-ASSIGN_BITOR
5060 js2-ASSIGN_BITXOR
5061 js2-ASSIGN_DIV
5062 js2-ASSIGN_LSH
5063 js2-ASSIGN_MOD
5064 js2-ASSIGN_MUL
5065 js2-ASSIGN_RSH
5066 js2-ASSIGN_SUB
5067 js2-ASSIGN_URSH
5068 js2-BLOCK
5069 js2-BREAK
5070 js2-CALL
5071 js2-CATCH
5072 js2-CATCH_SCOPE
5073 js2-CLASS
5074 js2-CONST
5075 js2-CONTINUE
5076 js2-DEBUGGER
5077 js2-DEC
5078 js2-DELPROP
5079 js2-DEL_REF
5080 js2-DO
5081 js2-ELSE
5082 js2-EMPTY
5083 js2-ENTERWITH
5084 js2-EXPORT
5085 js2-EXPR_RESULT
5086 js2-FINALLY
5087 js2-FOR
5088 js2-FUNCTION
5089 js2-GOTO
5090 js2-IF
5091 js2-IFEQ
5092 js2-IFNE
5093 js2-IMPORT
5094 js2-INC
5095 js2-JSR
5096 js2-LABEL
5097 js2-LEAVEWITH
5098 js2-LET
5099 js2-LETEXPR
5100 js2-LOCAL_BLOCK
5101 js2-LOOP
5102 js2-NEW
5103 js2-REF_CALL
5104 js2-RETHROW
5105 js2-RETURN
5106 js2-RETURN_RESULT
5107 js2-SEMI
5108 js2-SETELEM
5109 js2-SETELEM_OP
5110 js2-SETNAME
5111 js2-SETPROP
5112 js2-SETPROP_OP
5113 js2-SETVAR
5114 js2-SET_REF
5115 js2-SET_REF_OP
5116 js2-SWITCH
5117 js2-TARGET
5118 js2-THROW
5119 js2-TRY
5120 js2-VAR
5121 js2-WHILE
5122 js2-WITH
5123 js2-WITHEXPR
5124 js2-YIELD))
5125 (aset tokens tt t))
5126 (if js2-instanceof-has-side-effects
5127 (aset tokens js2-INSTANCEOF t))
5128 tokens))
5129
5130 (defun js2-node-has-side-effects (node)
5131 "Return t if NODE has side effects."
5132 (when node ; makes it easier to handle malformed expressions
5133 (let ((tt (js2-node-type node)))
5134 (cond
5135 ;; This doubtless needs some work, since EXPR_VOID is used
5136 ;; in several ways in Rhino and I may not have caught them all.
5137 ;; I'll wait for people to notice incorrect warnings.
5138 ((and (= tt js2-EXPR_VOID)
5139 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5140 (let ((expr (js2-expr-stmt-node-expr node)))
5141 (or (js2-node-has-side-effects expr)
5142 (when (js2-string-node-p expr)
5143 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5144 ((= tt js2-AWAIT)
5145 (js2-node-has-side-effects (js2-unary-node-operand node)))
5146 ((= tt js2-COMMA)
5147 (js2-node-has-side-effects (js2-infix-node-right node)))
5148 ((or (= tt js2-AND)
5149 (= tt js2-OR))
5150 (or (js2-node-has-side-effects (js2-infix-node-right node))
5151 (js2-node-has-side-effects (js2-infix-node-left node))))
5152 ((= tt js2-HOOK)
5153 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5154 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5155 ((js2-paren-node-p node)
5156 (js2-node-has-side-effects (js2-paren-node-expr node)))
5157 ((= tt js2-ERROR) ; avoid cascaded error messages
5158 nil)
5159 (t
5160 (aref js2-side-effecting-tokens tt))))))
5161
5162 (defconst js2-stmt-node-types
5163 (list js2-BLOCK
5164 js2-BREAK
5165 js2-CONTINUE
5166 js2-DEFAULT ; e4x "default xml namespace" statement
5167 js2-DO
5168 js2-EXPORT
5169 js2-EXPR_RESULT
5170 js2-EXPR_VOID
5171 js2-FOR
5172 js2-IF
5173 js2-IMPORT
5174 js2-RETURN
5175 js2-SWITCH
5176 js2-THROW
5177 js2-TRY
5178 js2-WHILE
5179 js2-WITH)
5180 "Node types that only appear in statement contexts.
5181 The list does not include nodes that always appear as the child
5182 of another specific statement type, such as switch-cases,
5183 catch and finally blocks, and else-clauses. The list also excludes
5184 nodes like yield, let and var, which may appear in either expression
5185 or statement context, and in the latter context always have a
5186 `js2-expr-stmt-node' parent. Finally, the list does not include
5187 functions or scripts, which are treated separately from statements
5188 by the JavaScript parser and runtime.")
5189
5190 (defun js2-stmt-node-p (node)
5191 "Heuristic for figuring out if NODE is a statement.
5192 Some node types can appear in either an expression context or a
5193 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5194 For these node types in a statement context, the parent will be a
5195 `js2-expr-stmt-node'.
5196 Functions aren't included in the check."
5197 (memq (js2-node-type node) js2-stmt-node-types))
5198
5199 (defun js2-mode-find-first-stmt (node)
5200 "Search upward starting from NODE looking for a statement.
5201 For purposes of this function, a `js2-function-node' counts."
5202 (while (not (or (js2-stmt-node-p node)
5203 (js2-function-node-p node)))
5204 (setq node (js2-node-parent node)))
5205 node)
5206
5207 (defun js2-node-parent-stmt (node)
5208 "Return the node's first ancestor that is a statement.
5209 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5210 appearing in a statement context will have a parent that is a
5211 `js2-expr-stmt-node' that will be returned by this function."
5212 (let ((parent (js2-node-parent node)))
5213 (if (or (null parent)
5214 (js2-stmt-node-p parent)
5215 (and (js2-function-node-p parent)
5216 (not (eq (js2-function-node-form parent)
5217 'FUNCTION_EXPRESSION))))
5218 parent
5219 (js2-node-parent-stmt parent))))
5220
5221 ;; In the Mozilla Rhino sources, Roshan James writes:
5222 ;; Does consistent-return analysis on the function body when strict mode is
5223 ;; enabled.
5224 ;;
5225 ;; function (x) { return (x+1) }
5226 ;;
5227 ;; is ok, but
5228 ;;
5229 ;; function (x) { if (x < 0) return (x+1); }
5230 ;;
5231 ;; is not because the function can potentially return a value when the
5232 ;; condition is satisfied and if not, the function does not explicitly
5233 ;; return a value.
5234 ;;
5235 ;; This extends to checking mismatches such as "return" and "return <value>"
5236 ;; used in the same function. Warnings are not emitted if inconsistent
5237 ;; returns exist in code that can be statically shown to be unreachable.
5238 ;; Ex.
5239 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5240 ;;
5241 ;; emits no warning. However if the loop had a break statement, then a
5242 ;; warning would be emitted.
5243 ;;
5244 ;; The consistency analysis looks at control structures such as loops, ifs,
5245 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5246 ;; warns the user about an inconsistent set of termination possibilities.
5247 ;;
5248 ;; These flags enumerate the possible ways a statement/function can
5249 ;; terminate. These flags are used by endCheck() and by the Parser to
5250 ;; detect inconsistent return usage.
5251 ;;
5252 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5253 ;; able to execute (example: throw, continue)
5254 ;;
5255 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5256 ;; next one. Statement such as return dont. A compound statement may have
5257 ;; some branch that drops off control to the next statement.
5258 ;;
5259 ;; END_RETURNS indicates that the statement can return with no value.
5260 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5261 ;;
5262 ;; A compound statement such as
5263 ;; if (condition) {
5264 ;; return value;
5265 ;; }
5266 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5267
5268 (defconst js2-END_UNREACHED 0)
5269 (defconst js2-END_DROPS_OFF 1)
5270 (defconst js2-END_RETURNS 2)
5271 (defconst js2-END_RETURNS_VALUE 4)
5272 (defconst js2-END_YIELDS 8)
5273
5274 (defun js2-has-consistent-return-usage (node)
5275 "Check that every return usage in a function body is consistent.
5276 Returns t if the function satisfies strict mode requirement."
5277 (let ((n (js2-end-check node)))
5278 ;; either it doesn't return a value in any branch...
5279 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5280 ;; or it returns a value (or is unreached) at every branch
5281 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5282 js2-END_RETURNS
5283 js2-END_YIELDS)))))
5284
5285 (defun js2-end-check-if (node)
5286 "Ensure that return usage in then/else blocks is consistent.
5287 If there is no else block, then the return statement can fall through.
5288 Returns logical OR of END_* flags"
5289 (let ((th (js2-if-node-then-part node))
5290 (el (js2-if-node-else-part node)))
5291 (if (null th)
5292 js2-END_UNREACHED
5293 (logior (js2-end-check th) (if el
5294 (js2-end-check el)
5295 js2-END_DROPS_OFF)))))
5296
5297 (defun js2-end-check-switch (node)
5298 "Consistency of return statements is checked between the case statements.
5299 If there is no default, then the switch can fall through. If there is a
5300 default, we check to see if all code paths in the default return or if
5301 there is a code path that can fall through.
5302 Returns logical OR of END_* flags."
5303 (let ((rv js2-END_UNREACHED)
5304 default-case)
5305 ;; examine the cases
5306 (catch 'break
5307 (dolist (c (js2-switch-node-cases node))
5308 (if (js2-case-node-expr c)
5309 (js2-set-flag rv (js2-end-check-block c))
5310 (setq default-case c)
5311 (throw 'break nil))))
5312 ;; we don't care how the cases drop into each other
5313 (js2-clear-flag rv js2-END_DROPS_OFF)
5314 ;; examine the default
5315 (js2-set-flag rv (if default-case
5316 (js2-end-check default-case)
5317 js2-END_DROPS_OFF))
5318 rv))
5319
5320 (defun js2-end-check-try (node)
5321 "If the block has a finally, return consistency is checked in the
5322 finally block. If all code paths in the finally return, then the
5323 returns in the try-catch blocks don't matter. If there is a code path
5324 that does not return or if there is no finally block, the returns
5325 of the try and catch blocks are checked for mismatch.
5326 Returns logical OR of END_* flags."
5327 (let ((finally (js2-try-node-finally-block node))
5328 rv)
5329 ;; check the finally if it exists
5330 (setq rv (if finally
5331 (js2-end-check (js2-finally-node-body finally))
5332 js2-END_DROPS_OFF))
5333 ;; If the finally block always returns, then none of the returns
5334 ;; in the try or catch blocks matter.
5335 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5336 (js2-clear-flag rv js2-END_DROPS_OFF)
5337 ;; examine the try block
5338 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5339 ;; check each catch block
5340 (dolist (cb (js2-try-node-catch-clauses node))
5341 (js2-set-flag rv (js2-end-check cb))))
5342 rv))
5343
5344 (defun js2-end-check-loop (node)
5345 "Return statement in the loop body must be consistent.
5346 The default assumption for any kind of a loop is that it will eventually
5347 terminate. The only exception is a loop with a constant true condition.
5348 Code that follows such a loop is examined only if one can determine
5349 statically that there is a break out of the loop.
5350
5351 for(... ; ... ; ...) {}
5352 for(... in ... ) {}
5353 while(...) { }
5354 do { } while(...)
5355
5356 Returns logical OR of END_* flags."
5357 (let ((rv (js2-end-check (js2-loop-node-body node)))
5358 (condition (cond
5359 ((js2-while-node-p node)
5360 (js2-while-node-condition node))
5361 ((js2-do-node-p node)
5362 (js2-do-node-condition node))
5363 ((js2-for-node-p node)
5364 (js2-for-node-condition node)))))
5365
5366 ;; check to see if the loop condition is always true
5367 (if (and condition
5368 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5369 (js2-clear-flag rv js2-END_DROPS_OFF))
5370
5371 ;; look for effect of breaks
5372 (js2-set-flag rv (js2-node-get-prop node
5373 'CONTROL_BLOCK_PROP
5374 js2-END_UNREACHED))
5375 rv))
5376
5377 (defun js2-end-check-block (node)
5378 "A general block of code is examined statement by statement.
5379 If any statement (even a compound one) returns in all branches, then
5380 subsequent statements are not examined.
5381 Returns logical OR of END_* flags."
5382 (let* ((rv js2-END_DROPS_OFF)
5383 (kids (js2-block-node-kids node))
5384 (n (car kids)))
5385 ;; Check each statement. If the statement can continue onto the next
5386 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5387 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5388 (js2-clear-flag rv js2-END_DROPS_OFF)
5389 (js2-set-flag rv (js2-end-check n))
5390 (setq kids (cdr kids)
5391 n (car kids)))
5392 rv))
5393
5394 (defun js2-end-check-label (node)
5395 "A labeled statement implies that there may be a break to the label.
5396 The function processes the labeled statement and then checks the
5397 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5398 particular label.
5399 Returns logical OR of END_* flags."
5400 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5401 (logior rv (js2-node-get-prop node
5402 'CONTROL_BLOCK_PROP
5403 js2-END_UNREACHED))))
5404
5405 (defun js2-end-check-break (node)
5406 "When a break is encountered annotate the statement being broken
5407 out of by setting its CONTROL_BLOCK_PROP property.
5408 Returns logical OR of END_* flags."
5409 (and (js2-break-node-target node)
5410 (js2-node-set-prop (js2-break-node-target node)
5411 'CONTROL_BLOCK_PROP
5412 js2-END_DROPS_OFF))
5413 js2-END_UNREACHED)
5414
5415 (defun js2-end-check (node)
5416 "Examine the body of a function, doing a basic reachability analysis.
5417 Returns a combination of flags END_* flags that indicate
5418 how the function execution can terminate. These constitute only the
5419 pessimistic set of termination conditions. It is possible that at
5420 runtime certain code paths will never be actually taken. Hence this
5421 analysis will flag errors in cases where there may not be errors.
5422 Returns logical OR of END_* flags"
5423 (let (kid)
5424 (cond
5425 ((js2-break-node-p node)
5426 (js2-end-check-break node))
5427 ((js2-expr-stmt-node-p node)
5428 (if (setq kid (js2-expr-stmt-node-expr node))
5429 (js2-end-check kid)
5430 js2-END_DROPS_OFF))
5431 ((or (js2-continue-node-p node)
5432 (js2-throw-node-p node))
5433 js2-END_UNREACHED)
5434 ((js2-return-node-p node)
5435 (if (setq kid (js2-return-node-retval node))
5436 js2-END_RETURNS_VALUE
5437 js2-END_RETURNS))
5438 ((js2-loop-node-p node)
5439 (js2-end-check-loop node))
5440 ((js2-switch-node-p node)
5441 (js2-end-check-switch node))
5442 ((js2-labeled-stmt-node-p node)
5443 (js2-end-check-label node))
5444 ((js2-if-node-p node)
5445 (js2-end-check-if node))
5446 ((js2-try-node-p node)
5447 (js2-end-check-try node))
5448 ((js2-block-node-p node)
5449 (if (null (js2-block-node-kids node))
5450 js2-END_DROPS_OFF
5451 (js2-end-check-block node)))
5452 ((js2-yield-node-p node)
5453 js2-END_YIELDS)
5454 (t
5455 js2-END_DROPS_OFF))))
5456
5457 (defun js2-always-defined-boolean-p (node)
5458 "Check if NODE always evaluates to true or false in boolean context.
5459 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5460 nor always false."
5461 (let ((tt (js2-node-type node))
5462 num)
5463 (cond
5464 ((or (= tt js2-FALSE) (= tt js2-NULL))
5465 'ALWAYS_FALSE)
5466 ((= tt js2-TRUE)
5467 'ALWAYS_TRUE)
5468 ((= tt js2-NUMBER)
5469 (setq num (js2-number-node-num-value node))
5470 (if (and (not (eq num 0.0e+NaN))
5471 (not (zerop num)))
5472 'ALWAYS_TRUE
5473 'ALWAYS_FALSE))
5474 (t
5475 nil))))
5476
5477 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5478 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5479
5480 (defvar js2-tokens nil
5481 "List of all defined token names.") ; initialized in `js2-token-names'
5482
5483 (defconst js2-token-names
5484 (let* ((names (make-vector js2-num-tokens -1))
5485 (case-fold-search nil) ; only match js2-UPPER_CASE
5486 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5487 (cl-loop for sym in syms
5488 for i from 0
5489 do
5490 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5491 (not (boundp sym)))
5492 (aset names (symbol-value sym) ; code, e.g. 152
5493 (downcase
5494 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5495 (push sym js2-tokens)))
5496 names)
5497 "Vector mapping int values to token string names, sans `js2-' prefix.")
5498
5499 (defun js2-tt-name (tok)
5500 "Return a string name for TOK, a token symbol or code.
5501 Signals an error if it's not a recognized token."
5502 (let ((code tok))
5503 (if (symbolp tok)
5504 (setq code (symbol-value tok)))
5505 (if (eq code -1)
5506 "ERROR"
5507 (if (and (numberp code)
5508 (not (cl-minusp code))
5509 (< code js2-num-tokens))
5510 (aref js2-token-names code)
5511 (error "Invalid token: %s" code)))))
5512
5513 (defsubst js2-tt-sym (tok)
5514 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5515 (intern (js2-tt-name tok)))
5516
5517 (defconst js2-token-codes
5518 (let ((table (make-hash-table :test 'eq :size 256)))
5519 (cl-loop for name across js2-token-names
5520 for sym = (intern (concat "js2-" (upcase name)))
5521 do
5522 (puthash sym (symbol-value sym) table))
5523 ;; clean up a few that are "wrong" in Rhino's token codes
5524 (puthash 'js2-DELETE js2-DELPROP table)
5525 table)
5526 "Hashtable mapping token type symbols to their bytecodes.")
5527
5528 (defsubst js2-tt-code (sym)
5529 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5530 (or (gethash sym js2-token-codes)
5531 (error "Invalid token symbol: %s " sym))) ; signal code bug
5532
5533 (defun js2-report-scan-error (msg &optional no-throw beg len)
5534 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5535 (js2-report-error msg nil
5536 (or beg (js2-current-token-beg))
5537 (or len (js2-current-token-len)))
5538 (unless no-throw
5539 (throw 'return js2-ERROR)))
5540
5541 (defun js2-set-string-from-buffer (token)
5542 "Set `string' and `end' slots for TOKEN, return the string."
5543 (setf (js2-token-end token) js2-ts-cursor
5544 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5545
5546 ;; TODO: could potentially avoid a lot of consing by allocating a
5547 ;; char buffer the way Rhino does.
5548 (defsubst js2-add-to-string (c)
5549 (push c js2-ts-string-buffer))
5550
5551 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5552 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5553 ;; any other character: when it's not part of the current token, we
5554 ;; unget it, allowing it to be read again by the following call.
5555 (defsubst js2-unget-char ()
5556 (cl-decf js2-ts-cursor))
5557
5558 ;; Rhino distinguishes \r and \n line endings. We don't need to
5559 ;; because we only scan from Emacs buffers, which always use \n.
5560 (defun js2-get-char ()
5561 "Read and return the next character from the input buffer.
5562 Increments `js2-ts-lineno' if the return value is a newline char.
5563 Updates `js2-ts-cursor' to the point after the returned char.
5564 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5565 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5566 (let (c)
5567 ;; check for end of buffer
5568 (if (>= js2-ts-cursor (point-max))
5569 (setq js2-ts-hit-eof t
5570 js2-ts-cursor (1+ js2-ts-cursor)
5571 c js2-EOF_CHAR) ; return value
5572 ;; otherwise read next char
5573 (setq c (char-before (cl-incf js2-ts-cursor)))
5574 ;; if we read a newline, update counters
5575 (if (= c ?\n)
5576 (setq js2-ts-line-start js2-ts-cursor
5577 js2-ts-lineno (1+ js2-ts-lineno)))
5578 ;; TODO: skip over format characters
5579 c)))
5580
5581 (defun js2-read-unicode-escape ()
5582 "Read a \\uNNNN sequence from the input.
5583 Assumes the ?\ and ?u have already been read.
5584 Returns the unicode character, or nil if it wasn't a valid character.
5585 Doesn't change the values of any scanner variables."
5586 ;; I really wish I knew a better way to do this, but I can't
5587 ;; find the Emacs function that takes a 16-bit int and converts
5588 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5589 ;; Have to first check that it's 4 hex characters or it may stop
5590 ;; the read early.
5591 (ignore-errors
5592 (let ((s (buffer-substring-no-properties js2-ts-cursor
5593 (+ 4 js2-ts-cursor))))
5594 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5595 (read (concat "?\\u" s))))))
5596
5597 (defun js2-match-char (test)
5598 "Consume and return next character if it matches TEST, a character.
5599 Returns nil and consumes nothing if TEST is not the next character."
5600 (let ((c (js2-get-char)))
5601 (if (eq c test)
5602 t
5603 (js2-unget-char)
5604 nil)))
5605
5606 (defun js2-peek-char ()
5607 (prog1
5608 (js2-get-char)
5609 (js2-unget-char)))
5610
5611 (defun js2-identifier-start-p (c)
5612 "Is C a valid start to an ES5 Identifier?
5613 See http://es5.github.io/#x7.6"
5614 (or
5615 (memq c '(?$ ?_))
5616 (memq (get-char-code-property c 'general-category)
5617 ;; Letters
5618 '(Lu Ll Lt Lm Lo Nl))))
5619
5620 (defun js2-identifier-part-p (c)
5621 "Is C a valid part of an ES5 Identifier?
5622 See http://es5.github.io/#x7.6"
5623 (or
5624 (memq c '(?$ ?_ ?\u200c ?\u200d))
5625 (memq (get-char-code-property c 'general-category)
5626 '(;; Letters
5627 Lu Ll Lt Lm Lo Nl
5628 ;; Combining Marks
5629 Mn Mc
5630 ;; Digits
5631 Nd
5632 ;; Connector Punctuation
5633 Pc))))
5634
5635 (defun js2-alpha-p (c)
5636 (cond ((and (<= ?A c) (<= c ?Z)) t)
5637 ((and (<= ?a c) (<= c ?z)) t)
5638 (t nil)))
5639
5640 (defsubst js2-digit-p (c)
5641 (and (<= ?0 c) (<= c ?9)))
5642
5643 (defun js2-js-space-p (c)
5644 (if (<= c 127)
5645 (memq c '(#x20 #x9 #xB #xC #xD))
5646 (or
5647 (eq c #xA0)
5648 ;; TODO: change this nil to check for Unicode space character
5649 nil)))
5650
5651 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5652
5653 (defun js2-skip-line ()
5654 "Skip to end of line."
5655 (while (not (memq (js2-get-char) js2-eol-chars)))
5656 (js2-unget-char)
5657 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5658
5659 (defun js2-init-scanner (&optional buf line)
5660 "Create token stream for BUF starting on LINE.
5661 BUF defaults to `current-buffer' and LINE defaults to 1.
5662
5663 A buffer can only have one scanner active at a time, which yields
5664 dramatically simpler code than using a defstruct. If you need to
5665 have simultaneous scanners in a buffer, copy the regions to scan
5666 into temp buffers."
5667 (with-current-buffer (or buf (current-buffer))
5668 (setq js2-ts-dirty-line nil
5669 js2-ts-hit-eof nil
5670 js2-ts-line-start 0
5671 js2-ts-lineno (or line 1)
5672 js2-ts-line-end-char -1
5673 js2-ts-cursor (point-min)
5674 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5675 js2-ti-tokens-cursor 0
5676 js2-ti-lookahead 0
5677 js2-ts-is-xml-attribute nil
5678 js2-ts-xml-is-tag-content nil
5679 js2-ts-xml-open-tags-count 0
5680 js2-ts-string-buffer nil)))
5681
5682 ;; This function uses the cached op, string and number fields in
5683 ;; TokenStream; if getToken has been called since the passed token
5684 ;; was scanned, the op or string printed may be incorrect.
5685 (defun js2-token-to-string (token)
5686 ;; Not sure where this function is used in Rhino. Not tested.
5687 (if (not js2-debug-print-trees)
5688 ""
5689 (let ((name (js2-tt-name token)))
5690 (cond
5691 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5692 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5693 (concat name " `" (js2-current-token-string) "'"))
5694 ((eq token js2-NUMBER)
5695 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5696 (t
5697 name)))))
5698
5699 (defconst js2-keywords
5700 '(break
5701 case catch class const continue
5702 debugger default delete do
5703 else extends export
5704 false finally for function
5705 if in instanceof import
5706 let
5707 new null
5708 return
5709 super switch
5710 this throw true try typeof
5711 var void
5712 while with
5713 yield))
5714
5715 ;; Token names aren't exactly the same as the keywords, unfortunately.
5716 ;; E.g. delete is js2-DELPROP.
5717 (defconst js2-kwd-tokens
5718 (let ((table (make-vector js2-num-tokens nil))
5719 (tokens
5720 (list js2-BREAK
5721 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5722 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5723 js2-ELSE js2-EXPORT
5724 js2-ELSE js2-EXTENDS js2-EXPORT
5725 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5726 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5727 js2-LET
5728 js2-NEW js2-NULL
5729 js2-RETURN
5730 js2-SUPER js2-SWITCH
5731 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5732 js2-VAR
5733 js2-WHILE js2-WITH
5734 js2-YIELD)))
5735 (dolist (i tokens)
5736 (aset table i 'font-lock-keyword-face))
5737 (aset table js2-STRING 'font-lock-string-face)
5738 (aset table js2-REGEXP 'font-lock-string-face)
5739 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5740 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5741 (aset table js2-COMMENT 'font-lock-comment-face)
5742 (aset table js2-THIS 'font-lock-builtin-face)
5743 (aset table js2-SUPER 'font-lock-builtin-face)
5744 (aset table js2-VOID 'font-lock-constant-face)
5745 (aset table js2-NULL 'font-lock-constant-face)
5746 (aset table js2-TRUE 'font-lock-constant-face)
5747 (aset table js2-FALSE 'font-lock-constant-face)
5748 (aset table js2-NOT 'font-lock-negation-char-face)
5749 table)
5750 "Vector whose values are non-nil for tokens that are keywords.
5751 The values are default faces to use for highlighting the keywords.")
5752
5753 ;; FIXME: Support strict mode-only future reserved words, after we know
5754 ;; which parts scopes are in strict mode, and which are not.
5755 (defconst js2-reserved-words '(class enum export extends import static super)
5756 "Future reserved keywords in ECMAScript 5.1.")
5757
5758 (defconst js2-keyword-names
5759 (let ((table (make-hash-table :test 'equal)))
5760 (cl-loop for k in js2-keywords
5761 do (puthash
5762 (symbol-name k) ; instanceof
5763 (intern (concat "js2-"
5764 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5765 table))
5766 table)
5767 "JavaScript keywords by name, mapped to their symbols.")
5768
5769 (defconst js2-reserved-word-names
5770 (let ((table (make-hash-table :test 'equal)))
5771 (cl-loop for k in js2-reserved-words
5772 do
5773 (puthash (symbol-name k) 'js2-RESERVED table))
5774 table)
5775 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5776
5777 (defun js2-collect-string (buf)
5778 "Convert BUF, a list of chars, to a string.
5779 Reverses BUF before converting."
5780 (if buf
5781 (apply #'string (nreverse buf))
5782 ""))
5783
5784 (defun js2-string-to-keyword (s)
5785 "Return token for S, a string, if S is a keyword or reserved word.
5786 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5787 (or (gethash s js2-keyword-names)
5788 (gethash s js2-reserved-word-names)))
5789
5790 (defsubst js2-ts-set-char-token-bounds (token)
5791 "Used when next token is one character."
5792 (setf (js2-token-beg token) (1- js2-ts-cursor)
5793 (js2-token-end token) js2-ts-cursor))
5794
5795 (defsubst js2-ts-return (token type)
5796 "Update the `end' and `type' slots of TOKEN,
5797 then throw `return' with value TYPE."
5798 (setf (js2-token-end token) js2-ts-cursor
5799 (js2-token-type token) type)
5800 (throw 'return type))
5801
5802 (defun js2-x-digit-to-int (c accumulator)
5803 "Build up a hex number.
5804 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5805 corresponding number. Otherwise return -1."
5806 (catch 'return
5807 (catch 'check
5808 ;; Use 0..9 < A..Z < a..z
5809 (cond
5810 ((<= c ?9)
5811 (cl-decf c ?0)
5812 (if (<= 0 c)
5813 (throw 'check nil)))
5814 ((<= c ?F)
5815 (when (<= ?A c)
5816 (cl-decf c (- ?A 10))
5817 (throw 'check nil)))
5818 ((<= c ?f)
5819 (when (<= ?a c)
5820 (cl-decf c (- ?a 10))
5821 (throw 'check nil))))
5822 (throw 'return -1))
5823 (logior c (lsh accumulator 4))))
5824
5825 (defun js2-get-token (&optional modifier)
5826 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5827 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5828 next saved token.
5829
5830 This function will not return a newline (js2-EOL) - instead, it
5831 gobbles newlines until it finds a non-newline token. Call
5832 `js2-peek-token-or-eol' when you care about newlines.
5833
5834 This function will also not return a js2-COMMENT. Instead, it
5835 records comments found in `js2-scanned-comments'. If the token
5836 returned by this function immediately follows a jsdoc comment,
5837 the token is flagged as such."
5838 (if (zerop js2-ti-lookahead)
5839 (js2-get-token-internal modifier)
5840 (cl-decf js2-ti-lookahead)
5841 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5842 (let ((tt (js2-current-token-type)))
5843 (cl-assert (not (= tt js2-EOL)))
5844 tt)))
5845
5846 (defun js2-unget-token ()
5847 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5848 (cl-incf js2-ti-lookahead)
5849 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5850
5851 (defun js2-get-token-internal (modifier)
5852 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5853 (tt (js2-token-type token))
5854 saw-eol
5855 face)
5856 ;; process comments
5857 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5858 (if (= tt js2-EOL)
5859 (setq saw-eol t)
5860 (setq saw-eol nil)
5861 (when js2-record-comments
5862 (js2-record-comment token)))
5863 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5864 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5865 tt (js2-token-type token)))
5866
5867 (when saw-eol
5868 (setf (js2-token-follows-eol-p token) t))
5869
5870 ;; perform lexical fontification as soon as token is scanned
5871 (when js2-parse-ide-mode
5872 (cond
5873 ((cl-minusp tt)
5874 (js2-record-face 'js2-error token))
5875 ((setq face (aref js2-kwd-tokens tt))
5876 (js2-record-face face token))
5877 ((and (= tt js2-NAME)
5878 (equal (js2-token-string token) "undefined"))
5879 (js2-record-face 'font-lock-constant-face token))))
5880 tt))
5881
5882 (defsubst js2-string-to-number (str base)
5883 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5884 (condition-case nil
5885 (string-to-number str base)
5886 (overflow-error -1)))
5887
5888 (defun js2-get-token-internal-1 (modifier)
5889 "Return next JavaScript token type, an int such as js2-RETURN.
5890 During operation, creates an instance of `js2-token' struct, sets
5891 its relevant fields and puts it into `js2-ti-tokens'."
5892 (let (identifier-start
5893 is-unicode-escape-start c
5894 contains-escape escape-val str result base
5895 look-for-slash continue tt
5896 (token (js2-new-token 0)))
5897 (setq
5898 tt
5899 (catch 'return
5900 (when (eq modifier 'TEMPLATE_TAIL)
5901 (setf (js2-token-beg token) (1- js2-ts-cursor))
5902 (throw 'return (js2-get-string-or-template-token ?` token)))
5903 (while t
5904 ;; Eat whitespace, possibly sensitive to newlines.
5905 (setq continue t)
5906 (while continue
5907 (setq c (js2-get-char))
5908 (cond
5909 ((eq c js2-EOF_CHAR)
5910 (js2-unget-char)
5911 (js2-ts-set-char-token-bounds token)
5912 (throw 'return js2-EOF))
5913 ((eq c ?\n)
5914 (js2-ts-set-char-token-bounds token)
5915 (setq js2-ts-dirty-line nil)
5916 (throw 'return js2-EOL))
5917 ((not (js2-js-space-p c))
5918 (if (/= c ?-) ; in case end of HTML comment
5919 (setq js2-ts-dirty-line t))
5920 (setq continue nil))))
5921 ;; Assume the token will be 1 char - fixed up below.
5922 (js2-ts-set-char-token-bounds token)
5923 (when (eq c ?@)
5924 (throw 'return js2-XMLATTR))
5925 ;; identifier/keyword/instanceof?
5926 ;; watch out for starting with a <backslash>
5927 (cond
5928 ((eq c ?\\)
5929 (setq c (js2-get-char))
5930 (if (eq c ?u)
5931 (setq identifier-start t
5932 is-unicode-escape-start t
5933 js2-ts-string-buffer nil)
5934 (setq identifier-start nil)
5935 (js2-unget-char)
5936 (setq c ?\\)))
5937 (t
5938 (when (setq identifier-start (js2-identifier-start-p c))
5939 (setq js2-ts-string-buffer nil)
5940 (js2-add-to-string c))))
5941 (when identifier-start
5942 (setq contains-escape is-unicode-escape-start)
5943 (catch 'break
5944 (while t
5945 (if is-unicode-escape-start
5946 ;; strictly speaking we should probably push-back
5947 ;; all the bad characters if the <backslash>uXXXX
5948 ;; sequence is malformed. But since there isn't a
5949 ;; correct context(is there?) for a bad Unicode
5950 ;; escape sequence in an identifier, we can report
5951 ;; an error here.
5952 (progn
5953 (setq escape-val 0)
5954 (dotimes (_ 4)
5955 (setq c (js2-get-char)
5956 escape-val (js2-x-digit-to-int c escape-val))
5957 ;; Next check takes care of c < 0 and bad escape
5958 (if (cl-minusp escape-val)
5959 (throw 'break nil)))
5960 (if (cl-minusp escape-val)
5961 (js2-report-scan-error "msg.invalid.escape" t))
5962 (js2-add-to-string escape-val)
5963 (setq is-unicode-escape-start nil))
5964 (setq c (js2-get-char))
5965 (cond
5966 ((eq c ?\\)
5967 (setq c (js2-get-char))
5968 (if (eq c ?u)
5969 (setq is-unicode-escape-start t
5970 contains-escape t)
5971 (js2-report-scan-error "msg.illegal.character" t)))
5972 (t
5973 (if (or (eq c js2-EOF_CHAR)
5974 (not (js2-identifier-part-p c)))
5975 (throw 'break nil))
5976 (js2-add-to-string c))))))
5977 (js2-unget-char)
5978 (setf str (js2-collect-string js2-ts-string-buffer)
5979 (js2-token-end token) js2-ts-cursor)
5980 ;; FIXME: Invalid in ES5 and ES6, see
5981 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5982 ;; Probably should just drop this conditional.
5983 (unless contains-escape
5984 ;; OPT we shouldn't have to make a string (object!) to
5985 ;; check if it's a keyword.
5986 ;; Return the corresponding token if it's a keyword
5987 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5988 (setq result (js2-string-to-keyword str)))
5989 (if (and (< js2-language-version 170)
5990 (memq result '(js2-LET js2-YIELD)))
5991 ;; LET and YIELD are tokens only in 1.7 and later
5992 (setq result 'js2-NAME))
5993 (when (eq result 'js2-RESERVED)
5994 (setf (js2-token-string token) str))
5995 (throw 'return (js2-tt-code result))))
5996 ;; If we want to intern these as Rhino does, just use (intern str)
5997 (setf (js2-token-string token) str)
5998 (throw 'return js2-NAME)) ; end identifier/kwd check
5999 ;; is it a number?
6000 (when (or (js2-digit-p c)
6001 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6002 (setq js2-ts-string-buffer nil
6003 base 10)
6004 (when (eq c ?0)
6005 (setq c (js2-get-char))
6006 (cond
6007 ((or (eq c ?x) (eq c ?X))
6008 (setq base 16)
6009 (setq c (js2-get-char)))
6010 ((and (or (eq c ?b) (eq c ?B))
6011 (>= js2-language-version 200))
6012 (setq base 2)
6013 (setq c (js2-get-char)))
6014 ((and (or (eq c ?o) (eq c ?O))
6015 (>= js2-language-version 200))
6016 (setq base 8)
6017 (setq c (js2-get-char)))
6018 ((js2-digit-p c)
6019 (setq base 'maybe-8))
6020 (t
6021 (js2-add-to-string ?0))))
6022 (cond
6023 ((eq base 16)
6024 (if (> 0 (js2-x-digit-to-int c 0))
6025 (js2-report-scan-error "msg.missing.hex.digits")
6026 (while (<= 0 (js2-x-digit-to-int c 0))
6027 (js2-add-to-string c)
6028 (setq c (js2-get-char)))))
6029 ((eq base 2)
6030 (if (not (memq c '(?0 ?1)))
6031 (js2-report-scan-error "msg.missing.binary.digits")
6032 (while (memq c '(?0 ?1))
6033 (js2-add-to-string c)
6034 (setq c (js2-get-char)))))
6035 ((eq base 8)
6036 (if (or (> ?0 c) (< ?7 c))
6037 (js2-report-scan-error "msg.missing.octal.digits")
6038 (while (and (<= ?0 c) (>= ?7 c))
6039 (js2-add-to-string c)
6040 (setq c (js2-get-char)))))
6041 (t
6042 (while (and (<= ?0 c) (<= c ?9))
6043 ;; We permit 08 and 09 as decimal numbers, which
6044 ;; makes our behavior a superset of the ECMA
6045 ;; numeric grammar. We might not always be so
6046 ;; permissive, so we warn about it.
6047 (when (and (eq base 'maybe-8) (>= c ?8))
6048 (js2-report-warning "msg.bad.octal.literal"
6049 (if (eq c ?8) "8" "9"))
6050 (setq base 10))
6051 (js2-add-to-string c)
6052 (setq c (js2-get-char)))
6053 (when (eq base 'maybe-8)
6054 (setq base 8))))
6055 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6056 (when (eq c ?.)
6057 (cl-loop do
6058 (js2-add-to-string c)
6059 (setq c (js2-get-char))
6060 while (js2-digit-p c)))
6061 (when (memq c '(?e ?E))
6062 (js2-add-to-string c)
6063 (setq c (js2-get-char))
6064 (when (memq c '(?+ ?-))
6065 (js2-add-to-string c)
6066 (setq c (js2-get-char)))
6067 (unless (js2-digit-p c)
6068 (js2-report-scan-error "msg.missing.exponent" t))
6069 (cl-loop do
6070 (js2-add-to-string c)
6071 (setq c (js2-get-char))
6072 while (js2-digit-p c))))
6073 (js2-unget-char)
6074 (let ((str (js2-set-string-from-buffer token)))
6075 (setf (js2-token-number token) (js2-string-to-number str base)
6076 (js2-token-number-base token) base))
6077 (throw 'return js2-NUMBER))
6078 ;; is it a string?
6079 (when (or (memq c '(?\" ?\'))
6080 (and (>= js2-language-version 200)
6081 (= c ?`)))
6082 (throw 'return
6083 (js2-get-string-or-template-token c token)))
6084 (js2-ts-return token
6085 (cl-case c
6086 (?\;
6087 (throw 'return js2-SEMI))
6088 (?\[
6089 (throw 'return js2-LB))
6090 (?\]
6091 (throw 'return js2-RB))
6092 (?{
6093 (throw 'return js2-LC))
6094 (?}
6095 (throw 'return js2-RC))
6096 (?\(
6097 (throw 'return js2-LP))
6098 (?\)
6099 (throw 'return js2-RP))
6100 (?,
6101 (throw 'return js2-COMMA))
6102 (??
6103 (throw 'return js2-HOOK))
6104 (?:
6105 (if (js2-match-char ?:)
6106 js2-COLONCOLON
6107 (throw 'return js2-COLON)))
6108 (?.
6109 (if (js2-match-char ?.)
6110 (if (js2-match-char ?.)
6111 js2-TRIPLEDOT js2-DOTDOT)
6112 (if (js2-match-char ?\()
6113 js2-DOTQUERY
6114 (throw 'return js2-DOT))))
6115 (?|
6116 (if (js2-match-char ?|)
6117 (throw 'return js2-OR)
6118 (if (js2-match-char ?=)
6119 js2-ASSIGN_BITOR
6120 (throw 'return js2-BITOR))))
6121 (?^
6122 (if (js2-match-char ?=)
6123 js2-ASSIGN_BITOR
6124 (throw 'return js2-BITXOR)))
6125 (?&
6126 (if (js2-match-char ?&)
6127 (throw 'return js2-AND)
6128 (if (js2-match-char ?=)
6129 js2-ASSIGN_BITAND
6130 (throw 'return js2-BITAND))))
6131 (?=
6132 (if (js2-match-char ?=)
6133 (if (js2-match-char ?=)
6134 js2-SHEQ
6135 (throw 'return js2-EQ))
6136 (if (js2-match-char ?>)
6137 (js2-ts-return token js2-ARROW)
6138 (throw 'return js2-ASSIGN))))
6139 (?!
6140 (if (js2-match-char ?=)
6141 (if (js2-match-char ?=)
6142 js2-SHNE
6143 js2-NE)
6144 (throw 'return js2-NOT)))
6145 (?<
6146 ;; NB:treat HTML begin-comment as comment-till-eol
6147 (when (js2-match-char ?!)
6148 (when (js2-match-char ?-)
6149 (when (js2-match-char ?-)
6150 (js2-skip-line)
6151 (setf (js2-token-comment-type (js2-current-token)) 'html)
6152 (throw 'return js2-COMMENT)))
6153 (js2-unget-char))
6154 (if (js2-match-char ?<)
6155 (if (js2-match-char ?=)
6156 js2-ASSIGN_LSH
6157 js2-LSH)
6158 (if (js2-match-char ?=)
6159 js2-LE
6160 (throw 'return js2-LT))))
6161 (?>
6162 (if (js2-match-char ?>)
6163 (if (js2-match-char ?>)
6164 (if (js2-match-char ?=)
6165 js2-ASSIGN_URSH
6166 js2-URSH)
6167 (if (js2-match-char ?=)
6168 js2-ASSIGN_RSH
6169 js2-RSH))
6170 (if (js2-match-char ?=)
6171 js2-GE
6172 (throw 'return js2-GT))))
6173 (?*
6174 (if (js2-match-char ?=)
6175 js2-ASSIGN_MUL
6176 (throw 'return js2-MUL)))
6177 (?/
6178 ;; is it a // comment?
6179 (when (js2-match-char ?/)
6180 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6181 (js2-skip-line)
6182 (setf (js2-token-comment-type token) 'line)
6183 ;; include newline so highlighting goes to end of
6184 ;; window, if there actually is a newline; if we
6185 ;; hit eof, then implicitly there isn't
6186 (unless js2-ts-hit-eof
6187 (cl-incf (js2-token-end token)))
6188 (throw 'return js2-COMMENT))
6189 ;; is it a /* comment?
6190 (when (js2-match-char ?*)
6191 (setf look-for-slash nil
6192 (js2-token-beg token) (- js2-ts-cursor 2)
6193 (js2-token-comment-type token)
6194 (if (js2-match-char ?*)
6195 (progn
6196 (setq look-for-slash t)
6197 'jsdoc)
6198 'block))
6199 (while t
6200 (setq c (js2-get-char))
6201 (cond
6202 ((eq c js2-EOF_CHAR)
6203 (setf (js2-token-end token) (1- js2-ts-cursor))
6204 (js2-report-error "msg.unterminated.comment")
6205 (throw 'return js2-COMMENT))
6206 ((eq c ?*)
6207 (setq look-for-slash t))
6208 ((eq c ?/)
6209 (if look-for-slash
6210 (js2-ts-return token js2-COMMENT)))
6211 (t
6212 (setf look-for-slash nil
6213 (js2-token-end token) js2-ts-cursor)))))
6214 (if (js2-match-char ?=)
6215 js2-ASSIGN_DIV
6216 (throw 'return js2-DIV)))
6217 (?#
6218 (when js2-skip-preprocessor-directives
6219 (js2-skip-line)
6220 (setf (js2-token-comment-type token) 'preprocessor
6221 (js2-token-end token) js2-ts-cursor)
6222 (throw 'return js2-COMMENT))
6223 (throw 'return js2-ERROR))
6224 (?%
6225 (if (js2-match-char ?=)
6226 js2-ASSIGN_MOD
6227 (throw 'return js2-MOD)))
6228 (?~
6229 (throw 'return js2-BITNOT))
6230 (?+
6231 (if (js2-match-char ?=)
6232 js2-ASSIGN_ADD
6233 (if (js2-match-char ?+)
6234 js2-INC
6235 (throw 'return js2-ADD))))
6236 (?-
6237 (cond
6238 ((js2-match-char ?=)
6239 (setq c js2-ASSIGN_SUB))
6240 ((js2-match-char ?-)
6241 (unless js2-ts-dirty-line
6242 ;; treat HTML end-comment after possible whitespace
6243 ;; after line start as comment-until-eol
6244 (when (js2-match-char ?>)
6245 (js2-skip-line)
6246 (setf (js2-token-comment-type (js2-current-token)) 'html)
6247 (throw 'return js2-COMMENT)))
6248 (setq c js2-DEC))
6249 (t
6250 (setq c js2-SUB)))
6251 (setq js2-ts-dirty-line t)
6252 c)
6253 (otherwise
6254 (js2-report-scan-error "msg.illegal.character")))))))
6255 (setf (js2-token-type token) tt)
6256 token))
6257
6258 (defun js2-get-string-or-template-token (quote-char token)
6259 ;; We attempt to accumulate a string the fast way, by
6260 ;; building it directly out of the reader. But if there
6261 ;; are any escaped characters in the string, we revert to
6262 ;; building it out of a string buffer.
6263 (let ((c (js2-get-char))
6264 js2-ts-string-buffer
6265 nc c1 val escape-val)
6266 (catch 'break
6267 (while (/= c quote-char)
6268 (catch 'continue
6269 (when (eq c js2-EOF_CHAR)
6270 (js2-unget-char)
6271 (js2-report-error "msg.unterminated.string.lit")
6272 (throw 'break nil))
6273 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6274 (js2-unget-char)
6275 (js2-report-error "msg.unterminated.string.lit")
6276 (throw 'break nil))
6277 (when (eq c ?\\)
6278 ;; We've hit an escaped character
6279 (setq c (js2-get-char))
6280 (cl-case c
6281 (?b (setq c ?\b))
6282 (?f (setq c ?\f))
6283 (?n (setq c ?\n))
6284 (?r (setq c ?\r))
6285 (?t (setq c ?\t))
6286 (?v (setq c ?\v))
6287 (?u
6288 (setq c1 (js2-read-unicode-escape))
6289 (if js2-parse-ide-mode
6290 (if c1
6291 (progn
6292 ;; just copy the string in IDE-mode
6293 (js2-add-to-string ?\\)
6294 (js2-add-to-string ?u)
6295 (dotimes (_ 3)
6296 (js2-add-to-string (js2-get-char)))
6297 (setq c (js2-get-char))) ; added at end of loop
6298 ;; flag it as an invalid escape
6299 (js2-report-warning "msg.invalid.escape"
6300 nil (- js2-ts-cursor 2) 6))
6301 ;; Get 4 hex digits; if the u escape is not
6302 ;; followed by 4 hex digits, use 'u' + the
6303 ;; literal character sequence that follows.
6304 (js2-add-to-string ?u)
6305 (setq escape-val 0)
6306 (dotimes (_ 4)
6307 (setq c (js2-get-char)
6308 escape-val (js2-x-digit-to-int c escape-val))
6309 (if (cl-minusp escape-val)
6310 (throw 'continue nil))
6311 (js2-add-to-string c))
6312 ;; prepare for replace of stored 'u' sequence by escape value
6313 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6314 c escape-val)))
6315 (?x
6316 ;; Get 2 hex digits, defaulting to 'x'+literal
6317 ;; sequence, as above.
6318 (setq c (js2-get-char)
6319 escape-val (js2-x-digit-to-int c 0))
6320 (if (cl-minusp escape-val)
6321 (progn
6322 (js2-add-to-string ?x)
6323 (throw 'continue nil))
6324 (setq c1 c
6325 c (js2-get-char)
6326 escape-val (js2-x-digit-to-int c escape-val))
6327 (if (cl-minusp escape-val)
6328 (progn
6329 (js2-add-to-string ?x)
6330 (js2-add-to-string c1)
6331 (throw 'continue nil))
6332 ;; got 2 hex digits
6333 (setq c escape-val))))
6334 (?\n
6335 ;; Remove line terminator after escape to follow
6336 ;; SpiderMonkey and C/C++
6337 (setq c (js2-get-char))
6338 (throw 'continue nil))
6339 (t
6340 (when (and (<= ?0 c) (< c ?8))
6341 (setq val (- c ?0)
6342 c (js2-get-char))
6343 (when (and (<= ?0 c) (< c ?8))
6344 (setq val (- (+ (* 8 val) c) ?0)
6345 c (js2-get-char))
6346 (when (and (<= ?0 c)
6347 (< c ?8)
6348 (< val #o37))
6349 ;; c is 3rd char of octal sequence only
6350 ;; if the resulting val <= 0377
6351 (setq val (- (+ (* 8 val) c) ?0)
6352 c (js2-get-char))))
6353 (js2-unget-char)
6354 (setq c val)))))
6355 (when (and (eq quote-char ?`) (eq c ?$))
6356 (when (eq (setq nc (js2-get-char)) ?\{)
6357 (throw 'break nil))
6358 (js2-unget-char))
6359 (js2-add-to-string c)
6360 (setq c (js2-get-char)))))
6361 (js2-set-string-from-buffer token)
6362 (if (not (eq quote-char ?`))
6363 js2-STRING
6364 (if (and (eq c ?$) (eq nc ?\{))
6365 js2-TEMPLATE_HEAD
6366 js2-NO_SUBS_TEMPLATE))))
6367
6368 (defun js2-read-regexp (start-tt)
6369 "Called by parser when it gets / or /= in literal context."
6370 (let (c err
6371 in-class ; inside a '[' .. ']' character-class
6372 flags
6373 (continue t)
6374 (token (js2-new-token 0)))
6375 (setq js2-ts-string-buffer nil)
6376 (if (eq start-tt js2-ASSIGN_DIV)
6377 ;; mis-scanned /=
6378 (js2-add-to-string ?=)
6379 (if (not (eq start-tt js2-DIV))
6380 (error "failed assertion")))
6381 (while (and (not err)
6382 (or (/= (setq c (js2-get-char)) ?/)
6383 in-class))
6384 (cond
6385 ((or (= c ?\n)
6386 (= c js2-EOF_CHAR))
6387 (setf (js2-token-end token) (1- js2-ts-cursor)
6388 err t
6389 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6390 (js2-report-error "msg.unterminated.re.lit"))
6391 (t (cond
6392 ((= c ?\\)
6393 (js2-add-to-string c)
6394 (setq c (js2-get-char)))
6395 ((= c ?\[)
6396 (setq in-class t))
6397 ((= c ?\])
6398 (setq in-class nil)))
6399 (js2-add-to-string c))))
6400 (unless err
6401 (while continue
6402 (cond
6403 ((js2-match-char ?g)
6404 (push ?g flags))
6405 ((js2-match-char ?i)
6406 (push ?i flags))
6407 ((js2-match-char ?m)
6408 (push ?m flags))
6409 ((and (js2-match-char ?u)
6410 (>= js2-language-version 200))
6411 (push ?u flags))
6412 ((and (js2-match-char ?y)
6413 (>= js2-language-version 200))
6414 (push ?y flags))
6415 (t
6416 (setq continue nil))))
6417 (if (js2-alpha-p (js2-peek-char))
6418 (js2-report-scan-error "msg.invalid.re.flag" t
6419 js2-ts-cursor 1))
6420 (js2-set-string-from-buffer token))
6421 (js2-collect-string flags)))
6422
6423 (defun js2-get-first-xml-token ()
6424 (setq js2-ts-xml-open-tags-count 0
6425 js2-ts-is-xml-attribute nil
6426 js2-ts-xml-is-tag-content nil)
6427 (js2-unget-char)
6428 (js2-get-next-xml-token))
6429
6430 (defun js2-xml-discard-string (token)
6431 "Throw away the string in progress and flag an XML parse error."
6432 (setf js2-ts-string-buffer nil
6433 (js2-token-string token) nil)
6434 (js2-report-scan-error "msg.XML.bad.form" t))
6435
6436 (defun js2-get-next-xml-token ()
6437 (setq js2-ts-string-buffer nil) ; for recording the XML
6438 (let ((token (js2-new-token 0))
6439 c result)
6440 (setq result
6441 (catch 'return
6442 (while t
6443 (setq c (js2-get-char))
6444 (cond
6445 ((= c js2-EOF_CHAR)
6446 (throw 'return js2-ERROR))
6447 (js2-ts-xml-is-tag-content
6448 (cl-case c
6449 (?>
6450 (js2-add-to-string c)
6451 (setq js2-ts-xml-is-tag-content nil
6452 js2-ts-is-xml-attribute nil))
6453 (?/
6454 (js2-add-to-string c)
6455 (when (eq ?> (js2-peek-char))
6456 (setq c (js2-get-char))
6457 (js2-add-to-string c)
6458 (setq js2-ts-xml-is-tag-content nil)
6459 (cl-decf js2-ts-xml-open-tags-count)))
6460 (?{
6461 (js2-unget-char)
6462 (js2-set-string-from-buffer token)
6463 (throw 'return js2-XML))
6464 ((?\' ?\")
6465 (js2-add-to-string c)
6466 (unless (js2-read-quoted-string c token)
6467 (throw 'return js2-ERROR)))
6468 (?=
6469 (js2-add-to-string c)
6470 (setq js2-ts-is-xml-attribute t))
6471 ((? ?\t ?\r ?\n)
6472 (js2-add-to-string c))
6473 (t
6474 (js2-add-to-string c)
6475 (setq js2-ts-is-xml-attribute nil)))
6476 (when (and (not js2-ts-xml-is-tag-content)
6477 (zerop js2-ts-xml-open-tags-count))
6478 (js2-set-string-from-buffer token)
6479 (throw 'return js2-XMLEND)))
6480 (t
6481 ;; else not tag content
6482 (cl-case c
6483 (?<
6484 (js2-add-to-string c)
6485 (setq c (js2-peek-char))
6486 (cl-case c
6487 (?!
6488 (setq c (js2-get-char)) ;; skip !
6489 (js2-add-to-string c)
6490 (setq c (js2-peek-char))
6491 (cl-case c
6492 (?-
6493 (setq c (js2-get-char)) ;; skip -
6494 (js2-add-to-string c)
6495 (if (eq c ?-)
6496 (progn
6497 (js2-add-to-string c)
6498 (unless (js2-read-xml-comment token)
6499 (throw 'return js2-ERROR)))
6500 (js2-xml-discard-string token)
6501 (throw 'return js2-ERROR)))
6502 (?\[
6503 (setq c (js2-get-char)) ;; skip [
6504 (js2-add-to-string c)
6505 (if (and (= (js2-get-char) ?C)
6506 (= (js2-get-char) ?D)
6507 (= (js2-get-char) ?A)
6508 (= (js2-get-char) ?T)
6509 (= (js2-get-char) ?A)
6510 (= (js2-get-char) ?\[))
6511 (progn
6512 (js2-add-to-string ?C)
6513 (js2-add-to-string ?D)
6514 (js2-add-to-string ?A)
6515 (js2-add-to-string ?T)
6516 (js2-add-to-string ?A)
6517 (js2-add-to-string ?\[)
6518 (unless (js2-read-cdata token)
6519 (throw 'return js2-ERROR)))
6520 (js2-xml-discard-string token)
6521 (throw 'return js2-ERROR)))
6522 (t
6523 (unless (js2-read-entity token)
6524 (throw 'return js2-ERROR))))
6525 ;; Allow bare CDATA section, e.g.:
6526 ;; let xml = <![CDATA[ foo bar baz ]]>;
6527 (when (zerop js2-ts-xml-open-tags-count)
6528 (throw 'return js2-XMLEND)))
6529 (??
6530 (setq c (js2-get-char)) ;; skip ?
6531 (js2-add-to-string c)
6532 (unless (js2-read-PI token)
6533 (throw 'return js2-ERROR)))
6534 (?/
6535 ;; end tag
6536 (setq c (js2-get-char)) ;; skip /
6537 (js2-add-to-string c)
6538 (when (zerop js2-ts-xml-open-tags-count)
6539 (js2-xml-discard-string token)
6540 (throw 'return js2-ERROR))
6541 (setq js2-ts-xml-is-tag-content t)
6542 (cl-decf js2-ts-xml-open-tags-count))
6543 (t
6544 ;; start tag
6545 (setq js2-ts-xml-is-tag-content t)
6546 (cl-incf js2-ts-xml-open-tags-count))))
6547 (?{
6548 (js2-unget-char)
6549 (js2-set-string-from-buffer token)
6550 (throw 'return js2-XML))
6551 (t
6552 (js2-add-to-string c))))))))
6553 (setf (js2-token-end token) js2-ts-cursor)
6554 (setf (js2-token-type token) result)
6555 result))
6556
6557 (defun js2-read-quoted-string (quote token)
6558 (let (c)
6559 (catch 'return
6560 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6561 (js2-add-to-string c)
6562 (if (eq c quote)
6563 (throw 'return t)))
6564 (js2-xml-discard-string token) ;; throw away string in progress
6565 nil)))
6566
6567 (defun js2-read-xml-comment (token)
6568 (let ((c (js2-get-char)))
6569 (catch 'return
6570 (while (/= c js2-EOF_CHAR)
6571 (catch 'continue
6572 (js2-add-to-string c)
6573 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6574 (setq c (js2-get-char))
6575 (js2-add-to-string c)
6576 (if (eq (js2-peek-char) ?>)
6577 (progn
6578 (setq c (js2-get-char)) ;; skip >
6579 (js2-add-to-string c)
6580 (throw 'return t))
6581 (throw 'continue nil)))
6582 (setq c (js2-get-char))))
6583 (js2-xml-discard-string token)
6584 nil)))
6585
6586 (defun js2-read-cdata (token)
6587 (let ((c (js2-get-char)))
6588 (catch 'return
6589 (while (/= c js2-EOF_CHAR)
6590 (catch 'continue
6591 (js2-add-to-string c)
6592 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6593 (setq c (js2-get-char))
6594 (js2-add-to-string c)
6595 (if (eq (js2-peek-char) ?>)
6596 (progn
6597 (setq c (js2-get-char)) ;; Skip >
6598 (js2-add-to-string c)
6599 (throw 'return t))
6600 (throw 'continue nil)))
6601 (setq c (js2-get-char))))
6602 (js2-xml-discard-string token)
6603 nil)))
6604
6605 (defun js2-read-entity (token)
6606 (let ((decl-tags 1)
6607 c)
6608 (catch 'return
6609 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6610 (js2-add-to-string c)
6611 (cl-case c
6612 (?<
6613 (cl-incf decl-tags))
6614 (?>
6615 (cl-decf decl-tags)
6616 (if (zerop decl-tags)
6617 (throw 'return t)))))
6618 (js2-xml-discard-string token)
6619 nil)))
6620
6621 (defun js2-read-PI (token)
6622 "Scan an XML processing instruction."
6623 (let (c)
6624 (catch 'return
6625 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6626 (js2-add-to-string c)
6627 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6628 (setq c (js2-get-char)) ;; Skip >
6629 (js2-add-to-string c)
6630 (throw 'return t)))
6631 (js2-xml-discard-string token)
6632 nil)))
6633
6634 ;;; Highlighting
6635
6636 (defun js2-set-face (beg end face &optional record)
6637 "Fontify a region. If RECORD is non-nil, record for later."
6638 (when (cl-plusp js2-highlight-level)
6639 (setq beg (min (point-max) beg)
6640 beg (max (point-min) beg)
6641 end (min (point-max) end)
6642 end (max (point-min) end))
6643 (if record
6644 (push (list beg end face) js2-mode-fontifications)
6645 (put-text-property beg end 'font-lock-face face))))
6646
6647 (defsubst js2-clear-face (beg end)
6648 (remove-text-properties beg end '(font-lock-face nil
6649 help-echo nil
6650 point-entered nil
6651 cursor-sensor-functions nil
6652 c-in-sws nil)))
6653
6654 (defconst js2-ecma-global-props
6655 (concat "^"
6656 (regexp-opt
6657 '("Infinity" "NaN" "undefined" "arguments") t)
6658 "$")
6659 "Value properties of the Ecma-262 Global Object.
6660 Shown at or above `js2-highlight-level' 2.")
6661
6662 ;; might want to add the name "arguments" to this list?
6663 (defconst js2-ecma-object-props
6664 (concat "^"
6665 (regexp-opt
6666 '("prototype" "__proto__" "__parent__") t)
6667 "$")
6668 "Value properties of the Ecma-262 Object constructor.
6669 Shown at or above `js2-highlight-level' 2.")
6670
6671 (defconst js2-ecma-global-funcs
6672 (concat
6673 "^"
6674 (regexp-opt
6675 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6676 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6677 "$")
6678 "Function properties of the Ecma-262 Global object.
6679 Shown at or above `js2-highlight-level' 2.")
6680
6681 (defconst js2-ecma-number-props
6682 (concat "^"
6683 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6684 "NEGATIVE_INFINITY"
6685 "POSITIVE_INFINITY") t)
6686 "$")
6687 "Properties of the Ecma-262 Number constructor.
6688 Shown at or above `js2-highlight-level' 2.")
6689
6690 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6691 "Properties of the Ecma-262 Date constructor.
6692 Shown at or above `js2-highlight-level' 2.")
6693
6694 (defconst js2-ecma-math-props
6695 (concat "^"
6696 (regexp-opt
6697 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6698 t)
6699 "$")
6700 "Properties of the Ecma-262 Math object.
6701 Shown at or above `js2-highlight-level' 2.")
6702
6703 (defconst js2-ecma-math-funcs
6704 (concat "^"
6705 (regexp-opt
6706 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6707 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6708 "$")
6709 "Function properties of the Ecma-262 Math object.
6710 Shown at or above `js2-highlight-level' 2.")
6711
6712 (defconst js2-ecma-function-props
6713 (concat
6714 "^"
6715 (regexp-opt
6716 '(;; properties of the Object prototype object
6717 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6718 "toLocaleString" "toString" "valueOf"
6719 ;; properties of the Function prototype object
6720 "apply" "call"
6721 ;; properties of the Array prototype object
6722 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6723 "splice" "unshift"
6724 ;; properties of the String prototype object
6725 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6726 "localeCompare" "match" "replace" "search" "split" "substring"
6727 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6728 "toUpperCase"
6729 ;; properties of the Number prototype object
6730 "toExponential" "toFixed" "toPrecision"
6731 ;; properties of the Date prototype object
6732 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6733 "getMinutes" "getMonth" "getSeconds" "getTime"
6734 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6735 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6736 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6737 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6738 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6739 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6740 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6741 "toTimeString" "toUTCString"
6742 ;; properties of the RegExp prototype object
6743 "exec" "test"
6744 ;; properties of the JSON prototype object
6745 "parse" "stringify"
6746 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6747 "toSource" "__defineGetter__" "__defineSetter__"
6748 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6749 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6750 t)
6751 "$")
6752 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6753 Shown at or above `js2-highlight-level' 3.")
6754
6755 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6756 (let ((target-name (and target
6757 (js2-name-node-p target)
6758 (js2-name-node-name target)))
6759 (prop-name (if prop (js2-name-node-name prop)))
6760 (level2 (>= js2-highlight-level 2))
6761 (level3 (>= js2-highlight-level 3)))
6762 (when level2
6763 (let ((face
6764 (if call-p
6765 (cond
6766 ((and target prop)
6767 (cond
6768 ((and level3 (string-match js2-ecma-function-props prop-name))
6769 'font-lock-builtin-face)
6770 ((and target-name prop)
6771 (cond
6772 ((string= target-name "Date")
6773 (if (string-match js2-ecma-date-props prop-name)
6774 'font-lock-builtin-face))
6775 ((string= target-name "Math")
6776 (if (string-match js2-ecma-math-funcs prop-name)
6777 'font-lock-builtin-face))))))
6778 (prop
6779 (if (string-match js2-ecma-global-funcs prop-name)
6780 'font-lock-builtin-face)))
6781 (cond
6782 ((and target prop)
6783 (cond
6784 ((string= target-name "Number")
6785 (if (string-match js2-ecma-number-props prop-name)
6786 'font-lock-constant-face))
6787 ((string= target-name "Math")
6788 (if (string-match js2-ecma-math-props prop-name)
6789 'font-lock-constant-face))))
6790 (prop
6791 (if (string-match js2-ecma-object-props prop-name)
6792 'font-lock-constant-face))))))
6793 (when (and (not face) target (not call-p) prop-name)
6794 (setq face 'js2-object-property))
6795 (when face
6796 (let ((pos (+ (js2-node-pos parent) ; absolute
6797 (js2-node-pos prop)))) ; relative
6798 (js2-set-face pos
6799 (+ pos (js2-node-len prop))
6800 face 'record)))))))
6801
6802 (defun js2-parse-highlight-member-expr-node (node)
6803 "Perform syntax highlighting of EcmaScript built-in properties.
6804 The variable `js2-highlight-level' governs this highlighting."
6805 (let (face target prop name pos end parent call-p callee)
6806 (cond
6807 ;; case 1: simple name, e.g. foo
6808 ((js2-name-node-p node)
6809 (setq name (js2-name-node-name node))
6810 ;; possible for name to be nil in rare cases - saw it when
6811 ;; running js2-mode on an elisp buffer. Might as well try to
6812 ;; make it so js2-mode never barfs.
6813 (when name
6814 (setq face (if (string-match js2-ecma-global-props name)
6815 'font-lock-constant-face))
6816 (when face
6817 (setq pos (js2-node-pos node)
6818 end (+ pos (js2-node-len node)))
6819 (js2-set-face pos end face 'record))))
6820 ;; case 2: property access or function call
6821 ((or (js2-prop-get-node-p node)
6822 ;; highlight function call if expr is a prop-get node
6823 ;; or a plain name (i.e. unqualified function call)
6824 (and (setq call-p (js2-call-node-p node))
6825 (setq callee (js2-call-node-target node)) ; separate setq!
6826 (or (js2-prop-get-node-p callee)
6827 (js2-name-node-p callee))))
6828 (setq parent node
6829 node (if call-p callee node))
6830 (if (and call-p (js2-name-node-p callee))
6831 (setq prop callee)
6832 (setq target (js2-prop-get-node-left node)
6833 prop (js2-prop-get-node-right node)))
6834 (cond
6835 ((js2-name-node-p prop)
6836 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6837 (js2-parse-highlight-prop-get parent target prop call-p))
6838 ((js2-name-node-p target)
6839 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6840 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6841
6842 (defun js2-parse-highlight-member-expr-fn-name (expr)
6843 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6844 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6845 We currently only handle the case where the last component is a prop-get
6846 of a simple name. Called before EXPR has a parent node."
6847 (let (pos
6848 (name (and (js2-prop-get-node-p expr)
6849 (js2-prop-get-node-right expr))))
6850 (when (js2-name-node-p name)
6851 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6852 (js2-node-pos name)))
6853 (+ pos (js2-node-len name))
6854 'font-lock-function-name-face
6855 'record))))
6856
6857 ;; source: http://jsdoc.sourceforge.net/
6858 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6859 ;; allows type specifications, and needs work before entering the wild.
6860
6861 (defconst js2-jsdoc-param-tag-regexp
6862 (concat "^\\s-*\\*+\\s-*\\(@"
6863 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6864 "\\)"
6865 "\\s-*\\({[^}]+}\\)?" ; optional type
6866 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6867 "\\_>")
6868 "Matches jsdoc tags with optional type and optional param name.")
6869
6870 (defconst js2-jsdoc-typed-tag-regexp
6871 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6872 (regexp-opt
6873 '("enum"
6874 "extends"
6875 "field"
6876 "id"
6877 "implements"
6878 "lends"
6879 "mods"
6880 "requires"
6881 "return"
6882 "returns"
6883 "throw"
6884 "throws"))
6885 "\\)\\)\\s-*\\({[^}]+}\\)?")
6886 "Matches jsdoc tags with optional type.")
6887
6888 (defconst js2-jsdoc-arg-tag-regexp
6889 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6890 (regexp-opt
6891 '("alias"
6892 "augments"
6893 "borrows"
6894 "bug"
6895 "base"
6896 "config"
6897 "default"
6898 "define"
6899 "exception"
6900 "function"
6901 "member"
6902 "memberOf"
6903 "name"
6904 "namespace"
6905 "since"
6906 "suppress"
6907 "this"
6908 "throws"
6909 "type"
6910 "version"))
6911 "\\)\\)\\s-+\\([^ \t]+\\)")
6912 "Matches jsdoc tags with a single argument.")
6913
6914 (defconst js2-jsdoc-empty-tag-regexp
6915 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6916 (regexp-opt
6917 '("addon"
6918 "author"
6919 "class"
6920 "const"
6921 "constant"
6922 "constructor"
6923 "constructs"
6924 "deprecated"
6925 "desc"
6926 "description"
6927 "event"
6928 "example"
6929 "exec"
6930 "export"
6931 "fileoverview"
6932 "final"
6933 "function"
6934 "hidden"
6935 "ignore"
6936 "implicitCast"
6937 "inheritDoc"
6938 "inner"
6939 "interface"
6940 "license"
6941 "noalias"
6942 "noshadow"
6943 "notypecheck"
6944 "override"
6945 "owner"
6946 "preserve"
6947 "preserveTry"
6948 "private"
6949 "protected"
6950 "public"
6951 "static"
6952 "supported"
6953 ))
6954 "\\)\\)\\s-*")
6955 "Matches empty jsdoc tags.")
6956
6957 (defconst js2-jsdoc-link-tag-regexp
6958 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6959 "Matches a jsdoc link or code tag.")
6960
6961 (defconst js2-jsdoc-see-tag-regexp
6962 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6963 "Matches a jsdoc @see tag.")
6964
6965 (defconst js2-jsdoc-html-tag-regexp
6966 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6967 "Matches a simple (no attributes) html start- or end-tag.")
6968
6969 (defun js2-jsdoc-highlight-helper ()
6970 (js2-set-face (match-beginning 1)
6971 (match-end 1)
6972 'js2-jsdoc-tag)
6973 (if (match-beginning 2)
6974 (if (save-excursion
6975 (goto-char (match-beginning 2))
6976 (= (char-after) ?{))
6977 (js2-set-face (1+ (match-beginning 2))
6978 (1- (match-end 2))
6979 'js2-jsdoc-type)
6980 (js2-set-face (match-beginning 2)
6981 (match-end 2)
6982 'js2-jsdoc-value)))
6983 (if (match-beginning 3)
6984 (js2-set-face (match-beginning 3)
6985 (match-end 3)
6986 'js2-jsdoc-value)))
6987
6988 (defun js2-highlight-jsdoc (ast)
6989 "Highlight doc comment tags."
6990 (let ((comments (js2-ast-root-comments ast))
6991 beg end)
6992 (save-excursion
6993 (dolist (node comments)
6994 (when (eq (js2-comment-node-format node) 'jsdoc)
6995 (setq beg (js2-node-abs-pos node)
6996 end (+ beg (js2-node-len node)))
6997 (save-restriction
6998 (narrow-to-region beg end)
6999 (dolist (re (list js2-jsdoc-param-tag-regexp
7000 js2-jsdoc-typed-tag-regexp
7001 js2-jsdoc-arg-tag-regexp
7002 js2-jsdoc-link-tag-regexp
7003 js2-jsdoc-see-tag-regexp
7004 js2-jsdoc-empty-tag-regexp))
7005 (goto-char beg)
7006 (while (re-search-forward re nil t)
7007 (js2-jsdoc-highlight-helper)))
7008 ;; simple highlighting for html tags
7009 (goto-char beg)
7010 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7011 (js2-set-face (match-beginning 1)
7012 (match-end 1)
7013 'js2-jsdoc-html-tag-delimiter)
7014 (js2-set-face (match-beginning 2)
7015 (match-end 2)
7016 'js2-jsdoc-html-tag-name)
7017 (js2-set-face (match-beginning 3)
7018 (match-end 3)
7019 'js2-jsdoc-html-tag-delimiter))))))))
7020
7021 (defun js2-highlight-assign-targets (_node left right)
7022 "Highlight function properties and external variables."
7023 (let (leftpos name)
7024 ;; highlight vars and props assigned function values
7025 (when (or (js2-function-node-p right)
7026 (js2-class-node-p right))
7027 (cond
7028 ;; var foo = function() {...}
7029 ((js2-name-node-p left)
7030 (setq name left))
7031 ;; foo.bar.baz = function() {...}
7032 ((and (js2-prop-get-node-p left)
7033 (js2-name-node-p (js2-prop-get-node-right left)))
7034 (setq name (js2-prop-get-node-right left))))
7035 (when name
7036 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7037 (+ leftpos (js2-node-len name))
7038 'font-lock-function-name-face
7039 'record)))))
7040
7041 (defun js2-record-name-node (node)
7042 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7043 later. NODE must be a name node."
7044 (let ((leftpos (js2-node-abs-pos node)))
7045 (push (list node js2-current-scope
7046 leftpos
7047 (+ leftpos (js2-node-len node)))
7048 js2-recorded-identifiers)))
7049
7050 (defun js2-highlight-undeclared-vars ()
7051 "After entire parse is finished, look for undeclared variable references.
7052 We have to wait until entire buffer is parsed, since JavaScript permits var
7053 decls to occur after they're used.
7054
7055 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7056 it is considered declared."
7057 (let (name)
7058 (dolist (entry js2-recorded-identifiers)
7059 (cl-destructuring-bind (name-node scope pos end) entry
7060 (setq name (js2-name-node-name name-node))
7061 (unless (or (member name js2-global-externs)
7062 (member name js2-default-externs)
7063 (member name js2-additional-externs)
7064 (js2-get-defining-scope scope name pos))
7065 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7066 'js2-external-variable))))))
7067
7068 (defun js2--add-or-update-symbol (symbol inition used vars)
7069 "Add or update SYMBOL entry in VARS, an hash table.
7070 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7071 respectively meaning that SYMBOL is a mere declaration, an
7072 assignment or a function parameter; when USED is t, the symbol
7073 node is assumed to be an usage and thus added to the list stored
7074 in the cdr of the entry.
7075 "
7076 (let* ((nm (js2-name-node-name symbol))
7077 (es (js2-node-get-enclosing-scope symbol))
7078 (ds (js2-get-defining-scope es nm)))
7079 (when (and ds (not (equal nm "arguments")))
7080 (let* ((sym (js2-scope-get-symbol ds nm))
7081 (var (gethash sym vars))
7082 (err-var-p (js2-catch-node-p ds)))
7083 (unless inition
7084 (setq inition err-var-p))
7085 (if var
7086 (progn
7087 (when (and inition (not (equal (car var) ?P)))
7088 (setcar var inition))
7089 (when used
7090 (push symbol (cdr var))))
7091 ;; do not consider the declaration of catch parameter as an usage
7092 (when (and err-var-p used)
7093 (setq used nil))
7094 (puthash sym (cons inition (if used (list symbol))) vars))))))
7095
7096 (defun js2--classify-variables ()
7097 "Collect and classify variables declared or used within js2-mode-ast.
7098 Traverse the whole ast tree returning a summary of the variables
7099 usage as an hash-table, keyed by their corresponding symbol table
7100 entry.
7101 Each variable is described by a tuple where the car is a flag
7102 indicating whether the variable has been initialized and the cdr
7103 is a possibly empty list of name nodes where it is used. External
7104 symbols, i.e. those not present in the whole scopes hierarchy,
7105 are ignored."
7106 (let ((vars (make-hash-table :test #'eq :size 100)))
7107 (js2-visit-ast
7108 js2-mode-ast
7109 (lambda (node end-p)
7110 (when (null end-p)
7111 (cond
7112 ((js2-var-init-node-p node)
7113 ;; take note about possibly initialized declarations
7114 (let ((target (js2-var-init-node-target node))
7115 (initializer (js2-var-init-node-initializer node)))
7116 (when target
7117 (let* ((parent (js2-node-parent node))
7118 (grandparent (if parent (js2-node-parent parent)))
7119 (inited (not (null initializer))))
7120 (unless inited
7121 (setq inited
7122 (and grandparent
7123 (js2-for-in-node-p grandparent)
7124 (memq target
7125 (mapcar #'js2-var-init-node-target
7126 (js2-var-decl-node-kids
7127 (js2-for-in-node-iterator grandparent)))))))
7128 (js2--add-or-update-symbol target inited nil vars)))))
7129
7130 ((js2-assign-node-p node)
7131 ;; take note about assignments
7132 (let ((left (js2-assign-node-left node)))
7133 (when (js2-name-node-p left)
7134 (js2--add-or-update-symbol left t nil vars))))
7135
7136 ((js2-prop-get-node-p node)
7137 ;; handle x.y.z nodes, considering only x
7138 (let ((left (js2-prop-get-node-left node)))
7139 (when (js2-name-node-p left)
7140 (js2--add-or-update-symbol left nil t vars))))
7141
7142 ((js2-name-node-p node)
7143 ;; take note about used variables
7144 (let ((parent (js2-node-parent node)))
7145 (when parent
7146 (unless (or (and (js2-var-init-node-p parent) ; handled above
7147 (eq node (js2-var-init-node-target parent)))
7148 (and (js2-assign-node-p parent)
7149 (eq node (js2-assign-node-left parent)))
7150 (js2-prop-get-node-p parent))
7151 (let ((used t) inited)
7152 (cond
7153 ((and (js2-function-node-p parent)
7154 (js2-wrapper-function-p parent))
7155 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7156
7157 ((js2-for-in-node-p parent)
7158 (if (eq node (js2-for-in-node-iterator parent))
7159 (setq inited t used nil)))
7160
7161 ((js2-function-node-p parent)
7162 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7163 used nil)))
7164
7165 (unless used
7166 (let ((grandparent (js2-node-parent parent)))
7167 (when grandparent
7168 (setq used (js2-return-node-p grandparent)))))
7169
7170 (js2--add-or-update-symbol node inited used vars))))))))
7171 t))
7172 vars))
7173
7174 (defun js2--get-name-node (node)
7175 (cond
7176 ((js2-name-node-p node) node)
7177 ((js2-function-node-p node)
7178 (js2-function-node-name node))
7179 ((js2-class-node-p node)
7180 (js2-class-node-name node))
7181 ((js2-comp-loop-node-p node)
7182 (js2-comp-loop-node-iterator node))
7183 (t node)))
7184
7185 (defun js2--highlight-unused-variable (symbol info)
7186 (let ((name (js2-symbol-name symbol))
7187 (inited (car info))
7188 (refs (cdr info))
7189 pos len)
7190 (unless (and inited refs)
7191 (if refs
7192 (dolist (ref refs)
7193 (setq pos (js2-node-abs-pos ref))
7194 (setq len (js2-name-node-len ref))
7195 (js2-report-warning "msg.uninitialized.variable" name pos len
7196 'js2-warning))
7197 (when (or js2-warn-about-unused-function-arguments
7198 (not (eq inited ?P)))
7199 (let* ((symn (js2-symbol-ast-node symbol))
7200 (namen (js2--get-name-node symn)))
7201 (unless (js2-node-top-level-decl-p namen)
7202 (setq pos (js2-node-abs-pos namen))
7203 (setq len (js2-name-node-len namen))
7204 (js2-report-warning "msg.unused.variable" name pos len
7205 'js2-warning))))))))
7206
7207 (defun js2-highlight-unused-variables ()
7208 "Highlight unused variables."
7209 (let ((vars (js2--classify-variables)))
7210 (maphash #'js2--highlight-unused-variable vars)))
7211
7212 ;;;###autoload
7213 (define-minor-mode js2-highlight-unused-variables-mode
7214 "Toggle highlight of unused variables."
7215 :lighter ""
7216 (if js2-highlight-unused-variables-mode
7217 (add-hook 'js2-post-parse-callbacks
7218 #'js2-highlight-unused-variables nil t)
7219 (remove-hook 'js2-post-parse-callbacks
7220 #'js2-highlight-unused-variables t)))
7221
7222 (defun js2-set-default-externs ()
7223 "Set the value of `js2-default-externs' based on the various
7224 `js2-include-?-externs' variables."
7225 (setq js2-default-externs
7226 (append js2-ecma-262-externs
7227 (if js2-include-browser-externs js2-browser-externs)
7228 (if (and js2-include-browser-externs
7229 (>= js2-language-version 200)) js2-harmony-externs)
7230 (if js2-include-rhino-externs js2-rhino-externs)
7231 (if js2-include-node-externs js2-node-externs)
7232 (if (or js2-include-browser-externs js2-include-node-externs)
7233 js2-typed-array-externs))))
7234
7235 (defun js2-apply-jslint-globals ()
7236 (setq js2-additional-externs
7237 (nconc (js2-get-jslint-globals)
7238 js2-additional-externs)))
7239
7240 (defun js2-get-jslint-globals ()
7241 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7242 when (and (eq 'block (js2-comment-node-format node))
7243 (save-excursion
7244 (goto-char (js2-node-abs-pos node))
7245 (looking-at "/\\*global ")))
7246 append (js2-get-jslint-globals-in
7247 (match-end 0)
7248 (js2-node-abs-end node))))
7249
7250 (defun js2-get-jslint-globals-in (beg end)
7251 (let (res)
7252 (save-excursion
7253 (goto-char beg)
7254 (while (re-search-forward js2-mode-identifier-re end t)
7255 (let ((match (match-string 0)))
7256 (unless (member match '("true" "false"))
7257 (push match res)))))
7258 (nreverse res)))
7259
7260 ;;; IMenu support
7261
7262 ;; We currently only support imenu, but eventually should support speedbar and
7263 ;; possibly other browsing mechanisms.
7264
7265 ;; The basic strategy is to identify function assignment targets of the form
7266 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7267 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7268 ;; for imenu after parsing is finished.
7269
7270 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7271 ;; JavaScript, and the general problem is undecidable. However, several forms
7272 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7273 ;; include:
7274
7275 ;; function foo() -- function declaration
7276 ;; foo = function() -- function expression assigned to variable
7277 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7278 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7279 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7280 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7281 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7282 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7283 ;; function foo() {function bar() {...}} -- nested function
7284 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7285
7286 ;; This list boils down to a few forms that can be combined recursively.
7287 ;; Top-level named function declarations include both the left-hand (name)
7288 ;; and the right-hand (function value) expressions needed to produce an imenu
7289 ;; entry. The other "right-hand" forms we need to look for are:
7290 ;; - functions declared as props/getters/setters in object literals
7291 ;; - nested named function declarations
7292 ;; The "left-hand" expressions that functions can be assigned to include:
7293 ;; - local/global variables
7294 ;; - nested property-get expressions like a.b.c.d
7295 ;; - element gets like foo[10] or foo['bar'] where the index
7296 ;; expression can be trivially converted to a property name. They
7297 ;; effectively then become property gets.
7298
7299 ;; All the different definition types are canonicalized into the form
7300 ;; foo.bar.baz = position-of-function-keyword
7301
7302 ;; We need to build a trie-like structure for imenu. As an example,
7303 ;; consider the following JavaScript code:
7304
7305 ;; a = function() {...} // function at position 5
7306 ;; b = function() {...} // function at position 25
7307 ;; foo = function() {...} // function at position 100
7308 ;; foo.bar = function() {...} // function at position 200
7309 ;; foo.bar.baz = function() {...} // function at position 300
7310 ;; foo.bar.zab = function() {...} // function at position 400
7311
7312 ;; During parsing we accumulate an entry for each definition in
7313 ;; the variable `js2-imenu-recorder', like so:
7314
7315 ;; '((fn a 5)
7316 ;; (fn b 25)
7317 ;; (fn foo 100)
7318 ;; (fn foo bar 200)
7319 ;; (fn foo bar baz 300)
7320 ;; (fn foo bar zab 400))
7321
7322 ;; Where 'fn' is the respective function node.
7323 ;; After parsing these entries are merged into this alist-trie:
7324
7325 ;; '((a . 1)
7326 ;; (b . 2)
7327 ;; (foo (<definition> . 3)
7328 ;; (bar (<definition> . 6)
7329 ;; (baz . 100)
7330 ;; (zab . 200))))
7331
7332 ;; Note the wacky need for a <definition> name. The token can be anything
7333 ;; that isn't a valid JavaScript identifier, because you might make foo
7334 ;; a function and then start setting properties on it that are also functions.
7335
7336 (defun js2-prop-node-name (node)
7337 "Return the name of a node that may be a property-get/property-name.
7338 If NODE is not a valid name-node, string-node or integral number-node,
7339 returns nil. Otherwise returns the string name/value of the node."
7340 (cond
7341 ((js2-name-node-p node)
7342 (js2-name-node-name node))
7343 ((js2-string-node-p node)
7344 (js2-string-node-value node))
7345 ((and (js2-number-node-p node)
7346 (string-match "^[0-9]+$" (js2-number-node-value node)))
7347 (js2-number-node-value node))
7348 ((eq (js2-node-type node) js2-THIS)
7349 "this")
7350 ((eq (js2-node-type node) js2-SUPER)
7351 "super")))
7352
7353 (defun js2-node-qname-component (node)
7354 "Return the name of this node, if it contributes to a qname.
7355 Returns nil if the node doesn't contribute."
7356 (copy-sequence
7357 (or (js2-prop-node-name node)
7358 (if (and (js2-function-node-p node)
7359 (js2-function-node-name node))
7360 (js2-name-node-name (js2-function-node-name node))))))
7361
7362 (defun js2-record-imenu-entry (fn-node qname pos)
7363 "Add an entry to `js2-imenu-recorder'.
7364 FN-NODE should be the current item's function node.
7365
7366 Associate FN-NODE with its QNAME for later lookup.
7367 This is used in postprocessing the chain list. For each chain, we find
7368 the parent function, look up its qname, then prepend a copy of it to the chain."
7369 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7370 (unless js2-imenu-function-map
7371 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7372 (puthash fn-node qname js2-imenu-function-map))
7373
7374 (defun js2-record-imenu-functions (node &optional var)
7375 "Record function definitions for imenu.
7376 NODE is a function node or an object literal.
7377 VAR, if non-nil, is the expression that NODE is being assigned to.
7378 When passed arguments of wrong type, does nothing."
7379 (when js2-parse-ide-mode
7380 (let ((fun-p (js2-function-node-p node))
7381 qname fname-node)
7382 (cond
7383 ;; non-anonymous function declaration?
7384 ((and fun-p
7385 (not var)
7386 (setq fname-node (js2-function-node-name node)))
7387 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7388 ;; for remaining forms, compute left-side tree branch first
7389 ((and var (setq qname (js2-compute-nested-prop-get var)))
7390 (cond
7391 ;; foo.bar.baz = function
7392 (fun-p
7393 (js2-record-imenu-entry node qname (js2-node-pos node)))
7394 ;; foo.bar.baz = object-literal
7395 ;; look for nested functions: {a: {b: function() {...} }}
7396 ((js2-object-node-p node)
7397 ;; Node position here is still absolute, since the parser
7398 ;; passes the assignment target and value expressions
7399 ;; to us before they are added as children of the assignment node.
7400 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7401
7402 (defun js2-compute-nested-prop-get (node)
7403 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7404 component nodes as a list. Otherwise return nil. Element-gets are treated
7405 as property-gets if the index expression is a string, or a positive integer."
7406 (let (left right head)
7407 (cond
7408 ((or (js2-name-node-p node)
7409 (js2-this-or-super-node-p node))
7410 (list node))
7411 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7412 ((js2-prop-get-node-p node) ; foo.bar
7413 (setq left (js2-prop-get-node-left node)
7414 right (js2-prop-get-node-right node))
7415 (if (setq head (js2-compute-nested-prop-get left))
7416 (nconc head (list right))))
7417 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7418 (setq left (js2-elem-get-node-target node)
7419 right (js2-elem-get-node-element node))
7420 (if (or (js2-string-node-p right) ; ['bar']
7421 (and (js2-number-node-p right) ; [10]
7422 (string-match "^[0-9]+$"
7423 (js2-number-node-value right))))
7424 (if (setq head (js2-compute-nested-prop-get left))
7425 (nconc head (list right))))))))
7426
7427 (defun js2-record-object-literal (node qname pos)
7428 "Recursively process an object literal looking for functions.
7429 NODE is an object literal that is the right-hand child of an assignment
7430 expression. QNAME is a list of nodes representing the assignment target,
7431 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7432 POS is the absolute position of the node.
7433 We do a depth-first traversal of NODE. For any functions we find,
7434 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7435 (let (right)
7436 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7437 (let ((left (js2-infix-node-left e))
7438 ;; Element positions are relative to the parent position.
7439 (pos (+ pos (js2-node-pos e))))
7440 (cond
7441 ;; foo: function() {...}
7442 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7443 (when (js2-prop-node-name left)
7444 ;; As a policy decision, we record the position of the property,
7445 ;; not the position of the `function' keyword, since the property
7446 ;; is effectively the name of the function.
7447 (js2-record-imenu-entry right (append qname (list left)) pos)))
7448 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7449 ((js2-object-node-p right)
7450 (js2-record-object-literal right
7451 (append qname (list (js2-infix-node-left e)))
7452 (+ pos (js2-node-pos right)))))))))
7453
7454 (defun js2-node-top-level-decl-p (node)
7455 "Return t if NODE's name is defined in the top-level scope.
7456 Also returns t if NODE's name is not defined in any scope, since it implies
7457 that it's an external variable, which must also be in the top-level scope."
7458 (let* ((name (js2-prop-node-name node))
7459 (this-scope (js2-node-get-enclosing-scope node))
7460 defining-scope)
7461 (cond
7462 ((js2-this-or-super-node-p node)
7463 nil)
7464 ((null this-scope)
7465 t)
7466 ((setq defining-scope (js2-get-defining-scope this-scope name))
7467 (js2-ast-root-p defining-scope))
7468 (t t))))
7469
7470 (defun js2-wrapper-function-p (node)
7471 "Return t if NODE is a function expression that's immediately invoked.
7472 NODE must be `js2-function-node'."
7473 (let ((parent (js2-node-parent node)))
7474 (or
7475 ;; function(){...}();
7476 (and (js2-call-node-p parent)
7477 (eq node (js2-call-node-target parent)))
7478 (and (js2-paren-node-p parent)
7479 ;; (function(){...})();
7480 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7481 ;; (function(){...}).call(this);
7482 (and (js2-prop-get-node-p parent)
7483 (member (js2-name-node-name (js2-prop-get-node-right parent))
7484 '("call" "apply"))
7485 (js2-call-node-p (js2-node-parent parent))))))))
7486
7487 (defun js2-browse-postprocess-chains ()
7488 "Modify function-declaration name chains after parsing finishes.
7489 Some of the information is only available after the parse tree is complete.
7490 For instance, processing a nested scope requires a parent function node."
7491 (let (result fn parent-qname p elem)
7492 (dolist (entry js2-imenu-recorder)
7493 ;; function node goes first
7494 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7495 ;; Examine head's defining scope:
7496 ;; Pre-processed chain, or top-level/external, keep as-is.
7497 (if (or (stringp head) (js2-node-top-level-decl-p head))
7498 (push chain result)
7499 (when (js2-this-or-super-node-p head)
7500 (setq chain (cdr chain))) ; discard this-node
7501 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7502 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7503 (when (eq parent-qname 'not-found)
7504 ;; anonymous function expressions are not recorded
7505 ;; during the parse, so we need to handle this case here
7506 (setq parent-qname
7507 (if (js2-wrapper-function-p fn)
7508 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7509 (if (js2-ast-root-p grandparent)
7510 nil
7511 (gethash grandparent js2-imenu-function-map 'skip)))
7512 'skip))
7513 (puthash fn parent-qname js2-imenu-function-map))
7514 (if (eq parent-qname 'skip)
7515 ;; We don't show it, let's record that fact.
7516 (remhash current-fn js2-imenu-function-map)
7517 ;; Prepend parent fn qname to this chain.
7518 (let ((qname (append parent-qname chain)))
7519 (puthash current-fn (butlast qname) js2-imenu-function-map)
7520 (push qname result)))))))
7521 ;; Collect chains obtained by third-party code.
7522 (let (js2-imenu-recorder)
7523 (run-hooks 'js2-build-imenu-callbacks)
7524 (dolist (entry js2-imenu-recorder)
7525 (push (cdr entry) result)))
7526 ;; Finally replace each node in each chain with its name.
7527 (dolist (chain result)
7528 (setq p chain)
7529 (while p
7530 (if (js2-node-p (setq elem (car p)))
7531 (setcar p (js2-node-qname-component elem)))
7532 (setq p (cdr p))))
7533 result))
7534
7535 ;; Merge name chains into a trie-like tree structure of nested lists.
7536 ;; To simplify construction of the trie, we first build it out using the rule
7537 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7538 ;; [key, num-or-list]. The second element can be a number; if so, this key
7539 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7540 ;; associated with the key at this level.) Otherwise the second element is
7541 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7542 ;; a simple recursive formulation.
7543 ;;
7544 ;; js2-mode is building the data structure for imenu. The imenu documentation
7545 ;; claims that it's the structure above, but in practice it wants the children
7546 ;; at the same list level as the key for that level, which is how I've drawn
7547 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7548 ;; list wrapper around the children at each level.
7549 ;;
7550 ;; A completed nested imenu-alist entry looks like this:
7551 ;; '(("foo"
7552 ;; ("<definition>" . 7)
7553 ;; ("bar"
7554 ;; ("a" . 40)
7555 ;; ("b" . 60))))
7556 ;;
7557 ;; In particular, the documentation for `imenu--index-alist' says that
7558 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7559 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7560
7561 (defun js2-treeify (lst)
7562 "Convert (a b c d) to (a ((b ((c d)))))."
7563 (if (null (cddr lst)) ; list length <= 2
7564 lst
7565 (list (car lst) (list (js2-treeify (cdr lst))))))
7566
7567 (defun js2-build-alist-trie (chains trie)
7568 "Merge declaration name chains into a trie-like alist structure for imenu.
7569 CHAINS is the qname chain list produced during parsing. TRIE is a
7570 list of elements built up so far."
7571 (let (head tail pos branch kids)
7572 (dolist (chain chains)
7573 (setq head (car chain)
7574 tail (cdr chain)
7575 pos (if (numberp (car tail)) (car tail))
7576 branch (js2-find-if (lambda (n)
7577 (string= (car n) head))
7578 trie)
7579 kids (cl-second branch))
7580 (cond
7581 ;; case 1: this key isn't in the trie yet
7582 ((null branch)
7583 (if trie
7584 (setcdr (last trie) (list (js2-treeify chain)))
7585 (setq trie (list (js2-treeify chain)))))
7586 ;; case 2: key is present with a single number entry: replace w/ list
7587 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7588 ;; ("<definition>" 20)))
7589 ((numberp kids)
7590 (setcar (cdr branch)
7591 (list (list "<definition-1>" kids)
7592 (if pos
7593 (list "<definition-2>" pos)
7594 (js2-treeify tail)))))
7595 ;; case 3: key is there (with kids), and we're a number entry
7596 (pos
7597 (setcdr (last kids)
7598 (list
7599 (list (format "<definition-%d>"
7600 (1+ (cl-loop for kid in kids
7601 count (eq ?< (aref (car kid) 0)))))
7602 pos))))
7603 ;; case 4: key is there with kids, need to merge in our chain
7604 (t
7605 (js2-build-alist-trie (list tail) kids))))
7606 trie))
7607
7608 (defun js2-flatten-trie (trie)
7609 "Convert TRIE to imenu-format.
7610 Recurses through nodes, and for each one whose second element is a list,
7611 appends the list's flattened elements to the current element. Also
7612 changes the tails into conses. For instance, this pre-flattened trie
7613
7614 '(a ((b 20)
7615 (c ((d 30)
7616 (e 40)))))
7617
7618 becomes
7619
7620 '(a (b . 20)
7621 (c (d . 30)
7622 (e . 40)))
7623
7624 Note that the root of the trie has no key, just a list of chains.
7625 This is also true for the value of any key with multiple children,
7626 e.g. key 'c' in the example above."
7627 (cond
7628 ((listp (car trie))
7629 (mapcar #'js2-flatten-trie trie))
7630 (t
7631 (if (numberp (cl-second trie))
7632 (cons (car trie) (cl-second trie))
7633 ;; else pop list and append its kids
7634 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7635
7636 (defun js2-build-imenu-index ()
7637 "Turn `js2-imenu-recorder' into an imenu data structure."
7638 (when (eq js2-imenu-recorder 'empty)
7639 (setq js2-imenu-recorder nil))
7640 (let* ((chains (js2-browse-postprocess-chains))
7641 (result (js2-build-alist-trie chains nil)))
7642 (js2-flatten-trie result)))
7643
7644 (defun js2-test-print-chains (chains)
7645 "Print a list of qname chains.
7646 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7647 i.e. one or more nodes, and an integer position as the list tail."
7648 (mapconcat (lambda (chain)
7649 (concat "("
7650 (mapconcat (lambda (elem)
7651 (if (js2-node-p elem)
7652 (or (js2-node-qname-component elem)
7653 "nil")
7654 (number-to-string elem)))
7655 chain
7656 " ")
7657 ")"))
7658 chains
7659 "\n"))
7660
7661 ;;; Parser
7662
7663 (defconst js2-version "1.8.5"
7664 "Version of JavaScript supported.")
7665
7666 (defun js2-record-face (face &optional token)
7667 "Record a style run of FACE for TOKEN or the current token."
7668 (unless token (setq token (js2-current-token)))
7669 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7670
7671 (defsubst js2-node-end (n)
7672 "Computes the absolute end of node N.
7673 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7674 is only true until the node is added to its parent; i.e., while parsing."
7675 (+ (js2-node-pos n)
7676 (js2-node-len n)))
7677
7678 (defun js2-record-comment (token)
7679 "Record a comment in `js2-scanned-comments'."
7680 (let ((ct (js2-token-comment-type token))
7681 (beg (js2-token-beg token))
7682 (end (js2-token-end token)))
7683 (push (make-js2-comment-node :len (- end beg)
7684 :format ct)
7685 js2-scanned-comments)
7686 (when js2-parse-ide-mode
7687 (js2-record-face (if (eq ct 'jsdoc)
7688 'font-lock-doc-face
7689 'font-lock-comment-face)
7690 token)
7691 (when (memq ct '(html preprocessor))
7692 ;; Tell cc-engine the bounds of the comment.
7693 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7694
7695 (defun js2-peek-token ()
7696 "Return the next token type without consuming it.
7697 If `js2-ti-lookahead' is positive, return the type of next token
7698 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7699 (if (not (zerop js2-ti-lookahead))
7700 (js2-token-type
7701 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7702 (let ((tt (js2-get-token-internal nil)))
7703 (js2-unget-token)
7704 tt)))
7705
7706 (defalias 'js2-next-token 'js2-get-token)
7707
7708 (defun js2-match-token (match &optional dont-unget)
7709 "Get next token and return t if it matches MATCH, a bytecode.
7710 Returns nil and consumes nothing if MATCH is not the next token."
7711 (if (/= (js2-get-token) match)
7712 (ignore (unless dont-unget (js2-unget-token)))
7713 t))
7714
7715 (defun js2-match-contextual-kwd (name)
7716 "Consume and return t if next token is `js2-NAME', and its
7717 string is NAME. Returns nil and keeps current token otherwise."
7718 (if (js2-contextual-kwd-p (progn (js2-get-token)
7719 (js2-current-token))
7720 name)
7721 (progn (js2-record-face 'font-lock-keyword-face) t)
7722 (js2-unget-token)
7723 nil))
7724
7725 (defun js2-contextual-kwd-p (token name)
7726 "Return t if TOKEN is `js2-NAME', and its string is NAME."
7727 (and (= (js2-token-type token) js2-NAME)
7728 (string= (js2-token-string token) name)))
7729
7730 (defun js2-match-async-function ()
7731 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7732 (= (js2-peek-token) js2-FUNCTION))
7733 (js2-record-face 'font-lock-keyword-face)
7734 (js2-get-token)
7735 t))
7736
7737 (defun js2-match-async-arrow-function ()
7738 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7739 (/= (js2-peek-token) js2-FUNCTION))
7740 (js2-record-face 'font-lock-keyword-face)
7741 (js2-get-token)
7742 t))
7743
7744 (defun js2-match-await ()
7745 (when (and (= tt js2-NAME)
7746 (js2-contextual-kwd-p (js2-current-token) "await"))
7747 (js2-record-face 'font-lock-keyword-face)
7748 (let ((beg (js2-current-token-beg))
7749 (end (js2-current-token-end)))
7750 (js2-get-token)
7751 (unless (and (js2-inside-function)
7752 (js2-function-node-async js2-current-script-or-fn))
7753 (js2-report-error "msg.bad.await" nil
7754 beg (- end beg))))
7755 t))
7756
7757 (defun js2-get-prop-name-token ()
7758 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7759
7760 (defun js2-match-prop-name ()
7761 "Consume token and return t if next token is a valid property name.
7762 If `js2-language-version' is >= 180, a keyword or reserved word
7763 is considered valid name as well."
7764 (if (eq js2-NAME (js2-get-prop-name-token))
7765 t
7766 (js2-unget-token)
7767 nil))
7768
7769 (defun js2-must-match-prop-name (msg-id &optional pos len)
7770 (if (js2-match-prop-name)
7771 t
7772 (js2-report-error msg-id nil pos len)
7773 nil))
7774
7775 (defun js2-peek-token-or-eol ()
7776 "Return js2-EOL if the next token immediately follows a newline.
7777 Else returns the next token. Used in situations where we don't
7778 consider certain token types valid if they are preceded by a newline.
7779 One example is the postfix ++ or -- operator, which has to be on the
7780 same line as its operand."
7781 (let ((tt (js2-get-token))
7782 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7783 (js2-unget-token)
7784 (if follows-eol
7785 js2-EOL
7786 tt)))
7787
7788 (defun js2-must-match (token msg-id &optional pos len)
7789 "Match next token to token code TOKEN, or record a syntax error.
7790 MSG-ID is the error message to report if the match fails.
7791 Returns t on match, nil if no match."
7792 (if (js2-match-token token t)
7793 t
7794 (js2-report-error msg-id nil pos len)
7795 (js2-unget-token)
7796 nil))
7797
7798 (defun js2-must-match-name (msg-id)
7799 (if (js2-match-token js2-NAME t)
7800 t
7801 (if (eq (js2-current-token-type) js2-RESERVED)
7802 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7803 (js2-report-error msg-id)
7804 (js2-unget-token))
7805 nil))
7806
7807 (defsubst js2-inside-function ()
7808 (cl-plusp js2-nesting-of-function))
7809
7810 (defun js2-set-requires-activation ()
7811 (if (js2-function-node-p js2-current-script-or-fn)
7812 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7813
7814 (defun js2-check-activation-name (name _token)
7815 (when (js2-inside-function)
7816 ;; skip language-version 1.2 check from Rhino
7817 (if (or (string= "arguments" name)
7818 (and js2-compiler-activation-names ; only used in codegen
7819 (gethash name js2-compiler-activation-names)))
7820 (js2-set-requires-activation))))
7821
7822 (defun js2-set-is-generator ()
7823 (let ((fn-node js2-current-script-or-fn))
7824 (when (and (js2-function-node-p fn-node)
7825 (not (js2-function-node-generator-type fn-node)))
7826 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7827
7828 (defun js2-must-have-xml ()
7829 (unless js2-compiler-xml-available
7830 (js2-report-error "msg.XML.not.available")))
7831
7832 (defun js2-push-scope (scope)
7833 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7834 (cl-assert (js2-scope-p scope))
7835 (cl-assert (null (js2-scope-parent-scope scope)))
7836 (cl-assert (not (eq js2-current-scope scope)))
7837 (setf (js2-scope-parent-scope scope) js2-current-scope
7838 js2-current-scope scope))
7839
7840 (defsubst js2-pop-scope ()
7841 (setq js2-current-scope
7842 (js2-scope-parent-scope js2-current-scope)))
7843
7844 (defun js2-enter-loop (loop-node)
7845 (push loop-node js2-loop-set)
7846 (push loop-node js2-loop-and-switch-set)
7847 (js2-push-scope loop-node)
7848 ;; Tell the current labeled statement (if any) its statement,
7849 ;; and set the jump target of the first label to the loop.
7850 ;; These are used in `js2-parse-continue' to verify that the
7851 ;; continue target is an actual labeled loop. (And for codegen.)
7852 (when js2-labeled-stmt
7853 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7854 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7855 js2-labeled-stmt))) loop-node)))
7856
7857 (defun js2-exit-loop ()
7858 (pop js2-loop-set)
7859 (pop js2-loop-and-switch-set)
7860 (js2-pop-scope))
7861
7862 (defsubst js2-enter-switch (switch-node)
7863 (push switch-node js2-loop-and-switch-set))
7864
7865 (defsubst js2-exit-switch ()
7866 (pop js2-loop-and-switch-set))
7867
7868 (defsubst js2-get-directive (node)
7869 "Return NODE's value if it is a directive, nil otherwise.
7870
7871 A directive is an otherwise-meaningless expression statement
7872 consisting of a string literal, such as \"use strict\"."
7873 (and (js2-expr-stmt-node-p node)
7874 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7875 (js2-string-node-value node)))
7876
7877 (defun js2-parse (&optional buf cb)
7878 "Tell the js2 parser to parse a region of JavaScript.
7879
7880 BUF is a buffer or buffer name containing the code to parse.
7881 Call `narrow-to-region' first to parse only part of the buffer.
7882
7883 The returned AST root node is given some additional properties:
7884 `node-count' - total number of nodes in the AST
7885 `buffer' - BUF. The buffer it refers to may change or be killed,
7886 so the value is not necessarily reliable.
7887
7888 An optional callback CB can be specified to report parsing
7889 progress. If `(functionp CB)' returns t, it will be called with
7890 the current line number once before parsing begins, then again
7891 each time the lexer reaches a new line number.
7892
7893 CB can also be a list of the form `(symbol cb ...)' to specify
7894 multiple callbacks with different criteria. Each symbol is a
7895 criterion keyword, and the following element is the callback to
7896 call
7897
7898 :line - called whenever the line number changes
7899 :token - called for each new token consumed
7900
7901 The list of criteria could be extended to include entering or
7902 leaving a statement, an expression, or a function definition."
7903 (if (and cb (not (functionp cb)))
7904 (error "criteria callbacks not yet implemented"))
7905 (let ((inhibit-point-motion-hooks t)
7906 (js2-compiler-xml-available (>= js2-language-version 160))
7907 ;; This is a recursive-descent parser, so give it a big stack.
7908 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7909 (max-specpdl-size (max max-specpdl-size 3000))
7910 (case-fold-search nil)
7911 ast)
7912 (with-current-buffer (or buf (current-buffer))
7913 (setq js2-scanned-comments nil
7914 js2-parsed-errors nil
7915 js2-parsed-warnings nil
7916 js2-imenu-recorder nil
7917 js2-imenu-function-map nil
7918 js2-label-set nil)
7919 (js2-init-scanner)
7920 (setq ast (js2-do-parse))
7921 (unless js2-ts-hit-eof
7922 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7923 (setf (js2-ast-root-errors ast) js2-parsed-errors
7924 (js2-ast-root-warnings ast) js2-parsed-warnings)
7925 ;; if we didn't find any declarations, put a dummy in this list so we
7926 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7927 (unless js2-imenu-recorder
7928 (setq js2-imenu-recorder 'empty))
7929 (run-hooks 'js2-parse-finished-hook)
7930 ast)))
7931
7932 ;; Corresponds to Rhino's Parser.parse() method.
7933 (defun js2-do-parse ()
7934 "Parse current buffer starting from current point.
7935 Scanner should be initialized."
7936 (let ((pos js2-ts-cursor)
7937 (end js2-ts-cursor) ; in case file is empty
7938 root n tt
7939 (in-directive-prologue t)
7940 (js2-in-use-strict-directive js2-in-use-strict-directive)
7941 directive)
7942 ;; initialize buffer-local parsing vars
7943 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7944 js2-current-script-or-fn root
7945 js2-current-scope root
7946 js2-nesting-of-function 0
7947 js2-labeled-stmt nil
7948 js2-recorded-identifiers nil ; for js2-highlight
7949 js2-in-use-strict-directive nil)
7950 (while (/= (setq tt (js2-get-token)) js2-EOF)
7951 (if (= tt js2-FUNCTION)
7952 (progn
7953 (setq n (if js2-called-by-compile-function
7954 (js2-parse-function-expr)
7955 (js2-parse-function-stmt))))
7956 ;; not a function - parse a statement
7957 (js2-unget-token)
7958 (setq n (js2-parse-statement))
7959 (when in-directive-prologue
7960 (setq directive (js2-get-directive n))
7961 (cond
7962 ((null directive)
7963 (setq in-directive-prologue nil))
7964 ((string= directive "use strict")
7965 (setq js2-in-use-strict-directive t)))))
7966 ;; add function or statement to script
7967 (setq end (js2-node-end n))
7968 (js2-block-node-push root n))
7969 ;; add comments to root in lexical order
7970 (when js2-scanned-comments
7971 ;; if we find a comment beyond end of normal kids, use its end
7972 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7973 (dolist (comment js2-scanned-comments)
7974 (push comment (js2-ast-root-comments root))
7975 (js2-node-add-children root comment)))
7976 (setf (js2-node-len root) (- end pos))
7977 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7978 ;; Give extensions a chance to muck with things before highlighting starts.
7979 (let ((js2-additional-externs js2-additional-externs))
7980 (save-excursion
7981 (run-hooks 'js2-post-parse-callbacks))
7982 (js2-highlight-undeclared-vars))
7983 root))
7984
7985 (defun js2-parse-function-closure-body (fn-node)
7986 "Parse a JavaScript 1.8 function closure body."
7987 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7988 (if js2-ts-hit-eof
7989 (js2-report-error "msg.no.brace.body" nil
7990 (js2-node-pos fn-node)
7991 (- js2-ts-cursor (js2-node-pos fn-node)))
7992 (js2-node-add-children fn-node
7993 (setf (js2-function-node-body fn-node)
7994 (js2-parse-expr t))))))
7995
7996 (defun js2-parse-function-body (fn-node)
7997 (js2-must-match js2-LC "msg.no.brace.body"
7998 (js2-node-pos fn-node)
7999 (- js2-ts-cursor (js2-node-pos fn-node)))
8000 (let ((pos (js2-current-token-beg)) ; LC position
8001 (pn (make-js2-block-node)) ; starts at LC position
8002 tt
8003 end
8004 not-in-directive-prologue
8005 node
8006 directive)
8007 (cl-incf js2-nesting-of-function)
8008 (unwind-protect
8009 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8010 (= tt js2-EOF)
8011 (= tt js2-RC)))
8012 (js2-block-node-push
8013 pn
8014 (if (/= tt js2-FUNCTION)
8015 (if not-in-directive-prologue
8016 (js2-parse-statement)
8017 (setq node (js2-parse-statement)
8018 directive (js2-get-directive node))
8019 (cond
8020 ((null directive)
8021 (setq not-in-directive-prologue t))
8022 ((string= directive "use strict")
8023 ;; Back up and reparse the function, because new rules apply
8024 ;; to the function name and parameters.
8025 (when (not js2-in-use-strict-directive)
8026 (setq js2-in-use-strict-directive t)
8027 (throw 'reparse t))))
8028 node)
8029 (js2-get-token)
8030 (js2-parse-function-stmt))))
8031 (cl-decf js2-nesting-of-function))
8032 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8033 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8034 (setq end (js2-current-token-end)))
8035 (setf (js2-node-pos pn) pos
8036 (js2-node-len pn) (- end pos))
8037 (setf (js2-function-node-body fn-node) pn)
8038 (js2-node-add-children fn-node pn)
8039 pn))
8040
8041 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8042 "Declare and fontify destructuring parameters inside NODE.
8043 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8044
8045 Return a list of `js2-name-node' nodes representing the symbols
8046 declared; probably to check them for errors."
8047 (let (name-nodes)
8048 (cond
8049 ((js2-name-node-p node)
8050 (let (leftpos)
8051 (js2-define-symbol decl-type (js2-name-node-name node)
8052 node ignore-not-in-block)
8053 (when face
8054 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8055 (+ leftpos (js2-node-len node))
8056 face 'record))
8057 (list node)))
8058 ((js2-object-node-p node)
8059 (dolist (elem (js2-object-node-elems node))
8060 ;; js2-infix-node-p catches both object prop node and initialized
8061 ;; binding element (which is directly an infix node).
8062 (when (js2-infix-node-p elem)
8063 (push (js2-define-destruct-symbols
8064 (js2-infix-node-left elem)
8065 decl-type face ignore-not-in-block)
8066 name-nodes)))
8067 (apply #'append (nreverse name-nodes)))
8068 ((js2-array-node-p node)
8069 (dolist (elem (js2-array-node-elems node))
8070 (when elem
8071 (if (js2-infix-node-p elem) (setq elem (js2-infix-node-left elem)))
8072 (push (js2-define-destruct-symbols
8073 elem decl-type face ignore-not-in-block)
8074 name-nodes)))
8075 (apply #'append (nreverse name-nodes)))
8076 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8077 (js2-node-len node))
8078 nil))))
8079
8080 (defvar js2-illegal-strict-identifiers
8081 '("eval" "arguments")
8082 "Identifiers not allowed as variables in strict mode.")
8083
8084 (defun js2-check-strict-identifier (name-node)
8085 "Check that NAME-NODE makes a legal strict mode identifier."
8086 (when js2-in-use-strict-directive
8087 (let ((param-name (js2-name-node-name name-node)))
8088 (when (member param-name js2-illegal-strict-identifiers)
8089 (js2-report-error "msg.bad.id.strict" param-name
8090 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8091
8092 (defun js2-check-strict-function-params (preceding-params params)
8093 "Given PRECEDING-PARAMS in a function's parameter list, check
8094 for strict mode errors caused by PARAMS."
8095 (when js2-in-use-strict-directive
8096 (dolist (param params)
8097 (let ((param-name (js2-name-node-name param)))
8098 (js2-check-strict-identifier param)
8099 (when (cl-some (lambda (param)
8100 (string= (js2-name-node-name param) param-name))
8101 preceding-params)
8102 (js2-report-error "msg.dup.param.strict" param-name
8103 (js2-node-abs-pos param) (js2-node-len param)))))))
8104
8105 (defun js2-parse-function-params (function-type fn-node pos)
8106 "Parse the parameters of a function of FUNCTION-TYPE
8107 represented by FN-NODE at POS."
8108 (if (js2-match-token js2-RP)
8109 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8110 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8111 (eq (js2-current-token-type) js2-NAME)))
8112 params param
8113 param-name-nodes new-param-name-nodes
8114 rest-param-at)
8115 (when paren-free-arrow
8116 (js2-unget-token))
8117 (cl-loop for tt = (js2-peek-token)
8118 do
8119 (cond
8120 ;; destructuring param
8121 ((and (not paren-free-arrow)
8122 (or (= tt js2-LB) (= tt js2-LC)))
8123 (js2-get-token)
8124 (setq param (js2-parse-destruct-primary-expr)
8125 new-param-name-nodes (js2-define-destruct-symbols
8126 param js2-LP 'js2-function-param))
8127 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8128 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8129 (push param params))
8130 ;; variable name
8131 (t
8132 (when (and (>= js2-language-version 200)
8133 (not paren-free-arrow)
8134 (js2-match-token js2-TRIPLEDOT)
8135 (not rest-param-at))
8136 ;; to report errors if there are more parameters
8137 (setq rest-param-at (length params)))
8138 (js2-must-match-name "msg.no.parm")
8139 (js2-record-face 'js2-function-param)
8140 (setq param (js2-create-name-node))
8141 (js2-define-symbol js2-LP (js2-current-token-string) param)
8142 (js2-check-strict-function-params param-name-nodes (list param))
8143 (setq param-name-nodes (append param-name-nodes (list param)))
8144 ;; default parameter value
8145 (when (and (>= js2-language-version 200)
8146 (js2-match-token js2-ASSIGN))
8147 (cl-assert (not paren-free-arrow))
8148 (let* ((pos (js2-node-pos param))
8149 (tt (js2-current-token-type))
8150 (op-pos (- (js2-current-token-beg) pos))
8151 (left param)
8152 (right (js2-parse-assign-expr))
8153 (len (- (js2-node-end right) pos)))
8154 (setq param (make-js2-assign-node
8155 :type tt :pos pos :len len :op-pos op-pos
8156 :left left :right right))
8157 (js2-node-add-children param left right)))
8158 (push param params)))
8159 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8160 (js2-report-error "msg.param.after.rest" nil
8161 (js2-node-pos param) (js2-node-len param)))
8162 while
8163 (js2-match-token js2-COMMA))
8164 (when (and (not paren-free-arrow)
8165 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8166 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8167 (when rest-param-at
8168 (setf (js2-function-node-rest-p fn-node) t))
8169 (dolist (p params)
8170 (js2-node-add-children fn-node p)
8171 (push p (js2-function-node-params fn-node))))))
8172
8173 (defun js2-check-inconsistent-return-warning (fn-node name)
8174 "Possibly show inconsistent-return warning.
8175 Last token scanned is the close-curly for the function body."
8176 (when (and js2-mode-show-strict-warnings
8177 js2-strict-inconsistent-return-warning
8178 (not (js2-has-consistent-return-usage
8179 (js2-function-node-body fn-node))))
8180 ;; Have it extend from close-curly to bol or beginning of block.
8181 (let ((pos (save-excursion
8182 (goto-char (js2-current-token-end))
8183 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8184 (point-at-bol))))
8185 (end (js2-current-token-end)))
8186 (if (cl-plusp (js2-name-node-length name))
8187 (js2-add-strict-warning "msg.no.return.value"
8188 (js2-name-node-name name) pos end)
8189 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8190
8191 (defun js2-parse-function-stmt (&optional async-p)
8192 (let ((pos (js2-current-token-beg))
8193 (star-p (js2-match-token js2-MUL)))
8194 (js2-must-match-name "msg.unnamed.function.stmt")
8195 (let ((name (js2-create-name-node t))
8196 pn member-expr)
8197 (cond
8198 ((js2-match-token js2-LP)
8199 (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p name))
8200 (js2-allow-member-expr-as-function-name
8201 (setq member-expr (js2-parse-member-expr-tail nil name))
8202 (js2-parse-highlight-member-expr-fn-name member-expr)
8203 (js2-must-match js2-LP "msg.no.paren.parms")
8204 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p)
8205 (js2-function-node-member-expr pn) member-expr)
8206 pn)
8207 (t
8208 (js2-report-error "msg.no.paren.parms")
8209 (make-js2-error-node))))))
8210
8211 (defun js2-parse-async-function-stmt ()
8212 (js2-parse-function-stmt t))
8213
8214 (defun js2-parse-function-expr (&optional async-p)
8215 (let ((pos (js2-current-token-beg))
8216 (star-p (js2-match-token js2-MUL))
8217 name)
8218 (when (js2-match-token js2-NAME)
8219 (setq name (js2-create-name-node t)))
8220 (js2-must-match js2-LP "msg.no.paren.parms")
8221 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p async-p name)))
8222
8223 (defun js2-parse-function-internal (function-type pos star-p &optional async-p name)
8224 (let (fn-node lp)
8225 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8226 (setq lp (js2-current-token-beg)))
8227 (setf fn-node (make-js2-function-node :pos pos
8228 :name name
8229 :form function-type
8230 :lp (if lp (- lp pos))
8231 :generator-type (and star-p 'STAR)
8232 :async async-p))
8233 (when name
8234 (js2-set-face (js2-node-pos name) (js2-node-end name)
8235 'font-lock-function-name-face 'record)
8236 (when (and (eq function-type 'FUNCTION_STATEMENT)
8237 (cl-plusp (js2-name-node-length name)))
8238 ;; Function statements define a symbol in the enclosing scope
8239 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8240 (when js2-in-use-strict-directive
8241 (js2-check-strict-identifier name)))
8242 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8243 ;; 1. Nested functions are not affected by the dynamic scope flag
8244 ;; as dynamic scope is already a parent of their scope.
8245 ;; 2. Functions defined under the with statement also immune to
8246 ;; this setup, in which case dynamic scope is ignored in favor
8247 ;; of the with object.
8248 (setf (js2-function-node-ignore-dynamic fn-node) t))
8249 ;; dynamically bind all the per-function variables
8250 (let ((js2-current-script-or-fn fn-node)
8251 (js2-current-scope fn-node)
8252 (js2-nesting-of-with 0)
8253 (js2-end-flags 0)
8254 js2-label-set
8255 js2-loop-set
8256 js2-loop-and-switch-set)
8257 (js2-parse-function-params function-type fn-node pos)
8258 (when (eq function-type 'FUNCTION_ARROW)
8259 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8260 (if (and (>= js2-language-version 180)
8261 (/= (js2-peek-token) js2-LC))
8262 (js2-parse-function-closure-body fn-node)
8263 (js2-parse-function-body fn-node))
8264 (js2-check-inconsistent-return-warning fn-node name)
8265
8266 (when name
8267 (js2-node-add-children fn-node name)
8268 ;; Function expressions define a name only in the body of the
8269 ;; function, and only if not hidden by a parameter name
8270 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8271 (null (js2-scope-get-symbol js2-current-scope
8272 (js2-name-node-name name))))
8273 (js2-define-symbol js2-FUNCTION
8274 (js2-name-node-name name)
8275 fn-node))
8276 (when (eq function-type 'FUNCTION_STATEMENT)
8277 (js2-record-imenu-functions fn-node))))
8278
8279 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8280 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8281 ;; We wait until after parsing the function to set its parent scope,
8282 ;; since `js2-define-symbol' needs the defining-scope check to stop
8283 ;; at the function boundary when checking for redeclarations.
8284 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8285 fn-node))
8286
8287 (defun js2-parse-function (function-type pos star-p &optional async-p name)
8288 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8289 beginning of the first token (function keyword, unless it's an
8290 arrow function), NAME is js2-name-node."
8291 (let ((continue t)
8292 ts-state
8293 fn-node
8294 ;; Preserve strict state outside this function.
8295 (js2-in-use-strict-directive js2-in-use-strict-directive))
8296 ;; Parse multiple times if a new strict mode directive is discovered in the
8297 ;; function body, as new rules will be retroactively applied to the legality
8298 ;; of function names and parameters.
8299 (while continue
8300 (setq ts-state (make-js2-ts-state))
8301 (setq continue (catch 'reparse
8302 (setq fn-node (js2-parse-function-internal
8303 function-type pos star-p async-p name))
8304 ;; Don't continue.
8305 nil))
8306 (when continue
8307 (js2-ts-seek ts-state)))
8308 fn-node))
8309
8310 (defun js2-parse-statements (&optional parent)
8311 "Parse a statement list. Last token consumed must be js2-LC.
8312
8313 PARENT can be a `js2-block-node', in which case the statements are
8314 appended to PARENT. Otherwise a new `js2-block-node' is created
8315 and returned.
8316
8317 This function does not match the closing js2-RC: the caller
8318 matches the RC so it can provide a suitable error message if not
8319 matched. This means it's up to the caller to set the length of
8320 the node to include the closing RC. The node start pos is set to
8321 the absolute buffer start position, and the caller should fix it
8322 up to be relative to the parent node. All children of this block
8323 node are given relative start positions and correct lengths."
8324 (let ((pn (or parent (make-js2-block-node)))
8325 tt)
8326 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8327 (/= tt js2-RC))
8328 (js2-block-node-push pn (js2-parse-statement)))
8329 pn))
8330
8331 (defun js2-parse-statement ()
8332 (let (pn beg end)
8333 ;; coarse-grained user-interrupt check - needs work
8334 (and js2-parse-interruptable-p
8335 (zerop (% (cl-incf js2-parse-stmt-count)
8336 js2-statements-per-pause))
8337 (input-pending-p)
8338 (throw 'interrupted t))
8339 (setq pn (js2-statement-helper))
8340 ;; no-side-effects warning check
8341 (unless (js2-node-has-side-effects pn)
8342 (setq end (js2-node-end pn))
8343 (save-excursion
8344 (goto-char end)
8345 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8346 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8347 pn))
8348
8349 ;; These correspond to the switch cases in Parser.statementHelper
8350 (defconst js2-parsers
8351 (let ((parsers (make-vector js2-num-tokens
8352 #'js2-parse-expr-stmt)))
8353 (aset parsers js2-BREAK #'js2-parse-break)
8354 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8355 (aset parsers js2-CONST #'js2-parse-const-var)
8356 (aset parsers js2-CONTINUE #'js2-parse-continue)
8357 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8358 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8359 (aset parsers js2-DO #'js2-parse-do)
8360 (aset parsers js2-EXPORT #'js2-parse-export)
8361 (aset parsers js2-FOR #'js2-parse-for)
8362 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8363 (aset parsers js2-IF #'js2-parse-if)
8364 (aset parsers js2-IMPORT #'js2-parse-import)
8365 (aset parsers js2-LC #'js2-parse-block)
8366 (aset parsers js2-LET #'js2-parse-let-stmt)
8367 (aset parsers js2-NAME #'js2-parse-name-or-label)
8368 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8369 (aset parsers js2-SEMI #'js2-parse-semi)
8370 (aset parsers js2-SWITCH #'js2-parse-switch)
8371 (aset parsers js2-THROW #'js2-parse-throw)
8372 (aset parsers js2-TRY #'js2-parse-try)
8373 (aset parsers js2-VAR #'js2-parse-const-var)
8374 (aset parsers js2-WHILE #'js2-parse-while)
8375 (aset parsers js2-WITH #'js2-parse-with)
8376 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8377 parsers)
8378 "A vector mapping token types to parser functions.")
8379
8380 (defun js2-parse-warn-missing-semi (beg end)
8381 (and js2-mode-show-strict-warnings
8382 js2-strict-missing-semi-warning
8383 (js2-add-strict-warning
8384 "msg.missing.semi" nil
8385 ;; back up to beginning of statement or line
8386 (max beg (save-excursion
8387 (goto-char end)
8388 (point-at-bol)))
8389 end)))
8390
8391 (defconst js2-no-semi-insertion
8392 (list js2-IF
8393 js2-SWITCH
8394 js2-WHILE
8395 js2-DO
8396 js2-FOR
8397 js2-TRY
8398 js2-WITH
8399 js2-LC
8400 js2-ERROR
8401 js2-SEMI
8402 js2-CLASS
8403 js2-FUNCTION
8404 js2-EXPORT)
8405 "List of tokens that don't do automatic semicolon insertion.")
8406
8407 (defconst js2-autoinsert-semi-and-warn
8408 (list js2-ERROR js2-EOF js2-RC))
8409
8410 (defun js2-statement-helper ()
8411 (let* ((tt (js2-get-token))
8412 (first-tt tt)
8413 (async-stmt (js2-match-async-function))
8414 (parser (if (= tt js2-ERROR)
8415 #'js2-parse-semi
8416 (if async-stmt
8417 #'js2-parse-async-function-stmt
8418 (aref js2-parsers tt))))
8419 pn)
8420 ;; If the statement is set, then it's been told its label by now.
8421 (and js2-labeled-stmt
8422 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8423 (setq js2-labeled-stmt nil))
8424 (setq pn (funcall parser))
8425 ;; Don't do auto semi insertion for certain statement types.
8426 (unless (or (memq first-tt js2-no-semi-insertion)
8427 (js2-labeled-stmt-node-p pn)
8428 async-stmt)
8429 (js2-auto-insert-semicolon pn))
8430 pn))
8431
8432 (defun js2-auto-insert-semicolon (pn)
8433 (let* ((tt (js2-get-token))
8434 (pos (js2-node-pos pn)))
8435 (cond
8436 ((= tt js2-SEMI)
8437 ;; extend the node bounds to include the semicolon.
8438 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8439 ((memq tt js2-autoinsert-semi-and-warn)
8440 (js2-unget-token) ; Not ';', do not consume.
8441 ;; Autoinsert ;
8442 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8443 (t
8444 (if (not (js2-token-follows-eol-p (js2-current-token)))
8445 ;; Report error if no EOL or autoinsert ';' otherwise
8446 (js2-report-error "msg.no.semi.stmt")
8447 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8448 (js2-unget-token) ; Not ';', do not consume.
8449 ))))
8450
8451 (defun js2-parse-condition ()
8452 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8453 The parens are discarded and the expression node is returned.
8454 The `pos' field of the return value is set to an absolute position
8455 that must be fixed up by the caller.
8456 Return value is a list (EXPR LP RP), with absolute paren positions."
8457 (let (pn lp rp)
8458 (if (js2-must-match js2-LP "msg.no.paren.cond")
8459 (setq lp (js2-current-token-beg)))
8460 (setq pn (js2-parse-expr))
8461 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8462 (setq rp (js2-current-token-beg)))
8463 ;; Report strict warning on code like "if (a = 7) ..."
8464 (if (and js2-strict-cond-assign-warning
8465 (js2-assign-node-p pn))
8466 (js2-add-strict-warning "msg.equal.as.assign" nil
8467 (js2-node-pos pn)
8468 (+ (js2-node-pos pn)
8469 (js2-node-len pn))))
8470 (list pn lp rp)))
8471
8472 (defun js2-parse-if ()
8473 "Parser for if-statement. Last matched token must be js2-IF."
8474 (let ((pos (js2-current-token-beg))
8475 cond if-true if-false else-pos end pn)
8476 (setq cond (js2-parse-condition)
8477 if-true (js2-parse-statement)
8478 if-false (if (js2-match-token js2-ELSE)
8479 (progn
8480 (setq else-pos (- (js2-current-token-beg) pos))
8481 (js2-parse-statement)))
8482 end (js2-node-end (or if-false if-true))
8483 pn (make-js2-if-node :pos pos
8484 :len (- end pos)
8485 :condition (car cond)
8486 :then-part if-true
8487 :else-part if-false
8488 :else-pos else-pos
8489 :lp (js2-relpos (cl-second cond) pos)
8490 :rp (js2-relpos (cl-third cond) pos)))
8491 (js2-node-add-children pn (car cond) if-true if-false)
8492 pn))
8493
8494 (defun js2-parse-import ()
8495 "Parse import statement. The current token must be js2-IMPORT."
8496 (unless (js2-ast-root-p js2-current-scope)
8497 (js2-report-error "msg.mod.import.decl.at.top.level"))
8498 (let ((beg (js2-current-token-beg)))
8499 (cond ((js2-match-token js2-STRING)
8500 (make-js2-import-node
8501 :pos beg
8502 :len (- (js2-current-token-end) beg)
8503 :module-id (js2-current-token-string)))
8504 (t
8505 (let* ((import-clause (js2-parse-import-clause))
8506 (from-clause (and import-clause (js2-parse-from-clause)))
8507 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8508 (node (make-js2-import-node
8509 :pos beg
8510 :len (- (js2-current-token-end) beg)
8511 :import import-clause
8512 :from from-clause
8513 :module-id module-id)))
8514 (when import-clause
8515 (js2-node-add-children node import-clause))
8516 (when from-clause
8517 (js2-node-add-children node from-clause))
8518 node)))))
8519
8520 (defun js2-parse-import-clause ()
8521 "Parse the bindings in an import statement.
8522 This can take many forms:
8523
8524 ImportedDefaultBinding -> 'foo'
8525 NameSpaceImport -> '* as lib'
8526 NamedImports -> '{foo as bar, bang}'
8527 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8528 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8529
8530 Try to match namespace imports and named imports first because nothing can
8531 come after them. If it is an imported default binding, then it could have named
8532 imports or a namespace import that follows it.
8533 "
8534 (let* ((beg (js2-current-token-beg))
8535 (clause (make-js2-import-clause-node
8536 :pos beg))
8537 (children (list)))
8538 (cond
8539 ((js2-match-token js2-MUL)
8540 (let ((ns-import (js2-parse-namespace-import)))
8541 (when ns-import
8542 (let ((name-node (js2-namespace-import-node-name ns-import)))
8543 (js2-define-symbol
8544 js2-LET (js2-name-node-name name-node) name-node t)))
8545 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8546 (push ns-import children)))
8547 ((js2-match-token js2-LC)
8548 (let ((imports (js2-parse-export-bindings t)))
8549 (setf (js2-import-clause-node-named-imports clause) imports)
8550 (dolist (import imports)
8551 (push import children)
8552 (let ((name-node (js2-export-binding-node-local-name import)))
8553 (when name-node
8554 (js2-define-symbol
8555 js2-LET (js2-name-node-name name-node) name-node t))))))
8556 ((= (js2-peek-token) js2-NAME)
8557 (let ((binding (js2-maybe-parse-export-binding)))
8558 (let ((node-name (js2-export-binding-node-local-name binding)))
8559 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8560 (setf (js2-import-clause-node-default-binding clause) binding)
8561 (push binding children))
8562 (when (js2-match-token js2-COMMA)
8563 (cond
8564 ((js2-match-token js2-MUL)
8565 (let ((ns-import (js2-parse-namespace-import)))
8566 (let ((name-node (js2-namespace-import-node-name ns-import)))
8567 (js2-define-symbol
8568 js2-LET (js2-name-node-name name-node) name-node t))
8569 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8570 (push ns-import children)))
8571 ((js2-match-token js2-LC)
8572 (let ((imports (js2-parse-export-bindings t)))
8573 (setf (js2-import-clause-node-named-imports clause) imports)
8574 (dolist (import imports)
8575 (push import children)
8576 (let ((name-node (js2-export-binding-node-local-name import)))
8577 (when name-node
8578 (js2-define-symbol
8579 js2-LET (js2-name-node-name name-node) name-node t))))))
8580 (t (js2-report-error "msg.syntax")))))
8581 (t (js2-report-error "msg.mod.declaration.after.import")))
8582 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8583 (apply #'js2-node-add-children clause children)
8584 clause))
8585
8586 (defun js2-parse-namespace-import ()
8587 "Parse a namespace import expression such as '* as bar'.
8588 The current token must be js2-MUL."
8589 (let ((beg (js2-current-token-beg)))
8590 (when (js2-must-match js2-NAME "msg.syntax")
8591 (if (equal "as" (js2-current-token-string))
8592 (when (js2-must-match-prop-name "msg.syntax")
8593 (let ((node (make-js2-namespace-import-node
8594 :pos beg
8595 :len (- (js2-current-token-end) beg)
8596 :name (make-js2-name-node
8597 :pos (js2-current-token-beg)
8598 :len (js2-current-token-end)
8599 :name (js2-current-token-string)))))
8600 (js2-node-add-children node (js2-namespace-import-node-name node))
8601 node))
8602 (js2-unget-token)
8603 (js2-report-error "msg.syntax")))))
8604
8605
8606 (defun js2-parse-from-clause ()
8607 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8608 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8609 (let ((beg (js2-current-token-beg)))
8610 (if (equal "from" (js2-current-token-string))
8611 (cond
8612 ((js2-match-token js2-STRING)
8613 (make-js2-from-clause-node
8614 :pos beg
8615 :len (- (js2-current-token-end) beg)
8616 :module-id (js2-current-token-string)
8617 :metadata-p nil))
8618 ((js2-match-token js2-THIS)
8619 (when (js2-must-match-name "msg.mod.spec.after.from")
8620 (if (equal "module" (js2-current-token-string))
8621 (make-js2-from-clause-node
8622 :pos beg
8623 :len (- (js2-current-token-end) beg)
8624 :module-id "this"
8625 :metadata-p t)
8626 (js2-unget-token)
8627 (js2-unget-token)
8628 (js2-report-error "msg.mod.spec.after.from")
8629 nil)))
8630 (t (js2-report-error "msg.mod.spec.after.from") nil))
8631 (js2-unget-token)
8632 (js2-report-error "msg.mod.from.after.import.spec.set")
8633 nil))))
8634
8635 (defun js2-parse-export-bindings (&optional import-p)
8636 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8637 {foo as bar, baz as bang}. The current token must be
8638 js2-LC. Return a lisp list of js2-export-binding-node"
8639 (let ((bindings (list)))
8640 (while
8641 (let ((binding (js2-maybe-parse-export-binding)))
8642 (when binding
8643 (push binding bindings))
8644 (js2-match-token js2-COMMA)))
8645 (when (js2-must-match js2-RC (if import-p
8646 "msg.mod.rc.after.import.spec.list"
8647 "msg.mod.rc.after.export.spec.list"))
8648 (reverse bindings))))
8649
8650 (defun js2-maybe-parse-export-binding ()
8651 "Attempt to parse a binding expression found inside an import/export statement.
8652 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8653 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8654 js2-export-binding-node and consume all the tokens. If it does not match, it
8655 consumes no tokens."
8656 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8657 (beg (js2-current-token-beg))
8658 (extern-name-len (js2-current-token-len))
8659 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8660 (aref js2-kwd-tokens (js2-current-token-type)))))
8661 (if extern-name
8662 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8663 (if (and as (equal "as" (js2-current-token-string)))
8664 (let ((name
8665 (or
8666 (and (js2-match-token js2-DEFAULT) "default")
8667 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8668 (if name
8669 (let ((node (make-js2-export-binding-node
8670 :pos beg
8671 :len (- (js2-current-token-end) beg)
8672 :local-name (make-js2-name-node
8673 :name name
8674 :pos (js2-current-token-beg)
8675 :len (js2-current-token-len))
8676 :extern-name (make-js2-name-node
8677 :name extern-name
8678 :pos beg
8679 :len extern-name-len))))
8680 (js2-node-add-children
8681 node
8682 (js2-export-binding-node-local-name node)
8683 (js2-export-binding-node-extern-name node))
8684 node)
8685 (js2-unget-token)
8686 nil))
8687 (when as (js2-unget-token))
8688 (let* ((name-node (make-js2-name-node
8689 :name (js2-current-token-string)
8690 :pos (js2-current-token-beg)
8691 :len (js2-current-token-len)))
8692 (node (make-js2-export-binding-node
8693 :pos (js2-current-token-beg)
8694 :len (js2-current-token-len)
8695 :local-name name-node
8696 :extern-name name-node)))
8697 (when is-reserved-name
8698 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8699 (js2-node-add-children node name-node)
8700 node)))
8701 nil)))
8702
8703 (defun js2-parse-switch ()
8704 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8705 (let ((pos (js2-current-token-beg))
8706 tt pn discriminant has-default case-expr case-node
8707 case-pos cases stmt lp)
8708 (if (js2-must-match js2-LP "msg.no.paren.switch")
8709 (setq lp (js2-current-token-beg)))
8710 (setq discriminant (js2-parse-expr)
8711 pn (make-js2-switch-node :discriminant discriminant
8712 :pos pos
8713 :lp (js2-relpos lp pos)))
8714 (js2-node-add-children pn discriminant)
8715 (js2-enter-switch pn)
8716 (unwind-protect
8717 (progn
8718 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8719 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8720 (js2-must-match js2-LC "msg.no.brace.switch")
8721 (catch 'break
8722 (while t
8723 (setq tt (js2-next-token)
8724 case-pos (js2-current-token-beg))
8725 (cond
8726 ((= tt js2-RC)
8727 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8728 (throw 'break nil)) ; done
8729 ((= tt js2-CASE)
8730 (setq case-expr (js2-parse-expr))
8731 (js2-must-match js2-COLON "msg.no.colon.case"))
8732 ((= tt js2-DEFAULT)
8733 (if has-default
8734 (js2-report-error "msg.double.switch.default"))
8735 (setq has-default t
8736 case-expr nil)
8737 (js2-must-match js2-COLON "msg.no.colon.case"))
8738 (t
8739 (js2-report-error "msg.bad.switch")
8740 (throw 'break nil)))
8741 (setq case-node (make-js2-case-node :pos case-pos
8742 :len (- (js2-current-token-end) case-pos)
8743 :expr case-expr))
8744 (js2-node-add-children case-node case-expr)
8745 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8746 (/= tt js2-CASE)
8747 (/= tt js2-DEFAULT)
8748 (/= tt js2-EOF))
8749 (setf stmt (js2-parse-statement)
8750 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8751 (js2-block-node-push case-node stmt))
8752 (push case-node cases)))
8753 ;; add cases last, as pushing reverses the order to be correct
8754 (dolist (kid cases)
8755 (js2-node-add-children pn kid)
8756 (push kid (js2-switch-node-cases pn)))
8757 pn) ; return value
8758 (js2-exit-switch))))
8759
8760 (defun js2-parse-while ()
8761 "Parser for while-statement. Last matched token must be js2-WHILE."
8762 (let ((pos (js2-current-token-beg))
8763 (pn (make-js2-while-node))
8764 cond body)
8765 (js2-enter-loop pn)
8766 (unwind-protect
8767 (progn
8768 (setf cond (js2-parse-condition)
8769 (js2-while-node-condition pn) (car cond)
8770 body (js2-parse-statement)
8771 (js2-while-node-body pn) body
8772 (js2-node-len pn) (- (js2-node-end body) pos)
8773 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8774 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8775 (js2-node-add-children pn body (car cond)))
8776 (js2-exit-loop))
8777 pn))
8778
8779 (defun js2-parse-do ()
8780 "Parser for do-statement. Last matched token must be js2-DO."
8781 (let ((pos (js2-current-token-beg))
8782 (pn (make-js2-do-node))
8783 cond body end)
8784 (js2-enter-loop pn)
8785 (unwind-protect
8786 (progn
8787 (setq body (js2-parse-statement))
8788 (js2-must-match js2-WHILE "msg.no.while.do")
8789 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8790 cond (js2-parse-condition)
8791 (js2-do-node-condition pn) (car cond)
8792 (js2-do-node-body pn) body
8793 end js2-ts-cursor
8794 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8795 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8796 (js2-node-add-children pn (car cond) body))
8797 (js2-exit-loop))
8798 ;; Always auto-insert semicolon to follow SpiderMonkey:
8799 ;; It is required by ECMAScript but is ignored by the rest of
8800 ;; world; see bug 238945
8801 (if (js2-match-token js2-SEMI)
8802 (setq end js2-ts-cursor))
8803 (setf (js2-node-len pn) (- end pos))
8804 pn))
8805
8806 (defun js2-parse-export ()
8807 "Parse an export statement.
8808 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8809 expressions should only be either hoistable expressions (function or generator)
8810 or assignment expressions, but there is no checking to enforce that and so it
8811 will parse without error a small subset of
8812 invalid export statements."
8813 (unless (js2-ast-root-p js2-current-scope)
8814 (js2-report-error "msg.mod.export.decl.at.top.level"))
8815 (let ((beg (js2-current-token-beg))
8816 (children (list))
8817 exports-list from-clause declaration default)
8818 (cond
8819 ((js2-match-token js2-MUL)
8820 (setq from-clause (js2-parse-from-clause))
8821 (when from-clause
8822 (push from-clause children)))
8823 ((js2-match-token js2-LC)
8824 (setq exports-list (js2-parse-export-bindings))
8825 (when exports-list
8826 (dolist (export exports-list)
8827 (push export children)))
8828 (when (js2-match-token js2-NAME)
8829 (if (equal "from" (js2-current-token-string))
8830 (progn
8831 (js2-unget-token)
8832 (setq from-clause (js2-parse-from-clause)))
8833 (js2-unget-token))))
8834 ((js2-match-token js2-DEFAULT)
8835 (setq default (js2-parse-expr)))
8836 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8837 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8838 (t
8839 (setq declaration (js2-parse-expr))))
8840 (when from-clause
8841 (push from-clause children))
8842 (when declaration
8843 (push declaration children)
8844 (when (not (js2-function-node-p declaration))
8845 (js2-auto-insert-semicolon declaration)))
8846 (when default
8847 (push default children)
8848 (when (not (js2-function-node-p default))
8849 (js2-auto-insert-semicolon default)))
8850 (let ((node (make-js2-export-node
8851 :pos beg
8852 :len (- (js2-current-token-end) beg)
8853 :exports-list exports-list
8854 :from-clause from-clause
8855 :declaration declaration
8856 :default default)))
8857 (apply #'js2-node-add-children node children)
8858 node)))
8859
8860 (defun js2-parse-for ()
8861 "Parse a for, for-in or for each-in statement.
8862 Last matched token must be js2-FOR."
8863 (let ((for-pos (js2-current-token-beg))
8864 (tmp-scope (make-js2-scope))
8865 pn is-for-each is-for-in-or-of is-for-of
8866 in-pos each-pos tmp-pos
8867 init ; Node init is also foo in 'foo in object'.
8868 cond ; Node cond is also object in 'foo in object'.
8869 incr ; 3rd section of for-loop initializer.
8870 body tt lp rp)
8871 ;; See if this is a for each () instead of just a for ()
8872 (when (js2-match-token js2-NAME)
8873 (if (string= "each" (js2-current-token-string))
8874 (progn
8875 (setq is-for-each t
8876 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8877 (js2-record-face 'font-lock-keyword-face))
8878 (js2-report-error "msg.no.paren.for")))
8879 (if (js2-must-match js2-LP "msg.no.paren.for")
8880 (setq lp (- (js2-current-token-beg) for-pos)))
8881 (setq tt (js2-get-token))
8882 ;; Capture identifiers inside parens. We can't create the node
8883 ;; (and use it as the current scope) until we know its type.
8884 (js2-push-scope tmp-scope)
8885 (unwind-protect
8886 (progn
8887 ;; parse init clause
8888 (let ((js2-in-for-init t)) ; set as dynamic variable
8889 (cond
8890 ((= tt js2-SEMI)
8891 (js2-unget-token)
8892 (setq init (make-js2-empty-expr-node)))
8893 ((or (= tt js2-VAR) (= tt js2-LET))
8894 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8895 (t
8896 (js2-unget-token)
8897 (setq init (js2-parse-expr)))))
8898 (if (or (js2-match-token js2-IN)
8899 (and (>= js2-language-version 200)
8900 (js2-match-contextual-kwd "of")
8901 (setq is-for-of t)))
8902 (setq is-for-in-or-of t
8903 in-pos (- (js2-current-token-beg) for-pos)
8904 ;; scope of iteration target object is not the scope we've created above.
8905 ;; stash current scope temporary.
8906 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8907 (js2-parse-expr))) ; object over which we're iterating
8908 ;; else ordinary for loop - parse cond and incr
8909 (js2-must-match js2-SEMI "msg.no.semi.for")
8910 (setq cond (if (= (js2-peek-token) js2-SEMI)
8911 (make-js2-empty-expr-node) ; no loop condition
8912 (js2-parse-expr)))
8913 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8914 (setq tmp-pos (js2-current-token-end)
8915 incr (if (= (js2-peek-token) js2-RP)
8916 (make-js2-empty-expr-node :pos tmp-pos)
8917 (js2-parse-expr)))))
8918 (js2-pop-scope))
8919 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8920 (setq rp (- (js2-current-token-beg) for-pos)))
8921 (if (not is-for-in-or-of)
8922 (setq pn (make-js2-for-node :init init
8923 :condition cond
8924 :update incr
8925 :lp lp
8926 :rp rp))
8927 ;; cond could be null if 'in obj' got eaten by the init node.
8928 (if (js2-infix-node-p init)
8929 ;; it was (foo in bar) instead of (var foo in bar)
8930 (setq cond (js2-infix-node-right init)
8931 init (js2-infix-node-left init))
8932 (if (and (js2-var-decl-node-p init)
8933 (> (length (js2-var-decl-node-kids init)) 1))
8934 (js2-report-error "msg.mult.index")))
8935 (setq pn (make-js2-for-in-node :iterator init
8936 :object cond
8937 :in-pos in-pos
8938 :foreach-p is-for-each
8939 :each-pos each-pos
8940 :forof-p is-for-of
8941 :lp lp
8942 :rp rp)))
8943 ;; Transplant the declarations.
8944 (setf (js2-scope-symbol-table pn)
8945 (js2-scope-symbol-table tmp-scope))
8946 (unwind-protect
8947 (progn
8948 (js2-enter-loop pn)
8949 ;; We have to parse the body -after- creating the loop node,
8950 ;; so that the loop node appears in the js2-loop-set, allowing
8951 ;; break/continue statements to find the enclosing loop.
8952 (setf body (js2-parse-statement)
8953 (js2-loop-node-body pn) body
8954 (js2-node-pos pn) for-pos
8955 (js2-node-len pn) (- (js2-node-end body) for-pos))
8956 (js2-node-add-children pn init cond incr body))
8957 ;; finally
8958 (js2-exit-loop))
8959 pn))
8960
8961 (defun js2-parse-try ()
8962 "Parse a try statement. Last matched token must be js2-TRY."
8963 (let ((try-pos (js2-current-token-beg))
8964 try-end
8965 try-block
8966 catch-blocks
8967 finally-block
8968 saw-default-catch
8969 peek)
8970 (if (/= (js2-peek-token) js2-LC)
8971 (js2-report-error "msg.no.brace.try"))
8972 (setq try-block (js2-parse-statement)
8973 try-end (js2-node-end try-block)
8974 peek (js2-peek-token))
8975 (cond
8976 ((= peek js2-CATCH)
8977 (while (js2-match-token js2-CATCH)
8978 (let* ((catch-pos (js2-current-token-beg))
8979 (catch-node (make-js2-catch-node :pos catch-pos))
8980 param
8981 guard-kwd
8982 catch-cond
8983 lp rp)
8984 (if saw-default-catch
8985 (js2-report-error "msg.catch.unreachable"))
8986 (if (js2-must-match js2-LP "msg.no.paren.catch")
8987 (setq lp (- (js2-current-token-beg) catch-pos)))
8988 (js2-push-scope catch-node)
8989 (let ((tt (js2-peek-token)))
8990 (cond
8991 ;; Destructuring pattern:
8992 ;; catch ({ message, file }) { ... }
8993 ((or (= tt js2-LB) (= tt js2-LC))
8994 (js2-get-token)
8995 (setq param (js2-parse-destruct-primary-expr))
8996 (js2-define-destruct-symbols param js2-LET nil))
8997 ;; Simple name.
8998 (t
8999 (js2-must-match-name "msg.bad.catchcond")
9000 (setq param (js2-create-name-node))
9001 (js2-define-symbol js2-LET (js2-current-token-string) param)
9002 (js2-check-strict-identifier param))))
9003 ;; Catch condition.
9004 (if (js2-match-token js2-IF)
9005 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9006 catch-cond (js2-parse-expr))
9007 (setq saw-default-catch t))
9008 (if (js2-must-match js2-RP "msg.bad.catchcond")
9009 (setq rp (- (js2-current-token-beg) catch-pos)))
9010 (js2-must-match js2-LC "msg.no.brace.catchblock")
9011 (js2-parse-statements catch-node)
9012 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9013 (setq try-end (js2-current-token-end)))
9014 (js2-pop-scope)
9015 (setf (js2-node-len catch-node) (- try-end catch-pos)
9016 (js2-catch-node-param catch-node) param
9017 (js2-catch-node-guard-expr catch-node) catch-cond
9018 (js2-catch-node-guard-kwd catch-node) guard-kwd
9019 (js2-catch-node-lp catch-node) lp
9020 (js2-catch-node-rp catch-node) rp)
9021 (js2-node-add-children catch-node param catch-cond)
9022 (push catch-node catch-blocks))))
9023 ((/= peek js2-FINALLY)
9024 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9025 (js2-node-pos try-block)
9026 (- (setq try-end (js2-node-end try-block))
9027 (js2-node-pos try-block)))))
9028 (when (js2-match-token js2-FINALLY)
9029 (let ((finally-pos (js2-current-token-beg))
9030 (block (js2-parse-statement)))
9031 (setq try-end (js2-node-end block)
9032 finally-block (make-js2-finally-node :pos finally-pos
9033 :len (- try-end finally-pos)
9034 :body block))
9035 (js2-node-add-children finally-block block)))
9036 (let ((pn (make-js2-try-node :pos try-pos
9037 :len (- try-end try-pos)
9038 :try-block try-block
9039 :finally-block finally-block)))
9040 (js2-node-add-children pn try-block finally-block)
9041 ;; Push them onto the try-node, which reverses and corrects their order.
9042 (dolist (cb catch-blocks)
9043 (js2-node-add-children pn cb)
9044 (push cb (js2-try-node-catch-clauses pn)))
9045 pn)))
9046
9047 (defun js2-parse-throw ()
9048 "Parser for throw-statement. Last matched token must be js2-THROW."
9049 (let ((pos (js2-current-token-beg))
9050 expr pn)
9051 (if (= (js2-peek-token-or-eol) js2-EOL)
9052 ;; ECMAScript does not allow new lines before throw expression,
9053 ;; see bug 256617
9054 (js2-report-error "msg.bad.throw.eol"))
9055 (setq expr (js2-parse-expr)
9056 pn (make-js2-throw-node :pos pos
9057 :len (- (js2-node-end expr) pos)
9058 :expr expr))
9059 (js2-node-add-children pn expr)
9060 pn))
9061
9062 (defun js2-match-jump-label-name (label-name)
9063 "If break/continue specified a label, return that label's labeled stmt.
9064 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9065 does not match an existing label, reports an error and returns nil."
9066 (let ((bundle (cdr (assoc label-name js2-label-set))))
9067 (if (null bundle)
9068 (js2-report-error "msg.undef.label"))
9069 bundle))
9070
9071 (defun js2-parse-break ()
9072 "Parser for break-statement. Last matched token must be js2-BREAK."
9073 (let ((pos (js2-current-token-beg))
9074 (end (js2-current-token-end))
9075 break-target ; statement to break from
9076 break-label ; in "break foo", name-node representing the foo
9077 labels ; matching labeled statement to break to
9078 pn)
9079 (when (eq (js2-peek-token-or-eol) js2-NAME)
9080 (js2-get-token)
9081 (setq break-label (js2-create-name-node)
9082 end (js2-node-end break-label)
9083 ;; matchJumpLabelName only matches if there is one
9084 labels (js2-match-jump-label-name (js2-current-token-string))
9085 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9086 (unless (or break-target break-label)
9087 ;; no break target specified - try for innermost enclosing loop/switch
9088 (if (null js2-loop-and-switch-set)
9089 (unless break-label
9090 (js2-report-error "msg.bad.break" nil pos (length "break")))
9091 (setq break-target (car js2-loop-and-switch-set))))
9092 (setq pn (make-js2-break-node :pos pos
9093 :len (- end pos)
9094 :label break-label
9095 :target break-target))
9096 (js2-node-add-children pn break-label) ; but not break-target
9097 pn))
9098
9099 (defun js2-parse-continue ()
9100 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9101 (let ((pos (js2-current-token-beg))
9102 (end (js2-current-token-end))
9103 label ; optional user-specified label, a `js2-name-node'
9104 labels ; current matching labeled stmt, if any
9105 target ; the `js2-loop-node' target of this continue stmt
9106 pn)
9107 (when (= (js2-peek-token-or-eol) js2-NAME)
9108 (js2-get-token)
9109 (setq label (js2-create-name-node)
9110 end (js2-node-end label)
9111 ;; matchJumpLabelName only matches if there is one
9112 labels (js2-match-jump-label-name (js2-current-token-string))))
9113 (cond
9114 ((null labels) ; no current label to go to
9115 (if (null js2-loop-set) ; no loop to continue to
9116 (js2-report-error "msg.continue.outside" nil pos
9117 (length "continue"))
9118 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9119 (t
9120 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9121 (setq target (js2-labeled-stmt-node-stmt labels))
9122 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9123 (setq pn (make-js2-continue-node :pos pos
9124 :len (- end pos)
9125 :label label
9126 :target target))
9127 (js2-node-add-children pn label) ; but not target - it's not our child
9128 pn))
9129
9130 (defun js2-parse-with ()
9131 "Parser for with-statement. Last matched token must be js2-WITH."
9132 (when js2-in-use-strict-directive
9133 (js2-report-error "msg.no.with.strict"))
9134 (let ((pos (js2-current-token-beg))
9135 obj body pn lp rp)
9136 (if (js2-must-match js2-LP "msg.no.paren.with")
9137 (setq lp (js2-current-token-beg)))
9138 (setq obj (js2-parse-expr))
9139 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9140 (setq rp (js2-current-token-beg)))
9141 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9142 (setq body (js2-parse-statement)))
9143 (setq pn (make-js2-with-node :pos pos
9144 :len (- (js2-node-end body) pos)
9145 :object obj
9146 :body body
9147 :lp (js2-relpos lp pos)
9148 :rp (js2-relpos rp pos)))
9149 (js2-node-add-children pn obj body)
9150 pn))
9151
9152 (defun js2-parse-const-var ()
9153 "Parser for var- or const-statement.
9154 Last matched token must be js2-CONST or js2-VAR."
9155 (let ((tt (js2-current-token-type))
9156 (pos (js2-current-token-beg))
9157 expr pn)
9158 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9159 pn (make-js2-expr-stmt-node :pos pos
9160 :len (- (js2-node-end expr) pos)
9161 :expr expr))
9162 (js2-node-add-children pn expr)
9163 pn))
9164
9165 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9166 (let ((pn (make-js2-expr-stmt-node :pos pos
9167 :len (js2-node-len expr)
9168 :type (if (js2-inside-function)
9169 js2-EXPR_VOID
9170 js2-EXPR_RESULT)
9171 :expr expr)))
9172 (if add-child
9173 (js2-node-add-children pn expr))
9174 pn))
9175
9176 (defun js2-parse-let-stmt ()
9177 "Parser for let-statement. Last matched token must be js2-LET."
9178 (let ((pos (js2-current-token-beg))
9179 expr pn)
9180 (if (= (js2-peek-token) js2-LP)
9181 ;; let expression in statement context
9182 (setq expr (js2-parse-let pos 'statement)
9183 pn (js2-wrap-with-expr-stmt pos expr t))
9184 ;; else we're looking at a statement like let x=6, y=7;
9185 (setf expr (js2-parse-variables js2-LET pos)
9186 pn (js2-wrap-with-expr-stmt pos expr t)
9187 (js2-node-type pn) js2-EXPR_RESULT))
9188 pn))
9189
9190 (defun js2-parse-ret-yield ()
9191 (js2-parse-return-or-yield (js2-current-token-type) nil))
9192
9193 (defconst js2-parse-return-stmt-enders
9194 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9195
9196 (defsubst js2-now-all-set (before after mask)
9197 "Return whether or not the bits in the mask have changed to all set.
9198 BEFORE is bits before change, AFTER is bits after change, and MASK is
9199 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9200 but not BEFORE."
9201 (and (/= (logand before mask) mask)
9202 (= (logand after mask) mask)))
9203
9204 (defun js2-parse-return-or-yield (tt expr-context)
9205 (let* ((pos (js2-current-token-beg))
9206 (end (js2-current-token-end))
9207 (before js2-end-flags)
9208 (inside-function (js2-inside-function))
9209 (gen-type (and inside-function (js2-function-node-generator-type
9210 js2-current-script-or-fn)))
9211 e ret name yield-star-p)
9212 (unless inside-function
9213 (js2-report-error (if (eq tt js2-RETURN)
9214 "msg.bad.return"
9215 "msg.bad.yield")))
9216 (when (and inside-function
9217 (eq gen-type 'STAR)
9218 (js2-match-token js2-MUL))
9219 (setq yield-star-p t))
9220 ;; This is ugly, but we don't want to require a semicolon.
9221 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9222 (setq e (js2-parse-expr)
9223 end (js2-node-end e)))
9224 (cond
9225 ((eq tt js2-RETURN)
9226 (js2-set-flag js2-end-flags (if (null e)
9227 js2-end-returns
9228 js2-end-returns-value))
9229 (setq ret (make-js2-return-node :pos pos
9230 :len (- end pos)
9231 :retval e))
9232 (js2-node-add-children ret e)
9233 ;; See if we need a strict mode warning.
9234 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9235 ;; more thorough and accurate than this before/after flag check.
9236 ;; E.g. if there's a finally-block that always returns, we shouldn't
9237 ;; show a warning generated by inconsistent returns in the catch blocks.
9238 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9239 ;; so we know which returns/yields to highlight, and we should get rid of
9240 ;; all the checking in `js2-parse-return-or-yield'.
9241 (if (and js2-strict-inconsistent-return-warning
9242 (js2-now-all-set before js2-end-flags
9243 (logior js2-end-returns js2-end-returns-value)))
9244 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9245 ((eq gen-type 'COMPREHENSION)
9246 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9247 ;; like SpiderMonkey does.
9248 (js2-report-error "msg.syntax" nil pos 5))
9249 (t
9250 (setq ret (make-js2-yield-node :pos pos
9251 :len (- end pos)
9252 :value e
9253 :star-p yield-star-p))
9254 (js2-node-add-children ret e)
9255 (unless expr-context
9256 (setq e ret
9257 ret (js2-wrap-with-expr-stmt pos e t))
9258 (js2-set-requires-activation)
9259 (js2-set-is-generator))))
9260 ;; see if we are mixing yields and value returns.
9261 (when (and inside-function
9262 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9263 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9264 'LEGACY))
9265 (setq name (js2-function-name js2-current-script-or-fn))
9266 (if (zerop (length name))
9267 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9268 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9269 ret))
9270
9271 (defun js2-parse-debugger ()
9272 (make-js2-keyword-node :type js2-DEBUGGER))
9273
9274 (defun js2-parse-block ()
9275 "Parser for a curly-delimited statement block.
9276 Last token matched must be `js2-LC'."
9277 (let ((pos (js2-current-token-beg))
9278 (pn (make-js2-scope)))
9279 (js2-push-scope pn)
9280 (unwind-protect
9281 (progn
9282 (js2-parse-statements pn)
9283 (js2-must-match js2-RC "msg.no.brace.block")
9284 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9285 (js2-pop-scope))
9286 pn))
9287
9288 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9289 (defun js2-parse-semi ()
9290 "Parse a statement or handle an error.
9291 Current token type is `js2-SEMI' or `js2-ERROR'."
9292 (let ((tt (js2-current-token-type)) pos len)
9293 (if (eq tt js2-SEMI)
9294 (make-js2-empty-expr-node :len 1)
9295 (setq pos (js2-current-token-beg)
9296 len (- (js2-current-token-end) pos))
9297 (js2-report-error "msg.syntax" nil pos len)
9298 (make-js2-error-node :pos pos :len len))))
9299
9300 (defun js2-parse-default-xml-namespace ()
9301 "Parse a `default xml namespace = <expr>' e4x statement."
9302 (let ((pos (js2-current-token-beg))
9303 end len expr unary)
9304 (js2-must-have-xml)
9305 (js2-set-requires-activation)
9306 (setq len (- js2-ts-cursor pos))
9307 (unless (and (js2-match-token js2-NAME)
9308 (string= (js2-current-token-string) "xml"))
9309 (js2-report-error "msg.bad.namespace" nil pos len))
9310 (unless (and (js2-match-token js2-NAME)
9311 (string= (js2-current-token-string) "namespace"))
9312 (js2-report-error "msg.bad.namespace" nil pos len))
9313 (unless (js2-match-token js2-ASSIGN)
9314 (js2-report-error "msg.bad.namespace" nil pos len))
9315 (setq expr (js2-parse-expr)
9316 end (js2-node-end expr)
9317 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9318 :pos pos
9319 :len (- end pos)
9320 :operand expr))
9321 (js2-node-add-children unary expr)
9322 (make-js2-expr-stmt-node :pos pos
9323 :len (- end pos)
9324 :expr unary)))
9325
9326 (defun js2-record-label (label bundle)
9327 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9328 (js2-get-token)
9329 (let ((name (js2-label-node-name label))
9330 labeled-stmt
9331 dup)
9332 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9333 ;; flag both labels if possible when used in editing mode
9334 (if (and js2-parse-ide-mode
9335 (setq dup (js2-get-label-by-name labeled-stmt name)))
9336 (js2-report-error "msg.dup.label" nil
9337 (js2-node-abs-pos dup) (js2-node-len dup)))
9338 (js2-report-error "msg.dup.label" nil
9339 (js2-node-pos label) (js2-node-len label)))
9340 (js2-labeled-stmt-node-add-label bundle label)
9341 (js2-node-add-children bundle label)
9342 ;; Add one reference to the bundle per label in `js2-label-set'
9343 (push (cons name bundle) js2-label-set)))
9344
9345 (defun js2-parse-name-or-label ()
9346 "Parser for identifier or label. Last token matched must be js2-NAME.
9347 Called when we found a name in a statement context. If it's a label, we gather
9348 up any following labels and the next non-label statement into a
9349 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9350 expression and return it wrapped in a `js2-expr-stmt-node'."
9351 (let ((pos (js2-current-token-beg))
9352 expr stmt bundle
9353 (continue t))
9354 ;; set check for label and call down to `js2-parse-primary-expr'
9355 (setq expr (js2-maybe-parse-label))
9356 (if (null expr)
9357 ;; Parse the non-label expression and wrap with expression stmt.
9358 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9359 ;; else parsed a label
9360 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9361 (js2-record-label expr bundle)
9362 ;; look for more labels
9363 (while (and continue (= (js2-get-token) js2-NAME))
9364 (if (setq expr (js2-maybe-parse-label))
9365 (js2-record-label expr bundle)
9366 (setq expr (js2-parse-expr)
9367 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9368 continue nil)
9369 (js2-auto-insert-semicolon stmt)))
9370 ;; no more labels; now parse the labeled statement
9371 (unwind-protect
9372 (unless stmt
9373 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9374 (js2-unget-token)
9375 (setq stmt (js2-statement-helper))))
9376 ;; remove the labels for this statement from the global set
9377 (dolist (label (js2-labeled-stmt-node-labels bundle))
9378 (setq js2-label-set (remove label js2-label-set))))
9379 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9380 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9381 (js2-node-add-children bundle stmt)
9382 bundle)))
9383
9384 (defun js2-maybe-parse-label ()
9385 (cl-assert (= (js2-current-token-type) js2-NAME))
9386 (let (label-pos
9387 (next-tt (js2-get-token))
9388 (label-end (js2-current-token-end)))
9389 ;; Do not consume colon, it is used as unwind indicator
9390 ;; to return to statementHelper.
9391 (js2-unget-token)
9392 (if (= next-tt js2-COLON)
9393 (prog2
9394 (setq label-pos (js2-current-token-beg))
9395 (make-js2-label-node :pos label-pos
9396 :len (- label-end label-pos)
9397 :name (js2-current-token-string))
9398 (js2-set-face label-pos
9399 label-end
9400 'font-lock-variable-name-face 'record))
9401 ;; Backtrack from the name token, too.
9402 (js2-unget-token)
9403 nil)))
9404
9405 (defun js2-parse-expr-stmt ()
9406 "Default parser in statement context, if no recognized statement found."
9407 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9408 (progn
9409 (js2-unget-token)
9410 (js2-parse-expr)) t))
9411
9412 (defun js2-parse-variables (decl-type pos)
9413 "Parse a comma-separated list of variable declarations.
9414 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9415
9416 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9417 For 'var' or 'const', the keyword should be the token last scanned.
9418
9419 POS is the position where the node should start. It's sometimes the
9420 var/const/let keyword, and other times the beginning of the first token
9421 in the first variable declaration.
9422
9423 Returns the parsed `js2-var-decl-node' expression node."
9424 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9425 :pos pos))
9426 destructuring kid-pos tt init name end nbeg nend vi
9427 (continue t))
9428 ;; Example:
9429 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9430 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9431 ;; var {a, b} = baz;
9432 (while continue
9433 (setq destructuring nil
9434 name nil
9435 tt (js2-get-token)
9436 kid-pos (js2-current-token-beg)
9437 end (js2-current-token-end)
9438 init nil)
9439 (if (or (= tt js2-LB) (= tt js2-LC))
9440 ;; Destructuring assignment, e.g., var [a, b] = ...
9441 (setq destructuring (js2-parse-destruct-primary-expr)
9442 end (js2-node-end destructuring))
9443 ;; Simple variable name
9444 (js2-unget-token)
9445 (when (js2-must-match-name "msg.bad.var")
9446 (setq name (js2-create-name-node)
9447 nbeg (js2-current-token-beg)
9448 nend (js2-current-token-end)
9449 end nend)
9450 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9451 (js2-check-strict-identifier name)))
9452 (when (js2-match-token js2-ASSIGN)
9453 (setq init (js2-parse-assign-expr)
9454 end (js2-node-end init))
9455 (js2-record-imenu-functions init name))
9456 (when name
9457 (js2-set-face nbeg nend (if (js2-function-node-p init)
9458 'font-lock-function-name-face
9459 'font-lock-variable-name-face)
9460 'record))
9461 (setq vi (make-js2-var-init-node :pos kid-pos
9462 :len (- end kid-pos)
9463 :type decl-type))
9464 (if destructuring
9465 (progn
9466 (if (and (null init) (not js2-in-for-init))
9467 (js2-report-error "msg.destruct.assign.no.init"))
9468 (js2-define-destruct-symbols destructuring
9469 decl-type
9470 'font-lock-variable-name-face)
9471 (setf (js2-var-init-node-target vi) destructuring))
9472 (setf (js2-var-init-node-target vi) name))
9473 (setf (js2-var-init-node-initializer vi) init)
9474 (js2-node-add-children vi name destructuring init)
9475 (js2-block-node-push result vi)
9476 (unless (js2-match-token js2-COMMA)
9477 (setq continue nil)))
9478 (setf (js2-node-len result) (- end pos))
9479 result))
9480
9481 (defun js2-parse-let (pos &optional stmt-p)
9482 "Parse a let expression or statement.
9483 A let-expression is of the form `let (vars) expr'.
9484 A let-statement is of the form `let (vars) {statements}'.
9485 The third form of let is a variable declaration list, handled
9486 by `js2-parse-variables'."
9487 (let ((pn (make-js2-let-node :pos pos))
9488 beg vars body)
9489 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9490 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9491 (js2-push-scope pn)
9492 (unwind-protect
9493 (progn
9494 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9495 (if (js2-must-match js2-RP "msg.no.paren.let")
9496 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9497 (if (and stmt-p (js2-match-token js2-LC))
9498 ;; let statement
9499 (progn
9500 (setf beg (js2-current-token-beg) ; position stmt at LC
9501 body (js2-parse-statements))
9502 (js2-must-match js2-RC "msg.no.curly.let")
9503 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9504 (js2-node-len pn) (- (js2-current-token-end) pos)
9505 (js2-let-node-body pn) body
9506 (js2-node-type pn) js2-LET))
9507 ;; let expression
9508 (setf body (js2-parse-expr)
9509 (js2-node-len pn) (- (js2-node-end body) pos)
9510 (js2-let-node-body pn) body))
9511 (setf (js2-let-node-vars pn) vars)
9512 (js2-node-add-children pn vars body))
9513 (js2-pop-scope))
9514 pn))
9515
9516 (defun js2-define-new-symbol (decl-type name node &optional scope)
9517 (js2-scope-put-symbol (or scope js2-current-scope)
9518 name
9519 (make-js2-symbol decl-type name node)))
9520
9521 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9522 "Define a symbol in the current scope.
9523 If NODE is non-nil, it is the AST node associated with the symbol."
9524 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9525 (symbol (if defining-scope
9526 (js2-scope-get-symbol defining-scope name)))
9527 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9528 (pos (if node (js2-node-abs-pos node)))
9529 (len (if node (js2-node-len node))))
9530 (cond
9531 ((and symbol ; already defined
9532 (or (if js2-in-use-strict-directive
9533 ;; two const-bound vars in this block have same name
9534 (and (= sdt js2-CONST)
9535 (eq defining-scope js2-current-scope))
9536 (or (= sdt js2-CONST) ; old version is const
9537 (= decl-type js2-CONST))) ; new version is const
9538 ;; two let-bound vars in this block have same name
9539 (and (= sdt js2-LET)
9540 (eq defining-scope js2-current-scope))))
9541 (js2-report-error
9542 (cond
9543 ((= sdt js2-CONST) "msg.const.redecl")
9544 ((= sdt js2-LET) "msg.let.redecl")
9545 ((= sdt js2-VAR) "msg.var.redecl")
9546 ((= sdt js2-FUNCTION) "msg.function.redecl")
9547 (t "msg.parm.redecl"))
9548 name pos len))
9549 ((or (= decl-type js2-LET)
9550 ;; strict mode const is scoped to the current LexicalEnvironment
9551 (and js2-in-use-strict-directive
9552 (= decl-type js2-CONST)))
9553 (if (and (= decl-type js2-LET)
9554 (not ignore-not-in-block)
9555 (or (= (js2-node-type js2-current-scope) js2-IF)
9556 (js2-loop-node-p js2-current-scope)))
9557 (js2-report-error "msg.let.decl.not.in.block")
9558 (js2-define-new-symbol decl-type name node)))
9559 ((or (= decl-type js2-VAR)
9560 (= decl-type js2-FUNCTION)
9561 ;; sloppy mode const is scoped to the current VariableEnvironment
9562 (and (not js2-in-use-strict-directive)
9563 (= decl-type js2-CONST)))
9564 (if symbol
9565 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9566 (js2-add-strict-warning "msg.var.redecl" name)
9567 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9568 (js2-add-strict-warning "msg.var.hides.arg" name)))
9569 (js2-define-new-symbol decl-type name node
9570 js2-current-script-or-fn)))
9571 ((= decl-type js2-LP)
9572 (if symbol
9573 ;; must be duplicate parameter. Second parameter hides the
9574 ;; first, so go ahead and add the second pararameter
9575 (js2-report-warning "msg.dup.parms" name))
9576 (js2-define-new-symbol decl-type name node))
9577 (t (js2-code-bug)))))
9578
9579 (defun js2-parse-paren-expr-or-generator-comp ()
9580 (let ((px-pos (js2-current-token-beg)))
9581 (cond
9582 ((and (>= js2-language-version 200)
9583 (js2-match-token js2-FOR))
9584 (js2-parse-generator-comp px-pos))
9585 ((and (>= js2-language-version 200)
9586 (js2-match-token js2-RP))
9587 ;; Not valid expression syntax, but this is valid in an arrow
9588 ;; function with no params: () => body.
9589 (if (eq (js2-peek-token) js2-ARROW)
9590 ;; Return whatever, it will hopefully be rewinded and
9591 ;; reparsed when we reach the =>.
9592 (make-js2-keyword-node :type js2-NULL)
9593 (js2-report-error "msg.syntax")
9594 (make-js2-error-node)))
9595 (t
9596 (let* ((js2-in-for-init nil)
9597 (expr (js2-parse-expr))
9598 (pn (make-js2-paren-node :pos px-pos
9599 :expr expr)))
9600 (js2-node-add-children pn (js2-paren-node-expr pn))
9601 (js2-must-match js2-RP "msg.no.paren")
9602 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9603 pn)))))
9604
9605 (defun js2-parse-expr (&optional oneshot)
9606 (let* ((pn (js2-parse-assign-expr))
9607 (pos (js2-node-pos pn))
9608 left
9609 right
9610 op-pos)
9611 (while (and (not oneshot)
9612 (js2-match-token js2-COMMA))
9613 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9614 (if (= (js2-peek-token) js2-YIELD)
9615 (js2-report-error "msg.yield.parenthesized"))
9616 (setq right (js2-parse-assign-expr)
9617 left pn
9618 pn (make-js2-infix-node :type js2-COMMA
9619 :pos pos
9620 :len (- js2-ts-cursor pos)
9621 :op-pos op-pos
9622 :left left
9623 :right right))
9624 (js2-node-add-children pn left right))
9625 pn))
9626
9627 (defun js2-parse-assign-expr ()
9628 (let ((tt (js2-get-token))
9629 (pos (js2-current-token-beg))
9630 pn left right op-pos
9631 ts-state recorded-identifiers parsed-errors
9632 async-p)
9633 (if (= tt js2-YIELD)
9634 (js2-parse-return-or-yield tt t)
9635 ;; TODO(mooz): Bit confusing.
9636 ;; If we meet `async` token and it's not part of `async
9637 ;; function`, then this `async` is for a succeeding async arrow
9638 ;; function.
9639 ;; Since arrow function parsing doesn't rely on neither
9640 ;; `js2-parse-function-stmt' nor `js2-parse-function-expr' that
9641 ;; interpret `async` token, we trash `async` and just remember
9642 ;; we met `async` keyword to `async-p'.
9643 (when (js2-match-async-arrow-function)
9644 (setq async-p t))
9645 ;; Save the tokenizer state in case we find an arrow function
9646 ;; and have to rewind.
9647 (setq ts-state (make-js2-ts-state)
9648 recorded-identifiers js2-recorded-identifiers
9649 parsed-errors js2-parsed-errors)
9650 ;; not yield - parse assignment expression
9651 (setq pn (js2-parse-cond-expr)
9652 tt (js2-get-token))
9653 (cond
9654 ((and (<= js2-first-assign tt)
9655 (<= tt js2-last-assign))
9656 ;; tt express assignment (=, |=, ^=, ..., %=)
9657 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9658 left pn)
9659 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9660 ;; care about assignment to strict variable names.
9661 (when (js2-name-node-p left)
9662 (js2-check-strict-identifier left))
9663 (setq right (js2-parse-assign-expr)
9664 pn (make-js2-assign-node :type tt
9665 :pos pos
9666 :len (- (js2-node-end right) pos)
9667 :op-pos op-pos
9668 :left left
9669 :right right))
9670 (when js2-parse-ide-mode
9671 (js2-highlight-assign-targets pn left right)
9672 (js2-record-imenu-functions right left))
9673 ;; do this last so ide checks above can use absolute positions
9674 (js2-node-add-children pn left right))
9675 ((and (= tt js2-ARROW)
9676 (>= js2-language-version 200))
9677 (js2-ts-seek ts-state)
9678 (setq js2-recorded-identifiers recorded-identifiers
9679 js2-parsed-errors parsed-errors)
9680 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil async-p)))
9681 (t
9682 (js2-unget-token)))
9683 pn)))
9684
9685 (defun js2-parse-cond-expr ()
9686 (let ((pos (js2-current-token-beg))
9687 (pn (js2-parse-or-expr))
9688 test-expr
9689 if-true
9690 if-false
9691 q-pos
9692 c-pos)
9693 (when (js2-match-token js2-HOOK)
9694 (setq q-pos (- (js2-current-token-beg) pos)
9695 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9696 (js2-must-match js2-COLON "msg.no.colon.cond")
9697 (setq c-pos (- (js2-current-token-beg) pos)
9698 if-false (js2-parse-assign-expr)
9699 test-expr pn
9700 pn (make-js2-cond-node :pos pos
9701 :len (- (js2-node-end if-false) pos)
9702 :test-expr test-expr
9703 :true-expr if-true
9704 :false-expr if-false
9705 :q-pos q-pos
9706 :c-pos c-pos))
9707 (js2-node-add-children pn test-expr if-true if-false))
9708 pn))
9709
9710 (defun js2-make-binary (type left parser &optional no-get)
9711 "Helper for constructing a binary-operator AST node.
9712 LEFT is the left-side-expression, already parsed, and the
9713 binary operator should have just been matched.
9714 PARSER is a function to call to parse the right operand,
9715 or a `js2-node' struct if it has already been parsed.
9716 FIXME: The latter option is unused?"
9717 (let* ((pos (js2-node-pos left))
9718 (op-pos (- (js2-current-token-beg) pos))
9719 (right (if (js2-node-p parser)
9720 parser
9721 (unless no-get (js2-get-token))
9722 (funcall parser)))
9723 (pn (make-js2-infix-node :type type
9724 :pos pos
9725 :len (- (js2-node-end right) pos)
9726 :op-pos op-pos
9727 :left left
9728 :right right)))
9729 (js2-node-add-children pn left right)
9730 pn))
9731
9732 (defun js2-parse-or-expr ()
9733 (let ((pn (js2-parse-and-expr)))
9734 (when (js2-match-token js2-OR)
9735 (setq pn (js2-make-binary js2-OR
9736 pn
9737 'js2-parse-or-expr)))
9738 pn))
9739
9740 (defun js2-parse-and-expr ()
9741 (let ((pn (js2-parse-bit-or-expr)))
9742 (when (js2-match-token js2-AND)
9743 (setq pn (js2-make-binary js2-AND
9744 pn
9745 'js2-parse-and-expr)))
9746 pn))
9747
9748 (defun js2-parse-bit-or-expr ()
9749 (let ((pn (js2-parse-bit-xor-expr)))
9750 (while (js2-match-token js2-BITOR)
9751 (setq pn (js2-make-binary js2-BITOR
9752 pn
9753 'js2-parse-bit-xor-expr)))
9754 pn))
9755
9756 (defun js2-parse-bit-xor-expr ()
9757 (let ((pn (js2-parse-bit-and-expr)))
9758 (while (js2-match-token js2-BITXOR)
9759 (setq pn (js2-make-binary js2-BITXOR
9760 pn
9761 'js2-parse-bit-and-expr)))
9762 pn))
9763
9764 (defun js2-parse-bit-and-expr ()
9765 (let ((pn (js2-parse-eq-expr)))
9766 (while (js2-match-token js2-BITAND)
9767 (setq pn (js2-make-binary js2-BITAND
9768 pn
9769 'js2-parse-eq-expr)))
9770 pn))
9771
9772 (defconst js2-parse-eq-ops
9773 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9774
9775 (defun js2-parse-eq-expr ()
9776 (let ((pn (js2-parse-rel-expr))
9777 tt)
9778 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9779 (setq pn (js2-make-binary tt
9780 pn
9781 'js2-parse-rel-expr)))
9782 (js2-unget-token)
9783 pn))
9784
9785 (defconst js2-parse-rel-ops
9786 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9787
9788 (defun js2-parse-rel-expr ()
9789 (let ((pn (js2-parse-shift-expr))
9790 (continue t)
9791 tt)
9792 (while continue
9793 (setq tt (js2-get-token))
9794 (cond
9795 ((and js2-in-for-init (= tt js2-IN))
9796 (js2-unget-token)
9797 (setq continue nil))
9798 ((memq tt js2-parse-rel-ops)
9799 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9800 (t
9801 (js2-unget-token)
9802 (setq continue nil))))
9803 pn))
9804
9805 (defconst js2-parse-shift-ops
9806 (list js2-LSH js2-URSH js2-RSH))
9807
9808 (defun js2-parse-shift-expr ()
9809 (let ((pn (js2-parse-add-expr))
9810 tt
9811 (continue t))
9812 (while continue
9813 (setq tt (js2-get-token))
9814 (if (memq tt js2-parse-shift-ops)
9815 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9816 (js2-unget-token)
9817 (setq continue nil)))
9818 pn))
9819
9820 (defun js2-parse-add-expr ()
9821 (let ((pn (js2-parse-mul-expr))
9822 tt
9823 (continue t))
9824 (while continue
9825 (setq tt (js2-get-token))
9826 (if (or (= tt js2-ADD) (= tt js2-SUB))
9827 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9828 (js2-unget-token)
9829 (setq continue nil)))
9830 pn))
9831
9832 (defconst js2-parse-mul-ops
9833 (list js2-MUL js2-DIV js2-MOD))
9834
9835 (defun js2-parse-mul-expr ()
9836 (let ((pn (js2-parse-unary-expr))
9837 tt
9838 (continue t))
9839 (while continue
9840 (setq tt (js2-get-token))
9841 (if (memq tt js2-parse-mul-ops)
9842 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9843 (js2-unget-token)
9844 (setq continue nil)))
9845 pn))
9846
9847 (defun js2-make-unary (type parser &rest args)
9848 "Make a unary node of type TYPE.
9849 PARSER is either a node (for postfix operators) or a function to call
9850 to parse the operand (for prefix operators)."
9851 (let* ((pos (js2-current-token-beg))
9852 (postfix (js2-node-p parser))
9853 (expr (if postfix
9854 parser
9855 (apply parser args)))
9856 end
9857 pn)
9858 (if postfix ; e.g. i++
9859 (setq pos (js2-node-pos expr)
9860 end (js2-current-token-end))
9861 (setq end (js2-node-end expr)))
9862 (setq pn (make-js2-unary-node :type type
9863 :pos pos
9864 :len (- end pos)
9865 :operand expr))
9866 (js2-node-add-children pn expr)
9867 pn))
9868
9869 (defun js2-make-await ()
9870 "Make an await node."
9871 (let* ((pos (js2-current-token-beg))
9872 (expr (js2-parse-unary-expr))
9873 (end (js2-node-end expr))
9874 pn)
9875 (setq pn (make-js2-await-node :pos pos
9876 :len (- end pos)
9877 :operand expr))
9878 (js2-node-add-children pn expr)
9879 pn))
9880
9881 (defconst js2-incrementable-node-types
9882 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9883 "Node types that can be the operand of a ++ or -- operator.")
9884
9885 (defun js2-check-bad-inc-dec (tt beg end unary)
9886 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9887 js2-incrementable-node-types)
9888 (js2-report-error (if (= tt js2-INC)
9889 "msg.bad.incr"
9890 "msg.bad.decr")
9891 nil beg (- end beg))))
9892
9893 (defun js2-parse-unary-expr ()
9894 (let ((tt (js2-current-token-type))
9895 pn expr beg end)
9896 (cond
9897 ((or (= tt js2-VOID)
9898 (= tt js2-NOT)
9899 (= tt js2-BITNOT)
9900 (= tt js2-TYPEOF))
9901 (js2-get-token)
9902 (js2-make-unary tt 'js2-parse-unary-expr))
9903 ((= tt js2-ADD)
9904 (js2-get-token)
9905 ;; Convert to special POS token in decompiler and parse tree
9906 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9907 ((= tt js2-SUB)
9908 (js2-get-token)
9909 ;; Convert to special NEG token in decompiler and parse tree
9910 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9911 ((or (= tt js2-INC)
9912 (= tt js2-DEC))
9913 (js2-get-token)
9914 (prog1
9915 (setq beg (js2-current-token-beg)
9916 end (js2-current-token-end)
9917 expr (js2-make-unary tt 'js2-parse-member-expr t))
9918 (js2-check-bad-inc-dec tt beg end expr)))
9919 ((= tt js2-DELPROP)
9920 (js2-get-token)
9921 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9922 ((js2-match-await)
9923 (js2-make-unary js2-AWAIT 'js2-parse-unary-expr))
9924 ((= tt js2-ERROR)
9925 (js2-get-token)
9926 (make-js2-error-node)) ; try to continue
9927 ((and (= tt js2-LT)
9928 js2-compiler-xml-available)
9929 ;; XML stream encountered in expression.
9930 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9931 (t
9932 (setq pn (js2-parse-member-expr t)
9933 ;; Don't look across a newline boundary for a postfix incop.
9934 tt (js2-peek-token-or-eol))
9935 (when (or (= tt js2-INC) (= tt js2-DEC))
9936 (js2-get-token)
9937 (setf expr pn
9938 pn (js2-make-unary tt expr))
9939 (js2-node-set-prop pn 'postfix t)
9940 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9941 pn))))
9942
9943 (defun js2-parse-xml-initializer ()
9944 "Parse an E4X XML initializer.
9945 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9946 Then I'll postprocess the result, depending on whether we're in IDE
9947 mode or codegen mode, and generate the appropriate rewritten AST.
9948 IDE mode uses a rich AST that models the XML structure. Codegen mode
9949 just concatenates everything and makes a new XML or XMLList out of it."
9950 (let ((tt (js2-get-first-xml-token))
9951 pn-xml pn expr kids expr-pos
9952 (continue t)
9953 (first-token t))
9954 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9955 (js2-report-error "msg.syntax"))
9956 (setq pn-xml (make-js2-xml-node))
9957 (while continue
9958 (if first-token
9959 (setq first-token nil)
9960 (setq tt (js2-get-next-xml-token)))
9961 (cond
9962 ;; js2-XML means we found a {expr} in the XML stream.
9963 ;; The token string is the XML up to the left-curly.
9964 ((= tt js2-XML)
9965 (push (make-js2-string-node :pos (js2-current-token-beg)
9966 :len (- js2-ts-cursor (js2-current-token-beg)))
9967 kids)
9968 (js2-must-match js2-LC "msg.syntax")
9969 (setq expr-pos js2-ts-cursor
9970 expr (if (eq (js2-peek-token) js2-RC)
9971 (make-js2-empty-expr-node :pos expr-pos)
9972 (js2-parse-expr)))
9973 (js2-must-match js2-RC "msg.syntax")
9974 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9975 :len (js2-node-len expr)
9976 :expr expr))
9977 (js2-node-add-children pn expr)
9978 (push pn kids))
9979 ;; a js2-XMLEND token means we hit the final close-tag.
9980 ((= tt js2-XMLEND)
9981 (push (make-js2-string-node :pos (js2-current-token-beg)
9982 :len (- js2-ts-cursor (js2-current-token-beg)))
9983 kids)
9984 (dolist (kid (nreverse kids))
9985 (js2-block-node-push pn-xml kid))
9986 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9987 (js2-node-pos pn-xml))
9988 continue nil))
9989 (t
9990 (js2-report-error "msg.syntax")
9991 (setq continue nil))))
9992 pn-xml))
9993
9994
9995 (defun js2-parse-argument-list ()
9996 "Parse an argument list and return it as a Lisp list of nodes.
9997 Returns the list in reverse order. Consumes the right-paren token."
9998 (let (result)
9999 (unless (js2-match-token js2-RP)
10000 (cl-loop do
10001 (let ((tt (js2-get-token)))
10002 (if (= tt js2-YIELD)
10003 (js2-report-error "msg.yield.parenthesized"))
10004 (if (and (= tt js2-TRIPLEDOT)
10005 (>= js2-language-version 200))
10006 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
10007 (js2-unget-token)
10008 (push (js2-parse-assign-expr) result)))
10009 while
10010 (js2-match-token js2-COMMA))
10011 (js2-must-match js2-RP "msg.no.paren.arg")
10012 result)))
10013
10014 (defun js2-parse-member-expr (&optional allow-call-syntax)
10015 (let ((tt (js2-current-token-type))
10016 pn pos target args beg end init)
10017 (if (/= tt js2-NEW)
10018 (setq pn (js2-parse-primary-expr))
10019 ;; parse a 'new' expression
10020 (js2-get-token)
10021 (setq pos (js2-current-token-beg)
10022 beg pos
10023 target (js2-parse-member-expr)
10024 end (js2-node-end target)
10025 pn (make-js2-new-node :pos pos
10026 :target target
10027 :len (- end pos)))
10028 (js2-highlight-function-call (js2-current-token))
10029 (js2-node-add-children pn target)
10030 (when (js2-match-token js2-LP)
10031 ;; Add the arguments to pn, if any are supplied.
10032 (setf beg pos ; start of "new" keyword
10033 pos (js2-current-token-beg)
10034 args (nreverse (js2-parse-argument-list))
10035 (js2-new-node-args pn) args
10036 end (js2-current-token-end)
10037 (js2-new-node-lp pn) (- pos beg)
10038 (js2-new-node-rp pn) (- end 1 beg))
10039 (apply #'js2-node-add-children pn args))
10040 (when (and js2-allow-rhino-new-expr-initializer
10041 (js2-match-token js2-LC))
10042 (setf init (js2-parse-object-literal)
10043 end (js2-node-end init)
10044 (js2-new-node-initializer pn) init)
10045 (js2-node-add-children pn init))
10046 (setf (js2-node-len pn) (- end beg))) ; end outer if
10047 (js2-parse-member-expr-tail allow-call-syntax pn)))
10048
10049 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10050 "Parse a chain of property/array accesses or function calls.
10051 Includes parsing for E4X operators like `..' and `.@'.
10052 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10053 Returns an expression tree that includes PN, the parent node."
10054 (let (tt
10055 (continue t))
10056 (while continue
10057 (setq tt (js2-get-token))
10058 (cond
10059 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10060 (setq pn (js2-parse-property-access tt pn)))
10061 ((= tt js2-DOTQUERY)
10062 (setq pn (js2-parse-dot-query pn)))
10063 ((= tt js2-LB)
10064 (setq pn (js2-parse-element-get pn)))
10065 ((= tt js2-LP)
10066 (js2-unget-token)
10067 (if allow-call-syntax
10068 (setq pn (js2-parse-function-call pn))
10069 (setq continue nil)))
10070 ((= tt js2-TEMPLATE_HEAD)
10071 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10072 ((= tt js2-NO_SUBS_TEMPLATE)
10073 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10074 (t
10075 (js2-unget-token)
10076 (setq continue nil)))
10077 (if (>= js2-highlight-level 2)
10078 (js2-parse-highlight-member-expr-node pn)))
10079 pn))
10080
10081 (defun js2-parse-tagged-template (tag-node tpl-node)
10082 "Parse tagged template expression."
10083 (let* ((beg (js2-node-pos tag-node))
10084 (pn (make-js2-tagged-template-node :beg beg
10085 :len (- (js2-current-token-end) beg)
10086 :tag tag-node
10087 :template tpl-node)))
10088 (js2-node-add-children pn tag-node tpl-node)
10089 pn))
10090
10091 (defun js2-parse-dot-query (pn)
10092 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10093 Last token parsed must be `js2-DOTQUERY'."
10094 (let ((pos (js2-node-pos pn))
10095 op-pos expr end)
10096 (js2-must-have-xml)
10097 (js2-set-requires-activation)
10098 (setq op-pos (js2-current-token-beg)
10099 expr (js2-parse-expr)
10100 end (js2-node-end expr)
10101 pn (make-js2-xml-dot-query-node :left pn
10102 :pos pos
10103 :op-pos op-pos
10104 :right expr))
10105 (js2-node-add-children pn
10106 (js2-xml-dot-query-node-left pn)
10107 (js2-xml-dot-query-node-right pn))
10108 (if (js2-must-match js2-RP "msg.no.paren")
10109 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10110 end (js2-current-token-end)))
10111 (setf (js2-node-len pn) (- end pos))
10112 pn))
10113
10114 (defun js2-parse-element-get (pn)
10115 "Parse an element-get expression, e.g. foo[bar].
10116 Last token parsed must be `js2-RB'."
10117 (let ((lb (js2-current-token-beg))
10118 (pos (js2-node-pos pn))
10119 rb expr)
10120 (setq expr (js2-parse-expr))
10121 (if (js2-must-match js2-RB "msg.no.bracket.index")
10122 (setq rb (js2-current-token-beg)))
10123 (setq pn (make-js2-elem-get-node :target pn
10124 :pos pos
10125 :element expr
10126 :lb (js2-relpos lb pos)
10127 :rb (js2-relpos rb pos)
10128 :len (- (js2-current-token-end) pos)))
10129 (js2-node-add-children pn
10130 (js2-elem-get-node-target pn)
10131 (js2-elem-get-node-element pn))
10132 pn))
10133
10134 (defun js2-highlight-function-call (token)
10135 (when (eq (js2-token-type token) js2-NAME)
10136 (js2-record-face 'js2-function-call token)))
10137
10138 (defun js2-parse-function-call (pn)
10139 (js2-highlight-function-call (js2-current-token))
10140 (js2-get-token)
10141 (let (args
10142 (pos (js2-node-pos pn)))
10143 (setq pn (make-js2-call-node :pos pos
10144 :target pn
10145 :lp (- (js2-current-token-beg) pos)))
10146 (js2-node-add-children pn (js2-call-node-target pn))
10147 ;; Add the arguments to pn, if any are supplied.
10148 (setf args (nreverse (js2-parse-argument-list))
10149 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10150 (js2-call-node-args pn) args)
10151 (apply #'js2-node-add-children pn args)
10152 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10153 pn))
10154
10155 (defun js2-parse-property-access (tt pn)
10156 "Parse a property access, XML descendants access, or XML attr access."
10157 (let ((member-type-flags 0)
10158 (dot-pos (js2-current-token-beg))
10159 (dot-len (if (= tt js2-DOTDOT) 2 1))
10160 name
10161 ref ; right side of . or .. operator
10162 result)
10163 (when (= tt js2-DOTDOT)
10164 (js2-must-have-xml)
10165 (setq member-type-flags js2-descendants-flag))
10166 (if (not js2-compiler-xml-available)
10167 (progn
10168 (js2-must-match-prop-name "msg.no.name.after.dot")
10169 (setq name (js2-create-name-node t js2-GETPROP)
10170 result (make-js2-prop-get-node :left pn
10171 :pos (js2-current-token-beg)
10172 :right name
10173 :len (js2-current-token-len)))
10174 (js2-node-add-children result pn name)
10175 result)
10176 ;; otherwise look for XML operators
10177 (setf result (if (= tt js2-DOT)
10178 (make-js2-prop-get-node)
10179 (make-js2-infix-node :type js2-DOTDOT))
10180 (js2-node-pos result) (js2-node-pos pn)
10181 (js2-infix-node-op-pos result) dot-pos
10182 (js2-infix-node-left result) pn ; do this after setting position
10183 tt (js2-get-prop-name-token))
10184 (cond
10185 ;; handles: name, ns::name, ns::*, ns::[expr]
10186 ((= tt js2-NAME)
10187 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10188 ;; handles: *, *::name, *::*, *::[expr]
10189 ((= tt js2-MUL)
10190 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10191 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10192 ((= tt js2-XMLATTR)
10193 (setq result (js2-parse-attribute-access)))
10194 (t
10195 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10196 (if ref
10197 (setf (js2-node-len result) (- (js2-node-end ref)
10198 (js2-node-pos result))
10199 (js2-infix-node-right result) ref))
10200 (if (js2-infix-node-p result)
10201 (js2-node-add-children result
10202 (js2-infix-node-left result)
10203 (js2-infix-node-right result)))
10204 result)))
10205
10206 (defun js2-parse-attribute-access ()
10207 "Parse an E4X XML attribute expression.
10208 This includes expressions of the forms:
10209
10210 @attr @ns::attr @ns::*
10211 @* @*::attr @*::*
10212 @[expr] @*::[expr] @ns::[expr]
10213
10214 Called if we peeked an '@' token."
10215 (let ((tt (js2-get-prop-name-token))
10216 (at-pos (js2-current-token-beg)))
10217 (cond
10218 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10219 ((= tt js2-NAME)
10220 (js2-parse-property-name at-pos nil 0))
10221 ;; handles: @*, @*::name, @*::*, @*::[expr]
10222 ((= tt js2-MUL)
10223 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10224 ;; handles @[expr]
10225 ((= tt js2-LB)
10226 (js2-parse-xml-elem-ref at-pos))
10227 (t
10228 (js2-report-error "msg.no.name.after.xmlAttr")
10229 ;; Avoid cascaded errors that happen if we make an error node here.
10230 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10231
10232 (defun js2-parse-property-name (at-pos s member-type-flags)
10233 "Check if :: follows name in which case it becomes qualified name.
10234
10235 AT-POS is a natural number if we just read an '@' token, else nil.
10236 S is the name or string that was matched: an identifier, 'throw' or '*'.
10237 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10238
10239 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10240 operator, or the name is followed by ::. For a plain name, returns a
10241 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10242 (let ((pos (or at-pos (js2-current-token-beg)))
10243 colon-pos
10244 (name (js2-create-name-node t (js2-current-token-type) s))
10245 ns tt pn)
10246 (catch 'return
10247 (when (js2-match-token js2-COLONCOLON)
10248 (setq ns name
10249 colon-pos (js2-current-token-beg)
10250 tt (js2-get-prop-name-token))
10251 (cond
10252 ;; handles name::name
10253 ((= tt js2-NAME)
10254 (setq name (js2-create-name-node)))
10255 ;; handles name::*
10256 ((= tt js2-MUL)
10257 (setq name (js2-create-name-node nil nil "*")))
10258 ;; handles name::[expr]
10259 ((= tt js2-LB)
10260 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10261 (t
10262 (js2-report-error "msg.no.name.after.coloncolon"))))
10263 (if (and (null ns) (zerop member-type-flags))
10264 name
10265 (prog1
10266 (setq pn
10267 (make-js2-xml-prop-ref-node :pos pos
10268 :len (- (js2-node-end name) pos)
10269 :at-pos at-pos
10270 :colon-pos colon-pos
10271 :propname name))
10272 (js2-node-add-children pn name))))))
10273
10274 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10275 "Parse the [expr] portion of an xml element reference.
10276 For instance, @[expr], @*::[expr], or ns::[expr]."
10277 (let* ((lb (js2-current-token-beg))
10278 (pos (or at-pos lb))
10279 rb
10280 (expr (js2-parse-expr))
10281 (end (js2-node-end expr))
10282 pn)
10283 (if (js2-must-match js2-RB "msg.no.bracket.index")
10284 (setq rb (js2-current-token-beg)
10285 end (js2-current-token-end)))
10286 (prog1
10287 (setq pn
10288 (make-js2-xml-elem-ref-node :pos pos
10289 :len (- end pos)
10290 :namespace namespace
10291 :colon-pos colon-pos
10292 :at-pos at-pos
10293 :expr expr
10294 :lb (js2-relpos lb pos)
10295 :rb (js2-relpos rb pos)))
10296 (js2-node-add-children pn namespace expr))))
10297
10298 (defun js2-parse-destruct-primary-expr ()
10299 (let ((js2-is-in-destructuring t))
10300 (js2-parse-primary-expr)))
10301
10302 (defun js2-parse-primary-expr ()
10303 "Parse a literal (leaf) expression of some sort.
10304 Includes complex literals such as functions, object-literals,
10305 array-literals, array comprehensions and regular expressions."
10306 (let (tt node)
10307 (setq tt (js2-current-token-type))
10308 (cond
10309 ((= tt js2-CLASS)
10310 (js2-parse-class-expr))
10311 ((= tt js2-FUNCTION)
10312 (js2-parse-function-expr))
10313 ((js2-match-async-function)
10314 (js2-parse-function-expr t))
10315 ((= tt js2-LB)
10316 (js2-parse-array-comp-or-literal))
10317 ((= tt js2-LC)
10318 (js2-parse-object-literal))
10319 ((= tt js2-LET)
10320 (js2-parse-let (js2-current-token-beg)))
10321 ((= tt js2-LP)
10322 (js2-parse-paren-expr-or-generator-comp))
10323 ((= tt js2-XMLATTR)
10324 (js2-must-have-xml)
10325 (js2-parse-attribute-access))
10326 ((= tt js2-NAME)
10327 (js2-parse-name tt))
10328 ((= tt js2-NUMBER)
10329 (setq node (make-js2-number-node))
10330 (when (and js2-in-use-strict-directive
10331 (= (js2-number-node-num-base node) 8))
10332 (js2-report-error "msg.no.octal.strict"))
10333 node)
10334 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10335 (make-js2-string-node :type tt))
10336 ((= tt js2-TEMPLATE_HEAD)
10337 (js2-parse-template-literal))
10338 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10339 ;; Got / or /= which in this context means a regexp literal
10340 (let ((px-pos (js2-current-token-beg))
10341 (flags (js2-read-regexp tt))
10342 (end (js2-current-token-end)))
10343 (prog1
10344 (make-js2-regexp-node :pos px-pos
10345 :len (- end px-pos)
10346 :value (js2-current-token-string)
10347 :flags flags)
10348 (js2-set-face px-pos end 'font-lock-string-face 'record)
10349 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10350 ((or (= tt js2-NULL)
10351 (= tt js2-THIS)
10352 (= tt js2-SUPER)
10353 (= tt js2-FALSE)
10354 (= tt js2-TRUE))
10355 (make-js2-keyword-node :type tt))
10356 ((= tt js2-TRIPLEDOT)
10357 ;; Likewise, only valid in an arrow function with a rest param.
10358 (if (and (js2-match-token js2-NAME)
10359 (js2-match-token js2-RP)
10360 (eq (js2-peek-token) js2-ARROW))
10361 (progn
10362 (js2-unget-token) ; Put back the right paren.
10363 ;; See the previous case.
10364 (make-js2-keyword-node :type js2-NULL))
10365 (js2-report-error "msg.syntax")
10366 (make-js2-error-node)))
10367 ((= tt js2-RESERVED)
10368 (js2-report-error "msg.reserved.id")
10369 (make-js2-name-node))
10370 ((= tt js2-ERROR)
10371 ;; the scanner or one of its subroutines reported the error.
10372 (make-js2-error-node))
10373 ((= tt js2-EOF)
10374 (let* ((px-pos (point-at-bol))
10375 (len (- js2-ts-cursor px-pos)))
10376 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10377 (make-js2-error-node :pos (1- js2-ts-cursor)))
10378 (t
10379 (js2-report-error "msg.syntax")
10380 (make-js2-error-node)))))
10381
10382 (defun js2-parse-template-literal ()
10383 (let ((beg (js2-current-token-beg))
10384 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10385 (tt js2-TEMPLATE_HEAD))
10386 (while (eq tt js2-TEMPLATE_HEAD)
10387 (push (js2-parse-expr) kids)
10388 (js2-must-match js2-RC "msg.syntax")
10389 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10390 (push (make-js2-string-node :type tt) kids))
10391 (setq kids (nreverse kids))
10392 (let ((tpl (make-js2-template-node :beg beg
10393 :len (- (js2-current-token-end) beg)
10394 :kids kids)))
10395 (apply #'js2-node-add-children tpl kids)
10396 tpl)))
10397
10398 (defun js2-parse-name (_tt)
10399 (let ((name (js2-current-token-string))
10400 node)
10401 (setq node (if js2-compiler-xml-available
10402 (js2-parse-property-name nil name 0)
10403 (js2-create-name-node 'check-activation nil name)))
10404 (if js2-highlight-external-variables
10405 (js2-record-name-node node))
10406 node))
10407
10408 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10409 (js2-add-strict-warning
10410 msg nil
10411 ;; back up from comma to beginning of line or array/objlit
10412 (max (if elems
10413 (js2-node-pos (car elems))
10414 pos)
10415 (save-excursion
10416 (goto-char comma-pos)
10417 (back-to-indentation)
10418 (point)))
10419 comma-pos))
10420
10421 (defun js2-parse-array-comp-or-literal ()
10422 (let ((pos (js2-current-token-beg)))
10423 (if (and (>= js2-language-version 200)
10424 (js2-match-token js2-FOR))
10425 (js2-parse-array-comp pos)
10426 (js2-parse-array-literal pos))))
10427
10428 (defun js2-parse-array-literal (pos)
10429 (let ((after-lb-or-comma t)
10430 after-comma tt elems pn
10431 (continue t))
10432 (unless js2-is-in-destructuring
10433 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10434 (while continue
10435 (setq tt (js2-get-token))
10436 (cond
10437 ;; comma
10438 ((= tt js2-COMMA)
10439 (setq after-comma (js2-current-token-end))
10440 (if (not after-lb-or-comma)
10441 (setq after-lb-or-comma t)
10442 (push nil elems)))
10443 ;; end of array
10444 ((or (= tt js2-RB)
10445 (= tt js2-EOF)) ; prevent infinite loop
10446 (if (= tt js2-EOF)
10447 (js2-report-error "msg.no.bracket.arg" nil pos))
10448 (when (and after-comma (< js2-language-version 170))
10449 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10450 pos (remove nil elems) after-comma))
10451 (setq continue nil
10452 pn (make-js2-array-node :pos pos
10453 :len (- js2-ts-cursor pos)
10454 :elems (nreverse elems)))
10455 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10456 ;; destructuring binding
10457 (js2-is-in-destructuring
10458 (push (cond
10459 ((and (= tt js2-NAME)
10460 (= js2-ASSIGN (js2-peek-token)))
10461 ;; a=defaultValue
10462 (js2-parse-initialized-binding (js2-parse-name js2-NAME)))
10463 ((or (= tt js2-LC)
10464 (= tt js2-LB)
10465 (= tt js2-NAME))
10466 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10467 (js2-parse-destruct-primary-expr))
10468 ;; invalid pattern
10469 (t
10470 (js2-report-error "msg.bad.var")
10471 (make-js2-error-node)))
10472 elems)
10473 (setq after-lb-or-comma nil
10474 after-comma nil))
10475 ;; array comp
10476 ((and (>= js2-language-version 170)
10477 (= tt js2-FOR) ; check for array comprehension
10478 (not after-lb-or-comma) ; "for" can't follow a comma
10479 elems ; must have at least 1 element
10480 (not (cdr elems))) ; but no 2nd element
10481 (js2-unget-token)
10482 (setf continue nil
10483 pn (js2-parse-legacy-array-comp (car elems) pos)))
10484 ;; another element
10485 (t
10486 (unless after-lb-or-comma
10487 (js2-report-error "msg.no.bracket.arg"))
10488 (if (and (= tt js2-TRIPLEDOT)
10489 (>= js2-language-version 200))
10490 ;; spread operator
10491 (push (js2-make-unary tt 'js2-parse-assign-expr)
10492 elems)
10493 (js2-unget-token)
10494 (push (js2-parse-assign-expr) elems))
10495 (setq after-lb-or-comma nil
10496 after-comma nil))))
10497 (unless js2-is-in-destructuring
10498 (js2-pop-scope))
10499 pn))
10500
10501 (defun js2-parse-legacy-array-comp (expr pos)
10502 "Parse a legacy array comprehension (JavaScript 1.7).
10503 EXPR is the first expression after the opening left-bracket.
10504 POS is the beginning of the LB token preceding EXPR.
10505 We should have just parsed the 'for' keyword before calling this function."
10506 (let ((current-scope js2-current-scope)
10507 loops first filter result)
10508 (unwind-protect
10509 (progn
10510 (while (js2-match-token js2-FOR)
10511 (let ((loop (make-js2-comp-loop-node)))
10512 (js2-push-scope loop)
10513 (push loop loops)
10514 (js2-parse-comp-loop loop)))
10515 ;; First loop takes expr scope's parent.
10516 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10517 (js2-scope-parent-scope current-scope))
10518 ;; Set expr scope's parent to the last loop.
10519 (setf (js2-scope-parent-scope current-scope) (car loops))
10520 (if (/= (js2-get-token) js2-IF)
10521 (js2-unget-token)
10522 (setq filter (js2-parse-condition))))
10523 (dotimes (_ (1- (length loops)))
10524 (js2-pop-scope)))
10525 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10526 (setq result (make-js2-comp-node :pos pos
10527 :len (- js2-ts-cursor pos)
10528 :result expr
10529 :loops (nreverse loops)
10530 :filters (and filter (list (car filter)))
10531 :form 'LEGACY_ARRAY))
10532 ;; Set comp loop's parent to the last loop.
10533 ;; TODO: Get rid of the bogus expr scope.
10534 (setf (js2-scope-parent-scope result) first)
10535 (apply #'js2-node-add-children result expr (car filter)
10536 (js2-comp-node-loops result))
10537 result))
10538
10539 (defun js2-parse-array-comp (pos)
10540 "Parse an ES6 array comprehension.
10541 POS is the beginning of the LB token.
10542 We should have just parsed the 'for' keyword before calling this function."
10543 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10544 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10545 pn))
10546
10547 (defun js2-parse-generator-comp (pos)
10548 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10549 (js2-current-script-or-fn
10550 (make-js2-function-node :generator-type 'COMPREHENSION))
10551 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10552 (js2-must-match js2-RP "msg.no.paren" pos)
10553 pn))
10554
10555 (defun js2-parse-comprehension (pos form)
10556 (let (loops filters expr result last)
10557 (unwind-protect
10558 (progn
10559 (js2-unget-token)
10560 (while (js2-match-token js2-FOR)
10561 (let ((loop (make-js2-comp-loop-node)))
10562 (js2-push-scope loop)
10563 (push loop loops)
10564 (js2-parse-comp-loop loop)))
10565 (while (js2-match-token js2-IF)
10566 (push (car (js2-parse-condition)) filters))
10567 (setq expr (js2-parse-assign-expr))
10568 (setq last (car loops)))
10569 (dolist (_ loops)
10570 (js2-pop-scope)))
10571 (setq result (make-js2-comp-node :pos pos
10572 :len (- js2-ts-cursor pos)
10573 :result expr
10574 :loops (nreverse loops)
10575 :filters (nreverse filters)
10576 :form form))
10577 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10578 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10579 (setf (js2-scope-parent-scope result) last)
10580 result))
10581
10582 (defun js2-parse-comp-loop (pn &optional only-of-p)
10583 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10584 The current token should be the initial FOR.
10585 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10586 (let ((pos (js2-comp-loop-node-pos pn))
10587 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10588 (when (and (not only-of-p) (js2-match-token js2-NAME))
10589 (if (string= (js2-current-token-string) "each")
10590 (progn
10591 (setq foreach-p t
10592 each-pos (- (js2-current-token-beg) pos)) ; relative
10593 (js2-record-face 'font-lock-keyword-face))
10594 (js2-report-error "msg.no.paren.for")))
10595 (if (js2-must-match js2-LP "msg.no.paren.for")
10596 (setq lp (- (js2-current-token-beg) pos)))
10597 (setq tt (js2-peek-token))
10598 (cond
10599 ((or (= tt js2-LB)
10600 (= tt js2-LC))
10601 (js2-get-token)
10602 (setq iter (js2-parse-destruct-primary-expr))
10603 (js2-define-destruct-symbols iter js2-LET
10604 'font-lock-variable-name-face t))
10605 ((js2-match-token js2-NAME)
10606 (setq iter (js2-create-name-node)))
10607 (t
10608 (js2-report-error "msg.bad.var")))
10609 ;; Define as a let since we want the scope of the variable to
10610 ;; be restricted to the array comprehension
10611 (if (js2-name-node-p iter)
10612 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10613 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10614 (and (>= js2-language-version 200)
10615 (js2-match-contextual-kwd "of")
10616 (setq forof-p t)))
10617 (setq in-pos (- (js2-current-token-beg) pos))
10618 (js2-report-error "msg.in.after.for.name"))
10619 (setq obj (js2-parse-expr))
10620 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10621 (setq rp (- (js2-current-token-beg) pos)))
10622 (setf (js2-node-pos pn) pos
10623 (js2-node-len pn) (- js2-ts-cursor pos)
10624 (js2-comp-loop-node-iterator pn) iter
10625 (js2-comp-loop-node-object pn) obj
10626 (js2-comp-loop-node-in-pos pn) in-pos
10627 (js2-comp-loop-node-each-pos pn) each-pos
10628 (js2-comp-loop-node-foreach-p pn) foreach-p
10629 (js2-comp-loop-node-forof-p pn) forof-p
10630 (js2-comp-loop-node-lp pn) lp
10631 (js2-comp-loop-node-rp pn) rp)
10632 (js2-node-add-children pn iter obj)
10633 pn))
10634
10635 (defun js2-parse-class-stmt ()
10636 (let ((pos (js2-current-token-beg))
10637 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10638 (name (js2-create-name-node t)))
10639 (js2-set-face (js2-node-pos name) (js2-node-end name)
10640 'font-lock-function-name-face 'record)
10641 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10642 (js2-define-symbol js2-FUNCTION
10643 (js2-name-node-name name)
10644 node)
10645 node)))
10646
10647 (defun js2-parse-class-expr ()
10648 (let ((pos (js2-current-token-beg))
10649 name)
10650 (when (js2-match-token js2-NAME)
10651 (setq name (js2-create-name-node t)))
10652 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10653
10654 (defun js2-parse-class (pos form name)
10655 ;; class X [extends ...] {
10656 (let (pn elems extends)
10657 (if (js2-match-token js2-EXTENDS)
10658 (if (= (js2-peek-token) js2-LC)
10659 (js2-report-error "msg.missing.extends")
10660 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10661 (setq extends (js2-parse-assign-expr))
10662 (if (not extends)
10663 (js2-report-error "msg.bad.extends"))))
10664 (js2-must-match js2-LC "msg.no.brace.class")
10665 (setq elems (js2-parse-object-literal-elems t)
10666 pn (make-js2-class-node :pos pos
10667 :len (- js2-ts-cursor pos)
10668 :form form
10669 :name name
10670 :extends extends
10671 :elems elems))
10672 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10673 pn))
10674
10675 (defun js2-parse-object-literal ()
10676 (let* ((pos (js2-current-token-beg))
10677 (elems (js2-parse-object-literal-elems))
10678 (result (make-js2-object-node :pos pos
10679 :len (- js2-ts-cursor pos)
10680 :elems elems)))
10681 (apply #'js2-node-add-children result (js2-object-node-elems result))
10682 result))
10683
10684 (defun js2-property-key-string (property-node)
10685 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10686 `js2-method-node') as a string, or nil if it can't be
10687 represented as a string (e.g., the key is computed by an
10688 expression)."
10689 (let ((key (js2-infix-node-left property-node)))
10690 (when (js2-computed-prop-name-node-p key)
10691 (setq key (js2-computed-prop-name-node-expr key)))
10692 (cond
10693 ((js2-name-node-p key)
10694 (js2-name-node-name key))
10695 ((js2-string-node-p key)
10696 (js2-string-node-value key))
10697 ((js2-number-node-p key)
10698 (js2-number-node-value key)))))
10699
10700 (defun js2-parse-object-literal-elems (&optional class-p)
10701 (let ((pos (js2-current-token-beg))
10702 (static nil)
10703 (continue t)
10704 tt elems elem
10705 elem-key-string previous-elem-key-string
10706 after-comma previous-token)
10707 (while continue
10708 (setq tt (js2-get-prop-name-token)
10709 static nil
10710 elem nil
10711 previous-token nil)
10712 ;; Handle 'static' keyword only if we're in a class
10713 (when (and class-p (= js2-NAME tt)
10714 (string= "static" (js2-current-token-string)))
10715 (js2-record-face 'font-lock-keyword-face)
10716 (setq static t
10717 tt (js2-get-prop-name-token)))
10718 ;; Handle generator * before the property name for in-line functions
10719 (when (and (>= js2-language-version 200)
10720 (= js2-MUL tt))
10721 (setq previous-token (js2-current-token)
10722 tt (js2-get-prop-name-token)))
10723 ;; Handle 'get' or 'set' keywords
10724 (let ((prop (js2-current-token-string)))
10725 (when (and (>= js2-language-version 200)
10726 (= js2-NAME tt)
10727 (or (string= prop "get")
10728 (string= prop "set"))
10729 (member (js2-peek-token)
10730 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10731 (setq previous-token (js2-current-token)
10732 tt (js2-get-prop-name-token))))
10733 (cond
10734 ;; Found a property (of any sort)
10735 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10736 (setq after-comma nil
10737 elem (js2-parse-named-prop tt pos previous-token))
10738 (if (and (null elem)
10739 (not js2-recover-from-parse-errors))
10740 (setq continue nil)))
10741 ;; Break out of loop, and handle trailing commas.
10742 ((or (= tt js2-RC)
10743 (= tt js2-EOF))
10744 (js2-unget-token)
10745 (setq continue nil)
10746 (if after-comma
10747 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10748 pos elems after-comma)))
10749 ;; Skip semicolons in a class body
10750 ((and class-p
10751 (= tt js2-SEMI))
10752 nil)
10753 (t
10754 (js2-report-error "msg.bad.prop")
10755 (unless js2-recover-from-parse-errors
10756 (setq continue nil)))) ; end switch
10757 ;; Handle static for classes' codegen.
10758 (if static
10759 (if elem (js2-node-set-prop elem 'STATIC t)
10760 (js2-report-error "msg.unexpected.static")))
10761 ;; Handle commas, depending on class-p.
10762 (let ((tok (js2-get-prop-name-token)))
10763 (if (eq tok js2-COMMA)
10764 (if class-p
10765 (js2-report-error "msg.class.unexpected.comma")
10766 (setq after-comma (js2-current-token-end)))
10767 (js2-unget-token)
10768 (unless class-p (setq continue nil))))
10769 (when elem
10770 (when (and js2-in-use-strict-directive
10771 (setq elem-key-string (js2-property-key-string elem))
10772 (cl-some
10773 (lambda (previous-elem)
10774 (and (setq previous-elem-key-string
10775 (js2-property-key-string previous-elem))
10776 ;; Check if the property is a duplicate.
10777 (string= previous-elem-key-string elem-key-string)
10778 ;; But make an exception for getter / setter pairs.
10779 (not (and (js2-method-node-p elem)
10780 (js2-method-node-p previous-elem)
10781 (/= (js2-method-node-type elem)
10782 (js2-method-node-type previous-elem))))))
10783 elems))
10784 (js2-report-error "msg.dup.obj.lit.prop.strict"
10785 elem-key-string
10786 (js2-node-abs-pos (js2-infix-node-left elem))
10787 (js2-node-len (js2-infix-node-left elem))))
10788 ;; Append any parsed element.
10789 (push elem elems))) ; end loop
10790 (js2-must-match js2-RC "msg.no.brace.prop")
10791 (nreverse elems)))
10792
10793 (defun js2-parse-named-prop (tt pos previous-token)
10794 "Parse a name, string, or getter/setter object property.
10795 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10796 (let ((key (js2-parse-prop-name tt))
10797 (prop (and previous-token (js2-token-string previous-token)))
10798 (property-type (when previous-token
10799 (if (= (js2-token-type previous-token) js2-MUL)
10800 "*"
10801 (js2-token-string previous-token)))))
10802 (when (or (string= prop "get")
10803 (string= prop "set"))
10804 (js2-set-face (js2-token-beg previous-token)
10805 (js2-token-end previous-token)
10806 'font-lock-keyword-face 'record)) ; get/set
10807 (cond
10808 ;; method definition: {f() {...}}
10809 ((and (= (js2-peek-token) js2-LP)
10810 (>= js2-language-version 200))
10811 (when (js2-name-node-p key) ; highlight function name properties
10812 (js2-record-face 'font-lock-function-name-face))
10813 (js2-parse-method-prop pos key property-type))
10814 ;; binding element with initializer
10815 ((and (= (js2-peek-token) js2-ASSIGN)
10816 (>= js2-language-version 200))
10817 (if (not js2-is-in-destructuring)
10818 (js2-report-error "msg.init.no.destruct"))
10819 (js2-parse-initialized-binding key))
10820 ;; regular prop
10821 (t
10822 (let ((beg (js2-current-token-beg))
10823 (end (js2-current-token-end))
10824 (expr (js2-parse-plain-property key)))
10825 (when (and (= tt js2-NAME)
10826 (not js2-is-in-destructuring)
10827 js2-highlight-external-variables
10828 (js2-node-get-prop expr 'SHORTHAND))
10829 (js2-record-name-node key))
10830 (js2-set-face beg end
10831 (if (js2-function-node-p
10832 (js2-object-prop-node-right expr))
10833 'font-lock-function-name-face
10834 'js2-object-property)
10835 'record)
10836 expr)))))
10837
10838 (defun js2-parse-initialized-binding (name)
10839 "Parse a `SingleNameBinding' with initializer.
10840
10841 `name' is the `BindingIdentifier'."
10842 (when (js2-match-token js2-ASSIGN)
10843 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10844
10845 (defun js2-parse-prop-name (tt)
10846 (cond
10847 ;; Literal string keys: {'foo': 'bar'}
10848 ((= tt js2-STRING)
10849 (make-js2-string-node))
10850 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10851 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10852 ((and (= tt js2-LB)
10853 (>= js2-language-version 200))
10854 (make-js2-computed-prop-name-node
10855 :expr (prog1 (js2-parse-assign-expr)
10856 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10857 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10858 ((= tt js2-NUMBER)
10859 (make-js2-number-node))
10860 ;; Unquoted names: {foo: 12}
10861 ((= tt js2-NAME)
10862 (js2-create-name-node))
10863 ;; Anything else is an error
10864 (t (js2-report-error "msg.bad.prop"))))
10865
10866 (defun js2-parse-plain-property (prop)
10867 "Parse a non-getter/setter property in an object literal.
10868 PROP is the node representing the property: a number, name,
10869 string or expression."
10870 (let* ((tt (js2-get-token))
10871 (pos (js2-node-pos prop))
10872 colon expr result)
10873 (cond
10874 ;; Abbreviated property, as in {foo, bar}
10875 ((and (>= js2-language-version 200)
10876 (or (= tt js2-COMMA)
10877 (= tt js2-RC))
10878 (not (js2-number-node-p prop)))
10879 (js2-unget-token)
10880 (setq result (make-js2-object-prop-node
10881 :pos pos
10882 :left prop
10883 :right prop
10884 :op-pos (js2-current-token-len)))
10885 (js2-node-add-children result prop)
10886 (js2-node-set-prop result 'SHORTHAND t)
10887 result)
10888 ;; Normal property
10889 (t
10890 (if (= tt js2-COLON)
10891 (setq colon (- (js2-current-token-beg) pos)
10892 expr (js2-parse-assign-expr))
10893 (js2-report-error "msg.no.colon.prop")
10894 (setq expr (make-js2-error-node)))
10895 (setq result (make-js2-object-prop-node
10896 :pos pos
10897 ;; don't include last consumed token in length
10898 :len (- (+ (js2-node-pos expr)
10899 (js2-node-len expr))
10900 pos)
10901 :left prop
10902 :right expr
10903 :op-pos colon))
10904 (js2-node-add-children result prop expr)
10905 result))))
10906
10907 (defun js2-parse-method-prop (pos prop type-string)
10908 "Parse method property in an object literal or a class body.
10909 JavaScript syntax is:
10910
10911 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...} }
10912
10913 and expression closure style is also supported
10914
10915 { get foo() x, set foo(x) _x = x }
10916
10917 POS is the start position of the `get' or `set' keyword.
10918 PROP is the `js2-name-node' representing the property name.
10919 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10920 (let ((type (cond
10921 ((string= "get" type-string) js2-GET)
10922 ((string= "set" type-string) js2-SET)
10923 (t js2-FUNCTION)))
10924 result end
10925 (fn (js2-parse-function-expr)))
10926 ;; it has to be an anonymous function, as we already parsed the name
10927 (if (/= (js2-node-type fn) js2-FUNCTION)
10928 (js2-report-error "msg.bad.prop")
10929 (if (cl-plusp (length (js2-function-name fn)))
10930 (js2-report-error "msg.bad.prop")))
10931 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10932 (when (string= type-string "*")
10933 (setf (js2-function-node-generator-type fn) 'STAR))
10934 (setq end (js2-node-end fn)
10935 result (make-js2-method-node :type type
10936 :pos pos
10937 :len (- end pos)
10938 :left prop
10939 :right fn))
10940 (js2-node-add-children result prop fn)
10941 result))
10942
10943 (defun js2-create-name-node (&optional check-activation-p token string)
10944 "Create a name node using the current token and, optionally, STRING.
10945 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10946 (let* ((beg (js2-current-token-beg))
10947 (tt (js2-current-token-type))
10948 (s (or string
10949 (if (= js2-NAME tt)
10950 (js2-current-token-string)
10951 (js2-tt-name tt))))
10952 name)
10953 (setq name (make-js2-name-node :pos beg
10954 :name s
10955 :len (length s)))
10956 (if check-activation-p
10957 (js2-check-activation-name s (or token js2-NAME)))
10958 name))
10959
10960 ;;; Use AST to extract semantic information
10961
10962 (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
10963 "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
10964 (let ((idx 0) elems (rlt hardcoded-array-index))
10965 (setq elems (js2-array-node-elems array-node))
10966 (if (and elem (not hardcoded-array-index))
10967 (setq rlt (catch 'nth-elt
10968 (dolist (x elems)
10969 ;; We know the ELEM does belong to ARRAY-NODE,
10970 (if (eq elem x) (throw 'nth-elt idx))
10971 (setq idx (1+ idx)))
10972 0)))
10973 (format "[%s]" rlt)))
10974
10975 (defun js2-print-json-path (&optional hardcoded-array-index)
10976 "Print the path to the JSON value under point, and save it in the kill ring.
10977 If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
10978 (interactive "P")
10979 (let (previous-node current-node
10980 key-name
10981 rlt)
10982
10983 ;; The `js2-node-at-point' starts scanning from AST root node.
10984 ;; So there is no way to optimize it.
10985 (setq current-node (js2-node-at-point))
10986
10987 (while (not (js2-ast-root-p current-node))
10988 (cond
10989 ;; JSON property node
10990 ((js2-object-prop-node-p current-node)
10991 (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
10992 (if rlt (setq rlt (concat "." key-name rlt))
10993 (setq rlt (concat "." key-name))))
10994
10995 ;; Array node
10996 ((or (js2-array-node-p current-node))
10997 (setq rlt (concat (js2-get-element-index-from-array-node previous-node
10998 current-node
10999 hardcoded-array-index)
11000 rlt)))
11001
11002 ;; Other nodes are ignored
11003 (t))
11004
11005 ;; current node is archived
11006 (setq previous-node current-node)
11007 ;; Get parent node and continue the loop
11008 (setq current-node (js2-node-parent current-node)))
11009
11010 (cond
11011 (rlt
11012 ;; Clean the final result
11013 (setq rlt (replace-regexp-in-string "^\\." "" rlt))
11014 (kill-new rlt)
11015 (message "%s => kill-ring" rlt))
11016 (t
11017 (message "No JSON path found!")))
11018
11019 rlt))
11020
11021 ;;; Indentation support (bouncing)
11022
11023 ;; In recent-enough Emacs, we reuse the indentation code from
11024 ;; `js-mode'. To continue support for the older versions, some code
11025 ;; that was here previously was moved to `js2-old-indent.el'.
11026
11027 ;; Whichever indenter is used, it's often "wrong", however, and needs
11028 ;; to be overridden. The right long-term solution is probably to
11029 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
11030 ;; of coding. Even when a parse tree from `js2-parse' is present,
11031 ;; which is not true at the moment the user is typing, computing
11032 ;; indentation is still thousands of lines of code to handle every
11033 ;; possible syntactic edge case.
11034
11035 ;; In the meantime, the compromise solution is that we offer a "bounce
11036 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
11037 ;; current line indent among various likely guess points. This approach
11038 ;; is far from perfect, but should at least make it slightly easier to
11039 ;; move the line towards its desired indentation when manually
11040 ;; overriding Karl's heuristic nesting guesser.
11041
11042 (defun js2-backward-sws ()
11043 "Move backward through whitespace and comments."
11044 (interactive)
11045 (while (forward-comment -1)))
11046
11047 (defun js2-forward-sws ()
11048 "Move forward through whitespace and comments."
11049 (interactive)
11050 (while (forward-comment 1)))
11051
11052 (defun js2-arglist-close ()
11053 "Return non-nil if we're on a line beginning with a close-paren/brace."
11054 (save-excursion
11055 (goto-char (point-at-bol))
11056 (js2-forward-sws)
11057 (looking-at "[])}]")))
11058
11059 (defun js2-indent-looks-like-label-p ()
11060 (goto-char (point-at-bol))
11061 (js2-forward-sws)
11062 (looking-at (concat js2-mode-identifier-re ":")))
11063
11064 (defun js2-indent-in-objlit-p (parse-status)
11065 "Return non-nil if this looks like an object-literal entry."
11066 (let ((start (nth 1 parse-status)))
11067 (and
11068 start
11069 (save-excursion
11070 (and (zerop (forward-line -1))
11071 (not (< (point) start)) ; crossed a {} boundary
11072 (js2-indent-looks-like-label-p)))
11073 (save-excursion
11074 (js2-indent-looks-like-label-p)))))
11075
11076 ;; If prev line looks like foobar({ then we're passing an object
11077 ;; literal to a function call, and people pretty much always want to
11078 ;; de-dent back to the previous line, so move the 'basic-offset'
11079 ;; position to the front.
11080 (defun js2-indent-objlit-arg-p (parse-status)
11081 (save-excursion
11082 (back-to-indentation)
11083 (js2-backward-sws)
11084 (and (eq (1- (point)) (nth 1 parse-status))
11085 (eq (char-before) ?{)
11086 (progn
11087 (forward-char -1)
11088 (skip-chars-backward " \t")
11089 (eq (char-before) ?\()))))
11090
11091 (defun js2-indent-case-block-p ()
11092 (save-excursion
11093 (back-to-indentation)
11094 (js2-backward-sws)
11095 (goto-char (point-at-bol))
11096 (skip-chars-forward " \t")
11097 (looking-at "case\\s-.+:")))
11098
11099 (defun js2-bounce-indent (normal-col parse-status &optional backward)
11100 "Cycle among alternate computed indentation positions.
11101 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11102 of the buffer to the current point. NORMAL-COL is the indentation
11103 column computed by the heuristic guesser based on current paren,
11104 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11105 in reverse."
11106 (let ((cur-indent (current-indentation))
11107 (old-buffer-undo-list buffer-undo-list)
11108 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11109 (current-line (save-excursion
11110 (forward-line 0) ; move to bol
11111 (1+ (count-lines (point-min) (point)))))
11112 positions pos main-pos anchor arglist-cont same-indent
11113 basic-offset computed-pos)
11114 ;; temporarily don't record undo info, if user requested this
11115 (when js2-mode-indent-inhibit-undo
11116 (setq buffer-undo-list t))
11117 (unwind-protect
11118 (progn
11119 ;; First likely point: indent from beginning of previous code line
11120 (push (setq basic-offset
11121 (+ (save-excursion
11122 (back-to-indentation)
11123 (js2-backward-sws)
11124 (back-to-indentation)
11125 (current-column))
11126 js2-basic-offset))
11127 positions)
11128
11129 ;; (First + epsilon) likely point: indent 2x from beginning of
11130 ;; previous code line. Google does it this way.
11131 (push (setq basic-offset
11132 (+ (save-excursion
11133 (back-to-indentation)
11134 (js2-backward-sws)
11135 (back-to-indentation)
11136 (current-column))
11137 (* 2 js2-basic-offset)))
11138 positions)
11139
11140 ;; Second likely point: indent from assign-expr RHS. This
11141 ;; is just a crude guess based on finding " = " on the previous
11142 ;; line containing actual code.
11143 (setq pos (save-excursion
11144 (forward-line -1)
11145 (goto-char (point-at-bol))
11146 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11147 (point-at-eol) t)
11148 (goto-char (match-end 1))
11149 (skip-chars-forward " \t\r\n")
11150 (current-column))))
11151 (when pos
11152 (cl-incf pos js2-basic-offset)
11153 (push pos positions))
11154
11155 ;; Third likely point: same indent as previous line of code.
11156 ;; Make it the first likely point if we're not on an
11157 ;; arglist-close line and previous line ends in a comma, or
11158 ;; both this line and prev line look like object-literal
11159 ;; elements.
11160 (setq pos (save-excursion
11161 (goto-char (point-at-bol))
11162 (js2-backward-sws)
11163 (back-to-indentation)
11164 (prog1
11165 (current-column)
11166 ;; while we're here, look for trailing comma
11167 (if (save-excursion
11168 (goto-char (point-at-eol))
11169 (js2-backward-sws)
11170 (eq (char-before) ?,))
11171 (setq arglist-cont (1- (point)))))))
11172 (when pos
11173 (if (and (or arglist-cont
11174 (js2-indent-in-objlit-p parse-status))
11175 (not (js2-arglist-close)))
11176 (setq same-indent pos))
11177 (push pos positions))
11178
11179 ;; Fourth likely point: first preceding code with less indentation.
11180 ;; than the immediately preceding code line.
11181 (setq pos (save-excursion
11182 (back-to-indentation)
11183 (js2-backward-sws)
11184 (back-to-indentation)
11185 (setq anchor (current-column))
11186 (while (and (zerop (forward-line -1))
11187 (>= (progn
11188 (back-to-indentation)
11189 (current-column))
11190 anchor)))
11191 (setq pos (current-column))))
11192 (push pos positions)
11193
11194 ;; nesting-heuristic position, main by default
11195 (push (setq main-pos normal-col) positions)
11196
11197 ;; delete duplicates and sort positions list
11198 (setq positions (sort (delete-dups positions) '<))
11199
11200 ;; comma-list continuation lines: prev line indent takes precedence
11201 (if same-indent
11202 (setq main-pos same-indent))
11203
11204 ;; common special cases where we want to indent in from previous line
11205 (if (or (js2-indent-case-block-p)
11206 (js2-indent-objlit-arg-p parse-status))
11207 (setq main-pos basic-offset))
11208
11209 ;; if bouncing backward, reverse positions list
11210 (if backward
11211 (setq positions (reverse positions)))
11212
11213 ;; record whether we're already sitting on one of the alternatives
11214 (setq pos (member cur-indent positions))
11215
11216 (cond
11217 ;; case 0: we're one one of the alternatives and this is the
11218 ;; first time they've pressed TAB on this line (best-guess).
11219 ((and js2-mode-indent-ignore-first-tab
11220 pos
11221 ;; first time pressing TAB on this line?
11222 (not (eq js2-mode-last-indented-line current-line)))
11223 ;; do nothing
11224 (setq computed-pos nil))
11225 ;; case 1: only one computed position => use it
11226 ((null (cdr positions))
11227 (setq computed-pos 0))
11228 ;; case 2: not on any of the computed spots => use main spot
11229 ((not pos)
11230 (setq computed-pos (js2-position main-pos positions)))
11231 ;; case 3: on last position: cycle to first position
11232 ((null (cdr pos))
11233 (setq computed-pos 0))
11234 ;; case 4: on intermediate position: cycle to next position
11235 (t
11236 (setq computed-pos (js2-position (cl-second pos) positions))))
11237
11238 ;; see if any hooks want to indent; otherwise we do it
11239 (cl-loop with result = nil
11240 for hook in js2-indent-hook
11241 while (null result)
11242 do
11243 (setq result (funcall hook positions computed-pos))
11244 finally do
11245 (unless (or result (null computed-pos))
11246 (indent-line-to (nth computed-pos positions)))))
11247
11248 ;; finally
11249 (if js2-mode-indent-inhibit-undo
11250 (setq buffer-undo-list old-buffer-undo-list))
11251 ;; see commentary for `js2-mode-last-indented-line'
11252 (setq js2-mode-last-indented-line current-line))))
11253
11254 (defun js2-1-line-comment-continuation-p ()
11255 "Return t if we're in a 1-line comment continuation.
11256 If so, we don't ever want to use bounce-indent."
11257 (save-excursion
11258 (and (progn
11259 (forward-line 0)
11260 (looking-at "\\s-*//"))
11261 (progn
11262 (forward-line -1)
11263 (forward-line 0)
11264 (when (looking-at "\\s-*$")
11265 (js2-backward-sws)
11266 (forward-line 0))
11267 (looking-at "\\s-*//")))))
11268
11269 (defun js2-indent-bounce (&optional backward)
11270 "Indent the current line, bouncing between several positions."
11271 (interactive)
11272 (let (parse-status offset indent-col
11273 ;; Don't whine about errors/warnings when we're indenting.
11274 ;; This has to be set before calling parse-partial-sexp below.
11275 (inhibit-point-motion-hooks t))
11276 (setq parse-status (save-excursion
11277 (syntax-ppss (point-at-bol)))
11278 offset (- (point) (save-excursion
11279 (back-to-indentation)
11280 (point))))
11281 ;; Don't touch multiline strings.
11282 (unless (nth 3 parse-status)
11283 (setq indent-col (js2-proper-indentation parse-status))
11284 (cond
11285 ;; It doesn't work well on first line of buffer.
11286 ((and (not (nth 4 parse-status))
11287 (not (js2-same-line (point-min)))
11288 (not (js2-1-line-comment-continuation-p)))
11289 (js2-bounce-indent indent-col parse-status backward))
11290 ;; just indent to the guesser's likely spot
11291 (t (indent-line-to indent-col)))
11292 (when (cl-plusp offset)
11293 (forward-char offset)))))
11294
11295 (defun js2-indent-bounce-backward ()
11296 "Indent the current line, bouncing between positions in reverse."
11297 (interactive)
11298 (js2-indent-bounce t))
11299
11300 (defun js2-indent-region (start end)
11301 "Indent the region, but don't use bounce indenting."
11302 (let ((js2-bounce-indent-p nil)
11303 (indent-region-function nil)
11304 (after-change-functions (remq 'js2-mode-edit
11305 after-change-functions)))
11306 (indent-region start end nil) ; nil for byte-compiler
11307 (js2-mode-edit start end (- end start))))
11308
11309 (defvar js2-minor-mode-map
11310 (let ((map (make-sparse-keymap)))
11311 (define-key map (kbd "C-c C-`") #'js2-next-error)
11312 (define-key map [mouse-1] #'js2-mode-show-node)
11313 map)
11314 "Keymap used when `js2-minor-mode' is active.")
11315
11316 ;;;###autoload
11317 (define-minor-mode js2-minor-mode
11318 "Minor mode for running js2 as a background linter.
11319 This allows you to use a different major mode for JavaScript editing,
11320 such as `js-mode', while retaining the asynchronous error/warning
11321 highlighting features of `js2-mode'."
11322 :group 'js2-mode
11323 :lighter " js-lint"
11324 (if (derived-mode-p 'js2-mode)
11325 (setq js2-minor-mode nil)
11326 (if js2-minor-mode
11327 (js2-minor-mode-enter)
11328 (js2-minor-mode-exit))))
11329
11330 (defun js2-minor-mode-enter ()
11331 "Initialization for `js2-minor-mode'."
11332 (set (make-local-variable 'max-lisp-eval-depth)
11333 (max max-lisp-eval-depth 3000))
11334 (setq next-error-function #'js2-next-error)
11335 (js2-set-default-externs)
11336 ;; Experiment: make reparse-delay longer for longer files.
11337 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11338 (setq js2-idle-timer-delay
11339 (* js2-idle-timer-delay
11340 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11341 (setq js2-mode-buffer-dirty-p t
11342 js2-mode-parsing nil)
11343 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11344 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11345 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11346 (when js2-include-jslint-globals
11347 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11348 (run-hooks 'js2-init-hook)
11349 (js2-reparse))
11350
11351 (defun js2-minor-mode-exit ()
11352 "Turn off `js2-minor-mode'."
11353 (setq next-error-function nil)
11354 (remove-hook 'after-change-functions #'js2-mode-edit t)
11355 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11356 (when js2-mode-node-overlay
11357 (delete-overlay js2-mode-node-overlay)
11358 (setq js2-mode-node-overlay nil))
11359 (js2-remove-overlays)
11360 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11361 (setq js2-mode-ast nil))
11362
11363 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11364 (make-variable-buffer-local 'js2-source-buffer)
11365
11366 (cl-defun js2-display-error-list ()
11367 "Display a navigable buffer listing parse errors/warnings."
11368 (interactive)
11369 (unless (js2-have-errors-p)
11370 (message "No errors")
11371 (cl-return-from js2-display-error-list))
11372 (cl-labels ((annotate-list
11373 (lst type)
11374 "Add diagnostic TYPE and line number to errs list"
11375 (mapcar (lambda (err)
11376 (list err type (line-number-at-pos (nth 1 err))))
11377 lst)))
11378 (let* ((srcbuf (current-buffer))
11379 (errbuf (get-buffer-create "*js-lint*"))
11380 (errors (annotate-list
11381 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11382 'js2-error)) ; must be a valid face name
11383 (warnings (annotate-list
11384 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11385 'js2-warning)) ; must be a valid face name
11386 (all-errs (sort (append errors warnings)
11387 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11388 (with-current-buffer errbuf
11389 (let ((inhibit-read-only t))
11390 (erase-buffer)
11391 (dolist (err all-errs)
11392 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11393 (insert-text-button
11394 (format "line %d: %s" line (js2-get-msg msg-key))
11395 'face type
11396 'follow-link "\C-m"
11397 'action 'js2-error-buffer-jump
11398 'js2-msg (js2-get-msg msg-key)
11399 'js2-pos beg)
11400 (insert "\n"))))
11401 (js2-error-buffer-mode)
11402 (setq js2-source-buffer srcbuf)
11403 (pop-to-buffer errbuf)
11404 (goto-char (point-min))
11405 (unless (eobp)
11406 (js2-error-buffer-view))))))
11407
11408 (defvar js2-error-buffer-mode-map
11409 (let ((map (make-sparse-keymap)))
11410 (define-key map "n" #'js2-error-buffer-next)
11411 (define-key map "p" #'js2-error-buffer-prev)
11412 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11413 (define-key map "o" #'js2-error-buffer-view)
11414 (define-key map "q" #'js2-error-buffer-quit)
11415 map)
11416 "Keymap used for js2 diagnostics buffers.")
11417
11418 (defun js2-error-buffer-mode ()
11419 "Major mode for js2 diagnostics buffers.
11420 Selecting an error will jump it to the corresponding source-buffer error.
11421 \\{js2-error-buffer-mode-map}"
11422 (interactive)
11423 (setq major-mode 'js2-error-buffer-mode
11424 mode-name "JS Lint Diagnostics")
11425 (use-local-map js2-error-buffer-mode-map)
11426 (setq truncate-lines t)
11427 (set-buffer-modified-p nil)
11428 (setq buffer-read-only t)
11429 (run-hooks 'js2-error-buffer-mode-hook))
11430
11431 (defun js2-error-buffer-next ()
11432 "Move to next error and view it."
11433 (interactive)
11434 (when (zerop (forward-line 1))
11435 (js2-error-buffer-view)))
11436
11437 (defun js2-error-buffer-prev ()
11438 "Move to previous error and view it."
11439 (interactive)
11440 (when (zerop (forward-line -1))
11441 (js2-error-buffer-view)))
11442
11443 (defun js2-error-buffer-quit ()
11444 "Kill the current buffer."
11445 (interactive)
11446 (kill-buffer))
11447
11448 (defun js2-error-buffer-jump (&rest ignored)
11449 "Jump cursor to current error in source buffer."
11450 (interactive)
11451 (when (js2-error-buffer-view)
11452 (pop-to-buffer js2-source-buffer)))
11453
11454 (defun js2-error-buffer-view ()
11455 "Scroll source buffer to show error at current line."
11456 (interactive)
11457 (cond
11458 ((not (eq major-mode 'js2-error-buffer-mode))
11459 (message "Not in a js2 errors buffer"))
11460 ((not (buffer-live-p js2-source-buffer))
11461 (message "Source buffer has been killed"))
11462 ((not (wholenump (get-text-property (point) 'js2-pos)))
11463 (message "There does not seem to be an error here"))
11464 (t
11465 (let ((pos (get-text-property (point) 'js2-pos))
11466 (msg (get-text-property (point) 'js2-msg)))
11467 (save-selected-window
11468 (pop-to-buffer js2-source-buffer)
11469 (goto-char pos)
11470 (message msg))))))
11471
11472 ;;;###autoload
11473 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11474 "Major mode for editing JavaScript code."
11475 (set (make-local-variable 'max-lisp-eval-depth)
11476 (max max-lisp-eval-depth 3000))
11477 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11478 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11479 (set (make-local-variable 'syntax-propertize-function) nil)
11480 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11481 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11482 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11483 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11484 ;; for characters inside regexp literals.
11485 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11486 ;; this is necessary to make `show-paren-function' work properly
11487 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11488 ;; needed for M-x rgrep, among other things
11489 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11490
11491 (setq font-lock-defaults '(nil t))
11492
11493 ;; Experiment: make reparse-delay longer for longer files.
11494 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11495 (setq js2-idle-timer-delay
11496 (* js2-idle-timer-delay
11497 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11498
11499 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11500 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11501 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11502 (setq next-error-function #'js2-next-error)
11503 (imenu-add-to-menubar (concat "IM-" mode-name))
11504 (add-to-invisibility-spec '(js2-outline . t))
11505 (set (make-local-variable 'line-move-ignore-invisible) t)
11506 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11507 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11508
11509 (setq js2-mode-functions-hidden nil
11510 js2-mode-comments-hidden nil
11511 js2-mode-buffer-dirty-p t
11512 js2-mode-parsing nil)
11513
11514 (js2-set-default-externs)
11515
11516 (when js2-include-jslint-globals
11517 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11518
11519 (run-hooks 'js2-init-hook)
11520
11521 (js2-reparse))
11522
11523 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11524 ;; a bit more complicated and it doesn't net us much yet.
11525 ;;;###autoload
11526 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11527 "Major mode for editing JSX code.
11528
11529 To customize the indentation for this mode, set the SGML offset
11530 variables (`sgml-basic-offset' et al) locally, like so:
11531
11532 (defun set-jsx-indentation ()
11533 (setq-local sgml-basic-offset js2-basic-offset))
11534 (add-hook 'js2-jsx-mode-hook #'set-jsx-indentation)"
11535 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11536
11537 (defun js2-mode-exit ()
11538 "Exit `js2-mode' and clean up."
11539 (interactive)
11540 (when js2-mode-node-overlay
11541 (delete-overlay js2-mode-node-overlay)
11542 (setq js2-mode-node-overlay nil))
11543 (js2-remove-overlays)
11544 (setq js2-mode-ast nil)
11545 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11546 (remove-from-invisibility-spec '(js2-outline . t))
11547 (js2-mode-show-all)
11548 (with-silent-modifications
11549 (js2-clear-face (point-min) (point-max))))
11550
11551 (defun js2-mode-reset-timer ()
11552 "Cancel any existing parse timer and schedule a new one."
11553 (if js2-mode-parse-timer
11554 (cancel-timer js2-mode-parse-timer))
11555 (setq js2-mode-parsing nil)
11556 (let ((timer (timer-create)))
11557 (setq js2-mode-parse-timer timer)
11558 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11559 (timer-set-idle-time timer js2-idle-timer-delay)
11560 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11561 (timer-activate-when-idle timer nil)))
11562
11563 (defun js2-mode-idle-reparse (buffer)
11564 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11565 it to be reparsed when the buffer is selected."
11566 (cond ((eq buffer (current-buffer))
11567 (js2-reparse))
11568 ((buffer-live-p buffer)
11569 ;; reparse when the buffer is selected again
11570 (with-current-buffer buffer
11571 (add-hook 'window-configuration-change-hook
11572 #'js2-mode-idle-reparse-inner
11573 nil t)))))
11574
11575 (defun js2-mode-idle-reparse-inner ()
11576 (remove-hook 'window-configuration-change-hook
11577 #'js2-mode-idle-reparse-inner
11578 t)
11579 (js2-reparse))
11580
11581 (defun js2-mode-edit (_beg _end _len)
11582 "Schedule a new parse after buffer is edited.
11583 Buffer edit spans from BEG to END and is of length LEN."
11584 (setq js2-mode-buffer-dirty-p t)
11585 (js2-mode-hide-overlay)
11586 (js2-mode-reset-timer))
11587
11588 (defun js2-minor-mode-edit (_beg _end _len)
11589 "Callback for buffer edits in `js2-mode'.
11590 Schedules a new parse after buffer is edited.
11591 Buffer edit spans from BEG to END and is of length LEN."
11592 (setq js2-mode-buffer-dirty-p t)
11593 (js2-mode-hide-overlay)
11594 (js2-mode-reset-timer))
11595
11596 (defun js2-reparse (&optional force)
11597 "Re-parse current buffer after user finishes some data entry.
11598 If we get any user input while parsing, including cursor motion,
11599 we discard the parse and reschedule it. If FORCE is nil, then the
11600 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11601 (let (time
11602 interrupted-p
11603 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11604 (unless js2-mode-parsing
11605 (setq js2-mode-parsing t)
11606 (unwind-protect
11607 (when (or js2-mode-buffer-dirty-p force)
11608 (js2-remove-overlays)
11609 (setq js2-mode-buffer-dirty-p nil
11610 js2-mode-fontifications nil
11611 js2-mode-deferred-properties nil)
11612 (if js2-mode-verbose-parse-p
11613 (message "parsing..."))
11614 (setq time
11615 (js2-time
11616 (setq interrupted-p
11617 (catch 'interrupted
11618 (js2-parse)
11619 (with-silent-modifications
11620 ;; if parsing is interrupted, comments and regex
11621 ;; literals stay ignored by `parse-partial-sexp'
11622 (remove-text-properties (point-min) (point-max)
11623 '(syntax-table))
11624 (js2-mode-apply-deferred-properties)
11625 (js2-mode-remove-suppressed-warnings)
11626 (js2-mode-show-warnings)
11627 (js2-mode-show-errors)
11628 (if (>= js2-highlight-level 1)
11629 (js2-highlight-jsdoc js2-mode-ast)))
11630 nil))))
11631 (if interrupted-p
11632 (progn
11633 ;; unfinished parse => try again
11634 (setq js2-mode-buffer-dirty-p t)
11635 (js2-mode-reset-timer))
11636 (if js2-mode-verbose-parse-p
11637 (message "Parse time: %s" time))))
11638 (setq js2-mode-parsing nil)
11639 (unless interrupted-p
11640 (setq js2-mode-parse-timer nil))))))
11641
11642 (defun js2-mode-show-node (event)
11643 "Debugging aid: highlight selected AST node on mouse click."
11644 (interactive "e")
11645 (mouse-set-point event)
11646 (setq deactivate-mark t)
11647 (when js2-mode-show-overlay
11648 (let ((node (js2-node-at-point))
11649 beg end)
11650 (if (null node)
11651 (message "No node found at location %s" (point))
11652 (setq beg (js2-node-abs-pos node)
11653 end (+ beg (js2-node-len node)))
11654 (if js2-mode-node-overlay
11655 (move-overlay js2-mode-node-overlay beg end)
11656 (setq js2-mode-node-overlay (make-overlay beg end))
11657 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11658 (with-silent-modifications
11659 (if (fboundp 'cursor-sensor-mode)
11660 (put-text-property beg end 'cursor-sensor-functions
11661 '(js2-mode-hide-overlay))
11662 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11663 (message "%s, parent: %s"
11664 (js2-node-short-name node)
11665 (if (js2-node-parent node)
11666 (js2-node-short-name (js2-node-parent node))
11667 "nil"))))))
11668
11669 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11670 "Remove the debugging overlay when point moves.
11671 ARG1, ARG2 and ARG3 have different values depending on whether this function
11672 was found on `point-left' or in `cursor-sensor-functions'."
11673 (when js2-mode-node-overlay
11674 (let ((beg (overlay-start js2-mode-node-overlay))
11675 (end (overlay-end js2-mode-node-overlay))
11676 (p2 (if (windowp arg1)
11677 ;; Called from cursor-sensor-functions.
11678 (window-point arg1)
11679 ;; Called from point-left.
11680 arg2)))
11681 ;; Sometimes we're called spuriously.
11682 (unless (and p2
11683 (>= p2 beg)
11684 (<= p2 end))
11685 (with-silent-modifications
11686 (remove-text-properties beg end
11687 '(point-left nil cursor-sensor-functions)))
11688 (delete-overlay js2-mode-node-overlay)
11689 (setq js2-mode-node-overlay nil)))))
11690
11691 (defun js2-mode-reset ()
11692 "Debugging helper: reset everything."
11693 (interactive)
11694 (js2-mode-exit)
11695 (js2-mode))
11696
11697 (defun js2-mode-show-warn-or-err (e face)
11698 "Highlight a warning or error E with FACE.
11699 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11700 The last element is optional. When present, use instead of FACE."
11701 (let* ((key (cl-first e))
11702 (beg (cl-second e))
11703 (end (+ beg (cl-third e)))
11704 ;; Don't inadvertently go out of bounds.
11705 (beg (max (point-min) (min beg (point-max))))
11706 (end (max (point-min) (min end (point-max))))
11707 (ovl (make-overlay beg end)))
11708 ;; FIXME: Why a mix of overlays and text-properties?
11709 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11710 (overlay-put ovl 'js2-error t)
11711 (put-text-property beg end 'help-echo (js2-get-msg key))
11712 (if (fboundp 'cursor-sensor-mode)
11713 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11714 (put-text-property beg end 'point-entered #'js2-echo-error))))
11715
11716 (defun js2-remove-overlays ()
11717 "Remove overlays from buffer that have a `js2-error' property."
11718 (let ((beg (point-min))
11719 (end (point-max)))
11720 (save-excursion
11721 (dolist (o (overlays-in beg end))
11722 (when (overlay-get o 'js2-error)
11723 (delete-overlay o))))))
11724
11725 (defun js2-mode-apply-deferred-properties ()
11726 "Apply fontifications and other text properties recorded during parsing."
11727 (when (cl-plusp js2-highlight-level)
11728 ;; We defer clearing faces as long as possible to eliminate flashing.
11729 (js2-clear-face (point-min) (point-max))
11730 ;; Have to reverse the recorded fontifications list so that errors
11731 ;; and warnings overwrite the normal fontifications.
11732 (dolist (f (nreverse js2-mode-fontifications))
11733 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11734 (setq js2-mode-fontifications nil))
11735 (dolist (p js2-mode-deferred-properties)
11736 (apply #'put-text-property p))
11737 (setq js2-mode-deferred-properties nil))
11738
11739 (defun js2-mode-show-errors ()
11740 "Highlight syntax errors."
11741 (when js2-mode-show-parse-errors
11742 (dolist (e (js2-ast-root-errors js2-mode-ast))
11743 (js2-mode-show-warn-or-err e 'js2-error))))
11744
11745 (defun js2-mode-remove-suppressed-warnings ()
11746 "Take suppressed warnings out of the AST warnings list.
11747 This ensures that the counts and `next-error' are correct."
11748 (setf (js2-ast-root-warnings js2-mode-ast)
11749 (js2-delete-if
11750 (lambda (e)
11751 (let ((key (caar e)))
11752 (or
11753 (and (not js2-strict-trailing-comma-warning)
11754 (string-match "trailing\\.comma" key))
11755 (and (not js2-strict-cond-assign-warning)
11756 (string= key "msg.equal.as.assign"))
11757 (and js2-missing-semi-one-line-override
11758 (string= key "msg.missing.semi")
11759 (let* ((beg (cl-second e))
11760 (node (js2-node-at-point beg))
11761 (fn (js2-mode-find-parent-fn node))
11762 (body (and fn (js2-function-node-body fn)))
11763 (lc (and body (js2-node-abs-pos body)))
11764 (rc (and lc (+ lc (js2-node-len body)))))
11765 (and fn
11766 (or (null body)
11767 (save-excursion
11768 (goto-char beg)
11769 (and (js2-same-line lc)
11770 (js2-same-line rc))))))))))
11771 (js2-ast-root-warnings js2-mode-ast))))
11772
11773 (defun js2-mode-show-warnings ()
11774 "Highlight strict-mode warnings."
11775 (when js2-mode-show-strict-warnings
11776 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11777 (js2-mode-show-warn-or-err e 'js2-warning))))
11778
11779 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11780 "Called by point-motion hooks.
11781 ARG1, ARG2 and ARG3 have different values depending on whether this function
11782 was found on `point-entered' or in `cursor-sensor-functions'."
11783 (let* ((new-point (if (windowp arg1)
11784 ;; Called from cursor-sensor-functions.
11785 (window-point arg1)
11786 ;; Called from point-left.
11787 arg2))
11788 (msg (get-text-property new-point 'help-echo)))
11789 (when (and (stringp msg)
11790 (not (active-minibuffer-window))
11791 (not (current-message)))
11792 (message msg))))
11793
11794 (defun js2-line-break (&optional _soft)
11795 "Break line at point and indent, continuing comment if within one.
11796 If inside a string, and `js2-concat-multiline-strings' is not
11797 nil, turn it into concatenation."
11798 (interactive)
11799 (let ((parse-status (syntax-ppss)))
11800 (cond
11801 ;; Check if we're inside a string.
11802 ((nth 3 parse-status)
11803 (if js2-concat-multiline-strings
11804 (js2-mode-split-string parse-status)
11805 (insert "\n")))
11806 ;; Check if inside a block comment.
11807 ((nth 4 parse-status)
11808 (js2-mode-extend-comment (nth 8 parse-status)))
11809 (t
11810 (newline-and-indent)))))
11811
11812 (defun js2-mode-split-string (parse-status)
11813 "Turn a newline in mid-string into a string concatenation.
11814 PARSE-STATUS is as documented in `parse-partial-sexp'."
11815 (let* ((quote-char (nth 3 parse-status))
11816 (at-eol (eq js2-concat-multiline-strings 'eol)))
11817 (insert quote-char)
11818 (insert (if at-eol " +\n" "\n"))
11819 (unless at-eol
11820 (insert "+ "))
11821 (js2-indent-line)
11822 (insert quote-char)
11823 (when (eolp)
11824 (insert quote-char)
11825 (backward-char 1))))
11826
11827 (defun js2-mode-extend-comment (start-pos)
11828 "Indent the line and, when inside a comment block, add comment prefix."
11829 (let (star single col first-line needs-close)
11830 (save-excursion
11831 (back-to-indentation)
11832 (when (< (point) start-pos)
11833 (goto-char start-pos))
11834 (cond
11835 ((looking-at "\\*[^/]")
11836 (setq star t
11837 col (current-column)))
11838 ((looking-at "/\\*")
11839 (setq star t
11840 first-line t
11841 col (1+ (current-column))))
11842 ((looking-at "//")
11843 (setq single t
11844 col (current-column)))))
11845 ;; Heuristic for whether we need to close the comment:
11846 ;; if we've got a parse error here, assume it's an unterminated
11847 ;; comment.
11848 (setq needs-close
11849 (or
11850 (get-char-property (1- (point)) 'js2-error)
11851 ;; The heuristic above doesn't work well when we're
11852 ;; creating a comment and there's another one downstream,
11853 ;; as our parser thinks this one ends at the end of the
11854 ;; next one. (You can have a /* inside a js block comment.)
11855 ;; So just close it if the next non-ws char isn't a *.
11856 (and first-line
11857 (eolp)
11858 (save-excursion
11859 (skip-chars-forward " \t\r\n")
11860 (not (eq (char-after) ?*))))))
11861 (delete-horizontal-space)
11862 (insert "\n")
11863 (cond
11864 (star
11865 (indent-to col)
11866 (insert "* ")
11867 (if (and first-line needs-close)
11868 (save-excursion
11869 (insert "\n")
11870 (indent-to col)
11871 (insert "*/"))))
11872 ((and single
11873 (save-excursion
11874 (and (zerop (forward-line 1))
11875 (looking-at "\\s-*//"))))
11876 (indent-to col)
11877 (insert "// ")))
11878 ;; Don't need to extend the comment after all.
11879 (js2-indent-line)))
11880
11881 (defun js2-beginning-of-line ()
11882 "Toggle point between bol and first non-whitespace char in line.
11883 Also moves past comment delimiters when inside comments."
11884 (interactive)
11885 (let (node)
11886 (cond
11887 ((bolp)
11888 (back-to-indentation))
11889 ((looking-at "//")
11890 (skip-chars-forward "/ \t"))
11891 ((and (eq (char-after) ?*)
11892 (setq node (js2-comment-at-point))
11893 (memq (js2-comment-node-format node) '(jsdoc block))
11894 (save-excursion
11895 (skip-chars-backward " \t")
11896 (bolp)))
11897 (skip-chars-forward "\* \t"))
11898 (t
11899 (goto-char (point-at-bol))))))
11900
11901 (defun js2-end-of-line ()
11902 "Toggle point between eol and last non-whitespace char in line."
11903 (interactive)
11904 (if (eolp)
11905 (skip-chars-backward " \t")
11906 (goto-char (point-at-eol))))
11907
11908 (defun js2-mode-wait-for-parse (callback)
11909 "Invoke CALLBACK when parsing is finished.
11910 If parsing is already finished, calls CALLBACK immediately."
11911 (if (not js2-mode-buffer-dirty-p)
11912 (funcall callback)
11913 (push callback js2-mode-pending-parse-callbacks)
11914 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11915
11916 (defun js2-mode-parse-finished ()
11917 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11918 ;; We can't let errors propagate up, since it prevents the
11919 ;; `js2-parse' method from completing normally and returning
11920 ;; the ast, which makes things mysteriously not work right.
11921 (unwind-protect
11922 (dolist (cb js2-mode-pending-parse-callbacks)
11923 (condition-case err
11924 (funcall cb)
11925 (error (message "%s" err))))
11926 (setq js2-mode-pending-parse-callbacks nil)))
11927
11928 (defun js2-mode-flag-region (from to flag)
11929 "Hide or show text from FROM to TO, according to FLAG.
11930 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11931 Returns the created overlay if FLAG is non-nil."
11932 (remove-overlays from to 'invisible 'js2-outline)
11933 (when flag
11934 (let ((o (make-overlay from to)))
11935 (overlay-put o 'invisible 'js2-outline)
11936 (overlay-put o 'isearch-open-invisible
11937 'js2-isearch-open-invisible)
11938 o)))
11939
11940 ;; Function to be set as an outline-isearch-open-invisible' property
11941 ;; to the overlay that makes the outline invisible (see
11942 ;; `js2-mode-flag-region').
11943 (defun js2-isearch-open-invisible (_overlay)
11944 ;; We rely on the fact that isearch places point on the matched text.
11945 (js2-mode-show-element))
11946
11947 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11948 "Return cons cell of bounds of folding overlay at POS.
11949 Returns nil if not found."
11950 (let ((overlays (overlays-at (or pos (point))))
11951 o)
11952 (while (and overlays
11953 (not o))
11954 (if (overlay-get (car overlays) 'invisible)
11955 (setq o (car overlays))
11956 (setq overlays (cdr overlays))))
11957 (if o
11958 (cons (overlay-start o) (overlay-end o)))))
11959
11960 (defun js2-mode-function-at-point (&optional pos)
11961 "Return the innermost function node enclosing current point.
11962 Returns nil if point is not in a function."
11963 (let ((node (js2-node-at-point pos)))
11964 (while (and node (not (js2-function-node-p node)))
11965 (setq node (js2-node-parent node)))
11966 (if (js2-function-node-p node)
11967 node)))
11968
11969 (defun js2-mode-toggle-element ()
11970 "Hide or show the foldable element at the point."
11971 (interactive)
11972 (let (comment fn pos)
11973 (save-excursion
11974 (cond
11975 ;; /* ... */ comment?
11976 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11977 (if (js2-mode-invisible-overlay-bounds
11978 (setq pos (+ 3 (js2-node-abs-pos comment))))
11979 (progn
11980 (goto-char pos)
11981 (js2-mode-show-element))
11982 (js2-mode-hide-element)))
11983 ;; //-comment?
11984 ((save-excursion
11985 (back-to-indentation)
11986 (looking-at js2-mode-//-comment-re))
11987 (js2-mode-toggle-//-comment))
11988 ;; function?
11989 ((setq fn (js2-mode-function-at-point))
11990 (setq pos (and (js2-function-node-body fn)
11991 (js2-node-abs-pos (js2-function-node-body fn))))
11992 (goto-char (1+ pos))
11993 (if (js2-mode-invisible-overlay-bounds)
11994 (js2-mode-show-element)
11995 (js2-mode-hide-element)))
11996 (t
11997 (message "Nothing at point to hide or show"))))))
11998
11999 (defun js2-mode-hide-element ()
12000 "Fold/hide contents of a block, showing ellipses.
12001 Show the hidden text with \\[js2-mode-show-element]."
12002 (interactive)
12003 (if js2-mode-buffer-dirty-p
12004 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12005 (let (node body beg end)
12006 (cond
12007 ((js2-mode-invisible-overlay-bounds)
12008 (message "already hidden"))
12009 (t
12010 (setq node (js2-node-at-point))
12011 (cond
12012 ((js2-block-comment-p node)
12013 (js2-mode-hide-comment node))
12014 (t
12015 (while (and node (not (js2-function-node-p node)))
12016 (setq node (js2-node-parent node)))
12017 (if (and node
12018 (setq body (js2-function-node-body node)))
12019 (progn
12020 (setq beg (js2-node-abs-pos body)
12021 end (+ beg (js2-node-len body)))
12022 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12023 (message "No collapsable element found at point"))))))))
12024
12025 (defun js2-mode-show-element ()
12026 "Show the hidden element at current point."
12027 (interactive)
12028 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12029 (if bounds
12030 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12031 (message "Nothing to un-hide"))))
12032
12033 (defun js2-mode-show-all ()
12034 "Show all of the text in the buffer."
12035 (interactive)
12036 (js2-mode-flag-region (point-min) (point-max) nil))
12037
12038 (defun js2-mode-toggle-hide-functions ()
12039 (interactive)
12040 (if js2-mode-functions-hidden
12041 (js2-mode-show-functions)
12042 (js2-mode-hide-functions)))
12043
12044 (defun js2-mode-hide-functions ()
12045 "Hides all non-nested function bodies in the buffer.
12046 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12047 to open an individual entry."
12048 (interactive)
12049 (if js2-mode-buffer-dirty-p
12050 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12051 (if (null js2-mode-ast)
12052 (message "Oops - parsing failed")
12053 (setq js2-mode-functions-hidden t)
12054 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12055
12056 (defun js2-mode-function-hider (n endp)
12057 (when (not endp)
12058 (let ((tt (js2-node-type n))
12059 body beg end)
12060 (cond
12061 ((and (= tt js2-FUNCTION)
12062 (setq body (js2-function-node-body n)))
12063 (setq beg (js2-node-abs-pos body)
12064 end (+ beg (js2-node-len body)))
12065 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12066 nil) ; don't process children of function
12067 (t
12068 t))))) ; keep processing other AST nodes
12069
12070 (defun js2-mode-show-functions ()
12071 "Un-hide any folded function bodies in the buffer."
12072 (interactive)
12073 (setq js2-mode-functions-hidden nil)
12074 (save-excursion
12075 (goto-char (point-min))
12076 (while (/= (goto-char (next-overlay-change (point)))
12077 (point-max))
12078 (dolist (o (overlays-at (point)))
12079 (when (and (overlay-get o 'invisible)
12080 (not (overlay-get o 'comment)))
12081 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12082
12083 (defun js2-mode-hide-comment (n)
12084 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12085 3 ; /**
12086 2)) ; /*
12087 (beg (+ (js2-node-abs-pos n) head))
12088 (end (- (+ beg (js2-node-len n)) head 2))
12089 (o (js2-mode-flag-region beg end 'hide)))
12090 (overlay-put o 'comment t)))
12091
12092 (defun js2-mode-toggle-hide-comments ()
12093 "Folds all block comments in the buffer.
12094 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12095 to open an individual entry."
12096 (interactive)
12097 (if js2-mode-comments-hidden
12098 (js2-mode-show-comments)
12099 (js2-mode-hide-comments)))
12100
12101 (defun js2-mode-hide-comments ()
12102 (interactive)
12103 (if js2-mode-buffer-dirty-p
12104 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12105 (if (null js2-mode-ast)
12106 (message "Oops - parsing failed")
12107 (setq js2-mode-comments-hidden t)
12108 (dolist (n (js2-ast-root-comments js2-mode-ast))
12109 (when (js2-block-comment-p n)
12110 (js2-mode-hide-comment n)))
12111 (js2-mode-hide-//-comments)))
12112
12113 (defun js2-mode-extend-//-comment (direction)
12114 "Find start or end of a block of similar //-comment lines.
12115 DIRECTION is -1 to look back, 1 to look forward.
12116 INDENT is the indentation level to match.
12117 Returns the end-of-line position of the furthest adjacent
12118 //-comment line with the same indentation as the current line.
12119 If there is no such matching line, returns current end of line."
12120 (let ((pos (point-at-eol))
12121 (indent (current-indentation)))
12122 (save-excursion
12123 (while (and (zerop (forward-line direction))
12124 (looking-at js2-mode-//-comment-re)
12125 (eq indent (length (match-string 1))))
12126 (setq pos (point-at-eol)))
12127 pos)))
12128
12129 (defun js2-mode-hide-//-comments ()
12130 "Fold adjacent 1-line comments, showing only snippet of first one."
12131 (let (beg end)
12132 (save-excursion
12133 (goto-char (point-min))
12134 (while (re-search-forward js2-mode-//-comment-re nil t)
12135 (setq beg (point)
12136 end (js2-mode-extend-//-comment 1))
12137 (unless (eq beg end)
12138 (overlay-put (js2-mode-flag-region beg end 'hide)
12139 'comment t))
12140 (goto-char end)
12141 (forward-char 1)))))
12142
12143 (defun js2-mode-toggle-//-comment ()
12144 "Fold or un-fold any multi-line //-comment at point.
12145 Caller should have determined that this line starts with a //-comment."
12146 (let* ((beg (point-at-eol))
12147 (end beg))
12148 (save-excursion
12149 (goto-char end)
12150 (if (js2-mode-invisible-overlay-bounds)
12151 (js2-mode-show-element)
12152 ;; else hide the comment
12153 (setq beg (js2-mode-extend-//-comment -1)
12154 end (js2-mode-extend-//-comment 1))
12155 (unless (eq beg end)
12156 (overlay-put (js2-mode-flag-region beg end 'hide)
12157 'comment t))))))
12158
12159 (defun js2-mode-show-comments ()
12160 "Un-hide any hidden comments, leaving other hidden elements alone."
12161 (interactive)
12162 (setq js2-mode-comments-hidden nil)
12163 (save-excursion
12164 (goto-char (point-min))
12165 (while (/= (goto-char (next-overlay-change (point)))
12166 (point-max))
12167 (dolist (o (overlays-at (point)))
12168 (when (overlay-get o 'comment)
12169 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12170
12171 (defun js2-mode-display-warnings-and-errors ()
12172 "Turn on display of warnings and errors."
12173 (interactive)
12174 (setq js2-mode-show-parse-errors t
12175 js2-mode-show-strict-warnings t)
12176 (js2-reparse 'force))
12177
12178 (defun js2-mode-hide-warnings-and-errors ()
12179 "Turn off display of warnings and errors."
12180 (interactive)
12181 (setq js2-mode-show-parse-errors nil
12182 js2-mode-show-strict-warnings nil)
12183 (js2-reparse 'force))
12184
12185 (defun js2-mode-toggle-warnings-and-errors ()
12186 "Toggle the display of warnings and errors.
12187 Some users don't like having warnings/errors reported while they type."
12188 (interactive)
12189 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12190 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12191 (if (called-interactively-p 'any)
12192 (message "warnings and errors %s"
12193 (if js2-mode-show-parse-errors
12194 "enabled"
12195 "disabled")))
12196 (js2-reparse 'force))
12197
12198 (defun js2-mode-customize ()
12199 (interactive)
12200 (customize-group 'js2-mode))
12201
12202 (defun js2-mode-forward-sexp (&optional arg)
12203 "Move forward across one statement or balanced expression.
12204 With ARG, do it that many times. Negative arg -N means
12205 move backward across N balanced expressions."
12206 (interactive "p")
12207 (setq arg (or arg 1))
12208 (save-restriction
12209 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12210 (js2-reparse)
12211 (let (forward-sexp-function
12212 node (start (point)) pos lp rp child)
12213 (cond
12214 ;; backward-sexp
12215 ;; could probably make this better for some cases:
12216 ;; - if in statement block (e.g. function body), go to parent
12217 ;; - infix exprs like (foo in bar) - maybe go to beginning
12218 ;; of infix expr if in the right-side expression?
12219 ((and arg (cl-minusp arg))
12220 (dotimes (_ (- arg))
12221 (js2-backward-sws)
12222 (forward-char -1) ; Enter the node we backed up to.
12223 (when (setq node (js2-node-at-point (point) t))
12224 (setq pos (js2-node-abs-pos node))
12225 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12226 (setq lp (car parens)
12227 rp (cdr parens)))
12228 (when (and lp (> start lp))
12229 (if (and rp (<= start rp))
12230 ;; Between parens, check if there's a child node we can jump.
12231 (when (setq child (js2-node-closest-child node (point) lp t))
12232 (setq pos (js2-node-abs-pos child)))
12233 ;; Before both parens.
12234 (setq pos lp)))
12235 (let ((state (parse-partial-sexp start pos)))
12236 (goto-char (if (not (zerop (car state)))
12237 ;; Stumble at the unbalanced paren if < 0, or
12238 ;; jump a bit further if > 0.
12239 (scan-sexps start -1)
12240 pos))))
12241 (unless pos (goto-char (point-min)))))
12242 (t
12243 ;; forward-sexp
12244 (dotimes (_ arg)
12245 (js2-forward-sws)
12246 (when (setq node (js2-node-at-point (point) t))
12247 (setq pos (js2-node-abs-pos node))
12248 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12249 (setq lp (car parens)
12250 rp (cdr parens)))
12251 (or
12252 (when (and rp (<= start rp))
12253 (if (> start lp)
12254 (when (setq child (js2-node-closest-child node (point) rp))
12255 (setq pos (js2-node-abs-end child)))
12256 (setq pos (1+ rp))))
12257 ;; No parens or child nodes, looks for the end of the current node.
12258 (cl-incf pos (js2-node-len
12259 (if (js2-expr-stmt-node-p (js2-node-parent node))
12260 ;; Stop after the semicolon.
12261 (js2-node-parent node)
12262 node))))
12263 (let ((state (save-excursion (parse-partial-sexp start pos))))
12264 (goto-char (if (not (zerop (car state)))
12265 (scan-sexps start 1)
12266 pos))))
12267 (unless pos (goto-char (point-max)))))))))
12268
12269 (defun js2-mode-forward-sexp-parens (node abs-pos)
12270 "Return a cons cell with positions of main parens in NODE."
12271 (cond
12272 ((or (js2-array-node-p node)
12273 (js2-object-node-p node)
12274 (js2-comp-node-p node)
12275 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12276 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12277 ((js2-paren-expr-node-p node)
12278 (let ((lp (js2-node-lp node))
12279 (rp (js2-node-rp node)))
12280 (cons (when lp (+ abs-pos lp))
12281 (when rp (+ abs-pos rp)))))))
12282
12283 (defun js2-node-closest-child (parent point limit &optional before)
12284 (let* ((parent-pos (js2-node-abs-pos parent))
12285 (rpoint (- point parent-pos))
12286 (rlimit (- limit parent-pos))
12287 (min (min rpoint rlimit))
12288 (max (max rpoint rlimit))
12289 found)
12290 (catch 'done
12291 (js2-visit-ast
12292 parent
12293 (lambda (node _end-p)
12294 (if (eq node parent)
12295 t
12296 (let ((pos (js2-node-pos node)) ;; Both relative values.
12297 (end (+ (js2-node-pos node) (js2-node-len node))))
12298 (when (and (>= pos min) (<= end max)
12299 (if before (< pos rpoint) (> end rpoint)))
12300 (setq found node))
12301 (when (> end rpoint)
12302 (throw 'done nil)))
12303 nil))))
12304 found))
12305
12306 (defun js2-errors ()
12307 "Return a list of errors found."
12308 (and js2-mode-ast
12309 (js2-ast-root-errors js2-mode-ast)))
12310
12311 (defun js2-warnings ()
12312 "Return a list of warnings found."
12313 (and js2-mode-ast
12314 (js2-ast-root-warnings js2-mode-ast)))
12315
12316 (defun js2-have-errors-p ()
12317 "Return non-nil if any parse errors or warnings were found."
12318 (or (js2-errors) (js2-warnings)))
12319
12320 (defun js2-errors-and-warnings ()
12321 "Return a copy of the concatenated errors and warnings lists.
12322 They are appended: first the errors, then the warnings.
12323 Entries are of the form (MSG BEG END)."
12324 (when js2-mode-ast
12325 (append (js2-ast-root-errors js2-mode-ast)
12326 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12327
12328 (defun js2-next-error (&optional arg reset)
12329 "Move to next parse error.
12330 Typically invoked via \\[next-error].
12331 ARG is the number of errors, forward or backward, to move.
12332 RESET means start over from the beginning."
12333 (interactive "p")
12334 (if (not (or (js2-errors) (js2-warnings)))
12335 (message "No errors")
12336 (when reset
12337 (goto-char (point-min)))
12338 (let* ((errs (js2-errors-and-warnings))
12339 (continue t)
12340 (start (point))
12341 (count (or arg 1))
12342 (backward (cl-minusp count))
12343 (sorter (if backward '> '<))
12344 (stopper (if backward '< '>))
12345 (count (abs count))
12346 all-errs err)
12347 ;; Sort by start position.
12348 (setq errs (sort errs (lambda (e1 e2)
12349 (funcall sorter (cl-second e1) (cl-second e2))))
12350 all-errs errs)
12351 ;; Find nth error with pos > start.
12352 (while (and errs continue)
12353 (when (funcall stopper (cl-cadar errs) start)
12354 (setq err (car errs))
12355 (if (zerop (cl-decf count))
12356 (setq continue nil)))
12357 (setq errs (cdr errs)))
12358 ;; Clear for `js2-echo-error'.
12359 (message nil)
12360 (if err
12361 (goto-char (cl-second err))
12362 ;; Wrap around to first error.
12363 (goto-char (cl-second (car all-errs)))
12364 ;; If we were already on it, echo msg again.
12365 (if (= (point) start)
12366 (js2-echo-error (point) (point)))))))
12367
12368 (defun js2-down-mouse-3 ()
12369 "Make right-click move the point to the click location.
12370 This makes right-click context menu operations a bit more intuitive.
12371 The point will not move if the region is active, however, to avoid
12372 destroying the region selection."
12373 (interactive)
12374 (when (and js2-move-point-on-right-click
12375 (not mark-active))
12376 (let ((e last-input-event))
12377 (ignore-errors
12378 (goto-char (cl-cadadr e))))))
12379
12380 (defun js2-mode-create-imenu-index ()
12381 "Return an alist for `imenu--index-alist'."
12382 ;; This is built up in `js2-parse-record-imenu' during parsing.
12383 (when js2-mode-ast
12384 ;; if we have an ast but no recorder, they're requesting a rescan
12385 (unless js2-imenu-recorder
12386 (js2-reparse 'force))
12387 (prog1
12388 (js2-build-imenu-index)
12389 (setq js2-imenu-recorder nil
12390 js2-imenu-function-map nil))))
12391
12392 (defun js2-mode-find-tag ()
12393 "Replacement for `find-tag-default'.
12394 `find-tag-default' returns a ridiculous answer inside comments."
12395 (let (beg end)
12396 (save-excursion
12397 (if (looking-at "\\_>")
12398 (setq beg (progn (forward-symbol -1) (point))
12399 end (progn (forward-symbol 1) (point)))
12400 (setq beg (progn (forward-symbol 1) (point))
12401 end (progn (forward-symbol -1) (point))))
12402 (replace-regexp-in-string
12403 "[\"']" ""
12404 (buffer-substring-no-properties beg end)))))
12405
12406 (defun js2-mode-forward-sibling ()
12407 "Move to the end of the sibling following point in parent.
12408 Returns non-nil if successful, or nil if there was no following sibling."
12409 (let* ((node (js2-node-at-point))
12410 (parent (js2-mode-find-enclosing-fn node))
12411 sib)
12412 (when (setq sib (js2-node-find-child-after (point) parent))
12413 (goto-char (+ (js2-node-abs-pos sib)
12414 (js2-node-len sib))))))
12415
12416 (defun js2-mode-backward-sibling ()
12417 "Move to the beginning of the sibling node preceding point in parent.
12418 Parent is defined as the enclosing script or function."
12419 (let* ((node (js2-node-at-point))
12420 (parent (js2-mode-find-enclosing-fn node))
12421 sib)
12422 (when (setq sib (js2-node-find-child-before (point) parent))
12423 (goto-char (js2-node-abs-pos sib)))))
12424
12425 (defun js2-beginning-of-defun (&optional arg)
12426 "Go to line on which current function starts, and return t on success.
12427 If we're not in a function or already at the beginning of one, go
12428 to beginning of previous script-level element.
12429 With ARG N, do that N times. If N is negative, move forward."
12430 (setq arg (or arg 1))
12431 (if (cl-plusp arg)
12432 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12433 (when (cond
12434 ((js2-function-node-p parent)
12435 (goto-char (js2-node-abs-pos parent)))
12436 (t
12437 (js2-mode-backward-sibling)))
12438 (if (> arg 1)
12439 (js2-beginning-of-defun (1- arg))
12440 t)))
12441 (when (js2-end-of-defun)
12442 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12443
12444 (defun js2-end-of-defun ()
12445 "Go to the char after the last position of the current function
12446 or script-level element."
12447 (let* ((node (js2-node-at-point))
12448 (parent (or (and (js2-function-node-p node) node)
12449 (js2-node-parent-script-or-fn node)))
12450 script)
12451 (unless (js2-function-node-p parent)
12452 ;; Use current script-level node, or, if none, the next one.
12453 (setq script (or parent node)
12454 parent (js2-node-find-child-before (point) script))
12455 (when (or (null parent)
12456 (>= (point) (+ (js2-node-abs-pos parent)
12457 (js2-node-len parent))))
12458 (setq parent (js2-node-find-child-after (point) script))))
12459 (when parent
12460 (goto-char (+ (js2-node-abs-pos parent)
12461 (js2-node-len parent))))))
12462
12463 (defun js2-mark-defun (&optional allow-extend)
12464 "Put mark at end of this function, point at beginning.
12465 The function marked is the one that contains point.
12466
12467 Interactively, if this command is repeated,
12468 or (in Transient Mark mode) if the mark is active,
12469 it marks the next defun after the ones already marked."
12470 (interactive "p")
12471 (let (extended)
12472 (when (and allow-extend
12473 (or (and (eq last-command this-command) (mark t))
12474 (and transient-mark-mode mark-active)))
12475 (let ((sib (save-excursion
12476 (goto-char (mark))
12477 (if (js2-mode-forward-sibling)
12478 (point)))))
12479 (if sib
12480 (progn
12481 (set-mark sib)
12482 (setq extended t))
12483 ;; no more siblings - try extending to enclosing node
12484 (goto-char (mark t)))))
12485 (when (not extended)
12486 (let ((node (js2-node-at-point (point) t)) ; skip comments
12487 ast fn stmt parent beg end)
12488 (when (js2-ast-root-p node)
12489 (setq ast node
12490 node (or (js2-node-find-child-after (point) node)
12491 (js2-node-find-child-before (point) node))))
12492 ;; only mark whole buffer if we can't find any children
12493 (if (null node)
12494 (setq node ast))
12495 (if (js2-function-node-p node)
12496 (setq parent node)
12497 (setq fn (js2-mode-find-enclosing-fn node)
12498 stmt (if (or (null fn)
12499 (js2-ast-root-p fn))
12500 (js2-mode-find-first-stmt node))
12501 parent (or stmt fn)))
12502 (setq beg (js2-node-abs-pos parent)
12503 end (+ beg (js2-node-len parent)))
12504 (push-mark beg)
12505 (goto-char end)
12506 (exchange-point-and-mark)))))
12507
12508 (defun js2-narrow-to-defun ()
12509 "Narrow to the function enclosing point."
12510 (interactive)
12511 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12512 (fn (if (js2-script-node-p node)
12513 node
12514 (js2-mode-find-enclosing-fn node)))
12515 (beg (js2-node-abs-pos fn)))
12516 (unless (js2-ast-root-p fn)
12517 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12518
12519 (defun js2-jump-to-definition (&optional arg)
12520 "Jump to the definition of an object's property, variable or function."
12521 (interactive "P")
12522 (ring-insert find-tag-marker-ring (point-marker))
12523 (let* ((node (js2-node-at-point))
12524 (parent (js2-node-parent node))
12525 (names (if (js2-prop-get-node-p parent)
12526 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12527 (cl-loop for n in temp
12528 with result = '()
12529 do (push n result)
12530 until (equal node n)
12531 finally return result)))))
12532 node-init)
12533 (unless (and (js2-name-node-p node)
12534 (not (js2-var-init-node-p parent))
12535 (not (js2-function-node-p parent)))
12536 (error "Node is not a supported jump node"))
12537 (push (or (and names (pop names))
12538 (unless (and (js2-object-prop-node-p parent)
12539 (eq node (js2-object-prop-node-left parent)))
12540 node)) names)
12541 (setq node-init (js2-search-scope node names))
12542
12543 ;; todo: display list of results in buffer
12544 ;; todo: group found references by buffer
12545 (unless node-init
12546 (switch-to-buffer
12547 (catch 'found
12548 (unless arg
12549 (mapc (lambda (b)
12550 (with-current-buffer b
12551 (when (derived-mode-p 'js2-mode)
12552 (setq node-init (js2-search-scope js2-mode-ast names))
12553 (if node-init
12554 (throw 'found b)))))
12555 (buffer-list)))
12556 nil)))
12557 (setq node-init (if (listp node-init) (car node-init) node-init))
12558 (unless node-init
12559 (pop-tag-mark)
12560 (error "No jump location found"))
12561 (goto-char (js2-node-abs-pos node-init))))
12562
12563 (defun js2-search-object (node name-node)
12564 "Check if object NODE contains element with NAME-NODE."
12565 (cl-assert (js2-object-node-p node))
12566 ;; Only support name-node and nodes for the time being
12567 (cl-loop for elem in (js2-object-node-elems node)
12568 for left = (js2-object-prop-node-left elem)
12569 if (or (and (js2-name-node-p left)
12570 (equal (js2-name-node-name name-node)
12571 (js2-name-node-name left)))
12572 (and (js2-string-node-p left)
12573 (string= (js2-name-node-name name-node)
12574 (js2-string-node-value left))))
12575 return elem))
12576
12577 (defun js2-search-object-for-prop (object prop-names)
12578 "Return node in OBJECT that matches PROP-NAMES or nil.
12579 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12580 i.e. ('name' 'value') = {name : { value: 3}}"
12581 (let (node
12582 (temp-object object)
12583 (temp t) ;temporay node
12584 (names prop-names))
12585 (while (and temp names (js2-object-node-p temp-object))
12586 (setq temp (js2-search-object temp-object (pop names)))
12587 (and (setq node temp)
12588 (setq temp-object (js2-object-prop-node-right temp))))
12589 (unless names node)))
12590
12591 (defun js2-search-scope (node names)
12592 "Searches NODE scope for jump location matching NAMES.
12593 NAMES is a list of property values to search for. For functions
12594 and variables NAMES will contain one element."
12595 (let (node-init
12596 (val (js2-name-node-name (car names))))
12597 (setq node-init (js2-get-symbol-declaration node val))
12598
12599 (when (> (length names) 1)
12600
12601 ;; Check var declarations
12602 (when (and node-init (string= val (js2-name-node-name node-init)))
12603 (let ((parent (js2-node-parent node-init))
12604 (temp-names names))
12605 (pop temp-names) ;; First element is var name
12606 (setq node-init (when (js2-var-init-node-p parent)
12607 (js2-search-object-for-prop
12608 (js2-var-init-node-initializer parent)
12609 temp-names)))))
12610
12611 ;; Check all assign nodes
12612 (js2-visit-ast
12613 js2-mode-ast
12614 (lambda (node endp)
12615 (unless endp
12616 (if (js2-assign-node-p node)
12617 (let ((left (js2-assign-node-left node))
12618 (right (js2-assign-node-right node))
12619 (temp-names names))
12620 (when (js2-prop-get-node-p left)
12621 (let* ((prop-list (js2-compute-nested-prop-get left))
12622 (found (cl-loop for prop in prop-list
12623 until (not (string= (js2-name-node-name
12624 (pop temp-names))
12625 (js2-name-node-name prop)))
12626 if (not temp-names) return prop))
12627 (found-node (or found
12628 (when (js2-object-node-p right)
12629 (js2-search-object-for-prop right
12630 temp-names)))))
12631 (if found-node (push found-node node-init))))))
12632 t))))
12633 node-init))
12634
12635 (defun js2-get-symbol-declaration (node name)
12636 "Find scope for NAME from NODE."
12637 (let ((scope (js2-get-defining-scope
12638 (or (js2-node-get-enclosing-scope node)
12639 node) name)))
12640 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12641
12642 (provide 'js2-mode)
12643
12644 ;;; js2-mode.el ends here