]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Fix await parsing
[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 (unless (or (and default (not (js2-assign-node-p default)))
2555 (and declaration (or (js2-function-node-p declaration)
2556 (js2-class-node-p declaration))))
2557 (insert ";\n"))))
2558
2559 (cl-defstruct (js2-while-node
2560 (:include js2-loop-node)
2561 (:constructor nil)
2562 (:constructor make-js2-while-node (&key (type js2-WHILE)
2563 (pos (js2-current-token-beg))
2564 len body
2565 condition lp
2566 rp)))
2567 "AST node for while-loop."
2568 condition) ; while-condition
2569
2570 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2571 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2572
2573 (defun js2-visit-while-node (n v)
2574 (js2-visit-ast (js2-while-node-condition n) v)
2575 (js2-visit-ast (js2-while-node-body n) v))
2576
2577 (defun js2-print-while-node (n i)
2578 (let ((pad (js2-make-pad i)))
2579 (insert pad "while (")
2580 (js2-print-ast (js2-while-node-condition n) 0)
2581 (insert ") {\n")
2582 (js2-print-body (js2-while-node-body n) (1+ i))
2583 (insert pad "}\n")))
2584
2585 (cl-defstruct (js2-for-node
2586 (:include js2-loop-node)
2587 (:constructor nil)
2588 (:constructor make-js2-for-node (&key (type js2-FOR)
2589 (pos js2-ts-cursor)
2590 len body init
2591 condition
2592 update lp rp)))
2593 "AST node for a C-style for-loop."
2594 init ; initialization expression
2595 condition ; loop condition
2596 update) ; update clause
2597
2598 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2599 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2600
2601 (defun js2-visit-for-node (n v)
2602 (js2-visit-ast (js2-for-node-init n) v)
2603 (js2-visit-ast (js2-for-node-condition n) v)
2604 (js2-visit-ast (js2-for-node-update n) v)
2605 (js2-visit-ast (js2-for-node-body n) v))
2606
2607 (defun js2-print-for-node (n i)
2608 (let ((pad (js2-make-pad i)))
2609 (insert pad "for (")
2610 (js2-print-ast (js2-for-node-init n) 0)
2611 (insert "; ")
2612 (js2-print-ast (js2-for-node-condition n) 0)
2613 (insert "; ")
2614 (js2-print-ast (js2-for-node-update n) 0)
2615 (insert ") {\n")
2616 (js2-print-body (js2-for-node-body n) (1+ i))
2617 (insert pad "}\n")))
2618
2619 (cl-defstruct (js2-for-in-node
2620 (:include js2-loop-node)
2621 (:constructor nil)
2622 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2623 (pos js2-ts-cursor)
2624 len body
2625 iterator
2626 object
2627 in-pos
2628 each-pos
2629 foreach-p forof-p
2630 lp rp)))
2631 "AST node for a for..in loop."
2632 iterator ; [var] foo in ...
2633 object ; object over which we're iterating
2634 in-pos ; buffer position of 'in' keyword
2635 each-pos ; buffer position of 'each' keyword, if foreach-p
2636 foreach-p ; t if it's a for-each loop
2637 forof-p) ; t if it's a for-of loop
2638
2639 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2640 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2641
2642 (defun js2-visit-for-in-node (n v)
2643 (js2-visit-ast (js2-for-in-node-iterator n) v)
2644 (js2-visit-ast (js2-for-in-node-object n) v)
2645 (js2-visit-ast (js2-for-in-node-body n) v))
2646
2647 (defun js2-print-for-in-node (n i)
2648 (let ((pad (js2-make-pad i))
2649 (foreach (js2-for-in-node-foreach-p n))
2650 (forof (js2-for-in-node-forof-p n)))
2651 (insert pad "for ")
2652 (if foreach
2653 (insert "each "))
2654 (insert "(")
2655 (js2-print-ast (js2-for-in-node-iterator n) 0)
2656 (insert (if forof " of " " in "))
2657 (js2-print-ast (js2-for-in-node-object n) 0)
2658 (insert ") {\n")
2659 (js2-print-body (js2-for-in-node-body n) (1+ i))
2660 (insert pad "}\n")))
2661
2662 (cl-defstruct (js2-return-node
2663 (:include js2-node)
2664 (:constructor nil)
2665 (:constructor make-js2-return-node (&key (type js2-RETURN)
2666 (pos js2-ts-cursor)
2667 len
2668 retval)))
2669 "AST node for a return statement."
2670 retval) ; expression to return, or 'undefined
2671
2672 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2673 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2674
2675 (defun js2-visit-return-node (n v)
2676 (js2-visit-ast (js2-return-node-retval n) v))
2677
2678 (defun js2-print-return-node (n i)
2679 (insert (js2-make-pad i) "return")
2680 (when (js2-return-node-retval n)
2681 (insert " ")
2682 (js2-print-ast (js2-return-node-retval n) 0))
2683 (insert ";\n"))
2684
2685 (cl-defstruct (js2-if-node
2686 (:include js2-node)
2687 (:constructor nil)
2688 (:constructor make-js2-if-node (&key (type js2-IF)
2689 (pos js2-ts-cursor)
2690 len condition
2691 then-part
2692 else-pos
2693 else-part lp
2694 rp)))
2695 "AST node for an if-statement."
2696 condition ; expression
2697 then-part ; statement or block
2698 else-pos ; optional buffer position of 'else' keyword
2699 else-part ; optional statement or block
2700 lp ; position of left-paren, nil if omitted
2701 rp) ; position of right-paren, nil if omitted
2702
2703 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2704 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2705
2706 (defun js2-visit-if-node (n v)
2707 (js2-visit-ast (js2-if-node-condition n) v)
2708 (js2-visit-ast (js2-if-node-then-part n) v)
2709 (js2-visit-ast (js2-if-node-else-part n) v))
2710
2711 (defun js2-print-if-node (n i)
2712 (let ((pad (js2-make-pad i))
2713 (then-part (js2-if-node-then-part n))
2714 (else-part (js2-if-node-else-part n)))
2715 (insert pad "if (")
2716 (js2-print-ast (js2-if-node-condition n) 0)
2717 (insert ") {\n")
2718 (js2-print-body then-part (1+ i))
2719 (insert pad "}")
2720 (cond
2721 ((not else-part)
2722 (insert "\n"))
2723 ((js2-if-node-p else-part)
2724 (insert " else ")
2725 (js2-print-body else-part i))
2726 (t
2727 (insert " else {\n")
2728 (js2-print-body else-part (1+ i))
2729 (insert pad "}\n")))))
2730
2731 (cl-defstruct (js2-export-binding-node
2732 (:include js2-node)
2733 (:constructor nil)
2734 (:constructor make-js2-export-binding-node (&key (type -1)
2735 pos
2736 len
2737 local-name
2738 extern-name)))
2739 "AST node for an external symbol binding.
2740 It contains a local-name node which is the name of the value in the
2741 current scope, and extern-name which is the name of the value in the
2742 imported or exported scope. By default these are the same, but if the
2743 name is aliased as in {foo as bar}, it would have an extern-name node
2744 containing 'foo' and a local-name node containing 'bar'."
2745 local-name ; js2-name-node with the variable name in this scope
2746 extern-name) ; js2-name-node with the value name in the exporting module
2747
2748 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2749 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2750
2751 (defun js2-visit-extern-binding (n v)
2752 "Visit an extern binding node. First visit the local-name, and, if
2753 different, visit the extern-name."
2754 (let ((local-name (js2-export-binding-node-local-name n))
2755 (extern-name (js2-export-binding-node-extern-name n)))
2756 (when local-name
2757 (js2-visit-ast local-name v))
2758 (when (not (equal local-name extern-name))
2759 (js2-visit-ast extern-name v))))
2760
2761 (defun js2-print-extern-binding (n _i)
2762 "Print a representation of a single extern binding. E.g. 'foo' or
2763 'foo as bar'."
2764 (let ((local-name (js2-export-binding-node-local-name n))
2765 (extern-name (js2-export-binding-node-extern-name n)))
2766 (insert (js2-name-node-name extern-name))
2767 (when (not (equal local-name extern-name))
2768 (insert " as ")
2769 (insert (js2-name-node-name local-name)))))
2770
2771
2772 (cl-defstruct (js2-import-node
2773 (:include js2-node)
2774 (:constructor nil)
2775 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2776 (pos (js2-current-token-beg))
2777 len
2778 import
2779 from
2780 module-id)))
2781 "AST node for an import statement. It follows the form
2782
2783 import ModuleSpecifier;
2784 import ImportClause FromClause;"
2785 import ; js2-import-clause-node specifying which names are to imported.
2786 from ; js2-from-clause-node indicating the module from which to import.
2787 module-id) ; module-id of the import. E.g. 'src/mylib'.
2788
2789 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2790 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2791
2792 (defun js2-visit-import (n v)
2793 (let ((import-clause (js2-import-node-import n))
2794 (from-clause (js2-import-node-from n)))
2795 (when import-clause
2796 (js2-visit-ast import-clause v))
2797 (when from-clause
2798 (js2-visit-ast from-clause v))))
2799
2800 (defun js2-print-import (n i)
2801 "Prints a representation of the import node"
2802 (let ((pad (js2-make-pad i))
2803 (import-clause (js2-import-node-import n))
2804 (from-clause (js2-import-node-from n))
2805 (module-id (js2-import-node-module-id n)))
2806 (insert pad "import ")
2807 (if import-clause
2808 (progn
2809 (js2-print-import-clause import-clause)
2810 (insert " ")
2811 (js2-print-from-clause from-clause))
2812 (insert "'")
2813 (insert module-id)
2814 (insert "'"))
2815 (insert ";\n")))
2816
2817 (cl-defstruct (js2-import-clause-node
2818 (:include js2-node)
2819 (:constructor nil)
2820 (:constructor make-js2-import-clause-node (&key (type -1)
2821 pos
2822 len
2823 namespace-import
2824 named-imports
2825 default-binding)))
2826 "AST node corresponding to the import clause of an import statement. This is
2827 the portion of the import that bindings names from the external context to the
2828 local context."
2829 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2830 named-imports ; lisp list of js2-export-binding-node for all named imports.
2831 default-binding) ; js2-export-binding-node for the default import binding
2832
2833 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2834 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2835
2836 (defun js2-visit-import-clause (n v)
2837 (let ((ns-import (js2-import-clause-node-namespace-import n))
2838 (named-imports (js2-import-clause-node-named-imports n))
2839 (default (js2-import-clause-node-default-binding n)))
2840 (when ns-import
2841 (js2-visit-ast ns-import v))
2842 (when named-imports
2843 (dolist (import named-imports)
2844 (js2-visit-ast import v)))
2845 (when default
2846 (js2-visit-ast default v))))
2847
2848 (defun js2-print-import-clause (n)
2849 (let ((ns-import (js2-import-clause-node-namespace-import n))
2850 (named-imports (js2-import-clause-node-named-imports n))
2851 (default (js2-import-clause-node-default-binding n)))
2852 (cond
2853 ((and default ns-import)
2854 (js2-print-ast default)
2855 (insert ", ")
2856 (js2-print-namespace-import ns-import))
2857 ((and default named-imports)
2858 (js2-print-ast default)
2859 (insert ", ")
2860 (js2-print-named-imports named-imports))
2861 (default
2862 (js2-print-ast default))
2863 (ns-import
2864 (js2-print-namespace-import ns-import))
2865 (named-imports
2866 (js2-print-named-imports named-imports)))))
2867
2868 (defun js2-print-namespace-import (node)
2869 (insert "* as ")
2870 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2871
2872 (defun js2-print-named-imports (imports)
2873 (insert "{")
2874 (let ((len (length imports))
2875 (n 0))
2876 (while (< n len)
2877 (js2-print-extern-binding (nth n imports) 0)
2878 (unless (= n (- len 1))
2879 (insert ", "))
2880 (setq n (+ n 1))))
2881 (insert "}"))
2882
2883 (cl-defstruct (js2-namespace-import-node
2884 (:include js2-node)
2885 (:constructor nil)
2886 (:constructor make-js2-namespace-import-node (&key (type -1)
2887 pos
2888 len
2889 name)))
2890 "AST node for a complete namespace import.
2891 E.g. the '* as lib' expression in:
2892
2893 import * as lib from 'src/lib'
2894
2895 It contains a single name node referring to the bound name."
2896 name) ; js2-name-node of the bound name.
2897
2898 (defun js2-visit-namespace-import (n v)
2899 (js2-visit-ast (js2-namespace-import-node-name n) v))
2900
2901 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2902 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2903
2904 (cl-defstruct (js2-from-clause-node
2905 (:include js2-node)
2906 (:constructor nil)
2907 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2908 pos
2909 len
2910 module-id
2911 metadata-p)))
2912 "AST node for the from clause in an import or export statement.
2913 E.g. from 'my/module'. It can refere to either an external module, or to the
2914 modules metadata itself."
2915 module-id ; string containing the module specifier.
2916 metadata-p) ; true if this clause refers to the module's metadata
2917
2918 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2919 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2920
2921 (defun js2-print-from-clause (n)
2922 (insert "from ")
2923 (if (js2-from-clause-node-metadata-p n)
2924 (insert "this module")
2925 (insert "'")
2926 (insert (js2-from-clause-node-module-id n))
2927 (insert "'")))
2928
2929 (cl-defstruct (js2-try-node
2930 (:include js2-node)
2931 (:constructor nil)
2932 (:constructor make-js2-try-node (&key (type js2-TRY)
2933 (pos js2-ts-cursor)
2934 len
2935 try-block
2936 catch-clauses
2937 finally-block)))
2938 "AST node for a try-statement."
2939 try-block
2940 catch-clauses ; a Lisp list of `js2-catch-node'
2941 finally-block) ; a `js2-finally-node'
2942
2943 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2944 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2945
2946 (defun js2-visit-try-node (n v)
2947 (js2-visit-ast (js2-try-node-try-block n) v)
2948 (dolist (clause (js2-try-node-catch-clauses n))
2949 (js2-visit-ast clause v))
2950 (js2-visit-ast (js2-try-node-finally-block n) v))
2951
2952 (defun js2-print-try-node (n i)
2953 (let ((pad (js2-make-pad i))
2954 (catches (js2-try-node-catch-clauses n))
2955 (finally (js2-try-node-finally-block n)))
2956 (insert pad "try {\n")
2957 (js2-print-body (js2-try-node-try-block n) (1+ i))
2958 (insert pad "}")
2959 (when catches
2960 (dolist (catch catches)
2961 (js2-print-ast catch i)))
2962 (if finally
2963 (js2-print-ast finally i)
2964 (insert "\n"))))
2965
2966 (cl-defstruct (js2-catch-node
2967 (:include js2-scope)
2968 (:constructor nil)
2969 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2970 (pos js2-ts-cursor)
2971 len
2972 param
2973 guard-kwd
2974 guard-expr
2975 lp rp)))
2976 "AST node for a catch clause."
2977 param ; destructuring form or simple name node
2978 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2979 guard-expr ; catch condition, a `js2-node'
2980 lp ; buffer position of left-paren, nil if omitted
2981 rp) ; buffer position of right-paren, nil if omitted
2982
2983 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2984 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2985
2986 (defun js2-visit-catch-node (n v)
2987 (js2-visit-ast (js2-catch-node-param n) v)
2988 (when (js2-catch-node-guard-kwd n)
2989 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2990 (js2-visit-block n v))
2991
2992 (defun js2-print-catch-node (n i)
2993 (let ((pad (js2-make-pad i))
2994 (guard-kwd (js2-catch-node-guard-kwd n))
2995 (guard-expr (js2-catch-node-guard-expr n)))
2996 (insert " catch (")
2997 (js2-print-ast (js2-catch-node-param n) 0)
2998 (when guard-kwd
2999 (insert " if ")
3000 (js2-print-ast guard-expr 0))
3001 (insert ") {\n")
3002 (js2-print-body n (1+ i))
3003 (insert pad "}")))
3004
3005 (cl-defstruct (js2-finally-node
3006 (:include js2-node)
3007 (:constructor nil)
3008 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3009 (pos js2-ts-cursor)
3010 len body)))
3011 "AST node for a finally clause."
3012 body) ; a `js2-node', often but not always a block node
3013
3014 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3015 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3016
3017 (defun js2-visit-finally-node (n v)
3018 (js2-visit-ast (js2-finally-node-body n) v))
3019
3020 (defun js2-print-finally-node (n i)
3021 (let ((pad (js2-make-pad i)))
3022 (insert " finally {\n")
3023 (js2-print-body (js2-finally-node-body n) (1+ i))
3024 (insert pad "}\n")))
3025
3026 (cl-defstruct (js2-switch-node
3027 (:include js2-node)
3028 (:constructor nil)
3029 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3030 (pos js2-ts-cursor)
3031 len
3032 discriminant
3033 cases lp
3034 rp)))
3035 "AST node for a switch statement."
3036 discriminant ; a `js2-node' (switch expression)
3037 cases ; a Lisp list of `js2-case-node'
3038 lp ; position of open-paren for discriminant, nil if omitted
3039 rp) ; position of close-paren for discriminant, nil if omitted
3040
3041 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3042 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3043
3044 (defun js2-visit-switch-node (n v)
3045 (js2-visit-ast (js2-switch-node-discriminant n) v)
3046 (dolist (c (js2-switch-node-cases n))
3047 (js2-visit-ast c v)))
3048
3049 (defun js2-print-switch-node (n i)
3050 (let ((pad (js2-make-pad i))
3051 (cases (js2-switch-node-cases n)))
3052 (insert pad "switch (")
3053 (js2-print-ast (js2-switch-node-discriminant n) 0)
3054 (insert ") {\n")
3055 (dolist (case cases)
3056 (js2-print-ast case i))
3057 (insert pad "}\n")))
3058
3059 (cl-defstruct (js2-case-node
3060 (:include js2-block-node)
3061 (:constructor nil)
3062 (:constructor make-js2-case-node (&key (type js2-CASE)
3063 (pos js2-ts-cursor)
3064 len kids expr)))
3065 "AST node for a case clause of a switch statement."
3066 expr) ; the case expression (nil for default)
3067
3068 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3069 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3070
3071 (defun js2-visit-case-node (n v)
3072 (js2-visit-ast (js2-case-node-expr n) v)
3073 (js2-visit-block n v))
3074
3075 (defun js2-print-case-node (n i)
3076 (let ((pad (js2-make-pad i))
3077 (expr (js2-case-node-expr n)))
3078 (insert pad)
3079 (if (null expr)
3080 (insert "default:\n")
3081 (insert "case ")
3082 (js2-print-ast expr 0)
3083 (insert ":\n"))
3084 (dolist (kid (js2-case-node-kids n))
3085 (js2-print-ast kid (1+ i)))))
3086
3087 (cl-defstruct (js2-throw-node
3088 (:include js2-node)
3089 (:constructor nil)
3090 (:constructor make-js2-throw-node (&key (type js2-THROW)
3091 (pos js2-ts-cursor)
3092 len expr)))
3093 "AST node for a throw statement."
3094 expr) ; the expression to throw
3095
3096 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3097 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3098
3099 (defun js2-visit-throw-node (n v)
3100 (js2-visit-ast (js2-throw-node-expr n) v))
3101
3102 (defun js2-print-throw-node (n i)
3103 (insert (js2-make-pad i) "throw ")
3104 (js2-print-ast (js2-throw-node-expr n) 0)
3105 (insert ";\n"))
3106
3107 (cl-defstruct (js2-with-node
3108 (:include js2-node)
3109 (:constructor nil)
3110 (:constructor make-js2-with-node (&key (type js2-WITH)
3111 (pos js2-ts-cursor)
3112 len object
3113 body lp rp)))
3114 "AST node for a with-statement."
3115 object
3116 body
3117 lp ; buffer position of left-paren around object, nil if omitted
3118 rp) ; buffer position of right-paren around object, nil if omitted
3119
3120 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3121 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3122
3123 (defun js2-visit-with-node (n v)
3124 (js2-visit-ast (js2-with-node-object n) v)
3125 (js2-visit-ast (js2-with-node-body n) v))
3126
3127 (defun js2-print-with-node (n i)
3128 (let ((pad (js2-make-pad i)))
3129 (insert pad "with (")
3130 (js2-print-ast (js2-with-node-object n) 0)
3131 (insert ") {\n")
3132 (js2-print-body (js2-with-node-body n) (1+ i))
3133 (insert pad "}\n")))
3134
3135 (cl-defstruct (js2-label-node
3136 (:include js2-node)
3137 (:constructor nil)
3138 (:constructor make-js2-label-node (&key (type js2-LABEL)
3139 (pos js2-ts-cursor)
3140 len name)))
3141 "AST node for a statement label or case label."
3142 name ; a string
3143 loop) ; for validating and code-generating continue-to-label
3144
3145 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3146 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3147
3148 (defun js2-print-label (n i)
3149 (insert (js2-make-pad i)
3150 (js2-label-node-name n)
3151 ":\n"))
3152
3153 (cl-defstruct (js2-labeled-stmt-node
3154 (:include js2-node)
3155 (:constructor nil)
3156 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3157 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3158 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3159 (pos js2-ts-cursor)
3160 len labels stmt)))
3161 "AST node for a statement with one or more labels.
3162 Multiple labels for a statement are collapsed into the labels field."
3163 labels ; Lisp list of `js2-label-node'
3164 stmt) ; the statement these labels are for
3165
3166 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3167 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3168
3169 (defun js2-get-label-by-name (lbl-stmt name)
3170 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3171 Returns nil if no such label is in the list."
3172 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3173 result)
3174 (while (and label-list (not result))
3175 (if (string= (js2-label-node-name (car label-list)) name)
3176 (setq result (car label-list))
3177 (setq label-list (cdr label-list))))
3178 result))
3179
3180 (defun js2-visit-labeled-stmt (n v)
3181 (dolist (label (js2-labeled-stmt-node-labels n))
3182 (js2-visit-ast label v))
3183 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3184
3185 (defun js2-print-labeled-stmt (n i)
3186 (dolist (label (js2-labeled-stmt-node-labels n))
3187 (js2-print-ast label i))
3188 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3189
3190 (defun js2-labeled-stmt-node-contains (node label)
3191 "Return t if NODE contains LABEL in its label set.
3192 NODE is a `js2-labels-node'. LABEL is an identifier."
3193 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3194 if (string= label (js2-label-node-name nl))
3195 return t
3196 finally return nil))
3197
3198 (defsubst js2-labeled-stmt-node-add-label (node label)
3199 "Add a `js2-label-node' to the label set for this statement."
3200 (setf (js2-labeled-stmt-node-labels node)
3201 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3202
3203 (cl-defstruct (js2-jump-node
3204 (:include js2-node)
3205 (:constructor nil))
3206 "Abstract supertype of break and continue nodes."
3207 label ; `js2-name-node' for location of label identifier, if present
3208 target) ; target js2-labels-node or loop/switch statement
3209
3210 (defun js2-visit-jump-node (n v)
3211 ;; We don't visit the target, since it's a back-link.
3212 (js2-visit-ast (js2-jump-node-label n) v))
3213
3214 (cl-defstruct (js2-break-node
3215 (:include js2-jump-node)
3216 (:constructor nil)
3217 (:constructor make-js2-break-node (&key (type js2-BREAK)
3218 (pos js2-ts-cursor)
3219 len label target)))
3220 "AST node for a break statement.
3221 The label field is a `js2-name-node', possibly nil, for the named label
3222 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3223 is the target of the break - a label node or enclosing loop/switch statement.")
3224
3225 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3226 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3227
3228 (defun js2-print-break-node (n i)
3229 (insert (js2-make-pad i) "break")
3230 (when (js2-break-node-label n)
3231 (insert " ")
3232 (js2-print-ast (js2-break-node-label n) 0))
3233 (insert ";\n"))
3234
3235 (cl-defstruct (js2-continue-node
3236 (:include js2-jump-node)
3237 (:constructor nil)
3238 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3239 (pos js2-ts-cursor)
3240 len label target)))
3241 "AST node for a continue statement.
3242 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3243 It is nil if continue specifies no label. The target field is the jump target:
3244 a `js2-label-node' or the innermost enclosing loop.")
3245
3246 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3247 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3248
3249 (defun js2-print-continue-node (n i)
3250 (insert (js2-make-pad i) "continue")
3251 (when (js2-continue-node-label n)
3252 (insert " ")
3253 (js2-print-ast (js2-continue-node-label n) 0))
3254 (insert ";\n"))
3255
3256 (cl-defstruct (js2-function-node
3257 (:include js2-script-node)
3258 (:constructor nil)
3259 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3260 (pos js2-ts-cursor)
3261 len
3262 (ftype 'FUNCTION)
3263 (form 'FUNCTION_STATEMENT)
3264 (name "")
3265 params rest-p
3266 body
3267 generator-type
3268 async
3269 lp rp)))
3270 "AST node for a function declaration.
3271 The `params' field is a Lisp list of nodes. Each node is either a simple
3272 `js2-name-node', or if it's a destructuring-assignment parameter, a
3273 `js2-array-node' or `js2-object-node'."
3274 ftype ; FUNCTION, GETTER or SETTER
3275 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3276 name ; function name (a `js2-name-node', or nil if anonymous)
3277 params ; a Lisp list of destructuring forms or simple name nodes
3278 rest-p ; if t, the last parameter is rest parameter
3279 body ; a `js2-block-node' or expression node (1.8 only)
3280 lp ; position of arg-list open-paren, or nil if omitted
3281 rp ; position of arg-list close-paren, or nil if omitted
3282 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3283 needs-activation ; t if we need an activation object for this frame
3284 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3285 async ; t if the function is defined as `async function`
3286 member-expr) ; nonstandard Ecma extension from Rhino
3287
3288 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3289 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3290
3291 (defun js2-visit-function-node (n v)
3292 (js2-visit-ast (js2-function-node-name n) v)
3293 (dolist (p (js2-function-node-params n))
3294 (js2-visit-ast p v))
3295 (js2-visit-ast (js2-function-node-body n) v))
3296
3297 (defun js2-print-function-node (n i)
3298 (let* ((pad (js2-make-pad i))
3299 (method (js2-node-get-prop n 'METHOD_TYPE))
3300 (name (or (js2-function-node-name n)
3301 (js2-function-node-member-expr n)))
3302 (params (js2-function-node-params n))
3303 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3304 (rest-p (js2-function-node-rest-p n))
3305 (body (js2-function-node-body n))
3306 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3307 (unless method
3308 (insert pad)
3309 (when (js2-function-node-async n) (insert "async "))
3310 (unless arrow (insert "function"))
3311 (when (eq (js2-function-node-generator-type n) 'STAR)
3312 (insert "*")))
3313 (when name
3314 (insert " ")
3315 (js2-print-ast name 0))
3316 (insert "(")
3317 (cl-loop with len = (length params)
3318 for param in params
3319 for count from 1
3320 do
3321 (when (and rest-p (= count len))
3322 (insert "..."))
3323 (js2-print-ast param 0)
3324 (when (< count len)
3325 (insert ", ")))
3326 (insert ") ")
3327 (when arrow
3328 (insert "=> "))
3329 (insert "{")
3330 ;; TODO: fix this to be smarter about indenting, etc.
3331 (unless expr
3332 (insert "\n"))
3333 (if (js2-block-node-p body)
3334 (js2-print-body body (1+ i))
3335 (js2-print-ast body 0))
3336 (insert pad "}")
3337 (unless expr
3338 (insert "\n"))))
3339
3340 (defun js2-function-name (node)
3341 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3342 (and (js2-function-node-name node)
3343 (js2-name-node-name (js2-function-node-name node))))
3344
3345 ;; Having this be an expression node makes it more flexible.
3346 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3347 ;; that work better if you assume it's an expression. Whenever we have
3348 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3349 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3350 (cl-defstruct (js2-var-decl-node
3351 (:include js2-node)
3352 (:constructor nil)
3353 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3354 (pos (js2-current-token-beg))
3355 len kids
3356 decl-type)))
3357 "AST node for a variable declaration list (VAR, CONST or LET).
3358 The node bounds differ depending on the declaration type. For VAR or
3359 CONST declarations, the bounds include the var/const keyword. For LET
3360 declarations, the node begins at the position of the first child."
3361 kids ; a Lisp list of `js2-var-init-node' structs.
3362 decl-type) ; js2-VAR, js2-CONST or js2-LET
3363
3364 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3365 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3366
3367 (defun js2-visit-var-decl (n v)
3368 (dolist (kid (js2-var-decl-node-kids n))
3369 (js2-visit-ast kid v)))
3370
3371 (defun js2-print-var-decl (n i)
3372 (let ((pad (js2-make-pad i))
3373 (tt (js2-var-decl-node-decl-type n)))
3374 (insert pad)
3375 (insert (cond
3376 ((= tt js2-VAR) "var ")
3377 ((= tt js2-LET) "let ")
3378 ((= tt js2-CONST) "const ")
3379 (t
3380 (error "malformed var-decl node"))))
3381 (cl-loop with kids = (js2-var-decl-node-kids n)
3382 with len = (length kids)
3383 for kid in kids
3384 for count from 1
3385 do
3386 (js2-print-ast kid 0)
3387 (if (< count len)
3388 (insert ", ")))))
3389
3390 (cl-defstruct (js2-var-init-node
3391 (:include js2-node)
3392 (:constructor nil)
3393 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3394 (pos js2-ts-cursor)
3395 len target
3396 initializer)))
3397 "AST node for a variable declaration.
3398 The type field will be js2-CONST for a const decl."
3399 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3400 initializer) ; initializer expression, a `js2-node'
3401
3402 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3403 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3404
3405 (defun js2-visit-var-init-node (n v)
3406 (js2-visit-ast (js2-var-init-node-target n) v)
3407 (js2-visit-ast (js2-var-init-node-initializer n) v))
3408
3409 (defun js2-print-var-init-node (n i)
3410 (let ((pad (js2-make-pad i))
3411 (name (js2-var-init-node-target n))
3412 (init (js2-var-init-node-initializer n)))
3413 (insert pad)
3414 (js2-print-ast name 0)
3415 (when init
3416 (insert " = ")
3417 (js2-print-ast init 0))))
3418
3419 (cl-defstruct (js2-cond-node
3420 (:include js2-node)
3421 (:constructor nil)
3422 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3423 (pos js2-ts-cursor)
3424 len
3425 test-expr
3426 true-expr
3427 false-expr
3428 q-pos c-pos)))
3429 "AST node for the ternary operator"
3430 test-expr
3431 true-expr
3432 false-expr
3433 q-pos ; buffer position of ?
3434 c-pos) ; buffer position of :
3435
3436 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3437 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3438
3439 (defun js2-visit-cond-node (n v)
3440 (js2-visit-ast (js2-cond-node-test-expr n) v)
3441 (js2-visit-ast (js2-cond-node-true-expr n) v)
3442 (js2-visit-ast (js2-cond-node-false-expr n) v))
3443
3444 (defun js2-print-cond-node (n i)
3445 (let ((pad (js2-make-pad i)))
3446 (insert pad)
3447 (js2-print-ast (js2-cond-node-test-expr n) 0)
3448 (insert " ? ")
3449 (js2-print-ast (js2-cond-node-true-expr n) 0)
3450 (insert " : ")
3451 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3452
3453 (cl-defstruct (js2-infix-node
3454 (:include js2-node)
3455 (:constructor nil)
3456 (:constructor make-js2-infix-node (&key type
3457 (pos js2-ts-cursor)
3458 len op-pos
3459 left right)))
3460 "Represents infix expressions.
3461 Includes assignment ops like `|=', and the comma operator.
3462 The type field inherited from `js2-node' holds the operator."
3463 op-pos ; buffer position where operator begins
3464 left ; any `js2-node'
3465 right) ; any `js2-node'
3466
3467 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3468 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3469
3470 (defun js2-visit-infix-node (n v)
3471 (js2-visit-ast (js2-infix-node-left n) v)
3472 (js2-visit-ast (js2-infix-node-right n) v))
3473
3474 (defconst js2-operator-tokens
3475 (let ((table (make-hash-table :test 'eq))
3476 (tokens
3477 (list (cons js2-IN "in")
3478 (cons js2-TYPEOF "typeof")
3479 (cons js2-INSTANCEOF "instanceof")
3480 (cons js2-DELPROP "delete")
3481 (cons js2-AWAIT "await")
3482 (cons js2-VOID "void")
3483 (cons js2-COMMA ",")
3484 (cons js2-COLON ":")
3485 (cons js2-OR "||")
3486 (cons js2-AND "&&")
3487 (cons js2-INC "++")
3488 (cons js2-DEC "--")
3489 (cons js2-BITOR "|")
3490 (cons js2-BITXOR "^")
3491 (cons js2-BITAND "&")
3492 (cons js2-EQ "==")
3493 (cons js2-NE "!=")
3494 (cons js2-LT "<")
3495 (cons js2-LE "<=")
3496 (cons js2-GT ">")
3497 (cons js2-GE ">=")
3498 (cons js2-LSH "<<")
3499 (cons js2-RSH ">>")
3500 (cons js2-URSH ">>>")
3501 (cons js2-ADD "+") ; infix plus
3502 (cons js2-SUB "-") ; infix minus
3503 (cons js2-MUL "*")
3504 (cons js2-DIV "/")
3505 (cons js2-MOD "%")
3506 (cons js2-NOT "!")
3507 (cons js2-BITNOT "~")
3508 (cons js2-POS "+") ; unary plus
3509 (cons js2-NEG "-") ; unary minus
3510 (cons js2-TRIPLEDOT "...")
3511 (cons js2-SHEQ "===") ; shallow equality
3512 (cons js2-SHNE "!==") ; shallow inequality
3513 (cons js2-ASSIGN "=")
3514 (cons js2-ASSIGN_BITOR "|=")
3515 (cons js2-ASSIGN_BITXOR "^=")
3516 (cons js2-ASSIGN_BITAND "&=")
3517 (cons js2-ASSIGN_LSH "<<=")
3518 (cons js2-ASSIGN_RSH ">>=")
3519 (cons js2-ASSIGN_URSH ">>>=")
3520 (cons js2-ASSIGN_ADD "+=")
3521 (cons js2-ASSIGN_SUB "-=")
3522 (cons js2-ASSIGN_MUL "*=")
3523 (cons js2-ASSIGN_DIV "/=")
3524 (cons js2-ASSIGN_MOD "%="))))
3525 (cl-loop for (k . v) in tokens do
3526 (puthash k v table))
3527 table))
3528
3529 (defun js2-print-infix-node (n i)
3530 (let* ((tt (js2-node-type n))
3531 (op (gethash tt js2-operator-tokens)))
3532 (unless op
3533 (error "unrecognized infix operator %s" (js2-node-type n)))
3534 (insert (js2-make-pad i))
3535 (js2-print-ast (js2-infix-node-left n) 0)
3536 (unless (= tt js2-COMMA)
3537 (insert " "))
3538 (insert op)
3539 (insert " ")
3540 (js2-print-ast (js2-infix-node-right n) 0)))
3541
3542 (cl-defstruct (js2-assign-node
3543 (:include js2-infix-node)
3544 (:constructor nil)
3545 (:constructor make-js2-assign-node (&key type
3546 (pos js2-ts-cursor)
3547 len op-pos
3548 left right)))
3549 "Represents any assignment.
3550 The type field holds the actual assignment operator.")
3551
3552 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3553 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3554
3555 (cl-defstruct (js2-unary-node
3556 (:include js2-node)
3557 (:constructor nil)
3558 (:constructor make-js2-unary-node (&key type ; required
3559 (pos js2-ts-cursor)
3560 len operand)))
3561 "AST node type for unary operator nodes.
3562 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3563 TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
3564 property is added if the operator follows the operand."
3565 operand) ; a `js2-node' expression
3566
3567 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3568 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3569
3570 (defun js2-visit-unary-node (n v)
3571 (js2-visit-ast (js2-unary-node-operand n) v))
3572
3573 (defun js2-print-unary-node (n i)
3574 (let* ((tt (js2-node-type n))
3575 (op (gethash tt js2-operator-tokens))
3576 (postfix (js2-node-get-prop n 'postfix)))
3577 (unless op
3578 (error "unrecognized unary operator %s" tt))
3579 (insert (js2-make-pad i))
3580 (unless postfix
3581 (insert op))
3582 (if (or (= tt js2-TYPEOF)
3583 (= tt js2-DELPROP)
3584 (= tt js2-AWAIT)
3585 (= tt js2-VOID))
3586 (insert " "))
3587 (js2-print-ast (js2-unary-node-operand n) 0)
3588 (when postfix
3589 (insert op))))
3590
3591 (cl-defstruct (js2-let-node
3592 (:include js2-scope)
3593 (:constructor nil)
3594 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3595 (pos (js2-current-token-beg))
3596 len vars body
3597 lp rp)))
3598 "AST node for a let expression or a let statement.
3599 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3600 vars ; a `js2-var-decl-node'
3601 body ; a `js2-node' representing the expression or body block
3602 lp
3603 rp)
3604
3605 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3606 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3607
3608 (defun js2-visit-let-node (n v)
3609 (js2-visit-ast (js2-let-node-vars n) v)
3610 (js2-visit-ast (js2-let-node-body n) v))
3611
3612 (defun js2-print-let-node (n i)
3613 (insert (js2-make-pad i) "let (")
3614 (let ((p (point)))
3615 (js2-print-ast (js2-let-node-vars n) 0)
3616 (delete-region p (+ p 4)))
3617 (insert ") ")
3618 (js2-print-ast (js2-let-node-body n) i))
3619
3620 (cl-defstruct (js2-keyword-node
3621 (:include js2-node)
3622 (:constructor nil)
3623 (:constructor make-js2-keyword-node (&key type
3624 (pos (js2-current-token-beg))
3625 (len (- js2-ts-cursor pos)))))
3626 "AST node representing a literal keyword such as `null'.
3627 Used for `null', `this', `true', `false' and `debugger'.
3628 The node type is set to js2-NULL, js2-THIS, etc.")
3629
3630 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3631 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3632
3633 (defun js2-print-keyword-node (n i)
3634 (insert (js2-make-pad i)
3635 (let ((tt (js2-node-type n)))
3636 (cond
3637 ((= tt js2-THIS) "this")
3638 ((= tt js2-SUPER) "super")
3639 ((= tt js2-NULL) "null")
3640 ((= tt js2-TRUE) "true")
3641 ((= tt js2-FALSE) "false")
3642 ((= tt js2-DEBUGGER) "debugger")
3643 (t (error "Invalid keyword literal type: %d" tt))))))
3644
3645 (defsubst js2-this-or-super-node-p (node)
3646 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3647 (let ((type (js2-node-type node)))
3648 (or (eq type js2-THIS) (eq type js2-SUPER))))
3649
3650 (cl-defstruct (js2-new-node
3651 (:include js2-node)
3652 (:constructor nil)
3653 (:constructor make-js2-new-node (&key (type js2-NEW)
3654 (pos (js2-current-token-beg))
3655 len target
3656 args initializer
3657 lp rp)))
3658 "AST node for new-expression such as new Foo()."
3659 target ; an identifier or reference
3660 args ; a Lisp list of argument nodes
3661 lp ; position of left-paren, nil if omitted
3662 rp ; position of right-paren, nil if omitted
3663 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3664
3665 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3666 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3667
3668 (defun js2-visit-new-node (n v)
3669 (js2-visit-ast (js2-new-node-target n) v)
3670 (dolist (arg (js2-new-node-args n))
3671 (js2-visit-ast arg v))
3672 (js2-visit-ast (js2-new-node-initializer n) v))
3673
3674 (defun js2-print-new-node (n i)
3675 (insert (js2-make-pad i) "new ")
3676 (js2-print-ast (js2-new-node-target n))
3677 (insert "(")
3678 (js2-print-list (js2-new-node-args n))
3679 (insert ")")
3680 (when (js2-new-node-initializer n)
3681 (insert " ")
3682 (js2-print-ast (js2-new-node-initializer n))))
3683
3684 (cl-defstruct (js2-name-node
3685 (:include js2-node)
3686 (:constructor nil)
3687 (:constructor make-js2-name-node (&key (type js2-NAME)
3688 (pos (js2-current-token-beg))
3689 (len (- js2-ts-cursor
3690 (js2-current-token-beg)))
3691 (name (js2-current-token-string)))))
3692 "AST node for a JavaScript identifier"
3693 name ; a string
3694 scope) ; a `js2-scope' (optional, used for codegen)
3695
3696 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3697 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3698
3699 (defun js2-print-name-node (n i)
3700 (insert (js2-make-pad i)
3701 (js2-name-node-name n)))
3702
3703 (defsubst js2-name-node-length (node)
3704 "Return identifier length of NODE, a `js2-name-node'.
3705 Returns 0 if NODE is nil or its identifier field is nil."
3706 (if node
3707 (length (js2-name-node-name node))
3708 0))
3709
3710 (cl-defstruct (js2-number-node
3711 (:include js2-node)
3712 (:constructor nil)
3713 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3714 (pos (js2-current-token-beg))
3715 (len (- js2-ts-cursor
3716 (js2-current-token-beg)))
3717 (value (js2-current-token-string))
3718 (num-value (js2-token-number
3719 (js2-current-token)))
3720 (num-base (js2-token-number-base
3721 (js2-current-token)))
3722 (legacy-octal-p (js2-token-number-legacy-octal-p
3723 (js2-current-token))))))
3724 "AST node for a number literal."
3725 value ; the original string, e.g. "6.02e23"
3726 num-value ; the parsed number value
3727 num-base ; the number's base
3728 legacy-octal-p) ; whether the number is a legacy octal (0123 instead of 0o123)
3729
3730 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3731 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3732
3733 (defun js2-print-number-node (n i)
3734 (insert (js2-make-pad i)
3735 (number-to-string (js2-number-node-num-value n))))
3736
3737 (cl-defstruct (js2-regexp-node
3738 (:include js2-node)
3739 (:constructor nil)
3740 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3741 (pos (js2-current-token-beg))
3742 (len (- js2-ts-cursor
3743 (js2-current-token-beg)))
3744 value flags)))
3745 "AST node for a regular expression literal."
3746 value ; the regexp string, without // delimiters
3747 flags) ; a string of flags, e.g. `mi'.
3748
3749 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3750 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3751
3752 (defun js2-print-regexp (n i)
3753 (insert (js2-make-pad i)
3754 "/"
3755 (js2-regexp-node-value n)
3756 "/")
3757 (if (js2-regexp-node-flags n)
3758 (insert (js2-regexp-node-flags n))))
3759
3760 (cl-defstruct (js2-string-node
3761 (:include js2-node)
3762 (:constructor nil)
3763 (:constructor make-js2-string-node (&key (type js2-STRING)
3764 (pos (js2-current-token-beg))
3765 (len (- js2-ts-cursor
3766 (js2-current-token-beg)))
3767 (value (js2-current-token-string)))))
3768 "String literal.
3769 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3770 You can tell the quote type by looking at the first character."
3771 value) ; the characters of the string, including the quotes
3772
3773 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3774 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3775
3776 (defun js2-print-string-node (n i)
3777 (insert (js2-make-pad i)
3778 (js2-node-string n)))
3779
3780 (cl-defstruct (js2-template-node
3781 (:include js2-node)
3782 (:constructor nil)
3783 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3784 beg len kids)))
3785 "Template literal."
3786 kids) ; `js2-string-node' is used for string segments, other nodes
3787 ; for substitutions inside.
3788
3789 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3790 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3791
3792 (defun js2-visit-template (n callback)
3793 (dolist (kid (js2-template-node-kids n))
3794 (js2-visit-ast kid callback)))
3795
3796 (defun js2-print-template (n i)
3797 (insert (js2-make-pad i))
3798 (dolist (kid (js2-template-node-kids n))
3799 (if (js2-string-node-p kid)
3800 (insert (js2-node-string kid))
3801 (js2-print-ast kid))))
3802
3803 (cl-defstruct (js2-tagged-template-node
3804 (:include js2-node)
3805 (:constructor nil)
3806 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3807 beg len tag template)))
3808 "Tagged template literal."
3809 tag ; `js2-node' with the tag expression.
3810 template) ; `js2-template-node' with the template.
3811
3812 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3813 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3814
3815 (defun js2-visit-tagged-template (n callback)
3816 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3817 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3818
3819 (defun js2-print-tagged-template (n i)
3820 (insert (js2-make-pad i))
3821 (js2-print-ast (js2-tagged-template-node-tag n))
3822 (js2-print-ast (js2-tagged-template-node-template n)))
3823
3824 (cl-defstruct (js2-array-node
3825 (:include js2-node)
3826 (:constructor nil)
3827 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3828 (pos js2-ts-cursor)
3829 len elems)))
3830 "AST node for an array literal."
3831 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3832
3833 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3834 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3835
3836 (defun js2-visit-array-node (n v)
3837 (dolist (e (js2-array-node-elems n))
3838 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3839
3840 (defun js2-print-array-node (n i)
3841 (insert (js2-make-pad i) "[")
3842 (let ((elems (js2-array-node-elems n)))
3843 (js2-print-list elems)
3844 (when (and elems (null (car (last elems))))
3845 (insert ",")))
3846 (insert "]"))
3847
3848 (cl-defstruct (js2-object-node
3849 (:include js2-node)
3850 (:constructor nil)
3851 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3852 (pos js2-ts-cursor)
3853 len
3854 elems)))
3855 "AST node for an object literal expression.
3856 `elems' is a list of `js2-object-prop-node'."
3857 elems)
3858
3859 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3860 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3861
3862 (defun js2-visit-object-node (n v)
3863 (dolist (e (js2-object-node-elems n))
3864 (js2-visit-ast e v)))
3865
3866 (defun js2-print-object-node (n i)
3867 (insert (js2-make-pad i) "{")
3868 (js2-print-list (js2-object-node-elems n))
3869 (insert "}"))
3870
3871 (cl-defstruct (js2-class-node
3872 (:include js2-object-node)
3873 (:constructor nil)
3874 (:constructor make-js2-class-node (&key (type js2-CLASS)
3875 (pos js2-ts-cursor)
3876 (form 'CLASS_STATEMENT)
3877 (name "")
3878 extends len elems)))
3879 "AST node for an class expression.
3880 `elems' is a list of `js2-object-prop-node', and `extends' is an
3881 optional `js2-expr-node'"
3882 form ; CLASS_{STATEMENT|EXPRESSION}
3883 name ; class name (a `js2-node-name', or nil if anonymous)
3884 extends ; class heritage (a `js2-expr-node', or nil if none)
3885 )
3886
3887 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3888 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3889
3890 (defun js2-visit-class-node (n v)
3891 (js2-visit-ast (js2-class-node-name n) v)
3892 (js2-visit-ast (js2-class-node-extends n) v)
3893 (dolist (e (js2-class-node-elems n))
3894 (js2-visit-ast e v)))
3895
3896 (defun js2-print-class-node (n i)
3897 (let* ((pad (js2-make-pad i))
3898 (name (js2-class-node-name n))
3899 (extends (js2-class-node-extends n))
3900 (elems (js2-class-node-elems n)))
3901 (insert pad "class")
3902 (when name
3903 (insert " ")
3904 (js2-print-ast name 0))
3905 (when extends
3906 (insert " extends ")
3907 (js2-print-ast extends))
3908 (insert " {")
3909 (dolist (elem elems)
3910 (insert "\n")
3911 (if (js2-node-get-prop elem 'STATIC)
3912 (progn (insert (js2-make-pad (1+ i)) "static ")
3913 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3914 (js2-print-ast elem (1+ i))))
3915 (insert "\n" pad "}")))
3916
3917 (cl-defstruct (js2-computed-prop-name-node
3918 (:include js2-node)
3919 (:constructor nil)
3920 (:constructor make-js2-computed-prop-name-node
3921 (&key
3922 (type js2-LB)
3923 expr
3924 (pos (js2-current-token-beg))
3925 (len (- js2-ts-cursor
3926 (js2-current-token-beg))))))
3927 "AST node for a `ComputedPropertyName'."
3928 expr)
3929
3930 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3931 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3932
3933 (defun js2-visit-computed-prop-name-node (n v)
3934 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3935
3936 (defun js2-print-computed-prop-name-node (n i)
3937 (insert (js2-make-pad i) "[")
3938 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3939 (insert "]"))
3940
3941 (cl-defstruct (js2-object-prop-node
3942 (:include js2-infix-node)
3943 (:constructor nil)
3944 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3945 (pos js2-ts-cursor)
3946 len left
3947 right op-pos)))
3948 "AST node for an object literal prop:value entry.
3949 The `left' field is the property: a name node, string node,
3950 number node or expression node. The `right' field is a
3951 `js2-node' representing the initializer value. If the property
3952 is abbreviated, the node's `SHORTHAND' property is non-nil and
3953 both fields have the same value.")
3954
3955 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3956 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3957
3958 (defun js2-print-object-prop-node (n i)
3959 (let* ((left (js2-object-prop-node-left n))
3960 (right (js2-object-prop-node-right n)))
3961 (js2-print-ast left i)
3962 (if (not (js2-node-get-prop n 'SHORTHAND))
3963 (progn
3964 (insert ": ")
3965 (js2-print-ast right 0)))))
3966
3967 (cl-defstruct (js2-method-node
3968 (:include js2-infix-node)
3969 (:constructor nil)
3970 (:constructor make-js2-method-node (&key (pos js2-ts-cursor)
3971 len left right)))
3972 "AST node for a method in an object literal or a class body.
3973 The `left' field is the `js2-name-node' naming the method.
3974 The `right' field is always an anonymous `js2-function-node' with a node
3975 property `METHOD_TYPE' set to 'GET or 'SET. ")
3976
3977 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3978 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3979
3980 (defun js2-print-method (n i)
3981 (let* ((pad (js2-make-pad i))
3982 (left (js2-method-node-left n))
3983 (right (js2-method-node-right n))
3984 (type (js2-node-get-prop right 'METHOD_TYPE)))
3985 (insert pad)
3986 (when type
3987 (insert (cdr (assoc type '((GET . "get ")
3988 (SET . "set ")
3989 (ASYNC . "async ")
3990 (FUNCTION . ""))))))
3991 (when (and (js2-function-node-p right)
3992 (eq 'STAR (js2-function-node-generator-type right)))
3993 (insert "*"))
3994 (js2-print-ast left 0)
3995 (js2-print-ast right 0)))
3996
3997 (cl-defstruct (js2-prop-get-node
3998 (:include js2-infix-node)
3999 (:constructor nil)
4000 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4001 (pos js2-ts-cursor)
4002 len left right)))
4003 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4004
4005 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4006 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4007
4008 (defun js2-visit-prop-get-node (n v)
4009 (js2-visit-ast (js2-prop-get-node-left n) v)
4010 (js2-visit-ast (js2-prop-get-node-right n) v))
4011
4012 (defun js2-print-prop-get-node (n i)
4013 (insert (js2-make-pad i))
4014 (js2-print-ast (js2-prop-get-node-left n) 0)
4015 (insert ".")
4016 (js2-print-ast (js2-prop-get-node-right n) 0))
4017
4018 (cl-defstruct (js2-elem-get-node
4019 (:include js2-node)
4020 (:constructor nil)
4021 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4022 (pos js2-ts-cursor)
4023 len target element
4024 lb rb)))
4025 "AST node for an array index expression such as foo[bar]."
4026 target ; a `js2-node' - the expression preceding the "."
4027 element ; a `js2-node' - the expression in brackets
4028 lb ; position of left-bracket, nil if omitted
4029 rb) ; position of right-bracket, nil if omitted
4030
4031 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4032 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4033
4034 (defun js2-visit-elem-get-node (n v)
4035 (js2-visit-ast (js2-elem-get-node-target n) v)
4036 (js2-visit-ast (js2-elem-get-node-element n) v))
4037
4038 (defun js2-print-elem-get-node (n i)
4039 (insert (js2-make-pad i))
4040 (js2-print-ast (js2-elem-get-node-target n) 0)
4041 (insert "[")
4042 (js2-print-ast (js2-elem-get-node-element n) 0)
4043 (insert "]"))
4044
4045 (cl-defstruct (js2-call-node
4046 (:include js2-node)
4047 (:constructor nil)
4048 (:constructor make-js2-call-node (&key (type js2-CALL)
4049 (pos js2-ts-cursor)
4050 len target args
4051 lp rp)))
4052 "AST node for a JavaScript function call."
4053 target ; a `js2-node' evaluating to the function to call
4054 args ; a Lisp list of `js2-node' arguments
4055 lp ; position of open-paren, or nil if missing
4056 rp) ; position of close-paren, or nil if missing
4057
4058 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4059 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4060
4061 (defun js2-visit-call-node (n v)
4062 (js2-visit-ast (js2-call-node-target n) v)
4063 (dolist (arg (js2-call-node-args n))
4064 (js2-visit-ast arg v)))
4065
4066 (defun js2-print-call-node (n i)
4067 (insert (js2-make-pad i))
4068 (js2-print-ast (js2-call-node-target n) 0)
4069 (insert "(")
4070 (js2-print-list (js2-call-node-args n))
4071 (insert ")"))
4072
4073 (cl-defstruct (js2-yield-node
4074 (:include js2-node)
4075 (:constructor nil)
4076 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4077 (pos js2-ts-cursor)
4078 len value star-p)))
4079 "AST node for yield statement or expression."
4080 star-p ; whether it's yield*
4081 value) ; optional: value to be yielded
4082
4083 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4084 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4085
4086 (defun js2-visit-yield-node (n v)
4087 (js2-visit-ast (js2-yield-node-value n) v))
4088
4089 (defun js2-print-yield-node (n i)
4090 (insert (js2-make-pad i))
4091 (insert "yield")
4092 (when (js2-yield-node-star-p n)
4093 (insert "*"))
4094 (when (js2-yield-node-value n)
4095 (insert " ")
4096 (js2-print-ast (js2-yield-node-value n) 0)))
4097
4098 (cl-defstruct (js2-paren-node
4099 (:include js2-node)
4100 (:constructor nil)
4101 (:constructor make-js2-paren-node (&key (type js2-LP)
4102 (pos js2-ts-cursor)
4103 len expr)))
4104 "AST node for a parenthesized expression.
4105 In particular, used when the parens are syntactically optional,
4106 as opposed to required parens such as those enclosing an if-conditional."
4107 expr) ; `js2-node'
4108
4109 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4110 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4111
4112 (defun js2-visit-paren-node (n v)
4113 (js2-visit-ast (js2-paren-node-expr n) v))
4114
4115 (defun js2-print-paren-node (n i)
4116 (insert (js2-make-pad i))
4117 (insert "(")
4118 (js2-print-ast (js2-paren-node-expr n) 0)
4119 (insert ")"))
4120
4121 (cl-defstruct (js2-comp-node
4122 (:include js2-scope)
4123 (:constructor nil)
4124 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4125 (pos js2-ts-cursor)
4126 len result
4127 loops filters
4128 form)))
4129 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4130 result ; result expression (just after left-bracket)
4131 loops ; a Lisp list of `js2-comp-loop-node'
4132 filters ; a Lisp list of guard/filter expressions
4133 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4134 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4135 )
4136
4137 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4138 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4139
4140 (defun js2-visit-comp-node (n v)
4141 (js2-visit-ast (js2-comp-node-result n) v)
4142 (dolist (l (js2-comp-node-loops n))
4143 (js2-visit-ast l v))
4144 (dolist (f (js2-comp-node-filters n))
4145 (js2-visit-ast f v)))
4146
4147 (defun js2-print-comp-node (n i)
4148 (let ((pad (js2-make-pad i))
4149 (result (js2-comp-node-result n))
4150 (loops (js2-comp-node-loops n))
4151 (filters (js2-comp-node-filters n))
4152 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4153 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4154 (insert pad (if gen-p "(" "["))
4155 (when legacy-p
4156 (js2-print-ast result 0))
4157 (dolist (l loops)
4158 (when legacy-p
4159 (insert " "))
4160 (js2-print-ast l 0)
4161 (unless legacy-p
4162 (insert " ")))
4163 (dolist (f filters)
4164 (when legacy-p
4165 (insert " "))
4166 (insert "if (")
4167 (js2-print-ast f 0)
4168 (insert ")")
4169 (unless legacy-p
4170 (insert " ")))
4171 (unless legacy-p
4172 (js2-print-ast result 0))
4173 (insert (if gen-p ")" "]"))))
4174
4175 (cl-defstruct (js2-comp-loop-node
4176 (:include js2-for-in-node)
4177 (:constructor nil)
4178 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4179 (pos js2-ts-cursor)
4180 len iterator
4181 object in-pos
4182 foreach-p
4183 each-pos
4184 forof-p
4185 lp rp)))
4186 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4187
4188 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4189 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4190
4191 (defun js2-visit-comp-loop (n v)
4192 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4193 (js2-visit-ast (js2-comp-loop-node-object n) v))
4194
4195 (defun js2-print-comp-loop (n _i)
4196 (insert "for ")
4197 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4198 (insert "(")
4199 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4200 (insert (if (js2-comp-loop-node-forof-p n)
4201 " of " " in "))
4202 (js2-print-ast (js2-comp-loop-node-object n) 0)
4203 (insert ")"))
4204
4205 (cl-defstruct (js2-empty-expr-node
4206 (:include js2-node)
4207 (:constructor nil)
4208 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4209 (pos (js2-current-token-beg))
4210 len)))
4211 "AST node for an empty expression.")
4212
4213 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4214 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4215
4216 (cl-defstruct (js2-xml-node
4217 (:include js2-block-node)
4218 (:constructor nil)
4219 (:constructor make-js2-xml-node (&key (type js2-XML)
4220 (pos (js2-current-token-beg))
4221 len kids)))
4222 "AST node for initial parse of E4X literals.
4223 The kids field is a list of XML fragments, each a `js2-string-node' or
4224 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4225
4226 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4227 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4228
4229 (defun js2-print-xml-node (n i)
4230 (dolist (kid (js2-xml-node-kids n))
4231 (js2-print-ast kid i)))
4232
4233 (cl-defstruct (js2-xml-js-expr-node
4234 (:include js2-xml-node)
4235 (:constructor nil)
4236 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4237 (pos js2-ts-cursor)
4238 len expr)))
4239 "AST node for an embedded JavaScript {expression} in an E4X literal.
4240 The start and end fields correspond to the curly-braces."
4241 expr) ; a `js2-expr-node' of some sort
4242
4243 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4244 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4245
4246 (defun js2-visit-xml-js-expr (n v)
4247 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4248
4249 (defun js2-print-xml-js-expr (n i)
4250 (insert (js2-make-pad i))
4251 (insert "{")
4252 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4253 (insert "}"))
4254
4255 (cl-defstruct (js2-xml-dot-query-node
4256 (:include js2-infix-node)
4257 (:constructor nil)
4258 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4259 (pos js2-ts-cursor)
4260 op-pos len left
4261 right rp)))
4262 "AST node for an E4X foo.(bar) filter expression.
4263 Note that the left-paren is automatically the character immediately
4264 following the dot (.) in the operator. No whitespace is permitted
4265 between the dot and the lp by the scanner."
4266 rp)
4267
4268 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4269 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4270
4271 (defun js2-print-xml-dot-query (n i)
4272 (insert (js2-make-pad i))
4273 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4274 (insert ".(")
4275 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4276 (insert ")"))
4277
4278 (cl-defstruct (js2-xml-ref-node
4279 (:include js2-node)
4280 (:constructor nil)) ; abstract
4281 "Base type for E4X XML attribute-access or property-get expressions.
4282 Such expressions can take a variety of forms. The general syntax has
4283 three parts:
4284
4285 - (optional) an @ (specifying an attribute access)
4286 - (optional) a namespace (a `js2-name-node') and double-colon
4287 - (required) either a `js2-name-node' or a bracketed [expression]
4288
4289 The property-name expressions (examples: ns::name, @name) are
4290 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4291 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4292
4293 This node type (or more specifically, its subclasses) will sometimes
4294 be the right-hand child of a `js2-prop-get-node' or a
4295 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4296 The `js2-xml-ref-node' may also be a standalone primary expression with
4297 no explicit target, which is valid in certain expression contexts such as
4298
4299 company..employee.(@id < 100)
4300
4301 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4302 expression whose parent is a `js2-xml-dot-query-node'."
4303 namespace
4304 at-pos
4305 colon-pos)
4306
4307 (defsubst js2-xml-ref-node-attr-access-p (node)
4308 "Return non-nil if this expression began with an @-token."
4309 (and (numberp (js2-xml-ref-node-at-pos node))
4310 (cl-plusp (js2-xml-ref-node-at-pos node))))
4311
4312 (cl-defstruct (js2-xml-prop-ref-node
4313 (:include js2-xml-ref-node)
4314 (:constructor nil)
4315 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4316 (pos (js2-current-token-beg))
4317 len propname
4318 namespace at-pos
4319 colon-pos)))
4320 "AST node for an E4X XML [expr] property-ref expression.
4321 The JavaScript syntax is an optional @, an optional ns::, and a name.
4322
4323 [ '@' ] [ name '::' ] name
4324
4325 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4326 @ns::*, @*::attr, @*::*, and @*.
4327
4328 The node starts at the @ token, if present. Otherwise it starts at the
4329 namespace name. The node bounds extend through the closing right-bracket,
4330 or if it is missing due to a syntax error, through the end of the index
4331 expression."
4332 propname)
4333
4334 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4335 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4336
4337 (defun js2-visit-xml-prop-ref-node (n v)
4338 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4339 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4340
4341 (defun js2-print-xml-prop-ref-node (n i)
4342 (insert (js2-make-pad i))
4343 (if (js2-xml-ref-node-attr-access-p n)
4344 (insert "@"))
4345 (when (js2-xml-prop-ref-node-namespace n)
4346 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4347 (insert "::"))
4348 (if (js2-xml-prop-ref-node-propname n)
4349 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4350
4351 (cl-defstruct (js2-xml-elem-ref-node
4352 (:include js2-xml-ref-node)
4353 (:constructor nil)
4354 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4355 (pos (js2-current-token-beg))
4356 len expr lb rb
4357 namespace at-pos
4358 colon-pos)))
4359 "AST node for an E4X XML [expr] member-ref expression.
4360 Syntax:
4361
4362 [ '@' ] [ name '::' ] '[' expr ']'
4363
4364 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4365
4366 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4367 is not a legal E4X XML element-ref expression, since it's already used
4368 for standard JavaScript element-get array indexing. Hence, a
4369 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4370 non-nil namespace node, or both.
4371
4372 The node starts at the @ token, if present. Otherwise it starts
4373 at the namespace name. The node bounds extend through the closing
4374 right-bracket, or if it is missing due to a syntax error, through the
4375 end of the index expression."
4376 expr ; the bracketed index expression
4377 lb
4378 rb)
4379
4380 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4381 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4382
4383 (defun js2-visit-xml-elem-ref-node (n v)
4384 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4385 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4386
4387 (defun js2-print-xml-elem-ref-node (n i)
4388 (insert (js2-make-pad i))
4389 (if (js2-xml-ref-node-attr-access-p n)
4390 (insert "@"))
4391 (when (js2-xml-elem-ref-node-namespace n)
4392 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4393 (insert "::"))
4394 (insert "[")
4395 (if (js2-xml-elem-ref-node-expr n)
4396 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4397 (insert "]"))
4398
4399 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4400
4401 (cl-defstruct (js2-xml-start-tag-node
4402 (:include js2-xml-node)
4403 (:constructor nil)
4404 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4405 (pos js2-ts-cursor)
4406 len name attrs kids
4407 empty-p)))
4408 "AST node for an XML start-tag. Not currently used.
4409 The `kids' field is a Lisp list of child content nodes."
4410 name ; a `js2-xml-name-node'
4411 attrs ; a Lisp list of `js2-xml-attr-node'
4412 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4413
4414 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4415 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4416
4417 (defun js2-visit-xml-start-tag (n v)
4418 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4419 (dolist (attr (js2-xml-start-tag-node-attrs n))
4420 (js2-visit-ast attr v))
4421 (js2-visit-block n v))
4422
4423 (defun js2-print-xml-start-tag (n i)
4424 (insert (js2-make-pad i) "<")
4425 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4426 (when (js2-xml-start-tag-node-attrs n)
4427 (insert " ")
4428 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4429 (insert ">"))
4430
4431 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4432 ;; and add the end-tag to the kids list of the parent as well.
4433 (cl-defstruct (js2-xml-end-tag-node
4434 (:include js2-xml-node)
4435 (:constructor nil)
4436 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4437 (pos js2-ts-cursor)
4438 len name)))
4439 "AST node for an XML end-tag. Not currently used."
4440 name) ; a `js2-xml-name-node'
4441
4442 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4443 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4444
4445 (defun js2-visit-xml-end-tag (n v)
4446 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4447
4448 (defun js2-print-xml-end-tag (n i)
4449 (insert (js2-make-pad i))
4450 (insert "</")
4451 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4452 (insert ">"))
4453
4454 (cl-defstruct (js2-xml-name-node
4455 (:include js2-xml-node)
4456 (:constructor nil)
4457 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4458 (pos js2-ts-cursor)
4459 len namespace kids)))
4460 "AST node for an E4X XML name. Not currently used.
4461 Any XML name can be qualified with a namespace, hence the namespace field.
4462 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4463 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4464 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4465 namespace) ; a `js2-string-node'
4466
4467 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4468 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4469
4470 (defun js2-visit-xml-name-node (n v)
4471 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4472
4473 (defun js2-print-xml-name-node (n i)
4474 (insert (js2-make-pad i))
4475 (when (js2-xml-name-node-namespace n)
4476 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4477 (insert "::"))
4478 (dolist (kid (js2-xml-name-node-kids n))
4479 (js2-print-ast kid 0)))
4480
4481 (cl-defstruct (js2-xml-pi-node
4482 (:include js2-xml-node)
4483 (:constructor nil)
4484 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4485 (pos js2-ts-cursor)
4486 len name attrs)))
4487 "AST node for an E4X XML processing instruction. Not currently used."
4488 name ; a `js2-xml-name-node'
4489 attrs) ; a list of `js2-xml-attr-node'
4490
4491 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4492 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4493
4494 (defun js2-visit-xml-pi-node (n v)
4495 (js2-visit-ast (js2-xml-pi-node-name n) v)
4496 (dolist (attr (js2-xml-pi-node-attrs n))
4497 (js2-visit-ast attr v)))
4498
4499 (defun js2-print-xml-pi-node (n i)
4500 (insert (js2-make-pad i) "<?")
4501 (js2-print-ast (js2-xml-pi-node-name n))
4502 (when (js2-xml-pi-node-attrs n)
4503 (insert " ")
4504 (js2-print-list (js2-xml-pi-node-attrs n)))
4505 (insert "?>"))
4506
4507 (cl-defstruct (js2-xml-cdata-node
4508 (:include js2-xml-node)
4509 (:constructor nil)
4510 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4511 (pos js2-ts-cursor)
4512 len content)))
4513 "AST node for a CDATA escape section. Not currently used."
4514 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4515
4516 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4517 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4518
4519 (defun js2-visit-xml-cdata-node (n v)
4520 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4521
4522 (defun js2-print-xml-cdata-node (n i)
4523 (insert (js2-make-pad i))
4524 (js2-print-ast (js2-xml-cdata-node-content n)))
4525
4526 (cl-defstruct (js2-xml-attr-node
4527 (:include js2-xml-node)
4528 (:constructor nil)
4529 (:constructor make-js2-attr-node (&key (type js2-XML)
4530 (pos js2-ts-cursor)
4531 len name value
4532 eq-pos quote-type)))
4533 "AST node representing a foo='bar' XML attribute value. Not yet used."
4534 name ; a `js2-xml-name-node'
4535 value ; a `js2-xml-name-node'
4536 eq-pos ; buffer position of "=" sign
4537 quote-type) ; 'single or 'double
4538
4539 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4540 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4541
4542 (defun js2-visit-xml-attr-node (n v)
4543 (js2-visit-ast (js2-xml-attr-node-name n) v)
4544 (js2-visit-ast (js2-xml-attr-node-value n) v))
4545
4546 (defun js2-print-xml-attr-node (n i)
4547 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4548 "'"
4549 "\"")))
4550 (insert (js2-make-pad i))
4551 (js2-print-ast (js2-xml-attr-node-name n) 0)
4552 (insert "=" quote)
4553 (js2-print-ast (js2-xml-attr-node-value n) 0)
4554 (insert quote)))
4555
4556 (cl-defstruct (js2-xml-text-node
4557 (:include js2-xml-node)
4558 (:constructor nil)
4559 (:constructor make-js2-text-node (&key (type js2-XML)
4560 (pos js2-ts-cursor)
4561 len content)))
4562 "AST node for an E4X XML text node. Not currently used."
4563 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4564
4565 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4566 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4567
4568 (defun js2-visit-xml-text-node (n v)
4569 (js2-visit-ast (js2-xml-text-node-content n) v))
4570
4571 (defun js2-print-xml-text-node (n i)
4572 (insert (js2-make-pad i))
4573 (dolist (kid (js2-xml-text-node-content n))
4574 (js2-print-ast kid)))
4575
4576 (cl-defstruct (js2-xml-comment-node
4577 (:include js2-xml-node)
4578 (:constructor nil)
4579 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4580 (pos js2-ts-cursor)
4581 len)))
4582 "AST node for E4X XML comment. Not currently used.")
4583
4584 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4585 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4586
4587 (defun js2-print-xml-comment (n i)
4588 (insert (js2-make-pad i)
4589 (js2-node-string n)))
4590
4591 ;;; Node utilities
4592
4593 (defsubst js2-node-line (n)
4594 "Fetch the source line number at the start of node N.
4595 This is O(n) in the length of the source buffer; use prudently."
4596 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4597
4598 (defsubst js2-block-node-kid (n i)
4599 "Return child I of node N, or nil if there aren't that many."
4600 (nth i (js2-block-node-kids n)))
4601
4602 (defsubst js2-block-node-first (n)
4603 "Return first child of block node N, or nil if there is none."
4604 (cl-first (js2-block-node-kids n)))
4605
4606 (defun js2-node-root (n)
4607 "Return the root of the AST containing N.
4608 If N has no parent pointer, returns N."
4609 (let ((parent (js2-node-parent n)))
4610 (if parent
4611 (js2-node-root parent)
4612 n)))
4613
4614 (defsubst js2-node-short-name (n)
4615 "Return the short name of node N as a string, e.g. `js2-if-node'."
4616 (substring (symbol-name (aref n 0))
4617 (length "cl-struct-")))
4618
4619 (defun js2-node-child-list (node)
4620 "Return the child list for NODE, a Lisp list of nodes.
4621 Works for block nodes, array nodes, obj literals, funarg lists,
4622 var decls and try nodes (for catch clauses). Note that you should call
4623 `js2-block-node-kids' on the function body for the body statements.
4624 Returns nil for zero-length child lists or unsupported nodes."
4625 (cond
4626 ((js2-function-node-p node)
4627 (js2-function-node-params node))
4628 ((js2-block-node-p node)
4629 (js2-block-node-kids node))
4630 ((js2-try-node-p node)
4631 (js2-try-node-catch-clauses node))
4632 ((js2-array-node-p node)
4633 (js2-array-node-elems node))
4634 ((js2-object-node-p node)
4635 (js2-object-node-elems node))
4636 ((js2-call-node-p node)
4637 (js2-call-node-args node))
4638 ((js2-new-node-p node)
4639 (js2-new-node-args node))
4640 ((js2-var-decl-node-p node)
4641 (js2-var-decl-node-kids node))
4642 (t
4643 nil)))
4644
4645 (defun js2-node-set-child-list (node kids)
4646 "Set the child list for NODE to KIDS."
4647 (cond
4648 ((js2-function-node-p node)
4649 (setf (js2-function-node-params node) kids))
4650 ((js2-block-node-p node)
4651 (setf (js2-block-node-kids node) kids))
4652 ((js2-try-node-p node)
4653 (setf (js2-try-node-catch-clauses node) kids))
4654 ((js2-array-node-p node)
4655 (setf (js2-array-node-elems node) kids))
4656 ((js2-object-node-p node)
4657 (setf (js2-object-node-elems node) kids))
4658 ((js2-call-node-p node)
4659 (setf (js2-call-node-args node) kids))
4660 ((js2-new-node-p node)
4661 (setf (js2-new-node-args node) kids))
4662 ((js2-var-decl-node-p node)
4663 (setf (js2-var-decl-node-kids node) kids))
4664 (t
4665 (error "Unsupported node type: %s" (js2-node-short-name node))))
4666 kids)
4667
4668 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4669 (defconst js2-paren-expr-nodes
4670 '(cl-struct-js2-comp-loop-node
4671 cl-struct-js2-comp-node
4672 cl-struct-js2-call-node
4673 cl-struct-js2-catch-node
4674 cl-struct-js2-do-node
4675 cl-struct-js2-elem-get-node
4676 cl-struct-js2-for-in-node
4677 cl-struct-js2-for-node
4678 cl-struct-js2-function-node
4679 cl-struct-js2-if-node
4680 cl-struct-js2-let-node
4681 cl-struct-js2-new-node
4682 cl-struct-js2-paren-node
4683 cl-struct-js2-switch-node
4684 cl-struct-js2-while-node
4685 cl-struct-js2-with-node
4686 cl-struct-js2-xml-dot-query-node)
4687 "Node types that can have a parenthesized child expression.
4688 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4689
4690 (defsubst js2-paren-expr-node-p (node)
4691 "Return t for nodes that typically have a parenthesized child expression.
4692 Useful for computing the indentation anchors for arg-lists and conditions.
4693 Note that it may return a false positive, for instance when NODE is
4694 a `js2-new-node' and there are no arguments or parentheses."
4695 (memq (aref node 0) js2-paren-expr-nodes))
4696
4697 ;; Fake polymorphism... yech.
4698 (defun js2-node-lp (node)
4699 "Return relative left-paren position for NODE, if applicable.
4700 For `js2-elem-get-node' structs, returns left-bracket position.
4701 Note that the position may be nil in the case of a parse error."
4702 (cond
4703 ((js2-elem-get-node-p node)
4704 (js2-elem-get-node-lb node))
4705 ((js2-loop-node-p node)
4706 (js2-loop-node-lp node))
4707 ((js2-function-node-p node)
4708 (js2-function-node-lp node))
4709 ((js2-if-node-p node)
4710 (js2-if-node-lp node))
4711 ((js2-new-node-p node)
4712 (js2-new-node-lp node))
4713 ((js2-call-node-p node)
4714 (js2-call-node-lp node))
4715 ((js2-paren-node-p node)
4716 0)
4717 ((js2-switch-node-p node)
4718 (js2-switch-node-lp node))
4719 ((js2-catch-node-p node)
4720 (js2-catch-node-lp node))
4721 ((js2-let-node-p node)
4722 (js2-let-node-lp node))
4723 ((js2-comp-node-p node)
4724 0)
4725 ((js2-with-node-p node)
4726 (js2-with-node-lp node))
4727 ((js2-xml-dot-query-node-p node)
4728 (1+ (js2-infix-node-op-pos node)))
4729 (t
4730 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4731
4732 ;; Fake polymorphism... blech.
4733 (defun js2-node-rp (node)
4734 "Return relative right-paren position for NODE, if applicable.
4735 For `js2-elem-get-node' structs, returns right-bracket position.
4736 Note that the position may be nil in the case of a parse error."
4737 (cond
4738 ((js2-elem-get-node-p node)
4739 (js2-elem-get-node-rb node))
4740 ((js2-loop-node-p node)
4741 (js2-loop-node-rp node))
4742 ((js2-function-node-p node)
4743 (js2-function-node-rp node))
4744 ((js2-if-node-p node)
4745 (js2-if-node-rp node))
4746 ((js2-new-node-p node)
4747 (js2-new-node-rp node))
4748 ((js2-call-node-p node)
4749 (js2-call-node-rp node))
4750 ((js2-paren-node-p node)
4751 (1- (js2-node-len node)))
4752 ((js2-switch-node-p node)
4753 (js2-switch-node-rp node))
4754 ((js2-catch-node-p node)
4755 (js2-catch-node-rp node))
4756 ((js2-let-node-p node)
4757 (js2-let-node-rp node))
4758 ((js2-comp-node-p node)
4759 (1- (js2-node-len node)))
4760 ((js2-with-node-p node)
4761 (js2-with-node-rp node))
4762 ((js2-xml-dot-query-node-p node)
4763 (1+ (js2-xml-dot-query-node-rp node)))
4764 (t
4765 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4766
4767 (defsubst js2-node-first-child (node)
4768 "Return the first element of `js2-node-child-list' for NODE."
4769 (car (js2-node-child-list node)))
4770
4771 (defsubst js2-node-last-child (node)
4772 "Return the last element of `js2-node-last-child' for NODE."
4773 (car (last (js2-node-child-list node))))
4774
4775 (defun js2-node-prev-sibling (node)
4776 "Return the previous statement in parent.
4777 Works for parents supported by `js2-node-child-list'.
4778 Returns nil if NODE is not in the parent, or PARENT is
4779 not a supported node, or if NODE is the first child."
4780 (let* ((p (js2-node-parent node))
4781 (kids (js2-node-child-list p))
4782 (sib (car kids)))
4783 (while (and kids
4784 (not (eq node (cadr kids))))
4785 (setq kids (cdr kids)
4786 sib (car kids)))
4787 sib))
4788
4789 (defun js2-node-next-sibling (node)
4790 "Return the next statement in parent block.
4791 Returns nil if NODE is not in the block, or PARENT is not
4792 a block node, or if NODE is the last statement."
4793 (let* ((p (js2-node-parent node))
4794 (kids (js2-node-child-list p)))
4795 (while (and kids
4796 (not (eq node (car kids))))
4797 (setq kids (cdr kids)))
4798 (cadr kids)))
4799
4800 (defun js2-node-find-child-before (pos parent &optional after)
4801 "Find the last child that starts before POS in parent.
4802 If AFTER is non-nil, returns first child starting after POS.
4803 POS is an absolute buffer position. PARENT is any node
4804 supported by `js2-node-child-list'.
4805 Returns nil if no applicable child is found."
4806 (let ((kids (if (js2-function-node-p parent)
4807 (js2-block-node-kids (js2-function-node-body parent))
4808 (js2-node-child-list parent)))
4809 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4810 (js2-function-node-body parent)
4811 parent)))
4812 kid result fn
4813 (continue t))
4814 (setq fn (if after '>= '<))
4815 (while (and kids continue)
4816 (setq kid (car kids))
4817 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4818 (setq result kid
4819 continue (not after))
4820 (setq continue after))
4821 (setq kids (cdr kids)))
4822 result))
4823
4824 (defun js2-node-find-child-after (pos parent)
4825 "Find first child that starts after POS in parent.
4826 POS is an absolute buffer position. PARENT is any node
4827 supported by `js2-node-child-list'.
4828 Returns nil if no applicable child is found."
4829 (js2-node-find-child-before pos parent 'after))
4830
4831 (defun js2-node-replace-child (pos parent new-node)
4832 "Replace node at index POS in PARENT with NEW-NODE.
4833 Only works for parents supported by `js2-node-child-list'."
4834 (let ((kids (js2-node-child-list parent))
4835 (i 0))
4836 (while (< i pos)
4837 (setq kids (cdr kids)
4838 i (1+ i)))
4839 (setcar kids new-node)
4840 (js2-node-add-children parent new-node)))
4841
4842 (defun js2-node-buffer (n)
4843 "Return the buffer associated with AST N.
4844 Returns nil if the buffer is not set as a property on the root
4845 node, or if parent links were not recorded during parsing."
4846 (let ((root (js2-node-root n)))
4847 (and root
4848 (js2-ast-root-p root)
4849 (js2-ast-root-buffer root))))
4850
4851 (defun js2-block-node-push (n kid)
4852 "Push js2-node KID onto the end of js2-block-node N's child list.
4853 KID is always added to the -end- of the kids list.
4854 Function also calls `js2-node-add-children' to add the parent link."
4855 (let ((kids (js2-node-child-list n)))
4856 (if kids
4857 (setcdr kids (nconc (cdr kids) (list kid)))
4858 (js2-node-set-child-list n (list kid)))
4859 (js2-node-add-children n kid)))
4860
4861 (defun js2-node-string (node)
4862 (with-current-buffer (or (js2-node-buffer node)
4863 (error "No buffer available for node %s" node))
4864 (let ((pos (js2-node-abs-pos node)))
4865 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4866
4867 ;; Container for storing the node we're looking for in a traversal.
4868 (js2-deflocal js2-discovered-node nil)
4869
4870 ;; Keep track of absolute node position during traversals.
4871 (js2-deflocal js2-visitor-offset nil)
4872
4873 (js2-deflocal js2-node-search-point nil)
4874
4875 (when js2-mode-dev-mode-p
4876 (defun js2-find-node-at-point ()
4877 (interactive)
4878 (let ((node (js2-node-at-point)))
4879 (message "%s" (or node "No node found at point"))))
4880 (defun js2-node-name-at-point ()
4881 (interactive)
4882 (let ((node (js2-node-at-point)))
4883 (message "%s" (if node
4884 (js2-node-short-name node)
4885 "No node found at point.")))))
4886
4887 (defun js2-node-at-point (&optional pos skip-comments)
4888 "Return AST node at POS, a buffer position, defaulting to current point.
4889 The `js2-mode-ast' variable must be set to the current parse tree.
4890 Signals an error if the AST (`js2-mode-ast') is nil.
4891 Always returns a node - if it can't find one, it returns the root.
4892 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4893 (let ((ast js2-mode-ast)
4894 result)
4895 (unless ast
4896 (error "No JavaScript AST available"))
4897 ;; Look through comments first, since they may be inside nodes that
4898 ;; would otherwise report a match.
4899 (setq pos (or pos (point))
4900 result (if (> pos (js2-node-abs-end ast))
4901 ast
4902 (if (not skip-comments)
4903 (js2-comment-at-point pos))))
4904 (unless result
4905 (setq js2-discovered-node nil
4906 js2-visitor-offset 0
4907 js2-node-search-point pos)
4908 (unwind-protect
4909 (catch 'js2-visit-done
4910 (js2-visit-ast ast #'js2-node-at-point-visitor))
4911 (setq js2-visitor-offset nil
4912 js2-node-search-point nil))
4913 (setq result js2-discovered-node))
4914 ;; may have found a comment beyond end of last child node,
4915 ;; since visiting the ast-root looks at the comment-list last.
4916 (if (and skip-comments
4917 (js2-comment-node-p result))
4918 (setq result nil))
4919 (or result js2-mode-ast)))
4920
4921 (defun js2-node-at-point-visitor (node end-p)
4922 (let ((rel-pos (js2-node-pos node))
4923 abs-pos
4924 abs-end
4925 (point js2-node-search-point))
4926 (cond
4927 (end-p
4928 ;; this evaluates to a non-nil return value, even if it's zero
4929 (cl-decf js2-visitor-offset rel-pos))
4930 ;; we already looked for comments before visiting, and don't want them now
4931 ((js2-comment-node-p node)
4932 nil)
4933 (t
4934 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4935 ;; we only want to use the node if the point is before
4936 ;; the last character position in the node, so we decrement
4937 ;; the absolute end by 1.
4938 abs-end (+ abs-pos (js2-node-len node) -1))
4939 (cond
4940 ;; If this node starts after search-point, stop the search.
4941 ((> abs-pos point)
4942 (throw 'js2-visit-done nil))
4943 ;; If this node ends before the search-point, don't check kids.
4944 ((> point abs-end)
4945 nil)
4946 (t
4947 ;; Otherwise point is within this node, possibly in a child.
4948 (setq js2-discovered-node node)
4949 t)))))) ; keep processing kids to look for more specific match
4950
4951 (defsubst js2-block-comment-p (node)
4952 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4953 (and (js2-comment-node-p node)
4954 (memq (js2-comment-node-format node) '(jsdoc block))))
4955
4956 ;; TODO: put the comments in a vector and binary-search them instead
4957 (defun js2-comment-at-point (&optional pos)
4958 "Look through scanned comment nodes for one containing POS.
4959 POS is a buffer position that defaults to current point.
4960 Function returns nil if POS was not in any comment node."
4961 (let ((ast js2-mode-ast)
4962 (x (or pos (point)))
4963 beg end)
4964 (unless ast
4965 (error "No JavaScript AST available"))
4966 (catch 'done
4967 ;; Comments are stored in lexical order.
4968 (dolist (comment (js2-ast-root-comments ast) nil)
4969 (setq beg (js2-node-abs-pos comment)
4970 end (+ beg (js2-node-len comment)))
4971 (if (and (>= x beg)
4972 (<= x end))
4973 (throw 'done comment))))))
4974
4975 (defun js2-mode-find-parent-fn (node)
4976 "Find function enclosing NODE.
4977 Returns nil if NODE is not inside a function."
4978 (setq node (js2-node-parent node))
4979 (while (and node (not (js2-function-node-p node)))
4980 (setq node (js2-node-parent node)))
4981 (and (js2-function-node-p node) node))
4982
4983 (defun js2-mode-find-enclosing-fn (node)
4984 "Find function or root enclosing NODE."
4985 (if (js2-ast-root-p node)
4986 node
4987 (setq node (js2-node-parent node))
4988 (while (not (or (js2-ast-root-p node)
4989 (js2-function-node-p node)))
4990 (setq node (js2-node-parent node)))
4991 node))
4992
4993 (defun js2-mode-find-enclosing-node (beg end)
4994 "Find node fully enclosing BEG and END."
4995 (let ((node (js2-node-at-point beg))
4996 pos
4997 (continue t))
4998 (while continue
4999 (if (or (js2-ast-root-p node)
5000 (and
5001 (<= (setq pos (js2-node-abs-pos node)) beg)
5002 (>= (+ pos (js2-node-len node)) end)))
5003 (setq continue nil)
5004 (setq node (js2-node-parent node))))
5005 node))
5006
5007 (defun js2-node-parent-script-or-fn (node)
5008 "Find script or function immediately enclosing NODE.
5009 If NODE is the ast-root, returns nil."
5010 (if (js2-ast-root-p node)
5011 nil
5012 (setq node (js2-node-parent node))
5013 (while (and node (not (or (js2-function-node-p node)
5014 (js2-script-node-p node))))
5015 (setq node (js2-node-parent node)))
5016 node))
5017
5018 (defun js2-node-is-descendant (node ancestor)
5019 "Return t if NODE is a descendant of ANCESTOR."
5020 (while (and node
5021 (not (eq node ancestor)))
5022 (setq node (js2-node-parent node)))
5023 node)
5024
5025 ;;; visitor infrastructure
5026
5027 (defun js2-visit-none (_node _callback)
5028 "Visitor for AST node that have no node children."
5029 nil)
5030
5031 (defun js2-print-none (_node _indent)
5032 "Visitor for AST node with no printed representation.")
5033
5034 (defun js2-print-body (node indent)
5035 "Print a statement, or a block without braces."
5036 (if (js2-block-node-p node)
5037 (dolist (kid (js2-block-node-kids node))
5038 (js2-print-ast kid indent))
5039 (js2-print-ast node indent)))
5040
5041 (defun js2-print-list (args &optional delimiter)
5042 (cl-loop with len = (length args)
5043 for arg in args
5044 for count from 1
5045 do
5046 (when arg (js2-print-ast arg 0))
5047 (if (< count len)
5048 (insert (or delimiter ", ")))))
5049
5050 (defun js2-print-tree (ast)
5051 "Prints an AST to the current buffer.
5052 Makes `js2-ast-parent-nodes' available to the printer functions."
5053 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5054 (js2-print-ast ast)))
5055
5056 (defun js2-print-ast (node &optional indent)
5057 "Helper function for printing AST nodes.
5058 Requires `js2-ast-parent-nodes' to be non-nil.
5059 You should use `js2-print-tree' instead of this function."
5060 (let ((printer (get (aref node 0) 'js2-printer))
5061 (i (or indent 0)))
5062 ;; TODO: wedge comments in here somewhere
5063 (if printer
5064 (funcall printer node i))))
5065
5066 (defconst js2-side-effecting-tokens
5067 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5068 (dolist (tt (list js2-ASSIGN
5069 js2-ASSIGN_ADD
5070 js2-ASSIGN_BITAND
5071 js2-ASSIGN_BITOR
5072 js2-ASSIGN_BITXOR
5073 js2-ASSIGN_DIV
5074 js2-ASSIGN_LSH
5075 js2-ASSIGN_MOD
5076 js2-ASSIGN_MUL
5077 js2-ASSIGN_RSH
5078 js2-ASSIGN_SUB
5079 js2-ASSIGN_URSH
5080 js2-BLOCK
5081 js2-BREAK
5082 js2-CALL
5083 js2-CATCH
5084 js2-CATCH_SCOPE
5085 js2-CLASS
5086 js2-CONST
5087 js2-CONTINUE
5088 js2-DEBUGGER
5089 js2-DEC
5090 js2-DELPROP
5091 js2-DEL_REF
5092 js2-DO
5093 js2-ELSE
5094 js2-EMPTY
5095 js2-ENTERWITH
5096 js2-EXPORT
5097 js2-EXPR_RESULT
5098 js2-FINALLY
5099 js2-FOR
5100 js2-FUNCTION
5101 js2-GOTO
5102 js2-IF
5103 js2-IFEQ
5104 js2-IFNE
5105 js2-IMPORT
5106 js2-INC
5107 js2-JSR
5108 js2-LABEL
5109 js2-LEAVEWITH
5110 js2-LET
5111 js2-LETEXPR
5112 js2-LOCAL_BLOCK
5113 js2-LOOP
5114 js2-NEW
5115 js2-REF_CALL
5116 js2-RETHROW
5117 js2-RETURN
5118 js2-RETURN_RESULT
5119 js2-SEMI
5120 js2-SETELEM
5121 js2-SETELEM_OP
5122 js2-SETNAME
5123 js2-SETPROP
5124 js2-SETPROP_OP
5125 js2-SETVAR
5126 js2-SET_REF
5127 js2-SET_REF_OP
5128 js2-SWITCH
5129 js2-TARGET
5130 js2-THROW
5131 js2-TRY
5132 js2-VAR
5133 js2-WHILE
5134 js2-WITH
5135 js2-WITHEXPR
5136 js2-YIELD))
5137 (aset tokens tt t))
5138 (if js2-instanceof-has-side-effects
5139 (aset tokens js2-INSTANCEOF t))
5140 tokens))
5141
5142 (defun js2-node-has-side-effects (node)
5143 "Return t if NODE has side effects."
5144 (when node ; makes it easier to handle malformed expressions
5145 (let ((tt (js2-node-type node)))
5146 (cond
5147 ;; This doubtless needs some work, since EXPR_VOID is used
5148 ;; in several ways in Rhino and I may not have caught them all.
5149 ;; I'll wait for people to notice incorrect warnings.
5150 ((and (= tt js2-EXPR_VOID)
5151 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5152 (let ((expr (js2-expr-stmt-node-expr node)))
5153 (or (js2-node-has-side-effects expr)
5154 (when (js2-string-node-p expr)
5155 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5156 ((= tt js2-AWAIT)
5157 (js2-node-has-side-effects (js2-unary-node-operand node)))
5158 ((= tt js2-COMMA)
5159 (js2-node-has-side-effects (js2-infix-node-right node)))
5160 ((or (= tt js2-AND)
5161 (= tt js2-OR))
5162 (or (js2-node-has-side-effects (js2-infix-node-right node))
5163 (js2-node-has-side-effects (js2-infix-node-left node))))
5164 ((= tt js2-HOOK)
5165 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5166 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5167 ((js2-paren-node-p node)
5168 (js2-node-has-side-effects (js2-paren-node-expr node)))
5169 ((= tt js2-ERROR) ; avoid cascaded error messages
5170 nil)
5171 (t
5172 (aref js2-side-effecting-tokens tt))))))
5173
5174 (defconst js2-stmt-node-types
5175 (list js2-BLOCK
5176 js2-BREAK
5177 js2-CONTINUE
5178 js2-DEFAULT ; e4x "default xml namespace" statement
5179 js2-DO
5180 js2-EXPORT
5181 js2-EXPR_RESULT
5182 js2-EXPR_VOID
5183 js2-FOR
5184 js2-IF
5185 js2-IMPORT
5186 js2-RETURN
5187 js2-SWITCH
5188 js2-THROW
5189 js2-TRY
5190 js2-WHILE
5191 js2-WITH)
5192 "Node types that only appear in statement contexts.
5193 The list does not include nodes that always appear as the child
5194 of another specific statement type, such as switch-cases,
5195 catch and finally blocks, and else-clauses. The list also excludes
5196 nodes like yield, let and var, which may appear in either expression
5197 or statement context, and in the latter context always have a
5198 `js2-expr-stmt-node' parent. Finally, the list does not include
5199 functions or scripts, which are treated separately from statements
5200 by the JavaScript parser and runtime.")
5201
5202 (defun js2-stmt-node-p (node)
5203 "Heuristic for figuring out if NODE is a statement.
5204 Some node types can appear in either an expression context or a
5205 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5206 For these node types in a statement context, the parent will be a
5207 `js2-expr-stmt-node'.
5208 Functions aren't included in the check."
5209 (memq (js2-node-type node) js2-stmt-node-types))
5210
5211 (defun js2-mode-find-first-stmt (node)
5212 "Search upward starting from NODE looking for a statement.
5213 For purposes of this function, a `js2-function-node' counts."
5214 (while (not (or (js2-stmt-node-p node)
5215 (js2-function-node-p node)))
5216 (setq node (js2-node-parent node)))
5217 node)
5218
5219 (defun js2-node-parent-stmt (node)
5220 "Return the node's first ancestor that is a statement.
5221 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5222 appearing in a statement context will have a parent that is a
5223 `js2-expr-stmt-node' that will be returned by this function."
5224 (let ((parent (js2-node-parent node)))
5225 (if (or (null parent)
5226 (js2-stmt-node-p parent)
5227 (and (js2-function-node-p parent)
5228 (not (eq (js2-function-node-form parent)
5229 'FUNCTION_EXPRESSION))))
5230 parent
5231 (js2-node-parent-stmt parent))))
5232
5233 ;; In the Mozilla Rhino sources, Roshan James writes:
5234 ;; Does consistent-return analysis on the function body when strict mode is
5235 ;; enabled.
5236 ;;
5237 ;; function (x) { return (x+1) }
5238 ;;
5239 ;; is ok, but
5240 ;;
5241 ;; function (x) { if (x < 0) return (x+1); }
5242 ;;
5243 ;; is not because the function can potentially return a value when the
5244 ;; condition is satisfied and if not, the function does not explicitly
5245 ;; return a value.
5246 ;;
5247 ;; This extends to checking mismatches such as "return" and "return <value>"
5248 ;; used in the same function. Warnings are not emitted if inconsistent
5249 ;; returns exist in code that can be statically shown to be unreachable.
5250 ;; Ex.
5251 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5252 ;;
5253 ;; emits no warning. However if the loop had a break statement, then a
5254 ;; warning would be emitted.
5255 ;;
5256 ;; The consistency analysis looks at control structures such as loops, ifs,
5257 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5258 ;; warns the user about an inconsistent set of termination possibilities.
5259 ;;
5260 ;; These flags enumerate the possible ways a statement/function can
5261 ;; terminate. These flags are used by endCheck() and by the Parser to
5262 ;; detect inconsistent return usage.
5263 ;;
5264 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5265 ;; able to execute (example: throw, continue)
5266 ;;
5267 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5268 ;; next one. Statement such as return dont. A compound statement may have
5269 ;; some branch that drops off control to the next statement.
5270 ;;
5271 ;; END_RETURNS indicates that the statement can return with no value.
5272 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5273 ;;
5274 ;; A compound statement such as
5275 ;; if (condition) {
5276 ;; return value;
5277 ;; }
5278 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5279
5280 (defconst js2-END_UNREACHED 0)
5281 (defconst js2-END_DROPS_OFF 1)
5282 (defconst js2-END_RETURNS 2)
5283 (defconst js2-END_RETURNS_VALUE 4)
5284 (defconst js2-END_YIELDS 8)
5285
5286 (defun js2-has-consistent-return-usage (node)
5287 "Check that every return usage in a function body is consistent.
5288 Returns t if the function satisfies strict mode requirement."
5289 (let ((n (js2-end-check node)))
5290 ;; either it doesn't return a value in any branch...
5291 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5292 ;; or it returns a value (or is unreached) at every branch
5293 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5294 js2-END_RETURNS
5295 js2-END_YIELDS)))))
5296
5297 (defun js2-end-check-if (node)
5298 "Ensure that return usage in then/else blocks is consistent.
5299 If there is no else block, then the return statement can fall through.
5300 Returns logical OR of END_* flags"
5301 (let ((th (js2-if-node-then-part node))
5302 (el (js2-if-node-else-part node)))
5303 (if (null th)
5304 js2-END_UNREACHED
5305 (logior (js2-end-check th) (if el
5306 (js2-end-check el)
5307 js2-END_DROPS_OFF)))))
5308
5309 (defun js2-end-check-switch (node)
5310 "Consistency of return statements is checked between the case statements.
5311 If there is no default, then the switch can fall through. If there is a
5312 default, we check to see if all code paths in the default return or if
5313 there is a code path that can fall through.
5314 Returns logical OR of END_* flags."
5315 (let ((rv js2-END_UNREACHED)
5316 default-case)
5317 ;; examine the cases
5318 (catch 'break
5319 (dolist (c (js2-switch-node-cases node))
5320 (if (js2-case-node-expr c)
5321 (js2-set-flag rv (js2-end-check-block c))
5322 (setq default-case c)
5323 (throw 'break nil))))
5324 ;; we don't care how the cases drop into each other
5325 (js2-clear-flag rv js2-END_DROPS_OFF)
5326 ;; examine the default
5327 (js2-set-flag rv (if default-case
5328 (js2-end-check default-case)
5329 js2-END_DROPS_OFF))
5330 rv))
5331
5332 (defun js2-end-check-try (node)
5333 "If the block has a finally, return consistency is checked in the
5334 finally block. If all code paths in the finally return, then the
5335 returns in the try-catch blocks don't matter. If there is a code path
5336 that does not return or if there is no finally block, the returns
5337 of the try and catch blocks are checked for mismatch.
5338 Returns logical OR of END_* flags."
5339 (let ((finally (js2-try-node-finally-block node))
5340 rv)
5341 ;; check the finally if it exists
5342 (setq rv (if finally
5343 (js2-end-check (js2-finally-node-body finally))
5344 js2-END_DROPS_OFF))
5345 ;; If the finally block always returns, then none of the returns
5346 ;; in the try or catch blocks matter.
5347 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5348 (js2-clear-flag rv js2-END_DROPS_OFF)
5349 ;; examine the try block
5350 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5351 ;; check each catch block
5352 (dolist (cb (js2-try-node-catch-clauses node))
5353 (js2-set-flag rv (js2-end-check cb))))
5354 rv))
5355
5356 (defun js2-end-check-loop (node)
5357 "Return statement in the loop body must be consistent.
5358 The default assumption for any kind of a loop is that it will eventually
5359 terminate. The only exception is a loop with a constant true condition.
5360 Code that follows such a loop is examined only if one can determine
5361 statically that there is a break out of the loop.
5362
5363 for(... ; ... ; ...) {}
5364 for(... in ... ) {}
5365 while(...) { }
5366 do { } while(...)
5367
5368 Returns logical OR of END_* flags."
5369 (let ((rv (js2-end-check (js2-loop-node-body node)))
5370 (condition (cond
5371 ((js2-while-node-p node)
5372 (js2-while-node-condition node))
5373 ((js2-do-node-p node)
5374 (js2-do-node-condition node))
5375 ((js2-for-node-p node)
5376 (js2-for-node-condition node)))))
5377
5378 ;; check to see if the loop condition is always true
5379 (if (and condition
5380 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5381 (js2-clear-flag rv js2-END_DROPS_OFF))
5382
5383 ;; look for effect of breaks
5384 (js2-set-flag rv (js2-node-get-prop node
5385 'CONTROL_BLOCK_PROP
5386 js2-END_UNREACHED))
5387 rv))
5388
5389 (defun js2-end-check-block (node)
5390 "A general block of code is examined statement by statement.
5391 If any statement (even a compound one) returns in all branches, then
5392 subsequent statements are not examined.
5393 Returns logical OR of END_* flags."
5394 (let* ((rv js2-END_DROPS_OFF)
5395 (kids (js2-block-node-kids node))
5396 (n (car kids)))
5397 ;; Check each statement. If the statement can continue onto the next
5398 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5399 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5400 (js2-clear-flag rv js2-END_DROPS_OFF)
5401 (js2-set-flag rv (js2-end-check n))
5402 (setq kids (cdr kids)
5403 n (car kids)))
5404 rv))
5405
5406 (defun js2-end-check-label (node)
5407 "A labeled statement implies that there may be a break to the label.
5408 The function processes the labeled statement and then checks the
5409 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5410 particular label.
5411 Returns logical OR of END_* flags."
5412 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5413 (logior rv (js2-node-get-prop node
5414 'CONTROL_BLOCK_PROP
5415 js2-END_UNREACHED))))
5416
5417 (defun js2-end-check-break (node)
5418 "When a break is encountered annotate the statement being broken
5419 out of by setting its CONTROL_BLOCK_PROP property.
5420 Returns logical OR of END_* flags."
5421 (and (js2-break-node-target node)
5422 (js2-node-set-prop (js2-break-node-target node)
5423 'CONTROL_BLOCK_PROP
5424 js2-END_DROPS_OFF))
5425 js2-END_UNREACHED)
5426
5427 (defun js2-end-check (node)
5428 "Examine the body of a function, doing a basic reachability analysis.
5429 Returns a combination of flags END_* flags that indicate
5430 how the function execution can terminate. These constitute only the
5431 pessimistic set of termination conditions. It is possible that at
5432 runtime certain code paths will never be actually taken. Hence this
5433 analysis will flag errors in cases where there may not be errors.
5434 Returns logical OR of END_* flags"
5435 (let (kid)
5436 (cond
5437 ((js2-break-node-p node)
5438 (js2-end-check-break node))
5439 ((js2-expr-stmt-node-p node)
5440 (if (setq kid (js2-expr-stmt-node-expr node))
5441 (js2-end-check kid)
5442 js2-END_DROPS_OFF))
5443 ((or (js2-continue-node-p node)
5444 (js2-throw-node-p node))
5445 js2-END_UNREACHED)
5446 ((js2-return-node-p node)
5447 (if (setq kid (js2-return-node-retval node))
5448 js2-END_RETURNS_VALUE
5449 js2-END_RETURNS))
5450 ((js2-loop-node-p node)
5451 (js2-end-check-loop node))
5452 ((js2-switch-node-p node)
5453 (js2-end-check-switch node))
5454 ((js2-labeled-stmt-node-p node)
5455 (js2-end-check-label node))
5456 ((js2-if-node-p node)
5457 (js2-end-check-if node))
5458 ((js2-try-node-p node)
5459 (js2-end-check-try node))
5460 ((js2-block-node-p node)
5461 (if (null (js2-block-node-kids node))
5462 js2-END_DROPS_OFF
5463 (js2-end-check-block node)))
5464 ((js2-yield-node-p node)
5465 js2-END_YIELDS)
5466 (t
5467 js2-END_DROPS_OFF))))
5468
5469 (defun js2-always-defined-boolean-p (node)
5470 "Check if NODE always evaluates to true or false in boolean context.
5471 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5472 nor always false."
5473 (let ((tt (js2-node-type node))
5474 num)
5475 (cond
5476 ((or (= tt js2-FALSE) (= tt js2-NULL))
5477 'ALWAYS_FALSE)
5478 ((= tt js2-TRUE)
5479 'ALWAYS_TRUE)
5480 ((= tt js2-NUMBER)
5481 (setq num (js2-number-node-num-value node))
5482 (if (and (not (eq num 0.0e+NaN))
5483 (not (zerop num)))
5484 'ALWAYS_TRUE
5485 'ALWAYS_FALSE))
5486 (t
5487 nil))))
5488
5489 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5490 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5491
5492 (defvar js2-tokens nil
5493 "List of all defined token names.") ; initialized in `js2-token-names'
5494
5495 (defconst js2-token-names
5496 (let* ((names (make-vector js2-num-tokens -1))
5497 (case-fold-search nil) ; only match js2-UPPER_CASE
5498 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5499 (cl-loop for sym in syms
5500 for i from 0
5501 do
5502 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5503 (not (boundp sym)))
5504 (aset names (symbol-value sym) ; code, e.g. 152
5505 (downcase
5506 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5507 (push sym js2-tokens)))
5508 names)
5509 "Vector mapping int values to token string names, sans `js2-' prefix.")
5510
5511 (defun js2-tt-name (tok)
5512 "Return a string name for TOK, a token symbol or code.
5513 Signals an error if it's not a recognized token."
5514 (let ((code tok))
5515 (if (symbolp tok)
5516 (setq code (symbol-value tok)))
5517 (if (eq code -1)
5518 "ERROR"
5519 (if (and (numberp code)
5520 (not (cl-minusp code))
5521 (< code js2-num-tokens))
5522 (aref js2-token-names code)
5523 (error "Invalid token: %s" code)))))
5524
5525 (defsubst js2-tt-sym (tok)
5526 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5527 (intern (js2-tt-name tok)))
5528
5529 (defconst js2-token-codes
5530 (let ((table (make-hash-table :test 'eq :size 256)))
5531 (cl-loop for name across js2-token-names
5532 for sym = (intern (concat "js2-" (upcase name)))
5533 do
5534 (puthash sym (symbol-value sym) table))
5535 ;; clean up a few that are "wrong" in Rhino's token codes
5536 (puthash 'js2-DELETE js2-DELPROP table)
5537 table)
5538 "Hashtable mapping token type symbols to their bytecodes.")
5539
5540 (defsubst js2-tt-code (sym)
5541 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5542 (or (gethash sym js2-token-codes)
5543 (error "Invalid token symbol: %s " sym))) ; signal code bug
5544
5545 (defun js2-report-scan-error (msg &optional no-throw beg len)
5546 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5547 (js2-report-error msg nil
5548 (or beg (js2-current-token-beg))
5549 (or len (js2-current-token-len)))
5550 (unless no-throw
5551 (throw 'return js2-ERROR)))
5552
5553 (defun js2-set-string-from-buffer (token)
5554 "Set `string' and `end' slots for TOKEN, return the string."
5555 (setf (js2-token-end token) js2-ts-cursor
5556 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5557
5558 ;; TODO: could potentially avoid a lot of consing by allocating a
5559 ;; char buffer the way Rhino does.
5560 (defsubst js2-add-to-string (c)
5561 (push c js2-ts-string-buffer))
5562
5563 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5564 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5565 ;; any other character: when it's not part of the current token, we
5566 ;; unget it, allowing it to be read again by the following call.
5567 (defsubst js2-unget-char ()
5568 (cl-decf js2-ts-cursor))
5569
5570 ;; Rhino distinguishes \r and \n line endings. We don't need to
5571 ;; because we only scan from Emacs buffers, which always use \n.
5572 (defun js2-get-char ()
5573 "Read and return the next character from the input buffer.
5574 Increments `js2-ts-lineno' if the return value is a newline char.
5575 Updates `js2-ts-cursor' to the point after the returned char.
5576 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5577 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5578 (let (c)
5579 ;; check for end of buffer
5580 (if (>= js2-ts-cursor (point-max))
5581 (setq js2-ts-hit-eof t
5582 js2-ts-cursor (1+ js2-ts-cursor)
5583 c js2-EOF_CHAR) ; return value
5584 ;; otherwise read next char
5585 (setq c (char-before (cl-incf js2-ts-cursor)))
5586 ;; if we read a newline, update counters
5587 (if (= c ?\n)
5588 (setq js2-ts-line-start js2-ts-cursor
5589 js2-ts-lineno (1+ js2-ts-lineno)))
5590 ;; TODO: skip over format characters
5591 c)))
5592
5593 (defun js2-read-unicode-escape ()
5594 "Read a \\uNNNN sequence from the input.
5595 Assumes the ?\ and ?u have already been read.
5596 Returns the unicode character, or nil if it wasn't a valid character.
5597 Doesn't change the values of any scanner variables."
5598 ;; I really wish I knew a better way to do this, but I can't
5599 ;; find the Emacs function that takes a 16-bit int and converts
5600 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5601 ;; Have to first check that it's 4 hex characters or it may stop
5602 ;; the read early.
5603 (ignore-errors
5604 (let ((s (buffer-substring-no-properties js2-ts-cursor
5605 (+ 4 js2-ts-cursor))))
5606 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5607 (read (concat "?\\u" s))))))
5608
5609 (defun js2-match-char (test)
5610 "Consume and return next character if it matches TEST, a character.
5611 Returns nil and consumes nothing if TEST is not the next character."
5612 (let ((c (js2-get-char)))
5613 (if (eq c test)
5614 t
5615 (js2-unget-char)
5616 nil)))
5617
5618 (defun js2-peek-char ()
5619 (prog1
5620 (js2-get-char)
5621 (js2-unget-char)))
5622
5623 (defun js2-identifier-start-p (c)
5624 "Is C a valid start to an ES5 Identifier?
5625 See http://es5.github.io/#x7.6"
5626 (or
5627 (memq c '(?$ ?_))
5628 (memq (get-char-code-property c 'general-category)
5629 ;; Letters
5630 '(Lu Ll Lt Lm Lo Nl))))
5631
5632 (defun js2-identifier-part-p (c)
5633 "Is C a valid part of an ES5 Identifier?
5634 See http://es5.github.io/#x7.6"
5635 (or
5636 (memq c '(?$ ?_ ?\u200c ?\u200d))
5637 (memq (get-char-code-property c 'general-category)
5638 '(;; Letters
5639 Lu Ll Lt Lm Lo Nl
5640 ;; Combining Marks
5641 Mn Mc
5642 ;; Digits
5643 Nd
5644 ;; Connector Punctuation
5645 Pc))))
5646
5647 (defun js2-alpha-p (c)
5648 (cond ((and (<= ?A c) (<= c ?Z)) t)
5649 ((and (<= ?a c) (<= c ?z)) t)
5650 (t nil)))
5651
5652 (defsubst js2-digit-p (c)
5653 (and (<= ?0 c) (<= c ?9)))
5654
5655 (defun js2-js-space-p (c)
5656 (if (<= c 127)
5657 (memq c '(#x20 #x9 #xB #xC #xD))
5658 (or
5659 (eq c #xA0)
5660 ;; TODO: change this nil to check for Unicode space character
5661 nil)))
5662
5663 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5664
5665 (defun js2-skip-line ()
5666 "Skip to end of line."
5667 (while (not (memq (js2-get-char) js2-eol-chars)))
5668 (js2-unget-char)
5669 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5670
5671 (defun js2-init-scanner (&optional buf line)
5672 "Create token stream for BUF starting on LINE.
5673 BUF defaults to `current-buffer' and LINE defaults to 1.
5674
5675 A buffer can only have one scanner active at a time, which yields
5676 dramatically simpler code than using a defstruct. If you need to
5677 have simultaneous scanners in a buffer, copy the regions to scan
5678 into temp buffers."
5679 (with-current-buffer (or buf (current-buffer))
5680 (setq js2-ts-dirty-line nil
5681 js2-ts-hit-eof nil
5682 js2-ts-line-start 0
5683 js2-ts-lineno (or line 1)
5684 js2-ts-line-end-char -1
5685 js2-ts-cursor (point-min)
5686 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5687 js2-ti-tokens-cursor 0
5688 js2-ti-lookahead 0
5689 js2-ts-is-xml-attribute nil
5690 js2-ts-xml-is-tag-content nil
5691 js2-ts-xml-open-tags-count 0
5692 js2-ts-string-buffer nil)))
5693
5694 ;; This function uses the cached op, string and number fields in
5695 ;; TokenStream; if getToken has been called since the passed token
5696 ;; was scanned, the op or string printed may be incorrect.
5697 (defun js2-token-to-string (token)
5698 ;; Not sure where this function is used in Rhino. Not tested.
5699 (if (not js2-debug-print-trees)
5700 ""
5701 (let ((name (js2-tt-name token)))
5702 (cond
5703 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5704 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5705 (concat name " `" (js2-current-token-string) "'"))
5706 ((eq token js2-NUMBER)
5707 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5708 (t
5709 name)))))
5710
5711 (defconst js2-keywords
5712 '(break
5713 case catch class const continue
5714 debugger default delete do
5715 else extends export
5716 false finally for function
5717 if in instanceof import
5718 let
5719 new null
5720 return
5721 super switch
5722 this throw true try typeof
5723 var void
5724 while with
5725 yield))
5726
5727 ;; Token names aren't exactly the same as the keywords, unfortunately.
5728 ;; E.g. delete is js2-DELPROP.
5729 (defconst js2-kwd-tokens
5730 (let ((table (make-vector js2-num-tokens nil))
5731 (tokens
5732 (list js2-BREAK
5733 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5734 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5735 js2-ELSE js2-EXPORT
5736 js2-ELSE js2-EXTENDS js2-EXPORT
5737 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5738 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5739 js2-LET
5740 js2-NEW js2-NULL
5741 js2-RETURN
5742 js2-SUPER js2-SWITCH
5743 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5744 js2-VAR
5745 js2-WHILE js2-WITH
5746 js2-YIELD)))
5747 (dolist (i tokens)
5748 (aset table i 'font-lock-keyword-face))
5749 (aset table js2-STRING 'font-lock-string-face)
5750 (aset table js2-REGEXP 'font-lock-string-face)
5751 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5752 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5753 (aset table js2-COMMENT 'font-lock-comment-face)
5754 (aset table js2-THIS 'font-lock-builtin-face)
5755 (aset table js2-SUPER 'font-lock-builtin-face)
5756 (aset table js2-VOID 'font-lock-constant-face)
5757 (aset table js2-NULL 'font-lock-constant-face)
5758 (aset table js2-TRUE 'font-lock-constant-face)
5759 (aset table js2-FALSE 'font-lock-constant-face)
5760 (aset table js2-NOT 'font-lock-negation-char-face)
5761 table)
5762 "Vector whose values are non-nil for tokens that are keywords.
5763 The values are default faces to use for highlighting the keywords.")
5764
5765 ;; FIXME: Support strict mode-only future reserved words, after we know
5766 ;; which parts scopes are in strict mode, and which are not.
5767 (defconst js2-reserved-words '(class enum export extends import static super)
5768 "Future reserved keywords in ECMAScript 5.1.")
5769
5770 (defconst js2-keyword-names
5771 (let ((table (make-hash-table :test 'equal)))
5772 (cl-loop for k in js2-keywords
5773 do (puthash
5774 (symbol-name k) ; instanceof
5775 (intern (concat "js2-"
5776 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5777 table))
5778 table)
5779 "JavaScript keywords by name, mapped to their symbols.")
5780
5781 (defconst js2-reserved-word-names
5782 (let ((table (make-hash-table :test 'equal)))
5783 (cl-loop for k in js2-reserved-words
5784 do
5785 (puthash (symbol-name k) 'js2-RESERVED table))
5786 table)
5787 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5788
5789 (defun js2-collect-string (buf)
5790 "Convert BUF, a list of chars, to a string.
5791 Reverses BUF before converting."
5792 (if buf
5793 (apply #'string (nreverse buf))
5794 ""))
5795
5796 (defun js2-string-to-keyword (s)
5797 "Return token for S, a string, if S is a keyword or reserved word.
5798 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5799 (or (gethash s js2-keyword-names)
5800 (gethash s js2-reserved-word-names)))
5801
5802 (defsubst js2-ts-set-char-token-bounds (token)
5803 "Used when next token is one character."
5804 (setf (js2-token-beg token) (1- js2-ts-cursor)
5805 (js2-token-end token) js2-ts-cursor))
5806
5807 (defsubst js2-ts-return (token type)
5808 "Update the `end' and `type' slots of TOKEN,
5809 then throw `return' with value TYPE."
5810 (setf (js2-token-end token) js2-ts-cursor
5811 (js2-token-type token) type)
5812 (throw 'return type))
5813
5814 (defun js2-x-digit-to-int (c accumulator)
5815 "Build up a hex number.
5816 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5817 corresponding number. Otherwise return -1."
5818 (catch 'return
5819 (catch 'check
5820 ;; Use 0..9 < A..Z < a..z
5821 (cond
5822 ((<= c ?9)
5823 (cl-decf c ?0)
5824 (if (<= 0 c)
5825 (throw 'check nil)))
5826 ((<= c ?F)
5827 (when (<= ?A c)
5828 (cl-decf c (- ?A 10))
5829 (throw 'check nil)))
5830 ((<= c ?f)
5831 (when (<= ?a c)
5832 (cl-decf c (- ?a 10))
5833 (throw 'check nil))))
5834 (throw 'return -1))
5835 (logior c (lsh accumulator 4))))
5836
5837 (defun js2-get-token (&optional modifier)
5838 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5839 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5840 next saved token.
5841
5842 This function will not return a newline (js2-EOL) - instead, it
5843 gobbles newlines until it finds a non-newline token. Call
5844 `js2-peek-token-or-eol' when you care about newlines.
5845
5846 This function will also not return a js2-COMMENT. Instead, it
5847 records comments found in `js2-scanned-comments'. If the token
5848 returned by this function immediately follows a jsdoc comment,
5849 the token is flagged as such."
5850 (if (zerop js2-ti-lookahead)
5851 (js2-get-token-internal modifier)
5852 (cl-decf js2-ti-lookahead)
5853 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5854 (let ((tt (js2-current-token-type)))
5855 (cl-assert (not (= tt js2-EOL)))
5856 tt)))
5857
5858 (defun js2-unget-token ()
5859 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5860 (cl-incf js2-ti-lookahead)
5861 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5862
5863 (defun js2-get-token-internal (modifier)
5864 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5865 (tt (js2-token-type token))
5866 saw-eol
5867 face)
5868 ;; process comments
5869 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5870 (if (= tt js2-EOL)
5871 (setq saw-eol t)
5872 (setq saw-eol nil)
5873 (when js2-record-comments
5874 (js2-record-comment token)))
5875 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5876 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5877 tt (js2-token-type token)))
5878
5879 (when saw-eol
5880 (setf (js2-token-follows-eol-p token) t))
5881
5882 ;; perform lexical fontification as soon as token is scanned
5883 (when js2-parse-ide-mode
5884 (cond
5885 ((cl-minusp tt)
5886 (js2-record-face 'js2-error token))
5887 ((setq face (aref js2-kwd-tokens tt))
5888 (js2-record-face face token))
5889 ((and (= tt js2-NAME)
5890 (equal (js2-token-string token) "undefined"))
5891 (js2-record-face 'font-lock-constant-face token))))
5892 tt))
5893
5894 (defsubst js2-string-to-number (str base)
5895 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5896 (condition-case nil
5897 (string-to-number str base)
5898 (overflow-error -1)))
5899
5900 (defun js2-get-token-internal-1 (modifier)
5901 "Return next JavaScript token type, an int such as js2-RETURN.
5902 During operation, creates an instance of `js2-token' struct, sets
5903 its relevant fields and puts it into `js2-ti-tokens'."
5904 (let (identifier-start
5905 is-unicode-escape-start c
5906 contains-escape escape-val str result base
5907 look-for-slash continue tt legacy-octal
5908 (token (js2-new-token 0)))
5909 (setq
5910 tt
5911 (catch 'return
5912 (when (eq modifier 'TEMPLATE_TAIL)
5913 (setf (js2-token-beg token) (1- js2-ts-cursor))
5914 (throw 'return (js2-get-string-or-template-token ?` token)))
5915 (while t
5916 ;; Eat whitespace, possibly sensitive to newlines.
5917 (setq continue t)
5918 (while continue
5919 (setq c (js2-get-char))
5920 (cond
5921 ((eq c js2-EOF_CHAR)
5922 (js2-unget-char)
5923 (js2-ts-set-char-token-bounds token)
5924 (throw 'return js2-EOF))
5925 ((eq c ?\n)
5926 (js2-ts-set-char-token-bounds token)
5927 (setq js2-ts-dirty-line nil)
5928 (throw 'return js2-EOL))
5929 ((not (js2-js-space-p c))
5930 (if (/= c ?-) ; in case end of HTML comment
5931 (setq js2-ts-dirty-line t))
5932 (setq continue nil))))
5933 ;; Assume the token will be 1 char - fixed up below.
5934 (js2-ts-set-char-token-bounds token)
5935 (when (eq c ?@)
5936 (throw 'return js2-XMLATTR))
5937 ;; identifier/keyword/instanceof?
5938 ;; watch out for starting with a <backslash>
5939 (cond
5940 ((eq c ?\\)
5941 (setq c (js2-get-char))
5942 (if (eq c ?u)
5943 (setq identifier-start t
5944 is-unicode-escape-start t
5945 js2-ts-string-buffer nil)
5946 (setq identifier-start nil)
5947 (js2-unget-char)
5948 (setq c ?\\)))
5949 (t
5950 (when (setq identifier-start (js2-identifier-start-p c))
5951 (setq js2-ts-string-buffer nil)
5952 (js2-add-to-string c))))
5953 (when identifier-start
5954 (setq contains-escape is-unicode-escape-start)
5955 (catch 'break
5956 (while t
5957 (if is-unicode-escape-start
5958 ;; strictly speaking we should probably push-back
5959 ;; all the bad characters if the <backslash>uXXXX
5960 ;; sequence is malformed. But since there isn't a
5961 ;; correct context(is there?) for a bad Unicode
5962 ;; escape sequence in an identifier, we can report
5963 ;; an error here.
5964 (progn
5965 (setq escape-val 0)
5966 (dotimes (_ 4)
5967 (setq c (js2-get-char)
5968 escape-val (js2-x-digit-to-int c escape-val))
5969 ;; Next check takes care of c < 0 and bad escape
5970 (if (cl-minusp escape-val)
5971 (throw 'break nil)))
5972 (if (cl-minusp escape-val)
5973 (js2-report-scan-error "msg.invalid.escape" t))
5974 (js2-add-to-string escape-val)
5975 (setq is-unicode-escape-start nil))
5976 (setq c (js2-get-char))
5977 (cond
5978 ((eq c ?\\)
5979 (setq c (js2-get-char))
5980 (if (eq c ?u)
5981 (setq is-unicode-escape-start t
5982 contains-escape t)
5983 (js2-report-scan-error "msg.illegal.character" t)))
5984 (t
5985 (if (or (eq c js2-EOF_CHAR)
5986 (not (js2-identifier-part-p c)))
5987 (throw 'break nil))
5988 (js2-add-to-string c))))))
5989 (js2-unget-char)
5990 (setf str (js2-collect-string js2-ts-string-buffer)
5991 (js2-token-end token) js2-ts-cursor)
5992 ;; FIXME: Invalid in ES5 and ES6, see
5993 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5994 ;; Probably should just drop this conditional.
5995 (unless contains-escape
5996 ;; OPT we shouldn't have to make a string (object!) to
5997 ;; check if it's a keyword.
5998 ;; Return the corresponding token if it's a keyword
5999 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6000 (setq result (js2-string-to-keyword str)))
6001 (if (and (< js2-language-version 170)
6002 (memq result '(js2-LET js2-YIELD)))
6003 ;; LET and YIELD are tokens only in 1.7 and later
6004 (setq result 'js2-NAME))
6005 (when (eq result 'js2-RESERVED)
6006 (setf (js2-token-string token) str))
6007 (throw 'return (js2-tt-code result))))
6008 ;; If we want to intern these as Rhino does, just use (intern str)
6009 (setf (js2-token-string token) str)
6010 (throw 'return js2-NAME)) ; end identifier/kwd check
6011 ;; is it a number?
6012 (when (or (js2-digit-p c)
6013 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6014 (setq js2-ts-string-buffer nil
6015 base 10)
6016 (when (eq c ?0)
6017 (setq c (js2-get-char))
6018 (cond
6019 ((or (eq c ?x) (eq c ?X))
6020 (setq base 16)
6021 (setq c (js2-get-char)))
6022 ((and (or (eq c ?b) (eq c ?B))
6023 (>= js2-language-version 200))
6024 (setq base 2)
6025 (setq c (js2-get-char)))
6026 ((and (or (eq c ?o) (eq c ?O))
6027 (>= js2-language-version 200))
6028 (setq base 8)
6029 (setq legacy-octal nil)
6030 (setq c (js2-get-char)))
6031 ((js2-digit-p c)
6032 (setq base 'maybe-8))
6033 (t
6034 (js2-add-to-string ?0))))
6035 (cond
6036 ((eq base 16)
6037 (if (> 0 (js2-x-digit-to-int c 0))
6038 (js2-report-scan-error "msg.missing.hex.digits")
6039 (while (<= 0 (js2-x-digit-to-int c 0))
6040 (js2-add-to-string c)
6041 (setq c (js2-get-char)))))
6042 ((eq base 2)
6043 (if (not (memq c '(?0 ?1)))
6044 (js2-report-scan-error "msg.missing.binary.digits")
6045 (while (memq c '(?0 ?1))
6046 (js2-add-to-string c)
6047 (setq c (js2-get-char)))))
6048 ((eq base 8)
6049 (if (or (> ?0 c) (< ?7 c))
6050 (js2-report-scan-error "msg.missing.octal.digits")
6051 (while (and (<= ?0 c) (>= ?7 c))
6052 (js2-add-to-string c)
6053 (setq c (js2-get-char)))))
6054 (t
6055 (while (and (<= ?0 c) (<= c ?9))
6056 ;; We permit 08 and 09 as decimal numbers, which
6057 ;; makes our behavior a superset of the ECMA
6058 ;; numeric grammar. We might not always be so
6059 ;; permissive, so we warn about it.
6060 (when (and (eq base 'maybe-8) (>= c ?8))
6061 (js2-report-warning "msg.bad.octal.literal"
6062 (if (eq c ?8) "8" "9"))
6063 (setq base 10))
6064 (js2-add-to-string c)
6065 (setq c (js2-get-char)))
6066 (when (eq base 'maybe-8)
6067 (setq base 8
6068 legacy-octal t))))
6069 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6070 (when (eq c ?.)
6071 (cl-loop do
6072 (js2-add-to-string c)
6073 (setq c (js2-get-char))
6074 while (js2-digit-p c)))
6075 (when (memq c '(?e ?E))
6076 (js2-add-to-string c)
6077 (setq c (js2-get-char))
6078 (when (memq c '(?+ ?-))
6079 (js2-add-to-string c)
6080 (setq c (js2-get-char)))
6081 (unless (js2-digit-p c)
6082 (js2-report-scan-error "msg.missing.exponent" t))
6083 (cl-loop do
6084 (js2-add-to-string c)
6085 (setq c (js2-get-char))
6086 while (js2-digit-p c))))
6087 (js2-unget-char)
6088 (let ((str (js2-set-string-from-buffer token)))
6089 (setf (js2-token-number token) (js2-string-to-number str base)
6090 (js2-token-number-base token) base
6091 (js2-token-number-legacy-octal-p token) (and (= base 8) legacy-octal)))
6092 (throw 'return js2-NUMBER))
6093 ;; is it a string?
6094 (when (or (memq c '(?\" ?\'))
6095 (and (>= js2-language-version 200)
6096 (= c ?`)))
6097 (throw 'return
6098 (js2-get-string-or-template-token c token)))
6099 (js2-ts-return token
6100 (cl-case c
6101 (?\;
6102 (throw 'return js2-SEMI))
6103 (?\[
6104 (throw 'return js2-LB))
6105 (?\]
6106 (throw 'return js2-RB))
6107 (?{
6108 (throw 'return js2-LC))
6109 (?}
6110 (throw 'return js2-RC))
6111 (?\(
6112 (throw 'return js2-LP))
6113 (?\)
6114 (throw 'return js2-RP))
6115 (?,
6116 (throw 'return js2-COMMA))
6117 (??
6118 (throw 'return js2-HOOK))
6119 (?:
6120 (if (js2-match-char ?:)
6121 js2-COLONCOLON
6122 (throw 'return js2-COLON)))
6123 (?.
6124 (if (js2-match-char ?.)
6125 (if (js2-match-char ?.)
6126 js2-TRIPLEDOT js2-DOTDOT)
6127 (if (js2-match-char ?\()
6128 js2-DOTQUERY
6129 (throw 'return js2-DOT))))
6130 (?|
6131 (if (js2-match-char ?|)
6132 (throw 'return js2-OR)
6133 (if (js2-match-char ?=)
6134 js2-ASSIGN_BITOR
6135 (throw 'return js2-BITOR))))
6136 (?^
6137 (if (js2-match-char ?=)
6138 js2-ASSIGN_BITOR
6139 (throw 'return js2-BITXOR)))
6140 (?&
6141 (if (js2-match-char ?&)
6142 (throw 'return js2-AND)
6143 (if (js2-match-char ?=)
6144 js2-ASSIGN_BITAND
6145 (throw 'return js2-BITAND))))
6146 (?=
6147 (if (js2-match-char ?=)
6148 (if (js2-match-char ?=)
6149 js2-SHEQ
6150 (throw 'return js2-EQ))
6151 (if (js2-match-char ?>)
6152 (js2-ts-return token js2-ARROW)
6153 (throw 'return js2-ASSIGN))))
6154 (?!
6155 (if (js2-match-char ?=)
6156 (if (js2-match-char ?=)
6157 js2-SHNE
6158 js2-NE)
6159 (throw 'return js2-NOT)))
6160 (?<
6161 ;; NB:treat HTML begin-comment as comment-till-eol
6162 (when (js2-match-char ?!)
6163 (when (js2-match-char ?-)
6164 (when (js2-match-char ?-)
6165 (js2-skip-line)
6166 (setf (js2-token-comment-type (js2-current-token)) 'html)
6167 (throw 'return js2-COMMENT)))
6168 (js2-unget-char))
6169 (if (js2-match-char ?<)
6170 (if (js2-match-char ?=)
6171 js2-ASSIGN_LSH
6172 js2-LSH)
6173 (if (js2-match-char ?=)
6174 js2-LE
6175 (throw 'return js2-LT))))
6176 (?>
6177 (if (js2-match-char ?>)
6178 (if (js2-match-char ?>)
6179 (if (js2-match-char ?=)
6180 js2-ASSIGN_URSH
6181 js2-URSH)
6182 (if (js2-match-char ?=)
6183 js2-ASSIGN_RSH
6184 js2-RSH))
6185 (if (js2-match-char ?=)
6186 js2-GE
6187 (throw 'return js2-GT))))
6188 (?*
6189 (if (js2-match-char ?=)
6190 js2-ASSIGN_MUL
6191 (throw 'return js2-MUL)))
6192 (?/
6193 ;; is it a // comment?
6194 (when (js2-match-char ?/)
6195 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6196 (js2-skip-line)
6197 (setf (js2-token-comment-type token) 'line)
6198 ;; include newline so highlighting goes to end of
6199 ;; window, if there actually is a newline; if we
6200 ;; hit eof, then implicitly there isn't
6201 (unless js2-ts-hit-eof
6202 (cl-incf (js2-token-end token)))
6203 (throw 'return js2-COMMENT))
6204 ;; is it a /* comment?
6205 (when (js2-match-char ?*)
6206 (setf look-for-slash nil
6207 (js2-token-beg token) (- js2-ts-cursor 2)
6208 (js2-token-comment-type token)
6209 (if (js2-match-char ?*)
6210 (progn
6211 (setq look-for-slash t)
6212 'jsdoc)
6213 'block))
6214 (while t
6215 (setq c (js2-get-char))
6216 (cond
6217 ((eq c js2-EOF_CHAR)
6218 (setf (js2-token-end token) (1- js2-ts-cursor))
6219 (js2-report-error "msg.unterminated.comment")
6220 (throw 'return js2-COMMENT))
6221 ((eq c ?*)
6222 (setq look-for-slash t))
6223 ((eq c ?/)
6224 (if look-for-slash
6225 (js2-ts-return token js2-COMMENT)))
6226 (t
6227 (setf look-for-slash nil
6228 (js2-token-end token) js2-ts-cursor)))))
6229 (if (js2-match-char ?=)
6230 js2-ASSIGN_DIV
6231 (throw 'return js2-DIV)))
6232 (?#
6233 (when js2-skip-preprocessor-directives
6234 (js2-skip-line)
6235 (setf (js2-token-comment-type token) 'preprocessor
6236 (js2-token-end token) js2-ts-cursor)
6237 (throw 'return js2-COMMENT))
6238 (throw 'return js2-ERROR))
6239 (?%
6240 (if (js2-match-char ?=)
6241 js2-ASSIGN_MOD
6242 (throw 'return js2-MOD)))
6243 (?~
6244 (throw 'return js2-BITNOT))
6245 (?+
6246 (if (js2-match-char ?=)
6247 js2-ASSIGN_ADD
6248 (if (js2-match-char ?+)
6249 js2-INC
6250 (throw 'return js2-ADD))))
6251 (?-
6252 (cond
6253 ((js2-match-char ?=)
6254 (setq c js2-ASSIGN_SUB))
6255 ((js2-match-char ?-)
6256 (unless js2-ts-dirty-line
6257 ;; treat HTML end-comment after possible whitespace
6258 ;; after line start as comment-until-eol
6259 (when (js2-match-char ?>)
6260 (js2-skip-line)
6261 (setf (js2-token-comment-type (js2-current-token)) 'html)
6262 (throw 'return js2-COMMENT)))
6263 (setq c js2-DEC))
6264 (t
6265 (setq c js2-SUB)))
6266 (setq js2-ts-dirty-line t)
6267 c)
6268 (otherwise
6269 (js2-report-scan-error "msg.illegal.character")))))))
6270 (setf (js2-token-type token) tt)
6271 token))
6272
6273 (defun js2-get-string-or-template-token (quote-char token)
6274 ;; We attempt to accumulate a string the fast way, by
6275 ;; building it directly out of the reader. But if there
6276 ;; are any escaped characters in the string, we revert to
6277 ;; building it out of a string buffer.
6278 (let ((c (js2-get-char))
6279 js2-ts-string-buffer
6280 nc c1 val escape-val)
6281 (catch 'break
6282 (while (/= c quote-char)
6283 (catch 'continue
6284 (when (eq c js2-EOF_CHAR)
6285 (js2-unget-char)
6286 (js2-report-error "msg.unterminated.string.lit")
6287 (throw 'break nil))
6288 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6289 (js2-unget-char)
6290 (js2-report-error "msg.unterminated.string.lit")
6291 (throw 'break nil))
6292 (when (eq c ?\\)
6293 ;; We've hit an escaped character
6294 (setq c (js2-get-char))
6295 (cl-case c
6296 (?b (setq c ?\b))
6297 (?f (setq c ?\f))
6298 (?n (setq c ?\n))
6299 (?r (setq c ?\r))
6300 (?t (setq c ?\t))
6301 (?v (setq c ?\v))
6302 (?u
6303 (setq c1 (js2-read-unicode-escape))
6304 (if js2-parse-ide-mode
6305 (if c1
6306 (progn
6307 ;; just copy the string in IDE-mode
6308 (js2-add-to-string ?\\)
6309 (js2-add-to-string ?u)
6310 (dotimes (_ 3)
6311 (js2-add-to-string (js2-get-char)))
6312 (setq c (js2-get-char))) ; added at end of loop
6313 ;; flag it as an invalid escape
6314 (js2-report-warning "msg.invalid.escape"
6315 nil (- js2-ts-cursor 2) 6))
6316 ;; Get 4 hex digits; if the u escape is not
6317 ;; followed by 4 hex digits, use 'u' + the
6318 ;; literal character sequence that follows.
6319 (js2-add-to-string ?u)
6320 (setq escape-val 0)
6321 (dotimes (_ 4)
6322 (setq c (js2-get-char)
6323 escape-val (js2-x-digit-to-int c escape-val))
6324 (if (cl-minusp escape-val)
6325 (throw 'continue nil))
6326 (js2-add-to-string c))
6327 ;; prepare for replace of stored 'u' sequence by escape value
6328 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6329 c escape-val)))
6330 (?x
6331 ;; Get 2 hex digits, defaulting to 'x'+literal
6332 ;; sequence, as above.
6333 (setq c (js2-get-char)
6334 escape-val (js2-x-digit-to-int c 0))
6335 (if (cl-minusp escape-val)
6336 (progn
6337 (js2-add-to-string ?x)
6338 (throw 'continue nil))
6339 (setq c1 c
6340 c (js2-get-char)
6341 escape-val (js2-x-digit-to-int c escape-val))
6342 (if (cl-minusp escape-val)
6343 (progn
6344 (js2-add-to-string ?x)
6345 (js2-add-to-string c1)
6346 (throw 'continue nil))
6347 ;; got 2 hex digits
6348 (setq c escape-val))))
6349 (?\n
6350 ;; Remove line terminator after escape to follow
6351 ;; SpiderMonkey and C/C++
6352 (setq c (js2-get-char))
6353 (throw 'continue nil))
6354 (t
6355 (when (and (<= ?0 c) (< c ?8))
6356 (setq val (- c ?0)
6357 c (js2-get-char))
6358 (when (and (<= ?0 c) (< c ?8))
6359 (setq val (- (+ (* 8 val) c) ?0)
6360 c (js2-get-char))
6361 (when (and (<= ?0 c)
6362 (< c ?8)
6363 (< val #o37))
6364 ;; c is 3rd char of octal sequence only
6365 ;; if the resulting val <= 0377
6366 (setq val (- (+ (* 8 val) c) ?0)
6367 c (js2-get-char))))
6368 (js2-unget-char)
6369 (setq c val)))))
6370 (when (and (eq quote-char ?`) (eq c ?$))
6371 (when (eq (setq nc (js2-get-char)) ?\{)
6372 (throw 'break nil))
6373 (js2-unget-char))
6374 (js2-add-to-string c)
6375 (setq c (js2-get-char)))))
6376 (js2-set-string-from-buffer token)
6377 (if (not (eq quote-char ?`))
6378 js2-STRING
6379 (if (and (eq c ?$) (eq nc ?\{))
6380 js2-TEMPLATE_HEAD
6381 js2-NO_SUBS_TEMPLATE))))
6382
6383 (defun js2-read-regexp (start-tt)
6384 "Called by parser when it gets / or /= in literal context."
6385 (let (c err
6386 in-class ; inside a '[' .. ']' character-class
6387 flags
6388 (continue t)
6389 (token (js2-new-token 0)))
6390 (setq js2-ts-string-buffer nil)
6391 (if (eq start-tt js2-ASSIGN_DIV)
6392 ;; mis-scanned /=
6393 (js2-add-to-string ?=)
6394 (if (not (eq start-tt js2-DIV))
6395 (error "failed assertion")))
6396 (while (and (not err)
6397 (or (/= (setq c (js2-get-char)) ?/)
6398 in-class))
6399 (cond
6400 ((or (= c ?\n)
6401 (= c js2-EOF_CHAR))
6402 (setf (js2-token-end token) (1- js2-ts-cursor)
6403 err t
6404 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6405 (js2-report-error "msg.unterminated.re.lit"))
6406 (t (cond
6407 ((= c ?\\)
6408 (js2-add-to-string c)
6409 (setq c (js2-get-char)))
6410 ((= c ?\[)
6411 (setq in-class t))
6412 ((= c ?\])
6413 (setq in-class nil)))
6414 (js2-add-to-string c))))
6415 (unless err
6416 (while continue
6417 (cond
6418 ((js2-match-char ?g)
6419 (push ?g flags))
6420 ((js2-match-char ?i)
6421 (push ?i flags))
6422 ((js2-match-char ?m)
6423 (push ?m flags))
6424 ((and (js2-match-char ?u)
6425 (>= js2-language-version 200))
6426 (push ?u flags))
6427 ((and (js2-match-char ?y)
6428 (>= js2-language-version 200))
6429 (push ?y flags))
6430 (t
6431 (setq continue nil))))
6432 (if (js2-alpha-p (js2-peek-char))
6433 (js2-report-scan-error "msg.invalid.re.flag" t
6434 js2-ts-cursor 1))
6435 (js2-set-string-from-buffer token))
6436 (js2-collect-string flags)))
6437
6438 (defun js2-get-first-xml-token ()
6439 (setq js2-ts-xml-open-tags-count 0
6440 js2-ts-is-xml-attribute nil
6441 js2-ts-xml-is-tag-content nil)
6442 (js2-unget-char)
6443 (js2-get-next-xml-token))
6444
6445 (defun js2-xml-discard-string (token)
6446 "Throw away the string in progress and flag an XML parse error."
6447 (setf js2-ts-string-buffer nil
6448 (js2-token-string token) nil)
6449 (js2-report-scan-error "msg.XML.bad.form" t))
6450
6451 (defun js2-get-next-xml-token ()
6452 (setq js2-ts-string-buffer nil) ; for recording the XML
6453 (let ((token (js2-new-token 0))
6454 c result)
6455 (setq result
6456 (catch 'return
6457 (while t
6458 (setq c (js2-get-char))
6459 (cond
6460 ((= c js2-EOF_CHAR)
6461 (throw 'return js2-ERROR))
6462 (js2-ts-xml-is-tag-content
6463 (cl-case c
6464 (?>
6465 (js2-add-to-string c)
6466 (setq js2-ts-xml-is-tag-content nil
6467 js2-ts-is-xml-attribute nil))
6468 (?/
6469 (js2-add-to-string c)
6470 (when (eq ?> (js2-peek-char))
6471 (setq c (js2-get-char))
6472 (js2-add-to-string c)
6473 (setq js2-ts-xml-is-tag-content nil)
6474 (cl-decf js2-ts-xml-open-tags-count)))
6475 (?{
6476 (js2-unget-char)
6477 (js2-set-string-from-buffer token)
6478 (throw 'return js2-XML))
6479 ((?\' ?\")
6480 (js2-add-to-string c)
6481 (unless (js2-read-quoted-string c token)
6482 (throw 'return js2-ERROR)))
6483 (?=
6484 (js2-add-to-string c)
6485 (setq js2-ts-is-xml-attribute t))
6486 ((? ?\t ?\r ?\n)
6487 (js2-add-to-string c))
6488 (t
6489 (js2-add-to-string c)
6490 (setq js2-ts-is-xml-attribute nil)))
6491 (when (and (not js2-ts-xml-is-tag-content)
6492 (zerop js2-ts-xml-open-tags-count))
6493 (js2-set-string-from-buffer token)
6494 (throw 'return js2-XMLEND)))
6495 (t
6496 ;; else not tag content
6497 (cl-case c
6498 (?<
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 (setq c (js2-peek-char))
6506 (cl-case c
6507 (?-
6508 (setq c (js2-get-char)) ;; skip -
6509 (js2-add-to-string c)
6510 (if (eq c ?-)
6511 (progn
6512 (js2-add-to-string c)
6513 (unless (js2-read-xml-comment token)
6514 (throw 'return js2-ERROR)))
6515 (js2-xml-discard-string token)
6516 (throw 'return js2-ERROR)))
6517 (?\[
6518 (setq c (js2-get-char)) ;; skip [
6519 (js2-add-to-string c)
6520 (if (and (= (js2-get-char) ?C)
6521 (= (js2-get-char) ?D)
6522 (= (js2-get-char) ?A)
6523 (= (js2-get-char) ?T)
6524 (= (js2-get-char) ?A)
6525 (= (js2-get-char) ?\[))
6526 (progn
6527 (js2-add-to-string ?C)
6528 (js2-add-to-string ?D)
6529 (js2-add-to-string ?A)
6530 (js2-add-to-string ?T)
6531 (js2-add-to-string ?A)
6532 (js2-add-to-string ?\[)
6533 (unless (js2-read-cdata token)
6534 (throw 'return js2-ERROR)))
6535 (js2-xml-discard-string token)
6536 (throw 'return js2-ERROR)))
6537 (t
6538 (unless (js2-read-entity token)
6539 (throw 'return js2-ERROR))))
6540 ;; Allow bare CDATA section, e.g.:
6541 ;; let xml = <![CDATA[ foo bar baz ]]>;
6542 (when (zerop js2-ts-xml-open-tags-count)
6543 (throw 'return js2-XMLEND)))
6544 (??
6545 (setq c (js2-get-char)) ;; skip ?
6546 (js2-add-to-string c)
6547 (unless (js2-read-PI token)
6548 (throw 'return js2-ERROR)))
6549 (?/
6550 ;; end tag
6551 (setq c (js2-get-char)) ;; skip /
6552 (js2-add-to-string c)
6553 (when (zerop js2-ts-xml-open-tags-count)
6554 (js2-xml-discard-string token)
6555 (throw 'return js2-ERROR))
6556 (setq js2-ts-xml-is-tag-content t)
6557 (cl-decf js2-ts-xml-open-tags-count))
6558 (t
6559 ;; start tag
6560 (setq js2-ts-xml-is-tag-content t)
6561 (cl-incf js2-ts-xml-open-tags-count))))
6562 (?{
6563 (js2-unget-char)
6564 (js2-set-string-from-buffer token)
6565 (throw 'return js2-XML))
6566 (t
6567 (js2-add-to-string c))))))))
6568 (setf (js2-token-end token) js2-ts-cursor)
6569 (setf (js2-token-type token) result)
6570 result))
6571
6572 (defun js2-read-quoted-string (quote token)
6573 (let (c)
6574 (catch 'return
6575 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6576 (js2-add-to-string c)
6577 (if (eq c quote)
6578 (throw 'return t)))
6579 (js2-xml-discard-string token) ;; throw away string in progress
6580 nil)))
6581
6582 (defun js2-read-xml-comment (token)
6583 (let ((c (js2-get-char)))
6584 (catch 'return
6585 (while (/= c js2-EOF_CHAR)
6586 (catch 'continue
6587 (js2-add-to-string c)
6588 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6589 (setq c (js2-get-char))
6590 (js2-add-to-string c)
6591 (if (eq (js2-peek-char) ?>)
6592 (progn
6593 (setq c (js2-get-char)) ;; skip >
6594 (js2-add-to-string c)
6595 (throw 'return t))
6596 (throw 'continue nil)))
6597 (setq c (js2-get-char))))
6598 (js2-xml-discard-string token)
6599 nil)))
6600
6601 (defun js2-read-cdata (token)
6602 (let ((c (js2-get-char)))
6603 (catch 'return
6604 (while (/= c js2-EOF_CHAR)
6605 (catch 'continue
6606 (js2-add-to-string c)
6607 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6608 (setq c (js2-get-char))
6609 (js2-add-to-string c)
6610 (if (eq (js2-peek-char) ?>)
6611 (progn
6612 (setq c (js2-get-char)) ;; Skip >
6613 (js2-add-to-string c)
6614 (throw 'return t))
6615 (throw 'continue nil)))
6616 (setq c (js2-get-char))))
6617 (js2-xml-discard-string token)
6618 nil)))
6619
6620 (defun js2-read-entity (token)
6621 (let ((decl-tags 1)
6622 c)
6623 (catch 'return
6624 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6625 (js2-add-to-string c)
6626 (cl-case c
6627 (?<
6628 (cl-incf decl-tags))
6629 (?>
6630 (cl-decf decl-tags)
6631 (if (zerop decl-tags)
6632 (throw 'return t)))))
6633 (js2-xml-discard-string token)
6634 nil)))
6635
6636 (defun js2-read-PI (token)
6637 "Scan an XML processing instruction."
6638 (let (c)
6639 (catch 'return
6640 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6641 (js2-add-to-string c)
6642 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6643 (setq c (js2-get-char)) ;; Skip >
6644 (js2-add-to-string c)
6645 (throw 'return t)))
6646 (js2-xml-discard-string token)
6647 nil)))
6648
6649 ;;; Highlighting
6650
6651 (defun js2-set-face (beg end face &optional record)
6652 "Fontify a region. If RECORD is non-nil, record for later."
6653 (when (cl-plusp js2-highlight-level)
6654 (setq beg (min (point-max) beg)
6655 beg (max (point-min) beg)
6656 end (min (point-max) end)
6657 end (max (point-min) end))
6658 (if record
6659 (push (list beg end face) js2-mode-fontifications)
6660 (put-text-property beg end 'font-lock-face face))))
6661
6662 (defsubst js2-clear-face (beg end)
6663 (remove-text-properties beg end '(font-lock-face nil
6664 help-echo nil
6665 point-entered nil
6666 cursor-sensor-functions nil
6667 c-in-sws nil)))
6668
6669 (defconst js2-ecma-global-props
6670 (concat "^"
6671 (regexp-opt
6672 '("Infinity" "NaN" "undefined" "arguments") t)
6673 "$")
6674 "Value properties of the Ecma-262 Global Object.
6675 Shown at or above `js2-highlight-level' 2.")
6676
6677 ;; might want to add the name "arguments" to this list?
6678 (defconst js2-ecma-object-props
6679 (concat "^"
6680 (regexp-opt
6681 '("prototype" "__proto__" "__parent__") t)
6682 "$")
6683 "Value properties of the Ecma-262 Object constructor.
6684 Shown at or above `js2-highlight-level' 2.")
6685
6686 (defconst js2-ecma-global-funcs
6687 (concat
6688 "^"
6689 (regexp-opt
6690 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6691 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6692 "$")
6693 "Function properties of the Ecma-262 Global object.
6694 Shown at or above `js2-highlight-level' 2.")
6695
6696 (defconst js2-ecma-number-props
6697 (concat "^"
6698 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6699 "NEGATIVE_INFINITY"
6700 "POSITIVE_INFINITY") t)
6701 "$")
6702 "Properties of the Ecma-262 Number constructor.
6703 Shown at or above `js2-highlight-level' 2.")
6704
6705 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6706 "Properties of the Ecma-262 Date constructor.
6707 Shown at or above `js2-highlight-level' 2.")
6708
6709 (defconst js2-ecma-math-props
6710 (concat "^"
6711 (regexp-opt
6712 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6713 t)
6714 "$")
6715 "Properties of the Ecma-262 Math object.
6716 Shown at or above `js2-highlight-level' 2.")
6717
6718 (defconst js2-ecma-math-funcs
6719 (concat "^"
6720 (regexp-opt
6721 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6722 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6723 "$")
6724 "Function properties of the Ecma-262 Math object.
6725 Shown at or above `js2-highlight-level' 2.")
6726
6727 (defconst js2-ecma-function-props
6728 (concat
6729 "^"
6730 (regexp-opt
6731 '(;; properties of the Object prototype object
6732 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6733 "toLocaleString" "toString" "valueOf"
6734 ;; properties of the Function prototype object
6735 "apply" "call"
6736 ;; properties of the Array prototype object
6737 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6738 "splice" "unshift"
6739 ;; properties of the String prototype object
6740 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6741 "localeCompare" "match" "replace" "search" "split" "substring"
6742 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6743 "toUpperCase"
6744 ;; properties of the Number prototype object
6745 "toExponential" "toFixed" "toPrecision"
6746 ;; properties of the Date prototype object
6747 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6748 "getMinutes" "getMonth" "getSeconds" "getTime"
6749 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6750 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6751 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6752 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6753 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6754 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6755 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6756 "toTimeString" "toUTCString"
6757 ;; properties of the RegExp prototype object
6758 "exec" "test"
6759 ;; properties of the JSON prototype object
6760 "parse" "stringify"
6761 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6762 "toSource" "__defineGetter__" "__defineSetter__"
6763 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6764 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6765 t)
6766 "$")
6767 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6768 Shown at or above `js2-highlight-level' 3.")
6769
6770 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6771 (let ((target-name (and target
6772 (js2-name-node-p target)
6773 (js2-name-node-name target)))
6774 (prop-name (if prop (js2-name-node-name prop)))
6775 (level2 (>= js2-highlight-level 2))
6776 (level3 (>= js2-highlight-level 3)))
6777 (when level2
6778 (let ((face
6779 (if call-p
6780 (cond
6781 ((and target prop)
6782 (cond
6783 ((and level3 (string-match js2-ecma-function-props prop-name))
6784 'font-lock-builtin-face)
6785 ((and target-name prop)
6786 (cond
6787 ((string= target-name "Date")
6788 (if (string-match js2-ecma-date-props prop-name)
6789 'font-lock-builtin-face))
6790 ((string= target-name "Math")
6791 (if (string-match js2-ecma-math-funcs prop-name)
6792 'font-lock-builtin-face))))))
6793 (prop
6794 (if (string-match js2-ecma-global-funcs prop-name)
6795 'font-lock-builtin-face)))
6796 (cond
6797 ((and target prop)
6798 (cond
6799 ((string= target-name "Number")
6800 (if (string-match js2-ecma-number-props prop-name)
6801 'font-lock-constant-face))
6802 ((string= target-name "Math")
6803 (if (string-match js2-ecma-math-props prop-name)
6804 'font-lock-constant-face))))
6805 (prop
6806 (if (string-match js2-ecma-object-props prop-name)
6807 'font-lock-constant-face))))))
6808 (when (and (not face) target (not call-p) prop-name)
6809 (setq face 'js2-object-property))
6810 (when face
6811 (let ((pos (+ (js2-node-pos parent) ; absolute
6812 (js2-node-pos prop)))) ; relative
6813 (js2-set-face pos
6814 (+ pos (js2-node-len prop))
6815 face 'record)))))))
6816
6817 (defun js2-parse-highlight-member-expr-node (node)
6818 "Perform syntax highlighting of EcmaScript built-in properties.
6819 The variable `js2-highlight-level' governs this highlighting."
6820 (let (face target prop name pos end parent call-p callee)
6821 (cond
6822 ;; case 1: simple name, e.g. foo
6823 ((js2-name-node-p node)
6824 (setq name (js2-name-node-name node))
6825 ;; possible for name to be nil in rare cases - saw it when
6826 ;; running js2-mode on an elisp buffer. Might as well try to
6827 ;; make it so js2-mode never barfs.
6828 (when name
6829 (setq face (if (string-match js2-ecma-global-props name)
6830 'font-lock-constant-face))
6831 (when face
6832 (setq pos (js2-node-pos node)
6833 end (+ pos (js2-node-len node)))
6834 (js2-set-face pos end face 'record))))
6835 ;; case 2: property access or function call
6836 ((or (js2-prop-get-node-p node)
6837 ;; highlight function call if expr is a prop-get node
6838 ;; or a plain name (i.e. unqualified function call)
6839 (and (setq call-p (js2-call-node-p node))
6840 (setq callee (js2-call-node-target node)) ; separate setq!
6841 (or (js2-prop-get-node-p callee)
6842 (js2-name-node-p callee))))
6843 (setq parent node
6844 node (if call-p callee node))
6845 (if (and call-p (js2-name-node-p callee))
6846 (setq prop callee)
6847 (setq target (js2-prop-get-node-left node)
6848 prop (js2-prop-get-node-right node)))
6849 (cond
6850 ((js2-name-node-p prop)
6851 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6852 (js2-parse-highlight-prop-get parent target prop call-p))
6853 ((js2-name-node-p target)
6854 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6855 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6856
6857 (defun js2-parse-highlight-member-expr-fn-name (expr)
6858 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6859 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6860 We currently only handle the case where the last component is a prop-get
6861 of a simple name. Called before EXPR has a parent node."
6862 (let (pos
6863 (name (and (js2-prop-get-node-p expr)
6864 (js2-prop-get-node-right expr))))
6865 (when (js2-name-node-p name)
6866 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6867 (js2-node-pos name)))
6868 (+ pos (js2-node-len name))
6869 'font-lock-function-name-face
6870 'record))))
6871
6872 ;; source: http://jsdoc.sourceforge.net/
6873 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6874 ;; allows type specifications, and needs work before entering the wild.
6875
6876 (defconst js2-jsdoc-param-tag-regexp
6877 (concat "^\\s-*\\*+\\s-*\\(@"
6878 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6879 "\\)"
6880 "\\s-*\\({[^}]+}\\)?" ; optional type
6881 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6882 "\\_>")
6883 "Matches jsdoc tags with optional type and optional param name.")
6884
6885 (defconst js2-jsdoc-typed-tag-regexp
6886 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6887 (regexp-opt
6888 '("enum"
6889 "extends"
6890 "field"
6891 "id"
6892 "implements"
6893 "lends"
6894 "mods"
6895 "requires"
6896 "return"
6897 "returns"
6898 "throw"
6899 "throws"))
6900 "\\)\\)\\s-*\\({[^}]+}\\)?")
6901 "Matches jsdoc tags with optional type.")
6902
6903 (defconst js2-jsdoc-arg-tag-regexp
6904 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6905 (regexp-opt
6906 '("alias"
6907 "augments"
6908 "borrows"
6909 "bug"
6910 "base"
6911 "config"
6912 "default"
6913 "define"
6914 "exception"
6915 "function"
6916 "member"
6917 "memberOf"
6918 "name"
6919 "namespace"
6920 "since"
6921 "suppress"
6922 "this"
6923 "throws"
6924 "type"
6925 "version"))
6926 "\\)\\)\\s-+\\([^ \t]+\\)")
6927 "Matches jsdoc tags with a single argument.")
6928
6929 (defconst js2-jsdoc-empty-tag-regexp
6930 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6931 (regexp-opt
6932 '("addon"
6933 "author"
6934 "class"
6935 "const"
6936 "constant"
6937 "constructor"
6938 "constructs"
6939 "deprecated"
6940 "desc"
6941 "description"
6942 "event"
6943 "example"
6944 "exec"
6945 "export"
6946 "fileoverview"
6947 "final"
6948 "function"
6949 "hidden"
6950 "ignore"
6951 "implicitCast"
6952 "inheritDoc"
6953 "inner"
6954 "interface"
6955 "license"
6956 "noalias"
6957 "noshadow"
6958 "notypecheck"
6959 "override"
6960 "owner"
6961 "preserve"
6962 "preserveTry"
6963 "private"
6964 "protected"
6965 "public"
6966 "static"
6967 "supported"
6968 ))
6969 "\\)\\)\\s-*")
6970 "Matches empty jsdoc tags.")
6971
6972 (defconst js2-jsdoc-link-tag-regexp
6973 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6974 "Matches a jsdoc link or code tag.")
6975
6976 (defconst js2-jsdoc-see-tag-regexp
6977 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6978 "Matches a jsdoc @see tag.")
6979
6980 (defconst js2-jsdoc-html-tag-regexp
6981 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6982 "Matches a simple (no attributes) html start- or end-tag.")
6983
6984 (defun js2-jsdoc-highlight-helper ()
6985 (js2-set-face (match-beginning 1)
6986 (match-end 1)
6987 'js2-jsdoc-tag)
6988 (if (match-beginning 2)
6989 (if (save-excursion
6990 (goto-char (match-beginning 2))
6991 (= (char-after) ?{))
6992 (js2-set-face (1+ (match-beginning 2))
6993 (1- (match-end 2))
6994 'js2-jsdoc-type)
6995 (js2-set-face (match-beginning 2)
6996 (match-end 2)
6997 'js2-jsdoc-value)))
6998 (if (match-beginning 3)
6999 (js2-set-face (match-beginning 3)
7000 (match-end 3)
7001 'js2-jsdoc-value)))
7002
7003 (defun js2-highlight-jsdoc (ast)
7004 "Highlight doc comment tags."
7005 (let ((comments (js2-ast-root-comments ast))
7006 beg end)
7007 (save-excursion
7008 (dolist (node comments)
7009 (when (eq (js2-comment-node-format node) 'jsdoc)
7010 (setq beg (js2-node-abs-pos node)
7011 end (+ beg (js2-node-len node)))
7012 (save-restriction
7013 (narrow-to-region beg end)
7014 (dolist (re (list js2-jsdoc-param-tag-regexp
7015 js2-jsdoc-typed-tag-regexp
7016 js2-jsdoc-arg-tag-regexp
7017 js2-jsdoc-link-tag-regexp
7018 js2-jsdoc-see-tag-regexp
7019 js2-jsdoc-empty-tag-regexp))
7020 (goto-char beg)
7021 (while (re-search-forward re nil t)
7022 (js2-jsdoc-highlight-helper)))
7023 ;; simple highlighting for html tags
7024 (goto-char beg)
7025 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7026 (js2-set-face (match-beginning 1)
7027 (match-end 1)
7028 'js2-jsdoc-html-tag-delimiter)
7029 (js2-set-face (match-beginning 2)
7030 (match-end 2)
7031 'js2-jsdoc-html-tag-name)
7032 (js2-set-face (match-beginning 3)
7033 (match-end 3)
7034 'js2-jsdoc-html-tag-delimiter))))))))
7035
7036 (defun js2-highlight-assign-targets (_node left right)
7037 "Highlight function properties and external variables."
7038 (let (leftpos name)
7039 ;; highlight vars and props assigned function values
7040 (when (or (js2-function-node-p right)
7041 (js2-class-node-p right))
7042 (cond
7043 ;; var foo = function() {...}
7044 ((js2-name-node-p left)
7045 (setq name left))
7046 ;; foo.bar.baz = function() {...}
7047 ((and (js2-prop-get-node-p left)
7048 (js2-name-node-p (js2-prop-get-node-right left)))
7049 (setq name (js2-prop-get-node-right left))))
7050 (when name
7051 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7052 (+ leftpos (js2-node-len name))
7053 'font-lock-function-name-face
7054 'record)))))
7055
7056 (defun js2-record-name-node (node)
7057 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7058 later. NODE must be a name node."
7059 (let ((leftpos (js2-node-abs-pos node)))
7060 (push (list node js2-current-scope
7061 leftpos
7062 (+ leftpos (js2-node-len node)))
7063 js2-recorded-identifiers)))
7064
7065 (defun js2-highlight-undeclared-vars ()
7066 "After entire parse is finished, look for undeclared variable references.
7067 We have to wait until entire buffer is parsed, since JavaScript permits var
7068 decls to occur after they're used.
7069
7070 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7071 it is considered declared."
7072 (let (name)
7073 (dolist (entry js2-recorded-identifiers)
7074 (cl-destructuring-bind (name-node scope pos end) entry
7075 (setq name (js2-name-node-name name-node))
7076 (unless (or (member name js2-global-externs)
7077 (member name js2-default-externs)
7078 (member name js2-additional-externs)
7079 (js2-get-defining-scope scope name pos))
7080 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7081 'js2-external-variable))))))
7082
7083 (defun js2--add-or-update-symbol (symbol inition used vars)
7084 "Add or update SYMBOL entry in VARS, an hash table.
7085 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7086 respectively meaning that SYMBOL is a mere declaration, an
7087 assignment or a function parameter; when USED is t, the symbol
7088 node is assumed to be an usage and thus added to the list stored
7089 in the cdr of the entry.
7090 "
7091 (let* ((nm (js2-name-node-name symbol))
7092 (es (js2-node-get-enclosing-scope symbol))
7093 (ds (js2-get-defining-scope es nm)))
7094 (when (and ds (not (equal nm "arguments")))
7095 (let* ((sym (js2-scope-get-symbol ds nm))
7096 (var (gethash sym vars))
7097 (err-var-p (js2-catch-node-p ds)))
7098 (unless inition
7099 (setq inition err-var-p))
7100 (if var
7101 (progn
7102 (when (and inition (not (equal (car var) ?P)))
7103 (setcar var inition))
7104 (when used
7105 (push symbol (cdr var))))
7106 ;; do not consider the declaration of catch parameter as an usage
7107 (when (and err-var-p used)
7108 (setq used nil))
7109 (puthash sym (cons inition (if used (list symbol))) vars))))))
7110
7111 (defun js2--classify-variables ()
7112 "Collect and classify variables declared or used within js2-mode-ast.
7113 Traverse the whole ast tree returning a summary of the variables
7114 usage as an hash-table, keyed by their corresponding symbol table
7115 entry.
7116 Each variable is described by a tuple where the car is a flag
7117 indicating whether the variable has been initialized and the cdr
7118 is a possibly empty list of name nodes where it is used. External
7119 symbols, i.e. those not present in the whole scopes hierarchy,
7120 are ignored."
7121 (let ((vars (make-hash-table :test #'eq :size 100)))
7122 (js2-visit-ast
7123 js2-mode-ast
7124 (lambda (node end-p)
7125 (when (null end-p)
7126 (cond
7127 ((js2-var-init-node-p node)
7128 ;; take note about possibly initialized declarations
7129 (let ((target (js2-var-init-node-target node))
7130 (initializer (js2-var-init-node-initializer node)))
7131 (when target
7132 (let* ((parent (js2-node-parent node))
7133 (grandparent (if parent (js2-node-parent parent)))
7134 (inited (not (null initializer))))
7135 (unless inited
7136 (setq inited
7137 (and grandparent
7138 (js2-for-in-node-p grandparent)
7139 (memq target
7140 (mapcar #'js2-var-init-node-target
7141 (js2-var-decl-node-kids
7142 (js2-for-in-node-iterator grandparent)))))))
7143 (js2--add-or-update-symbol target inited nil vars)))))
7144
7145 ((js2-assign-node-p node)
7146 ;; take note about assignments
7147 (let ((left (js2-assign-node-left node)))
7148 (when (js2-name-node-p left)
7149 (js2--add-or-update-symbol left t nil vars))))
7150
7151 ((js2-prop-get-node-p node)
7152 ;; handle x.y.z nodes, considering only x
7153 (let ((left (js2-prop-get-node-left node)))
7154 (when (js2-name-node-p left)
7155 (js2--add-or-update-symbol left nil t vars))))
7156
7157 ((js2-name-node-p node)
7158 ;; take note about used variables
7159 (let ((parent (js2-node-parent node)))
7160 (when parent
7161 (unless (or (and (js2-var-init-node-p parent) ; handled above
7162 (eq node (js2-var-init-node-target parent)))
7163 (and (js2-assign-node-p parent)
7164 (eq node (js2-assign-node-left parent)))
7165 (js2-prop-get-node-p parent))
7166 (let ((used t) inited)
7167 (cond
7168 ((and (js2-function-node-p parent)
7169 (js2-wrapper-function-p parent))
7170 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7171
7172 ((js2-for-in-node-p parent)
7173 (if (eq node (js2-for-in-node-iterator parent))
7174 (setq inited t used nil)))
7175
7176 ((js2-function-node-p parent)
7177 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7178 used nil)))
7179
7180 (unless used
7181 (let ((grandparent (js2-node-parent parent)))
7182 (when grandparent
7183 (setq used (js2-return-node-p grandparent)))))
7184
7185 (js2--add-or-update-symbol node inited used vars))))))))
7186 t))
7187 vars))
7188
7189 (defun js2--get-name-node (node)
7190 (cond
7191 ((js2-name-node-p node) node)
7192 ((js2-function-node-p node)
7193 (js2-function-node-name node))
7194 ((js2-class-node-p node)
7195 (js2-class-node-name node))
7196 ((js2-comp-loop-node-p node)
7197 (js2-comp-loop-node-iterator node))
7198 (t node)))
7199
7200 (defun js2--highlight-unused-variable (symbol info)
7201 (let ((name (js2-symbol-name symbol))
7202 (inited (car info))
7203 (refs (cdr info))
7204 pos len)
7205 (unless (and inited refs)
7206 (if refs
7207 (dolist (ref refs)
7208 (setq pos (js2-node-abs-pos ref))
7209 (setq len (js2-name-node-len ref))
7210 (js2-report-warning "msg.uninitialized.variable" name pos len
7211 'js2-warning))
7212 (when (or js2-warn-about-unused-function-arguments
7213 (not (eq inited ?P)))
7214 (let* ((symn (js2-symbol-ast-node symbol))
7215 (namen (js2--get-name-node symn)))
7216 (unless (js2-node-top-level-decl-p namen)
7217 (setq pos (js2-node-abs-pos namen))
7218 (setq len (js2-name-node-len namen))
7219 (js2-report-warning "msg.unused.variable" name pos len
7220 'js2-warning))))))))
7221
7222 (defun js2-highlight-unused-variables ()
7223 "Highlight unused variables."
7224 (let ((vars (js2--classify-variables)))
7225 (maphash #'js2--highlight-unused-variable vars)))
7226
7227 ;;;###autoload
7228 (define-minor-mode js2-highlight-unused-variables-mode
7229 "Toggle highlight of unused variables."
7230 :lighter ""
7231 (if js2-highlight-unused-variables-mode
7232 (add-hook 'js2-post-parse-callbacks
7233 #'js2-highlight-unused-variables nil t)
7234 (remove-hook 'js2-post-parse-callbacks
7235 #'js2-highlight-unused-variables t)))
7236
7237 (defun js2-set-default-externs ()
7238 "Set the value of `js2-default-externs' based on the various
7239 `js2-include-?-externs' variables."
7240 (setq js2-default-externs
7241 (append js2-ecma-262-externs
7242 (if js2-include-browser-externs js2-browser-externs)
7243 (if (and js2-include-browser-externs
7244 (>= js2-language-version 200)) js2-harmony-externs)
7245 (if js2-include-rhino-externs js2-rhino-externs)
7246 (if js2-include-node-externs js2-node-externs)
7247 (if (or js2-include-browser-externs js2-include-node-externs)
7248 js2-typed-array-externs))))
7249
7250 (defun js2-apply-jslint-globals ()
7251 (setq js2-additional-externs
7252 (nconc (js2-get-jslint-globals)
7253 js2-additional-externs)))
7254
7255 (defun js2-get-jslint-globals ()
7256 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7257 when (and (eq 'block (js2-comment-node-format node))
7258 (save-excursion
7259 (goto-char (js2-node-abs-pos node))
7260 (looking-at "/\\*global ")))
7261 append (js2-get-jslint-globals-in
7262 (match-end 0)
7263 (js2-node-abs-end node))))
7264
7265 (defun js2-get-jslint-globals-in (beg end)
7266 (let (res)
7267 (save-excursion
7268 (goto-char beg)
7269 (while (re-search-forward js2-mode-identifier-re end t)
7270 (let ((match (match-string 0)))
7271 (unless (member match '("true" "false"))
7272 (push match res)))))
7273 (nreverse res)))
7274
7275 ;;; IMenu support
7276
7277 ;; We currently only support imenu, but eventually should support speedbar and
7278 ;; possibly other browsing mechanisms.
7279
7280 ;; The basic strategy is to identify function assignment targets of the form
7281 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7282 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7283 ;; for imenu after parsing is finished.
7284
7285 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7286 ;; JavaScript, and the general problem is undecidable. However, several forms
7287 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7288 ;; include:
7289
7290 ;; function foo() -- function declaration
7291 ;; foo = function() -- function expression assigned to variable
7292 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7293 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7294 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7295 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7296 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7297 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7298 ;; function foo() {function bar() {...}} -- nested function
7299 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7300
7301 ;; This list boils down to a few forms that can be combined recursively.
7302 ;; Top-level named function declarations include both the left-hand (name)
7303 ;; and the right-hand (function value) expressions needed to produce an imenu
7304 ;; entry. The other "right-hand" forms we need to look for are:
7305 ;; - functions declared as props/getters/setters in object literals
7306 ;; - nested named function declarations
7307 ;; The "left-hand" expressions that functions can be assigned to include:
7308 ;; - local/global variables
7309 ;; - nested property-get expressions like a.b.c.d
7310 ;; - element gets like foo[10] or foo['bar'] where the index
7311 ;; expression can be trivially converted to a property name. They
7312 ;; effectively then become property gets.
7313
7314 ;; All the different definition types are canonicalized into the form
7315 ;; foo.bar.baz = position-of-function-keyword
7316
7317 ;; We need to build a trie-like structure for imenu. As an example,
7318 ;; consider the following JavaScript code:
7319
7320 ;; a = function() {...} // function at position 5
7321 ;; b = function() {...} // function at position 25
7322 ;; foo = function() {...} // function at position 100
7323 ;; foo.bar = function() {...} // function at position 200
7324 ;; foo.bar.baz = function() {...} // function at position 300
7325 ;; foo.bar.zab = function() {...} // function at position 400
7326
7327 ;; During parsing we accumulate an entry for each definition in
7328 ;; the variable `js2-imenu-recorder', like so:
7329
7330 ;; '((fn a 5)
7331 ;; (fn b 25)
7332 ;; (fn foo 100)
7333 ;; (fn foo bar 200)
7334 ;; (fn foo bar baz 300)
7335 ;; (fn foo bar zab 400))
7336
7337 ;; Where 'fn' is the respective function node.
7338 ;; After parsing these entries are merged into this alist-trie:
7339
7340 ;; '((a . 1)
7341 ;; (b . 2)
7342 ;; (foo (<definition> . 3)
7343 ;; (bar (<definition> . 6)
7344 ;; (baz . 100)
7345 ;; (zab . 200))))
7346
7347 ;; Note the wacky need for a <definition> name. The token can be anything
7348 ;; that isn't a valid JavaScript identifier, because you might make foo
7349 ;; a function and then start setting properties on it that are also functions.
7350
7351 (defun js2-prop-node-name (node)
7352 "Return the name of a node that may be a property-get/property-name.
7353 If NODE is not a valid name-node, string-node or integral number-node,
7354 returns nil. Otherwise returns the string name/value of the node."
7355 (cond
7356 ((js2-name-node-p node)
7357 (js2-name-node-name node))
7358 ((js2-string-node-p node)
7359 (js2-string-node-value node))
7360 ((and (js2-number-node-p node)
7361 (string-match "^[0-9]+$" (js2-number-node-value node)))
7362 (js2-number-node-value node))
7363 ((eq (js2-node-type node) js2-THIS)
7364 "this")
7365 ((eq (js2-node-type node) js2-SUPER)
7366 "super")))
7367
7368 (defun js2-node-qname-component (node)
7369 "Return the name of this node, if it contributes to a qname.
7370 Returns nil if the node doesn't contribute."
7371 (copy-sequence
7372 (or (js2-prop-node-name node)
7373 (if (and (js2-function-node-p node)
7374 (js2-function-node-name node))
7375 (js2-name-node-name (js2-function-node-name node))))))
7376
7377 (defun js2-record-imenu-entry (fn-node qname pos)
7378 "Add an entry to `js2-imenu-recorder'.
7379 FN-NODE should be the current item's function node.
7380
7381 Associate FN-NODE with its QNAME for later lookup.
7382 This is used in postprocessing the chain list. For each chain, we find
7383 the parent function, look up its qname, then prepend a copy of it to the chain."
7384 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7385 (unless js2-imenu-function-map
7386 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7387 (puthash fn-node qname js2-imenu-function-map))
7388
7389 (defun js2-record-imenu-functions (node &optional var)
7390 "Record function definitions for imenu.
7391 NODE is a function node or an object literal.
7392 VAR, if non-nil, is the expression that NODE is being assigned to.
7393 When passed arguments of wrong type, does nothing."
7394 (when js2-parse-ide-mode
7395 (let ((fun-p (js2-function-node-p node))
7396 qname fname-node)
7397 (cond
7398 ;; non-anonymous function declaration?
7399 ((and fun-p
7400 (not var)
7401 (setq fname-node (js2-function-node-name node)))
7402 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7403 ;; for remaining forms, compute left-side tree branch first
7404 ((and var (setq qname (js2-compute-nested-prop-get var)))
7405 (cond
7406 ;; foo.bar.baz = function
7407 (fun-p
7408 (js2-record-imenu-entry node qname (js2-node-pos node)))
7409 ;; foo.bar.baz = object-literal
7410 ;; look for nested functions: {a: {b: function() {...} }}
7411 ((js2-object-node-p node)
7412 ;; Node position here is still absolute, since the parser
7413 ;; passes the assignment target and value expressions
7414 ;; to us before they are added as children of the assignment node.
7415 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7416
7417 (defun js2-compute-nested-prop-get (node)
7418 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7419 component nodes as a list. Otherwise return nil. Element-gets are treated
7420 as property-gets if the index expression is a string, or a positive integer."
7421 (let (left right head)
7422 (cond
7423 ((or (js2-name-node-p node)
7424 (js2-this-or-super-node-p node))
7425 (list node))
7426 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7427 ((js2-prop-get-node-p node) ; foo.bar
7428 (setq left (js2-prop-get-node-left node)
7429 right (js2-prop-get-node-right node))
7430 (if (setq head (js2-compute-nested-prop-get left))
7431 (nconc head (list right))))
7432 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7433 (setq left (js2-elem-get-node-target node)
7434 right (js2-elem-get-node-element node))
7435 (if (or (js2-string-node-p right) ; ['bar']
7436 (and (js2-number-node-p right) ; [10]
7437 (string-match "^[0-9]+$"
7438 (js2-number-node-value right))))
7439 (if (setq head (js2-compute-nested-prop-get left))
7440 (nconc head (list right))))))))
7441
7442 (defun js2-record-object-literal (node qname pos)
7443 "Recursively process an object literal looking for functions.
7444 NODE is an object literal that is the right-hand child of an assignment
7445 expression. QNAME is a list of nodes representing the assignment target,
7446 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7447 POS is the absolute position of the node.
7448 We do a depth-first traversal of NODE. For any functions we find,
7449 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7450 (let (right)
7451 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7452 (let ((left (js2-infix-node-left e))
7453 ;; Element positions are relative to the parent position.
7454 (pos (+ pos (js2-node-pos e))))
7455 (cond
7456 ;; foo: function() {...}
7457 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7458 (when (js2-prop-node-name left)
7459 ;; As a policy decision, we record the position of the property,
7460 ;; not the position of the `function' keyword, since the property
7461 ;; is effectively the name of the function.
7462 (js2-record-imenu-entry right (append qname (list left)) pos)))
7463 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7464 ((js2-object-node-p right)
7465 (js2-record-object-literal right
7466 (append qname (list (js2-infix-node-left e)))
7467 (+ pos (js2-node-pos right)))))))))
7468
7469 (defun js2-node-top-level-decl-p (node)
7470 "Return t if NODE's name is defined in the top-level scope.
7471 Also returns t if NODE's name is not defined in any scope, since it implies
7472 that it's an external variable, which must also be in the top-level scope."
7473 (let* ((name (js2-prop-node-name node))
7474 (this-scope (js2-node-get-enclosing-scope node))
7475 defining-scope)
7476 (cond
7477 ((js2-this-or-super-node-p node)
7478 nil)
7479 ((null this-scope)
7480 t)
7481 ((setq defining-scope (js2-get-defining-scope this-scope name))
7482 (js2-ast-root-p defining-scope))
7483 (t t))))
7484
7485 (defun js2-wrapper-function-p (node)
7486 "Return t if NODE is a function expression that's immediately invoked.
7487 NODE must be `js2-function-node'."
7488 (let ((parent (js2-node-parent node)))
7489 (or
7490 ;; function(){...}();
7491 (and (js2-call-node-p parent)
7492 (eq node (js2-call-node-target parent)))
7493 (and (js2-paren-node-p parent)
7494 ;; (function(){...})();
7495 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7496 ;; (function(){...}).call(this);
7497 (and (js2-prop-get-node-p parent)
7498 (member (js2-name-node-name (js2-prop-get-node-right parent))
7499 '("call" "apply"))
7500 (js2-call-node-p (js2-node-parent parent))))))))
7501
7502 (defun js2-browse-postprocess-chains ()
7503 "Modify function-declaration name chains after parsing finishes.
7504 Some of the information is only available after the parse tree is complete.
7505 For instance, processing a nested scope requires a parent function node."
7506 (let (result fn parent-qname p elem)
7507 (dolist (entry js2-imenu-recorder)
7508 ;; function node goes first
7509 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest _)) entry
7510 ;; Examine head's defining scope:
7511 ;; Pre-processed chain, or top-level/external, keep as-is.
7512 (if (or (stringp head) (js2-node-top-level-decl-p head))
7513 (push chain result)
7514 (when (js2-this-or-super-node-p head)
7515 (setq chain (cdr chain))) ; discard this-node
7516 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7517 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7518 (when (eq parent-qname 'not-found)
7519 ;; anonymous function expressions are not recorded
7520 ;; during the parse, so we need to handle this case here
7521 (setq parent-qname
7522 (if (js2-wrapper-function-p fn)
7523 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7524 (if (js2-ast-root-p grandparent)
7525 nil
7526 (gethash grandparent js2-imenu-function-map 'skip)))
7527 'skip))
7528 (puthash fn parent-qname js2-imenu-function-map))
7529 (if (eq parent-qname 'skip)
7530 ;; We don't show it, let's record that fact.
7531 (remhash current-fn js2-imenu-function-map)
7532 ;; Prepend parent fn qname to this chain.
7533 (let ((qname (append parent-qname chain)))
7534 (puthash current-fn (butlast qname) js2-imenu-function-map)
7535 (push qname result)))))))
7536 ;; Collect chains obtained by third-party code.
7537 (let (js2-imenu-recorder)
7538 (run-hooks 'js2-build-imenu-callbacks)
7539 (dolist (entry js2-imenu-recorder)
7540 (push (cdr entry) result)))
7541 ;; Finally replace each node in each chain with its name.
7542 (dolist (chain result)
7543 (setq p chain)
7544 (while p
7545 (if (js2-node-p (setq elem (car p)))
7546 (setcar p (js2-node-qname-component elem)))
7547 (setq p (cdr p))))
7548 result))
7549
7550 ;; Merge name chains into a trie-like tree structure of nested lists.
7551 ;; To simplify construction of the trie, we first build it out using the rule
7552 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7553 ;; [key, num-or-list]. The second element can be a number; if so, this key
7554 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7555 ;; associated with the key at this level.) Otherwise the second element is
7556 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7557 ;; a simple recursive formulation.
7558 ;;
7559 ;; js2-mode is building the data structure for imenu. The imenu documentation
7560 ;; claims that it's the structure above, but in practice it wants the children
7561 ;; at the same list level as the key for that level, which is how I've drawn
7562 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7563 ;; list wrapper around the children at each level.
7564 ;;
7565 ;; A completed nested imenu-alist entry looks like this:
7566 ;; '(("foo"
7567 ;; ("<definition>" . 7)
7568 ;; ("bar"
7569 ;; ("a" . 40)
7570 ;; ("b" . 60))))
7571 ;;
7572 ;; In particular, the documentation for `imenu--index-alist' says that
7573 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7574 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7575
7576 (defun js2-treeify (lst)
7577 "Convert (a b c d) to (a ((b ((c d)))))."
7578 (if (null (cddr lst)) ; list length <= 2
7579 lst
7580 (list (car lst) (list (js2-treeify (cdr lst))))))
7581
7582 (defun js2-build-alist-trie (chains trie)
7583 "Merge declaration name chains into a trie-like alist structure for imenu.
7584 CHAINS is the qname chain list produced during parsing. TRIE is a
7585 list of elements built up so far."
7586 (let (head tail pos branch kids)
7587 (dolist (chain chains)
7588 (setq head (car chain)
7589 tail (cdr chain)
7590 pos (if (numberp (car tail)) (car tail))
7591 branch (js2-find-if (lambda (n)
7592 (string= (car n) head))
7593 trie)
7594 kids (cl-second branch))
7595 (cond
7596 ;; case 1: this key isn't in the trie yet
7597 ((null branch)
7598 (if trie
7599 (setcdr (last trie) (list (js2-treeify chain)))
7600 (setq trie (list (js2-treeify chain)))))
7601 ;; case 2: key is present with a single number entry: replace w/ list
7602 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7603 ;; ("<definition>" 20)))
7604 ((numberp kids)
7605 (setcar (cdr branch)
7606 (list (list "<definition-1>" kids)
7607 (if pos
7608 (list "<definition-2>" pos)
7609 (js2-treeify tail)))))
7610 ;; case 3: key is there (with kids), and we're a number entry
7611 (pos
7612 (setcdr (last kids)
7613 (list
7614 (list (format "<definition-%d>"
7615 (1+ (cl-loop for kid in kids
7616 count (eq ?< (aref (car kid) 0)))))
7617 pos))))
7618 ;; case 4: key is there with kids, need to merge in our chain
7619 (t
7620 (js2-build-alist-trie (list tail) kids))))
7621 trie))
7622
7623 (defun js2-flatten-trie (trie)
7624 "Convert TRIE to imenu-format.
7625 Recurses through nodes, and for each one whose second element is a list,
7626 appends the list's flattened elements to the current element. Also
7627 changes the tails into conses. For instance, this pre-flattened trie
7628
7629 '(a ((b 20)
7630 (c ((d 30)
7631 (e 40)))))
7632
7633 becomes
7634
7635 '(a (b . 20)
7636 (c (d . 30)
7637 (e . 40)))
7638
7639 Note that the root of the trie has no key, just a list of chains.
7640 This is also true for the value of any key with multiple children,
7641 e.g. key 'c' in the example above."
7642 (cond
7643 ((listp (car trie))
7644 (mapcar #'js2-flatten-trie trie))
7645 (t
7646 (if (numberp (cl-second trie))
7647 (cons (car trie) (cl-second trie))
7648 ;; else pop list and append its kids
7649 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7650
7651 (defun js2-build-imenu-index ()
7652 "Turn `js2-imenu-recorder' into an imenu data structure."
7653 (when (eq js2-imenu-recorder 'empty)
7654 (setq js2-imenu-recorder nil))
7655 (let* ((chains (js2-browse-postprocess-chains))
7656 (result (js2-build-alist-trie chains nil)))
7657 (js2-flatten-trie result)))
7658
7659 (defun js2-test-print-chains (chains)
7660 "Print a list of qname chains.
7661 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7662 i.e. one or more nodes, and an integer position as the list tail."
7663 (mapconcat (lambda (chain)
7664 (concat "("
7665 (mapconcat (lambda (elem)
7666 (if (js2-node-p elem)
7667 (or (js2-node-qname-component elem)
7668 "nil")
7669 (number-to-string elem)))
7670 chain
7671 " ")
7672 ")"))
7673 chains
7674 "\n"))
7675
7676 ;;; Parser
7677
7678 (defconst js2-version "1.8.5"
7679 "Version of JavaScript supported.")
7680
7681 (defun js2-record-face (face &optional token)
7682 "Record a style run of FACE for TOKEN or the current token."
7683 (unless token (setq token (js2-current-token)))
7684 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7685
7686 (defsubst js2-node-end (n)
7687 "Computes the absolute end of node N.
7688 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7689 is only true until the node is added to its parent; i.e., while parsing."
7690 (+ (js2-node-pos n)
7691 (js2-node-len n)))
7692
7693 (defun js2-record-comment (token)
7694 "Record a comment in `js2-scanned-comments'."
7695 (let ((ct (js2-token-comment-type token))
7696 (beg (js2-token-beg token))
7697 (end (js2-token-end token)))
7698 (push (make-js2-comment-node :len (- end beg)
7699 :format ct)
7700 js2-scanned-comments)
7701 (when js2-parse-ide-mode
7702 (js2-record-face (if (eq ct 'jsdoc)
7703 'font-lock-doc-face
7704 'font-lock-comment-face)
7705 token)
7706 (when (memq ct '(html preprocessor))
7707 ;; Tell cc-engine the bounds of the comment.
7708 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7709
7710 (defun js2-peek-token ()
7711 "Return the next token type without consuming it.
7712 If `js2-ti-lookahead' is positive, return the type of next token
7713 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7714 (if (not (zerop js2-ti-lookahead))
7715 (js2-token-type
7716 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7717 (let ((tt (js2-get-token-internal nil)))
7718 (js2-unget-token)
7719 tt)))
7720
7721 (defalias 'js2-next-token 'js2-get-token)
7722
7723 (defun js2-match-token (match &optional dont-unget)
7724 "Get next token and return t if it matches MATCH, a bytecode.
7725 Returns nil and consumes nothing if MATCH is not the next token."
7726 (if (/= (js2-get-token) match)
7727 (ignore (unless dont-unget (js2-unget-token)))
7728 t))
7729
7730 (defun js2-match-contextual-kwd (name)
7731 "Consume and return t if next token is `js2-NAME', and its
7732 string is NAME. Returns nil and keeps current token otherwise."
7733 (if (js2-contextual-kwd-p (progn (js2-get-token)
7734 (js2-current-token))
7735 name)
7736 (progn (js2-record-face 'font-lock-keyword-face) t)
7737 (js2-unget-token)
7738 nil))
7739
7740 (defun js2-contextual-kwd-p (token name)
7741 "Return t if TOKEN is `js2-NAME', and its string is NAME."
7742 (and (= (js2-token-type token) js2-NAME)
7743 (string= (js2-token-string token) name)))
7744
7745 (defun js2-match-async-function ()
7746 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7747 (= (js2-peek-token) js2-FUNCTION))
7748 (js2-record-face 'font-lock-keyword-face)
7749 (js2-get-token)
7750 t))
7751
7752 ;; Matching "async" is performed in two parts, because in the functions' one use
7753 ;; case, it isn't known whether an arrow function is actually being parsed (and
7754 ;; thus whether `js2-get-token' should be called) until later. If
7755 ;; `js2-get-token' were called eccentrically, `js2-current-token' would be
7756 ;; off-by-one, causing `js2-parse-unary-expr' to potentially fail when "async"
7757 ;; is unused in a non-keyword context.
7758
7759 (defun js2-match-async-arrow-function-1 ()
7760 (and (js2-contextual-kwd-p (js2-current-token) "async")
7761 (/= (js2-peek-token) js2-FUNCTION)))
7762
7763 (defun js2-match-async-arrow-function-2 ()
7764 (js2-record-face 'font-lock-keyword-face)
7765 (js2-get-token))
7766
7767 (defun js2-match-await (tt)
7768 (when (and (= tt js2-NAME)
7769 (js2-contextual-kwd-p (js2-current-token) "await")
7770 ;; Per the proposal, AwaitExpression consists of "await"
7771 ;; followed by a UnaryExpression. So look ahead for one.
7772 (let ((ts-state (make-js2-ts-state))
7773 js2-recorded-identifiers
7774 js2-parsed-errors)
7775 (js2-get-token)
7776 (prog1
7777 (/= (js2-node-type (js2-parse-unary-expr)) js2-ERROR)
7778 (js2-ts-seek ts-state))))
7779 (js2-record-face 'font-lock-keyword-face)
7780 (let ((beg (js2-current-token-beg))
7781 (end (js2-current-token-end)))
7782 (js2-get-token)
7783 (unless (and (js2-inside-function)
7784 (js2-function-node-async js2-current-script-or-fn))
7785 (js2-report-error "msg.bad.await" nil
7786 beg (- end beg))))
7787 t))
7788
7789 (defun js2-get-prop-name-token ()
7790 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7791
7792 (defun js2-match-prop-name ()
7793 "Consume token and return t if next token is a valid property name.
7794 If `js2-language-version' is >= 180, a keyword or reserved word
7795 is considered valid name as well."
7796 (if (eq js2-NAME (js2-get-prop-name-token))
7797 t
7798 (js2-unget-token)
7799 nil))
7800
7801 (defun js2-must-match-prop-name (msg-id &optional pos len)
7802 (if (js2-match-prop-name)
7803 t
7804 (js2-report-error msg-id nil pos len)
7805 nil))
7806
7807 (defun js2-peek-token-or-eol ()
7808 "Return js2-EOL if the next token immediately follows a newline.
7809 Else returns the next token. Used in situations where we don't
7810 consider certain token types valid if they are preceded by a newline.
7811 One example is the postfix ++ or -- operator, which has to be on the
7812 same line as its operand."
7813 (let ((tt (js2-get-token))
7814 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7815 (js2-unget-token)
7816 (if follows-eol
7817 js2-EOL
7818 tt)))
7819
7820 (defun js2-must-match (token msg-id &optional pos len)
7821 "Match next token to token code TOKEN, or record a syntax error.
7822 MSG-ID is the error message to report if the match fails.
7823 Returns t on match, nil if no match."
7824 (if (js2-match-token token t)
7825 t
7826 (js2-report-error msg-id nil pos len)
7827 (js2-unget-token)
7828 nil))
7829
7830 (defun js2-must-match-name (msg-id)
7831 (if (js2-match-token js2-NAME t)
7832 t
7833 (if (eq (js2-current-token-type) js2-RESERVED)
7834 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7835 (js2-report-error msg-id)
7836 (js2-unget-token))
7837 nil))
7838
7839 (defsubst js2-inside-function ()
7840 (cl-plusp js2-nesting-of-function))
7841
7842 (defun js2-set-requires-activation ()
7843 (if (js2-function-node-p js2-current-script-or-fn)
7844 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7845
7846 (defun js2-check-activation-name (name _token)
7847 (when (js2-inside-function)
7848 ;; skip language-version 1.2 check from Rhino
7849 (if (or (string= "arguments" name)
7850 (and js2-compiler-activation-names ; only used in codegen
7851 (gethash name js2-compiler-activation-names)))
7852 (js2-set-requires-activation))))
7853
7854 (defun js2-set-is-generator ()
7855 (let ((fn-node js2-current-script-or-fn))
7856 (when (and (js2-function-node-p fn-node)
7857 (not (js2-function-node-generator-type fn-node)))
7858 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7859
7860 (defun js2-must-have-xml ()
7861 (unless js2-compiler-xml-available
7862 (js2-report-error "msg.XML.not.available")))
7863
7864 (defun js2-push-scope (scope)
7865 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7866 (cl-assert (js2-scope-p scope))
7867 (cl-assert (null (js2-scope-parent-scope scope)))
7868 (cl-assert (not (eq js2-current-scope scope)))
7869 (setf (js2-scope-parent-scope scope) js2-current-scope
7870 js2-current-scope scope))
7871
7872 (defsubst js2-pop-scope ()
7873 (setq js2-current-scope
7874 (js2-scope-parent-scope js2-current-scope)))
7875
7876 (defun js2-enter-loop (loop-node)
7877 (push loop-node js2-loop-set)
7878 (push loop-node js2-loop-and-switch-set)
7879 (js2-push-scope loop-node)
7880 ;; Tell the current labeled statement (if any) its statement,
7881 ;; and set the jump target of the first label to the loop.
7882 ;; These are used in `js2-parse-continue' to verify that the
7883 ;; continue target is an actual labeled loop. (And for codegen.)
7884 (when js2-labeled-stmt
7885 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7886 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7887 js2-labeled-stmt))) loop-node)))
7888
7889 (defun js2-exit-loop ()
7890 (pop js2-loop-set)
7891 (pop js2-loop-and-switch-set)
7892 (js2-pop-scope))
7893
7894 (defsubst js2-enter-switch (switch-node)
7895 (push switch-node js2-loop-and-switch-set))
7896
7897 (defsubst js2-exit-switch ()
7898 (pop js2-loop-and-switch-set))
7899
7900 (defsubst js2-get-directive (node)
7901 "Return NODE's value if it is a directive, nil otherwise.
7902
7903 A directive is an otherwise-meaningless expression statement
7904 consisting of a string literal, such as \"use strict\"."
7905 (and (js2-expr-stmt-node-p node)
7906 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7907 (js2-string-node-value node)))
7908
7909 (defun js2-parse (&optional buf cb)
7910 "Tell the js2 parser to parse a region of JavaScript.
7911
7912 BUF is a buffer or buffer name containing the code to parse.
7913 Call `narrow-to-region' first to parse only part of the buffer.
7914
7915 The returned AST root node is given some additional properties:
7916 `node-count' - total number of nodes in the AST
7917 `buffer' - BUF. The buffer it refers to may change or be killed,
7918 so the value is not necessarily reliable.
7919
7920 An optional callback CB can be specified to report parsing
7921 progress. If `(functionp CB)' returns t, it will be called with
7922 the current line number once before parsing begins, then again
7923 each time the lexer reaches a new line number.
7924
7925 CB can also be a list of the form `(symbol cb ...)' to specify
7926 multiple callbacks with different criteria. Each symbol is a
7927 criterion keyword, and the following element is the callback to
7928 call
7929
7930 :line - called whenever the line number changes
7931 :token - called for each new token consumed
7932
7933 The list of criteria could be extended to include entering or
7934 leaving a statement, an expression, or a function definition."
7935 (if (and cb (not (functionp cb)))
7936 (error "criteria callbacks not yet implemented"))
7937 (let ((inhibit-point-motion-hooks t)
7938 (js2-compiler-xml-available (>= js2-language-version 160))
7939 ;; This is a recursive-descent parser, so give it a big stack.
7940 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7941 (max-specpdl-size (max max-specpdl-size 3000))
7942 (case-fold-search nil)
7943 ast)
7944 (with-current-buffer (or buf (current-buffer))
7945 (setq js2-scanned-comments nil
7946 js2-parsed-errors nil
7947 js2-parsed-warnings nil
7948 js2-imenu-recorder nil
7949 js2-imenu-function-map nil
7950 js2-label-set nil)
7951 (js2-init-scanner)
7952 (setq ast (js2-do-parse))
7953 (unless js2-ts-hit-eof
7954 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7955 (setf (js2-ast-root-errors ast) js2-parsed-errors
7956 (js2-ast-root-warnings ast) js2-parsed-warnings)
7957 ;; if we didn't find any declarations, put a dummy in this list so we
7958 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7959 (unless js2-imenu-recorder
7960 (setq js2-imenu-recorder 'empty))
7961 (run-hooks 'js2-parse-finished-hook)
7962 ast)))
7963
7964 ;; Corresponds to Rhino's Parser.parse() method.
7965 (defun js2-do-parse ()
7966 "Parse current buffer starting from current point.
7967 Scanner should be initialized."
7968 (let ((pos js2-ts-cursor)
7969 (end js2-ts-cursor) ; in case file is empty
7970 root n tt
7971 (in-directive-prologue t)
7972 (js2-in-use-strict-directive js2-in-use-strict-directive)
7973 directive)
7974 ;; initialize buffer-local parsing vars
7975 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7976 js2-current-script-or-fn root
7977 js2-current-scope root
7978 js2-nesting-of-function 0
7979 js2-labeled-stmt nil
7980 js2-recorded-identifiers nil ; for js2-highlight
7981 js2-in-use-strict-directive nil)
7982 (while (/= (setq tt (js2-get-token)) js2-EOF)
7983 (if (= tt js2-FUNCTION)
7984 (progn
7985 (setq n (if js2-called-by-compile-function
7986 (js2-parse-function-expr)
7987 (js2-parse-function-stmt))))
7988 ;; not a function - parse a statement
7989 (js2-unget-token)
7990 (setq n (js2-parse-statement))
7991 (when in-directive-prologue
7992 (setq directive (js2-get-directive n))
7993 (cond
7994 ((null directive)
7995 (setq in-directive-prologue nil))
7996 ((string= directive "use strict")
7997 (setq js2-in-use-strict-directive t)))))
7998 ;; add function or statement to script
7999 (setq end (js2-node-end n))
8000 (js2-block-node-push root n))
8001 ;; add comments to root in lexical order
8002 (when js2-scanned-comments
8003 ;; if we find a comment beyond end of normal kids, use its end
8004 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
8005 (dolist (comment js2-scanned-comments)
8006 (push comment (js2-ast-root-comments root))
8007 (js2-node-add-children root comment)))
8008 (setf (js2-node-len root) (- end pos))
8009 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
8010 ;; Give extensions a chance to muck with things before highlighting starts.
8011 (let ((js2-additional-externs js2-additional-externs))
8012 (save-excursion
8013 (run-hooks 'js2-post-parse-callbacks))
8014 (js2-highlight-undeclared-vars))
8015 root))
8016
8017 (defun js2-parse-function-closure-body (fn-node)
8018 "Parse a JavaScript 1.8 function closure body."
8019 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
8020 (if js2-ts-hit-eof
8021 (js2-report-error "msg.no.brace.body" nil
8022 (js2-node-pos fn-node)
8023 (- js2-ts-cursor (js2-node-pos fn-node)))
8024 (js2-node-add-children fn-node
8025 (setf (js2-function-node-body fn-node)
8026 (js2-parse-expr t))))))
8027
8028 (defun js2-parse-function-body (fn-node)
8029 (js2-must-match js2-LC "msg.no.brace.body"
8030 (js2-node-pos fn-node)
8031 (- js2-ts-cursor (js2-node-pos fn-node)))
8032 (let ((pos (js2-current-token-beg)) ; LC position
8033 (pn (make-js2-block-node)) ; starts at LC position
8034 tt
8035 end
8036 not-in-directive-prologue
8037 node
8038 directive)
8039 (cl-incf js2-nesting-of-function)
8040 (unwind-protect
8041 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8042 (= tt js2-EOF)
8043 (= tt js2-RC)))
8044 (js2-block-node-push
8045 pn
8046 (if (/= tt js2-FUNCTION)
8047 (if not-in-directive-prologue
8048 (js2-parse-statement)
8049 (setq node (js2-parse-statement)
8050 directive (js2-get-directive node))
8051 (cond
8052 ((null directive)
8053 (setq not-in-directive-prologue t))
8054 ((string= directive "use strict")
8055 ;; Back up and reparse the function, because new rules apply
8056 ;; to the function name and parameters.
8057 (when (not js2-in-use-strict-directive)
8058 (setq js2-in-use-strict-directive t)
8059 (throw 'reparse t))))
8060 node)
8061 (js2-get-token)
8062 (js2-parse-function-stmt))))
8063 (cl-decf js2-nesting-of-function))
8064 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8065 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8066 (setq end (js2-current-token-end)))
8067 (setf (js2-node-pos pn) pos
8068 (js2-node-len pn) (- end pos))
8069 (setf (js2-function-node-body fn-node) pn)
8070 (js2-node-add-children fn-node pn)
8071 pn))
8072
8073 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8074 "Declare and fontify destructuring parameters inside NODE.
8075 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8076
8077 Return a list of `js2-name-node' nodes representing the symbols
8078 declared; probably to check them for errors."
8079 (let (name-nodes)
8080 (cond
8081 ((js2-name-node-p node)
8082 (let (leftpos)
8083 (js2-define-symbol decl-type (js2-name-node-name node)
8084 node ignore-not-in-block)
8085 (when face
8086 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8087 (+ leftpos (js2-node-len node))
8088 face 'record))
8089 (list node)))
8090 ((js2-object-node-p node)
8091 (dolist (elem (js2-object-node-elems node))
8092 ;; js2-infix-node-p catches both object prop node and initialized
8093 ;; binding element (which is directly an infix node).
8094 (when (js2-infix-node-p elem)
8095 (push (js2-define-destruct-symbols
8096 (js2-infix-node-left elem)
8097 decl-type face ignore-not-in-block)
8098 name-nodes)))
8099 (apply #'append (nreverse name-nodes)))
8100 ((js2-array-node-p node)
8101 (dolist (elem (js2-array-node-elems node))
8102 (when elem
8103 (if (js2-infix-node-p elem) (setq elem (js2-infix-node-left elem)))
8104 (push (js2-define-destruct-symbols
8105 elem decl-type face ignore-not-in-block)
8106 name-nodes)))
8107 (apply #'append (nreverse name-nodes)))
8108 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8109 (js2-node-len node))
8110 nil))))
8111
8112 (defvar js2-illegal-strict-identifiers
8113 '("eval" "arguments")
8114 "Identifiers not allowed as variables in strict mode.")
8115
8116 (defun js2-check-strict-identifier (name-node)
8117 "Check that NAME-NODE makes a legal strict mode identifier."
8118 (when js2-in-use-strict-directive
8119 (let ((param-name (js2-name-node-name name-node)))
8120 (when (member param-name js2-illegal-strict-identifiers)
8121 (js2-report-error "msg.bad.id.strict" param-name
8122 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8123
8124 (defun js2-check-strict-function-params (preceding-params params)
8125 "Given PRECEDING-PARAMS in a function's parameter list, check
8126 for strict mode errors caused by PARAMS."
8127 (when js2-in-use-strict-directive
8128 (dolist (param params)
8129 (let ((param-name (js2-name-node-name param)))
8130 (js2-check-strict-identifier param)
8131 (when (cl-some (lambda (param)
8132 (string= (js2-name-node-name param) param-name))
8133 preceding-params)
8134 (js2-report-error "msg.dup.param.strict" param-name
8135 (js2-node-abs-pos param) (js2-node-len param)))))))
8136
8137 (defun js2-parse-function-params (function-type fn-node pos)
8138 "Parse the parameters of a function of FUNCTION-TYPE
8139 represented by FN-NODE at POS."
8140 (if (js2-match-token js2-RP)
8141 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8142 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8143 (eq (js2-current-token-type) js2-NAME)))
8144 params param
8145 param-name-nodes new-param-name-nodes
8146 rest-param-at)
8147 (when paren-free-arrow
8148 (js2-unget-token))
8149 (cl-loop for tt = (js2-peek-token)
8150 do
8151 (cond
8152 ;; destructuring param
8153 ((and (not paren-free-arrow)
8154 (or (= tt js2-LB) (= tt js2-LC)))
8155 (js2-get-token)
8156 (setq param (js2-parse-destruct-primary-expr)
8157 new-param-name-nodes (js2-define-destruct-symbols
8158 param js2-LP 'js2-function-param))
8159 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8160 (setq param-name-nodes (append param-name-nodes new-param-name-nodes)))
8161 ;; variable name
8162 (t
8163 (when (and (>= js2-language-version 200)
8164 (not paren-free-arrow)
8165 (js2-match-token js2-TRIPLEDOT)
8166 (not rest-param-at))
8167 ;; to report errors if there are more parameters
8168 (setq rest-param-at (length params)))
8169 (js2-must-match-name "msg.no.parm")
8170 (js2-record-face 'js2-function-param)
8171 (setq param (js2-create-name-node))
8172 (js2-define-symbol js2-LP (js2-current-token-string) param)
8173 (js2-check-strict-function-params param-name-nodes (list param))
8174 (setq param-name-nodes (append param-name-nodes (list param)))))
8175 ;; default parameter value
8176 (when (and (not rest-param-at)
8177 (>= js2-language-version 200)
8178 (js2-match-token js2-ASSIGN))
8179 (cl-assert (not paren-free-arrow))
8180 (let* ((pos (js2-node-pos param))
8181 (tt (js2-current-token-type))
8182 (op-pos (- (js2-current-token-beg) pos))
8183 (left param)
8184 (right (js2-parse-assign-expr))
8185 (len (- (js2-node-end right) pos)))
8186 (setq param (make-js2-assign-node
8187 :type tt :pos pos :len len :op-pos op-pos
8188 :left left :right right))
8189 (js2-node-add-children param left right)))
8190 (push param params)
8191 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8192 (js2-report-error "msg.param.after.rest" nil
8193 (js2-node-pos param) (js2-node-len param)))
8194 while
8195 (js2-match-token js2-COMMA))
8196 (when (and (not paren-free-arrow)
8197 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8198 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8199 (when rest-param-at
8200 (setf (js2-function-node-rest-p fn-node) t))
8201 (dolist (p params)
8202 (js2-node-add-children fn-node p)
8203 (push p (js2-function-node-params fn-node))))))
8204
8205 (defun js2-check-inconsistent-return-warning (fn-node name)
8206 "Possibly show inconsistent-return warning.
8207 Last token scanned is the close-curly for the function body."
8208 (when (and js2-mode-show-strict-warnings
8209 js2-strict-inconsistent-return-warning
8210 (not (js2-has-consistent-return-usage
8211 (js2-function-node-body fn-node))))
8212 ;; Have it extend from close-curly to bol or beginning of block.
8213 (let ((pos (save-excursion
8214 (goto-char (js2-current-token-end))
8215 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8216 (point-at-bol))))
8217 (end (js2-current-token-end)))
8218 (if (cl-plusp (js2-name-node-length name))
8219 (js2-add-strict-warning "msg.no.return.value"
8220 (js2-name-node-name name) pos end)
8221 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8222
8223 (defun js2-parse-function-stmt (&optional async-p)
8224 (let ((pos (js2-current-token-beg))
8225 (star-p (js2-match-token js2-MUL)))
8226 (js2-must-match-name "msg.unnamed.function.stmt")
8227 (let ((name (js2-create-name-node t))
8228 pn member-expr)
8229 (cond
8230 ((js2-match-token js2-LP)
8231 (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p name))
8232 (js2-allow-member-expr-as-function-name
8233 (setq member-expr (js2-parse-member-expr-tail nil name))
8234 (js2-parse-highlight-member-expr-fn-name member-expr)
8235 (js2-must-match js2-LP "msg.no.paren.parms")
8236 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p)
8237 (js2-function-node-member-expr pn) member-expr)
8238 pn)
8239 (t
8240 (js2-report-error "msg.no.paren.parms")
8241 (make-js2-error-node))))))
8242
8243 (defun js2-parse-async-function-stmt ()
8244 (js2-parse-function-stmt t))
8245
8246 (defun js2-parse-function-expr (&optional async-p)
8247 (let ((pos (js2-current-token-beg))
8248 (star-p (js2-match-token js2-MUL))
8249 name)
8250 (when (js2-match-token js2-NAME)
8251 (setq name (js2-create-name-node t)))
8252 (js2-must-match js2-LP "msg.no.paren.parms")
8253 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p async-p name)))
8254
8255 (defun js2-parse-function-internal (function-type pos star-p &optional async-p name)
8256 (let (fn-node lp)
8257 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8258 (setq lp (js2-current-token-beg)))
8259 (setf fn-node (make-js2-function-node :pos pos
8260 :name name
8261 :form function-type
8262 :lp (if lp (- lp pos))
8263 :generator-type (and star-p 'STAR)
8264 :async async-p))
8265 (when name
8266 (js2-set-face (js2-node-pos name) (js2-node-end name)
8267 'font-lock-function-name-face 'record)
8268 (when (and (eq function-type 'FUNCTION_STATEMENT)
8269 (cl-plusp (js2-name-node-length name)))
8270 ;; Function statements define a symbol in the enclosing scope
8271 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8272 (when js2-in-use-strict-directive
8273 (js2-check-strict-identifier name)))
8274 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8275 ;; 1. Nested functions are not affected by the dynamic scope flag
8276 ;; as dynamic scope is already a parent of their scope.
8277 ;; 2. Functions defined under the with statement also immune to
8278 ;; this setup, in which case dynamic scope is ignored in favor
8279 ;; of the with object.
8280 (setf (js2-function-node-ignore-dynamic fn-node) t))
8281 ;; dynamically bind all the per-function variables
8282 (let ((js2-current-script-or-fn fn-node)
8283 (js2-current-scope fn-node)
8284 (js2-nesting-of-with 0)
8285 (js2-end-flags 0)
8286 js2-label-set
8287 js2-loop-set
8288 js2-loop-and-switch-set)
8289 (js2-parse-function-params function-type fn-node pos)
8290 (when (eq function-type 'FUNCTION_ARROW)
8291 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8292 (if (and (>= js2-language-version 180)
8293 (/= (js2-peek-token) js2-LC))
8294 (js2-parse-function-closure-body fn-node)
8295 (js2-parse-function-body fn-node))
8296 (js2-check-inconsistent-return-warning fn-node name)
8297
8298 (when name
8299 (js2-node-add-children fn-node name)
8300 ;; Function expressions define a name only in the body of the
8301 ;; function, and only if not hidden by a parameter name
8302 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8303 (null (js2-scope-get-symbol js2-current-scope
8304 (js2-name-node-name name))))
8305 (js2-define-symbol js2-FUNCTION
8306 (js2-name-node-name name)
8307 fn-node))
8308 (when (eq function-type 'FUNCTION_STATEMENT)
8309 (js2-record-imenu-functions fn-node))))
8310
8311 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8312 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8313 ;; We wait until after parsing the function to set its parent scope,
8314 ;; since `js2-define-symbol' needs the defining-scope check to stop
8315 ;; at the function boundary when checking for redeclarations.
8316 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8317 fn-node))
8318
8319 (defun js2-parse-function (function-type pos star-p &optional async-p name)
8320 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8321 beginning of the first token (function keyword, unless it's an
8322 arrow function), NAME is js2-name-node."
8323 (let ((continue t)
8324 ts-state
8325 fn-node
8326 ;; Preserve strict state outside this function.
8327 (js2-in-use-strict-directive js2-in-use-strict-directive))
8328 ;; Parse multiple times if a new strict mode directive is discovered in the
8329 ;; function body, as new rules will be retroactively applied to the legality
8330 ;; of function names and parameters.
8331 (while continue
8332 (setq ts-state (make-js2-ts-state))
8333 (setq continue (catch 'reparse
8334 (setq fn-node (js2-parse-function-internal
8335 function-type pos star-p async-p name))
8336 ;; Don't continue.
8337 nil))
8338 (when continue
8339 (js2-ts-seek ts-state)))
8340 fn-node))
8341
8342 (defun js2-parse-statements (&optional parent)
8343 "Parse a statement list. Last token consumed must be js2-LC.
8344
8345 PARENT can be a `js2-block-node', in which case the statements are
8346 appended to PARENT. Otherwise a new `js2-block-node' is created
8347 and returned.
8348
8349 This function does not match the closing js2-RC: the caller
8350 matches the RC so it can provide a suitable error message if not
8351 matched. This means it's up to the caller to set the length of
8352 the node to include the closing RC. The node start pos is set to
8353 the absolute buffer start position, and the caller should fix it
8354 up to be relative to the parent node. All children of this block
8355 node are given relative start positions and correct lengths."
8356 (let ((pn (or parent (make-js2-block-node)))
8357 tt)
8358 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8359 (/= tt js2-RC))
8360 (js2-block-node-push pn (js2-parse-statement)))
8361 pn))
8362
8363 (defun js2-parse-statement ()
8364 (let (pn beg end)
8365 ;; coarse-grained user-interrupt check - needs work
8366 (and js2-parse-interruptable-p
8367 (zerop (% (cl-incf js2-parse-stmt-count)
8368 js2-statements-per-pause))
8369 (input-pending-p)
8370 (throw 'interrupted t))
8371 (setq pn (js2-statement-helper))
8372 ;; no-side-effects warning check
8373 (unless (js2-node-has-side-effects pn)
8374 (setq end (js2-node-end pn))
8375 (save-excursion
8376 (goto-char end)
8377 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8378 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8379 pn))
8380
8381 ;; These correspond to the switch cases in Parser.statementHelper
8382 (defconst js2-parsers
8383 (let ((parsers (make-vector js2-num-tokens
8384 #'js2-parse-expr-stmt)))
8385 (aset parsers js2-BREAK #'js2-parse-break)
8386 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8387 (aset parsers js2-CONST #'js2-parse-const-var)
8388 (aset parsers js2-CONTINUE #'js2-parse-continue)
8389 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8390 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8391 (aset parsers js2-DO #'js2-parse-do)
8392 (aset parsers js2-EXPORT #'js2-parse-export)
8393 (aset parsers js2-FOR #'js2-parse-for)
8394 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8395 (aset parsers js2-IF #'js2-parse-if)
8396 (aset parsers js2-IMPORT #'js2-parse-import)
8397 (aset parsers js2-LC #'js2-parse-block)
8398 (aset parsers js2-LET #'js2-parse-let-stmt)
8399 (aset parsers js2-NAME #'js2-parse-name-or-label)
8400 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8401 (aset parsers js2-SEMI #'js2-parse-semi)
8402 (aset parsers js2-SWITCH #'js2-parse-switch)
8403 (aset parsers js2-THROW #'js2-parse-throw)
8404 (aset parsers js2-TRY #'js2-parse-try)
8405 (aset parsers js2-VAR #'js2-parse-const-var)
8406 (aset parsers js2-WHILE #'js2-parse-while)
8407 (aset parsers js2-WITH #'js2-parse-with)
8408 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8409 parsers)
8410 "A vector mapping token types to parser functions.")
8411
8412 (defun js2-parse-warn-missing-semi (beg end)
8413 (and js2-mode-show-strict-warnings
8414 js2-strict-missing-semi-warning
8415 (js2-add-strict-warning
8416 "msg.missing.semi" nil
8417 ;; back up to beginning of statement or line
8418 (max beg (save-excursion
8419 (goto-char end)
8420 (point-at-bol)))
8421 end)))
8422
8423 (defconst js2-no-semi-insertion
8424 (list js2-IF
8425 js2-SWITCH
8426 js2-WHILE
8427 js2-DO
8428 js2-FOR
8429 js2-TRY
8430 js2-WITH
8431 js2-LC
8432 js2-ERROR
8433 js2-SEMI
8434 js2-CLASS
8435 js2-FUNCTION
8436 js2-EXPORT)
8437 "List of tokens that don't do automatic semicolon insertion.")
8438
8439 (defconst js2-autoinsert-semi-and-warn
8440 (list js2-ERROR js2-EOF js2-RC))
8441
8442 (defun js2-statement-helper ()
8443 (let* ((tt (js2-get-token))
8444 (first-tt tt)
8445 (async-stmt (js2-match-async-function))
8446 (parser (if (= tt js2-ERROR)
8447 #'js2-parse-semi
8448 (if async-stmt
8449 #'js2-parse-async-function-stmt
8450 (aref js2-parsers tt))))
8451 pn)
8452 ;; If the statement is set, then it's been told its label by now.
8453 (and js2-labeled-stmt
8454 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8455 (setq js2-labeled-stmt nil))
8456 (setq pn (funcall parser))
8457 ;; Don't do auto semi insertion for certain statement types.
8458 (unless (or (memq first-tt js2-no-semi-insertion)
8459 (js2-labeled-stmt-node-p pn)
8460 async-stmt)
8461 (js2-auto-insert-semicolon pn))
8462 pn))
8463
8464 (defun js2-auto-insert-semicolon (pn)
8465 (let* ((tt (js2-get-token))
8466 (pos (js2-node-pos pn)))
8467 (cond
8468 ((= tt js2-SEMI)
8469 ;; extend the node bounds to include the semicolon.
8470 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8471 ((memq tt js2-autoinsert-semi-and-warn)
8472 (js2-unget-token) ; Not ';', do not consume.
8473 ;; Autoinsert ;
8474 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8475 (t
8476 (if (not (js2-token-follows-eol-p (js2-current-token)))
8477 ;; Report error if no EOL or autoinsert ';' otherwise
8478 (js2-report-error "msg.no.semi.stmt")
8479 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8480 (js2-unget-token) ; Not ';', do not consume.
8481 ))))
8482
8483 (defun js2-parse-condition ()
8484 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8485 The parens are discarded and the expression node is returned.
8486 The `pos' field of the return value is set to an absolute position
8487 that must be fixed up by the caller.
8488 Return value is a list (EXPR LP RP), with absolute paren positions."
8489 (let (pn lp rp)
8490 (if (js2-must-match js2-LP "msg.no.paren.cond")
8491 (setq lp (js2-current-token-beg)))
8492 (setq pn (js2-parse-expr))
8493 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8494 (setq rp (js2-current-token-beg)))
8495 ;; Report strict warning on code like "if (a = 7) ..."
8496 (if (and js2-strict-cond-assign-warning
8497 (js2-assign-node-p pn))
8498 (js2-add-strict-warning "msg.equal.as.assign" nil
8499 (js2-node-pos pn)
8500 (+ (js2-node-pos pn)
8501 (js2-node-len pn))))
8502 (list pn lp rp)))
8503
8504 (defun js2-parse-if ()
8505 "Parser for if-statement. Last matched token must be js2-IF."
8506 (let ((pos (js2-current-token-beg))
8507 cond if-true if-false else-pos end pn)
8508 (setq cond (js2-parse-condition)
8509 if-true (js2-parse-statement)
8510 if-false (if (js2-match-token js2-ELSE)
8511 (progn
8512 (setq else-pos (- (js2-current-token-beg) pos))
8513 (js2-parse-statement)))
8514 end (js2-node-end (or if-false if-true))
8515 pn (make-js2-if-node :pos pos
8516 :len (- end pos)
8517 :condition (car cond)
8518 :then-part if-true
8519 :else-part if-false
8520 :else-pos else-pos
8521 :lp (js2-relpos (cl-second cond) pos)
8522 :rp (js2-relpos (cl-third cond) pos)))
8523 (js2-node-add-children pn (car cond) if-true if-false)
8524 pn))
8525
8526 (defun js2-parse-import ()
8527 "Parse import statement. The current token must be js2-IMPORT."
8528 (unless (js2-ast-root-p js2-current-scope)
8529 (js2-report-error "msg.mod.import.decl.at.top.level"))
8530 (let ((beg (js2-current-token-beg)))
8531 (cond ((js2-match-token js2-STRING)
8532 (make-js2-import-node
8533 :pos beg
8534 :len (- (js2-current-token-end) beg)
8535 :module-id (js2-current-token-string)))
8536 (t
8537 (let* ((import-clause (js2-parse-import-clause))
8538 (from-clause (and import-clause (js2-parse-from-clause)))
8539 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8540 (node (make-js2-import-node
8541 :pos beg
8542 :len (- (js2-current-token-end) beg)
8543 :import import-clause
8544 :from from-clause
8545 :module-id module-id)))
8546 (when import-clause
8547 (js2-node-add-children node import-clause))
8548 (when from-clause
8549 (js2-node-add-children node from-clause))
8550 node)))))
8551
8552 (defun js2-parse-import-clause ()
8553 "Parse the bindings in an import statement.
8554 This can take many forms:
8555
8556 ImportedDefaultBinding -> 'foo'
8557 NameSpaceImport -> '* as lib'
8558 NamedImports -> '{foo as bar, bang}'
8559 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8560 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8561
8562 Try to match namespace imports and named imports first because nothing can
8563 come after them. If it is an imported default binding, then it could have named
8564 imports or a namespace import that follows it.
8565 "
8566 (let* ((beg (js2-current-token-beg))
8567 (clause (make-js2-import-clause-node
8568 :pos beg))
8569 (children (list)))
8570 (cond
8571 ((js2-match-token js2-MUL)
8572 (let ((ns-import (js2-parse-namespace-import)))
8573 (when ns-import
8574 (let ((name-node (js2-namespace-import-node-name ns-import)))
8575 (js2-define-symbol
8576 js2-LET (js2-name-node-name name-node) name-node t)))
8577 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8578 (push ns-import children)))
8579 ((js2-match-token js2-LC)
8580 (let ((imports (js2-parse-export-bindings t)))
8581 (setf (js2-import-clause-node-named-imports clause) imports)
8582 (dolist (import imports)
8583 (push import children)
8584 (let ((name-node (js2-export-binding-node-local-name import)))
8585 (when name-node
8586 (js2-define-symbol
8587 js2-LET (js2-name-node-name name-node) name-node t))))))
8588 ((= (js2-peek-token) js2-NAME)
8589 (let ((binding (js2-maybe-parse-export-binding)))
8590 (let ((node-name (js2-export-binding-node-local-name binding)))
8591 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8592 (setf (js2-import-clause-node-default-binding clause) binding)
8593 (push binding children))
8594 (when (js2-match-token js2-COMMA)
8595 (cond
8596 ((js2-match-token js2-MUL)
8597 (let ((ns-import (js2-parse-namespace-import)))
8598 (let ((name-node (js2-namespace-import-node-name ns-import)))
8599 (js2-define-symbol
8600 js2-LET (js2-name-node-name name-node) name-node t))
8601 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8602 (push ns-import children)))
8603 ((js2-match-token js2-LC)
8604 (let ((imports (js2-parse-export-bindings t)))
8605 (setf (js2-import-clause-node-named-imports clause) imports)
8606 (dolist (import imports)
8607 (push import children)
8608 (let ((name-node (js2-export-binding-node-local-name import)))
8609 (when name-node
8610 (js2-define-symbol
8611 js2-LET (js2-name-node-name name-node) name-node t))))))
8612 (t (js2-report-error "msg.syntax")))))
8613 (t (js2-report-error "msg.mod.declaration.after.import")))
8614 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8615 (apply #'js2-node-add-children clause children)
8616 clause))
8617
8618 (defun js2-parse-namespace-import ()
8619 "Parse a namespace import expression such as '* as bar'.
8620 The current token must be js2-MUL."
8621 (let ((beg (js2-current-token-beg)))
8622 (when (js2-must-match js2-NAME "msg.syntax")
8623 (if (equal "as" (js2-current-token-string))
8624 (when (js2-must-match-prop-name "msg.syntax")
8625 (let ((node (make-js2-namespace-import-node
8626 :pos beg
8627 :len (- (js2-current-token-end) beg)
8628 :name (make-js2-name-node
8629 :pos (js2-current-token-beg)
8630 :len (js2-current-token-end)
8631 :name (js2-current-token-string)))))
8632 (js2-node-add-children node (js2-namespace-import-node-name node))
8633 node))
8634 (js2-unget-token)
8635 (js2-report-error "msg.syntax")))))
8636
8637
8638 (defun js2-parse-from-clause ()
8639 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8640 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8641 (let ((beg (js2-current-token-beg)))
8642 (if (equal "from" (js2-current-token-string))
8643 (cond
8644 ((js2-match-token js2-STRING)
8645 (make-js2-from-clause-node
8646 :pos beg
8647 :len (- (js2-current-token-end) beg)
8648 :module-id (js2-current-token-string)
8649 :metadata-p nil))
8650 ((js2-match-token js2-THIS)
8651 (when (js2-must-match-name "msg.mod.spec.after.from")
8652 (if (equal "module" (js2-current-token-string))
8653 (make-js2-from-clause-node
8654 :pos beg
8655 :len (- (js2-current-token-end) beg)
8656 :module-id "this"
8657 :metadata-p t)
8658 (js2-unget-token)
8659 (js2-unget-token)
8660 (js2-report-error "msg.mod.spec.after.from")
8661 nil)))
8662 (t (js2-report-error "msg.mod.spec.after.from") nil))
8663 (js2-unget-token)
8664 (js2-report-error "msg.mod.from.after.import.spec.set")
8665 nil))))
8666
8667 (defun js2-parse-export-bindings (&optional import-p)
8668 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8669 {foo as bar, baz as bang}. The current token must be
8670 js2-LC. Return a lisp list of js2-export-binding-node"
8671 (let ((bindings (list)))
8672 (while
8673 (let ((binding (js2-maybe-parse-export-binding)))
8674 (when binding
8675 (push binding bindings))
8676 (js2-match-token js2-COMMA)))
8677 (when (js2-must-match js2-RC (if import-p
8678 "msg.mod.rc.after.import.spec.list"
8679 "msg.mod.rc.after.export.spec.list"))
8680 (reverse bindings))))
8681
8682 (defun js2-maybe-parse-export-binding ()
8683 "Attempt to parse a binding expression found inside an import/export statement.
8684 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8685 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8686 js2-export-binding-node and consume all the tokens. If it does not match, it
8687 consumes no tokens."
8688 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8689 (beg (js2-current-token-beg))
8690 (extern-name-len (js2-current-token-len))
8691 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8692 (aref js2-kwd-tokens (js2-current-token-type)))))
8693 (if extern-name
8694 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8695 (if (and as (equal "as" (js2-current-token-string)))
8696 (let ((name
8697 (or
8698 (and (js2-match-token js2-DEFAULT) "default")
8699 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8700 (if name
8701 (let ((node (make-js2-export-binding-node
8702 :pos beg
8703 :len (- (js2-current-token-end) beg)
8704 :local-name (make-js2-name-node
8705 :name name
8706 :pos (js2-current-token-beg)
8707 :len (js2-current-token-len))
8708 :extern-name (make-js2-name-node
8709 :name extern-name
8710 :pos beg
8711 :len extern-name-len))))
8712 (js2-node-add-children
8713 node
8714 (js2-export-binding-node-local-name node)
8715 (js2-export-binding-node-extern-name node))
8716 node)
8717 (js2-unget-token)
8718 nil))
8719 (when as (js2-unget-token))
8720 (let* ((name-node (make-js2-name-node
8721 :name (js2-current-token-string)
8722 :pos (js2-current-token-beg)
8723 :len (js2-current-token-len)))
8724 (node (make-js2-export-binding-node
8725 :pos (js2-current-token-beg)
8726 :len (js2-current-token-len)
8727 :local-name name-node
8728 :extern-name name-node)))
8729 (when is-reserved-name
8730 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8731 (js2-node-add-children node name-node)
8732 node)))
8733 nil)))
8734
8735 (defun js2-parse-switch ()
8736 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8737 (let ((pos (js2-current-token-beg))
8738 tt pn discriminant has-default case-expr case-node
8739 case-pos cases stmt lp)
8740 (if (js2-must-match js2-LP "msg.no.paren.switch")
8741 (setq lp (js2-current-token-beg)))
8742 (setq discriminant (js2-parse-expr)
8743 pn (make-js2-switch-node :discriminant discriminant
8744 :pos pos
8745 :lp (js2-relpos lp pos)))
8746 (js2-node-add-children pn discriminant)
8747 (js2-enter-switch pn)
8748 (unwind-protect
8749 (progn
8750 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8751 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8752 (js2-must-match js2-LC "msg.no.brace.switch")
8753 (catch 'break
8754 (while t
8755 (setq tt (js2-next-token)
8756 case-pos (js2-current-token-beg))
8757 (cond
8758 ((= tt js2-RC)
8759 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8760 (throw 'break nil)) ; done
8761 ((= tt js2-CASE)
8762 (setq case-expr (js2-parse-expr))
8763 (js2-must-match js2-COLON "msg.no.colon.case"))
8764 ((= tt js2-DEFAULT)
8765 (if has-default
8766 (js2-report-error "msg.double.switch.default"))
8767 (setq has-default t
8768 case-expr nil)
8769 (js2-must-match js2-COLON "msg.no.colon.case"))
8770 (t
8771 (js2-report-error "msg.bad.switch")
8772 (throw 'break nil)))
8773 (setq case-node (make-js2-case-node :pos case-pos
8774 :len (- (js2-current-token-end) case-pos)
8775 :expr case-expr))
8776 (js2-node-add-children case-node case-expr)
8777 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8778 (/= tt js2-CASE)
8779 (/= tt js2-DEFAULT)
8780 (/= tt js2-EOF))
8781 (setf stmt (js2-parse-statement)
8782 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8783 (js2-block-node-push case-node stmt))
8784 (push case-node cases)))
8785 ;; add cases last, as pushing reverses the order to be correct
8786 (dolist (kid cases)
8787 (js2-node-add-children pn kid)
8788 (push kid (js2-switch-node-cases pn)))
8789 pn) ; return value
8790 (js2-exit-switch))))
8791
8792 (defun js2-parse-while ()
8793 "Parser for while-statement. Last matched token must be js2-WHILE."
8794 (let ((pos (js2-current-token-beg))
8795 (pn (make-js2-while-node))
8796 cond body)
8797 (js2-enter-loop pn)
8798 (unwind-protect
8799 (progn
8800 (setf cond (js2-parse-condition)
8801 (js2-while-node-condition pn) (car cond)
8802 body (js2-parse-statement)
8803 (js2-while-node-body pn) body
8804 (js2-node-len pn) (- (js2-node-end body) pos)
8805 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8806 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8807 (js2-node-add-children pn body (car cond)))
8808 (js2-exit-loop))
8809 pn))
8810
8811 (defun js2-parse-do ()
8812 "Parser for do-statement. Last matched token must be js2-DO."
8813 (let ((pos (js2-current-token-beg))
8814 (pn (make-js2-do-node))
8815 cond body end)
8816 (js2-enter-loop pn)
8817 (unwind-protect
8818 (progn
8819 (setq body (js2-parse-statement))
8820 (js2-must-match js2-WHILE "msg.no.while.do")
8821 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8822 cond (js2-parse-condition)
8823 (js2-do-node-condition pn) (car cond)
8824 (js2-do-node-body pn) body
8825 end js2-ts-cursor
8826 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8827 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8828 (js2-node-add-children pn (car cond) body))
8829 (js2-exit-loop))
8830 ;; Always auto-insert semicolon to follow SpiderMonkey:
8831 ;; It is required by ECMAScript but is ignored by the rest of
8832 ;; world; see bug 238945
8833 (if (js2-match-token js2-SEMI)
8834 (setq end js2-ts-cursor))
8835 (setf (js2-node-len pn) (- end pos))
8836 pn))
8837
8838 (defun js2-parse-export ()
8839 "Parse an export statement.
8840 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8841 expressions should only be either hoistable expressions (function or generator)
8842 or assignment expressions, but there is no checking to enforce that and so it
8843 will parse without error a small subset of
8844 invalid export statements."
8845 (unless (js2-ast-root-p js2-current-scope)
8846 (js2-report-error "msg.mod.export.decl.at.top.level"))
8847 (let ((beg (js2-current-token-beg))
8848 (children (list))
8849 exports-list from-clause declaration default)
8850 (cond
8851 ((js2-match-token js2-MUL)
8852 (setq from-clause (js2-parse-from-clause))
8853 (when from-clause
8854 (push from-clause children)))
8855 ((js2-match-token js2-LC)
8856 (setq exports-list (js2-parse-export-bindings))
8857 (when exports-list
8858 (dolist (export exports-list)
8859 (push export children)))
8860 (when (js2-match-token js2-NAME)
8861 (if (equal "from" (js2-current-token-string))
8862 (progn
8863 (js2-unget-token)
8864 (setq from-clause (js2-parse-from-clause)))
8865 (js2-unget-token))))
8866 ((js2-match-token js2-DEFAULT)
8867 (setq default (cond ((js2-match-token js2-CLASS)
8868 (js2-parse-class-stmt))
8869 ((js2-match-token js2-NAME)
8870 (if (js2-match-async-function)
8871 (js2-parse-async-function-stmt)
8872 (js2-unget-token)
8873 (js2-parse-expr)))
8874 ((js2-match-token js2-FUNCTION)
8875 (js2-parse-function-stmt))
8876 (t (js2-parse-expr)))))
8877 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8878 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8879 ((js2-match-token js2-CLASS)
8880 (setq declaration (js2-parse-class-stmt)))
8881 ((js2-match-token js2-NAME)
8882 (setq declaration
8883 (if (js2-match-async-function)
8884 (js2-parse-async-function-stmt)
8885 (js2-unget-token)
8886 (js2-parse-expr))))
8887 ((js2-match-token js2-FUNCTION)
8888 (setq declaration (js2-parse-function-stmt)))
8889 (t
8890 (setq declaration (js2-parse-expr))))
8891 (when from-clause
8892 (push from-clause children))
8893 (when declaration
8894 (push declaration children)
8895 (when (not (or (js2-function-node-p declaration)
8896 (js2-class-node-p declaration)))
8897 (js2-auto-insert-semicolon declaration)))
8898 (when default
8899 (push default children)
8900 (when (not (or (js2-function-node-p default)
8901 (js2-class-node-p default)))
8902 (js2-auto-insert-semicolon default)))
8903 (let ((node (make-js2-export-node
8904 :pos beg
8905 :len (- (js2-current-token-end) beg)
8906 :exports-list exports-list
8907 :from-clause from-clause
8908 :declaration declaration
8909 :default default)))
8910 (apply #'js2-node-add-children node children)
8911 node)))
8912
8913 (defun js2-parse-for ()
8914 "Parse a for, for-in or for each-in statement.
8915 Last matched token must be js2-FOR."
8916 (let ((for-pos (js2-current-token-beg))
8917 (tmp-scope (make-js2-scope))
8918 pn is-for-each is-for-in-or-of is-for-of
8919 in-pos each-pos tmp-pos
8920 init ; Node init is also foo in 'foo in object'.
8921 cond ; Node cond is also object in 'foo in object'.
8922 incr ; 3rd section of for-loop initializer.
8923 body tt lp rp)
8924 ;; See if this is a for each () instead of just a for ()
8925 (when (js2-match-token js2-NAME)
8926 (if (string= "each" (js2-current-token-string))
8927 (progn
8928 (setq is-for-each t
8929 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8930 (js2-record-face 'font-lock-keyword-face))
8931 (js2-report-error "msg.no.paren.for")))
8932 (if (js2-must-match js2-LP "msg.no.paren.for")
8933 (setq lp (- (js2-current-token-beg) for-pos)))
8934 (setq tt (js2-get-token))
8935 ;; Capture identifiers inside parens. We can't create the node
8936 ;; (and use it as the current scope) until we know its type.
8937 (js2-push-scope tmp-scope)
8938 (unwind-protect
8939 (progn
8940 ;; parse init clause
8941 (let ((js2-in-for-init t)) ; set as dynamic variable
8942 (cond
8943 ((= tt js2-SEMI)
8944 (js2-unget-token)
8945 (setq init (make-js2-empty-expr-node)))
8946 ((or (= tt js2-VAR) (= tt js2-LET) (= tt js2-CONST))
8947 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8948 (t
8949 (js2-unget-token)
8950 (setq init (js2-parse-expr)))))
8951 (if (or (js2-match-token js2-IN)
8952 (and (>= js2-language-version 200)
8953 (js2-match-contextual-kwd "of")
8954 (setq is-for-of t)))
8955 (setq is-for-in-or-of t
8956 in-pos (- (js2-current-token-beg) for-pos)
8957 ;; scope of iteration target object is not the scope we've created above.
8958 ;; stash current scope temporary.
8959 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8960 (js2-parse-expr))) ; object over which we're iterating
8961 ;; else ordinary for loop - parse cond and incr
8962 (js2-must-match js2-SEMI "msg.no.semi.for")
8963 (setq cond (if (= (js2-peek-token) js2-SEMI)
8964 (make-js2-empty-expr-node) ; no loop condition
8965 (js2-parse-expr)))
8966 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8967 (setq tmp-pos (js2-current-token-end)
8968 incr (if (= (js2-peek-token) js2-RP)
8969 (make-js2-empty-expr-node :pos tmp-pos)
8970 (js2-parse-expr)))))
8971 (js2-pop-scope))
8972 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8973 (setq rp (- (js2-current-token-beg) for-pos)))
8974 (if (not is-for-in-or-of)
8975 (setq pn (make-js2-for-node :init init
8976 :condition cond
8977 :update incr
8978 :lp lp
8979 :rp rp))
8980 ;; cond could be null if 'in obj' got eaten by the init node.
8981 (if (js2-infix-node-p init)
8982 ;; it was (foo in bar) instead of (var foo in bar)
8983 (setq cond (js2-infix-node-right init)
8984 init (js2-infix-node-left init))
8985 (if (and (js2-var-decl-node-p init)
8986 (> (length (js2-var-decl-node-kids init)) 1))
8987 (js2-report-error "msg.mult.index")))
8988 (setq pn (make-js2-for-in-node :iterator init
8989 :object cond
8990 :in-pos in-pos
8991 :foreach-p is-for-each
8992 :each-pos each-pos
8993 :forof-p is-for-of
8994 :lp lp
8995 :rp rp)))
8996 ;; Transplant the declarations.
8997 (setf (js2-scope-symbol-table pn)
8998 (js2-scope-symbol-table tmp-scope))
8999 (unwind-protect
9000 (progn
9001 (js2-enter-loop pn)
9002 ;; We have to parse the body -after- creating the loop node,
9003 ;; so that the loop node appears in the js2-loop-set, allowing
9004 ;; break/continue statements to find the enclosing loop.
9005 (setf body (js2-parse-statement)
9006 (js2-loop-node-body pn) body
9007 (js2-node-pos pn) for-pos
9008 (js2-node-len pn) (- (js2-node-end body) for-pos))
9009 (js2-node-add-children pn init cond incr body))
9010 ;; finally
9011 (js2-exit-loop))
9012 pn))
9013
9014 (defun js2-parse-try ()
9015 "Parse a try statement. Last matched token must be js2-TRY."
9016 (let ((try-pos (js2-current-token-beg))
9017 try-end
9018 try-block
9019 catch-blocks
9020 finally-block
9021 saw-default-catch
9022 peek)
9023 (if (/= (js2-peek-token) js2-LC)
9024 (js2-report-error "msg.no.brace.try"))
9025 (setq try-block (js2-parse-statement)
9026 try-end (js2-node-end try-block)
9027 peek (js2-peek-token))
9028 (cond
9029 ((= peek js2-CATCH)
9030 (while (js2-match-token js2-CATCH)
9031 (let* ((catch-pos (js2-current-token-beg))
9032 (catch-node (make-js2-catch-node :pos catch-pos))
9033 param
9034 guard-kwd
9035 catch-cond
9036 lp rp)
9037 (if saw-default-catch
9038 (js2-report-error "msg.catch.unreachable"))
9039 (if (js2-must-match js2-LP "msg.no.paren.catch")
9040 (setq lp (- (js2-current-token-beg) catch-pos)))
9041 (js2-push-scope catch-node)
9042 (let ((tt (js2-peek-token)))
9043 (cond
9044 ;; Destructuring pattern:
9045 ;; catch ({ message, file }) { ... }
9046 ((or (= tt js2-LB) (= tt js2-LC))
9047 (js2-get-token)
9048 (setq param (js2-parse-destruct-primary-expr))
9049 (js2-define-destruct-symbols param js2-LET nil))
9050 ;; Simple name.
9051 (t
9052 (js2-must-match-name "msg.bad.catchcond")
9053 (setq param (js2-create-name-node))
9054 (js2-define-symbol js2-LET (js2-current-token-string) param)
9055 (js2-check-strict-identifier param))))
9056 ;; Catch condition.
9057 (if (js2-match-token js2-IF)
9058 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9059 catch-cond (js2-parse-expr))
9060 (setq saw-default-catch t))
9061 (if (js2-must-match js2-RP "msg.bad.catchcond")
9062 (setq rp (- (js2-current-token-beg) catch-pos)))
9063 (js2-must-match js2-LC "msg.no.brace.catchblock")
9064 (js2-parse-statements catch-node)
9065 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9066 (setq try-end (js2-current-token-end)))
9067 (js2-pop-scope)
9068 (setf (js2-node-len catch-node) (- try-end catch-pos)
9069 (js2-catch-node-param catch-node) param
9070 (js2-catch-node-guard-expr catch-node) catch-cond
9071 (js2-catch-node-guard-kwd catch-node) guard-kwd
9072 (js2-catch-node-lp catch-node) lp
9073 (js2-catch-node-rp catch-node) rp)
9074 (js2-node-add-children catch-node param catch-cond)
9075 (push catch-node catch-blocks))))
9076 ((/= peek js2-FINALLY)
9077 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9078 (js2-node-pos try-block)
9079 (- (setq try-end (js2-node-end try-block))
9080 (js2-node-pos try-block)))))
9081 (when (js2-match-token js2-FINALLY)
9082 (let ((finally-pos (js2-current-token-beg))
9083 (block (js2-parse-statement)))
9084 (setq try-end (js2-node-end block)
9085 finally-block (make-js2-finally-node :pos finally-pos
9086 :len (- try-end finally-pos)
9087 :body block))
9088 (js2-node-add-children finally-block block)))
9089 (let ((pn (make-js2-try-node :pos try-pos
9090 :len (- try-end try-pos)
9091 :try-block try-block
9092 :finally-block finally-block)))
9093 (js2-node-add-children pn try-block finally-block)
9094 ;; Push them onto the try-node, which reverses and corrects their order.
9095 (dolist (cb catch-blocks)
9096 (js2-node-add-children pn cb)
9097 (push cb (js2-try-node-catch-clauses pn)))
9098 pn)))
9099
9100 (defun js2-parse-throw ()
9101 "Parser for throw-statement. Last matched token must be js2-THROW."
9102 (let ((pos (js2-current-token-beg))
9103 expr pn)
9104 (if (= (js2-peek-token-or-eol) js2-EOL)
9105 ;; ECMAScript does not allow new lines before throw expression,
9106 ;; see bug 256617
9107 (js2-report-error "msg.bad.throw.eol"))
9108 (setq expr (js2-parse-expr)
9109 pn (make-js2-throw-node :pos pos
9110 :len (- (js2-node-end expr) pos)
9111 :expr expr))
9112 (js2-node-add-children pn expr)
9113 pn))
9114
9115 (defun js2-match-jump-label-name (label-name)
9116 "If break/continue specified a label, return that label's labeled stmt.
9117 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9118 does not match an existing label, reports an error and returns nil."
9119 (let ((bundle (cdr (assoc label-name js2-label-set))))
9120 (if (null bundle)
9121 (js2-report-error "msg.undef.label"))
9122 bundle))
9123
9124 (defun js2-parse-break ()
9125 "Parser for break-statement. Last matched token must be js2-BREAK."
9126 (let ((pos (js2-current-token-beg))
9127 (end (js2-current-token-end))
9128 break-target ; statement to break from
9129 break-label ; in "break foo", name-node representing the foo
9130 labels ; matching labeled statement to break to
9131 pn)
9132 (when (eq (js2-peek-token-or-eol) js2-NAME)
9133 (js2-get-token)
9134 (setq break-label (js2-create-name-node)
9135 end (js2-node-end break-label)
9136 ;; matchJumpLabelName only matches if there is one
9137 labels (js2-match-jump-label-name (js2-current-token-string))
9138 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9139 (unless (or break-target break-label)
9140 ;; no break target specified - try for innermost enclosing loop/switch
9141 (if (null js2-loop-and-switch-set)
9142 (unless break-label
9143 (js2-report-error "msg.bad.break" nil pos (length "break")))
9144 (setq break-target (car js2-loop-and-switch-set))))
9145 (setq pn (make-js2-break-node :pos pos
9146 :len (- end pos)
9147 :label break-label
9148 :target break-target))
9149 (js2-node-add-children pn break-label) ; but not break-target
9150 pn))
9151
9152 (defun js2-parse-continue ()
9153 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9154 (let ((pos (js2-current-token-beg))
9155 (end (js2-current-token-end))
9156 label ; optional user-specified label, a `js2-name-node'
9157 labels ; current matching labeled stmt, if any
9158 target ; the `js2-loop-node' target of this continue stmt
9159 pn)
9160 (when (= (js2-peek-token-or-eol) js2-NAME)
9161 (js2-get-token)
9162 (setq label (js2-create-name-node)
9163 end (js2-node-end label)
9164 ;; matchJumpLabelName only matches if there is one
9165 labels (js2-match-jump-label-name (js2-current-token-string))))
9166 (cond
9167 ((null labels) ; no current label to go to
9168 (if (null js2-loop-set) ; no loop to continue to
9169 (js2-report-error "msg.continue.outside" nil pos
9170 (length "continue"))
9171 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9172 (t
9173 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9174 (setq target (js2-labeled-stmt-node-stmt labels))
9175 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9176 (setq pn (make-js2-continue-node :pos pos
9177 :len (- end pos)
9178 :label label
9179 :target target))
9180 (js2-node-add-children pn label) ; but not target - it's not our child
9181 pn))
9182
9183 (defun js2-parse-with ()
9184 "Parser for with-statement. Last matched token must be js2-WITH."
9185 (when js2-in-use-strict-directive
9186 (js2-report-error "msg.no.with.strict"))
9187 (let ((pos (js2-current-token-beg))
9188 obj body pn lp rp)
9189 (if (js2-must-match js2-LP "msg.no.paren.with")
9190 (setq lp (js2-current-token-beg)))
9191 (setq obj (js2-parse-expr))
9192 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9193 (setq rp (js2-current-token-beg)))
9194 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9195 (setq body (js2-parse-statement)))
9196 (setq pn (make-js2-with-node :pos pos
9197 :len (- (js2-node-end body) pos)
9198 :object obj
9199 :body body
9200 :lp (js2-relpos lp pos)
9201 :rp (js2-relpos rp pos)))
9202 (js2-node-add-children pn obj body)
9203 pn))
9204
9205 (defun js2-parse-const-var ()
9206 "Parser for var- or const-statement.
9207 Last matched token must be js2-CONST or js2-VAR."
9208 (let ((tt (js2-current-token-type))
9209 (pos (js2-current-token-beg))
9210 expr pn)
9211 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9212 pn (make-js2-expr-stmt-node :pos pos
9213 :len (- (js2-node-end expr) pos)
9214 :expr expr))
9215 (js2-node-add-children pn expr)
9216 pn))
9217
9218 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9219 (let ((pn (make-js2-expr-stmt-node :pos pos
9220 :len (js2-node-len expr)
9221 :type (if (js2-inside-function)
9222 js2-EXPR_VOID
9223 js2-EXPR_RESULT)
9224 :expr expr)))
9225 (if add-child
9226 (js2-node-add-children pn expr))
9227 pn))
9228
9229 (defun js2-parse-let-stmt ()
9230 "Parser for let-statement. Last matched token must be js2-LET."
9231 (let ((pos (js2-current-token-beg))
9232 expr pn)
9233 (if (= (js2-peek-token) js2-LP)
9234 ;; let expression in statement context
9235 (setq expr (js2-parse-let pos 'statement)
9236 pn (js2-wrap-with-expr-stmt pos expr t))
9237 ;; else we're looking at a statement like let x=6, y=7;
9238 (setf expr (js2-parse-variables js2-LET pos)
9239 pn (js2-wrap-with-expr-stmt pos expr t)
9240 (js2-node-type pn) js2-EXPR_RESULT))
9241 pn))
9242
9243 (defun js2-parse-ret-yield ()
9244 (js2-parse-return-or-yield (js2-current-token-type) nil))
9245
9246 (defconst js2-parse-return-stmt-enders
9247 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9248
9249 (defsubst js2-now-all-set (before after mask)
9250 "Return whether or not the bits in the mask have changed to all set.
9251 BEFORE is bits before change, AFTER is bits after change, and MASK is
9252 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9253 but not BEFORE."
9254 (and (/= (logand before mask) mask)
9255 (= (logand after mask) mask)))
9256
9257 (defun js2-parse-return-or-yield (tt expr-context)
9258 (let* ((pos (js2-current-token-beg))
9259 (end (js2-current-token-end))
9260 (before js2-end-flags)
9261 (inside-function (js2-inside-function))
9262 (gen-type (and inside-function (js2-function-node-generator-type
9263 js2-current-script-or-fn)))
9264 e ret name yield-star-p)
9265 (unless inside-function
9266 (js2-report-error (if (eq tt js2-RETURN)
9267 "msg.bad.return"
9268 "msg.bad.yield")))
9269 (when (and inside-function
9270 (eq gen-type 'STAR)
9271 (js2-match-token js2-MUL))
9272 (setq yield-star-p t))
9273 ;; This is ugly, but we don't want to require a semicolon.
9274 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9275 (setq e (js2-parse-expr)
9276 end (js2-node-end e)))
9277 (cond
9278 ((eq tt js2-RETURN)
9279 (js2-set-flag js2-end-flags (if (null e)
9280 js2-end-returns
9281 js2-end-returns-value))
9282 (setq ret (make-js2-return-node :pos pos
9283 :len (- end pos)
9284 :retval e))
9285 (js2-node-add-children ret e)
9286 ;; See if we need a strict mode warning.
9287 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9288 ;; more thorough and accurate than this before/after flag check.
9289 ;; E.g. if there's a finally-block that always returns, we shouldn't
9290 ;; show a warning generated by inconsistent returns in the catch blocks.
9291 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9292 ;; so we know which returns/yields to highlight, and we should get rid of
9293 ;; all the checking in `js2-parse-return-or-yield'.
9294 (if (and js2-strict-inconsistent-return-warning
9295 (js2-now-all-set before js2-end-flags
9296 (logior js2-end-returns js2-end-returns-value)))
9297 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9298 ((eq gen-type 'COMPREHENSION)
9299 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9300 ;; like SpiderMonkey does.
9301 (js2-report-error "msg.syntax" nil pos 5))
9302 (t
9303 (setq ret (make-js2-yield-node :pos pos
9304 :len (- end pos)
9305 :value e
9306 :star-p yield-star-p))
9307 (js2-node-add-children ret e)
9308 (unless expr-context
9309 (setq e ret
9310 ret (js2-wrap-with-expr-stmt pos e t))
9311 (js2-set-requires-activation)
9312 (js2-set-is-generator))))
9313 ;; see if we are mixing yields and value returns.
9314 (when (and inside-function
9315 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9316 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9317 'LEGACY))
9318 (setq name (js2-function-name js2-current-script-or-fn))
9319 (if (zerop (length name))
9320 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9321 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9322 ret))
9323
9324 (defun js2-parse-debugger ()
9325 (make-js2-keyword-node :type js2-DEBUGGER))
9326
9327 (defun js2-parse-block ()
9328 "Parser for a curly-delimited statement block.
9329 Last token matched must be `js2-LC'."
9330 (let ((pos (js2-current-token-beg))
9331 (pn (make-js2-scope)))
9332 (js2-push-scope pn)
9333 (unwind-protect
9334 (progn
9335 (js2-parse-statements pn)
9336 (js2-must-match js2-RC "msg.no.brace.block")
9337 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9338 (js2-pop-scope))
9339 pn))
9340
9341 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9342 (defun js2-parse-semi ()
9343 "Parse a statement or handle an error.
9344 Current token type is `js2-SEMI' or `js2-ERROR'."
9345 (let ((tt (js2-current-token-type)) pos len)
9346 (if (eq tt js2-SEMI)
9347 (make-js2-empty-expr-node :len 1)
9348 (setq pos (js2-current-token-beg)
9349 len (- (js2-current-token-end) pos))
9350 (js2-report-error "msg.syntax" nil pos len)
9351 (make-js2-error-node :pos pos :len len))))
9352
9353 (defun js2-parse-default-xml-namespace ()
9354 "Parse a `default xml namespace = <expr>' e4x statement."
9355 (let ((pos (js2-current-token-beg))
9356 end len expr unary)
9357 (js2-must-have-xml)
9358 (js2-set-requires-activation)
9359 (setq len (- js2-ts-cursor pos))
9360 (unless (and (js2-match-token js2-NAME)
9361 (string= (js2-current-token-string) "xml"))
9362 (js2-report-error "msg.bad.namespace" nil pos len))
9363 (unless (and (js2-match-token js2-NAME)
9364 (string= (js2-current-token-string) "namespace"))
9365 (js2-report-error "msg.bad.namespace" nil pos len))
9366 (unless (js2-match-token js2-ASSIGN)
9367 (js2-report-error "msg.bad.namespace" nil pos len))
9368 (setq expr (js2-parse-expr)
9369 end (js2-node-end expr)
9370 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9371 :pos pos
9372 :len (- end pos)
9373 :operand expr))
9374 (js2-node-add-children unary expr)
9375 (make-js2-expr-stmt-node :pos pos
9376 :len (- end pos)
9377 :expr unary)))
9378
9379 (defun js2-record-label (label bundle)
9380 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9381 (js2-get-token)
9382 (let ((name (js2-label-node-name label))
9383 labeled-stmt
9384 dup)
9385 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9386 ;; flag both labels if possible when used in editing mode
9387 (if (and js2-parse-ide-mode
9388 (setq dup (js2-get-label-by-name labeled-stmt name)))
9389 (js2-report-error "msg.dup.label" nil
9390 (js2-node-abs-pos dup) (js2-node-len dup)))
9391 (js2-report-error "msg.dup.label" nil
9392 (js2-node-pos label) (js2-node-len label)))
9393 (js2-labeled-stmt-node-add-label bundle label)
9394 (js2-node-add-children bundle label)
9395 ;; Add one reference to the bundle per label in `js2-label-set'
9396 (push (cons name bundle) js2-label-set)))
9397
9398 (defun js2-parse-name-or-label ()
9399 "Parser for identifier or label. Last token matched must be js2-NAME.
9400 Called when we found a name in a statement context. If it's a label, we gather
9401 up any following labels and the next non-label statement into a
9402 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9403 expression and return it wrapped in a `js2-expr-stmt-node'."
9404 (let ((pos (js2-current-token-beg))
9405 expr stmt bundle
9406 (continue t))
9407 ;; set check for label and call down to `js2-parse-primary-expr'
9408 (setq expr (js2-maybe-parse-label))
9409 (if (null expr)
9410 ;; Parse the non-label expression and wrap with expression stmt.
9411 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9412 ;; else parsed a label
9413 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9414 (js2-record-label expr bundle)
9415 ;; look for more labels
9416 (while (and continue (= (js2-get-token) js2-NAME))
9417 (if (setq expr (js2-maybe-parse-label))
9418 (js2-record-label expr bundle)
9419 (setq expr (js2-parse-expr)
9420 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9421 continue nil)
9422 (js2-auto-insert-semicolon stmt)))
9423 ;; no more labels; now parse the labeled statement
9424 (unwind-protect
9425 (unless stmt
9426 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9427 (js2-unget-token)
9428 (setq stmt (js2-statement-helper))))
9429 ;; remove the labels for this statement from the global set
9430 (dolist (label (js2-labeled-stmt-node-labels bundle))
9431 (setq js2-label-set (remove label js2-label-set))))
9432 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9433 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9434 (js2-node-add-children bundle stmt)
9435 bundle)))
9436
9437 (defun js2-maybe-parse-label ()
9438 (cl-assert (= (js2-current-token-type) js2-NAME))
9439 (let (label-pos
9440 (next-tt (js2-get-token))
9441 (label-end (js2-current-token-end)))
9442 ;; Do not consume colon, it is used as unwind indicator
9443 ;; to return to statementHelper.
9444 (js2-unget-token)
9445 (if (= next-tt js2-COLON)
9446 (prog2
9447 (setq label-pos (js2-current-token-beg))
9448 (make-js2-label-node :pos label-pos
9449 :len (- label-end label-pos)
9450 :name (js2-current-token-string))
9451 (js2-set-face label-pos
9452 label-end
9453 'font-lock-variable-name-face 'record))
9454 ;; Backtrack from the name token, too.
9455 (js2-unget-token)
9456 nil)))
9457
9458 (defun js2-parse-expr-stmt ()
9459 "Default parser in statement context, if no recognized statement found."
9460 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9461 (progn
9462 (js2-unget-token)
9463 (js2-parse-expr)) t))
9464
9465 (defun js2-parse-variables (decl-type pos)
9466 "Parse a comma-separated list of variable declarations.
9467 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9468
9469 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9470 For 'var' or 'const', the keyword should be the token last scanned.
9471
9472 POS is the position where the node should start. It's sometimes the
9473 var/const/let keyword, and other times the beginning of the first token
9474 in the first variable declaration.
9475
9476 Returns the parsed `js2-var-decl-node' expression node."
9477 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9478 :pos pos))
9479 destructuring kid-pos tt init name end nbeg nend vi
9480 (continue t))
9481 ;; Example:
9482 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9483 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9484 ;; var {a, b} = baz;
9485 (while continue
9486 (setq destructuring nil
9487 name nil
9488 tt (js2-get-token)
9489 kid-pos (js2-current-token-beg)
9490 end (js2-current-token-end)
9491 init nil)
9492 (if (or (= tt js2-LB) (= tt js2-LC))
9493 ;; Destructuring assignment, e.g., var [a, b] = ...
9494 (setq destructuring (js2-parse-destruct-primary-expr)
9495 end (js2-node-end destructuring))
9496 ;; Simple variable name
9497 (js2-unget-token)
9498 (when (js2-must-match-name "msg.bad.var")
9499 (setq name (js2-create-name-node)
9500 nbeg (js2-current-token-beg)
9501 nend (js2-current-token-end)
9502 end nend)
9503 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9504 (js2-check-strict-identifier name)))
9505 (when (js2-match-token js2-ASSIGN)
9506 (setq init (js2-parse-assign-expr)
9507 end (js2-node-end init))
9508 (js2-record-imenu-functions init name))
9509 (when name
9510 (js2-set-face nbeg nend (if (js2-function-node-p init)
9511 'font-lock-function-name-face
9512 'font-lock-variable-name-face)
9513 'record))
9514 (setq vi (make-js2-var-init-node :pos kid-pos
9515 :len (- end kid-pos)
9516 :type decl-type))
9517 (if destructuring
9518 (progn
9519 (if (and (null init) (not js2-in-for-init))
9520 (js2-report-error "msg.destruct.assign.no.init"))
9521 (js2-define-destruct-symbols destructuring
9522 decl-type
9523 'font-lock-variable-name-face)
9524 (setf (js2-var-init-node-target vi) destructuring))
9525 (setf (js2-var-init-node-target vi) name))
9526 (setf (js2-var-init-node-initializer vi) init)
9527 (js2-node-add-children vi name destructuring init)
9528 (js2-block-node-push result vi)
9529 (unless (js2-match-token js2-COMMA)
9530 (setq continue nil)))
9531 (setf (js2-node-len result) (- end pos))
9532 result))
9533
9534 (defun js2-parse-let (pos &optional stmt-p)
9535 "Parse a let expression or statement.
9536 A let-expression is of the form `let (vars) expr'.
9537 A let-statement is of the form `let (vars) {statements}'.
9538 The third form of let is a variable declaration list, handled
9539 by `js2-parse-variables'."
9540 (let ((pn (make-js2-let-node :pos pos))
9541 beg vars body)
9542 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9543 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9544 (js2-push-scope pn)
9545 (unwind-protect
9546 (progn
9547 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9548 (if (js2-must-match js2-RP "msg.no.paren.let")
9549 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9550 (if (and stmt-p (js2-match-token js2-LC))
9551 ;; let statement
9552 (progn
9553 (setf beg (js2-current-token-beg) ; position stmt at LC
9554 body (js2-parse-statements))
9555 (js2-must-match js2-RC "msg.no.curly.let")
9556 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9557 (js2-node-len pn) (- (js2-current-token-end) pos)
9558 (js2-let-node-body pn) body
9559 (js2-node-type pn) js2-LET))
9560 ;; let expression
9561 (setf body (js2-parse-expr)
9562 (js2-node-len pn) (- (js2-node-end body) pos)
9563 (js2-let-node-body pn) body))
9564 (setf (js2-let-node-vars pn) vars)
9565 (js2-node-add-children pn vars body))
9566 (js2-pop-scope))
9567 pn))
9568
9569 (defun js2-define-new-symbol (decl-type name node &optional scope)
9570 (js2-scope-put-symbol (or scope js2-current-scope)
9571 name
9572 (make-js2-symbol decl-type name node)))
9573
9574 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9575 "Define a symbol in the current scope.
9576 If NODE is non-nil, it is the AST node associated with the symbol."
9577 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9578 (symbol (if defining-scope
9579 (js2-scope-get-symbol defining-scope name)))
9580 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9581 (pos (if node (js2-node-abs-pos node)))
9582 (len (if node (js2-node-len node))))
9583 (cond
9584 ((and symbol ; already defined
9585 (or (if js2-in-use-strict-directive
9586 ;; two const-bound vars in this block have same name
9587 (and (= sdt js2-CONST)
9588 (eq defining-scope js2-current-scope))
9589 (or (= sdt js2-CONST) ; old version is const
9590 (= decl-type js2-CONST))) ; new version is const
9591 ;; two let-bound vars in this block have same name
9592 (and (= sdt js2-LET)
9593 (eq defining-scope js2-current-scope))))
9594 (js2-report-error
9595 (cond
9596 ((= sdt js2-CONST) "msg.const.redecl")
9597 ((= sdt js2-LET) "msg.let.redecl")
9598 ((= sdt js2-VAR) "msg.var.redecl")
9599 ((= sdt js2-FUNCTION) "msg.function.redecl")
9600 (t "msg.parm.redecl"))
9601 name pos len))
9602 ((or (= decl-type js2-LET)
9603 ;; strict mode const is scoped to the current LexicalEnvironment
9604 (and js2-in-use-strict-directive
9605 (= decl-type js2-CONST)))
9606 (if (and (= decl-type js2-LET)
9607 (not ignore-not-in-block)
9608 (or (= (js2-node-type js2-current-scope) js2-IF)
9609 (js2-loop-node-p js2-current-scope)))
9610 (js2-report-error "msg.let.decl.not.in.block")
9611 (js2-define-new-symbol decl-type name node)))
9612 ((or (= decl-type js2-VAR)
9613 (= decl-type js2-FUNCTION)
9614 ;; sloppy mode const is scoped to the current VariableEnvironment
9615 (and (not js2-in-use-strict-directive)
9616 (= decl-type js2-CONST)))
9617 (if symbol
9618 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9619 (js2-add-strict-warning "msg.var.redecl" name)
9620 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9621 (js2-add-strict-warning "msg.var.hides.arg" name)))
9622 (js2-define-new-symbol decl-type name node
9623 js2-current-script-or-fn)))
9624 ((= decl-type js2-LP)
9625 (if symbol
9626 ;; must be duplicate parameter. Second parameter hides the
9627 ;; first, so go ahead and add the second pararameter
9628 (js2-report-warning "msg.dup.parms" name))
9629 (js2-define-new-symbol decl-type name node))
9630 (t (js2-code-bug)))))
9631
9632 (defun js2-parse-paren-expr-or-generator-comp ()
9633 (let ((px-pos (js2-current-token-beg)))
9634 (cond
9635 ((and (>= js2-language-version 200)
9636 (js2-match-token js2-FOR))
9637 (js2-parse-generator-comp px-pos))
9638 ((and (>= js2-language-version 200)
9639 (js2-match-token js2-RP))
9640 ;; Not valid expression syntax, but this is valid in an arrow
9641 ;; function with no params: () => body.
9642 (if (eq (js2-peek-token) js2-ARROW)
9643 ;; Return whatever, it will hopefully be rewinded and
9644 ;; reparsed when we reach the =>.
9645 (make-js2-keyword-node :type js2-NULL)
9646 (js2-report-error "msg.syntax")
9647 (make-js2-error-node)))
9648 (t
9649 (let* ((js2-in-for-init nil)
9650 (expr (js2-parse-expr))
9651 (pn (make-js2-paren-node :pos px-pos
9652 :expr expr)))
9653 (js2-node-add-children pn (js2-paren-node-expr pn))
9654 (js2-must-match js2-RP "msg.no.paren")
9655 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9656 pn)))))
9657
9658 (defun js2-parse-expr (&optional oneshot)
9659 (let* ((pn (js2-parse-assign-expr))
9660 (pos (js2-node-pos pn))
9661 left
9662 right
9663 op-pos)
9664 (while (and (not oneshot)
9665 (js2-match-token js2-COMMA))
9666 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9667 (if (= (js2-peek-token) js2-YIELD)
9668 (js2-report-error "msg.yield.parenthesized"))
9669 (setq right (js2-parse-assign-expr)
9670 left pn
9671 pn (make-js2-infix-node :type js2-COMMA
9672 :pos pos
9673 :len (- js2-ts-cursor pos)
9674 :op-pos op-pos
9675 :left left
9676 :right right))
9677 (js2-node-add-children pn left right))
9678 pn))
9679
9680 (defun js2-parse-assign-expr ()
9681 (let ((tt (js2-get-token))
9682 (pos (js2-current-token-beg))
9683 pn left right op-pos
9684 ts-state recorded-identifiers parsed-errors
9685 async-p)
9686 (if (= tt js2-YIELD)
9687 (js2-parse-return-or-yield tt t)
9688 ;; TODO(mooz): Bit confusing.
9689 ;; If we meet `async` token and it's not part of `async
9690 ;; function`, then this `async` is for a succeeding async arrow
9691 ;; function.
9692 ;; Since arrow function parsing doesn't rely on neither
9693 ;; `js2-parse-function-stmt' nor `js2-parse-function-expr' that
9694 ;; interpret `async` token, we trash `async` and just remember
9695 ;; we met `async` keyword to `async-p'.
9696 (when (js2-match-async-arrow-function-1)
9697 (setq async-p t))
9698 ;; Save the tokenizer state in case we find an arrow function
9699 ;; and have to rewind.
9700 (setq ts-state (make-js2-ts-state)
9701 recorded-identifiers js2-recorded-identifiers
9702 parsed-errors js2-parsed-errors)
9703 ;; not yield - parse assignment expression
9704 (setq pn (js2-parse-cond-expr)
9705 tt (js2-get-token))
9706 (cond
9707 ((and (<= js2-first-assign tt)
9708 (<= tt js2-last-assign))
9709 ;; tt express assignment (=, |=, ^=, ..., %=)
9710 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9711 left pn)
9712 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9713 ;; care about assignment to strict variable names.
9714 (when (js2-name-node-p left)
9715 (js2-check-strict-identifier left))
9716 (setq right (js2-parse-assign-expr)
9717 pn (make-js2-assign-node :type tt
9718 :pos pos
9719 :len (- (js2-node-end right) pos)
9720 :op-pos op-pos
9721 :left left
9722 :right right))
9723 (when js2-parse-ide-mode
9724 (js2-highlight-assign-targets pn left right)
9725 (js2-record-imenu-functions right left))
9726 ;; do this last so ide checks above can use absolute positions
9727 (js2-node-add-children pn left right))
9728 ((and (= tt js2-ARROW)
9729 (>= js2-language-version 200))
9730 (js2-ts-seek ts-state)
9731 (when async-p
9732 (js2-match-async-arrow-function-2))
9733 (setq js2-recorded-identifiers recorded-identifiers
9734 js2-parsed-errors parsed-errors)
9735 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil async-p)))
9736 (t
9737 (js2-unget-token)))
9738 pn)))
9739
9740 (defun js2-parse-cond-expr ()
9741 (let ((pos (js2-current-token-beg))
9742 (pn (js2-parse-or-expr))
9743 test-expr
9744 if-true
9745 if-false
9746 q-pos
9747 c-pos)
9748 (when (js2-match-token js2-HOOK)
9749 (setq q-pos (- (js2-current-token-beg) pos)
9750 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9751 (js2-must-match js2-COLON "msg.no.colon.cond")
9752 (setq c-pos (- (js2-current-token-beg) pos)
9753 if-false (js2-parse-assign-expr)
9754 test-expr pn
9755 pn (make-js2-cond-node :pos pos
9756 :len (- (js2-node-end if-false) pos)
9757 :test-expr test-expr
9758 :true-expr if-true
9759 :false-expr if-false
9760 :q-pos q-pos
9761 :c-pos c-pos))
9762 (js2-node-add-children pn test-expr if-true if-false))
9763 pn))
9764
9765 (defun js2-make-binary (type left parser &optional no-get)
9766 "Helper for constructing a binary-operator AST node.
9767 LEFT is the left-side-expression, already parsed, and the
9768 binary operator should have just been matched.
9769 PARSER is a function to call to parse the right operand,
9770 or a `js2-node' struct if it has already been parsed.
9771 FIXME: The latter option is unused?"
9772 (let* ((pos (js2-node-pos left))
9773 (op-pos (- (js2-current-token-beg) pos))
9774 (right (if (js2-node-p parser)
9775 parser
9776 (unless no-get (js2-get-token))
9777 (funcall parser)))
9778 (pn (make-js2-infix-node :type type
9779 :pos pos
9780 :len (- (js2-node-end right) pos)
9781 :op-pos op-pos
9782 :left left
9783 :right right)))
9784 (js2-node-add-children pn left right)
9785 pn))
9786
9787 (defun js2-parse-or-expr ()
9788 (let ((pn (js2-parse-and-expr)))
9789 (when (js2-match-token js2-OR)
9790 (setq pn (js2-make-binary js2-OR
9791 pn
9792 'js2-parse-or-expr)))
9793 pn))
9794
9795 (defun js2-parse-and-expr ()
9796 (let ((pn (js2-parse-bit-or-expr)))
9797 (when (js2-match-token js2-AND)
9798 (setq pn (js2-make-binary js2-AND
9799 pn
9800 'js2-parse-and-expr)))
9801 pn))
9802
9803 (defun js2-parse-bit-or-expr ()
9804 (let ((pn (js2-parse-bit-xor-expr)))
9805 (while (js2-match-token js2-BITOR)
9806 (setq pn (js2-make-binary js2-BITOR
9807 pn
9808 'js2-parse-bit-xor-expr)))
9809 pn))
9810
9811 (defun js2-parse-bit-xor-expr ()
9812 (let ((pn (js2-parse-bit-and-expr)))
9813 (while (js2-match-token js2-BITXOR)
9814 (setq pn (js2-make-binary js2-BITXOR
9815 pn
9816 'js2-parse-bit-and-expr)))
9817 pn))
9818
9819 (defun js2-parse-bit-and-expr ()
9820 (let ((pn (js2-parse-eq-expr)))
9821 (while (js2-match-token js2-BITAND)
9822 (setq pn (js2-make-binary js2-BITAND
9823 pn
9824 'js2-parse-eq-expr)))
9825 pn))
9826
9827 (defconst js2-parse-eq-ops
9828 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9829
9830 (defun js2-parse-eq-expr ()
9831 (let ((pn (js2-parse-rel-expr))
9832 tt)
9833 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9834 (setq pn (js2-make-binary tt
9835 pn
9836 'js2-parse-rel-expr)))
9837 (js2-unget-token)
9838 pn))
9839
9840 (defconst js2-parse-rel-ops
9841 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9842
9843 (defun js2-parse-rel-expr ()
9844 (let ((pn (js2-parse-shift-expr))
9845 (continue t)
9846 tt)
9847 (while continue
9848 (setq tt (js2-get-token))
9849 (cond
9850 ((and js2-in-for-init (= tt js2-IN))
9851 (js2-unget-token)
9852 (setq continue nil))
9853 ((memq tt js2-parse-rel-ops)
9854 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9855 (t
9856 (js2-unget-token)
9857 (setq continue nil))))
9858 pn))
9859
9860 (defconst js2-parse-shift-ops
9861 (list js2-LSH js2-URSH js2-RSH))
9862
9863 (defun js2-parse-shift-expr ()
9864 (let ((pn (js2-parse-add-expr))
9865 tt
9866 (continue t))
9867 (while continue
9868 (setq tt (js2-get-token))
9869 (if (memq tt js2-parse-shift-ops)
9870 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9871 (js2-unget-token)
9872 (setq continue nil)))
9873 pn))
9874
9875 (defun js2-parse-add-expr ()
9876 (let ((pn (js2-parse-mul-expr))
9877 tt
9878 (continue t))
9879 (while continue
9880 (setq tt (js2-get-token))
9881 (if (or (= tt js2-ADD) (= tt js2-SUB))
9882 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9883 (js2-unget-token)
9884 (setq continue nil)))
9885 pn))
9886
9887 (defconst js2-parse-mul-ops
9888 (list js2-MUL js2-DIV js2-MOD))
9889
9890 (defun js2-parse-mul-expr ()
9891 (let ((pn (js2-parse-unary-expr))
9892 tt
9893 (continue t))
9894 (while continue
9895 (setq tt (js2-get-token))
9896 (if (memq tt js2-parse-mul-ops)
9897 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9898 (js2-unget-token)
9899 (setq continue nil)))
9900 pn))
9901
9902 (defun js2-make-unary (type parser &rest args)
9903 "Make a unary node of type TYPE.
9904 PARSER is either a node (for postfix operators) or a function to call
9905 to parse the operand (for prefix operators)."
9906 (let* ((pos (js2-current-token-beg))
9907 (postfix (js2-node-p parser))
9908 (expr (if postfix
9909 parser
9910 (apply parser args)))
9911 end
9912 pn)
9913 (if postfix ; e.g. i++
9914 (setq pos (js2-node-pos expr)
9915 end (js2-current-token-end))
9916 (setq end (js2-node-end expr)))
9917 (setq pn (make-js2-unary-node :type type
9918 :pos pos
9919 :len (- end pos)
9920 :operand expr))
9921 (js2-node-add-children pn expr)
9922 pn))
9923
9924 (defconst js2-incrementable-node-types
9925 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9926 "Node types that can be the operand of a ++ or -- operator.")
9927
9928 (defun js2-check-bad-inc-dec (tt beg end unary)
9929 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9930 js2-incrementable-node-types)
9931 (js2-report-error (if (= tt js2-INC)
9932 "msg.bad.incr"
9933 "msg.bad.decr")
9934 nil beg (- end beg))))
9935
9936 (defun js2-parse-unary-expr ()
9937 (let ((tt (js2-current-token-type))
9938 pn expr beg end)
9939 (cond
9940 ((or (= tt js2-VOID)
9941 (= tt js2-NOT)
9942 (= tt js2-BITNOT)
9943 (= tt js2-TYPEOF))
9944 (js2-get-token)
9945 (js2-make-unary tt 'js2-parse-unary-expr))
9946 ((= tt js2-ADD)
9947 (js2-get-token)
9948 ;; Convert to special POS token in decompiler and parse tree
9949 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9950 ((= tt js2-SUB)
9951 (js2-get-token)
9952 ;; Convert to special NEG token in decompiler and parse tree
9953 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9954 ((or (= tt js2-INC)
9955 (= tt js2-DEC))
9956 (js2-get-token)
9957 (prog1
9958 (setq beg (js2-current-token-beg)
9959 end (js2-current-token-end)
9960 expr (js2-make-unary tt 'js2-parse-member-expr t))
9961 (js2-check-bad-inc-dec tt beg end expr)))
9962 ((= tt js2-DELPROP)
9963 (js2-get-token)
9964 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9965 ((js2-match-await tt)
9966 (js2-make-unary js2-AWAIT 'js2-parse-unary-expr))
9967 ((= tt js2-ERROR)
9968 (js2-get-token)
9969 (make-js2-error-node)) ; try to continue
9970 ((and (= tt js2-LT)
9971 js2-compiler-xml-available)
9972 ;; XML stream encountered in expression.
9973 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9974 (t
9975 (setq pn (js2-parse-member-expr t)
9976 ;; Don't look across a newline boundary for a postfix incop.
9977 tt (js2-peek-token-or-eol))
9978 (when (or (= tt js2-INC) (= tt js2-DEC))
9979 (js2-get-token)
9980 (setf expr pn
9981 pn (js2-make-unary tt expr))
9982 (js2-node-set-prop pn 'postfix t)
9983 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9984 pn))))
9985
9986 (defun js2-parse-xml-initializer ()
9987 "Parse an E4X XML initializer.
9988 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9989 Then I'll postprocess the result, depending on whether we're in IDE
9990 mode or codegen mode, and generate the appropriate rewritten AST.
9991 IDE mode uses a rich AST that models the XML structure. Codegen mode
9992 just concatenates everything and makes a new XML or XMLList out of it."
9993 (let ((tt (js2-get-first-xml-token))
9994 pn-xml pn expr kids expr-pos
9995 (continue t)
9996 (first-token t))
9997 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9998 (js2-report-error "msg.syntax"))
9999 (setq pn-xml (make-js2-xml-node))
10000 (while continue
10001 (if first-token
10002 (setq first-token nil)
10003 (setq tt (js2-get-next-xml-token)))
10004 (cond
10005 ;; js2-XML means we found a {expr} in the XML stream.
10006 ;; The token string is the XML up to the left-curly.
10007 ((= tt js2-XML)
10008 (push (make-js2-string-node :pos (js2-current-token-beg)
10009 :len (- js2-ts-cursor (js2-current-token-beg)))
10010 kids)
10011 (js2-must-match js2-LC "msg.syntax")
10012 (setq expr-pos js2-ts-cursor
10013 expr (if (eq (js2-peek-token) js2-RC)
10014 (make-js2-empty-expr-node :pos expr-pos)
10015 (js2-parse-expr)))
10016 (js2-must-match js2-RC "msg.syntax")
10017 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
10018 :len (js2-node-len expr)
10019 :expr expr))
10020 (js2-node-add-children pn expr)
10021 (push pn kids))
10022 ;; a js2-XMLEND token means we hit the final close-tag.
10023 ((= tt js2-XMLEND)
10024 (push (make-js2-string-node :pos (js2-current-token-beg)
10025 :len (- js2-ts-cursor (js2-current-token-beg)))
10026 kids)
10027 (dolist (kid (nreverse kids))
10028 (js2-block-node-push pn-xml kid))
10029 (setf (js2-node-len pn-xml) (- js2-ts-cursor
10030 (js2-node-pos pn-xml))
10031 continue nil))
10032 (t
10033 (js2-report-error "msg.syntax")
10034 (setq continue nil))))
10035 pn-xml))
10036
10037
10038 (defun js2-parse-argument-list ()
10039 "Parse an argument list and return it as a Lisp list of nodes.
10040 Returns the list in reverse order. Consumes the right-paren token."
10041 (let (result)
10042 (unless (js2-match-token js2-RP)
10043 (cl-loop do
10044 (let ((tt (js2-get-token)))
10045 (if (= tt js2-YIELD)
10046 (js2-report-error "msg.yield.parenthesized"))
10047 (if (and (= tt js2-TRIPLEDOT)
10048 (>= js2-language-version 200))
10049 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
10050 (js2-unget-token)
10051 (push (js2-parse-assign-expr) result)))
10052 while
10053 (js2-match-token js2-COMMA))
10054 (js2-must-match js2-RP "msg.no.paren.arg")
10055 result)))
10056
10057 (defun js2-parse-member-expr (&optional allow-call-syntax)
10058 (let ((tt (js2-current-token-type))
10059 pn pos target args beg end init)
10060 (if (/= tt js2-NEW)
10061 (setq pn (js2-parse-primary-expr))
10062 ;; parse a 'new' expression
10063 (js2-get-token)
10064 (setq pos (js2-current-token-beg)
10065 beg pos
10066 target (js2-parse-member-expr)
10067 end (js2-node-end target)
10068 pn (make-js2-new-node :pos pos
10069 :target target
10070 :len (- end pos)))
10071 (js2-highlight-function-call (js2-current-token))
10072 (js2-node-add-children pn target)
10073 (when (js2-match-token js2-LP)
10074 ;; Add the arguments to pn, if any are supplied.
10075 (setf beg pos ; start of "new" keyword
10076 pos (js2-current-token-beg)
10077 args (nreverse (js2-parse-argument-list))
10078 (js2-new-node-args pn) args
10079 end (js2-current-token-end)
10080 (js2-new-node-lp pn) (- pos beg)
10081 (js2-new-node-rp pn) (- end 1 beg))
10082 (apply #'js2-node-add-children pn args))
10083 (when (and js2-allow-rhino-new-expr-initializer
10084 (js2-match-token js2-LC))
10085 (setf init (js2-parse-object-literal)
10086 end (js2-node-end init)
10087 (js2-new-node-initializer pn) init)
10088 (js2-node-add-children pn init))
10089 (setf (js2-node-len pn) (- end beg))) ; end outer if
10090 (js2-parse-member-expr-tail allow-call-syntax pn)))
10091
10092 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10093 "Parse a chain of property/array accesses or function calls.
10094 Includes parsing for E4X operators like `..' and `.@'.
10095 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10096 Returns an expression tree that includes PN, the parent node."
10097 (let (tt
10098 (continue t))
10099 (while continue
10100 (setq tt (js2-get-token))
10101 (cond
10102 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10103 (setq pn (js2-parse-property-access tt pn)))
10104 ((= tt js2-DOTQUERY)
10105 (setq pn (js2-parse-dot-query pn)))
10106 ((= tt js2-LB)
10107 (setq pn (js2-parse-element-get pn)))
10108 ((= tt js2-LP)
10109 (js2-unget-token)
10110 (if allow-call-syntax
10111 (setq pn (js2-parse-function-call pn))
10112 (setq continue nil)))
10113 ((= tt js2-TEMPLATE_HEAD)
10114 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10115 ((= tt js2-NO_SUBS_TEMPLATE)
10116 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10117 (t
10118 (js2-unget-token)
10119 (setq continue nil)))
10120 (if (>= js2-highlight-level 2)
10121 (js2-parse-highlight-member-expr-node pn)))
10122 pn))
10123
10124 (defun js2-parse-tagged-template (tag-node tpl-node)
10125 "Parse tagged template expression."
10126 (let* ((beg (js2-node-pos tag-node))
10127 (pn (make-js2-tagged-template-node :beg beg
10128 :len (- (js2-current-token-end) beg)
10129 :tag tag-node
10130 :template tpl-node)))
10131 (js2-node-add-children pn tag-node tpl-node)
10132 pn))
10133
10134 (defun js2-parse-dot-query (pn)
10135 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10136 Last token parsed must be `js2-DOTQUERY'."
10137 (let ((pos (js2-node-pos pn))
10138 op-pos expr end)
10139 (js2-must-have-xml)
10140 (js2-set-requires-activation)
10141 (setq op-pos (js2-current-token-beg)
10142 expr (js2-parse-expr)
10143 end (js2-node-end expr)
10144 pn (make-js2-xml-dot-query-node :left pn
10145 :pos pos
10146 :op-pos op-pos
10147 :right expr))
10148 (js2-node-add-children pn
10149 (js2-xml-dot-query-node-left pn)
10150 (js2-xml-dot-query-node-right pn))
10151 (if (js2-must-match js2-RP "msg.no.paren")
10152 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10153 end (js2-current-token-end)))
10154 (setf (js2-node-len pn) (- end pos))
10155 pn))
10156
10157 (defun js2-parse-element-get (pn)
10158 "Parse an element-get expression, e.g. foo[bar].
10159 Last token parsed must be `js2-RB'."
10160 (let ((lb (js2-current-token-beg))
10161 (pos (js2-node-pos pn))
10162 rb expr)
10163 (setq expr (js2-parse-expr))
10164 (if (js2-must-match js2-RB "msg.no.bracket.index")
10165 (setq rb (js2-current-token-beg)))
10166 (setq pn (make-js2-elem-get-node :target pn
10167 :pos pos
10168 :element expr
10169 :lb (js2-relpos lb pos)
10170 :rb (js2-relpos rb pos)
10171 :len (- (js2-current-token-end) pos)))
10172 (js2-node-add-children pn
10173 (js2-elem-get-node-target pn)
10174 (js2-elem-get-node-element pn))
10175 pn))
10176
10177 (defun js2-highlight-function-call (token)
10178 (when (eq (js2-token-type token) js2-NAME)
10179 (js2-record-face 'js2-function-call token)))
10180
10181 (defun js2-parse-function-call (pn)
10182 (js2-highlight-function-call (js2-current-token))
10183 (js2-get-token)
10184 (let (args
10185 (pos (js2-node-pos pn)))
10186 (setq pn (make-js2-call-node :pos pos
10187 :target pn
10188 :lp (- (js2-current-token-beg) pos)))
10189 (js2-node-add-children pn (js2-call-node-target pn))
10190 ;; Add the arguments to pn, if any are supplied.
10191 (setf args (nreverse (js2-parse-argument-list))
10192 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10193 (js2-call-node-args pn) args)
10194 (apply #'js2-node-add-children pn args)
10195 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10196 pn))
10197
10198 (defun js2-parse-property-access (tt pn)
10199 "Parse a property access, XML descendants access, or XML attr access."
10200 (let ((member-type-flags 0)
10201 (dot-pos (js2-current-token-beg))
10202 (dot-len (if (= tt js2-DOTDOT) 2 1))
10203 name
10204 ref ; right side of . or .. operator
10205 result)
10206 (when (= tt js2-DOTDOT)
10207 (js2-must-have-xml)
10208 (setq member-type-flags js2-descendants-flag))
10209 (if (not js2-compiler-xml-available)
10210 (progn
10211 (js2-must-match-prop-name "msg.no.name.after.dot")
10212 (setq name (js2-create-name-node t js2-GETPROP)
10213 result (make-js2-prop-get-node :left pn
10214 :pos (js2-current-token-beg)
10215 :right name
10216 :len (js2-current-token-len)))
10217 (js2-node-add-children result pn name)
10218 result)
10219 ;; otherwise look for XML operators
10220 (setf result (if (= tt js2-DOT)
10221 (make-js2-prop-get-node)
10222 (make-js2-infix-node :type js2-DOTDOT))
10223 (js2-node-pos result) (js2-node-pos pn)
10224 (js2-infix-node-op-pos result) dot-pos
10225 (js2-infix-node-left result) pn ; do this after setting position
10226 tt (js2-get-prop-name-token))
10227 (cond
10228 ;; handles: name, ns::name, ns::*, ns::[expr]
10229 ((= tt js2-NAME)
10230 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10231 ;; handles: *, *::name, *::*, *::[expr]
10232 ((= tt js2-MUL)
10233 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10234 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10235 ((= tt js2-XMLATTR)
10236 (setq result (js2-parse-attribute-access)))
10237 (t
10238 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10239 (if ref
10240 (setf (js2-node-len result) (- (js2-node-end ref)
10241 (js2-node-pos result))
10242 (js2-infix-node-right result) ref))
10243 (if (js2-infix-node-p result)
10244 (js2-node-add-children result
10245 (js2-infix-node-left result)
10246 (js2-infix-node-right result)))
10247 result)))
10248
10249 (defun js2-parse-attribute-access ()
10250 "Parse an E4X XML attribute expression.
10251 This includes expressions of the forms:
10252
10253 @attr @ns::attr @ns::*
10254 @* @*::attr @*::*
10255 @[expr] @*::[expr] @ns::[expr]
10256
10257 Called if we peeked an '@' token."
10258 (let ((tt (js2-get-prop-name-token))
10259 (at-pos (js2-current-token-beg)))
10260 (cond
10261 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10262 ((= tt js2-NAME)
10263 (js2-parse-property-name at-pos nil 0))
10264 ;; handles: @*, @*::name, @*::*, @*::[expr]
10265 ((= tt js2-MUL)
10266 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10267 ;; handles @[expr]
10268 ((= tt js2-LB)
10269 (js2-parse-xml-elem-ref at-pos))
10270 (t
10271 (js2-report-error "msg.no.name.after.xmlAttr")
10272 ;; Avoid cascaded errors that happen if we make an error node here.
10273 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10274
10275 (defun js2-parse-property-name (at-pos s member-type-flags)
10276 "Check if :: follows name in which case it becomes qualified name.
10277
10278 AT-POS is a natural number if we just read an '@' token, else nil.
10279 S is the name or string that was matched: an identifier, 'throw' or '*'.
10280 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10281
10282 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10283 operator, or the name is followed by ::. For a plain name, returns a
10284 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10285 (let ((pos (or at-pos (js2-current-token-beg)))
10286 colon-pos
10287 (name (js2-create-name-node t (js2-current-token-type) s))
10288 ns tt pn)
10289 (catch 'return
10290 (when (js2-match-token js2-COLONCOLON)
10291 (setq ns name
10292 colon-pos (js2-current-token-beg)
10293 tt (js2-get-prop-name-token))
10294 (cond
10295 ;; handles name::name
10296 ((= tt js2-NAME)
10297 (setq name (js2-create-name-node)))
10298 ;; handles name::*
10299 ((= tt js2-MUL)
10300 (setq name (js2-create-name-node nil nil "*")))
10301 ;; handles name::[expr]
10302 ((= tt js2-LB)
10303 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10304 (t
10305 (js2-report-error "msg.no.name.after.coloncolon"))))
10306 (if (and (null ns) (zerop member-type-flags))
10307 name
10308 (prog1
10309 (setq pn
10310 (make-js2-xml-prop-ref-node :pos pos
10311 :len (- (js2-node-end name) pos)
10312 :at-pos at-pos
10313 :colon-pos colon-pos
10314 :propname name))
10315 (js2-node-add-children pn name))))))
10316
10317 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10318 "Parse the [expr] portion of an xml element reference.
10319 For instance, @[expr], @*::[expr], or ns::[expr]."
10320 (let* ((lb (js2-current-token-beg))
10321 (pos (or at-pos lb))
10322 rb
10323 (expr (js2-parse-expr))
10324 (end (js2-node-end expr))
10325 pn)
10326 (if (js2-must-match js2-RB "msg.no.bracket.index")
10327 (setq rb (js2-current-token-beg)
10328 end (js2-current-token-end)))
10329 (prog1
10330 (setq pn
10331 (make-js2-xml-elem-ref-node :pos pos
10332 :len (- end pos)
10333 :namespace namespace
10334 :colon-pos colon-pos
10335 :at-pos at-pos
10336 :expr expr
10337 :lb (js2-relpos lb pos)
10338 :rb (js2-relpos rb pos)))
10339 (js2-node-add-children pn namespace expr))))
10340
10341 (defun js2-parse-destruct-primary-expr ()
10342 (let ((js2-is-in-destructuring t))
10343 (js2-parse-primary-expr)))
10344
10345 (defun js2-parse-primary-expr ()
10346 "Parse a literal (leaf) expression of some sort.
10347 Includes complex literals such as functions, object-literals,
10348 array-literals, array comprehensions and regular expressions."
10349 (let (tt node)
10350 (setq tt (js2-current-token-type))
10351 (cond
10352 ((= tt js2-CLASS)
10353 (js2-parse-class-expr))
10354 ((= tt js2-FUNCTION)
10355 (js2-parse-function-expr))
10356 ((js2-match-async-function)
10357 (js2-parse-function-expr t))
10358 ((= tt js2-LB)
10359 (js2-parse-array-comp-or-literal))
10360 ((= tt js2-LC)
10361 (js2-parse-object-literal))
10362 ((= tt js2-LET)
10363 (js2-parse-let (js2-current-token-beg)))
10364 ((= tt js2-LP)
10365 (js2-parse-paren-expr-or-generator-comp))
10366 ((= tt js2-XMLATTR)
10367 (js2-must-have-xml)
10368 (js2-parse-attribute-access))
10369 ((= tt js2-NAME)
10370 (js2-parse-name tt))
10371 ((= tt js2-NUMBER)
10372 (setq node (make-js2-number-node))
10373 (when (and js2-in-use-strict-directive
10374 (= (js2-number-node-num-base node) 8)
10375 (js2-number-node-legacy-octal-p node))
10376 (js2-report-error "msg.no.octal.strict"))
10377 node)
10378 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10379 (make-js2-string-node :type tt))
10380 ((= tt js2-TEMPLATE_HEAD)
10381 (js2-parse-template-literal))
10382 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10383 ;; Got / or /= which in this context means a regexp literal
10384 (let ((px-pos (js2-current-token-beg))
10385 (flags (js2-read-regexp tt))
10386 (end (js2-current-token-end)))
10387 (prog1
10388 (make-js2-regexp-node :pos px-pos
10389 :len (- end px-pos)
10390 :value (js2-current-token-string)
10391 :flags flags)
10392 (js2-set-face px-pos end 'font-lock-string-face 'record)
10393 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10394 ((or (= tt js2-NULL)
10395 (= tt js2-THIS)
10396 (= tt js2-SUPER)
10397 (= tt js2-FALSE)
10398 (= tt js2-TRUE))
10399 (make-js2-keyword-node :type tt))
10400 ((= tt js2-TRIPLEDOT)
10401 ;; Likewise, only valid in an arrow function with a rest param.
10402 (if (and (js2-match-token js2-NAME)
10403 (js2-match-token js2-RP)
10404 (eq (js2-peek-token) js2-ARROW))
10405 (progn
10406 (js2-unget-token) ; Put back the right paren.
10407 ;; See the previous case.
10408 (make-js2-keyword-node :type js2-NULL))
10409 (js2-report-error "msg.syntax")
10410 (make-js2-error-node)))
10411 ((= tt js2-RESERVED)
10412 (js2-report-error "msg.reserved.id")
10413 (make-js2-name-node))
10414 ((= tt js2-ERROR)
10415 ;; the scanner or one of its subroutines reported the error.
10416 (make-js2-error-node))
10417 ((= tt js2-EOF)
10418 (let* ((px-pos (point-at-bol))
10419 (len (- js2-ts-cursor px-pos)))
10420 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10421 (make-js2-error-node :pos (1- js2-ts-cursor)))
10422 (t
10423 (js2-report-error "msg.syntax")
10424 (make-js2-error-node)))))
10425
10426 (defun js2-parse-template-literal ()
10427 (let ((beg (js2-current-token-beg))
10428 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10429 (tt js2-TEMPLATE_HEAD))
10430 (while (eq tt js2-TEMPLATE_HEAD)
10431 (push (js2-parse-expr) kids)
10432 (js2-must-match js2-RC "msg.syntax")
10433 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10434 (push (make-js2-string-node :type tt) kids))
10435 (setq kids (nreverse kids))
10436 (let ((tpl (make-js2-template-node :beg beg
10437 :len (- (js2-current-token-end) beg)
10438 :kids kids)))
10439 (apply #'js2-node-add-children tpl kids)
10440 tpl)))
10441
10442 (defun js2-parse-name (_tt)
10443 (let ((name (js2-current-token-string))
10444 node)
10445 (setq node (if js2-compiler-xml-available
10446 (js2-parse-property-name nil name 0)
10447 (js2-create-name-node 'check-activation nil name)))
10448 (if js2-highlight-external-variables
10449 (js2-record-name-node node))
10450 node))
10451
10452 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10453 (js2-add-strict-warning
10454 msg nil
10455 ;; back up from comma to beginning of line or array/objlit
10456 (max (if elems
10457 (js2-node-pos (car elems))
10458 pos)
10459 (save-excursion
10460 (goto-char comma-pos)
10461 (back-to-indentation)
10462 (point)))
10463 comma-pos))
10464
10465 (defun js2-parse-array-comp-or-literal ()
10466 (let ((pos (js2-current-token-beg)))
10467 (if (and (>= js2-language-version 200)
10468 (js2-match-token js2-FOR))
10469 (js2-parse-array-comp pos)
10470 (js2-parse-array-literal pos))))
10471
10472 (defun js2-parse-array-literal (pos)
10473 (let ((after-lb-or-comma t)
10474 after-comma tt elems pn
10475 (continue t))
10476 (unless js2-is-in-destructuring
10477 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10478 (while continue
10479 (setq tt (js2-get-token))
10480 (cond
10481 ;; comma
10482 ((= tt js2-COMMA)
10483 (setq after-comma (js2-current-token-end))
10484 (if (not after-lb-or-comma)
10485 (setq after-lb-or-comma t)
10486 (push nil elems)))
10487 ;; end of array
10488 ((or (= tt js2-RB)
10489 (= tt js2-EOF)) ; prevent infinite loop
10490 (if (= tt js2-EOF)
10491 (js2-report-error "msg.no.bracket.arg" nil pos))
10492 (when (and after-comma (< js2-language-version 170))
10493 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10494 pos (remove nil elems) after-comma))
10495 (setq continue nil
10496 pn (make-js2-array-node :pos pos
10497 :len (- js2-ts-cursor pos)
10498 :elems (nreverse elems)))
10499 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10500 ;; destructuring binding
10501 (js2-is-in-destructuring
10502 (push (cond
10503 ((and (= tt js2-NAME)
10504 (= js2-ASSIGN (js2-peek-token)))
10505 ;; a=defaultValue
10506 (js2-parse-initialized-binding (js2-parse-name js2-NAME)))
10507 ((or (= tt js2-LC)
10508 (= tt js2-LB)
10509 (= tt js2-NAME))
10510 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10511 (js2-parse-destruct-primary-expr))
10512 ;; invalid pattern
10513 (t
10514 (js2-report-error "msg.bad.var")
10515 (make-js2-error-node)))
10516 elems)
10517 (setq after-lb-or-comma nil
10518 after-comma nil))
10519 ;; array comp
10520 ((and (>= js2-language-version 170)
10521 (= tt js2-FOR) ; check for array comprehension
10522 (not after-lb-or-comma) ; "for" can't follow a comma
10523 elems ; must have at least 1 element
10524 (not (cdr elems))) ; but no 2nd element
10525 (js2-unget-token)
10526 (setf continue nil
10527 pn (js2-parse-legacy-array-comp (car elems) pos)))
10528 ;; another element
10529 (t
10530 (unless after-lb-or-comma
10531 (js2-report-error "msg.no.bracket.arg"))
10532 (if (and (= tt js2-TRIPLEDOT)
10533 (>= js2-language-version 200))
10534 ;; spread operator
10535 (push (js2-make-unary tt 'js2-parse-assign-expr)
10536 elems)
10537 (js2-unget-token)
10538 (push (js2-parse-assign-expr) elems))
10539 (setq after-lb-or-comma nil
10540 after-comma nil))))
10541 (unless js2-is-in-destructuring
10542 (js2-pop-scope))
10543 pn))
10544
10545 (defun js2-parse-legacy-array-comp (expr pos)
10546 "Parse a legacy array comprehension (JavaScript 1.7).
10547 EXPR is the first expression after the opening left-bracket.
10548 POS is the beginning of the LB token preceding EXPR.
10549 We should have just parsed the 'for' keyword before calling this function."
10550 (let ((current-scope js2-current-scope)
10551 loops first filter result)
10552 (unwind-protect
10553 (progn
10554 (while (js2-match-token js2-FOR)
10555 (let ((loop (make-js2-comp-loop-node)))
10556 (js2-push-scope loop)
10557 (push loop loops)
10558 (js2-parse-comp-loop loop)))
10559 ;; First loop takes expr scope's parent.
10560 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10561 (js2-scope-parent-scope current-scope))
10562 ;; Set expr scope's parent to the last loop.
10563 (setf (js2-scope-parent-scope current-scope) (car loops))
10564 (if (/= (js2-get-token) js2-IF)
10565 (js2-unget-token)
10566 (setq filter (js2-parse-condition))))
10567 (dotimes (_ (1- (length loops)))
10568 (js2-pop-scope)))
10569 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10570 (setq result (make-js2-comp-node :pos pos
10571 :len (- js2-ts-cursor pos)
10572 :result expr
10573 :loops (nreverse loops)
10574 :filters (and filter (list (car filter)))
10575 :form 'LEGACY_ARRAY))
10576 ;; Set comp loop's parent to the last loop.
10577 ;; TODO: Get rid of the bogus expr scope.
10578 (setf (js2-scope-parent-scope result) first)
10579 (apply #'js2-node-add-children result expr (car filter)
10580 (js2-comp-node-loops result))
10581 result))
10582
10583 (defun js2-parse-array-comp (pos)
10584 "Parse an ES6 array comprehension.
10585 POS is the beginning of the LB token.
10586 We should have just parsed the 'for' keyword before calling this function."
10587 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10588 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10589 pn))
10590
10591 (defun js2-parse-generator-comp (pos)
10592 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10593 (js2-current-script-or-fn
10594 (make-js2-function-node :generator-type 'COMPREHENSION))
10595 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10596 (js2-must-match js2-RP "msg.no.paren" pos)
10597 pn))
10598
10599 (defun js2-parse-comprehension (pos form)
10600 (let (loops filters expr result last)
10601 (unwind-protect
10602 (progn
10603 (js2-unget-token)
10604 (while (js2-match-token js2-FOR)
10605 (let ((loop (make-js2-comp-loop-node)))
10606 (js2-push-scope loop)
10607 (push loop loops)
10608 (js2-parse-comp-loop loop)))
10609 (while (js2-match-token js2-IF)
10610 (push (car (js2-parse-condition)) filters))
10611 (setq expr (js2-parse-assign-expr))
10612 (setq last (car loops)))
10613 (dolist (_ loops)
10614 (js2-pop-scope)))
10615 (setq result (make-js2-comp-node :pos pos
10616 :len (- js2-ts-cursor pos)
10617 :result expr
10618 :loops (nreverse loops)
10619 :filters (nreverse filters)
10620 :form form))
10621 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10622 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10623 (setf (js2-scope-parent-scope result) last)
10624 result))
10625
10626 (defun js2-parse-comp-loop (pn &optional only-of-p)
10627 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10628 The current token should be the initial FOR.
10629 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10630 (let ((pos (js2-comp-loop-node-pos pn))
10631 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10632 (when (and (not only-of-p) (js2-match-token js2-NAME))
10633 (if (string= (js2-current-token-string) "each")
10634 (progn
10635 (setq foreach-p t
10636 each-pos (- (js2-current-token-beg) pos)) ; relative
10637 (js2-record-face 'font-lock-keyword-face))
10638 (js2-report-error "msg.no.paren.for")))
10639 (if (js2-must-match js2-LP "msg.no.paren.for")
10640 (setq lp (- (js2-current-token-beg) pos)))
10641 (setq tt (js2-peek-token))
10642 (cond
10643 ((or (= tt js2-LB)
10644 (= tt js2-LC))
10645 (js2-get-token)
10646 (setq iter (js2-parse-destruct-primary-expr))
10647 (js2-define-destruct-symbols iter js2-LET
10648 'font-lock-variable-name-face t))
10649 ((js2-match-token js2-NAME)
10650 (setq iter (js2-create-name-node)))
10651 (t
10652 (js2-report-error "msg.bad.var")))
10653 ;; Define as a let since we want the scope of the variable to
10654 ;; be restricted to the array comprehension
10655 (if (js2-name-node-p iter)
10656 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10657 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10658 (and (>= js2-language-version 200)
10659 (js2-match-contextual-kwd "of")
10660 (setq forof-p t)))
10661 (setq in-pos (- (js2-current-token-beg) pos))
10662 (js2-report-error "msg.in.after.for.name"))
10663 (setq obj (js2-parse-expr))
10664 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10665 (setq rp (- (js2-current-token-beg) pos)))
10666 (setf (js2-node-pos pn) pos
10667 (js2-node-len pn) (- js2-ts-cursor pos)
10668 (js2-comp-loop-node-iterator pn) iter
10669 (js2-comp-loop-node-object pn) obj
10670 (js2-comp-loop-node-in-pos pn) in-pos
10671 (js2-comp-loop-node-each-pos pn) each-pos
10672 (js2-comp-loop-node-foreach-p pn) foreach-p
10673 (js2-comp-loop-node-forof-p pn) forof-p
10674 (js2-comp-loop-node-lp pn) lp
10675 (js2-comp-loop-node-rp pn) rp)
10676 (js2-node-add-children pn iter obj)
10677 pn))
10678
10679 (defun js2-parse-class-stmt ()
10680 (let ((pos (js2-current-token-beg))
10681 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10682 (name (js2-create-name-node t)))
10683 (js2-set-face (js2-node-pos name) (js2-node-end name)
10684 'font-lock-function-name-face 'record)
10685 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10686 (js2-record-imenu-functions node name)
10687 (js2-define-symbol js2-FUNCTION
10688 (js2-name-node-name name)
10689 node)
10690 node)))
10691
10692 (defun js2-parse-class-expr ()
10693 (let ((pos (js2-current-token-beg))
10694 name)
10695 (when (js2-match-token js2-NAME)
10696 (setq name (js2-create-name-node t)))
10697 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10698
10699 (defun js2-parse-class (pos form name)
10700 ;; class X [extends ...] {
10701 (let (pn elems extends)
10702 (if (js2-match-token js2-EXTENDS)
10703 (if (= (js2-peek-token) js2-LC)
10704 (js2-report-error "msg.missing.extends")
10705 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10706 (setq extends (js2-parse-assign-expr))
10707 (if (not extends)
10708 (js2-report-error "msg.bad.extends"))))
10709 (js2-must-match js2-LC "msg.no.brace.class")
10710 (setq elems (js2-parse-object-literal-elems t)
10711 pn (make-js2-class-node :pos pos
10712 :len (- js2-ts-cursor pos)
10713 :form form
10714 :name name
10715 :extends extends
10716 :elems elems))
10717 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10718 pn))
10719
10720 (defun js2-parse-object-literal ()
10721 (let* ((pos (js2-current-token-beg))
10722 (elems (js2-parse-object-literal-elems))
10723 (result (make-js2-object-node :pos pos
10724 :len (- js2-ts-cursor pos)
10725 :elems elems)))
10726 (apply #'js2-node-add-children result (js2-object-node-elems result))
10727 result))
10728
10729 (defun js2-property-key-string (property-node)
10730 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10731 `js2-method-node') as a string, or nil if it can't be
10732 represented as a string (e.g., the key is computed by an
10733 expression)."
10734 (let ((key (js2-infix-node-left property-node)))
10735 (when (js2-computed-prop-name-node-p key)
10736 (setq key (js2-computed-prop-name-node-expr key)))
10737 (cond
10738 ((js2-name-node-p key)
10739 (js2-name-node-name key))
10740 ((js2-string-node-p key)
10741 (js2-string-node-value key))
10742 ((js2-number-node-p key)
10743 (js2-number-node-value key)))))
10744
10745 (defun js2-parse-object-literal-elems (&optional class-p)
10746 (let ((pos (js2-current-token-beg))
10747 (static nil)
10748 (continue t)
10749 tt elems elem
10750 elem-key-string previous-elem-key-string
10751 after-comma previous-token)
10752 (while continue
10753 (setq tt (js2-get-prop-name-token)
10754 static nil
10755 elem nil
10756 previous-token nil)
10757 ;; Handle 'static' keyword only if we're in a class
10758 (when (and class-p (= js2-NAME tt)
10759 (string= "static" (js2-current-token-string)))
10760 (js2-record-face 'font-lock-keyword-face)
10761 (setq static t
10762 tt (js2-get-prop-name-token)))
10763 ;; Handle generator * before the property name for in-line functions
10764 (when (and (>= js2-language-version 200)
10765 (= js2-MUL tt))
10766 (setq previous-token (js2-current-token)
10767 tt (js2-get-prop-name-token)))
10768 ;; Handle getter, setter and async methods
10769 (let ((prop (js2-current-token-string)))
10770 (when (and (>= js2-language-version 200)
10771 (= js2-NAME tt)
10772 (member prop '("get" "set" "async"))
10773 (member (js2-peek-token)
10774 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10775 (setq previous-token (js2-current-token)
10776 tt (js2-get-prop-name-token))))
10777 (cond
10778 ;; Found a property (of any sort)
10779 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10780 (setq after-comma nil
10781 elem (js2-parse-named-prop tt previous-token))
10782 (if (and (null elem)
10783 (not js2-recover-from-parse-errors))
10784 (setq continue nil)))
10785 ;; Break out of loop, and handle trailing commas.
10786 ((or (= tt js2-RC)
10787 (= tt js2-EOF))
10788 (js2-unget-token)
10789 (setq continue nil)
10790 (if after-comma
10791 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10792 pos elems after-comma)))
10793 ;; Skip semicolons in a class body
10794 ((and class-p
10795 (= tt js2-SEMI))
10796 nil)
10797 (t
10798 (js2-report-error "msg.bad.prop")
10799 (unless js2-recover-from-parse-errors
10800 (setq continue nil)))) ; end switch
10801 ;; Handle static for classes' codegen.
10802 (if static
10803 (if elem (js2-node-set-prop elem 'STATIC t)
10804 (js2-report-error "msg.unexpected.static")))
10805 ;; Handle commas, depending on class-p.
10806 (let ((tok (js2-get-prop-name-token)))
10807 (if (eq tok js2-COMMA)
10808 (if class-p
10809 (js2-report-error "msg.class.unexpected.comma")
10810 (setq after-comma (js2-current-token-end)))
10811 (js2-unget-token)
10812 (unless class-p (setq continue nil))))
10813 (when elem
10814 (when (and js2-in-use-strict-directive
10815 (setq elem-key-string (js2-property-key-string elem))
10816 (cl-some
10817 (lambda (previous-elem)
10818 (and (setq previous-elem-key-string
10819 (js2-property-key-string previous-elem))
10820 ;; Check if the property is a duplicate.
10821 (string= previous-elem-key-string elem-key-string)
10822 ;; But make an exception for getter / setter pairs.
10823 (not (and (js2-method-node-p elem)
10824 (js2-method-node-p previous-elem)
10825 (let ((type (js2-node-get-prop (js2-method-node-right elem) 'METHOD_TYPE))
10826 (previous-type (js2-node-get-prop (js2-method-node-right previous-elem) 'METHOD_TYPE)))
10827 (and (member type '(GET SET))
10828 (member previous-type '(GET SET))
10829 (not (eq type previous-type))))))))
10830 elems))
10831 (js2-report-error "msg.dup.obj.lit.prop.strict"
10832 elem-key-string
10833 (js2-node-abs-pos (js2-infix-node-left elem))
10834 (js2-node-len (js2-infix-node-left elem))))
10835 ;; Append any parsed element.
10836 (push elem elems))) ; end loop
10837 (js2-must-match js2-RC "msg.no.brace.prop")
10838 (nreverse elems)))
10839
10840 (defun js2-parse-named-prop (tt previous-token)
10841 "Parse a name, string, or getter/setter object property.
10842 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10843 (let ((key (js2-parse-prop-name tt))
10844 (prop (and previous-token (js2-token-string previous-token)))
10845 (property-type (when previous-token
10846 (if (= (js2-token-type previous-token) js2-MUL)
10847 "*"
10848 (js2-token-string previous-token))))
10849 pos)
10850 (when (member prop '("get" "set" "async"))
10851 (setq pos (js2-token-beg previous-token))
10852 (js2-set-face (js2-token-beg previous-token)
10853 (js2-token-end previous-token)
10854 'font-lock-keyword-face 'record)) ; get/set/async
10855 (cond
10856 ;; method definition: {f() {...}}
10857 ((and (= (js2-peek-token) js2-LP)
10858 (>= js2-language-version 200))
10859 (when (js2-name-node-p key) ; highlight function name properties
10860 (js2-record-face 'font-lock-function-name-face))
10861 (js2-parse-method-prop pos key property-type))
10862 ;; binding element with initializer
10863 ((and (= (js2-peek-token) js2-ASSIGN)
10864 (>= js2-language-version 200))
10865 (if (not js2-is-in-destructuring)
10866 (js2-report-error "msg.init.no.destruct"))
10867 (js2-parse-initialized-binding key))
10868 ;; regular prop
10869 (t
10870 (let ((beg (js2-current-token-beg))
10871 (end (js2-current-token-end))
10872 (expr (js2-parse-plain-property key)))
10873 (when (and (= tt js2-NAME)
10874 (not js2-is-in-destructuring)
10875 js2-highlight-external-variables
10876 (js2-node-get-prop expr 'SHORTHAND))
10877 (js2-record-name-node key))
10878 (js2-set-face beg end
10879 (if (js2-function-node-p
10880 (js2-object-prop-node-right expr))
10881 'font-lock-function-name-face
10882 'js2-object-property)
10883 'record)
10884 expr)))))
10885
10886 (defun js2-parse-initialized-binding (name)
10887 "Parse a `SingleNameBinding' with initializer.
10888
10889 `name' is the `BindingIdentifier'."
10890 (when (js2-match-token js2-ASSIGN)
10891 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10892
10893 (defun js2-parse-prop-name (tt)
10894 (cond
10895 ;; Literal string keys: {'foo': 'bar'}
10896 ((= tt js2-STRING)
10897 (make-js2-string-node))
10898 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10899 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10900 ((and (= tt js2-LB)
10901 (>= js2-language-version 200))
10902 (make-js2-computed-prop-name-node
10903 :expr (prog1 (js2-parse-assign-expr)
10904 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10905 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10906 ((= tt js2-NUMBER)
10907 (make-js2-number-node))
10908 ;; Unquoted names: {foo: 12}
10909 ((= tt js2-NAME)
10910 (js2-create-name-node))
10911 ;; Anything else is an error
10912 (t (js2-report-error "msg.bad.prop"))))
10913
10914 (defun js2-parse-plain-property (prop)
10915 "Parse a non-getter/setter property in an object literal.
10916 PROP is the node representing the property: a number, name,
10917 string or expression."
10918 (let* ((tt (js2-get-token))
10919 (pos (js2-node-pos prop))
10920 colon expr result)
10921 (cond
10922 ;; Abbreviated property, as in {foo, bar}
10923 ((and (>= js2-language-version 200)
10924 (or (= tt js2-COMMA)
10925 (= tt js2-RC))
10926 (not (js2-number-node-p prop)))
10927 (js2-unget-token)
10928 (setq result (make-js2-object-prop-node
10929 :pos pos
10930 :left prop
10931 :right prop
10932 :op-pos (js2-current-token-len)))
10933 (js2-node-add-children result prop)
10934 (js2-node-set-prop result 'SHORTHAND t)
10935 result)
10936 ;; Normal property
10937 (t
10938 (if (= tt js2-COLON)
10939 (setq colon (- (js2-current-token-beg) pos)
10940 expr (js2-parse-assign-expr))
10941 (js2-report-error "msg.no.colon.prop")
10942 (setq expr (make-js2-error-node)))
10943 (setq result (make-js2-object-prop-node
10944 :pos pos
10945 ;; don't include last consumed token in length
10946 :len (- (+ (js2-node-pos expr)
10947 (js2-node-len expr))
10948 pos)
10949 :left prop
10950 :right expr
10951 :op-pos colon))
10952 (js2-node-add-children result prop expr)
10953 result))))
10954
10955 (defun js2-parse-method-prop (pos prop type-string)
10956 "Parse method property in an object literal or a class body.
10957 JavaScript syntax is:
10958
10959 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...},
10960 async foo(...) {...} }
10961
10962 and expression closure style is also supported
10963
10964 { get foo() x, set foo(x) _x = x }
10965
10966 POS is the start position of the `get' or `set' keyword.
10967 PROP is the `js2-name-node' representing the property name.
10968 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10969 (let* ((type (or (cdr (assoc type-string '(("get" . GET)
10970 ("set" . SET)
10971 ("async" . ASYNC))))
10972 'FUNCTION))
10973 result end
10974 (fn (js2-parse-function-expr (eq type 'ASYNC))))
10975 ;; it has to be an anonymous function, as we already parsed the name
10976 (if (/= (js2-node-type fn) js2-FUNCTION)
10977 (js2-report-error "msg.bad.prop")
10978 (if (cl-plusp (length (js2-function-name fn)))
10979 (js2-report-error "msg.bad.prop")))
10980 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10981 (when (string= type-string "*")
10982 (setf (js2-function-node-generator-type fn) 'STAR))
10983 (unless pos (setq pos (js2-node-pos prop)))
10984 (setq end (js2-node-end fn)
10985 result (make-js2-method-node :pos pos
10986 :len (- end pos)
10987 :left prop
10988 :right fn))
10989 (js2-node-add-children result prop fn)
10990 result))
10991
10992 (defun js2-create-name-node (&optional check-activation-p token string)
10993 "Create a name node using the current token and, optionally, STRING.
10994 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10995 (let* ((beg (js2-current-token-beg))
10996 (tt (js2-current-token-type))
10997 (s (or string
10998 (if (= js2-NAME tt)
10999 (js2-current-token-string)
11000 (js2-tt-name tt))))
11001 name)
11002 (setq name (make-js2-name-node :pos beg
11003 :name s
11004 :len (length s)))
11005 (if check-activation-p
11006 (js2-check-activation-name s (or token js2-NAME)))
11007 name))
11008
11009 ;;; Use AST to extract semantic information
11010
11011 (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
11012 "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
11013 (let ((idx 0) elems (rlt hardcoded-array-index))
11014 (setq elems (js2-array-node-elems array-node))
11015 (if (and elem (not hardcoded-array-index))
11016 (setq rlt (catch 'nth-elt
11017 (dolist (x elems)
11018 ;; We know the ELEM does belong to ARRAY-NODE,
11019 (if (eq elem x) (throw 'nth-elt idx))
11020 (setq idx (1+ idx)))
11021 0)))
11022 (format "[%s]" rlt)))
11023
11024 (defun js2-print-json-path (&optional hardcoded-array-index)
11025 "Print the path to the JSON value under point, and save it in the kill ring.
11026 If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
11027 (interactive "P")
11028 (let (previous-node current-node
11029 key-name
11030 rlt)
11031
11032 ;; The `js2-node-at-point' starts scanning from AST root node.
11033 ;; So there is no way to optimize it.
11034 (setq current-node (js2-node-at-point))
11035
11036 (while (not (js2-ast-root-p current-node))
11037 (cond
11038 ;; JSON property node
11039 ((js2-object-prop-node-p current-node)
11040 (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
11041 (if rlt (setq rlt (concat "." key-name rlt))
11042 (setq rlt (concat "." key-name))))
11043
11044 ;; Array node
11045 ((or (js2-array-node-p current-node))
11046 (setq rlt (concat (js2-get-element-index-from-array-node previous-node
11047 current-node
11048 hardcoded-array-index)
11049 rlt)))
11050
11051 ;; Other nodes are ignored
11052 (t))
11053
11054 ;; current node is archived
11055 (setq previous-node current-node)
11056 ;; Get parent node and continue the loop
11057 (setq current-node (js2-node-parent current-node)))
11058
11059 (cond
11060 (rlt
11061 ;; Clean the final result
11062 (setq rlt (replace-regexp-in-string "^\\." "" rlt))
11063 (kill-new rlt)
11064 (message "%s => kill-ring" rlt))
11065 (t
11066 (message "No JSON path found!")))
11067
11068 rlt))
11069
11070 ;;; Indentation support (bouncing)
11071
11072 ;; In recent-enough Emacs, we reuse the indentation code from
11073 ;; `js-mode'. To continue support for the older versions, some code
11074 ;; that was here previously was moved to `js2-old-indent.el'.
11075
11076 ;; Whichever indenter is used, it's often "wrong", however, and needs
11077 ;; to be overridden. The right long-term solution is probably to
11078 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
11079 ;; of coding. Even when a parse tree from `js2-parse' is present,
11080 ;; which is not true at the moment the user is typing, computing
11081 ;; indentation is still thousands of lines of code to handle every
11082 ;; possible syntactic edge case.
11083
11084 ;; In the meantime, the compromise solution is that we offer a "bounce
11085 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
11086 ;; current line indent among various likely guess points. This approach
11087 ;; is far from perfect, but should at least make it slightly easier to
11088 ;; move the line towards its desired indentation when manually
11089 ;; overriding Karl's heuristic nesting guesser.
11090
11091 (defun js2-backward-sws ()
11092 "Move backward through whitespace and comments."
11093 (interactive)
11094 (while (forward-comment -1)))
11095
11096 (defun js2-forward-sws ()
11097 "Move forward through whitespace and comments."
11098 (interactive)
11099 (while (forward-comment 1)))
11100
11101 (defun js2-arglist-close ()
11102 "Return non-nil if we're on a line beginning with a close-paren/brace."
11103 (save-excursion
11104 (goto-char (point-at-bol))
11105 (js2-forward-sws)
11106 (looking-at "[])}]")))
11107
11108 (defun js2-indent-looks-like-label-p ()
11109 (goto-char (point-at-bol))
11110 (js2-forward-sws)
11111 (looking-at (concat js2-mode-identifier-re ":")))
11112
11113 (defun js2-indent-in-objlit-p (parse-status)
11114 "Return non-nil if this looks like an object-literal entry."
11115 (let ((start (nth 1 parse-status)))
11116 (and
11117 start
11118 (save-excursion
11119 (and (zerop (forward-line -1))
11120 (not (< (point) start)) ; crossed a {} boundary
11121 (js2-indent-looks-like-label-p)))
11122 (save-excursion
11123 (js2-indent-looks-like-label-p)))))
11124
11125 ;; If prev line looks like foobar({ then we're passing an object
11126 ;; literal to a function call, and people pretty much always want to
11127 ;; de-dent back to the previous line, so move the 'basic-offset'
11128 ;; position to the front.
11129 (defun js2-indent-objlit-arg-p (parse-status)
11130 (save-excursion
11131 (back-to-indentation)
11132 (js2-backward-sws)
11133 (and (eq (1- (point)) (nth 1 parse-status))
11134 (eq (char-before) ?{)
11135 (progn
11136 (forward-char -1)
11137 (skip-chars-backward " \t")
11138 (eq (char-before) ?\()))))
11139
11140 (defun js2-indent-case-block-p ()
11141 (save-excursion
11142 (back-to-indentation)
11143 (js2-backward-sws)
11144 (goto-char (point-at-bol))
11145 (skip-chars-forward " \t")
11146 (looking-at "case\\s-.+:")))
11147
11148 (defun js2-bounce-indent (normal-col parse-status &optional backward)
11149 "Cycle among alternate computed indentation positions.
11150 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11151 of the buffer to the current point. NORMAL-COL is the indentation
11152 column computed by the heuristic guesser based on current paren,
11153 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11154 in reverse."
11155 (let ((cur-indent (current-indentation))
11156 (old-buffer-undo-list buffer-undo-list)
11157 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11158 (current-line (save-excursion
11159 (forward-line 0) ; move to bol
11160 (1+ (count-lines (point-min) (point)))))
11161 positions pos main-pos anchor arglist-cont same-indent
11162 basic-offset computed-pos)
11163 ;; temporarily don't record undo info, if user requested this
11164 (when js2-mode-indent-inhibit-undo
11165 (setq buffer-undo-list t))
11166 (unwind-protect
11167 (progn
11168 ;; First likely point: indent from beginning of previous code line
11169 (push (setq basic-offset
11170 (+ (save-excursion
11171 (back-to-indentation)
11172 (js2-backward-sws)
11173 (back-to-indentation)
11174 (current-column))
11175 js2-basic-offset))
11176 positions)
11177
11178 ;; (First + epsilon) likely point: indent 2x from beginning of
11179 ;; previous code line. Google does it this way.
11180 (push (setq basic-offset
11181 (+ (save-excursion
11182 (back-to-indentation)
11183 (js2-backward-sws)
11184 (back-to-indentation)
11185 (current-column))
11186 (* 2 js2-basic-offset)))
11187 positions)
11188
11189 ;; Second likely point: indent from assign-expr RHS. This
11190 ;; is just a crude guess based on finding " = " on the previous
11191 ;; line containing actual code.
11192 (setq pos (save-excursion
11193 (forward-line -1)
11194 (goto-char (point-at-bol))
11195 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11196 (point-at-eol) t)
11197 (goto-char (match-end 1))
11198 (skip-chars-forward " \t\r\n")
11199 (current-column))))
11200 (when pos
11201 (cl-incf pos js2-basic-offset)
11202 (push pos positions))
11203
11204 ;; Third likely point: same indent as previous line of code.
11205 ;; Make it the first likely point if we're not on an
11206 ;; arglist-close line and previous line ends in a comma, or
11207 ;; both this line and prev line look like object-literal
11208 ;; elements.
11209 (setq pos (save-excursion
11210 (goto-char (point-at-bol))
11211 (js2-backward-sws)
11212 (back-to-indentation)
11213 (prog1
11214 (current-column)
11215 ;; while we're here, look for trailing comma
11216 (if (save-excursion
11217 (goto-char (point-at-eol))
11218 (js2-backward-sws)
11219 (eq (char-before) ?,))
11220 (setq arglist-cont (1- (point)))))))
11221 (when pos
11222 (if (and (or arglist-cont
11223 (js2-indent-in-objlit-p parse-status))
11224 (not (js2-arglist-close)))
11225 (setq same-indent pos))
11226 (push pos positions))
11227
11228 ;; Fourth likely point: first preceding code with less indentation.
11229 ;; than the immediately preceding code line.
11230 (setq pos (save-excursion
11231 (back-to-indentation)
11232 (js2-backward-sws)
11233 (back-to-indentation)
11234 (setq anchor (current-column))
11235 (while (and (zerop (forward-line -1))
11236 (>= (progn
11237 (back-to-indentation)
11238 (current-column))
11239 anchor)))
11240 (setq pos (current-column))))
11241 (push pos positions)
11242
11243 ;; nesting-heuristic position, main by default
11244 (push (setq main-pos normal-col) positions)
11245
11246 ;; delete duplicates and sort positions list
11247 (setq positions (sort (delete-dups positions) '<))
11248
11249 ;; comma-list continuation lines: prev line indent takes precedence
11250 (if same-indent
11251 (setq main-pos same-indent))
11252
11253 ;; common special cases where we want to indent in from previous line
11254 (if (or (js2-indent-case-block-p)
11255 (js2-indent-objlit-arg-p parse-status))
11256 (setq main-pos basic-offset))
11257
11258 ;; if bouncing backward, reverse positions list
11259 (if backward
11260 (setq positions (reverse positions)))
11261
11262 ;; record whether we're already sitting on one of the alternatives
11263 (setq pos (member cur-indent positions))
11264
11265 (cond
11266 ;; case 0: we're one one of the alternatives and this is the
11267 ;; first time they've pressed TAB on this line (best-guess).
11268 ((and js2-mode-indent-ignore-first-tab
11269 pos
11270 ;; first time pressing TAB on this line?
11271 (not (eq js2-mode-last-indented-line current-line)))
11272 ;; do nothing
11273 (setq computed-pos nil))
11274 ;; case 1: only one computed position => use it
11275 ((null (cdr positions))
11276 (setq computed-pos 0))
11277 ;; case 2: not on any of the computed spots => use main spot
11278 ((not pos)
11279 (setq computed-pos (js2-position main-pos positions)))
11280 ;; case 3: on last position: cycle to first position
11281 ((null (cdr pos))
11282 (setq computed-pos 0))
11283 ;; case 4: on intermediate position: cycle to next position
11284 (t
11285 (setq computed-pos (js2-position (cl-second pos) positions))))
11286
11287 ;; see if any hooks want to indent; otherwise we do it
11288 (cl-loop with result = nil
11289 for hook in js2-indent-hook
11290 while (null result)
11291 do
11292 (setq result (funcall hook positions computed-pos))
11293 finally do
11294 (unless (or result (null computed-pos))
11295 (indent-line-to (nth computed-pos positions)))))
11296
11297 ;; finally
11298 (if js2-mode-indent-inhibit-undo
11299 (setq buffer-undo-list old-buffer-undo-list))
11300 ;; see commentary for `js2-mode-last-indented-line'
11301 (setq js2-mode-last-indented-line current-line))))
11302
11303 (defun js2-1-line-comment-continuation-p ()
11304 "Return t if we're in a 1-line comment continuation.
11305 If so, we don't ever want to use bounce-indent."
11306 (save-excursion
11307 (and (progn
11308 (forward-line 0)
11309 (looking-at "\\s-*//"))
11310 (progn
11311 (forward-line -1)
11312 (forward-line 0)
11313 (when (looking-at "\\s-*$")
11314 (js2-backward-sws)
11315 (forward-line 0))
11316 (looking-at "\\s-*//")))))
11317
11318 (defun js2-indent-bounce (&optional backward)
11319 "Indent the current line, bouncing between several positions."
11320 (interactive)
11321 (let (parse-status offset indent-col
11322 ;; Don't whine about errors/warnings when we're indenting.
11323 ;; This has to be set before calling parse-partial-sexp below.
11324 (inhibit-point-motion-hooks t))
11325 (setq parse-status (save-excursion
11326 (syntax-ppss (point-at-bol)))
11327 offset (- (point) (save-excursion
11328 (back-to-indentation)
11329 (point))))
11330 ;; Don't touch multiline strings.
11331 (unless (nth 3 parse-status)
11332 (setq indent-col (js2-proper-indentation parse-status))
11333 (cond
11334 ;; It doesn't work well on first line of buffer.
11335 ((and (not (nth 4 parse-status))
11336 (not (js2-same-line (point-min)))
11337 (not (js2-1-line-comment-continuation-p)))
11338 (js2-bounce-indent indent-col parse-status backward))
11339 ;; just indent to the guesser's likely spot
11340 (t (indent-line-to indent-col)))
11341 (when (cl-plusp offset)
11342 (forward-char offset)))))
11343
11344 (defun js2-indent-bounce-backward ()
11345 "Indent the current line, bouncing between positions in reverse."
11346 (interactive)
11347 (js2-indent-bounce t))
11348
11349 (defun js2-indent-region (start end)
11350 "Indent the region, but don't use bounce indenting."
11351 (let ((js2-bounce-indent-p nil)
11352 (indent-region-function nil)
11353 (after-change-functions (remq 'js2-mode-edit
11354 after-change-functions)))
11355 (indent-region start end nil) ; nil for byte-compiler
11356 (js2-mode-edit start end (- end start))))
11357
11358 (defvar js2-minor-mode-map
11359 (let ((map (make-sparse-keymap)))
11360 (define-key map (kbd "C-c C-`") #'js2-next-error)
11361 (define-key map [mouse-1] #'js2-mode-show-node)
11362 map)
11363 "Keymap used when `js2-minor-mode' is active.")
11364
11365 ;;;###autoload
11366 (define-minor-mode js2-minor-mode
11367 "Minor mode for running js2 as a background linter.
11368 This allows you to use a different major mode for JavaScript editing,
11369 such as `js-mode', while retaining the asynchronous error/warning
11370 highlighting features of `js2-mode'."
11371 :group 'js2-mode
11372 :lighter " js-lint"
11373 (if (derived-mode-p 'js2-mode)
11374 (setq js2-minor-mode nil)
11375 (if js2-minor-mode
11376 (js2-minor-mode-enter)
11377 (js2-minor-mode-exit))))
11378
11379 (defun js2-minor-mode-enter ()
11380 "Initialization for `js2-minor-mode'."
11381 (set (make-local-variable 'max-lisp-eval-depth)
11382 (max max-lisp-eval-depth 3000))
11383 (setq next-error-function #'js2-next-error)
11384 (js2-set-default-externs)
11385 ;; Experiment: make reparse-delay longer for longer files.
11386 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11387 (setq js2-idle-timer-delay
11388 (* js2-idle-timer-delay
11389 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11390 (setq js2-mode-buffer-dirty-p t
11391 js2-mode-parsing nil)
11392 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11393 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11394 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11395 (when js2-include-jslint-globals
11396 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11397 (run-hooks 'js2-init-hook)
11398 (js2-reparse))
11399
11400 (defun js2-minor-mode-exit ()
11401 "Turn off `js2-minor-mode'."
11402 (setq next-error-function nil)
11403 (remove-hook 'after-change-functions #'js2-mode-edit t)
11404 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11405 (when js2-mode-node-overlay
11406 (delete-overlay js2-mode-node-overlay)
11407 (setq js2-mode-node-overlay nil))
11408 (js2-remove-overlays)
11409 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11410 (setq js2-mode-ast nil))
11411
11412 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11413 (make-variable-buffer-local 'js2-source-buffer)
11414
11415 (cl-defun js2-display-error-list ()
11416 "Display a navigable buffer listing parse errors/warnings."
11417 (interactive)
11418 (unless (js2-have-errors-p)
11419 (message "No errors")
11420 (cl-return-from js2-display-error-list))
11421 (cl-labels ((annotate-list
11422 (lst type)
11423 "Add diagnostic TYPE and line number to errs list"
11424 (mapcar (lambda (err)
11425 (list err type (line-number-at-pos (nth 1 err))))
11426 lst)))
11427 (let* ((srcbuf (current-buffer))
11428 (errbuf (get-buffer-create "*js-lint*"))
11429 (errors (annotate-list
11430 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11431 'js2-error)) ; must be a valid face name
11432 (warnings (annotate-list
11433 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11434 'js2-warning)) ; must be a valid face name
11435 (all-errs (sort (append errors warnings)
11436 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11437 (with-current-buffer errbuf
11438 (let ((inhibit-read-only t))
11439 (erase-buffer)
11440 (dolist (err all-errs)
11441 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11442 (insert-text-button
11443 (format "line %d: %s" line (js2-get-msg msg-key))
11444 'face type
11445 'follow-link "\C-m"
11446 'action 'js2-error-buffer-jump
11447 'js2-msg (js2-get-msg msg-key)
11448 'js2-pos beg)
11449 (insert "\n"))))
11450 (js2-error-buffer-mode)
11451 (setq js2-source-buffer srcbuf)
11452 (pop-to-buffer errbuf)
11453 (goto-char (point-min))
11454 (unless (eobp)
11455 (js2-error-buffer-view))))))
11456
11457 (defvar js2-error-buffer-mode-map
11458 (let ((map (make-sparse-keymap)))
11459 (define-key map "n" #'js2-error-buffer-next)
11460 (define-key map "p" #'js2-error-buffer-prev)
11461 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11462 (define-key map "o" #'js2-error-buffer-view)
11463 (define-key map "q" #'js2-error-buffer-quit)
11464 map)
11465 "Keymap used for js2 diagnostics buffers.")
11466
11467 (defun js2-error-buffer-mode ()
11468 "Major mode for js2 diagnostics buffers.
11469 Selecting an error will jump it to the corresponding source-buffer error.
11470 \\{js2-error-buffer-mode-map}"
11471 (interactive)
11472 (setq major-mode 'js2-error-buffer-mode
11473 mode-name "JS Lint Diagnostics")
11474 (use-local-map js2-error-buffer-mode-map)
11475 (setq truncate-lines t)
11476 (set-buffer-modified-p nil)
11477 (setq buffer-read-only t)
11478 (run-hooks 'js2-error-buffer-mode-hook))
11479
11480 (defun js2-error-buffer-next ()
11481 "Move to next error and view it."
11482 (interactive)
11483 (when (zerop (forward-line 1))
11484 (js2-error-buffer-view)))
11485
11486 (defun js2-error-buffer-prev ()
11487 "Move to previous error and view it."
11488 (interactive)
11489 (when (zerop (forward-line -1))
11490 (js2-error-buffer-view)))
11491
11492 (defun js2-error-buffer-quit ()
11493 "Kill the current buffer."
11494 (interactive)
11495 (kill-buffer))
11496
11497 (defun js2-error-buffer-jump (&rest ignored)
11498 "Jump cursor to current error in source buffer."
11499 (interactive)
11500 (when (js2-error-buffer-view)
11501 (pop-to-buffer js2-source-buffer)))
11502
11503 (defun js2-error-buffer-view ()
11504 "Scroll source buffer to show error at current line."
11505 (interactive)
11506 (cond
11507 ((not (eq major-mode 'js2-error-buffer-mode))
11508 (message "Not in a js2 errors buffer"))
11509 ((not (buffer-live-p js2-source-buffer))
11510 (message "Source buffer has been killed"))
11511 ((not (wholenump (get-text-property (point) 'js2-pos)))
11512 (message "There does not seem to be an error here"))
11513 (t
11514 (let ((pos (get-text-property (point) 'js2-pos))
11515 (msg (get-text-property (point) 'js2-msg)))
11516 (save-selected-window
11517 (pop-to-buffer js2-source-buffer)
11518 (goto-char pos)
11519 (message msg))))))
11520
11521 ;;;###autoload
11522 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11523 "Major mode for editing JavaScript code."
11524 (set (make-local-variable 'max-lisp-eval-depth)
11525 (max max-lisp-eval-depth 3000))
11526 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11527 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11528 (set (make-local-variable 'syntax-propertize-function) nil)
11529 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11530 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11531 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11532 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11533 ;; for characters inside regexp literals.
11534 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11535 ;; this is necessary to make `show-paren-function' work properly
11536 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11537 ;; needed for M-x rgrep, among other things
11538 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11539
11540 (setq font-lock-defaults '(nil t))
11541
11542 ;; Experiment: make reparse-delay longer for longer files.
11543 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11544 (setq js2-idle-timer-delay
11545 (* js2-idle-timer-delay
11546 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11547
11548 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11549 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11550 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11551 (setq next-error-function #'js2-next-error)
11552 (imenu-add-to-menubar (concat "IM-" mode-name))
11553 (add-to-invisibility-spec '(js2-outline . t))
11554 (set (make-local-variable 'line-move-ignore-invisible) t)
11555 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11556 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11557
11558 (setq js2-mode-functions-hidden nil
11559 js2-mode-comments-hidden nil
11560 js2-mode-buffer-dirty-p t
11561 js2-mode-parsing nil)
11562
11563 (js2-set-default-externs)
11564
11565 (when js2-include-jslint-globals
11566 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11567
11568 (run-hooks 'js2-init-hook)
11569
11570 (js2-reparse))
11571
11572 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11573 ;; a bit more complicated and it doesn't net us much yet.
11574 ;;;###autoload
11575 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11576 "Major mode for editing JSX code.
11577
11578 To customize the indentation for this mode, set the SGML offset
11579 variables (`sgml-basic-offset' et al) locally, like so:
11580
11581 (defun set-jsx-indentation ()
11582 (setq-local sgml-basic-offset js2-basic-offset))
11583 (add-hook 'js2-jsx-mode-hook #'set-jsx-indentation)"
11584 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11585
11586 (defun js2-mode-exit ()
11587 "Exit `js2-mode' and clean up."
11588 (interactive)
11589 (when js2-mode-node-overlay
11590 (delete-overlay js2-mode-node-overlay)
11591 (setq js2-mode-node-overlay nil))
11592 (js2-remove-overlays)
11593 (setq js2-mode-ast nil)
11594 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11595 (remove-from-invisibility-spec '(js2-outline . t))
11596 (js2-mode-show-all)
11597 (with-silent-modifications
11598 (js2-clear-face (point-min) (point-max))))
11599
11600 (defun js2-mode-reset-timer ()
11601 "Cancel any existing parse timer and schedule a new one."
11602 (if js2-mode-parse-timer
11603 (cancel-timer js2-mode-parse-timer))
11604 (setq js2-mode-parsing nil)
11605 (let ((timer (timer-create)))
11606 (setq js2-mode-parse-timer timer)
11607 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11608 (timer-set-idle-time timer js2-idle-timer-delay)
11609 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11610 (timer-activate-when-idle timer nil)))
11611
11612 (defun js2-mode-idle-reparse (buffer)
11613 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11614 it to be reparsed when the buffer is selected."
11615 (cond ((eq buffer (current-buffer))
11616 (js2-reparse))
11617 ((buffer-live-p buffer)
11618 ;; reparse when the buffer is selected again
11619 (with-current-buffer buffer
11620 (add-hook 'window-configuration-change-hook
11621 #'js2-mode-idle-reparse-inner
11622 nil t)))))
11623
11624 (defun js2-mode-idle-reparse-inner ()
11625 (remove-hook 'window-configuration-change-hook
11626 #'js2-mode-idle-reparse-inner
11627 t)
11628 (js2-reparse))
11629
11630 (defun js2-mode-edit (_beg _end _len)
11631 "Schedule a new parse after buffer is edited.
11632 Buffer edit spans from BEG to END and is of length LEN."
11633 (setq js2-mode-buffer-dirty-p t)
11634 (js2-mode-hide-overlay)
11635 (js2-mode-reset-timer))
11636
11637 (defun js2-minor-mode-edit (_beg _end _len)
11638 "Callback for buffer edits in `js2-mode'.
11639 Schedules a new parse after buffer is edited.
11640 Buffer edit spans from BEG to END and is of length LEN."
11641 (setq js2-mode-buffer-dirty-p t)
11642 (js2-mode-hide-overlay)
11643 (js2-mode-reset-timer))
11644
11645 (defun js2-reparse (&optional force)
11646 "Re-parse current buffer after user finishes some data entry.
11647 If we get any user input while parsing, including cursor motion,
11648 we discard the parse and reschedule it. If FORCE is nil, then the
11649 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11650 (let (time
11651 interrupted-p
11652 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11653 (unless js2-mode-parsing
11654 (setq js2-mode-parsing t)
11655 (unwind-protect
11656 (when (or js2-mode-buffer-dirty-p force)
11657 (js2-remove-overlays)
11658 (setq js2-mode-buffer-dirty-p nil
11659 js2-mode-fontifications nil
11660 js2-mode-deferred-properties nil)
11661 (if js2-mode-verbose-parse-p
11662 (message "parsing..."))
11663 (setq time
11664 (js2-time
11665 (setq interrupted-p
11666 (catch 'interrupted
11667 (js2-parse)
11668 (with-silent-modifications
11669 ;; if parsing is interrupted, comments and regex
11670 ;; literals stay ignored by `parse-partial-sexp'
11671 (remove-text-properties (point-min) (point-max)
11672 '(syntax-table))
11673 (js2-mode-apply-deferred-properties)
11674 (js2-mode-remove-suppressed-warnings)
11675 (js2-mode-show-warnings)
11676 (js2-mode-show-errors)
11677 (if (>= js2-highlight-level 1)
11678 (js2-highlight-jsdoc js2-mode-ast)))
11679 nil))))
11680 (if interrupted-p
11681 (progn
11682 ;; unfinished parse => try again
11683 (setq js2-mode-buffer-dirty-p t)
11684 (js2-mode-reset-timer))
11685 (if js2-mode-verbose-parse-p
11686 (message "Parse time: %s" time))))
11687 (setq js2-mode-parsing nil)
11688 (unless interrupted-p
11689 (setq js2-mode-parse-timer nil))))))
11690
11691 (defun js2-mode-show-node (event)
11692 "Debugging aid: highlight selected AST node on mouse click."
11693 (interactive "e")
11694 (mouse-set-point event)
11695 (setq deactivate-mark t)
11696 (when js2-mode-show-overlay
11697 (let ((node (js2-node-at-point))
11698 beg end)
11699 (if (null node)
11700 (message "No node found at location %s" (point))
11701 (setq beg (js2-node-abs-pos node)
11702 end (+ beg (js2-node-len node)))
11703 (if js2-mode-node-overlay
11704 (move-overlay js2-mode-node-overlay beg end)
11705 (setq js2-mode-node-overlay (make-overlay beg end))
11706 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11707 (with-silent-modifications
11708 (if (fboundp 'cursor-sensor-mode)
11709 (put-text-property beg end 'cursor-sensor-functions
11710 '(js2-mode-hide-overlay))
11711 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11712 (message "%s, parent: %s"
11713 (js2-node-short-name node)
11714 (if (js2-node-parent node)
11715 (js2-node-short-name (js2-node-parent node))
11716 "nil"))))))
11717
11718 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11719 "Remove the debugging overlay when point moves.
11720 ARG1, ARG2 and ARG3 have different values depending on whether this function
11721 was found on `point-left' or in `cursor-sensor-functions'."
11722 (when js2-mode-node-overlay
11723 (let ((beg (overlay-start js2-mode-node-overlay))
11724 (end (overlay-end js2-mode-node-overlay))
11725 (p2 (if (windowp arg1)
11726 ;; Called from cursor-sensor-functions.
11727 (window-point arg1)
11728 ;; Called from point-left.
11729 arg2)))
11730 ;; Sometimes we're called spuriously.
11731 (unless (and p2
11732 (>= p2 beg)
11733 (<= p2 end))
11734 (with-silent-modifications
11735 (remove-text-properties beg end
11736 '(point-left nil cursor-sensor-functions)))
11737 (delete-overlay js2-mode-node-overlay)
11738 (setq js2-mode-node-overlay nil)))))
11739
11740 (defun js2-mode-reset ()
11741 "Debugging helper: reset everything."
11742 (interactive)
11743 (js2-mode-exit)
11744 (js2-mode))
11745
11746 (defun js2-mode-show-warn-or-err (e face)
11747 "Highlight a warning or error E with FACE.
11748 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11749 The last element is optional. When present, use instead of FACE."
11750 (let* ((key (cl-first e))
11751 (beg (cl-second e))
11752 (end (+ beg (cl-third e)))
11753 ;; Don't inadvertently go out of bounds.
11754 (beg (max (point-min) (min beg (point-max))))
11755 (end (max (point-min) (min end (point-max))))
11756 (ovl (make-overlay beg end)))
11757 ;; FIXME: Why a mix of overlays and text-properties?
11758 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11759 (overlay-put ovl 'js2-error t)
11760 (put-text-property beg end 'help-echo (js2-get-msg key))
11761 (if (fboundp 'cursor-sensor-mode)
11762 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11763 (put-text-property beg end 'point-entered #'js2-echo-error))))
11764
11765 (defun js2-remove-overlays ()
11766 "Remove overlays from buffer that have a `js2-error' property."
11767 (let ((beg (point-min))
11768 (end (point-max)))
11769 (save-excursion
11770 (dolist (o (overlays-in beg end))
11771 (when (overlay-get o 'js2-error)
11772 (delete-overlay o))))))
11773
11774 (defun js2-mode-apply-deferred-properties ()
11775 "Apply fontifications and other text properties recorded during parsing."
11776 (when (cl-plusp js2-highlight-level)
11777 ;; We defer clearing faces as long as possible to eliminate flashing.
11778 (js2-clear-face (point-min) (point-max))
11779 ;; Have to reverse the recorded fontifications list so that errors
11780 ;; and warnings overwrite the normal fontifications.
11781 (dolist (f (nreverse js2-mode-fontifications))
11782 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11783 (setq js2-mode-fontifications nil))
11784 (dolist (p js2-mode-deferred-properties)
11785 (apply #'put-text-property p))
11786 (setq js2-mode-deferred-properties nil))
11787
11788 (defun js2-mode-show-errors ()
11789 "Highlight syntax errors."
11790 (when js2-mode-show-parse-errors
11791 (dolist (e (js2-ast-root-errors js2-mode-ast))
11792 (js2-mode-show-warn-or-err e 'js2-error))))
11793
11794 (defun js2-mode-remove-suppressed-warnings ()
11795 "Take suppressed warnings out of the AST warnings list.
11796 This ensures that the counts and `next-error' are correct."
11797 (setf (js2-ast-root-warnings js2-mode-ast)
11798 (js2-delete-if
11799 (lambda (e)
11800 (let ((key (caar e)))
11801 (or
11802 (and (not js2-strict-trailing-comma-warning)
11803 (string-match "trailing\\.comma" key))
11804 (and (not js2-strict-cond-assign-warning)
11805 (string= key "msg.equal.as.assign"))
11806 (and js2-missing-semi-one-line-override
11807 (string= key "msg.missing.semi")
11808 (let* ((beg (cl-second e))
11809 (node (js2-node-at-point beg))
11810 (fn (js2-mode-find-parent-fn node))
11811 (body (and fn (js2-function-node-body fn)))
11812 (lc (and body (js2-node-abs-pos body)))
11813 (rc (and lc (+ lc (js2-node-len body)))))
11814 (and fn
11815 (or (null body)
11816 (save-excursion
11817 (goto-char beg)
11818 (and (js2-same-line lc)
11819 (js2-same-line rc))))))))))
11820 (js2-ast-root-warnings js2-mode-ast))))
11821
11822 (defun js2-mode-show-warnings ()
11823 "Highlight strict-mode warnings."
11824 (when js2-mode-show-strict-warnings
11825 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11826 (js2-mode-show-warn-or-err e 'js2-warning))))
11827
11828 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11829 "Called by point-motion hooks.
11830 ARG1, ARG2 and ARG3 have different values depending on whether this function
11831 was found on `point-entered' or in `cursor-sensor-functions'."
11832 (let* ((new-point (if (windowp arg1)
11833 ;; Called from cursor-sensor-functions.
11834 (window-point arg1)
11835 ;; Called from point-left.
11836 arg2))
11837 (msg (get-text-property new-point 'help-echo)))
11838 (when (and (stringp msg)
11839 (not (active-minibuffer-window))
11840 (not (current-message)))
11841 (message msg))))
11842
11843 (defun js2-line-break (&optional _soft)
11844 "Break line at point and indent, continuing comment if within one.
11845 If inside a string, and `js2-concat-multiline-strings' is not
11846 nil, turn it into concatenation."
11847 (interactive)
11848 (let ((parse-status (syntax-ppss)))
11849 (cond
11850 ;; Check if we're inside a string.
11851 ((nth 3 parse-status)
11852 (if js2-concat-multiline-strings
11853 (js2-mode-split-string parse-status)
11854 (insert "\n")))
11855 ;; Check if inside a block comment.
11856 ((nth 4 parse-status)
11857 (js2-mode-extend-comment (nth 8 parse-status)))
11858 (t
11859 (newline-and-indent)))))
11860
11861 (defun js2-mode-split-string (parse-status)
11862 "Turn a newline in mid-string into a string concatenation.
11863 PARSE-STATUS is as documented in `parse-partial-sexp'."
11864 (let* ((quote-char (nth 3 parse-status))
11865 (at-eol (eq js2-concat-multiline-strings 'eol)))
11866 (insert quote-char)
11867 (insert (if at-eol " +\n" "\n"))
11868 (unless at-eol
11869 (insert "+ "))
11870 (js2-indent-line)
11871 (insert quote-char)
11872 (when (eolp)
11873 (insert quote-char)
11874 (backward-char 1))))
11875
11876 (defun js2-mode-extend-comment (start-pos)
11877 "Indent the line and, when inside a comment block, add comment prefix."
11878 (let (star single col first-line needs-close)
11879 (save-excursion
11880 (back-to-indentation)
11881 (when (< (point) start-pos)
11882 (goto-char start-pos))
11883 (cond
11884 ((looking-at "\\*[^/]")
11885 (setq star t
11886 col (current-column)))
11887 ((looking-at "/\\*")
11888 (setq star t
11889 first-line t
11890 col (1+ (current-column))))
11891 ((looking-at "//")
11892 (setq single t
11893 col (current-column)))))
11894 ;; Heuristic for whether we need to close the comment:
11895 ;; if we've got a parse error here, assume it's an unterminated
11896 ;; comment.
11897 (setq needs-close
11898 (or
11899 (get-char-property (1- (point)) 'js2-error)
11900 ;; The heuristic above doesn't work well when we're
11901 ;; creating a comment and there's another one downstream,
11902 ;; as our parser thinks this one ends at the end of the
11903 ;; next one. (You can have a /* inside a js block comment.)
11904 ;; So just close it if the next non-ws char isn't a *.
11905 (and first-line
11906 (eolp)
11907 (save-excursion
11908 (skip-chars-forward " \t\r\n")
11909 (not (eq (char-after) ?*))))))
11910 (delete-horizontal-space)
11911 (insert "\n")
11912 (cond
11913 (star
11914 (indent-to col)
11915 (insert "* ")
11916 (if (and first-line needs-close)
11917 (save-excursion
11918 (insert "\n")
11919 (indent-to col)
11920 (insert "*/"))))
11921 (single
11922 (indent-to col)
11923 (insert "// ")))
11924 ;; Don't need to extend the comment after all.
11925 (js2-indent-line)))
11926
11927 (defun js2-beginning-of-line ()
11928 "Toggle point between bol and first non-whitespace char in line.
11929 Also moves past comment delimiters when inside comments."
11930 (interactive)
11931 (let (node)
11932 (cond
11933 ((bolp)
11934 (back-to-indentation))
11935 ((looking-at "//")
11936 (skip-chars-forward "/ \t"))
11937 ((and (eq (char-after) ?*)
11938 (setq node (js2-comment-at-point))
11939 (memq (js2-comment-node-format node) '(jsdoc block))
11940 (save-excursion
11941 (skip-chars-backward " \t")
11942 (bolp)))
11943 (skip-chars-forward "\* \t"))
11944 (t
11945 (goto-char (point-at-bol))))))
11946
11947 (defun js2-end-of-line ()
11948 "Toggle point between eol and last non-whitespace char in line."
11949 (interactive)
11950 (if (eolp)
11951 (skip-chars-backward " \t")
11952 (goto-char (point-at-eol))))
11953
11954 (defun js2-mode-wait-for-parse (callback)
11955 "Invoke CALLBACK when parsing is finished.
11956 If parsing is already finished, calls CALLBACK immediately."
11957 (if (not js2-mode-buffer-dirty-p)
11958 (funcall callback)
11959 (push callback js2-mode-pending-parse-callbacks)
11960 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11961
11962 (defun js2-mode-parse-finished ()
11963 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11964 ;; We can't let errors propagate up, since it prevents the
11965 ;; `js2-parse' method from completing normally and returning
11966 ;; the ast, which makes things mysteriously not work right.
11967 (unwind-protect
11968 (dolist (cb js2-mode-pending-parse-callbacks)
11969 (condition-case err
11970 (funcall cb)
11971 (error (message "%s" err))))
11972 (setq js2-mode-pending-parse-callbacks nil)))
11973
11974 (defun js2-mode-flag-region (from to flag)
11975 "Hide or show text from FROM to TO, according to FLAG.
11976 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11977 Returns the created overlay if FLAG is non-nil."
11978 (remove-overlays from to 'invisible 'js2-outline)
11979 (when flag
11980 (let ((o (make-overlay from to)))
11981 (overlay-put o 'invisible 'js2-outline)
11982 (overlay-put o 'isearch-open-invisible
11983 'js2-isearch-open-invisible)
11984 o)))
11985
11986 ;; Function to be set as an outline-isearch-open-invisible' property
11987 ;; to the overlay that makes the outline invisible (see
11988 ;; `js2-mode-flag-region').
11989 (defun js2-isearch-open-invisible (_overlay)
11990 ;; We rely on the fact that isearch places point on the matched text.
11991 (js2-mode-show-element))
11992
11993 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11994 "Return cons cell of bounds of folding overlay at POS.
11995 Returns nil if not found."
11996 (let ((overlays (overlays-at (or pos (point))))
11997 o)
11998 (while (and overlays
11999 (not o))
12000 (if (overlay-get (car overlays) 'invisible)
12001 (setq o (car overlays))
12002 (setq overlays (cdr overlays))))
12003 (if o
12004 (cons (overlay-start o) (overlay-end o)))))
12005
12006 (defun js2-mode-function-at-point (&optional pos)
12007 "Return the innermost function node enclosing current point.
12008 Returns nil if point is not in a function."
12009 (let ((node (js2-node-at-point pos)))
12010 (while (and node (not (js2-function-node-p node)))
12011 (setq node (js2-node-parent node)))
12012 (if (js2-function-node-p node)
12013 node)))
12014
12015 (defun js2-mode-toggle-element ()
12016 "Hide or show the foldable element at the point."
12017 (interactive)
12018 (let (comment fn pos)
12019 (save-excursion
12020 (cond
12021 ;; /* ... */ comment?
12022 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
12023 (if (js2-mode-invisible-overlay-bounds
12024 (setq pos (+ 3 (js2-node-abs-pos comment))))
12025 (progn
12026 (goto-char pos)
12027 (js2-mode-show-element))
12028 (js2-mode-hide-element)))
12029 ;; //-comment?
12030 ((save-excursion
12031 (back-to-indentation)
12032 (looking-at js2-mode-//-comment-re))
12033 (js2-mode-toggle-//-comment))
12034 ;; function?
12035 ((setq fn (js2-mode-function-at-point))
12036 (setq pos (and (js2-function-node-body fn)
12037 (js2-node-abs-pos (js2-function-node-body fn))))
12038 (goto-char (1+ pos))
12039 (if (js2-mode-invisible-overlay-bounds)
12040 (js2-mode-show-element)
12041 (js2-mode-hide-element)))
12042 (t
12043 (message "Nothing at point to hide or show"))))))
12044
12045 (defun js2-mode-hide-element ()
12046 "Fold/hide contents of a block, showing ellipses.
12047 Show the hidden text with \\[js2-mode-show-element]."
12048 (interactive)
12049 (if js2-mode-buffer-dirty-p
12050 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12051 (let (node body beg end)
12052 (cond
12053 ((js2-mode-invisible-overlay-bounds)
12054 (message "already hidden"))
12055 (t
12056 (setq node (js2-node-at-point))
12057 (cond
12058 ((js2-block-comment-p node)
12059 (js2-mode-hide-comment node))
12060 (t
12061 (while (and node (not (js2-function-node-p node)))
12062 (setq node (js2-node-parent node)))
12063 (if (and node
12064 (setq body (js2-function-node-body node)))
12065 (progn
12066 (setq beg (js2-node-abs-pos body)
12067 end (+ beg (js2-node-len body)))
12068 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12069 (message "No collapsable element found at point"))))))))
12070
12071 (defun js2-mode-show-element ()
12072 "Show the hidden element at current point."
12073 (interactive)
12074 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12075 (if bounds
12076 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12077 (message "Nothing to un-hide"))))
12078
12079 (defun js2-mode-show-all ()
12080 "Show all of the text in the buffer."
12081 (interactive)
12082 (js2-mode-flag-region (point-min) (point-max) nil))
12083
12084 (defun js2-mode-toggle-hide-functions ()
12085 (interactive)
12086 (if js2-mode-functions-hidden
12087 (js2-mode-show-functions)
12088 (js2-mode-hide-functions)))
12089
12090 (defun js2-mode-hide-functions ()
12091 "Hides all non-nested function bodies in the buffer.
12092 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12093 to open an individual entry."
12094 (interactive)
12095 (if js2-mode-buffer-dirty-p
12096 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12097 (if (null js2-mode-ast)
12098 (message "Oops - parsing failed")
12099 (setq js2-mode-functions-hidden t)
12100 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12101
12102 (defun js2-mode-function-hider (n endp)
12103 (when (not endp)
12104 (let ((tt (js2-node-type n))
12105 body beg end)
12106 (cond
12107 ((and (= tt js2-FUNCTION)
12108 (setq body (js2-function-node-body n)))
12109 (setq beg (js2-node-abs-pos body)
12110 end (+ beg (js2-node-len body)))
12111 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12112 nil) ; don't process children of function
12113 (t
12114 t))))) ; keep processing other AST nodes
12115
12116 (defun js2-mode-show-functions ()
12117 "Un-hide any folded function bodies in the buffer."
12118 (interactive)
12119 (setq js2-mode-functions-hidden nil)
12120 (save-excursion
12121 (goto-char (point-min))
12122 (while (/= (goto-char (next-overlay-change (point)))
12123 (point-max))
12124 (dolist (o (overlays-at (point)))
12125 (when (and (overlay-get o 'invisible)
12126 (not (overlay-get o 'comment)))
12127 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12128
12129 (defun js2-mode-hide-comment (n)
12130 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12131 3 ; /**
12132 2)) ; /*
12133 (beg (+ (js2-node-abs-pos n) head))
12134 (end (- (+ beg (js2-node-len n)) head 2))
12135 (o (js2-mode-flag-region beg end 'hide)))
12136 (overlay-put o 'comment t)))
12137
12138 (defun js2-mode-toggle-hide-comments ()
12139 "Folds all block comments in the buffer.
12140 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12141 to open an individual entry."
12142 (interactive)
12143 (if js2-mode-comments-hidden
12144 (js2-mode-show-comments)
12145 (js2-mode-hide-comments)))
12146
12147 (defun js2-mode-hide-comments ()
12148 (interactive)
12149 (if js2-mode-buffer-dirty-p
12150 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12151 (if (null js2-mode-ast)
12152 (message "Oops - parsing failed")
12153 (setq js2-mode-comments-hidden t)
12154 (dolist (n (js2-ast-root-comments js2-mode-ast))
12155 (when (js2-block-comment-p n)
12156 (js2-mode-hide-comment n)))
12157 (js2-mode-hide-//-comments)))
12158
12159 (defun js2-mode-extend-//-comment (direction)
12160 "Find start or end of a block of similar //-comment lines.
12161 DIRECTION is -1 to look back, 1 to look forward.
12162 INDENT is the indentation level to match.
12163 Returns the end-of-line position of the furthest adjacent
12164 //-comment line with the same indentation as the current line.
12165 If there is no such matching line, returns current end of line."
12166 (let ((pos (point-at-eol))
12167 (indent (current-indentation)))
12168 (save-excursion
12169 (while (and (zerop (forward-line direction))
12170 (looking-at js2-mode-//-comment-re)
12171 (eq indent (length (match-string 1))))
12172 (setq pos (point-at-eol)))
12173 pos)))
12174
12175 (defun js2-mode-hide-//-comments ()
12176 "Fold adjacent 1-line comments, showing only snippet of first one."
12177 (let (beg end)
12178 (save-excursion
12179 (goto-char (point-min))
12180 (while (re-search-forward js2-mode-//-comment-re nil t)
12181 (setq beg (point)
12182 end (js2-mode-extend-//-comment 1))
12183 (unless (eq beg end)
12184 (overlay-put (js2-mode-flag-region beg end 'hide)
12185 'comment t))
12186 (goto-char end)
12187 (forward-char 1)))))
12188
12189 (defun js2-mode-toggle-//-comment ()
12190 "Fold or un-fold any multi-line //-comment at point.
12191 Caller should have determined that this line starts with a //-comment."
12192 (let* ((beg (point-at-eol))
12193 (end beg))
12194 (save-excursion
12195 (goto-char end)
12196 (if (js2-mode-invisible-overlay-bounds)
12197 (js2-mode-show-element)
12198 ;; else hide the comment
12199 (setq beg (js2-mode-extend-//-comment -1)
12200 end (js2-mode-extend-//-comment 1))
12201 (unless (eq beg end)
12202 (overlay-put (js2-mode-flag-region beg end 'hide)
12203 'comment t))))))
12204
12205 (defun js2-mode-show-comments ()
12206 "Un-hide any hidden comments, leaving other hidden elements alone."
12207 (interactive)
12208 (setq js2-mode-comments-hidden nil)
12209 (save-excursion
12210 (goto-char (point-min))
12211 (while (/= (goto-char (next-overlay-change (point)))
12212 (point-max))
12213 (dolist (o (overlays-at (point)))
12214 (when (overlay-get o 'comment)
12215 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12216
12217 (defun js2-mode-display-warnings-and-errors ()
12218 "Turn on display of warnings and errors."
12219 (interactive)
12220 (setq js2-mode-show-parse-errors t
12221 js2-mode-show-strict-warnings t)
12222 (js2-reparse 'force))
12223
12224 (defun js2-mode-hide-warnings-and-errors ()
12225 "Turn off display of warnings and errors."
12226 (interactive)
12227 (setq js2-mode-show-parse-errors nil
12228 js2-mode-show-strict-warnings nil)
12229 (js2-reparse 'force))
12230
12231 (defun js2-mode-toggle-warnings-and-errors ()
12232 "Toggle the display of warnings and errors.
12233 Some users don't like having warnings/errors reported while they type."
12234 (interactive)
12235 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12236 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12237 (if (called-interactively-p 'any)
12238 (message "warnings and errors %s"
12239 (if js2-mode-show-parse-errors
12240 "enabled"
12241 "disabled")))
12242 (js2-reparse 'force))
12243
12244 (defun js2-mode-customize ()
12245 (interactive)
12246 (customize-group 'js2-mode))
12247
12248 (defun js2-mode-forward-sexp (&optional arg)
12249 "Move forward across one statement or balanced expression.
12250 With ARG, do it that many times. Negative arg -N means
12251 move backward across N balanced expressions."
12252 (interactive "p")
12253 (setq arg (or arg 1))
12254 (save-restriction
12255 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12256 (js2-reparse)
12257 (let (forward-sexp-function
12258 node (start (point)) pos lp rp child)
12259 (cond
12260 ;; backward-sexp
12261 ;; could probably make this better for some cases:
12262 ;; - if in statement block (e.g. function body), go to parent
12263 ;; - infix exprs like (foo in bar) - maybe go to beginning
12264 ;; of infix expr if in the right-side expression?
12265 ((and arg (cl-minusp arg))
12266 (dotimes (_ (- arg))
12267 (js2-backward-sws)
12268 (forward-char -1) ; Enter the node we backed up to.
12269 (when (setq node (js2-node-at-point (point) t))
12270 (setq pos (js2-node-abs-pos node))
12271 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12272 (setq lp (car parens)
12273 rp (cdr parens)))
12274 (when (and lp (> start lp))
12275 (if (and rp (<= start rp))
12276 ;; Between parens, check if there's a child node we can jump.
12277 (when (setq child (js2-node-closest-child node (point) lp t))
12278 (setq pos (js2-node-abs-pos child)))
12279 ;; Before both parens.
12280 (setq pos lp)))
12281 (let ((state (parse-partial-sexp start pos)))
12282 (goto-char (if (not (zerop (car state)))
12283 ;; Stumble at the unbalanced paren if < 0, or
12284 ;; jump a bit further if > 0.
12285 (scan-sexps start -1)
12286 pos))))
12287 (unless pos (goto-char (point-min)))))
12288 (t
12289 ;; forward-sexp
12290 (dotimes (_ arg)
12291 (js2-forward-sws)
12292 (when (setq node (js2-node-at-point (point) t))
12293 (setq pos (js2-node-abs-pos node))
12294 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12295 (setq lp (car parens)
12296 rp (cdr parens)))
12297 (or
12298 (when (and rp (<= start rp))
12299 (if (> start lp)
12300 (when (setq child (js2-node-closest-child node (point) rp))
12301 (setq pos (js2-node-abs-end child)))
12302 (setq pos (1+ rp))))
12303 ;; No parens or child nodes, looks for the end of the current node.
12304 (cl-incf pos (js2-node-len
12305 (if (js2-expr-stmt-node-p (js2-node-parent node))
12306 ;; Stop after the semicolon.
12307 (js2-node-parent node)
12308 node))))
12309 (let ((state (save-excursion (parse-partial-sexp start pos))))
12310 (goto-char (if (not (zerop (car state)))
12311 (scan-sexps start 1)
12312 pos))))
12313 (unless pos (goto-char (point-max)))))))))
12314
12315 (defun js2-mode-forward-sexp-parens (node abs-pos)
12316 "Return a cons cell with positions of main parens in NODE."
12317 (cond
12318 ((or (js2-array-node-p node)
12319 (js2-object-node-p node)
12320 (js2-comp-node-p node)
12321 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12322 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12323 ((js2-paren-expr-node-p node)
12324 (let ((lp (js2-node-lp node))
12325 (rp (js2-node-rp node)))
12326 (cons (when lp (+ abs-pos lp))
12327 (when rp (+ abs-pos rp)))))))
12328
12329 (defun js2-node-closest-child (parent point limit &optional before)
12330 (let* ((parent-pos (js2-node-abs-pos parent))
12331 (rpoint (- point parent-pos))
12332 (rlimit (- limit parent-pos))
12333 (min (min rpoint rlimit))
12334 (max (max rpoint rlimit))
12335 found)
12336 (catch 'done
12337 (js2-visit-ast
12338 parent
12339 (lambda (node _end-p)
12340 (if (eq node parent)
12341 t
12342 (let ((pos (js2-node-pos node)) ;; Both relative values.
12343 (end (+ (js2-node-pos node) (js2-node-len node))))
12344 (when (and (>= pos min) (<= end max)
12345 (if before (< pos rpoint) (> end rpoint)))
12346 (setq found node))
12347 (when (> end rpoint)
12348 (throw 'done nil)))
12349 nil))))
12350 found))
12351
12352 (defun js2-errors ()
12353 "Return a list of errors found."
12354 (and js2-mode-ast
12355 (js2-ast-root-errors js2-mode-ast)))
12356
12357 (defun js2-warnings ()
12358 "Return a list of warnings found."
12359 (and js2-mode-ast
12360 (js2-ast-root-warnings js2-mode-ast)))
12361
12362 (defun js2-have-errors-p ()
12363 "Return non-nil if any parse errors or warnings were found."
12364 (or (js2-errors) (js2-warnings)))
12365
12366 (defun js2-errors-and-warnings ()
12367 "Return a copy of the concatenated errors and warnings lists.
12368 They are appended: first the errors, then the warnings.
12369 Entries are of the form (MSG BEG END)."
12370 (when js2-mode-ast
12371 (append (js2-ast-root-errors js2-mode-ast)
12372 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12373
12374 (defun js2-next-error (&optional arg reset)
12375 "Move to next parse error.
12376 Typically invoked via \\[next-error].
12377 ARG is the number of errors, forward or backward, to move.
12378 RESET means start over from the beginning."
12379 (interactive "p")
12380 (if (not (or (js2-errors) (js2-warnings)))
12381 (message "No errors")
12382 (when reset
12383 (goto-char (point-min)))
12384 (let* ((errs (js2-errors-and-warnings))
12385 (continue t)
12386 (start (point))
12387 (count (or arg 1))
12388 (backward (cl-minusp count))
12389 (sorter (if backward '> '<))
12390 (stopper (if backward '< '>))
12391 (count (abs count))
12392 all-errs err)
12393 ;; Sort by start position.
12394 (setq errs (sort errs (lambda (e1 e2)
12395 (funcall sorter (cl-second e1) (cl-second e2))))
12396 all-errs errs)
12397 ;; Find nth error with pos > start.
12398 (while (and errs continue)
12399 (when (funcall stopper (cl-cadar errs) start)
12400 (setq err (car errs))
12401 (if (zerop (cl-decf count))
12402 (setq continue nil)))
12403 (setq errs (cdr errs)))
12404 ;; Clear for `js2-echo-error'.
12405 (message nil)
12406 (if err
12407 (goto-char (cl-second err))
12408 ;; Wrap around to first error.
12409 (goto-char (cl-second (car all-errs)))
12410 ;; If we were already on it, echo msg again.
12411 (if (= (point) start)
12412 (js2-echo-error (point) (point)))))))
12413
12414 (defun js2-down-mouse-3 ()
12415 "Make right-click move the point to the click location.
12416 This makes right-click context menu operations a bit more intuitive.
12417 The point will not move if the region is active, however, to avoid
12418 destroying the region selection."
12419 (interactive)
12420 (when (and js2-move-point-on-right-click
12421 (not mark-active))
12422 (let ((e last-input-event))
12423 (ignore-errors
12424 (goto-char (cl-cadadr e))))))
12425
12426 (defun js2-mode-create-imenu-index ()
12427 "Return an alist for `imenu--index-alist'."
12428 ;; This is built up in `js2-parse-record-imenu' during parsing.
12429 (when js2-mode-ast
12430 ;; if we have an ast but no recorder, they're requesting a rescan
12431 (unless js2-imenu-recorder
12432 (js2-reparse 'force))
12433 (prog1
12434 (js2-build-imenu-index)
12435 (setq js2-imenu-recorder nil
12436 js2-imenu-function-map nil))))
12437
12438 (defun js2-mode-find-tag ()
12439 "Replacement for `find-tag-default'.
12440 `find-tag-default' returns a ridiculous answer inside comments."
12441 (let (beg end)
12442 (save-excursion
12443 (if (looking-at "\\_>")
12444 (setq beg (progn (forward-symbol -1) (point))
12445 end (progn (forward-symbol 1) (point)))
12446 (setq beg (progn (forward-symbol 1) (point))
12447 end (progn (forward-symbol -1) (point))))
12448 (replace-regexp-in-string
12449 "[\"']" ""
12450 (buffer-substring-no-properties beg end)))))
12451
12452 (defun js2-mode-forward-sibling ()
12453 "Move to the end of the sibling following point in parent.
12454 Returns non-nil if successful, or nil if there was no following sibling."
12455 (let* ((node (js2-node-at-point))
12456 (parent (js2-mode-find-enclosing-fn node))
12457 sib)
12458 (when (setq sib (js2-node-find-child-after (point) parent))
12459 (goto-char (+ (js2-node-abs-pos sib)
12460 (js2-node-len sib))))))
12461
12462 (defun js2-mode-backward-sibling ()
12463 "Move to the beginning of the sibling node preceding point in parent.
12464 Parent is defined as the enclosing script or function."
12465 (let* ((node (js2-node-at-point))
12466 (parent (js2-mode-find-enclosing-fn node))
12467 sib)
12468 (when (setq sib (js2-node-find-child-before (point) parent))
12469 (goto-char (js2-node-abs-pos sib)))))
12470
12471 (defun js2-beginning-of-defun (&optional arg)
12472 "Go to line on which current function starts, and return t on success.
12473 If we're not in a function or already at the beginning of one, go
12474 to beginning of previous script-level element.
12475 With ARG N, do that N times. If N is negative, move forward."
12476 (setq arg (or arg 1))
12477 (if (cl-plusp arg)
12478 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12479 (when (cond
12480 ((js2-function-node-p parent)
12481 (goto-char (js2-node-abs-pos parent)))
12482 (t
12483 (js2-mode-backward-sibling)))
12484 (if (> arg 1)
12485 (js2-beginning-of-defun (1- arg))
12486 t)))
12487 (when (js2-end-of-defun)
12488 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12489
12490 (defun js2-end-of-defun ()
12491 "Go to the char after the last position of the current function
12492 or script-level element."
12493 (let* ((node (js2-node-at-point))
12494 (parent (or (and (js2-function-node-p node) node)
12495 (js2-node-parent-script-or-fn node)))
12496 script)
12497 (unless (js2-function-node-p parent)
12498 ;; Use current script-level node, or, if none, the next one.
12499 (setq script (or parent node)
12500 parent (js2-node-find-child-before (point) script))
12501 (when (or (null parent)
12502 (>= (point) (+ (js2-node-abs-pos parent)
12503 (js2-node-len parent))))
12504 (setq parent (js2-node-find-child-after (point) script))))
12505 (when parent
12506 (goto-char (+ (js2-node-abs-pos parent)
12507 (js2-node-len parent))))))
12508
12509 (defun js2-mark-defun (&optional allow-extend)
12510 "Put mark at end of this function, point at beginning.
12511 The function marked is the one that contains point.
12512
12513 Interactively, if this command is repeated,
12514 or (in Transient Mark mode) if the mark is active,
12515 it marks the next defun after the ones already marked."
12516 (interactive "p")
12517 (let (extended)
12518 (when (and allow-extend
12519 (or (and (eq last-command this-command) (mark t))
12520 (and transient-mark-mode mark-active)))
12521 (let ((sib (save-excursion
12522 (goto-char (mark))
12523 (if (js2-mode-forward-sibling)
12524 (point)))))
12525 (if sib
12526 (progn
12527 (set-mark sib)
12528 (setq extended t))
12529 ;; no more siblings - try extending to enclosing node
12530 (goto-char (mark t)))))
12531 (when (not extended)
12532 (let ((node (js2-node-at-point (point) t)) ; skip comments
12533 ast fn stmt parent beg end)
12534 (when (js2-ast-root-p node)
12535 (setq ast node
12536 node (or (js2-node-find-child-after (point) node)
12537 (js2-node-find-child-before (point) node))))
12538 ;; only mark whole buffer if we can't find any children
12539 (if (null node)
12540 (setq node ast))
12541 (if (js2-function-node-p node)
12542 (setq parent node)
12543 (setq fn (js2-mode-find-enclosing-fn node)
12544 stmt (if (or (null fn)
12545 (js2-ast-root-p fn))
12546 (js2-mode-find-first-stmt node))
12547 parent (or stmt fn)))
12548 (setq beg (js2-node-abs-pos parent)
12549 end (+ beg (js2-node-len parent)))
12550 (push-mark beg)
12551 (goto-char end)
12552 (exchange-point-and-mark)))))
12553
12554 (defun js2-narrow-to-defun ()
12555 "Narrow to the function enclosing point."
12556 (interactive)
12557 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12558 (fn (if (js2-script-node-p node)
12559 node
12560 (js2-mode-find-enclosing-fn node)))
12561 (beg (js2-node-abs-pos fn)))
12562 (unless (js2-ast-root-p fn)
12563 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12564
12565 (defun js2-jump-to-definition (&optional arg)
12566 "Jump to the definition of an object's property, variable or function."
12567 (interactive "P")
12568 (ring-insert find-tag-marker-ring (point-marker))
12569 (let* ((node (js2-node-at-point))
12570 (parent (js2-node-parent node))
12571 (names (if (js2-prop-get-node-p parent)
12572 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12573 (cl-loop for n in temp
12574 with result = '()
12575 do (push n result)
12576 until (equal node n)
12577 finally return result)))))
12578 node-init)
12579 (unless (and (js2-name-node-p node)
12580 (not (js2-var-init-node-p parent))
12581 (not (js2-function-node-p parent)))
12582 (error "Node is not a supported jump node"))
12583 (push (or (and names (pop names))
12584 (unless (and (js2-object-prop-node-p parent)
12585 (eq node (js2-object-prop-node-left parent)))
12586 node)) names)
12587 (setq node-init (js2-search-scope node names))
12588
12589 ;; todo: display list of results in buffer
12590 ;; todo: group found references by buffer
12591 (unless node-init
12592 (switch-to-buffer
12593 (catch 'found
12594 (unless arg
12595 (mapc (lambda (b)
12596 (with-current-buffer b
12597 (when (derived-mode-p 'js2-mode)
12598 (setq node-init (js2-search-scope js2-mode-ast names))
12599 (if node-init
12600 (throw 'found b)))))
12601 (buffer-list)))
12602 nil)))
12603 (setq node-init (if (listp node-init) (car node-init) node-init))
12604 (unless node-init
12605 (pop-tag-mark)
12606 (error "No jump location found"))
12607 (goto-char (js2-node-abs-pos node-init))))
12608
12609 (defun js2-search-object (node name-node)
12610 "Check if object NODE contains element with NAME-NODE."
12611 (cl-assert (js2-object-node-p node))
12612 ;; Only support name-node and nodes for the time being
12613 (cl-loop for elem in (js2-object-node-elems node)
12614 for left = (js2-object-prop-node-left elem)
12615 if (or (and (js2-name-node-p left)
12616 (equal (js2-name-node-name name-node)
12617 (js2-name-node-name left)))
12618 (and (js2-string-node-p left)
12619 (string= (js2-name-node-name name-node)
12620 (js2-string-node-value left))))
12621 return elem))
12622
12623 (defun js2-search-object-for-prop (object prop-names)
12624 "Return node in OBJECT that matches PROP-NAMES or nil.
12625 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12626 i.e. ('name' 'value') = {name : { value: 3}}"
12627 (let (node
12628 (temp-object object)
12629 (temp t) ;temporay node
12630 (names prop-names))
12631 (while (and temp names (js2-object-node-p temp-object))
12632 (setq temp (js2-search-object temp-object (pop names)))
12633 (and (setq node temp)
12634 (setq temp-object (js2-object-prop-node-right temp))))
12635 (unless names node)))
12636
12637 (defun js2-search-scope (node names)
12638 "Searches NODE scope for jump location matching NAMES.
12639 NAMES is a list of property values to search for. For functions
12640 and variables NAMES will contain one element."
12641 (let (node-init
12642 (val (js2-name-node-name (car names))))
12643 (setq node-init (js2-get-symbol-declaration node val))
12644
12645 (when (> (length names) 1)
12646
12647 ;; Check var declarations
12648 (when (and node-init (string= val (js2-name-node-name node-init)))
12649 (let ((parent (js2-node-parent node-init))
12650 (temp-names names))
12651 (pop temp-names) ;; First element is var name
12652 (setq node-init (when (js2-var-init-node-p parent)
12653 (js2-search-object-for-prop
12654 (js2-var-init-node-initializer parent)
12655 temp-names)))))
12656
12657 ;; Check all assign nodes
12658 (js2-visit-ast
12659 js2-mode-ast
12660 (lambda (node endp)
12661 (unless endp
12662 (if (js2-assign-node-p node)
12663 (let ((left (js2-assign-node-left node))
12664 (right (js2-assign-node-right node))
12665 (temp-names names))
12666 (when (js2-prop-get-node-p left)
12667 (let* ((prop-list (js2-compute-nested-prop-get left))
12668 (found (cl-loop for prop in prop-list
12669 until (not (string= (js2-name-node-name
12670 (pop temp-names))
12671 (js2-name-node-name prop)))
12672 if (not temp-names) return prop))
12673 (found-node (or found
12674 (when (js2-object-node-p right)
12675 (js2-search-object-for-prop right
12676 temp-names)))))
12677 (if found-node (push found-node node-init))))))
12678 t))))
12679 node-init))
12680
12681 (defun js2-get-symbol-declaration (node name)
12682 "Find scope for NAME from NODE."
12683 (let ((scope (js2-get-defining-scope
12684 (or (js2-node-get-enclosing-scope node)
12685 node) name)))
12686 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12687
12688 (provide 'js2-mode)
12689
12690 ;;; js2-mode.el ends here