]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Fix semicolons and scoping in exported decls
[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 setImmediate clearImmediate))
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 number-legacy-octal-p
681 regexp-flags
682 comment-type
683 follows-eol-p)
684
685 ;; Have to call `js2-init-scanner' to initialize the values.
686 (js2-deflocal js2-ti-tokens nil)
687 (js2-deflocal js2-ti-tokens-cursor nil)
688 (js2-deflocal js2-ti-lookahead nil)
689
690 (cl-defstruct (js2-ts-state
691 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
692 (cursor js2-ts-cursor)
693 (tokens (copy-sequence js2-ti-tokens))
694 (tokens-cursor js2-ti-tokens-cursor)
695 (lookahead js2-ti-lookahead))))
696 lineno
697 cursor
698 tokens
699 tokens-cursor
700 lookahead)
701
702 ;;; Parser variables
703
704 (js2-deflocal js2-parsed-errors nil
705 "List of errors produced during scanning/parsing.")
706
707 (js2-deflocal js2-parsed-warnings nil
708 "List of warnings produced during scanning/parsing.")
709
710 (js2-deflocal js2-recover-from-parse-errors t
711 "Non-nil to continue parsing after a syntax error.
712
713 In recovery mode, the AST will be built in full, and any error
714 nodes will be flagged with appropriate error information. If
715 this flag is nil, a syntax error will result in an error being
716 signaled.
717
718 The variable is automatically buffer-local, because different
719 modes that use the parser will need different settings.")
720
721 (js2-deflocal js2-parse-hook nil
722 "List of callbacks for receiving parsing progress.")
723
724 (defvar js2-parse-finished-hook nil
725 "List of callbacks to notify when parsing finishes.
726 Not called if parsing was interrupted.")
727
728 (js2-deflocal js2-is-eval-code nil
729 "True if we're evaluating code in a string.
730 If non-nil, the tokenizer will record the token text, and the AST nodes
731 will record their source text. Off by default for IDE modes, since the
732 text is available in the buffer.")
733
734 (defvar js2-parse-ide-mode t
735 "Non-nil if the parser is being used for `js2-mode'.
736 If non-nil, the parser will set text properties for fontification
737 and the syntax table. The value should be nil when using the
738 parser as a frontend to an interpreter or byte compiler.")
739
740 ;;; Parser instance variables (buffer-local vars for js2-parse)
741
742 (defconst js2-ti-after-eol (lsh 1 16)
743 "Flag: first token of the source line.")
744
745 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
746
747 (js2-deflocal js2-compiler-generate-debug-info t)
748 (js2-deflocal js2-compiler-use-dynamic-scope nil)
749 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
750 (js2-deflocal js2-compiler-xml-available t)
751 (js2-deflocal js2-compiler-optimization-level 0)
752 (js2-deflocal js2-compiler-generating-source t)
753 (js2-deflocal js2-compiler-strict-mode nil)
754 (js2-deflocal js2-compiler-report-warning-as-error nil)
755 (js2-deflocal js2-compiler-generate-observer-count nil)
756 (js2-deflocal js2-compiler-activation-names nil)
757
758 ;; SKIP: sourceURI
759
760 ;; There's a compileFunction method in Context.java - may need it.
761 (js2-deflocal js2-called-by-compile-function nil
762 "True if `js2-parse' was called by `js2-compile-function'.
763 Will only be used when we finish implementing the interpreter.")
764
765 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
766
767 ;; SKIP: node factory - we're going to just call functions directly,
768 ;; and eventually go to a unified AST format.
769
770 (js2-deflocal js2-nesting-of-function 0)
771
772 (js2-deflocal js2-recorded-identifiers nil
773 "Tracks identifiers found during parsing.")
774
775 (js2-deflocal js2-is-in-destructuring nil
776 "True while parsing destructuring expression.")
777
778 (js2-deflocal js2-in-use-strict-directive nil
779 "True while inside a script or function under strict mode.")
780
781 (defcustom js2-global-externs nil
782 "A list of any extern names you'd like to consider always declared.
783 This list is global and is used by all `js2-mode' files.
784 You can create buffer-local externs list using `js2-additional-externs'.
785
786 There is also a buffer-local variable `js2-default-externs',
787 which is initialized by default to include the Ecma-262 externs
788 and the standard browser externs. The three lists are all
789 checked during highlighting."
790 :type 'list
791 :group 'js2-mode)
792
793 (js2-deflocal js2-default-externs nil
794 "Default external declarations.
795
796 These are currently only used for highlighting undeclared variables,
797 which only worries about top-level (unqualified) references.
798 As js2-mode's processing improves, we will flesh out this list.
799
800 The initial value is set to `js2-ecma-262-externs', unless some
801 of the `js2-include-?-externs' variables are set to t, in which
802 case the browser, Rhino and/or Node.js externs are also included.
803
804 See `js2-additional-externs' for more information.")
805
806 (defcustom js2-include-browser-externs t
807 "Non-nil to include browser externs in the master externs list.
808 If you work on JavaScript files that are not intended for browsers,
809 such as Mozilla Rhino server-side JavaScript, set this to nil.
810 See `js2-additional-externs' for more information about externs."
811 :type 'boolean
812 :group 'js2-mode)
813
814 (defcustom js2-include-rhino-externs nil
815 "Non-nil to include Mozilla Rhino externs in the master externs list.
816 See `js2-additional-externs' for more information about externs."
817 :type 'boolean
818 :group 'js2-mode)
819
820 (defcustom js2-include-node-externs nil
821 "Non-nil to include Node.js externs in the master externs list.
822 See `js2-additional-externs' for more information about externs."
823 :type 'boolean
824 :group 'js2-mode)
825
826 (js2-deflocal js2-additional-externs nil
827 "A buffer-local list of additional external declarations.
828 It is used to decide whether variables are considered undeclared
829 for purposes of highlighting.
830
831 Each entry is a Lisp string. The string should be the fully qualified
832 name of an external entity. All externs should be added to this list,
833 so that as js2-mode's processing improves it can take advantage of them.
834
835 You may want to declare your externs in three ways.
836 First, you can add externs that are valid for all your JavaScript files.
837 You should probably do this by adding them to `js2-global-externs', which
838 is a global list used for all js2-mode files.
839
840 Next, you can add a function to `js2-init-hook' that adds additional
841 externs appropriate for the specific file, perhaps based on its path.
842 These should go in `js2-additional-externs', which is buffer-local.
843
844 Third, you can use JSLint's global declaration, as long as
845 `js2-include-jslint-globals' is non-nil, which see.
846
847 Finally, you can add a function to `js2-post-parse-callbacks',
848 which is called after parsing completes, and `js2-mode-ast' is bound to
849 the root of the parse tree. At this stage you can set up an AST
850 node visitor using `js2-visit-ast' and examine the parse tree
851 for specific import patterns that may imply the existence of
852 other externs, possibly tied to your build system. These should also
853 be added to `js2-additional-externs'.
854
855 Your post-parse callback may of course also use the simpler and
856 faster (but perhaps less robust) approach of simply scanning the
857 buffer text for your imports, using regular expressions.")
858
859 ;; SKIP: decompiler
860 ;; SKIP: encoded-source
861
862 ;;; The following variables are per-function and should be saved/restored
863 ;;; during function parsing...
864
865 (js2-deflocal js2-current-script-or-fn nil)
866 (js2-deflocal js2-current-scope nil)
867 (js2-deflocal js2-nesting-of-with 0)
868 (js2-deflocal js2-label-set nil
869 "An alist mapping label names to nodes.")
870
871 (js2-deflocal js2-loop-set nil)
872 (js2-deflocal js2-loop-and-switch-set nil)
873 (js2-deflocal js2-has-return-value nil)
874 (js2-deflocal js2-end-flags 0)
875
876 ;;; ...end of per function variables
877
878 ;; These flags enumerate the possible ways a statement/function can
879 ;; terminate. These flags are used by endCheck() and by the Parser to
880 ;; detect inconsistent return usage.
881 ;;
882 ;; END_UNREACHED is reserved for code paths that are assumed to always be
883 ;; able to execute (example: throw, continue)
884 ;;
885 ;; END_DROPS_OFF indicates if the statement can transfer control to the
886 ;; next one. Statement such as return dont. A compound statement may have
887 ;; some branch that drops off control to the next statement.
888 ;;
889 ;; END_RETURNS indicates that the statement can return (without arguments)
890 ;; END_RETURNS_VALUE indicates that the statement can return a value.
891 ;;
892 ;; A compound statement such as
893 ;; if (condition) {
894 ;; return value;
895 ;; }
896 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
897
898 (defconst js2-end-unreached #x0)
899 (defconst js2-end-drops-off #x1)
900 (defconst js2-end-returns #x2)
901 (defconst js2-end-returns-value #x4)
902
903 ;; Rhino awkwardly passes a statementLabel parameter to the
904 ;; statementHelper() function, the main statement parser, which
905 ;; is then used by quite a few of the sub-parsers. We just make
906 ;; it a buffer-local variable and make sure it's cleaned up properly.
907 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
908
909 ;; Similarly, Rhino passes an inForInit boolean through about half
910 ;; the expression parsers. We use a dynamically-scoped variable,
911 ;; which makes it easier to funcall the parsers individually without
912 ;; worrying about whether they take the parameter or not.
913 (js2-deflocal js2-in-for-init nil)
914 (js2-deflocal js2-temp-name-counter 0)
915 (js2-deflocal js2-parse-stmt-count 0)
916
917 (defsubst js2-get-next-temp-name ()
918 (format "$%d" (cl-incf js2-temp-name-counter)))
919
920 (defvar js2-parse-interruptable-p t
921 "Set this to nil to force parse to continue until finished.
922 This will mostly be useful for interpreters.")
923
924 (defvar js2-statements-per-pause 50
925 "Pause after this many statements to check for user input.
926 If user input is pending, stop the parse and discard the tree.
927 This makes for a smoother user experience for large files.
928 You may have to wait a second or two before the highlighting
929 and error-reporting appear, but you can always type ahead if
930 you wish. This appears to be more or less how Eclipse, IntelliJ
931 and other editors work.")
932
933 (js2-deflocal js2-record-comments t
934 "Instructs the scanner to record comments in `js2-scanned-comments'.")
935
936 (js2-deflocal js2-scanned-comments nil
937 "List of all comments from the current parse.")
938
939 (defcustom js2-mode-indent-inhibit-undo nil
940 "Non-nil to disable collection of Undo information when indenting lines.
941 Some users have requested this behavior. It's nil by default because
942 other Emacs modes don't work this way."
943 :type 'boolean
944 :group 'js2-mode)
945
946 (defcustom js2-mode-indent-ignore-first-tab nil
947 "If non-nil, ignore first TAB keypress if we look indented properly.
948 It's fairly common for users to navigate to an already-indented line
949 and press TAB for reassurance that it's been indented. For this class
950 of users, we want the first TAB press on a line to be ignored if the
951 line is already indented to one of the precomputed alternatives.
952
953 This behavior is only partly implemented. If you TAB-indent a line,
954 navigate to another line, and then navigate back, it fails to clear
955 the last-indented variable, so it thinks you've already hit TAB once,
956 and performs the indent. A full solution would involve getting on the
957 point-motion hooks for the entire buffer. If we come across another
958 use cases that requires watching point motion, I'll consider doing it.
959
960 If you set this variable to nil, then the TAB key will always change
961 the indentation of the current line, if more than one alternative
962 indentation spot exists."
963 :type 'boolean
964 :group 'js2-mode)
965
966 (defvar js2-indent-hook nil
967 "A hook for user-defined indentation rules.
968
969 Functions on this hook should expect two arguments: (LIST INDEX)
970 The LIST argument is the list of computed indentation points for
971 the current line. INDEX is the list index of the indentation point
972 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
973 indent function is not going to change the current line indentation.
974
975 If a hook function on this list returns a non-nil value, then
976 `js2-bounce-indent' assumes the hook function has performed its own
977 indentation, and will do nothing. If all hook functions on the list
978 return nil, then `js2-bounce-indent' will use its computed indentation
979 and reindent the line.
980
981 When hook functions on this hook list are called, the variable
982 `js2-mode-ast' may or may not be set, depending on whether the
983 parse tree is available. If the variable is nil, you can pass a
984 callback to `js2-mode-wait-for-parse', and your callback will be
985 called after the new parse tree is built. This can take some time
986 in large files.")
987
988 (defface js2-warning
989 `((((class color) (background light))
990 (:underline "orange"))
991 (((class color) (background dark))
992 (:underline "orange"))
993 (t (:underline t)))
994 "Face for JavaScript warnings."
995 :group 'js2-mode)
996
997 (defface js2-error
998 `((((class color) (background light))
999 (:foreground "red"))
1000 (((class color) (background dark))
1001 (:foreground "red"))
1002 (t (:foreground "red")))
1003 "Face for JavaScript errors."
1004 :group 'js2-mode)
1005
1006 (defface js2-jsdoc-tag
1007 '((t :foreground "SlateGray"))
1008 "Face used to highlight @whatever tags in jsdoc comments."
1009 :group 'js2-mode)
1010
1011 (defface js2-jsdoc-type
1012 '((t :foreground "SteelBlue"))
1013 "Face used to highlight {FooBar} types in jsdoc comments."
1014 :group 'js2-mode)
1015
1016 (defface js2-jsdoc-value
1017 '((t :foreground "PeachPuff3"))
1018 "Face used to highlight tag values in jsdoc comments."
1019 :group 'js2-mode)
1020
1021 (defface js2-function-param
1022 '((t :foreground "SeaGreen"))
1023 "Face used to highlight function parameters in javascript."
1024 :group 'js2-mode)
1025
1026 (defface js2-function-call
1027 '((t :inherit default))
1028 "Face used to highlight function name in calls."
1029 :group 'js2-mode)
1030
1031 (defface js2-object-property
1032 '((t :inherit default))
1033 "Face used to highlight named property in object literal."
1034 :group 'js2-mode)
1035
1036 (defface js2-instance-member
1037 '((t :foreground "DarkOrchid"))
1038 "Face used to highlight instance variables in javascript.
1039 Not currently used."
1040 :group 'js2-mode)
1041
1042 (defface js2-private-member
1043 '((t :foreground "PeachPuff3"))
1044 "Face used to highlight calls to private methods in javascript.
1045 Not currently used."
1046 :group 'js2-mode)
1047
1048 (defface js2-private-function-call
1049 '((t :foreground "goldenrod"))
1050 "Face used to highlight calls to private functions in javascript.
1051 Not currently used."
1052 :group 'js2-mode)
1053
1054 (defface js2-jsdoc-html-tag-name
1055 '((((class color) (min-colors 88) (background light))
1056 (:foreground "rosybrown"))
1057 (((class color) (min-colors 8) (background dark))
1058 (:foreground "yellow"))
1059 (((class color) (min-colors 8) (background light))
1060 (:foreground "magenta")))
1061 "Face used to highlight jsdoc html tag names"
1062 :group 'js2-mode)
1063
1064 (defface js2-jsdoc-html-tag-delimiter
1065 '((((class color) (min-colors 88) (background light))
1066 (:foreground "dark khaki"))
1067 (((class color) (min-colors 8) (background dark))
1068 (:foreground "green"))
1069 (((class color) (min-colors 8) (background light))
1070 (:foreground "green")))
1071 "Face used to highlight brackets in jsdoc html tags."
1072 :group 'js2-mode)
1073
1074 (defface js2-external-variable
1075 '((t :foreground "orange"))
1076 "Face used to highlight undeclared variable identifiers.")
1077
1078 (defcustom js2-init-hook nil
1079 "List of functions to be called after `js2-mode' or
1080 `js2-minor-mode' has initialized all variables, before parsing
1081 the buffer for the first time."
1082 :type 'hook
1083 :group 'js2-mode
1084 :version "20130608")
1085
1086 (defcustom js2-post-parse-callbacks nil
1087 "List of callback functions invoked after parsing finishes.
1088 Currently, the main use for this function is to add synthetic
1089 declarations to `js2-recorded-identifiers', which see."
1090 :type 'hook
1091 :group 'js2-mode)
1092
1093 (defcustom js2-build-imenu-callbacks nil
1094 "List of functions called during Imenu index generation.
1095 It's a good place to add additional entries to it, using
1096 `js2-record-imenu-entry'."
1097 :type 'hook
1098 :group 'js2-mode)
1099
1100 (defcustom js2-highlight-external-variables t
1101 "Non-nil to highlight undeclared variable identifiers.
1102 An undeclared variable is any variable not declared with var or let
1103 in the current scope or any lexically enclosing scope. If you use
1104 such a variable, then you are either expecting it to originate from
1105 another file, or you've got a potential bug."
1106 :type 'boolean
1107 :group 'js2-mode)
1108
1109 (defcustom js2-warn-about-unused-function-arguments nil
1110 "Non-nil to treat function arguments like declared-but-unused variables."
1111 :type 'booleanp
1112 :group 'js2-mode)
1113
1114 (defcustom js2-include-jslint-globals t
1115 "Non-nil to include the identifiers from JSLint global
1116 declaration (see http://www.jslint.com/lint.html#global) in the
1117 buffer-local externs list. See `js2-additional-externs' for more
1118 information."
1119 :type 'boolean
1120 :group 'js2-mode)
1121
1122 (defvar js2-mode-map
1123 (let ((map (make-sparse-keymap)))
1124 (define-key map [mouse-1] #'js2-mode-show-node)
1125 (define-key map (kbd "M-j") #'js2-line-break)
1126 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1127 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1128 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1129 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1130 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1131 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1132 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1133 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1134 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1135
1136 (define-key map [menu-bar javascript]
1137 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1138
1139 (define-key map [menu-bar javascript customize-js2-mode]
1140 '(menu-item "Customize js2-mode" js2-mode-customize
1141 :help "Customize the behavior of this mode"))
1142
1143 (define-key map [menu-bar javascript js2-force-refresh]
1144 '(menu-item "Force buffer refresh" js2-mode-reset
1145 :help "Re-parse the buffer from scratch"))
1146
1147 (define-key map [menu-bar javascript separator-2]
1148 '("--"))
1149
1150 (define-key map [menu-bar javascript next-error]
1151 '(menu-item "Next warning or error" next-error
1152 :enabled (and js2-mode-ast
1153 (or (js2-ast-root-errors js2-mode-ast)
1154 (js2-ast-root-warnings js2-mode-ast)))
1155 :help "Move to next warning or error"))
1156
1157 (define-key map [menu-bar javascript display-errors]
1158 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1159 :visible (not js2-mode-show-parse-errors)
1160 :help "Turn on display of warnings and errors"))
1161
1162 (define-key map [menu-bar javascript hide-errors]
1163 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1164 :visible js2-mode-show-parse-errors
1165 :help "Turn off display of warnings and errors"))
1166
1167 (define-key map [menu-bar javascript separator-1]
1168 '("--"))
1169
1170 (define-key map [menu-bar javascript js2-toggle-function]
1171 '(menu-item "Show/collapse element" js2-mode-toggle-element
1172 :help "Hide or show function body or comment"))
1173
1174 (define-key map [menu-bar javascript show-comments]
1175 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1176 :visible js2-mode-comments-hidden
1177 :help "Expand all hidden block comments"))
1178
1179 (define-key map [menu-bar javascript hide-comments]
1180 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1181 :visible (not js2-mode-comments-hidden)
1182 :help "Show block comments as /*...*/"))
1183
1184 (define-key map [menu-bar javascript show-all-functions]
1185 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1186 :visible js2-mode-functions-hidden
1187 :help "Expand all hidden function bodies"))
1188
1189 (define-key map [menu-bar javascript hide-all-functions]
1190 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1191 :visible (not js2-mode-functions-hidden)
1192 :help "Show {...} for all top-level function bodies"))
1193
1194 map)
1195 "Keymap used in `js2-mode' buffers.")
1196
1197 (defcustom js2-bounce-indent-p nil
1198 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1199 They will augment the default indent-line behavior with cycling
1200 among several computed alternatives. See the function
1201 `js2-bounce-indent' for details. The above commands will be
1202 bound to TAB and backtab."
1203 :type 'boolean
1204 :group 'js2-mode
1205 :set (lambda (sym value)
1206 (set-default sym value)
1207 (let ((map js2-mode-map))
1208 (if (not value)
1209 (progn
1210 (define-key map "\t" nil)
1211 (define-key map (kbd "<backtab>") nil))
1212 (define-key map "\t" #'js2-indent-bounce)
1213 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1214
1215 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1216
1217 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1218 "Matches a //-comment line. Must be first non-whitespace on line.
1219 First match-group is the leading whitespace.")
1220
1221 (defvar js2-mode-hook nil)
1222
1223 (js2-deflocal js2-mode-ast nil "Private variable.")
1224 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1225 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1226 (js2-deflocal js2-mode-parsing nil "Private variable.")
1227 (js2-deflocal js2-mode-node-overlay nil)
1228
1229 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1230 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1231
1232 (js2-deflocal js2-mode-fontifications nil "Private variable")
1233 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1234 (js2-deflocal js2-imenu-recorder nil "Private variable")
1235 (js2-deflocal js2-imenu-function-map nil "Private variable")
1236
1237 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1238 "Non-nil to emit status messages during parsing.")
1239
1240 (defvar js2-mode-functions-hidden nil "Private variable.")
1241 (defvar js2-mode-comments-hidden nil "Private variable.")
1242
1243 (defvar js2-mode-syntax-table
1244 (let ((table (make-syntax-table)))
1245 (c-populate-syntax-table table)
1246 (modify-syntax-entry ?` "\"" table)
1247 table)
1248 "Syntax table used in `js2-mode' buffers.")
1249
1250 (defvar js2-mode-abbrev-table nil
1251 "Abbrev table in use in `js2-mode' buffers.")
1252 (define-abbrev-table 'js2-mode-abbrev-table ())
1253
1254 (defvar js2-mode-pending-parse-callbacks nil
1255 "List of functions waiting to be notified that parse is finished.")
1256
1257 (defvar js2-mode-last-indented-line -1)
1258
1259 ;;; Localizable error and warning messages
1260
1261 ;; Messages are copied from Rhino's Messages.properties.
1262 ;; Many of the Java-specific messages have been elided.
1263 ;; Add any js2-specific ones at the end, so we can keep
1264 ;; this file synced with changes to Rhino's.
1265
1266 (defvar js2-message-table
1267 (make-hash-table :test 'equal :size 250)
1268 "Contains localized messages for `js2-mode'.")
1269
1270 ;; TODO(stevey): construct this table at compile-time.
1271 (defmacro js2-msg (key &rest strings)
1272 `(puthash ,key (concat ,@strings)
1273 js2-message-table))
1274
1275 (defun js2-get-msg (msg-key)
1276 "Look up a localized message.
1277 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1278 the correct number of ARGS must be provided."
1279 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1280 (args (if (listp msg-key) (cdr msg-key)))
1281 (msg (gethash key js2-message-table)))
1282 (if msg
1283 (apply #'format msg args)
1284 key))) ; default to showing the key
1285
1286 (js2-msg "msg.dup.parms"
1287 "Duplicate parameter name '%s'.")
1288
1289 (js2-msg "msg.too.big.jump"
1290 "Program too complex: jump offset too big.")
1291
1292 (js2-msg "msg.too.big.index"
1293 "Program too complex: internal index exceeds 64K limit.")
1294
1295 (js2-msg "msg.while.compiling.fn"
1296 "Encountered code generation error while compiling function '%s': %s")
1297
1298 (js2-msg "msg.while.compiling.script"
1299 "Encountered code generation error while compiling script: %s")
1300
1301 ;; Context
1302 (js2-msg "msg.ctor.not.found"
1303 "Constructor for '%s' not found.")
1304
1305 (js2-msg "msg.not.ctor"
1306 "'%s' is not a constructor.")
1307
1308 ;; FunctionObject
1309 (js2-msg "msg.varargs.ctor"
1310 "Method or constructor '%s' must be static "
1311 "with the signature (Context cx, Object[] args, "
1312 "Function ctorObj, boolean inNewExpr) "
1313 "to define a variable arguments constructor.")
1314
1315 (js2-msg "msg.varargs.fun"
1316 "Method '%s' must be static with the signature "
1317 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1318 "to define a variable arguments function.")
1319
1320 (js2-msg "msg.incompat.call"
1321 "Method '%s' called on incompatible object.")
1322
1323 (js2-msg "msg.bad.parms"
1324 "Unsupported parameter type '%s' in method '%s'.")
1325
1326 (js2-msg "msg.bad.method.return"
1327 "Unsupported return type '%s' in method '%s'.")
1328
1329 (js2-msg "msg.bad.ctor.return"
1330 "Construction of objects of type '%s' is not supported.")
1331
1332 (js2-msg "msg.no.overload"
1333 "Method '%s' occurs multiple times in class '%s'.")
1334
1335 (js2-msg "msg.method.not.found"
1336 "Method '%s' not found in '%s'.")
1337
1338 ;; IRFactory
1339
1340 (js2-msg "msg.bad.for.in.lhs"
1341 "Invalid left-hand side of for..in loop.")
1342
1343 (js2-msg "msg.mult.index"
1344 "Only one variable allowed in for..in loop.")
1345
1346 (js2-msg "msg.bad.for.in.destruct"
1347 "Left hand side of for..in loop must be an array of "
1348 "length 2 to accept key/value pair.")
1349
1350 (js2-msg "msg.cant.convert"
1351 "Can't convert to type '%s'.")
1352
1353 (js2-msg "msg.bad.assign.left"
1354 "Invalid assignment left-hand side.")
1355
1356 (js2-msg "msg.bad.decr"
1357 "Invalid decrement operand.")
1358
1359 (js2-msg "msg.bad.incr"
1360 "Invalid increment operand.")
1361
1362 (js2-msg "msg.bad.yield"
1363 "yield must be in a function.")
1364
1365 (js2-msg "msg.yield.parenthesized"
1366 "yield expression must be parenthesized.")
1367
1368 (js2-msg "msg.bad.await"
1369 "await must be in async functions.")
1370
1371 ;; NativeGlobal
1372 (js2-msg "msg.cant.call.indirect"
1373 "Function '%s' must be called directly, and not by way of a "
1374 "function of another name.")
1375
1376 (js2-msg "msg.eval.nonstring"
1377 "Calling eval() with anything other than a primitive "
1378 "string value will simply return the value. "
1379 "Is this what you intended?")
1380
1381 (js2-msg "msg.eval.nonstring.strict"
1382 "Calling eval() with anything other than a primitive "
1383 "string value is not allowed in strict mode.")
1384
1385 (js2-msg "msg.bad.destruct.op"
1386 "Invalid destructuring assignment operator")
1387
1388 ;; NativeCall
1389 (js2-msg "msg.only.from.new"
1390 "'%s' may only be invoked from a `new' expression.")
1391
1392 (js2-msg "msg.deprec.ctor"
1393 "The '%s' constructor is deprecated.")
1394
1395 ;; NativeFunction
1396 (js2-msg "msg.no.function.ref.found"
1397 "no source found to decompile function reference %s")
1398
1399 (js2-msg "msg.arg.isnt.array"
1400 "second argument to Function.prototype.apply must be an array")
1401
1402 ;; NativeGlobal
1403 (js2-msg "msg.bad.esc.mask"
1404 "invalid string escape mask")
1405
1406 ;; NativeRegExp
1407 (js2-msg "msg.bad.quant"
1408 "Invalid quantifier %s")
1409
1410 (js2-msg "msg.overlarge.backref"
1411 "Overly large back reference %s")
1412
1413 (js2-msg "msg.overlarge.min"
1414 "Overly large minimum %s")
1415
1416 (js2-msg "msg.overlarge.max"
1417 "Overly large maximum %s")
1418
1419 (js2-msg "msg.zero.quant"
1420 "Zero quantifier %s")
1421
1422 (js2-msg "msg.max.lt.min"
1423 "Maximum %s less than minimum")
1424
1425 (js2-msg "msg.unterm.quant"
1426 "Unterminated quantifier %s")
1427
1428 (js2-msg "msg.unterm.paren"
1429 "Unterminated parenthetical %s")
1430
1431 (js2-msg "msg.unterm.class"
1432 "Unterminated character class %s")
1433
1434 (js2-msg "msg.bad.range"
1435 "Invalid range in character class.")
1436
1437 (js2-msg "msg.trail.backslash"
1438 "Trailing \\ in regular expression.")
1439
1440 (js2-msg "msg.re.unmatched.right.paren"
1441 "unmatched ) in regular expression.")
1442
1443 (js2-msg "msg.no.regexp"
1444 "Regular expressions are not available.")
1445
1446 (js2-msg "msg.bad.backref"
1447 "back-reference exceeds number of capturing parentheses.")
1448
1449 (js2-msg "msg.bad.regexp.compile"
1450 "Only one argument may be specified if the first "
1451 "argument to RegExp.prototype.compile is a RegExp object.")
1452
1453 ;; Parser
1454 (js2-msg "msg.got.syntax.errors"
1455 "Compilation produced %s syntax errors.")
1456
1457 (js2-msg "msg.var.redecl"
1458 "TypeError: redeclaration of var %s.")
1459
1460 (js2-msg "msg.const.redecl"
1461 "TypeError: redeclaration of const %s.")
1462
1463 (js2-msg "msg.let.redecl"
1464 "TypeError: redeclaration of variable %s.")
1465
1466 (js2-msg "msg.parm.redecl"
1467 "TypeError: redeclaration of formal parameter %s.")
1468
1469 (js2-msg "msg.fn.redecl"
1470 "TypeError: redeclaration of function %s.")
1471
1472 (js2-msg "msg.let.decl.not.in.block"
1473 "SyntaxError: let declaration not directly within block")
1474
1475 (js2-msg "msg.mod.import.decl.at.top.level"
1476 "SyntaxError: import declarations may only appear at the top level")
1477
1478 (js2-msg "msg.mod.as.after.reserved.word"
1479 "SyntaxError: missing keyword 'as' after reserved word %s")
1480
1481 (js2-msg "msg.mod.rc.after.import.spec.list"
1482 "SyntaxError: missing '}' after module specifier list")
1483
1484 (js2-msg "msg.mod.from.after.import.spec.set"
1485 "SyntaxError: missing keyword 'from' after import specifier set")
1486
1487 (js2-msg "msg.mod.declaration.after.import"
1488 "SyntaxError: missing declaration after 'import' keyword")
1489
1490 (js2-msg "msg.mod.spec.after.from"
1491 "SyntaxError: missing module specifier after 'from' keyword")
1492
1493 (js2-msg "msg.mod.export.decl.at.top.level"
1494 "SyntaxError: export declarations may only appear at top level")
1495
1496 (js2-msg "msg.mod.rc.after.export.spec.list"
1497 "SyntaxError: missing '}' after export specifier list")
1498
1499 ;; NodeTransformer
1500 (js2-msg "msg.dup.label"
1501 "duplicated label")
1502
1503 (js2-msg "msg.undef.label"
1504 "undefined label")
1505
1506 (js2-msg "msg.bad.break"
1507 "unlabelled break must be inside loop or switch")
1508
1509 (js2-msg "msg.continue.outside"
1510 "continue must be inside loop")
1511
1512 (js2-msg "msg.continue.nonloop"
1513 "continue can only use labels of iteration statements")
1514
1515 (js2-msg "msg.bad.throw.eol"
1516 "Line terminator is not allowed between the throw "
1517 "keyword and throw expression.")
1518
1519 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1520 "function statement requires a name")
1521
1522 (js2-msg "msg.no.paren.parms"
1523 "missing ( before function parameters.")
1524
1525 (js2-msg "msg.no.parm"
1526 "missing formal parameter")
1527
1528 (js2-msg "msg.no.paren.after.parms"
1529 "missing ) after formal parameters")
1530
1531 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1532 "parameter without default follows parameter with default")
1533
1534 (js2-msg "msg.param.after.rest" ; added by js2-mode
1535 "parameter after rest parameter")
1536
1537 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1538 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1539
1540 (js2-msg "msg.no.brace.body"
1541 "missing '{' before function body")
1542
1543 (js2-msg "msg.no.brace.after.body"
1544 "missing } after function body")
1545
1546 (js2-msg "msg.no.paren.cond"
1547 "missing ( before condition")
1548
1549 (js2-msg "msg.no.paren.after.cond"
1550 "missing ) after condition")
1551
1552 (js2-msg "msg.no.semi.stmt"
1553 "missing ; before statement")
1554
1555 (js2-msg "msg.missing.semi"
1556 "missing ; after statement")
1557
1558 (js2-msg "msg.no.name.after.dot"
1559 "missing name after . operator")
1560
1561 (js2-msg "msg.no.name.after.coloncolon"
1562 "missing name after :: operator")
1563
1564 (js2-msg "msg.no.name.after.dotdot"
1565 "missing name after .. operator")
1566
1567 (js2-msg "msg.no.name.after.xmlAttr"
1568 "missing name after .@")
1569
1570 (js2-msg "msg.no.bracket.index"
1571 "missing ] in index expression")
1572
1573 (js2-msg "msg.no.paren.switch"
1574 "missing ( before switch expression")
1575
1576 (js2-msg "msg.no.paren.after.switch"
1577 "missing ) after switch expression")
1578
1579 (js2-msg "msg.no.brace.switch"
1580 "missing '{' before switch body")
1581
1582 (js2-msg "msg.bad.switch"
1583 "invalid switch statement")
1584
1585 (js2-msg "msg.no.colon.case"
1586 "missing : after case expression")
1587
1588 (js2-msg "msg.double.switch.default"
1589 "double default label in the switch statement")
1590
1591 (js2-msg "msg.no.while.do"
1592 "missing while after do-loop body")
1593
1594 (js2-msg "msg.no.paren.for"
1595 "missing ( after for")
1596
1597 (js2-msg "msg.no.semi.for"
1598 "missing ; after for-loop initializer")
1599
1600 (js2-msg "msg.no.semi.for.cond"
1601 "missing ; after for-loop condition")
1602
1603 (js2-msg "msg.in.after.for.name"
1604 "missing in or of after for")
1605
1606 (js2-msg "msg.no.paren.for.ctrl"
1607 "missing ) after for-loop control")
1608
1609 (js2-msg "msg.no.paren.with"
1610 "missing ( before with-statement object")
1611
1612 (js2-msg "msg.no.paren.after.with"
1613 "missing ) after with-statement object")
1614
1615 (js2-msg "msg.no.with.strict"
1616 "with statements not allowed in strict mode")
1617
1618 (js2-msg "msg.no.paren.after.let"
1619 "missing ( after let")
1620
1621 (js2-msg "msg.no.paren.let"
1622 "missing ) after variable list")
1623
1624 (js2-msg "msg.no.curly.let"
1625 "missing } after let statement")
1626
1627 (js2-msg "msg.bad.return"
1628 "invalid return")
1629
1630 (js2-msg "msg.no.brace.block"
1631 "missing } in compound statement")
1632
1633 (js2-msg "msg.bad.label"
1634 "invalid label")
1635
1636 (js2-msg "msg.bad.var"
1637 "missing variable name")
1638
1639 (js2-msg "msg.bad.var.init"
1640 "invalid variable initialization")
1641
1642 (js2-msg "msg.no.colon.cond"
1643 "missing : in conditional expression")
1644
1645 (js2-msg "msg.no.paren.arg"
1646 "missing ) after argument list")
1647
1648 (js2-msg "msg.no.bracket.arg"
1649 "missing ] after element list")
1650
1651 (js2-msg "msg.bad.prop"
1652 "invalid property id")
1653
1654 (js2-msg "msg.no.colon.prop"
1655 "missing : after property id")
1656
1657 (js2-msg "msg.no.brace.prop"
1658 "missing } after property list")
1659
1660 (js2-msg "msg.no.paren"
1661 "missing ) in parenthetical")
1662
1663 (js2-msg "msg.reserved.id"
1664 "'%s' is a reserved identifier")
1665
1666 (js2-msg "msg.no.paren.catch"
1667 "missing ( before catch-block condition")
1668
1669 (js2-msg "msg.bad.catchcond"
1670 "invalid catch block condition")
1671
1672 (js2-msg "msg.catch.unreachable"
1673 "any catch clauses following an unqualified catch are unreachable")
1674
1675 (js2-msg "msg.no.brace.try"
1676 "missing '{' before try block")
1677
1678 (js2-msg "msg.no.brace.catchblock"
1679 "missing '{' before catch-block body")
1680
1681 (js2-msg "msg.try.no.catchfinally"
1682 "'try' without 'catch' or 'finally'")
1683
1684 (js2-msg "msg.no.return.value"
1685 "function %s does not always return a value")
1686
1687 (js2-msg "msg.anon.no.return.value"
1688 "anonymous function does not always return a value")
1689
1690 (js2-msg "msg.return.inconsistent"
1691 "return statement is inconsistent with previous usage")
1692
1693 (js2-msg "msg.generator.returns"
1694 "TypeError: legacy generator function '%s' returns a value")
1695
1696 (js2-msg "msg.anon.generator.returns"
1697 "TypeError: anonymous legacy generator function returns a value")
1698
1699 (js2-msg "msg.syntax"
1700 "syntax error")
1701
1702 (js2-msg "msg.unexpected.eof"
1703 "Unexpected end of file")
1704
1705 (js2-msg "msg.XML.bad.form"
1706 "illegally formed XML syntax")
1707
1708 (js2-msg "msg.XML.not.available"
1709 "XML runtime not available")
1710
1711 (js2-msg "msg.too.deep.parser.recursion"
1712 "Too deep recursion while parsing")
1713
1714 (js2-msg "msg.no.side.effects"
1715 "Code has no side effects")
1716
1717 (js2-msg "msg.extra.trailing.comma"
1718 "Trailing comma is not supported in some browsers")
1719
1720 (js2-msg "msg.array.trailing.comma"
1721 "Trailing comma yields different behavior across browsers")
1722
1723 (js2-msg "msg.equal.as.assign"
1724 (concat "Test for equality (==) mistyped as assignment (=)?"
1725 " (parenthesize to suppress warning)"))
1726
1727 (js2-msg "msg.var.hides.arg"
1728 "Variable %s hides argument")
1729
1730 (js2-msg "msg.destruct.assign.no.init"
1731 "Missing = in destructuring declaration")
1732
1733 (js2-msg "msg.init.no.destruct"
1734 "Binding initializer not in destructuring assignment")
1735
1736 (js2-msg "msg.no.octal.strict"
1737 "Octal numbers prohibited in strict mode.")
1738
1739 (js2-msg "msg.dup.obj.lit.prop.strict"
1740 "Property '%s' already defined in this object literal.")
1741
1742 (js2-msg "msg.dup.param.strict"
1743 "Parameter '%s' already declared in this function.")
1744
1745 (js2-msg "msg.bad.id.strict"
1746 "'%s' is not a valid identifier for this use in strict mode.")
1747
1748 ;; ScriptRuntime
1749 (js2-msg "msg.no.properties"
1750 "%s has no properties.")
1751
1752 (js2-msg "msg.invalid.iterator"
1753 "Invalid iterator value")
1754
1755 (js2-msg "msg.iterator.primitive"
1756 "__iterator__ returned a primitive value")
1757
1758 (js2-msg "msg.assn.create.strict"
1759 "Assignment to undeclared variable %s")
1760
1761 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1762 "Undeclared variable or function '%s'")
1763
1764 (js2-msg "msg.unused.variable" ; added by js2-mode
1765 "Unused variable or function '%s'")
1766
1767 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1768 "Variable '%s' referenced but never initialized")
1769
1770 (js2-msg "msg.ref.undefined.prop"
1771 "Reference to undefined property '%s'")
1772
1773 (js2-msg "msg.prop.not.found"
1774 "Property %s not found.")
1775
1776 (js2-msg "msg.invalid.type"
1777 "Invalid JavaScript value of type %s")
1778
1779 (js2-msg "msg.primitive.expected"
1780 "Primitive type expected (had %s instead)")
1781
1782 (js2-msg "msg.namespace.expected"
1783 "Namespace object expected to left of :: (found %s instead)")
1784
1785 (js2-msg "msg.null.to.object"
1786 "Cannot convert null to an object.")
1787
1788 (js2-msg "msg.undef.to.object"
1789 "Cannot convert undefined to an object.")
1790
1791 (js2-msg "msg.cyclic.value"
1792 "Cyclic %s value not allowed.")
1793
1794 (js2-msg "msg.is.not.defined"
1795 "'%s' is not defined.")
1796
1797 (js2-msg "msg.undef.prop.read"
1798 "Cannot read property '%s' from %s")
1799
1800 (js2-msg "msg.undef.prop.write"
1801 "Cannot set property '%s' of %s to '%s'")
1802
1803 (js2-msg "msg.undef.prop.delete"
1804 "Cannot delete property '%s' of %s")
1805
1806 (js2-msg "msg.undef.method.call"
1807 "Cannot call method '%s' of %s")
1808
1809 (js2-msg "msg.undef.with"
1810 "Cannot apply 'with' to %s")
1811
1812 (js2-msg "msg.isnt.function"
1813 "%s is not a function, it is %s.")
1814
1815 (js2-msg "msg.isnt.function.in"
1816 "Cannot call property %s in object %s. "
1817 "It is not a function, it is '%s'.")
1818
1819 (js2-msg "msg.function.not.found"
1820 "Cannot find function %s.")
1821
1822 (js2-msg "msg.function.not.found.in"
1823 "Cannot find function %s in object %s.")
1824
1825 (js2-msg "msg.isnt.xml.object"
1826 "%s is not an xml object.")
1827
1828 (js2-msg "msg.no.ref.to.get"
1829 "%s is not a reference to read reference value.")
1830
1831 (js2-msg "msg.no.ref.to.set"
1832 "%s is not a reference to set reference value to %s.")
1833
1834 (js2-msg "msg.no.ref.from.function"
1835 "Function %s can not be used as the left-hand "
1836 "side of assignment or as an operand of ++ or -- operator.")
1837
1838 (js2-msg "msg.bad.default.value"
1839 "Object's getDefaultValue() method returned an object.")
1840
1841 (js2-msg "msg.instanceof.not.object"
1842 "Can't use instanceof on a non-object.")
1843
1844 (js2-msg "msg.instanceof.bad.prototype"
1845 "'prototype' property of %s is not an object.")
1846
1847 (js2-msg "msg.bad.radix"
1848 "illegal radix %s.")
1849
1850 ;; ScriptableObject
1851 (js2-msg "msg.default.value"
1852 "Cannot find default value for object.")
1853
1854 (js2-msg "msg.zero.arg.ctor"
1855 "Cannot load class '%s' which has no zero-parameter constructor.")
1856
1857 (js2-msg "msg.ctor.multiple.parms"
1858 "Can't define constructor or class %s since more than "
1859 "one constructor has multiple parameters.")
1860
1861 (js2-msg "msg.extend.scriptable"
1862 "%s must extend ScriptableObject in order to define property %s.")
1863
1864 (js2-msg "msg.bad.getter.parms"
1865 "In order to define a property, getter %s must have zero "
1866 "parameters or a single ScriptableObject parameter.")
1867
1868 (js2-msg "msg.obj.getter.parms"
1869 "Expected static or delegated getter %s to take "
1870 "a ScriptableObject parameter.")
1871
1872 (js2-msg "msg.getter.static"
1873 "Getter and setter must both be static or neither be static.")
1874
1875 (js2-msg "msg.setter.return"
1876 "Setter must have void return type: %s")
1877
1878 (js2-msg "msg.setter2.parms"
1879 "Two-parameter setter must take a ScriptableObject as "
1880 "its first parameter.")
1881
1882 (js2-msg "msg.setter1.parms"
1883 "Expected single parameter setter for %s")
1884
1885 (js2-msg "msg.setter2.expected"
1886 "Expected static or delegated setter %s to take two parameters.")
1887
1888 (js2-msg "msg.setter.parms"
1889 "Expected either one or two parameters for setter.")
1890
1891 (js2-msg "msg.setter.bad.type"
1892 "Unsupported parameter type '%s' in setter '%s'.")
1893
1894 (js2-msg "msg.add.sealed"
1895 "Cannot add a property to a sealed object: %s.")
1896
1897 (js2-msg "msg.remove.sealed"
1898 "Cannot remove a property from a sealed object: %s.")
1899
1900 (js2-msg "msg.modify.sealed"
1901 "Cannot modify a property of a sealed object: %s.")
1902
1903 (js2-msg "msg.modify.readonly"
1904 "Cannot modify readonly property: %s.")
1905
1906 ;; TokenStream
1907 (js2-msg "msg.missing.exponent"
1908 "missing exponent")
1909
1910 (js2-msg "msg.caught.nfe"
1911 "number format error")
1912
1913 (js2-msg "msg.unterminated.string.lit"
1914 "unterminated string literal")
1915
1916 (js2-msg "msg.unterminated.comment"
1917 "unterminated comment")
1918
1919 (js2-msg "msg.unterminated.re.lit"
1920 "unterminated regular expression literal")
1921
1922 (js2-msg "msg.invalid.re.flag"
1923 "invalid flag after regular expression")
1924
1925 (js2-msg "msg.no.re.input.for"
1926 "no input for %s")
1927
1928 (js2-msg "msg.illegal.character"
1929 "illegal character")
1930
1931 (js2-msg "msg.invalid.escape"
1932 "invalid Unicode escape sequence")
1933
1934 (js2-msg "msg.bad.namespace"
1935 "not a valid default namespace statement. "
1936 "Syntax is: default xml namespace = EXPRESSION;")
1937
1938 ;; TokensStream warnings
1939 (js2-msg "msg.bad.octal.literal"
1940 "illegal octal literal digit %s; "
1941 "interpreting it as a decimal digit")
1942
1943 (js2-msg "msg.missing.hex.digits"
1944 "missing hexadecimal digits after '0x'")
1945
1946 (js2-msg "msg.missing.binary.digits"
1947 "missing binary digits after '0b'")
1948
1949 (js2-msg "msg.missing.octal.digits"
1950 "missing octal digits after '0o'")
1951
1952 (js2-msg "msg.script.is.not.constructor"
1953 "Script objects are not constructors.")
1954
1955 ;; Arrays
1956 (js2-msg "msg.arraylength.bad"
1957 "Inappropriate array length.")
1958
1959 ;; Arrays
1960 (js2-msg "msg.arraylength.too.big"
1961 "Array length %s exceeds supported capacity limit.")
1962
1963 ;; URI
1964 (js2-msg "msg.bad.uri"
1965 "Malformed URI sequence.")
1966
1967 ;; Number
1968 (js2-msg "msg.bad.precision"
1969 "Precision %s out of range.")
1970
1971 ;; NativeGenerator
1972 (js2-msg "msg.send.newborn"
1973 "Attempt to send value to newborn generator")
1974
1975 (js2-msg "msg.already.exec.gen"
1976 "Already executing generator")
1977
1978 (js2-msg "msg.StopIteration.invalid"
1979 "StopIteration may not be changed to an arbitrary object.")
1980
1981 ;; Interpreter
1982 (js2-msg "msg.yield.closing"
1983 "Yield from closing generator")
1984
1985 ;; Classes
1986 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1987 "class statement requires a name")
1988
1989 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1990 "unexpected ',' between class properties")
1991
1992 (js2-msg "msg.unexpected.static" ; added by js2-mode
1993 "unexpected 'static'")
1994
1995 (js2-msg "msg.missing.extends" ; added by js2-mode
1996 "name is required after extends")
1997
1998 (js2-msg "msg.no.brace.class" ; added by js2-mode
1999 "missing '{' before class body")
2000
2001 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2002 "missing ']' after computed property expression")
2003
2004 ;;; Tokens Buffer
2005
2006 (defconst js2-ti-max-lookahead 2)
2007 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2008
2009 (defun js2-new-token (offset)
2010 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2011 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2012 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2013 token))
2014
2015 (defsubst js2-current-token ()
2016 (aref js2-ti-tokens js2-ti-tokens-cursor))
2017
2018 (defsubst js2-current-token-string ()
2019 (js2-token-string (js2-current-token)))
2020
2021 (defsubst js2-current-token-type ()
2022 (js2-token-type (js2-current-token)))
2023
2024 (defsubst js2-current-token-beg ()
2025 (js2-token-beg (js2-current-token)))
2026
2027 (defsubst js2-current-token-end ()
2028 (js2-token-end (js2-current-token)))
2029
2030 (defun js2-current-token-len ()
2031 (let ((token (js2-current-token)))
2032 (- (js2-token-end token)
2033 (js2-token-beg token))))
2034
2035 (defun js2-ts-seek (state)
2036 (setq js2-ts-lineno (js2-ts-state-lineno state)
2037 js2-ts-cursor (js2-ts-state-cursor state)
2038 js2-ti-tokens (js2-ts-state-tokens state)
2039 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2040 js2-ti-lookahead (js2-ts-state-lookahead state)))
2041
2042 ;;; Utilities
2043
2044 (defun js2-delete-if (predicate list)
2045 "Remove all items satisfying PREDICATE in LIST."
2046 (cl-loop for item in list
2047 if (not (funcall predicate item))
2048 collect item))
2049
2050 (defun js2-position (element list)
2051 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2052 Returns nil if element is not found in the list."
2053 (let ((count 0)
2054 found)
2055 (while (and list (not found))
2056 (if (eq element (car list))
2057 (setq found t)
2058 (setq count (1+ count)
2059 list (cdr list))))
2060 (if found count)))
2061
2062 (defun js2-find-if (predicate list)
2063 "Find first item satisfying PREDICATE in LIST."
2064 (let (result)
2065 (while (and list (not result))
2066 (if (funcall predicate (car list))
2067 (setq result (car list)))
2068 (setq list (cdr list)))
2069 result))
2070
2071 (defmacro js2-time (form)
2072 "Evaluate FORM, discard result, and return elapsed time in sec."
2073 (declare (debug t))
2074 (let ((beg (make-symbol "--js2-time-beg--")))
2075 `(let ((,beg (current-time)))
2076 ,form
2077 (/ (truncate (* (- (float-time (current-time))
2078 (float-time ,beg))
2079 10000))
2080 10000.0))))
2081
2082 (defsubst js2-same-line (pos)
2083 "Return t if POS is on the same line as current point."
2084 (and (>= pos (point-at-bol))
2085 (<= pos (point-at-eol))))
2086
2087 (defun js2-code-bug ()
2088 "Signal an error when we encounter an unexpected code path."
2089 (error "failed assertion"))
2090
2091 (defsubst js2-record-text-property (beg end prop value)
2092 "Record a text property to set when parsing finishes."
2093 (push (list beg end prop value) js2-mode-deferred-properties))
2094
2095 ;; I'd like to associate errors with nodes, but for now the
2096 ;; easiest thing to do is get the context info from the last token.
2097 (defun js2-record-parse-error (msg &optional arg pos len)
2098 (push (list (list msg arg)
2099 (or pos (js2-current-token-beg))
2100 (or len (js2-current-token-len)))
2101 js2-parsed-errors))
2102
2103 (defun js2-report-error (msg &optional msg-arg pos len)
2104 "Signal a syntax error or record a parse error."
2105 (if js2-recover-from-parse-errors
2106 (js2-record-parse-error msg msg-arg pos len)
2107 (signal 'js2-syntax-error
2108 (list msg
2109 js2-ts-lineno
2110 (save-excursion
2111 (goto-char js2-ts-cursor)
2112 (current-column))
2113 js2-ts-hit-eof))))
2114
2115 (defun js2-report-warning (msg &optional msg-arg pos len face)
2116 (if js2-compiler-report-warning-as-error
2117 (js2-report-error msg msg-arg pos len)
2118 (push (list (list msg msg-arg)
2119 (or pos (js2-current-token-beg))
2120 (or len (js2-current-token-len))
2121 face)
2122 js2-parsed-warnings)))
2123
2124 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2125 (if js2-compiler-strict-mode
2126 (js2-report-warning msg-id msg-arg beg
2127 (and beg end (- end beg)))))
2128
2129 (put 'js2-syntax-error 'error-conditions
2130 '(error syntax-error js2-syntax-error))
2131 (put 'js2-syntax-error 'error-message "Syntax error")
2132
2133 (put 'js2-parse-error 'error-conditions
2134 '(error parse-error js2-parse-error))
2135 (put 'js2-parse-error 'error-message "Parse error")
2136
2137 (defmacro js2-clear-flag (flags flag)
2138 `(setq ,flags (logand ,flags (lognot ,flag))))
2139
2140 (defmacro js2-set-flag (flags flag)
2141 "Logical-or FLAG into FLAGS."
2142 `(setq ,flags (logior ,flags ,flag)))
2143
2144 (defsubst js2-flag-set-p (flags flag)
2145 (/= 0 (logand flags flag)))
2146
2147 (defsubst js2-flag-not-set-p (flags flag)
2148 (zerop (logand flags flag)))
2149
2150 ;;; AST struct and function definitions
2151
2152 ;; flags for ast node property 'member-type (used for e4x operators)
2153 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2154 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2155 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2156
2157 (defsubst js2-relpos (pos anchor)
2158 "Convert POS to be relative to ANCHOR.
2159 If POS is nil, returns nil."
2160 (and pos (- pos anchor)))
2161
2162 (defun js2-make-pad (indent)
2163 (if (zerop indent)
2164 ""
2165 (make-string (* indent js2-basic-offset) ? )))
2166
2167 (defun js2-visit-ast (node callback)
2168 "Visit every node in ast NODE with visitor CALLBACK.
2169
2170 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2171 called twice: once to visit the node, and again after all the node's
2172 children have been processed. The END-P argument is nil on the first
2173 call and non-nil on the second call. The return value of the callback
2174 affects the traversal: if non-nil, the children of NODE are processed.
2175 If the callback returns nil, or if the node has no children, then the
2176 callback is called immediately with a non-nil END-P argument.
2177
2178 The node traversal is approximately lexical-order, although there
2179 are currently no guarantees around this."
2180 (when node
2181 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2182 ;; visit the node
2183 (when (funcall callback node nil)
2184 ;; visit the kids
2185 (cond
2186 ((eq vfunc 'js2-visit-none)
2187 nil) ; don't even bother calling it
2188 ;; Each AST node type has to define a `js2-visitor' function
2189 ;; that takes a node and a callback, and calls `js2-visit-ast'
2190 ;; on each child of the node.
2191 (vfunc
2192 (funcall vfunc node callback))
2193 (t
2194 (error "%s does not define a visitor-traversal function"
2195 (aref node 0)))))
2196 ;; call the end-visit
2197 (funcall callback node t))))
2198
2199 (cl-defstruct (js2-node
2200 (:constructor nil)) ; abstract
2201 "Base AST node type."
2202 (type -1) ; token type
2203 (pos -1) ; start position of this AST node in parsed input
2204 (len 1) ; num characters spanned by the node
2205 props ; optional node property list (an alist)
2206 parent) ; link to parent node; null for root
2207
2208 (defsubst js2-node-get-prop (node prop &optional default)
2209 (or (cadr (assoc prop (js2-node-props node))) default))
2210
2211 (defsubst js2-node-set-prop (node prop value)
2212 (setf (js2-node-props node)
2213 (cons (list prop value) (js2-node-props node))))
2214
2215 (defun js2-fixup-starts (n nodes)
2216 "Adjust the start positions of NODES to be relative to N.
2217 Any node in the list may be nil, for convenience."
2218 (dolist (node nodes)
2219 (when node
2220 (setf (js2-node-pos node) (- (js2-node-pos node)
2221 (js2-node-pos n))))))
2222
2223 (defun js2-node-add-children (parent &rest nodes)
2224 "Set parent node of NODES to PARENT, and return PARENT.
2225 Does nothing if we're not recording parent links.
2226 If any given node in NODES is nil, doesn't record that link."
2227 (js2-fixup-starts parent nodes)
2228 (dolist (node nodes)
2229 (and node
2230 (setf (js2-node-parent node) parent))))
2231
2232 ;; Non-recursive since it's called a frightening number of times.
2233 (defun js2-node-abs-pos (n)
2234 (let ((pos (js2-node-pos n)))
2235 (while (setq n (js2-node-parent n))
2236 (setq pos (+ pos (js2-node-pos n))))
2237 pos))
2238
2239 (defsubst js2-node-abs-end (n)
2240 "Return absolute buffer position of end of N."
2241 (+ (js2-node-abs-pos n) (js2-node-len n)))
2242
2243 ;; It's important to make sure block nodes have a Lisp list for the
2244 ;; child nodes, to limit printing recursion depth in an AST that
2245 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2246 ;; a sufficiently large vector tree.
2247
2248 (cl-defstruct (js2-block-node
2249 (:include js2-node)
2250 (:constructor nil)
2251 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2252 (pos (js2-current-token-beg))
2253 len
2254 props
2255 kids)))
2256 "A block of statements."
2257 kids) ; a Lisp list of the child statement nodes
2258
2259 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2260 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2261
2262 (defun js2-visit-block (ast callback)
2263 "Visit the `js2-block-node' children of AST."
2264 (dolist (kid (js2-block-node-kids ast))
2265 (js2-visit-ast kid callback)))
2266
2267 (defun js2-print-block (n i)
2268 (let ((pad (js2-make-pad i)))
2269 (insert pad "{\n")
2270 (dolist (kid (js2-block-node-kids n))
2271 (js2-print-ast kid (1+ i)))
2272 (insert pad "}")))
2273
2274 (cl-defstruct (js2-scope
2275 (:include js2-block-node)
2276 (:constructor nil)
2277 (:constructor make-js2-scope (&key (type js2-BLOCK)
2278 (pos (js2-current-token-beg))
2279 len
2280 kids)))
2281 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2282 ;; I don't have one of those handy, so I'll use an alist for now.
2283 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2284 ;; and is much lighter-weight to construct (both CPU and mem).
2285 ;; The keys are interned strings (symbols) for faster lookup.
2286 ;; Should switch to hybrid alist/hashtable eventually.
2287 symbol-table ; an alist of (symbol . js2-symbol)
2288 parent-scope ; a `js2-scope'
2289 top) ; top-level `js2-scope' (script/function)
2290
2291 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2292 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2293
2294 (defun js2-node-get-enclosing-scope (node)
2295 "Return the innermost `js2-scope' node surrounding NODE.
2296 Returns nil if there is no enclosing scope node."
2297 (while (and (setq node (js2-node-parent node))
2298 (not (js2-scope-p node))))
2299 node)
2300
2301 (defun js2-get-defining-scope (scope name &optional point)
2302 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2303 Returns `js2-scope' in which NAME is defined, or nil if not found.
2304
2305 If POINT is non-nil, and if the found declaration type is
2306 `js2-LET', also check that the declaration node is before POINT."
2307 (let ((sym (if (symbolp name)
2308 name
2309 (intern name)))
2310 result
2311 (continue t))
2312 (while (and scope continue)
2313 (if (or
2314 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2315 (and entry
2316 (or (not point)
2317 (not (eq js2-LET (js2-symbol-decl-type entry)))
2318 (>= point
2319 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2320 (and (eq sym 'arguments)
2321 (js2-function-node-p scope)))
2322 (setq continue nil
2323 result scope)
2324 (setq scope (js2-scope-parent-scope scope))))
2325 result))
2326
2327 (defun js2-scope-get-symbol (scope name)
2328 "Return symbol table entry for NAME in SCOPE.
2329 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2330 (and (js2-scope-symbol-table scope)
2331 (cdr (assq (if (symbolp name)
2332 name
2333 (intern name))
2334 (js2-scope-symbol-table scope)))))
2335
2336 (defun js2-scope-put-symbol (scope name symbol)
2337 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2338 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2339 (let* ((table (js2-scope-symbol-table scope))
2340 (sym (if (symbolp name) name (intern name)))
2341 (entry (assq sym table)))
2342 (if entry
2343 (setcdr entry symbol)
2344 (push (cons sym symbol)
2345 (js2-scope-symbol-table scope)))))
2346
2347 (cl-defstruct (js2-symbol
2348 (:constructor nil)
2349 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2350 "A symbol table entry."
2351 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2352 ;; js2-LET, or js2-CONST
2353 decl-type
2354 name ; string
2355 ast-node) ; a `js2-node'
2356
2357 (cl-defstruct (js2-error-node
2358 (:include js2-node)
2359 (:constructor nil) ; silence emacs21 byte-compiler
2360 (:constructor make-js2-error-node (&key (type js2-ERROR)
2361 (pos (js2-current-token-beg))
2362 len)))
2363 "AST node representing a parse error.")
2364
2365 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2366 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2367
2368 (cl-defstruct (js2-script-node
2369 (:include js2-scope)
2370 (:constructor nil)
2371 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2372 (pos (js2-current-token-beg))
2373 len
2374 ;; FIXME: What are those?
2375 var-decls
2376 fun-decls)))
2377 functions ; Lisp list of nested functions
2378 regexps ; Lisp list of (string . flags)
2379 symbols ; alist (every symbol gets unique index)
2380 (param-count 0)
2381 var-names ; vector of string names
2382 consts ; bool-vector matching var-decls
2383 (temp-number 0)) ; for generating temp variables
2384
2385 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2386 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2387
2388 (defun js2-print-script (node indent)
2389 (dolist (kid (js2-block-node-kids node))
2390 (js2-print-ast kid indent)))
2391
2392 (cl-defstruct (js2-ast-root
2393 (:include js2-script-node)
2394 (:constructor nil)
2395 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2396 (pos (js2-current-token-beg))
2397 len
2398 buffer)))
2399 "The root node of a js2 AST."
2400 buffer ; the source buffer from which the code was parsed
2401 comments ; a Lisp list of comments, ordered by start position
2402 errors ; a Lisp list of errors found during parsing
2403 warnings ; a Lisp list of warnings found during parsing
2404 node-count) ; number of nodes in the tree, including the root
2405
2406 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2407 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2408
2409 (defun js2-visit-ast-root (ast callback)
2410 (dolist (kid (js2-ast-root-kids ast))
2411 (js2-visit-ast kid callback))
2412 (dolist (comment (js2-ast-root-comments ast))
2413 (js2-visit-ast comment callback)))
2414
2415 (cl-defstruct (js2-comment-node
2416 (:include js2-node)
2417 (:constructor nil)
2418 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2419 (pos (js2-current-token-beg))
2420 len
2421 format)))
2422 format) ; 'line, 'block, 'jsdoc or 'html
2423
2424 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2425 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2426
2427 (defun js2-print-comment (n i)
2428 ;; We really ought to link end-of-line comments to their nodes.
2429 ;; Or maybe we could add a new comment type, 'endline.
2430 (insert (js2-make-pad i)
2431 (js2-node-string n)))
2432
2433 (cl-defstruct (js2-expr-stmt-node
2434 (:include js2-node)
2435 (:constructor nil)
2436 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2437 (pos js2-ts-cursor)
2438 len
2439 expr)))
2440 "An expression statement."
2441 expr)
2442
2443 (defsubst js2-expr-stmt-node-set-has-result (node)
2444 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2445 (setf (js2-node-type node) js2-EXPR_RESULT))
2446
2447 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2448 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2449
2450 (defun js2-visit-expr-stmt-node (n v)
2451 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2452
2453 (defun js2-print-expr-stmt-node (n indent)
2454 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2455 (insert ";\n"))
2456
2457 (cl-defstruct (js2-loop-node
2458 (:include js2-scope)
2459 (:constructor nil))
2460 "Abstract supertype of loop nodes."
2461 body ; a `js2-block-node'
2462 lp ; position of left-paren, nil if omitted
2463 rp) ; position of right-paren, nil if omitted
2464
2465 (cl-defstruct (js2-do-node
2466 (:include js2-loop-node)
2467 (:constructor nil)
2468 (:constructor make-js2-do-node (&key (type js2-DO)
2469 (pos (js2-current-token-beg))
2470 len
2471 body
2472 condition
2473 while-pos
2474 lp
2475 rp)))
2476 "AST node for do-loop."
2477 condition ; while (expression)
2478 while-pos) ; buffer position of 'while' keyword
2479
2480 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2481 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2482
2483 (defun js2-visit-do-node (n v)
2484 (js2-visit-ast (js2-do-node-body n) v)
2485 (js2-visit-ast (js2-do-node-condition n) v))
2486
2487 (defun js2-print-do-node (n i)
2488 (let ((pad (js2-make-pad i)))
2489 (insert pad "do {\n")
2490 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2491 (js2-print-ast kid (1+ i)))
2492 (insert pad "} while (")
2493 (js2-print-ast (js2-do-node-condition n) 0)
2494 (insert ");\n")))
2495
2496 (cl-defstruct (js2-export-node
2497 (:include js2-node)
2498 (:constructor nil)
2499 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2500 (pos (js2-current-token-beg))
2501 len
2502 exports-list
2503 from-clause
2504 declaration
2505 default)))
2506 "AST node for an export statement. There are many things that can be exported,
2507 so many of its properties will be nil.
2508 "
2509 exports-list ; lisp list of js2-export-binding-node to export
2510 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2511 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2512 default) ; js2-function-node or js2-assign-node
2513
2514 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2515 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2516
2517 (defun js2-visit-export-node (n v)
2518 (let ((exports-list (js2-export-node-exports-list n))
2519 (from (js2-export-node-from-clause n))
2520 (declaration (js2-export-node-declaration n))
2521 (default (js2-export-node-default n)))
2522 (when exports-list
2523 (dolist (export exports-list)
2524 (js2-visit-ast export v)))
2525 (when from
2526 (js2-visit-ast from v))
2527 (when declaration
2528 (js2-visit-ast declaration v))
2529 (when default
2530 (js2-visit-ast default v))))
2531
2532 (defun js2-print-export-node (n i)
2533 (let ((pad (js2-make-pad i))
2534 (exports-list (js2-export-node-exports-list n))
2535 (from (js2-export-node-from-clause n))
2536 (declaration (js2-export-node-declaration n))
2537 (default (js2-export-node-default n)))
2538 (insert pad "export ")
2539 (cond
2540 (default
2541 (insert "default ")
2542 (js2-print-ast default i))
2543 (declaration
2544 (js2-print-ast declaration i))
2545 ((and exports-list from)
2546 (js2-print-named-imports exports-list)
2547 (insert " ")
2548 (js2-print-from-clause from))
2549 (from
2550 (insert "* ")
2551 (js2-print-from-clause from))
2552 (exports-list
2553 (js2-print-named-imports exports-list)))
2554 (insert ";\n")))
2555
2556 (cl-defstruct (js2-while-node
2557 (:include js2-loop-node)
2558 (:constructor nil)
2559 (:constructor make-js2-while-node (&key (type js2-WHILE)
2560 (pos (js2-current-token-beg))
2561 len body
2562 condition lp
2563 rp)))
2564 "AST node for while-loop."
2565 condition) ; while-condition
2566
2567 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2568 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2569
2570 (defun js2-visit-while-node (n v)
2571 (js2-visit-ast (js2-while-node-condition n) v)
2572 (js2-visit-ast (js2-while-node-body n) v))
2573
2574 (defun js2-print-while-node (n i)
2575 (let ((pad (js2-make-pad i)))
2576 (insert pad "while (")
2577 (js2-print-ast (js2-while-node-condition n) 0)
2578 (insert ") {\n")
2579 (js2-print-body (js2-while-node-body n) (1+ i))
2580 (insert pad "}\n")))
2581
2582 (cl-defstruct (js2-for-node
2583 (:include js2-loop-node)
2584 (:constructor nil)
2585 (:constructor make-js2-for-node (&key (type js2-FOR)
2586 (pos js2-ts-cursor)
2587 len body init
2588 condition
2589 update lp rp)))
2590 "AST node for a C-style for-loop."
2591 init ; initialization expression
2592 condition ; loop condition
2593 update) ; update clause
2594
2595 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2596 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2597
2598 (defun js2-visit-for-node (n v)
2599 (js2-visit-ast (js2-for-node-init n) v)
2600 (js2-visit-ast (js2-for-node-condition n) v)
2601 (js2-visit-ast (js2-for-node-update n) v)
2602 (js2-visit-ast (js2-for-node-body n) v))
2603
2604 (defun js2-print-for-node (n i)
2605 (let ((pad (js2-make-pad i)))
2606 (insert pad "for (")
2607 (js2-print-ast (js2-for-node-init n) 0)
2608 (insert "; ")
2609 (js2-print-ast (js2-for-node-condition n) 0)
2610 (insert "; ")
2611 (js2-print-ast (js2-for-node-update n) 0)
2612 (insert ") {\n")
2613 (js2-print-body (js2-for-node-body n) (1+ i))
2614 (insert pad "}\n")))
2615
2616 (cl-defstruct (js2-for-in-node
2617 (:include js2-loop-node)
2618 (:constructor nil)
2619 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2620 (pos js2-ts-cursor)
2621 len body
2622 iterator
2623 object
2624 in-pos
2625 each-pos
2626 foreach-p forof-p
2627 lp rp)))
2628 "AST node for a for..in loop."
2629 iterator ; [var] foo in ...
2630 object ; object over which we're iterating
2631 in-pos ; buffer position of 'in' keyword
2632 each-pos ; buffer position of 'each' keyword, if foreach-p
2633 foreach-p ; t if it's a for-each loop
2634 forof-p) ; t if it's a for-of loop
2635
2636 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2637 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2638
2639 (defun js2-visit-for-in-node (n v)
2640 (js2-visit-ast (js2-for-in-node-iterator n) v)
2641 (js2-visit-ast (js2-for-in-node-object n) v)
2642 (js2-visit-ast (js2-for-in-node-body n) v))
2643
2644 (defun js2-print-for-in-node (n i)
2645 (let ((pad (js2-make-pad i))
2646 (foreach (js2-for-in-node-foreach-p n))
2647 (forof (js2-for-in-node-forof-p n)))
2648 (insert pad "for ")
2649 (if foreach
2650 (insert "each "))
2651 (insert "(")
2652 (js2-print-ast (js2-for-in-node-iterator n) 0)
2653 (insert (if forof " of " " in "))
2654 (js2-print-ast (js2-for-in-node-object n) 0)
2655 (insert ") {\n")
2656 (js2-print-body (js2-for-in-node-body n) (1+ i))
2657 (insert pad "}\n")))
2658
2659 (cl-defstruct (js2-return-node
2660 (:include js2-node)
2661 (:constructor nil)
2662 (:constructor make-js2-return-node (&key (type js2-RETURN)
2663 (pos js2-ts-cursor)
2664 len
2665 retval)))
2666 "AST node for a return statement."
2667 retval) ; expression to return, or 'undefined
2668
2669 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2670 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2671
2672 (defun js2-visit-return-node (n v)
2673 (js2-visit-ast (js2-return-node-retval n) v))
2674
2675 (defun js2-print-return-node (n i)
2676 (insert (js2-make-pad i) "return")
2677 (when (js2-return-node-retval n)
2678 (insert " ")
2679 (js2-print-ast (js2-return-node-retval n) 0))
2680 (insert ";\n"))
2681
2682 (cl-defstruct (js2-if-node
2683 (:include js2-node)
2684 (:constructor nil)
2685 (:constructor make-js2-if-node (&key (type js2-IF)
2686 (pos js2-ts-cursor)
2687 len condition
2688 then-part
2689 else-pos
2690 else-part lp
2691 rp)))
2692 "AST node for an if-statement."
2693 condition ; expression
2694 then-part ; statement or block
2695 else-pos ; optional buffer position of 'else' keyword
2696 else-part ; optional statement or block
2697 lp ; position of left-paren, nil if omitted
2698 rp) ; position of right-paren, nil if omitted
2699
2700 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2701 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2702
2703 (defun js2-visit-if-node (n v)
2704 (js2-visit-ast (js2-if-node-condition n) v)
2705 (js2-visit-ast (js2-if-node-then-part n) v)
2706 (js2-visit-ast (js2-if-node-else-part n) v))
2707
2708 (defun js2-print-if-node (n i)
2709 (let ((pad (js2-make-pad i))
2710 (then-part (js2-if-node-then-part n))
2711 (else-part (js2-if-node-else-part n)))
2712 (insert pad "if (")
2713 (js2-print-ast (js2-if-node-condition n) 0)
2714 (insert ") {\n")
2715 (js2-print-body then-part (1+ i))
2716 (insert pad "}")
2717 (cond
2718 ((not else-part)
2719 (insert "\n"))
2720 ((js2-if-node-p else-part)
2721 (insert " else ")
2722 (js2-print-body else-part i))
2723 (t
2724 (insert " else {\n")
2725 (js2-print-body else-part (1+ i))
2726 (insert pad "}\n")))))
2727
2728 (cl-defstruct (js2-export-binding-node
2729 (:include js2-node)
2730 (:constructor nil)
2731 (:constructor make-js2-export-binding-node (&key (type -1)
2732 pos
2733 len
2734 local-name
2735 extern-name)))
2736 "AST node for an external symbol binding.
2737 It contains a local-name node which is the name of the value in the
2738 current scope, and extern-name which is the name of the value in the
2739 imported or exported scope. By default these are the same, but if the
2740 name is aliased as in {foo as bar}, it would have an extern-name node
2741 containing 'foo' and a local-name node containing 'bar'."
2742 local-name ; js2-name-node with the variable name in this scope
2743 extern-name) ; js2-name-node with the value name in the exporting module
2744
2745 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2746 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2747
2748 (defun js2-visit-extern-binding (n v)
2749 "Visit an extern binding node. First visit the local-name, and, if
2750 different, visit the extern-name."
2751 (let ((local-name (js2-export-binding-node-local-name n))
2752 (extern-name (js2-export-binding-node-extern-name n)))
2753 (when local-name
2754 (js2-visit-ast local-name v))
2755 (when (not (equal local-name extern-name))
2756 (js2-visit-ast extern-name v))))
2757
2758 (defun js2-print-extern-binding (n _i)
2759 "Print a representation of a single extern binding. E.g. 'foo' or
2760 'foo as bar'."
2761 (let ((local-name (js2-export-binding-node-local-name n))
2762 (extern-name (js2-export-binding-node-extern-name n)))
2763 (insert (js2-name-node-name extern-name))
2764 (when (not (equal local-name extern-name))
2765 (insert " as ")
2766 (insert (js2-name-node-name local-name)))))
2767
2768
2769 (cl-defstruct (js2-import-node
2770 (:include js2-node)
2771 (:constructor nil)
2772 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2773 (pos (js2-current-token-beg))
2774 len
2775 import
2776 from
2777 module-id)))
2778 "AST node for an import statement. It follows the form
2779
2780 import ModuleSpecifier;
2781 import ImportClause FromClause;"
2782 import ; js2-import-clause-node specifying which names are to imported.
2783 from ; js2-from-clause-node indicating the module from which to import.
2784 module-id) ; module-id of the import. E.g. 'src/mylib'.
2785
2786 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2787 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2788
2789 (defun js2-visit-import (n v)
2790 (let ((import-clause (js2-import-node-import n))
2791 (from-clause (js2-import-node-from n)))
2792 (when import-clause
2793 (js2-visit-ast import-clause v))
2794 (when from-clause
2795 (js2-visit-ast from-clause v))))
2796
2797 (defun js2-print-import (n i)
2798 "Prints a representation of the import node"
2799 (let ((pad (js2-make-pad i))
2800 (import-clause (js2-import-node-import n))
2801 (from-clause (js2-import-node-from n))
2802 (module-id (js2-import-node-module-id n)))
2803 (insert pad "import ")
2804 (if import-clause
2805 (progn
2806 (js2-print-import-clause import-clause)
2807 (insert " ")
2808 (js2-print-from-clause from-clause))
2809 (insert "'")
2810 (insert module-id)
2811 (insert "'"))
2812 (insert ";\n")))
2813
2814 (cl-defstruct (js2-import-clause-node
2815 (:include js2-node)
2816 (:constructor nil)
2817 (:constructor make-js2-import-clause-node (&key (type -1)
2818 pos
2819 len
2820 namespace-import
2821 named-imports
2822 default-binding)))
2823 "AST node corresponding to the import clause of an import statement. This is
2824 the portion of the import that bindings names from the external context to the
2825 local context."
2826 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2827 named-imports ; lisp list of js2-export-binding-node for all named imports.
2828 default-binding) ; js2-export-binding-node for the default import binding
2829
2830 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2831 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2832
2833 (defun js2-visit-import-clause (n v)
2834 (let ((ns-import (js2-import-clause-node-namespace-import n))
2835 (named-imports (js2-import-clause-node-named-imports n))
2836 (default (js2-import-clause-node-default-binding n)))
2837 (when ns-import
2838 (js2-visit-ast ns-import v))
2839 (when named-imports
2840 (dolist (import named-imports)
2841 (js2-visit-ast import v)))
2842 (when default
2843 (js2-visit-ast default v))))
2844
2845 (defun js2-print-import-clause (n)
2846 (let ((ns-import (js2-import-clause-node-namespace-import n))
2847 (named-imports (js2-import-clause-node-named-imports n))
2848 (default (js2-import-clause-node-default-binding n)))
2849 (cond
2850 ((and default ns-import)
2851 (js2-print-ast default)
2852 (insert ", ")
2853 (js2-print-namespace-import ns-import))
2854 ((and default named-imports)
2855 (js2-print-ast default)
2856 (insert ", ")
2857 (js2-print-named-imports named-imports))
2858 (default
2859 (js2-print-ast default))
2860 (ns-import
2861 (js2-print-namespace-import ns-import))
2862 (named-imports
2863 (js2-print-named-imports named-imports)))))
2864
2865 (defun js2-print-namespace-import (node)
2866 (insert "* as ")
2867 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2868
2869 (defun js2-print-named-imports (imports)
2870 (insert "{")
2871 (let ((len (length imports))
2872 (n 0))
2873 (while (< n len)
2874 (js2-print-extern-binding (nth n imports) 0)
2875 (unless (= n (- len 1))
2876 (insert ", "))
2877 (setq n (+ n 1))))
2878 (insert "}"))
2879
2880 (cl-defstruct (js2-namespace-import-node
2881 (:include js2-node)
2882 (:constructor nil)
2883 (:constructor make-js2-namespace-import-node (&key (type -1)
2884 pos
2885 len
2886 name)))
2887 "AST node for a complete namespace import.
2888 E.g. the '* as lib' expression in:
2889
2890 import * as lib from 'src/lib'
2891
2892 It contains a single name node referring to the bound name."
2893 name) ; js2-name-node of the bound name.
2894
2895 (defun js2-visit-namespace-import (n v)
2896 (js2-visit-ast (js2-namespace-import-node-name n) v))
2897
2898 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2899 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2900
2901 (cl-defstruct (js2-from-clause-node
2902 (:include js2-node)
2903 (:constructor nil)
2904 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2905 pos
2906 len
2907 module-id
2908 metadata-p)))
2909 "AST node for the from clause in an import or export statement.
2910 E.g. from 'my/module'. It can refere to either an external module, or to the
2911 modules metadata itself."
2912 module-id ; string containing the module specifier.
2913 metadata-p) ; true if this clause refers to the module's metadata
2914
2915 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2916 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2917
2918 (defun js2-print-from-clause (n)
2919 (insert "from ")
2920 (if (js2-from-clause-node-metadata-p n)
2921 (insert "this module")
2922 (insert "'")
2923 (insert (js2-from-clause-node-module-id n))
2924 (insert "'")))
2925
2926 (cl-defstruct (js2-try-node
2927 (:include js2-node)
2928 (:constructor nil)
2929 (:constructor make-js2-try-node (&key (type js2-TRY)
2930 (pos js2-ts-cursor)
2931 len
2932 try-block
2933 catch-clauses
2934 finally-block)))
2935 "AST node for a try-statement."
2936 try-block
2937 catch-clauses ; a Lisp list of `js2-catch-node'
2938 finally-block) ; a `js2-finally-node'
2939
2940 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2941 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2942
2943 (defun js2-visit-try-node (n v)
2944 (js2-visit-ast (js2-try-node-try-block n) v)
2945 (dolist (clause (js2-try-node-catch-clauses n))
2946 (js2-visit-ast clause v))
2947 (js2-visit-ast (js2-try-node-finally-block n) v))
2948
2949 (defun js2-print-try-node (n i)
2950 (let ((pad (js2-make-pad i))
2951 (catches (js2-try-node-catch-clauses n))
2952 (finally (js2-try-node-finally-block n)))
2953 (insert pad "try {\n")
2954 (js2-print-body (js2-try-node-try-block n) (1+ i))
2955 (insert pad "}")
2956 (when catches
2957 (dolist (catch catches)
2958 (js2-print-ast catch i)))
2959 (if finally
2960 (js2-print-ast finally i)
2961 (insert "\n"))))
2962
2963 (cl-defstruct (js2-catch-node
2964 (:include js2-scope)
2965 (:constructor nil)
2966 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2967 (pos js2-ts-cursor)
2968 len
2969 param
2970 guard-kwd
2971 guard-expr
2972 lp rp)))
2973 "AST node for a catch clause."
2974 param ; destructuring form or simple name node
2975 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2976 guard-expr ; catch condition, a `js2-node'
2977 lp ; buffer position of left-paren, nil if omitted
2978 rp) ; buffer position of right-paren, nil if omitted
2979
2980 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2981 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2982
2983 (defun js2-visit-catch-node (n v)
2984 (js2-visit-ast (js2-catch-node-param n) v)
2985 (when (js2-catch-node-guard-kwd n)
2986 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2987 (js2-visit-block n v))
2988
2989 (defun js2-print-catch-node (n i)
2990 (let ((pad (js2-make-pad i))
2991 (guard-kwd (js2-catch-node-guard-kwd n))
2992 (guard-expr (js2-catch-node-guard-expr n)))
2993 (insert " catch (")
2994 (js2-print-ast (js2-catch-node-param n) 0)
2995 (when guard-kwd
2996 (insert " if ")
2997 (js2-print-ast guard-expr 0))
2998 (insert ") {\n")
2999 (js2-print-body n (1+ i))
3000 (insert pad "}")))
3001
3002 (cl-defstruct (js2-finally-node
3003 (:include js2-node)
3004 (:constructor nil)
3005 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3006 (pos js2-ts-cursor)
3007 len body)))
3008 "AST node for a finally clause."
3009 body) ; a `js2-node', often but not always a block node
3010
3011 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3012 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3013
3014 (defun js2-visit-finally-node (n v)
3015 (js2-visit-ast (js2-finally-node-body n) v))
3016
3017 (defun js2-print-finally-node (n i)
3018 (let ((pad (js2-make-pad i)))
3019 (insert " finally {\n")
3020 (js2-print-body (js2-finally-node-body n) (1+ i))
3021 (insert pad "}\n")))
3022
3023 (cl-defstruct (js2-switch-node
3024 (:include js2-node)
3025 (:constructor nil)
3026 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3027 (pos js2-ts-cursor)
3028 len
3029 discriminant
3030 cases lp
3031 rp)))
3032 "AST node for a switch statement."
3033 discriminant ; a `js2-node' (switch expression)
3034 cases ; a Lisp list of `js2-case-node'
3035 lp ; position of open-paren for discriminant, nil if omitted
3036 rp) ; position of close-paren for discriminant, nil if omitted
3037
3038 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3039 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3040
3041 (defun js2-visit-switch-node (n v)
3042 (js2-visit-ast (js2-switch-node-discriminant n) v)
3043 (dolist (c (js2-switch-node-cases n))
3044 (js2-visit-ast c v)))
3045
3046 (defun js2-print-switch-node (n i)
3047 (let ((pad (js2-make-pad i))
3048 (cases (js2-switch-node-cases n)))
3049 (insert pad "switch (")
3050 (js2-print-ast (js2-switch-node-discriminant n) 0)
3051 (insert ") {\n")
3052 (dolist (case cases)
3053 (js2-print-ast case i))
3054 (insert pad "}\n")))
3055
3056 (cl-defstruct (js2-case-node
3057 (:include js2-block-node)
3058 (:constructor nil)
3059 (:constructor make-js2-case-node (&key (type js2-CASE)
3060 (pos js2-ts-cursor)
3061 len kids expr)))
3062 "AST node for a case clause of a switch statement."
3063 expr) ; the case expression (nil for default)
3064
3065 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3066 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3067
3068 (defun js2-visit-case-node (n v)
3069 (js2-visit-ast (js2-case-node-expr n) v)
3070 (js2-visit-block n v))
3071
3072 (defun js2-print-case-node (n i)
3073 (let ((pad (js2-make-pad i))
3074 (expr (js2-case-node-expr n)))
3075 (insert pad)
3076 (if (null expr)
3077 (insert "default:\n")
3078 (insert "case ")
3079 (js2-print-ast expr 0)
3080 (insert ":\n"))
3081 (dolist (kid (js2-case-node-kids n))
3082 (js2-print-ast kid (1+ i)))))
3083
3084 (cl-defstruct (js2-throw-node
3085 (:include js2-node)
3086 (:constructor nil)
3087 (:constructor make-js2-throw-node (&key (type js2-THROW)
3088 (pos js2-ts-cursor)
3089 len expr)))
3090 "AST node for a throw statement."
3091 expr) ; the expression to throw
3092
3093 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3094 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3095
3096 (defun js2-visit-throw-node (n v)
3097 (js2-visit-ast (js2-throw-node-expr n) v))
3098
3099 (defun js2-print-throw-node (n i)
3100 (insert (js2-make-pad i) "throw ")
3101 (js2-print-ast (js2-throw-node-expr n) 0)
3102 (insert ";\n"))
3103
3104 (cl-defstruct (js2-with-node
3105 (:include js2-node)
3106 (:constructor nil)
3107 (:constructor make-js2-with-node (&key (type js2-WITH)
3108 (pos js2-ts-cursor)
3109 len object
3110 body lp rp)))
3111 "AST node for a with-statement."
3112 object
3113 body
3114 lp ; buffer position of left-paren around object, nil if omitted
3115 rp) ; buffer position of right-paren around object, nil if omitted
3116
3117 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3118 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3119
3120 (defun js2-visit-with-node (n v)
3121 (js2-visit-ast (js2-with-node-object n) v)
3122 (js2-visit-ast (js2-with-node-body n) v))
3123
3124 (defun js2-print-with-node (n i)
3125 (let ((pad (js2-make-pad i)))
3126 (insert pad "with (")
3127 (js2-print-ast (js2-with-node-object n) 0)
3128 (insert ") {\n")
3129 (js2-print-body (js2-with-node-body n) (1+ i))
3130 (insert pad "}\n")))
3131
3132 (cl-defstruct (js2-label-node
3133 (:include js2-node)
3134 (:constructor nil)
3135 (:constructor make-js2-label-node (&key (type js2-LABEL)
3136 (pos js2-ts-cursor)
3137 len name)))
3138 "AST node for a statement label or case label."
3139 name ; a string
3140 loop) ; for validating and code-generating continue-to-label
3141
3142 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3143 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3144
3145 (defun js2-print-label (n i)
3146 (insert (js2-make-pad i)
3147 (js2-label-node-name n)
3148 ":\n"))
3149
3150 (cl-defstruct (js2-labeled-stmt-node
3151 (:include js2-node)
3152 (:constructor nil)
3153 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3154 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3155 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3156 (pos js2-ts-cursor)
3157 len labels stmt)))
3158 "AST node for a statement with one or more labels.
3159 Multiple labels for a statement are collapsed into the labels field."
3160 labels ; Lisp list of `js2-label-node'
3161 stmt) ; the statement these labels are for
3162
3163 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3164 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3165
3166 (defun js2-get-label-by-name (lbl-stmt name)
3167 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3168 Returns nil if no such label is in the list."
3169 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3170 result)
3171 (while (and label-list (not result))
3172 (if (string= (js2-label-node-name (car label-list)) name)
3173 (setq result (car label-list))
3174 (setq label-list (cdr label-list))))
3175 result))
3176
3177 (defun js2-visit-labeled-stmt (n v)
3178 (dolist (label (js2-labeled-stmt-node-labels n))
3179 (js2-visit-ast label v))
3180 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3181
3182 (defun js2-print-labeled-stmt (n i)
3183 (dolist (label (js2-labeled-stmt-node-labels n))
3184 (js2-print-ast label i))
3185 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3186
3187 (defun js2-labeled-stmt-node-contains (node label)
3188 "Return t if NODE contains LABEL in its label set.
3189 NODE is a `js2-labels-node'. LABEL is an identifier."
3190 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3191 if (string= label (js2-label-node-name nl))
3192 return t
3193 finally return nil))
3194
3195 (defsubst js2-labeled-stmt-node-add-label (node label)
3196 "Add a `js2-label-node' to the label set for this statement."
3197 (setf (js2-labeled-stmt-node-labels node)
3198 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3199
3200 (cl-defstruct (js2-jump-node
3201 (:include js2-node)
3202 (:constructor nil))
3203 "Abstract supertype of break and continue nodes."
3204 label ; `js2-name-node' for location of label identifier, if present
3205 target) ; target js2-labels-node or loop/switch statement
3206
3207 (defun js2-visit-jump-node (n v)
3208 ;; We don't visit the target, since it's a back-link.
3209 (js2-visit-ast (js2-jump-node-label n) v))
3210
3211 (cl-defstruct (js2-break-node
3212 (:include js2-jump-node)
3213 (:constructor nil)
3214 (:constructor make-js2-break-node (&key (type js2-BREAK)
3215 (pos js2-ts-cursor)
3216 len label target)))
3217 "AST node for a break statement.
3218 The label field is a `js2-name-node', possibly nil, for the named label
3219 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3220 is the target of the break - a label node or enclosing loop/switch statement.")
3221
3222 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3223 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3224
3225 (defun js2-print-break-node (n i)
3226 (insert (js2-make-pad i) "break")
3227 (when (js2-break-node-label n)
3228 (insert " ")
3229 (js2-print-ast (js2-break-node-label n) 0))
3230 (insert ";\n"))
3231
3232 (cl-defstruct (js2-continue-node
3233 (:include js2-jump-node)
3234 (:constructor nil)
3235 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3236 (pos js2-ts-cursor)
3237 len label target)))
3238 "AST node for a continue statement.
3239 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3240 It is nil if continue specifies no label. The target field is the jump target:
3241 a `js2-label-node' or the innermost enclosing loop.")
3242
3243 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3244 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3245
3246 (defun js2-print-continue-node (n i)
3247 (insert (js2-make-pad i) "continue")
3248 (when (js2-continue-node-label n)
3249 (insert " ")
3250 (js2-print-ast (js2-continue-node-label n) 0))
3251 (insert ";\n"))
3252
3253 (cl-defstruct (js2-function-node
3254 (:include js2-script-node)
3255 (:constructor nil)
3256 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3257 (pos js2-ts-cursor)
3258 len
3259 (ftype 'FUNCTION)
3260 (form 'FUNCTION_STATEMENT)
3261 (name "")
3262 params rest-p
3263 body
3264 generator-type
3265 async
3266 lp rp)))
3267 "AST node for a function declaration.
3268 The `params' field is a Lisp list of nodes. Each node is either a simple
3269 `js2-name-node', or if it's a destructuring-assignment parameter, a
3270 `js2-array-node' or `js2-object-node'."
3271 ftype ; FUNCTION, GETTER or SETTER
3272 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3273 name ; function name (a `js2-name-node', or nil if anonymous)
3274 params ; a Lisp list of destructuring forms or simple name nodes
3275 rest-p ; if t, the last parameter is rest parameter
3276 body ; a `js2-block-node' or expression node (1.8 only)
3277 lp ; position of arg-list open-paren, or nil if omitted
3278 rp ; position of arg-list close-paren, or nil if omitted
3279 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3280 needs-activation ; t if we need an activation object for this frame
3281 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3282 async ; t if the function is defined as `async function`
3283 member-expr) ; nonstandard Ecma extension from Rhino
3284
3285 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3286 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3287
3288 (defun js2-visit-function-node (n v)
3289 (js2-visit-ast (js2-function-node-name n) v)
3290 (dolist (p (js2-function-node-params n))
3291 (js2-visit-ast p v))
3292 (js2-visit-ast (js2-function-node-body n) v))
3293
3294 (defun js2-print-function-node (n i)
3295 (let* ((pad (js2-make-pad i))
3296 (method (js2-node-get-prop n 'METHOD_TYPE))
3297 (name (or (js2-function-node-name n)
3298 (js2-function-node-member-expr n)))
3299 (params (js2-function-node-params n))
3300 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3301 (rest-p (js2-function-node-rest-p n))
3302 (body (js2-function-node-body n))
3303 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3304 (unless method
3305 (insert pad)
3306 (when (js2-function-node-async n) (insert "async "))
3307 (unless arrow (insert "function"))
3308 (when (eq (js2-function-node-generator-type n) 'STAR)
3309 (insert "*")))
3310 (when name
3311 (insert " ")
3312 (js2-print-ast name 0))
3313 (insert "(")
3314 (cl-loop with len = (length params)
3315 for param in params
3316 for count from 1
3317 do
3318 (when (and rest-p (= count len))
3319 (insert "..."))
3320 (js2-print-ast param 0)
3321 (when (< count len)
3322 (insert ", ")))
3323 (insert ") ")
3324 (when arrow
3325 (insert "=> "))
3326 (insert "{")
3327 ;; TODO: fix this to be smarter about indenting, etc.
3328 (unless expr
3329 (insert "\n"))
3330 (if (js2-block-node-p body)
3331 (js2-print-body body (1+ i))
3332 (js2-print-ast body 0))
3333 (insert pad "}")
3334 (unless expr
3335 (insert "\n"))))
3336
3337 (defun js2-function-name (node)
3338 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3339 (and (js2-function-node-name node)
3340 (js2-name-node-name (js2-function-node-name node))))
3341
3342 ;; Having this be an expression node makes it more flexible.
3343 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3344 ;; that work better if you assume it's an expression. Whenever we have
3345 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3346 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3347 (cl-defstruct (js2-var-decl-node
3348 (:include js2-node)
3349 (:constructor nil)
3350 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3351 (pos (js2-current-token-beg))
3352 len kids
3353 decl-type)))
3354 "AST node for a variable declaration list (VAR, CONST or LET).
3355 The node bounds differ depending on the declaration type. For VAR or
3356 CONST declarations, the bounds include the var/const keyword. For LET
3357 declarations, the node begins at the position of the first child."
3358 kids ; a Lisp list of `js2-var-init-node' structs.
3359 decl-type) ; js2-VAR, js2-CONST or js2-LET
3360
3361 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3362 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3363
3364 (defun js2-visit-var-decl (n v)
3365 (dolist (kid (js2-var-decl-node-kids n))
3366 (js2-visit-ast kid v)))
3367
3368 (defun js2-print-var-decl (n i)
3369 (let ((pad (js2-make-pad i))
3370 (tt (js2-var-decl-node-decl-type n)))
3371 (insert pad)
3372 (insert (cond
3373 ((= tt js2-VAR) "var ")
3374 ((= tt js2-LET) "let ")
3375 ((= tt js2-CONST) "const ")
3376 (t
3377 (error "malformed var-decl node"))))
3378 (cl-loop with kids = (js2-var-decl-node-kids n)
3379 with len = (length kids)
3380 for kid in kids
3381 for count from 1
3382 do
3383 (js2-print-ast kid 0)
3384 (if (< count len)
3385 (insert ", ")))))
3386
3387 (cl-defstruct (js2-var-init-node
3388 (:include js2-node)
3389 (:constructor nil)
3390 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3391 (pos js2-ts-cursor)
3392 len target
3393 initializer)))
3394 "AST node for a variable declaration.
3395 The type field will be js2-CONST for a const decl."
3396 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3397 initializer) ; initializer expression, a `js2-node'
3398
3399 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3400 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3401
3402 (defun js2-visit-var-init-node (n v)
3403 (js2-visit-ast (js2-var-init-node-target n) v)
3404 (js2-visit-ast (js2-var-init-node-initializer n) v))
3405
3406 (defun js2-print-var-init-node (n i)
3407 (let ((pad (js2-make-pad i))
3408 (name (js2-var-init-node-target n))
3409 (init (js2-var-init-node-initializer n)))
3410 (insert pad)
3411 (js2-print-ast name 0)
3412 (when init
3413 (insert " = ")
3414 (js2-print-ast init 0))))
3415
3416 (cl-defstruct (js2-cond-node
3417 (:include js2-node)
3418 (:constructor nil)
3419 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3420 (pos js2-ts-cursor)
3421 len
3422 test-expr
3423 true-expr
3424 false-expr
3425 q-pos c-pos)))
3426 "AST node for the ternary operator"
3427 test-expr
3428 true-expr
3429 false-expr
3430 q-pos ; buffer position of ?
3431 c-pos) ; buffer position of :
3432
3433 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3434 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3435
3436 (defun js2-visit-cond-node (n v)
3437 (js2-visit-ast (js2-cond-node-test-expr n) v)
3438 (js2-visit-ast (js2-cond-node-true-expr n) v)
3439 (js2-visit-ast (js2-cond-node-false-expr n) v))
3440
3441 (defun js2-print-cond-node (n i)
3442 (let ((pad (js2-make-pad i)))
3443 (insert pad)
3444 (js2-print-ast (js2-cond-node-test-expr n) 0)
3445 (insert " ? ")
3446 (js2-print-ast (js2-cond-node-true-expr n) 0)
3447 (insert " : ")
3448 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3449
3450 (cl-defstruct (js2-infix-node
3451 (:include js2-node)
3452 (:constructor nil)
3453 (:constructor make-js2-infix-node (&key type
3454 (pos js2-ts-cursor)
3455 len op-pos
3456 left right)))
3457 "Represents infix expressions.
3458 Includes assignment ops like `|=', and the comma operator.
3459 The type field inherited from `js2-node' holds the operator."
3460 op-pos ; buffer position where operator begins
3461 left ; any `js2-node'
3462 right) ; any `js2-node'
3463
3464 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3465 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3466
3467 (defun js2-visit-infix-node (n v)
3468 (js2-visit-ast (js2-infix-node-left n) v)
3469 (js2-visit-ast (js2-infix-node-right n) v))
3470
3471 (defconst js2-operator-tokens
3472 (let ((table (make-hash-table :test 'eq))
3473 (tokens
3474 (list (cons js2-IN "in")
3475 (cons js2-TYPEOF "typeof")
3476 (cons js2-INSTANCEOF "instanceof")
3477 (cons js2-DELPROP "delete")
3478 (cons js2-AWAIT "await")
3479 (cons js2-COMMA ",")
3480 (cons js2-COLON ":")
3481 (cons js2-OR "||")
3482 (cons js2-AND "&&")
3483 (cons js2-INC "++")
3484 (cons js2-DEC "--")
3485 (cons js2-BITOR "|")
3486 (cons js2-BITXOR "^")
3487 (cons js2-BITAND "&")
3488 (cons js2-EQ "==")
3489 (cons js2-NE "!=")
3490 (cons js2-LT "<")
3491 (cons js2-LE "<=")
3492 (cons js2-GT ">")
3493 (cons js2-GE ">=")
3494 (cons js2-LSH "<<")
3495 (cons js2-RSH ">>")
3496 (cons js2-URSH ">>>")
3497 (cons js2-ADD "+") ; infix plus
3498 (cons js2-SUB "-") ; infix minus
3499 (cons js2-MUL "*")
3500 (cons js2-DIV "/")
3501 (cons js2-MOD "%")
3502 (cons js2-NOT "!")
3503 (cons js2-BITNOT "~")
3504 (cons js2-POS "+") ; unary plus
3505 (cons js2-NEG "-") ; unary minus
3506 (cons js2-TRIPLEDOT "...")
3507 (cons js2-SHEQ "===") ; shallow equality
3508 (cons js2-SHNE "!==") ; shallow inequality
3509 (cons js2-ASSIGN "=")
3510 (cons js2-ASSIGN_BITOR "|=")
3511 (cons js2-ASSIGN_BITXOR "^=")
3512 (cons js2-ASSIGN_BITAND "&=")
3513 (cons js2-ASSIGN_LSH "<<=")
3514 (cons js2-ASSIGN_RSH ">>=")
3515 (cons js2-ASSIGN_URSH ">>>=")
3516 (cons js2-ASSIGN_ADD "+=")
3517 (cons js2-ASSIGN_SUB "-=")
3518 (cons js2-ASSIGN_MUL "*=")
3519 (cons js2-ASSIGN_DIV "/=")
3520 (cons js2-ASSIGN_MOD "%="))))
3521 (cl-loop for (k . v) in tokens do
3522 (puthash k v table))
3523 table))
3524
3525 (defun js2-print-infix-node (n i)
3526 (let* ((tt (js2-node-type n))
3527 (op (gethash tt js2-operator-tokens)))
3528 (unless op
3529 (error "unrecognized infix operator %s" (js2-node-type n)))
3530 (insert (js2-make-pad i))
3531 (js2-print-ast (js2-infix-node-left n) 0)
3532 (unless (= tt js2-COMMA)
3533 (insert " "))
3534 (insert op)
3535 (insert " ")
3536 (js2-print-ast (js2-infix-node-right n) 0)))
3537
3538 (cl-defstruct (js2-assign-node
3539 (:include js2-infix-node)
3540 (:constructor nil)
3541 (:constructor make-js2-assign-node (&key type
3542 (pos js2-ts-cursor)
3543 len op-pos
3544 left right)))
3545 "Represents any assignment.
3546 The type field holds the actual assignment operator.")
3547
3548 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3549 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3550
3551 (cl-defstruct (js2-unary-node
3552 (:include js2-node)
3553 (:constructor nil)
3554 (:constructor make-js2-unary-node (&key type ; required
3555 (pos js2-ts-cursor)
3556 len operand)))
3557 "AST node type for unary operator nodes.
3558 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3559 TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
3560 property is added if the operator follows the operand."
3561 operand) ; a `js2-node' expression
3562
3563 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3564 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3565
3566 (defun js2-visit-unary-node (n v)
3567 (js2-visit-ast (js2-unary-node-operand n) v))
3568
3569 (defun js2-print-unary-node (n i)
3570 (let* ((tt (js2-node-type n))
3571 (op (gethash tt js2-operator-tokens))
3572 (postfix (js2-node-get-prop n 'postfix)))
3573 (unless op
3574 (error "unrecognized unary operator %s" tt))
3575 (insert (js2-make-pad i))
3576 (unless postfix
3577 (insert op))
3578 (if (or (= tt js2-TYPEOF)
3579 (= tt js2-DELPROP)
3580 (= tt js2-AWAIT))
3581 (insert " "))
3582 (js2-print-ast (js2-unary-node-operand n) 0)
3583 (when postfix
3584 (insert op))))
3585
3586 (cl-defstruct (js2-let-node
3587 (:include js2-scope)
3588 (:constructor nil)
3589 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3590 (pos (js2-current-token-beg))
3591 len vars body
3592 lp rp)))
3593 "AST node for a let expression or a let statement.
3594 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3595 vars ; a `js2-var-decl-node'
3596 body ; a `js2-node' representing the expression or body block
3597 lp
3598 rp)
3599
3600 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3601 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3602
3603 (defun js2-visit-let-node (n v)
3604 (js2-visit-ast (js2-let-node-vars n) v)
3605 (js2-visit-ast (js2-let-node-body n) v))
3606
3607 (defun js2-print-let-node (n i)
3608 (insert (js2-make-pad i) "let (")
3609 (let ((p (point)))
3610 (js2-print-ast (js2-let-node-vars n) 0)
3611 (delete-region p (+ p 4)))
3612 (insert ") ")
3613 (js2-print-ast (js2-let-node-body n) i))
3614
3615 (cl-defstruct (js2-keyword-node
3616 (:include js2-node)
3617 (:constructor nil)
3618 (:constructor make-js2-keyword-node (&key type
3619 (pos (js2-current-token-beg))
3620 (len (- js2-ts-cursor pos)))))
3621 "AST node representing a literal keyword such as `null'.
3622 Used for `null', `this', `true', `false' and `debugger'.
3623 The node type is set to js2-NULL, js2-THIS, etc.")
3624
3625 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3626 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3627
3628 (defun js2-print-keyword-node (n i)
3629 (insert (js2-make-pad i)
3630 (let ((tt (js2-node-type n)))
3631 (cond
3632 ((= tt js2-THIS) "this")
3633 ((= tt js2-SUPER) "super")
3634 ((= tt js2-NULL) "null")
3635 ((= tt js2-TRUE) "true")
3636 ((= tt js2-FALSE) "false")
3637 ((= tt js2-DEBUGGER) "debugger")
3638 (t (error "Invalid keyword literal type: %d" tt))))))
3639
3640 (defsubst js2-this-or-super-node-p (node)
3641 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3642 (let ((type (js2-node-type node)))
3643 (or (eq type js2-THIS) (eq type js2-SUPER))))
3644
3645 (cl-defstruct (js2-new-node
3646 (:include js2-node)
3647 (:constructor nil)
3648 (:constructor make-js2-new-node (&key (type js2-NEW)
3649 (pos (js2-current-token-beg))
3650 len target
3651 args initializer
3652 lp rp)))
3653 "AST node for new-expression such as new Foo()."
3654 target ; an identifier or reference
3655 args ; a Lisp list of argument nodes
3656 lp ; position of left-paren, nil if omitted
3657 rp ; position of right-paren, nil if omitted
3658 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3659
3660 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3661 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3662
3663 (defun js2-visit-new-node (n v)
3664 (js2-visit-ast (js2-new-node-target n) v)
3665 (dolist (arg (js2-new-node-args n))
3666 (js2-visit-ast arg v))
3667 (js2-visit-ast (js2-new-node-initializer n) v))
3668
3669 (defun js2-print-new-node (n i)
3670 (insert (js2-make-pad i) "new ")
3671 (js2-print-ast (js2-new-node-target n))
3672 (insert "(")
3673 (js2-print-list (js2-new-node-args n))
3674 (insert ")")
3675 (when (js2-new-node-initializer n)
3676 (insert " ")
3677 (js2-print-ast (js2-new-node-initializer n))))
3678
3679 (cl-defstruct (js2-name-node
3680 (:include js2-node)
3681 (:constructor nil)
3682 (:constructor make-js2-name-node (&key (type js2-NAME)
3683 (pos (js2-current-token-beg))
3684 (len (- js2-ts-cursor
3685 (js2-current-token-beg)))
3686 (name (js2-current-token-string)))))
3687 "AST node for a JavaScript identifier"
3688 name ; a string
3689 scope) ; a `js2-scope' (optional, used for codegen)
3690
3691 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3692 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3693
3694 (defun js2-print-name-node (n i)
3695 (insert (js2-make-pad i)
3696 (js2-name-node-name n)))
3697
3698 (defsubst js2-name-node-length (node)
3699 "Return identifier length of NODE, a `js2-name-node'.
3700 Returns 0 if NODE is nil or its identifier field is nil."
3701 (if node
3702 (length (js2-name-node-name node))
3703 0))
3704
3705 (cl-defstruct (js2-number-node
3706 (:include js2-node)
3707 (:constructor nil)
3708 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3709 (pos (js2-current-token-beg))
3710 (len (- js2-ts-cursor
3711 (js2-current-token-beg)))
3712 (value (js2-current-token-string))
3713 (num-value (js2-token-number
3714 (js2-current-token)))
3715 (num-base (js2-token-number-base
3716 (js2-current-token)))
3717 (legacy-octal-p (js2-token-number-legacy-octal-p
3718 (js2-current-token))))))
3719 "AST node for a number literal."
3720 value ; the original string, e.g. "6.02e23"
3721 num-value ; the parsed number value
3722 num-base ; the number's base
3723 legacy-octal-p) ; whether the number is a legacy octal (0123 instead of 0o123)
3724
3725 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3726 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3727
3728 (defun js2-print-number-node (n i)
3729 (insert (js2-make-pad i)
3730 (number-to-string (js2-number-node-num-value n))))
3731
3732 (cl-defstruct (js2-regexp-node
3733 (:include js2-node)
3734 (:constructor nil)
3735 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3736 (pos (js2-current-token-beg))
3737 (len (- js2-ts-cursor
3738 (js2-current-token-beg)))
3739 value flags)))
3740 "AST node for a regular expression literal."
3741 value ; the regexp string, without // delimiters
3742 flags) ; a string of flags, e.g. `mi'.
3743
3744 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3745 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3746
3747 (defun js2-print-regexp (n i)
3748 (insert (js2-make-pad i)
3749 "/"
3750 (js2-regexp-node-value n)
3751 "/")
3752 (if (js2-regexp-node-flags n)
3753 (insert (js2-regexp-node-flags n))))
3754
3755 (cl-defstruct (js2-string-node
3756 (:include js2-node)
3757 (:constructor nil)
3758 (:constructor make-js2-string-node (&key (type js2-STRING)
3759 (pos (js2-current-token-beg))
3760 (len (- js2-ts-cursor
3761 (js2-current-token-beg)))
3762 (value (js2-current-token-string)))))
3763 "String literal.
3764 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3765 You can tell the quote type by looking at the first character."
3766 value) ; the characters of the string, including the quotes
3767
3768 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3769 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3770
3771 (defun js2-print-string-node (n i)
3772 (insert (js2-make-pad i)
3773 (js2-node-string n)))
3774
3775 (cl-defstruct (js2-template-node
3776 (:include js2-node)
3777 (:constructor nil)
3778 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3779 beg len kids)))
3780 "Template literal."
3781 kids) ; `js2-string-node' is used for string segments, other nodes
3782 ; for substitutions inside.
3783
3784 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3785 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3786
3787 (defun js2-visit-template (n callback)
3788 (dolist (kid (js2-template-node-kids n))
3789 (js2-visit-ast kid callback)))
3790
3791 (defun js2-print-template (n i)
3792 (insert (js2-make-pad i))
3793 (dolist (kid (js2-template-node-kids n))
3794 (if (js2-string-node-p kid)
3795 (insert (js2-node-string kid))
3796 (js2-print-ast kid))))
3797
3798 (cl-defstruct (js2-tagged-template-node
3799 (:include js2-node)
3800 (:constructor nil)
3801 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3802 beg len tag template)))
3803 "Tagged template literal."
3804 tag ; `js2-node' with the tag expression.
3805 template) ; `js2-template-node' with the template.
3806
3807 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3808 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3809
3810 (defun js2-visit-tagged-template (n callback)
3811 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3812 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3813
3814 (defun js2-print-tagged-template (n i)
3815 (insert (js2-make-pad i))
3816 (js2-print-ast (js2-tagged-template-node-tag n))
3817 (js2-print-ast (js2-tagged-template-node-template n)))
3818
3819 (cl-defstruct (js2-array-node
3820 (:include js2-node)
3821 (:constructor nil)
3822 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3823 (pos js2-ts-cursor)
3824 len elems)))
3825 "AST node for an array literal."
3826 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3827
3828 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3829 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3830
3831 (defun js2-visit-array-node (n v)
3832 (dolist (e (js2-array-node-elems n))
3833 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3834
3835 (defun js2-print-array-node (n i)
3836 (insert (js2-make-pad i) "[")
3837 (let ((elems (js2-array-node-elems n)))
3838 (js2-print-list elems)
3839 (when (and elems (null (car (last elems))))
3840 (insert ",")))
3841 (insert "]"))
3842
3843 (cl-defstruct (js2-class-node
3844 (:include js2-node)
3845 (:constructor nil)
3846 (:constructor make-js2-class-node (&key (type js2-CLASS)
3847 (pos js2-ts-cursor)
3848 (form 'CLASS_STATEMENT)
3849 (name "")
3850 extends len elems)))
3851 "AST node for an class expression.
3852 `elems' is a list of `js2-object-prop-node', and `extends' is an
3853 optional `js2-expr-node'"
3854 form ; CLASS_{STATEMENT|EXPRESSION}
3855 name ; class name (a `js2-node-name', or nil if anonymous)
3856 extends ; class heritage (a `js2-expr-node', or nil if none)
3857 elems)
3858
3859 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3860 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3861
3862 (defun js2-visit-class-node (n v)
3863 (js2-visit-ast (js2-class-node-name n) v)
3864 (js2-visit-ast (js2-class-node-extends n) v)
3865 (dolist (e (js2-class-node-elems n))
3866 (js2-visit-ast e v)))
3867
3868 (defun js2-print-class-node (n i)
3869 (let* ((pad (js2-make-pad i))
3870 (name (js2-class-node-name n))
3871 (extends (js2-class-node-extends n))
3872 (elems (js2-class-node-elems n)))
3873 (insert pad "class")
3874 (when name
3875 (insert " ")
3876 (js2-print-ast name 0))
3877 (when extends
3878 (insert " extends ")
3879 (js2-print-ast extends))
3880 (insert " {")
3881 (dolist (elem elems)
3882 (insert "\n")
3883 (if (js2-node-get-prop elem 'STATIC)
3884 (progn (insert (js2-make-pad (1+ i)) "static ")
3885 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3886 (js2-print-ast elem (1+ i))))
3887 (insert "\n" pad "}")))
3888
3889 (cl-defstruct (js2-object-node
3890 (:include js2-node)
3891 (:constructor nil)
3892 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3893 (pos js2-ts-cursor)
3894 len
3895 elems)))
3896 "AST node for an object literal expression.
3897 `elems' is a list of `js2-object-prop-node'."
3898 elems)
3899
3900 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3901 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3902
3903 (defun js2-visit-object-node (n v)
3904 (dolist (e (js2-object-node-elems n))
3905 (js2-visit-ast e v)))
3906
3907 (defun js2-print-object-node (n i)
3908 (insert (js2-make-pad i) "{")
3909 (js2-print-list (js2-object-node-elems n))
3910 (insert "}"))
3911
3912 (cl-defstruct (js2-computed-prop-name-node
3913 (:include js2-node)
3914 (:constructor nil)
3915 (:constructor make-js2-computed-prop-name-node
3916 (&key
3917 (type js2-LB)
3918 expr
3919 (pos (js2-current-token-beg))
3920 (len (- js2-ts-cursor
3921 (js2-current-token-beg))))))
3922 "AST node for a `ComputedPropertyName'."
3923 expr)
3924
3925 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3926 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3927
3928 (defun js2-visit-computed-prop-name-node (n v)
3929 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3930
3931 (defun js2-print-computed-prop-name-node (n i)
3932 (insert (js2-make-pad i) "[")
3933 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3934 (insert "]"))
3935
3936 (cl-defstruct (js2-object-prop-node
3937 (:include js2-infix-node)
3938 (:constructor nil)
3939 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3940 (pos js2-ts-cursor)
3941 len left
3942 right op-pos)))
3943 "AST node for an object literal prop:value entry.
3944 The `left' field is the property: a name node, string node,
3945 number node or expression node. The `right' field is a
3946 `js2-node' representing the initializer value. If the property
3947 is abbreviated, the node's `SHORTHAND' property is non-nil and
3948 both fields have the same value.")
3949
3950 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3951 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3952
3953 (defun js2-print-object-prop-node (n i)
3954 (let* ((left (js2-object-prop-node-left n))
3955 (right (js2-object-prop-node-right n)))
3956 (js2-print-ast left i)
3957 (if (not (js2-node-get-prop n 'SHORTHAND))
3958 (progn
3959 (insert ": ")
3960 (js2-print-ast right 0)))))
3961
3962 (cl-defstruct (js2-method-node
3963 (:include js2-infix-node)
3964 (:constructor nil)
3965 (:constructor make-js2-method-node (&key (pos js2-ts-cursor)
3966 len left right)))
3967 "AST node for a method in an object literal or a class body.
3968 The `left' field is the `js2-name-node' naming the method.
3969 The `right' field is always an anonymous `js2-function-node' with a node
3970 property `METHOD_TYPE' set to 'GET or 'SET. ")
3971
3972 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3973 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3974
3975 (defun js2-print-method (n i)
3976 (let* ((pad (js2-make-pad i))
3977 (left (js2-method-node-left n))
3978 (right (js2-method-node-right n))
3979 (type (js2-node-get-prop right 'METHOD_TYPE)))
3980 (insert pad)
3981 (when type
3982 (insert (cdr (assoc type '((GET . "get ")
3983 (SET . "set ")
3984 (ASYNC . "async ")
3985 (FUNCTION . ""))))))
3986 (when (and (js2-function-node-p right)
3987 (eq 'STAR (js2-function-node-generator-type right)))
3988 (insert "*"))
3989 (js2-print-ast left 0)
3990 (js2-print-ast right 0)))
3991
3992 (cl-defstruct (js2-prop-get-node
3993 (:include js2-infix-node)
3994 (:constructor nil)
3995 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3996 (pos js2-ts-cursor)
3997 len left right)))
3998 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3999
4000 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4001 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4002
4003 (defun js2-visit-prop-get-node (n v)
4004 (js2-visit-ast (js2-prop-get-node-left n) v)
4005 (js2-visit-ast (js2-prop-get-node-right n) v))
4006
4007 (defun js2-print-prop-get-node (n i)
4008 (insert (js2-make-pad i))
4009 (js2-print-ast (js2-prop-get-node-left n) 0)
4010 (insert ".")
4011 (js2-print-ast (js2-prop-get-node-right n) 0))
4012
4013 (cl-defstruct (js2-elem-get-node
4014 (:include js2-node)
4015 (:constructor nil)
4016 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4017 (pos js2-ts-cursor)
4018 len target element
4019 lb rb)))
4020 "AST node for an array index expression such as foo[bar]."
4021 target ; a `js2-node' - the expression preceding the "."
4022 element ; a `js2-node' - the expression in brackets
4023 lb ; position of left-bracket, nil if omitted
4024 rb) ; position of right-bracket, nil if omitted
4025
4026 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4027 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4028
4029 (defun js2-visit-elem-get-node (n v)
4030 (js2-visit-ast (js2-elem-get-node-target n) v)
4031 (js2-visit-ast (js2-elem-get-node-element n) v))
4032
4033 (defun js2-print-elem-get-node (n i)
4034 (insert (js2-make-pad i))
4035 (js2-print-ast (js2-elem-get-node-target n) 0)
4036 (insert "[")
4037 (js2-print-ast (js2-elem-get-node-element n) 0)
4038 (insert "]"))
4039
4040 (cl-defstruct (js2-call-node
4041 (:include js2-node)
4042 (:constructor nil)
4043 (:constructor make-js2-call-node (&key (type js2-CALL)
4044 (pos js2-ts-cursor)
4045 len target args
4046 lp rp)))
4047 "AST node for a JavaScript function call."
4048 target ; a `js2-node' evaluating to the function to call
4049 args ; a Lisp list of `js2-node' arguments
4050 lp ; position of open-paren, or nil if missing
4051 rp) ; position of close-paren, or nil if missing
4052
4053 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4054 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4055
4056 (defun js2-visit-call-node (n v)
4057 (js2-visit-ast (js2-call-node-target n) v)
4058 (dolist (arg (js2-call-node-args n))
4059 (js2-visit-ast arg v)))
4060
4061 (defun js2-print-call-node (n i)
4062 (insert (js2-make-pad i))
4063 (js2-print-ast (js2-call-node-target n) 0)
4064 (insert "(")
4065 (js2-print-list (js2-call-node-args n))
4066 (insert ")"))
4067
4068 (cl-defstruct (js2-yield-node
4069 (:include js2-node)
4070 (:constructor nil)
4071 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4072 (pos js2-ts-cursor)
4073 len value star-p)))
4074 "AST node for yield statement or expression."
4075 star-p ; whether it's yield*
4076 value) ; optional: value to be yielded
4077
4078 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4079 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4080
4081 (defun js2-visit-yield-node (n v)
4082 (js2-visit-ast (js2-yield-node-value n) v))
4083
4084 (defun js2-print-yield-node (n i)
4085 (insert (js2-make-pad i))
4086 (insert "yield")
4087 (when (js2-yield-node-star-p n)
4088 (insert "*"))
4089 (when (js2-yield-node-value n)
4090 (insert " ")
4091 (js2-print-ast (js2-yield-node-value n) 0)))
4092
4093 (cl-defstruct (js2-paren-node
4094 (:include js2-node)
4095 (:constructor nil)
4096 (:constructor make-js2-paren-node (&key (type js2-LP)
4097 (pos js2-ts-cursor)
4098 len expr)))
4099 "AST node for a parenthesized expression.
4100 In particular, used when the parens are syntactically optional,
4101 as opposed to required parens such as those enclosing an if-conditional."
4102 expr) ; `js2-node'
4103
4104 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4105 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4106
4107 (defun js2-visit-paren-node (n v)
4108 (js2-visit-ast (js2-paren-node-expr n) v))
4109
4110 (defun js2-print-paren-node (n i)
4111 (insert (js2-make-pad i))
4112 (insert "(")
4113 (js2-print-ast (js2-paren-node-expr n) 0)
4114 (insert ")"))
4115
4116 (cl-defstruct (js2-comp-node
4117 (:include js2-scope)
4118 (:constructor nil)
4119 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4120 (pos js2-ts-cursor)
4121 len result
4122 loops filters
4123 form)))
4124 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4125 result ; result expression (just after left-bracket)
4126 loops ; a Lisp list of `js2-comp-loop-node'
4127 filters ; a Lisp list of guard/filter expressions
4128 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4129 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4130 )
4131
4132 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4133 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4134
4135 (defun js2-visit-comp-node (n v)
4136 (js2-visit-ast (js2-comp-node-result n) v)
4137 (dolist (l (js2-comp-node-loops n))
4138 (js2-visit-ast l v))
4139 (dolist (f (js2-comp-node-filters n))
4140 (js2-visit-ast f v)))
4141
4142 (defun js2-print-comp-node (n i)
4143 (let ((pad (js2-make-pad i))
4144 (result (js2-comp-node-result n))
4145 (loops (js2-comp-node-loops n))
4146 (filters (js2-comp-node-filters n))
4147 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4148 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4149 (insert pad (if gen-p "(" "["))
4150 (when legacy-p
4151 (js2-print-ast result 0))
4152 (dolist (l loops)
4153 (when legacy-p
4154 (insert " "))
4155 (js2-print-ast l 0)
4156 (unless legacy-p
4157 (insert " ")))
4158 (dolist (f filters)
4159 (when legacy-p
4160 (insert " "))
4161 (insert "if (")
4162 (js2-print-ast f 0)
4163 (insert ")")
4164 (unless legacy-p
4165 (insert " ")))
4166 (unless legacy-p
4167 (js2-print-ast result 0))
4168 (insert (if gen-p ")" "]"))))
4169
4170 (cl-defstruct (js2-comp-loop-node
4171 (:include js2-for-in-node)
4172 (:constructor nil)
4173 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4174 (pos js2-ts-cursor)
4175 len iterator
4176 object in-pos
4177 foreach-p
4178 each-pos
4179 forof-p
4180 lp rp)))
4181 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4182
4183 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4184 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4185
4186 (defun js2-visit-comp-loop (n v)
4187 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4188 (js2-visit-ast (js2-comp-loop-node-object n) v))
4189
4190 (defun js2-print-comp-loop (n _i)
4191 (insert "for ")
4192 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4193 (insert "(")
4194 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4195 (insert (if (js2-comp-loop-node-forof-p n)
4196 " of " " in "))
4197 (js2-print-ast (js2-comp-loop-node-object n) 0)
4198 (insert ")"))
4199
4200 (cl-defstruct (js2-empty-expr-node
4201 (:include js2-node)
4202 (:constructor nil)
4203 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4204 (pos (js2-current-token-beg))
4205 len)))
4206 "AST node for an empty expression.")
4207
4208 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4209 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4210
4211 (cl-defstruct (js2-xml-node
4212 (:include js2-block-node)
4213 (:constructor nil)
4214 (:constructor make-js2-xml-node (&key (type js2-XML)
4215 (pos (js2-current-token-beg))
4216 len kids)))
4217 "AST node for initial parse of E4X literals.
4218 The kids field is a list of XML fragments, each a `js2-string-node' or
4219 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4220
4221 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4222 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4223
4224 (defun js2-print-xml-node (n i)
4225 (dolist (kid (js2-xml-node-kids n))
4226 (js2-print-ast kid i)))
4227
4228 (cl-defstruct (js2-xml-js-expr-node
4229 (:include js2-xml-node)
4230 (:constructor nil)
4231 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4232 (pos js2-ts-cursor)
4233 len expr)))
4234 "AST node for an embedded JavaScript {expression} in an E4X literal.
4235 The start and end fields correspond to the curly-braces."
4236 expr) ; a `js2-expr-node' of some sort
4237
4238 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4239 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4240
4241 (defun js2-visit-xml-js-expr (n v)
4242 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4243
4244 (defun js2-print-xml-js-expr (n i)
4245 (insert (js2-make-pad i))
4246 (insert "{")
4247 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4248 (insert "}"))
4249
4250 (cl-defstruct (js2-xml-dot-query-node
4251 (:include js2-infix-node)
4252 (:constructor nil)
4253 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4254 (pos js2-ts-cursor)
4255 op-pos len left
4256 right rp)))
4257 "AST node for an E4X foo.(bar) filter expression.
4258 Note that the left-paren is automatically the character immediately
4259 following the dot (.) in the operator. No whitespace is permitted
4260 between the dot and the lp by the scanner."
4261 rp)
4262
4263 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4264 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4265
4266 (defun js2-print-xml-dot-query (n i)
4267 (insert (js2-make-pad i))
4268 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4269 (insert ".(")
4270 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4271 (insert ")"))
4272
4273 (cl-defstruct (js2-xml-ref-node
4274 (:include js2-node)
4275 (:constructor nil)) ; abstract
4276 "Base type for E4X XML attribute-access or property-get expressions.
4277 Such expressions can take a variety of forms. The general syntax has
4278 three parts:
4279
4280 - (optional) an @ (specifying an attribute access)
4281 - (optional) a namespace (a `js2-name-node') and double-colon
4282 - (required) either a `js2-name-node' or a bracketed [expression]
4283
4284 The property-name expressions (examples: ns::name, @name) are
4285 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4286 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4287
4288 This node type (or more specifically, its subclasses) will sometimes
4289 be the right-hand child of a `js2-prop-get-node' or a
4290 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4291 The `js2-xml-ref-node' may also be a standalone primary expression with
4292 no explicit target, which is valid in certain expression contexts such as
4293
4294 company..employee.(@id < 100)
4295
4296 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4297 expression whose parent is a `js2-xml-dot-query-node'."
4298 namespace
4299 at-pos
4300 colon-pos)
4301
4302 (defsubst js2-xml-ref-node-attr-access-p (node)
4303 "Return non-nil if this expression began with an @-token."
4304 (and (numberp (js2-xml-ref-node-at-pos node))
4305 (cl-plusp (js2-xml-ref-node-at-pos node))))
4306
4307 (cl-defstruct (js2-xml-prop-ref-node
4308 (:include js2-xml-ref-node)
4309 (:constructor nil)
4310 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4311 (pos (js2-current-token-beg))
4312 len propname
4313 namespace at-pos
4314 colon-pos)))
4315 "AST node for an E4X XML [expr] property-ref expression.
4316 The JavaScript syntax is an optional @, an optional ns::, and a name.
4317
4318 [ '@' ] [ name '::' ] name
4319
4320 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4321 @ns::*, @*::attr, @*::*, and @*.
4322
4323 The node starts at the @ token, if present. Otherwise it starts at the
4324 namespace name. The node bounds extend through the closing right-bracket,
4325 or if it is missing due to a syntax error, through the end of the index
4326 expression."
4327 propname)
4328
4329 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4330 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4331
4332 (defun js2-visit-xml-prop-ref-node (n v)
4333 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4334 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4335
4336 (defun js2-print-xml-prop-ref-node (n i)
4337 (insert (js2-make-pad i))
4338 (if (js2-xml-ref-node-attr-access-p n)
4339 (insert "@"))
4340 (when (js2-xml-prop-ref-node-namespace n)
4341 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4342 (insert "::"))
4343 (if (js2-xml-prop-ref-node-propname n)
4344 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4345
4346 (cl-defstruct (js2-xml-elem-ref-node
4347 (:include js2-xml-ref-node)
4348 (:constructor nil)
4349 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4350 (pos (js2-current-token-beg))
4351 len expr lb rb
4352 namespace at-pos
4353 colon-pos)))
4354 "AST node for an E4X XML [expr] member-ref expression.
4355 Syntax:
4356
4357 [ '@' ] [ name '::' ] '[' expr ']'
4358
4359 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4360
4361 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4362 is not a legal E4X XML element-ref expression, since it's already used
4363 for standard JavaScript element-get array indexing. Hence, a
4364 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4365 non-nil namespace node, or both.
4366
4367 The node starts at the @ token, if present. Otherwise it starts
4368 at the namespace name. The node bounds extend through the closing
4369 right-bracket, or if it is missing due to a syntax error, through the
4370 end of the index expression."
4371 expr ; the bracketed index expression
4372 lb
4373 rb)
4374
4375 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4376 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4377
4378 (defun js2-visit-xml-elem-ref-node (n v)
4379 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4380 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4381
4382 (defun js2-print-xml-elem-ref-node (n i)
4383 (insert (js2-make-pad i))
4384 (if (js2-xml-ref-node-attr-access-p n)
4385 (insert "@"))
4386 (when (js2-xml-elem-ref-node-namespace n)
4387 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4388 (insert "::"))
4389 (insert "[")
4390 (if (js2-xml-elem-ref-node-expr n)
4391 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4392 (insert "]"))
4393
4394 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4395
4396 (cl-defstruct (js2-xml-start-tag-node
4397 (:include js2-xml-node)
4398 (:constructor nil)
4399 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4400 (pos js2-ts-cursor)
4401 len name attrs kids
4402 empty-p)))
4403 "AST node for an XML start-tag. Not currently used.
4404 The `kids' field is a Lisp list of child content nodes."
4405 name ; a `js2-xml-name-node'
4406 attrs ; a Lisp list of `js2-xml-attr-node'
4407 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4408
4409 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4410 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4411
4412 (defun js2-visit-xml-start-tag (n v)
4413 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4414 (dolist (attr (js2-xml-start-tag-node-attrs n))
4415 (js2-visit-ast attr v))
4416 (js2-visit-block n v))
4417
4418 (defun js2-print-xml-start-tag (n i)
4419 (insert (js2-make-pad i) "<")
4420 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4421 (when (js2-xml-start-tag-node-attrs n)
4422 (insert " ")
4423 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4424 (insert ">"))
4425
4426 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4427 ;; and add the end-tag to the kids list of the parent as well.
4428 (cl-defstruct (js2-xml-end-tag-node
4429 (:include js2-xml-node)
4430 (:constructor nil)
4431 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4432 (pos js2-ts-cursor)
4433 len name)))
4434 "AST node for an XML end-tag. Not currently used."
4435 name) ; a `js2-xml-name-node'
4436
4437 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4438 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4439
4440 (defun js2-visit-xml-end-tag (n v)
4441 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4442
4443 (defun js2-print-xml-end-tag (n i)
4444 (insert (js2-make-pad i))
4445 (insert "</")
4446 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4447 (insert ">"))
4448
4449 (cl-defstruct (js2-xml-name-node
4450 (:include js2-xml-node)
4451 (:constructor nil)
4452 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4453 (pos js2-ts-cursor)
4454 len namespace kids)))
4455 "AST node for an E4X XML name. Not currently used.
4456 Any XML name can be qualified with a namespace, hence the namespace field.
4457 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4458 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4459 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4460 namespace) ; a `js2-string-node'
4461
4462 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4463 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4464
4465 (defun js2-visit-xml-name-node (n v)
4466 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4467
4468 (defun js2-print-xml-name-node (n i)
4469 (insert (js2-make-pad i))
4470 (when (js2-xml-name-node-namespace n)
4471 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4472 (insert "::"))
4473 (dolist (kid (js2-xml-name-node-kids n))
4474 (js2-print-ast kid 0)))
4475
4476 (cl-defstruct (js2-xml-pi-node
4477 (:include js2-xml-node)
4478 (:constructor nil)
4479 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4480 (pos js2-ts-cursor)
4481 len name attrs)))
4482 "AST node for an E4X XML processing instruction. Not currently used."
4483 name ; a `js2-xml-name-node'
4484 attrs) ; a list of `js2-xml-attr-node'
4485
4486 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4487 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4488
4489 (defun js2-visit-xml-pi-node (n v)
4490 (js2-visit-ast (js2-xml-pi-node-name n) v)
4491 (dolist (attr (js2-xml-pi-node-attrs n))
4492 (js2-visit-ast attr v)))
4493
4494 (defun js2-print-xml-pi-node (n i)
4495 (insert (js2-make-pad i) "<?")
4496 (js2-print-ast (js2-xml-pi-node-name n))
4497 (when (js2-xml-pi-node-attrs n)
4498 (insert " ")
4499 (js2-print-list (js2-xml-pi-node-attrs n)))
4500 (insert "?>"))
4501
4502 (cl-defstruct (js2-xml-cdata-node
4503 (:include js2-xml-node)
4504 (:constructor nil)
4505 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4506 (pos js2-ts-cursor)
4507 len content)))
4508 "AST node for a CDATA escape section. Not currently used."
4509 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4510
4511 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4512 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4513
4514 (defun js2-visit-xml-cdata-node (n v)
4515 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4516
4517 (defun js2-print-xml-cdata-node (n i)
4518 (insert (js2-make-pad i))
4519 (js2-print-ast (js2-xml-cdata-node-content n)))
4520
4521 (cl-defstruct (js2-xml-attr-node
4522 (:include js2-xml-node)
4523 (:constructor nil)
4524 (:constructor make-js2-attr-node (&key (type js2-XML)
4525 (pos js2-ts-cursor)
4526 len name value
4527 eq-pos quote-type)))
4528 "AST node representing a foo='bar' XML attribute value. Not yet used."
4529 name ; a `js2-xml-name-node'
4530 value ; a `js2-xml-name-node'
4531 eq-pos ; buffer position of "=" sign
4532 quote-type) ; 'single or 'double
4533
4534 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4535 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4536
4537 (defun js2-visit-xml-attr-node (n v)
4538 (js2-visit-ast (js2-xml-attr-node-name n) v)
4539 (js2-visit-ast (js2-xml-attr-node-value n) v))
4540
4541 (defun js2-print-xml-attr-node (n i)
4542 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4543 "'"
4544 "\"")))
4545 (insert (js2-make-pad i))
4546 (js2-print-ast (js2-xml-attr-node-name n) 0)
4547 (insert "=" quote)
4548 (js2-print-ast (js2-xml-attr-node-value n) 0)
4549 (insert quote)))
4550
4551 (cl-defstruct (js2-xml-text-node
4552 (:include js2-xml-node)
4553 (:constructor nil)
4554 (:constructor make-js2-text-node (&key (type js2-XML)
4555 (pos js2-ts-cursor)
4556 len content)))
4557 "AST node for an E4X XML text node. Not currently used."
4558 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4559
4560 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4561 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4562
4563 (defun js2-visit-xml-text-node (n v)
4564 (js2-visit-ast (js2-xml-text-node-content n) v))
4565
4566 (defun js2-print-xml-text-node (n i)
4567 (insert (js2-make-pad i))
4568 (dolist (kid (js2-xml-text-node-content n))
4569 (js2-print-ast kid)))
4570
4571 (cl-defstruct (js2-xml-comment-node
4572 (:include js2-xml-node)
4573 (:constructor nil)
4574 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4575 (pos js2-ts-cursor)
4576 len)))
4577 "AST node for E4X XML comment. Not currently used.")
4578
4579 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4580 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4581
4582 (defun js2-print-xml-comment (n i)
4583 (insert (js2-make-pad i)
4584 (js2-node-string n)))
4585
4586 ;;; Node utilities
4587
4588 (defsubst js2-node-line (n)
4589 "Fetch the source line number at the start of node N.
4590 This is O(n) in the length of the source buffer; use prudently."
4591 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4592
4593 (defsubst js2-block-node-kid (n i)
4594 "Return child I of node N, or nil if there aren't that many."
4595 (nth i (js2-block-node-kids n)))
4596
4597 (defsubst js2-block-node-first (n)
4598 "Return first child of block node N, or nil if there is none."
4599 (cl-first (js2-block-node-kids n)))
4600
4601 (defun js2-node-root (n)
4602 "Return the root of the AST containing N.
4603 If N has no parent pointer, returns N."
4604 (let ((parent (js2-node-parent n)))
4605 (if parent
4606 (js2-node-root parent)
4607 n)))
4608
4609 (defsubst js2-node-short-name (n)
4610 "Return the short name of node N as a string, e.g. `js2-if-node'."
4611 (substring (symbol-name (aref n 0))
4612 (length "cl-struct-")))
4613
4614 (defun js2-node-child-list (node)
4615 "Return the child list for NODE, a Lisp list of nodes.
4616 Works for block nodes, array nodes, obj literals, funarg lists,
4617 var decls and try nodes (for catch clauses). Note that you should call
4618 `js2-block-node-kids' on the function body for the body statements.
4619 Returns nil for zero-length child lists or unsupported nodes."
4620 (cond
4621 ((js2-function-node-p node)
4622 (js2-function-node-params node))
4623 ((js2-block-node-p node)
4624 (js2-block-node-kids node))
4625 ((js2-try-node-p node)
4626 (js2-try-node-catch-clauses node))
4627 ((js2-array-node-p node)
4628 (js2-array-node-elems node))
4629 ((js2-object-node-p node)
4630 (js2-object-node-elems node))
4631 ((js2-call-node-p node)
4632 (js2-call-node-args node))
4633 ((js2-new-node-p node)
4634 (js2-new-node-args node))
4635 ((js2-var-decl-node-p node)
4636 (js2-var-decl-node-kids node))
4637 (t
4638 nil)))
4639
4640 (defun js2-node-set-child-list (node kids)
4641 "Set the child list for NODE to KIDS."
4642 (cond
4643 ((js2-function-node-p node)
4644 (setf (js2-function-node-params node) kids))
4645 ((js2-block-node-p node)
4646 (setf (js2-block-node-kids node) kids))
4647 ((js2-try-node-p node)
4648 (setf (js2-try-node-catch-clauses node) kids))
4649 ((js2-array-node-p node)
4650 (setf (js2-array-node-elems node) kids))
4651 ((js2-object-node-p node)
4652 (setf (js2-object-node-elems node) kids))
4653 ((js2-call-node-p node)
4654 (setf (js2-call-node-args node) kids))
4655 ((js2-new-node-p node)
4656 (setf (js2-new-node-args node) kids))
4657 ((js2-var-decl-node-p node)
4658 (setf (js2-var-decl-node-kids node) kids))
4659 (t
4660 (error "Unsupported node type: %s" (js2-node-short-name node))))
4661 kids)
4662
4663 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4664 (defconst js2-paren-expr-nodes
4665 '(cl-struct-js2-comp-loop-node
4666 cl-struct-js2-comp-node
4667 cl-struct-js2-call-node
4668 cl-struct-js2-catch-node
4669 cl-struct-js2-do-node
4670 cl-struct-js2-elem-get-node
4671 cl-struct-js2-for-in-node
4672 cl-struct-js2-for-node
4673 cl-struct-js2-function-node
4674 cl-struct-js2-if-node
4675 cl-struct-js2-let-node
4676 cl-struct-js2-new-node
4677 cl-struct-js2-paren-node
4678 cl-struct-js2-switch-node
4679 cl-struct-js2-while-node
4680 cl-struct-js2-with-node
4681 cl-struct-js2-xml-dot-query-node)
4682 "Node types that can have a parenthesized child expression.
4683 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4684
4685 (defsubst js2-paren-expr-node-p (node)
4686 "Return t for nodes that typically have a parenthesized child expression.
4687 Useful for computing the indentation anchors for arg-lists and conditions.
4688 Note that it may return a false positive, for instance when NODE is
4689 a `js2-new-node' and there are no arguments or parentheses."
4690 (memq (aref node 0) js2-paren-expr-nodes))
4691
4692 ;; Fake polymorphism... yech.
4693 (defun js2-node-lp (node)
4694 "Return relative left-paren position for NODE, if applicable.
4695 For `js2-elem-get-node' structs, returns left-bracket position.
4696 Note that the position may be nil in the case of a parse error."
4697 (cond
4698 ((js2-elem-get-node-p node)
4699 (js2-elem-get-node-lb node))
4700 ((js2-loop-node-p node)
4701 (js2-loop-node-lp node))
4702 ((js2-function-node-p node)
4703 (js2-function-node-lp node))
4704 ((js2-if-node-p node)
4705 (js2-if-node-lp node))
4706 ((js2-new-node-p node)
4707 (js2-new-node-lp node))
4708 ((js2-call-node-p node)
4709 (js2-call-node-lp node))
4710 ((js2-paren-node-p node)
4711 0)
4712 ((js2-switch-node-p node)
4713 (js2-switch-node-lp node))
4714 ((js2-catch-node-p node)
4715 (js2-catch-node-lp node))
4716 ((js2-let-node-p node)
4717 (js2-let-node-lp node))
4718 ((js2-comp-node-p node)
4719 0)
4720 ((js2-with-node-p node)
4721 (js2-with-node-lp node))
4722 ((js2-xml-dot-query-node-p node)
4723 (1+ (js2-infix-node-op-pos node)))
4724 (t
4725 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4726
4727 ;; Fake polymorphism... blech.
4728 (defun js2-node-rp (node)
4729 "Return relative right-paren position for NODE, if applicable.
4730 For `js2-elem-get-node' structs, returns right-bracket position.
4731 Note that the position may be nil in the case of a parse error."
4732 (cond
4733 ((js2-elem-get-node-p node)
4734 (js2-elem-get-node-rb node))
4735 ((js2-loop-node-p node)
4736 (js2-loop-node-rp node))
4737 ((js2-function-node-p node)
4738 (js2-function-node-rp node))
4739 ((js2-if-node-p node)
4740 (js2-if-node-rp node))
4741 ((js2-new-node-p node)
4742 (js2-new-node-rp node))
4743 ((js2-call-node-p node)
4744 (js2-call-node-rp node))
4745 ((js2-paren-node-p node)
4746 (1- (js2-node-len node)))
4747 ((js2-switch-node-p node)
4748 (js2-switch-node-rp node))
4749 ((js2-catch-node-p node)
4750 (js2-catch-node-rp node))
4751 ((js2-let-node-p node)
4752 (js2-let-node-rp node))
4753 ((js2-comp-node-p node)
4754 (1- (js2-node-len node)))
4755 ((js2-with-node-p node)
4756 (js2-with-node-rp node))
4757 ((js2-xml-dot-query-node-p node)
4758 (1+ (js2-xml-dot-query-node-rp node)))
4759 (t
4760 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4761
4762 (defsubst js2-node-first-child (node)
4763 "Return the first element of `js2-node-child-list' for NODE."
4764 (car (js2-node-child-list node)))
4765
4766 (defsubst js2-node-last-child (node)
4767 "Return the last element of `js2-node-last-child' for NODE."
4768 (car (last (js2-node-child-list node))))
4769
4770 (defun js2-node-prev-sibling (node)
4771 "Return the previous statement in parent.
4772 Works for parents supported by `js2-node-child-list'.
4773 Returns nil if NODE is not in the parent, or PARENT is
4774 not a supported node, or if NODE is the first child."
4775 (let* ((p (js2-node-parent node))
4776 (kids (js2-node-child-list p))
4777 (sib (car kids)))
4778 (while (and kids
4779 (not (eq node (cadr kids))))
4780 (setq kids (cdr kids)
4781 sib (car kids)))
4782 sib))
4783
4784 (defun js2-node-next-sibling (node)
4785 "Return the next statement in parent block.
4786 Returns nil if NODE is not in the block, or PARENT is not
4787 a block node, or if NODE is the last statement."
4788 (let* ((p (js2-node-parent node))
4789 (kids (js2-node-child-list p)))
4790 (while (and kids
4791 (not (eq node (car kids))))
4792 (setq kids (cdr kids)))
4793 (cadr kids)))
4794
4795 (defun js2-node-find-child-before (pos parent &optional after)
4796 "Find the last child that starts before POS in parent.
4797 If AFTER is non-nil, returns first child starting after POS.
4798 POS is an absolute buffer position. PARENT is any node
4799 supported by `js2-node-child-list'.
4800 Returns nil if no applicable child is found."
4801 (let ((kids (if (js2-function-node-p parent)
4802 (js2-block-node-kids (js2-function-node-body parent))
4803 (js2-node-child-list parent)))
4804 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4805 (js2-function-node-body parent)
4806 parent)))
4807 kid result fn
4808 (continue t))
4809 (setq fn (if after '>= '<))
4810 (while (and kids continue)
4811 (setq kid (car kids))
4812 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4813 (setq result kid
4814 continue (not after))
4815 (setq continue after))
4816 (setq kids (cdr kids)))
4817 result))
4818
4819 (defun js2-node-find-child-after (pos parent)
4820 "Find first child that starts after POS in parent.
4821 POS is an absolute buffer position. PARENT is any node
4822 supported by `js2-node-child-list'.
4823 Returns nil if no applicable child is found."
4824 (js2-node-find-child-before pos parent 'after))
4825
4826 (defun js2-node-replace-child (pos parent new-node)
4827 "Replace node at index POS in PARENT with NEW-NODE.
4828 Only works for parents supported by `js2-node-child-list'."
4829 (let ((kids (js2-node-child-list parent))
4830 (i 0))
4831 (while (< i pos)
4832 (setq kids (cdr kids)
4833 i (1+ i)))
4834 (setcar kids new-node)
4835 (js2-node-add-children parent new-node)))
4836
4837 (defun js2-node-buffer (n)
4838 "Return the buffer associated with AST N.
4839 Returns nil if the buffer is not set as a property on the root
4840 node, or if parent links were not recorded during parsing."
4841 (let ((root (js2-node-root n)))
4842 (and root
4843 (js2-ast-root-p root)
4844 (js2-ast-root-buffer root))))
4845
4846 (defun js2-block-node-push (n kid)
4847 "Push js2-node KID onto the end of js2-block-node N's child list.
4848 KID is always added to the -end- of the kids list.
4849 Function also calls `js2-node-add-children' to add the parent link."
4850 (let ((kids (js2-node-child-list n)))
4851 (if kids
4852 (setcdr kids (nconc (cdr kids) (list kid)))
4853 (js2-node-set-child-list n (list kid)))
4854 (js2-node-add-children n kid)))
4855
4856 (defun js2-node-string (node)
4857 (with-current-buffer (or (js2-node-buffer node)
4858 (error "No buffer available for node %s" node))
4859 (let ((pos (js2-node-abs-pos node)))
4860 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4861
4862 ;; Container for storing the node we're looking for in a traversal.
4863 (js2-deflocal js2-discovered-node nil)
4864
4865 ;; Keep track of absolute node position during traversals.
4866 (js2-deflocal js2-visitor-offset nil)
4867
4868 (js2-deflocal js2-node-search-point nil)
4869
4870 (when js2-mode-dev-mode-p
4871 (defun js2-find-node-at-point ()
4872 (interactive)
4873 (let ((node (js2-node-at-point)))
4874 (message "%s" (or node "No node found at point"))))
4875 (defun js2-node-name-at-point ()
4876 (interactive)
4877 (let ((node (js2-node-at-point)))
4878 (message "%s" (if node
4879 (js2-node-short-name node)
4880 "No node found at point.")))))
4881
4882 (defun js2-node-at-point (&optional pos skip-comments)
4883 "Return AST node at POS, a buffer position, defaulting to current point.
4884 The `js2-mode-ast' variable must be set to the current parse tree.
4885 Signals an error if the AST (`js2-mode-ast') is nil.
4886 Always returns a node - if it can't find one, it returns the root.
4887 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4888 (let ((ast js2-mode-ast)
4889 result)
4890 (unless ast
4891 (error "No JavaScript AST available"))
4892 ;; Look through comments first, since they may be inside nodes that
4893 ;; would otherwise report a match.
4894 (setq pos (or pos (point))
4895 result (if (> pos (js2-node-abs-end ast))
4896 ast
4897 (if (not skip-comments)
4898 (js2-comment-at-point pos))))
4899 (unless result
4900 (setq js2-discovered-node nil
4901 js2-visitor-offset 0
4902 js2-node-search-point pos)
4903 (unwind-protect
4904 (catch 'js2-visit-done
4905 (js2-visit-ast ast #'js2-node-at-point-visitor))
4906 (setq js2-visitor-offset nil
4907 js2-node-search-point nil))
4908 (setq result js2-discovered-node))
4909 ;; may have found a comment beyond end of last child node,
4910 ;; since visiting the ast-root looks at the comment-list last.
4911 (if (and skip-comments
4912 (js2-comment-node-p result))
4913 (setq result nil))
4914 (or result js2-mode-ast)))
4915
4916 (defun js2-node-at-point-visitor (node end-p)
4917 (let ((rel-pos (js2-node-pos node))
4918 abs-pos
4919 abs-end
4920 (point js2-node-search-point))
4921 (cond
4922 (end-p
4923 ;; this evaluates to a non-nil return value, even if it's zero
4924 (cl-decf js2-visitor-offset rel-pos))
4925 ;; we already looked for comments before visiting, and don't want them now
4926 ((js2-comment-node-p node)
4927 nil)
4928 (t
4929 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4930 ;; we only want to use the node if the point is before
4931 ;; the last character position in the node, so we decrement
4932 ;; the absolute end by 1.
4933 abs-end (+ abs-pos (js2-node-len node) -1))
4934 (cond
4935 ;; If this node starts after search-point, stop the search.
4936 ((> abs-pos point)
4937 (throw 'js2-visit-done nil))
4938 ;; If this node ends before the search-point, don't check kids.
4939 ((> point abs-end)
4940 nil)
4941 (t
4942 ;; Otherwise point is within this node, possibly in a child.
4943 (setq js2-discovered-node node)
4944 t)))))) ; keep processing kids to look for more specific match
4945
4946 (defsubst js2-block-comment-p (node)
4947 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4948 (and (js2-comment-node-p node)
4949 (memq (js2-comment-node-format node) '(jsdoc block))))
4950
4951 ;; TODO: put the comments in a vector and binary-search them instead
4952 (defun js2-comment-at-point (&optional pos)
4953 "Look through scanned comment nodes for one containing POS.
4954 POS is a buffer position that defaults to current point.
4955 Function returns nil if POS was not in any comment node."
4956 (let ((ast js2-mode-ast)
4957 (x (or pos (point)))
4958 beg end)
4959 (unless ast
4960 (error "No JavaScript AST available"))
4961 (catch 'done
4962 ;; Comments are stored in lexical order.
4963 (dolist (comment (js2-ast-root-comments ast) nil)
4964 (setq beg (js2-node-abs-pos comment)
4965 end (+ beg (js2-node-len comment)))
4966 (if (and (>= x beg)
4967 (<= x end))
4968 (throw 'done comment))))))
4969
4970 (defun js2-mode-find-parent-fn (node)
4971 "Find function enclosing NODE.
4972 Returns nil if NODE is not inside a function."
4973 (setq node (js2-node-parent node))
4974 (while (and node (not (js2-function-node-p node)))
4975 (setq node (js2-node-parent node)))
4976 (and (js2-function-node-p node) node))
4977
4978 (defun js2-mode-find-enclosing-fn (node)
4979 "Find function or root enclosing NODE."
4980 (if (js2-ast-root-p node)
4981 node
4982 (setq node (js2-node-parent node))
4983 (while (not (or (js2-ast-root-p node)
4984 (js2-function-node-p node)))
4985 (setq node (js2-node-parent node)))
4986 node))
4987
4988 (defun js2-mode-find-enclosing-node (beg end)
4989 "Find node fully enclosing BEG and END."
4990 (let ((node (js2-node-at-point beg))
4991 pos
4992 (continue t))
4993 (while continue
4994 (if (or (js2-ast-root-p node)
4995 (and
4996 (<= (setq pos (js2-node-abs-pos node)) beg)
4997 (>= (+ pos (js2-node-len node)) end)))
4998 (setq continue nil)
4999 (setq node (js2-node-parent node))))
5000 node))
5001
5002 (defun js2-node-parent-script-or-fn (node)
5003 "Find script or function immediately enclosing NODE.
5004 If NODE is the ast-root, returns nil."
5005 (if (js2-ast-root-p node)
5006 nil
5007 (setq node (js2-node-parent node))
5008 (while (and node (not (or (js2-function-node-p node)
5009 (js2-script-node-p node))))
5010 (setq node (js2-node-parent node)))
5011 node))
5012
5013 (defun js2-node-is-descendant (node ancestor)
5014 "Return t if NODE is a descendant of ANCESTOR."
5015 (while (and node
5016 (not (eq node ancestor)))
5017 (setq node (js2-node-parent node)))
5018 node)
5019
5020 ;;; visitor infrastructure
5021
5022 (defun js2-visit-none (_node _callback)
5023 "Visitor for AST node that have no node children."
5024 nil)
5025
5026 (defun js2-print-none (_node _indent)
5027 "Visitor for AST node with no printed representation.")
5028
5029 (defun js2-print-body (node indent)
5030 "Print a statement, or a block without braces."
5031 (if (js2-block-node-p node)
5032 (dolist (kid (js2-block-node-kids node))
5033 (js2-print-ast kid indent))
5034 (js2-print-ast node indent)))
5035
5036 (defun js2-print-list (args &optional delimiter)
5037 (cl-loop with len = (length args)
5038 for arg in args
5039 for count from 1
5040 do
5041 (when arg (js2-print-ast arg 0))
5042 (if (< count len)
5043 (insert (or delimiter ", ")))))
5044
5045 (defun js2-print-tree (ast)
5046 "Prints an AST to the current buffer.
5047 Makes `js2-ast-parent-nodes' available to the printer functions."
5048 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5049 (js2-print-ast ast)))
5050
5051 (defun js2-print-ast (node &optional indent)
5052 "Helper function for printing AST nodes.
5053 Requires `js2-ast-parent-nodes' to be non-nil.
5054 You should use `js2-print-tree' instead of this function."
5055 (let ((printer (get (aref node 0) 'js2-printer))
5056 (i (or indent 0)))
5057 ;; TODO: wedge comments in here somewhere
5058 (if printer
5059 (funcall printer node i))))
5060
5061 (defconst js2-side-effecting-tokens
5062 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5063 (dolist (tt (list js2-ASSIGN
5064 js2-ASSIGN_ADD
5065 js2-ASSIGN_BITAND
5066 js2-ASSIGN_BITOR
5067 js2-ASSIGN_BITXOR
5068 js2-ASSIGN_DIV
5069 js2-ASSIGN_LSH
5070 js2-ASSIGN_MOD
5071 js2-ASSIGN_MUL
5072 js2-ASSIGN_RSH
5073 js2-ASSIGN_SUB
5074 js2-ASSIGN_URSH
5075 js2-BLOCK
5076 js2-BREAK
5077 js2-CALL
5078 js2-CATCH
5079 js2-CATCH_SCOPE
5080 js2-CLASS
5081 js2-CONST
5082 js2-CONTINUE
5083 js2-DEBUGGER
5084 js2-DEC
5085 js2-DELPROP
5086 js2-DEL_REF
5087 js2-DO
5088 js2-ELSE
5089 js2-EMPTY
5090 js2-ENTERWITH
5091 js2-EXPORT
5092 js2-EXPR_RESULT
5093 js2-FINALLY
5094 js2-FOR
5095 js2-FUNCTION
5096 js2-GOTO
5097 js2-IF
5098 js2-IFEQ
5099 js2-IFNE
5100 js2-IMPORT
5101 js2-INC
5102 js2-JSR
5103 js2-LABEL
5104 js2-LEAVEWITH
5105 js2-LET
5106 js2-LETEXPR
5107 js2-LOCAL_BLOCK
5108 js2-LOOP
5109 js2-NEW
5110 js2-REF_CALL
5111 js2-RETHROW
5112 js2-RETURN
5113 js2-RETURN_RESULT
5114 js2-SEMI
5115 js2-SETELEM
5116 js2-SETELEM_OP
5117 js2-SETNAME
5118 js2-SETPROP
5119 js2-SETPROP_OP
5120 js2-SETVAR
5121 js2-SET_REF
5122 js2-SET_REF_OP
5123 js2-SWITCH
5124 js2-TARGET
5125 js2-THROW
5126 js2-TRY
5127 js2-VAR
5128 js2-WHILE
5129 js2-WITH
5130 js2-WITHEXPR
5131 js2-YIELD))
5132 (aset tokens tt t))
5133 (if js2-instanceof-has-side-effects
5134 (aset tokens js2-INSTANCEOF t))
5135 tokens))
5136
5137 (defun js2-node-has-side-effects (node)
5138 "Return t if NODE has side effects."
5139 (when node ; makes it easier to handle malformed expressions
5140 (let ((tt (js2-node-type node)))
5141 (cond
5142 ;; This doubtless needs some work, since EXPR_VOID is used
5143 ;; in several ways in Rhino and I may not have caught them all.
5144 ;; I'll wait for people to notice incorrect warnings.
5145 ((and (= tt js2-EXPR_VOID)
5146 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5147 (let ((expr (js2-expr-stmt-node-expr node)))
5148 (or (js2-node-has-side-effects expr)
5149 (when (js2-string-node-p expr)
5150 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5151 ((= tt js2-AWAIT)
5152 (js2-node-has-side-effects (js2-unary-node-operand node)))
5153 ((= tt js2-COMMA)
5154 (js2-node-has-side-effects (js2-infix-node-right node)))
5155 ((or (= tt js2-AND)
5156 (= tt js2-OR))
5157 (or (js2-node-has-side-effects (js2-infix-node-right node))
5158 (js2-node-has-side-effects (js2-infix-node-left node))))
5159 ((= tt js2-HOOK)
5160 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5161 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5162 ((js2-paren-node-p node)
5163 (js2-node-has-side-effects (js2-paren-node-expr node)))
5164 ((= tt js2-ERROR) ; avoid cascaded error messages
5165 nil)
5166 (t
5167 (aref js2-side-effecting-tokens tt))))))
5168
5169 (defconst js2-stmt-node-types
5170 (list js2-BLOCK
5171 js2-BREAK
5172 js2-CONTINUE
5173 js2-DEFAULT ; e4x "default xml namespace" statement
5174 js2-DO
5175 js2-EXPORT
5176 js2-EXPR_RESULT
5177 js2-EXPR_VOID
5178 js2-FOR
5179 js2-IF
5180 js2-IMPORT
5181 js2-RETURN
5182 js2-SWITCH
5183 js2-THROW
5184 js2-TRY
5185 js2-WHILE
5186 js2-WITH)
5187 "Node types that only appear in statement contexts.
5188 The list does not include nodes that always appear as the child
5189 of another specific statement type, such as switch-cases,
5190 catch and finally blocks, and else-clauses. The list also excludes
5191 nodes like yield, let and var, which may appear in either expression
5192 or statement context, and in the latter context always have a
5193 `js2-expr-stmt-node' parent. Finally, the list does not include
5194 functions or scripts, which are treated separately from statements
5195 by the JavaScript parser and runtime.")
5196
5197 (defun js2-stmt-node-p (node)
5198 "Heuristic for figuring out if NODE is a statement.
5199 Some node types can appear in either an expression context or a
5200 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5201 For these node types in a statement context, the parent will be a
5202 `js2-expr-stmt-node'.
5203 Functions aren't included in the check."
5204 (memq (js2-node-type node) js2-stmt-node-types))
5205
5206 (defun js2-mode-find-first-stmt (node)
5207 "Search upward starting from NODE looking for a statement.
5208 For purposes of this function, a `js2-function-node' counts."
5209 (while (not (or (js2-stmt-node-p node)
5210 (js2-function-node-p node)))
5211 (setq node (js2-node-parent node)))
5212 node)
5213
5214 (defun js2-node-parent-stmt (node)
5215 "Return the node's first ancestor that is a statement.
5216 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5217 appearing in a statement context will have a parent that is a
5218 `js2-expr-stmt-node' that will be returned by this function."
5219 (let ((parent (js2-node-parent node)))
5220 (if (or (null parent)
5221 (js2-stmt-node-p parent)
5222 (and (js2-function-node-p parent)
5223 (not (eq (js2-function-node-form parent)
5224 'FUNCTION_EXPRESSION))))
5225 parent
5226 (js2-node-parent-stmt parent))))
5227
5228 ;; In the Mozilla Rhino sources, Roshan James writes:
5229 ;; Does consistent-return analysis on the function body when strict mode is
5230 ;; enabled.
5231 ;;
5232 ;; function (x) { return (x+1) }
5233 ;;
5234 ;; is ok, but
5235 ;;
5236 ;; function (x) { if (x < 0) return (x+1); }
5237 ;;
5238 ;; is not because the function can potentially return a value when the
5239 ;; condition is satisfied and if not, the function does not explicitly
5240 ;; return a value.
5241 ;;
5242 ;; This extends to checking mismatches such as "return" and "return <value>"
5243 ;; used in the same function. Warnings are not emitted if inconsistent
5244 ;; returns exist in code that can be statically shown to be unreachable.
5245 ;; Ex.
5246 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5247 ;;
5248 ;; emits no warning. However if the loop had a break statement, then a
5249 ;; warning would be emitted.
5250 ;;
5251 ;; The consistency analysis looks at control structures such as loops, ifs,
5252 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5253 ;; warns the user about an inconsistent set of termination possibilities.
5254 ;;
5255 ;; These flags enumerate the possible ways a statement/function can
5256 ;; terminate. These flags are used by endCheck() and by the Parser to
5257 ;; detect inconsistent return usage.
5258 ;;
5259 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5260 ;; able to execute (example: throw, continue)
5261 ;;
5262 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5263 ;; next one. Statement such as return dont. A compound statement may have
5264 ;; some branch that drops off control to the next statement.
5265 ;;
5266 ;; END_RETURNS indicates that the statement can return with no value.
5267 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5268 ;;
5269 ;; A compound statement such as
5270 ;; if (condition) {
5271 ;; return value;
5272 ;; }
5273 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5274
5275 (defconst js2-END_UNREACHED 0)
5276 (defconst js2-END_DROPS_OFF 1)
5277 (defconst js2-END_RETURNS 2)
5278 (defconst js2-END_RETURNS_VALUE 4)
5279 (defconst js2-END_YIELDS 8)
5280
5281 (defun js2-has-consistent-return-usage (node)
5282 "Check that every return usage in a function body is consistent.
5283 Returns t if the function satisfies strict mode requirement."
5284 (let ((n (js2-end-check node)))
5285 ;; either it doesn't return a value in any branch...
5286 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5287 ;; or it returns a value (or is unreached) at every branch
5288 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5289 js2-END_RETURNS
5290 js2-END_YIELDS)))))
5291
5292 (defun js2-end-check-if (node)
5293 "Ensure that return usage in then/else blocks is consistent.
5294 If there is no else block, then the return statement can fall through.
5295 Returns logical OR of END_* flags"
5296 (let ((th (js2-if-node-then-part node))
5297 (el (js2-if-node-else-part node)))
5298 (if (null th)
5299 js2-END_UNREACHED
5300 (logior (js2-end-check th) (if el
5301 (js2-end-check el)
5302 js2-END_DROPS_OFF)))))
5303
5304 (defun js2-end-check-switch (node)
5305 "Consistency of return statements is checked between the case statements.
5306 If there is no default, then the switch can fall through. If there is a
5307 default, we check to see if all code paths in the default return or if
5308 there is a code path that can fall through.
5309 Returns logical OR of END_* flags."
5310 (let ((rv js2-END_UNREACHED)
5311 default-case)
5312 ;; examine the cases
5313 (catch 'break
5314 (dolist (c (js2-switch-node-cases node))
5315 (if (js2-case-node-expr c)
5316 (js2-set-flag rv (js2-end-check-block c))
5317 (setq default-case c)
5318 (throw 'break nil))))
5319 ;; we don't care how the cases drop into each other
5320 (js2-clear-flag rv js2-END_DROPS_OFF)
5321 ;; examine the default
5322 (js2-set-flag rv (if default-case
5323 (js2-end-check default-case)
5324 js2-END_DROPS_OFF))
5325 rv))
5326
5327 (defun js2-end-check-try (node)
5328 "If the block has a finally, return consistency is checked in the
5329 finally block. If all code paths in the finally return, then the
5330 returns in the try-catch blocks don't matter. If there is a code path
5331 that does not return or if there is no finally block, the returns
5332 of the try and catch blocks are checked for mismatch.
5333 Returns logical OR of END_* flags."
5334 (let ((finally (js2-try-node-finally-block node))
5335 rv)
5336 ;; check the finally if it exists
5337 (setq rv (if finally
5338 (js2-end-check (js2-finally-node-body finally))
5339 js2-END_DROPS_OFF))
5340 ;; If the finally block always returns, then none of the returns
5341 ;; in the try or catch blocks matter.
5342 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5343 (js2-clear-flag rv js2-END_DROPS_OFF)
5344 ;; examine the try block
5345 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5346 ;; check each catch block
5347 (dolist (cb (js2-try-node-catch-clauses node))
5348 (js2-set-flag rv (js2-end-check cb))))
5349 rv))
5350
5351 (defun js2-end-check-loop (node)
5352 "Return statement in the loop body must be consistent.
5353 The default assumption for any kind of a loop is that it will eventually
5354 terminate. The only exception is a loop with a constant true condition.
5355 Code that follows such a loop is examined only if one can determine
5356 statically that there is a break out of the loop.
5357
5358 for(... ; ... ; ...) {}
5359 for(... in ... ) {}
5360 while(...) { }
5361 do { } while(...)
5362
5363 Returns logical OR of END_* flags."
5364 (let ((rv (js2-end-check (js2-loop-node-body node)))
5365 (condition (cond
5366 ((js2-while-node-p node)
5367 (js2-while-node-condition node))
5368 ((js2-do-node-p node)
5369 (js2-do-node-condition node))
5370 ((js2-for-node-p node)
5371 (js2-for-node-condition node)))))
5372
5373 ;; check to see if the loop condition is always true
5374 (if (and condition
5375 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5376 (js2-clear-flag rv js2-END_DROPS_OFF))
5377
5378 ;; look for effect of breaks
5379 (js2-set-flag rv (js2-node-get-prop node
5380 'CONTROL_BLOCK_PROP
5381 js2-END_UNREACHED))
5382 rv))
5383
5384 (defun js2-end-check-block (node)
5385 "A general block of code is examined statement by statement.
5386 If any statement (even a compound one) returns in all branches, then
5387 subsequent statements are not examined.
5388 Returns logical OR of END_* flags."
5389 (let* ((rv js2-END_DROPS_OFF)
5390 (kids (js2-block-node-kids node))
5391 (n (car kids)))
5392 ;; Check each statement. If the statement can continue onto the next
5393 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5394 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5395 (js2-clear-flag rv js2-END_DROPS_OFF)
5396 (js2-set-flag rv (js2-end-check n))
5397 (setq kids (cdr kids)
5398 n (car kids)))
5399 rv))
5400
5401 (defun js2-end-check-label (node)
5402 "A labeled statement implies that there may be a break to the label.
5403 The function processes the labeled statement and then checks the
5404 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5405 particular label.
5406 Returns logical OR of END_* flags."
5407 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5408 (logior rv (js2-node-get-prop node
5409 'CONTROL_BLOCK_PROP
5410 js2-END_UNREACHED))))
5411
5412 (defun js2-end-check-break (node)
5413 "When a break is encountered annotate the statement being broken
5414 out of by setting its CONTROL_BLOCK_PROP property.
5415 Returns logical OR of END_* flags."
5416 (and (js2-break-node-target node)
5417 (js2-node-set-prop (js2-break-node-target node)
5418 'CONTROL_BLOCK_PROP
5419 js2-END_DROPS_OFF))
5420 js2-END_UNREACHED)
5421
5422 (defun js2-end-check (node)
5423 "Examine the body of a function, doing a basic reachability analysis.
5424 Returns a combination of flags END_* flags that indicate
5425 how the function execution can terminate. These constitute only the
5426 pessimistic set of termination conditions. It is possible that at
5427 runtime certain code paths will never be actually taken. Hence this
5428 analysis will flag errors in cases where there may not be errors.
5429 Returns logical OR of END_* flags"
5430 (let (kid)
5431 (cond
5432 ((js2-break-node-p node)
5433 (js2-end-check-break node))
5434 ((js2-expr-stmt-node-p node)
5435 (if (setq kid (js2-expr-stmt-node-expr node))
5436 (js2-end-check kid)
5437 js2-END_DROPS_OFF))
5438 ((or (js2-continue-node-p node)
5439 (js2-throw-node-p node))
5440 js2-END_UNREACHED)
5441 ((js2-return-node-p node)
5442 (if (setq kid (js2-return-node-retval node))
5443 js2-END_RETURNS_VALUE
5444 js2-END_RETURNS))
5445 ((js2-loop-node-p node)
5446 (js2-end-check-loop node))
5447 ((js2-switch-node-p node)
5448 (js2-end-check-switch node))
5449 ((js2-labeled-stmt-node-p node)
5450 (js2-end-check-label node))
5451 ((js2-if-node-p node)
5452 (js2-end-check-if node))
5453 ((js2-try-node-p node)
5454 (js2-end-check-try node))
5455 ((js2-block-node-p node)
5456 (if (null (js2-block-node-kids node))
5457 js2-END_DROPS_OFF
5458 (js2-end-check-block node)))
5459 ((js2-yield-node-p node)
5460 js2-END_YIELDS)
5461 (t
5462 js2-END_DROPS_OFF))))
5463
5464 (defun js2-always-defined-boolean-p (node)
5465 "Check if NODE always evaluates to true or false in boolean context.
5466 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5467 nor always false."
5468 (let ((tt (js2-node-type node))
5469 num)
5470 (cond
5471 ((or (= tt js2-FALSE) (= tt js2-NULL))
5472 'ALWAYS_FALSE)
5473 ((= tt js2-TRUE)
5474 'ALWAYS_TRUE)
5475 ((= tt js2-NUMBER)
5476 (setq num (js2-number-node-num-value node))
5477 (if (and (not (eq num 0.0e+NaN))
5478 (not (zerop num)))
5479 'ALWAYS_TRUE
5480 'ALWAYS_FALSE))
5481 (t
5482 nil))))
5483
5484 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5485 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5486
5487 (defvar js2-tokens nil
5488 "List of all defined token names.") ; initialized in `js2-token-names'
5489
5490 (defconst js2-token-names
5491 (let* ((names (make-vector js2-num-tokens -1))
5492 (case-fold-search nil) ; only match js2-UPPER_CASE
5493 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5494 (cl-loop for sym in syms
5495 for i from 0
5496 do
5497 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5498 (not (boundp sym)))
5499 (aset names (symbol-value sym) ; code, e.g. 152
5500 (downcase
5501 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5502 (push sym js2-tokens)))
5503 names)
5504 "Vector mapping int values to token string names, sans `js2-' prefix.")
5505
5506 (defun js2-tt-name (tok)
5507 "Return a string name for TOK, a token symbol or code.
5508 Signals an error if it's not a recognized token."
5509 (let ((code tok))
5510 (if (symbolp tok)
5511 (setq code (symbol-value tok)))
5512 (if (eq code -1)
5513 "ERROR"
5514 (if (and (numberp code)
5515 (not (cl-minusp code))
5516 (< code js2-num-tokens))
5517 (aref js2-token-names code)
5518 (error "Invalid token: %s" code)))))
5519
5520 (defsubst js2-tt-sym (tok)
5521 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5522 (intern (js2-tt-name tok)))
5523
5524 (defconst js2-token-codes
5525 (let ((table (make-hash-table :test 'eq :size 256)))
5526 (cl-loop for name across js2-token-names
5527 for sym = (intern (concat "js2-" (upcase name)))
5528 do
5529 (puthash sym (symbol-value sym) table))
5530 ;; clean up a few that are "wrong" in Rhino's token codes
5531 (puthash 'js2-DELETE js2-DELPROP table)
5532 table)
5533 "Hashtable mapping token type symbols to their bytecodes.")
5534
5535 (defsubst js2-tt-code (sym)
5536 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5537 (or (gethash sym js2-token-codes)
5538 (error "Invalid token symbol: %s " sym))) ; signal code bug
5539
5540 (defun js2-report-scan-error (msg &optional no-throw beg len)
5541 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5542 (js2-report-error msg nil
5543 (or beg (js2-current-token-beg))
5544 (or len (js2-current-token-len)))
5545 (unless no-throw
5546 (throw 'return js2-ERROR)))
5547
5548 (defun js2-set-string-from-buffer (token)
5549 "Set `string' and `end' slots for TOKEN, return the string."
5550 (setf (js2-token-end token) js2-ts-cursor
5551 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5552
5553 ;; TODO: could potentially avoid a lot of consing by allocating a
5554 ;; char buffer the way Rhino does.
5555 (defsubst js2-add-to-string (c)
5556 (push c js2-ts-string-buffer))
5557
5558 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5559 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5560 ;; any other character: when it's not part of the current token, we
5561 ;; unget it, allowing it to be read again by the following call.
5562 (defsubst js2-unget-char ()
5563 (cl-decf js2-ts-cursor))
5564
5565 ;; Rhino distinguishes \r and \n line endings. We don't need to
5566 ;; because we only scan from Emacs buffers, which always use \n.
5567 (defun js2-get-char ()
5568 "Read and return the next character from the input buffer.
5569 Increments `js2-ts-lineno' if the return value is a newline char.
5570 Updates `js2-ts-cursor' to the point after the returned char.
5571 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5572 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5573 (let (c)
5574 ;; check for end of buffer
5575 (if (>= js2-ts-cursor (point-max))
5576 (setq js2-ts-hit-eof t
5577 js2-ts-cursor (1+ js2-ts-cursor)
5578 c js2-EOF_CHAR) ; return value
5579 ;; otherwise read next char
5580 (setq c (char-before (cl-incf js2-ts-cursor)))
5581 ;; if we read a newline, update counters
5582 (if (= c ?\n)
5583 (setq js2-ts-line-start js2-ts-cursor
5584 js2-ts-lineno (1+ js2-ts-lineno)))
5585 ;; TODO: skip over format characters
5586 c)))
5587
5588 (defun js2-read-unicode-escape ()
5589 "Read a \\uNNNN sequence from the input.
5590 Assumes the ?\ and ?u have already been read.
5591 Returns the unicode character, or nil if it wasn't a valid character.
5592 Doesn't change the values of any scanner variables."
5593 ;; I really wish I knew a better way to do this, but I can't
5594 ;; find the Emacs function that takes a 16-bit int and converts
5595 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5596 ;; Have to first check that it's 4 hex characters or it may stop
5597 ;; the read early.
5598 (ignore-errors
5599 (let ((s (buffer-substring-no-properties js2-ts-cursor
5600 (+ 4 js2-ts-cursor))))
5601 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5602 (read (concat "?\\u" s))))))
5603
5604 (defun js2-match-char (test)
5605 "Consume and return next character if it matches TEST, a character.
5606 Returns nil and consumes nothing if TEST is not the next character."
5607 (let ((c (js2-get-char)))
5608 (if (eq c test)
5609 t
5610 (js2-unget-char)
5611 nil)))
5612
5613 (defun js2-peek-char ()
5614 (prog1
5615 (js2-get-char)
5616 (js2-unget-char)))
5617
5618 (defun js2-identifier-start-p (c)
5619 "Is C a valid start to an ES5 Identifier?
5620 See http://es5.github.io/#x7.6"
5621 (or
5622 (memq c '(?$ ?_))
5623 (memq (get-char-code-property c 'general-category)
5624 ;; Letters
5625 '(Lu Ll Lt Lm Lo Nl))))
5626
5627 (defun js2-identifier-part-p (c)
5628 "Is C a valid part of an ES5 Identifier?
5629 See http://es5.github.io/#x7.6"
5630 (or
5631 (memq c '(?$ ?_ ?\u200c ?\u200d))
5632 (memq (get-char-code-property c 'general-category)
5633 '(;; Letters
5634 Lu Ll Lt Lm Lo Nl
5635 ;; Combining Marks
5636 Mn Mc
5637 ;; Digits
5638 Nd
5639 ;; Connector Punctuation
5640 Pc))))
5641
5642 (defun js2-alpha-p (c)
5643 (cond ((and (<= ?A c) (<= c ?Z)) t)
5644 ((and (<= ?a c) (<= c ?z)) t)
5645 (t nil)))
5646
5647 (defsubst js2-digit-p (c)
5648 (and (<= ?0 c) (<= c ?9)))
5649
5650 (defun js2-js-space-p (c)
5651 (if (<= c 127)
5652 (memq c '(#x20 #x9 #xB #xC #xD))
5653 (or
5654 (eq c #xA0)
5655 ;; TODO: change this nil to check for Unicode space character
5656 nil)))
5657
5658 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5659
5660 (defun js2-skip-line ()
5661 "Skip to end of line."
5662 (while (not (memq (js2-get-char) js2-eol-chars)))
5663 (js2-unget-char)
5664 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5665
5666 (defun js2-init-scanner (&optional buf line)
5667 "Create token stream for BUF starting on LINE.
5668 BUF defaults to `current-buffer' and LINE defaults to 1.
5669
5670 A buffer can only have one scanner active at a time, which yields
5671 dramatically simpler code than using a defstruct. If you need to
5672 have simultaneous scanners in a buffer, copy the regions to scan
5673 into temp buffers."
5674 (with-current-buffer (or buf (current-buffer))
5675 (setq js2-ts-dirty-line nil
5676 js2-ts-hit-eof nil
5677 js2-ts-line-start 0
5678 js2-ts-lineno (or line 1)
5679 js2-ts-line-end-char -1
5680 js2-ts-cursor (point-min)
5681 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5682 js2-ti-tokens-cursor 0
5683 js2-ti-lookahead 0
5684 js2-ts-is-xml-attribute nil
5685 js2-ts-xml-is-tag-content nil
5686 js2-ts-xml-open-tags-count 0
5687 js2-ts-string-buffer nil)))
5688
5689 ;; This function uses the cached op, string and number fields in
5690 ;; TokenStream; if getToken has been called since the passed token
5691 ;; was scanned, the op or string printed may be incorrect.
5692 (defun js2-token-to-string (token)
5693 ;; Not sure where this function is used in Rhino. Not tested.
5694 (if (not js2-debug-print-trees)
5695 ""
5696 (let ((name (js2-tt-name token)))
5697 (cond
5698 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5699 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5700 (concat name " `" (js2-current-token-string) "'"))
5701 ((eq token js2-NUMBER)
5702 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5703 (t
5704 name)))))
5705
5706 (defconst js2-keywords
5707 '(break
5708 case catch class const continue
5709 debugger default delete do
5710 else extends export
5711 false finally for function
5712 if in instanceof import
5713 let
5714 new null
5715 return
5716 super switch
5717 this throw true try typeof
5718 var void
5719 while with
5720 yield))
5721
5722 ;; Token names aren't exactly the same as the keywords, unfortunately.
5723 ;; E.g. delete is js2-DELPROP.
5724 (defconst js2-kwd-tokens
5725 (let ((table (make-vector js2-num-tokens nil))
5726 (tokens
5727 (list js2-BREAK
5728 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5729 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5730 js2-ELSE js2-EXPORT
5731 js2-ELSE js2-EXTENDS js2-EXPORT
5732 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5733 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5734 js2-LET
5735 js2-NEW js2-NULL
5736 js2-RETURN
5737 js2-SUPER js2-SWITCH
5738 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5739 js2-VAR
5740 js2-WHILE js2-WITH
5741 js2-YIELD)))
5742 (dolist (i tokens)
5743 (aset table i 'font-lock-keyword-face))
5744 (aset table js2-STRING 'font-lock-string-face)
5745 (aset table js2-REGEXP 'font-lock-string-face)
5746 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5747 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5748 (aset table js2-COMMENT 'font-lock-comment-face)
5749 (aset table js2-THIS 'font-lock-builtin-face)
5750 (aset table js2-SUPER 'font-lock-builtin-face)
5751 (aset table js2-VOID 'font-lock-constant-face)
5752 (aset table js2-NULL 'font-lock-constant-face)
5753 (aset table js2-TRUE 'font-lock-constant-face)
5754 (aset table js2-FALSE 'font-lock-constant-face)
5755 (aset table js2-NOT 'font-lock-negation-char-face)
5756 table)
5757 "Vector whose values are non-nil for tokens that are keywords.
5758 The values are default faces to use for highlighting the keywords.")
5759
5760 ;; FIXME: Support strict mode-only future reserved words, after we know
5761 ;; which parts scopes are in strict mode, and which are not.
5762 (defconst js2-reserved-words '(class enum export extends import static super)
5763 "Future reserved keywords in ECMAScript 5.1.")
5764
5765 (defconst js2-keyword-names
5766 (let ((table (make-hash-table :test 'equal)))
5767 (cl-loop for k in js2-keywords
5768 do (puthash
5769 (symbol-name k) ; instanceof
5770 (intern (concat "js2-"
5771 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5772 table))
5773 table)
5774 "JavaScript keywords by name, mapped to their symbols.")
5775
5776 (defconst js2-reserved-word-names
5777 (let ((table (make-hash-table :test 'equal)))
5778 (cl-loop for k in js2-reserved-words
5779 do
5780 (puthash (symbol-name k) 'js2-RESERVED table))
5781 table)
5782 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5783
5784 (defun js2-collect-string (buf)
5785 "Convert BUF, a list of chars, to a string.
5786 Reverses BUF before converting."
5787 (if buf
5788 (apply #'string (nreverse buf))
5789 ""))
5790
5791 (defun js2-string-to-keyword (s)
5792 "Return token for S, a string, if S is a keyword or reserved word.
5793 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5794 (or (gethash s js2-keyword-names)
5795 (gethash s js2-reserved-word-names)))
5796
5797 (defsubst js2-ts-set-char-token-bounds (token)
5798 "Used when next token is one character."
5799 (setf (js2-token-beg token) (1- js2-ts-cursor)
5800 (js2-token-end token) js2-ts-cursor))
5801
5802 (defsubst js2-ts-return (token type)
5803 "Update the `end' and `type' slots of TOKEN,
5804 then throw `return' with value TYPE."
5805 (setf (js2-token-end token) js2-ts-cursor
5806 (js2-token-type token) type)
5807 (throw 'return type))
5808
5809 (defun js2-x-digit-to-int (c accumulator)
5810 "Build up a hex number.
5811 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5812 corresponding number. Otherwise return -1."
5813 (catch 'return
5814 (catch 'check
5815 ;; Use 0..9 < A..Z < a..z
5816 (cond
5817 ((<= c ?9)
5818 (cl-decf c ?0)
5819 (if (<= 0 c)
5820 (throw 'check nil)))
5821 ((<= c ?F)
5822 (when (<= ?A c)
5823 (cl-decf c (- ?A 10))
5824 (throw 'check nil)))
5825 ((<= c ?f)
5826 (when (<= ?a c)
5827 (cl-decf c (- ?a 10))
5828 (throw 'check nil))))
5829 (throw 'return -1))
5830 (logior c (lsh accumulator 4))))
5831
5832 (defun js2-get-token (&optional modifier)
5833 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5834 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5835 next saved token.
5836
5837 This function will not return a newline (js2-EOL) - instead, it
5838 gobbles newlines until it finds a non-newline token. Call
5839 `js2-peek-token-or-eol' when you care about newlines.
5840
5841 This function will also not return a js2-COMMENT. Instead, it
5842 records comments found in `js2-scanned-comments'. If the token
5843 returned by this function immediately follows a jsdoc comment,
5844 the token is flagged as such."
5845 (if (zerop js2-ti-lookahead)
5846 (js2-get-token-internal modifier)
5847 (cl-decf js2-ti-lookahead)
5848 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5849 (let ((tt (js2-current-token-type)))
5850 (cl-assert (not (= tt js2-EOL)))
5851 tt)))
5852
5853 (defun js2-unget-token ()
5854 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5855 (cl-incf js2-ti-lookahead)
5856 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5857
5858 (defun js2-get-token-internal (modifier)
5859 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5860 (tt (js2-token-type token))
5861 saw-eol
5862 face)
5863 ;; process comments
5864 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5865 (if (= tt js2-EOL)
5866 (setq saw-eol t)
5867 (setq saw-eol nil)
5868 (when js2-record-comments
5869 (js2-record-comment token)))
5870 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5871 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5872 tt (js2-token-type token)))
5873
5874 (when saw-eol
5875 (setf (js2-token-follows-eol-p token) t))
5876
5877 ;; perform lexical fontification as soon as token is scanned
5878 (when js2-parse-ide-mode
5879 (cond
5880 ((cl-minusp tt)
5881 (js2-record-face 'js2-error token))
5882 ((setq face (aref js2-kwd-tokens tt))
5883 (js2-record-face face token))
5884 ((and (= tt js2-NAME)
5885 (equal (js2-token-string token) "undefined"))
5886 (js2-record-face 'font-lock-constant-face token))))
5887 tt))
5888
5889 (defsubst js2-string-to-number (str base)
5890 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5891 (condition-case nil
5892 (string-to-number str base)
5893 (overflow-error -1)))
5894
5895 (defun js2-get-token-internal-1 (modifier)
5896 "Return next JavaScript token type, an int such as js2-RETURN.
5897 During operation, creates an instance of `js2-token' struct, sets
5898 its relevant fields and puts it into `js2-ti-tokens'."
5899 (let (identifier-start
5900 is-unicode-escape-start c
5901 contains-escape escape-val str result base
5902 look-for-slash continue tt legacy-octal
5903 (token (js2-new-token 0)))
5904 (setq
5905 tt
5906 (catch 'return
5907 (when (eq modifier 'TEMPLATE_TAIL)
5908 (setf (js2-token-beg token) (1- js2-ts-cursor))
5909 (throw 'return (js2-get-string-or-template-token ?` token)))
5910 (while t
5911 ;; Eat whitespace, possibly sensitive to newlines.
5912 (setq continue t)
5913 (while continue
5914 (setq c (js2-get-char))
5915 (cond
5916 ((eq c js2-EOF_CHAR)
5917 (js2-unget-char)
5918 (js2-ts-set-char-token-bounds token)
5919 (throw 'return js2-EOF))
5920 ((eq c ?\n)
5921 (js2-ts-set-char-token-bounds token)
5922 (setq js2-ts-dirty-line nil)
5923 (throw 'return js2-EOL))
5924 ((not (js2-js-space-p c))
5925 (if (/= c ?-) ; in case end of HTML comment
5926 (setq js2-ts-dirty-line t))
5927 (setq continue nil))))
5928 ;; Assume the token will be 1 char - fixed up below.
5929 (js2-ts-set-char-token-bounds token)
5930 (when (eq c ?@)
5931 (throw 'return js2-XMLATTR))
5932 ;; identifier/keyword/instanceof?
5933 ;; watch out for starting with a <backslash>
5934 (cond
5935 ((eq c ?\\)
5936 (setq c (js2-get-char))
5937 (if (eq c ?u)
5938 (setq identifier-start t
5939 is-unicode-escape-start t
5940 js2-ts-string-buffer nil)
5941 (setq identifier-start nil)
5942 (js2-unget-char)
5943 (setq c ?\\)))
5944 (t
5945 (when (setq identifier-start (js2-identifier-start-p c))
5946 (setq js2-ts-string-buffer nil)
5947 (js2-add-to-string c))))
5948 (when identifier-start
5949 (setq contains-escape is-unicode-escape-start)
5950 (catch 'break
5951 (while t
5952 (if is-unicode-escape-start
5953 ;; strictly speaking we should probably push-back
5954 ;; all the bad characters if the <backslash>uXXXX
5955 ;; sequence is malformed. But since there isn't a
5956 ;; correct context(is there?) for a bad Unicode
5957 ;; escape sequence in an identifier, we can report
5958 ;; an error here.
5959 (progn
5960 (setq escape-val 0)
5961 (dotimes (_ 4)
5962 (setq c (js2-get-char)
5963 escape-val (js2-x-digit-to-int c escape-val))
5964 ;; Next check takes care of c < 0 and bad escape
5965 (if (cl-minusp escape-val)
5966 (throw 'break nil)))
5967 (if (cl-minusp escape-val)
5968 (js2-report-scan-error "msg.invalid.escape" t))
5969 (js2-add-to-string escape-val)
5970 (setq is-unicode-escape-start nil))
5971 (setq c (js2-get-char))
5972 (cond
5973 ((eq c ?\\)
5974 (setq c (js2-get-char))
5975 (if (eq c ?u)
5976 (setq is-unicode-escape-start t
5977 contains-escape t)
5978 (js2-report-scan-error "msg.illegal.character" t)))
5979 (t
5980 (if (or (eq c js2-EOF_CHAR)
5981 (not (js2-identifier-part-p c)))
5982 (throw 'break nil))
5983 (js2-add-to-string c))))))
5984 (js2-unget-char)
5985 (setf str (js2-collect-string js2-ts-string-buffer)
5986 (js2-token-end token) js2-ts-cursor)
5987 ;; FIXME: Invalid in ES5 and ES6, see
5988 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5989 ;; Probably should just drop this conditional.
5990 (unless contains-escape
5991 ;; OPT we shouldn't have to make a string (object!) to
5992 ;; check if it's a keyword.
5993 ;; Return the corresponding token if it's a keyword
5994 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5995 (setq result (js2-string-to-keyword str)))
5996 (if (and (< js2-language-version 170)
5997 (memq result '(js2-LET js2-YIELD)))
5998 ;; LET and YIELD are tokens only in 1.7 and later
5999 (setq result 'js2-NAME))
6000 (when (eq result 'js2-RESERVED)
6001 (setf (js2-token-string token) str))
6002 (throw 'return (js2-tt-code result))))
6003 ;; If we want to intern these as Rhino does, just use (intern str)
6004 (setf (js2-token-string token) str)
6005 (throw 'return js2-NAME)) ; end identifier/kwd check
6006 ;; is it a number?
6007 (when (or (js2-digit-p c)
6008 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6009 (setq js2-ts-string-buffer nil
6010 base 10)
6011 (when (eq c ?0)
6012 (setq c (js2-get-char))
6013 (cond
6014 ((or (eq c ?x) (eq c ?X))
6015 (setq base 16)
6016 (setq c (js2-get-char)))
6017 ((and (or (eq c ?b) (eq c ?B))
6018 (>= js2-language-version 200))
6019 (setq base 2)
6020 (setq c (js2-get-char)))
6021 ((and (or (eq c ?o) (eq c ?O))
6022 (>= js2-language-version 200))
6023 (setq base 8)
6024 (setq legacy-octal nil)
6025 (setq c (js2-get-char)))
6026 ((js2-digit-p c)
6027 (setq base 'maybe-8))
6028 (t
6029 (js2-add-to-string ?0))))
6030 (cond
6031 ((eq base 16)
6032 (if (> 0 (js2-x-digit-to-int c 0))
6033 (js2-report-scan-error "msg.missing.hex.digits")
6034 (while (<= 0 (js2-x-digit-to-int c 0))
6035 (js2-add-to-string c)
6036 (setq c (js2-get-char)))))
6037 ((eq base 2)
6038 (if (not (memq c '(?0 ?1)))
6039 (js2-report-scan-error "msg.missing.binary.digits")
6040 (while (memq c '(?0 ?1))
6041 (js2-add-to-string c)
6042 (setq c (js2-get-char)))))
6043 ((eq base 8)
6044 (if (or (> ?0 c) (< ?7 c))
6045 (js2-report-scan-error "msg.missing.octal.digits")
6046 (while (and (<= ?0 c) (>= ?7 c))
6047 (js2-add-to-string c)
6048 (setq c (js2-get-char)))))
6049 (t
6050 (while (and (<= ?0 c) (<= c ?9))
6051 ;; We permit 08 and 09 as decimal numbers, which
6052 ;; makes our behavior a superset of the ECMA
6053 ;; numeric grammar. We might not always be so
6054 ;; permissive, so we warn about it.
6055 (when (and (eq base 'maybe-8) (>= c ?8))
6056 (js2-report-warning "msg.bad.octal.literal"
6057 (if (eq c ?8) "8" "9"))
6058 (setq base 10))
6059 (js2-add-to-string c)
6060 (setq c (js2-get-char)))
6061 (when (eq base 'maybe-8)
6062 (setq base 8
6063 legacy-octal t))))
6064 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6065 (when (eq c ?.)
6066 (cl-loop do
6067 (js2-add-to-string c)
6068 (setq c (js2-get-char))
6069 while (js2-digit-p c)))
6070 (when (memq c '(?e ?E))
6071 (js2-add-to-string c)
6072 (setq c (js2-get-char))
6073 (when (memq c '(?+ ?-))
6074 (js2-add-to-string c)
6075 (setq c (js2-get-char)))
6076 (unless (js2-digit-p c)
6077 (js2-report-scan-error "msg.missing.exponent" t))
6078 (cl-loop do
6079 (js2-add-to-string c)
6080 (setq c (js2-get-char))
6081 while (js2-digit-p c))))
6082 (js2-unget-char)
6083 (let ((str (js2-set-string-from-buffer token)))
6084 (setf (js2-token-number token) (js2-string-to-number str base)
6085 (js2-token-number-base token) base
6086 (js2-token-number-legacy-octal-p token) (and (= base 8) legacy-octal)))
6087 (throw 'return js2-NUMBER))
6088 ;; is it a string?
6089 (when (or (memq c '(?\" ?\'))
6090 (and (>= js2-language-version 200)
6091 (= c ?`)))
6092 (throw 'return
6093 (js2-get-string-or-template-token c token)))
6094 (js2-ts-return token
6095 (cl-case c
6096 (?\;
6097 (throw 'return js2-SEMI))
6098 (?\[
6099 (throw 'return js2-LB))
6100 (?\]
6101 (throw 'return js2-RB))
6102 (?{
6103 (throw 'return js2-LC))
6104 (?}
6105 (throw 'return js2-RC))
6106 (?\(
6107 (throw 'return js2-LP))
6108 (?\)
6109 (throw 'return js2-RP))
6110 (?,
6111 (throw 'return js2-COMMA))
6112 (??
6113 (throw 'return js2-HOOK))
6114 (?:
6115 (if (js2-match-char ?:)
6116 js2-COLONCOLON
6117 (throw 'return js2-COLON)))
6118 (?.
6119 (if (js2-match-char ?.)
6120 (if (js2-match-char ?.)
6121 js2-TRIPLEDOT js2-DOTDOT)
6122 (if (js2-match-char ?\()
6123 js2-DOTQUERY
6124 (throw 'return js2-DOT))))
6125 (?|
6126 (if (js2-match-char ?|)
6127 (throw 'return js2-OR)
6128 (if (js2-match-char ?=)
6129 js2-ASSIGN_BITOR
6130 (throw 'return js2-BITOR))))
6131 (?^
6132 (if (js2-match-char ?=)
6133 js2-ASSIGN_BITOR
6134 (throw 'return js2-BITXOR)))
6135 (?&
6136 (if (js2-match-char ?&)
6137 (throw 'return js2-AND)
6138 (if (js2-match-char ?=)
6139 js2-ASSIGN_BITAND
6140 (throw 'return js2-BITAND))))
6141 (?=
6142 (if (js2-match-char ?=)
6143 (if (js2-match-char ?=)
6144 js2-SHEQ
6145 (throw 'return js2-EQ))
6146 (if (js2-match-char ?>)
6147 (js2-ts-return token js2-ARROW)
6148 (throw 'return js2-ASSIGN))))
6149 (?!
6150 (if (js2-match-char ?=)
6151 (if (js2-match-char ?=)
6152 js2-SHNE
6153 js2-NE)
6154 (throw 'return js2-NOT)))
6155 (?<
6156 ;; NB:treat HTML begin-comment as comment-till-eol
6157 (when (js2-match-char ?!)
6158 (when (js2-match-char ?-)
6159 (when (js2-match-char ?-)
6160 (js2-skip-line)
6161 (setf (js2-token-comment-type (js2-current-token)) 'html)
6162 (throw 'return js2-COMMENT)))
6163 (js2-unget-char))
6164 (if (js2-match-char ?<)
6165 (if (js2-match-char ?=)
6166 js2-ASSIGN_LSH
6167 js2-LSH)
6168 (if (js2-match-char ?=)
6169 js2-LE
6170 (throw 'return js2-LT))))
6171 (?>
6172 (if (js2-match-char ?>)
6173 (if (js2-match-char ?>)
6174 (if (js2-match-char ?=)
6175 js2-ASSIGN_URSH
6176 js2-URSH)
6177 (if (js2-match-char ?=)
6178 js2-ASSIGN_RSH
6179 js2-RSH))
6180 (if (js2-match-char ?=)
6181 js2-GE
6182 (throw 'return js2-GT))))
6183 (?*
6184 (if (js2-match-char ?=)
6185 js2-ASSIGN_MUL
6186 (throw 'return js2-MUL)))
6187 (?/
6188 ;; is it a // comment?
6189 (when (js2-match-char ?/)
6190 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6191 (js2-skip-line)
6192 (setf (js2-token-comment-type token) 'line)
6193 ;; include newline so highlighting goes to end of
6194 ;; window, if there actually is a newline; if we
6195 ;; hit eof, then implicitly there isn't
6196 (unless js2-ts-hit-eof
6197 (cl-incf (js2-token-end token)))
6198 (throw 'return js2-COMMENT))
6199 ;; is it a /* comment?
6200 (when (js2-match-char ?*)
6201 (setf look-for-slash nil
6202 (js2-token-beg token) (- js2-ts-cursor 2)
6203 (js2-token-comment-type token)
6204 (if (js2-match-char ?*)
6205 (progn
6206 (setq look-for-slash t)
6207 'jsdoc)
6208 'block))
6209 (while t
6210 (setq c (js2-get-char))
6211 (cond
6212 ((eq c js2-EOF_CHAR)
6213 (setf (js2-token-end token) (1- js2-ts-cursor))
6214 (js2-report-error "msg.unterminated.comment")
6215 (throw 'return js2-COMMENT))
6216 ((eq c ?*)
6217 (setq look-for-slash t))
6218 ((eq c ?/)
6219 (if look-for-slash
6220 (js2-ts-return token js2-COMMENT)))
6221 (t
6222 (setf look-for-slash nil
6223 (js2-token-end token) js2-ts-cursor)))))
6224 (if (js2-match-char ?=)
6225 js2-ASSIGN_DIV
6226 (throw 'return js2-DIV)))
6227 (?#
6228 (when js2-skip-preprocessor-directives
6229 (js2-skip-line)
6230 (setf (js2-token-comment-type token) 'preprocessor
6231 (js2-token-end token) js2-ts-cursor)
6232 (throw 'return js2-COMMENT))
6233 (throw 'return js2-ERROR))
6234 (?%
6235 (if (js2-match-char ?=)
6236 js2-ASSIGN_MOD
6237 (throw 'return js2-MOD)))
6238 (?~
6239 (throw 'return js2-BITNOT))
6240 (?+
6241 (if (js2-match-char ?=)
6242 js2-ASSIGN_ADD
6243 (if (js2-match-char ?+)
6244 js2-INC
6245 (throw 'return js2-ADD))))
6246 (?-
6247 (cond
6248 ((js2-match-char ?=)
6249 (setq c js2-ASSIGN_SUB))
6250 ((js2-match-char ?-)
6251 (unless js2-ts-dirty-line
6252 ;; treat HTML end-comment after possible whitespace
6253 ;; after line start as comment-until-eol
6254 (when (js2-match-char ?>)
6255 (js2-skip-line)
6256 (setf (js2-token-comment-type (js2-current-token)) 'html)
6257 (throw 'return js2-COMMENT)))
6258 (setq c js2-DEC))
6259 (t
6260 (setq c js2-SUB)))
6261 (setq js2-ts-dirty-line t)
6262 c)
6263 (otherwise
6264 (js2-report-scan-error "msg.illegal.character")))))))
6265 (setf (js2-token-type token) tt)
6266 token))
6267
6268 (defun js2-get-string-or-template-token (quote-char token)
6269 ;; We attempt to accumulate a string the fast way, by
6270 ;; building it directly out of the reader. But if there
6271 ;; are any escaped characters in the string, we revert to
6272 ;; building it out of a string buffer.
6273 (let ((c (js2-get-char))
6274 js2-ts-string-buffer
6275 nc c1 val escape-val)
6276 (catch 'break
6277 (while (/= c quote-char)
6278 (catch 'continue
6279 (when (eq c js2-EOF_CHAR)
6280 (js2-unget-char)
6281 (js2-report-error "msg.unterminated.string.lit")
6282 (throw 'break nil))
6283 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6284 (js2-unget-char)
6285 (js2-report-error "msg.unterminated.string.lit")
6286 (throw 'break nil))
6287 (when (eq c ?\\)
6288 ;; We've hit an escaped character
6289 (setq c (js2-get-char))
6290 (cl-case c
6291 (?b (setq c ?\b))
6292 (?f (setq c ?\f))
6293 (?n (setq c ?\n))
6294 (?r (setq c ?\r))
6295 (?t (setq c ?\t))
6296 (?v (setq c ?\v))
6297 (?u
6298 (setq c1 (js2-read-unicode-escape))
6299 (if js2-parse-ide-mode
6300 (if c1
6301 (progn
6302 ;; just copy the string in IDE-mode
6303 (js2-add-to-string ?\\)
6304 (js2-add-to-string ?u)
6305 (dotimes (_ 3)
6306 (js2-add-to-string (js2-get-char)))
6307 (setq c (js2-get-char))) ; added at end of loop
6308 ;; flag it as an invalid escape
6309 (js2-report-warning "msg.invalid.escape"
6310 nil (- js2-ts-cursor 2) 6))
6311 ;; Get 4 hex digits; if the u escape is not
6312 ;; followed by 4 hex digits, use 'u' + the
6313 ;; literal character sequence that follows.
6314 (js2-add-to-string ?u)
6315 (setq escape-val 0)
6316 (dotimes (_ 4)
6317 (setq c (js2-get-char)
6318 escape-val (js2-x-digit-to-int c escape-val))
6319 (if (cl-minusp escape-val)
6320 (throw 'continue nil))
6321 (js2-add-to-string c))
6322 ;; prepare for replace of stored 'u' sequence by escape value
6323 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6324 c escape-val)))
6325 (?x
6326 ;; Get 2 hex digits, defaulting to 'x'+literal
6327 ;; sequence, as above.
6328 (setq c (js2-get-char)
6329 escape-val (js2-x-digit-to-int c 0))
6330 (if (cl-minusp escape-val)
6331 (progn
6332 (js2-add-to-string ?x)
6333 (throw 'continue nil))
6334 (setq c1 c
6335 c (js2-get-char)
6336 escape-val (js2-x-digit-to-int c escape-val))
6337 (if (cl-minusp escape-val)
6338 (progn
6339 (js2-add-to-string ?x)
6340 (js2-add-to-string c1)
6341 (throw 'continue nil))
6342 ;; got 2 hex digits
6343 (setq c escape-val))))
6344 (?\n
6345 ;; Remove line terminator after escape to follow
6346 ;; SpiderMonkey and C/C++
6347 (setq c (js2-get-char))
6348 (throw 'continue nil))
6349 (t
6350 (when (and (<= ?0 c) (< c ?8))
6351 (setq val (- c ?0)
6352 c (js2-get-char))
6353 (when (and (<= ?0 c) (< c ?8))
6354 (setq val (- (+ (* 8 val) c) ?0)
6355 c (js2-get-char))
6356 (when (and (<= ?0 c)
6357 (< c ?8)
6358 (< val #o37))
6359 ;; c is 3rd char of octal sequence only
6360 ;; if the resulting val <= 0377
6361 (setq val (- (+ (* 8 val) c) ?0)
6362 c (js2-get-char))))
6363 (js2-unget-char)
6364 (setq c val)))))
6365 (when (and (eq quote-char ?`) (eq c ?$))
6366 (when (eq (setq nc (js2-get-char)) ?\{)
6367 (throw 'break nil))
6368 (js2-unget-char))
6369 (js2-add-to-string c)
6370 (setq c (js2-get-char)))))
6371 (js2-set-string-from-buffer token)
6372 (if (not (eq quote-char ?`))
6373 js2-STRING
6374 (if (and (eq c ?$) (eq nc ?\{))
6375 js2-TEMPLATE_HEAD
6376 js2-NO_SUBS_TEMPLATE))))
6377
6378 (defun js2-read-regexp (start-tt)
6379 "Called by parser when it gets / or /= in literal context."
6380 (let (c err
6381 in-class ; inside a '[' .. ']' character-class
6382 flags
6383 (continue t)
6384 (token (js2-new-token 0)))
6385 (setq js2-ts-string-buffer nil)
6386 (if (eq start-tt js2-ASSIGN_DIV)
6387 ;; mis-scanned /=
6388 (js2-add-to-string ?=)
6389 (if (not (eq start-tt js2-DIV))
6390 (error "failed assertion")))
6391 (while (and (not err)
6392 (or (/= (setq c (js2-get-char)) ?/)
6393 in-class))
6394 (cond
6395 ((or (= c ?\n)
6396 (= c js2-EOF_CHAR))
6397 (setf (js2-token-end token) (1- js2-ts-cursor)
6398 err t
6399 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6400 (js2-report-error "msg.unterminated.re.lit"))
6401 (t (cond
6402 ((= c ?\\)
6403 (js2-add-to-string c)
6404 (setq c (js2-get-char)))
6405 ((= c ?\[)
6406 (setq in-class t))
6407 ((= c ?\])
6408 (setq in-class nil)))
6409 (js2-add-to-string c))))
6410 (unless err
6411 (while continue
6412 (cond
6413 ((js2-match-char ?g)
6414 (push ?g flags))
6415 ((js2-match-char ?i)
6416 (push ?i flags))
6417 ((js2-match-char ?m)
6418 (push ?m flags))
6419 ((and (js2-match-char ?u)
6420 (>= js2-language-version 200))
6421 (push ?u flags))
6422 ((and (js2-match-char ?y)
6423 (>= js2-language-version 200))
6424 (push ?y flags))
6425 (t
6426 (setq continue nil))))
6427 (if (js2-alpha-p (js2-peek-char))
6428 (js2-report-scan-error "msg.invalid.re.flag" t
6429 js2-ts-cursor 1))
6430 (js2-set-string-from-buffer token))
6431 (js2-collect-string flags)))
6432
6433 (defun js2-get-first-xml-token ()
6434 (setq js2-ts-xml-open-tags-count 0
6435 js2-ts-is-xml-attribute nil
6436 js2-ts-xml-is-tag-content nil)
6437 (js2-unget-char)
6438 (js2-get-next-xml-token))
6439
6440 (defun js2-xml-discard-string (token)
6441 "Throw away the string in progress and flag an XML parse error."
6442 (setf js2-ts-string-buffer nil
6443 (js2-token-string token) nil)
6444 (js2-report-scan-error "msg.XML.bad.form" t))
6445
6446 (defun js2-get-next-xml-token ()
6447 (setq js2-ts-string-buffer nil) ; for recording the XML
6448 (let ((token (js2-new-token 0))
6449 c result)
6450 (setq result
6451 (catch 'return
6452 (while t
6453 (setq c (js2-get-char))
6454 (cond
6455 ((= c js2-EOF_CHAR)
6456 (throw 'return js2-ERROR))
6457 (js2-ts-xml-is-tag-content
6458 (cl-case c
6459 (?>
6460 (js2-add-to-string c)
6461 (setq js2-ts-xml-is-tag-content nil
6462 js2-ts-is-xml-attribute nil))
6463 (?/
6464 (js2-add-to-string c)
6465 (when (eq ?> (js2-peek-char))
6466 (setq c (js2-get-char))
6467 (js2-add-to-string c)
6468 (setq js2-ts-xml-is-tag-content nil)
6469 (cl-decf js2-ts-xml-open-tags-count)))
6470 (?{
6471 (js2-unget-char)
6472 (js2-set-string-from-buffer token)
6473 (throw 'return js2-XML))
6474 ((?\' ?\")
6475 (js2-add-to-string c)
6476 (unless (js2-read-quoted-string c token)
6477 (throw 'return js2-ERROR)))
6478 (?=
6479 (js2-add-to-string c)
6480 (setq js2-ts-is-xml-attribute t))
6481 ((? ?\t ?\r ?\n)
6482 (js2-add-to-string c))
6483 (t
6484 (js2-add-to-string c)
6485 (setq js2-ts-is-xml-attribute nil)))
6486 (when (and (not js2-ts-xml-is-tag-content)
6487 (zerop js2-ts-xml-open-tags-count))
6488 (js2-set-string-from-buffer token)
6489 (throw 'return js2-XMLEND)))
6490 (t
6491 ;; else not tag content
6492 (cl-case c
6493 (?<
6494 (js2-add-to-string c)
6495 (setq c (js2-peek-char))
6496 (cl-case c
6497 (?!
6498 (setq c (js2-get-char)) ;; skip !
6499 (js2-add-to-string c)
6500 (setq c (js2-peek-char))
6501 (cl-case c
6502 (?-
6503 (setq c (js2-get-char)) ;; skip -
6504 (js2-add-to-string c)
6505 (if (eq c ?-)
6506 (progn
6507 (js2-add-to-string c)
6508 (unless (js2-read-xml-comment token)
6509 (throw 'return js2-ERROR)))
6510 (js2-xml-discard-string token)
6511 (throw 'return js2-ERROR)))
6512 (?\[
6513 (setq c (js2-get-char)) ;; skip [
6514 (js2-add-to-string c)
6515 (if (and (= (js2-get-char) ?C)
6516 (= (js2-get-char) ?D)
6517 (= (js2-get-char) ?A)
6518 (= (js2-get-char) ?T)
6519 (= (js2-get-char) ?A)
6520 (= (js2-get-char) ?\[))
6521 (progn
6522 (js2-add-to-string ?C)
6523 (js2-add-to-string ?D)
6524 (js2-add-to-string ?A)
6525 (js2-add-to-string ?T)
6526 (js2-add-to-string ?A)
6527 (js2-add-to-string ?\[)
6528 (unless (js2-read-cdata token)
6529 (throw 'return js2-ERROR)))
6530 (js2-xml-discard-string token)
6531 (throw 'return js2-ERROR)))
6532 (t
6533 (unless (js2-read-entity token)
6534 (throw 'return js2-ERROR))))
6535 ;; Allow bare CDATA section, e.g.:
6536 ;; let xml = <![CDATA[ foo bar baz ]]>;
6537 (when (zerop js2-ts-xml-open-tags-count)
6538 (throw 'return js2-XMLEND)))
6539 (??
6540 (setq c (js2-get-char)) ;; skip ?
6541 (js2-add-to-string c)
6542 (unless (js2-read-PI token)
6543 (throw 'return js2-ERROR)))
6544 (?/
6545 ;; end tag
6546 (setq c (js2-get-char)) ;; skip /
6547 (js2-add-to-string c)
6548 (when (zerop js2-ts-xml-open-tags-count)
6549 (js2-xml-discard-string token)
6550 (throw 'return js2-ERROR))
6551 (setq js2-ts-xml-is-tag-content t)
6552 (cl-decf js2-ts-xml-open-tags-count))
6553 (t
6554 ;; start tag
6555 (setq js2-ts-xml-is-tag-content t)
6556 (cl-incf js2-ts-xml-open-tags-count))))
6557 (?{
6558 (js2-unget-char)
6559 (js2-set-string-from-buffer token)
6560 (throw 'return js2-XML))
6561 (t
6562 (js2-add-to-string c))))))))
6563 (setf (js2-token-end token) js2-ts-cursor)
6564 (setf (js2-token-type token) result)
6565 result))
6566
6567 (defun js2-read-quoted-string (quote token)
6568 (let (c)
6569 (catch 'return
6570 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6571 (js2-add-to-string c)
6572 (if (eq c quote)
6573 (throw 'return t)))
6574 (js2-xml-discard-string token) ;; throw away string in progress
6575 nil)))
6576
6577 (defun js2-read-xml-comment (token)
6578 (let ((c (js2-get-char)))
6579 (catch 'return
6580 (while (/= c js2-EOF_CHAR)
6581 (catch 'continue
6582 (js2-add-to-string c)
6583 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6584 (setq c (js2-get-char))
6585 (js2-add-to-string c)
6586 (if (eq (js2-peek-char) ?>)
6587 (progn
6588 (setq c (js2-get-char)) ;; skip >
6589 (js2-add-to-string c)
6590 (throw 'return t))
6591 (throw 'continue nil)))
6592 (setq c (js2-get-char))))
6593 (js2-xml-discard-string token)
6594 nil)))
6595
6596 (defun js2-read-cdata (token)
6597 (let ((c (js2-get-char)))
6598 (catch 'return
6599 (while (/= c js2-EOF_CHAR)
6600 (catch 'continue
6601 (js2-add-to-string c)
6602 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6603 (setq c (js2-get-char))
6604 (js2-add-to-string c)
6605 (if (eq (js2-peek-char) ?>)
6606 (progn
6607 (setq c (js2-get-char)) ;; Skip >
6608 (js2-add-to-string c)
6609 (throw 'return t))
6610 (throw 'continue nil)))
6611 (setq c (js2-get-char))))
6612 (js2-xml-discard-string token)
6613 nil)))
6614
6615 (defun js2-read-entity (token)
6616 (let ((decl-tags 1)
6617 c)
6618 (catch 'return
6619 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6620 (js2-add-to-string c)
6621 (cl-case c
6622 (?<
6623 (cl-incf decl-tags))
6624 (?>
6625 (cl-decf decl-tags)
6626 (if (zerop decl-tags)
6627 (throw 'return t)))))
6628 (js2-xml-discard-string token)
6629 nil)))
6630
6631 (defun js2-read-PI (token)
6632 "Scan an XML processing instruction."
6633 (let (c)
6634 (catch 'return
6635 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6636 (js2-add-to-string c)
6637 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6638 (setq c (js2-get-char)) ;; Skip >
6639 (js2-add-to-string c)
6640 (throw 'return t)))
6641 (js2-xml-discard-string token)
6642 nil)))
6643
6644 ;;; Highlighting
6645
6646 (defun js2-set-face (beg end face &optional record)
6647 "Fontify a region. If RECORD is non-nil, record for later."
6648 (when (cl-plusp js2-highlight-level)
6649 (setq beg (min (point-max) beg)
6650 beg (max (point-min) beg)
6651 end (min (point-max) end)
6652 end (max (point-min) end))
6653 (if record
6654 (push (list beg end face) js2-mode-fontifications)
6655 (put-text-property beg end 'font-lock-face face))))
6656
6657 (defsubst js2-clear-face (beg end)
6658 (remove-text-properties beg end '(font-lock-face nil
6659 help-echo nil
6660 point-entered nil
6661 cursor-sensor-functions nil
6662 c-in-sws nil)))
6663
6664 (defconst js2-ecma-global-props
6665 (concat "^"
6666 (regexp-opt
6667 '("Infinity" "NaN" "undefined" "arguments") t)
6668 "$")
6669 "Value properties of the Ecma-262 Global Object.
6670 Shown at or above `js2-highlight-level' 2.")
6671
6672 ;; might want to add the name "arguments" to this list?
6673 (defconst js2-ecma-object-props
6674 (concat "^"
6675 (regexp-opt
6676 '("prototype" "__proto__" "__parent__") t)
6677 "$")
6678 "Value properties of the Ecma-262 Object constructor.
6679 Shown at or above `js2-highlight-level' 2.")
6680
6681 (defconst js2-ecma-global-funcs
6682 (concat
6683 "^"
6684 (regexp-opt
6685 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6686 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6687 "$")
6688 "Function properties of the Ecma-262 Global object.
6689 Shown at or above `js2-highlight-level' 2.")
6690
6691 (defconst js2-ecma-number-props
6692 (concat "^"
6693 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6694 "NEGATIVE_INFINITY"
6695 "POSITIVE_INFINITY") t)
6696 "$")
6697 "Properties of the Ecma-262 Number constructor.
6698 Shown at or above `js2-highlight-level' 2.")
6699
6700 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6701 "Properties of the Ecma-262 Date constructor.
6702 Shown at or above `js2-highlight-level' 2.")
6703
6704 (defconst js2-ecma-math-props
6705 (concat "^"
6706 (regexp-opt
6707 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6708 t)
6709 "$")
6710 "Properties of the Ecma-262 Math object.
6711 Shown at or above `js2-highlight-level' 2.")
6712
6713 (defconst js2-ecma-math-funcs
6714 (concat "^"
6715 (regexp-opt
6716 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6717 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6718 "$")
6719 "Function properties of the Ecma-262 Math object.
6720 Shown at or above `js2-highlight-level' 2.")
6721
6722 (defconst js2-ecma-function-props
6723 (concat
6724 "^"
6725 (regexp-opt
6726 '(;; properties of the Object prototype object
6727 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6728 "toLocaleString" "toString" "valueOf"
6729 ;; properties of the Function prototype object
6730 "apply" "call"
6731 ;; properties of the Array prototype object
6732 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6733 "splice" "unshift"
6734 ;; properties of the String prototype object
6735 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6736 "localeCompare" "match" "replace" "search" "split" "substring"
6737 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6738 "toUpperCase"
6739 ;; properties of the Number prototype object
6740 "toExponential" "toFixed" "toPrecision"
6741 ;; properties of the Date prototype object
6742 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6743 "getMinutes" "getMonth" "getSeconds" "getTime"
6744 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6745 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6746 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6747 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6748 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6749 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6750 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6751 "toTimeString" "toUTCString"
6752 ;; properties of the RegExp prototype object
6753 "exec" "test"
6754 ;; properties of the JSON prototype object
6755 "parse" "stringify"
6756 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6757 "toSource" "__defineGetter__" "__defineSetter__"
6758 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6759 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6760 t)
6761 "$")
6762 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6763 Shown at or above `js2-highlight-level' 3.")
6764
6765 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6766 (let ((target-name (and target
6767 (js2-name-node-p target)
6768 (js2-name-node-name target)))
6769 (prop-name (if prop (js2-name-node-name prop)))
6770 (level2 (>= js2-highlight-level 2))
6771 (level3 (>= js2-highlight-level 3)))
6772 (when level2
6773 (let ((face
6774 (if call-p
6775 (cond
6776 ((and target prop)
6777 (cond
6778 ((and level3 (string-match js2-ecma-function-props prop-name))
6779 'font-lock-builtin-face)
6780 ((and target-name prop)
6781 (cond
6782 ((string= target-name "Date")
6783 (if (string-match js2-ecma-date-props prop-name)
6784 'font-lock-builtin-face))
6785 ((string= target-name "Math")
6786 (if (string-match js2-ecma-math-funcs prop-name)
6787 'font-lock-builtin-face))))))
6788 (prop
6789 (if (string-match js2-ecma-global-funcs prop-name)
6790 'font-lock-builtin-face)))
6791 (cond
6792 ((and target prop)
6793 (cond
6794 ((string= target-name "Number")
6795 (if (string-match js2-ecma-number-props prop-name)
6796 'font-lock-constant-face))
6797 ((string= target-name "Math")
6798 (if (string-match js2-ecma-math-props prop-name)
6799 'font-lock-constant-face))))
6800 (prop
6801 (if (string-match js2-ecma-object-props prop-name)
6802 'font-lock-constant-face))))))
6803 (when (and (not face) target (not call-p) prop-name)
6804 (setq face 'js2-object-property))
6805 (when face
6806 (let ((pos (+ (js2-node-pos parent) ; absolute
6807 (js2-node-pos prop)))) ; relative
6808 (js2-set-face pos
6809 (+ pos (js2-node-len prop))
6810 face 'record)))))))
6811
6812 (defun js2-parse-highlight-member-expr-node (node)
6813 "Perform syntax highlighting of EcmaScript built-in properties.
6814 The variable `js2-highlight-level' governs this highlighting."
6815 (let (face target prop name pos end parent call-p callee)
6816 (cond
6817 ;; case 1: simple name, e.g. foo
6818 ((js2-name-node-p node)
6819 (setq name (js2-name-node-name node))
6820 ;; possible for name to be nil in rare cases - saw it when
6821 ;; running js2-mode on an elisp buffer. Might as well try to
6822 ;; make it so js2-mode never barfs.
6823 (when name
6824 (setq face (if (string-match js2-ecma-global-props name)
6825 'font-lock-constant-face))
6826 (when face
6827 (setq pos (js2-node-pos node)
6828 end (+ pos (js2-node-len node)))
6829 (js2-set-face pos end face 'record))))
6830 ;; case 2: property access or function call
6831 ((or (js2-prop-get-node-p node)
6832 ;; highlight function call if expr is a prop-get node
6833 ;; or a plain name (i.e. unqualified function call)
6834 (and (setq call-p (js2-call-node-p node))
6835 (setq callee (js2-call-node-target node)) ; separate setq!
6836 (or (js2-prop-get-node-p callee)
6837 (js2-name-node-p callee))))
6838 (setq parent node
6839 node (if call-p callee node))
6840 (if (and call-p (js2-name-node-p callee))
6841 (setq prop callee)
6842 (setq target (js2-prop-get-node-left node)
6843 prop (js2-prop-get-node-right node)))
6844 (cond
6845 ((js2-name-node-p prop)
6846 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6847 (js2-parse-highlight-prop-get parent target prop call-p))
6848 ((js2-name-node-p target)
6849 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6850 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6851
6852 (defun js2-parse-highlight-member-expr-fn-name (expr)
6853 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6854 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6855 We currently only handle the case where the last component is a prop-get
6856 of a simple name. Called before EXPR has a parent node."
6857 (let (pos
6858 (name (and (js2-prop-get-node-p expr)
6859 (js2-prop-get-node-right expr))))
6860 (when (js2-name-node-p name)
6861 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6862 (js2-node-pos name)))
6863 (+ pos (js2-node-len name))
6864 'font-lock-function-name-face
6865 'record))))
6866
6867 ;; source: http://jsdoc.sourceforge.net/
6868 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6869 ;; allows type specifications, and needs work before entering the wild.
6870
6871 (defconst js2-jsdoc-param-tag-regexp
6872 (concat "^\\s-*\\*+\\s-*\\(@"
6873 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6874 "\\)"
6875 "\\s-*\\({[^}]+}\\)?" ; optional type
6876 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6877 "\\_>")
6878 "Matches jsdoc tags with optional type and optional param name.")
6879
6880 (defconst js2-jsdoc-typed-tag-regexp
6881 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6882 (regexp-opt
6883 '("enum"
6884 "extends"
6885 "field"
6886 "id"
6887 "implements"
6888 "lends"
6889 "mods"
6890 "requires"
6891 "return"
6892 "returns"
6893 "throw"
6894 "throws"))
6895 "\\)\\)\\s-*\\({[^}]+}\\)?")
6896 "Matches jsdoc tags with optional type.")
6897
6898 (defconst js2-jsdoc-arg-tag-regexp
6899 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6900 (regexp-opt
6901 '("alias"
6902 "augments"
6903 "borrows"
6904 "bug"
6905 "base"
6906 "config"
6907 "default"
6908 "define"
6909 "exception"
6910 "function"
6911 "member"
6912 "memberOf"
6913 "name"
6914 "namespace"
6915 "since"
6916 "suppress"
6917 "this"
6918 "throws"
6919 "type"
6920 "version"))
6921 "\\)\\)\\s-+\\([^ \t]+\\)")
6922 "Matches jsdoc tags with a single argument.")
6923
6924 (defconst js2-jsdoc-empty-tag-regexp
6925 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6926 (regexp-opt
6927 '("addon"
6928 "author"
6929 "class"
6930 "const"
6931 "constant"
6932 "constructor"
6933 "constructs"
6934 "deprecated"
6935 "desc"
6936 "description"
6937 "event"
6938 "example"
6939 "exec"
6940 "export"
6941 "fileoverview"
6942 "final"
6943 "function"
6944 "hidden"
6945 "ignore"
6946 "implicitCast"
6947 "inheritDoc"
6948 "inner"
6949 "interface"
6950 "license"
6951 "noalias"
6952 "noshadow"
6953 "notypecheck"
6954 "override"
6955 "owner"
6956 "preserve"
6957 "preserveTry"
6958 "private"
6959 "protected"
6960 "public"
6961 "static"
6962 "supported"
6963 ))
6964 "\\)\\)\\s-*")
6965 "Matches empty jsdoc tags.")
6966
6967 (defconst js2-jsdoc-link-tag-regexp
6968 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6969 "Matches a jsdoc link or code tag.")
6970
6971 (defconst js2-jsdoc-see-tag-regexp
6972 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6973 "Matches a jsdoc @see tag.")
6974
6975 (defconst js2-jsdoc-html-tag-regexp
6976 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6977 "Matches a simple (no attributes) html start- or end-tag.")
6978
6979 (defun js2-jsdoc-highlight-helper ()
6980 (js2-set-face (match-beginning 1)
6981 (match-end 1)
6982 'js2-jsdoc-tag)
6983 (if (match-beginning 2)
6984 (if (save-excursion
6985 (goto-char (match-beginning 2))
6986 (= (char-after) ?{))
6987 (js2-set-face (1+ (match-beginning 2))
6988 (1- (match-end 2))
6989 'js2-jsdoc-type)
6990 (js2-set-face (match-beginning 2)
6991 (match-end 2)
6992 'js2-jsdoc-value)))
6993 (if (match-beginning 3)
6994 (js2-set-face (match-beginning 3)
6995 (match-end 3)
6996 'js2-jsdoc-value)))
6997
6998 (defun js2-highlight-jsdoc (ast)
6999 "Highlight doc comment tags."
7000 (let ((comments (js2-ast-root-comments ast))
7001 beg end)
7002 (save-excursion
7003 (dolist (node comments)
7004 (when (eq (js2-comment-node-format node) 'jsdoc)
7005 (setq beg (js2-node-abs-pos node)
7006 end (+ beg (js2-node-len node)))
7007 (save-restriction
7008 (narrow-to-region beg end)
7009 (dolist (re (list js2-jsdoc-param-tag-regexp
7010 js2-jsdoc-typed-tag-regexp
7011 js2-jsdoc-arg-tag-regexp
7012 js2-jsdoc-link-tag-regexp
7013 js2-jsdoc-see-tag-regexp
7014 js2-jsdoc-empty-tag-regexp))
7015 (goto-char beg)
7016 (while (re-search-forward re nil t)
7017 (js2-jsdoc-highlight-helper)))
7018 ;; simple highlighting for html tags
7019 (goto-char beg)
7020 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7021 (js2-set-face (match-beginning 1)
7022 (match-end 1)
7023 'js2-jsdoc-html-tag-delimiter)
7024 (js2-set-face (match-beginning 2)
7025 (match-end 2)
7026 'js2-jsdoc-html-tag-name)
7027 (js2-set-face (match-beginning 3)
7028 (match-end 3)
7029 'js2-jsdoc-html-tag-delimiter))))))))
7030
7031 (defun js2-highlight-assign-targets (_node left right)
7032 "Highlight function properties and external variables."
7033 (let (leftpos name)
7034 ;; highlight vars and props assigned function values
7035 (when (or (js2-function-node-p right)
7036 (js2-class-node-p right))
7037 (cond
7038 ;; var foo = function() {...}
7039 ((js2-name-node-p left)
7040 (setq name left))
7041 ;; foo.bar.baz = function() {...}
7042 ((and (js2-prop-get-node-p left)
7043 (js2-name-node-p (js2-prop-get-node-right left)))
7044 (setq name (js2-prop-get-node-right left))))
7045 (when name
7046 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7047 (+ leftpos (js2-node-len name))
7048 'font-lock-function-name-face
7049 'record)))))
7050
7051 (defun js2-record-name-node (node)
7052 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7053 later. NODE must be a name node."
7054 (let ((leftpos (js2-node-abs-pos node)))
7055 (push (list node js2-current-scope
7056 leftpos
7057 (+ leftpos (js2-node-len node)))
7058 js2-recorded-identifiers)))
7059
7060 (defun js2-highlight-undeclared-vars ()
7061 "After entire parse is finished, look for undeclared variable references.
7062 We have to wait until entire buffer is parsed, since JavaScript permits var
7063 decls to occur after they're used.
7064
7065 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7066 it is considered declared."
7067 (let (name)
7068 (dolist (entry js2-recorded-identifiers)
7069 (cl-destructuring-bind (name-node scope pos end) entry
7070 (setq name (js2-name-node-name name-node))
7071 (unless (or (member name js2-global-externs)
7072 (member name js2-default-externs)
7073 (member name js2-additional-externs)
7074 (js2-get-defining-scope scope name pos))
7075 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7076 'js2-external-variable))))))
7077
7078 (defun js2--add-or-update-symbol (symbol inition used vars)
7079 "Add or update SYMBOL entry in VARS, an hash table.
7080 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7081 respectively meaning that SYMBOL is a mere declaration, an
7082 assignment or a function parameter; when USED is t, the symbol
7083 node is assumed to be an usage and thus added to the list stored
7084 in the cdr of the entry.
7085 "
7086 (let* ((nm (js2-name-node-name symbol))
7087 (es (js2-node-get-enclosing-scope symbol))
7088 (ds (js2-get-defining-scope es nm)))
7089 (when (and ds (not (equal nm "arguments")))
7090 (let* ((sym (js2-scope-get-symbol ds nm))
7091 (var (gethash sym vars))
7092 (err-var-p (js2-catch-node-p ds)))
7093 (unless inition
7094 (setq inition err-var-p))
7095 (if var
7096 (progn
7097 (when (and inition (not (equal (car var) ?P)))
7098 (setcar var inition))
7099 (when used
7100 (push symbol (cdr var))))
7101 ;; do not consider the declaration of catch parameter as an usage
7102 (when (and err-var-p used)
7103 (setq used nil))
7104 (puthash sym (cons inition (if used (list symbol))) vars))))))
7105
7106 (defun js2--classify-variables ()
7107 "Collect and classify variables declared or used within js2-mode-ast.
7108 Traverse the whole ast tree returning a summary of the variables
7109 usage as an hash-table, keyed by their corresponding symbol table
7110 entry.
7111 Each variable is described by a tuple where the car is a flag
7112 indicating whether the variable has been initialized and the cdr
7113 is a possibly empty list of name nodes where it is used. External
7114 symbols, i.e. those not present in the whole scopes hierarchy,
7115 are ignored."
7116 (let ((vars (make-hash-table :test #'eq :size 100)))
7117 (js2-visit-ast
7118 js2-mode-ast
7119 (lambda (node end-p)
7120 (when (null end-p)
7121 (cond
7122 ((js2-var-init-node-p node)
7123 ;; take note about possibly initialized declarations
7124 (let ((target (js2-var-init-node-target node))
7125 (initializer (js2-var-init-node-initializer node)))
7126 (when target
7127 (let* ((parent (js2-node-parent node))
7128 (grandparent (if parent (js2-node-parent parent)))
7129 (inited (not (null initializer))))
7130 (unless inited
7131 (setq inited
7132 (and grandparent
7133 (js2-for-in-node-p grandparent)
7134 (memq target
7135 (mapcar #'js2-var-init-node-target
7136 (js2-var-decl-node-kids
7137 (js2-for-in-node-iterator grandparent)))))))
7138 (js2--add-or-update-symbol target inited nil vars)))))
7139
7140 ((js2-assign-node-p node)
7141 ;; take note about assignments
7142 (let ((left (js2-assign-node-left node)))
7143 (when (js2-name-node-p left)
7144 (js2--add-or-update-symbol left t nil vars))))
7145
7146 ((js2-prop-get-node-p node)
7147 ;; handle x.y.z nodes, considering only x
7148 (let ((left (js2-prop-get-node-left node)))
7149 (when (js2-name-node-p left)
7150 (js2--add-or-update-symbol left nil t vars))))
7151
7152 ((js2-name-node-p node)
7153 ;; take note about used variables
7154 (let ((parent (js2-node-parent node)))
7155 (when parent
7156 (unless (or (and (js2-var-init-node-p parent) ; handled above
7157 (eq node (js2-var-init-node-target parent)))
7158 (and (js2-assign-node-p parent)
7159 (eq node (js2-assign-node-left parent)))
7160 (js2-prop-get-node-p parent))
7161 (let ((used t) inited)
7162 (cond
7163 ((and (js2-function-node-p parent)
7164 (js2-wrapper-function-p parent))
7165 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7166
7167 ((js2-for-in-node-p parent)
7168 (if (eq node (js2-for-in-node-iterator parent))
7169 (setq inited t used nil)))
7170
7171 ((js2-function-node-p parent)
7172 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7173 used nil)))
7174
7175 (unless used
7176 (let ((grandparent (js2-node-parent parent)))
7177 (when grandparent
7178 (setq used (js2-return-node-p grandparent)))))
7179
7180 (js2--add-or-update-symbol node inited used vars))))))))
7181 t))
7182 vars))
7183
7184 (defun js2--get-name-node (node)
7185 (cond
7186 ((js2-name-node-p node) node)
7187 ((js2-function-node-p node)
7188 (js2-function-node-name node))
7189 ((js2-class-node-p node)
7190 (js2-class-node-name node))
7191 ((js2-comp-loop-node-p node)
7192 (js2-comp-loop-node-iterator node))
7193 (t node)))
7194
7195 (defun js2--highlight-unused-variable (symbol info)
7196 (let ((name (js2-symbol-name symbol))
7197 (inited (car info))
7198 (refs (cdr info))
7199 pos len)
7200 (unless (and inited refs)
7201 (if refs
7202 (dolist (ref refs)
7203 (setq pos (js2-node-abs-pos ref))
7204 (setq len (js2-name-node-len ref))
7205 (js2-report-warning "msg.uninitialized.variable" name pos len
7206 'js2-warning))
7207 (when (or js2-warn-about-unused-function-arguments
7208 (not (eq inited ?P)))
7209 (let* ((symn (js2-symbol-ast-node symbol))
7210 (namen (js2--get-name-node symn)))
7211 (unless (js2-node-top-level-decl-p namen)
7212 (setq pos (js2-node-abs-pos namen))
7213 (setq len (js2-name-node-len namen))
7214 (js2-report-warning "msg.unused.variable" name pos len
7215 'js2-warning))))))))
7216
7217 (defun js2-highlight-unused-variables ()
7218 "Highlight unused variables."
7219 (let ((vars (js2--classify-variables)))
7220 (maphash #'js2--highlight-unused-variable vars)))
7221
7222 ;;;###autoload
7223 (define-minor-mode js2-highlight-unused-variables-mode
7224 "Toggle highlight of unused variables."
7225 :lighter ""
7226 (if js2-highlight-unused-variables-mode
7227 (add-hook 'js2-post-parse-callbacks
7228 #'js2-highlight-unused-variables nil t)
7229 (remove-hook 'js2-post-parse-callbacks
7230 #'js2-highlight-unused-variables t)))
7231
7232 (defun js2-set-default-externs ()
7233 "Set the value of `js2-default-externs' based on the various
7234 `js2-include-?-externs' variables."
7235 (setq js2-default-externs
7236 (append js2-ecma-262-externs
7237 (if js2-include-browser-externs js2-browser-externs)
7238 (if (and js2-include-browser-externs
7239 (>= js2-language-version 200)) js2-harmony-externs)
7240 (if js2-include-rhino-externs js2-rhino-externs)
7241 (if js2-include-node-externs js2-node-externs)
7242 (if (or js2-include-browser-externs js2-include-node-externs)
7243 js2-typed-array-externs))))
7244
7245 (defun js2-apply-jslint-globals ()
7246 (setq js2-additional-externs
7247 (nconc (js2-get-jslint-globals)
7248 js2-additional-externs)))
7249
7250 (defun js2-get-jslint-globals ()
7251 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7252 when (and (eq 'block (js2-comment-node-format node))
7253 (save-excursion
7254 (goto-char (js2-node-abs-pos node))
7255 (looking-at "/\\*global ")))
7256 append (js2-get-jslint-globals-in
7257 (match-end 0)
7258 (js2-node-abs-end node))))
7259
7260 (defun js2-get-jslint-globals-in (beg end)
7261 (let (res)
7262 (save-excursion
7263 (goto-char beg)
7264 (while (re-search-forward js2-mode-identifier-re end t)
7265 (let ((match (match-string 0)))
7266 (unless (member match '("true" "false"))
7267 (push match res)))))
7268 (nreverse res)))
7269
7270 ;;; IMenu support
7271
7272 ;; We currently only support imenu, but eventually should support speedbar and
7273 ;; possibly other browsing mechanisms.
7274
7275 ;; The basic strategy is to identify function assignment targets of the form
7276 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7277 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7278 ;; for imenu after parsing is finished.
7279
7280 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7281 ;; JavaScript, and the general problem is undecidable. However, several forms
7282 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7283 ;; include:
7284
7285 ;; function foo() -- function declaration
7286 ;; foo = function() -- function expression assigned to variable
7287 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7288 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7289 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7290 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7291 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7292 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7293 ;; function foo() {function bar() {...}} -- nested function
7294 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7295
7296 ;; This list boils down to a few forms that can be combined recursively.
7297 ;; Top-level named function declarations include both the left-hand (name)
7298 ;; and the right-hand (function value) expressions needed to produce an imenu
7299 ;; entry. The other "right-hand" forms we need to look for are:
7300 ;; - functions declared as props/getters/setters in object literals
7301 ;; - nested named function declarations
7302 ;; The "left-hand" expressions that functions can be assigned to include:
7303 ;; - local/global variables
7304 ;; - nested property-get expressions like a.b.c.d
7305 ;; - element gets like foo[10] or foo['bar'] where the index
7306 ;; expression can be trivially converted to a property name. They
7307 ;; effectively then become property gets.
7308
7309 ;; All the different definition types are canonicalized into the form
7310 ;; foo.bar.baz = position-of-function-keyword
7311
7312 ;; We need to build a trie-like structure for imenu. As an example,
7313 ;; consider the following JavaScript code:
7314
7315 ;; a = function() {...} // function at position 5
7316 ;; b = function() {...} // function at position 25
7317 ;; foo = function() {...} // function at position 100
7318 ;; foo.bar = function() {...} // function at position 200
7319 ;; foo.bar.baz = function() {...} // function at position 300
7320 ;; foo.bar.zab = function() {...} // function at position 400
7321
7322 ;; During parsing we accumulate an entry for each definition in
7323 ;; the variable `js2-imenu-recorder', like so:
7324
7325 ;; '((fn a 5)
7326 ;; (fn b 25)
7327 ;; (fn foo 100)
7328 ;; (fn foo bar 200)
7329 ;; (fn foo bar baz 300)
7330 ;; (fn foo bar zab 400))
7331
7332 ;; Where 'fn' is the respective function node.
7333 ;; After parsing these entries are merged into this alist-trie:
7334
7335 ;; '((a . 1)
7336 ;; (b . 2)
7337 ;; (foo (<definition> . 3)
7338 ;; (bar (<definition> . 6)
7339 ;; (baz . 100)
7340 ;; (zab . 200))))
7341
7342 ;; Note the wacky need for a <definition> name. The token can be anything
7343 ;; that isn't a valid JavaScript identifier, because you might make foo
7344 ;; a function and then start setting properties on it that are also functions.
7345
7346 (defun js2-prop-node-name (node)
7347 "Return the name of a node that may be a property-get/property-name.
7348 If NODE is not a valid name-node, string-node or integral number-node,
7349 returns nil. Otherwise returns the string name/value of the node."
7350 (cond
7351 ((js2-name-node-p node)
7352 (js2-name-node-name node))
7353 ((js2-string-node-p node)
7354 (js2-string-node-value node))
7355 ((and (js2-number-node-p node)
7356 (string-match "^[0-9]+$" (js2-number-node-value node)))
7357 (js2-number-node-value node))
7358 ((eq (js2-node-type node) js2-THIS)
7359 "this")
7360 ((eq (js2-node-type node) js2-SUPER)
7361 "super")))
7362
7363 (defun js2-node-qname-component (node)
7364 "Return the name of this node, if it contributes to a qname.
7365 Returns nil if the node doesn't contribute."
7366 (copy-sequence
7367 (or (js2-prop-node-name node)
7368 (if (and (js2-function-node-p node)
7369 (js2-function-node-name node))
7370 (js2-name-node-name (js2-function-node-name node))))))
7371
7372 (defun js2-record-imenu-entry (fn-node qname pos)
7373 "Add an entry to `js2-imenu-recorder'.
7374 FN-NODE should be the current item's function node.
7375
7376 Associate FN-NODE with its QNAME for later lookup.
7377 This is used in postprocessing the chain list. For each chain, we find
7378 the parent function, look up its qname, then prepend a copy of it to the chain."
7379 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7380 (unless js2-imenu-function-map
7381 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7382 (puthash fn-node qname js2-imenu-function-map))
7383
7384 (defun js2-record-imenu-functions (node &optional var)
7385 "Record function definitions for imenu.
7386 NODE is a function node or an object literal.
7387 VAR, if non-nil, is the expression that NODE is being assigned to.
7388 When passed arguments of wrong type, does nothing."
7389 (when js2-parse-ide-mode
7390 (let ((fun-p (js2-function-node-p node))
7391 qname fname-node)
7392 (cond
7393 ;; non-anonymous function declaration?
7394 ((and fun-p
7395 (not var)
7396 (setq fname-node (js2-function-node-name node)))
7397 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7398 ;; for remaining forms, compute left-side tree branch first
7399 ((and var (setq qname (js2-compute-nested-prop-get var)))
7400 (cond
7401 ;; foo.bar.baz = function
7402 (fun-p
7403 (js2-record-imenu-entry node qname (js2-node-pos node)))
7404 ;; foo.bar.baz = object-literal
7405 ;; look for nested functions: {a: {b: function() {...} }}
7406 ((js2-object-node-p node)
7407 ;; Node position here is still absolute, since the parser
7408 ;; passes the assignment target and value expressions
7409 ;; to us before they are added as children of the assignment node.
7410 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7411
7412 (defun js2-compute-nested-prop-get (node)
7413 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7414 component nodes as a list. Otherwise return nil. Element-gets are treated
7415 as property-gets if the index expression is a string, or a positive integer."
7416 (let (left right head)
7417 (cond
7418 ((or (js2-name-node-p node)
7419 (js2-this-or-super-node-p node))
7420 (list node))
7421 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7422 ((js2-prop-get-node-p node) ; foo.bar
7423 (setq left (js2-prop-get-node-left node)
7424 right (js2-prop-get-node-right node))
7425 (if (setq head (js2-compute-nested-prop-get left))
7426 (nconc head (list right))))
7427 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7428 (setq left (js2-elem-get-node-target node)
7429 right (js2-elem-get-node-element node))
7430 (if (or (js2-string-node-p right) ; ['bar']
7431 (and (js2-number-node-p right) ; [10]
7432 (string-match "^[0-9]+$"
7433 (js2-number-node-value right))))
7434 (if (setq head (js2-compute-nested-prop-get left))
7435 (nconc head (list right))))))))
7436
7437 (defun js2-record-object-literal (node qname pos)
7438 "Recursively process an object literal looking for functions.
7439 NODE is an object literal that is the right-hand child of an assignment
7440 expression. QNAME is a list of nodes representing the assignment target,
7441 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7442 POS is the absolute position of the node.
7443 We do a depth-first traversal of NODE. For any functions we find,
7444 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7445 (let (right)
7446 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7447 (let ((left (js2-infix-node-left e))
7448 ;; Element positions are relative to the parent position.
7449 (pos (+ pos (js2-node-pos e))))
7450 (cond
7451 ;; foo: function() {...}
7452 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7453 (when (js2-prop-node-name left)
7454 ;; As a policy decision, we record the position of the property,
7455 ;; not the position of the `function' keyword, since the property
7456 ;; is effectively the name of the function.
7457 (js2-record-imenu-entry right (append qname (list left)) pos)))
7458 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7459 ((js2-object-node-p right)
7460 (js2-record-object-literal right
7461 (append qname (list (js2-infix-node-left e)))
7462 (+ pos (js2-node-pos right)))))))))
7463
7464 (defun js2-node-top-level-decl-p (node)
7465 "Return t if NODE's name is defined in the top-level scope.
7466 Also returns t if NODE's name is not defined in any scope, since it implies
7467 that it's an external variable, which must also be in the top-level scope."
7468 (let* ((name (js2-prop-node-name node))
7469 (this-scope (js2-node-get-enclosing-scope node))
7470 defining-scope)
7471 (cond
7472 ((js2-this-or-super-node-p node)
7473 nil)
7474 ((null this-scope)
7475 t)
7476 ((setq defining-scope (js2-get-defining-scope this-scope name))
7477 (js2-ast-root-p defining-scope))
7478 (t t))))
7479
7480 (defun js2-wrapper-function-p (node)
7481 "Return t if NODE is a function expression that's immediately invoked.
7482 NODE must be `js2-function-node'."
7483 (let ((parent (js2-node-parent node)))
7484 (or
7485 ;; function(){...}();
7486 (and (js2-call-node-p parent)
7487 (eq node (js2-call-node-target parent)))
7488 (and (js2-paren-node-p parent)
7489 ;; (function(){...})();
7490 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7491 ;; (function(){...}).call(this);
7492 (and (js2-prop-get-node-p parent)
7493 (member (js2-name-node-name (js2-prop-get-node-right parent))
7494 '("call" "apply"))
7495 (js2-call-node-p (js2-node-parent parent))))))))
7496
7497 (defun js2-browse-postprocess-chains ()
7498 "Modify function-declaration name chains after parsing finishes.
7499 Some of the information is only available after the parse tree is complete.
7500 For instance, processing a nested scope requires a parent function node."
7501 (let (result fn parent-qname p elem)
7502 (dolist (entry js2-imenu-recorder)
7503 ;; function node goes first
7504 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7505 ;; Examine head's defining scope:
7506 ;; Pre-processed chain, or top-level/external, keep as-is.
7507 (if (or (stringp head) (js2-node-top-level-decl-p head))
7508 (push chain result)
7509 (when (js2-this-or-super-node-p head)
7510 (setq chain (cdr chain))) ; discard this-node
7511 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7512 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7513 (when (eq parent-qname 'not-found)
7514 ;; anonymous function expressions are not recorded
7515 ;; during the parse, so we need to handle this case here
7516 (setq parent-qname
7517 (if (js2-wrapper-function-p fn)
7518 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7519 (if (js2-ast-root-p grandparent)
7520 nil
7521 (gethash grandparent js2-imenu-function-map 'skip)))
7522 'skip))
7523 (puthash fn parent-qname js2-imenu-function-map))
7524 (if (eq parent-qname 'skip)
7525 ;; We don't show it, let's record that fact.
7526 (remhash current-fn js2-imenu-function-map)
7527 ;; Prepend parent fn qname to this chain.
7528 (let ((qname (append parent-qname chain)))
7529 (puthash current-fn (butlast qname) js2-imenu-function-map)
7530 (push qname result)))))))
7531 ;; Collect chains obtained by third-party code.
7532 (let (js2-imenu-recorder)
7533 (run-hooks 'js2-build-imenu-callbacks)
7534 (dolist (entry js2-imenu-recorder)
7535 (push (cdr entry) result)))
7536 ;; Finally replace each node in each chain with its name.
7537 (dolist (chain result)
7538 (setq p chain)
7539 (while p
7540 (if (js2-node-p (setq elem (car p)))
7541 (setcar p (js2-node-qname-component elem)))
7542 (setq p (cdr p))))
7543 result))
7544
7545 ;; Merge name chains into a trie-like tree structure of nested lists.
7546 ;; To simplify construction of the trie, we first build it out using the rule
7547 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7548 ;; [key, num-or-list]. The second element can be a number; if so, this key
7549 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7550 ;; associated with the key at this level.) Otherwise the second element is
7551 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7552 ;; a simple recursive formulation.
7553 ;;
7554 ;; js2-mode is building the data structure for imenu. The imenu documentation
7555 ;; claims that it's the structure above, but in practice it wants the children
7556 ;; at the same list level as the key for that level, which is how I've drawn
7557 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7558 ;; list wrapper around the children at each level.
7559 ;;
7560 ;; A completed nested imenu-alist entry looks like this:
7561 ;; '(("foo"
7562 ;; ("<definition>" . 7)
7563 ;; ("bar"
7564 ;; ("a" . 40)
7565 ;; ("b" . 60))))
7566 ;;
7567 ;; In particular, the documentation for `imenu--index-alist' says that
7568 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7569 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7570
7571 (defun js2-treeify (lst)
7572 "Convert (a b c d) to (a ((b ((c d)))))."
7573 (if (null (cddr lst)) ; list length <= 2
7574 lst
7575 (list (car lst) (list (js2-treeify (cdr lst))))))
7576
7577 (defun js2-build-alist-trie (chains trie)
7578 "Merge declaration name chains into a trie-like alist structure for imenu.
7579 CHAINS is the qname chain list produced during parsing. TRIE is a
7580 list of elements built up so far."
7581 (let (head tail pos branch kids)
7582 (dolist (chain chains)
7583 (setq head (car chain)
7584 tail (cdr chain)
7585 pos (if (numberp (car tail)) (car tail))
7586 branch (js2-find-if (lambda (n)
7587 (string= (car n) head))
7588 trie)
7589 kids (cl-second branch))
7590 (cond
7591 ;; case 1: this key isn't in the trie yet
7592 ((null branch)
7593 (if trie
7594 (setcdr (last trie) (list (js2-treeify chain)))
7595 (setq trie (list (js2-treeify chain)))))
7596 ;; case 2: key is present with a single number entry: replace w/ list
7597 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7598 ;; ("<definition>" 20)))
7599 ((numberp kids)
7600 (setcar (cdr branch)
7601 (list (list "<definition-1>" kids)
7602 (if pos
7603 (list "<definition-2>" pos)
7604 (js2-treeify tail)))))
7605 ;; case 3: key is there (with kids), and we're a number entry
7606 (pos
7607 (setcdr (last kids)
7608 (list
7609 (list (format "<definition-%d>"
7610 (1+ (cl-loop for kid in kids
7611 count (eq ?< (aref (car kid) 0)))))
7612 pos))))
7613 ;; case 4: key is there with kids, need to merge in our chain
7614 (t
7615 (js2-build-alist-trie (list tail) kids))))
7616 trie))
7617
7618 (defun js2-flatten-trie (trie)
7619 "Convert TRIE to imenu-format.
7620 Recurses through nodes, and for each one whose second element is a list,
7621 appends the list's flattened elements to the current element. Also
7622 changes the tails into conses. For instance, this pre-flattened trie
7623
7624 '(a ((b 20)
7625 (c ((d 30)
7626 (e 40)))))
7627
7628 becomes
7629
7630 '(a (b . 20)
7631 (c (d . 30)
7632 (e . 40)))
7633
7634 Note that the root of the trie has no key, just a list of chains.
7635 This is also true for the value of any key with multiple children,
7636 e.g. key 'c' in the example above."
7637 (cond
7638 ((listp (car trie))
7639 (mapcar #'js2-flatten-trie trie))
7640 (t
7641 (if (numberp (cl-second trie))
7642 (cons (car trie) (cl-second trie))
7643 ;; else pop list and append its kids
7644 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7645
7646 (defun js2-build-imenu-index ()
7647 "Turn `js2-imenu-recorder' into an imenu data structure."
7648 (when (eq js2-imenu-recorder 'empty)
7649 (setq js2-imenu-recorder nil))
7650 (let* ((chains (js2-browse-postprocess-chains))
7651 (result (js2-build-alist-trie chains nil)))
7652 (js2-flatten-trie result)))
7653
7654 (defun js2-test-print-chains (chains)
7655 "Print a list of qname chains.
7656 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7657 i.e. one or more nodes, and an integer position as the list tail."
7658 (mapconcat (lambda (chain)
7659 (concat "("
7660 (mapconcat (lambda (elem)
7661 (if (js2-node-p elem)
7662 (or (js2-node-qname-component elem)
7663 "nil")
7664 (number-to-string elem)))
7665 chain
7666 " ")
7667 ")"))
7668 chains
7669 "\n"))
7670
7671 ;;; Parser
7672
7673 (defconst js2-version "1.8.5"
7674 "Version of JavaScript supported.")
7675
7676 (defun js2-record-face (face &optional token)
7677 "Record a style run of FACE for TOKEN or the current token."
7678 (unless token (setq token (js2-current-token)))
7679 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7680
7681 (defsubst js2-node-end (n)
7682 "Computes the absolute end of node N.
7683 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7684 is only true until the node is added to its parent; i.e., while parsing."
7685 (+ (js2-node-pos n)
7686 (js2-node-len n)))
7687
7688 (defun js2-record-comment (token)
7689 "Record a comment in `js2-scanned-comments'."
7690 (let ((ct (js2-token-comment-type token))
7691 (beg (js2-token-beg token))
7692 (end (js2-token-end token)))
7693 (push (make-js2-comment-node :len (- end beg)
7694 :format ct)
7695 js2-scanned-comments)
7696 (when js2-parse-ide-mode
7697 (js2-record-face (if (eq ct 'jsdoc)
7698 'font-lock-doc-face
7699 'font-lock-comment-face)
7700 token)
7701 (when (memq ct '(html preprocessor))
7702 ;; Tell cc-engine the bounds of the comment.
7703 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7704
7705 (defun js2-peek-token ()
7706 "Return the next token type without consuming it.
7707 If `js2-ti-lookahead' is positive, return the type of next token
7708 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7709 (if (not (zerop js2-ti-lookahead))
7710 (js2-token-type
7711 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7712 (let ((tt (js2-get-token-internal nil)))
7713 (js2-unget-token)
7714 tt)))
7715
7716 (defalias 'js2-next-token 'js2-get-token)
7717
7718 (defun js2-match-token (match &optional dont-unget)
7719 "Get next token and return t if it matches MATCH, a bytecode.
7720 Returns nil and consumes nothing if MATCH is not the next token."
7721 (if (/= (js2-get-token) match)
7722 (ignore (unless dont-unget (js2-unget-token)))
7723 t))
7724
7725 (defun js2-match-contextual-kwd (name)
7726 "Consume and return t if next token is `js2-NAME', and its
7727 string is NAME. Returns nil and keeps current token otherwise."
7728 (if (js2-contextual-kwd-p (progn (js2-get-token)
7729 (js2-current-token))
7730 name)
7731 (progn (js2-record-face 'font-lock-keyword-face) t)
7732 (js2-unget-token)
7733 nil))
7734
7735 (defun js2-contextual-kwd-p (token name)
7736 "Return t if TOKEN is `js2-NAME', and its string is NAME."
7737 (and (= (js2-token-type token) js2-NAME)
7738 (string= (js2-token-string token) name)))
7739
7740 (defun js2-match-async-function ()
7741 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7742 (= (js2-peek-token) js2-FUNCTION))
7743 (js2-record-face 'font-lock-keyword-face)
7744 (js2-get-token)
7745 t))
7746
7747 (defun js2-match-async-arrow-function ()
7748 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7749 (/= (js2-peek-token) js2-FUNCTION))
7750 (js2-record-face 'font-lock-keyword-face)
7751 (js2-get-token)
7752 t))
7753
7754 (defun js2-match-await ()
7755 (when (and (= tt js2-NAME)
7756 (js2-contextual-kwd-p (js2-current-token) "await"))
7757 (js2-record-face 'font-lock-keyword-face)
7758 (let ((beg (js2-current-token-beg))
7759 (end (js2-current-token-end)))
7760 (js2-get-token)
7761 (unless (and (js2-inside-function)
7762 (js2-function-node-async js2-current-script-or-fn))
7763 (js2-report-error "msg.bad.await" nil
7764 beg (- end beg))))
7765 t))
7766
7767 (defun js2-get-prop-name-token ()
7768 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7769
7770 (defun js2-match-prop-name ()
7771 "Consume token and return t if next token is a valid property name.
7772 If `js2-language-version' is >= 180, a keyword or reserved word
7773 is considered valid name as well."
7774 (if (eq js2-NAME (js2-get-prop-name-token))
7775 t
7776 (js2-unget-token)
7777 nil))
7778
7779 (defun js2-must-match-prop-name (msg-id &optional pos len)
7780 (if (js2-match-prop-name)
7781 t
7782 (js2-report-error msg-id nil pos len)
7783 nil))
7784
7785 (defun js2-peek-token-or-eol ()
7786 "Return js2-EOL if the next token immediately follows a newline.
7787 Else returns the next token. Used in situations where we don't
7788 consider certain token types valid if they are preceded by a newline.
7789 One example is the postfix ++ or -- operator, which has to be on the
7790 same line as its operand."
7791 (let ((tt (js2-get-token))
7792 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7793 (js2-unget-token)
7794 (if follows-eol
7795 js2-EOL
7796 tt)))
7797
7798 (defun js2-must-match (token msg-id &optional pos len)
7799 "Match next token to token code TOKEN, or record a syntax error.
7800 MSG-ID is the error message to report if the match fails.
7801 Returns t on match, nil if no match."
7802 (if (js2-match-token token t)
7803 t
7804 (js2-report-error msg-id nil pos len)
7805 (js2-unget-token)
7806 nil))
7807
7808 (defun js2-must-match-name (msg-id)
7809 (if (js2-match-token js2-NAME t)
7810 t
7811 (if (eq (js2-current-token-type) js2-RESERVED)
7812 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7813 (js2-report-error msg-id)
7814 (js2-unget-token))
7815 nil))
7816
7817 (defsubst js2-inside-function ()
7818 (cl-plusp js2-nesting-of-function))
7819
7820 (defun js2-set-requires-activation ()
7821 (if (js2-function-node-p js2-current-script-or-fn)
7822 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7823
7824 (defun js2-check-activation-name (name _token)
7825 (when (js2-inside-function)
7826 ;; skip language-version 1.2 check from Rhino
7827 (if (or (string= "arguments" name)
7828 (and js2-compiler-activation-names ; only used in codegen
7829 (gethash name js2-compiler-activation-names)))
7830 (js2-set-requires-activation))))
7831
7832 (defun js2-set-is-generator ()
7833 (let ((fn-node js2-current-script-or-fn))
7834 (when (and (js2-function-node-p fn-node)
7835 (not (js2-function-node-generator-type fn-node)))
7836 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7837
7838 (defun js2-must-have-xml ()
7839 (unless js2-compiler-xml-available
7840 (js2-report-error "msg.XML.not.available")))
7841
7842 (defun js2-push-scope (scope)
7843 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7844 (cl-assert (js2-scope-p scope))
7845 (cl-assert (null (js2-scope-parent-scope scope)))
7846 (cl-assert (not (eq js2-current-scope scope)))
7847 (setf (js2-scope-parent-scope scope) js2-current-scope
7848 js2-current-scope scope))
7849
7850 (defsubst js2-pop-scope ()
7851 (setq js2-current-scope
7852 (js2-scope-parent-scope js2-current-scope)))
7853
7854 (defun js2-enter-loop (loop-node)
7855 (push loop-node js2-loop-set)
7856 (push loop-node js2-loop-and-switch-set)
7857 (js2-push-scope loop-node)
7858 ;; Tell the current labeled statement (if any) its statement,
7859 ;; and set the jump target of the first label to the loop.
7860 ;; These are used in `js2-parse-continue' to verify that the
7861 ;; continue target is an actual labeled loop. (And for codegen.)
7862 (when js2-labeled-stmt
7863 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7864 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7865 js2-labeled-stmt))) loop-node)))
7866
7867 (defun js2-exit-loop ()
7868 (pop js2-loop-set)
7869 (pop js2-loop-and-switch-set)
7870 (js2-pop-scope))
7871
7872 (defsubst js2-enter-switch (switch-node)
7873 (push switch-node js2-loop-and-switch-set))
7874
7875 (defsubst js2-exit-switch ()
7876 (pop js2-loop-and-switch-set))
7877
7878 (defsubst js2-get-directive (node)
7879 "Return NODE's value if it is a directive, nil otherwise.
7880
7881 A directive is an otherwise-meaningless expression statement
7882 consisting of a string literal, such as \"use strict\"."
7883 (and (js2-expr-stmt-node-p node)
7884 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7885 (js2-string-node-value node)))
7886
7887 (defun js2-parse (&optional buf cb)
7888 "Tell the js2 parser to parse a region of JavaScript.
7889
7890 BUF is a buffer or buffer name containing the code to parse.
7891 Call `narrow-to-region' first to parse only part of the buffer.
7892
7893 The returned AST root node is given some additional properties:
7894 `node-count' - total number of nodes in the AST
7895 `buffer' - BUF. The buffer it refers to may change or be killed,
7896 so the value is not necessarily reliable.
7897
7898 An optional callback CB can be specified to report parsing
7899 progress. If `(functionp CB)' returns t, it will be called with
7900 the current line number once before parsing begins, then again
7901 each time the lexer reaches a new line number.
7902
7903 CB can also be a list of the form `(symbol cb ...)' to specify
7904 multiple callbacks with different criteria. Each symbol is a
7905 criterion keyword, and the following element is the callback to
7906 call
7907
7908 :line - called whenever the line number changes
7909 :token - called for each new token consumed
7910
7911 The list of criteria could be extended to include entering or
7912 leaving a statement, an expression, or a function definition."
7913 (if (and cb (not (functionp cb)))
7914 (error "criteria callbacks not yet implemented"))
7915 (let ((inhibit-point-motion-hooks t)
7916 (js2-compiler-xml-available (>= js2-language-version 160))
7917 ;; This is a recursive-descent parser, so give it a big stack.
7918 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7919 (max-specpdl-size (max max-specpdl-size 3000))
7920 (case-fold-search nil)
7921 ast)
7922 (with-current-buffer (or buf (current-buffer))
7923 (setq js2-scanned-comments nil
7924 js2-parsed-errors nil
7925 js2-parsed-warnings nil
7926 js2-imenu-recorder nil
7927 js2-imenu-function-map nil
7928 js2-label-set nil)
7929 (js2-init-scanner)
7930 (setq ast (js2-do-parse))
7931 (unless js2-ts-hit-eof
7932 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7933 (setf (js2-ast-root-errors ast) js2-parsed-errors
7934 (js2-ast-root-warnings ast) js2-parsed-warnings)
7935 ;; if we didn't find any declarations, put a dummy in this list so we
7936 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7937 (unless js2-imenu-recorder
7938 (setq js2-imenu-recorder 'empty))
7939 (run-hooks 'js2-parse-finished-hook)
7940 ast)))
7941
7942 ;; Corresponds to Rhino's Parser.parse() method.
7943 (defun js2-do-parse ()
7944 "Parse current buffer starting from current point.
7945 Scanner should be initialized."
7946 (let ((pos js2-ts-cursor)
7947 (end js2-ts-cursor) ; in case file is empty
7948 root n tt
7949 (in-directive-prologue t)
7950 (js2-in-use-strict-directive js2-in-use-strict-directive)
7951 directive)
7952 ;; initialize buffer-local parsing vars
7953 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7954 js2-current-script-or-fn root
7955 js2-current-scope root
7956 js2-nesting-of-function 0
7957 js2-labeled-stmt nil
7958 js2-recorded-identifiers nil ; for js2-highlight
7959 js2-in-use-strict-directive nil)
7960 (while (/= (setq tt (js2-get-token)) js2-EOF)
7961 (if (= tt js2-FUNCTION)
7962 (progn
7963 (setq n (if js2-called-by-compile-function
7964 (js2-parse-function-expr)
7965 (js2-parse-function-stmt))))
7966 ;; not a function - parse a statement
7967 (js2-unget-token)
7968 (setq n (js2-parse-statement))
7969 (when in-directive-prologue
7970 (setq directive (js2-get-directive n))
7971 (cond
7972 ((null directive)
7973 (setq in-directive-prologue nil))
7974 ((string= directive "use strict")
7975 (setq js2-in-use-strict-directive t)))))
7976 ;; add function or statement to script
7977 (setq end (js2-node-end n))
7978 (js2-block-node-push root n))
7979 ;; add comments to root in lexical order
7980 (when js2-scanned-comments
7981 ;; if we find a comment beyond end of normal kids, use its end
7982 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7983 (dolist (comment js2-scanned-comments)
7984 (push comment (js2-ast-root-comments root))
7985 (js2-node-add-children root comment)))
7986 (setf (js2-node-len root) (- end pos))
7987 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7988 ;; Give extensions a chance to muck with things before highlighting starts.
7989 (let ((js2-additional-externs js2-additional-externs))
7990 (save-excursion
7991 (run-hooks 'js2-post-parse-callbacks))
7992 (js2-highlight-undeclared-vars))
7993 root))
7994
7995 (defun js2-parse-function-closure-body (fn-node)
7996 "Parse a JavaScript 1.8 function closure body."
7997 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7998 (if js2-ts-hit-eof
7999 (js2-report-error "msg.no.brace.body" nil
8000 (js2-node-pos fn-node)
8001 (- js2-ts-cursor (js2-node-pos fn-node)))
8002 (js2-node-add-children fn-node
8003 (setf (js2-function-node-body fn-node)
8004 (js2-parse-expr t))))))
8005
8006 (defun js2-parse-function-body (fn-node)
8007 (js2-must-match js2-LC "msg.no.brace.body"
8008 (js2-node-pos fn-node)
8009 (- js2-ts-cursor (js2-node-pos fn-node)))
8010 (let ((pos (js2-current-token-beg)) ; LC position
8011 (pn (make-js2-block-node)) ; starts at LC position
8012 tt
8013 end
8014 not-in-directive-prologue
8015 node
8016 directive)
8017 (cl-incf js2-nesting-of-function)
8018 (unwind-protect
8019 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8020 (= tt js2-EOF)
8021 (= tt js2-RC)))
8022 (js2-block-node-push
8023 pn
8024 (if (/= tt js2-FUNCTION)
8025 (if not-in-directive-prologue
8026 (js2-parse-statement)
8027 (setq node (js2-parse-statement)
8028 directive (js2-get-directive node))
8029 (cond
8030 ((null directive)
8031 (setq not-in-directive-prologue t))
8032 ((string= directive "use strict")
8033 ;; Back up and reparse the function, because new rules apply
8034 ;; to the function name and parameters.
8035 (when (not js2-in-use-strict-directive)
8036 (setq js2-in-use-strict-directive t)
8037 (throw 'reparse t))))
8038 node)
8039 (js2-get-token)
8040 (js2-parse-function-stmt))))
8041 (cl-decf js2-nesting-of-function))
8042 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8043 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8044 (setq end (js2-current-token-end)))
8045 (setf (js2-node-pos pn) pos
8046 (js2-node-len pn) (- end pos))
8047 (setf (js2-function-node-body fn-node) pn)
8048 (js2-node-add-children fn-node pn)
8049 pn))
8050
8051 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8052 "Declare and fontify destructuring parameters inside NODE.
8053 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8054
8055 Return a list of `js2-name-node' nodes representing the symbols
8056 declared; probably to check them for errors."
8057 (let (name-nodes)
8058 (cond
8059 ((js2-name-node-p node)
8060 (let (leftpos)
8061 (js2-define-symbol decl-type (js2-name-node-name node)
8062 node ignore-not-in-block)
8063 (when face
8064 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8065 (+ leftpos (js2-node-len node))
8066 face 'record))
8067 (list node)))
8068 ((js2-object-node-p node)
8069 (dolist (elem (js2-object-node-elems node))
8070 ;; js2-infix-node-p catches both object prop node and initialized
8071 ;; binding element (which is directly an infix node).
8072 (when (js2-infix-node-p elem)
8073 (push (js2-define-destruct-symbols
8074 (js2-infix-node-left elem)
8075 decl-type face ignore-not-in-block)
8076 name-nodes)))
8077 (apply #'append (nreverse name-nodes)))
8078 ((js2-array-node-p node)
8079 (dolist (elem (js2-array-node-elems node))
8080 (when elem
8081 (if (js2-infix-node-p elem) (setq elem (js2-infix-node-left elem)))
8082 (push (js2-define-destruct-symbols
8083 elem decl-type face ignore-not-in-block)
8084 name-nodes)))
8085 (apply #'append (nreverse name-nodes)))
8086 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8087 (js2-node-len node))
8088 nil))))
8089
8090 (defvar js2-illegal-strict-identifiers
8091 '("eval" "arguments")
8092 "Identifiers not allowed as variables in strict mode.")
8093
8094 (defun js2-check-strict-identifier (name-node)
8095 "Check that NAME-NODE makes a legal strict mode identifier."
8096 (when js2-in-use-strict-directive
8097 (let ((param-name (js2-name-node-name name-node)))
8098 (when (member param-name js2-illegal-strict-identifiers)
8099 (js2-report-error "msg.bad.id.strict" param-name
8100 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8101
8102 (defun js2-check-strict-function-params (preceding-params params)
8103 "Given PRECEDING-PARAMS in a function's parameter list, check
8104 for strict mode errors caused by PARAMS."
8105 (when js2-in-use-strict-directive
8106 (dolist (param params)
8107 (let ((param-name (js2-name-node-name param)))
8108 (js2-check-strict-identifier param)
8109 (when (cl-some (lambda (param)
8110 (string= (js2-name-node-name param) param-name))
8111 preceding-params)
8112 (js2-report-error "msg.dup.param.strict" param-name
8113 (js2-node-abs-pos param) (js2-node-len param)))))))
8114
8115 (defun js2-parse-function-params (function-type fn-node pos)
8116 "Parse the parameters of a function of FUNCTION-TYPE
8117 represented by FN-NODE at POS."
8118 (if (js2-match-token js2-RP)
8119 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8120 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8121 (eq (js2-current-token-type) js2-NAME)))
8122 params param
8123 param-name-nodes new-param-name-nodes
8124 rest-param-at)
8125 (when paren-free-arrow
8126 (js2-unget-token))
8127 (cl-loop for tt = (js2-peek-token)
8128 do
8129 (cond
8130 ;; destructuring param
8131 ((and (not paren-free-arrow)
8132 (or (= tt js2-LB) (= tt js2-LC)))
8133 (js2-get-token)
8134 (setq param (js2-parse-destruct-primary-expr)
8135 new-param-name-nodes (js2-define-destruct-symbols
8136 param js2-LP 'js2-function-param))
8137 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8138 (setq param-name-nodes (append param-name-nodes new-param-name-nodes)))
8139 ;; variable name
8140 (t
8141 (when (and (>= js2-language-version 200)
8142 (not paren-free-arrow)
8143 (js2-match-token js2-TRIPLEDOT)
8144 (not rest-param-at))
8145 ;; to report errors if there are more parameters
8146 (setq rest-param-at (length params)))
8147 (js2-must-match-name "msg.no.parm")
8148 (js2-record-face 'js2-function-param)
8149 (setq param (js2-create-name-node))
8150 (js2-define-symbol js2-LP (js2-current-token-string) param)
8151 (js2-check-strict-function-params param-name-nodes (list param))
8152 (setq param-name-nodes (append param-name-nodes (list param)))))
8153 ;; default parameter value
8154 (when (and (not rest-param-at)
8155 (>= js2-language-version 200)
8156 (js2-match-token js2-ASSIGN))
8157 (cl-assert (not paren-free-arrow))
8158 (let* ((pos (js2-node-pos param))
8159 (tt (js2-current-token-type))
8160 (op-pos (- (js2-current-token-beg) pos))
8161 (left param)
8162 (right (js2-parse-assign-expr))
8163 (len (- (js2-node-end right) pos)))
8164 (setq param (make-js2-assign-node
8165 :type tt :pos pos :len len :op-pos op-pos
8166 :left left :right right))
8167 (js2-node-add-children param left right)))
8168 (push param params)
8169 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8170 (js2-report-error "msg.param.after.rest" nil
8171 (js2-node-pos param) (js2-node-len param)))
8172 while
8173 (js2-match-token js2-COMMA))
8174 (when (and (not paren-free-arrow)
8175 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8176 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8177 (when rest-param-at
8178 (setf (js2-function-node-rest-p fn-node) t))
8179 (dolist (p params)
8180 (js2-node-add-children fn-node p)
8181 (push p (js2-function-node-params fn-node))))))
8182
8183 (defun js2-check-inconsistent-return-warning (fn-node name)
8184 "Possibly show inconsistent-return warning.
8185 Last token scanned is the close-curly for the function body."
8186 (when (and js2-mode-show-strict-warnings
8187 js2-strict-inconsistent-return-warning
8188 (not (js2-has-consistent-return-usage
8189 (js2-function-node-body fn-node))))
8190 ;; Have it extend from close-curly to bol or beginning of block.
8191 (let ((pos (save-excursion
8192 (goto-char (js2-current-token-end))
8193 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8194 (point-at-bol))))
8195 (end (js2-current-token-end)))
8196 (if (cl-plusp (js2-name-node-length name))
8197 (js2-add-strict-warning "msg.no.return.value"
8198 (js2-name-node-name name) pos end)
8199 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8200
8201 (defun js2-parse-function-stmt (&optional async-p)
8202 (let ((pos (js2-current-token-beg))
8203 (star-p (js2-match-token js2-MUL)))
8204 (js2-must-match-name "msg.unnamed.function.stmt")
8205 (let ((name (js2-create-name-node t))
8206 pn member-expr)
8207 (cond
8208 ((js2-match-token js2-LP)
8209 (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p name))
8210 (js2-allow-member-expr-as-function-name
8211 (setq member-expr (js2-parse-member-expr-tail nil name))
8212 (js2-parse-highlight-member-expr-fn-name member-expr)
8213 (js2-must-match js2-LP "msg.no.paren.parms")
8214 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p)
8215 (js2-function-node-member-expr pn) member-expr)
8216 pn)
8217 (t
8218 (js2-report-error "msg.no.paren.parms")
8219 (make-js2-error-node))))))
8220
8221 (defun js2-parse-async-function-stmt ()
8222 (js2-parse-function-stmt t))
8223
8224 (defun js2-parse-function-expr (&optional async-p)
8225 (let ((pos (js2-current-token-beg))
8226 (star-p (js2-match-token js2-MUL))
8227 name)
8228 (when (js2-match-token js2-NAME)
8229 (setq name (js2-create-name-node t)))
8230 (js2-must-match js2-LP "msg.no.paren.parms")
8231 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p async-p name)))
8232
8233 (defun js2-parse-function-internal (function-type pos star-p &optional async-p name)
8234 (let (fn-node lp)
8235 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8236 (setq lp (js2-current-token-beg)))
8237 (setf fn-node (make-js2-function-node :pos pos
8238 :name name
8239 :form function-type
8240 :lp (if lp (- lp pos))
8241 :generator-type (and star-p 'STAR)
8242 :async async-p))
8243 (when name
8244 (js2-set-face (js2-node-pos name) (js2-node-end name)
8245 'font-lock-function-name-face 'record)
8246 (when (and (eq function-type 'FUNCTION_STATEMENT)
8247 (cl-plusp (js2-name-node-length name)))
8248 ;; Function statements define a symbol in the enclosing scope
8249 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8250 (when js2-in-use-strict-directive
8251 (js2-check-strict-identifier name)))
8252 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8253 ;; 1. Nested functions are not affected by the dynamic scope flag
8254 ;; as dynamic scope is already a parent of their scope.
8255 ;; 2. Functions defined under the with statement also immune to
8256 ;; this setup, in which case dynamic scope is ignored in favor
8257 ;; of the with object.
8258 (setf (js2-function-node-ignore-dynamic fn-node) t))
8259 ;; dynamically bind all the per-function variables
8260 (let ((js2-current-script-or-fn fn-node)
8261 (js2-current-scope fn-node)
8262 (js2-nesting-of-with 0)
8263 (js2-end-flags 0)
8264 js2-label-set
8265 js2-loop-set
8266 js2-loop-and-switch-set)
8267 (js2-parse-function-params function-type fn-node pos)
8268 (when (eq function-type 'FUNCTION_ARROW)
8269 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8270 (if (and (>= js2-language-version 180)
8271 (/= (js2-peek-token) js2-LC))
8272 (js2-parse-function-closure-body fn-node)
8273 (js2-parse-function-body fn-node))
8274 (js2-check-inconsistent-return-warning fn-node name)
8275
8276 (when name
8277 (js2-node-add-children fn-node name)
8278 ;; Function expressions define a name only in the body of the
8279 ;; function, and only if not hidden by a parameter name
8280 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8281 (null (js2-scope-get-symbol js2-current-scope
8282 (js2-name-node-name name))))
8283 (js2-define-symbol js2-FUNCTION
8284 (js2-name-node-name name)
8285 fn-node))
8286 (when (eq function-type 'FUNCTION_STATEMENT)
8287 (js2-record-imenu-functions fn-node))))
8288
8289 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8290 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8291 ;; We wait until after parsing the function to set its parent scope,
8292 ;; since `js2-define-symbol' needs the defining-scope check to stop
8293 ;; at the function boundary when checking for redeclarations.
8294 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8295 fn-node))
8296
8297 (defun js2-parse-function (function-type pos star-p &optional async-p name)
8298 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8299 beginning of the first token (function keyword, unless it's an
8300 arrow function), NAME is js2-name-node."
8301 (let ((continue t)
8302 ts-state
8303 fn-node
8304 ;; Preserve strict state outside this function.
8305 (js2-in-use-strict-directive js2-in-use-strict-directive))
8306 ;; Parse multiple times if a new strict mode directive is discovered in the
8307 ;; function body, as new rules will be retroactively applied to the legality
8308 ;; of function names and parameters.
8309 (while continue
8310 (setq ts-state (make-js2-ts-state))
8311 (setq continue (catch 'reparse
8312 (setq fn-node (js2-parse-function-internal
8313 function-type pos star-p async-p name))
8314 ;; Don't continue.
8315 nil))
8316 (when continue
8317 (js2-ts-seek ts-state)))
8318 fn-node))
8319
8320 (defun js2-parse-statements (&optional parent)
8321 "Parse a statement list. Last token consumed must be js2-LC.
8322
8323 PARENT can be a `js2-block-node', in which case the statements are
8324 appended to PARENT. Otherwise a new `js2-block-node' is created
8325 and returned.
8326
8327 This function does not match the closing js2-RC: the caller
8328 matches the RC so it can provide a suitable error message if not
8329 matched. This means it's up to the caller to set the length of
8330 the node to include the closing RC. The node start pos is set to
8331 the absolute buffer start position, and the caller should fix it
8332 up to be relative to the parent node. All children of this block
8333 node are given relative start positions and correct lengths."
8334 (let ((pn (or parent (make-js2-block-node)))
8335 tt)
8336 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8337 (/= tt js2-RC))
8338 (js2-block-node-push pn (js2-parse-statement)))
8339 pn))
8340
8341 (defun js2-parse-statement ()
8342 (let (pn beg end)
8343 ;; coarse-grained user-interrupt check - needs work
8344 (and js2-parse-interruptable-p
8345 (zerop (% (cl-incf js2-parse-stmt-count)
8346 js2-statements-per-pause))
8347 (input-pending-p)
8348 (throw 'interrupted t))
8349 (setq pn (js2-statement-helper))
8350 ;; no-side-effects warning check
8351 (unless (js2-node-has-side-effects pn)
8352 (setq end (js2-node-end pn))
8353 (save-excursion
8354 (goto-char end)
8355 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8356 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8357 pn))
8358
8359 ;; These correspond to the switch cases in Parser.statementHelper
8360 (defconst js2-parsers
8361 (let ((parsers (make-vector js2-num-tokens
8362 #'js2-parse-expr-stmt)))
8363 (aset parsers js2-BREAK #'js2-parse-break)
8364 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8365 (aset parsers js2-CONST #'js2-parse-const-var)
8366 (aset parsers js2-CONTINUE #'js2-parse-continue)
8367 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8368 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8369 (aset parsers js2-DO #'js2-parse-do)
8370 (aset parsers js2-EXPORT #'js2-parse-export)
8371 (aset parsers js2-FOR #'js2-parse-for)
8372 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8373 (aset parsers js2-IF #'js2-parse-if)
8374 (aset parsers js2-IMPORT #'js2-parse-import)
8375 (aset parsers js2-LC #'js2-parse-block)
8376 (aset parsers js2-LET #'js2-parse-let-stmt)
8377 (aset parsers js2-NAME #'js2-parse-name-or-label)
8378 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8379 (aset parsers js2-SEMI #'js2-parse-semi)
8380 (aset parsers js2-SWITCH #'js2-parse-switch)
8381 (aset parsers js2-THROW #'js2-parse-throw)
8382 (aset parsers js2-TRY #'js2-parse-try)
8383 (aset parsers js2-VAR #'js2-parse-const-var)
8384 (aset parsers js2-WHILE #'js2-parse-while)
8385 (aset parsers js2-WITH #'js2-parse-with)
8386 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8387 parsers)
8388 "A vector mapping token types to parser functions.")
8389
8390 (defun js2-parse-warn-missing-semi (beg end)
8391 (and js2-mode-show-strict-warnings
8392 js2-strict-missing-semi-warning
8393 (js2-add-strict-warning
8394 "msg.missing.semi" nil
8395 ;; back up to beginning of statement or line
8396 (max beg (save-excursion
8397 (goto-char end)
8398 (point-at-bol)))
8399 end)))
8400
8401 (defconst js2-no-semi-insertion
8402 (list js2-IF
8403 js2-SWITCH
8404 js2-WHILE
8405 js2-DO
8406 js2-FOR
8407 js2-TRY
8408 js2-WITH
8409 js2-LC
8410 js2-ERROR
8411 js2-SEMI
8412 js2-CLASS
8413 js2-FUNCTION
8414 js2-EXPORT)
8415 "List of tokens that don't do automatic semicolon insertion.")
8416
8417 (defconst js2-autoinsert-semi-and-warn
8418 (list js2-ERROR js2-EOF js2-RC))
8419
8420 (defun js2-statement-helper ()
8421 (let* ((tt (js2-get-token))
8422 (first-tt tt)
8423 (async-stmt (js2-match-async-function))
8424 (parser (if (= tt js2-ERROR)
8425 #'js2-parse-semi
8426 (if async-stmt
8427 #'js2-parse-async-function-stmt
8428 (aref js2-parsers tt))))
8429 pn)
8430 ;; If the statement is set, then it's been told its label by now.
8431 (and js2-labeled-stmt
8432 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8433 (setq js2-labeled-stmt nil))
8434 (setq pn (funcall parser))
8435 ;; Don't do auto semi insertion for certain statement types.
8436 (unless (or (memq first-tt js2-no-semi-insertion)
8437 (js2-labeled-stmt-node-p pn)
8438 async-stmt)
8439 (js2-auto-insert-semicolon pn))
8440 pn))
8441
8442 (defun js2-auto-insert-semicolon (pn)
8443 (let* ((tt (js2-get-token))
8444 (pos (js2-node-pos pn)))
8445 (cond
8446 ((= tt js2-SEMI)
8447 ;; extend the node bounds to include the semicolon.
8448 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8449 ((memq tt js2-autoinsert-semi-and-warn)
8450 (js2-unget-token) ; Not ';', do not consume.
8451 ;; Autoinsert ;
8452 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8453 (t
8454 (if (not (js2-token-follows-eol-p (js2-current-token)))
8455 ;; Report error if no EOL or autoinsert ';' otherwise
8456 (js2-report-error "msg.no.semi.stmt")
8457 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8458 (js2-unget-token) ; Not ';', do not consume.
8459 ))))
8460
8461 (defun js2-parse-condition ()
8462 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8463 The parens are discarded and the expression node is returned.
8464 The `pos' field of the return value is set to an absolute position
8465 that must be fixed up by the caller.
8466 Return value is a list (EXPR LP RP), with absolute paren positions."
8467 (let (pn lp rp)
8468 (if (js2-must-match js2-LP "msg.no.paren.cond")
8469 (setq lp (js2-current-token-beg)))
8470 (setq pn (js2-parse-expr))
8471 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8472 (setq rp (js2-current-token-beg)))
8473 ;; Report strict warning on code like "if (a = 7) ..."
8474 (if (and js2-strict-cond-assign-warning
8475 (js2-assign-node-p pn))
8476 (js2-add-strict-warning "msg.equal.as.assign" nil
8477 (js2-node-pos pn)
8478 (+ (js2-node-pos pn)
8479 (js2-node-len pn))))
8480 (list pn lp rp)))
8481
8482 (defun js2-parse-if ()
8483 "Parser for if-statement. Last matched token must be js2-IF."
8484 (let ((pos (js2-current-token-beg))
8485 cond if-true if-false else-pos end pn)
8486 (setq cond (js2-parse-condition)
8487 if-true (js2-parse-statement)
8488 if-false (if (js2-match-token js2-ELSE)
8489 (progn
8490 (setq else-pos (- (js2-current-token-beg) pos))
8491 (js2-parse-statement)))
8492 end (js2-node-end (or if-false if-true))
8493 pn (make-js2-if-node :pos pos
8494 :len (- end pos)
8495 :condition (car cond)
8496 :then-part if-true
8497 :else-part if-false
8498 :else-pos else-pos
8499 :lp (js2-relpos (cl-second cond) pos)
8500 :rp (js2-relpos (cl-third cond) pos)))
8501 (js2-node-add-children pn (car cond) if-true if-false)
8502 pn))
8503
8504 (defun js2-parse-import ()
8505 "Parse import statement. The current token must be js2-IMPORT."
8506 (unless (js2-ast-root-p js2-current-scope)
8507 (js2-report-error "msg.mod.import.decl.at.top.level"))
8508 (let ((beg (js2-current-token-beg)))
8509 (cond ((js2-match-token js2-STRING)
8510 (make-js2-import-node
8511 :pos beg
8512 :len (- (js2-current-token-end) beg)
8513 :module-id (js2-current-token-string)))
8514 (t
8515 (let* ((import-clause (js2-parse-import-clause))
8516 (from-clause (and import-clause (js2-parse-from-clause)))
8517 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8518 (node (make-js2-import-node
8519 :pos beg
8520 :len (- (js2-current-token-end) beg)
8521 :import import-clause
8522 :from from-clause
8523 :module-id module-id)))
8524 (when import-clause
8525 (js2-node-add-children node import-clause))
8526 (when from-clause
8527 (js2-node-add-children node from-clause))
8528 node)))))
8529
8530 (defun js2-parse-import-clause ()
8531 "Parse the bindings in an import statement.
8532 This can take many forms:
8533
8534 ImportedDefaultBinding -> 'foo'
8535 NameSpaceImport -> '* as lib'
8536 NamedImports -> '{foo as bar, bang}'
8537 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8538 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8539
8540 Try to match namespace imports and named imports first because nothing can
8541 come after them. If it is an imported default binding, then it could have named
8542 imports or a namespace import that follows it.
8543 "
8544 (let* ((beg (js2-current-token-beg))
8545 (clause (make-js2-import-clause-node
8546 :pos beg))
8547 (children (list)))
8548 (cond
8549 ((js2-match-token js2-MUL)
8550 (let ((ns-import (js2-parse-namespace-import)))
8551 (when ns-import
8552 (let ((name-node (js2-namespace-import-node-name ns-import)))
8553 (js2-define-symbol
8554 js2-LET (js2-name-node-name name-node) name-node t)))
8555 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8556 (push ns-import children)))
8557 ((js2-match-token js2-LC)
8558 (let ((imports (js2-parse-export-bindings t)))
8559 (setf (js2-import-clause-node-named-imports clause) imports)
8560 (dolist (import imports)
8561 (push import children)
8562 (let ((name-node (js2-export-binding-node-local-name import)))
8563 (when name-node
8564 (js2-define-symbol
8565 js2-LET (js2-name-node-name name-node) name-node t))))))
8566 ((= (js2-peek-token) js2-NAME)
8567 (let ((binding (js2-maybe-parse-export-binding)))
8568 (let ((node-name (js2-export-binding-node-local-name binding)))
8569 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8570 (setf (js2-import-clause-node-default-binding clause) binding)
8571 (push binding children))
8572 (when (js2-match-token js2-COMMA)
8573 (cond
8574 ((js2-match-token js2-MUL)
8575 (let ((ns-import (js2-parse-namespace-import)))
8576 (let ((name-node (js2-namespace-import-node-name ns-import)))
8577 (js2-define-symbol
8578 js2-LET (js2-name-node-name name-node) name-node t))
8579 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8580 (push ns-import children)))
8581 ((js2-match-token js2-LC)
8582 (let ((imports (js2-parse-export-bindings t)))
8583 (setf (js2-import-clause-node-named-imports clause) imports)
8584 (dolist (import imports)
8585 (push import children)
8586 (let ((name-node (js2-export-binding-node-local-name import)))
8587 (when name-node
8588 (js2-define-symbol
8589 js2-LET (js2-name-node-name name-node) name-node t))))))
8590 (t (js2-report-error "msg.syntax")))))
8591 (t (js2-report-error "msg.mod.declaration.after.import")))
8592 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8593 (apply #'js2-node-add-children clause children)
8594 clause))
8595
8596 (defun js2-parse-namespace-import ()
8597 "Parse a namespace import expression such as '* as bar'.
8598 The current token must be js2-MUL."
8599 (let ((beg (js2-current-token-beg)))
8600 (when (js2-must-match js2-NAME "msg.syntax")
8601 (if (equal "as" (js2-current-token-string))
8602 (when (js2-must-match-prop-name "msg.syntax")
8603 (let ((node (make-js2-namespace-import-node
8604 :pos beg
8605 :len (- (js2-current-token-end) beg)
8606 :name (make-js2-name-node
8607 :pos (js2-current-token-beg)
8608 :len (js2-current-token-end)
8609 :name (js2-current-token-string)))))
8610 (js2-node-add-children node (js2-namespace-import-node-name node))
8611 node))
8612 (js2-unget-token)
8613 (js2-report-error "msg.syntax")))))
8614
8615
8616 (defun js2-parse-from-clause ()
8617 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8618 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8619 (let ((beg (js2-current-token-beg)))
8620 (if (equal "from" (js2-current-token-string))
8621 (cond
8622 ((js2-match-token js2-STRING)
8623 (make-js2-from-clause-node
8624 :pos beg
8625 :len (- (js2-current-token-end) beg)
8626 :module-id (js2-current-token-string)
8627 :metadata-p nil))
8628 ((js2-match-token js2-THIS)
8629 (when (js2-must-match-name "msg.mod.spec.after.from")
8630 (if (equal "module" (js2-current-token-string))
8631 (make-js2-from-clause-node
8632 :pos beg
8633 :len (- (js2-current-token-end) beg)
8634 :module-id "this"
8635 :metadata-p t)
8636 (js2-unget-token)
8637 (js2-unget-token)
8638 (js2-report-error "msg.mod.spec.after.from")
8639 nil)))
8640 (t (js2-report-error "msg.mod.spec.after.from") nil))
8641 (js2-unget-token)
8642 (js2-report-error "msg.mod.from.after.import.spec.set")
8643 nil))))
8644
8645 (defun js2-parse-export-bindings (&optional import-p)
8646 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8647 {foo as bar, baz as bang}. The current token must be
8648 js2-LC. Return a lisp list of js2-export-binding-node"
8649 (let ((bindings (list)))
8650 (while
8651 (let ((binding (js2-maybe-parse-export-binding)))
8652 (when binding
8653 (push binding bindings))
8654 (js2-match-token js2-COMMA)))
8655 (when (js2-must-match js2-RC (if import-p
8656 "msg.mod.rc.after.import.spec.list"
8657 "msg.mod.rc.after.export.spec.list"))
8658 (reverse bindings))))
8659
8660 (defun js2-maybe-parse-export-binding ()
8661 "Attempt to parse a binding expression found inside an import/export statement.
8662 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8663 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8664 js2-export-binding-node and consume all the tokens. If it does not match, it
8665 consumes no tokens."
8666 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8667 (beg (js2-current-token-beg))
8668 (extern-name-len (js2-current-token-len))
8669 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8670 (aref js2-kwd-tokens (js2-current-token-type)))))
8671 (if extern-name
8672 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8673 (if (and as (equal "as" (js2-current-token-string)))
8674 (let ((name
8675 (or
8676 (and (js2-match-token js2-DEFAULT) "default")
8677 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8678 (if name
8679 (let ((node (make-js2-export-binding-node
8680 :pos beg
8681 :len (- (js2-current-token-end) beg)
8682 :local-name (make-js2-name-node
8683 :name name
8684 :pos (js2-current-token-beg)
8685 :len (js2-current-token-len))
8686 :extern-name (make-js2-name-node
8687 :name extern-name
8688 :pos beg
8689 :len extern-name-len))))
8690 (js2-node-add-children
8691 node
8692 (js2-export-binding-node-local-name node)
8693 (js2-export-binding-node-extern-name node))
8694 node)
8695 (js2-unget-token)
8696 nil))
8697 (when as (js2-unget-token))
8698 (let* ((name-node (make-js2-name-node
8699 :name (js2-current-token-string)
8700 :pos (js2-current-token-beg)
8701 :len (js2-current-token-len)))
8702 (node (make-js2-export-binding-node
8703 :pos (js2-current-token-beg)
8704 :len (js2-current-token-len)
8705 :local-name name-node
8706 :extern-name name-node)))
8707 (when is-reserved-name
8708 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8709 (js2-node-add-children node name-node)
8710 node)))
8711 nil)))
8712
8713 (defun js2-parse-switch ()
8714 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8715 (let ((pos (js2-current-token-beg))
8716 tt pn discriminant has-default case-expr case-node
8717 case-pos cases stmt lp)
8718 (if (js2-must-match js2-LP "msg.no.paren.switch")
8719 (setq lp (js2-current-token-beg)))
8720 (setq discriminant (js2-parse-expr)
8721 pn (make-js2-switch-node :discriminant discriminant
8722 :pos pos
8723 :lp (js2-relpos lp pos)))
8724 (js2-node-add-children pn discriminant)
8725 (js2-enter-switch pn)
8726 (unwind-protect
8727 (progn
8728 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8729 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8730 (js2-must-match js2-LC "msg.no.brace.switch")
8731 (catch 'break
8732 (while t
8733 (setq tt (js2-next-token)
8734 case-pos (js2-current-token-beg))
8735 (cond
8736 ((= tt js2-RC)
8737 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8738 (throw 'break nil)) ; done
8739 ((= tt js2-CASE)
8740 (setq case-expr (js2-parse-expr))
8741 (js2-must-match js2-COLON "msg.no.colon.case"))
8742 ((= tt js2-DEFAULT)
8743 (if has-default
8744 (js2-report-error "msg.double.switch.default"))
8745 (setq has-default t
8746 case-expr nil)
8747 (js2-must-match js2-COLON "msg.no.colon.case"))
8748 (t
8749 (js2-report-error "msg.bad.switch")
8750 (throw 'break nil)))
8751 (setq case-node (make-js2-case-node :pos case-pos
8752 :len (- (js2-current-token-end) case-pos)
8753 :expr case-expr))
8754 (js2-node-add-children case-node case-expr)
8755 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8756 (/= tt js2-CASE)
8757 (/= tt js2-DEFAULT)
8758 (/= tt js2-EOF))
8759 (setf stmt (js2-parse-statement)
8760 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8761 (js2-block-node-push case-node stmt))
8762 (push case-node cases)))
8763 ;; add cases last, as pushing reverses the order to be correct
8764 (dolist (kid cases)
8765 (js2-node-add-children pn kid)
8766 (push kid (js2-switch-node-cases pn)))
8767 pn) ; return value
8768 (js2-exit-switch))))
8769
8770 (defun js2-parse-while ()
8771 "Parser for while-statement. Last matched token must be js2-WHILE."
8772 (let ((pos (js2-current-token-beg))
8773 (pn (make-js2-while-node))
8774 cond body)
8775 (js2-enter-loop pn)
8776 (unwind-protect
8777 (progn
8778 (setf cond (js2-parse-condition)
8779 (js2-while-node-condition pn) (car cond)
8780 body (js2-parse-statement)
8781 (js2-while-node-body pn) body
8782 (js2-node-len pn) (- (js2-node-end body) pos)
8783 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8784 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8785 (js2-node-add-children pn body (car cond)))
8786 (js2-exit-loop))
8787 pn))
8788
8789 (defun js2-parse-do ()
8790 "Parser for do-statement. Last matched token must be js2-DO."
8791 (let ((pos (js2-current-token-beg))
8792 (pn (make-js2-do-node))
8793 cond body end)
8794 (js2-enter-loop pn)
8795 (unwind-protect
8796 (progn
8797 (setq body (js2-parse-statement))
8798 (js2-must-match js2-WHILE "msg.no.while.do")
8799 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8800 cond (js2-parse-condition)
8801 (js2-do-node-condition pn) (car cond)
8802 (js2-do-node-body pn) body
8803 end js2-ts-cursor
8804 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8805 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8806 (js2-node-add-children pn (car cond) body))
8807 (js2-exit-loop))
8808 ;; Always auto-insert semicolon to follow SpiderMonkey:
8809 ;; It is required by ECMAScript but is ignored by the rest of
8810 ;; world; see bug 238945
8811 (if (js2-match-token js2-SEMI)
8812 (setq end js2-ts-cursor))
8813 (setf (js2-node-len pn) (- end pos))
8814 pn))
8815
8816 (defun js2-parse-export ()
8817 "Parse an export statement.
8818 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8819 expressions should only be either hoistable expressions (function or generator)
8820 or assignment expressions, but there is no checking to enforce that and so it
8821 will parse without error a small subset of
8822 invalid export statements."
8823 (unless (js2-ast-root-p js2-current-scope)
8824 (js2-report-error "msg.mod.export.decl.at.top.level"))
8825 (let ((beg (js2-current-token-beg))
8826 (children (list))
8827 exports-list from-clause declaration default)
8828 (cond
8829 ((js2-match-token js2-MUL)
8830 (setq from-clause (js2-parse-from-clause))
8831 (when from-clause
8832 (push from-clause children)))
8833 ((js2-match-token js2-LC)
8834 (setq exports-list (js2-parse-export-bindings))
8835 (when exports-list
8836 (dolist (export exports-list)
8837 (push export children)))
8838 (when (js2-match-token js2-NAME)
8839 (if (equal "from" (js2-current-token-string))
8840 (progn
8841 (js2-unget-token)
8842 (setq from-clause (js2-parse-from-clause)))
8843 (js2-unget-token))))
8844 ((js2-match-token js2-DEFAULT)
8845 (setq default (cond ((js2-match-token js2-CLASS)
8846 (js2-parse-class-stmt))
8847 ((js2-match-token js2-FUNCTION)
8848 (js2-parse-function-stmt))
8849 (t (js2-parse-expr)))))
8850 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8851 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8852 ((js2-match-token js2-CLASS)
8853 (setq declaration (js2-parse-class-stmt)))
8854 ((js2-match-token js2-FUNCTION)
8855 (setq declaration (js2-parse-function-stmt)))
8856 (t
8857 (setq declaration (js2-parse-expr))))
8858 (when from-clause
8859 (push from-clause children))
8860 (when declaration
8861 (push declaration children)
8862 (when (not (or (js2-function-node-p declaration)
8863 (js2-class-node-p declaration)))
8864 (js2-auto-insert-semicolon declaration)))
8865 (when default
8866 (push default children)
8867 (when (not (or (js2-function-node-p default)
8868 (js2-class-node-p default)))
8869 (js2-auto-insert-semicolon default)))
8870 (let ((node (make-js2-export-node
8871 :pos beg
8872 :len (- (js2-current-token-end) beg)
8873 :exports-list exports-list
8874 :from-clause from-clause
8875 :declaration declaration
8876 :default default)))
8877 (apply #'js2-node-add-children node children)
8878 node)))
8879
8880 (defun js2-parse-for ()
8881 "Parse a for, for-in or for each-in statement.
8882 Last matched token must be js2-FOR."
8883 (let ((for-pos (js2-current-token-beg))
8884 (tmp-scope (make-js2-scope))
8885 pn is-for-each is-for-in-or-of is-for-of
8886 in-pos each-pos tmp-pos
8887 init ; Node init is also foo in 'foo in object'.
8888 cond ; Node cond is also object in 'foo in object'.
8889 incr ; 3rd section of for-loop initializer.
8890 body tt lp rp)
8891 ;; See if this is a for each () instead of just a for ()
8892 (when (js2-match-token js2-NAME)
8893 (if (string= "each" (js2-current-token-string))
8894 (progn
8895 (setq is-for-each t
8896 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8897 (js2-record-face 'font-lock-keyword-face))
8898 (js2-report-error "msg.no.paren.for")))
8899 (if (js2-must-match js2-LP "msg.no.paren.for")
8900 (setq lp (- (js2-current-token-beg) for-pos)))
8901 (setq tt (js2-get-token))
8902 ;; Capture identifiers inside parens. We can't create the node
8903 ;; (and use it as the current scope) until we know its type.
8904 (js2-push-scope tmp-scope)
8905 (unwind-protect
8906 (progn
8907 ;; parse init clause
8908 (let ((js2-in-for-init t)) ; set as dynamic variable
8909 (cond
8910 ((= tt js2-SEMI)
8911 (js2-unget-token)
8912 (setq init (make-js2-empty-expr-node)))
8913 ((or (= tt js2-VAR) (= tt js2-LET))
8914 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8915 (t
8916 (js2-unget-token)
8917 (setq init (js2-parse-expr)))))
8918 (if (or (js2-match-token js2-IN)
8919 (and (>= js2-language-version 200)
8920 (js2-match-contextual-kwd "of")
8921 (setq is-for-of t)))
8922 (setq is-for-in-or-of t
8923 in-pos (- (js2-current-token-beg) for-pos)
8924 ;; scope of iteration target object is not the scope we've created above.
8925 ;; stash current scope temporary.
8926 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8927 (js2-parse-expr))) ; object over which we're iterating
8928 ;; else ordinary for loop - parse cond and incr
8929 (js2-must-match js2-SEMI "msg.no.semi.for")
8930 (setq cond (if (= (js2-peek-token) js2-SEMI)
8931 (make-js2-empty-expr-node) ; no loop condition
8932 (js2-parse-expr)))
8933 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8934 (setq tmp-pos (js2-current-token-end)
8935 incr (if (= (js2-peek-token) js2-RP)
8936 (make-js2-empty-expr-node :pos tmp-pos)
8937 (js2-parse-expr)))))
8938 (js2-pop-scope))
8939 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8940 (setq rp (- (js2-current-token-beg) for-pos)))
8941 (if (not is-for-in-or-of)
8942 (setq pn (make-js2-for-node :init init
8943 :condition cond
8944 :update incr
8945 :lp lp
8946 :rp rp))
8947 ;; cond could be null if 'in obj' got eaten by the init node.
8948 (if (js2-infix-node-p init)
8949 ;; it was (foo in bar) instead of (var foo in bar)
8950 (setq cond (js2-infix-node-right init)
8951 init (js2-infix-node-left init))
8952 (if (and (js2-var-decl-node-p init)
8953 (> (length (js2-var-decl-node-kids init)) 1))
8954 (js2-report-error "msg.mult.index")))
8955 (setq pn (make-js2-for-in-node :iterator init
8956 :object cond
8957 :in-pos in-pos
8958 :foreach-p is-for-each
8959 :each-pos each-pos
8960 :forof-p is-for-of
8961 :lp lp
8962 :rp rp)))
8963 ;; Transplant the declarations.
8964 (setf (js2-scope-symbol-table pn)
8965 (js2-scope-symbol-table tmp-scope))
8966 (unwind-protect
8967 (progn
8968 (js2-enter-loop pn)
8969 ;; We have to parse the body -after- creating the loop node,
8970 ;; so that the loop node appears in the js2-loop-set, allowing
8971 ;; break/continue statements to find the enclosing loop.
8972 (setf body (js2-parse-statement)
8973 (js2-loop-node-body pn) body
8974 (js2-node-pos pn) for-pos
8975 (js2-node-len pn) (- (js2-node-end body) for-pos))
8976 (js2-node-add-children pn init cond incr body))
8977 ;; finally
8978 (js2-exit-loop))
8979 pn))
8980
8981 (defun js2-parse-try ()
8982 "Parse a try statement. Last matched token must be js2-TRY."
8983 (let ((try-pos (js2-current-token-beg))
8984 try-end
8985 try-block
8986 catch-blocks
8987 finally-block
8988 saw-default-catch
8989 peek)
8990 (if (/= (js2-peek-token) js2-LC)
8991 (js2-report-error "msg.no.brace.try"))
8992 (setq try-block (js2-parse-statement)
8993 try-end (js2-node-end try-block)
8994 peek (js2-peek-token))
8995 (cond
8996 ((= peek js2-CATCH)
8997 (while (js2-match-token js2-CATCH)
8998 (let* ((catch-pos (js2-current-token-beg))
8999 (catch-node (make-js2-catch-node :pos catch-pos))
9000 param
9001 guard-kwd
9002 catch-cond
9003 lp rp)
9004 (if saw-default-catch
9005 (js2-report-error "msg.catch.unreachable"))
9006 (if (js2-must-match js2-LP "msg.no.paren.catch")
9007 (setq lp (- (js2-current-token-beg) catch-pos)))
9008 (js2-push-scope catch-node)
9009 (let ((tt (js2-peek-token)))
9010 (cond
9011 ;; Destructuring pattern:
9012 ;; catch ({ message, file }) { ... }
9013 ((or (= tt js2-LB) (= tt js2-LC))
9014 (js2-get-token)
9015 (setq param (js2-parse-destruct-primary-expr))
9016 (js2-define-destruct-symbols param js2-LET nil))
9017 ;; Simple name.
9018 (t
9019 (js2-must-match-name "msg.bad.catchcond")
9020 (setq param (js2-create-name-node))
9021 (js2-define-symbol js2-LET (js2-current-token-string) param)
9022 (js2-check-strict-identifier param))))
9023 ;; Catch condition.
9024 (if (js2-match-token js2-IF)
9025 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9026 catch-cond (js2-parse-expr))
9027 (setq saw-default-catch t))
9028 (if (js2-must-match js2-RP "msg.bad.catchcond")
9029 (setq rp (- (js2-current-token-beg) catch-pos)))
9030 (js2-must-match js2-LC "msg.no.brace.catchblock")
9031 (js2-parse-statements catch-node)
9032 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9033 (setq try-end (js2-current-token-end)))
9034 (js2-pop-scope)
9035 (setf (js2-node-len catch-node) (- try-end catch-pos)
9036 (js2-catch-node-param catch-node) param
9037 (js2-catch-node-guard-expr catch-node) catch-cond
9038 (js2-catch-node-guard-kwd catch-node) guard-kwd
9039 (js2-catch-node-lp catch-node) lp
9040 (js2-catch-node-rp catch-node) rp)
9041 (js2-node-add-children catch-node param catch-cond)
9042 (push catch-node catch-blocks))))
9043 ((/= peek js2-FINALLY)
9044 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9045 (js2-node-pos try-block)
9046 (- (setq try-end (js2-node-end try-block))
9047 (js2-node-pos try-block)))))
9048 (when (js2-match-token js2-FINALLY)
9049 (let ((finally-pos (js2-current-token-beg))
9050 (block (js2-parse-statement)))
9051 (setq try-end (js2-node-end block)
9052 finally-block (make-js2-finally-node :pos finally-pos
9053 :len (- try-end finally-pos)
9054 :body block))
9055 (js2-node-add-children finally-block block)))
9056 (let ((pn (make-js2-try-node :pos try-pos
9057 :len (- try-end try-pos)
9058 :try-block try-block
9059 :finally-block finally-block)))
9060 (js2-node-add-children pn try-block finally-block)
9061 ;; Push them onto the try-node, which reverses and corrects their order.
9062 (dolist (cb catch-blocks)
9063 (js2-node-add-children pn cb)
9064 (push cb (js2-try-node-catch-clauses pn)))
9065 pn)))
9066
9067 (defun js2-parse-throw ()
9068 "Parser for throw-statement. Last matched token must be js2-THROW."
9069 (let ((pos (js2-current-token-beg))
9070 expr pn)
9071 (if (= (js2-peek-token-or-eol) js2-EOL)
9072 ;; ECMAScript does not allow new lines before throw expression,
9073 ;; see bug 256617
9074 (js2-report-error "msg.bad.throw.eol"))
9075 (setq expr (js2-parse-expr)
9076 pn (make-js2-throw-node :pos pos
9077 :len (- (js2-node-end expr) pos)
9078 :expr expr))
9079 (js2-node-add-children pn expr)
9080 pn))
9081
9082 (defun js2-match-jump-label-name (label-name)
9083 "If break/continue specified a label, return that label's labeled stmt.
9084 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9085 does not match an existing label, reports an error and returns nil."
9086 (let ((bundle (cdr (assoc label-name js2-label-set))))
9087 (if (null bundle)
9088 (js2-report-error "msg.undef.label"))
9089 bundle))
9090
9091 (defun js2-parse-break ()
9092 "Parser for break-statement. Last matched token must be js2-BREAK."
9093 (let ((pos (js2-current-token-beg))
9094 (end (js2-current-token-end))
9095 break-target ; statement to break from
9096 break-label ; in "break foo", name-node representing the foo
9097 labels ; matching labeled statement to break to
9098 pn)
9099 (when (eq (js2-peek-token-or-eol) js2-NAME)
9100 (js2-get-token)
9101 (setq break-label (js2-create-name-node)
9102 end (js2-node-end break-label)
9103 ;; matchJumpLabelName only matches if there is one
9104 labels (js2-match-jump-label-name (js2-current-token-string))
9105 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9106 (unless (or break-target break-label)
9107 ;; no break target specified - try for innermost enclosing loop/switch
9108 (if (null js2-loop-and-switch-set)
9109 (unless break-label
9110 (js2-report-error "msg.bad.break" nil pos (length "break")))
9111 (setq break-target (car js2-loop-and-switch-set))))
9112 (setq pn (make-js2-break-node :pos pos
9113 :len (- end pos)
9114 :label break-label
9115 :target break-target))
9116 (js2-node-add-children pn break-label) ; but not break-target
9117 pn))
9118
9119 (defun js2-parse-continue ()
9120 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9121 (let ((pos (js2-current-token-beg))
9122 (end (js2-current-token-end))
9123 label ; optional user-specified label, a `js2-name-node'
9124 labels ; current matching labeled stmt, if any
9125 target ; the `js2-loop-node' target of this continue stmt
9126 pn)
9127 (when (= (js2-peek-token-or-eol) js2-NAME)
9128 (js2-get-token)
9129 (setq label (js2-create-name-node)
9130 end (js2-node-end label)
9131 ;; matchJumpLabelName only matches if there is one
9132 labels (js2-match-jump-label-name (js2-current-token-string))))
9133 (cond
9134 ((null labels) ; no current label to go to
9135 (if (null js2-loop-set) ; no loop to continue to
9136 (js2-report-error "msg.continue.outside" nil pos
9137 (length "continue"))
9138 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9139 (t
9140 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9141 (setq target (js2-labeled-stmt-node-stmt labels))
9142 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9143 (setq pn (make-js2-continue-node :pos pos
9144 :len (- end pos)
9145 :label label
9146 :target target))
9147 (js2-node-add-children pn label) ; but not target - it's not our child
9148 pn))
9149
9150 (defun js2-parse-with ()
9151 "Parser for with-statement. Last matched token must be js2-WITH."
9152 (when js2-in-use-strict-directive
9153 (js2-report-error "msg.no.with.strict"))
9154 (let ((pos (js2-current-token-beg))
9155 obj body pn lp rp)
9156 (if (js2-must-match js2-LP "msg.no.paren.with")
9157 (setq lp (js2-current-token-beg)))
9158 (setq obj (js2-parse-expr))
9159 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9160 (setq rp (js2-current-token-beg)))
9161 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9162 (setq body (js2-parse-statement)))
9163 (setq pn (make-js2-with-node :pos pos
9164 :len (- (js2-node-end body) pos)
9165 :object obj
9166 :body body
9167 :lp (js2-relpos lp pos)
9168 :rp (js2-relpos rp pos)))
9169 (js2-node-add-children pn obj body)
9170 pn))
9171
9172 (defun js2-parse-const-var ()
9173 "Parser for var- or const-statement.
9174 Last matched token must be js2-CONST or js2-VAR."
9175 (let ((tt (js2-current-token-type))
9176 (pos (js2-current-token-beg))
9177 expr pn)
9178 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9179 pn (make-js2-expr-stmt-node :pos pos
9180 :len (- (js2-node-end expr) pos)
9181 :expr expr))
9182 (js2-node-add-children pn expr)
9183 pn))
9184
9185 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9186 (let ((pn (make-js2-expr-stmt-node :pos pos
9187 :len (js2-node-len expr)
9188 :type (if (js2-inside-function)
9189 js2-EXPR_VOID
9190 js2-EXPR_RESULT)
9191 :expr expr)))
9192 (if add-child
9193 (js2-node-add-children pn expr))
9194 pn))
9195
9196 (defun js2-parse-let-stmt ()
9197 "Parser for let-statement. Last matched token must be js2-LET."
9198 (let ((pos (js2-current-token-beg))
9199 expr pn)
9200 (if (= (js2-peek-token) js2-LP)
9201 ;; let expression in statement context
9202 (setq expr (js2-parse-let pos 'statement)
9203 pn (js2-wrap-with-expr-stmt pos expr t))
9204 ;; else we're looking at a statement like let x=6, y=7;
9205 (setf expr (js2-parse-variables js2-LET pos)
9206 pn (js2-wrap-with-expr-stmt pos expr t)
9207 (js2-node-type pn) js2-EXPR_RESULT))
9208 pn))
9209
9210 (defun js2-parse-ret-yield ()
9211 (js2-parse-return-or-yield (js2-current-token-type) nil))
9212
9213 (defconst js2-parse-return-stmt-enders
9214 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9215
9216 (defsubst js2-now-all-set (before after mask)
9217 "Return whether or not the bits in the mask have changed to all set.
9218 BEFORE is bits before change, AFTER is bits after change, and MASK is
9219 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9220 but not BEFORE."
9221 (and (/= (logand before mask) mask)
9222 (= (logand after mask) mask)))
9223
9224 (defun js2-parse-return-or-yield (tt expr-context)
9225 (let* ((pos (js2-current-token-beg))
9226 (end (js2-current-token-end))
9227 (before js2-end-flags)
9228 (inside-function (js2-inside-function))
9229 (gen-type (and inside-function (js2-function-node-generator-type
9230 js2-current-script-or-fn)))
9231 e ret name yield-star-p)
9232 (unless inside-function
9233 (js2-report-error (if (eq tt js2-RETURN)
9234 "msg.bad.return"
9235 "msg.bad.yield")))
9236 (when (and inside-function
9237 (eq gen-type 'STAR)
9238 (js2-match-token js2-MUL))
9239 (setq yield-star-p t))
9240 ;; This is ugly, but we don't want to require a semicolon.
9241 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9242 (setq e (js2-parse-expr)
9243 end (js2-node-end e)))
9244 (cond
9245 ((eq tt js2-RETURN)
9246 (js2-set-flag js2-end-flags (if (null e)
9247 js2-end-returns
9248 js2-end-returns-value))
9249 (setq ret (make-js2-return-node :pos pos
9250 :len (- end pos)
9251 :retval e))
9252 (js2-node-add-children ret e)
9253 ;; See if we need a strict mode warning.
9254 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9255 ;; more thorough and accurate than this before/after flag check.
9256 ;; E.g. if there's a finally-block that always returns, we shouldn't
9257 ;; show a warning generated by inconsistent returns in the catch blocks.
9258 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9259 ;; so we know which returns/yields to highlight, and we should get rid of
9260 ;; all the checking in `js2-parse-return-or-yield'.
9261 (if (and js2-strict-inconsistent-return-warning
9262 (js2-now-all-set before js2-end-flags
9263 (logior js2-end-returns js2-end-returns-value)))
9264 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9265 ((eq gen-type 'COMPREHENSION)
9266 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9267 ;; like SpiderMonkey does.
9268 (js2-report-error "msg.syntax" nil pos 5))
9269 (t
9270 (setq ret (make-js2-yield-node :pos pos
9271 :len (- end pos)
9272 :value e
9273 :star-p yield-star-p))
9274 (js2-node-add-children ret e)
9275 (unless expr-context
9276 (setq e ret
9277 ret (js2-wrap-with-expr-stmt pos e t))
9278 (js2-set-requires-activation)
9279 (js2-set-is-generator))))
9280 ;; see if we are mixing yields and value returns.
9281 (when (and inside-function
9282 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9283 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9284 'LEGACY))
9285 (setq name (js2-function-name js2-current-script-or-fn))
9286 (if (zerop (length name))
9287 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9288 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9289 ret))
9290
9291 (defun js2-parse-debugger ()
9292 (make-js2-keyword-node :type js2-DEBUGGER))
9293
9294 (defun js2-parse-block ()
9295 "Parser for a curly-delimited statement block.
9296 Last token matched must be `js2-LC'."
9297 (let ((pos (js2-current-token-beg))
9298 (pn (make-js2-scope)))
9299 (js2-push-scope pn)
9300 (unwind-protect
9301 (progn
9302 (js2-parse-statements pn)
9303 (js2-must-match js2-RC "msg.no.brace.block")
9304 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9305 (js2-pop-scope))
9306 pn))
9307
9308 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9309 (defun js2-parse-semi ()
9310 "Parse a statement or handle an error.
9311 Current token type is `js2-SEMI' or `js2-ERROR'."
9312 (let ((tt (js2-current-token-type)) pos len)
9313 (if (eq tt js2-SEMI)
9314 (make-js2-empty-expr-node :len 1)
9315 (setq pos (js2-current-token-beg)
9316 len (- (js2-current-token-end) pos))
9317 (js2-report-error "msg.syntax" nil pos len)
9318 (make-js2-error-node :pos pos :len len))))
9319
9320 (defun js2-parse-default-xml-namespace ()
9321 "Parse a `default xml namespace = <expr>' e4x statement."
9322 (let ((pos (js2-current-token-beg))
9323 end len expr unary)
9324 (js2-must-have-xml)
9325 (js2-set-requires-activation)
9326 (setq len (- js2-ts-cursor pos))
9327 (unless (and (js2-match-token js2-NAME)
9328 (string= (js2-current-token-string) "xml"))
9329 (js2-report-error "msg.bad.namespace" nil pos len))
9330 (unless (and (js2-match-token js2-NAME)
9331 (string= (js2-current-token-string) "namespace"))
9332 (js2-report-error "msg.bad.namespace" nil pos len))
9333 (unless (js2-match-token js2-ASSIGN)
9334 (js2-report-error "msg.bad.namespace" nil pos len))
9335 (setq expr (js2-parse-expr)
9336 end (js2-node-end expr)
9337 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9338 :pos pos
9339 :len (- end pos)
9340 :operand expr))
9341 (js2-node-add-children unary expr)
9342 (make-js2-expr-stmt-node :pos pos
9343 :len (- end pos)
9344 :expr unary)))
9345
9346 (defun js2-record-label (label bundle)
9347 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9348 (js2-get-token)
9349 (let ((name (js2-label-node-name label))
9350 labeled-stmt
9351 dup)
9352 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9353 ;; flag both labels if possible when used in editing mode
9354 (if (and js2-parse-ide-mode
9355 (setq dup (js2-get-label-by-name labeled-stmt name)))
9356 (js2-report-error "msg.dup.label" nil
9357 (js2-node-abs-pos dup) (js2-node-len dup)))
9358 (js2-report-error "msg.dup.label" nil
9359 (js2-node-pos label) (js2-node-len label)))
9360 (js2-labeled-stmt-node-add-label bundle label)
9361 (js2-node-add-children bundle label)
9362 ;; Add one reference to the bundle per label in `js2-label-set'
9363 (push (cons name bundle) js2-label-set)))
9364
9365 (defun js2-parse-name-or-label ()
9366 "Parser for identifier or label. Last token matched must be js2-NAME.
9367 Called when we found a name in a statement context. If it's a label, we gather
9368 up any following labels and the next non-label statement into a
9369 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9370 expression and return it wrapped in a `js2-expr-stmt-node'."
9371 (let ((pos (js2-current-token-beg))
9372 expr stmt bundle
9373 (continue t))
9374 ;; set check for label and call down to `js2-parse-primary-expr'
9375 (setq expr (js2-maybe-parse-label))
9376 (if (null expr)
9377 ;; Parse the non-label expression and wrap with expression stmt.
9378 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9379 ;; else parsed a label
9380 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9381 (js2-record-label expr bundle)
9382 ;; look for more labels
9383 (while (and continue (= (js2-get-token) js2-NAME))
9384 (if (setq expr (js2-maybe-parse-label))
9385 (js2-record-label expr bundle)
9386 (setq expr (js2-parse-expr)
9387 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9388 continue nil)
9389 (js2-auto-insert-semicolon stmt)))
9390 ;; no more labels; now parse the labeled statement
9391 (unwind-protect
9392 (unless stmt
9393 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9394 (js2-unget-token)
9395 (setq stmt (js2-statement-helper))))
9396 ;; remove the labels for this statement from the global set
9397 (dolist (label (js2-labeled-stmt-node-labels bundle))
9398 (setq js2-label-set (remove label js2-label-set))))
9399 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9400 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9401 (js2-node-add-children bundle stmt)
9402 bundle)))
9403
9404 (defun js2-maybe-parse-label ()
9405 (cl-assert (= (js2-current-token-type) js2-NAME))
9406 (let (label-pos
9407 (next-tt (js2-get-token))
9408 (label-end (js2-current-token-end)))
9409 ;; Do not consume colon, it is used as unwind indicator
9410 ;; to return to statementHelper.
9411 (js2-unget-token)
9412 (if (= next-tt js2-COLON)
9413 (prog2
9414 (setq label-pos (js2-current-token-beg))
9415 (make-js2-label-node :pos label-pos
9416 :len (- label-end label-pos)
9417 :name (js2-current-token-string))
9418 (js2-set-face label-pos
9419 label-end
9420 'font-lock-variable-name-face 'record))
9421 ;; Backtrack from the name token, too.
9422 (js2-unget-token)
9423 nil)))
9424
9425 (defun js2-parse-expr-stmt ()
9426 "Default parser in statement context, if no recognized statement found."
9427 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9428 (progn
9429 (js2-unget-token)
9430 (js2-parse-expr)) t))
9431
9432 (defun js2-parse-variables (decl-type pos)
9433 "Parse a comma-separated list of variable declarations.
9434 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9435
9436 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9437 For 'var' or 'const', the keyword should be the token last scanned.
9438
9439 POS is the position where the node should start. It's sometimes the
9440 var/const/let keyword, and other times the beginning of the first token
9441 in the first variable declaration.
9442
9443 Returns the parsed `js2-var-decl-node' expression node."
9444 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9445 :pos pos))
9446 destructuring kid-pos tt init name end nbeg nend vi
9447 (continue t))
9448 ;; Example:
9449 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9450 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9451 ;; var {a, b} = baz;
9452 (while continue
9453 (setq destructuring nil
9454 name nil
9455 tt (js2-get-token)
9456 kid-pos (js2-current-token-beg)
9457 end (js2-current-token-end)
9458 init nil)
9459 (if (or (= tt js2-LB) (= tt js2-LC))
9460 ;; Destructuring assignment, e.g., var [a, b] = ...
9461 (setq destructuring (js2-parse-destruct-primary-expr)
9462 end (js2-node-end destructuring))
9463 ;; Simple variable name
9464 (js2-unget-token)
9465 (when (js2-must-match-name "msg.bad.var")
9466 (setq name (js2-create-name-node)
9467 nbeg (js2-current-token-beg)
9468 nend (js2-current-token-end)
9469 end nend)
9470 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9471 (js2-check-strict-identifier name)))
9472 (when (js2-match-token js2-ASSIGN)
9473 (setq init (js2-parse-assign-expr)
9474 end (js2-node-end init))
9475 (js2-record-imenu-functions init name))
9476 (when name
9477 (js2-set-face nbeg nend (if (js2-function-node-p init)
9478 'font-lock-function-name-face
9479 'font-lock-variable-name-face)
9480 'record))
9481 (setq vi (make-js2-var-init-node :pos kid-pos
9482 :len (- end kid-pos)
9483 :type decl-type))
9484 (if destructuring
9485 (progn
9486 (if (and (null init) (not js2-in-for-init))
9487 (js2-report-error "msg.destruct.assign.no.init"))
9488 (js2-define-destruct-symbols destructuring
9489 decl-type
9490 'font-lock-variable-name-face)
9491 (setf (js2-var-init-node-target vi) destructuring))
9492 (setf (js2-var-init-node-target vi) name))
9493 (setf (js2-var-init-node-initializer vi) init)
9494 (js2-node-add-children vi name destructuring init)
9495 (js2-block-node-push result vi)
9496 (unless (js2-match-token js2-COMMA)
9497 (setq continue nil)))
9498 (setf (js2-node-len result) (- end pos))
9499 result))
9500
9501 (defun js2-parse-let (pos &optional stmt-p)
9502 "Parse a let expression or statement.
9503 A let-expression is of the form `let (vars) expr'.
9504 A let-statement is of the form `let (vars) {statements}'.
9505 The third form of let is a variable declaration list, handled
9506 by `js2-parse-variables'."
9507 (let ((pn (make-js2-let-node :pos pos))
9508 beg vars body)
9509 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9510 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9511 (js2-push-scope pn)
9512 (unwind-protect
9513 (progn
9514 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9515 (if (js2-must-match js2-RP "msg.no.paren.let")
9516 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9517 (if (and stmt-p (js2-match-token js2-LC))
9518 ;; let statement
9519 (progn
9520 (setf beg (js2-current-token-beg) ; position stmt at LC
9521 body (js2-parse-statements))
9522 (js2-must-match js2-RC "msg.no.curly.let")
9523 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9524 (js2-node-len pn) (- (js2-current-token-end) pos)
9525 (js2-let-node-body pn) body
9526 (js2-node-type pn) js2-LET))
9527 ;; let expression
9528 (setf body (js2-parse-expr)
9529 (js2-node-len pn) (- (js2-node-end body) pos)
9530 (js2-let-node-body pn) body))
9531 (setf (js2-let-node-vars pn) vars)
9532 (js2-node-add-children pn vars body))
9533 (js2-pop-scope))
9534 pn))
9535
9536 (defun js2-define-new-symbol (decl-type name node &optional scope)
9537 (js2-scope-put-symbol (or scope js2-current-scope)
9538 name
9539 (make-js2-symbol decl-type name node)))
9540
9541 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9542 "Define a symbol in the current scope.
9543 If NODE is non-nil, it is the AST node associated with the symbol."
9544 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9545 (symbol (if defining-scope
9546 (js2-scope-get-symbol defining-scope name)))
9547 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9548 (pos (if node (js2-node-abs-pos node)))
9549 (len (if node (js2-node-len node))))
9550 (cond
9551 ((and symbol ; already defined
9552 (or (if js2-in-use-strict-directive
9553 ;; two const-bound vars in this block have same name
9554 (and (= sdt js2-CONST)
9555 (eq defining-scope js2-current-scope))
9556 (or (= sdt js2-CONST) ; old version is const
9557 (= decl-type js2-CONST))) ; new version is const
9558 ;; two let-bound vars in this block have same name
9559 (and (= sdt js2-LET)
9560 (eq defining-scope js2-current-scope))))
9561 (js2-report-error
9562 (cond
9563 ((= sdt js2-CONST) "msg.const.redecl")
9564 ((= sdt js2-LET) "msg.let.redecl")
9565 ((= sdt js2-VAR) "msg.var.redecl")
9566 ((= sdt js2-FUNCTION) "msg.function.redecl")
9567 (t "msg.parm.redecl"))
9568 name pos len))
9569 ((or (= decl-type js2-LET)
9570 ;; strict mode const is scoped to the current LexicalEnvironment
9571 (and js2-in-use-strict-directive
9572 (= decl-type js2-CONST)))
9573 (if (and (= decl-type js2-LET)
9574 (not ignore-not-in-block)
9575 (or (= (js2-node-type js2-current-scope) js2-IF)
9576 (js2-loop-node-p js2-current-scope)))
9577 (js2-report-error "msg.let.decl.not.in.block")
9578 (js2-define-new-symbol decl-type name node)))
9579 ((or (= decl-type js2-VAR)
9580 (= decl-type js2-FUNCTION)
9581 ;; sloppy mode const is scoped to the current VariableEnvironment
9582 (and (not js2-in-use-strict-directive)
9583 (= decl-type js2-CONST)))
9584 (if symbol
9585 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9586 (js2-add-strict-warning "msg.var.redecl" name)
9587 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9588 (js2-add-strict-warning "msg.var.hides.arg" name)))
9589 (js2-define-new-symbol decl-type name node
9590 js2-current-script-or-fn)))
9591 ((= decl-type js2-LP)
9592 (if symbol
9593 ;; must be duplicate parameter. Second parameter hides the
9594 ;; first, so go ahead and add the second pararameter
9595 (js2-report-warning "msg.dup.parms" name))
9596 (js2-define-new-symbol decl-type name node))
9597 (t (js2-code-bug)))))
9598
9599 (defun js2-parse-paren-expr-or-generator-comp ()
9600 (let ((px-pos (js2-current-token-beg)))
9601 (cond
9602 ((and (>= js2-language-version 200)
9603 (js2-match-token js2-FOR))
9604 (js2-parse-generator-comp px-pos))
9605 ((and (>= js2-language-version 200)
9606 (js2-match-token js2-RP))
9607 ;; Not valid expression syntax, but this is valid in an arrow
9608 ;; function with no params: () => body.
9609 (if (eq (js2-peek-token) js2-ARROW)
9610 ;; Return whatever, it will hopefully be rewinded and
9611 ;; reparsed when we reach the =>.
9612 (make-js2-keyword-node :type js2-NULL)
9613 (js2-report-error "msg.syntax")
9614 (make-js2-error-node)))
9615 (t
9616 (let* ((js2-in-for-init nil)
9617 (expr (js2-parse-expr))
9618 (pn (make-js2-paren-node :pos px-pos
9619 :expr expr)))
9620 (js2-node-add-children pn (js2-paren-node-expr pn))
9621 (js2-must-match js2-RP "msg.no.paren")
9622 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9623 pn)))))
9624
9625 (defun js2-parse-expr (&optional oneshot)
9626 (let* ((pn (js2-parse-assign-expr))
9627 (pos (js2-node-pos pn))
9628 left
9629 right
9630 op-pos)
9631 (while (and (not oneshot)
9632 (js2-match-token js2-COMMA))
9633 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9634 (if (= (js2-peek-token) js2-YIELD)
9635 (js2-report-error "msg.yield.parenthesized"))
9636 (setq right (js2-parse-assign-expr)
9637 left pn
9638 pn (make-js2-infix-node :type js2-COMMA
9639 :pos pos
9640 :len (- js2-ts-cursor pos)
9641 :op-pos op-pos
9642 :left left
9643 :right right))
9644 (js2-node-add-children pn left right))
9645 pn))
9646
9647 (defun js2-parse-assign-expr ()
9648 (let ((tt (js2-get-token))
9649 (pos (js2-current-token-beg))
9650 pn left right op-pos
9651 ts-state recorded-identifiers parsed-errors
9652 async-p)
9653 (if (= tt js2-YIELD)
9654 (js2-parse-return-or-yield tt t)
9655 ;; TODO(mooz): Bit confusing.
9656 ;; If we meet `async` token and it's not part of `async
9657 ;; function`, then this `async` is for a succeeding async arrow
9658 ;; function.
9659 ;; Since arrow function parsing doesn't rely on neither
9660 ;; `js2-parse-function-stmt' nor `js2-parse-function-expr' that
9661 ;; interpret `async` token, we trash `async` and just remember
9662 ;; we met `async` keyword to `async-p'.
9663 (when (js2-match-async-arrow-function)
9664 (setq async-p t))
9665 ;; Save the tokenizer state in case we find an arrow function
9666 ;; and have to rewind.
9667 (setq ts-state (make-js2-ts-state)
9668 recorded-identifiers js2-recorded-identifiers
9669 parsed-errors js2-parsed-errors)
9670 ;; not yield - parse assignment expression
9671 (setq pn (js2-parse-cond-expr)
9672 tt (js2-get-token))
9673 (cond
9674 ((and (<= js2-first-assign tt)
9675 (<= tt js2-last-assign))
9676 ;; tt express assignment (=, |=, ^=, ..., %=)
9677 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9678 left pn)
9679 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9680 ;; care about assignment to strict variable names.
9681 (when (js2-name-node-p left)
9682 (js2-check-strict-identifier left))
9683 (setq right (js2-parse-assign-expr)
9684 pn (make-js2-assign-node :type tt
9685 :pos pos
9686 :len (- (js2-node-end right) pos)
9687 :op-pos op-pos
9688 :left left
9689 :right right))
9690 (when js2-parse-ide-mode
9691 (js2-highlight-assign-targets pn left right)
9692 (js2-record-imenu-functions right left))
9693 ;; do this last so ide checks above can use absolute positions
9694 (js2-node-add-children pn left right))
9695 ((and (= tt js2-ARROW)
9696 (>= js2-language-version 200))
9697 (js2-ts-seek ts-state)
9698 (setq js2-recorded-identifiers recorded-identifiers
9699 js2-parsed-errors parsed-errors)
9700 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil async-p)))
9701 (t
9702 (js2-unget-token)))
9703 pn)))
9704
9705 (defun js2-parse-cond-expr ()
9706 (let ((pos (js2-current-token-beg))
9707 (pn (js2-parse-or-expr))
9708 test-expr
9709 if-true
9710 if-false
9711 q-pos
9712 c-pos)
9713 (when (js2-match-token js2-HOOK)
9714 (setq q-pos (- (js2-current-token-beg) pos)
9715 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9716 (js2-must-match js2-COLON "msg.no.colon.cond")
9717 (setq c-pos (- (js2-current-token-beg) pos)
9718 if-false (js2-parse-assign-expr)
9719 test-expr pn
9720 pn (make-js2-cond-node :pos pos
9721 :len (- (js2-node-end if-false) pos)
9722 :test-expr test-expr
9723 :true-expr if-true
9724 :false-expr if-false
9725 :q-pos q-pos
9726 :c-pos c-pos))
9727 (js2-node-add-children pn test-expr if-true if-false))
9728 pn))
9729
9730 (defun js2-make-binary (type left parser &optional no-get)
9731 "Helper for constructing a binary-operator AST node.
9732 LEFT is the left-side-expression, already parsed, and the
9733 binary operator should have just been matched.
9734 PARSER is a function to call to parse the right operand,
9735 or a `js2-node' struct if it has already been parsed.
9736 FIXME: The latter option is unused?"
9737 (let* ((pos (js2-node-pos left))
9738 (op-pos (- (js2-current-token-beg) pos))
9739 (right (if (js2-node-p parser)
9740 parser
9741 (unless no-get (js2-get-token))
9742 (funcall parser)))
9743 (pn (make-js2-infix-node :type type
9744 :pos pos
9745 :len (- (js2-node-end right) pos)
9746 :op-pos op-pos
9747 :left left
9748 :right right)))
9749 (js2-node-add-children pn left right)
9750 pn))
9751
9752 (defun js2-parse-or-expr ()
9753 (let ((pn (js2-parse-and-expr)))
9754 (when (js2-match-token js2-OR)
9755 (setq pn (js2-make-binary js2-OR
9756 pn
9757 'js2-parse-or-expr)))
9758 pn))
9759
9760 (defun js2-parse-and-expr ()
9761 (let ((pn (js2-parse-bit-or-expr)))
9762 (when (js2-match-token js2-AND)
9763 (setq pn (js2-make-binary js2-AND
9764 pn
9765 'js2-parse-and-expr)))
9766 pn))
9767
9768 (defun js2-parse-bit-or-expr ()
9769 (let ((pn (js2-parse-bit-xor-expr)))
9770 (while (js2-match-token js2-BITOR)
9771 (setq pn (js2-make-binary js2-BITOR
9772 pn
9773 'js2-parse-bit-xor-expr)))
9774 pn))
9775
9776 (defun js2-parse-bit-xor-expr ()
9777 (let ((pn (js2-parse-bit-and-expr)))
9778 (while (js2-match-token js2-BITXOR)
9779 (setq pn (js2-make-binary js2-BITXOR
9780 pn
9781 'js2-parse-bit-and-expr)))
9782 pn))
9783
9784 (defun js2-parse-bit-and-expr ()
9785 (let ((pn (js2-parse-eq-expr)))
9786 (while (js2-match-token js2-BITAND)
9787 (setq pn (js2-make-binary js2-BITAND
9788 pn
9789 'js2-parse-eq-expr)))
9790 pn))
9791
9792 (defconst js2-parse-eq-ops
9793 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9794
9795 (defun js2-parse-eq-expr ()
9796 (let ((pn (js2-parse-rel-expr))
9797 tt)
9798 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9799 (setq pn (js2-make-binary tt
9800 pn
9801 'js2-parse-rel-expr)))
9802 (js2-unget-token)
9803 pn))
9804
9805 (defconst js2-parse-rel-ops
9806 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9807
9808 (defun js2-parse-rel-expr ()
9809 (let ((pn (js2-parse-shift-expr))
9810 (continue t)
9811 tt)
9812 (while continue
9813 (setq tt (js2-get-token))
9814 (cond
9815 ((and js2-in-for-init (= tt js2-IN))
9816 (js2-unget-token)
9817 (setq continue nil))
9818 ((memq tt js2-parse-rel-ops)
9819 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9820 (t
9821 (js2-unget-token)
9822 (setq continue nil))))
9823 pn))
9824
9825 (defconst js2-parse-shift-ops
9826 (list js2-LSH js2-URSH js2-RSH))
9827
9828 (defun js2-parse-shift-expr ()
9829 (let ((pn (js2-parse-add-expr))
9830 tt
9831 (continue t))
9832 (while continue
9833 (setq tt (js2-get-token))
9834 (if (memq tt js2-parse-shift-ops)
9835 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9836 (js2-unget-token)
9837 (setq continue nil)))
9838 pn))
9839
9840 (defun js2-parse-add-expr ()
9841 (let ((pn (js2-parse-mul-expr))
9842 tt
9843 (continue t))
9844 (while continue
9845 (setq tt (js2-get-token))
9846 (if (or (= tt js2-ADD) (= tt js2-SUB))
9847 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9848 (js2-unget-token)
9849 (setq continue nil)))
9850 pn))
9851
9852 (defconst js2-parse-mul-ops
9853 (list js2-MUL js2-DIV js2-MOD))
9854
9855 (defun js2-parse-mul-expr ()
9856 (let ((pn (js2-parse-unary-expr))
9857 tt
9858 (continue t))
9859 (while continue
9860 (setq tt (js2-get-token))
9861 (if (memq tt js2-parse-mul-ops)
9862 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9863 (js2-unget-token)
9864 (setq continue nil)))
9865 pn))
9866
9867 (defun js2-make-unary (type parser &rest args)
9868 "Make a unary node of type TYPE.
9869 PARSER is either a node (for postfix operators) or a function to call
9870 to parse the operand (for prefix operators)."
9871 (let* ((pos (js2-current-token-beg))
9872 (postfix (js2-node-p parser))
9873 (expr (if postfix
9874 parser
9875 (apply parser args)))
9876 end
9877 pn)
9878 (if postfix ; e.g. i++
9879 (setq pos (js2-node-pos expr)
9880 end (js2-current-token-end))
9881 (setq end (js2-node-end expr)))
9882 (setq pn (make-js2-unary-node :type type
9883 :pos pos
9884 :len (- end pos)
9885 :operand expr))
9886 (js2-node-add-children pn expr)
9887 pn))
9888
9889 (defun js2-make-await ()
9890 "Make an await node."
9891 (let* ((pos (js2-current-token-beg))
9892 (expr (js2-parse-unary-expr))
9893 (end (js2-node-end expr))
9894 pn)
9895 (setq pn (make-js2-await-node :pos pos
9896 :len (- end pos)
9897 :operand expr))
9898 (js2-node-add-children pn expr)
9899 pn))
9900
9901 (defconst js2-incrementable-node-types
9902 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9903 "Node types that can be the operand of a ++ or -- operator.")
9904
9905 (defun js2-check-bad-inc-dec (tt beg end unary)
9906 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9907 js2-incrementable-node-types)
9908 (js2-report-error (if (= tt js2-INC)
9909 "msg.bad.incr"
9910 "msg.bad.decr")
9911 nil beg (- end beg))))
9912
9913 (defun js2-parse-unary-expr ()
9914 (let ((tt (js2-current-token-type))
9915 pn expr beg end)
9916 (cond
9917 ((or (= tt js2-VOID)
9918 (= tt js2-NOT)
9919 (= tt js2-BITNOT)
9920 (= tt js2-TYPEOF))
9921 (js2-get-token)
9922 (js2-make-unary tt 'js2-parse-unary-expr))
9923 ((= tt js2-ADD)
9924 (js2-get-token)
9925 ;; Convert to special POS token in decompiler and parse tree
9926 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9927 ((= tt js2-SUB)
9928 (js2-get-token)
9929 ;; Convert to special NEG token in decompiler and parse tree
9930 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9931 ((or (= tt js2-INC)
9932 (= tt js2-DEC))
9933 (js2-get-token)
9934 (prog1
9935 (setq beg (js2-current-token-beg)
9936 end (js2-current-token-end)
9937 expr (js2-make-unary tt 'js2-parse-member-expr t))
9938 (js2-check-bad-inc-dec tt beg end expr)))
9939 ((= tt js2-DELPROP)
9940 (js2-get-token)
9941 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9942 ((js2-match-await)
9943 (js2-make-unary js2-AWAIT 'js2-parse-unary-expr))
9944 ((= tt js2-ERROR)
9945 (js2-get-token)
9946 (make-js2-error-node)) ; try to continue
9947 ((and (= tt js2-LT)
9948 js2-compiler-xml-available)
9949 ;; XML stream encountered in expression.
9950 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9951 (t
9952 (setq pn (js2-parse-member-expr t)
9953 ;; Don't look across a newline boundary for a postfix incop.
9954 tt (js2-peek-token-or-eol))
9955 (when (or (= tt js2-INC) (= tt js2-DEC))
9956 (js2-get-token)
9957 (setf expr pn
9958 pn (js2-make-unary tt expr))
9959 (js2-node-set-prop pn 'postfix t)
9960 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9961 pn))))
9962
9963 (defun js2-parse-xml-initializer ()
9964 "Parse an E4X XML initializer.
9965 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9966 Then I'll postprocess the result, depending on whether we're in IDE
9967 mode or codegen mode, and generate the appropriate rewritten AST.
9968 IDE mode uses a rich AST that models the XML structure. Codegen mode
9969 just concatenates everything and makes a new XML or XMLList out of it."
9970 (let ((tt (js2-get-first-xml-token))
9971 pn-xml pn expr kids expr-pos
9972 (continue t)
9973 (first-token t))
9974 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9975 (js2-report-error "msg.syntax"))
9976 (setq pn-xml (make-js2-xml-node))
9977 (while continue
9978 (if first-token
9979 (setq first-token nil)
9980 (setq tt (js2-get-next-xml-token)))
9981 (cond
9982 ;; js2-XML means we found a {expr} in the XML stream.
9983 ;; The token string is the XML up to the left-curly.
9984 ((= tt js2-XML)
9985 (push (make-js2-string-node :pos (js2-current-token-beg)
9986 :len (- js2-ts-cursor (js2-current-token-beg)))
9987 kids)
9988 (js2-must-match js2-LC "msg.syntax")
9989 (setq expr-pos js2-ts-cursor
9990 expr (if (eq (js2-peek-token) js2-RC)
9991 (make-js2-empty-expr-node :pos expr-pos)
9992 (js2-parse-expr)))
9993 (js2-must-match js2-RC "msg.syntax")
9994 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9995 :len (js2-node-len expr)
9996 :expr expr))
9997 (js2-node-add-children pn expr)
9998 (push pn kids))
9999 ;; a js2-XMLEND token means we hit the final close-tag.
10000 ((= tt js2-XMLEND)
10001 (push (make-js2-string-node :pos (js2-current-token-beg)
10002 :len (- js2-ts-cursor (js2-current-token-beg)))
10003 kids)
10004 (dolist (kid (nreverse kids))
10005 (js2-block-node-push pn-xml kid))
10006 (setf (js2-node-len pn-xml) (- js2-ts-cursor
10007 (js2-node-pos pn-xml))
10008 continue nil))
10009 (t
10010 (js2-report-error "msg.syntax")
10011 (setq continue nil))))
10012 pn-xml))
10013
10014
10015 (defun js2-parse-argument-list ()
10016 "Parse an argument list and return it as a Lisp list of nodes.
10017 Returns the list in reverse order. Consumes the right-paren token."
10018 (let (result)
10019 (unless (js2-match-token js2-RP)
10020 (cl-loop do
10021 (let ((tt (js2-get-token)))
10022 (if (= tt js2-YIELD)
10023 (js2-report-error "msg.yield.parenthesized"))
10024 (if (and (= tt js2-TRIPLEDOT)
10025 (>= js2-language-version 200))
10026 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
10027 (js2-unget-token)
10028 (push (js2-parse-assign-expr) result)))
10029 while
10030 (js2-match-token js2-COMMA))
10031 (js2-must-match js2-RP "msg.no.paren.arg")
10032 result)))
10033
10034 (defun js2-parse-member-expr (&optional allow-call-syntax)
10035 (let ((tt (js2-current-token-type))
10036 pn pos target args beg end init)
10037 (if (/= tt js2-NEW)
10038 (setq pn (js2-parse-primary-expr))
10039 ;; parse a 'new' expression
10040 (js2-get-token)
10041 (setq pos (js2-current-token-beg)
10042 beg pos
10043 target (js2-parse-member-expr)
10044 end (js2-node-end target)
10045 pn (make-js2-new-node :pos pos
10046 :target target
10047 :len (- end pos)))
10048 (js2-highlight-function-call (js2-current-token))
10049 (js2-node-add-children pn target)
10050 (when (js2-match-token js2-LP)
10051 ;; Add the arguments to pn, if any are supplied.
10052 (setf beg pos ; start of "new" keyword
10053 pos (js2-current-token-beg)
10054 args (nreverse (js2-parse-argument-list))
10055 (js2-new-node-args pn) args
10056 end (js2-current-token-end)
10057 (js2-new-node-lp pn) (- pos beg)
10058 (js2-new-node-rp pn) (- end 1 beg))
10059 (apply #'js2-node-add-children pn args))
10060 (when (and js2-allow-rhino-new-expr-initializer
10061 (js2-match-token js2-LC))
10062 (setf init (js2-parse-object-literal)
10063 end (js2-node-end init)
10064 (js2-new-node-initializer pn) init)
10065 (js2-node-add-children pn init))
10066 (setf (js2-node-len pn) (- end beg))) ; end outer if
10067 (js2-parse-member-expr-tail allow-call-syntax pn)))
10068
10069 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10070 "Parse a chain of property/array accesses or function calls.
10071 Includes parsing for E4X operators like `..' and `.@'.
10072 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10073 Returns an expression tree that includes PN, the parent node."
10074 (let (tt
10075 (continue t))
10076 (while continue
10077 (setq tt (js2-get-token))
10078 (cond
10079 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10080 (setq pn (js2-parse-property-access tt pn)))
10081 ((= tt js2-DOTQUERY)
10082 (setq pn (js2-parse-dot-query pn)))
10083 ((= tt js2-LB)
10084 (setq pn (js2-parse-element-get pn)))
10085 ((= tt js2-LP)
10086 (js2-unget-token)
10087 (if allow-call-syntax
10088 (setq pn (js2-parse-function-call pn))
10089 (setq continue nil)))
10090 ((= tt js2-TEMPLATE_HEAD)
10091 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10092 ((= tt js2-NO_SUBS_TEMPLATE)
10093 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10094 (t
10095 (js2-unget-token)
10096 (setq continue nil)))
10097 (if (>= js2-highlight-level 2)
10098 (js2-parse-highlight-member-expr-node pn)))
10099 pn))
10100
10101 (defun js2-parse-tagged-template (tag-node tpl-node)
10102 "Parse tagged template expression."
10103 (let* ((beg (js2-node-pos tag-node))
10104 (pn (make-js2-tagged-template-node :beg beg
10105 :len (- (js2-current-token-end) beg)
10106 :tag tag-node
10107 :template tpl-node)))
10108 (js2-node-add-children pn tag-node tpl-node)
10109 pn))
10110
10111 (defun js2-parse-dot-query (pn)
10112 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10113 Last token parsed must be `js2-DOTQUERY'."
10114 (let ((pos (js2-node-pos pn))
10115 op-pos expr end)
10116 (js2-must-have-xml)
10117 (js2-set-requires-activation)
10118 (setq op-pos (js2-current-token-beg)
10119 expr (js2-parse-expr)
10120 end (js2-node-end expr)
10121 pn (make-js2-xml-dot-query-node :left pn
10122 :pos pos
10123 :op-pos op-pos
10124 :right expr))
10125 (js2-node-add-children pn
10126 (js2-xml-dot-query-node-left pn)
10127 (js2-xml-dot-query-node-right pn))
10128 (if (js2-must-match js2-RP "msg.no.paren")
10129 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10130 end (js2-current-token-end)))
10131 (setf (js2-node-len pn) (- end pos))
10132 pn))
10133
10134 (defun js2-parse-element-get (pn)
10135 "Parse an element-get expression, e.g. foo[bar].
10136 Last token parsed must be `js2-RB'."
10137 (let ((lb (js2-current-token-beg))
10138 (pos (js2-node-pos pn))
10139 rb expr)
10140 (setq expr (js2-parse-expr))
10141 (if (js2-must-match js2-RB "msg.no.bracket.index")
10142 (setq rb (js2-current-token-beg)))
10143 (setq pn (make-js2-elem-get-node :target pn
10144 :pos pos
10145 :element expr
10146 :lb (js2-relpos lb pos)
10147 :rb (js2-relpos rb pos)
10148 :len (- (js2-current-token-end) pos)))
10149 (js2-node-add-children pn
10150 (js2-elem-get-node-target pn)
10151 (js2-elem-get-node-element pn))
10152 pn))
10153
10154 (defun js2-highlight-function-call (token)
10155 (when (eq (js2-token-type token) js2-NAME)
10156 (js2-record-face 'js2-function-call token)))
10157
10158 (defun js2-parse-function-call (pn)
10159 (js2-highlight-function-call (js2-current-token))
10160 (js2-get-token)
10161 (let (args
10162 (pos (js2-node-pos pn)))
10163 (setq pn (make-js2-call-node :pos pos
10164 :target pn
10165 :lp (- (js2-current-token-beg) pos)))
10166 (js2-node-add-children pn (js2-call-node-target pn))
10167 ;; Add the arguments to pn, if any are supplied.
10168 (setf args (nreverse (js2-parse-argument-list))
10169 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10170 (js2-call-node-args pn) args)
10171 (apply #'js2-node-add-children pn args)
10172 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10173 pn))
10174
10175 (defun js2-parse-property-access (tt pn)
10176 "Parse a property access, XML descendants access, or XML attr access."
10177 (let ((member-type-flags 0)
10178 (dot-pos (js2-current-token-beg))
10179 (dot-len (if (= tt js2-DOTDOT) 2 1))
10180 name
10181 ref ; right side of . or .. operator
10182 result)
10183 (when (= tt js2-DOTDOT)
10184 (js2-must-have-xml)
10185 (setq member-type-flags js2-descendants-flag))
10186 (if (not js2-compiler-xml-available)
10187 (progn
10188 (js2-must-match-prop-name "msg.no.name.after.dot")
10189 (setq name (js2-create-name-node t js2-GETPROP)
10190 result (make-js2-prop-get-node :left pn
10191 :pos (js2-current-token-beg)
10192 :right name
10193 :len (js2-current-token-len)))
10194 (js2-node-add-children result pn name)
10195 result)
10196 ;; otherwise look for XML operators
10197 (setf result (if (= tt js2-DOT)
10198 (make-js2-prop-get-node)
10199 (make-js2-infix-node :type js2-DOTDOT))
10200 (js2-node-pos result) (js2-node-pos pn)
10201 (js2-infix-node-op-pos result) dot-pos
10202 (js2-infix-node-left result) pn ; do this after setting position
10203 tt (js2-get-prop-name-token))
10204 (cond
10205 ;; handles: name, ns::name, ns::*, ns::[expr]
10206 ((= tt js2-NAME)
10207 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10208 ;; handles: *, *::name, *::*, *::[expr]
10209 ((= tt js2-MUL)
10210 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10211 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10212 ((= tt js2-XMLATTR)
10213 (setq result (js2-parse-attribute-access)))
10214 (t
10215 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10216 (if ref
10217 (setf (js2-node-len result) (- (js2-node-end ref)
10218 (js2-node-pos result))
10219 (js2-infix-node-right result) ref))
10220 (if (js2-infix-node-p result)
10221 (js2-node-add-children result
10222 (js2-infix-node-left result)
10223 (js2-infix-node-right result)))
10224 result)))
10225
10226 (defun js2-parse-attribute-access ()
10227 "Parse an E4X XML attribute expression.
10228 This includes expressions of the forms:
10229
10230 @attr @ns::attr @ns::*
10231 @* @*::attr @*::*
10232 @[expr] @*::[expr] @ns::[expr]
10233
10234 Called if we peeked an '@' token."
10235 (let ((tt (js2-get-prop-name-token))
10236 (at-pos (js2-current-token-beg)))
10237 (cond
10238 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10239 ((= tt js2-NAME)
10240 (js2-parse-property-name at-pos nil 0))
10241 ;; handles: @*, @*::name, @*::*, @*::[expr]
10242 ((= tt js2-MUL)
10243 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10244 ;; handles @[expr]
10245 ((= tt js2-LB)
10246 (js2-parse-xml-elem-ref at-pos))
10247 (t
10248 (js2-report-error "msg.no.name.after.xmlAttr")
10249 ;; Avoid cascaded errors that happen if we make an error node here.
10250 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10251
10252 (defun js2-parse-property-name (at-pos s member-type-flags)
10253 "Check if :: follows name in which case it becomes qualified name.
10254
10255 AT-POS is a natural number if we just read an '@' token, else nil.
10256 S is the name or string that was matched: an identifier, 'throw' or '*'.
10257 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10258
10259 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10260 operator, or the name is followed by ::. For a plain name, returns a
10261 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10262 (let ((pos (or at-pos (js2-current-token-beg)))
10263 colon-pos
10264 (name (js2-create-name-node t (js2-current-token-type) s))
10265 ns tt pn)
10266 (catch 'return
10267 (when (js2-match-token js2-COLONCOLON)
10268 (setq ns name
10269 colon-pos (js2-current-token-beg)
10270 tt (js2-get-prop-name-token))
10271 (cond
10272 ;; handles name::name
10273 ((= tt js2-NAME)
10274 (setq name (js2-create-name-node)))
10275 ;; handles name::*
10276 ((= tt js2-MUL)
10277 (setq name (js2-create-name-node nil nil "*")))
10278 ;; handles name::[expr]
10279 ((= tt js2-LB)
10280 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10281 (t
10282 (js2-report-error "msg.no.name.after.coloncolon"))))
10283 (if (and (null ns) (zerop member-type-flags))
10284 name
10285 (prog1
10286 (setq pn
10287 (make-js2-xml-prop-ref-node :pos pos
10288 :len (- (js2-node-end name) pos)
10289 :at-pos at-pos
10290 :colon-pos colon-pos
10291 :propname name))
10292 (js2-node-add-children pn name))))))
10293
10294 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10295 "Parse the [expr] portion of an xml element reference.
10296 For instance, @[expr], @*::[expr], or ns::[expr]."
10297 (let* ((lb (js2-current-token-beg))
10298 (pos (or at-pos lb))
10299 rb
10300 (expr (js2-parse-expr))
10301 (end (js2-node-end expr))
10302 pn)
10303 (if (js2-must-match js2-RB "msg.no.bracket.index")
10304 (setq rb (js2-current-token-beg)
10305 end (js2-current-token-end)))
10306 (prog1
10307 (setq pn
10308 (make-js2-xml-elem-ref-node :pos pos
10309 :len (- end pos)
10310 :namespace namespace
10311 :colon-pos colon-pos
10312 :at-pos at-pos
10313 :expr expr
10314 :lb (js2-relpos lb pos)
10315 :rb (js2-relpos rb pos)))
10316 (js2-node-add-children pn namespace expr))))
10317
10318 (defun js2-parse-destruct-primary-expr ()
10319 (let ((js2-is-in-destructuring t))
10320 (js2-parse-primary-expr)))
10321
10322 (defun js2-parse-primary-expr ()
10323 "Parse a literal (leaf) expression of some sort.
10324 Includes complex literals such as functions, object-literals,
10325 array-literals, array comprehensions and regular expressions."
10326 (let (tt node)
10327 (setq tt (js2-current-token-type))
10328 (cond
10329 ((= tt js2-CLASS)
10330 (js2-parse-class-expr))
10331 ((= tt js2-FUNCTION)
10332 (js2-parse-function-expr))
10333 ((js2-match-async-function)
10334 (js2-parse-function-expr t))
10335 ((= tt js2-LB)
10336 (js2-parse-array-comp-or-literal))
10337 ((= tt js2-LC)
10338 (js2-parse-object-literal))
10339 ((= tt js2-LET)
10340 (js2-parse-let (js2-current-token-beg)))
10341 ((= tt js2-LP)
10342 (js2-parse-paren-expr-or-generator-comp))
10343 ((= tt js2-XMLATTR)
10344 (js2-must-have-xml)
10345 (js2-parse-attribute-access))
10346 ((= tt js2-NAME)
10347 (js2-parse-name tt))
10348 ((= tt js2-NUMBER)
10349 (setq node (make-js2-number-node))
10350 (when (and js2-in-use-strict-directive
10351 (= (js2-number-node-num-base node) 8)
10352 (js2-number-node-legacy-octal-p node))
10353 (js2-report-error "msg.no.octal.strict"))
10354 node)
10355 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10356 (make-js2-string-node :type tt))
10357 ((= tt js2-TEMPLATE_HEAD)
10358 (js2-parse-template-literal))
10359 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10360 ;; Got / or /= which in this context means a regexp literal
10361 (let ((px-pos (js2-current-token-beg))
10362 (flags (js2-read-regexp tt))
10363 (end (js2-current-token-end)))
10364 (prog1
10365 (make-js2-regexp-node :pos px-pos
10366 :len (- end px-pos)
10367 :value (js2-current-token-string)
10368 :flags flags)
10369 (js2-set-face px-pos end 'font-lock-string-face 'record)
10370 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10371 ((or (= tt js2-NULL)
10372 (= tt js2-THIS)
10373 (= tt js2-SUPER)
10374 (= tt js2-FALSE)
10375 (= tt js2-TRUE))
10376 (make-js2-keyword-node :type tt))
10377 ((= tt js2-TRIPLEDOT)
10378 ;; Likewise, only valid in an arrow function with a rest param.
10379 (if (and (js2-match-token js2-NAME)
10380 (js2-match-token js2-RP)
10381 (eq (js2-peek-token) js2-ARROW))
10382 (progn
10383 (js2-unget-token) ; Put back the right paren.
10384 ;; See the previous case.
10385 (make-js2-keyword-node :type js2-NULL))
10386 (js2-report-error "msg.syntax")
10387 (make-js2-error-node)))
10388 ((= tt js2-RESERVED)
10389 (js2-report-error "msg.reserved.id")
10390 (make-js2-name-node))
10391 ((= tt js2-ERROR)
10392 ;; the scanner or one of its subroutines reported the error.
10393 (make-js2-error-node))
10394 ((= tt js2-EOF)
10395 (let* ((px-pos (point-at-bol))
10396 (len (- js2-ts-cursor px-pos)))
10397 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10398 (make-js2-error-node :pos (1- js2-ts-cursor)))
10399 (t
10400 (js2-report-error "msg.syntax")
10401 (make-js2-error-node)))))
10402
10403 (defun js2-parse-template-literal ()
10404 (let ((beg (js2-current-token-beg))
10405 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10406 (tt js2-TEMPLATE_HEAD))
10407 (while (eq tt js2-TEMPLATE_HEAD)
10408 (push (js2-parse-expr) kids)
10409 (js2-must-match js2-RC "msg.syntax")
10410 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10411 (push (make-js2-string-node :type tt) kids))
10412 (setq kids (nreverse kids))
10413 (let ((tpl (make-js2-template-node :beg beg
10414 :len (- (js2-current-token-end) beg)
10415 :kids kids)))
10416 (apply #'js2-node-add-children tpl kids)
10417 tpl)))
10418
10419 (defun js2-parse-name (_tt)
10420 (let ((name (js2-current-token-string))
10421 node)
10422 (setq node (if js2-compiler-xml-available
10423 (js2-parse-property-name nil name 0)
10424 (js2-create-name-node 'check-activation nil name)))
10425 (if js2-highlight-external-variables
10426 (js2-record-name-node node))
10427 node))
10428
10429 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10430 (js2-add-strict-warning
10431 msg nil
10432 ;; back up from comma to beginning of line or array/objlit
10433 (max (if elems
10434 (js2-node-pos (car elems))
10435 pos)
10436 (save-excursion
10437 (goto-char comma-pos)
10438 (back-to-indentation)
10439 (point)))
10440 comma-pos))
10441
10442 (defun js2-parse-array-comp-or-literal ()
10443 (let ((pos (js2-current-token-beg)))
10444 (if (and (>= js2-language-version 200)
10445 (js2-match-token js2-FOR))
10446 (js2-parse-array-comp pos)
10447 (js2-parse-array-literal pos))))
10448
10449 (defun js2-parse-array-literal (pos)
10450 (let ((after-lb-or-comma t)
10451 after-comma tt elems pn
10452 (continue t))
10453 (unless js2-is-in-destructuring
10454 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10455 (while continue
10456 (setq tt (js2-get-token))
10457 (cond
10458 ;; comma
10459 ((= tt js2-COMMA)
10460 (setq after-comma (js2-current-token-end))
10461 (if (not after-lb-or-comma)
10462 (setq after-lb-or-comma t)
10463 (push nil elems)))
10464 ;; end of array
10465 ((or (= tt js2-RB)
10466 (= tt js2-EOF)) ; prevent infinite loop
10467 (if (= tt js2-EOF)
10468 (js2-report-error "msg.no.bracket.arg" nil pos))
10469 (when (and after-comma (< js2-language-version 170))
10470 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10471 pos (remove nil elems) after-comma))
10472 (setq continue nil
10473 pn (make-js2-array-node :pos pos
10474 :len (- js2-ts-cursor pos)
10475 :elems (nreverse elems)))
10476 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10477 ;; destructuring binding
10478 (js2-is-in-destructuring
10479 (push (cond
10480 ((and (= tt js2-NAME)
10481 (= js2-ASSIGN (js2-peek-token)))
10482 ;; a=defaultValue
10483 (js2-parse-initialized-binding (js2-parse-name js2-NAME)))
10484 ((or (= tt js2-LC)
10485 (= tt js2-LB)
10486 (= tt js2-NAME))
10487 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10488 (js2-parse-destruct-primary-expr))
10489 ;; invalid pattern
10490 (t
10491 (js2-report-error "msg.bad.var")
10492 (make-js2-error-node)))
10493 elems)
10494 (setq after-lb-or-comma nil
10495 after-comma nil))
10496 ;; array comp
10497 ((and (>= js2-language-version 170)
10498 (= tt js2-FOR) ; check for array comprehension
10499 (not after-lb-or-comma) ; "for" can't follow a comma
10500 elems ; must have at least 1 element
10501 (not (cdr elems))) ; but no 2nd element
10502 (js2-unget-token)
10503 (setf continue nil
10504 pn (js2-parse-legacy-array-comp (car elems) pos)))
10505 ;; another element
10506 (t
10507 (unless after-lb-or-comma
10508 (js2-report-error "msg.no.bracket.arg"))
10509 (if (and (= tt js2-TRIPLEDOT)
10510 (>= js2-language-version 200))
10511 ;; spread operator
10512 (push (js2-make-unary tt 'js2-parse-assign-expr)
10513 elems)
10514 (js2-unget-token)
10515 (push (js2-parse-assign-expr) elems))
10516 (setq after-lb-or-comma nil
10517 after-comma nil))))
10518 (unless js2-is-in-destructuring
10519 (js2-pop-scope))
10520 pn))
10521
10522 (defun js2-parse-legacy-array-comp (expr pos)
10523 "Parse a legacy array comprehension (JavaScript 1.7).
10524 EXPR is the first expression after the opening left-bracket.
10525 POS is the beginning of the LB token preceding EXPR.
10526 We should have just parsed the 'for' keyword before calling this function."
10527 (let ((current-scope js2-current-scope)
10528 loops first filter result)
10529 (unwind-protect
10530 (progn
10531 (while (js2-match-token js2-FOR)
10532 (let ((loop (make-js2-comp-loop-node)))
10533 (js2-push-scope loop)
10534 (push loop loops)
10535 (js2-parse-comp-loop loop)))
10536 ;; First loop takes expr scope's parent.
10537 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10538 (js2-scope-parent-scope current-scope))
10539 ;; Set expr scope's parent to the last loop.
10540 (setf (js2-scope-parent-scope current-scope) (car loops))
10541 (if (/= (js2-get-token) js2-IF)
10542 (js2-unget-token)
10543 (setq filter (js2-parse-condition))))
10544 (dotimes (_ (1- (length loops)))
10545 (js2-pop-scope)))
10546 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10547 (setq result (make-js2-comp-node :pos pos
10548 :len (- js2-ts-cursor pos)
10549 :result expr
10550 :loops (nreverse loops)
10551 :filters (and filter (list (car filter)))
10552 :form 'LEGACY_ARRAY))
10553 ;; Set comp loop's parent to the last loop.
10554 ;; TODO: Get rid of the bogus expr scope.
10555 (setf (js2-scope-parent-scope result) first)
10556 (apply #'js2-node-add-children result expr (car filter)
10557 (js2-comp-node-loops result))
10558 result))
10559
10560 (defun js2-parse-array-comp (pos)
10561 "Parse an ES6 array comprehension.
10562 POS is the beginning of the LB token.
10563 We should have just parsed the 'for' keyword before calling this function."
10564 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10565 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10566 pn))
10567
10568 (defun js2-parse-generator-comp (pos)
10569 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10570 (js2-current-script-or-fn
10571 (make-js2-function-node :generator-type 'COMPREHENSION))
10572 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10573 (js2-must-match js2-RP "msg.no.paren" pos)
10574 pn))
10575
10576 (defun js2-parse-comprehension (pos form)
10577 (let (loops filters expr result last)
10578 (unwind-protect
10579 (progn
10580 (js2-unget-token)
10581 (while (js2-match-token js2-FOR)
10582 (let ((loop (make-js2-comp-loop-node)))
10583 (js2-push-scope loop)
10584 (push loop loops)
10585 (js2-parse-comp-loop loop)))
10586 (while (js2-match-token js2-IF)
10587 (push (car (js2-parse-condition)) filters))
10588 (setq expr (js2-parse-assign-expr))
10589 (setq last (car loops)))
10590 (dolist (_ loops)
10591 (js2-pop-scope)))
10592 (setq result (make-js2-comp-node :pos pos
10593 :len (- js2-ts-cursor pos)
10594 :result expr
10595 :loops (nreverse loops)
10596 :filters (nreverse filters)
10597 :form form))
10598 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10599 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10600 (setf (js2-scope-parent-scope result) last)
10601 result))
10602
10603 (defun js2-parse-comp-loop (pn &optional only-of-p)
10604 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10605 The current token should be the initial FOR.
10606 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10607 (let ((pos (js2-comp-loop-node-pos pn))
10608 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10609 (when (and (not only-of-p) (js2-match-token js2-NAME))
10610 (if (string= (js2-current-token-string) "each")
10611 (progn
10612 (setq foreach-p t
10613 each-pos (- (js2-current-token-beg) pos)) ; relative
10614 (js2-record-face 'font-lock-keyword-face))
10615 (js2-report-error "msg.no.paren.for")))
10616 (if (js2-must-match js2-LP "msg.no.paren.for")
10617 (setq lp (- (js2-current-token-beg) pos)))
10618 (setq tt (js2-peek-token))
10619 (cond
10620 ((or (= tt js2-LB)
10621 (= tt js2-LC))
10622 (js2-get-token)
10623 (setq iter (js2-parse-destruct-primary-expr))
10624 (js2-define-destruct-symbols iter js2-LET
10625 'font-lock-variable-name-face t))
10626 ((js2-match-token js2-NAME)
10627 (setq iter (js2-create-name-node)))
10628 (t
10629 (js2-report-error "msg.bad.var")))
10630 ;; Define as a let since we want the scope of the variable to
10631 ;; be restricted to the array comprehension
10632 (if (js2-name-node-p iter)
10633 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10634 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10635 (and (>= js2-language-version 200)
10636 (js2-match-contextual-kwd "of")
10637 (setq forof-p t)))
10638 (setq in-pos (- (js2-current-token-beg) pos))
10639 (js2-report-error "msg.in.after.for.name"))
10640 (setq obj (js2-parse-expr))
10641 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10642 (setq rp (- (js2-current-token-beg) pos)))
10643 (setf (js2-node-pos pn) pos
10644 (js2-node-len pn) (- js2-ts-cursor pos)
10645 (js2-comp-loop-node-iterator pn) iter
10646 (js2-comp-loop-node-object pn) obj
10647 (js2-comp-loop-node-in-pos pn) in-pos
10648 (js2-comp-loop-node-each-pos pn) each-pos
10649 (js2-comp-loop-node-foreach-p pn) foreach-p
10650 (js2-comp-loop-node-forof-p pn) forof-p
10651 (js2-comp-loop-node-lp pn) lp
10652 (js2-comp-loop-node-rp pn) rp)
10653 (js2-node-add-children pn iter obj)
10654 pn))
10655
10656 (defun js2-parse-class-stmt ()
10657 (let ((pos (js2-current-token-beg))
10658 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10659 (name (js2-create-name-node t)))
10660 (js2-set-face (js2-node-pos name) (js2-node-end name)
10661 'font-lock-function-name-face 'record)
10662 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10663 (js2-define-symbol js2-FUNCTION
10664 (js2-name-node-name name)
10665 node)
10666 node)))
10667
10668 (defun js2-parse-class-expr ()
10669 (let ((pos (js2-current-token-beg))
10670 name)
10671 (when (js2-match-token js2-NAME)
10672 (setq name (js2-create-name-node t)))
10673 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10674
10675 (defun js2-parse-class (pos form name)
10676 ;; class X [extends ...] {
10677 (let (pn elems extends)
10678 (if (js2-match-token js2-EXTENDS)
10679 (if (= (js2-peek-token) js2-LC)
10680 (js2-report-error "msg.missing.extends")
10681 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10682 (setq extends (js2-parse-assign-expr))
10683 (if (not extends)
10684 (js2-report-error "msg.bad.extends"))))
10685 (js2-must-match js2-LC "msg.no.brace.class")
10686 (setq elems (js2-parse-object-literal-elems t)
10687 pn (make-js2-class-node :pos pos
10688 :len (- js2-ts-cursor pos)
10689 :form form
10690 :name name
10691 :extends extends
10692 :elems elems))
10693 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10694 pn))
10695
10696 (defun js2-parse-object-literal ()
10697 (let* ((pos (js2-current-token-beg))
10698 (elems (js2-parse-object-literal-elems))
10699 (result (make-js2-object-node :pos pos
10700 :len (- js2-ts-cursor pos)
10701 :elems elems)))
10702 (apply #'js2-node-add-children result (js2-object-node-elems result))
10703 result))
10704
10705 (defun js2-property-key-string (property-node)
10706 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10707 `js2-method-node') as a string, or nil if it can't be
10708 represented as a string (e.g., the key is computed by an
10709 expression)."
10710 (let ((key (js2-infix-node-left property-node)))
10711 (when (js2-computed-prop-name-node-p key)
10712 (setq key (js2-computed-prop-name-node-expr key)))
10713 (cond
10714 ((js2-name-node-p key)
10715 (js2-name-node-name key))
10716 ((js2-string-node-p key)
10717 (js2-string-node-value key))
10718 ((js2-number-node-p key)
10719 (js2-number-node-value key)))))
10720
10721 (defun js2-parse-object-literal-elems (&optional class-p)
10722 (let ((pos (js2-current-token-beg))
10723 (static nil)
10724 (continue t)
10725 tt elems elem
10726 elem-key-string previous-elem-key-string
10727 after-comma previous-token)
10728 (while continue
10729 (setq tt (js2-get-prop-name-token)
10730 static nil
10731 elem nil
10732 previous-token nil)
10733 ;; Handle 'static' keyword only if we're in a class
10734 (when (and class-p (= js2-NAME tt)
10735 (string= "static" (js2-current-token-string)))
10736 (js2-record-face 'font-lock-keyword-face)
10737 (setq static t
10738 tt (js2-get-prop-name-token)))
10739 ;; Handle generator * before the property name for in-line functions
10740 (when (and (>= js2-language-version 200)
10741 (= js2-MUL tt))
10742 (setq previous-token (js2-current-token)
10743 tt (js2-get-prop-name-token)))
10744 ;; Handle getter, setter and async methods
10745 (let ((prop (js2-current-token-string)))
10746 (when (and (>= js2-language-version 200)
10747 (= js2-NAME tt)
10748 (member prop '("get" "set" "async"))
10749 (member (js2-peek-token)
10750 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10751 (setq previous-token (js2-current-token)
10752 tt (js2-get-prop-name-token))))
10753 (cond
10754 ;; Found a property (of any sort)
10755 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10756 (setq after-comma nil
10757 elem (js2-parse-named-prop tt pos previous-token))
10758 (if (and (null elem)
10759 (not js2-recover-from-parse-errors))
10760 (setq continue nil)))
10761 ;; Break out of loop, and handle trailing commas.
10762 ((or (= tt js2-RC)
10763 (= tt js2-EOF))
10764 (js2-unget-token)
10765 (setq continue nil)
10766 (if after-comma
10767 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10768 pos elems after-comma)))
10769 ;; Skip semicolons in a class body
10770 ((and class-p
10771 (= tt js2-SEMI))
10772 nil)
10773 (t
10774 (js2-report-error "msg.bad.prop")
10775 (unless js2-recover-from-parse-errors
10776 (setq continue nil)))) ; end switch
10777 ;; Handle static for classes' codegen.
10778 (if static
10779 (if elem (js2-node-set-prop elem 'STATIC t)
10780 (js2-report-error "msg.unexpected.static")))
10781 ;; Handle commas, depending on class-p.
10782 (let ((tok (js2-get-prop-name-token)))
10783 (if (eq tok js2-COMMA)
10784 (if class-p
10785 (js2-report-error "msg.class.unexpected.comma")
10786 (setq after-comma (js2-current-token-end)))
10787 (js2-unget-token)
10788 (unless class-p (setq continue nil))))
10789 (when elem
10790 (when (and js2-in-use-strict-directive
10791 (setq elem-key-string (js2-property-key-string elem))
10792 (cl-some
10793 (lambda (previous-elem)
10794 (and (setq previous-elem-key-string
10795 (js2-property-key-string previous-elem))
10796 ;; Check if the property is a duplicate.
10797 (string= previous-elem-key-string elem-key-string)
10798 ;; But make an exception for getter / setter pairs.
10799 (not (and (js2-method-node-p elem)
10800 (js2-method-node-p previous-elem)
10801 (let ((type (js2-node-get-prop (js2-method-node-right elem) 'METHOD_TYPE))
10802 (previous-type (js2-node-get-prop (js2-method-node-right previous-elem) 'METHOD_TYPE)))
10803 (and (member type '(GET SET))
10804 (member previous-type '(GET SET))
10805 (not (eq type previous-type))))))))
10806 elems))
10807 (js2-report-error "msg.dup.obj.lit.prop.strict"
10808 elem-key-string
10809 (js2-node-abs-pos (js2-infix-node-left elem))
10810 (js2-node-len (js2-infix-node-left elem))))
10811 ;; Append any parsed element.
10812 (push elem elems))) ; end loop
10813 (js2-must-match js2-RC "msg.no.brace.prop")
10814 (nreverse elems)))
10815
10816 (defun js2-parse-named-prop (tt pos previous-token)
10817 "Parse a name, string, or getter/setter object property.
10818 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10819 (let ((key (js2-parse-prop-name tt))
10820 (prop (and previous-token (js2-token-string previous-token)))
10821 (property-type (when previous-token
10822 (if (= (js2-token-type previous-token) js2-MUL)
10823 "*"
10824 (js2-token-string previous-token)))))
10825 (when (member prop '("get" "set" "async"))
10826 (js2-set-face (js2-token-beg previous-token)
10827 (js2-token-end previous-token)
10828 'font-lock-keyword-face 'record)) ; get/set/async
10829 (cond
10830 ;; method definition: {f() {...}}
10831 ((and (= (js2-peek-token) js2-LP)
10832 (>= js2-language-version 200))
10833 (when (js2-name-node-p key) ; highlight function name properties
10834 (js2-record-face 'font-lock-function-name-face))
10835 (js2-parse-method-prop pos key property-type))
10836 ;; binding element with initializer
10837 ((and (= (js2-peek-token) js2-ASSIGN)
10838 (>= js2-language-version 200))
10839 (if (not js2-is-in-destructuring)
10840 (js2-report-error "msg.init.no.destruct"))
10841 (js2-parse-initialized-binding key))
10842 ;; regular prop
10843 (t
10844 (let ((beg (js2-current-token-beg))
10845 (end (js2-current-token-end))
10846 (expr (js2-parse-plain-property key)))
10847 (when (and (= tt js2-NAME)
10848 (not js2-is-in-destructuring)
10849 js2-highlight-external-variables
10850 (js2-node-get-prop expr 'SHORTHAND))
10851 (js2-record-name-node key))
10852 (js2-set-face beg end
10853 (if (js2-function-node-p
10854 (js2-object-prop-node-right expr))
10855 'font-lock-function-name-face
10856 'js2-object-property)
10857 'record)
10858 expr)))))
10859
10860 (defun js2-parse-initialized-binding (name)
10861 "Parse a `SingleNameBinding' with initializer.
10862
10863 `name' is the `BindingIdentifier'."
10864 (when (js2-match-token js2-ASSIGN)
10865 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10866
10867 (defun js2-parse-prop-name (tt)
10868 (cond
10869 ;; Literal string keys: {'foo': 'bar'}
10870 ((= tt js2-STRING)
10871 (make-js2-string-node))
10872 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10873 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10874 ((and (= tt js2-LB)
10875 (>= js2-language-version 200))
10876 (make-js2-computed-prop-name-node
10877 :expr (prog1 (js2-parse-assign-expr)
10878 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10879 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10880 ((= tt js2-NUMBER)
10881 (make-js2-number-node))
10882 ;; Unquoted names: {foo: 12}
10883 ((= tt js2-NAME)
10884 (js2-create-name-node))
10885 ;; Anything else is an error
10886 (t (js2-report-error "msg.bad.prop"))))
10887
10888 (defun js2-parse-plain-property (prop)
10889 "Parse a non-getter/setter property in an object literal.
10890 PROP is the node representing the property: a number, name,
10891 string or expression."
10892 (let* ((tt (js2-get-token))
10893 (pos (js2-node-pos prop))
10894 colon expr result)
10895 (cond
10896 ;; Abbreviated property, as in {foo, bar}
10897 ((and (>= js2-language-version 200)
10898 (or (= tt js2-COMMA)
10899 (= tt js2-RC))
10900 (not (js2-number-node-p prop)))
10901 (js2-unget-token)
10902 (setq result (make-js2-object-prop-node
10903 :pos pos
10904 :left prop
10905 :right prop
10906 :op-pos (js2-current-token-len)))
10907 (js2-node-add-children result prop)
10908 (js2-node-set-prop result 'SHORTHAND t)
10909 result)
10910 ;; Normal property
10911 (t
10912 (if (= tt js2-COLON)
10913 (setq colon (- (js2-current-token-beg) pos)
10914 expr (js2-parse-assign-expr))
10915 (js2-report-error "msg.no.colon.prop")
10916 (setq expr (make-js2-error-node)))
10917 (setq result (make-js2-object-prop-node
10918 :pos pos
10919 ;; don't include last consumed token in length
10920 :len (- (+ (js2-node-pos expr)
10921 (js2-node-len expr))
10922 pos)
10923 :left prop
10924 :right expr
10925 :op-pos colon))
10926 (js2-node-add-children result prop expr)
10927 result))))
10928
10929 (defun js2-parse-method-prop (pos prop type-string)
10930 "Parse method property in an object literal or a class body.
10931 JavaScript syntax is:
10932
10933 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...},
10934 async foo(...) {...} }
10935
10936 and expression closure style is also supported
10937
10938 { get foo() x, set foo(x) _x = x }
10939
10940 POS is the start position of the `get' or `set' keyword.
10941 PROP is the `js2-name-node' representing the property name.
10942 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10943 (let* ((type (or (cdr (assoc type-string '(("get" . GET)
10944 ("set" . SET)
10945 ("async" . ASYNC))))
10946 'FUNCTION))
10947 result end
10948 (fn (js2-parse-function-expr (eq type 'ASYNC))))
10949 ;; it has to be an anonymous function, as we already parsed the name
10950 (if (/= (js2-node-type fn) js2-FUNCTION)
10951 (js2-report-error "msg.bad.prop")
10952 (if (cl-plusp (length (js2-function-name fn)))
10953 (js2-report-error "msg.bad.prop")))
10954 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10955 (when (string= type-string "*")
10956 (setf (js2-function-node-generator-type fn) 'STAR))
10957 (setq end (js2-node-end fn)
10958 result (make-js2-method-node :pos pos
10959 :len (- end pos)
10960 :left prop
10961 :right fn))
10962 (js2-node-add-children result prop fn)
10963 result))
10964
10965 (defun js2-create-name-node (&optional check-activation-p token string)
10966 "Create a name node using the current token and, optionally, STRING.
10967 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10968 (let* ((beg (js2-current-token-beg))
10969 (tt (js2-current-token-type))
10970 (s (or string
10971 (if (= js2-NAME tt)
10972 (js2-current-token-string)
10973 (js2-tt-name tt))))
10974 name)
10975 (setq name (make-js2-name-node :pos beg
10976 :name s
10977 :len (length s)))
10978 (if check-activation-p
10979 (js2-check-activation-name s (or token js2-NAME)))
10980 name))
10981
10982 ;;; Use AST to extract semantic information
10983
10984 (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
10985 "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
10986 (let ((idx 0) elems (rlt hardcoded-array-index))
10987 (setq elems (js2-array-node-elems array-node))
10988 (if (and elem (not hardcoded-array-index))
10989 (setq rlt (catch 'nth-elt
10990 (dolist (x elems)
10991 ;; We know the ELEM does belong to ARRAY-NODE,
10992 (if (eq elem x) (throw 'nth-elt idx))
10993 (setq idx (1+ idx)))
10994 0)))
10995 (format "[%s]" rlt)))
10996
10997 (defun js2-print-json-path (&optional hardcoded-array-index)
10998 "Print the path to the JSON value under point, and save it in the kill ring.
10999 If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
11000 (interactive "P")
11001 (let (previous-node current-node
11002 key-name
11003 rlt)
11004
11005 ;; The `js2-node-at-point' starts scanning from AST root node.
11006 ;; So there is no way to optimize it.
11007 (setq current-node (js2-node-at-point))
11008
11009 (while (not (js2-ast-root-p current-node))
11010 (cond
11011 ;; JSON property node
11012 ((js2-object-prop-node-p current-node)
11013 (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
11014 (if rlt (setq rlt (concat "." key-name rlt))
11015 (setq rlt (concat "." key-name))))
11016
11017 ;; Array node
11018 ((or (js2-array-node-p current-node))
11019 (setq rlt (concat (js2-get-element-index-from-array-node previous-node
11020 current-node
11021 hardcoded-array-index)
11022 rlt)))
11023
11024 ;; Other nodes are ignored
11025 (t))
11026
11027 ;; current node is archived
11028 (setq previous-node current-node)
11029 ;; Get parent node and continue the loop
11030 (setq current-node (js2-node-parent current-node)))
11031
11032 (cond
11033 (rlt
11034 ;; Clean the final result
11035 (setq rlt (replace-regexp-in-string "^\\." "" rlt))
11036 (kill-new rlt)
11037 (message "%s => kill-ring" rlt))
11038 (t
11039 (message "No JSON path found!")))
11040
11041 rlt))
11042
11043 ;;; Indentation support (bouncing)
11044
11045 ;; In recent-enough Emacs, we reuse the indentation code from
11046 ;; `js-mode'. To continue support for the older versions, some code
11047 ;; that was here previously was moved to `js2-old-indent.el'.
11048
11049 ;; Whichever indenter is used, it's often "wrong", however, and needs
11050 ;; to be overridden. The right long-term solution is probably to
11051 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
11052 ;; of coding. Even when a parse tree from `js2-parse' is present,
11053 ;; which is not true at the moment the user is typing, computing
11054 ;; indentation is still thousands of lines of code to handle every
11055 ;; possible syntactic edge case.
11056
11057 ;; In the meantime, the compromise solution is that we offer a "bounce
11058 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
11059 ;; current line indent among various likely guess points. This approach
11060 ;; is far from perfect, but should at least make it slightly easier to
11061 ;; move the line towards its desired indentation when manually
11062 ;; overriding Karl's heuristic nesting guesser.
11063
11064 (defun js2-backward-sws ()
11065 "Move backward through whitespace and comments."
11066 (interactive)
11067 (while (forward-comment -1)))
11068
11069 (defun js2-forward-sws ()
11070 "Move forward through whitespace and comments."
11071 (interactive)
11072 (while (forward-comment 1)))
11073
11074 (defun js2-arglist-close ()
11075 "Return non-nil if we're on a line beginning with a close-paren/brace."
11076 (save-excursion
11077 (goto-char (point-at-bol))
11078 (js2-forward-sws)
11079 (looking-at "[])}]")))
11080
11081 (defun js2-indent-looks-like-label-p ()
11082 (goto-char (point-at-bol))
11083 (js2-forward-sws)
11084 (looking-at (concat js2-mode-identifier-re ":")))
11085
11086 (defun js2-indent-in-objlit-p (parse-status)
11087 "Return non-nil if this looks like an object-literal entry."
11088 (let ((start (nth 1 parse-status)))
11089 (and
11090 start
11091 (save-excursion
11092 (and (zerop (forward-line -1))
11093 (not (< (point) start)) ; crossed a {} boundary
11094 (js2-indent-looks-like-label-p)))
11095 (save-excursion
11096 (js2-indent-looks-like-label-p)))))
11097
11098 ;; If prev line looks like foobar({ then we're passing an object
11099 ;; literal to a function call, and people pretty much always want to
11100 ;; de-dent back to the previous line, so move the 'basic-offset'
11101 ;; position to the front.
11102 (defun js2-indent-objlit-arg-p (parse-status)
11103 (save-excursion
11104 (back-to-indentation)
11105 (js2-backward-sws)
11106 (and (eq (1- (point)) (nth 1 parse-status))
11107 (eq (char-before) ?{)
11108 (progn
11109 (forward-char -1)
11110 (skip-chars-backward " \t")
11111 (eq (char-before) ?\()))))
11112
11113 (defun js2-indent-case-block-p ()
11114 (save-excursion
11115 (back-to-indentation)
11116 (js2-backward-sws)
11117 (goto-char (point-at-bol))
11118 (skip-chars-forward " \t")
11119 (looking-at "case\\s-.+:")))
11120
11121 (defun js2-bounce-indent (normal-col parse-status &optional backward)
11122 "Cycle among alternate computed indentation positions.
11123 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11124 of the buffer to the current point. NORMAL-COL is the indentation
11125 column computed by the heuristic guesser based on current paren,
11126 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11127 in reverse."
11128 (let ((cur-indent (current-indentation))
11129 (old-buffer-undo-list buffer-undo-list)
11130 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11131 (current-line (save-excursion
11132 (forward-line 0) ; move to bol
11133 (1+ (count-lines (point-min) (point)))))
11134 positions pos main-pos anchor arglist-cont same-indent
11135 basic-offset computed-pos)
11136 ;; temporarily don't record undo info, if user requested this
11137 (when js2-mode-indent-inhibit-undo
11138 (setq buffer-undo-list t))
11139 (unwind-protect
11140 (progn
11141 ;; First likely point: indent from beginning of previous code line
11142 (push (setq basic-offset
11143 (+ (save-excursion
11144 (back-to-indentation)
11145 (js2-backward-sws)
11146 (back-to-indentation)
11147 (current-column))
11148 js2-basic-offset))
11149 positions)
11150
11151 ;; (First + epsilon) likely point: indent 2x from beginning of
11152 ;; previous code line. Google does it this way.
11153 (push (setq basic-offset
11154 (+ (save-excursion
11155 (back-to-indentation)
11156 (js2-backward-sws)
11157 (back-to-indentation)
11158 (current-column))
11159 (* 2 js2-basic-offset)))
11160 positions)
11161
11162 ;; Second likely point: indent from assign-expr RHS. This
11163 ;; is just a crude guess based on finding " = " on the previous
11164 ;; line containing actual code.
11165 (setq pos (save-excursion
11166 (forward-line -1)
11167 (goto-char (point-at-bol))
11168 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11169 (point-at-eol) t)
11170 (goto-char (match-end 1))
11171 (skip-chars-forward " \t\r\n")
11172 (current-column))))
11173 (when pos
11174 (cl-incf pos js2-basic-offset)
11175 (push pos positions))
11176
11177 ;; Third likely point: same indent as previous line of code.
11178 ;; Make it the first likely point if we're not on an
11179 ;; arglist-close line and previous line ends in a comma, or
11180 ;; both this line and prev line look like object-literal
11181 ;; elements.
11182 (setq pos (save-excursion
11183 (goto-char (point-at-bol))
11184 (js2-backward-sws)
11185 (back-to-indentation)
11186 (prog1
11187 (current-column)
11188 ;; while we're here, look for trailing comma
11189 (if (save-excursion
11190 (goto-char (point-at-eol))
11191 (js2-backward-sws)
11192 (eq (char-before) ?,))
11193 (setq arglist-cont (1- (point)))))))
11194 (when pos
11195 (if (and (or arglist-cont
11196 (js2-indent-in-objlit-p parse-status))
11197 (not (js2-arglist-close)))
11198 (setq same-indent pos))
11199 (push pos positions))
11200
11201 ;; Fourth likely point: first preceding code with less indentation.
11202 ;; than the immediately preceding code line.
11203 (setq pos (save-excursion
11204 (back-to-indentation)
11205 (js2-backward-sws)
11206 (back-to-indentation)
11207 (setq anchor (current-column))
11208 (while (and (zerop (forward-line -1))
11209 (>= (progn
11210 (back-to-indentation)
11211 (current-column))
11212 anchor)))
11213 (setq pos (current-column))))
11214 (push pos positions)
11215
11216 ;; nesting-heuristic position, main by default
11217 (push (setq main-pos normal-col) positions)
11218
11219 ;; delete duplicates and sort positions list
11220 (setq positions (sort (delete-dups positions) '<))
11221
11222 ;; comma-list continuation lines: prev line indent takes precedence
11223 (if same-indent
11224 (setq main-pos same-indent))
11225
11226 ;; common special cases where we want to indent in from previous line
11227 (if (or (js2-indent-case-block-p)
11228 (js2-indent-objlit-arg-p parse-status))
11229 (setq main-pos basic-offset))
11230
11231 ;; if bouncing backward, reverse positions list
11232 (if backward
11233 (setq positions (reverse positions)))
11234
11235 ;; record whether we're already sitting on one of the alternatives
11236 (setq pos (member cur-indent positions))
11237
11238 (cond
11239 ;; case 0: we're one one of the alternatives and this is the
11240 ;; first time they've pressed TAB on this line (best-guess).
11241 ((and js2-mode-indent-ignore-first-tab
11242 pos
11243 ;; first time pressing TAB on this line?
11244 (not (eq js2-mode-last-indented-line current-line)))
11245 ;; do nothing
11246 (setq computed-pos nil))
11247 ;; case 1: only one computed position => use it
11248 ((null (cdr positions))
11249 (setq computed-pos 0))
11250 ;; case 2: not on any of the computed spots => use main spot
11251 ((not pos)
11252 (setq computed-pos (js2-position main-pos positions)))
11253 ;; case 3: on last position: cycle to first position
11254 ((null (cdr pos))
11255 (setq computed-pos 0))
11256 ;; case 4: on intermediate position: cycle to next position
11257 (t
11258 (setq computed-pos (js2-position (cl-second pos) positions))))
11259
11260 ;; see if any hooks want to indent; otherwise we do it
11261 (cl-loop with result = nil
11262 for hook in js2-indent-hook
11263 while (null result)
11264 do
11265 (setq result (funcall hook positions computed-pos))
11266 finally do
11267 (unless (or result (null computed-pos))
11268 (indent-line-to (nth computed-pos positions)))))
11269
11270 ;; finally
11271 (if js2-mode-indent-inhibit-undo
11272 (setq buffer-undo-list old-buffer-undo-list))
11273 ;; see commentary for `js2-mode-last-indented-line'
11274 (setq js2-mode-last-indented-line current-line))))
11275
11276 (defun js2-1-line-comment-continuation-p ()
11277 "Return t if we're in a 1-line comment continuation.
11278 If so, we don't ever want to use bounce-indent."
11279 (save-excursion
11280 (and (progn
11281 (forward-line 0)
11282 (looking-at "\\s-*//"))
11283 (progn
11284 (forward-line -1)
11285 (forward-line 0)
11286 (when (looking-at "\\s-*$")
11287 (js2-backward-sws)
11288 (forward-line 0))
11289 (looking-at "\\s-*//")))))
11290
11291 (defun js2-indent-bounce (&optional backward)
11292 "Indent the current line, bouncing between several positions."
11293 (interactive)
11294 (let (parse-status offset indent-col
11295 ;; Don't whine about errors/warnings when we're indenting.
11296 ;; This has to be set before calling parse-partial-sexp below.
11297 (inhibit-point-motion-hooks t))
11298 (setq parse-status (save-excursion
11299 (syntax-ppss (point-at-bol)))
11300 offset (- (point) (save-excursion
11301 (back-to-indentation)
11302 (point))))
11303 ;; Don't touch multiline strings.
11304 (unless (nth 3 parse-status)
11305 (setq indent-col (js2-proper-indentation parse-status))
11306 (cond
11307 ;; It doesn't work well on first line of buffer.
11308 ((and (not (nth 4 parse-status))
11309 (not (js2-same-line (point-min)))
11310 (not (js2-1-line-comment-continuation-p)))
11311 (js2-bounce-indent indent-col parse-status backward))
11312 ;; just indent to the guesser's likely spot
11313 (t (indent-line-to indent-col)))
11314 (when (cl-plusp offset)
11315 (forward-char offset)))))
11316
11317 (defun js2-indent-bounce-backward ()
11318 "Indent the current line, bouncing between positions in reverse."
11319 (interactive)
11320 (js2-indent-bounce t))
11321
11322 (defun js2-indent-region (start end)
11323 "Indent the region, but don't use bounce indenting."
11324 (let ((js2-bounce-indent-p nil)
11325 (indent-region-function nil)
11326 (after-change-functions (remq 'js2-mode-edit
11327 after-change-functions)))
11328 (indent-region start end nil) ; nil for byte-compiler
11329 (js2-mode-edit start end (- end start))))
11330
11331 (defvar js2-minor-mode-map
11332 (let ((map (make-sparse-keymap)))
11333 (define-key map (kbd "C-c C-`") #'js2-next-error)
11334 (define-key map [mouse-1] #'js2-mode-show-node)
11335 map)
11336 "Keymap used when `js2-minor-mode' is active.")
11337
11338 ;;;###autoload
11339 (define-minor-mode js2-minor-mode
11340 "Minor mode for running js2 as a background linter.
11341 This allows you to use a different major mode for JavaScript editing,
11342 such as `js-mode', while retaining the asynchronous error/warning
11343 highlighting features of `js2-mode'."
11344 :group 'js2-mode
11345 :lighter " js-lint"
11346 (if (derived-mode-p 'js2-mode)
11347 (setq js2-minor-mode nil)
11348 (if js2-minor-mode
11349 (js2-minor-mode-enter)
11350 (js2-minor-mode-exit))))
11351
11352 (defun js2-minor-mode-enter ()
11353 "Initialization for `js2-minor-mode'."
11354 (set (make-local-variable 'max-lisp-eval-depth)
11355 (max max-lisp-eval-depth 3000))
11356 (setq next-error-function #'js2-next-error)
11357 (js2-set-default-externs)
11358 ;; Experiment: make reparse-delay longer for longer files.
11359 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11360 (setq js2-idle-timer-delay
11361 (* js2-idle-timer-delay
11362 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11363 (setq js2-mode-buffer-dirty-p t
11364 js2-mode-parsing nil)
11365 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11366 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11367 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11368 (when js2-include-jslint-globals
11369 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11370 (run-hooks 'js2-init-hook)
11371 (js2-reparse))
11372
11373 (defun js2-minor-mode-exit ()
11374 "Turn off `js2-minor-mode'."
11375 (setq next-error-function nil)
11376 (remove-hook 'after-change-functions #'js2-mode-edit t)
11377 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11378 (when js2-mode-node-overlay
11379 (delete-overlay js2-mode-node-overlay)
11380 (setq js2-mode-node-overlay nil))
11381 (js2-remove-overlays)
11382 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11383 (setq js2-mode-ast nil))
11384
11385 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11386 (make-variable-buffer-local 'js2-source-buffer)
11387
11388 (cl-defun js2-display-error-list ()
11389 "Display a navigable buffer listing parse errors/warnings."
11390 (interactive)
11391 (unless (js2-have-errors-p)
11392 (message "No errors")
11393 (cl-return-from js2-display-error-list))
11394 (cl-labels ((annotate-list
11395 (lst type)
11396 "Add diagnostic TYPE and line number to errs list"
11397 (mapcar (lambda (err)
11398 (list err type (line-number-at-pos (nth 1 err))))
11399 lst)))
11400 (let* ((srcbuf (current-buffer))
11401 (errbuf (get-buffer-create "*js-lint*"))
11402 (errors (annotate-list
11403 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11404 'js2-error)) ; must be a valid face name
11405 (warnings (annotate-list
11406 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11407 'js2-warning)) ; must be a valid face name
11408 (all-errs (sort (append errors warnings)
11409 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11410 (with-current-buffer errbuf
11411 (let ((inhibit-read-only t))
11412 (erase-buffer)
11413 (dolist (err all-errs)
11414 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11415 (insert-text-button
11416 (format "line %d: %s" line (js2-get-msg msg-key))
11417 'face type
11418 'follow-link "\C-m"
11419 'action 'js2-error-buffer-jump
11420 'js2-msg (js2-get-msg msg-key)
11421 'js2-pos beg)
11422 (insert "\n"))))
11423 (js2-error-buffer-mode)
11424 (setq js2-source-buffer srcbuf)
11425 (pop-to-buffer errbuf)
11426 (goto-char (point-min))
11427 (unless (eobp)
11428 (js2-error-buffer-view))))))
11429
11430 (defvar js2-error-buffer-mode-map
11431 (let ((map (make-sparse-keymap)))
11432 (define-key map "n" #'js2-error-buffer-next)
11433 (define-key map "p" #'js2-error-buffer-prev)
11434 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11435 (define-key map "o" #'js2-error-buffer-view)
11436 (define-key map "q" #'js2-error-buffer-quit)
11437 map)
11438 "Keymap used for js2 diagnostics buffers.")
11439
11440 (defun js2-error-buffer-mode ()
11441 "Major mode for js2 diagnostics buffers.
11442 Selecting an error will jump it to the corresponding source-buffer error.
11443 \\{js2-error-buffer-mode-map}"
11444 (interactive)
11445 (setq major-mode 'js2-error-buffer-mode
11446 mode-name "JS Lint Diagnostics")
11447 (use-local-map js2-error-buffer-mode-map)
11448 (setq truncate-lines t)
11449 (set-buffer-modified-p nil)
11450 (setq buffer-read-only t)
11451 (run-hooks 'js2-error-buffer-mode-hook))
11452
11453 (defun js2-error-buffer-next ()
11454 "Move to next error and view it."
11455 (interactive)
11456 (when (zerop (forward-line 1))
11457 (js2-error-buffer-view)))
11458
11459 (defun js2-error-buffer-prev ()
11460 "Move to previous error and view it."
11461 (interactive)
11462 (when (zerop (forward-line -1))
11463 (js2-error-buffer-view)))
11464
11465 (defun js2-error-buffer-quit ()
11466 "Kill the current buffer."
11467 (interactive)
11468 (kill-buffer))
11469
11470 (defun js2-error-buffer-jump (&rest ignored)
11471 "Jump cursor to current error in source buffer."
11472 (interactive)
11473 (when (js2-error-buffer-view)
11474 (pop-to-buffer js2-source-buffer)))
11475
11476 (defun js2-error-buffer-view ()
11477 "Scroll source buffer to show error at current line."
11478 (interactive)
11479 (cond
11480 ((not (eq major-mode 'js2-error-buffer-mode))
11481 (message "Not in a js2 errors buffer"))
11482 ((not (buffer-live-p js2-source-buffer))
11483 (message "Source buffer has been killed"))
11484 ((not (wholenump (get-text-property (point) 'js2-pos)))
11485 (message "There does not seem to be an error here"))
11486 (t
11487 (let ((pos (get-text-property (point) 'js2-pos))
11488 (msg (get-text-property (point) 'js2-msg)))
11489 (save-selected-window
11490 (pop-to-buffer js2-source-buffer)
11491 (goto-char pos)
11492 (message msg))))))
11493
11494 ;;;###autoload
11495 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11496 "Major mode for editing JavaScript code."
11497 (set (make-local-variable 'max-lisp-eval-depth)
11498 (max max-lisp-eval-depth 3000))
11499 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11500 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11501 (set (make-local-variable 'syntax-propertize-function) nil)
11502 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11503 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11504 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11505 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11506 ;; for characters inside regexp literals.
11507 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11508 ;; this is necessary to make `show-paren-function' work properly
11509 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11510 ;; needed for M-x rgrep, among other things
11511 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11512
11513 (setq font-lock-defaults '(nil t))
11514
11515 ;; Experiment: make reparse-delay longer for longer files.
11516 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11517 (setq js2-idle-timer-delay
11518 (* js2-idle-timer-delay
11519 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11520
11521 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11522 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11523 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11524 (setq next-error-function #'js2-next-error)
11525 (imenu-add-to-menubar (concat "IM-" mode-name))
11526 (add-to-invisibility-spec '(js2-outline . t))
11527 (set (make-local-variable 'line-move-ignore-invisible) t)
11528 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11529 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11530
11531 (setq js2-mode-functions-hidden nil
11532 js2-mode-comments-hidden nil
11533 js2-mode-buffer-dirty-p t
11534 js2-mode-parsing nil)
11535
11536 (js2-set-default-externs)
11537
11538 (when js2-include-jslint-globals
11539 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11540
11541 (run-hooks 'js2-init-hook)
11542
11543 (js2-reparse))
11544
11545 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11546 ;; a bit more complicated and it doesn't net us much yet.
11547 ;;;###autoload
11548 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11549 "Major mode for editing JSX code.
11550
11551 To customize the indentation for this mode, set the SGML offset
11552 variables (`sgml-basic-offset' et al) locally, like so:
11553
11554 (defun set-jsx-indentation ()
11555 (setq-local sgml-basic-offset js2-basic-offset))
11556 (add-hook 'js2-jsx-mode-hook #'set-jsx-indentation)"
11557 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11558
11559 (defun js2-mode-exit ()
11560 "Exit `js2-mode' and clean up."
11561 (interactive)
11562 (when js2-mode-node-overlay
11563 (delete-overlay js2-mode-node-overlay)
11564 (setq js2-mode-node-overlay nil))
11565 (js2-remove-overlays)
11566 (setq js2-mode-ast nil)
11567 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11568 (remove-from-invisibility-spec '(js2-outline . t))
11569 (js2-mode-show-all)
11570 (with-silent-modifications
11571 (js2-clear-face (point-min) (point-max))))
11572
11573 (defun js2-mode-reset-timer ()
11574 "Cancel any existing parse timer and schedule a new one."
11575 (if js2-mode-parse-timer
11576 (cancel-timer js2-mode-parse-timer))
11577 (setq js2-mode-parsing nil)
11578 (let ((timer (timer-create)))
11579 (setq js2-mode-parse-timer timer)
11580 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11581 (timer-set-idle-time timer js2-idle-timer-delay)
11582 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11583 (timer-activate-when-idle timer nil)))
11584
11585 (defun js2-mode-idle-reparse (buffer)
11586 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11587 it to be reparsed when the buffer is selected."
11588 (cond ((eq buffer (current-buffer))
11589 (js2-reparse))
11590 ((buffer-live-p buffer)
11591 ;; reparse when the buffer is selected again
11592 (with-current-buffer buffer
11593 (add-hook 'window-configuration-change-hook
11594 #'js2-mode-idle-reparse-inner
11595 nil t)))))
11596
11597 (defun js2-mode-idle-reparse-inner ()
11598 (remove-hook 'window-configuration-change-hook
11599 #'js2-mode-idle-reparse-inner
11600 t)
11601 (js2-reparse))
11602
11603 (defun js2-mode-edit (_beg _end _len)
11604 "Schedule a new parse after buffer is edited.
11605 Buffer edit spans from BEG to END and is of length LEN."
11606 (setq js2-mode-buffer-dirty-p t)
11607 (js2-mode-hide-overlay)
11608 (js2-mode-reset-timer))
11609
11610 (defun js2-minor-mode-edit (_beg _end _len)
11611 "Callback for buffer edits in `js2-mode'.
11612 Schedules a new parse after buffer is edited.
11613 Buffer edit spans from BEG to END and is of length LEN."
11614 (setq js2-mode-buffer-dirty-p t)
11615 (js2-mode-hide-overlay)
11616 (js2-mode-reset-timer))
11617
11618 (defun js2-reparse (&optional force)
11619 "Re-parse current buffer after user finishes some data entry.
11620 If we get any user input while parsing, including cursor motion,
11621 we discard the parse and reschedule it. If FORCE is nil, then the
11622 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11623 (let (time
11624 interrupted-p
11625 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11626 (unless js2-mode-parsing
11627 (setq js2-mode-parsing t)
11628 (unwind-protect
11629 (when (or js2-mode-buffer-dirty-p force)
11630 (js2-remove-overlays)
11631 (setq js2-mode-buffer-dirty-p nil
11632 js2-mode-fontifications nil
11633 js2-mode-deferred-properties nil)
11634 (if js2-mode-verbose-parse-p
11635 (message "parsing..."))
11636 (setq time
11637 (js2-time
11638 (setq interrupted-p
11639 (catch 'interrupted
11640 (js2-parse)
11641 (with-silent-modifications
11642 ;; if parsing is interrupted, comments and regex
11643 ;; literals stay ignored by `parse-partial-sexp'
11644 (remove-text-properties (point-min) (point-max)
11645 '(syntax-table))
11646 (js2-mode-apply-deferred-properties)
11647 (js2-mode-remove-suppressed-warnings)
11648 (js2-mode-show-warnings)
11649 (js2-mode-show-errors)
11650 (if (>= js2-highlight-level 1)
11651 (js2-highlight-jsdoc js2-mode-ast)))
11652 nil))))
11653 (if interrupted-p
11654 (progn
11655 ;; unfinished parse => try again
11656 (setq js2-mode-buffer-dirty-p t)
11657 (js2-mode-reset-timer))
11658 (if js2-mode-verbose-parse-p
11659 (message "Parse time: %s" time))))
11660 (setq js2-mode-parsing nil)
11661 (unless interrupted-p
11662 (setq js2-mode-parse-timer nil))))))
11663
11664 (defun js2-mode-show-node (event)
11665 "Debugging aid: highlight selected AST node on mouse click."
11666 (interactive "e")
11667 (mouse-set-point event)
11668 (setq deactivate-mark t)
11669 (when js2-mode-show-overlay
11670 (let ((node (js2-node-at-point))
11671 beg end)
11672 (if (null node)
11673 (message "No node found at location %s" (point))
11674 (setq beg (js2-node-abs-pos node)
11675 end (+ beg (js2-node-len node)))
11676 (if js2-mode-node-overlay
11677 (move-overlay js2-mode-node-overlay beg end)
11678 (setq js2-mode-node-overlay (make-overlay beg end))
11679 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11680 (with-silent-modifications
11681 (if (fboundp 'cursor-sensor-mode)
11682 (put-text-property beg end 'cursor-sensor-functions
11683 '(js2-mode-hide-overlay))
11684 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11685 (message "%s, parent: %s"
11686 (js2-node-short-name node)
11687 (if (js2-node-parent node)
11688 (js2-node-short-name (js2-node-parent node))
11689 "nil"))))))
11690
11691 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11692 "Remove the debugging overlay when point moves.
11693 ARG1, ARG2 and ARG3 have different values depending on whether this function
11694 was found on `point-left' or in `cursor-sensor-functions'."
11695 (when js2-mode-node-overlay
11696 (let ((beg (overlay-start js2-mode-node-overlay))
11697 (end (overlay-end js2-mode-node-overlay))
11698 (p2 (if (windowp arg1)
11699 ;; Called from cursor-sensor-functions.
11700 (window-point arg1)
11701 ;; Called from point-left.
11702 arg2)))
11703 ;; Sometimes we're called spuriously.
11704 (unless (and p2
11705 (>= p2 beg)
11706 (<= p2 end))
11707 (with-silent-modifications
11708 (remove-text-properties beg end
11709 '(point-left nil cursor-sensor-functions)))
11710 (delete-overlay js2-mode-node-overlay)
11711 (setq js2-mode-node-overlay nil)))))
11712
11713 (defun js2-mode-reset ()
11714 "Debugging helper: reset everything."
11715 (interactive)
11716 (js2-mode-exit)
11717 (js2-mode))
11718
11719 (defun js2-mode-show-warn-or-err (e face)
11720 "Highlight a warning or error E with FACE.
11721 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11722 The last element is optional. When present, use instead of FACE."
11723 (let* ((key (cl-first e))
11724 (beg (cl-second e))
11725 (end (+ beg (cl-third e)))
11726 ;; Don't inadvertently go out of bounds.
11727 (beg (max (point-min) (min beg (point-max))))
11728 (end (max (point-min) (min end (point-max))))
11729 (ovl (make-overlay beg end)))
11730 ;; FIXME: Why a mix of overlays and text-properties?
11731 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11732 (overlay-put ovl 'js2-error t)
11733 (put-text-property beg end 'help-echo (js2-get-msg key))
11734 (if (fboundp 'cursor-sensor-mode)
11735 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11736 (put-text-property beg end 'point-entered #'js2-echo-error))))
11737
11738 (defun js2-remove-overlays ()
11739 "Remove overlays from buffer that have a `js2-error' property."
11740 (let ((beg (point-min))
11741 (end (point-max)))
11742 (save-excursion
11743 (dolist (o (overlays-in beg end))
11744 (when (overlay-get o 'js2-error)
11745 (delete-overlay o))))))
11746
11747 (defun js2-mode-apply-deferred-properties ()
11748 "Apply fontifications and other text properties recorded during parsing."
11749 (when (cl-plusp js2-highlight-level)
11750 ;; We defer clearing faces as long as possible to eliminate flashing.
11751 (js2-clear-face (point-min) (point-max))
11752 ;; Have to reverse the recorded fontifications list so that errors
11753 ;; and warnings overwrite the normal fontifications.
11754 (dolist (f (nreverse js2-mode-fontifications))
11755 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11756 (setq js2-mode-fontifications nil))
11757 (dolist (p js2-mode-deferred-properties)
11758 (apply #'put-text-property p))
11759 (setq js2-mode-deferred-properties nil))
11760
11761 (defun js2-mode-show-errors ()
11762 "Highlight syntax errors."
11763 (when js2-mode-show-parse-errors
11764 (dolist (e (js2-ast-root-errors js2-mode-ast))
11765 (js2-mode-show-warn-or-err e 'js2-error))))
11766
11767 (defun js2-mode-remove-suppressed-warnings ()
11768 "Take suppressed warnings out of the AST warnings list.
11769 This ensures that the counts and `next-error' are correct."
11770 (setf (js2-ast-root-warnings js2-mode-ast)
11771 (js2-delete-if
11772 (lambda (e)
11773 (let ((key (caar e)))
11774 (or
11775 (and (not js2-strict-trailing-comma-warning)
11776 (string-match "trailing\\.comma" key))
11777 (and (not js2-strict-cond-assign-warning)
11778 (string= key "msg.equal.as.assign"))
11779 (and js2-missing-semi-one-line-override
11780 (string= key "msg.missing.semi")
11781 (let* ((beg (cl-second e))
11782 (node (js2-node-at-point beg))
11783 (fn (js2-mode-find-parent-fn node))
11784 (body (and fn (js2-function-node-body fn)))
11785 (lc (and body (js2-node-abs-pos body)))
11786 (rc (and lc (+ lc (js2-node-len body)))))
11787 (and fn
11788 (or (null body)
11789 (save-excursion
11790 (goto-char beg)
11791 (and (js2-same-line lc)
11792 (js2-same-line rc))))))))))
11793 (js2-ast-root-warnings js2-mode-ast))))
11794
11795 (defun js2-mode-show-warnings ()
11796 "Highlight strict-mode warnings."
11797 (when js2-mode-show-strict-warnings
11798 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11799 (js2-mode-show-warn-or-err e 'js2-warning))))
11800
11801 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11802 "Called by point-motion hooks.
11803 ARG1, ARG2 and ARG3 have different values depending on whether this function
11804 was found on `point-entered' or in `cursor-sensor-functions'."
11805 (let* ((new-point (if (windowp arg1)
11806 ;; Called from cursor-sensor-functions.
11807 (window-point arg1)
11808 ;; Called from point-left.
11809 arg2))
11810 (msg (get-text-property new-point 'help-echo)))
11811 (when (and (stringp msg)
11812 (not (active-minibuffer-window))
11813 (not (current-message)))
11814 (message msg))))
11815
11816 (defun js2-line-break (&optional _soft)
11817 "Break line at point and indent, continuing comment if within one.
11818 If inside a string, and `js2-concat-multiline-strings' is not
11819 nil, turn it into concatenation."
11820 (interactive)
11821 (let ((parse-status (syntax-ppss)))
11822 (cond
11823 ;; Check if we're inside a string.
11824 ((nth 3 parse-status)
11825 (if js2-concat-multiline-strings
11826 (js2-mode-split-string parse-status)
11827 (insert "\n")))
11828 ;; Check if inside a block comment.
11829 ((nth 4 parse-status)
11830 (js2-mode-extend-comment (nth 8 parse-status)))
11831 (t
11832 (newline-and-indent)))))
11833
11834 (defun js2-mode-split-string (parse-status)
11835 "Turn a newline in mid-string into a string concatenation.
11836 PARSE-STATUS is as documented in `parse-partial-sexp'."
11837 (let* ((quote-char (nth 3 parse-status))
11838 (at-eol (eq js2-concat-multiline-strings 'eol)))
11839 (insert quote-char)
11840 (insert (if at-eol " +\n" "\n"))
11841 (unless at-eol
11842 (insert "+ "))
11843 (js2-indent-line)
11844 (insert quote-char)
11845 (when (eolp)
11846 (insert quote-char)
11847 (backward-char 1))))
11848
11849 (defun js2-mode-extend-comment (start-pos)
11850 "Indent the line and, when inside a comment block, add comment prefix."
11851 (let (star single col first-line needs-close)
11852 (save-excursion
11853 (back-to-indentation)
11854 (when (< (point) start-pos)
11855 (goto-char start-pos))
11856 (cond
11857 ((looking-at "\\*[^/]")
11858 (setq star t
11859 col (current-column)))
11860 ((looking-at "/\\*")
11861 (setq star t
11862 first-line t
11863 col (1+ (current-column))))
11864 ((looking-at "//")
11865 (setq single t
11866 col (current-column)))))
11867 ;; Heuristic for whether we need to close the comment:
11868 ;; if we've got a parse error here, assume it's an unterminated
11869 ;; comment.
11870 (setq needs-close
11871 (or
11872 (get-char-property (1- (point)) 'js2-error)
11873 ;; The heuristic above doesn't work well when we're
11874 ;; creating a comment and there's another one downstream,
11875 ;; as our parser thinks this one ends at the end of the
11876 ;; next one. (You can have a /* inside a js block comment.)
11877 ;; So just close it if the next non-ws char isn't a *.
11878 (and first-line
11879 (eolp)
11880 (save-excursion
11881 (skip-chars-forward " \t\r\n")
11882 (not (eq (char-after) ?*))))))
11883 (delete-horizontal-space)
11884 (insert "\n")
11885 (cond
11886 (star
11887 (indent-to col)
11888 (insert "* ")
11889 (if (and first-line needs-close)
11890 (save-excursion
11891 (insert "\n")
11892 (indent-to col)
11893 (insert "*/"))))
11894 ((and single
11895 (save-excursion
11896 (and (zerop (forward-line 1))
11897 (looking-at "\\s-*//"))))
11898 (indent-to col)
11899 (insert "// ")))
11900 ;; Don't need to extend the comment after all.
11901 (js2-indent-line)))
11902
11903 (defun js2-beginning-of-line ()
11904 "Toggle point between bol and first non-whitespace char in line.
11905 Also moves past comment delimiters when inside comments."
11906 (interactive)
11907 (let (node)
11908 (cond
11909 ((bolp)
11910 (back-to-indentation))
11911 ((looking-at "//")
11912 (skip-chars-forward "/ \t"))
11913 ((and (eq (char-after) ?*)
11914 (setq node (js2-comment-at-point))
11915 (memq (js2-comment-node-format node) '(jsdoc block))
11916 (save-excursion
11917 (skip-chars-backward " \t")
11918 (bolp)))
11919 (skip-chars-forward "\* \t"))
11920 (t
11921 (goto-char (point-at-bol))))))
11922
11923 (defun js2-end-of-line ()
11924 "Toggle point between eol and last non-whitespace char in line."
11925 (interactive)
11926 (if (eolp)
11927 (skip-chars-backward " \t")
11928 (goto-char (point-at-eol))))
11929
11930 (defun js2-mode-wait-for-parse (callback)
11931 "Invoke CALLBACK when parsing is finished.
11932 If parsing is already finished, calls CALLBACK immediately."
11933 (if (not js2-mode-buffer-dirty-p)
11934 (funcall callback)
11935 (push callback js2-mode-pending-parse-callbacks)
11936 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11937
11938 (defun js2-mode-parse-finished ()
11939 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11940 ;; We can't let errors propagate up, since it prevents the
11941 ;; `js2-parse' method from completing normally and returning
11942 ;; the ast, which makes things mysteriously not work right.
11943 (unwind-protect
11944 (dolist (cb js2-mode-pending-parse-callbacks)
11945 (condition-case err
11946 (funcall cb)
11947 (error (message "%s" err))))
11948 (setq js2-mode-pending-parse-callbacks nil)))
11949
11950 (defun js2-mode-flag-region (from to flag)
11951 "Hide or show text from FROM to TO, according to FLAG.
11952 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11953 Returns the created overlay if FLAG is non-nil."
11954 (remove-overlays from to 'invisible 'js2-outline)
11955 (when flag
11956 (let ((o (make-overlay from to)))
11957 (overlay-put o 'invisible 'js2-outline)
11958 (overlay-put o 'isearch-open-invisible
11959 'js2-isearch-open-invisible)
11960 o)))
11961
11962 ;; Function to be set as an outline-isearch-open-invisible' property
11963 ;; to the overlay that makes the outline invisible (see
11964 ;; `js2-mode-flag-region').
11965 (defun js2-isearch-open-invisible (_overlay)
11966 ;; We rely on the fact that isearch places point on the matched text.
11967 (js2-mode-show-element))
11968
11969 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11970 "Return cons cell of bounds of folding overlay at POS.
11971 Returns nil if not found."
11972 (let ((overlays (overlays-at (or pos (point))))
11973 o)
11974 (while (and overlays
11975 (not o))
11976 (if (overlay-get (car overlays) 'invisible)
11977 (setq o (car overlays))
11978 (setq overlays (cdr overlays))))
11979 (if o
11980 (cons (overlay-start o) (overlay-end o)))))
11981
11982 (defun js2-mode-function-at-point (&optional pos)
11983 "Return the innermost function node enclosing current point.
11984 Returns nil if point is not in a function."
11985 (let ((node (js2-node-at-point pos)))
11986 (while (and node (not (js2-function-node-p node)))
11987 (setq node (js2-node-parent node)))
11988 (if (js2-function-node-p node)
11989 node)))
11990
11991 (defun js2-mode-toggle-element ()
11992 "Hide or show the foldable element at the point."
11993 (interactive)
11994 (let (comment fn pos)
11995 (save-excursion
11996 (cond
11997 ;; /* ... */ comment?
11998 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11999 (if (js2-mode-invisible-overlay-bounds
12000 (setq pos (+ 3 (js2-node-abs-pos comment))))
12001 (progn
12002 (goto-char pos)
12003 (js2-mode-show-element))
12004 (js2-mode-hide-element)))
12005 ;; //-comment?
12006 ((save-excursion
12007 (back-to-indentation)
12008 (looking-at js2-mode-//-comment-re))
12009 (js2-mode-toggle-//-comment))
12010 ;; function?
12011 ((setq fn (js2-mode-function-at-point))
12012 (setq pos (and (js2-function-node-body fn)
12013 (js2-node-abs-pos (js2-function-node-body fn))))
12014 (goto-char (1+ pos))
12015 (if (js2-mode-invisible-overlay-bounds)
12016 (js2-mode-show-element)
12017 (js2-mode-hide-element)))
12018 (t
12019 (message "Nothing at point to hide or show"))))))
12020
12021 (defun js2-mode-hide-element ()
12022 "Fold/hide contents of a block, showing ellipses.
12023 Show the hidden text with \\[js2-mode-show-element]."
12024 (interactive)
12025 (if js2-mode-buffer-dirty-p
12026 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12027 (let (node body beg end)
12028 (cond
12029 ((js2-mode-invisible-overlay-bounds)
12030 (message "already hidden"))
12031 (t
12032 (setq node (js2-node-at-point))
12033 (cond
12034 ((js2-block-comment-p node)
12035 (js2-mode-hide-comment node))
12036 (t
12037 (while (and node (not (js2-function-node-p node)))
12038 (setq node (js2-node-parent node)))
12039 (if (and node
12040 (setq body (js2-function-node-body node)))
12041 (progn
12042 (setq beg (js2-node-abs-pos body)
12043 end (+ beg (js2-node-len body)))
12044 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12045 (message "No collapsable element found at point"))))))))
12046
12047 (defun js2-mode-show-element ()
12048 "Show the hidden element at current point."
12049 (interactive)
12050 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12051 (if bounds
12052 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12053 (message "Nothing to un-hide"))))
12054
12055 (defun js2-mode-show-all ()
12056 "Show all of the text in the buffer."
12057 (interactive)
12058 (js2-mode-flag-region (point-min) (point-max) nil))
12059
12060 (defun js2-mode-toggle-hide-functions ()
12061 (interactive)
12062 (if js2-mode-functions-hidden
12063 (js2-mode-show-functions)
12064 (js2-mode-hide-functions)))
12065
12066 (defun js2-mode-hide-functions ()
12067 "Hides all non-nested function bodies in the buffer.
12068 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12069 to open an individual entry."
12070 (interactive)
12071 (if js2-mode-buffer-dirty-p
12072 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12073 (if (null js2-mode-ast)
12074 (message "Oops - parsing failed")
12075 (setq js2-mode-functions-hidden t)
12076 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12077
12078 (defun js2-mode-function-hider (n endp)
12079 (when (not endp)
12080 (let ((tt (js2-node-type n))
12081 body beg end)
12082 (cond
12083 ((and (= tt js2-FUNCTION)
12084 (setq body (js2-function-node-body n)))
12085 (setq beg (js2-node-abs-pos body)
12086 end (+ beg (js2-node-len body)))
12087 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12088 nil) ; don't process children of function
12089 (t
12090 t))))) ; keep processing other AST nodes
12091
12092 (defun js2-mode-show-functions ()
12093 "Un-hide any folded function bodies in the buffer."
12094 (interactive)
12095 (setq js2-mode-functions-hidden nil)
12096 (save-excursion
12097 (goto-char (point-min))
12098 (while (/= (goto-char (next-overlay-change (point)))
12099 (point-max))
12100 (dolist (o (overlays-at (point)))
12101 (when (and (overlay-get o 'invisible)
12102 (not (overlay-get o 'comment)))
12103 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12104
12105 (defun js2-mode-hide-comment (n)
12106 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12107 3 ; /**
12108 2)) ; /*
12109 (beg (+ (js2-node-abs-pos n) head))
12110 (end (- (+ beg (js2-node-len n)) head 2))
12111 (o (js2-mode-flag-region beg end 'hide)))
12112 (overlay-put o 'comment t)))
12113
12114 (defun js2-mode-toggle-hide-comments ()
12115 "Folds all block comments in the buffer.
12116 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12117 to open an individual entry."
12118 (interactive)
12119 (if js2-mode-comments-hidden
12120 (js2-mode-show-comments)
12121 (js2-mode-hide-comments)))
12122
12123 (defun js2-mode-hide-comments ()
12124 (interactive)
12125 (if js2-mode-buffer-dirty-p
12126 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12127 (if (null js2-mode-ast)
12128 (message "Oops - parsing failed")
12129 (setq js2-mode-comments-hidden t)
12130 (dolist (n (js2-ast-root-comments js2-mode-ast))
12131 (when (js2-block-comment-p n)
12132 (js2-mode-hide-comment n)))
12133 (js2-mode-hide-//-comments)))
12134
12135 (defun js2-mode-extend-//-comment (direction)
12136 "Find start or end of a block of similar //-comment lines.
12137 DIRECTION is -1 to look back, 1 to look forward.
12138 INDENT is the indentation level to match.
12139 Returns the end-of-line position of the furthest adjacent
12140 //-comment line with the same indentation as the current line.
12141 If there is no such matching line, returns current end of line."
12142 (let ((pos (point-at-eol))
12143 (indent (current-indentation)))
12144 (save-excursion
12145 (while (and (zerop (forward-line direction))
12146 (looking-at js2-mode-//-comment-re)
12147 (eq indent (length (match-string 1))))
12148 (setq pos (point-at-eol)))
12149 pos)))
12150
12151 (defun js2-mode-hide-//-comments ()
12152 "Fold adjacent 1-line comments, showing only snippet of first one."
12153 (let (beg end)
12154 (save-excursion
12155 (goto-char (point-min))
12156 (while (re-search-forward js2-mode-//-comment-re nil t)
12157 (setq beg (point)
12158 end (js2-mode-extend-//-comment 1))
12159 (unless (eq beg end)
12160 (overlay-put (js2-mode-flag-region beg end 'hide)
12161 'comment t))
12162 (goto-char end)
12163 (forward-char 1)))))
12164
12165 (defun js2-mode-toggle-//-comment ()
12166 "Fold or un-fold any multi-line //-comment at point.
12167 Caller should have determined that this line starts with a //-comment."
12168 (let* ((beg (point-at-eol))
12169 (end beg))
12170 (save-excursion
12171 (goto-char end)
12172 (if (js2-mode-invisible-overlay-bounds)
12173 (js2-mode-show-element)
12174 ;; else hide the comment
12175 (setq beg (js2-mode-extend-//-comment -1)
12176 end (js2-mode-extend-//-comment 1))
12177 (unless (eq beg end)
12178 (overlay-put (js2-mode-flag-region beg end 'hide)
12179 'comment t))))))
12180
12181 (defun js2-mode-show-comments ()
12182 "Un-hide any hidden comments, leaving other hidden elements alone."
12183 (interactive)
12184 (setq js2-mode-comments-hidden nil)
12185 (save-excursion
12186 (goto-char (point-min))
12187 (while (/= (goto-char (next-overlay-change (point)))
12188 (point-max))
12189 (dolist (o (overlays-at (point)))
12190 (when (overlay-get o 'comment)
12191 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12192
12193 (defun js2-mode-display-warnings-and-errors ()
12194 "Turn on display of warnings and errors."
12195 (interactive)
12196 (setq js2-mode-show-parse-errors t
12197 js2-mode-show-strict-warnings t)
12198 (js2-reparse 'force))
12199
12200 (defun js2-mode-hide-warnings-and-errors ()
12201 "Turn off display of warnings and errors."
12202 (interactive)
12203 (setq js2-mode-show-parse-errors nil
12204 js2-mode-show-strict-warnings nil)
12205 (js2-reparse 'force))
12206
12207 (defun js2-mode-toggle-warnings-and-errors ()
12208 "Toggle the display of warnings and errors.
12209 Some users don't like having warnings/errors reported while they type."
12210 (interactive)
12211 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12212 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12213 (if (called-interactively-p 'any)
12214 (message "warnings and errors %s"
12215 (if js2-mode-show-parse-errors
12216 "enabled"
12217 "disabled")))
12218 (js2-reparse 'force))
12219
12220 (defun js2-mode-customize ()
12221 (interactive)
12222 (customize-group 'js2-mode))
12223
12224 (defun js2-mode-forward-sexp (&optional arg)
12225 "Move forward across one statement or balanced expression.
12226 With ARG, do it that many times. Negative arg -N means
12227 move backward across N balanced expressions."
12228 (interactive "p")
12229 (setq arg (or arg 1))
12230 (save-restriction
12231 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12232 (js2-reparse)
12233 (let (forward-sexp-function
12234 node (start (point)) pos lp rp child)
12235 (cond
12236 ;; backward-sexp
12237 ;; could probably make this better for some cases:
12238 ;; - if in statement block (e.g. function body), go to parent
12239 ;; - infix exprs like (foo in bar) - maybe go to beginning
12240 ;; of infix expr if in the right-side expression?
12241 ((and arg (cl-minusp arg))
12242 (dotimes (_ (- arg))
12243 (js2-backward-sws)
12244 (forward-char -1) ; Enter the node we backed up to.
12245 (when (setq node (js2-node-at-point (point) t))
12246 (setq pos (js2-node-abs-pos node))
12247 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12248 (setq lp (car parens)
12249 rp (cdr parens)))
12250 (when (and lp (> start lp))
12251 (if (and rp (<= start rp))
12252 ;; Between parens, check if there's a child node we can jump.
12253 (when (setq child (js2-node-closest-child node (point) lp t))
12254 (setq pos (js2-node-abs-pos child)))
12255 ;; Before both parens.
12256 (setq pos lp)))
12257 (let ((state (parse-partial-sexp start pos)))
12258 (goto-char (if (not (zerop (car state)))
12259 ;; Stumble at the unbalanced paren if < 0, or
12260 ;; jump a bit further if > 0.
12261 (scan-sexps start -1)
12262 pos))))
12263 (unless pos (goto-char (point-min)))))
12264 (t
12265 ;; forward-sexp
12266 (dotimes (_ arg)
12267 (js2-forward-sws)
12268 (when (setq node (js2-node-at-point (point) t))
12269 (setq pos (js2-node-abs-pos node))
12270 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12271 (setq lp (car parens)
12272 rp (cdr parens)))
12273 (or
12274 (when (and rp (<= start rp))
12275 (if (> start lp)
12276 (when (setq child (js2-node-closest-child node (point) rp))
12277 (setq pos (js2-node-abs-end child)))
12278 (setq pos (1+ rp))))
12279 ;; No parens or child nodes, looks for the end of the current node.
12280 (cl-incf pos (js2-node-len
12281 (if (js2-expr-stmt-node-p (js2-node-parent node))
12282 ;; Stop after the semicolon.
12283 (js2-node-parent node)
12284 node))))
12285 (let ((state (save-excursion (parse-partial-sexp start pos))))
12286 (goto-char (if (not (zerop (car state)))
12287 (scan-sexps start 1)
12288 pos))))
12289 (unless pos (goto-char (point-max)))))))))
12290
12291 (defun js2-mode-forward-sexp-parens (node abs-pos)
12292 "Return a cons cell with positions of main parens in NODE."
12293 (cond
12294 ((or (js2-array-node-p node)
12295 (js2-object-node-p node)
12296 (js2-comp-node-p node)
12297 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12298 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12299 ((js2-paren-expr-node-p node)
12300 (let ((lp (js2-node-lp node))
12301 (rp (js2-node-rp node)))
12302 (cons (when lp (+ abs-pos lp))
12303 (when rp (+ abs-pos rp)))))))
12304
12305 (defun js2-node-closest-child (parent point limit &optional before)
12306 (let* ((parent-pos (js2-node-abs-pos parent))
12307 (rpoint (- point parent-pos))
12308 (rlimit (- limit parent-pos))
12309 (min (min rpoint rlimit))
12310 (max (max rpoint rlimit))
12311 found)
12312 (catch 'done
12313 (js2-visit-ast
12314 parent
12315 (lambda (node _end-p)
12316 (if (eq node parent)
12317 t
12318 (let ((pos (js2-node-pos node)) ;; Both relative values.
12319 (end (+ (js2-node-pos node) (js2-node-len node))))
12320 (when (and (>= pos min) (<= end max)
12321 (if before (< pos rpoint) (> end rpoint)))
12322 (setq found node))
12323 (when (> end rpoint)
12324 (throw 'done nil)))
12325 nil))))
12326 found))
12327
12328 (defun js2-errors ()
12329 "Return a list of errors found."
12330 (and js2-mode-ast
12331 (js2-ast-root-errors js2-mode-ast)))
12332
12333 (defun js2-warnings ()
12334 "Return a list of warnings found."
12335 (and js2-mode-ast
12336 (js2-ast-root-warnings js2-mode-ast)))
12337
12338 (defun js2-have-errors-p ()
12339 "Return non-nil if any parse errors or warnings were found."
12340 (or (js2-errors) (js2-warnings)))
12341
12342 (defun js2-errors-and-warnings ()
12343 "Return a copy of the concatenated errors and warnings lists.
12344 They are appended: first the errors, then the warnings.
12345 Entries are of the form (MSG BEG END)."
12346 (when js2-mode-ast
12347 (append (js2-ast-root-errors js2-mode-ast)
12348 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12349
12350 (defun js2-next-error (&optional arg reset)
12351 "Move to next parse error.
12352 Typically invoked via \\[next-error].
12353 ARG is the number of errors, forward or backward, to move.
12354 RESET means start over from the beginning."
12355 (interactive "p")
12356 (if (not (or (js2-errors) (js2-warnings)))
12357 (message "No errors")
12358 (when reset
12359 (goto-char (point-min)))
12360 (let* ((errs (js2-errors-and-warnings))
12361 (continue t)
12362 (start (point))
12363 (count (or arg 1))
12364 (backward (cl-minusp count))
12365 (sorter (if backward '> '<))
12366 (stopper (if backward '< '>))
12367 (count (abs count))
12368 all-errs err)
12369 ;; Sort by start position.
12370 (setq errs (sort errs (lambda (e1 e2)
12371 (funcall sorter (cl-second e1) (cl-second e2))))
12372 all-errs errs)
12373 ;; Find nth error with pos > start.
12374 (while (and errs continue)
12375 (when (funcall stopper (cl-cadar errs) start)
12376 (setq err (car errs))
12377 (if (zerop (cl-decf count))
12378 (setq continue nil)))
12379 (setq errs (cdr errs)))
12380 ;; Clear for `js2-echo-error'.
12381 (message nil)
12382 (if err
12383 (goto-char (cl-second err))
12384 ;; Wrap around to first error.
12385 (goto-char (cl-second (car all-errs)))
12386 ;; If we were already on it, echo msg again.
12387 (if (= (point) start)
12388 (js2-echo-error (point) (point)))))))
12389
12390 (defun js2-down-mouse-3 ()
12391 "Make right-click move the point to the click location.
12392 This makes right-click context menu operations a bit more intuitive.
12393 The point will not move if the region is active, however, to avoid
12394 destroying the region selection."
12395 (interactive)
12396 (when (and js2-move-point-on-right-click
12397 (not mark-active))
12398 (let ((e last-input-event))
12399 (ignore-errors
12400 (goto-char (cl-cadadr e))))))
12401
12402 (defun js2-mode-create-imenu-index ()
12403 "Return an alist for `imenu--index-alist'."
12404 ;; This is built up in `js2-parse-record-imenu' during parsing.
12405 (when js2-mode-ast
12406 ;; if we have an ast but no recorder, they're requesting a rescan
12407 (unless js2-imenu-recorder
12408 (js2-reparse 'force))
12409 (prog1
12410 (js2-build-imenu-index)
12411 (setq js2-imenu-recorder nil
12412 js2-imenu-function-map nil))))
12413
12414 (defun js2-mode-find-tag ()
12415 "Replacement for `find-tag-default'.
12416 `find-tag-default' returns a ridiculous answer inside comments."
12417 (let (beg end)
12418 (save-excursion
12419 (if (looking-at "\\_>")
12420 (setq beg (progn (forward-symbol -1) (point))
12421 end (progn (forward-symbol 1) (point)))
12422 (setq beg (progn (forward-symbol 1) (point))
12423 end (progn (forward-symbol -1) (point))))
12424 (replace-regexp-in-string
12425 "[\"']" ""
12426 (buffer-substring-no-properties beg end)))))
12427
12428 (defun js2-mode-forward-sibling ()
12429 "Move to the end of the sibling following point in parent.
12430 Returns non-nil if successful, or nil if there was no following sibling."
12431 (let* ((node (js2-node-at-point))
12432 (parent (js2-mode-find-enclosing-fn node))
12433 sib)
12434 (when (setq sib (js2-node-find-child-after (point) parent))
12435 (goto-char (+ (js2-node-abs-pos sib)
12436 (js2-node-len sib))))))
12437
12438 (defun js2-mode-backward-sibling ()
12439 "Move to the beginning of the sibling node preceding point in parent.
12440 Parent is defined as the enclosing script or function."
12441 (let* ((node (js2-node-at-point))
12442 (parent (js2-mode-find-enclosing-fn node))
12443 sib)
12444 (when (setq sib (js2-node-find-child-before (point) parent))
12445 (goto-char (js2-node-abs-pos sib)))))
12446
12447 (defun js2-beginning-of-defun (&optional arg)
12448 "Go to line on which current function starts, and return t on success.
12449 If we're not in a function or already at the beginning of one, go
12450 to beginning of previous script-level element.
12451 With ARG N, do that N times. If N is negative, move forward."
12452 (setq arg (or arg 1))
12453 (if (cl-plusp arg)
12454 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12455 (when (cond
12456 ((js2-function-node-p parent)
12457 (goto-char (js2-node-abs-pos parent)))
12458 (t
12459 (js2-mode-backward-sibling)))
12460 (if (> arg 1)
12461 (js2-beginning-of-defun (1- arg))
12462 t)))
12463 (when (js2-end-of-defun)
12464 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12465
12466 (defun js2-end-of-defun ()
12467 "Go to the char after the last position of the current function
12468 or script-level element."
12469 (let* ((node (js2-node-at-point))
12470 (parent (or (and (js2-function-node-p node) node)
12471 (js2-node-parent-script-or-fn node)))
12472 script)
12473 (unless (js2-function-node-p parent)
12474 ;; Use current script-level node, or, if none, the next one.
12475 (setq script (or parent node)
12476 parent (js2-node-find-child-before (point) script))
12477 (when (or (null parent)
12478 (>= (point) (+ (js2-node-abs-pos parent)
12479 (js2-node-len parent))))
12480 (setq parent (js2-node-find-child-after (point) script))))
12481 (when parent
12482 (goto-char (+ (js2-node-abs-pos parent)
12483 (js2-node-len parent))))))
12484
12485 (defun js2-mark-defun (&optional allow-extend)
12486 "Put mark at end of this function, point at beginning.
12487 The function marked is the one that contains point.
12488
12489 Interactively, if this command is repeated,
12490 or (in Transient Mark mode) if the mark is active,
12491 it marks the next defun after the ones already marked."
12492 (interactive "p")
12493 (let (extended)
12494 (when (and allow-extend
12495 (or (and (eq last-command this-command) (mark t))
12496 (and transient-mark-mode mark-active)))
12497 (let ((sib (save-excursion
12498 (goto-char (mark))
12499 (if (js2-mode-forward-sibling)
12500 (point)))))
12501 (if sib
12502 (progn
12503 (set-mark sib)
12504 (setq extended t))
12505 ;; no more siblings - try extending to enclosing node
12506 (goto-char (mark t)))))
12507 (when (not extended)
12508 (let ((node (js2-node-at-point (point) t)) ; skip comments
12509 ast fn stmt parent beg end)
12510 (when (js2-ast-root-p node)
12511 (setq ast node
12512 node (or (js2-node-find-child-after (point) node)
12513 (js2-node-find-child-before (point) node))))
12514 ;; only mark whole buffer if we can't find any children
12515 (if (null node)
12516 (setq node ast))
12517 (if (js2-function-node-p node)
12518 (setq parent node)
12519 (setq fn (js2-mode-find-enclosing-fn node)
12520 stmt (if (or (null fn)
12521 (js2-ast-root-p fn))
12522 (js2-mode-find-first-stmt node))
12523 parent (or stmt fn)))
12524 (setq beg (js2-node-abs-pos parent)
12525 end (+ beg (js2-node-len parent)))
12526 (push-mark beg)
12527 (goto-char end)
12528 (exchange-point-and-mark)))))
12529
12530 (defun js2-narrow-to-defun ()
12531 "Narrow to the function enclosing point."
12532 (interactive)
12533 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12534 (fn (if (js2-script-node-p node)
12535 node
12536 (js2-mode-find-enclosing-fn node)))
12537 (beg (js2-node-abs-pos fn)))
12538 (unless (js2-ast-root-p fn)
12539 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12540
12541 (defun js2-jump-to-definition (&optional arg)
12542 "Jump to the definition of an object's property, variable or function."
12543 (interactive "P")
12544 (ring-insert find-tag-marker-ring (point-marker))
12545 (let* ((node (js2-node-at-point))
12546 (parent (js2-node-parent node))
12547 (names (if (js2-prop-get-node-p parent)
12548 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12549 (cl-loop for n in temp
12550 with result = '()
12551 do (push n result)
12552 until (equal node n)
12553 finally return result)))))
12554 node-init)
12555 (unless (and (js2-name-node-p node)
12556 (not (js2-var-init-node-p parent))
12557 (not (js2-function-node-p parent)))
12558 (error "Node is not a supported jump node"))
12559 (push (or (and names (pop names))
12560 (unless (and (js2-object-prop-node-p parent)
12561 (eq node (js2-object-prop-node-left parent)))
12562 node)) names)
12563 (setq node-init (js2-search-scope node names))
12564
12565 ;; todo: display list of results in buffer
12566 ;; todo: group found references by buffer
12567 (unless node-init
12568 (switch-to-buffer
12569 (catch 'found
12570 (unless arg
12571 (mapc (lambda (b)
12572 (with-current-buffer b
12573 (when (derived-mode-p 'js2-mode)
12574 (setq node-init (js2-search-scope js2-mode-ast names))
12575 (if node-init
12576 (throw 'found b)))))
12577 (buffer-list)))
12578 nil)))
12579 (setq node-init (if (listp node-init) (car node-init) node-init))
12580 (unless node-init
12581 (pop-tag-mark)
12582 (error "No jump location found"))
12583 (goto-char (js2-node-abs-pos node-init))))
12584
12585 (defun js2-search-object (node name-node)
12586 "Check if object NODE contains element with NAME-NODE."
12587 (cl-assert (js2-object-node-p node))
12588 ;; Only support name-node and nodes for the time being
12589 (cl-loop for elem in (js2-object-node-elems node)
12590 for left = (js2-object-prop-node-left elem)
12591 if (or (and (js2-name-node-p left)
12592 (equal (js2-name-node-name name-node)
12593 (js2-name-node-name left)))
12594 (and (js2-string-node-p left)
12595 (string= (js2-name-node-name name-node)
12596 (js2-string-node-value left))))
12597 return elem))
12598
12599 (defun js2-search-object-for-prop (object prop-names)
12600 "Return node in OBJECT that matches PROP-NAMES or nil.
12601 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12602 i.e. ('name' 'value') = {name : { value: 3}}"
12603 (let (node
12604 (temp-object object)
12605 (temp t) ;temporay node
12606 (names prop-names))
12607 (while (and temp names (js2-object-node-p temp-object))
12608 (setq temp (js2-search-object temp-object (pop names)))
12609 (and (setq node temp)
12610 (setq temp-object (js2-object-prop-node-right temp))))
12611 (unless names node)))
12612
12613 (defun js2-search-scope (node names)
12614 "Searches NODE scope for jump location matching NAMES.
12615 NAMES is a list of property values to search for. For functions
12616 and variables NAMES will contain one element."
12617 (let (node-init
12618 (val (js2-name-node-name (car names))))
12619 (setq node-init (js2-get-symbol-declaration node val))
12620
12621 (when (> (length names) 1)
12622
12623 ;; Check var declarations
12624 (when (and node-init (string= val (js2-name-node-name node-init)))
12625 (let ((parent (js2-node-parent node-init))
12626 (temp-names names))
12627 (pop temp-names) ;; First element is var name
12628 (setq node-init (when (js2-var-init-node-p parent)
12629 (js2-search-object-for-prop
12630 (js2-var-init-node-initializer parent)
12631 temp-names)))))
12632
12633 ;; Check all assign nodes
12634 (js2-visit-ast
12635 js2-mode-ast
12636 (lambda (node endp)
12637 (unless endp
12638 (if (js2-assign-node-p node)
12639 (let ((left (js2-assign-node-left node))
12640 (right (js2-assign-node-right node))
12641 (temp-names names))
12642 (when (js2-prop-get-node-p left)
12643 (let* ((prop-list (js2-compute-nested-prop-get left))
12644 (found (cl-loop for prop in prop-list
12645 until (not (string= (js2-name-node-name
12646 (pop temp-names))
12647 (js2-name-node-name prop)))
12648 if (not temp-names) return prop))
12649 (found-node (or found
12650 (when (js2-object-node-p right)
12651 (js2-search-object-for-prop right
12652 temp-names)))))
12653 (if found-node (push found-node node-init))))))
12654 t))))
12655 node-init))
12656
12657 (defun js2-get-symbol-declaration (node name)
12658 "Find scope for NAME from NODE."
12659 (let ((scope (js2-get-defining-scope
12660 (or (js2-node-get-enclosing-scope node)
12661 node) name)))
12662 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12663
12664 (provide 'js2-mode)
12665
12666 ;;; js2-mode.el ends here