]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Merge branch 'dgreensp-object-rest-spread'
[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 ;; FIXME: We don't really need this anymore.
1080 "List of functions to be called after `js2-mode' or
1081 `js2-minor-mode' has initialized all variables, before parsing
1082 the buffer for the first time."
1083 :type 'hook
1084 :group 'js2-mode
1085 :version "20130608")
1086
1087 (defcustom js2-post-parse-callbacks nil
1088 "List of callback functions invoked after parsing finishes.
1089 Currently, the main use for this function is to add synthetic
1090 declarations to `js2-recorded-identifiers', which see."
1091 :type 'hook
1092 :group 'js2-mode)
1093
1094 (defcustom js2-build-imenu-callbacks nil
1095 "List of functions called during Imenu index generation.
1096 It's a good place to add additional entries to it, using
1097 `js2-record-imenu-entry'."
1098 :type 'hook
1099 :group 'js2-mode)
1100
1101 (defcustom js2-highlight-external-variables t
1102 "Non-nil to highlight undeclared variable identifiers.
1103 An undeclared variable is any variable not declared with var or let
1104 in the current scope or any lexically enclosing scope. If you use
1105 such a variable, then you are either expecting it to originate from
1106 another file, or you've got a potential bug."
1107 :type 'boolean
1108 :group 'js2-mode)
1109
1110 (defcustom js2-warn-about-unused-function-arguments nil
1111 "Non-nil to treat function arguments like declared-but-unused variables."
1112 :type 'booleanp
1113 :group 'js2-mode)
1114
1115 (defcustom js2-include-jslint-globals t
1116 "Non-nil to include the identifiers from JSLint global
1117 declaration (see http://www.jslint.com/lint.html#global) in the
1118 buffer-local externs list. See `js2-additional-externs' for more
1119 information."
1120 :type 'boolean
1121 :group 'js2-mode)
1122
1123 (defvar js2-mode-map
1124 (let ((map (make-sparse-keymap)))
1125 (define-key map [mouse-1] #'js2-mode-show-node)
1126 (define-key map (kbd "M-j") #'js2-line-break)
1127 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1128 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1129 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1130 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1131 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1132 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1133 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1134 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1135 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1136
1137 (define-key map [menu-bar javascript]
1138 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1139
1140 (define-key map [menu-bar javascript customize-js2-mode]
1141 '(menu-item "Customize js2-mode" js2-mode-customize
1142 :help "Customize the behavior of this mode"))
1143
1144 (define-key map [menu-bar javascript js2-force-refresh]
1145 '(menu-item "Force buffer refresh" js2-mode-reset
1146 :help "Re-parse the buffer from scratch"))
1147
1148 (define-key map [menu-bar javascript separator-2]
1149 '("--"))
1150
1151 (define-key map [menu-bar javascript next-error]
1152 '(menu-item "Next warning or error" next-error
1153 :enabled (and js2-mode-ast
1154 (or (js2-ast-root-errors js2-mode-ast)
1155 (js2-ast-root-warnings js2-mode-ast)))
1156 :help "Move to next warning or error"))
1157
1158 (define-key map [menu-bar javascript display-errors]
1159 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1160 :visible (not js2-mode-show-parse-errors)
1161 :help "Turn on display of warnings and errors"))
1162
1163 (define-key map [menu-bar javascript hide-errors]
1164 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1165 :visible js2-mode-show-parse-errors
1166 :help "Turn off display of warnings and errors"))
1167
1168 (define-key map [menu-bar javascript separator-1]
1169 '("--"))
1170
1171 (define-key map [menu-bar javascript js2-toggle-function]
1172 '(menu-item "Show/collapse element" js2-mode-toggle-element
1173 :help "Hide or show function body or comment"))
1174
1175 (define-key map [menu-bar javascript show-comments]
1176 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1177 :visible js2-mode-comments-hidden
1178 :help "Expand all hidden block comments"))
1179
1180 (define-key map [menu-bar javascript hide-comments]
1181 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1182 :visible (not js2-mode-comments-hidden)
1183 :help "Show block comments as /*...*/"))
1184
1185 (define-key map [menu-bar javascript show-all-functions]
1186 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1187 :visible js2-mode-functions-hidden
1188 :help "Expand all hidden function bodies"))
1189
1190 (define-key map [menu-bar javascript hide-all-functions]
1191 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1192 :visible (not js2-mode-functions-hidden)
1193 :help "Show {...} for all top-level function bodies"))
1194
1195 map)
1196 "Keymap used in `js2-mode' buffers.")
1197
1198 (defcustom js2-bounce-indent-p nil
1199 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1200 They will augment the default indent-line behavior with cycling
1201 among several computed alternatives. See the function
1202 `js2-bounce-indent' for details. The above commands will be
1203 bound to TAB and backtab."
1204 :type 'boolean
1205 :group 'js2-mode
1206 :set (lambda (sym value)
1207 (set-default sym value)
1208 (let ((map js2-mode-map))
1209 (if (not value)
1210 (progn
1211 (define-key map "\t" nil)
1212 (define-key map (kbd "<backtab>") nil))
1213 (define-key map "\t" #'js2-indent-bounce)
1214 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1215
1216 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1217
1218 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1219 "Matches a //-comment line. Must be first non-whitespace on line.
1220 First match-group is the leading whitespace.")
1221
1222 (defvar js2-mode-hook nil)
1223
1224 (js2-deflocal js2-mode-ast nil "Private variable.")
1225 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1226 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1227 (js2-deflocal js2-mode-parsing nil "Private variable.")
1228 (js2-deflocal js2-mode-node-overlay nil)
1229
1230 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1231 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1232
1233 (js2-deflocal js2-mode-fontifications nil "Private variable")
1234 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1235 (js2-deflocal js2-imenu-recorder nil "Private variable")
1236 (js2-deflocal js2-imenu-function-map nil "Private variable")
1237
1238 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1239 "Non-nil to emit status messages during parsing.")
1240
1241 (defvar js2-mode-functions-hidden nil "Private variable.")
1242 (defvar js2-mode-comments-hidden nil "Private variable.")
1243
1244 (defvar js2-mode-syntax-table
1245 (let ((table (make-syntax-table)))
1246 (c-populate-syntax-table table)
1247 (modify-syntax-entry ?` "\"" table)
1248 table)
1249 "Syntax table used in `js2-mode' buffers.")
1250
1251 (defvar js2-mode-abbrev-table nil
1252 "Abbrev table in use in `js2-mode' buffers.")
1253 (define-abbrev-table 'js2-mode-abbrev-table ())
1254
1255 (defvar js2-mode-pending-parse-callbacks nil
1256 "List of functions waiting to be notified that parse is finished.")
1257
1258 (defvar js2-mode-last-indented-line -1)
1259
1260 ;;; Localizable error and warning messages
1261
1262 ;; Messages are copied from Rhino's Messages.properties.
1263 ;; Many of the Java-specific messages have been elided.
1264 ;; Add any js2-specific ones at the end, so we can keep
1265 ;; this file synced with changes to Rhino's.
1266
1267 (defvar js2-message-table
1268 (make-hash-table :test 'equal :size 250)
1269 "Contains localized messages for `js2-mode'.")
1270
1271 ;; TODO(stevey): construct this table at compile-time.
1272 (defmacro js2-msg (key &rest strings)
1273 `(puthash ,key (concat ,@strings)
1274 js2-message-table))
1275
1276 (defun js2-get-msg (msg-key)
1277 "Look up a localized message.
1278 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1279 the correct number of ARGS must be provided."
1280 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1281 (args (if (listp msg-key) (cdr msg-key)))
1282 (msg (gethash key js2-message-table)))
1283 (if msg
1284 (apply #'format msg args)
1285 key))) ; default to showing the key
1286
1287 (js2-msg "msg.dup.parms"
1288 "Duplicate parameter name '%s'.")
1289
1290 (js2-msg "msg.too.big.jump"
1291 "Program too complex: jump offset too big.")
1292
1293 (js2-msg "msg.too.big.index"
1294 "Program too complex: internal index exceeds 64K limit.")
1295
1296 (js2-msg "msg.while.compiling.fn"
1297 "Encountered code generation error while compiling function '%s': %s")
1298
1299 (js2-msg "msg.while.compiling.script"
1300 "Encountered code generation error while compiling script: %s")
1301
1302 ;; Context
1303 (js2-msg "msg.ctor.not.found"
1304 "Constructor for '%s' not found.")
1305
1306 (js2-msg "msg.not.ctor"
1307 "'%s' is not a constructor.")
1308
1309 ;; FunctionObject
1310 (js2-msg "msg.varargs.ctor"
1311 "Method or constructor '%s' must be static "
1312 "with the signature (Context cx, Object[] args, "
1313 "Function ctorObj, boolean inNewExpr) "
1314 "to define a variable arguments constructor.")
1315
1316 (js2-msg "msg.varargs.fun"
1317 "Method '%s' must be static with the signature "
1318 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1319 "to define a variable arguments function.")
1320
1321 (js2-msg "msg.incompat.call"
1322 "Method '%s' called on incompatible object.")
1323
1324 (js2-msg "msg.bad.parms"
1325 "Unsupported parameter type '%s' in method '%s'.")
1326
1327 (js2-msg "msg.bad.method.return"
1328 "Unsupported return type '%s' in method '%s'.")
1329
1330 (js2-msg "msg.bad.ctor.return"
1331 "Construction of objects of type '%s' is not supported.")
1332
1333 (js2-msg "msg.no.overload"
1334 "Method '%s' occurs multiple times in class '%s'.")
1335
1336 (js2-msg "msg.method.not.found"
1337 "Method '%s' not found in '%s'.")
1338
1339 ;; IRFactory
1340
1341 (js2-msg "msg.bad.for.in.lhs"
1342 "Invalid left-hand side of for..in loop.")
1343
1344 (js2-msg "msg.mult.index"
1345 "Only one variable allowed in for..in loop.")
1346
1347 (js2-msg "msg.bad.for.in.destruct"
1348 "Left hand side of for..in loop must be an array of "
1349 "length 2 to accept key/value pair.")
1350
1351 (js2-msg "msg.cant.convert"
1352 "Can't convert to type '%s'.")
1353
1354 (js2-msg "msg.bad.assign.left"
1355 "Invalid assignment left-hand side.")
1356
1357 (js2-msg "msg.bad.decr"
1358 "Invalid decrement operand.")
1359
1360 (js2-msg "msg.bad.incr"
1361 "Invalid increment operand.")
1362
1363 (js2-msg "msg.bad.yield"
1364 "yield must be in a function.")
1365
1366 (js2-msg "msg.yield.parenthesized"
1367 "yield expression must be parenthesized.")
1368
1369 (js2-msg "msg.bad.await"
1370 "await must be in async functions.")
1371
1372 ;; NativeGlobal
1373 (js2-msg "msg.cant.call.indirect"
1374 "Function '%s' must be called directly, and not by way of a "
1375 "function of another name.")
1376
1377 (js2-msg "msg.eval.nonstring"
1378 "Calling eval() with anything other than a primitive "
1379 "string value will simply return the value. "
1380 "Is this what you intended?")
1381
1382 (js2-msg "msg.eval.nonstring.strict"
1383 "Calling eval() with anything other than a primitive "
1384 "string value is not allowed in strict mode.")
1385
1386 (js2-msg "msg.bad.destruct.op"
1387 "Invalid destructuring assignment operator")
1388
1389 ;; NativeCall
1390 (js2-msg "msg.only.from.new"
1391 "'%s' may only be invoked from a `new' expression.")
1392
1393 (js2-msg "msg.deprec.ctor"
1394 "The '%s' constructor is deprecated.")
1395
1396 ;; NativeFunction
1397 (js2-msg "msg.no.function.ref.found"
1398 "no source found to decompile function reference %s")
1399
1400 (js2-msg "msg.arg.isnt.array"
1401 "second argument to Function.prototype.apply must be an array")
1402
1403 ;; NativeGlobal
1404 (js2-msg "msg.bad.esc.mask"
1405 "invalid string escape mask")
1406
1407 ;; NativeRegExp
1408 (js2-msg "msg.bad.quant"
1409 "Invalid quantifier %s")
1410
1411 (js2-msg "msg.overlarge.backref"
1412 "Overly large back reference %s")
1413
1414 (js2-msg "msg.overlarge.min"
1415 "Overly large minimum %s")
1416
1417 (js2-msg "msg.overlarge.max"
1418 "Overly large maximum %s")
1419
1420 (js2-msg "msg.zero.quant"
1421 "Zero quantifier %s")
1422
1423 (js2-msg "msg.max.lt.min"
1424 "Maximum %s less than minimum")
1425
1426 (js2-msg "msg.unterm.quant"
1427 "Unterminated quantifier %s")
1428
1429 (js2-msg "msg.unterm.paren"
1430 "Unterminated parenthetical %s")
1431
1432 (js2-msg "msg.unterm.class"
1433 "Unterminated character class %s")
1434
1435 (js2-msg "msg.bad.range"
1436 "Invalid range in character class.")
1437
1438 (js2-msg "msg.trail.backslash"
1439 "Trailing \\ in regular expression.")
1440
1441 (js2-msg "msg.re.unmatched.right.paren"
1442 "unmatched ) in regular expression.")
1443
1444 (js2-msg "msg.no.regexp"
1445 "Regular expressions are not available.")
1446
1447 (js2-msg "msg.bad.backref"
1448 "back-reference exceeds number of capturing parentheses.")
1449
1450 (js2-msg "msg.bad.regexp.compile"
1451 "Only one argument may be specified if the first "
1452 "argument to RegExp.prototype.compile is a RegExp object.")
1453
1454 ;; Parser
1455 (js2-msg "msg.got.syntax.errors"
1456 "Compilation produced %s syntax errors.")
1457
1458 (js2-msg "msg.var.redecl"
1459 "Redeclaration of var %s.")
1460
1461 (js2-msg "msg.const.redecl"
1462 "TypeError: redeclaration of const %s.")
1463
1464 (js2-msg "msg.let.redecl"
1465 "TypeError: redeclaration of variable %s.")
1466
1467 (js2-msg "msg.parm.redecl"
1468 "TypeError: redeclaration of formal parameter %s.")
1469
1470 (js2-msg "msg.fn.redecl"
1471 "TypeError: redeclaration of function %s.")
1472
1473 (js2-msg "msg.let.decl.not.in.block"
1474 "SyntaxError: let declaration not directly within block")
1475
1476 (js2-msg "msg.mod.import.decl.at.top.level"
1477 "SyntaxError: import declarations may only appear at the top level")
1478
1479 (js2-msg "msg.mod.as.after.reserved.word"
1480 "SyntaxError: missing keyword 'as' after reserved word %s")
1481
1482 (js2-msg "msg.mod.rc.after.import.spec.list"
1483 "SyntaxError: missing '}' after module specifier list")
1484
1485 (js2-msg "msg.mod.from.after.import.spec.set"
1486 "SyntaxError: missing keyword 'from' after import specifier set")
1487
1488 (js2-msg "msg.mod.declaration.after.import"
1489 "SyntaxError: missing declaration after 'import' keyword")
1490
1491 (js2-msg "msg.mod.spec.after.from"
1492 "SyntaxError: missing module specifier after 'from' keyword")
1493
1494 (js2-msg "msg.mod.export.decl.at.top.level"
1495 "SyntaxError: export declarations may only appear at top level")
1496
1497 (js2-msg "msg.mod.rc.after.export.spec.list"
1498 "SyntaxError: missing '}' after export specifier list")
1499
1500 ;; NodeTransformer
1501 (js2-msg "msg.dup.label"
1502 "duplicated label")
1503
1504 (js2-msg "msg.undef.label"
1505 "undefined label")
1506
1507 (js2-msg "msg.bad.break"
1508 "unlabelled break must be inside loop or switch")
1509
1510 (js2-msg "msg.continue.outside"
1511 "continue must be inside loop")
1512
1513 (js2-msg "msg.continue.nonloop"
1514 "continue can only use labels of iteration statements")
1515
1516 (js2-msg "msg.bad.throw.eol"
1517 "Line terminator is not allowed between the throw "
1518 "keyword and throw expression.")
1519
1520 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1521 "function statement requires a name")
1522
1523 (js2-msg "msg.no.paren.parms"
1524 "missing ( before function parameters.")
1525
1526 (js2-msg "msg.no.parm"
1527 "missing formal parameter")
1528
1529 (js2-msg "msg.no.paren.after.parms"
1530 "missing ) after formal parameters")
1531
1532 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1533 "parameter without default follows parameter with default")
1534
1535 (js2-msg "msg.param.after.rest" ; added by js2-mode
1536 "parameter after rest parameter")
1537
1538 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1539 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1540
1541 (js2-msg "msg.no.brace.body"
1542 "missing '{' before function body")
1543
1544 (js2-msg "msg.no.brace.after.body"
1545 "missing } after function body")
1546
1547 (js2-msg "msg.no.paren.cond"
1548 "missing ( before condition")
1549
1550 (js2-msg "msg.no.paren.after.cond"
1551 "missing ) after condition")
1552
1553 (js2-msg "msg.no.semi.stmt"
1554 "missing ; before statement")
1555
1556 (js2-msg "msg.missing.semi"
1557 "missing ; after statement")
1558
1559 (js2-msg "msg.no.name.after.dot"
1560 "missing name after . operator")
1561
1562 (js2-msg "msg.no.name.after.coloncolon"
1563 "missing name after :: operator")
1564
1565 (js2-msg "msg.no.name.after.dotdot"
1566 "missing name after .. operator")
1567
1568 (js2-msg "msg.no.name.after.xmlAttr"
1569 "missing name after .@")
1570
1571 (js2-msg "msg.no.bracket.index"
1572 "missing ] in index expression")
1573
1574 (js2-msg "msg.no.paren.switch"
1575 "missing ( before switch expression")
1576
1577 (js2-msg "msg.no.paren.after.switch"
1578 "missing ) after switch expression")
1579
1580 (js2-msg "msg.no.brace.switch"
1581 "missing '{' before switch body")
1582
1583 (js2-msg "msg.bad.switch"
1584 "invalid switch statement")
1585
1586 (js2-msg "msg.no.colon.case"
1587 "missing : after case expression")
1588
1589 (js2-msg "msg.double.switch.default"
1590 "double default label in the switch statement")
1591
1592 (js2-msg "msg.no.while.do"
1593 "missing while after do-loop body")
1594
1595 (js2-msg "msg.no.paren.for"
1596 "missing ( after for")
1597
1598 (js2-msg "msg.no.semi.for"
1599 "missing ; after for-loop initializer")
1600
1601 (js2-msg "msg.no.semi.for.cond"
1602 "missing ; after for-loop condition")
1603
1604 (js2-msg "msg.in.after.for.name"
1605 "missing in or of after for")
1606
1607 (js2-msg "msg.no.paren.for.ctrl"
1608 "missing ) after for-loop control")
1609
1610 (js2-msg "msg.no.paren.with"
1611 "missing ( before with-statement object")
1612
1613 (js2-msg "msg.no.paren.after.with"
1614 "missing ) after with-statement object")
1615
1616 (js2-msg "msg.no.with.strict"
1617 "with statements not allowed in strict mode")
1618
1619 (js2-msg "msg.no.paren.after.let"
1620 "missing ( after let")
1621
1622 (js2-msg "msg.no.paren.let"
1623 "missing ) after variable list")
1624
1625 (js2-msg "msg.no.curly.let"
1626 "missing } after let statement")
1627
1628 (js2-msg "msg.bad.return"
1629 "invalid return")
1630
1631 (js2-msg "msg.no.brace.block"
1632 "missing } in compound statement")
1633
1634 (js2-msg "msg.bad.label"
1635 "invalid label")
1636
1637 (js2-msg "msg.bad.var"
1638 "missing variable name")
1639
1640 (js2-msg "msg.bad.var.init"
1641 "invalid variable initialization")
1642
1643 (js2-msg "msg.no.colon.cond"
1644 "missing : in conditional expression")
1645
1646 (js2-msg "msg.no.paren.arg"
1647 "missing ) after argument list")
1648
1649 (js2-msg "msg.no.bracket.arg"
1650 "missing ] after element list")
1651
1652 (js2-msg "msg.bad.prop"
1653 "invalid property id")
1654
1655 (js2-msg "msg.no.colon.prop"
1656 "missing : after property id")
1657
1658 (js2-msg "msg.no.brace.prop"
1659 "missing } after property list")
1660
1661 (js2-msg "msg.no.paren"
1662 "missing ) in parenthetical")
1663
1664 (js2-msg "msg.reserved.id"
1665 "'%s' is a reserved identifier")
1666
1667 (js2-msg "msg.no.paren.catch"
1668 "missing ( before catch-block condition")
1669
1670 (js2-msg "msg.bad.catchcond"
1671 "invalid catch block condition")
1672
1673 (js2-msg "msg.catch.unreachable"
1674 "any catch clauses following an unqualified catch are unreachable")
1675
1676 (js2-msg "msg.no.brace.try"
1677 "missing '{' before try block")
1678
1679 (js2-msg "msg.no.brace.catchblock"
1680 "missing '{' before catch-block body")
1681
1682 (js2-msg "msg.try.no.catchfinally"
1683 "'try' without 'catch' or 'finally'")
1684
1685 (js2-msg "msg.no.return.value"
1686 "function %s does not always return a value")
1687
1688 (js2-msg "msg.anon.no.return.value"
1689 "anonymous function does not always return a value")
1690
1691 (js2-msg "msg.return.inconsistent"
1692 "return statement is inconsistent with previous usage")
1693
1694 (js2-msg "msg.generator.returns"
1695 "TypeError: legacy generator function '%s' returns a value")
1696
1697 (js2-msg "msg.anon.generator.returns"
1698 "TypeError: anonymous legacy generator function returns a value")
1699
1700 (js2-msg "msg.syntax"
1701 "syntax error")
1702
1703 (js2-msg "msg.unexpected.eof"
1704 "Unexpected end of file")
1705
1706 (js2-msg "msg.XML.bad.form"
1707 "illegally formed XML syntax")
1708
1709 (js2-msg "msg.XML.not.available"
1710 "XML runtime not available")
1711
1712 (js2-msg "msg.too.deep.parser.recursion"
1713 "Too deep recursion while parsing")
1714
1715 (js2-msg "msg.no.side.effects"
1716 "Code has no side effects")
1717
1718 (js2-msg "msg.extra.trailing.comma"
1719 "Trailing comma is not supported in some browsers")
1720
1721 (js2-msg "msg.array.trailing.comma"
1722 "Trailing comma yields different behavior across browsers")
1723
1724 (js2-msg "msg.equal.as.assign"
1725 (concat "Test for equality (==) mistyped as assignment (=)?"
1726 " (parenthesize to suppress warning)"))
1727
1728 (js2-msg "msg.var.hides.arg"
1729 "Variable %s hides argument")
1730
1731 (js2-msg "msg.destruct.assign.no.init"
1732 "Missing = in destructuring declaration")
1733
1734 (js2-msg "msg.init.no.destruct"
1735 "Binding initializer not in destructuring assignment")
1736
1737 (js2-msg "msg.no.octal.strict"
1738 "Octal numbers prohibited in strict mode.")
1739
1740 (js2-msg "msg.dup.obj.lit.prop.strict"
1741 "Property '%s' already defined in this object literal.")
1742
1743 (js2-msg "msg.dup.param.strict"
1744 "Parameter '%s' already declared in this function.")
1745
1746 (js2-msg "msg.bad.id.strict"
1747 "'%s' is not a valid identifier for this use in strict mode.")
1748
1749 ;; ScriptRuntime
1750 (js2-msg "msg.no.properties"
1751 "%s has no properties.")
1752
1753 (js2-msg "msg.invalid.iterator"
1754 "Invalid iterator value")
1755
1756 (js2-msg "msg.iterator.primitive"
1757 "__iterator__ returned a primitive value")
1758
1759 (js2-msg "msg.assn.create.strict"
1760 "Assignment to undeclared variable %s")
1761
1762 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1763 "Undeclared variable or function '%s'")
1764
1765 (js2-msg "msg.unused.variable" ; added by js2-mode
1766 "Unused variable or function '%s'")
1767
1768 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1769 "Variable '%s' referenced but never initialized")
1770
1771 (js2-msg "msg.ref.undefined.prop"
1772 "Reference to undefined property '%s'")
1773
1774 (js2-msg "msg.prop.not.found"
1775 "Property %s not found.")
1776
1777 (js2-msg "msg.invalid.type"
1778 "Invalid JavaScript value of type %s")
1779
1780 (js2-msg "msg.primitive.expected"
1781 "Primitive type expected (had %s instead)")
1782
1783 (js2-msg "msg.namespace.expected"
1784 "Namespace object expected to left of :: (found %s instead)")
1785
1786 (js2-msg "msg.null.to.object"
1787 "Cannot convert null to an object.")
1788
1789 (js2-msg "msg.undef.to.object"
1790 "Cannot convert undefined to an object.")
1791
1792 (js2-msg "msg.cyclic.value"
1793 "Cyclic %s value not allowed.")
1794
1795 (js2-msg "msg.is.not.defined"
1796 "'%s' is not defined.")
1797
1798 (js2-msg "msg.undef.prop.read"
1799 "Cannot read property '%s' from %s")
1800
1801 (js2-msg "msg.undef.prop.write"
1802 "Cannot set property '%s' of %s to '%s'")
1803
1804 (js2-msg "msg.undef.prop.delete"
1805 "Cannot delete property '%s' of %s")
1806
1807 (js2-msg "msg.undef.method.call"
1808 "Cannot call method '%s' of %s")
1809
1810 (js2-msg "msg.undef.with"
1811 "Cannot apply 'with' to %s")
1812
1813 (js2-msg "msg.isnt.function"
1814 "%s is not a function, it is %s.")
1815
1816 (js2-msg "msg.isnt.function.in"
1817 "Cannot call property %s in object %s. "
1818 "It is not a function, it is '%s'.")
1819
1820 (js2-msg "msg.function.not.found"
1821 "Cannot find function %s.")
1822
1823 (js2-msg "msg.function.not.found.in"
1824 "Cannot find function %s in object %s.")
1825
1826 (js2-msg "msg.isnt.xml.object"
1827 "%s is not an xml object.")
1828
1829 (js2-msg "msg.no.ref.to.get"
1830 "%s is not a reference to read reference value.")
1831
1832 (js2-msg "msg.no.ref.to.set"
1833 "%s is not a reference to set reference value to %s.")
1834
1835 (js2-msg "msg.no.ref.from.function"
1836 "Function %s can not be used as the left-hand "
1837 "side of assignment or as an operand of ++ or -- operator.")
1838
1839 (js2-msg "msg.bad.default.value"
1840 "Object's getDefaultValue() method returned an object.")
1841
1842 (js2-msg "msg.instanceof.not.object"
1843 "Can't use instanceof on a non-object.")
1844
1845 (js2-msg "msg.instanceof.bad.prototype"
1846 "'prototype' property of %s is not an object.")
1847
1848 (js2-msg "msg.bad.radix"
1849 "illegal radix %s.")
1850
1851 ;; ScriptableObject
1852 (js2-msg "msg.default.value"
1853 "Cannot find default value for object.")
1854
1855 (js2-msg "msg.zero.arg.ctor"
1856 "Cannot load class '%s' which has no zero-parameter constructor.")
1857
1858 (js2-msg "msg.ctor.multiple.parms"
1859 "Can't define constructor or class %s since more than "
1860 "one constructor has multiple parameters.")
1861
1862 (js2-msg "msg.extend.scriptable"
1863 "%s must extend ScriptableObject in order to define property %s.")
1864
1865 (js2-msg "msg.bad.getter.parms"
1866 "In order to define a property, getter %s must have zero "
1867 "parameters or a single ScriptableObject parameter.")
1868
1869 (js2-msg "msg.obj.getter.parms"
1870 "Expected static or delegated getter %s to take "
1871 "a ScriptableObject parameter.")
1872
1873 (js2-msg "msg.getter.static"
1874 "Getter and setter must both be static or neither be static.")
1875
1876 (js2-msg "msg.setter.return"
1877 "Setter must have void return type: %s")
1878
1879 (js2-msg "msg.setter2.parms"
1880 "Two-parameter setter must take a ScriptableObject as "
1881 "its first parameter.")
1882
1883 (js2-msg "msg.setter1.parms"
1884 "Expected single parameter setter for %s")
1885
1886 (js2-msg "msg.setter2.expected"
1887 "Expected static or delegated setter %s to take two parameters.")
1888
1889 (js2-msg "msg.setter.parms"
1890 "Expected either one or two parameters for setter.")
1891
1892 (js2-msg "msg.setter.bad.type"
1893 "Unsupported parameter type '%s' in setter '%s'.")
1894
1895 (js2-msg "msg.add.sealed"
1896 "Cannot add a property to a sealed object: %s.")
1897
1898 (js2-msg "msg.remove.sealed"
1899 "Cannot remove a property from a sealed object: %s.")
1900
1901 (js2-msg "msg.modify.sealed"
1902 "Cannot modify a property of a sealed object: %s.")
1903
1904 (js2-msg "msg.modify.readonly"
1905 "Cannot modify readonly property: %s.")
1906
1907 ;; TokenStream
1908 (js2-msg "msg.missing.exponent"
1909 "missing exponent")
1910
1911 (js2-msg "msg.caught.nfe"
1912 "number format error")
1913
1914 (js2-msg "msg.unterminated.string.lit"
1915 "unterminated string literal")
1916
1917 (js2-msg "msg.unterminated.comment"
1918 "unterminated comment")
1919
1920 (js2-msg "msg.unterminated.re.lit"
1921 "unterminated regular expression literal")
1922
1923 (js2-msg "msg.invalid.re.flag"
1924 "invalid flag after regular expression")
1925
1926 (js2-msg "msg.no.re.input.for"
1927 "no input for %s")
1928
1929 (js2-msg "msg.illegal.character"
1930 "illegal character")
1931
1932 (js2-msg "msg.invalid.escape"
1933 "invalid Unicode escape sequence")
1934
1935 (js2-msg "msg.bad.namespace"
1936 "not a valid default namespace statement. "
1937 "Syntax is: default xml namespace = EXPRESSION;")
1938
1939 ;; TokensStream warnings
1940 (js2-msg "msg.bad.octal.literal"
1941 "illegal octal literal digit %s; "
1942 "interpreting it as a decimal digit")
1943
1944 (js2-msg "msg.missing.hex.digits"
1945 "missing hexadecimal digits after '0x'")
1946
1947 (js2-msg "msg.missing.binary.digits"
1948 "missing binary digits after '0b'")
1949
1950 (js2-msg "msg.missing.octal.digits"
1951 "missing octal digits after '0o'")
1952
1953 (js2-msg "msg.script.is.not.constructor"
1954 "Script objects are not constructors.")
1955
1956 ;; Arrays
1957 (js2-msg "msg.arraylength.bad"
1958 "Inappropriate array length.")
1959
1960 ;; Arrays
1961 (js2-msg "msg.arraylength.too.big"
1962 "Array length %s exceeds supported capacity limit.")
1963
1964 ;; URI
1965 (js2-msg "msg.bad.uri"
1966 "Malformed URI sequence.")
1967
1968 ;; Number
1969 (js2-msg "msg.bad.precision"
1970 "Precision %s out of range.")
1971
1972 ;; NativeGenerator
1973 (js2-msg "msg.send.newborn"
1974 "Attempt to send value to newborn generator")
1975
1976 (js2-msg "msg.already.exec.gen"
1977 "Already executing generator")
1978
1979 (js2-msg "msg.StopIteration.invalid"
1980 "StopIteration may not be changed to an arbitrary object.")
1981
1982 ;; Interpreter
1983 (js2-msg "msg.yield.closing"
1984 "Yield from closing generator")
1985
1986 ;; Classes
1987 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1988 "class statement requires a name")
1989
1990 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1991 "unexpected ',' between class properties")
1992
1993 (js2-msg "msg.unexpected.static" ; added by js2-mode
1994 "unexpected 'static'")
1995
1996 (js2-msg "msg.missing.extends" ; added by js2-mode
1997 "name is required after extends")
1998
1999 (js2-msg "msg.no.brace.class" ; added by js2-mode
2000 "missing '{' before class body")
2001
2002 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2003 "missing ']' after computed property expression")
2004
2005 ;;; Tokens Buffer
2006
2007 (defconst js2-ti-max-lookahead 2)
2008 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2009
2010 (defun js2-new-token (offset)
2011 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2012 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2013 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2014 token))
2015
2016 (defsubst js2-current-token ()
2017 (aref js2-ti-tokens js2-ti-tokens-cursor))
2018
2019 (defsubst js2-current-token-string ()
2020 (js2-token-string (js2-current-token)))
2021
2022 (defsubst js2-current-token-type ()
2023 (js2-token-type (js2-current-token)))
2024
2025 (defsubst js2-current-token-beg ()
2026 (js2-token-beg (js2-current-token)))
2027
2028 (defsubst js2-current-token-end ()
2029 (js2-token-end (js2-current-token)))
2030
2031 (defun js2-current-token-len ()
2032 (let ((token (js2-current-token)))
2033 (- (js2-token-end token)
2034 (js2-token-beg token))))
2035
2036 (defun js2-ts-seek (state)
2037 (setq js2-ts-lineno (js2-ts-state-lineno state)
2038 js2-ts-cursor (js2-ts-state-cursor state)
2039 js2-ti-tokens (js2-ts-state-tokens state)
2040 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2041 js2-ti-lookahead (js2-ts-state-lookahead state)))
2042
2043 ;;; Utilities
2044
2045 (defun js2-delete-if (predicate list)
2046 "Remove all items satisfying PREDICATE in LIST."
2047 (cl-loop for item in list
2048 if (not (funcall predicate item))
2049 collect item))
2050
2051 (defun js2-position (element list)
2052 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2053 Returns nil if element is not found in the list."
2054 (let ((count 0)
2055 found)
2056 (while (and list (not found))
2057 (if (eq element (car list))
2058 (setq found t)
2059 (setq count (1+ count)
2060 list (cdr list))))
2061 (if found count)))
2062
2063 (defun js2-find-if (predicate list)
2064 "Find first item satisfying PREDICATE in LIST."
2065 (let (result)
2066 (while (and list (not result))
2067 (if (funcall predicate (car list))
2068 (setq result (car list)))
2069 (setq list (cdr list)))
2070 result))
2071
2072 (defmacro js2-time (form)
2073 "Evaluate FORM, discard result, and return elapsed time in sec."
2074 (declare (debug t))
2075 (let ((beg (make-symbol "--js2-time-beg--")))
2076 `(let ((,beg (current-time)))
2077 ,form
2078 (/ (truncate (* (- (float-time (current-time))
2079 (float-time ,beg))
2080 10000))
2081 10000.0))))
2082
2083 (defsubst js2-same-line (pos)
2084 "Return t if POS is on the same line as current point."
2085 (and (>= pos (point-at-bol))
2086 (<= pos (point-at-eol))))
2087
2088 (defun js2-code-bug ()
2089 "Signal an error when we encounter an unexpected code path."
2090 (error "failed assertion"))
2091
2092 (defsubst js2-record-text-property (beg end prop value)
2093 "Record a text property to set when parsing finishes."
2094 (push (list beg end prop value) js2-mode-deferred-properties))
2095
2096 ;; I'd like to associate errors with nodes, but for now the
2097 ;; easiest thing to do is get the context info from the last token.
2098 (defun js2-record-parse-error (msg &optional arg pos len)
2099 (push (list (list msg arg)
2100 (or pos (js2-current-token-beg))
2101 (or len (js2-current-token-len)))
2102 js2-parsed-errors))
2103
2104 (defun js2-report-error (msg &optional msg-arg pos len)
2105 "Signal a syntax error or record a parse error."
2106 (if js2-recover-from-parse-errors
2107 (js2-record-parse-error msg msg-arg pos len)
2108 (signal 'js2-syntax-error
2109 (list msg
2110 js2-ts-lineno
2111 (save-excursion
2112 (goto-char js2-ts-cursor)
2113 (current-column))
2114 js2-ts-hit-eof))))
2115
2116 (defun js2-report-warning (msg &optional msg-arg pos len face)
2117 (if js2-compiler-report-warning-as-error
2118 (js2-report-error msg msg-arg pos len)
2119 (push (list (list msg msg-arg)
2120 (or pos (js2-current-token-beg))
2121 (or len (js2-current-token-len))
2122 face)
2123 js2-parsed-warnings)))
2124
2125 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2126 (if js2-compiler-strict-mode
2127 (js2-report-warning msg-id msg-arg beg
2128 (and beg end (- end beg)))))
2129
2130 (put 'js2-syntax-error 'error-conditions
2131 '(error syntax-error js2-syntax-error))
2132 (put 'js2-syntax-error 'error-message "Syntax error")
2133
2134 (put 'js2-parse-error 'error-conditions
2135 '(error parse-error js2-parse-error))
2136 (put 'js2-parse-error 'error-message "Parse error")
2137
2138 (defmacro js2-clear-flag (flags flag)
2139 `(setq ,flags (logand ,flags (lognot ,flag))))
2140
2141 (defmacro js2-set-flag (flags flag)
2142 "Logical-or FLAG into FLAGS."
2143 `(setq ,flags (logior ,flags ,flag)))
2144
2145 (defsubst js2-flag-set-p (flags flag)
2146 (/= 0 (logand flags flag)))
2147
2148 (defsubst js2-flag-not-set-p (flags flag)
2149 (zerop (logand flags flag)))
2150
2151 ;;; AST struct and function definitions
2152
2153 ;; flags for ast node property 'member-type (used for e4x operators)
2154 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2155 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2156 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2157
2158 (defsubst js2-relpos (pos anchor)
2159 "Convert POS to be relative to ANCHOR.
2160 If POS is nil, returns nil."
2161 (and pos (- pos anchor)))
2162
2163 (defun js2-make-pad (indent)
2164 (if (zerop indent)
2165 ""
2166 (make-string (* indent js2-basic-offset) ? )))
2167
2168 (defun js2-visit-ast (node callback)
2169 "Visit every node in ast NODE with visitor CALLBACK.
2170
2171 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2172 called twice: once to visit the node, and again after all the node's
2173 children have been processed. The END-P argument is nil on the first
2174 call and non-nil on the second call. The return value of the callback
2175 affects the traversal: if non-nil, the children of NODE are processed.
2176 If the callback returns nil, or if the node has no children, then the
2177 callback is called immediately with a non-nil END-P argument.
2178
2179 The node traversal is approximately lexical-order, although there
2180 are currently no guarantees around this."
2181 (when node
2182 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2183 ;; visit the node
2184 (when (funcall callback node nil)
2185 ;; visit the kids
2186 (cond
2187 ((eq vfunc 'js2-visit-none)
2188 nil) ; don't even bother calling it
2189 ;; Each AST node type has to define a `js2-visitor' function
2190 ;; that takes a node and a callback, and calls `js2-visit-ast'
2191 ;; on each child of the node.
2192 (vfunc
2193 (funcall vfunc node callback))
2194 (t
2195 (error "%s does not define a visitor-traversal function"
2196 (aref node 0)))))
2197 ;; call the end-visit
2198 (funcall callback node t))))
2199
2200 (cl-defstruct (js2-node
2201 (:constructor nil)) ; abstract
2202 "Base AST node type."
2203 (type -1) ; token type
2204 (pos -1) ; start position of this AST node in parsed input
2205 (len 1) ; num characters spanned by the node
2206 props ; optional node property list (an alist)
2207 parent) ; link to parent node; null for root
2208
2209 (defsubst js2-node-get-prop (node prop &optional default)
2210 (or (cadr (assoc prop (js2-node-props node))) default))
2211
2212 (defsubst js2-node-set-prop (node prop value)
2213 (setf (js2-node-props node)
2214 (cons (list prop value) (js2-node-props node))))
2215
2216 (defun js2-fixup-starts (n nodes)
2217 "Adjust the start positions of NODES to be relative to N.
2218 Any node in the list may be nil, for convenience."
2219 (dolist (node nodes)
2220 (when node
2221 (setf (js2-node-pos node) (- (js2-node-pos node)
2222 (js2-node-pos n))))))
2223
2224 (defun js2-node-add-children (parent &rest nodes)
2225 "Set parent node of NODES to PARENT, and return PARENT.
2226 Does nothing if we're not recording parent links.
2227 If any given node in NODES is nil, doesn't record that link."
2228 (js2-fixup-starts parent nodes)
2229 (dolist (node nodes)
2230 (and node
2231 (setf (js2-node-parent node) parent))))
2232
2233 ;; Non-recursive since it's called a frightening number of times.
2234 (defun js2-node-abs-pos (n)
2235 (let ((pos (js2-node-pos n)))
2236 (while (setq n (js2-node-parent n))
2237 (setq pos (+ pos (js2-node-pos n))))
2238 pos))
2239
2240 (defsubst js2-node-abs-end (n)
2241 "Return absolute buffer position of end of N."
2242 (+ (js2-node-abs-pos n) (js2-node-len n)))
2243
2244 ;; It's important to make sure block nodes have a Lisp list for the
2245 ;; child nodes, to limit printing recursion depth in an AST that
2246 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2247 ;; a sufficiently large vector tree.
2248
2249 (cl-defstruct (js2-block-node
2250 (:include js2-node)
2251 (:constructor nil)
2252 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2253 (pos (js2-current-token-beg))
2254 len
2255 props
2256 kids)))
2257 "A block of statements."
2258 kids) ; a Lisp list of the child statement nodes
2259
2260 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2261 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2262
2263 (defun js2-visit-block (ast callback)
2264 "Visit the `js2-block-node' children of AST."
2265 (dolist (kid (js2-block-node-kids ast))
2266 (js2-visit-ast kid callback)))
2267
2268 (defun js2-print-block (n i)
2269 (let ((pad (js2-make-pad i)))
2270 (insert pad "{\n")
2271 (dolist (kid (js2-block-node-kids n))
2272 (js2-print-ast kid (1+ i)))
2273 (insert pad "}")))
2274
2275 (cl-defstruct (js2-scope
2276 (:include js2-block-node)
2277 (:constructor nil)
2278 (:constructor make-js2-scope (&key (type js2-BLOCK)
2279 (pos (js2-current-token-beg))
2280 len
2281 kids)))
2282 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2283 ;; I don't have one of those handy, so I'll use an alist for now.
2284 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2285 ;; and is much lighter-weight to construct (both CPU and mem).
2286 ;; The keys are interned strings (symbols) for faster lookup.
2287 ;; Should switch to hybrid alist/hashtable eventually.
2288 symbol-table ; an alist of (symbol . js2-symbol)
2289 parent-scope ; a `js2-scope'
2290 top) ; top-level `js2-scope' (script/function)
2291
2292 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2293 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2294
2295 (defun js2-node-get-enclosing-scope (node)
2296 "Return the innermost `js2-scope' node surrounding NODE.
2297 Returns nil if there is no enclosing scope node."
2298 (while (and (setq node (js2-node-parent node))
2299 (not (js2-scope-p node))))
2300 node)
2301
2302 (defun js2-get-defining-scope (scope name &optional point)
2303 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2304 Returns `js2-scope' in which NAME is defined, or nil if not found.
2305
2306 If POINT is non-nil, and if the found declaration type is
2307 `js2-LET', also check that the declaration node is before POINT."
2308 (let ((sym (if (symbolp name)
2309 name
2310 (intern name)))
2311 result
2312 (continue t))
2313 (while (and scope continue)
2314 (if (or
2315 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2316 (and entry
2317 (or (not point)
2318 (not (eq js2-LET (js2-symbol-decl-type entry)))
2319 (>= point
2320 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2321 (and (eq sym 'arguments)
2322 (js2-function-node-p scope)))
2323 (setq continue nil
2324 result scope)
2325 (setq scope (js2-scope-parent-scope scope))))
2326 result))
2327
2328 (defun js2-scope-get-symbol (scope name)
2329 "Return symbol table entry for NAME in SCOPE.
2330 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2331 (and (js2-scope-symbol-table scope)
2332 (cdr (assq (if (symbolp name)
2333 name
2334 (intern name))
2335 (js2-scope-symbol-table scope)))))
2336
2337 (defun js2-scope-put-symbol (scope name symbol)
2338 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2339 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2340 (let* ((table (js2-scope-symbol-table scope))
2341 (sym (if (symbolp name) name (intern name)))
2342 (entry (assq sym table)))
2343 (if entry
2344 (setcdr entry symbol)
2345 (push (cons sym symbol)
2346 (js2-scope-symbol-table scope)))))
2347
2348 (cl-defstruct (js2-symbol
2349 (:constructor nil)
2350 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2351 "A symbol table entry."
2352 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2353 ;; js2-LET, or js2-CONST
2354 decl-type
2355 name ; string
2356 ast-node) ; a `js2-node'
2357
2358 (cl-defstruct (js2-error-node
2359 (:include js2-node)
2360 (:constructor nil) ; silence emacs21 byte-compiler
2361 (:constructor make-js2-error-node (&key (type js2-ERROR)
2362 (pos (js2-current-token-beg))
2363 len)))
2364 "AST node representing a parse error.")
2365
2366 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2367 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2368
2369 (cl-defstruct (js2-script-node
2370 (:include js2-scope)
2371 (:constructor nil)
2372 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2373 (pos (js2-current-token-beg))
2374 len
2375 ;; FIXME: What are those?
2376 var-decls
2377 fun-decls)))
2378 functions ; Lisp list of nested functions
2379 regexps ; Lisp list of (string . flags)
2380 symbols ; alist (every symbol gets unique index)
2381 (param-count 0)
2382 var-names ; vector of string names
2383 consts ; bool-vector matching var-decls
2384 (temp-number 0)) ; for generating temp variables
2385
2386 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2387 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2388
2389 (defun js2-print-script (node indent)
2390 (dolist (kid (js2-block-node-kids node))
2391 (js2-print-ast kid indent)))
2392
2393 (cl-defstruct (js2-ast-root
2394 (:include js2-script-node)
2395 (:constructor nil)
2396 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2397 (pos (js2-current-token-beg))
2398 len
2399 buffer)))
2400 "The root node of a js2 AST."
2401 buffer ; the source buffer from which the code was parsed
2402 comments ; a Lisp list of comments, ordered by start position
2403 errors ; a Lisp list of errors found during parsing
2404 warnings ; a Lisp list of warnings found during parsing
2405 node-count) ; number of nodes in the tree, including the root
2406
2407 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2408 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2409
2410 (defun js2-visit-ast-root (ast callback)
2411 (dolist (kid (js2-ast-root-kids ast))
2412 (js2-visit-ast kid callback))
2413 (dolist (comment (js2-ast-root-comments ast))
2414 (js2-visit-ast comment callback)))
2415
2416 (cl-defstruct (js2-comment-node
2417 (:include js2-node)
2418 (:constructor nil)
2419 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2420 (pos (js2-current-token-beg))
2421 len
2422 format)))
2423 format) ; 'line, 'block, 'jsdoc or 'html
2424
2425 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2426 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2427
2428 (defun js2-print-comment (n i)
2429 ;; We really ought to link end-of-line comments to their nodes.
2430 ;; Or maybe we could add a new comment type, 'endline.
2431 (insert (js2-make-pad i)
2432 (js2-node-string n)))
2433
2434 (cl-defstruct (js2-expr-stmt-node
2435 (:include js2-node)
2436 (:constructor nil)
2437 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2438 (pos js2-ts-cursor)
2439 len
2440 expr)))
2441 "An expression statement."
2442 expr)
2443
2444 (defsubst js2-expr-stmt-node-set-has-result (node)
2445 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2446 (setf (js2-node-type node) js2-EXPR_RESULT))
2447
2448 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2449 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2450
2451 (defun js2-visit-expr-stmt-node (n v)
2452 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2453
2454 (defun js2-print-expr-stmt-node (n indent)
2455 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2456 (insert ";\n"))
2457
2458 (cl-defstruct (js2-loop-node
2459 (:include js2-scope)
2460 (:constructor nil))
2461 "Abstract supertype of loop nodes."
2462 body ; a `js2-block-node'
2463 lp ; position of left-paren, nil if omitted
2464 rp) ; position of right-paren, nil if omitted
2465
2466 (cl-defstruct (js2-do-node
2467 (:include js2-loop-node)
2468 (:constructor nil)
2469 (:constructor make-js2-do-node (&key (type js2-DO)
2470 (pos (js2-current-token-beg))
2471 len
2472 body
2473 condition
2474 while-pos
2475 lp
2476 rp)))
2477 "AST node for do-loop."
2478 condition ; while (expression)
2479 while-pos) ; buffer position of 'while' keyword
2480
2481 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2482 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2483
2484 (defun js2-visit-do-node (n v)
2485 (js2-visit-ast (js2-do-node-body n) v)
2486 (js2-visit-ast (js2-do-node-condition n) v))
2487
2488 (defun js2-print-do-node (n i)
2489 (let ((pad (js2-make-pad i)))
2490 (insert pad "do {\n")
2491 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2492 (js2-print-ast kid (1+ i)))
2493 (insert pad "} while (")
2494 (js2-print-ast (js2-do-node-condition n) 0)
2495 (insert ");\n")))
2496
2497 (cl-defstruct (js2-export-node
2498 (:include js2-node)
2499 (:constructor nil)
2500 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2501 (pos (js2-current-token-beg))
2502 len
2503 exports-list
2504 from-clause
2505 declaration
2506 default)))
2507 "AST node for an export statement. There are many things that can be exported,
2508 so many of its properties will be nil.
2509 "
2510 exports-list ; lisp list of js2-export-binding-node to export
2511 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2512 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2513 default) ; js2-function-node or js2-assign-node
2514
2515 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2516 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2517
2518 (defun js2-visit-export-node (n v)
2519 (let ((exports-list (js2-export-node-exports-list n))
2520 (from (js2-export-node-from-clause n))
2521 (declaration (js2-export-node-declaration n))
2522 (default (js2-export-node-default n)))
2523 (when exports-list
2524 (dolist (export exports-list)
2525 (js2-visit-ast export v)))
2526 (when from
2527 (js2-visit-ast from v))
2528 (when declaration
2529 (js2-visit-ast declaration v))
2530 (when default
2531 (js2-visit-ast default v))))
2532
2533 (defun js2-print-export-node (n i)
2534 (let ((pad (js2-make-pad i))
2535 (exports-list (js2-export-node-exports-list n))
2536 (from (js2-export-node-from-clause n))
2537 (declaration (js2-export-node-declaration n))
2538 (default (js2-export-node-default n)))
2539 (insert pad "export ")
2540 (cond
2541 (default
2542 (insert "default ")
2543 (js2-print-ast default i))
2544 (declaration
2545 (js2-print-ast declaration i))
2546 ((and exports-list from)
2547 (js2-print-named-imports exports-list)
2548 (insert " ")
2549 (js2-print-from-clause from))
2550 (from
2551 (insert "* ")
2552 (js2-print-from-clause from))
2553 (exports-list
2554 (js2-print-named-imports exports-list)))
2555 (unless (or (and default (not (js2-assign-node-p default)))
2556 (and declaration (or (js2-function-node-p declaration)
2557 (js2-class-node-p declaration))))
2558 (insert ";\n"))))
2559
2560 (cl-defstruct (js2-while-node
2561 (:include js2-loop-node)
2562 (:constructor nil)
2563 (:constructor make-js2-while-node (&key (type js2-WHILE)
2564 (pos (js2-current-token-beg))
2565 len body
2566 condition lp
2567 rp)))
2568 "AST node for while-loop."
2569 condition) ; while-condition
2570
2571 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2572 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2573
2574 (defun js2-visit-while-node (n v)
2575 (js2-visit-ast (js2-while-node-condition n) v)
2576 (js2-visit-ast (js2-while-node-body n) v))
2577
2578 (defun js2-print-while-node (n i)
2579 (let ((pad (js2-make-pad i)))
2580 (insert pad "while (")
2581 (js2-print-ast (js2-while-node-condition n) 0)
2582 (insert ") {\n")
2583 (js2-print-body (js2-while-node-body n) (1+ i))
2584 (insert pad "}\n")))
2585
2586 (cl-defstruct (js2-for-node
2587 (:include js2-loop-node)
2588 (:constructor nil)
2589 (:constructor make-js2-for-node (&key (type js2-FOR)
2590 (pos js2-ts-cursor)
2591 len body init
2592 condition
2593 update lp rp)))
2594 "AST node for a C-style for-loop."
2595 init ; initialization expression
2596 condition ; loop condition
2597 update) ; update clause
2598
2599 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2600 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2601
2602 (defun js2-visit-for-node (n v)
2603 (js2-visit-ast (js2-for-node-init n) v)
2604 (js2-visit-ast (js2-for-node-condition n) v)
2605 (js2-visit-ast (js2-for-node-update n) v)
2606 (js2-visit-ast (js2-for-node-body n) v))
2607
2608 (defun js2-print-for-node (n i)
2609 (let ((pad (js2-make-pad i)))
2610 (insert pad "for (")
2611 (js2-print-ast (js2-for-node-init n) 0)
2612 (insert "; ")
2613 (js2-print-ast (js2-for-node-condition n) 0)
2614 (insert "; ")
2615 (js2-print-ast (js2-for-node-update n) 0)
2616 (insert ") {\n")
2617 (js2-print-body (js2-for-node-body n) (1+ i))
2618 (insert pad "}\n")))
2619
2620 (cl-defstruct (js2-for-in-node
2621 (:include js2-loop-node)
2622 (:constructor nil)
2623 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2624 (pos js2-ts-cursor)
2625 len body
2626 iterator
2627 object
2628 in-pos
2629 each-pos
2630 foreach-p forof-p
2631 lp rp)))
2632 "AST node for a for..in loop."
2633 iterator ; [var] foo in ...
2634 object ; object over which we're iterating
2635 in-pos ; buffer position of 'in' keyword
2636 each-pos ; buffer position of 'each' keyword, if foreach-p
2637 foreach-p ; t if it's a for-each loop
2638 forof-p) ; t if it's a for-of loop
2639
2640 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2641 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2642
2643 (defun js2-visit-for-in-node (n v)
2644 (js2-visit-ast (js2-for-in-node-iterator n) v)
2645 (js2-visit-ast (js2-for-in-node-object n) v)
2646 (js2-visit-ast (js2-for-in-node-body n) v))
2647
2648 (defun js2-print-for-in-node (n i)
2649 (let ((pad (js2-make-pad i))
2650 (foreach (js2-for-in-node-foreach-p n))
2651 (forof (js2-for-in-node-forof-p n)))
2652 (insert pad "for ")
2653 (if foreach
2654 (insert "each "))
2655 (insert "(")
2656 (js2-print-ast (js2-for-in-node-iterator n) 0)
2657 (insert (if forof " of " " in "))
2658 (js2-print-ast (js2-for-in-node-object n) 0)
2659 (insert ") {\n")
2660 (js2-print-body (js2-for-in-node-body n) (1+ i))
2661 (insert pad "}\n")))
2662
2663 (cl-defstruct (js2-return-node
2664 (:include js2-node)
2665 (:constructor nil)
2666 (:constructor make-js2-return-node (&key (type js2-RETURN)
2667 (pos js2-ts-cursor)
2668 len
2669 retval)))
2670 "AST node for a return statement."
2671 retval) ; expression to return, or 'undefined
2672
2673 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2674 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2675
2676 (defun js2-visit-return-node (n v)
2677 (js2-visit-ast (js2-return-node-retval n) v))
2678
2679 (defun js2-print-return-node (n i)
2680 (insert (js2-make-pad i) "return")
2681 (when (js2-return-node-retval n)
2682 (insert " ")
2683 (js2-print-ast (js2-return-node-retval n) 0))
2684 (insert ";\n"))
2685
2686 (cl-defstruct (js2-if-node
2687 (:include js2-node)
2688 (:constructor nil)
2689 (:constructor make-js2-if-node (&key (type js2-IF)
2690 (pos js2-ts-cursor)
2691 len condition
2692 then-part
2693 else-pos
2694 else-part lp
2695 rp)))
2696 "AST node for an if-statement."
2697 condition ; expression
2698 then-part ; statement or block
2699 else-pos ; optional buffer position of 'else' keyword
2700 else-part ; optional statement or block
2701 lp ; position of left-paren, nil if omitted
2702 rp) ; position of right-paren, nil if omitted
2703
2704 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2705 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2706
2707 (defun js2-visit-if-node (n v)
2708 (js2-visit-ast (js2-if-node-condition n) v)
2709 (js2-visit-ast (js2-if-node-then-part n) v)
2710 (js2-visit-ast (js2-if-node-else-part n) v))
2711
2712 (defun js2-print-if-node (n i)
2713 (let ((pad (js2-make-pad i))
2714 (then-part (js2-if-node-then-part n))
2715 (else-part (js2-if-node-else-part n)))
2716 (insert pad "if (")
2717 (js2-print-ast (js2-if-node-condition n) 0)
2718 (insert ") {\n")
2719 (js2-print-body then-part (1+ i))
2720 (insert pad "}")
2721 (cond
2722 ((not else-part)
2723 (insert "\n"))
2724 ((js2-if-node-p else-part)
2725 (insert " else ")
2726 (js2-print-body else-part i))
2727 (t
2728 (insert " else {\n")
2729 (js2-print-body else-part (1+ i))
2730 (insert pad "}\n")))))
2731
2732 (cl-defstruct (js2-export-binding-node
2733 (:include js2-node)
2734 (:constructor nil)
2735 (:constructor make-js2-export-binding-node (&key (type -1)
2736 pos
2737 len
2738 local-name
2739 extern-name)))
2740 "AST node for an external symbol binding.
2741 It contains a local-name node which is the name of the value in the
2742 current scope, and extern-name which is the name of the value in the
2743 imported or exported scope. By default these are the same, but if the
2744 name is aliased as in {foo as bar}, it would have an extern-name node
2745 containing 'foo' and a local-name node containing 'bar'."
2746 local-name ; js2-name-node with the variable name in this scope
2747 extern-name) ; js2-name-node with the value name in the exporting module
2748
2749 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2750 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2751
2752 (defun js2-visit-extern-binding (n v)
2753 "Visit an extern binding node. First visit the local-name, and, if
2754 different, visit the extern-name."
2755 (let ((local-name (js2-export-binding-node-local-name n))
2756 (extern-name (js2-export-binding-node-extern-name n)))
2757 (when local-name
2758 (js2-visit-ast local-name v))
2759 (when (not (equal local-name extern-name))
2760 (js2-visit-ast extern-name v))))
2761
2762 (defun js2-print-extern-binding (n _i)
2763 "Print a representation of a single extern binding. E.g. 'foo' or
2764 'foo as bar'."
2765 (let ((local-name (js2-export-binding-node-local-name n))
2766 (extern-name (js2-export-binding-node-extern-name n)))
2767 (insert (js2-name-node-name extern-name))
2768 (when (not (equal local-name extern-name))
2769 (insert " as ")
2770 (insert (js2-name-node-name local-name)))))
2771
2772
2773 (cl-defstruct (js2-import-node
2774 (:include js2-node)
2775 (:constructor nil)
2776 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2777 (pos (js2-current-token-beg))
2778 len
2779 import
2780 from
2781 module-id)))
2782 "AST node for an import statement. It follows the form
2783
2784 import ModuleSpecifier;
2785 import ImportClause FromClause;"
2786 import ; js2-import-clause-node specifying which names are to imported.
2787 from ; js2-from-clause-node indicating the module from which to import.
2788 module-id) ; module-id of the import. E.g. 'src/mylib'.
2789
2790 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2791 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2792
2793 (defun js2-visit-import (n v)
2794 (let ((import-clause (js2-import-node-import n))
2795 (from-clause (js2-import-node-from n)))
2796 (when import-clause
2797 (js2-visit-ast import-clause v))
2798 (when from-clause
2799 (js2-visit-ast from-clause v))))
2800
2801 (defun js2-print-import (n i)
2802 "Prints a representation of the import node"
2803 (let ((pad (js2-make-pad i))
2804 (import-clause (js2-import-node-import n))
2805 (from-clause (js2-import-node-from n))
2806 (module-id (js2-import-node-module-id n)))
2807 (insert pad "import ")
2808 (if import-clause
2809 (progn
2810 (js2-print-import-clause import-clause)
2811 (insert " ")
2812 (js2-print-from-clause from-clause))
2813 (insert "'")
2814 (insert module-id)
2815 (insert "'"))
2816 (insert ";\n")))
2817
2818 (cl-defstruct (js2-import-clause-node
2819 (:include js2-node)
2820 (:constructor nil)
2821 (:constructor make-js2-import-clause-node (&key (type -1)
2822 pos
2823 len
2824 namespace-import
2825 named-imports
2826 default-binding)))
2827 "AST node corresponding to the import clause of an import statement. This is
2828 the portion of the import that bindings names from the external context to the
2829 local context."
2830 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2831 named-imports ; lisp list of js2-export-binding-node for all named imports.
2832 default-binding) ; js2-export-binding-node for the default import binding
2833
2834 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2835 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2836
2837 (defun js2-visit-import-clause (n v)
2838 (let ((ns-import (js2-import-clause-node-namespace-import n))
2839 (named-imports (js2-import-clause-node-named-imports n))
2840 (default (js2-import-clause-node-default-binding n)))
2841 (when ns-import
2842 (js2-visit-ast ns-import v))
2843 (when named-imports
2844 (dolist (import named-imports)
2845 (js2-visit-ast import v)))
2846 (when default
2847 (js2-visit-ast default v))))
2848
2849 (defun js2-print-import-clause (n)
2850 (let ((ns-import (js2-import-clause-node-namespace-import n))
2851 (named-imports (js2-import-clause-node-named-imports n))
2852 (default (js2-import-clause-node-default-binding n)))
2853 (cond
2854 ((and default ns-import)
2855 (js2-print-ast default)
2856 (insert ", ")
2857 (js2-print-namespace-import ns-import))
2858 ((and default named-imports)
2859 (js2-print-ast default)
2860 (insert ", ")
2861 (js2-print-named-imports named-imports))
2862 (default
2863 (js2-print-ast default))
2864 (ns-import
2865 (js2-print-namespace-import ns-import))
2866 (named-imports
2867 (js2-print-named-imports named-imports)))))
2868
2869 (defun js2-print-namespace-import (node)
2870 (insert "* as ")
2871 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2872
2873 (defun js2-print-named-imports (imports)
2874 (insert "{")
2875 (let ((len (length imports))
2876 (n 0))
2877 (while (< n len)
2878 (js2-print-extern-binding (nth n imports) 0)
2879 (unless (= n (- len 1))
2880 (insert ", "))
2881 (setq n (+ n 1))))
2882 (insert "}"))
2883
2884 (cl-defstruct (js2-namespace-import-node
2885 (:include js2-node)
2886 (:constructor nil)
2887 (:constructor make-js2-namespace-import-node (&key (type -1)
2888 pos
2889 len
2890 name)))
2891 "AST node for a complete namespace import.
2892 E.g. the '* as lib' expression in:
2893
2894 import * as lib from 'src/lib'
2895
2896 It contains a single name node referring to the bound name."
2897 name) ; js2-name-node of the bound name.
2898
2899 (defun js2-visit-namespace-import (n v)
2900 (js2-visit-ast (js2-namespace-import-node-name n) v))
2901
2902 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2903 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2904
2905 (cl-defstruct (js2-from-clause-node
2906 (:include js2-node)
2907 (:constructor nil)
2908 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2909 pos
2910 len
2911 module-id
2912 metadata-p)))
2913 "AST node for the from clause in an import or export statement.
2914 E.g. from 'my/module'. It can refere to either an external module, or to the
2915 modules metadata itself."
2916 module-id ; string containing the module specifier.
2917 metadata-p) ; true if this clause refers to the module's metadata
2918
2919 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2920 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2921
2922 (defun js2-print-from-clause (n)
2923 (insert "from ")
2924 (if (js2-from-clause-node-metadata-p n)
2925 (insert "this module")
2926 (insert "'")
2927 (insert (js2-from-clause-node-module-id n))
2928 (insert "'")))
2929
2930 (cl-defstruct (js2-try-node
2931 (:include js2-node)
2932 (:constructor nil)
2933 (:constructor make-js2-try-node (&key (type js2-TRY)
2934 (pos js2-ts-cursor)
2935 len
2936 try-block
2937 catch-clauses
2938 finally-block)))
2939 "AST node for a try-statement."
2940 try-block
2941 catch-clauses ; a Lisp list of `js2-catch-node'
2942 finally-block) ; a `js2-finally-node'
2943
2944 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2945 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2946
2947 (defun js2-visit-try-node (n v)
2948 (js2-visit-ast (js2-try-node-try-block n) v)
2949 (dolist (clause (js2-try-node-catch-clauses n))
2950 (js2-visit-ast clause v))
2951 (js2-visit-ast (js2-try-node-finally-block n) v))
2952
2953 (defun js2-print-try-node (n i)
2954 (let ((pad (js2-make-pad i))
2955 (catches (js2-try-node-catch-clauses n))
2956 (finally (js2-try-node-finally-block n)))
2957 (insert pad "try {\n")
2958 (js2-print-body (js2-try-node-try-block n) (1+ i))
2959 (insert pad "}")
2960 (when catches
2961 (dolist (catch catches)
2962 (js2-print-ast catch i)))
2963 (if finally
2964 (js2-print-ast finally i)
2965 (insert "\n"))))
2966
2967 (cl-defstruct (js2-catch-node
2968 (:include js2-scope)
2969 (:constructor nil)
2970 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2971 (pos js2-ts-cursor)
2972 len
2973 param
2974 guard-kwd
2975 guard-expr
2976 lp rp)))
2977 "AST node for a catch clause."
2978 param ; destructuring form or simple name node
2979 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2980 guard-expr ; catch condition, a `js2-node'
2981 lp ; buffer position of left-paren, nil if omitted
2982 rp) ; buffer position of right-paren, nil if omitted
2983
2984 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2985 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2986
2987 (defun js2-visit-catch-node (n v)
2988 (js2-visit-ast (js2-catch-node-param n) v)
2989 (when (js2-catch-node-guard-kwd n)
2990 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2991 (js2-visit-block n v))
2992
2993 (defun js2-print-catch-node (n i)
2994 (let ((pad (js2-make-pad i))
2995 (guard-kwd (js2-catch-node-guard-kwd n))
2996 (guard-expr (js2-catch-node-guard-expr n)))
2997 (insert " catch (")
2998 (js2-print-ast (js2-catch-node-param n) 0)
2999 (when guard-kwd
3000 (insert " if ")
3001 (js2-print-ast guard-expr 0))
3002 (insert ") {\n")
3003 (js2-print-body n (1+ i))
3004 (insert pad "}")))
3005
3006 (cl-defstruct (js2-finally-node
3007 (:include js2-node)
3008 (:constructor nil)
3009 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3010 (pos js2-ts-cursor)
3011 len body)))
3012 "AST node for a finally clause."
3013 body) ; a `js2-node', often but not always a block node
3014
3015 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3016 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3017
3018 (defun js2-visit-finally-node (n v)
3019 (js2-visit-ast (js2-finally-node-body n) v))
3020
3021 (defun js2-print-finally-node (n i)
3022 (let ((pad (js2-make-pad i)))
3023 (insert " finally {\n")
3024 (js2-print-body (js2-finally-node-body n) (1+ i))
3025 (insert pad "}\n")))
3026
3027 (cl-defstruct (js2-switch-node
3028 (:include js2-node)
3029 (:constructor nil)
3030 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3031 (pos js2-ts-cursor)
3032 len
3033 discriminant
3034 cases lp
3035 rp)))
3036 "AST node for a switch statement."
3037 discriminant ; a `js2-node' (switch expression)
3038 cases ; a Lisp list of `js2-case-node'
3039 lp ; position of open-paren for discriminant, nil if omitted
3040 rp) ; position of close-paren for discriminant, nil if omitted
3041
3042 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3043 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3044
3045 (defun js2-visit-switch-node (n v)
3046 (js2-visit-ast (js2-switch-node-discriminant n) v)
3047 (dolist (c (js2-switch-node-cases n))
3048 (js2-visit-ast c v)))
3049
3050 (defun js2-print-switch-node (n i)
3051 (let ((pad (js2-make-pad i))
3052 (cases (js2-switch-node-cases n)))
3053 (insert pad "switch (")
3054 (js2-print-ast (js2-switch-node-discriminant n) 0)
3055 (insert ") {\n")
3056 (dolist (case cases)
3057 (js2-print-ast case i))
3058 (insert pad "}\n")))
3059
3060 (cl-defstruct (js2-case-node
3061 (:include js2-block-node)
3062 (:constructor nil)
3063 (:constructor make-js2-case-node (&key (type js2-CASE)
3064 (pos js2-ts-cursor)
3065 len kids expr)))
3066 "AST node for a case clause of a switch statement."
3067 expr) ; the case expression (nil for default)
3068
3069 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3070 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3071
3072 (defun js2-visit-case-node (n v)
3073 (js2-visit-ast (js2-case-node-expr n) v)
3074 (js2-visit-block n v))
3075
3076 (defun js2-print-case-node (n i)
3077 (let ((pad (js2-make-pad i))
3078 (expr (js2-case-node-expr n)))
3079 (insert pad)
3080 (if (null expr)
3081 (insert "default:\n")
3082 (insert "case ")
3083 (js2-print-ast expr 0)
3084 (insert ":\n"))
3085 (dolist (kid (js2-case-node-kids n))
3086 (js2-print-ast kid (1+ i)))))
3087
3088 (cl-defstruct (js2-throw-node
3089 (:include js2-node)
3090 (:constructor nil)
3091 (:constructor make-js2-throw-node (&key (type js2-THROW)
3092 (pos js2-ts-cursor)
3093 len expr)))
3094 "AST node for a throw statement."
3095 expr) ; the expression to throw
3096
3097 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3098 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3099
3100 (defun js2-visit-throw-node (n v)
3101 (js2-visit-ast (js2-throw-node-expr n) v))
3102
3103 (defun js2-print-throw-node (n i)
3104 (insert (js2-make-pad i) "throw ")
3105 (js2-print-ast (js2-throw-node-expr n) 0)
3106 (insert ";\n"))
3107
3108 (cl-defstruct (js2-with-node
3109 (:include js2-node)
3110 (:constructor nil)
3111 (:constructor make-js2-with-node (&key (type js2-WITH)
3112 (pos js2-ts-cursor)
3113 len object
3114 body lp rp)))
3115 "AST node for a with-statement."
3116 object
3117 body
3118 lp ; buffer position of left-paren around object, nil if omitted
3119 rp) ; buffer position of right-paren around object, nil if omitted
3120
3121 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3122 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3123
3124 (defun js2-visit-with-node (n v)
3125 (js2-visit-ast (js2-with-node-object n) v)
3126 (js2-visit-ast (js2-with-node-body n) v))
3127
3128 (defun js2-print-with-node (n i)
3129 (let ((pad (js2-make-pad i)))
3130 (insert pad "with (")
3131 (js2-print-ast (js2-with-node-object n) 0)
3132 (insert ") {\n")
3133 (js2-print-body (js2-with-node-body n) (1+ i))
3134 (insert pad "}\n")))
3135
3136 (cl-defstruct (js2-label-node
3137 (:include js2-node)
3138 (:constructor nil)
3139 (:constructor make-js2-label-node (&key (type js2-LABEL)
3140 (pos js2-ts-cursor)
3141 len name)))
3142 "AST node for a statement label or case label."
3143 name ; a string
3144 loop) ; for validating and code-generating continue-to-label
3145
3146 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3147 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3148
3149 (defun js2-print-label (n i)
3150 (insert (js2-make-pad i)
3151 (js2-label-node-name n)
3152 ":\n"))
3153
3154 (cl-defstruct (js2-labeled-stmt-node
3155 (:include js2-node)
3156 (:constructor nil)
3157 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3158 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3159 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3160 (pos js2-ts-cursor)
3161 len labels stmt)))
3162 "AST node for a statement with one or more labels.
3163 Multiple labels for a statement are collapsed into the labels field."
3164 labels ; Lisp list of `js2-label-node'
3165 stmt) ; the statement these labels are for
3166
3167 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3168 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3169
3170 (defun js2-get-label-by-name (lbl-stmt name)
3171 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3172 Returns nil if no such label is in the list."
3173 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3174 result)
3175 (while (and label-list (not result))
3176 (if (string= (js2-label-node-name (car label-list)) name)
3177 (setq result (car label-list))
3178 (setq label-list (cdr label-list))))
3179 result))
3180
3181 (defun js2-visit-labeled-stmt (n v)
3182 (dolist (label (js2-labeled-stmt-node-labels n))
3183 (js2-visit-ast label v))
3184 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3185
3186 (defun js2-print-labeled-stmt (n i)
3187 (dolist (label (js2-labeled-stmt-node-labels n))
3188 (js2-print-ast label i))
3189 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3190
3191 (defun js2-labeled-stmt-node-contains (node label)
3192 "Return t if NODE contains LABEL in its label set.
3193 NODE is a `js2-labels-node'. LABEL is an identifier."
3194 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3195 if (string= label (js2-label-node-name nl))
3196 return t
3197 finally return nil))
3198
3199 (defsubst js2-labeled-stmt-node-add-label (node label)
3200 "Add a `js2-label-node' to the label set for this statement."
3201 (setf (js2-labeled-stmt-node-labels node)
3202 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3203
3204 (cl-defstruct (js2-jump-node
3205 (:include js2-node)
3206 (:constructor nil))
3207 "Abstract supertype of break and continue nodes."
3208 label ; `js2-name-node' for location of label identifier, if present
3209 target) ; target js2-labels-node or loop/switch statement
3210
3211 (defun js2-visit-jump-node (n v)
3212 ;; We don't visit the target, since it's a back-link.
3213 (js2-visit-ast (js2-jump-node-label n) v))
3214
3215 (cl-defstruct (js2-break-node
3216 (:include js2-jump-node)
3217 (:constructor nil)
3218 (:constructor make-js2-break-node (&key (type js2-BREAK)
3219 (pos js2-ts-cursor)
3220 len label target)))
3221 "AST node for a break statement.
3222 The label field is a `js2-name-node', possibly nil, for the named label
3223 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3224 is the target of the break - a label node or enclosing loop/switch statement.")
3225
3226 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3227 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3228
3229 (defun js2-print-break-node (n i)
3230 (insert (js2-make-pad i) "break")
3231 (when (js2-break-node-label n)
3232 (insert " ")
3233 (js2-print-ast (js2-break-node-label n) 0))
3234 (insert ";\n"))
3235
3236 (cl-defstruct (js2-continue-node
3237 (:include js2-jump-node)
3238 (:constructor nil)
3239 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3240 (pos js2-ts-cursor)
3241 len label target)))
3242 "AST node for a continue statement.
3243 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3244 It is nil if continue specifies no label. The target field is the jump target:
3245 a `js2-label-node' or the innermost enclosing loop.")
3246
3247 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3248 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3249
3250 (defun js2-print-continue-node (n i)
3251 (insert (js2-make-pad i) "continue")
3252 (when (js2-continue-node-label n)
3253 (insert " ")
3254 (js2-print-ast (js2-continue-node-label n) 0))
3255 (insert ";\n"))
3256
3257 (cl-defstruct (js2-function-node
3258 (:include js2-script-node)
3259 (:constructor nil)
3260 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3261 (pos js2-ts-cursor)
3262 len
3263 (ftype 'FUNCTION)
3264 (form 'FUNCTION_STATEMENT)
3265 (name "")
3266 params rest-p
3267 body
3268 generator-type
3269 async
3270 lp rp)))
3271 "AST node for a function declaration.
3272 The `params' field is a Lisp list of nodes. Each node is either a simple
3273 `js2-name-node', or if it's a destructuring-assignment parameter, a
3274 `js2-array-node' or `js2-object-node'."
3275 ftype ; FUNCTION, GETTER or SETTER
3276 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3277 name ; function name (a `js2-name-node', or nil if anonymous)
3278 params ; a Lisp list of destructuring forms or simple name nodes
3279 rest-p ; if t, the last parameter is rest parameter
3280 body ; a `js2-block-node' or expression node (1.8 only)
3281 lp ; position of arg-list open-paren, or nil if omitted
3282 rp ; position of arg-list close-paren, or nil if omitted
3283 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3284 needs-activation ; t if we need an activation object for this frame
3285 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3286 async ; t if the function is defined as `async function`
3287 member-expr) ; nonstandard Ecma extension from Rhino
3288
3289 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3290 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3291
3292 (defun js2-visit-function-node (n v)
3293 (js2-visit-ast (js2-function-node-name n) v)
3294 (dolist (p (js2-function-node-params n))
3295 (js2-visit-ast p v))
3296 (js2-visit-ast (js2-function-node-body n) v))
3297
3298 (defun js2-print-function-node (n i)
3299 (let* ((pad (js2-make-pad i))
3300 (method (js2-node-get-prop n 'METHOD_TYPE))
3301 (name (or (js2-function-node-name n)
3302 (js2-function-node-member-expr n)))
3303 (params (js2-function-node-params n))
3304 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3305 (rest-p (js2-function-node-rest-p n))
3306 (body (js2-function-node-body n))
3307 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3308 (unless method
3309 (insert pad)
3310 (when (js2-function-node-async n) (insert "async "))
3311 (unless arrow (insert "function"))
3312 (when (eq (js2-function-node-generator-type n) 'STAR)
3313 (insert "*")))
3314 (when name
3315 (insert " ")
3316 (js2-print-ast name 0))
3317 (insert "(")
3318 (cl-loop with len = (length params)
3319 for param in params
3320 for count from 1
3321 do
3322 (when (and rest-p (= count len))
3323 (insert "..."))
3324 (js2-print-ast param 0)
3325 (when (< count len)
3326 (insert ", ")))
3327 (insert ") ")
3328 (when arrow
3329 (insert "=> "))
3330 (insert "{")
3331 ;; TODO: fix this to be smarter about indenting, etc.
3332 (unless expr
3333 (insert "\n"))
3334 (if (js2-block-node-p body)
3335 (js2-print-body body (1+ i))
3336 (js2-print-ast body 0))
3337 (insert pad "}")
3338 (unless expr
3339 (insert "\n"))))
3340
3341 (defun js2-function-name (node)
3342 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3343 (and (js2-function-node-name node)
3344 (js2-name-node-name (js2-function-node-name node))))
3345
3346 ;; Having this be an expression node makes it more flexible.
3347 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3348 ;; that work better if you assume it's an expression. Whenever we have
3349 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3350 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3351 (cl-defstruct (js2-var-decl-node
3352 (:include js2-node)
3353 (:constructor nil)
3354 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3355 (pos (js2-current-token-beg))
3356 len kids
3357 decl-type)))
3358 "AST node for a variable declaration list (VAR, CONST or LET).
3359 The node bounds differ depending on the declaration type. For VAR or
3360 CONST declarations, the bounds include the var/const keyword. For LET
3361 declarations, the node begins at the position of the first child."
3362 kids ; a Lisp list of `js2-var-init-node' structs.
3363 decl-type) ; js2-VAR, js2-CONST or js2-LET
3364
3365 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3366 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3367
3368 (defun js2-visit-var-decl (n v)
3369 (dolist (kid (js2-var-decl-node-kids n))
3370 (js2-visit-ast kid v)))
3371
3372 (defun js2-print-var-decl (n i)
3373 (let ((pad (js2-make-pad i))
3374 (tt (js2-var-decl-node-decl-type n)))
3375 (insert pad)
3376 (insert (cond
3377 ((= tt js2-VAR) "var ")
3378 ((= tt js2-LET) "let ")
3379 ((= tt js2-CONST) "const ")
3380 (t
3381 (error "malformed var-decl node"))))
3382 (cl-loop with kids = (js2-var-decl-node-kids n)
3383 with len = (length kids)
3384 for kid in kids
3385 for count from 1
3386 do
3387 (js2-print-ast kid 0)
3388 (if (< count len)
3389 (insert ", ")))))
3390
3391 (cl-defstruct (js2-var-init-node
3392 (:include js2-node)
3393 (:constructor nil)
3394 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3395 (pos js2-ts-cursor)
3396 len target
3397 initializer)))
3398 "AST node for a variable declaration.
3399 The type field will be js2-CONST for a const decl."
3400 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3401 initializer) ; initializer expression, a `js2-node'
3402
3403 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3404 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3405
3406 (defun js2-visit-var-init-node (n v)
3407 (js2-visit-ast (js2-var-init-node-target n) v)
3408 (js2-visit-ast (js2-var-init-node-initializer n) v))
3409
3410 (defun js2-print-var-init-node (n i)
3411 (let ((pad (js2-make-pad i))
3412 (name (js2-var-init-node-target n))
3413 (init (js2-var-init-node-initializer n)))
3414 (insert pad)
3415 (js2-print-ast name 0)
3416 (when init
3417 (insert " = ")
3418 (js2-print-ast init 0))))
3419
3420 (cl-defstruct (js2-cond-node
3421 (:include js2-node)
3422 (:constructor nil)
3423 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3424 (pos js2-ts-cursor)
3425 len
3426 test-expr
3427 true-expr
3428 false-expr
3429 q-pos c-pos)))
3430 "AST node for the ternary operator"
3431 test-expr
3432 true-expr
3433 false-expr
3434 q-pos ; buffer position of ?
3435 c-pos) ; buffer position of :
3436
3437 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3438 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3439
3440 (defun js2-visit-cond-node (n v)
3441 (js2-visit-ast (js2-cond-node-test-expr n) v)
3442 (js2-visit-ast (js2-cond-node-true-expr n) v)
3443 (js2-visit-ast (js2-cond-node-false-expr n) v))
3444
3445 (defun js2-print-cond-node (n i)
3446 (let ((pad (js2-make-pad i)))
3447 (insert pad)
3448 (js2-print-ast (js2-cond-node-test-expr n) 0)
3449 (insert " ? ")
3450 (js2-print-ast (js2-cond-node-true-expr n) 0)
3451 (insert " : ")
3452 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3453
3454 (cl-defstruct (js2-infix-node
3455 (:include js2-node)
3456 (:constructor nil)
3457 (:constructor make-js2-infix-node (&key type
3458 (pos js2-ts-cursor)
3459 len op-pos
3460 left right)))
3461 "Represents infix expressions.
3462 Includes assignment ops like `|=', and the comma operator.
3463 The type field inherited from `js2-node' holds the operator."
3464 op-pos ; buffer position where operator begins
3465 left ; any `js2-node'
3466 right) ; any `js2-node'
3467
3468 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3469 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3470
3471 (defun js2-visit-infix-node (n v)
3472 (js2-visit-ast (js2-infix-node-left n) v)
3473 (js2-visit-ast (js2-infix-node-right n) v))
3474
3475 (defconst js2-operator-tokens
3476 (let ((table (make-hash-table :test 'eq))
3477 (tokens
3478 (list (cons js2-IN "in")
3479 (cons js2-TYPEOF "typeof")
3480 (cons js2-INSTANCEOF "instanceof")
3481 (cons js2-DELPROP "delete")
3482 (cons js2-AWAIT "await")
3483 (cons js2-VOID "void")
3484 (cons js2-COMMA ",")
3485 (cons js2-COLON ":")
3486 (cons js2-OR "||")
3487 (cons js2-AND "&&")
3488 (cons js2-INC "++")
3489 (cons js2-DEC "--")
3490 (cons js2-BITOR "|")
3491 (cons js2-BITXOR "^")
3492 (cons js2-BITAND "&")
3493 (cons js2-EQ "==")
3494 (cons js2-NE "!=")
3495 (cons js2-LT "<")
3496 (cons js2-LE "<=")
3497 (cons js2-GT ">")
3498 (cons js2-GE ">=")
3499 (cons js2-LSH "<<")
3500 (cons js2-RSH ">>")
3501 (cons js2-URSH ">>>")
3502 (cons js2-ADD "+") ; infix plus
3503 (cons js2-SUB "-") ; infix minus
3504 (cons js2-MUL "*")
3505 (cons js2-DIV "/")
3506 (cons js2-MOD "%")
3507 (cons js2-NOT "!")
3508 (cons js2-BITNOT "~")
3509 (cons js2-POS "+") ; unary plus
3510 (cons js2-NEG "-") ; unary minus
3511 (cons js2-TRIPLEDOT "...")
3512 (cons js2-SHEQ "===") ; shallow equality
3513 (cons js2-SHNE "!==") ; shallow inequality
3514 (cons js2-ASSIGN "=")
3515 (cons js2-ASSIGN_BITOR "|=")
3516 (cons js2-ASSIGN_BITXOR "^=")
3517 (cons js2-ASSIGN_BITAND "&=")
3518 (cons js2-ASSIGN_LSH "<<=")
3519 (cons js2-ASSIGN_RSH ">>=")
3520 (cons js2-ASSIGN_URSH ">>>=")
3521 (cons js2-ASSIGN_ADD "+=")
3522 (cons js2-ASSIGN_SUB "-=")
3523 (cons js2-ASSIGN_MUL "*=")
3524 (cons js2-ASSIGN_DIV "/=")
3525 (cons js2-ASSIGN_MOD "%="))))
3526 (cl-loop for (k . v) in tokens do
3527 (puthash k v table))
3528 table))
3529
3530 (defun js2-print-infix-node (n i)
3531 (let* ((tt (js2-node-type n))
3532 (op (gethash tt js2-operator-tokens)))
3533 (unless op
3534 (error "unrecognized infix operator %s" (js2-node-type n)))
3535 (insert (js2-make-pad i))
3536 (js2-print-ast (js2-infix-node-left n) 0)
3537 (unless (= tt js2-COMMA)
3538 (insert " "))
3539 (insert op)
3540 (insert " ")
3541 (js2-print-ast (js2-infix-node-right n) 0)))
3542
3543 (cl-defstruct (js2-assign-node
3544 (:include js2-infix-node)
3545 (:constructor nil)
3546 (:constructor make-js2-assign-node (&key type
3547 (pos js2-ts-cursor)
3548 len op-pos
3549 left right)))
3550 "Represents any assignment.
3551 The type field holds the actual assignment operator.")
3552
3553 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3554 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3555
3556 (cl-defstruct (js2-unary-node
3557 (:include js2-node)
3558 (:constructor nil)
3559 (:constructor make-js2-unary-node (&key type ; required
3560 (pos js2-ts-cursor)
3561 len operand)))
3562 "AST node type for unary operator nodes.
3563 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3564 TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
3565 property is added if the operator follows the operand."
3566 operand) ; a `js2-node' expression
3567
3568 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3569 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3570
3571 (defun js2-visit-unary-node (n v)
3572 (js2-visit-ast (js2-unary-node-operand n) v))
3573
3574 (defun js2-print-unary-node (n i)
3575 (let* ((tt (js2-node-type n))
3576 (op (gethash tt js2-operator-tokens))
3577 (postfix (js2-node-get-prop n 'postfix)))
3578 (unless op
3579 (error "unrecognized unary operator %s" tt))
3580 (insert (js2-make-pad i))
3581 (unless postfix
3582 (insert op))
3583 (if (or (= tt js2-TYPEOF)
3584 (= tt js2-DELPROP)
3585 (= tt js2-AWAIT)
3586 (= tt js2-VOID))
3587 (insert " "))
3588 (js2-print-ast (js2-unary-node-operand n) 0)
3589 (when postfix
3590 (insert op))))
3591
3592 (cl-defstruct (js2-let-node
3593 (:include js2-scope)
3594 (:constructor nil)
3595 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3596 (pos (js2-current-token-beg))
3597 len vars body
3598 lp rp)))
3599 "AST node for a let expression or a let statement.
3600 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3601 vars ; a `js2-var-decl-node'
3602 body ; a `js2-node' representing the expression or body block
3603 lp
3604 rp)
3605
3606 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3607 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3608
3609 (defun js2-visit-let-node (n v)
3610 (js2-visit-ast (js2-let-node-vars n) v)
3611 (js2-visit-ast (js2-let-node-body n) v))
3612
3613 (defun js2-print-let-node (n i)
3614 (insert (js2-make-pad i) "let (")
3615 (let ((p (point)))
3616 (js2-print-ast (js2-let-node-vars n) 0)
3617 (delete-region p (+ p 4)))
3618 (insert ") ")
3619 (js2-print-ast (js2-let-node-body n) i))
3620
3621 (cl-defstruct (js2-keyword-node
3622 (:include js2-node)
3623 (:constructor nil)
3624 (:constructor make-js2-keyword-node (&key type
3625 (pos (js2-current-token-beg))
3626 (len (- js2-ts-cursor pos)))))
3627 "AST node representing a literal keyword such as `null'.
3628 Used for `null', `this', `true', `false' and `debugger'.
3629 The node type is set to js2-NULL, js2-THIS, etc.")
3630
3631 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3632 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3633
3634 (defun js2-print-keyword-node (n i)
3635 (insert (js2-make-pad i)
3636 (let ((tt (js2-node-type n)))
3637 (cond
3638 ((= tt js2-THIS) "this")
3639 ((= tt js2-SUPER) "super")
3640 ((= tt js2-NULL) "null")
3641 ((= tt js2-TRUE) "true")
3642 ((= tt js2-FALSE) "false")
3643 ((= tt js2-DEBUGGER) "debugger")
3644 (t (error "Invalid keyword literal type: %d" tt))))))
3645
3646 (defsubst js2-this-or-super-node-p (node)
3647 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3648 (let ((type (js2-node-type node)))
3649 (or (eq type js2-THIS) (eq type js2-SUPER))))
3650
3651 (cl-defstruct (js2-new-node
3652 (:include js2-node)
3653 (:constructor nil)
3654 (:constructor make-js2-new-node (&key (type js2-NEW)
3655 (pos (js2-current-token-beg))
3656 len target
3657 args initializer
3658 lp rp)))
3659 "AST node for new-expression such as new Foo()."
3660 target ; an identifier or reference
3661 args ; a Lisp list of argument nodes
3662 lp ; position of left-paren, nil if omitted
3663 rp ; position of right-paren, nil if omitted
3664 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3665
3666 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3667 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3668
3669 (defun js2-visit-new-node (n v)
3670 (js2-visit-ast (js2-new-node-target n) v)
3671 (dolist (arg (js2-new-node-args n))
3672 (js2-visit-ast arg v))
3673 (js2-visit-ast (js2-new-node-initializer n) v))
3674
3675 (defun js2-print-new-node (n i)
3676 (insert (js2-make-pad i) "new ")
3677 (js2-print-ast (js2-new-node-target n))
3678 (insert "(")
3679 (js2-print-list (js2-new-node-args n))
3680 (insert ")")
3681 (when (js2-new-node-initializer n)
3682 (insert " ")
3683 (js2-print-ast (js2-new-node-initializer n))))
3684
3685 (cl-defstruct (js2-name-node
3686 (:include js2-node)
3687 (:constructor nil)
3688 (:constructor make-js2-name-node (&key (type js2-NAME)
3689 (pos (js2-current-token-beg))
3690 (len (- js2-ts-cursor
3691 (js2-current-token-beg)))
3692 (name (js2-current-token-string)))))
3693 "AST node for a JavaScript identifier"
3694 name ; a string
3695 scope) ; a `js2-scope' (optional, used for codegen)
3696
3697 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3698 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3699
3700 (defun js2-print-name-node (n i)
3701 (insert (js2-make-pad i)
3702 (js2-name-node-name n)))
3703
3704 (defsubst js2-name-node-length (node)
3705 "Return identifier length of NODE, a `js2-name-node'.
3706 Returns 0 if NODE is nil or its identifier field is nil."
3707 (if node
3708 (length (js2-name-node-name node))
3709 0))
3710
3711 (cl-defstruct (js2-number-node
3712 (:include js2-node)
3713 (:constructor nil)
3714 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3715 (pos (js2-current-token-beg))
3716 (len (- js2-ts-cursor
3717 (js2-current-token-beg)))
3718 (value (js2-current-token-string))
3719 (num-value (js2-token-number
3720 (js2-current-token)))
3721 (num-base (js2-token-number-base
3722 (js2-current-token)))
3723 (legacy-octal-p (js2-token-number-legacy-octal-p
3724 (js2-current-token))))))
3725 "AST node for a number literal."
3726 value ; the original string, e.g. "6.02e23"
3727 num-value ; the parsed number value
3728 num-base ; the number's base
3729 legacy-octal-p) ; whether the number is a legacy octal (0123 instead of 0o123)
3730
3731 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3732 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3733
3734 (defun js2-print-number-node (n i)
3735 (insert (js2-make-pad i)
3736 (number-to-string (js2-number-node-num-value n))))
3737
3738 (cl-defstruct (js2-regexp-node
3739 (:include js2-node)
3740 (:constructor nil)
3741 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3742 (pos (js2-current-token-beg))
3743 (len (- js2-ts-cursor
3744 (js2-current-token-beg)))
3745 value flags)))
3746 "AST node for a regular expression literal."
3747 value ; the regexp string, without // delimiters
3748 flags) ; a string of flags, e.g. `mi'.
3749
3750 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3751 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3752
3753 (defun js2-print-regexp (n i)
3754 (insert (js2-make-pad i)
3755 "/"
3756 (js2-regexp-node-value n)
3757 "/")
3758 (if (js2-regexp-node-flags n)
3759 (insert (js2-regexp-node-flags n))))
3760
3761 (cl-defstruct (js2-string-node
3762 (:include js2-node)
3763 (:constructor nil)
3764 (:constructor make-js2-string-node (&key (type js2-STRING)
3765 (pos (js2-current-token-beg))
3766 (len (- js2-ts-cursor
3767 (js2-current-token-beg)))
3768 (value (js2-current-token-string)))))
3769 "String literal.
3770 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3771 You can tell the quote type by looking at the first character."
3772 value) ; the characters of the string, including the quotes
3773
3774 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3775 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3776
3777 (defun js2-print-string-node (n i)
3778 (insert (js2-make-pad i)
3779 (js2-node-string n)))
3780
3781 (cl-defstruct (js2-template-node
3782 (:include js2-node)
3783 (:constructor nil)
3784 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3785 beg len kids)))
3786 "Template literal."
3787 kids) ; `js2-string-node' is used for string segments, other nodes
3788 ; for substitutions inside.
3789
3790 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3791 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3792
3793 (defun js2-visit-template (n callback)
3794 (dolist (kid (js2-template-node-kids n))
3795 (js2-visit-ast kid callback)))
3796
3797 (defun js2-print-template (n i)
3798 (insert (js2-make-pad i))
3799 (dolist (kid (js2-template-node-kids n))
3800 (if (js2-string-node-p kid)
3801 (insert (js2-node-string kid))
3802 (js2-print-ast kid))))
3803
3804 (cl-defstruct (js2-tagged-template-node
3805 (:include js2-node)
3806 (:constructor nil)
3807 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3808 beg len tag template)))
3809 "Tagged template literal."
3810 tag ; `js2-node' with the tag expression.
3811 template) ; `js2-template-node' with the template.
3812
3813 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3814 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3815
3816 (defun js2-visit-tagged-template (n callback)
3817 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3818 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3819
3820 (defun js2-print-tagged-template (n i)
3821 (insert (js2-make-pad i))
3822 (js2-print-ast (js2-tagged-template-node-tag n))
3823 (js2-print-ast (js2-tagged-template-node-template n)))
3824
3825 (cl-defstruct (js2-array-node
3826 (:include js2-node)
3827 (:constructor nil)
3828 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3829 (pos js2-ts-cursor)
3830 len elems)))
3831 "AST node for an array literal."
3832 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3833
3834 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3835 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3836
3837 (defun js2-visit-array-node (n v)
3838 (dolist (e (js2-array-node-elems n))
3839 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3840
3841 (defun js2-print-array-node (n i)
3842 (insert (js2-make-pad i) "[")
3843 (let ((elems (js2-array-node-elems n)))
3844 (js2-print-list elems)
3845 (when (and elems (null (car (last elems))))
3846 (insert ",")))
3847 (insert "]"))
3848
3849 (cl-defstruct (js2-object-node
3850 (:include js2-node)
3851 (:constructor nil)
3852 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3853 (pos js2-ts-cursor)
3854 len
3855 elems)))
3856 "AST node for an object literal expression.
3857 `elems' is a list of `js2-object-prop-node'."
3858 elems)
3859
3860 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3861 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3862
3863 (defun js2-visit-object-node (n v)
3864 (dolist (e (js2-object-node-elems n))
3865 (js2-visit-ast e v)))
3866
3867 (defun js2-print-object-node (n i)
3868 (insert (js2-make-pad i) "{")
3869 (js2-print-list (js2-object-node-elems n))
3870 (insert "}"))
3871
3872 (cl-defstruct (js2-class-node
3873 (:include js2-object-node)
3874 (:constructor nil)
3875 (:constructor make-js2-class-node (&key (type js2-CLASS)
3876 (pos js2-ts-cursor)
3877 (form 'CLASS_STATEMENT)
3878 (name "")
3879 extends len elems)))
3880 "AST node for an class expression.
3881 `elems' is a list of `js2-object-prop-node', and `extends' is an
3882 optional `js2-expr-node'"
3883 form ; CLASS_{STATEMENT|EXPRESSION}
3884 name ; class name (a `js2-node-name', or nil if anonymous)
3885 extends ; class heritage (a `js2-expr-node', or nil if none)
3886 )
3887
3888 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3889 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3890
3891 (defun js2-visit-class-node (n v)
3892 (js2-visit-ast (js2-class-node-name n) v)
3893 (js2-visit-ast (js2-class-node-extends n) v)
3894 (dolist (e (js2-class-node-elems n))
3895 (js2-visit-ast e v)))
3896
3897 (defun js2-print-class-node (n i)
3898 (let* ((pad (js2-make-pad i))
3899 (name (js2-class-node-name n))
3900 (extends (js2-class-node-extends n))
3901 (elems (js2-class-node-elems n)))
3902 (insert pad "class")
3903 (when name
3904 (insert " ")
3905 (js2-print-ast name 0))
3906 (when extends
3907 (insert " extends ")
3908 (js2-print-ast extends))
3909 (insert " {")
3910 (dolist (elem elems)
3911 (insert "\n")
3912 (if (js2-node-get-prop elem 'STATIC)
3913 (progn (insert (js2-make-pad (1+ i)) "static ")
3914 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3915 (js2-print-ast elem (1+ i))))
3916 (insert "\n" pad "}")))
3917
3918 (cl-defstruct (js2-computed-prop-name-node
3919 (:include js2-node)
3920 (:constructor nil)
3921 (:constructor make-js2-computed-prop-name-node
3922 (&key
3923 (type js2-LB)
3924 expr
3925 (pos (js2-current-token-beg))
3926 (len (- js2-ts-cursor
3927 (js2-current-token-beg))))))
3928 "AST node for a `ComputedPropertyName'."
3929 expr)
3930
3931 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3932 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3933
3934 (defun js2-visit-computed-prop-name-node (n v)
3935 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3936
3937 (defun js2-print-computed-prop-name-node (n i)
3938 (insert (js2-make-pad i) "[")
3939 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3940 (insert "]"))
3941
3942 (cl-defstruct (js2-object-prop-node
3943 (:include js2-infix-node)
3944 (:constructor nil)
3945 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3946 (pos js2-ts-cursor)
3947 len left
3948 right op-pos)))
3949 "AST node for an object literal prop:value entry.
3950 The `left' field is the property: a name node, string node,
3951 number node or expression node. The `right' field is a
3952 `js2-node' representing the initializer value. If the property
3953 is abbreviated, the node's `SHORTHAND' property is non-nil and
3954 both fields have the same value.")
3955
3956 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3957 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3958
3959 (defun js2-print-object-prop-node (n i)
3960 (let* ((left (js2-object-prop-node-left n))
3961 (right (js2-object-prop-node-right n)))
3962 (js2-print-ast left i)
3963 (if (not (js2-node-get-prop n 'SHORTHAND))
3964 (progn
3965 (insert ": ")
3966 (js2-print-ast right 0)))))
3967
3968 (cl-defstruct (js2-method-node
3969 (:include js2-infix-node)
3970 (:constructor nil)
3971 (:constructor make-js2-method-node (&key (pos js2-ts-cursor)
3972 len left right)))
3973 "AST node for a method in an object literal or a class body.
3974 The `left' field is the `js2-name-node' naming the method.
3975 The `right' field is always an anonymous `js2-function-node' with a node
3976 property `METHOD_TYPE' set to 'GET or 'SET. ")
3977
3978 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3979 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3980
3981 (defun js2-print-method (n i)
3982 (let* ((pad (js2-make-pad i))
3983 (left (js2-method-node-left n))
3984 (right (js2-method-node-right n))
3985 (type (js2-node-get-prop right 'METHOD_TYPE)))
3986 (insert pad)
3987 (when type
3988 (insert (cdr (assoc type '((GET . "get ")
3989 (SET . "set ")
3990 (ASYNC . "async ")
3991 (FUNCTION . ""))))))
3992 (when (and (js2-function-node-p right)
3993 (eq 'STAR (js2-function-node-generator-type right)))
3994 (insert "*"))
3995 (js2-print-ast left 0)
3996 (js2-print-ast right 0)))
3997
3998 (cl-defstruct (js2-prop-get-node
3999 (:include js2-infix-node)
4000 (:constructor nil)
4001 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4002 (pos js2-ts-cursor)
4003 len left right)))
4004 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4005
4006 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4007 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4008
4009 (defun js2-visit-prop-get-node (n v)
4010 (js2-visit-ast (js2-prop-get-node-left n) v)
4011 (js2-visit-ast (js2-prop-get-node-right n) v))
4012
4013 (defun js2-print-prop-get-node (n i)
4014 (insert (js2-make-pad i))
4015 (js2-print-ast (js2-prop-get-node-left n) 0)
4016 (insert ".")
4017 (js2-print-ast (js2-prop-get-node-right n) 0))
4018
4019 (cl-defstruct (js2-elem-get-node
4020 (:include js2-node)
4021 (:constructor nil)
4022 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4023 (pos js2-ts-cursor)
4024 len target element
4025 lb rb)))
4026 "AST node for an array index expression such as foo[bar]."
4027 target ; a `js2-node' - the expression preceding the "."
4028 element ; a `js2-node' - the expression in brackets
4029 lb ; position of left-bracket, nil if omitted
4030 rb) ; position of right-bracket, nil if omitted
4031
4032 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4033 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4034
4035 (defun js2-visit-elem-get-node (n v)
4036 (js2-visit-ast (js2-elem-get-node-target n) v)
4037 (js2-visit-ast (js2-elem-get-node-element n) v))
4038
4039 (defun js2-print-elem-get-node (n i)
4040 (insert (js2-make-pad i))
4041 (js2-print-ast (js2-elem-get-node-target n) 0)
4042 (insert "[")
4043 (js2-print-ast (js2-elem-get-node-element n) 0)
4044 (insert "]"))
4045
4046 (cl-defstruct (js2-call-node
4047 (:include js2-node)
4048 (:constructor nil)
4049 (:constructor make-js2-call-node (&key (type js2-CALL)
4050 (pos js2-ts-cursor)
4051 len target args
4052 lp rp)))
4053 "AST node for a JavaScript function call."
4054 target ; a `js2-node' evaluating to the function to call
4055 args ; a Lisp list of `js2-node' arguments
4056 lp ; position of open-paren, or nil if missing
4057 rp) ; position of close-paren, or nil if missing
4058
4059 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4060 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4061
4062 (defun js2-visit-call-node (n v)
4063 (js2-visit-ast (js2-call-node-target n) v)
4064 (dolist (arg (js2-call-node-args n))
4065 (js2-visit-ast arg v)))
4066
4067 (defun js2-print-call-node (n i)
4068 (insert (js2-make-pad i))
4069 (js2-print-ast (js2-call-node-target n) 0)
4070 (insert "(")
4071 (js2-print-list (js2-call-node-args n))
4072 (insert ")"))
4073
4074 (cl-defstruct (js2-yield-node
4075 (:include js2-node)
4076 (:constructor nil)
4077 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4078 (pos js2-ts-cursor)
4079 len value star-p)))
4080 "AST node for yield statement or expression."
4081 star-p ; whether it's yield*
4082 value) ; optional: value to be yielded
4083
4084 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4085 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4086
4087 (defun js2-visit-yield-node (n v)
4088 (js2-visit-ast (js2-yield-node-value n) v))
4089
4090 (defun js2-print-yield-node (n i)
4091 (insert (js2-make-pad i))
4092 (insert "yield")
4093 (when (js2-yield-node-star-p n)
4094 (insert "*"))
4095 (when (js2-yield-node-value n)
4096 (insert " ")
4097 (js2-print-ast (js2-yield-node-value n) 0)))
4098
4099 (cl-defstruct (js2-paren-node
4100 (:include js2-node)
4101 (:constructor nil)
4102 (:constructor make-js2-paren-node (&key (type js2-LP)
4103 (pos js2-ts-cursor)
4104 len expr)))
4105 "AST node for a parenthesized expression.
4106 In particular, used when the parens are syntactically optional,
4107 as opposed to required parens such as those enclosing an if-conditional."
4108 expr) ; `js2-node'
4109
4110 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4111 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4112
4113 (defun js2-visit-paren-node (n v)
4114 (js2-visit-ast (js2-paren-node-expr n) v))
4115
4116 (defun js2-print-paren-node (n i)
4117 (insert (js2-make-pad i))
4118 (insert "(")
4119 (js2-print-ast (js2-paren-node-expr n) 0)
4120 (insert ")"))
4121
4122 (cl-defstruct (js2-comp-node
4123 (:include js2-scope)
4124 (:constructor nil)
4125 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4126 (pos js2-ts-cursor)
4127 len result
4128 loops filters
4129 form)))
4130 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4131 result ; result expression (just after left-bracket)
4132 loops ; a Lisp list of `js2-comp-loop-node'
4133 filters ; a Lisp list of guard/filter expressions
4134 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4135 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4136 )
4137
4138 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4139 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4140
4141 (defun js2-visit-comp-node (n v)
4142 (js2-visit-ast (js2-comp-node-result n) v)
4143 (dolist (l (js2-comp-node-loops n))
4144 (js2-visit-ast l v))
4145 (dolist (f (js2-comp-node-filters n))
4146 (js2-visit-ast f v)))
4147
4148 (defun js2-print-comp-node (n i)
4149 (let ((pad (js2-make-pad i))
4150 (result (js2-comp-node-result n))
4151 (loops (js2-comp-node-loops n))
4152 (filters (js2-comp-node-filters n))
4153 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4154 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4155 (insert pad (if gen-p "(" "["))
4156 (when legacy-p
4157 (js2-print-ast result 0))
4158 (dolist (l loops)
4159 (when legacy-p
4160 (insert " "))
4161 (js2-print-ast l 0)
4162 (unless legacy-p
4163 (insert " ")))
4164 (dolist (f filters)
4165 (when legacy-p
4166 (insert " "))
4167 (insert "if (")
4168 (js2-print-ast f 0)
4169 (insert ")")
4170 (unless legacy-p
4171 (insert " ")))
4172 (unless legacy-p
4173 (js2-print-ast result 0))
4174 (insert (if gen-p ")" "]"))))
4175
4176 (cl-defstruct (js2-comp-loop-node
4177 (:include js2-for-in-node)
4178 (:constructor nil)
4179 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4180 (pos js2-ts-cursor)
4181 len iterator
4182 object in-pos
4183 foreach-p
4184 each-pos
4185 forof-p
4186 lp rp)))
4187 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4188
4189 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4190 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4191
4192 (defun js2-visit-comp-loop (n v)
4193 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4194 (js2-visit-ast (js2-comp-loop-node-object n) v))
4195
4196 (defun js2-print-comp-loop (n _i)
4197 (insert "for ")
4198 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4199 (insert "(")
4200 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4201 (insert (if (js2-comp-loop-node-forof-p n)
4202 " of " " in "))
4203 (js2-print-ast (js2-comp-loop-node-object n) 0)
4204 (insert ")"))
4205
4206 (cl-defstruct (js2-empty-expr-node
4207 (:include js2-node)
4208 (:constructor nil)
4209 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4210 (pos (js2-current-token-beg))
4211 len)))
4212 "AST node for an empty expression.")
4213
4214 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4215 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4216
4217 (cl-defstruct (js2-xml-node
4218 (:include js2-block-node)
4219 (:constructor nil)
4220 (:constructor make-js2-xml-node (&key (type js2-XML)
4221 (pos (js2-current-token-beg))
4222 len kids)))
4223 "AST node for initial parse of E4X literals.
4224 The kids field is a list of XML fragments, each a `js2-string-node' or
4225 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4226
4227 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4228 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4229
4230 (defun js2-print-xml-node (n i)
4231 (dolist (kid (js2-xml-node-kids n))
4232 (js2-print-ast kid i)))
4233
4234 (cl-defstruct (js2-xml-js-expr-node
4235 (:include js2-xml-node)
4236 (:constructor nil)
4237 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4238 (pos js2-ts-cursor)
4239 len expr)))
4240 "AST node for an embedded JavaScript {expression} in an E4X literal.
4241 The start and end fields correspond to the curly-braces."
4242 expr) ; a `js2-expr-node' of some sort
4243
4244 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4245 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4246
4247 (defun js2-visit-xml-js-expr (n v)
4248 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4249
4250 (defun js2-print-xml-js-expr (n i)
4251 (insert (js2-make-pad i))
4252 (insert "{")
4253 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4254 (insert "}"))
4255
4256 (cl-defstruct (js2-xml-dot-query-node
4257 (:include js2-infix-node)
4258 (:constructor nil)
4259 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4260 (pos js2-ts-cursor)
4261 op-pos len left
4262 right rp)))
4263 "AST node for an E4X foo.(bar) filter expression.
4264 Note that the left-paren is automatically the character immediately
4265 following the dot (.) in the operator. No whitespace is permitted
4266 between the dot and the lp by the scanner."
4267 rp)
4268
4269 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4270 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4271
4272 (defun js2-print-xml-dot-query (n i)
4273 (insert (js2-make-pad i))
4274 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4275 (insert ".(")
4276 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4277 (insert ")"))
4278
4279 (cl-defstruct (js2-xml-ref-node
4280 (:include js2-node)
4281 (:constructor nil)) ; abstract
4282 "Base type for E4X XML attribute-access or property-get expressions.
4283 Such expressions can take a variety of forms. The general syntax has
4284 three parts:
4285
4286 - (optional) an @ (specifying an attribute access)
4287 - (optional) a namespace (a `js2-name-node') and double-colon
4288 - (required) either a `js2-name-node' or a bracketed [expression]
4289
4290 The property-name expressions (examples: ns::name, @name) are
4291 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4292 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4293
4294 This node type (or more specifically, its subclasses) will sometimes
4295 be the right-hand child of a `js2-prop-get-node' or a
4296 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4297 The `js2-xml-ref-node' may also be a standalone primary expression with
4298 no explicit target, which is valid in certain expression contexts such as
4299
4300 company..employee.(@id < 100)
4301
4302 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4303 expression whose parent is a `js2-xml-dot-query-node'."
4304 namespace
4305 at-pos
4306 colon-pos)
4307
4308 (defsubst js2-xml-ref-node-attr-access-p (node)
4309 "Return non-nil if this expression began with an @-token."
4310 (and (numberp (js2-xml-ref-node-at-pos node))
4311 (cl-plusp (js2-xml-ref-node-at-pos node))))
4312
4313 (cl-defstruct (js2-xml-prop-ref-node
4314 (:include js2-xml-ref-node)
4315 (:constructor nil)
4316 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4317 (pos (js2-current-token-beg))
4318 len propname
4319 namespace at-pos
4320 colon-pos)))
4321 "AST node for an E4X XML [expr] property-ref expression.
4322 The JavaScript syntax is an optional @, an optional ns::, and a name.
4323
4324 [ '@' ] [ name '::' ] name
4325
4326 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4327 @ns::*, @*::attr, @*::*, and @*.
4328
4329 The node starts at the @ token, if present. Otherwise it starts at the
4330 namespace name. The node bounds extend through the closing right-bracket,
4331 or if it is missing due to a syntax error, through the end of the index
4332 expression."
4333 propname)
4334
4335 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4336 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4337
4338 (defun js2-visit-xml-prop-ref-node (n v)
4339 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4340 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4341
4342 (defun js2-print-xml-prop-ref-node (n i)
4343 (insert (js2-make-pad i))
4344 (if (js2-xml-ref-node-attr-access-p n)
4345 (insert "@"))
4346 (when (js2-xml-prop-ref-node-namespace n)
4347 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4348 (insert "::"))
4349 (if (js2-xml-prop-ref-node-propname n)
4350 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4351
4352 (cl-defstruct (js2-xml-elem-ref-node
4353 (:include js2-xml-ref-node)
4354 (:constructor nil)
4355 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4356 (pos (js2-current-token-beg))
4357 len expr lb rb
4358 namespace at-pos
4359 colon-pos)))
4360 "AST node for an E4X XML [expr] member-ref expression.
4361 Syntax:
4362
4363 [ '@' ] [ name '::' ] '[' expr ']'
4364
4365 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4366
4367 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4368 is not a legal E4X XML element-ref expression, since it's already used
4369 for standard JavaScript element-get array indexing. Hence, a
4370 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4371 non-nil namespace node, or both.
4372
4373 The node starts at the @ token, if present. Otherwise it starts
4374 at the namespace name. The node bounds extend through the closing
4375 right-bracket, or if it is missing due to a syntax error, through the
4376 end of the index expression."
4377 expr ; the bracketed index expression
4378 lb
4379 rb)
4380
4381 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4382 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4383
4384 (defun js2-visit-xml-elem-ref-node (n v)
4385 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4386 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4387
4388 (defun js2-print-xml-elem-ref-node (n i)
4389 (insert (js2-make-pad i))
4390 (if (js2-xml-ref-node-attr-access-p n)
4391 (insert "@"))
4392 (when (js2-xml-elem-ref-node-namespace n)
4393 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4394 (insert "::"))
4395 (insert "[")
4396 (if (js2-xml-elem-ref-node-expr n)
4397 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4398 (insert "]"))
4399
4400 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4401
4402 (cl-defstruct (js2-xml-start-tag-node
4403 (:include js2-xml-node)
4404 (:constructor nil)
4405 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4406 (pos js2-ts-cursor)
4407 len name attrs kids
4408 empty-p)))
4409 "AST node for an XML start-tag. Not currently used.
4410 The `kids' field is a Lisp list of child content nodes."
4411 name ; a `js2-xml-name-node'
4412 attrs ; a Lisp list of `js2-xml-attr-node'
4413 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4414
4415 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4416 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4417
4418 (defun js2-visit-xml-start-tag (n v)
4419 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4420 (dolist (attr (js2-xml-start-tag-node-attrs n))
4421 (js2-visit-ast attr v))
4422 (js2-visit-block n v))
4423
4424 (defun js2-print-xml-start-tag (n i)
4425 (insert (js2-make-pad i) "<")
4426 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4427 (when (js2-xml-start-tag-node-attrs n)
4428 (insert " ")
4429 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4430 (insert ">"))
4431
4432 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4433 ;; and add the end-tag to the kids list of the parent as well.
4434 (cl-defstruct (js2-xml-end-tag-node
4435 (:include js2-xml-node)
4436 (:constructor nil)
4437 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4438 (pos js2-ts-cursor)
4439 len name)))
4440 "AST node for an XML end-tag. Not currently used."
4441 name) ; a `js2-xml-name-node'
4442
4443 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4444 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4445
4446 (defun js2-visit-xml-end-tag (n v)
4447 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4448
4449 (defun js2-print-xml-end-tag (n i)
4450 (insert (js2-make-pad i))
4451 (insert "</")
4452 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4453 (insert ">"))
4454
4455 (cl-defstruct (js2-xml-name-node
4456 (:include js2-xml-node)
4457 (:constructor nil)
4458 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4459 (pos js2-ts-cursor)
4460 len namespace kids)))
4461 "AST node for an E4X XML name. Not currently used.
4462 Any XML name can be qualified with a namespace, hence the namespace field.
4463 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4464 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4465 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4466 namespace) ; a `js2-string-node'
4467
4468 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4469 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4470
4471 (defun js2-visit-xml-name-node (n v)
4472 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4473
4474 (defun js2-print-xml-name-node (n i)
4475 (insert (js2-make-pad i))
4476 (when (js2-xml-name-node-namespace n)
4477 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4478 (insert "::"))
4479 (dolist (kid (js2-xml-name-node-kids n))
4480 (js2-print-ast kid 0)))
4481
4482 (cl-defstruct (js2-xml-pi-node
4483 (:include js2-xml-node)
4484 (:constructor nil)
4485 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4486 (pos js2-ts-cursor)
4487 len name attrs)))
4488 "AST node for an E4X XML processing instruction. Not currently used."
4489 name ; a `js2-xml-name-node'
4490 attrs) ; a list of `js2-xml-attr-node'
4491
4492 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4493 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4494
4495 (defun js2-visit-xml-pi-node (n v)
4496 (js2-visit-ast (js2-xml-pi-node-name n) v)
4497 (dolist (attr (js2-xml-pi-node-attrs n))
4498 (js2-visit-ast attr v)))
4499
4500 (defun js2-print-xml-pi-node (n i)
4501 (insert (js2-make-pad i) "<?")
4502 (js2-print-ast (js2-xml-pi-node-name n))
4503 (when (js2-xml-pi-node-attrs n)
4504 (insert " ")
4505 (js2-print-list (js2-xml-pi-node-attrs n)))
4506 (insert "?>"))
4507
4508 (cl-defstruct (js2-xml-cdata-node
4509 (:include js2-xml-node)
4510 (:constructor nil)
4511 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4512 (pos js2-ts-cursor)
4513 len content)))
4514 "AST node for a CDATA escape section. Not currently used."
4515 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4516
4517 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4518 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4519
4520 (defun js2-visit-xml-cdata-node (n v)
4521 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4522
4523 (defun js2-print-xml-cdata-node (n i)
4524 (insert (js2-make-pad i))
4525 (js2-print-ast (js2-xml-cdata-node-content n)))
4526
4527 (cl-defstruct (js2-xml-attr-node
4528 (:include js2-xml-node)
4529 (:constructor nil)
4530 (:constructor make-js2-attr-node (&key (type js2-XML)
4531 (pos js2-ts-cursor)
4532 len name value
4533 eq-pos quote-type)))
4534 "AST node representing a foo='bar' XML attribute value. Not yet used."
4535 name ; a `js2-xml-name-node'
4536 value ; a `js2-xml-name-node'
4537 eq-pos ; buffer position of "=" sign
4538 quote-type) ; 'single or 'double
4539
4540 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4541 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4542
4543 (defun js2-visit-xml-attr-node (n v)
4544 (js2-visit-ast (js2-xml-attr-node-name n) v)
4545 (js2-visit-ast (js2-xml-attr-node-value n) v))
4546
4547 (defun js2-print-xml-attr-node (n i)
4548 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4549 "'"
4550 "\"")))
4551 (insert (js2-make-pad i))
4552 (js2-print-ast (js2-xml-attr-node-name n) 0)
4553 (insert "=" quote)
4554 (js2-print-ast (js2-xml-attr-node-value n) 0)
4555 (insert quote)))
4556
4557 (cl-defstruct (js2-xml-text-node
4558 (:include js2-xml-node)
4559 (:constructor nil)
4560 (:constructor make-js2-text-node (&key (type js2-XML)
4561 (pos js2-ts-cursor)
4562 len content)))
4563 "AST node for an E4X XML text node. Not currently used."
4564 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4565
4566 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4567 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4568
4569 (defun js2-visit-xml-text-node (n v)
4570 (js2-visit-ast (js2-xml-text-node-content n) v))
4571
4572 (defun js2-print-xml-text-node (n i)
4573 (insert (js2-make-pad i))
4574 (dolist (kid (js2-xml-text-node-content n))
4575 (js2-print-ast kid)))
4576
4577 (cl-defstruct (js2-xml-comment-node
4578 (:include js2-xml-node)
4579 (:constructor nil)
4580 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4581 (pos js2-ts-cursor)
4582 len)))
4583 "AST node for E4X XML comment. Not currently used.")
4584
4585 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4586 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4587
4588 (defun js2-print-xml-comment (n i)
4589 (insert (js2-make-pad i)
4590 (js2-node-string n)))
4591
4592 ;;; Node utilities
4593
4594 (defsubst js2-node-line (n)
4595 "Fetch the source line number at the start of node N.
4596 This is O(n) in the length of the source buffer; use prudently."
4597 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4598
4599 (defsubst js2-block-node-kid (n i)
4600 "Return child I of node N, or nil if there aren't that many."
4601 (nth i (js2-block-node-kids n)))
4602
4603 (defsubst js2-block-node-first (n)
4604 "Return first child of block node N, or nil if there is none."
4605 (cl-first (js2-block-node-kids n)))
4606
4607 (defun js2-node-root (n)
4608 "Return the root of the AST containing N.
4609 If N has no parent pointer, returns N."
4610 (let ((parent (js2-node-parent n)))
4611 (if parent
4612 (js2-node-root parent)
4613 n)))
4614
4615 (defsubst js2-node-short-name (n)
4616 "Return the short name of node N as a string, e.g. `js2-if-node'."
4617 (substring (symbol-name (aref n 0))
4618 (length "cl-struct-")))
4619
4620 (defun js2-node-child-list (node)
4621 "Return the child list for NODE, a Lisp list of nodes.
4622 Works for block nodes, array nodes, obj literals, funarg lists,
4623 var decls and try nodes (for catch clauses). Note that you should call
4624 `js2-block-node-kids' on the function body for the body statements.
4625 Returns nil for zero-length child lists or unsupported nodes."
4626 (cond
4627 ((js2-function-node-p node)
4628 (js2-function-node-params node))
4629 ((js2-block-node-p node)
4630 (js2-block-node-kids node))
4631 ((js2-try-node-p node)
4632 (js2-try-node-catch-clauses node))
4633 ((js2-array-node-p node)
4634 (js2-array-node-elems node))
4635 ((js2-object-node-p node)
4636 (js2-object-node-elems node))
4637 ((js2-call-node-p node)
4638 (js2-call-node-args node))
4639 ((js2-new-node-p node)
4640 (js2-new-node-args node))
4641 ((js2-var-decl-node-p node)
4642 (js2-var-decl-node-kids node))
4643 (t
4644 nil)))
4645
4646 (defun js2-node-set-child-list (node kids)
4647 "Set the child list for NODE to KIDS."
4648 (cond
4649 ((js2-function-node-p node)
4650 (setf (js2-function-node-params node) kids))
4651 ((js2-block-node-p node)
4652 (setf (js2-block-node-kids node) kids))
4653 ((js2-try-node-p node)
4654 (setf (js2-try-node-catch-clauses node) kids))
4655 ((js2-array-node-p node)
4656 (setf (js2-array-node-elems node) kids))
4657 ((js2-object-node-p node)
4658 (setf (js2-object-node-elems node) kids))
4659 ((js2-call-node-p node)
4660 (setf (js2-call-node-args node) kids))
4661 ((js2-new-node-p node)
4662 (setf (js2-new-node-args node) kids))
4663 ((js2-var-decl-node-p node)
4664 (setf (js2-var-decl-node-kids node) kids))
4665 (t
4666 (error "Unsupported node type: %s" (js2-node-short-name node))))
4667 kids)
4668
4669 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4670 (defconst js2-paren-expr-nodes
4671 '(cl-struct-js2-comp-loop-node
4672 cl-struct-js2-comp-node
4673 cl-struct-js2-call-node
4674 cl-struct-js2-catch-node
4675 cl-struct-js2-do-node
4676 cl-struct-js2-elem-get-node
4677 cl-struct-js2-for-in-node
4678 cl-struct-js2-for-node
4679 cl-struct-js2-function-node
4680 cl-struct-js2-if-node
4681 cl-struct-js2-let-node
4682 cl-struct-js2-new-node
4683 cl-struct-js2-paren-node
4684 cl-struct-js2-switch-node
4685 cl-struct-js2-while-node
4686 cl-struct-js2-with-node
4687 cl-struct-js2-xml-dot-query-node)
4688 "Node types that can have a parenthesized child expression.
4689 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4690
4691 (defsubst js2-paren-expr-node-p (node)
4692 "Return t for nodes that typically have a parenthesized child expression.
4693 Useful for computing the indentation anchors for arg-lists and conditions.
4694 Note that it may return a false positive, for instance when NODE is
4695 a `js2-new-node' and there are no arguments or parentheses."
4696 (memq (aref node 0) js2-paren-expr-nodes))
4697
4698 ;; Fake polymorphism... yech.
4699 (defun js2-node-lp (node)
4700 "Return relative left-paren position for NODE, if applicable.
4701 For `js2-elem-get-node' structs, returns left-bracket position.
4702 Note that the position may be nil in the case of a parse error."
4703 (cond
4704 ((js2-elem-get-node-p node)
4705 (js2-elem-get-node-lb node))
4706 ((js2-loop-node-p node)
4707 (js2-loop-node-lp node))
4708 ((js2-function-node-p node)
4709 (js2-function-node-lp node))
4710 ((js2-if-node-p node)
4711 (js2-if-node-lp node))
4712 ((js2-new-node-p node)
4713 (js2-new-node-lp node))
4714 ((js2-call-node-p node)
4715 (js2-call-node-lp node))
4716 ((js2-paren-node-p node)
4717 0)
4718 ((js2-switch-node-p node)
4719 (js2-switch-node-lp node))
4720 ((js2-catch-node-p node)
4721 (js2-catch-node-lp node))
4722 ((js2-let-node-p node)
4723 (js2-let-node-lp node))
4724 ((js2-comp-node-p node)
4725 0)
4726 ((js2-with-node-p node)
4727 (js2-with-node-lp node))
4728 ((js2-xml-dot-query-node-p node)
4729 (1+ (js2-infix-node-op-pos node)))
4730 (t
4731 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4732
4733 ;; Fake polymorphism... blech.
4734 (defun js2-node-rp (node)
4735 "Return relative right-paren position for NODE, if applicable.
4736 For `js2-elem-get-node' structs, returns right-bracket position.
4737 Note that the position may be nil in the case of a parse error."
4738 (cond
4739 ((js2-elem-get-node-p node)
4740 (js2-elem-get-node-rb node))
4741 ((js2-loop-node-p node)
4742 (js2-loop-node-rp node))
4743 ((js2-function-node-p node)
4744 (js2-function-node-rp node))
4745 ((js2-if-node-p node)
4746 (js2-if-node-rp node))
4747 ((js2-new-node-p node)
4748 (js2-new-node-rp node))
4749 ((js2-call-node-p node)
4750 (js2-call-node-rp node))
4751 ((js2-paren-node-p node)
4752 (1- (js2-node-len node)))
4753 ((js2-switch-node-p node)
4754 (js2-switch-node-rp node))
4755 ((js2-catch-node-p node)
4756 (js2-catch-node-rp node))
4757 ((js2-let-node-p node)
4758 (js2-let-node-rp node))
4759 ((js2-comp-node-p node)
4760 (1- (js2-node-len node)))
4761 ((js2-with-node-p node)
4762 (js2-with-node-rp node))
4763 ((js2-xml-dot-query-node-p node)
4764 (1+ (js2-xml-dot-query-node-rp node)))
4765 (t
4766 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4767
4768 (defsubst js2-node-first-child (node)
4769 "Return the first element of `js2-node-child-list' for NODE."
4770 (car (js2-node-child-list node)))
4771
4772 (defsubst js2-node-last-child (node)
4773 "Return the last element of `js2-node-last-child' for NODE."
4774 (car (last (js2-node-child-list node))))
4775
4776 (defun js2-node-prev-sibling (node)
4777 "Return the previous statement in parent.
4778 Works for parents supported by `js2-node-child-list'.
4779 Returns nil if NODE is not in the parent, or PARENT is
4780 not a supported node, or if NODE is the first child."
4781 (let* ((p (js2-node-parent node))
4782 (kids (js2-node-child-list p))
4783 (sib (car kids)))
4784 (while (and kids
4785 (not (eq node (cadr kids))))
4786 (setq kids (cdr kids)
4787 sib (car kids)))
4788 sib))
4789
4790 (defun js2-node-next-sibling (node)
4791 "Return the next statement in parent block.
4792 Returns nil if NODE is not in the block, or PARENT is not
4793 a block node, or if NODE is the last statement."
4794 (let* ((p (js2-node-parent node))
4795 (kids (js2-node-child-list p)))
4796 (while (and kids
4797 (not (eq node (car kids))))
4798 (setq kids (cdr kids)))
4799 (cadr kids)))
4800
4801 (defun js2-node-find-child-before (pos parent &optional after)
4802 "Find the last child that starts before POS in parent.
4803 If AFTER is non-nil, returns first child starting after POS.
4804 POS is an absolute buffer position. PARENT is any node
4805 supported by `js2-node-child-list'.
4806 Returns nil if no applicable child is found."
4807 (let ((kids (if (js2-function-node-p parent)
4808 (js2-block-node-kids (js2-function-node-body parent))
4809 (js2-node-child-list parent)))
4810 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4811 (js2-function-node-body parent)
4812 parent)))
4813 kid result fn
4814 (continue t))
4815 (setq fn (if after '>= '<))
4816 (while (and kids continue)
4817 (setq kid (car kids))
4818 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4819 (setq result kid
4820 continue (not after))
4821 (setq continue after))
4822 (setq kids (cdr kids)))
4823 result))
4824
4825 (defun js2-node-find-child-after (pos parent)
4826 "Find first child that starts after POS in parent.
4827 POS is an absolute buffer position. PARENT is any node
4828 supported by `js2-node-child-list'.
4829 Returns nil if no applicable child is found."
4830 (js2-node-find-child-before pos parent 'after))
4831
4832 (defun js2-node-replace-child (pos parent new-node)
4833 "Replace node at index POS in PARENT with NEW-NODE.
4834 Only works for parents supported by `js2-node-child-list'."
4835 (let ((kids (js2-node-child-list parent))
4836 (i 0))
4837 (while (< i pos)
4838 (setq kids (cdr kids)
4839 i (1+ i)))
4840 (setcar kids new-node)
4841 (js2-node-add-children parent new-node)))
4842
4843 (defun js2-node-buffer (n)
4844 "Return the buffer associated with AST N.
4845 Returns nil if the buffer is not set as a property on the root
4846 node, or if parent links were not recorded during parsing."
4847 (let ((root (js2-node-root n)))
4848 (and root
4849 (js2-ast-root-p root)
4850 (js2-ast-root-buffer root))))
4851
4852 (defun js2-block-node-push (n kid)
4853 "Push js2-node KID onto the end of js2-block-node N's child list.
4854 KID is always added to the -end- of the kids list.
4855 Function also calls `js2-node-add-children' to add the parent link."
4856 (let ((kids (js2-node-child-list n)))
4857 (if kids
4858 (setcdr kids (nconc (cdr kids) (list kid)))
4859 (js2-node-set-child-list n (list kid)))
4860 (js2-node-add-children n kid)))
4861
4862 (defun js2-node-string (node)
4863 (with-current-buffer (or (js2-node-buffer node)
4864 (error "No buffer available for node %s" node))
4865 (let ((pos (js2-node-abs-pos node)))
4866 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4867
4868 ;; Container for storing the node we're looking for in a traversal.
4869 (js2-deflocal js2-discovered-node nil)
4870
4871 ;; Keep track of absolute node position during traversals.
4872 (js2-deflocal js2-visitor-offset nil)
4873
4874 (js2-deflocal js2-node-search-point nil)
4875
4876 (when js2-mode-dev-mode-p
4877 (defun js2-find-node-at-point ()
4878 (interactive)
4879 (let ((node (js2-node-at-point)))
4880 (message "%s" (or node "No node found at point"))))
4881 (defun js2-node-name-at-point ()
4882 (interactive)
4883 (let ((node (js2-node-at-point)))
4884 (message "%s" (if node
4885 (js2-node-short-name node)
4886 "No node found at point.")))))
4887
4888 (defun js2-node-at-point (&optional pos skip-comments)
4889 "Return AST node at POS, a buffer position, defaulting to current point.
4890 The `js2-mode-ast' variable must be set to the current parse tree.
4891 Signals an error if the AST (`js2-mode-ast') is nil.
4892 Always returns a node - if it can't find one, it returns the root.
4893 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4894 (let ((ast js2-mode-ast)
4895 result)
4896 (unless ast
4897 (error "No JavaScript AST available"))
4898 ;; Look through comments first, since they may be inside nodes that
4899 ;; would otherwise report a match.
4900 (setq pos (or pos (point))
4901 result (if (> pos (js2-node-abs-end ast))
4902 ast
4903 (if (not skip-comments)
4904 (js2-comment-at-point pos))))
4905 (unless result
4906 (setq js2-discovered-node nil
4907 js2-visitor-offset 0
4908 js2-node-search-point pos)
4909 (unwind-protect
4910 (catch 'js2-visit-done
4911 (js2-visit-ast ast #'js2-node-at-point-visitor))
4912 (setq js2-visitor-offset nil
4913 js2-node-search-point nil))
4914 (setq result js2-discovered-node))
4915 ;; may have found a comment beyond end of last child node,
4916 ;; since visiting the ast-root looks at the comment-list last.
4917 (if (and skip-comments
4918 (js2-comment-node-p result))
4919 (setq result nil))
4920 (or result js2-mode-ast)))
4921
4922 (defun js2-node-at-point-visitor (node end-p)
4923 (let ((rel-pos (js2-node-pos node))
4924 abs-pos
4925 abs-end
4926 (point js2-node-search-point))
4927 (cond
4928 (end-p
4929 ;; this evaluates to a non-nil return value, even if it's zero
4930 (cl-decf js2-visitor-offset rel-pos))
4931 ;; we already looked for comments before visiting, and don't want them now
4932 ((js2-comment-node-p node)
4933 nil)
4934 (t
4935 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4936 ;; we only want to use the node if the point is before
4937 ;; the last character position in the node, so we decrement
4938 ;; the absolute end by 1.
4939 abs-end (+ abs-pos (js2-node-len node) -1))
4940 (cond
4941 ;; If this node starts after search-point, stop the search.
4942 ((> abs-pos point)
4943 (throw 'js2-visit-done nil))
4944 ;; If this node ends before the search-point, don't check kids.
4945 ((> point abs-end)
4946 nil)
4947 (t
4948 ;; Otherwise point is within this node, possibly in a child.
4949 (setq js2-discovered-node node)
4950 t)))))) ; keep processing kids to look for more specific match
4951
4952 (defsubst js2-block-comment-p (node)
4953 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4954 (and (js2-comment-node-p node)
4955 (memq (js2-comment-node-format node) '(jsdoc block))))
4956
4957 ;; TODO: put the comments in a vector and binary-search them instead
4958 (defun js2-comment-at-point (&optional pos)
4959 "Look through scanned comment nodes for one containing POS.
4960 POS is a buffer position that defaults to current point.
4961 Function returns nil if POS was not in any comment node."
4962 (let ((ast js2-mode-ast)
4963 (x (or pos (point)))
4964 beg end)
4965 (unless ast
4966 (error "No JavaScript AST available"))
4967 (catch 'done
4968 ;; Comments are stored in lexical order.
4969 (dolist (comment (js2-ast-root-comments ast) nil)
4970 (setq beg (js2-node-abs-pos comment)
4971 end (+ beg (js2-node-len comment)))
4972 (if (and (>= x beg)
4973 (<= x end))
4974 (throw 'done comment))))))
4975
4976 (defun js2-mode-find-parent-fn (node)
4977 "Find function enclosing NODE.
4978 Returns nil if NODE is not inside a function."
4979 (setq node (js2-node-parent node))
4980 (while (and node (not (js2-function-node-p node)))
4981 (setq node (js2-node-parent node)))
4982 (and (js2-function-node-p node) node))
4983
4984 (defun js2-mode-find-enclosing-fn (node)
4985 "Find function or root enclosing NODE."
4986 (if (js2-ast-root-p node)
4987 node
4988 (setq node (js2-node-parent node))
4989 (while (not (or (js2-ast-root-p node)
4990 (js2-function-node-p node)))
4991 (setq node (js2-node-parent node)))
4992 node))
4993
4994 (defun js2-mode-find-enclosing-node (beg end)
4995 "Find node fully enclosing BEG and END."
4996 (let ((node (js2-node-at-point beg))
4997 pos
4998 (continue t))
4999 (while continue
5000 (if (or (js2-ast-root-p node)
5001 (and
5002 (<= (setq pos (js2-node-abs-pos node)) beg)
5003 (>= (+ pos (js2-node-len node)) end)))
5004 (setq continue nil)
5005 (setq node (js2-node-parent node))))
5006 node))
5007
5008 (defun js2-node-parent-script-or-fn (node)
5009 "Find script or function immediately enclosing NODE.
5010 If NODE is the ast-root, returns nil."
5011 (if (js2-ast-root-p node)
5012 nil
5013 (setq node (js2-node-parent node))
5014 (while (and node (not (or (js2-function-node-p node)
5015 (js2-script-node-p node))))
5016 (setq node (js2-node-parent node)))
5017 node))
5018
5019 (defun js2-node-is-descendant (node ancestor)
5020 "Return t if NODE is a descendant of ANCESTOR."
5021 (while (and node
5022 (not (eq node ancestor)))
5023 (setq node (js2-node-parent node)))
5024 node)
5025
5026 ;;; visitor infrastructure
5027
5028 (defun js2-visit-none (_node _callback)
5029 "Visitor for AST node that have no node children."
5030 nil)
5031
5032 (defun js2-print-none (_node _indent)
5033 "Visitor for AST node with no printed representation.")
5034
5035 (defun js2-print-body (node indent)
5036 "Print a statement, or a block without braces."
5037 (if (js2-block-node-p node)
5038 (dolist (kid (js2-block-node-kids node))
5039 (js2-print-ast kid indent))
5040 (js2-print-ast node indent)))
5041
5042 (defun js2-print-list (args &optional delimiter)
5043 (cl-loop with len = (length args)
5044 for arg in args
5045 for count from 1
5046 do
5047 (when arg (js2-print-ast arg 0))
5048 (if (< count len)
5049 (insert (or delimiter ", ")))))
5050
5051 (defun js2-print-tree (ast)
5052 "Prints an AST to the current buffer.
5053 Makes `js2-ast-parent-nodes' available to the printer functions."
5054 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5055 (js2-print-ast ast)))
5056
5057 (defun js2-print-ast (node &optional indent)
5058 "Helper function for printing AST nodes.
5059 Requires `js2-ast-parent-nodes' to be non-nil.
5060 You should use `js2-print-tree' instead of this function."
5061 (let ((printer (get (aref node 0) 'js2-printer))
5062 (i (or indent 0)))
5063 ;; TODO: wedge comments in here somewhere
5064 (if printer
5065 (funcall printer node i))))
5066
5067 (defconst js2-side-effecting-tokens
5068 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5069 (dolist (tt (list js2-ASSIGN
5070 js2-ASSIGN_ADD
5071 js2-ASSIGN_BITAND
5072 js2-ASSIGN_BITOR
5073 js2-ASSIGN_BITXOR
5074 js2-ASSIGN_DIV
5075 js2-ASSIGN_LSH
5076 js2-ASSIGN_MOD
5077 js2-ASSIGN_MUL
5078 js2-ASSIGN_RSH
5079 js2-ASSIGN_SUB
5080 js2-ASSIGN_URSH
5081 js2-BLOCK
5082 js2-BREAK
5083 js2-CALL
5084 js2-CATCH
5085 js2-CATCH_SCOPE
5086 js2-CLASS
5087 js2-CONST
5088 js2-CONTINUE
5089 js2-DEBUGGER
5090 js2-DEC
5091 js2-DELPROP
5092 js2-DEL_REF
5093 js2-DO
5094 js2-ELSE
5095 js2-EMPTY
5096 js2-ENTERWITH
5097 js2-EXPORT
5098 js2-EXPR_RESULT
5099 js2-FINALLY
5100 js2-FOR
5101 js2-FUNCTION
5102 js2-GOTO
5103 js2-IF
5104 js2-IFEQ
5105 js2-IFNE
5106 js2-IMPORT
5107 js2-INC
5108 js2-JSR
5109 js2-LABEL
5110 js2-LEAVEWITH
5111 js2-LET
5112 js2-LETEXPR
5113 js2-LOCAL_BLOCK
5114 js2-LOOP
5115 js2-NEW
5116 js2-REF_CALL
5117 js2-RETHROW
5118 js2-RETURN
5119 js2-RETURN_RESULT
5120 js2-SEMI
5121 js2-SETELEM
5122 js2-SETELEM_OP
5123 js2-SETNAME
5124 js2-SETPROP
5125 js2-SETPROP_OP
5126 js2-SETVAR
5127 js2-SET_REF
5128 js2-SET_REF_OP
5129 js2-SWITCH
5130 js2-TARGET
5131 js2-THROW
5132 js2-TRY
5133 js2-VAR
5134 js2-WHILE
5135 js2-WITH
5136 js2-WITHEXPR
5137 js2-YIELD))
5138 (aset tokens tt t))
5139 (if js2-instanceof-has-side-effects
5140 (aset tokens js2-INSTANCEOF t))
5141 tokens))
5142
5143 (defun js2-node-has-side-effects (node)
5144 "Return t if NODE has side effects."
5145 (when node ; makes it easier to handle malformed expressions
5146 (let ((tt (js2-node-type node)))
5147 (cond
5148 ;; This doubtless needs some work, since EXPR_VOID is used
5149 ;; in several ways in Rhino and I may not have caught them all.
5150 ;; I'll wait for people to notice incorrect warnings.
5151 ((and (= tt js2-EXPR_VOID)
5152 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5153 (let ((expr (js2-expr-stmt-node-expr node)))
5154 (or (js2-node-has-side-effects expr)
5155 (when (js2-string-node-p expr)
5156 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5157 ((= tt js2-AWAIT)
5158 (js2-node-has-side-effects (js2-unary-node-operand node)))
5159 ((= tt js2-COMMA)
5160 (js2-node-has-side-effects (js2-infix-node-right node)))
5161 ((or (= tt js2-AND)
5162 (= tt js2-OR))
5163 (or (js2-node-has-side-effects (js2-infix-node-right node))
5164 (js2-node-has-side-effects (js2-infix-node-left node))))
5165 ((= tt js2-HOOK)
5166 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5167 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5168 ((js2-paren-node-p node)
5169 (js2-node-has-side-effects (js2-paren-node-expr node)))
5170 ((= tt js2-ERROR) ; avoid cascaded error messages
5171 nil)
5172 (t
5173 (aref js2-side-effecting-tokens tt))))))
5174
5175 (defconst js2-stmt-node-types
5176 (list js2-BLOCK
5177 js2-BREAK
5178 js2-CONTINUE
5179 js2-DEFAULT ; e4x "default xml namespace" statement
5180 js2-DO
5181 js2-EXPORT
5182 js2-EXPR_RESULT
5183 js2-EXPR_VOID
5184 js2-FOR
5185 js2-IF
5186 js2-IMPORT
5187 js2-RETURN
5188 js2-SWITCH
5189 js2-THROW
5190 js2-TRY
5191 js2-WHILE
5192 js2-WITH)
5193 "Node types that only appear in statement contexts.
5194 The list does not include nodes that always appear as the child
5195 of another specific statement type, such as switch-cases,
5196 catch and finally blocks, and else-clauses. The list also excludes
5197 nodes like yield, let and var, which may appear in either expression
5198 or statement context, and in the latter context always have a
5199 `js2-expr-stmt-node' parent. Finally, the list does not include
5200 functions or scripts, which are treated separately from statements
5201 by the JavaScript parser and runtime.")
5202
5203 (defun js2-stmt-node-p (node)
5204 "Heuristic for figuring out if NODE is a statement.
5205 Some node types can appear in either an expression context or a
5206 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5207 For these node types in a statement context, the parent will be a
5208 `js2-expr-stmt-node'.
5209 Functions aren't included in the check."
5210 (memq (js2-node-type node) js2-stmt-node-types))
5211
5212 (defun js2-mode-find-first-stmt (node)
5213 "Search upward starting from NODE looking for a statement.
5214 For purposes of this function, a `js2-function-node' counts."
5215 (while (not (or (js2-stmt-node-p node)
5216 (js2-function-node-p node)))
5217 (setq node (js2-node-parent node)))
5218 node)
5219
5220 (defun js2-node-parent-stmt (node)
5221 "Return the node's first ancestor that is a statement.
5222 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5223 appearing in a statement context will have a parent that is a
5224 `js2-expr-stmt-node' that will be returned by this function."
5225 (let ((parent (js2-node-parent node)))
5226 (if (or (null parent)
5227 (js2-stmt-node-p parent)
5228 (and (js2-function-node-p parent)
5229 (not (eq (js2-function-node-form parent)
5230 'FUNCTION_EXPRESSION))))
5231 parent
5232 (js2-node-parent-stmt parent))))
5233
5234 ;; In the Mozilla Rhino sources, Roshan James writes:
5235 ;; Does consistent-return analysis on the function body when strict mode is
5236 ;; enabled.
5237 ;;
5238 ;; function (x) { return (x+1) }
5239 ;;
5240 ;; is ok, but
5241 ;;
5242 ;; function (x) { if (x < 0) return (x+1); }
5243 ;;
5244 ;; is not because the function can potentially return a value when the
5245 ;; condition is satisfied and if not, the function does not explicitly
5246 ;; return a value.
5247 ;;
5248 ;; This extends to checking mismatches such as "return" and "return <value>"
5249 ;; used in the same function. Warnings are not emitted if inconsistent
5250 ;; returns exist in code that can be statically shown to be unreachable.
5251 ;; Ex.
5252 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5253 ;;
5254 ;; emits no warning. However if the loop had a break statement, then a
5255 ;; warning would be emitted.
5256 ;;
5257 ;; The consistency analysis looks at control structures such as loops, ifs,
5258 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5259 ;; warns the user about an inconsistent set of termination possibilities.
5260 ;;
5261 ;; These flags enumerate the possible ways a statement/function can
5262 ;; terminate. These flags are used by endCheck() and by the Parser to
5263 ;; detect inconsistent return usage.
5264 ;;
5265 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5266 ;; able to execute (example: throw, continue)
5267 ;;
5268 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5269 ;; next one. Statement such as return dont. A compound statement may have
5270 ;; some branch that drops off control to the next statement.
5271 ;;
5272 ;; END_RETURNS indicates that the statement can return with no value.
5273 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5274 ;;
5275 ;; A compound statement such as
5276 ;; if (condition) {
5277 ;; return value;
5278 ;; }
5279 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5280
5281 (defconst js2-END_UNREACHED 0)
5282 (defconst js2-END_DROPS_OFF 1)
5283 (defconst js2-END_RETURNS 2)
5284 (defconst js2-END_RETURNS_VALUE 4)
5285 (defconst js2-END_YIELDS 8)
5286
5287 (defun js2-has-consistent-return-usage (node)
5288 "Check that every return usage in a function body is consistent.
5289 Returns t if the function satisfies strict mode requirement."
5290 (let ((n (js2-end-check node)))
5291 ;; either it doesn't return a value in any branch...
5292 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5293 ;; or it returns a value (or is unreached) at every branch
5294 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5295 js2-END_RETURNS
5296 js2-END_YIELDS)))))
5297
5298 (defun js2-end-check-if (node)
5299 "Ensure that return usage in then/else blocks is consistent.
5300 If there is no else block, then the return statement can fall through.
5301 Returns logical OR of END_* flags"
5302 (let ((th (js2-if-node-then-part node))
5303 (el (js2-if-node-else-part node)))
5304 (if (null th)
5305 js2-END_UNREACHED
5306 (logior (js2-end-check th) (if el
5307 (js2-end-check el)
5308 js2-END_DROPS_OFF)))))
5309
5310 (defun js2-end-check-switch (node)
5311 "Consistency of return statements is checked between the case statements.
5312 If there is no default, then the switch can fall through. If there is a
5313 default, we check to see if all code paths in the default return or if
5314 there is a code path that can fall through.
5315 Returns logical OR of END_* flags."
5316 (let ((rv js2-END_UNREACHED)
5317 default-case)
5318 ;; examine the cases
5319 (catch 'break
5320 (dolist (c (js2-switch-node-cases node))
5321 (if (js2-case-node-expr c)
5322 (js2-set-flag rv (js2-end-check-block c))
5323 (setq default-case c)
5324 (throw 'break nil))))
5325 ;; we don't care how the cases drop into each other
5326 (js2-clear-flag rv js2-END_DROPS_OFF)
5327 ;; examine the default
5328 (js2-set-flag rv (if default-case
5329 (js2-end-check default-case)
5330 js2-END_DROPS_OFF))
5331 rv))
5332
5333 (defun js2-end-check-try (node)
5334 "If the block has a finally, return consistency is checked in the
5335 finally block. If all code paths in the finally return, then the
5336 returns in the try-catch blocks don't matter. If there is a code path
5337 that does not return or if there is no finally block, the returns
5338 of the try and catch blocks are checked for mismatch.
5339 Returns logical OR of END_* flags."
5340 (let ((finally (js2-try-node-finally-block node))
5341 rv)
5342 ;; check the finally if it exists
5343 (setq rv (if finally
5344 (js2-end-check (js2-finally-node-body finally))
5345 js2-END_DROPS_OFF))
5346 ;; If the finally block always returns, then none of the returns
5347 ;; in the try or catch blocks matter.
5348 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5349 (js2-clear-flag rv js2-END_DROPS_OFF)
5350 ;; examine the try block
5351 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5352 ;; check each catch block
5353 (dolist (cb (js2-try-node-catch-clauses node))
5354 (js2-set-flag rv (js2-end-check cb))))
5355 rv))
5356
5357 (defun js2-end-check-loop (node)
5358 "Return statement in the loop body must be consistent.
5359 The default assumption for any kind of a loop is that it will eventually
5360 terminate. The only exception is a loop with a constant true condition.
5361 Code that follows such a loop is examined only if one can determine
5362 statically that there is a break out of the loop.
5363
5364 for(... ; ... ; ...) {}
5365 for(... in ... ) {}
5366 while(...) { }
5367 do { } while(...)
5368
5369 Returns logical OR of END_* flags."
5370 (let ((rv (js2-end-check (js2-loop-node-body node)))
5371 (condition (cond
5372 ((js2-while-node-p node)
5373 (js2-while-node-condition node))
5374 ((js2-do-node-p node)
5375 (js2-do-node-condition node))
5376 ((js2-for-node-p node)
5377 (js2-for-node-condition node)))))
5378
5379 ;; check to see if the loop condition is always true
5380 (if (and condition
5381 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5382 (js2-clear-flag rv js2-END_DROPS_OFF))
5383
5384 ;; look for effect of breaks
5385 (js2-set-flag rv (js2-node-get-prop node
5386 'CONTROL_BLOCK_PROP
5387 js2-END_UNREACHED))
5388 rv))
5389
5390 (defun js2-end-check-block (node)
5391 "A general block of code is examined statement by statement.
5392 If any statement (even a compound one) returns in all branches, then
5393 subsequent statements are not examined.
5394 Returns logical OR of END_* flags."
5395 (let* ((rv js2-END_DROPS_OFF)
5396 (kids (js2-block-node-kids node))
5397 (n (car kids)))
5398 ;; Check each statement. If the statement can continue onto the next
5399 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5400 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5401 (js2-clear-flag rv js2-END_DROPS_OFF)
5402 (js2-set-flag rv (js2-end-check n))
5403 (setq kids (cdr kids)
5404 n (car kids)))
5405 rv))
5406
5407 (defun js2-end-check-label (node)
5408 "A labeled statement implies that there may be a break to the label.
5409 The function processes the labeled statement and then checks the
5410 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5411 particular label.
5412 Returns logical OR of END_* flags."
5413 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5414 (logior rv (js2-node-get-prop node
5415 'CONTROL_BLOCK_PROP
5416 js2-END_UNREACHED))))
5417
5418 (defun js2-end-check-break (node)
5419 "When a break is encountered annotate the statement being broken
5420 out of by setting its CONTROL_BLOCK_PROP property.
5421 Returns logical OR of END_* flags."
5422 (and (js2-break-node-target node)
5423 (js2-node-set-prop (js2-break-node-target node)
5424 'CONTROL_BLOCK_PROP
5425 js2-END_DROPS_OFF))
5426 js2-END_UNREACHED)
5427
5428 (defun js2-end-check (node)
5429 "Examine the body of a function, doing a basic reachability analysis.
5430 Returns a combination of flags END_* flags that indicate
5431 how the function execution can terminate. These constitute only the
5432 pessimistic set of termination conditions. It is possible that at
5433 runtime certain code paths will never be actually taken. Hence this
5434 analysis will flag errors in cases where there may not be errors.
5435 Returns logical OR of END_* flags"
5436 (let (kid)
5437 (cond
5438 ((js2-break-node-p node)
5439 (js2-end-check-break node))
5440 ((js2-expr-stmt-node-p node)
5441 (if (setq kid (js2-expr-stmt-node-expr node))
5442 (js2-end-check kid)
5443 js2-END_DROPS_OFF))
5444 ((or (js2-continue-node-p node)
5445 (js2-throw-node-p node))
5446 js2-END_UNREACHED)
5447 ((js2-return-node-p node)
5448 (if (setq kid (js2-return-node-retval node))
5449 js2-END_RETURNS_VALUE
5450 js2-END_RETURNS))
5451 ((js2-loop-node-p node)
5452 (js2-end-check-loop node))
5453 ((js2-switch-node-p node)
5454 (js2-end-check-switch node))
5455 ((js2-labeled-stmt-node-p node)
5456 (js2-end-check-label node))
5457 ((js2-if-node-p node)
5458 (js2-end-check-if node))
5459 ((js2-try-node-p node)
5460 (js2-end-check-try node))
5461 ((js2-block-node-p node)
5462 (if (null (js2-block-node-kids node))
5463 js2-END_DROPS_OFF
5464 (js2-end-check-block node)))
5465 ((js2-yield-node-p node)
5466 js2-END_YIELDS)
5467 (t
5468 js2-END_DROPS_OFF))))
5469
5470 (defun js2-always-defined-boolean-p (node)
5471 "Check if NODE always evaluates to true or false in boolean context.
5472 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5473 nor always false."
5474 (let ((tt (js2-node-type node))
5475 num)
5476 (cond
5477 ((or (= tt js2-FALSE) (= tt js2-NULL))
5478 'ALWAYS_FALSE)
5479 ((= tt js2-TRUE)
5480 'ALWAYS_TRUE)
5481 ((= tt js2-NUMBER)
5482 (setq num (js2-number-node-num-value node))
5483 (if (and (not (eq num 0.0e+NaN))
5484 (not (zerop num)))
5485 'ALWAYS_TRUE
5486 'ALWAYS_FALSE))
5487 (t
5488 nil))))
5489
5490 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5491 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5492
5493 (defvar js2-tokens nil
5494 "List of all defined token names.") ; initialized in `js2-token-names'
5495
5496 (defconst js2-token-names
5497 (let* ((names (make-vector js2-num-tokens -1))
5498 (case-fold-search nil) ; only match js2-UPPER_CASE
5499 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5500 (cl-loop for sym in syms
5501 for i from 0
5502 do
5503 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5504 (not (boundp sym)))
5505 (aset names (symbol-value sym) ; code, e.g. 152
5506 (downcase
5507 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5508 (push sym js2-tokens)))
5509 names)
5510 "Vector mapping int values to token string names, sans `js2-' prefix.")
5511
5512 (defun js2-tt-name (tok)
5513 "Return a string name for TOK, a token symbol or code.
5514 Signals an error if it's not a recognized token."
5515 (let ((code tok))
5516 (if (symbolp tok)
5517 (setq code (symbol-value tok)))
5518 (if (eq code -1)
5519 "ERROR"
5520 (if (and (numberp code)
5521 (not (cl-minusp code))
5522 (< code js2-num-tokens))
5523 (aref js2-token-names code)
5524 (error "Invalid token: %s" code)))))
5525
5526 (defsubst js2-tt-sym (tok)
5527 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5528 (intern (js2-tt-name tok)))
5529
5530 (defconst js2-token-codes
5531 (let ((table (make-hash-table :test 'eq :size 256)))
5532 (cl-loop for name across js2-token-names
5533 for sym = (intern (concat "js2-" (upcase name)))
5534 do
5535 (puthash sym (symbol-value sym) table))
5536 ;; clean up a few that are "wrong" in Rhino's token codes
5537 (puthash 'js2-DELETE js2-DELPROP table)
5538 table)
5539 "Hashtable mapping token type symbols to their bytecodes.")
5540
5541 (defsubst js2-tt-code (sym)
5542 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5543 (or (gethash sym js2-token-codes)
5544 (error "Invalid token symbol: %s " sym))) ; signal code bug
5545
5546 (defun js2-report-scan-error (msg &optional no-throw beg len)
5547 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5548 (js2-report-error msg nil
5549 (or beg (js2-current-token-beg))
5550 (or len (js2-current-token-len)))
5551 (unless no-throw
5552 (throw 'return js2-ERROR)))
5553
5554 (defun js2-set-string-from-buffer (token)
5555 "Set `string' and `end' slots for TOKEN, return the string."
5556 (setf (js2-token-end token) js2-ts-cursor
5557 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5558
5559 ;; TODO: could potentially avoid a lot of consing by allocating a
5560 ;; char buffer the way Rhino does.
5561 (defsubst js2-add-to-string (c)
5562 (push c js2-ts-string-buffer))
5563
5564 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5565 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5566 ;; any other character: when it's not part of the current token, we
5567 ;; unget it, allowing it to be read again by the following call.
5568 (defsubst js2-unget-char ()
5569 (cl-decf js2-ts-cursor))
5570
5571 ;; Rhino distinguishes \r and \n line endings. We don't need to
5572 ;; because we only scan from Emacs buffers, which always use \n.
5573 (defun js2-get-char ()
5574 "Read and return the next character from the input buffer.
5575 Increments `js2-ts-lineno' if the return value is a newline char.
5576 Updates `js2-ts-cursor' to the point after the returned char.
5577 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5578 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5579 (let (c)
5580 ;; check for end of buffer
5581 (if (>= js2-ts-cursor (point-max))
5582 (setq js2-ts-hit-eof t
5583 js2-ts-cursor (1+ js2-ts-cursor)
5584 c js2-EOF_CHAR) ; return value
5585 ;; otherwise read next char
5586 (setq c (char-before (cl-incf js2-ts-cursor)))
5587 ;; if we read a newline, update counters
5588 (if (= c ?\n)
5589 (setq js2-ts-line-start js2-ts-cursor
5590 js2-ts-lineno (1+ js2-ts-lineno)))
5591 ;; TODO: skip over format characters
5592 c)))
5593
5594 (defun js2-read-unicode-escape ()
5595 "Read a \\uNNNN sequence from the input.
5596 Assumes the ?\ and ?u have already been read.
5597 Returns the unicode character, or nil if it wasn't a valid character.
5598 Doesn't change the values of any scanner variables."
5599 ;; I really wish I knew a better way to do this, but I can't
5600 ;; find the Emacs function that takes a 16-bit int and converts
5601 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5602 ;; Have to first check that it's 4 hex characters or it may stop
5603 ;; the read early.
5604 (ignore-errors
5605 (let ((s (buffer-substring-no-properties js2-ts-cursor
5606 (+ 4 js2-ts-cursor))))
5607 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5608 (read (concat "?\\u" s))))))
5609
5610 (defun js2-match-char (test)
5611 "Consume and return next character if it matches TEST, a character.
5612 Returns nil and consumes nothing if TEST is not the next character."
5613 (let ((c (js2-get-char)))
5614 (if (eq c test)
5615 t
5616 (js2-unget-char)
5617 nil)))
5618
5619 (defun js2-peek-char ()
5620 (prog1
5621 (js2-get-char)
5622 (js2-unget-char)))
5623
5624 (defun js2-identifier-start-p (c)
5625 "Is C a valid start to an ES5 Identifier?
5626 See http://es5.github.io/#x7.6"
5627 (or
5628 (memq c '(?$ ?_))
5629 (memq (get-char-code-property c 'general-category)
5630 ;; Letters
5631 '(Lu Ll Lt Lm Lo Nl))))
5632
5633 (defun js2-identifier-part-p (c)
5634 "Is C a valid part of an ES5 Identifier?
5635 See http://es5.github.io/#x7.6"
5636 (or
5637 (memq c '(?$ ?_ ?\u200c ?\u200d))
5638 (memq (get-char-code-property c 'general-category)
5639 '(;; Letters
5640 Lu Ll Lt Lm Lo Nl
5641 ;; Combining Marks
5642 Mn Mc
5643 ;; Digits
5644 Nd
5645 ;; Connector Punctuation
5646 Pc))))
5647
5648 (defun js2-alpha-p (c)
5649 (cond ((and (<= ?A c) (<= c ?Z)) t)
5650 ((and (<= ?a c) (<= c ?z)) t)
5651 (t nil)))
5652
5653 (defsubst js2-digit-p (c)
5654 (and (<= ?0 c) (<= c ?9)))
5655
5656 (defun js2-js-space-p (c)
5657 (if (<= c 127)
5658 (memq c '(#x20 #x9 #xB #xC #xD))
5659 (or
5660 (eq c #xA0)
5661 ;; TODO: change this nil to check for Unicode space character
5662 nil)))
5663
5664 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5665
5666 (defun js2-skip-line ()
5667 "Skip to end of line."
5668 (while (not (memq (js2-get-char) js2-eol-chars)))
5669 (js2-unget-char)
5670 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5671
5672 (defun js2-init-scanner (&optional buf line)
5673 "Create token stream for BUF starting on LINE.
5674 BUF defaults to `current-buffer' and LINE defaults to 1.
5675
5676 A buffer can only have one scanner active at a time, which yields
5677 dramatically simpler code than using a defstruct. If you need to
5678 have simultaneous scanners in a buffer, copy the regions to scan
5679 into temp buffers."
5680 (with-current-buffer (or buf (current-buffer))
5681 (setq js2-ts-dirty-line nil
5682 js2-ts-hit-eof nil
5683 js2-ts-line-start 0
5684 js2-ts-lineno (or line 1)
5685 js2-ts-line-end-char -1
5686 js2-ts-cursor (point-min)
5687 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5688 js2-ti-tokens-cursor 0
5689 js2-ti-lookahead 0
5690 js2-ts-is-xml-attribute nil
5691 js2-ts-xml-is-tag-content nil
5692 js2-ts-xml-open-tags-count 0
5693 js2-ts-string-buffer nil)))
5694
5695 ;; This function uses the cached op, string and number fields in
5696 ;; TokenStream; if getToken has been called since the passed token
5697 ;; was scanned, the op or string printed may be incorrect.
5698 (defun js2-token-to-string (token)
5699 ;; Not sure where this function is used in Rhino. Not tested.
5700 (if (not js2-debug-print-trees)
5701 ""
5702 (let ((name (js2-tt-name token)))
5703 (cond
5704 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5705 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5706 (concat name " `" (js2-current-token-string) "'"))
5707 ((eq token js2-NUMBER)
5708 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5709 (t
5710 name)))))
5711
5712 (defconst js2-keywords
5713 '(break
5714 case catch class const continue
5715 debugger default delete do
5716 else extends export
5717 false finally for function
5718 if in instanceof import
5719 let
5720 new null
5721 return
5722 super switch
5723 this throw true try typeof
5724 var void
5725 while with
5726 yield))
5727
5728 ;; Token names aren't exactly the same as the keywords, unfortunately.
5729 ;; E.g. delete is js2-DELPROP.
5730 (defconst js2-kwd-tokens
5731 (let ((table (make-vector js2-num-tokens nil))
5732 (tokens
5733 (list js2-BREAK
5734 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5735 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5736 js2-ELSE js2-EXPORT
5737 js2-ELSE js2-EXTENDS js2-EXPORT
5738 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5739 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5740 js2-LET
5741 js2-NEW js2-NULL
5742 js2-RETURN
5743 js2-SUPER js2-SWITCH
5744 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5745 js2-VAR
5746 js2-WHILE js2-WITH
5747 js2-YIELD)))
5748 (dolist (i tokens)
5749 (aset table i 'font-lock-keyword-face))
5750 (aset table js2-STRING 'font-lock-string-face)
5751 (aset table js2-REGEXP 'font-lock-string-face)
5752 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5753 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5754 (aset table js2-COMMENT 'font-lock-comment-face)
5755 (aset table js2-THIS 'font-lock-builtin-face)
5756 (aset table js2-SUPER 'font-lock-builtin-face)
5757 (aset table js2-VOID 'font-lock-constant-face)
5758 (aset table js2-NULL 'font-lock-constant-face)
5759 (aset table js2-TRUE 'font-lock-constant-face)
5760 (aset table js2-FALSE 'font-lock-constant-face)
5761 (aset table js2-NOT 'font-lock-negation-char-face)
5762 table)
5763 "Vector whose values are non-nil for tokens that are keywords.
5764 The values are default faces to use for highlighting the keywords.")
5765
5766 ;; FIXME: Support strict mode-only future reserved words, after we know
5767 ;; which parts scopes are in strict mode, and which are not.
5768 (defconst js2-reserved-words '(class enum export extends import static super)
5769 "Future reserved keywords in ECMAScript 5.1.")
5770
5771 (defconst js2-keyword-names
5772 (let ((table (make-hash-table :test 'equal)))
5773 (cl-loop for k in js2-keywords
5774 do (puthash
5775 (symbol-name k) ; instanceof
5776 (intern (concat "js2-"
5777 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5778 table))
5779 table)
5780 "JavaScript keywords by name, mapped to their symbols.")
5781
5782 (defconst js2-reserved-word-names
5783 (let ((table (make-hash-table :test 'equal)))
5784 (cl-loop for k in js2-reserved-words
5785 do
5786 (puthash (symbol-name k) 'js2-RESERVED table))
5787 table)
5788 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5789
5790 (defun js2-collect-string (buf)
5791 "Convert BUF, a list of chars, to a string.
5792 Reverses BUF before converting."
5793 (if buf
5794 (apply #'string (nreverse buf))
5795 ""))
5796
5797 (defun js2-string-to-keyword (s)
5798 "Return token for S, a string, if S is a keyword or reserved word.
5799 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5800 (or (gethash s js2-keyword-names)
5801 (gethash s js2-reserved-word-names)))
5802
5803 (defsubst js2-ts-set-char-token-bounds (token)
5804 "Used when next token is one character."
5805 (setf (js2-token-beg token) (1- js2-ts-cursor)
5806 (js2-token-end token) js2-ts-cursor))
5807
5808 (defsubst js2-ts-return (token type)
5809 "Update the `end' and `type' slots of TOKEN,
5810 then throw `return' with value TYPE."
5811 (setf (js2-token-end token) js2-ts-cursor
5812 (js2-token-type token) type)
5813 (throw 'return type))
5814
5815 (defun js2-x-digit-to-int (c accumulator)
5816 "Build up a hex number.
5817 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5818 corresponding number. Otherwise return -1."
5819 (catch 'return
5820 (catch 'check
5821 ;; Use 0..9 < A..Z < a..z
5822 (cond
5823 ((<= c ?9)
5824 (cl-decf c ?0)
5825 (if (<= 0 c)
5826 (throw 'check nil)))
5827 ((<= c ?F)
5828 (when (<= ?A c)
5829 (cl-decf c (- ?A 10))
5830 (throw 'check nil)))
5831 ((<= c ?f)
5832 (when (<= ?a c)
5833 (cl-decf c (- ?a 10))
5834 (throw 'check nil))))
5835 (throw 'return -1))
5836 (logior c (lsh accumulator 4))))
5837
5838 (defun js2-get-token (&optional modifier)
5839 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5840 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5841 next saved token.
5842
5843 This function will not return a newline (js2-EOL) - instead, it
5844 gobbles newlines until it finds a non-newline token. Call
5845 `js2-peek-token-or-eol' when you care about newlines.
5846
5847 This function will also not return a js2-COMMENT. Instead, it
5848 records comments found in `js2-scanned-comments'. If the token
5849 returned by this function immediately follows a jsdoc comment,
5850 the token is flagged as such."
5851 (if (zerop js2-ti-lookahead)
5852 (js2-get-token-internal modifier)
5853 (cl-decf js2-ti-lookahead)
5854 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5855 (let ((tt (js2-current-token-type)))
5856 (cl-assert (not (= tt js2-EOL)))
5857 tt)))
5858
5859 (defun js2-unget-token ()
5860 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5861 (cl-incf js2-ti-lookahead)
5862 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5863
5864 (defun js2-get-token-internal (modifier)
5865 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5866 (tt (js2-token-type token))
5867 saw-eol
5868 face)
5869 ;; process comments
5870 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5871 (if (= tt js2-EOL)
5872 (setq saw-eol t)
5873 (setq saw-eol nil)
5874 (when js2-record-comments
5875 (js2-record-comment token)))
5876 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5877 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5878 tt (js2-token-type token)))
5879
5880 (when saw-eol
5881 (setf (js2-token-follows-eol-p token) t))
5882
5883 ;; perform lexical fontification as soon as token is scanned
5884 (when js2-parse-ide-mode
5885 (cond
5886 ((cl-minusp tt)
5887 (js2-record-face 'js2-error token))
5888 ((setq face (aref js2-kwd-tokens tt))
5889 (js2-record-face face token))
5890 ((and (= tt js2-NAME)
5891 (equal (js2-token-string token) "undefined"))
5892 (js2-record-face 'font-lock-constant-face token))))
5893 tt))
5894
5895 (defsubst js2-string-to-number (str base)
5896 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5897 (condition-case nil
5898 (string-to-number str base)
5899 (overflow-error -1)))
5900
5901 (defun js2-get-token-internal-1 (modifier)
5902 "Return next JavaScript token type, an int such as js2-RETURN.
5903 During operation, creates an instance of `js2-token' struct, sets
5904 its relevant fields and puts it into `js2-ti-tokens'."
5905 (let (identifier-start
5906 is-unicode-escape-start c
5907 contains-escape escape-val str result base
5908 look-for-slash continue tt legacy-octal
5909 (token (js2-new-token 0)))
5910 (setq
5911 tt
5912 (catch 'return
5913 (when (eq modifier 'TEMPLATE_TAIL)
5914 (setf (js2-token-beg token) (1- js2-ts-cursor))
5915 (throw 'return (js2-get-string-or-template-token ?` token)))
5916 (while t
5917 ;; Eat whitespace, possibly sensitive to newlines.
5918 (setq continue t)
5919 (while continue
5920 (setq c (js2-get-char))
5921 (cond
5922 ((eq c js2-EOF_CHAR)
5923 (js2-unget-char)
5924 (js2-ts-set-char-token-bounds token)
5925 (throw 'return js2-EOF))
5926 ((eq c ?\n)
5927 (js2-ts-set-char-token-bounds token)
5928 (setq js2-ts-dirty-line nil)
5929 (throw 'return js2-EOL))
5930 ((not (js2-js-space-p c))
5931 (if (/= c ?-) ; in case end of HTML comment
5932 (setq js2-ts-dirty-line t))
5933 (setq continue nil))))
5934 ;; Assume the token will be 1 char - fixed up below.
5935 (js2-ts-set-char-token-bounds token)
5936 (when (eq c ?@)
5937 (throw 'return js2-XMLATTR))
5938 ;; identifier/keyword/instanceof?
5939 ;; watch out for starting with a <backslash>
5940 (cond
5941 ((eq c ?\\)
5942 (setq c (js2-get-char))
5943 (if (eq c ?u)
5944 (setq identifier-start t
5945 is-unicode-escape-start t
5946 js2-ts-string-buffer nil)
5947 (setq identifier-start nil)
5948 (js2-unget-char)
5949 (setq c ?\\)))
5950 (t
5951 (when (setq identifier-start (js2-identifier-start-p c))
5952 (setq js2-ts-string-buffer nil)
5953 (js2-add-to-string c))))
5954 (when identifier-start
5955 (setq contains-escape is-unicode-escape-start)
5956 (catch 'break
5957 (while t
5958 (if is-unicode-escape-start
5959 ;; strictly speaking we should probably push-back
5960 ;; all the bad characters if the <backslash>uXXXX
5961 ;; sequence is malformed. But since there isn't a
5962 ;; correct context(is there?) for a bad Unicode
5963 ;; escape sequence in an identifier, we can report
5964 ;; an error here.
5965 (progn
5966 (setq escape-val 0)
5967 (dotimes (_ 4)
5968 (setq c (js2-get-char)
5969 escape-val (js2-x-digit-to-int c escape-val))
5970 ;; Next check takes care of c < 0 and bad escape
5971 (if (cl-minusp escape-val)
5972 (throw 'break nil)))
5973 (if (cl-minusp escape-val)
5974 (js2-report-scan-error "msg.invalid.escape" t))
5975 (js2-add-to-string escape-val)
5976 (setq is-unicode-escape-start nil))
5977 (setq c (js2-get-char))
5978 (cond
5979 ((eq c ?\\)
5980 (setq c (js2-get-char))
5981 (if (eq c ?u)
5982 (setq is-unicode-escape-start t
5983 contains-escape t)
5984 (js2-report-scan-error "msg.illegal.character" t)))
5985 (t
5986 (if (or (eq c js2-EOF_CHAR)
5987 (not (js2-identifier-part-p c)))
5988 (throw 'break nil))
5989 (js2-add-to-string c))))))
5990 (js2-unget-char)
5991 (setf str (js2-collect-string js2-ts-string-buffer)
5992 (js2-token-end token) js2-ts-cursor)
5993 ;; FIXME: Invalid in ES5 and ES6, see
5994 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5995 ;; Probably should just drop this conditional.
5996 (unless contains-escape
5997 ;; OPT we shouldn't have to make a string (object!) to
5998 ;; check if it's a keyword.
5999 ;; Return the corresponding token if it's a keyword
6000 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6001 (setq result (js2-string-to-keyword str)))
6002 (if (and (< js2-language-version 170)
6003 (memq result '(js2-LET js2-YIELD)))
6004 ;; LET and YIELD are tokens only in 1.7 and later
6005 (setq result 'js2-NAME))
6006 (when (eq result 'js2-RESERVED)
6007 (setf (js2-token-string token) str))
6008 (throw 'return (js2-tt-code result))))
6009 ;; If we want to intern these as Rhino does, just use (intern str)
6010 (setf (js2-token-string token) str)
6011 (throw 'return js2-NAME)) ; end identifier/kwd check
6012 ;; is it a number?
6013 (when (or (js2-digit-p c)
6014 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6015 (setq js2-ts-string-buffer nil
6016 base 10)
6017 (when (eq c ?0)
6018 (setq c (js2-get-char))
6019 (cond
6020 ((or (eq c ?x) (eq c ?X))
6021 (setq base 16)
6022 (setq c (js2-get-char)))
6023 ((and (or (eq c ?b) (eq c ?B))
6024 (>= js2-language-version 200))
6025 (setq base 2)
6026 (setq c (js2-get-char)))
6027 ((and (or (eq c ?o) (eq c ?O))
6028 (>= js2-language-version 200))
6029 (setq base 8)
6030 (setq legacy-octal nil)
6031 (setq c (js2-get-char)))
6032 ((js2-digit-p c)
6033 (setq base 'maybe-8))
6034 (t
6035 (js2-add-to-string ?0))))
6036 (cond
6037 ((eq base 16)
6038 (if (> 0 (js2-x-digit-to-int c 0))
6039 (js2-report-scan-error "msg.missing.hex.digits")
6040 (while (<= 0 (js2-x-digit-to-int c 0))
6041 (js2-add-to-string c)
6042 (setq c (js2-get-char)))))
6043 ((eq base 2)
6044 (if (not (memq c '(?0 ?1)))
6045 (js2-report-scan-error "msg.missing.binary.digits")
6046 (while (memq c '(?0 ?1))
6047 (js2-add-to-string c)
6048 (setq c (js2-get-char)))))
6049 ((eq base 8)
6050 (if (or (> ?0 c) (< ?7 c))
6051 (js2-report-scan-error "msg.missing.octal.digits")
6052 (while (and (<= ?0 c) (>= ?7 c))
6053 (js2-add-to-string c)
6054 (setq c (js2-get-char)))))
6055 (t
6056 (while (and (<= ?0 c) (<= c ?9))
6057 ;; We permit 08 and 09 as decimal numbers, which
6058 ;; makes our behavior a superset of the ECMA
6059 ;; numeric grammar. We might not always be so
6060 ;; permissive, so we warn about it.
6061 (when (and (eq base 'maybe-8) (>= c ?8))
6062 (js2-report-warning "msg.bad.octal.literal"
6063 (if (eq c ?8) "8" "9"))
6064 (setq base 10))
6065 (js2-add-to-string c)
6066 (setq c (js2-get-char)))
6067 (when (eq base 'maybe-8)
6068 (setq base 8
6069 legacy-octal t))))
6070 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6071 (when (eq c ?.)
6072 (cl-loop do
6073 (js2-add-to-string c)
6074 (setq c (js2-get-char))
6075 while (js2-digit-p c)))
6076 (when (memq c '(?e ?E))
6077 (js2-add-to-string c)
6078 (setq c (js2-get-char))
6079 (when (memq c '(?+ ?-))
6080 (js2-add-to-string c)
6081 (setq c (js2-get-char)))
6082 (unless (js2-digit-p c)
6083 (js2-report-scan-error "msg.missing.exponent" t))
6084 (cl-loop do
6085 (js2-add-to-string c)
6086 (setq c (js2-get-char))
6087 while (js2-digit-p c))))
6088 (js2-unget-char)
6089 (let ((str (js2-set-string-from-buffer token)))
6090 (setf (js2-token-number token) (js2-string-to-number str base)
6091 (js2-token-number-base token) base
6092 (js2-token-number-legacy-octal-p token) (and (= base 8) legacy-octal)))
6093 (throw 'return js2-NUMBER))
6094 ;; is it a string?
6095 (when (or (memq c '(?\" ?\'))
6096 (and (>= js2-language-version 200)
6097 (= c ?`)))
6098 (throw 'return
6099 (js2-get-string-or-template-token c token)))
6100 (js2-ts-return token
6101 (cl-case c
6102 (?\;
6103 (throw 'return js2-SEMI))
6104 (?\[
6105 (throw 'return js2-LB))
6106 (?\]
6107 (throw 'return js2-RB))
6108 (?{
6109 (throw 'return js2-LC))
6110 (?}
6111 (throw 'return js2-RC))
6112 (?\(
6113 (throw 'return js2-LP))
6114 (?\)
6115 (throw 'return js2-RP))
6116 (?,
6117 (throw 'return js2-COMMA))
6118 (??
6119 (throw 'return js2-HOOK))
6120 (?:
6121 (if (js2-match-char ?:)
6122 js2-COLONCOLON
6123 (throw 'return js2-COLON)))
6124 (?.
6125 (if (js2-match-char ?.)
6126 (if (js2-match-char ?.)
6127 js2-TRIPLEDOT js2-DOTDOT)
6128 (if (js2-match-char ?\()
6129 js2-DOTQUERY
6130 (throw 'return js2-DOT))))
6131 (?|
6132 (if (js2-match-char ?|)
6133 (throw 'return js2-OR)
6134 (if (js2-match-char ?=)
6135 js2-ASSIGN_BITOR
6136 (throw 'return js2-BITOR))))
6137 (?^
6138 (if (js2-match-char ?=)
6139 js2-ASSIGN_BITOR
6140 (throw 'return js2-BITXOR)))
6141 (?&
6142 (if (js2-match-char ?&)
6143 (throw 'return js2-AND)
6144 (if (js2-match-char ?=)
6145 js2-ASSIGN_BITAND
6146 (throw 'return js2-BITAND))))
6147 (?=
6148 (if (js2-match-char ?=)
6149 (if (js2-match-char ?=)
6150 js2-SHEQ
6151 (throw 'return js2-EQ))
6152 (if (js2-match-char ?>)
6153 (js2-ts-return token js2-ARROW)
6154 (throw 'return js2-ASSIGN))))
6155 (?!
6156 (if (js2-match-char ?=)
6157 (if (js2-match-char ?=)
6158 js2-SHNE
6159 js2-NE)
6160 (throw 'return js2-NOT)))
6161 (?<
6162 ;; NB:treat HTML begin-comment as comment-till-eol
6163 (when (js2-match-char ?!)
6164 (when (js2-match-char ?-)
6165 (when (js2-match-char ?-)
6166 (js2-skip-line)
6167 (setf (js2-token-comment-type (js2-current-token)) 'html)
6168 (throw 'return js2-COMMENT)))
6169 (js2-unget-char))
6170 (if (js2-match-char ?<)
6171 (if (js2-match-char ?=)
6172 js2-ASSIGN_LSH
6173 js2-LSH)
6174 (if (js2-match-char ?=)
6175 js2-LE
6176 (throw 'return js2-LT))))
6177 (?>
6178 (if (js2-match-char ?>)
6179 (if (js2-match-char ?>)
6180 (if (js2-match-char ?=)
6181 js2-ASSIGN_URSH
6182 js2-URSH)
6183 (if (js2-match-char ?=)
6184 js2-ASSIGN_RSH
6185 js2-RSH))
6186 (if (js2-match-char ?=)
6187 js2-GE
6188 (throw 'return js2-GT))))
6189 (?*
6190 (if (js2-match-char ?=)
6191 js2-ASSIGN_MUL
6192 (throw 'return js2-MUL)))
6193 (?/
6194 ;; is it a // comment?
6195 (when (js2-match-char ?/)
6196 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6197 (js2-skip-line)
6198 (setf (js2-token-comment-type token) 'line)
6199 ;; include newline so highlighting goes to end of
6200 ;; window, if there actually is a newline; if we
6201 ;; hit eof, then implicitly there isn't
6202 (unless js2-ts-hit-eof
6203 (cl-incf (js2-token-end token)))
6204 (throw 'return js2-COMMENT))
6205 ;; is it a /* comment?
6206 (when (js2-match-char ?*)
6207 (setf look-for-slash nil
6208 (js2-token-beg token) (- js2-ts-cursor 2)
6209 (js2-token-comment-type token)
6210 (if (js2-match-char ?*)
6211 (progn
6212 (setq look-for-slash t)
6213 'jsdoc)
6214 'block))
6215 (while t
6216 (setq c (js2-get-char))
6217 (cond
6218 ((eq c js2-EOF_CHAR)
6219 (setf (js2-token-end token) (1- js2-ts-cursor))
6220 (js2-report-error "msg.unterminated.comment")
6221 (throw 'return js2-COMMENT))
6222 ((eq c ?*)
6223 (setq look-for-slash t))
6224 ((eq c ?/)
6225 (if look-for-slash
6226 (js2-ts-return token js2-COMMENT)))
6227 (t
6228 (setf look-for-slash nil
6229 (js2-token-end token) js2-ts-cursor)))))
6230 (if (js2-match-char ?=)
6231 js2-ASSIGN_DIV
6232 (throw 'return js2-DIV)))
6233 (?#
6234 (when js2-skip-preprocessor-directives
6235 (js2-skip-line)
6236 (setf (js2-token-comment-type token) 'preprocessor
6237 (js2-token-end token) js2-ts-cursor)
6238 (throw 'return js2-COMMENT))
6239 (throw 'return js2-ERROR))
6240 (?%
6241 (if (js2-match-char ?=)
6242 js2-ASSIGN_MOD
6243 (throw 'return js2-MOD)))
6244 (?~
6245 (throw 'return js2-BITNOT))
6246 (?+
6247 (if (js2-match-char ?=)
6248 js2-ASSIGN_ADD
6249 (if (js2-match-char ?+)
6250 js2-INC
6251 (throw 'return js2-ADD))))
6252 (?-
6253 (cond
6254 ((js2-match-char ?=)
6255 (setq c js2-ASSIGN_SUB))
6256 ((js2-match-char ?-)
6257 (unless js2-ts-dirty-line
6258 ;; treat HTML end-comment after possible whitespace
6259 ;; after line start as comment-until-eol
6260 (when (js2-match-char ?>)
6261 (js2-skip-line)
6262 (setf (js2-token-comment-type (js2-current-token)) 'html)
6263 (throw 'return js2-COMMENT)))
6264 (setq c js2-DEC))
6265 (t
6266 (setq c js2-SUB)))
6267 (setq js2-ts-dirty-line t)
6268 c)
6269 (otherwise
6270 (js2-report-scan-error "msg.illegal.character")))))))
6271 (setf (js2-token-type token) tt)
6272 token))
6273
6274 (defun js2-get-string-or-template-token (quote-char token)
6275 ;; We attempt to accumulate a string the fast way, by
6276 ;; building it directly out of the reader. But if there
6277 ;; are any escaped characters in the string, we revert to
6278 ;; building it out of a string buffer.
6279 (let ((c (js2-get-char))
6280 js2-ts-string-buffer
6281 nc c1 val escape-val)
6282 (catch 'break
6283 (while (/= c quote-char)
6284 (catch 'continue
6285 (when (eq c js2-EOF_CHAR)
6286 (js2-unget-char)
6287 (js2-report-error "msg.unterminated.string.lit")
6288 (throw 'break nil))
6289 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6290 (js2-unget-char)
6291 (js2-report-error "msg.unterminated.string.lit")
6292 (throw 'break nil))
6293 (when (eq c ?\\)
6294 ;; We've hit an escaped character
6295 (setq c (js2-get-char))
6296 (cl-case c
6297 (?b (setq c ?\b))
6298 (?f (setq c ?\f))
6299 (?n (setq c ?\n))
6300 (?r (setq c ?\r))
6301 (?t (setq c ?\t))
6302 (?v (setq c ?\v))
6303 (?u
6304 (setq c1 (js2-read-unicode-escape))
6305 (if js2-parse-ide-mode
6306 (if c1
6307 (progn
6308 ;; just copy the string in IDE-mode
6309 (js2-add-to-string ?\\)
6310 (js2-add-to-string ?u)
6311 (dotimes (_ 3)
6312 (js2-add-to-string (js2-get-char)))
6313 (setq c (js2-get-char))) ; added at end of loop
6314 ;; flag it as an invalid escape
6315 (js2-report-warning "msg.invalid.escape"
6316 nil (- js2-ts-cursor 2) 6))
6317 ;; Get 4 hex digits; if the u escape is not
6318 ;; followed by 4 hex digits, use 'u' + the
6319 ;; literal character sequence that follows.
6320 (js2-add-to-string ?u)
6321 (setq escape-val 0)
6322 (dotimes (_ 4)
6323 (setq c (js2-get-char)
6324 escape-val (js2-x-digit-to-int c escape-val))
6325 (if (cl-minusp escape-val)
6326 (throw 'continue nil))
6327 (js2-add-to-string c))
6328 ;; prepare for replace of stored 'u' sequence by escape value
6329 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6330 c escape-val)))
6331 (?x
6332 ;; Get 2 hex digits, defaulting to 'x'+literal
6333 ;; sequence, as above.
6334 (setq c (js2-get-char)
6335 escape-val (js2-x-digit-to-int c 0))
6336 (if (cl-minusp escape-val)
6337 (progn
6338 (js2-add-to-string ?x)
6339 (throw 'continue nil))
6340 (setq c1 c
6341 c (js2-get-char)
6342 escape-val (js2-x-digit-to-int c escape-val))
6343 (if (cl-minusp escape-val)
6344 (progn
6345 (js2-add-to-string ?x)
6346 (js2-add-to-string c1)
6347 (throw 'continue nil))
6348 ;; got 2 hex digits
6349 (setq c escape-val))))
6350 (?\n
6351 ;; Remove line terminator after escape to follow
6352 ;; SpiderMonkey and C/C++
6353 (setq c (js2-get-char))
6354 (throw 'continue nil))
6355 (t
6356 (when (and (<= ?0 c) (< c ?8))
6357 (setq val (- c ?0)
6358 c (js2-get-char))
6359 (when (and (<= ?0 c) (< c ?8))
6360 (setq val (- (+ (* 8 val) c) ?0)
6361 c (js2-get-char))
6362 (when (and (<= ?0 c)
6363 (< c ?8)
6364 (< val #o37))
6365 ;; c is 3rd char of octal sequence only
6366 ;; if the resulting val <= 0377
6367 (setq val (- (+ (* 8 val) c) ?0)
6368 c (js2-get-char))))
6369 (js2-unget-char)
6370 (setq c val)))))
6371 (when (and (eq quote-char ?`) (eq c ?$))
6372 (when (eq (setq nc (js2-get-char)) ?\{)
6373 (throw 'break nil))
6374 (js2-unget-char))
6375 (js2-add-to-string c)
6376 (setq c (js2-get-char)))))
6377 (js2-set-string-from-buffer token)
6378 (if (not (eq quote-char ?`))
6379 js2-STRING
6380 (if (and (eq c ?$) (eq nc ?\{))
6381 js2-TEMPLATE_HEAD
6382 js2-NO_SUBS_TEMPLATE))))
6383
6384 (defun js2-read-regexp (start-tt)
6385 "Called by parser when it gets / or /= in literal context."
6386 (let (c err
6387 in-class ; inside a '[' .. ']' character-class
6388 flags
6389 (continue t)
6390 (token (js2-new-token 0)))
6391 (setq js2-ts-string-buffer nil)
6392 (if (eq start-tt js2-ASSIGN_DIV)
6393 ;; mis-scanned /=
6394 (js2-add-to-string ?=)
6395 (if (not (eq start-tt js2-DIV))
6396 (error "failed assertion")))
6397 (while (and (not err)
6398 (or (/= (setq c (js2-get-char)) ?/)
6399 in-class))
6400 (cond
6401 ((or (= c ?\n)
6402 (= c js2-EOF_CHAR))
6403 (setf (js2-token-end token) (1- js2-ts-cursor)
6404 err t
6405 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6406 (js2-report-error "msg.unterminated.re.lit"))
6407 (t (cond
6408 ((= c ?\\)
6409 (js2-add-to-string c)
6410 (setq c (js2-get-char)))
6411 ((= c ?\[)
6412 (setq in-class t))
6413 ((= c ?\])
6414 (setq in-class nil)))
6415 (js2-add-to-string c))))
6416 (unless err
6417 (while continue
6418 (cond
6419 ((js2-match-char ?g)
6420 (push ?g flags))
6421 ((js2-match-char ?i)
6422 (push ?i flags))
6423 ((js2-match-char ?m)
6424 (push ?m flags))
6425 ((and (js2-match-char ?u)
6426 (>= js2-language-version 200))
6427 (push ?u flags))
6428 ((and (js2-match-char ?y)
6429 (>= js2-language-version 200))
6430 (push ?y flags))
6431 (t
6432 (setq continue nil))))
6433 (if (js2-alpha-p (js2-peek-char))
6434 (js2-report-scan-error "msg.invalid.re.flag" t
6435 js2-ts-cursor 1))
6436 (js2-set-string-from-buffer token))
6437 (js2-collect-string flags)))
6438
6439 (defun js2-get-first-xml-token ()
6440 (setq js2-ts-xml-open-tags-count 0
6441 js2-ts-is-xml-attribute nil
6442 js2-ts-xml-is-tag-content nil)
6443 (js2-unget-char)
6444 (js2-get-next-xml-token))
6445
6446 (defun js2-xml-discard-string (token)
6447 "Throw away the string in progress and flag an XML parse error."
6448 (setf js2-ts-string-buffer nil
6449 (js2-token-string token) nil)
6450 (js2-report-scan-error "msg.XML.bad.form" t))
6451
6452 (defun js2-get-next-xml-token ()
6453 (setq js2-ts-string-buffer nil) ; for recording the XML
6454 (let ((token (js2-new-token 0))
6455 c result)
6456 (setq result
6457 (catch 'return
6458 (while t
6459 (setq c (js2-get-char))
6460 (cond
6461 ((= c js2-EOF_CHAR)
6462 (throw 'return js2-ERROR))
6463 (js2-ts-xml-is-tag-content
6464 (cl-case c
6465 (?>
6466 (js2-add-to-string c)
6467 (setq js2-ts-xml-is-tag-content nil
6468 js2-ts-is-xml-attribute nil))
6469 (?/
6470 (js2-add-to-string c)
6471 (when (eq ?> (js2-peek-char))
6472 (setq c (js2-get-char))
6473 (js2-add-to-string c)
6474 (setq js2-ts-xml-is-tag-content nil)
6475 (cl-decf js2-ts-xml-open-tags-count)))
6476 (?{
6477 (js2-unget-char)
6478 (js2-set-string-from-buffer token)
6479 (throw 'return js2-XML))
6480 ((?\' ?\")
6481 (js2-add-to-string c)
6482 (unless (js2-read-quoted-string c token)
6483 (throw 'return js2-ERROR)))
6484 (?=
6485 (js2-add-to-string c)
6486 (setq js2-ts-is-xml-attribute t))
6487 ((? ?\t ?\r ?\n)
6488 (js2-add-to-string c))
6489 (t
6490 (js2-add-to-string c)
6491 (setq js2-ts-is-xml-attribute nil)))
6492 (when (and (not js2-ts-xml-is-tag-content)
6493 (zerop js2-ts-xml-open-tags-count))
6494 (js2-set-string-from-buffer token)
6495 (throw 'return js2-XMLEND)))
6496 (t
6497 ;; else not tag content
6498 (cl-case c
6499 (?<
6500 (js2-add-to-string c)
6501 (setq c (js2-peek-char))
6502 (cl-case c
6503 (?!
6504 (setq c (js2-get-char)) ;; skip !
6505 (js2-add-to-string c)
6506 (setq c (js2-peek-char))
6507 (cl-case c
6508 (?-
6509 (setq c (js2-get-char)) ;; skip -
6510 (js2-add-to-string c)
6511 (if (eq c ?-)
6512 (progn
6513 (js2-add-to-string c)
6514 (unless (js2-read-xml-comment token)
6515 (throw 'return js2-ERROR)))
6516 (js2-xml-discard-string token)
6517 (throw 'return js2-ERROR)))
6518 (?\[
6519 (setq c (js2-get-char)) ;; skip [
6520 (js2-add-to-string c)
6521 (if (and (= (js2-get-char) ?C)
6522 (= (js2-get-char) ?D)
6523 (= (js2-get-char) ?A)
6524 (= (js2-get-char) ?T)
6525 (= (js2-get-char) ?A)
6526 (= (js2-get-char) ?\[))
6527 (progn
6528 (js2-add-to-string ?C)
6529 (js2-add-to-string ?D)
6530 (js2-add-to-string ?A)
6531 (js2-add-to-string ?T)
6532 (js2-add-to-string ?A)
6533 (js2-add-to-string ?\[)
6534 (unless (js2-read-cdata token)
6535 (throw 'return js2-ERROR)))
6536 (js2-xml-discard-string token)
6537 (throw 'return js2-ERROR)))
6538 (t
6539 (unless (js2-read-entity token)
6540 (throw 'return js2-ERROR))))
6541 ;; Allow bare CDATA section, e.g.:
6542 ;; let xml = <![CDATA[ foo bar baz ]]>;
6543 (when (zerop js2-ts-xml-open-tags-count)
6544 (throw 'return js2-XMLEND)))
6545 (??
6546 (setq c (js2-get-char)) ;; skip ?
6547 (js2-add-to-string c)
6548 (unless (js2-read-PI token)
6549 (throw 'return js2-ERROR)))
6550 (?/
6551 ;; end tag
6552 (setq c (js2-get-char)) ;; skip /
6553 (js2-add-to-string c)
6554 (when (zerop js2-ts-xml-open-tags-count)
6555 (js2-xml-discard-string token)
6556 (throw 'return js2-ERROR))
6557 (setq js2-ts-xml-is-tag-content t)
6558 (cl-decf js2-ts-xml-open-tags-count))
6559 (t
6560 ;; start tag
6561 (setq js2-ts-xml-is-tag-content t)
6562 (cl-incf js2-ts-xml-open-tags-count))))
6563 (?{
6564 (js2-unget-char)
6565 (js2-set-string-from-buffer token)
6566 (throw 'return js2-XML))
6567 (t
6568 (js2-add-to-string c))))))))
6569 (setf (js2-token-end token) js2-ts-cursor)
6570 (setf (js2-token-type token) result)
6571 result))
6572
6573 (defun js2-read-quoted-string (quote token)
6574 (let (c)
6575 (catch 'return
6576 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6577 (js2-add-to-string c)
6578 (if (eq c quote)
6579 (throw 'return t)))
6580 (js2-xml-discard-string token) ;; throw away string in progress
6581 nil)))
6582
6583 (defun js2-read-xml-comment (token)
6584 (let ((c (js2-get-char)))
6585 (catch 'return
6586 (while (/= c js2-EOF_CHAR)
6587 (catch 'continue
6588 (js2-add-to-string c)
6589 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6590 (setq c (js2-get-char))
6591 (js2-add-to-string c)
6592 (if (eq (js2-peek-char) ?>)
6593 (progn
6594 (setq c (js2-get-char)) ;; skip >
6595 (js2-add-to-string c)
6596 (throw 'return t))
6597 (throw 'continue nil)))
6598 (setq c (js2-get-char))))
6599 (js2-xml-discard-string token)
6600 nil)))
6601
6602 (defun js2-read-cdata (token)
6603 (let ((c (js2-get-char)))
6604 (catch 'return
6605 (while (/= c js2-EOF_CHAR)
6606 (catch 'continue
6607 (js2-add-to-string c)
6608 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6609 (setq c (js2-get-char))
6610 (js2-add-to-string c)
6611 (if (eq (js2-peek-char) ?>)
6612 (progn
6613 (setq c (js2-get-char)) ;; Skip >
6614 (js2-add-to-string c)
6615 (throw 'return t))
6616 (throw 'continue nil)))
6617 (setq c (js2-get-char))))
6618 (js2-xml-discard-string token)
6619 nil)))
6620
6621 (defun js2-read-entity (token)
6622 (let ((decl-tags 1)
6623 c)
6624 (catch 'return
6625 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6626 (js2-add-to-string c)
6627 (cl-case c
6628 (?<
6629 (cl-incf decl-tags))
6630 (?>
6631 (cl-decf decl-tags)
6632 (if (zerop decl-tags)
6633 (throw 'return t)))))
6634 (js2-xml-discard-string token)
6635 nil)))
6636
6637 (defun js2-read-PI (token)
6638 "Scan an XML processing instruction."
6639 (let (c)
6640 (catch 'return
6641 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6642 (js2-add-to-string c)
6643 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6644 (setq c (js2-get-char)) ;; Skip >
6645 (js2-add-to-string c)
6646 (throw 'return t)))
6647 (js2-xml-discard-string token)
6648 nil)))
6649
6650 ;;; Highlighting
6651
6652 (defun js2-set-face (beg end face &optional record)
6653 "Fontify a region. If RECORD is non-nil, record for later."
6654 (when (cl-plusp js2-highlight-level)
6655 (setq beg (min (point-max) beg)
6656 beg (max (point-min) beg)
6657 end (min (point-max) end)
6658 end (max (point-min) end))
6659 (if record
6660 (push (list beg end face) js2-mode-fontifications)
6661 (put-text-property beg end 'font-lock-face face))))
6662
6663 (defsubst js2-clear-face (beg end)
6664 (remove-text-properties beg end '(font-lock-face nil
6665 help-echo nil
6666 point-entered nil
6667 cursor-sensor-functions nil
6668 c-in-sws nil)))
6669
6670 (defconst js2-ecma-global-props
6671 (concat "^"
6672 (regexp-opt
6673 '("Infinity" "NaN" "undefined" "arguments") t)
6674 "$")
6675 "Value properties of the Ecma-262 Global Object.
6676 Shown at or above `js2-highlight-level' 2.")
6677
6678 ;; might want to add the name "arguments" to this list?
6679 (defconst js2-ecma-object-props
6680 (concat "^"
6681 (regexp-opt
6682 '("prototype" "__proto__" "__parent__") t)
6683 "$")
6684 "Value properties of the Ecma-262 Object constructor.
6685 Shown at or above `js2-highlight-level' 2.")
6686
6687 (defconst js2-ecma-global-funcs
6688 (concat
6689 "^"
6690 (regexp-opt
6691 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6692 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6693 "$")
6694 "Function properties of the Ecma-262 Global object.
6695 Shown at or above `js2-highlight-level' 2.")
6696
6697 (defconst js2-ecma-number-props
6698 (concat "^"
6699 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6700 "NEGATIVE_INFINITY"
6701 "POSITIVE_INFINITY") t)
6702 "$")
6703 "Properties of the Ecma-262 Number constructor.
6704 Shown at or above `js2-highlight-level' 2.")
6705
6706 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6707 "Properties of the Ecma-262 Date constructor.
6708 Shown at or above `js2-highlight-level' 2.")
6709
6710 (defconst js2-ecma-math-props
6711 (concat "^"
6712 (regexp-opt
6713 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6714 t)
6715 "$")
6716 "Properties of the Ecma-262 Math object.
6717 Shown at or above `js2-highlight-level' 2.")
6718
6719 (defconst js2-ecma-math-funcs
6720 (concat "^"
6721 (regexp-opt
6722 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6723 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6724 "$")
6725 "Function properties of the Ecma-262 Math object.
6726 Shown at or above `js2-highlight-level' 2.")
6727
6728 (defconst js2-ecma-function-props
6729 (concat
6730 "^"
6731 (regexp-opt
6732 '(;; properties of the Object prototype object
6733 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6734 "toLocaleString" "toString" "valueOf"
6735 ;; properties of the Function prototype object
6736 "apply" "call"
6737 ;; properties of the Array prototype object
6738 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6739 "splice" "unshift"
6740 ;; properties of the String prototype object
6741 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6742 "localeCompare" "match" "replace" "search" "split" "substring"
6743 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6744 "toUpperCase"
6745 ;; properties of the Number prototype object
6746 "toExponential" "toFixed" "toPrecision"
6747 ;; properties of the Date prototype object
6748 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6749 "getMinutes" "getMonth" "getSeconds" "getTime"
6750 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6751 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6752 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6753 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6754 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6755 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6756 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6757 "toTimeString" "toUTCString"
6758 ;; properties of the RegExp prototype object
6759 "exec" "test"
6760 ;; properties of the JSON prototype object
6761 "parse" "stringify"
6762 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6763 "toSource" "__defineGetter__" "__defineSetter__"
6764 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6765 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6766 t)
6767 "$")
6768 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6769 Shown at or above `js2-highlight-level' 3.")
6770
6771 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6772 (let ((target-name (and target
6773 (js2-name-node-p target)
6774 (js2-name-node-name target)))
6775 (prop-name (if prop (js2-name-node-name prop)))
6776 (level2 (>= js2-highlight-level 2))
6777 (level3 (>= js2-highlight-level 3)))
6778 (when level2
6779 (let ((face
6780 (if call-p
6781 (cond
6782 ((and target prop)
6783 (cond
6784 ((and level3 (string-match js2-ecma-function-props prop-name))
6785 'font-lock-builtin-face)
6786 ((and target-name prop)
6787 (cond
6788 ((string= target-name "Date")
6789 (if (string-match js2-ecma-date-props prop-name)
6790 'font-lock-builtin-face))
6791 ((string= target-name "Math")
6792 (if (string-match js2-ecma-math-funcs prop-name)
6793 'font-lock-builtin-face))))))
6794 (prop
6795 (if (string-match js2-ecma-global-funcs prop-name)
6796 'font-lock-builtin-face)))
6797 (cond
6798 ((and target prop)
6799 (cond
6800 ((string= target-name "Number")
6801 (if (string-match js2-ecma-number-props prop-name)
6802 'font-lock-constant-face))
6803 ((string= target-name "Math")
6804 (if (string-match js2-ecma-math-props prop-name)
6805 'font-lock-constant-face))))
6806 (prop
6807 (if (string-match js2-ecma-object-props prop-name)
6808 'font-lock-constant-face))))))
6809 (when (and (not face) target (not call-p) prop-name)
6810 (setq face 'js2-object-property))
6811 (when face
6812 (let ((pos (+ (js2-node-pos parent) ; absolute
6813 (js2-node-pos prop)))) ; relative
6814 (js2-set-face pos
6815 (+ pos (js2-node-len prop))
6816 face 'record)))))))
6817
6818 (defun js2-parse-highlight-member-expr-node (node)
6819 "Perform syntax highlighting of EcmaScript built-in properties.
6820 The variable `js2-highlight-level' governs this highlighting."
6821 (let (face target prop name pos end parent call-p callee)
6822 (cond
6823 ;; case 1: simple name, e.g. foo
6824 ((js2-name-node-p node)
6825 (setq name (js2-name-node-name node))
6826 ;; possible for name to be nil in rare cases - saw it when
6827 ;; running js2-mode on an elisp buffer. Might as well try to
6828 ;; make it so js2-mode never barfs.
6829 (when name
6830 (setq face (if (string-match js2-ecma-global-props name)
6831 'font-lock-constant-face))
6832 (when face
6833 (setq pos (js2-node-pos node)
6834 end (+ pos (js2-node-len node)))
6835 (js2-set-face pos end face 'record))))
6836 ;; case 2: property access or function call
6837 ((or (js2-prop-get-node-p node)
6838 ;; highlight function call if expr is a prop-get node
6839 ;; or a plain name (i.e. unqualified function call)
6840 (and (setq call-p (js2-call-node-p node))
6841 (setq callee (js2-call-node-target node)) ; separate setq!
6842 (or (js2-prop-get-node-p callee)
6843 (js2-name-node-p callee))))
6844 (setq parent node
6845 node (if call-p callee node))
6846 (if (and call-p (js2-name-node-p callee))
6847 (setq prop callee)
6848 (setq target (js2-prop-get-node-left node)
6849 prop (js2-prop-get-node-right node)))
6850 (cond
6851 ((js2-name-node-p prop)
6852 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6853 (js2-parse-highlight-prop-get parent target prop call-p))
6854 ((js2-name-node-p target)
6855 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6856 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6857
6858 (defun js2-parse-highlight-member-expr-fn-name (expr)
6859 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6860 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6861 We currently only handle the case where the last component is a prop-get
6862 of a simple name. Called before EXPR has a parent node."
6863 (let (pos
6864 (name (and (js2-prop-get-node-p expr)
6865 (js2-prop-get-node-right expr))))
6866 (when (js2-name-node-p name)
6867 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6868 (js2-node-pos name)))
6869 (+ pos (js2-node-len name))
6870 'font-lock-function-name-face
6871 'record))))
6872
6873 ;; source: http://jsdoc.sourceforge.net/
6874 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6875 ;; allows type specifications, and needs work before entering the wild.
6876
6877 (defconst js2-jsdoc-param-tag-regexp
6878 (concat "^\\s-*\\*+\\s-*\\(@"
6879 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6880 "\\)"
6881 "\\s-*\\({[^}]+}\\)?" ; optional type
6882 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6883 "\\_>")
6884 "Matches jsdoc tags with optional type and optional param name.")
6885
6886 (defconst js2-jsdoc-typed-tag-regexp
6887 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6888 (regexp-opt
6889 '("enum"
6890 "extends"
6891 "field"
6892 "id"
6893 "implements"
6894 "lends"
6895 "mods"
6896 "requires"
6897 "return"
6898 "returns"
6899 "throw"
6900 "throws"))
6901 "\\)\\)\\s-*\\({[^}]+}\\)?")
6902 "Matches jsdoc tags with optional type.")
6903
6904 (defconst js2-jsdoc-arg-tag-regexp
6905 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6906 (regexp-opt
6907 '("alias"
6908 "augments"
6909 "borrows"
6910 "callback"
6911 "bug"
6912 "base"
6913 "config"
6914 "default"
6915 "define"
6916 "exception"
6917 "func"
6918 "function"
6919 "member"
6920 "memberOf"
6921 "method"
6922 "name"
6923 "namespace"
6924 "since"
6925 "suppress"
6926 "this"
6927 "throws"
6928 "type"
6929 "version"))
6930 "\\)\\)\\s-+\\([^ \t]+\\)")
6931 "Matches jsdoc tags with a single argument.")
6932
6933 (defconst js2-jsdoc-empty-tag-regexp
6934 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6935 (regexp-opt
6936 '("addon"
6937 "author"
6938 "class"
6939 "const"
6940 "constant"
6941 "constructor"
6942 "constructs"
6943 "deprecated"
6944 "desc"
6945 "description"
6946 "event"
6947 "example"
6948 "exec"
6949 "export"
6950 "fileoverview"
6951 "final"
6952 "func"
6953 "function"
6954 "hidden"
6955 "ignore"
6956 "implicitCast"
6957 "inheritDoc"
6958 "inner"
6959 "interface"
6960 "license"
6961 "method"
6962 "noalias"
6963 "noshadow"
6964 "notypecheck"
6965 "override"
6966 "owner"
6967 "preserve"
6968 "preserveTry"
6969 "private"
6970 "protected"
6971 "public"
6972 "static"
6973 "supported"
6974 ))
6975 "\\)\\)\\s-*")
6976 "Matches empty jsdoc tags.")
6977
6978 (defconst js2-jsdoc-link-tag-regexp
6979 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6980 "Matches a jsdoc link or code tag.")
6981
6982 (defconst js2-jsdoc-see-tag-regexp
6983 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6984 "Matches a jsdoc @see tag.")
6985
6986 (defconst js2-jsdoc-html-tag-regexp
6987 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6988 "Matches a simple (no attributes) html start- or end-tag.")
6989
6990 (defun js2-jsdoc-highlight-helper ()
6991 (js2-set-face (match-beginning 1)
6992 (match-end 1)
6993 'js2-jsdoc-tag)
6994 (if (match-beginning 2)
6995 (if (save-excursion
6996 (goto-char (match-beginning 2))
6997 (= (char-after) ?{))
6998 (js2-set-face (1+ (match-beginning 2))
6999 (1- (match-end 2))
7000 'js2-jsdoc-type)
7001 (js2-set-face (match-beginning 2)
7002 (match-end 2)
7003 'js2-jsdoc-value)))
7004 (if (match-beginning 3)
7005 (js2-set-face (match-beginning 3)
7006 (match-end 3)
7007 'js2-jsdoc-value)))
7008
7009 (defun js2-highlight-jsdoc (ast)
7010 "Highlight doc comment tags."
7011 (let ((comments (js2-ast-root-comments ast))
7012 beg end)
7013 (save-excursion
7014 (dolist (node comments)
7015 (when (eq (js2-comment-node-format node) 'jsdoc)
7016 (setq beg (js2-node-abs-pos node)
7017 end (+ beg (js2-node-len node)))
7018 (save-restriction
7019 (narrow-to-region beg end)
7020 (dolist (re (list js2-jsdoc-param-tag-regexp
7021 js2-jsdoc-typed-tag-regexp
7022 js2-jsdoc-arg-tag-regexp
7023 js2-jsdoc-link-tag-regexp
7024 js2-jsdoc-see-tag-regexp
7025 js2-jsdoc-empty-tag-regexp))
7026 (goto-char beg)
7027 (while (re-search-forward re nil t)
7028 (js2-jsdoc-highlight-helper)))
7029 ;; simple highlighting for html tags
7030 (goto-char beg)
7031 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7032 (js2-set-face (match-beginning 1)
7033 (match-end 1)
7034 'js2-jsdoc-html-tag-delimiter)
7035 (js2-set-face (match-beginning 2)
7036 (match-end 2)
7037 'js2-jsdoc-html-tag-name)
7038 (js2-set-face (match-beginning 3)
7039 (match-end 3)
7040 'js2-jsdoc-html-tag-delimiter))))))))
7041
7042 (defun js2-highlight-assign-targets (_node left right)
7043 "Highlight function properties and external variables."
7044 (let (leftpos name)
7045 ;; highlight vars and props assigned function values
7046 (when (or (js2-function-node-p right)
7047 (js2-class-node-p right))
7048 (cond
7049 ;; var foo = function() {...}
7050 ((js2-name-node-p left)
7051 (setq name left))
7052 ;; foo.bar.baz = function() {...}
7053 ((and (js2-prop-get-node-p left)
7054 (js2-name-node-p (js2-prop-get-node-right left)))
7055 (setq name (js2-prop-get-node-right left))))
7056 (when name
7057 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7058 (+ leftpos (js2-node-len name))
7059 'font-lock-function-name-face
7060 'record)))))
7061
7062 (defun js2-record-name-node (node)
7063 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7064 later. NODE must be a name node."
7065 (let ((leftpos (js2-node-abs-pos node)))
7066 (push (list node js2-current-scope
7067 leftpos
7068 (+ leftpos (js2-node-len node)))
7069 js2-recorded-identifiers)))
7070
7071 (defun js2-highlight-undeclared-vars ()
7072 "After entire parse is finished, look for undeclared variable references.
7073 We have to wait until entire buffer is parsed, since JavaScript permits var
7074 decls to occur after they're used.
7075
7076 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7077 it is considered declared."
7078 (let (name)
7079 (dolist (entry js2-recorded-identifiers)
7080 (cl-destructuring-bind (name-node scope pos end) entry
7081 (setq name (js2-name-node-name name-node))
7082 (unless (or (member name js2-global-externs)
7083 (member name js2-default-externs)
7084 (member name js2-additional-externs)
7085 (js2-get-defining-scope scope name pos))
7086 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7087 'js2-external-variable))))))
7088
7089 (defun js2--add-or-update-symbol (symbol inition used vars)
7090 "Add or update SYMBOL entry in VARS, an hash table.
7091 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7092 respectively meaning that SYMBOL is a mere declaration, an
7093 assignment or a function parameter; when USED is t, the symbol
7094 node is assumed to be an usage and thus added to the list stored
7095 in the cdr of the entry.
7096 "
7097 (let* ((nm (js2-name-node-name symbol))
7098 (es (js2-node-get-enclosing-scope symbol))
7099 (ds (js2-get-defining-scope es nm)))
7100 (when (and ds (not (equal nm "arguments")))
7101 (let* ((sym (js2-scope-get-symbol ds nm))
7102 (var (gethash sym vars))
7103 (err-var-p (js2-catch-node-p ds)))
7104 (unless inition
7105 (setq inition err-var-p))
7106 (if var
7107 (progn
7108 (when (and inition (not (equal (car var) ?P)))
7109 (setcar var inition))
7110 (when used
7111 (push symbol (cdr var))))
7112 ;; do not consider the declaration of catch parameter as an usage
7113 (when (and err-var-p used)
7114 (setq used nil))
7115 (puthash sym (cons inition (if used (list symbol))) vars))))))
7116
7117 (defun js2--classify-variables ()
7118 "Collect and classify variables declared or used within js2-mode-ast.
7119 Traverse the whole ast tree returning a summary of the variables
7120 usage as an hash-table, keyed by their corresponding symbol table
7121 entry.
7122 Each variable is described by a tuple where the car is a flag
7123 indicating whether the variable has been initialized and the cdr
7124 is a possibly empty list of name nodes where it is used. External
7125 symbols, i.e. those not present in the whole scopes hierarchy,
7126 are ignored."
7127 (let ((vars (make-hash-table :test #'eq :size 100)))
7128 (js2-visit-ast
7129 js2-mode-ast
7130 (lambda (node end-p)
7131 (when (null end-p)
7132 (cond
7133 ((js2-var-init-node-p node)
7134 ;; take note about possibly initialized declarations
7135 (let ((target (js2-var-init-node-target node))
7136 (initializer (js2-var-init-node-initializer node)))
7137 (when target
7138 (let* ((parent (js2-node-parent node))
7139 (grandparent (if parent (js2-node-parent parent)))
7140 (inited (not (null initializer))))
7141 (unless inited
7142 (setq inited
7143 (and grandparent
7144 (js2-for-in-node-p grandparent)
7145 (memq target
7146 (mapcar #'js2-var-init-node-target
7147 (js2-var-decl-node-kids
7148 (js2-for-in-node-iterator grandparent)))))))
7149 (js2--add-or-update-symbol target inited nil vars)))))
7150
7151 ((js2-assign-node-p node)
7152 ;; take note about assignments
7153 (let ((left (js2-assign-node-left node)))
7154 (when (js2-name-node-p left)
7155 (js2--add-or-update-symbol left t nil vars))))
7156
7157 ((js2-prop-get-node-p node)
7158 ;; handle x.y.z nodes, considering only x
7159 (let ((left (js2-prop-get-node-left node)))
7160 (when (js2-name-node-p left)
7161 (js2--add-or-update-symbol left nil t vars))))
7162
7163 ((js2-name-node-p node)
7164 ;; take note about used variables
7165 (let ((parent (js2-node-parent node)))
7166 (when parent
7167 (unless (or (and (js2-var-init-node-p parent) ; handled above
7168 (eq node (js2-var-init-node-target parent)))
7169 (and (js2-assign-node-p parent)
7170 (eq node (js2-assign-node-left parent)))
7171 (js2-prop-get-node-p parent))
7172 (let ((used t) inited)
7173 (cond
7174 ((and (js2-function-node-p parent)
7175 (js2-wrapper-function-p parent))
7176 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7177
7178 ((js2-for-in-node-p parent)
7179 (if (eq node (js2-for-in-node-iterator parent))
7180 (setq inited t used nil)))
7181
7182 ((js2-function-node-p parent)
7183 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7184 used nil)))
7185
7186 (unless used
7187 (let ((grandparent (js2-node-parent parent)))
7188 (when grandparent
7189 (setq used (js2-return-node-p grandparent)))))
7190
7191 (js2--add-or-update-symbol node inited used vars))))))))
7192 t))
7193 vars))
7194
7195 (defun js2--get-name-node (node)
7196 (cond
7197 ((js2-name-node-p node) node)
7198 ((js2-function-node-p node)
7199 (js2-function-node-name node))
7200 ((js2-class-node-p node)
7201 (js2-class-node-name node))
7202 ((js2-comp-loop-node-p node)
7203 (js2-comp-loop-node-iterator node))
7204 (t node)))
7205
7206 (defun js2--highlight-unused-variable (symbol info)
7207 (let ((name (js2-symbol-name symbol))
7208 (inited (car info))
7209 (refs (cdr info))
7210 pos len)
7211 (unless (and inited refs)
7212 (if refs
7213 (dolist (ref refs)
7214 (setq pos (js2-node-abs-pos ref))
7215 (setq len (js2-name-node-len ref))
7216 (js2-report-warning "msg.uninitialized.variable" name pos len
7217 'js2-warning))
7218 (when (or js2-warn-about-unused-function-arguments
7219 (not (eq inited ?P)))
7220 (let* ((symn (js2-symbol-ast-node symbol))
7221 (namen (js2--get-name-node symn)))
7222 (unless (js2-node-top-level-decl-p namen)
7223 (setq pos (js2-node-abs-pos namen))
7224 (setq len (js2-name-node-len namen))
7225 (js2-report-warning "msg.unused.variable" name pos len
7226 'js2-warning))))))))
7227
7228 (defun js2-highlight-unused-variables ()
7229 "Highlight unused variables."
7230 (let ((vars (js2--classify-variables)))
7231 (maphash #'js2--highlight-unused-variable vars)))
7232
7233 ;;;###autoload
7234 (define-minor-mode js2-highlight-unused-variables-mode
7235 "Toggle highlight of unused variables."
7236 :lighter ""
7237 (if js2-highlight-unused-variables-mode
7238 (add-hook 'js2-post-parse-callbacks
7239 #'js2-highlight-unused-variables nil t)
7240 (remove-hook 'js2-post-parse-callbacks
7241 #'js2-highlight-unused-variables t)))
7242
7243 (defun js2-set-default-externs ()
7244 "Set the value of `js2-default-externs' based on the various
7245 `js2-include-?-externs' variables."
7246 (setq js2-default-externs
7247 (append js2-ecma-262-externs
7248 (if js2-include-browser-externs js2-browser-externs)
7249 (if (and js2-include-browser-externs
7250 (>= js2-language-version 200)) js2-harmony-externs)
7251 (if js2-include-rhino-externs js2-rhino-externs)
7252 (if js2-include-node-externs js2-node-externs)
7253 (if (or js2-include-browser-externs js2-include-node-externs)
7254 js2-typed-array-externs))))
7255
7256 (defun js2-apply-jslint-globals ()
7257 (setq js2-additional-externs
7258 (nconc (js2-get-jslint-globals)
7259 js2-additional-externs)))
7260
7261 (defun js2-get-jslint-globals ()
7262 (js2-reparse)
7263 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7264 when (and (eq 'block (js2-comment-node-format node))
7265 (save-excursion
7266 (goto-char (js2-node-abs-pos node))
7267 (looking-at "/\\* *global ")))
7268 append (js2-get-jslint-globals-in
7269 (match-end 0)
7270 (js2-node-abs-end node))))
7271
7272 (defun js2-get-jslint-globals-in (beg end)
7273 (let (res)
7274 (save-excursion
7275 (goto-char beg)
7276 (while (re-search-forward js2-mode-identifier-re end t)
7277 (let ((match (match-string 0)))
7278 (unless (member match '("true" "false"))
7279 (push match res)))))
7280 (nreverse res)))
7281
7282 ;;; IMenu support
7283
7284 ;; We currently only support imenu, but eventually should support speedbar and
7285 ;; possibly other browsing mechanisms.
7286
7287 ;; The basic strategy is to identify function assignment targets of the form
7288 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7289 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7290 ;; for imenu after parsing is finished.
7291
7292 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7293 ;; JavaScript, and the general problem is undecidable. However, several forms
7294 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7295 ;; include:
7296
7297 ;; function foo() -- function declaration
7298 ;; foo = function() -- function expression assigned to variable
7299 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7300 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7301 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7302 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7303 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7304 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7305 ;; function foo() {function bar() {...}} -- nested function
7306 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7307
7308 ;; This list boils down to a few forms that can be combined recursively.
7309 ;; Top-level named function declarations include both the left-hand (name)
7310 ;; and the right-hand (function value) expressions needed to produce an imenu
7311 ;; entry. The other "right-hand" forms we need to look for are:
7312 ;; - functions declared as props/getters/setters in object literals
7313 ;; - nested named function declarations
7314 ;; The "left-hand" expressions that functions can be assigned to include:
7315 ;; - local/global variables
7316 ;; - nested property-get expressions like a.b.c.d
7317 ;; - element gets like foo[10] or foo['bar'] where the index
7318 ;; expression can be trivially converted to a property name. They
7319 ;; effectively then become property gets.
7320
7321 ;; All the different definition types are canonicalized into the form
7322 ;; foo.bar.baz = position-of-function-keyword
7323
7324 ;; We need to build a trie-like structure for imenu. As an example,
7325 ;; consider the following JavaScript code:
7326
7327 ;; a = function() {...} // function at position 5
7328 ;; b = function() {...} // function at position 25
7329 ;; foo = function() {...} // function at position 100
7330 ;; foo.bar = function() {...} // function at position 200
7331 ;; foo.bar.baz = function() {...} // function at position 300
7332 ;; foo.bar.zab = function() {...} // function at position 400
7333
7334 ;; During parsing we accumulate an entry for each definition in
7335 ;; the variable `js2-imenu-recorder', like so:
7336
7337 ;; '((fn a 5)
7338 ;; (fn b 25)
7339 ;; (fn foo 100)
7340 ;; (fn foo bar 200)
7341 ;; (fn foo bar baz 300)
7342 ;; (fn foo bar zab 400))
7343
7344 ;; Where 'fn' is the respective function node.
7345 ;; After parsing these entries are merged into this alist-trie:
7346
7347 ;; '((a . 1)
7348 ;; (b . 2)
7349 ;; (foo (<definition> . 3)
7350 ;; (bar (<definition> . 6)
7351 ;; (baz . 100)
7352 ;; (zab . 200))))
7353
7354 ;; Note the wacky need for a <definition> name. The token can be anything
7355 ;; that isn't a valid JavaScript identifier, because you might make foo
7356 ;; a function and then start setting properties on it that are also functions.
7357
7358 (defun js2-prop-node-name (node)
7359 "Return the name of a node that may be a property-get/property-name.
7360 If NODE is not a valid name-node, string-node or integral number-node,
7361 returns nil. Otherwise returns the string name/value of the node."
7362 (cond
7363 ((js2-name-node-p node)
7364 (js2-name-node-name node))
7365 ((js2-string-node-p node)
7366 (js2-string-node-value node))
7367 ((and (js2-number-node-p node)
7368 (string-match "^[0-9]+$" (js2-number-node-value node)))
7369 (js2-number-node-value node))
7370 ((eq (js2-node-type node) js2-THIS)
7371 "this")
7372 ((eq (js2-node-type node) js2-SUPER)
7373 "super")))
7374
7375 (defun js2-node-qname-component (node)
7376 "Return the name of this node, if it contributes to a qname.
7377 Returns nil if the node doesn't contribute."
7378 (copy-sequence
7379 (or (js2-prop-node-name node)
7380 (if (and (js2-function-node-p node)
7381 (js2-function-node-name node))
7382 (js2-name-node-name (js2-function-node-name node))))))
7383
7384 (defun js2-record-imenu-entry (fn-node qname pos)
7385 "Add an entry to `js2-imenu-recorder'.
7386 FN-NODE should be the current item's function node.
7387
7388 Associate FN-NODE with its QNAME for later lookup.
7389 This is used in postprocessing the chain list. For each chain, we find
7390 the parent function, look up its qname, then prepend a copy of it to the chain."
7391 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7392 (unless js2-imenu-function-map
7393 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7394 (puthash fn-node qname js2-imenu-function-map))
7395
7396 (defun js2-record-imenu-functions (node &optional var)
7397 "Record function definitions for imenu.
7398 NODE is a function node or an object literal.
7399 VAR, if non-nil, is the expression that NODE is being assigned to.
7400 When passed arguments of wrong type, does nothing."
7401 (when js2-parse-ide-mode
7402 (let ((fun-p (js2-function-node-p node))
7403 qname fname-node)
7404 (cond
7405 ;; non-anonymous function declaration?
7406 ((and fun-p
7407 (not var)
7408 (setq fname-node (js2-function-node-name node)))
7409 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7410 ;; for remaining forms, compute left-side tree branch first
7411 ((and var (setq qname (js2-compute-nested-prop-get var)))
7412 (cond
7413 ;; foo.bar.baz = function
7414 (fun-p
7415 (js2-record-imenu-entry node qname (js2-node-pos node)))
7416 ;; foo.bar.baz = object-literal
7417 ;; look for nested functions: {a: {b: function() {...} }}
7418 ((js2-object-node-p node)
7419 ;; Node position here is still absolute, since the parser
7420 ;; passes the assignment target and value expressions
7421 ;; to us before they are added as children of the assignment node.
7422 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7423
7424 (defun js2-compute-nested-prop-get (node)
7425 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7426 component nodes as a list. Otherwise return nil. Element-gets are treated
7427 as property-gets if the index expression is a string, or a positive integer."
7428 (let (left right head)
7429 (cond
7430 ((or (js2-name-node-p node)
7431 (js2-this-or-super-node-p node))
7432 (list node))
7433 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7434 ((js2-prop-get-node-p node) ; foo.bar
7435 (setq left (js2-prop-get-node-left node)
7436 right (js2-prop-get-node-right node))
7437 (if (setq head (js2-compute-nested-prop-get left))
7438 (nconc head (list right))))
7439 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7440 (setq left (js2-elem-get-node-target node)
7441 right (js2-elem-get-node-element node))
7442 (if (or (js2-string-node-p right) ; ['bar']
7443 (and (js2-number-node-p right) ; [10]
7444 (string-match "^[0-9]+$"
7445 (js2-number-node-value right))))
7446 (if (setq head (js2-compute-nested-prop-get left))
7447 (nconc head (list right))))))))
7448
7449 (defun js2-record-object-literal (node qname pos)
7450 "Recursively process an object literal looking for functions.
7451 NODE is an object literal that is the right-hand child of an assignment
7452 expression. QNAME is a list of nodes representing the assignment target,
7453 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7454 POS is the absolute position of the node.
7455 We do a depth-first traversal of NODE. For any functions we find,
7456 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7457 (let (right)
7458 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7459 (when (js2-infix-node-p e)
7460 (let ((left (js2-infix-node-left e))
7461 ;; Element positions are relative to the parent position.
7462 (pos (+ pos (js2-node-pos e))))
7463 (cond
7464 ;; foo: function() {...}
7465 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7466 (when (js2-prop-node-name left)
7467 ;; As a policy decision, we record the position of the property,
7468 ;; not the position of the `function' keyword, since the property
7469 ;; is effectively the name of the function.
7470 (js2-record-imenu-entry right (append qname (list left)) pos)))
7471 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7472 ((js2-object-node-p right)
7473 (js2-record-object-literal right
7474 (append qname (list (js2-infix-node-left e)))
7475 (+ pos (js2-node-pos right))))))))))
7476
7477 (defun js2-node-top-level-decl-p (node)
7478 "Return t if NODE's name is defined in the top-level scope.
7479 Also returns t if NODE's name is not defined in any scope, since it implies
7480 that it's an external variable, which must also be in the top-level scope."
7481 (let* ((name (js2-prop-node-name node))
7482 (this-scope (js2-node-get-enclosing-scope node))
7483 defining-scope)
7484 (cond
7485 ((js2-this-or-super-node-p node)
7486 nil)
7487 ((null this-scope)
7488 t)
7489 ((setq defining-scope (js2-get-defining-scope this-scope name))
7490 (js2-ast-root-p defining-scope))
7491 (t t))))
7492
7493 (defun js2-wrapper-function-p (node)
7494 "Return t if NODE is a function expression that's immediately invoked.
7495 NODE must be `js2-function-node'."
7496 (let ((parent (js2-node-parent node)))
7497 (or
7498 ;; function(){...}();
7499 (and (js2-call-node-p parent)
7500 (eq node (js2-call-node-target parent)))
7501 (and (js2-paren-node-p parent)
7502 ;; (function(){...})();
7503 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7504 ;; (function(){...}).call(this);
7505 (and (js2-prop-get-node-p parent)
7506 (member (js2-name-node-name (js2-prop-get-node-right parent))
7507 '("call" "apply"))
7508 (js2-call-node-p (js2-node-parent parent))))))))
7509
7510 (defun js2-browse-postprocess-chains ()
7511 "Modify function-declaration name chains after parsing finishes.
7512 Some of the information is only available after the parse tree is complete.
7513 For instance, processing a nested scope requires a parent function node."
7514 (let (result fn parent-qname p elem)
7515 (dolist (entry js2-imenu-recorder)
7516 ;; function node goes first
7517 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest _)) entry
7518 ;; Examine head's defining scope:
7519 ;; Pre-processed chain, or top-level/external, keep as-is.
7520 (if (or (stringp head) (js2-node-top-level-decl-p head))
7521 (push chain result)
7522 (when (js2-this-or-super-node-p head)
7523 (setq chain (cdr chain))) ; discard this-node
7524 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7525 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7526 (when (eq parent-qname 'not-found)
7527 ;; anonymous function expressions are not recorded
7528 ;; during the parse, so we need to handle this case here
7529 (setq parent-qname
7530 (if (js2-wrapper-function-p fn)
7531 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7532 (if (js2-ast-root-p grandparent)
7533 nil
7534 (gethash grandparent js2-imenu-function-map 'skip)))
7535 'skip))
7536 (puthash fn parent-qname js2-imenu-function-map))
7537 (if (eq parent-qname 'skip)
7538 ;; We don't show it, let's record that fact.
7539 (remhash current-fn js2-imenu-function-map)
7540 ;; Prepend parent fn qname to this chain.
7541 (let ((qname (append parent-qname chain)))
7542 (puthash current-fn (butlast qname) js2-imenu-function-map)
7543 (push qname result)))))))
7544 ;; Collect chains obtained by third-party code.
7545 (let (js2-imenu-recorder)
7546 (run-hooks 'js2-build-imenu-callbacks)
7547 (dolist (entry js2-imenu-recorder)
7548 (push (cdr entry) result)))
7549 ;; Finally replace each node in each chain with its name.
7550 (dolist (chain result)
7551 (setq p chain)
7552 (while p
7553 (if (js2-node-p (setq elem (car p)))
7554 (setcar p (js2-node-qname-component elem)))
7555 (setq p (cdr p))))
7556 result))
7557
7558 ;; Merge name chains into a trie-like tree structure of nested lists.
7559 ;; To simplify construction of the trie, we first build it out using the rule
7560 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7561 ;; [key, num-or-list]. The second element can be a number; if so, this key
7562 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7563 ;; associated with the key at this level.) Otherwise the second element is
7564 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7565 ;; a simple recursive formulation.
7566 ;;
7567 ;; js2-mode is building the data structure for imenu. The imenu documentation
7568 ;; claims that it's the structure above, but in practice it wants the children
7569 ;; at the same list level as the key for that level, which is how I've drawn
7570 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7571 ;; list wrapper around the children at each level.
7572 ;;
7573 ;; A completed nested imenu-alist entry looks like this:
7574 ;; '(("foo"
7575 ;; ("<definition>" . 7)
7576 ;; ("bar"
7577 ;; ("a" . 40)
7578 ;; ("b" . 60))))
7579 ;;
7580 ;; In particular, the documentation for `imenu--index-alist' says that
7581 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7582 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7583
7584 (defun js2-treeify (lst)
7585 "Convert (a b c d) to (a ((b ((c d)))))."
7586 (if (null (cddr lst)) ; list length <= 2
7587 lst
7588 (list (car lst) (list (js2-treeify (cdr lst))))))
7589
7590 (defun js2-build-alist-trie (chains trie)
7591 "Merge declaration name chains into a trie-like alist structure for imenu.
7592 CHAINS is the qname chain list produced during parsing. TRIE is a
7593 list of elements built up so far."
7594 (let (head tail pos branch kids)
7595 (dolist (chain chains)
7596 (setq head (car chain)
7597 tail (cdr chain)
7598 pos (if (numberp (car tail)) (car tail))
7599 branch (js2-find-if (lambda (n)
7600 (string= (car n) head))
7601 trie)
7602 kids (cl-second branch))
7603 (cond
7604 ;; case 1: this key isn't in the trie yet
7605 ((null branch)
7606 (if trie
7607 (setcdr (last trie) (list (js2-treeify chain)))
7608 (setq trie (list (js2-treeify chain)))))
7609 ;; case 2: key is present with a single number entry: replace w/ list
7610 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7611 ;; ("<definition>" 20)))
7612 ((numberp kids)
7613 (setcar (cdr branch)
7614 (list (list "<definition-1>" kids)
7615 (if pos
7616 (list "<definition-2>" pos)
7617 (js2-treeify tail)))))
7618 ;; case 3: key is there (with kids), and we're a number entry
7619 (pos
7620 (setcdr (last kids)
7621 (list
7622 (list (format "<definition-%d>"
7623 (1+ (cl-loop for kid in kids
7624 count (eq ?< (aref (car kid) 0)))))
7625 pos))))
7626 ;; case 4: key is there with kids, need to merge in our chain
7627 (t
7628 (js2-build-alist-trie (list tail) kids))))
7629 trie))
7630
7631 (defun js2-flatten-trie (trie)
7632 "Convert TRIE to imenu-format.
7633 Recurses through nodes, and for each one whose second element is a list,
7634 appends the list's flattened elements to the current element. Also
7635 changes the tails into conses. For instance, this pre-flattened trie
7636
7637 '(a ((b 20)
7638 (c ((d 30)
7639 (e 40)))))
7640
7641 becomes
7642
7643 '(a (b . 20)
7644 (c (d . 30)
7645 (e . 40)))
7646
7647 Note that the root of the trie has no key, just a list of chains.
7648 This is also true for the value of any key with multiple children,
7649 e.g. key 'c' in the example above."
7650 (cond
7651 ((listp (car trie))
7652 (mapcar #'js2-flatten-trie trie))
7653 (t
7654 (if (numberp (cl-second trie))
7655 (cons (car trie) (cl-second trie))
7656 ;; else pop list and append its kids
7657 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7658
7659 (defun js2-build-imenu-index ()
7660 "Turn `js2-imenu-recorder' into an imenu data structure."
7661 (when (eq js2-imenu-recorder 'empty)
7662 (setq js2-imenu-recorder nil))
7663 (let* ((chains (js2-browse-postprocess-chains))
7664 (result (js2-build-alist-trie chains nil)))
7665 (js2-flatten-trie result)))
7666
7667 (defun js2-test-print-chains (chains)
7668 "Print a list of qname chains.
7669 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7670 i.e. one or more nodes, and an integer position as the list tail."
7671 (mapconcat (lambda (chain)
7672 (concat "("
7673 (mapconcat (lambda (elem)
7674 (if (js2-node-p elem)
7675 (or (js2-node-qname-component elem)
7676 "nil")
7677 (number-to-string elem)))
7678 chain
7679 " ")
7680 ")"))
7681 chains
7682 "\n"))
7683
7684 ;;; Parser
7685
7686 (defconst js2-version "1.8.5"
7687 "Version of JavaScript supported.")
7688
7689 (defun js2-record-face (face &optional token)
7690 "Record a style run of FACE for TOKEN or the current token."
7691 (unless token (setq token (js2-current-token)))
7692 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7693
7694 (defsubst js2-node-end (n)
7695 "Computes the absolute end of node N.
7696 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7697 is only true until the node is added to its parent; i.e., while parsing."
7698 (+ (js2-node-pos n)
7699 (js2-node-len n)))
7700
7701 (defun js2-record-comment (token)
7702 "Record a comment in `js2-scanned-comments'."
7703 (let ((ct (js2-token-comment-type token))
7704 (beg (js2-token-beg token))
7705 (end (js2-token-end token)))
7706 (push (make-js2-comment-node :len (- end beg)
7707 :format ct)
7708 js2-scanned-comments)
7709 (when js2-parse-ide-mode
7710 (js2-record-face (if (eq ct 'jsdoc)
7711 'font-lock-doc-face
7712 'font-lock-comment-face)
7713 token)
7714 (when (memq ct '(html preprocessor))
7715 ;; Tell cc-engine the bounds of the comment.
7716 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7717
7718 (defun js2-peek-token ()
7719 "Return the next token type without consuming it.
7720 If `js2-ti-lookahead' is positive, return the type of next token
7721 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7722 (if (not (zerop js2-ti-lookahead))
7723 (js2-token-type
7724 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7725 (let ((tt (js2-get-token-internal nil)))
7726 (js2-unget-token)
7727 tt)))
7728
7729 (defalias 'js2-next-token 'js2-get-token)
7730
7731 (defun js2-match-token (match &optional dont-unget)
7732 "Get next token and return t if it matches MATCH, a bytecode.
7733 Returns nil and consumes nothing if MATCH is not the next token."
7734 (if (/= (js2-get-token) match)
7735 (ignore (unless dont-unget (js2-unget-token)))
7736 t))
7737
7738 (defun js2-match-contextual-kwd (name)
7739 "Consume and return t if next token is `js2-NAME', and its
7740 string is NAME. Returns nil and keeps current token otherwise."
7741 (if (js2-contextual-kwd-p (progn (js2-get-token)
7742 (js2-current-token))
7743 name)
7744 (progn (js2-record-face 'font-lock-keyword-face) t)
7745 (js2-unget-token)
7746 nil))
7747
7748 (defun js2-contextual-kwd-p (token name)
7749 "Return t if TOKEN is `js2-NAME', and its string is NAME."
7750 (and (= (js2-token-type token) js2-NAME)
7751 (string= (js2-token-string token) name)))
7752
7753 (defun js2-match-async-function ()
7754 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7755 (= (js2-peek-token) js2-FUNCTION))
7756 (js2-record-face 'font-lock-keyword-face)
7757 (js2-get-token)
7758 t))
7759
7760 (defun js2-match-async-arrow-function ()
7761 (and (js2-contextual-kwd-p (js2-current-token) "async")
7762 (/= (js2-peek-token) js2-FUNCTION)))
7763
7764 (defsubst js2-inside-function ()
7765 (cl-plusp js2-nesting-of-function))
7766
7767 (defsubst js2-inside-async-function ()
7768 (and (js2-inside-function)
7769 (js2-function-node-async js2-current-script-or-fn)))
7770
7771 (defun js2-parse-await-maybe (tt)
7772 "Parse \"await\" as an AwaitExpression, if it is one."
7773 (and (= tt js2-NAME)
7774 (js2-contextual-kwd-p (js2-current-token) "await")
7775 ;; Per the proposal, AwaitExpression consists of "await"
7776 ;; followed by a UnaryExpression. So look ahead for one.
7777 (let ((ts-state (make-js2-ts-state))
7778 (recorded-identifiers js2-recorded-identifiers)
7779 (parsed-errors js2-parsed-errors)
7780 (current-token (js2-current-token))
7781 (beg (js2-current-token-beg))
7782 (end (js2-current-token-end))
7783 pn)
7784 (js2-get-token)
7785 (setq pn (js2-make-unary js2-AWAIT 'js2-parse-unary-expr))
7786 (if (= (js2-node-type (js2-unary-node-operand pn)) js2-ERROR)
7787 ;; The parse failed, so pretend like nothing happened and restore
7788 ;; the previous parsing state.
7789 (progn
7790 (js2-ts-seek ts-state)
7791 (setq js2-recorded-identifiers recorded-identifiers
7792 js2-parsed-errors parsed-errors)
7793 ;; And ensure the caller knows about the failure.
7794 nil)
7795 ;; The parse was successful, so process and return the "await".
7796 (js2-record-face 'font-lock-keyword-face current-token)
7797 (unless (js2-inside-async-function)
7798 (js2-report-error "msg.bad.await" nil
7799 beg (- end beg)))
7800 pn))))
7801
7802 (defun js2-get-prop-name-token ()
7803 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7804
7805 (defun js2-match-prop-name ()
7806 "Consume token and return t if next token is a valid property name.
7807 If `js2-language-version' is >= 180, a keyword or reserved word
7808 is considered valid name as well."
7809 (if (eq js2-NAME (js2-get-prop-name-token))
7810 t
7811 (js2-unget-token)
7812 nil))
7813
7814 (defun js2-must-match-prop-name (msg-id &optional pos len)
7815 (if (js2-match-prop-name)
7816 t
7817 (js2-report-error msg-id nil pos len)
7818 nil))
7819
7820 (defun js2-peek-token-or-eol ()
7821 "Return js2-EOL if the next token immediately follows a newline.
7822 Else returns the next token. Used in situations where we don't
7823 consider certain token types valid if they are preceded by a newline.
7824 One example is the postfix ++ or -- operator, which has to be on the
7825 same line as its operand."
7826 (let ((tt (js2-get-token))
7827 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7828 (js2-unget-token)
7829 (if follows-eol
7830 js2-EOL
7831 tt)))
7832
7833 (defun js2-must-match (token msg-id &optional pos len)
7834 "Match next token to token code TOKEN, or record a syntax error.
7835 MSG-ID is the error message to report if the match fails.
7836 Returns t on match, nil if no match."
7837 (if (js2-match-token token t)
7838 t
7839 (js2-report-error msg-id nil pos len)
7840 (js2-unget-token)
7841 nil))
7842
7843 (defun js2-must-match-name (msg-id)
7844 (if (js2-match-token js2-NAME t)
7845 t
7846 (if (eq (js2-current-token-type) js2-RESERVED)
7847 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7848 (js2-report-error msg-id)
7849 (js2-unget-token))
7850 nil))
7851
7852 (defun js2-set-requires-activation ()
7853 (if (js2-function-node-p js2-current-script-or-fn)
7854 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7855
7856 (defun js2-check-activation-name (name _token)
7857 (when (js2-inside-function)
7858 ;; skip language-version 1.2 check from Rhino
7859 (if (or (string= "arguments" name)
7860 (and js2-compiler-activation-names ; only used in codegen
7861 (gethash name js2-compiler-activation-names)))
7862 (js2-set-requires-activation))))
7863
7864 (defun js2-set-is-generator ()
7865 (let ((fn-node js2-current-script-or-fn))
7866 (when (and (js2-function-node-p fn-node)
7867 (not (js2-function-node-generator-type fn-node)))
7868 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7869
7870 (defun js2-must-have-xml ()
7871 (unless js2-compiler-xml-available
7872 (js2-report-error "msg.XML.not.available")))
7873
7874 (defun js2-push-scope (scope)
7875 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7876 (cl-assert (js2-scope-p scope))
7877 (cl-assert (null (js2-scope-parent-scope scope)))
7878 (cl-assert (not (eq js2-current-scope scope)))
7879 (setf (js2-scope-parent-scope scope) js2-current-scope
7880 js2-current-scope scope))
7881
7882 (defsubst js2-pop-scope ()
7883 (setq js2-current-scope
7884 (js2-scope-parent-scope js2-current-scope)))
7885
7886 (defun js2-enter-loop (loop-node)
7887 (push loop-node js2-loop-set)
7888 (push loop-node js2-loop-and-switch-set)
7889 (js2-push-scope loop-node)
7890 ;; Tell the current labeled statement (if any) its statement,
7891 ;; and set the jump target of the first label to the loop.
7892 ;; These are used in `js2-parse-continue' to verify that the
7893 ;; continue target is an actual labeled loop. (And for codegen.)
7894 (when js2-labeled-stmt
7895 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7896 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7897 js2-labeled-stmt))) loop-node)))
7898
7899 (defun js2-exit-loop ()
7900 (pop js2-loop-set)
7901 (pop js2-loop-and-switch-set)
7902 (js2-pop-scope))
7903
7904 (defsubst js2-enter-switch (switch-node)
7905 (push switch-node js2-loop-and-switch-set))
7906
7907 (defsubst js2-exit-switch ()
7908 (pop js2-loop-and-switch-set))
7909
7910 (defsubst js2-get-directive (node)
7911 "Return NODE's value if it is a directive, nil otherwise.
7912
7913 A directive is an otherwise-meaningless expression statement
7914 consisting of a string literal, such as \"use strict\"."
7915 (and (js2-expr-stmt-node-p node)
7916 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7917 (js2-string-node-value node)))
7918
7919 (defun js2-parse (&optional buf cb)
7920 "Tell the js2 parser to parse a region of JavaScript.
7921
7922 BUF is a buffer or buffer name containing the code to parse.
7923 Call `narrow-to-region' first to parse only part of the buffer.
7924
7925 The returned AST root node is given some additional properties:
7926 `node-count' - total number of nodes in the AST
7927 `buffer' - BUF. The buffer it refers to may change or be killed,
7928 so the value is not necessarily reliable.
7929
7930 An optional callback CB can be specified to report parsing
7931 progress. If `(functionp CB)' returns t, it will be called with
7932 the current line number once before parsing begins, then again
7933 each time the lexer reaches a new line number.
7934
7935 CB can also be a list of the form `(symbol cb ...)' to specify
7936 multiple callbacks with different criteria. Each symbol is a
7937 criterion keyword, and the following element is the callback to
7938 call
7939
7940 :line - called whenever the line number changes
7941 :token - called for each new token consumed
7942
7943 The list of criteria could be extended to include entering or
7944 leaving a statement, an expression, or a function definition."
7945 (if (and cb (not (functionp cb)))
7946 (error "criteria callbacks not yet implemented"))
7947 (let ((inhibit-point-motion-hooks t)
7948 (js2-compiler-xml-available (>= js2-language-version 160))
7949 ;; This is a recursive-descent parser, so give it a big stack.
7950 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7951 (max-specpdl-size (max max-specpdl-size 3000))
7952 (case-fold-search nil)
7953 ast)
7954 (with-current-buffer (or buf (current-buffer))
7955 (setq js2-scanned-comments nil
7956 js2-parsed-errors nil
7957 js2-parsed-warnings nil
7958 js2-imenu-recorder nil
7959 js2-imenu-function-map nil
7960 js2-label-set nil)
7961 (js2-init-scanner)
7962 (setq ast (js2-do-parse))
7963 (unless js2-ts-hit-eof
7964 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7965 (setf (js2-ast-root-errors ast) js2-parsed-errors
7966 (js2-ast-root-warnings ast) js2-parsed-warnings)
7967 ;; if we didn't find any declarations, put a dummy in this list so we
7968 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7969 (unless js2-imenu-recorder
7970 (setq js2-imenu-recorder 'empty))
7971 (run-hooks 'js2-parse-finished-hook)
7972 ast)))
7973
7974 ;; Corresponds to Rhino's Parser.parse() method.
7975 (defun js2-do-parse ()
7976 "Parse current buffer starting from current point.
7977 Scanner should be initialized."
7978 (let ((pos js2-ts-cursor)
7979 (end js2-ts-cursor) ; in case file is empty
7980 root n tt
7981 (in-directive-prologue t)
7982 (js2-in-use-strict-directive js2-in-use-strict-directive)
7983 directive)
7984 ;; initialize buffer-local parsing vars
7985 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7986 js2-current-script-or-fn root
7987 js2-current-scope root
7988 js2-nesting-of-function 0
7989 js2-labeled-stmt nil
7990 js2-recorded-identifiers nil ; for js2-highlight
7991 js2-in-use-strict-directive nil)
7992 (while (/= (setq tt (js2-get-token)) js2-EOF)
7993 (if (= tt js2-FUNCTION)
7994 (progn
7995 (setq n (if js2-called-by-compile-function
7996 (js2-parse-function-expr)
7997 (js2-parse-function-stmt))))
7998 ;; not a function - parse a statement
7999 (js2-unget-token)
8000 (setq n (js2-parse-statement))
8001 (when in-directive-prologue
8002 (setq directive (js2-get-directive n))
8003 (cond
8004 ((null directive)
8005 (setq in-directive-prologue nil))
8006 ((string= directive "use strict")
8007 (setq js2-in-use-strict-directive t)))))
8008 ;; add function or statement to script
8009 (setq end (js2-node-end n))
8010 (js2-block-node-push root n))
8011 ;; add comments to root in lexical order
8012 (when js2-scanned-comments
8013 ;; if we find a comment beyond end of normal kids, use its end
8014 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
8015 (dolist (comment js2-scanned-comments)
8016 (push comment (js2-ast-root-comments root))
8017 (js2-node-add-children root comment)))
8018 (setf (js2-node-len root) (- end pos))
8019 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
8020 ;; Give extensions a chance to muck with things before highlighting starts.
8021 (let ((js2-additional-externs js2-additional-externs))
8022 (save-excursion
8023 (run-hooks 'js2-post-parse-callbacks))
8024 (js2-highlight-undeclared-vars))
8025 root))
8026
8027 (defun js2-parse-function-closure-body (fn-node)
8028 "Parse a JavaScript 1.8 function closure body."
8029 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
8030 (if js2-ts-hit-eof
8031 (js2-report-error "msg.no.brace.body" nil
8032 (js2-node-pos fn-node)
8033 (- js2-ts-cursor (js2-node-pos fn-node)))
8034 (js2-node-add-children fn-node
8035 (setf (js2-function-node-body fn-node)
8036 (js2-parse-expr t))))))
8037
8038 (defun js2-parse-function-body (fn-node)
8039 (js2-must-match js2-LC "msg.no.brace.body"
8040 (js2-node-pos fn-node)
8041 (- js2-ts-cursor (js2-node-pos fn-node)))
8042 (let ((pos (js2-current-token-beg)) ; LC position
8043 (pn (make-js2-block-node)) ; starts at LC position
8044 tt
8045 end
8046 not-in-directive-prologue
8047 node
8048 directive)
8049 (cl-incf js2-nesting-of-function)
8050 (unwind-protect
8051 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8052 (= tt js2-EOF)
8053 (= tt js2-RC)))
8054 (js2-block-node-push
8055 pn
8056 (if (/= tt js2-FUNCTION)
8057 (if not-in-directive-prologue
8058 (js2-parse-statement)
8059 (setq node (js2-parse-statement)
8060 directive (js2-get-directive node))
8061 (cond
8062 ((null directive)
8063 (setq not-in-directive-prologue t))
8064 ((string= directive "use strict")
8065 ;; Back up and reparse the function, because new rules apply
8066 ;; to the function name and parameters.
8067 (when (not js2-in-use-strict-directive)
8068 (setq js2-in-use-strict-directive t)
8069 (throw 'reparse t))))
8070 node)
8071 (js2-get-token)
8072 (js2-parse-function-stmt))))
8073 (cl-decf js2-nesting-of-function))
8074 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8075 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8076 (setq end (js2-current-token-end)))
8077 (setf (js2-node-pos pn) pos
8078 (js2-node-len pn) (- end pos))
8079 (setf (js2-function-node-body fn-node) pn)
8080 (js2-node-add-children fn-node pn)
8081 pn))
8082
8083 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8084 "Declare and fontify destructuring parameters inside NODE.
8085 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8086
8087 Return a list of `js2-name-node' nodes representing the symbols
8088 declared; probably to check them for errors."
8089 (let (name-nodes)
8090 (cond
8091 ((js2-name-node-p node)
8092 (let (leftpos)
8093 (js2-define-symbol decl-type (js2-name-node-name node)
8094 node ignore-not-in-block)
8095 (when face
8096 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8097 (+ leftpos (js2-node-len node))
8098 face 'record))
8099 (list node)))
8100 ((js2-object-node-p node)
8101 (dolist (elem (js2-object-node-elems node))
8102 (let ((subexpr (cond
8103 ((and (js2-infix-node-p elem)
8104 (= js2-ASSIGN (js2-infix-node-type elem)))
8105 ;; Destructuring with default argument.
8106 (js2-infix-node-left elem))
8107 ((and (js2-infix-node-p elem)
8108 (= js2-COLON (js2-infix-node-type elem)))
8109 ;; In regular destructuring {a: aa, b: bb},
8110 ;; the var is on the right. In abbreviated
8111 ;; destructuring {a, b}, right == left.
8112 (js2-infix-node-right elem))
8113 ((and (js2-unary-node-p elem)
8114 (= js2-TRIPLEDOT (js2-unary-node-type elem)))
8115 ;; Destructuring with spread.
8116 (js2-unary-node-operand elem)))))
8117 (when subexpr
8118 (push (js2-define-destruct-symbols
8119 subexpr decl-type face ignore-not-in-block)
8120 name-nodes))))
8121 (apply #'append (nreverse name-nodes)))
8122 ((js2-array-node-p node)
8123 (dolist (elem (js2-array-node-elems node))
8124 (when elem
8125 (setq elem (cond ((js2-infix-node-p elem) ;; default (=)
8126 (js2-infix-node-left elem))
8127 ((js2-unary-node-p elem) ;; rest (...)
8128 (js2-unary-node-operand elem))
8129 (t elem)))
8130 (push (js2-define-destruct-symbols
8131 elem decl-type face ignore-not-in-block)
8132 name-nodes)))
8133 (apply #'append (nreverse name-nodes)))
8134 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8135 (js2-node-len node))
8136 nil))))
8137
8138 (defvar js2-illegal-strict-identifiers
8139 '("eval" "arguments")
8140 "Identifiers not allowed as variables in strict mode.")
8141
8142 (defun js2-check-strict-identifier (name-node)
8143 "Check that NAME-NODE makes a legal strict mode identifier."
8144 (when js2-in-use-strict-directive
8145 (let ((param-name (js2-name-node-name name-node)))
8146 (when (member param-name js2-illegal-strict-identifiers)
8147 (js2-report-error "msg.bad.id.strict" param-name
8148 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8149
8150 (defun js2-check-strict-function-params (preceding-params params)
8151 "Given PRECEDING-PARAMS in a function's parameter list, check
8152 for strict mode errors caused by PARAMS."
8153 (when js2-in-use-strict-directive
8154 (dolist (param params)
8155 (let ((param-name (js2-name-node-name param)))
8156 (js2-check-strict-identifier param)
8157 (when (cl-some (lambda (param)
8158 (string= (js2-name-node-name param) param-name))
8159 preceding-params)
8160 (js2-report-error "msg.dup.param.strict" param-name
8161 (js2-node-abs-pos param) (js2-node-len param)))))))
8162
8163 (defun js2-parse-function-params (function-type fn-node pos)
8164 "Parse the parameters of a function of FUNCTION-TYPE
8165 represented by FN-NODE at POS."
8166 (if (js2-match-token js2-RP)
8167 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8168 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8169 (eq (js2-current-token-type) js2-NAME)))
8170 params param
8171 param-name-nodes new-param-name-nodes
8172 rest-param-at)
8173 (when paren-free-arrow
8174 (js2-unget-token))
8175 (cl-loop for tt = (js2-peek-token)
8176 do
8177 (cond
8178 ;; destructuring param
8179 ((and (not paren-free-arrow)
8180 (or (= tt js2-LB) (= tt js2-LC)))
8181 (js2-get-token)
8182 (setq param (js2-parse-destruct-primary-expr)
8183 new-param-name-nodes (js2-define-destruct-symbols
8184 param js2-LP 'js2-function-param))
8185 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8186 (setq param-name-nodes (append param-name-nodes new-param-name-nodes)))
8187 ;; variable name
8188 (t
8189 (when (and (>= js2-language-version 200)
8190 (not paren-free-arrow)
8191 (js2-match-token js2-TRIPLEDOT)
8192 (not rest-param-at))
8193 ;; to report errors if there are more parameters
8194 (setq rest-param-at (length params)))
8195 (js2-must-match-name "msg.no.parm")
8196 (js2-record-face 'js2-function-param)
8197 (setq param (js2-create-name-node))
8198 (js2-define-symbol js2-LP (js2-current-token-string) param)
8199 (js2-check-strict-function-params param-name-nodes (list param))
8200 (setq param-name-nodes (append param-name-nodes (list param)))))
8201 ;; default parameter value
8202 (when (and (not rest-param-at)
8203 (>= js2-language-version 200)
8204 (js2-match-token js2-ASSIGN))
8205 (cl-assert (not paren-free-arrow))
8206 (let* ((pos (js2-node-pos param))
8207 (tt (js2-current-token-type))
8208 (op-pos (- (js2-current-token-beg) pos))
8209 (left param)
8210 (right (js2-parse-assign-expr))
8211 (len (- (js2-node-end right) pos)))
8212 (setq param (make-js2-assign-node
8213 :type tt :pos pos :len len :op-pos op-pos
8214 :left left :right right))
8215 (js2-node-add-children param left right)))
8216 (push param params)
8217 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8218 (js2-report-error "msg.param.after.rest" nil
8219 (js2-node-pos param) (js2-node-len param)))
8220 while
8221 (js2-match-token js2-COMMA))
8222 (when (and (not paren-free-arrow)
8223 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8224 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8225 (when rest-param-at
8226 (setf (js2-function-node-rest-p fn-node) t))
8227 (dolist (p params)
8228 (js2-node-add-children fn-node p)
8229 (push p (js2-function-node-params fn-node))))))
8230
8231 (defun js2-check-inconsistent-return-warning (fn-node name)
8232 "Possibly show inconsistent-return warning.
8233 Last token scanned is the close-curly for the function body."
8234 (when (and js2-mode-show-strict-warnings
8235 js2-strict-inconsistent-return-warning
8236 (not (js2-has-consistent-return-usage
8237 (js2-function-node-body fn-node))))
8238 ;; Have it extend from close-curly to bol or beginning of block.
8239 (let ((pos (save-excursion
8240 (goto-char (js2-current-token-end))
8241 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8242 (point-at-bol))))
8243 (end (js2-current-token-end)))
8244 (if (cl-plusp (js2-name-node-length name))
8245 (js2-add-strict-warning "msg.no.return.value"
8246 (js2-name-node-name name) pos end)
8247 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8248
8249 (defun js2-parse-function-stmt (&optional async-p)
8250 (let ((pos (js2-current-token-beg))
8251 (star-p (js2-match-token js2-MUL)))
8252 (js2-must-match-name "msg.unnamed.function.stmt")
8253 (let ((name (js2-create-name-node t))
8254 pn member-expr)
8255 (cond
8256 ((js2-match-token js2-LP)
8257 (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p name))
8258 (js2-allow-member-expr-as-function-name
8259 (setq member-expr (js2-parse-member-expr-tail nil name))
8260 (js2-parse-highlight-member-expr-fn-name member-expr)
8261 (js2-must-match js2-LP "msg.no.paren.parms")
8262 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p)
8263 (js2-function-node-member-expr pn) member-expr)
8264 pn)
8265 (t
8266 (js2-report-error "msg.no.paren.parms")
8267 (make-js2-error-node))))))
8268
8269 (defun js2-parse-async-function-stmt ()
8270 (js2-parse-function-stmt t))
8271
8272 (defun js2-parse-function-expr (&optional async-p)
8273 (let ((pos (js2-current-token-beg))
8274 (star-p (js2-match-token js2-MUL))
8275 name)
8276 (when (js2-match-token js2-NAME)
8277 (setq name (js2-create-name-node t)))
8278 (js2-must-match js2-LP "msg.no.paren.parms")
8279 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p async-p name)))
8280
8281 (defun js2-parse-function-internal (function-type pos star-p &optional async-p name)
8282 (let (fn-node lp)
8283 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8284 (setq lp (js2-current-token-beg)))
8285 (setf fn-node (make-js2-function-node :pos pos
8286 :name name
8287 :form function-type
8288 :lp (if lp (- lp pos))
8289 :generator-type (and star-p 'STAR)
8290 :async async-p))
8291 (when name
8292 (js2-set-face (js2-node-pos name) (js2-node-end name)
8293 'font-lock-function-name-face 'record)
8294 (when (and (eq function-type 'FUNCTION_STATEMENT)
8295 (cl-plusp (js2-name-node-length name)))
8296 ;; Function statements define a symbol in the enclosing scope
8297 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8298 (when js2-in-use-strict-directive
8299 (js2-check-strict-identifier name)))
8300 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8301 ;; 1. Nested functions are not affected by the dynamic scope flag
8302 ;; as dynamic scope is already a parent of their scope.
8303 ;; 2. Functions defined under the with statement also immune to
8304 ;; this setup, in which case dynamic scope is ignored in favor
8305 ;; of the with object.
8306 (setf (js2-function-node-ignore-dynamic fn-node) t))
8307 ;; dynamically bind all the per-function variables
8308 (let ((js2-current-script-or-fn fn-node)
8309 (js2-current-scope fn-node)
8310 (js2-nesting-of-with 0)
8311 (js2-end-flags 0)
8312 js2-label-set
8313 js2-loop-set
8314 js2-loop-and-switch-set)
8315 (js2-parse-function-params function-type fn-node pos)
8316 (when (eq function-type 'FUNCTION_ARROW)
8317 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8318 (if (and (>= js2-language-version 180)
8319 (/= (js2-peek-token) js2-LC))
8320 (js2-parse-function-closure-body fn-node)
8321 (js2-parse-function-body fn-node))
8322 (js2-check-inconsistent-return-warning fn-node name)
8323
8324 (when name
8325 (js2-node-add-children fn-node name)
8326 ;; Function expressions define a name only in the body of the
8327 ;; function, and only if not hidden by a parameter name
8328 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8329 (null (js2-scope-get-symbol js2-current-scope
8330 (js2-name-node-name name))))
8331 (js2-define-symbol js2-FUNCTION
8332 (js2-name-node-name name)
8333 fn-node))
8334 (when (eq function-type 'FUNCTION_STATEMENT)
8335 (js2-record-imenu-functions fn-node))))
8336
8337 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8338 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8339 ;; We wait until after parsing the function to set its parent scope,
8340 ;; since `js2-define-symbol' needs the defining-scope check to stop
8341 ;; at the function boundary when checking for redeclarations.
8342 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8343 fn-node))
8344
8345 (defun js2-parse-function (function-type pos star-p &optional async-p name)
8346 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8347 beginning of the first token (function keyword, unless it's an
8348 arrow function), NAME is js2-name-node."
8349 (let ((continue t)
8350 ts-state
8351 fn-node
8352 ;; Preserve strict state outside this function.
8353 (js2-in-use-strict-directive js2-in-use-strict-directive))
8354 ;; Parse multiple times if a new strict mode directive is discovered in the
8355 ;; function body, as new rules will be retroactively applied to the legality
8356 ;; of function names and parameters.
8357 (while continue
8358 (setq ts-state (make-js2-ts-state))
8359 (setq continue (catch 'reparse
8360 (setq fn-node (js2-parse-function-internal
8361 function-type pos star-p async-p name))
8362 ;; Don't continue.
8363 nil))
8364 (when continue
8365 (js2-ts-seek ts-state)))
8366 fn-node))
8367
8368 (defun js2-parse-statements (&optional parent)
8369 "Parse a statement list. Last token consumed must be js2-LC.
8370
8371 PARENT can be a `js2-block-node', in which case the statements are
8372 appended to PARENT. Otherwise a new `js2-block-node' is created
8373 and returned.
8374
8375 This function does not match the closing js2-RC: the caller
8376 matches the RC so it can provide a suitable error message if not
8377 matched. This means it's up to the caller to set the length of
8378 the node to include the closing RC. The node start pos is set to
8379 the absolute buffer start position, and the caller should fix it
8380 up to be relative to the parent node. All children of this block
8381 node are given relative start positions and correct lengths."
8382 (let ((pn (or parent (make-js2-block-node)))
8383 tt)
8384 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8385 (/= tt js2-RC))
8386 (js2-block-node-push pn (js2-parse-statement)))
8387 pn))
8388
8389 (defun js2-parse-statement ()
8390 (let (pn beg end)
8391 ;; coarse-grained user-interrupt check - needs work
8392 (and js2-parse-interruptable-p
8393 (zerop (% (cl-incf js2-parse-stmt-count)
8394 js2-statements-per-pause))
8395 (input-pending-p)
8396 (throw 'interrupted t))
8397 (setq pn (js2-statement-helper))
8398 ;; no-side-effects warning check
8399 (unless (js2-node-has-side-effects pn)
8400 (setq end (js2-node-end pn))
8401 (save-excursion
8402 (goto-char end)
8403 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8404 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8405 pn))
8406
8407 ;; These correspond to the switch cases in Parser.statementHelper
8408 (defconst js2-parsers
8409 (let ((parsers (make-vector js2-num-tokens
8410 #'js2-parse-expr-stmt)))
8411 (aset parsers js2-BREAK #'js2-parse-break)
8412 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8413 (aset parsers js2-CONST #'js2-parse-const-var)
8414 (aset parsers js2-CONTINUE #'js2-parse-continue)
8415 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8416 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8417 (aset parsers js2-DO #'js2-parse-do)
8418 (aset parsers js2-EXPORT #'js2-parse-export)
8419 (aset parsers js2-FOR #'js2-parse-for)
8420 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8421 (aset parsers js2-IF #'js2-parse-if)
8422 (aset parsers js2-IMPORT #'js2-parse-import)
8423 (aset parsers js2-LC #'js2-parse-block)
8424 (aset parsers js2-LET #'js2-parse-let-stmt)
8425 (aset parsers js2-NAME #'js2-parse-name-or-label)
8426 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8427 (aset parsers js2-SEMI #'js2-parse-semi)
8428 (aset parsers js2-SWITCH #'js2-parse-switch)
8429 (aset parsers js2-THROW #'js2-parse-throw)
8430 (aset parsers js2-TRY #'js2-parse-try)
8431 (aset parsers js2-VAR #'js2-parse-const-var)
8432 (aset parsers js2-WHILE #'js2-parse-while)
8433 (aset parsers js2-WITH #'js2-parse-with)
8434 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8435 parsers)
8436 "A vector mapping token types to parser functions.")
8437
8438 (defun js2-parse-warn-missing-semi (beg end)
8439 (and js2-mode-show-strict-warnings
8440 js2-strict-missing-semi-warning
8441 (js2-add-strict-warning
8442 "msg.missing.semi" nil
8443 ;; back up to beginning of statement or line
8444 (max beg (save-excursion
8445 (goto-char end)
8446 (point-at-bol)))
8447 end)))
8448
8449 (defconst js2-no-semi-insertion
8450 (list js2-IF
8451 js2-SWITCH
8452 js2-WHILE
8453 js2-DO
8454 js2-FOR
8455 js2-TRY
8456 js2-WITH
8457 js2-LC
8458 js2-ERROR
8459 js2-SEMI
8460 js2-CLASS
8461 js2-FUNCTION
8462 js2-EXPORT)
8463 "List of tokens that don't do automatic semicolon insertion.")
8464
8465 (defconst js2-autoinsert-semi-and-warn
8466 (list js2-ERROR js2-EOF js2-RC))
8467
8468 (defun js2-statement-helper ()
8469 (let* ((tt (js2-get-token))
8470 (first-tt tt)
8471 (async-stmt (js2-match-async-function))
8472 (parser (if (= tt js2-ERROR)
8473 #'js2-parse-semi
8474 (if async-stmt
8475 #'js2-parse-async-function-stmt
8476 (aref js2-parsers tt))))
8477 pn)
8478 ;; If the statement is set, then it's been told its label by now.
8479 (and js2-labeled-stmt
8480 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8481 (setq js2-labeled-stmt nil))
8482 (setq pn (funcall parser))
8483 ;; Don't do auto semi insertion for certain statement types.
8484 (unless (or (memq first-tt js2-no-semi-insertion)
8485 (js2-labeled-stmt-node-p pn)
8486 async-stmt)
8487 (js2-auto-insert-semicolon pn))
8488 pn))
8489
8490 (defun js2-auto-insert-semicolon (pn)
8491 (let* ((tt (js2-get-token))
8492 (pos (js2-node-pos pn)))
8493 (cond
8494 ((= tt js2-SEMI)
8495 ;; extend the node bounds to include the semicolon.
8496 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8497 ((memq tt js2-autoinsert-semi-and-warn)
8498 (js2-unget-token) ; Not ';', do not consume.
8499 ;; Autoinsert ;
8500 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8501 (t
8502 (if (not (js2-token-follows-eol-p (js2-current-token)))
8503 ;; Report error if no EOL or autoinsert ';' otherwise
8504 (js2-report-error "msg.no.semi.stmt")
8505 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8506 (js2-unget-token) ; Not ';', do not consume.
8507 ))))
8508
8509 (defun js2-parse-condition ()
8510 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8511 The parens are discarded and the expression node is returned.
8512 The `pos' field of the return value is set to an absolute position
8513 that must be fixed up by the caller.
8514 Return value is a list (EXPR LP RP), with absolute paren positions."
8515 (let (pn lp rp)
8516 (if (js2-must-match js2-LP "msg.no.paren.cond")
8517 (setq lp (js2-current-token-beg)))
8518 (setq pn (js2-parse-expr))
8519 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8520 (setq rp (js2-current-token-beg)))
8521 ;; Report strict warning on code like "if (a = 7) ..."
8522 (if (and js2-strict-cond-assign-warning
8523 (js2-assign-node-p pn))
8524 (js2-add-strict-warning "msg.equal.as.assign" nil
8525 (js2-node-pos pn)
8526 (+ (js2-node-pos pn)
8527 (js2-node-len pn))))
8528 (list pn lp rp)))
8529
8530 (defun js2-parse-if ()
8531 "Parser for if-statement. Last matched token must be js2-IF."
8532 (let ((pos (js2-current-token-beg))
8533 cond if-true if-false else-pos end pn)
8534 (setq cond (js2-parse-condition)
8535 if-true (js2-parse-statement)
8536 if-false (if (js2-match-token js2-ELSE)
8537 (progn
8538 (setq else-pos (- (js2-current-token-beg) pos))
8539 (js2-parse-statement)))
8540 end (js2-node-end (or if-false if-true))
8541 pn (make-js2-if-node :pos pos
8542 :len (- end pos)
8543 :condition (car cond)
8544 :then-part if-true
8545 :else-part if-false
8546 :else-pos else-pos
8547 :lp (js2-relpos (cl-second cond) pos)
8548 :rp (js2-relpos (cl-third cond) pos)))
8549 (js2-node-add-children pn (car cond) if-true if-false)
8550 pn))
8551
8552 (defun js2-parse-import ()
8553 "Parse import statement. The current token must be js2-IMPORT."
8554 (unless (js2-ast-root-p js2-current-scope)
8555 (js2-report-error "msg.mod.import.decl.at.top.level"))
8556 (let ((beg (js2-current-token-beg)))
8557 (cond ((js2-match-token js2-STRING)
8558 (make-js2-import-node
8559 :pos beg
8560 :len (- (js2-current-token-end) beg)
8561 :module-id (js2-current-token-string)))
8562 (t
8563 (let* ((import-clause (js2-parse-import-clause))
8564 (from-clause (and import-clause (js2-parse-from-clause)))
8565 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8566 (node (make-js2-import-node
8567 :pos beg
8568 :len (- (js2-current-token-end) beg)
8569 :import import-clause
8570 :from from-clause
8571 :module-id module-id)))
8572 (when import-clause
8573 (js2-node-add-children node import-clause))
8574 (when from-clause
8575 (js2-node-add-children node from-clause))
8576 node)))))
8577
8578 (defun js2-parse-import-clause ()
8579 "Parse the bindings in an import statement.
8580 This can take many forms:
8581
8582 ImportedDefaultBinding -> 'foo'
8583 NameSpaceImport -> '* as lib'
8584 NamedImports -> '{foo as bar, bang}'
8585 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8586 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8587
8588 Try to match namespace imports and named imports first because nothing can
8589 come after them. If it is an imported default binding, then it could have named
8590 imports or a namespace import that follows it.
8591 "
8592 (let* ((beg (js2-current-token-beg))
8593 (clause (make-js2-import-clause-node
8594 :pos beg))
8595 (children (list)))
8596 (cond
8597 ((js2-match-token js2-MUL)
8598 (let ((ns-import (js2-parse-namespace-import)))
8599 (when ns-import
8600 (let ((name-node (js2-namespace-import-node-name ns-import)))
8601 (js2-define-symbol
8602 js2-LET (js2-name-node-name name-node) name-node t)))
8603 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8604 (push ns-import children)))
8605 ((js2-match-token js2-LC)
8606 (let ((imports (js2-parse-export-bindings t)))
8607 (setf (js2-import-clause-node-named-imports clause) imports)
8608 (dolist (import imports)
8609 (push import children)
8610 (let ((name-node (js2-export-binding-node-local-name import)))
8611 (when name-node
8612 (js2-define-symbol
8613 js2-LET (js2-name-node-name name-node) name-node t))))))
8614 ((= (js2-peek-token) js2-NAME)
8615 (let ((binding (js2-maybe-parse-export-binding t)))
8616 (let ((node-name (js2-export-binding-node-local-name binding)))
8617 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8618 (setf (js2-import-clause-node-default-binding clause) binding)
8619 (push binding children))
8620 (when (js2-match-token js2-COMMA)
8621 (cond
8622 ((js2-match-token js2-MUL)
8623 (let ((ns-import (js2-parse-namespace-import)))
8624 (let ((name-node (js2-namespace-import-node-name ns-import)))
8625 (js2-define-symbol
8626 js2-LET (js2-name-node-name name-node) name-node t))
8627 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8628 (push ns-import children)))
8629 ((js2-match-token js2-LC)
8630 (let ((imports (js2-parse-export-bindings t)))
8631 (setf (js2-import-clause-node-named-imports clause) imports)
8632 (dolist (import imports)
8633 (push import children)
8634 (let ((name-node (js2-export-binding-node-local-name import)))
8635 (when name-node
8636 (js2-define-symbol
8637 js2-LET (js2-name-node-name name-node) name-node t))))))
8638 (t (js2-report-error "msg.syntax")))))
8639 (t (js2-report-error "msg.mod.declaration.after.import")))
8640 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8641 (apply #'js2-node-add-children clause children)
8642 clause))
8643
8644 (defun js2-parse-namespace-import ()
8645 "Parse a namespace import expression such as '* as bar'.
8646 The current token must be js2-MUL."
8647 (let ((beg (js2-current-token-beg)))
8648 (if (js2-match-contextual-kwd "as")
8649 (when (js2-must-match-prop-name "msg.syntax")
8650 (let ((node (make-js2-namespace-import-node
8651 :pos beg
8652 :len (- (js2-current-token-end) beg)
8653 :name (make-js2-name-node
8654 :pos (js2-current-token-beg)
8655 :len (js2-current-token-end)
8656 :name (js2-current-token-string)))))
8657 (js2-node-add-children node (js2-namespace-import-node-name node))
8658 node))
8659 (js2-unget-token)
8660 (js2-report-error "msg.syntax"))))
8661
8662
8663 (defun js2-parse-from-clause ()
8664 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8665 (if (js2-match-contextual-kwd "from")
8666 (let ((beg (js2-current-token-beg)))
8667 (cond
8668 ((js2-match-token js2-STRING)
8669 (make-js2-from-clause-node
8670 :pos beg
8671 :len (- (js2-current-token-end) beg)
8672 :module-id (js2-current-token-string)
8673 :metadata-p nil))
8674 ((js2-match-token js2-THIS)
8675 (when (js2-must-match-name "msg.mod.spec.after.from")
8676 (if (equal "module" (js2-current-token-string))
8677 (make-js2-from-clause-node
8678 :pos beg
8679 :len (- (js2-current-token-end) beg)
8680 :module-id "this"
8681 :metadata-p t)
8682 (js2-unget-token)
8683 (js2-unget-token)
8684 (js2-report-error "msg.mod.spec.after.from")
8685 nil)))
8686 (t (js2-report-error "msg.mod.spec.after.from") nil)))
8687 (js2-report-error "msg.mod.from.after.import.spec.set")
8688 nil))
8689
8690 (defun js2-parse-export-bindings (&optional import-p)
8691 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8692 {foo as bar, baz as bang}. The current token must be
8693 js2-LC. Return a lisp list of js2-export-binding-node"
8694 (let ((bindings (list)))
8695 (while
8696 (let ((binding (js2-maybe-parse-export-binding import-p)))
8697 (when binding
8698 (push binding bindings))
8699 (js2-match-token js2-COMMA)))
8700 (when (js2-must-match js2-RC (if import-p
8701 "msg.mod.rc.after.import.spec.list"
8702 "msg.mod.rc.after.export.spec.list"))
8703 (reverse bindings))))
8704
8705 (defun js2-maybe-parse-export-binding (&optional import-p)
8706 "Attempt to parse a binding expression found inside an import/export statement.
8707 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8708 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8709 js2-export-binding-node and consume all the tokens. If it does not match, it
8710 consumes no tokens."
8711 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8712 (beg (js2-current-token-beg))
8713 (extern-name-len (js2-current-token-len))
8714 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8715 (aref js2-kwd-tokens (js2-current-token-type)))))
8716 (if extern-name
8717 (if (js2-match-contextual-kwd "as")
8718 (let ((name
8719 (or
8720 (and (js2-match-token js2-DEFAULT) "default")
8721 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8722 (if name
8723 (let ((node (make-js2-export-binding-node
8724 :pos beg
8725 :len (- (js2-current-token-end) beg)
8726 :local-name (make-js2-name-node
8727 :name name
8728 :pos (js2-current-token-beg)
8729 :len (js2-current-token-len))
8730 :extern-name (make-js2-name-node
8731 :name extern-name
8732 :pos beg
8733 :len extern-name-len))))
8734 (js2-node-add-children
8735 node
8736 (js2-export-binding-node-local-name node)
8737 (js2-export-binding-node-extern-name node))
8738 (if import-p
8739 (js2-set-face (js2-current-token-beg) (js2-current-token-end)
8740 'font-lock-variable-name-face 'record))
8741 node)
8742 (js2-unget-token)
8743 nil))
8744 (let* ((name-node (make-js2-name-node
8745 :name (js2-current-token-string)
8746 :pos (js2-current-token-beg)
8747 :len (js2-current-token-len)))
8748 (node (make-js2-export-binding-node
8749 :pos (js2-current-token-beg)
8750 :len (js2-current-token-len)
8751 :local-name name-node
8752 :extern-name name-node)))
8753 (when is-reserved-name
8754 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8755 (js2-node-add-children node name-node)
8756 (if import-p
8757 (js2-set-face (js2-current-token-beg) (js2-current-token-end)
8758 'font-lock-variable-name-face 'record))
8759 node))
8760 nil)))
8761
8762 (defun js2-parse-switch ()
8763 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8764 (let ((pos (js2-current-token-beg))
8765 tt pn discriminant has-default case-expr case-node
8766 case-pos cases stmt lp)
8767 (if (js2-must-match js2-LP "msg.no.paren.switch")
8768 (setq lp (js2-current-token-beg)))
8769 (setq discriminant (js2-parse-expr)
8770 pn (make-js2-switch-node :discriminant discriminant
8771 :pos pos
8772 :lp (js2-relpos lp pos)))
8773 (js2-node-add-children pn discriminant)
8774 (js2-enter-switch pn)
8775 (unwind-protect
8776 (progn
8777 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8778 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8779 (js2-must-match js2-LC "msg.no.brace.switch")
8780 (catch 'break
8781 (while t
8782 (setq tt (js2-next-token)
8783 case-pos (js2-current-token-beg))
8784 (cond
8785 ((= tt js2-RC)
8786 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8787 (throw 'break nil)) ; done
8788 ((= tt js2-CASE)
8789 (setq case-expr (js2-parse-expr))
8790 (js2-must-match js2-COLON "msg.no.colon.case"))
8791 ((= tt js2-DEFAULT)
8792 (if has-default
8793 (js2-report-error "msg.double.switch.default"))
8794 (setq has-default t
8795 case-expr nil)
8796 (js2-must-match js2-COLON "msg.no.colon.case"))
8797 (t
8798 (js2-report-error "msg.bad.switch")
8799 (throw 'break nil)))
8800 (setq case-node (make-js2-case-node :pos case-pos
8801 :len (- (js2-current-token-end) case-pos)
8802 :expr case-expr))
8803 (js2-node-add-children case-node case-expr)
8804 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8805 (/= tt js2-CASE)
8806 (/= tt js2-DEFAULT)
8807 (/= tt js2-EOF))
8808 (setf stmt (js2-parse-statement)
8809 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8810 (js2-block-node-push case-node stmt))
8811 (push case-node cases)))
8812 ;; add cases last, as pushing reverses the order to be correct
8813 (dolist (kid cases)
8814 (js2-node-add-children pn kid)
8815 (push kid (js2-switch-node-cases pn)))
8816 pn) ; return value
8817 (js2-exit-switch))))
8818
8819 (defun js2-parse-while ()
8820 "Parser for while-statement. Last matched token must be js2-WHILE."
8821 (let ((pos (js2-current-token-beg))
8822 (pn (make-js2-while-node))
8823 cond body)
8824 (js2-enter-loop pn)
8825 (unwind-protect
8826 (progn
8827 (setf cond (js2-parse-condition)
8828 (js2-while-node-condition pn) (car cond)
8829 body (js2-parse-statement)
8830 (js2-while-node-body pn) body
8831 (js2-node-len pn) (- (js2-node-end body) pos)
8832 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8833 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8834 (js2-node-add-children pn body (car cond)))
8835 (js2-exit-loop))
8836 pn))
8837
8838 (defun js2-parse-do ()
8839 "Parser for do-statement. Last matched token must be js2-DO."
8840 (let ((pos (js2-current-token-beg))
8841 (pn (make-js2-do-node))
8842 cond body end)
8843 (js2-enter-loop pn)
8844 (unwind-protect
8845 (progn
8846 (setq body (js2-parse-statement))
8847 (js2-must-match js2-WHILE "msg.no.while.do")
8848 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8849 cond (js2-parse-condition)
8850 (js2-do-node-condition pn) (car cond)
8851 (js2-do-node-body pn) body
8852 end js2-ts-cursor
8853 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8854 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8855 (js2-node-add-children pn (car cond) body))
8856 (js2-exit-loop))
8857 ;; Always auto-insert semicolon to follow SpiderMonkey:
8858 ;; It is required by ECMAScript but is ignored by the rest of
8859 ;; world; see bug 238945
8860 (if (js2-match-token js2-SEMI)
8861 (setq end js2-ts-cursor))
8862 (setf (js2-node-len pn) (- end pos))
8863 pn))
8864
8865 (defun js2-parse-export ()
8866 "Parse an export statement.
8867 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8868 expressions should only be either hoistable expressions (function or generator)
8869 or assignment expressions, but there is no checking to enforce that and so it
8870 will parse without error a small subset of
8871 invalid export statements."
8872 (unless (js2-ast-root-p js2-current-scope)
8873 (js2-report-error "msg.mod.export.decl.at.top.level"))
8874 (let ((beg (js2-current-token-beg))
8875 (children (list))
8876 exports-list from-clause declaration default)
8877 (cond
8878 ((js2-match-token js2-MUL)
8879 (setq from-clause (js2-parse-from-clause))
8880 (when from-clause
8881 (push from-clause children)))
8882 ((js2-match-token js2-LC)
8883 (setq exports-list (js2-parse-export-bindings))
8884 (when exports-list
8885 (dolist (export exports-list)
8886 (push export children)))
8887 (when (js2-match-contextual-kwd "from")
8888 (js2-unget-token)
8889 (setq from-clause (js2-parse-from-clause))))
8890 ((js2-match-token js2-DEFAULT)
8891 (setq default (cond ((js2-match-token js2-CLASS)
8892 (js2-parse-class-stmt))
8893 ((js2-match-token js2-NAME)
8894 (if (js2-match-async-function)
8895 (js2-parse-async-function-stmt)
8896 (js2-unget-token)
8897 (js2-parse-expr)))
8898 ((js2-match-token js2-FUNCTION)
8899 (js2-parse-function-stmt))
8900 (t (js2-parse-expr)))))
8901 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8902 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8903 ((js2-match-token js2-CLASS)
8904 (setq declaration (js2-parse-class-stmt)))
8905 ((js2-match-token js2-NAME)
8906 (setq declaration
8907 (if (js2-match-async-function)
8908 (js2-parse-async-function-stmt)
8909 (js2-unget-token)
8910 (js2-parse-expr))))
8911 ((js2-match-token js2-FUNCTION)
8912 (setq declaration (js2-parse-function-stmt)))
8913 (t
8914 (setq declaration (js2-parse-expr))))
8915 (when from-clause
8916 (push from-clause children))
8917 (when declaration
8918 (push declaration children)
8919 (when (not (or (js2-function-node-p declaration)
8920 (js2-class-node-p declaration)))
8921 (js2-auto-insert-semicolon declaration)))
8922 (when default
8923 (push default children)
8924 (when (not (or (js2-function-node-p default)
8925 (js2-class-node-p default)))
8926 (js2-auto-insert-semicolon default)))
8927 (let ((node (make-js2-export-node
8928 :pos beg
8929 :len (- (js2-current-token-end) beg)
8930 :exports-list exports-list
8931 :from-clause from-clause
8932 :declaration declaration
8933 :default default)))
8934 (apply #'js2-node-add-children node children)
8935 node)))
8936
8937 (defun js2-parse-for ()
8938 "Parse a for, for-in or for each-in statement.
8939 Last matched token must be js2-FOR."
8940 (let ((for-pos (js2-current-token-beg))
8941 (tmp-scope (make-js2-scope))
8942 pn is-for-each is-for-in-or-of is-for-of
8943 in-pos each-pos tmp-pos
8944 init ; Node init is also foo in 'foo in object'.
8945 cond ; Node cond is also object in 'foo in object'.
8946 incr ; 3rd section of for-loop initializer.
8947 body tt lp rp)
8948 ;; See if this is a for each () instead of just a for ()
8949 (when (js2-match-token js2-NAME)
8950 (if (string= "each" (js2-current-token-string))
8951 (progn
8952 (setq is-for-each t
8953 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8954 (js2-record-face 'font-lock-keyword-face))
8955 (js2-report-error "msg.no.paren.for")))
8956 (if (js2-must-match js2-LP "msg.no.paren.for")
8957 (setq lp (- (js2-current-token-beg) for-pos)))
8958 (setq tt (js2-get-token))
8959 ;; Capture identifiers inside parens. We can't create the node
8960 ;; (and use it as the current scope) until we know its type.
8961 (js2-push-scope tmp-scope)
8962 (unwind-protect
8963 (progn
8964 ;; parse init clause
8965 (let ((js2-in-for-init t)) ; set as dynamic variable
8966 (cond
8967 ((= tt js2-SEMI)
8968 (js2-unget-token)
8969 (setq init (make-js2-empty-expr-node)))
8970 ((or (= tt js2-VAR) (= tt js2-LET) (= tt js2-CONST))
8971 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8972 (t
8973 (js2-unget-token)
8974 (setq init (js2-parse-expr)))))
8975 (if (or (js2-match-token js2-IN)
8976 (and (>= js2-language-version 200)
8977 (js2-match-contextual-kwd "of")
8978 (setq is-for-of t)))
8979 (setq is-for-in-or-of t
8980 in-pos (- (js2-current-token-beg) for-pos)
8981 ;; scope of iteration target object is not the scope we've created above.
8982 ;; stash current scope temporary.
8983 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8984 (js2-parse-expr))) ; object over which we're iterating
8985 ;; else ordinary for loop - parse cond and incr
8986 (js2-must-match js2-SEMI "msg.no.semi.for")
8987 (setq cond (if (= (js2-peek-token) js2-SEMI)
8988 (make-js2-empty-expr-node) ; no loop condition
8989 (js2-parse-expr)))
8990 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8991 (setq tmp-pos (js2-current-token-end)
8992 incr (if (= (js2-peek-token) js2-RP)
8993 (make-js2-empty-expr-node :pos tmp-pos)
8994 (js2-parse-expr)))))
8995 (js2-pop-scope))
8996 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8997 (setq rp (- (js2-current-token-beg) for-pos)))
8998 (if (not is-for-in-or-of)
8999 (setq pn (make-js2-for-node :init init
9000 :condition cond
9001 :update incr
9002 :lp lp
9003 :rp rp))
9004 ;; cond could be null if 'in obj' got eaten by the init node.
9005 (if (js2-infix-node-p init)
9006 ;; it was (foo in bar) instead of (var foo in bar)
9007 (setq cond (js2-infix-node-right init)
9008 init (js2-infix-node-left init))
9009 (if (and (js2-var-decl-node-p init)
9010 (> (length (js2-var-decl-node-kids init)) 1))
9011 (js2-report-error "msg.mult.index")))
9012 (setq pn (make-js2-for-in-node :iterator init
9013 :object cond
9014 :in-pos in-pos
9015 :foreach-p is-for-each
9016 :each-pos each-pos
9017 :forof-p is-for-of
9018 :lp lp
9019 :rp rp)))
9020 ;; Transplant the declarations.
9021 (setf (js2-scope-symbol-table pn)
9022 (js2-scope-symbol-table tmp-scope))
9023 (unwind-protect
9024 (progn
9025 (js2-enter-loop pn)
9026 ;; We have to parse the body -after- creating the loop node,
9027 ;; so that the loop node appears in the js2-loop-set, allowing
9028 ;; break/continue statements to find the enclosing loop.
9029 (setf body (js2-parse-statement)
9030 (js2-loop-node-body pn) body
9031 (js2-node-pos pn) for-pos
9032 (js2-node-len pn) (- (js2-node-end body) for-pos))
9033 (js2-node-add-children pn init cond incr body))
9034 ;; finally
9035 (js2-exit-loop))
9036 pn))
9037
9038 (defun js2-parse-try ()
9039 "Parse a try statement. Last matched token must be js2-TRY."
9040 (let ((try-pos (js2-current-token-beg))
9041 try-end
9042 try-block
9043 catch-blocks
9044 finally-block
9045 saw-default-catch
9046 peek)
9047 (if (/= (js2-peek-token) js2-LC)
9048 (js2-report-error "msg.no.brace.try"))
9049 (setq try-block (js2-parse-statement)
9050 try-end (js2-node-end try-block)
9051 peek (js2-peek-token))
9052 (cond
9053 ((= peek js2-CATCH)
9054 (while (js2-match-token js2-CATCH)
9055 (let* ((catch-pos (js2-current-token-beg))
9056 (catch-node (make-js2-catch-node :pos catch-pos))
9057 param
9058 guard-kwd
9059 catch-cond
9060 lp rp)
9061 (if saw-default-catch
9062 (js2-report-error "msg.catch.unreachable"))
9063 (if (js2-must-match js2-LP "msg.no.paren.catch")
9064 (setq lp (- (js2-current-token-beg) catch-pos)))
9065 (js2-push-scope catch-node)
9066 (let ((tt (js2-peek-token)))
9067 (cond
9068 ;; Destructuring pattern:
9069 ;; catch ({ message, file }) { ... }
9070 ((or (= tt js2-LB) (= tt js2-LC))
9071 (js2-get-token)
9072 (setq param (js2-parse-destruct-primary-expr))
9073 (js2-define-destruct-symbols param js2-LET nil))
9074 ;; Simple name.
9075 (t
9076 (js2-must-match-name "msg.bad.catchcond")
9077 (setq param (js2-create-name-node))
9078 (js2-define-symbol js2-LET (js2-current-token-string) param)
9079 (js2-check-strict-identifier param))))
9080 ;; Catch condition.
9081 (if (js2-match-token js2-IF)
9082 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9083 catch-cond (js2-parse-expr))
9084 (setq saw-default-catch t))
9085 (if (js2-must-match js2-RP "msg.bad.catchcond")
9086 (setq rp (- (js2-current-token-beg) catch-pos)))
9087 (js2-must-match js2-LC "msg.no.brace.catchblock")
9088 (js2-parse-statements catch-node)
9089 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9090 (setq try-end (js2-current-token-end)))
9091 (js2-pop-scope)
9092 (setf (js2-node-len catch-node) (- try-end catch-pos)
9093 (js2-catch-node-param catch-node) param
9094 (js2-catch-node-guard-expr catch-node) catch-cond
9095 (js2-catch-node-guard-kwd catch-node) guard-kwd
9096 (js2-catch-node-lp catch-node) lp
9097 (js2-catch-node-rp catch-node) rp)
9098 (js2-node-add-children catch-node param catch-cond)
9099 (push catch-node catch-blocks))))
9100 ((/= peek js2-FINALLY)
9101 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9102 (js2-node-pos try-block)
9103 (- (setq try-end (js2-node-end try-block))
9104 (js2-node-pos try-block)))))
9105 (when (js2-match-token js2-FINALLY)
9106 (let ((finally-pos (js2-current-token-beg))
9107 (block (js2-parse-statement)))
9108 (setq try-end (js2-node-end block)
9109 finally-block (make-js2-finally-node :pos finally-pos
9110 :len (- try-end finally-pos)
9111 :body block))
9112 (js2-node-add-children finally-block block)))
9113 (let ((pn (make-js2-try-node :pos try-pos
9114 :len (- try-end try-pos)
9115 :try-block try-block
9116 :finally-block finally-block)))
9117 (js2-node-add-children pn try-block finally-block)
9118 ;; Push them onto the try-node, which reverses and corrects their order.
9119 (dolist (cb catch-blocks)
9120 (js2-node-add-children pn cb)
9121 (push cb (js2-try-node-catch-clauses pn)))
9122 pn)))
9123
9124 (defun js2-parse-throw ()
9125 "Parser for throw-statement. Last matched token must be js2-THROW."
9126 (let ((pos (js2-current-token-beg))
9127 expr pn)
9128 (if (= (js2-peek-token-or-eol) js2-EOL)
9129 ;; ECMAScript does not allow new lines before throw expression,
9130 ;; see bug 256617
9131 (js2-report-error "msg.bad.throw.eol"))
9132 (setq expr (js2-parse-expr)
9133 pn (make-js2-throw-node :pos pos
9134 :len (- (js2-node-end expr) pos)
9135 :expr expr))
9136 (js2-node-add-children pn expr)
9137 pn))
9138
9139 (defun js2-match-jump-label-name (label-name)
9140 "If break/continue specified a label, return that label's labeled stmt.
9141 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9142 does not match an existing label, reports an error and returns nil."
9143 (let ((bundle (cdr (assoc label-name js2-label-set))))
9144 (if (null bundle)
9145 (js2-report-error "msg.undef.label"))
9146 bundle))
9147
9148 (defun js2-parse-break ()
9149 "Parser for break-statement. Last matched token must be js2-BREAK."
9150 (let ((pos (js2-current-token-beg))
9151 (end (js2-current-token-end))
9152 break-target ; statement to break from
9153 break-label ; in "break foo", name-node representing the foo
9154 labels ; matching labeled statement to break to
9155 pn)
9156 (when (eq (js2-peek-token-or-eol) js2-NAME)
9157 (js2-get-token)
9158 (setq break-label (js2-create-name-node)
9159 end (js2-node-end break-label)
9160 ;; matchJumpLabelName only matches if there is one
9161 labels (js2-match-jump-label-name (js2-current-token-string))
9162 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9163 (unless (or break-target break-label)
9164 ;; no break target specified - try for innermost enclosing loop/switch
9165 (if (null js2-loop-and-switch-set)
9166 (unless break-label
9167 (js2-report-error "msg.bad.break" nil pos (length "break")))
9168 (setq break-target (car js2-loop-and-switch-set))))
9169 (setq pn (make-js2-break-node :pos pos
9170 :len (- end pos)
9171 :label break-label
9172 :target break-target))
9173 (js2-node-add-children pn break-label) ; but not break-target
9174 pn))
9175
9176 (defun js2-parse-continue ()
9177 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9178 (let ((pos (js2-current-token-beg))
9179 (end (js2-current-token-end))
9180 label ; optional user-specified label, a `js2-name-node'
9181 labels ; current matching labeled stmt, if any
9182 target ; the `js2-loop-node' target of this continue stmt
9183 pn)
9184 (when (= (js2-peek-token-or-eol) js2-NAME)
9185 (js2-get-token)
9186 (setq label (js2-create-name-node)
9187 end (js2-node-end label)
9188 ;; matchJumpLabelName only matches if there is one
9189 labels (js2-match-jump-label-name (js2-current-token-string))))
9190 (cond
9191 ((null labels) ; no current label to go to
9192 (if (null js2-loop-set) ; no loop to continue to
9193 (js2-report-error "msg.continue.outside" nil pos
9194 (length "continue"))
9195 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9196 (t
9197 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9198 (setq target (js2-labeled-stmt-node-stmt labels))
9199 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9200 (setq pn (make-js2-continue-node :pos pos
9201 :len (- end pos)
9202 :label label
9203 :target target))
9204 (js2-node-add-children pn label) ; but not target - it's not our child
9205 pn))
9206
9207 (defun js2-parse-with ()
9208 "Parser for with-statement. Last matched token must be js2-WITH."
9209 (when js2-in-use-strict-directive
9210 (js2-report-error "msg.no.with.strict"))
9211 (let ((pos (js2-current-token-beg))
9212 obj body pn lp rp)
9213 (if (js2-must-match js2-LP "msg.no.paren.with")
9214 (setq lp (js2-current-token-beg)))
9215 (setq obj (js2-parse-expr))
9216 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9217 (setq rp (js2-current-token-beg)))
9218 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9219 (setq body (js2-parse-statement)))
9220 (setq pn (make-js2-with-node :pos pos
9221 :len (- (js2-node-end body) pos)
9222 :object obj
9223 :body body
9224 :lp (js2-relpos lp pos)
9225 :rp (js2-relpos rp pos)))
9226 (js2-node-add-children pn obj body)
9227 pn))
9228
9229 (defun js2-parse-const-var ()
9230 "Parser for var- or const-statement.
9231 Last matched token must be js2-CONST or js2-VAR."
9232 (let ((tt (js2-current-token-type))
9233 (pos (js2-current-token-beg))
9234 expr pn)
9235 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9236 pn (make-js2-expr-stmt-node :pos pos
9237 :len (- (js2-node-end expr) pos)
9238 :expr expr))
9239 (js2-node-add-children pn expr)
9240 pn))
9241
9242 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9243 (let ((pn (make-js2-expr-stmt-node :pos pos
9244 :len (js2-node-len expr)
9245 :type (if (js2-inside-function)
9246 js2-EXPR_VOID
9247 js2-EXPR_RESULT)
9248 :expr expr)))
9249 (if add-child
9250 (js2-node-add-children pn expr))
9251 pn))
9252
9253 (defun js2-parse-let-stmt ()
9254 "Parser for let-statement. Last matched token must be js2-LET."
9255 (let ((pos (js2-current-token-beg))
9256 expr pn)
9257 (if (= (js2-peek-token) js2-LP)
9258 ;; let expression in statement context
9259 (setq expr (js2-parse-let pos 'statement)
9260 pn (js2-wrap-with-expr-stmt pos expr t))
9261 ;; else we're looking at a statement like let x=6, y=7;
9262 (setf expr (js2-parse-variables js2-LET pos)
9263 pn (js2-wrap-with-expr-stmt pos expr t)
9264 (js2-node-type pn) js2-EXPR_RESULT))
9265 pn))
9266
9267 (defun js2-parse-ret-yield ()
9268 (js2-parse-return-or-yield (js2-current-token-type) nil))
9269
9270 (defconst js2-parse-return-stmt-enders
9271 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9272
9273 (defsubst js2-now-all-set (before after mask)
9274 "Return whether or not the bits in the mask have changed to all set.
9275 BEFORE is bits before change, AFTER is bits after change, and MASK is
9276 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9277 but not BEFORE."
9278 (and (/= (logand before mask) mask)
9279 (= (logand after mask) mask)))
9280
9281 (defun js2-parse-return-or-yield (tt expr-context)
9282 (let* ((pos (js2-current-token-beg))
9283 (end (js2-current-token-end))
9284 (before js2-end-flags)
9285 (inside-function (js2-inside-function))
9286 (gen-type (and inside-function (js2-function-node-generator-type
9287 js2-current-script-or-fn)))
9288 e ret name yield-star-p)
9289 (unless inside-function
9290 (js2-report-error (if (eq tt js2-RETURN)
9291 "msg.bad.return"
9292 "msg.bad.yield")))
9293 (when (and inside-function
9294 (eq gen-type 'STAR)
9295 (js2-match-token js2-MUL))
9296 (setq yield-star-p t))
9297 ;; This is ugly, but we don't want to require a semicolon.
9298 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9299 (setq e (js2-parse-expr)
9300 end (js2-node-end e)))
9301 (cond
9302 ((eq tt js2-RETURN)
9303 (js2-set-flag js2-end-flags (if (null e)
9304 js2-end-returns
9305 js2-end-returns-value))
9306 (setq ret (make-js2-return-node :pos pos
9307 :len (- end pos)
9308 :retval e))
9309 (js2-node-add-children ret e)
9310 ;; See if we need a strict mode warning.
9311 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9312 ;; more thorough and accurate than this before/after flag check.
9313 ;; E.g. if there's a finally-block that always returns, we shouldn't
9314 ;; show a warning generated by inconsistent returns in the catch blocks.
9315 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9316 ;; so we know which returns/yields to highlight, and we should get rid of
9317 ;; all the checking in `js2-parse-return-or-yield'.
9318 (if (and js2-strict-inconsistent-return-warning
9319 (js2-now-all-set before js2-end-flags
9320 (logior js2-end-returns js2-end-returns-value)))
9321 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9322 ((eq gen-type 'COMPREHENSION)
9323 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9324 ;; like SpiderMonkey does.
9325 (js2-report-error "msg.syntax" nil pos 5))
9326 (t
9327 (setq ret (make-js2-yield-node :pos pos
9328 :len (- end pos)
9329 :value e
9330 :star-p yield-star-p))
9331 (js2-node-add-children ret e)
9332 (unless expr-context
9333 (setq e ret
9334 ret (js2-wrap-with-expr-stmt pos e t))
9335 (js2-set-requires-activation)
9336 (js2-set-is-generator))))
9337 ;; see if we are mixing yields and value returns.
9338 (when (and inside-function
9339 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9340 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9341 'LEGACY))
9342 (setq name (js2-function-name js2-current-script-or-fn))
9343 (if (zerop (length name))
9344 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9345 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9346 ret))
9347
9348 (defun js2-parse-debugger ()
9349 (make-js2-keyword-node :type js2-DEBUGGER))
9350
9351 (defun js2-parse-block ()
9352 "Parser for a curly-delimited statement block.
9353 Last token matched must be `js2-LC'."
9354 (let ((pos (js2-current-token-beg))
9355 (pn (make-js2-scope)))
9356 (js2-push-scope pn)
9357 (unwind-protect
9358 (progn
9359 (js2-parse-statements pn)
9360 (js2-must-match js2-RC "msg.no.brace.block")
9361 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9362 (js2-pop-scope))
9363 pn))
9364
9365 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9366 (defun js2-parse-semi ()
9367 "Parse a statement or handle an error.
9368 Current token type is `js2-SEMI' or `js2-ERROR'."
9369 (let ((tt (js2-current-token-type)) pos len)
9370 (if (eq tt js2-SEMI)
9371 (make-js2-empty-expr-node :len 1)
9372 (setq pos (js2-current-token-beg)
9373 len (- (js2-current-token-end) pos))
9374 (js2-report-error "msg.syntax" nil pos len)
9375 (make-js2-error-node :pos pos :len len))))
9376
9377 (defun js2-parse-default-xml-namespace ()
9378 "Parse a `default xml namespace = <expr>' e4x statement."
9379 (let ((pos (js2-current-token-beg))
9380 end len expr unary)
9381 (js2-must-have-xml)
9382 (js2-set-requires-activation)
9383 (setq len (- js2-ts-cursor pos))
9384 (unless (and (js2-match-token js2-NAME)
9385 (string= (js2-current-token-string) "xml"))
9386 (js2-report-error "msg.bad.namespace" nil pos len))
9387 (unless (and (js2-match-token js2-NAME)
9388 (string= (js2-current-token-string) "namespace"))
9389 (js2-report-error "msg.bad.namespace" nil pos len))
9390 (unless (js2-match-token js2-ASSIGN)
9391 (js2-report-error "msg.bad.namespace" nil pos len))
9392 (setq expr (js2-parse-expr)
9393 end (js2-node-end expr)
9394 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9395 :pos pos
9396 :len (- end pos)
9397 :operand expr))
9398 (js2-node-add-children unary expr)
9399 (make-js2-expr-stmt-node :pos pos
9400 :len (- end pos)
9401 :expr unary)))
9402
9403 (defun js2-record-label (label bundle)
9404 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9405 (js2-get-token)
9406 (let ((name (js2-label-node-name label))
9407 labeled-stmt
9408 dup)
9409 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9410 ;; flag both labels if possible when used in editing mode
9411 (if (and js2-parse-ide-mode
9412 (setq dup (js2-get-label-by-name labeled-stmt name)))
9413 (js2-report-error "msg.dup.label" nil
9414 (js2-node-abs-pos dup) (js2-node-len dup)))
9415 (js2-report-error "msg.dup.label" nil
9416 (js2-node-pos label) (js2-node-len label)))
9417 (js2-labeled-stmt-node-add-label bundle label)
9418 (js2-node-add-children bundle label)
9419 ;; Add one reference to the bundle per label in `js2-label-set'
9420 (push (cons name bundle) js2-label-set)))
9421
9422 (defun js2-parse-name-or-label ()
9423 "Parser for identifier or label. Last token matched must be js2-NAME.
9424 Called when we found a name in a statement context. If it's a label, we gather
9425 up any following labels and the next non-label statement into a
9426 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9427 expression and return it wrapped in a `js2-expr-stmt-node'."
9428 (let ((pos (js2-current-token-beg))
9429 expr stmt bundle
9430 (continue t))
9431 ;; set check for label and call down to `js2-parse-primary-expr'
9432 (setq expr (js2-maybe-parse-label))
9433 (if (null expr)
9434 ;; Parse the non-label expression and wrap with expression stmt.
9435 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9436 ;; else parsed a label
9437 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9438 (js2-record-label expr bundle)
9439 ;; look for more labels
9440 (while (and continue (= (js2-get-token) js2-NAME))
9441 (if (setq expr (js2-maybe-parse-label))
9442 (js2-record-label expr bundle)
9443 (setq expr (js2-parse-expr)
9444 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9445 continue nil)
9446 (js2-auto-insert-semicolon stmt)))
9447 ;; no more labels; now parse the labeled statement
9448 (unwind-protect
9449 (unless stmt
9450 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9451 (js2-unget-token)
9452 (setq stmt (js2-statement-helper))))
9453 ;; remove the labels for this statement from the global set
9454 (dolist (label (js2-labeled-stmt-node-labels bundle))
9455 (setq js2-label-set (remove label js2-label-set))))
9456 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9457 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9458 (js2-node-add-children bundle stmt)
9459 bundle)))
9460
9461 (defun js2-maybe-parse-label ()
9462 (cl-assert (= (js2-current-token-type) js2-NAME))
9463 (let (label-pos
9464 (next-tt (js2-get-token))
9465 (label-end (js2-current-token-end)))
9466 ;; Do not consume colon, it is used as unwind indicator
9467 ;; to return to statementHelper.
9468 (js2-unget-token)
9469 (if (= next-tt js2-COLON)
9470 (prog2
9471 (setq label-pos (js2-current-token-beg))
9472 (make-js2-label-node :pos label-pos
9473 :len (- label-end label-pos)
9474 :name (js2-current-token-string))
9475 (js2-set-face label-pos
9476 label-end
9477 'font-lock-variable-name-face 'record))
9478 ;; Backtrack from the name token, too.
9479 (js2-unget-token)
9480 nil)))
9481
9482 (defun js2-parse-expr-stmt ()
9483 "Default parser in statement context, if no recognized statement found."
9484 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9485 (progn
9486 (js2-unget-token)
9487 (js2-parse-expr)) t))
9488
9489 (defun js2-parse-variables (decl-type pos)
9490 "Parse a comma-separated list of variable declarations.
9491 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9492
9493 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9494 For 'var' or 'const', the keyword should be the token last scanned.
9495
9496 POS is the position where the node should start. It's sometimes the
9497 var/const/let keyword, and other times the beginning of the first token
9498 in the first variable declaration.
9499
9500 Returns the parsed `js2-var-decl-node' expression node."
9501 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9502 :pos pos))
9503 destructuring kid-pos tt init name end nbeg nend vi
9504 (continue t))
9505 ;; Example:
9506 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9507 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9508 ;; var {a, b} = baz;
9509 (while continue
9510 (setq destructuring nil
9511 name nil
9512 tt (js2-get-token)
9513 kid-pos (js2-current-token-beg)
9514 end (js2-current-token-end)
9515 init nil)
9516 (if (or (= tt js2-LB) (= tt js2-LC))
9517 ;; Destructuring assignment, e.g., var [a, b] = ...
9518 (setq destructuring (js2-parse-destruct-primary-expr)
9519 end (js2-node-end destructuring))
9520 ;; Simple variable name
9521 (js2-unget-token)
9522 (when (js2-must-match-name "msg.bad.var")
9523 (setq name (js2-create-name-node)
9524 nbeg (js2-current-token-beg)
9525 nend (js2-current-token-end)
9526 end nend)
9527 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9528 (js2-check-strict-identifier name)))
9529 (when (js2-match-token js2-ASSIGN)
9530 (setq init (js2-parse-assign-expr)
9531 end (js2-node-end init))
9532 (js2-record-imenu-functions init name))
9533 (when name
9534 (js2-set-face nbeg nend (if (js2-function-node-p init)
9535 'font-lock-function-name-face
9536 'font-lock-variable-name-face)
9537 'record))
9538 (setq vi (make-js2-var-init-node :pos kid-pos
9539 :len (- end kid-pos)
9540 :type decl-type))
9541 (if destructuring
9542 (progn
9543 (if (and (null init) (not js2-in-for-init))
9544 (js2-report-error "msg.destruct.assign.no.init"))
9545 (js2-define-destruct-symbols destructuring
9546 decl-type
9547 'font-lock-variable-name-face)
9548 (setf (js2-var-init-node-target vi) destructuring))
9549 (setf (js2-var-init-node-target vi) name))
9550 (setf (js2-var-init-node-initializer vi) init)
9551 (js2-node-add-children vi name destructuring init)
9552 (js2-block-node-push result vi)
9553 (unless (js2-match-token js2-COMMA)
9554 (setq continue nil)))
9555 (setf (js2-node-len result) (- end pos))
9556 result))
9557
9558 (defun js2-parse-let (pos &optional stmt-p)
9559 "Parse a let expression or statement.
9560 A let-expression is of the form `let (vars) expr'.
9561 A let-statement is of the form `let (vars) {statements}'.
9562 The third form of let is a variable declaration list, handled
9563 by `js2-parse-variables'."
9564 (let ((pn (make-js2-let-node :pos pos))
9565 beg vars body)
9566 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9567 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9568 (js2-push-scope pn)
9569 (unwind-protect
9570 (progn
9571 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9572 (if (js2-must-match js2-RP "msg.no.paren.let")
9573 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9574 (if (and stmt-p (js2-match-token js2-LC))
9575 ;; let statement
9576 (progn
9577 (setf beg (js2-current-token-beg) ; position stmt at LC
9578 body (js2-parse-statements))
9579 (js2-must-match js2-RC "msg.no.curly.let")
9580 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9581 (js2-node-len pn) (- (js2-current-token-end) pos)
9582 (js2-let-node-body pn) body
9583 (js2-node-type pn) js2-LET))
9584 ;; let expression
9585 (setf body (js2-parse-expr)
9586 (js2-node-len pn) (- (js2-node-end body) pos)
9587 (js2-let-node-body pn) body))
9588 (setf (js2-let-node-vars pn) vars)
9589 (js2-node-add-children pn vars body))
9590 (js2-pop-scope))
9591 pn))
9592
9593 (defun js2-define-new-symbol (decl-type name node &optional scope)
9594 (js2-scope-put-symbol (or scope js2-current-scope)
9595 name
9596 (make-js2-symbol decl-type name node)))
9597
9598 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9599 "Define a symbol in the current scope.
9600 If NODE is non-nil, it is the AST node associated with the symbol."
9601 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9602 (symbol (if defining-scope
9603 (js2-scope-get-symbol defining-scope name)))
9604 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9605 (pos (if node (js2-node-abs-pos node)))
9606 (len (if node (js2-node-len node))))
9607 (cond
9608 ((and symbol ; already defined
9609 (or (if js2-in-use-strict-directive
9610 ;; two const-bound vars in this block have same name
9611 (and (= sdt js2-CONST)
9612 (eq defining-scope js2-current-scope))
9613 (or (= sdt js2-CONST) ; old version is const
9614 (= decl-type js2-CONST))) ; new version is const
9615 ;; two let-bound vars in this block have same name
9616 (and (= sdt js2-LET)
9617 (eq defining-scope js2-current-scope))))
9618 (js2-report-error
9619 (cond
9620 ((= sdt js2-CONST) "msg.const.redecl")
9621 ((= sdt js2-LET) "msg.let.redecl")
9622 ((= sdt js2-VAR) "msg.var.redecl")
9623 ((= sdt js2-FUNCTION) "msg.function.redecl")
9624 (t "msg.parm.redecl"))
9625 name pos len))
9626 ((or (= decl-type js2-LET)
9627 ;; strict mode const is scoped to the current LexicalEnvironment
9628 (and js2-in-use-strict-directive
9629 (= decl-type js2-CONST)))
9630 (if (and (= decl-type js2-LET)
9631 (not ignore-not-in-block)
9632 (or (= (js2-node-type js2-current-scope) js2-IF)
9633 (js2-loop-node-p js2-current-scope)))
9634 (js2-report-error "msg.let.decl.not.in.block")
9635 (js2-define-new-symbol decl-type name node)))
9636 ((or (= decl-type js2-VAR)
9637 (= decl-type js2-FUNCTION)
9638 ;; sloppy mode const is scoped to the current VariableEnvironment
9639 (and (not js2-in-use-strict-directive)
9640 (= decl-type js2-CONST)))
9641 (if symbol
9642 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9643 (js2-add-strict-warning "msg.var.redecl" name)
9644 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9645 (js2-add-strict-warning "msg.var.hides.arg" name)))
9646 (js2-define-new-symbol decl-type name node
9647 js2-current-script-or-fn)))
9648 ((= decl-type js2-LP)
9649 (if symbol
9650 ;; must be duplicate parameter. Second parameter hides the
9651 ;; first, so go ahead and add the second pararameter
9652 (js2-report-warning "msg.dup.parms" name))
9653 (js2-define-new-symbol decl-type name node))
9654 (t (js2-code-bug)))))
9655
9656 (defun js2-parse-paren-expr-or-generator-comp ()
9657 (let ((px-pos (js2-current-token-beg)))
9658 (cond
9659 ((and (>= js2-language-version 200)
9660 (js2-match-token js2-FOR))
9661 (js2-parse-generator-comp px-pos))
9662 ((and (>= js2-language-version 200)
9663 (js2-match-token js2-RP))
9664 ;; Not valid expression syntax, but this is valid in an arrow
9665 ;; function with no params: () => body.
9666 (if (eq (js2-peek-token) js2-ARROW)
9667 ;; Return whatever, it will hopefully be rewinded and
9668 ;; reparsed when we reach the =>.
9669 (make-js2-keyword-node :type js2-NULL)
9670 (js2-report-error "msg.syntax")
9671 (make-js2-error-node)))
9672 (t
9673 (let* ((js2-in-for-init nil)
9674 (expr (js2-parse-expr))
9675 (pn (make-js2-paren-node :pos px-pos
9676 :expr expr)))
9677 (js2-node-add-children pn (js2-paren-node-expr pn))
9678 (js2-must-match js2-RP "msg.no.paren")
9679 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9680 pn)))))
9681
9682 (defun js2-parse-expr (&optional oneshot)
9683 (let* ((pn (js2-parse-assign-expr))
9684 (pos (js2-node-pos pn))
9685 left
9686 right
9687 op-pos)
9688 (while (and (not oneshot)
9689 (js2-match-token js2-COMMA))
9690 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9691 (if (= (js2-peek-token) js2-YIELD)
9692 (js2-report-error "msg.yield.parenthesized"))
9693 (setq right (js2-parse-assign-expr)
9694 left pn
9695 pn (make-js2-infix-node :type js2-COMMA
9696 :pos pos
9697 :len (- js2-ts-cursor pos)
9698 :op-pos op-pos
9699 :left left
9700 :right right))
9701 (js2-node-add-children pn left right))
9702 pn))
9703
9704 (defun js2-parse-assign-expr ()
9705 (let ((tt (js2-get-token))
9706 (pos (js2-current-token-beg))
9707 pn left right op-pos
9708 ts-state recorded-identifiers parsed-errors
9709 async-p)
9710 (if (= tt js2-YIELD)
9711 (js2-parse-return-or-yield tt t)
9712 ;; TODO(mooz): Bit confusing.
9713 ;; If we meet `async` token and it's not part of `async
9714 ;; function`, then this `async` is for a succeeding async arrow
9715 ;; function.
9716 ;; Since arrow function parsing doesn't rely on neither
9717 ;; `js2-parse-function-stmt' nor `js2-parse-function-expr' that
9718 ;; interpret `async` token, we trash `async` and just remember
9719 ;; we met `async` keyword to `async-p'.
9720 (when (js2-match-async-arrow-function)
9721 (setq async-p t))
9722 ;; Save the tokenizer state in case we find an arrow function
9723 ;; and have to rewind.
9724 (setq ts-state (make-js2-ts-state)
9725 recorded-identifiers js2-recorded-identifiers
9726 parsed-errors js2-parsed-errors)
9727 ;; not yield - parse assignment expression
9728 (setq pn (js2-parse-cond-expr)
9729 tt (js2-get-token))
9730 (cond
9731 ((and (<= js2-first-assign tt)
9732 (<= tt js2-last-assign))
9733 ;; tt express assignment (=, |=, ^=, ..., %=)
9734 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9735 left pn)
9736 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9737 ;; care about assignment to strict variable names.
9738 (when (js2-name-node-p left)
9739 (js2-check-strict-identifier left))
9740 (setq right (js2-parse-assign-expr)
9741 pn (make-js2-assign-node :type tt
9742 :pos pos
9743 :len (- (js2-node-end right) pos)
9744 :op-pos op-pos
9745 :left left
9746 :right right))
9747 (when js2-parse-ide-mode
9748 (js2-highlight-assign-targets pn left right)
9749 (js2-record-imenu-functions right left))
9750 ;; do this last so ide checks above can use absolute positions
9751 (js2-node-add-children pn left right))
9752 ((and (= tt js2-ARROW)
9753 (>= js2-language-version 200))
9754 (js2-ts-seek ts-state)
9755 (when async-p
9756 (js2-record-face 'font-lock-keyword-face)
9757 (js2-get-token))
9758 (setq js2-recorded-identifiers recorded-identifiers
9759 js2-parsed-errors parsed-errors)
9760 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil async-p)))
9761 (t
9762 (js2-unget-token)))
9763 pn)))
9764
9765 (defun js2-parse-cond-expr ()
9766 (let ((pos (js2-current-token-beg))
9767 (pn (js2-parse-or-expr))
9768 test-expr
9769 if-true
9770 if-false
9771 q-pos
9772 c-pos)
9773 (when (js2-match-token js2-HOOK)
9774 (setq q-pos (- (js2-current-token-beg) pos)
9775 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9776 (js2-must-match js2-COLON "msg.no.colon.cond")
9777 (setq c-pos (- (js2-current-token-beg) pos)
9778 if-false (js2-parse-assign-expr)
9779 test-expr pn
9780 pn (make-js2-cond-node :pos pos
9781 :len (- (js2-node-end if-false) pos)
9782 :test-expr test-expr
9783 :true-expr if-true
9784 :false-expr if-false
9785 :q-pos q-pos
9786 :c-pos c-pos))
9787 (js2-node-add-children pn test-expr if-true if-false))
9788 pn))
9789
9790 (defun js2-make-binary (type left parser &optional no-get)
9791 "Helper for constructing a binary-operator AST node.
9792 LEFT is the left-side-expression, already parsed, and the
9793 binary operator should have just been matched.
9794 PARSER is a function to call to parse the right operand,
9795 or a `js2-node' struct if it has already been parsed.
9796 FIXME: The latter option is unused?"
9797 (let* ((pos (js2-node-pos left))
9798 (op-pos (- (js2-current-token-beg) pos))
9799 (right (if (js2-node-p parser)
9800 parser
9801 (unless no-get (js2-get-token))
9802 (funcall parser)))
9803 (pn (make-js2-infix-node :type type
9804 :pos pos
9805 :len (- (js2-node-end right) pos)
9806 :op-pos op-pos
9807 :left left
9808 :right right)))
9809 (js2-node-add-children pn left right)
9810 pn))
9811
9812 (defun js2-parse-or-expr ()
9813 (let ((pn (js2-parse-and-expr)))
9814 (when (js2-match-token js2-OR)
9815 (setq pn (js2-make-binary js2-OR
9816 pn
9817 'js2-parse-or-expr)))
9818 pn))
9819
9820 (defun js2-parse-and-expr ()
9821 (let ((pn (js2-parse-bit-or-expr)))
9822 (when (js2-match-token js2-AND)
9823 (setq pn (js2-make-binary js2-AND
9824 pn
9825 'js2-parse-and-expr)))
9826 pn))
9827
9828 (defun js2-parse-bit-or-expr ()
9829 (let ((pn (js2-parse-bit-xor-expr)))
9830 (while (js2-match-token js2-BITOR)
9831 (setq pn (js2-make-binary js2-BITOR
9832 pn
9833 'js2-parse-bit-xor-expr)))
9834 pn))
9835
9836 (defun js2-parse-bit-xor-expr ()
9837 (let ((pn (js2-parse-bit-and-expr)))
9838 (while (js2-match-token js2-BITXOR)
9839 (setq pn (js2-make-binary js2-BITXOR
9840 pn
9841 'js2-parse-bit-and-expr)))
9842 pn))
9843
9844 (defun js2-parse-bit-and-expr ()
9845 (let ((pn (js2-parse-eq-expr)))
9846 (while (js2-match-token js2-BITAND)
9847 (setq pn (js2-make-binary js2-BITAND
9848 pn
9849 'js2-parse-eq-expr)))
9850 pn))
9851
9852 (defconst js2-parse-eq-ops
9853 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9854
9855 (defun js2-parse-eq-expr ()
9856 (let ((pn (js2-parse-rel-expr))
9857 tt)
9858 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9859 (setq pn (js2-make-binary tt
9860 pn
9861 'js2-parse-rel-expr)))
9862 (js2-unget-token)
9863 pn))
9864
9865 (defconst js2-parse-rel-ops
9866 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9867
9868 (defun js2-parse-rel-expr ()
9869 (let ((pn (js2-parse-shift-expr))
9870 (continue t)
9871 tt)
9872 (while continue
9873 (setq tt (js2-get-token))
9874 (cond
9875 ((and js2-in-for-init (= tt js2-IN))
9876 (js2-unget-token)
9877 (setq continue nil))
9878 ((memq tt js2-parse-rel-ops)
9879 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9880 (t
9881 (js2-unget-token)
9882 (setq continue nil))))
9883 pn))
9884
9885 (defconst js2-parse-shift-ops
9886 (list js2-LSH js2-URSH js2-RSH))
9887
9888 (defun js2-parse-shift-expr ()
9889 (let ((pn (js2-parse-add-expr))
9890 tt
9891 (continue t))
9892 (while continue
9893 (setq tt (js2-get-token))
9894 (if (memq tt js2-parse-shift-ops)
9895 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9896 (js2-unget-token)
9897 (setq continue nil)))
9898 pn))
9899
9900 (defun js2-parse-add-expr ()
9901 (let ((pn (js2-parse-mul-expr))
9902 tt
9903 (continue t))
9904 (while continue
9905 (setq tt (js2-get-token))
9906 (if (or (= tt js2-ADD) (= tt js2-SUB))
9907 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9908 (js2-unget-token)
9909 (setq continue nil)))
9910 pn))
9911
9912 (defconst js2-parse-mul-ops
9913 (list js2-MUL js2-DIV js2-MOD))
9914
9915 (defun js2-parse-mul-expr ()
9916 (let ((pn (js2-parse-unary-expr))
9917 tt
9918 (continue t))
9919 (while continue
9920 (setq tt (js2-get-token))
9921 (if (memq tt js2-parse-mul-ops)
9922 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9923 (js2-unget-token)
9924 (setq continue nil)))
9925 pn))
9926
9927 (defun js2-make-unary (type parser &rest args)
9928 "Make a unary node of type TYPE.
9929 PARSER is either a node (for postfix operators) or a function to call
9930 to parse the operand (for prefix operators)."
9931 (let* ((pos (js2-current-token-beg))
9932 (postfix (js2-node-p parser))
9933 (expr (if postfix
9934 parser
9935 (apply parser args)))
9936 end
9937 pn)
9938 (if postfix ; e.g. i++
9939 (setq pos (js2-node-pos expr)
9940 end (js2-current-token-end))
9941 (setq end (js2-node-end expr)))
9942 (setq pn (make-js2-unary-node :type type
9943 :pos pos
9944 :len (- end pos)
9945 :operand expr))
9946 (js2-node-add-children pn expr)
9947 pn))
9948
9949 (defconst js2-incrementable-node-types
9950 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9951 "Node types that can be the operand of a ++ or -- operator.")
9952
9953 (defun js2-check-bad-inc-dec (tt beg end unary)
9954 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9955 js2-incrementable-node-types)
9956 (js2-report-error (if (= tt js2-INC)
9957 "msg.bad.incr"
9958 "msg.bad.decr")
9959 nil beg (- end beg))))
9960
9961 (defun js2-parse-unary-expr ()
9962 (let ((tt (js2-current-token-type))
9963 pn expr beg end)
9964 (cond
9965 ((or (= tt js2-VOID)
9966 (= tt js2-NOT)
9967 (= tt js2-BITNOT)
9968 (= tt js2-TYPEOF))
9969 (js2-get-token)
9970 (js2-make-unary tt 'js2-parse-unary-expr))
9971 ((= tt js2-ADD)
9972 (js2-get-token)
9973 ;; Convert to special POS token in decompiler and parse tree
9974 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9975 ((= tt js2-SUB)
9976 (js2-get-token)
9977 ;; Convert to special NEG token in decompiler and parse tree
9978 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9979 ((or (= tt js2-INC)
9980 (= tt js2-DEC))
9981 (js2-get-token)
9982 (prog1
9983 (setq beg (js2-current-token-beg)
9984 end (js2-current-token-end)
9985 expr (js2-make-unary tt 'js2-parse-member-expr t))
9986 (js2-check-bad-inc-dec tt beg end expr)))
9987 ((= tt js2-DELPROP)
9988 (js2-get-token)
9989 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9990 ((js2-parse-await-maybe tt))
9991 ((= tt js2-ERROR)
9992 (js2-get-token)
9993 (make-js2-error-node)) ; try to continue
9994 ((and (= tt js2-LT)
9995 js2-compiler-xml-available)
9996 ;; XML stream encountered in expression.
9997 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9998 (t
9999 (setq pn (js2-parse-member-expr t)
10000 ;; Don't look across a newline boundary for a postfix incop.
10001 tt (js2-peek-token-or-eol))
10002 (when (or (= tt js2-INC) (= tt js2-DEC))
10003 (js2-get-token)
10004 (setf expr pn
10005 pn (js2-make-unary tt expr))
10006 (js2-node-set-prop pn 'postfix t)
10007 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
10008 pn))))
10009
10010 (defun js2-parse-xml-initializer ()
10011 "Parse an E4X XML initializer.
10012 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
10013 Then I'll postprocess the result, depending on whether we're in IDE
10014 mode or codegen mode, and generate the appropriate rewritten AST.
10015 IDE mode uses a rich AST that models the XML structure. Codegen mode
10016 just concatenates everything and makes a new XML or XMLList out of it."
10017 (let ((tt (js2-get-first-xml-token))
10018 pn-xml pn expr kids expr-pos
10019 (continue t)
10020 (first-token t))
10021 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
10022 (js2-report-error "msg.syntax"))
10023 (setq pn-xml (make-js2-xml-node))
10024 (while continue
10025 (if first-token
10026 (setq first-token nil)
10027 (setq tt (js2-get-next-xml-token)))
10028 (cond
10029 ;; js2-XML means we found a {expr} in the XML stream.
10030 ;; The token string is the XML up to the left-curly.
10031 ((= tt js2-XML)
10032 (push (make-js2-string-node :pos (js2-current-token-beg)
10033 :len (- js2-ts-cursor (js2-current-token-beg)))
10034 kids)
10035 (js2-must-match js2-LC "msg.syntax")
10036 (setq expr-pos js2-ts-cursor
10037 expr (if (eq (js2-peek-token) js2-RC)
10038 (make-js2-empty-expr-node :pos expr-pos)
10039 (js2-parse-expr)))
10040 (js2-must-match js2-RC "msg.syntax")
10041 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
10042 :len (js2-node-len expr)
10043 :expr expr))
10044 (js2-node-add-children pn expr)
10045 (push pn kids))
10046 ;; a js2-XMLEND token means we hit the final close-tag.
10047 ((= tt js2-XMLEND)
10048 (push (make-js2-string-node :pos (js2-current-token-beg)
10049 :len (- js2-ts-cursor (js2-current-token-beg)))
10050 kids)
10051 (dolist (kid (nreverse kids))
10052 (js2-block-node-push pn-xml kid))
10053 (setf (js2-node-len pn-xml) (- js2-ts-cursor
10054 (js2-node-pos pn-xml))
10055 continue nil))
10056 (t
10057 (js2-report-error "msg.syntax")
10058 (setq continue nil))))
10059 pn-xml))
10060
10061
10062 (defun js2-parse-argument-list ()
10063 "Parse an argument list and return it as a Lisp list of nodes.
10064 Returns the list in reverse order. Consumes the right-paren token."
10065 (let (result)
10066 (unless (js2-match-token js2-RP)
10067 (cl-loop do
10068 (let ((tt (js2-get-token)))
10069 (if (= tt js2-YIELD)
10070 (js2-report-error "msg.yield.parenthesized"))
10071 (if (and (= tt js2-TRIPLEDOT)
10072 (>= js2-language-version 200))
10073 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
10074 (js2-unget-token)
10075 (push (js2-parse-assign-expr) result)))
10076 while
10077 (js2-match-token js2-COMMA))
10078 (js2-must-match js2-RP "msg.no.paren.arg")
10079 result)))
10080
10081 (defun js2-parse-member-expr (&optional allow-call-syntax)
10082 (let ((tt (js2-current-token-type))
10083 pn pos target args beg end init)
10084 (if (/= tt js2-NEW)
10085 (setq pn (js2-parse-primary-expr))
10086 ;; parse a 'new' expression
10087 (js2-get-token)
10088 (setq pos (js2-current-token-beg)
10089 beg pos
10090 target (js2-parse-member-expr)
10091 end (js2-node-end target)
10092 pn (make-js2-new-node :pos pos
10093 :target target
10094 :len (- end pos)))
10095 (js2-highlight-function-call (js2-current-token))
10096 (js2-node-add-children pn target)
10097 (when (js2-match-token js2-LP)
10098 ;; Add the arguments to pn, if any are supplied.
10099 (setf beg pos ; start of "new" keyword
10100 pos (js2-current-token-beg)
10101 args (nreverse (js2-parse-argument-list))
10102 (js2-new-node-args pn) args
10103 end (js2-current-token-end)
10104 (js2-new-node-lp pn) (- pos beg)
10105 (js2-new-node-rp pn) (- end 1 beg))
10106 (apply #'js2-node-add-children pn args))
10107 (when (and js2-allow-rhino-new-expr-initializer
10108 (js2-match-token js2-LC))
10109 (setf init (js2-parse-object-literal)
10110 end (js2-node-end init)
10111 (js2-new-node-initializer pn) init)
10112 (js2-node-add-children pn init))
10113 (setf (js2-node-len pn) (- end beg))) ; end outer if
10114 (js2-parse-member-expr-tail allow-call-syntax pn)))
10115
10116 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10117 "Parse a chain of property/array accesses or function calls.
10118 Includes parsing for E4X operators like `..' and `.@'.
10119 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10120 Returns an expression tree that includes PN, the parent node."
10121 (let (tt
10122 (continue t))
10123 (while continue
10124 (setq tt (js2-get-token))
10125 (cond
10126 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10127 (setq pn (js2-parse-property-access tt pn)))
10128 ((= tt js2-DOTQUERY)
10129 (setq pn (js2-parse-dot-query pn)))
10130 ((= tt js2-LB)
10131 (setq pn (js2-parse-element-get pn)))
10132 ((= tt js2-LP)
10133 (js2-unget-token)
10134 (if allow-call-syntax
10135 (setq pn (js2-parse-function-call pn))
10136 (setq continue nil)))
10137 ((= tt js2-TEMPLATE_HEAD)
10138 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10139 ((= tt js2-NO_SUBS_TEMPLATE)
10140 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10141 (t
10142 (js2-unget-token)
10143 (setq continue nil)))
10144 (if (>= js2-highlight-level 2)
10145 (js2-parse-highlight-member-expr-node pn)))
10146 pn))
10147
10148 (defun js2-parse-tagged-template (tag-node tpl-node)
10149 "Parse tagged template expression."
10150 (let* ((beg (js2-node-pos tag-node))
10151 (pn (make-js2-tagged-template-node :beg beg
10152 :len (- (js2-current-token-end) beg)
10153 :tag tag-node
10154 :template tpl-node)))
10155 (js2-node-add-children pn tag-node tpl-node)
10156 pn))
10157
10158 (defun js2-parse-dot-query (pn)
10159 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10160 Last token parsed must be `js2-DOTQUERY'."
10161 (let ((pos (js2-node-pos pn))
10162 op-pos expr end)
10163 (js2-must-have-xml)
10164 (js2-set-requires-activation)
10165 (setq op-pos (js2-current-token-beg)
10166 expr (js2-parse-expr)
10167 end (js2-node-end expr)
10168 pn (make-js2-xml-dot-query-node :left pn
10169 :pos pos
10170 :op-pos op-pos
10171 :right expr))
10172 (js2-node-add-children pn
10173 (js2-xml-dot-query-node-left pn)
10174 (js2-xml-dot-query-node-right pn))
10175 (if (js2-must-match js2-RP "msg.no.paren")
10176 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10177 end (js2-current-token-end)))
10178 (setf (js2-node-len pn) (- end pos))
10179 pn))
10180
10181 (defun js2-parse-element-get (pn)
10182 "Parse an element-get expression, e.g. foo[bar].
10183 Last token parsed must be `js2-RB'."
10184 (let ((lb (js2-current-token-beg))
10185 (pos (js2-node-pos pn))
10186 rb expr)
10187 (setq expr (js2-parse-expr))
10188 (if (js2-must-match js2-RB "msg.no.bracket.index")
10189 (setq rb (js2-current-token-beg)))
10190 (setq pn (make-js2-elem-get-node :target pn
10191 :pos pos
10192 :element expr
10193 :lb (js2-relpos lb pos)
10194 :rb (js2-relpos rb pos)
10195 :len (- (js2-current-token-end) pos)))
10196 (js2-node-add-children pn
10197 (js2-elem-get-node-target pn)
10198 (js2-elem-get-node-element pn))
10199 pn))
10200
10201 (defun js2-highlight-function-call (token)
10202 (when (eq (js2-token-type token) js2-NAME)
10203 (js2-record-face 'js2-function-call token)))
10204
10205 (defun js2-parse-function-call (pn)
10206 (js2-highlight-function-call (js2-current-token))
10207 (js2-get-token)
10208 (let (args
10209 (pos (js2-node-pos pn)))
10210 (setq pn (make-js2-call-node :pos pos
10211 :target pn
10212 :lp (- (js2-current-token-beg) pos)))
10213 (js2-node-add-children pn (js2-call-node-target pn))
10214 ;; Add the arguments to pn, if any are supplied.
10215 (setf args (nreverse (js2-parse-argument-list))
10216 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10217 (js2-call-node-args pn) args)
10218 (apply #'js2-node-add-children pn args)
10219 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10220 pn))
10221
10222 (defun js2-parse-property-access (tt pn)
10223 "Parse a property access, XML descendants access, or XML attr access."
10224 (let ((member-type-flags 0)
10225 (dot-pos (js2-current-token-beg))
10226 (dot-len (if (= tt js2-DOTDOT) 2 1))
10227 name
10228 ref ; right side of . or .. operator
10229 result)
10230 (when (= tt js2-DOTDOT)
10231 (js2-must-have-xml)
10232 (setq member-type-flags js2-descendants-flag))
10233 (if (not js2-compiler-xml-available)
10234 (progn
10235 (js2-must-match-prop-name "msg.no.name.after.dot")
10236 (setq name (js2-create-name-node t js2-GETPROP)
10237 result (make-js2-prop-get-node :left pn
10238 :pos (js2-current-token-beg)
10239 :right name
10240 :len (js2-current-token-len)))
10241 (js2-node-add-children result pn name)
10242 result)
10243 ;; otherwise look for XML operators
10244 (setf result (if (= tt js2-DOT)
10245 (make-js2-prop-get-node)
10246 (make-js2-infix-node :type js2-DOTDOT))
10247 (js2-node-pos result) (js2-node-pos pn)
10248 (js2-infix-node-op-pos result) dot-pos
10249 (js2-infix-node-left result) pn ; do this after setting position
10250 tt (js2-get-prop-name-token))
10251 (cond
10252 ;; handles: name, ns::name, ns::*, ns::[expr]
10253 ((= tt js2-NAME)
10254 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10255 ;; handles: *, *::name, *::*, *::[expr]
10256 ((= tt js2-MUL)
10257 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10258 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10259 ((= tt js2-XMLATTR)
10260 (setq result (js2-parse-attribute-access)))
10261 (t
10262 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10263 (if ref
10264 (setf (js2-node-len result) (- (js2-node-end ref)
10265 (js2-node-pos result))
10266 (js2-infix-node-right result) ref))
10267 (if (js2-infix-node-p result)
10268 (js2-node-add-children result
10269 (js2-infix-node-left result)
10270 (js2-infix-node-right result)))
10271 result)))
10272
10273 (defun js2-parse-attribute-access ()
10274 "Parse an E4X XML attribute expression.
10275 This includes expressions of the forms:
10276
10277 @attr @ns::attr @ns::*
10278 @* @*::attr @*::*
10279 @[expr] @*::[expr] @ns::[expr]
10280
10281 Called if we peeked an '@' token."
10282 (let ((tt (js2-get-prop-name-token))
10283 (at-pos (js2-current-token-beg)))
10284 (cond
10285 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10286 ((= tt js2-NAME)
10287 (js2-parse-property-name at-pos nil 0))
10288 ;; handles: @*, @*::name, @*::*, @*::[expr]
10289 ((= tt js2-MUL)
10290 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10291 ;; handles @[expr]
10292 ((= tt js2-LB)
10293 (js2-parse-xml-elem-ref at-pos))
10294 (t
10295 (js2-report-error "msg.no.name.after.xmlAttr")
10296 ;; Avoid cascaded errors that happen if we make an error node here.
10297 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10298
10299 (defun js2-parse-property-name (at-pos s member-type-flags)
10300 "Check if :: follows name in which case it becomes qualified name.
10301
10302 AT-POS is a natural number if we just read an '@' token, else nil.
10303 S is the name or string that was matched: an identifier, 'throw' or '*'.
10304 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10305
10306 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10307 operator, or the name is followed by ::. For a plain name, returns a
10308 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10309 (let ((pos (or at-pos (js2-current-token-beg)))
10310 colon-pos
10311 (name (js2-create-name-node t (js2-current-token-type) s))
10312 ns tt pn)
10313 (catch 'return
10314 (when (js2-match-token js2-COLONCOLON)
10315 (setq ns name
10316 colon-pos (js2-current-token-beg)
10317 tt (js2-get-prop-name-token))
10318 (cond
10319 ;; handles name::name
10320 ((= tt js2-NAME)
10321 (setq name (js2-create-name-node)))
10322 ;; handles name::*
10323 ((= tt js2-MUL)
10324 (setq name (js2-create-name-node nil nil "*")))
10325 ;; handles name::[expr]
10326 ((= tt js2-LB)
10327 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10328 (t
10329 (js2-report-error "msg.no.name.after.coloncolon"))))
10330 (if (and (null ns) (zerop member-type-flags))
10331 name
10332 (prog1
10333 (setq pn
10334 (make-js2-xml-prop-ref-node :pos pos
10335 :len (- (js2-node-end name) pos)
10336 :at-pos at-pos
10337 :colon-pos colon-pos
10338 :propname name))
10339 (js2-node-add-children pn name))))))
10340
10341 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10342 "Parse the [expr] portion of an xml element reference.
10343 For instance, @[expr], @*::[expr], or ns::[expr]."
10344 (let* ((lb (js2-current-token-beg))
10345 (pos (or at-pos lb))
10346 rb
10347 (expr (js2-parse-expr))
10348 (end (js2-node-end expr))
10349 pn)
10350 (if (js2-must-match js2-RB "msg.no.bracket.index")
10351 (setq rb (js2-current-token-beg)
10352 end (js2-current-token-end)))
10353 (prog1
10354 (setq pn
10355 (make-js2-xml-elem-ref-node :pos pos
10356 :len (- end pos)
10357 :namespace namespace
10358 :colon-pos colon-pos
10359 :at-pos at-pos
10360 :expr expr
10361 :lb (js2-relpos lb pos)
10362 :rb (js2-relpos rb pos)))
10363 (js2-node-add-children pn namespace expr))))
10364
10365 (defun js2-parse-destruct-primary-expr ()
10366 (let ((js2-is-in-destructuring t))
10367 (js2-parse-primary-expr)))
10368
10369 (defun js2-parse-primary-expr ()
10370 "Parse a literal (leaf) expression of some sort.
10371 Includes complex literals such as functions, object-literals,
10372 array-literals, array comprehensions and regular expressions."
10373 (let (tt node)
10374 (setq tt (js2-current-token-type))
10375 (cond
10376 ((= tt js2-CLASS)
10377 (js2-parse-class-expr))
10378 ((= tt js2-FUNCTION)
10379 (js2-parse-function-expr))
10380 ((js2-match-async-function)
10381 (js2-parse-function-expr t))
10382 ((= tt js2-LB)
10383 (js2-parse-array-comp-or-literal))
10384 ((= tt js2-LC)
10385 (js2-parse-object-literal))
10386 ((= tt js2-LET)
10387 (js2-parse-let (js2-current-token-beg)))
10388 ((= tt js2-LP)
10389 (js2-parse-paren-expr-or-generator-comp))
10390 ((= tt js2-XMLATTR)
10391 (js2-must-have-xml)
10392 (js2-parse-attribute-access))
10393 ((= tt js2-NAME)
10394 (js2-parse-name tt))
10395 ((= tt js2-NUMBER)
10396 (setq node (make-js2-number-node))
10397 (when (and js2-in-use-strict-directive
10398 (= (js2-number-node-num-base node) 8)
10399 (js2-number-node-legacy-octal-p node))
10400 (js2-report-error "msg.no.octal.strict"))
10401 node)
10402 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10403 (make-js2-string-node :type tt))
10404 ((= tt js2-TEMPLATE_HEAD)
10405 (js2-parse-template-literal))
10406 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10407 ;; Got / or /= which in this context means a regexp literal
10408 (let ((px-pos (js2-current-token-beg))
10409 (flags (js2-read-regexp tt))
10410 (end (js2-current-token-end)))
10411 (prog1
10412 (make-js2-regexp-node :pos px-pos
10413 :len (- end px-pos)
10414 :value (js2-current-token-string)
10415 :flags flags)
10416 (js2-set-face px-pos end 'font-lock-string-face 'record)
10417 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10418 ((or (= tt js2-NULL)
10419 (= tt js2-THIS)
10420 (= tt js2-SUPER)
10421 (= tt js2-FALSE)
10422 (= tt js2-TRUE))
10423 (make-js2-keyword-node :type tt))
10424 ((= tt js2-TRIPLEDOT)
10425 ;; Likewise, only valid in an arrow function with a rest param.
10426 (if (and (js2-match-token js2-NAME)
10427 (js2-match-token js2-RP)
10428 (eq (js2-peek-token) js2-ARROW))
10429 (progn
10430 (js2-unget-token) ; Put back the right paren.
10431 ;; See the previous case.
10432 (make-js2-keyword-node :type js2-NULL))
10433 (js2-report-error "msg.syntax")
10434 (make-js2-error-node)))
10435 ((= tt js2-RESERVED)
10436 (js2-report-error "msg.reserved.id")
10437 (make-js2-name-node))
10438 ((= tt js2-ERROR)
10439 ;; the scanner or one of its subroutines reported the error.
10440 (make-js2-error-node))
10441 ((= tt js2-EOF)
10442 (let* ((px-pos (point-at-bol))
10443 (len (- js2-ts-cursor px-pos)))
10444 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10445 (make-js2-error-node :pos (1- js2-ts-cursor)))
10446 (t
10447 (js2-report-error "msg.syntax")
10448 (make-js2-error-node)))))
10449
10450 (defun js2-parse-template-literal ()
10451 (let ((beg (js2-current-token-beg))
10452 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10453 (tt js2-TEMPLATE_HEAD))
10454 (while (eq tt js2-TEMPLATE_HEAD)
10455 (push (js2-parse-expr) kids)
10456 (js2-must-match js2-RC "msg.syntax")
10457 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10458 (push (make-js2-string-node :type tt) kids))
10459 (setq kids (nreverse kids))
10460 (let ((tpl (make-js2-template-node :beg beg
10461 :len (- (js2-current-token-end) beg)
10462 :kids kids)))
10463 (apply #'js2-node-add-children tpl kids)
10464 tpl)))
10465
10466 (defun js2-parse-name (_tt)
10467 (let ((name (js2-current-token-string))
10468 node)
10469 (setq node (if js2-compiler-xml-available
10470 (js2-parse-property-name nil name 0)
10471 (js2-create-name-node 'check-activation nil name)))
10472 (if js2-highlight-external-variables
10473 (js2-record-name-node node))
10474 node))
10475
10476 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10477 (js2-add-strict-warning
10478 msg nil
10479 ;; back up from comma to beginning of line or array/objlit
10480 (max (if elems
10481 (js2-node-pos (car elems))
10482 pos)
10483 (save-excursion
10484 (goto-char comma-pos)
10485 (back-to-indentation)
10486 (point)))
10487 comma-pos))
10488
10489 (defun js2-parse-array-comp-or-literal ()
10490 (let ((pos (js2-current-token-beg)))
10491 (if (and (>= js2-language-version 200)
10492 (js2-match-token js2-FOR))
10493 (js2-parse-array-comp pos)
10494 (js2-parse-array-literal pos))))
10495
10496 (defun js2-parse-array-literal (pos)
10497 (let ((after-lb-or-comma t)
10498 after-comma tt elems pn was-rest
10499 (continue t))
10500 (unless js2-is-in-destructuring
10501 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10502 (while continue
10503 (setq tt (js2-get-token))
10504 (cond
10505 ;; end of array
10506 ((or (= tt js2-RB)
10507 (= tt js2-EOF)) ; prevent infinite loop
10508 (if (= tt js2-EOF)
10509 (js2-report-error "msg.no.bracket.arg" nil pos))
10510 (when (and after-comma (< js2-language-version 170))
10511 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10512 pos (remove nil elems) after-comma))
10513 (setq continue nil
10514 pn (make-js2-array-node :pos pos
10515 :len (- js2-ts-cursor pos)
10516 :elems (nreverse elems)))
10517 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10518 ;; anything after rest element (...foo)
10519 (was-rest
10520 (js2-report-error "msg.param.after.rest"))
10521 ;; comma
10522 ((= tt js2-COMMA)
10523 (setq after-comma (js2-current-token-end))
10524 (if (not after-lb-or-comma)
10525 (setq after-lb-or-comma t)
10526 (push nil elems)))
10527 ;; array comp
10528 ((and (>= js2-language-version 170)
10529 (not js2-is-in-destructuring)
10530 (= tt js2-FOR) ; check for array comprehension
10531 (not after-lb-or-comma) ; "for" can't follow a comma
10532 elems ; must have at least 1 element
10533 (not (cdr elems))) ; but no 2nd element
10534 (js2-unget-token)
10535 (setf continue nil
10536 pn (js2-parse-legacy-array-comp (car elems) pos)))
10537 ;; another element
10538 (t
10539 (unless after-lb-or-comma
10540 (js2-report-error "msg.no.bracket.arg"))
10541 (if (and (= tt js2-TRIPLEDOT)
10542 (>= js2-language-version 200))
10543 ;; rest/spread operator
10544 (progn
10545 (push (js2-make-unary tt 'js2-parse-assign-expr)
10546 elems)
10547 (if js2-is-in-destructuring
10548 (setq was-rest t)))
10549 (js2-unget-token)
10550 (push (js2-parse-assign-expr) elems))
10551 (setq after-lb-or-comma nil
10552 after-comma nil))))
10553 (unless js2-is-in-destructuring
10554 (js2-pop-scope))
10555 pn))
10556
10557 (defun js2-parse-legacy-array-comp (expr pos)
10558 "Parse a legacy array comprehension (JavaScript 1.7).
10559 EXPR is the first expression after the opening left-bracket.
10560 POS is the beginning of the LB token preceding EXPR.
10561 We should have just parsed the 'for' keyword before calling this function."
10562 (let ((current-scope js2-current-scope)
10563 loops first filter result)
10564 (unwind-protect
10565 (progn
10566 (while (js2-match-token js2-FOR)
10567 (let ((loop (make-js2-comp-loop-node)))
10568 (js2-push-scope loop)
10569 (push loop loops)
10570 (js2-parse-comp-loop loop)))
10571 ;; First loop takes expr scope's parent.
10572 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10573 (js2-scope-parent-scope current-scope))
10574 ;; Set expr scope's parent to the last loop.
10575 (setf (js2-scope-parent-scope current-scope) (car loops))
10576 (if (/= (js2-get-token) js2-IF)
10577 (js2-unget-token)
10578 (setq filter (js2-parse-condition))))
10579 (dotimes (_ (1- (length loops)))
10580 (js2-pop-scope)))
10581 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10582 (setq result (make-js2-comp-node :pos pos
10583 :len (- js2-ts-cursor pos)
10584 :result expr
10585 :loops (nreverse loops)
10586 :filters (and filter (list (car filter)))
10587 :form 'LEGACY_ARRAY))
10588 ;; Set comp loop's parent to the last loop.
10589 ;; TODO: Get rid of the bogus expr scope.
10590 (setf (js2-scope-parent-scope result) first)
10591 (apply #'js2-node-add-children result expr (car filter)
10592 (js2-comp-node-loops result))
10593 result))
10594
10595 (defun js2-parse-array-comp (pos)
10596 "Parse an ES6 array comprehension.
10597 POS is the beginning of the LB token.
10598 We should have just parsed the 'for' keyword before calling this function."
10599 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10600 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10601 pn))
10602
10603 (defun js2-parse-generator-comp (pos)
10604 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10605 (js2-current-script-or-fn
10606 (make-js2-function-node :generator-type 'COMPREHENSION))
10607 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10608 (js2-must-match js2-RP "msg.no.paren" pos)
10609 pn))
10610
10611 (defun js2-parse-comprehension (pos form)
10612 (let (loops filters expr result last)
10613 (unwind-protect
10614 (progn
10615 (js2-unget-token)
10616 (while (js2-match-token js2-FOR)
10617 (let ((loop (make-js2-comp-loop-node)))
10618 (js2-push-scope loop)
10619 (push loop loops)
10620 (js2-parse-comp-loop loop)))
10621 (while (js2-match-token js2-IF)
10622 (push (car (js2-parse-condition)) filters))
10623 (setq expr (js2-parse-assign-expr))
10624 (setq last (car loops)))
10625 (dolist (_ loops)
10626 (js2-pop-scope)))
10627 (setq result (make-js2-comp-node :pos pos
10628 :len (- js2-ts-cursor pos)
10629 :result expr
10630 :loops (nreverse loops)
10631 :filters (nreverse filters)
10632 :form form))
10633 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10634 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10635 (setf (js2-scope-parent-scope result) last)
10636 result))
10637
10638 (defun js2-parse-comp-loop (pn &optional only-of-p)
10639 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10640 The current token should be the initial FOR.
10641 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10642 (let ((pos (js2-comp-loop-node-pos pn))
10643 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10644 (when (and (not only-of-p) (js2-match-token js2-NAME))
10645 (if (string= (js2-current-token-string) "each")
10646 (progn
10647 (setq foreach-p t
10648 each-pos (- (js2-current-token-beg) pos)) ; relative
10649 (js2-record-face 'font-lock-keyword-face))
10650 (js2-report-error "msg.no.paren.for")))
10651 (if (js2-must-match js2-LP "msg.no.paren.for")
10652 (setq lp (- (js2-current-token-beg) pos)))
10653 (setq tt (js2-peek-token))
10654 (cond
10655 ((or (= tt js2-LB)
10656 (= tt js2-LC))
10657 (js2-get-token)
10658 (setq iter (js2-parse-destruct-primary-expr))
10659 (js2-define-destruct-symbols iter js2-LET
10660 'font-lock-variable-name-face t))
10661 ((js2-match-token js2-NAME)
10662 (setq iter (js2-create-name-node)))
10663 (t
10664 (js2-report-error "msg.bad.var")))
10665 ;; Define as a let since we want the scope of the variable to
10666 ;; be restricted to the array comprehension
10667 (if (js2-name-node-p iter)
10668 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10669 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10670 (and (>= js2-language-version 200)
10671 (js2-match-contextual-kwd "of")
10672 (setq forof-p t)))
10673 (setq in-pos (- (js2-current-token-beg) pos))
10674 (js2-report-error "msg.in.after.for.name"))
10675 (setq obj (js2-parse-expr))
10676 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10677 (setq rp (- (js2-current-token-beg) pos)))
10678 (setf (js2-node-pos pn) pos
10679 (js2-node-len pn) (- js2-ts-cursor pos)
10680 (js2-comp-loop-node-iterator pn) iter
10681 (js2-comp-loop-node-object pn) obj
10682 (js2-comp-loop-node-in-pos pn) in-pos
10683 (js2-comp-loop-node-each-pos pn) each-pos
10684 (js2-comp-loop-node-foreach-p pn) foreach-p
10685 (js2-comp-loop-node-forof-p pn) forof-p
10686 (js2-comp-loop-node-lp pn) lp
10687 (js2-comp-loop-node-rp pn) rp)
10688 (js2-node-add-children pn iter obj)
10689 pn))
10690
10691 (defun js2-parse-class-stmt ()
10692 (let ((pos (js2-current-token-beg))
10693 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10694 (name (js2-create-name-node t)))
10695 (js2-set-face (js2-node-pos name) (js2-node-end name)
10696 'font-lock-function-name-face 'record)
10697 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10698 (js2-record-imenu-functions node name)
10699 (js2-define-symbol js2-FUNCTION
10700 (js2-name-node-name name)
10701 node)
10702 node)))
10703
10704 (defun js2-parse-class-expr ()
10705 (let ((pos (js2-current-token-beg))
10706 name)
10707 (when (js2-match-token js2-NAME)
10708 (setq name (js2-create-name-node t)))
10709 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10710
10711 (defun js2-parse-class (pos form name)
10712 ;; class X [extends ...] {
10713 (let (pn elems extends)
10714 (if (js2-match-token js2-EXTENDS)
10715 (if (= (js2-peek-token) js2-LC)
10716 (js2-report-error "msg.missing.extends")
10717 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10718 (setq extends (js2-parse-assign-expr))
10719 (if (not extends)
10720 (js2-report-error "msg.bad.extends"))))
10721 (js2-must-match js2-LC "msg.no.brace.class")
10722 (setq elems (js2-parse-object-literal-elems t)
10723 pn (make-js2-class-node :pos pos
10724 :len (- js2-ts-cursor pos)
10725 :form form
10726 :name name
10727 :extends extends
10728 :elems elems))
10729 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10730 pn))
10731
10732 (defun js2-parse-object-literal ()
10733 (let* ((pos (js2-current-token-beg))
10734 (elems (js2-parse-object-literal-elems))
10735 (result (make-js2-object-node :pos pos
10736 :len (- js2-ts-cursor pos)
10737 :elems elems)))
10738 (apply #'js2-node-add-children result (js2-object-node-elems result))
10739 result))
10740
10741 (defun js2-property-key-string (property-node)
10742 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10743 `js2-method-node') as a string, or nil if it can't be
10744 represented as a string (e.g., the key is computed by an
10745 expression)."
10746 (cond
10747 ((js2-unary-node-p property-node) nil) ;; {...foo}
10748 (t
10749 (let ((key (js2-infix-node-left property-node)))
10750 (when (js2-computed-prop-name-node-p key)
10751 (setq key (js2-computed-prop-name-node-expr key)))
10752 (cond
10753 ((js2-name-node-p key)
10754 (js2-name-node-name key))
10755 ((js2-string-node-p key)
10756 (js2-string-node-value key))
10757 ((js2-number-node-p key)
10758 (js2-number-node-value key)))))))
10759
10760 (defun js2-parse-object-literal-elems (&optional class-p)
10761 (let ((pos (js2-current-token-beg))
10762 (static nil)
10763 (continue t)
10764 tt elems elem
10765 elem-key-string previous-elem-key-string
10766 after-comma previous-token)
10767 (while continue
10768 (setq tt (js2-get-prop-name-token)
10769 static nil
10770 elem nil
10771 previous-token nil)
10772 ;; Handle 'static' keyword only if we're in a class
10773 (when (and class-p (= js2-NAME tt)
10774 (string= "static" (js2-current-token-string)))
10775 (js2-record-face 'font-lock-keyword-face)
10776 (setq static t
10777 tt (js2-get-prop-name-token)))
10778 ;; Handle generator * before the property name for in-line functions
10779 (when (and (>= js2-language-version 200)
10780 (= js2-MUL tt))
10781 (setq previous-token (js2-current-token)
10782 tt (js2-get-prop-name-token)))
10783 ;; Handle getter, setter and async methods
10784 (let ((prop (js2-current-token-string)))
10785 (when (and (>= js2-language-version 200)
10786 (= js2-NAME tt)
10787 (member prop '("get" "set" "async"))
10788 (member (js2-peek-token)
10789 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10790 (setq previous-token (js2-current-token)
10791 tt (js2-get-prop-name-token))))
10792 (cond
10793 ;; Rest/spread (...expr)
10794 ((and (>= js2-language-version 200)
10795 (not class-p) (not static) (not previous-token)
10796 (= js2-TRIPLEDOT tt))
10797 (setq after-comma nil
10798 elem (js2-make-unary js2-TRIPLEDOT 'js2-parse-assign-expr)))
10799 ;; Found a key/value property (of any sort)
10800 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10801 (setq after-comma nil
10802 elem (js2-parse-named-prop tt previous-token))
10803 (if (and (null elem)
10804 (not js2-recover-from-parse-errors))
10805 (setq continue nil)))
10806 ;; Break out of loop, and handle trailing commas.
10807 ((or (= tt js2-RC)
10808 (= tt js2-EOF))
10809 (js2-unget-token)
10810 (setq continue nil)
10811 (if after-comma
10812 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10813 pos elems after-comma)))
10814 ;; Skip semicolons in a class body
10815 ((and class-p
10816 (= tt js2-SEMI))
10817 nil)
10818 (t
10819 (js2-report-error "msg.bad.prop")
10820 (unless js2-recover-from-parse-errors
10821 (setq continue nil)))) ; end switch
10822 ;; Handle static for classes' codegen.
10823 (if static
10824 (if elem (js2-node-set-prop elem 'STATIC t)
10825 (js2-report-error "msg.unexpected.static")))
10826 ;; Handle commas, depending on class-p.
10827 (let ((tok (js2-get-prop-name-token)))
10828 (if (eq tok js2-COMMA)
10829 (if class-p
10830 (js2-report-error "msg.class.unexpected.comma")
10831 (setq after-comma (js2-current-token-end)))
10832 (js2-unget-token)
10833 (unless class-p (setq continue nil))))
10834 (when elem
10835 (when (and js2-in-use-strict-directive
10836 (setq elem-key-string (js2-property-key-string elem))
10837 (cl-some
10838 (lambda (previous-elem)
10839 (and (setq previous-elem-key-string
10840 (js2-property-key-string previous-elem))
10841 ;; Check if the property is a duplicate.
10842 (string= previous-elem-key-string elem-key-string)
10843 ;; But make an exception for getter / setter pairs.
10844 (not (and (js2-method-node-p elem)
10845 (js2-method-node-p previous-elem)
10846 (let ((type (js2-node-get-prop (js2-method-node-right elem) 'METHOD_TYPE))
10847 (previous-type (js2-node-get-prop (js2-method-node-right previous-elem) 'METHOD_TYPE)))
10848 (and (member type '(GET SET))
10849 (member previous-type '(GET SET))
10850 (not (eq type previous-type))))))))
10851 elems))
10852 (js2-report-error "msg.dup.obj.lit.prop.strict"
10853 elem-key-string
10854 (js2-node-abs-pos (js2-infix-node-left elem))
10855 (js2-node-len (js2-infix-node-left elem))))
10856 ;; Append any parsed element.
10857 (push elem elems))) ; end loop
10858 (js2-must-match js2-RC "msg.no.brace.prop")
10859 (nreverse elems)))
10860
10861 (defun js2-parse-named-prop (tt previous-token)
10862 "Parse a name, string, or getter/setter object property.
10863 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10864 (let ((key (js2-parse-prop-name tt))
10865 (prop (and previous-token (js2-token-string previous-token)))
10866 (property-type (when previous-token
10867 (if (= (js2-token-type previous-token) js2-MUL)
10868 "*"
10869 (js2-token-string previous-token))))
10870 pos)
10871 (when (member prop '("get" "set" "async"))
10872 (setq pos (js2-token-beg previous-token))
10873 (js2-set-face (js2-token-beg previous-token)
10874 (js2-token-end previous-token)
10875 'font-lock-keyword-face 'record)) ; get/set/async
10876 (cond
10877 ;; method definition: {f() {...}}
10878 ((and (= (js2-peek-token) js2-LP)
10879 (>= js2-language-version 200))
10880 (when (js2-name-node-p key) ; highlight function name properties
10881 (js2-record-face 'font-lock-function-name-face))
10882 (js2-parse-method-prop pos key property-type))
10883 ;; binding element with initializer
10884 ((and (= (js2-peek-token) js2-ASSIGN)
10885 (>= js2-language-version 200))
10886 (if (not js2-is-in-destructuring)
10887 (js2-report-error "msg.init.no.destruct"))
10888 (js2-parse-initialized-binding key))
10889 ;; regular prop
10890 (t
10891 (let ((beg (js2-current-token-beg))
10892 (end (js2-current-token-end))
10893 (expr (js2-parse-plain-property key)))
10894 (when (and (= tt js2-NAME)
10895 (not js2-is-in-destructuring)
10896 js2-highlight-external-variables
10897 (js2-node-get-prop expr 'SHORTHAND))
10898 (js2-record-name-node key))
10899 (js2-set-face beg end
10900 (if (js2-function-node-p
10901 (js2-object-prop-node-right expr))
10902 'font-lock-function-name-face
10903 'js2-object-property)
10904 'record)
10905 expr)))))
10906
10907 (defun js2-parse-initialized-binding (name)
10908 "Parse a `SingleNameBinding' with initializer.
10909
10910 `name' is the `BindingIdentifier'."
10911 (when (js2-match-token js2-ASSIGN)
10912 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10913
10914 (defun js2-parse-prop-name (tt)
10915 (cond
10916 ;; Literal string keys: {'foo': 'bar'}
10917 ((= tt js2-STRING)
10918 (make-js2-string-node))
10919 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10920 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10921 ((and (= tt js2-LB)
10922 (>= js2-language-version 200))
10923 (make-js2-computed-prop-name-node
10924 :expr (prog1 (js2-parse-assign-expr)
10925 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10926 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10927 ((= tt js2-NUMBER)
10928 (make-js2-number-node))
10929 ;; Unquoted names: {foo: 12}
10930 ((= tt js2-NAME)
10931 (js2-create-name-node))
10932 ;; Anything else is an error
10933 (t (js2-report-error "msg.bad.prop"))))
10934
10935 (defun js2-parse-plain-property (prop)
10936 "Parse a non-getter/setter property in an object literal.
10937 PROP is the node representing the property: a number, name,
10938 string or expression."
10939 (let* ((tt (js2-get-token))
10940 (pos (js2-node-pos prop))
10941 colon expr result)
10942 (cond
10943 ;; Abbreviated property, as in {foo, bar}
10944 ((and (>= js2-language-version 200)
10945 (or (= tt js2-COMMA)
10946 (= tt js2-RC))
10947 (not (js2-number-node-p prop)))
10948 (js2-unget-token)
10949 (setq result (make-js2-object-prop-node
10950 :pos pos
10951 :left prop
10952 :right prop
10953 :op-pos (js2-current-token-len)))
10954 (js2-node-add-children result prop)
10955 (js2-node-set-prop result 'SHORTHAND t)
10956 result)
10957 ;; Normal property
10958 (t
10959 (if (= tt js2-COLON)
10960 (setq colon (- (js2-current-token-beg) pos)
10961 expr (js2-parse-assign-expr))
10962 (js2-report-error "msg.no.colon.prop")
10963 (setq expr (make-js2-error-node)))
10964 (setq result (make-js2-object-prop-node
10965 :pos pos
10966 ;; don't include last consumed token in length
10967 :len (- (+ (js2-node-pos expr)
10968 (js2-node-len expr))
10969 pos)
10970 :left prop
10971 :right expr
10972 :op-pos colon))
10973 (js2-node-add-children result prop expr)
10974 result))))
10975
10976 (defun js2-parse-method-prop (pos prop type-string)
10977 "Parse method property in an object literal or a class body.
10978 JavaScript syntax is:
10979
10980 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...},
10981 async foo(...) {...} }
10982
10983 and expression closure style is also supported
10984
10985 { get foo() x, set foo(x) _x = x }
10986
10987 POS is the start position of the `get' or `set' keyword.
10988 PROP is the `js2-name-node' representing the property name.
10989 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10990 (let* ((type (or (cdr (assoc type-string '(("get" . GET)
10991 ("set" . SET)
10992 ("async" . ASYNC))))
10993 'FUNCTION))
10994 result end
10995 (fn (js2-parse-function-expr (eq type 'ASYNC))))
10996 ;; it has to be an anonymous function, as we already parsed the name
10997 (if (/= (js2-node-type fn) js2-FUNCTION)
10998 (js2-report-error "msg.bad.prop")
10999 (if (cl-plusp (length (js2-function-name fn)))
11000 (js2-report-error "msg.bad.prop")))
11001 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
11002 (when (string= type-string "*")
11003 (setf (js2-function-node-generator-type fn) 'STAR))
11004 (unless pos (setq pos (js2-node-pos prop)))
11005 (setq end (js2-node-end fn)
11006 result (make-js2-method-node :pos pos
11007 :len (- end pos)
11008 :left prop
11009 :right fn))
11010 (js2-node-add-children result prop fn)
11011 result))
11012
11013 (defun js2-create-name-node (&optional check-activation-p token string)
11014 "Create a name node using the current token and, optionally, STRING.
11015 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
11016 (let* ((beg (js2-current-token-beg))
11017 (tt (js2-current-token-type))
11018 (s (or string
11019 (if (= js2-NAME tt)
11020 (js2-current-token-string)
11021 (js2-tt-name tt))))
11022 name)
11023 (setq name (make-js2-name-node :pos beg
11024 :name s
11025 :len (length s)))
11026 (if check-activation-p
11027 (js2-check-activation-name s (or token js2-NAME)))
11028 name))
11029
11030 ;;; Use AST to extract semantic information
11031
11032 (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
11033 "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
11034 (let ((idx 0) elems (rlt hardcoded-array-index))
11035 (setq elems (js2-array-node-elems array-node))
11036 (if (and elem (not hardcoded-array-index))
11037 (setq rlt (catch 'nth-elt
11038 (dolist (x elems)
11039 ;; We know the ELEM does belong to ARRAY-NODE,
11040 (if (eq elem x) (throw 'nth-elt idx))
11041 (setq idx (1+ idx)))
11042 0)))
11043 (format "[%s]" rlt)))
11044
11045 (defun js2-print-json-path (&optional hardcoded-array-index)
11046 "Print the path to the JSON value under point, and save it in the kill ring.
11047 If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
11048 (interactive "P")
11049 (js2-reparse)
11050 (let (previous-node current-node
11051 key-name
11052 rlt)
11053
11054 ;; The `js2-node-at-point' starts scanning from AST root node.
11055 ;; So there is no way to optimize it.
11056 (setq current-node (js2-node-at-point))
11057
11058 (while (not (js2-ast-root-p current-node))
11059 (cond
11060 ;; JSON property node
11061 ((js2-object-prop-node-p current-node)
11062 (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
11063 (if rlt (setq rlt (concat "." key-name rlt))
11064 (setq rlt (concat "." key-name))))
11065
11066 ;; Array node
11067 ((or (js2-array-node-p current-node))
11068 (setq rlt (concat (js2-get-element-index-from-array-node previous-node
11069 current-node
11070 hardcoded-array-index)
11071 rlt)))
11072
11073 ;; Other nodes are ignored
11074 (t))
11075
11076 ;; current node is archived
11077 (setq previous-node current-node)
11078 ;; Get parent node and continue the loop
11079 (setq current-node (js2-node-parent current-node)))
11080
11081 (cond
11082 (rlt
11083 ;; Clean the final result
11084 (setq rlt (replace-regexp-in-string "^\\." "" rlt))
11085 (kill-new rlt)
11086 (message "%s => kill-ring" rlt))
11087 (t
11088 (message "No JSON path found!")))
11089
11090 rlt))
11091
11092 ;;; Indentation support (bouncing)
11093
11094 ;; In recent-enough Emacs, we reuse the indentation code from
11095 ;; `js-mode'. To continue support for the older versions, some code
11096 ;; that was here previously was moved to `js2-old-indent.el'.
11097
11098 ;; Whichever indenter is used, it's often "wrong", however, and needs
11099 ;; to be overridden. The right long-term solution is probably to
11100 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
11101 ;; of coding. Even when a parse tree from `js2-parse' is present,
11102 ;; which is not true at the moment the user is typing, computing
11103 ;; indentation is still thousands of lines of code to handle every
11104 ;; possible syntactic edge case.
11105
11106 ;; In the meantime, the compromise solution is that we offer a "bounce
11107 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
11108 ;; current line indent among various likely guess points. This approach
11109 ;; is far from perfect, but should at least make it slightly easier to
11110 ;; move the line towards its desired indentation when manually
11111 ;; overriding Karl's heuristic nesting guesser.
11112
11113 (defun js2-backward-sws ()
11114 "Move backward through whitespace and comments."
11115 (interactive)
11116 (while (forward-comment -1)))
11117
11118 (defun js2-forward-sws ()
11119 "Move forward through whitespace and comments."
11120 (interactive)
11121 (while (forward-comment 1)))
11122
11123 (defun js2-arglist-close ()
11124 "Return non-nil if we're on a line beginning with a close-paren/brace."
11125 (save-excursion
11126 (goto-char (point-at-bol))
11127 (js2-forward-sws)
11128 (looking-at "[])}]")))
11129
11130 (defun js2-indent-looks-like-label-p ()
11131 (goto-char (point-at-bol))
11132 (js2-forward-sws)
11133 (looking-at (concat js2-mode-identifier-re ":")))
11134
11135 (defun js2-indent-in-objlit-p (parse-status)
11136 "Return non-nil if this looks like an object-literal entry."
11137 (let ((start (nth 1 parse-status)))
11138 (and
11139 start
11140 (save-excursion
11141 (and (zerop (forward-line -1))
11142 (not (< (point) start)) ; crossed a {} boundary
11143 (js2-indent-looks-like-label-p)))
11144 (save-excursion
11145 (js2-indent-looks-like-label-p)))))
11146
11147 ;; If prev line looks like foobar({ then we're passing an object
11148 ;; literal to a function call, and people pretty much always want to
11149 ;; de-dent back to the previous line, so move the 'basic-offset'
11150 ;; position to the front.
11151 (defun js2-indent-objlit-arg-p (parse-status)
11152 (save-excursion
11153 (back-to-indentation)
11154 (js2-backward-sws)
11155 (and (eq (1- (point)) (nth 1 parse-status))
11156 (eq (char-before) ?{)
11157 (progn
11158 (forward-char -1)
11159 (skip-chars-backward " \t")
11160 (eq (char-before) ?\()))))
11161
11162 (defun js2-indent-case-block-p ()
11163 (save-excursion
11164 (back-to-indentation)
11165 (js2-backward-sws)
11166 (goto-char (point-at-bol))
11167 (skip-chars-forward " \t")
11168 (looking-at "case\\s-.+:")))
11169
11170 (defun js2-bounce-indent (normal-col parse-status &optional backward)
11171 "Cycle among alternate computed indentation positions.
11172 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11173 of the buffer to the current point. NORMAL-COL is the indentation
11174 column computed by the heuristic guesser based on current paren,
11175 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11176 in reverse."
11177 (let ((cur-indent (current-indentation))
11178 (old-buffer-undo-list buffer-undo-list)
11179 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11180 (current-line (save-excursion
11181 (forward-line 0) ; move to bol
11182 (1+ (count-lines (point-min) (point)))))
11183 positions pos main-pos anchor arglist-cont same-indent
11184 basic-offset computed-pos)
11185 ;; temporarily don't record undo info, if user requested this
11186 (when js2-mode-indent-inhibit-undo
11187 (setq buffer-undo-list t))
11188 (unwind-protect
11189 (progn
11190 ;; First likely point: indent from beginning of previous code line
11191 (push (setq basic-offset
11192 (+ (save-excursion
11193 (back-to-indentation)
11194 (js2-backward-sws)
11195 (back-to-indentation)
11196 (current-column))
11197 js2-basic-offset))
11198 positions)
11199
11200 ;; (First + epsilon) likely point: indent 2x from beginning of
11201 ;; previous code line. Google does it this way.
11202 (push (setq basic-offset
11203 (+ (save-excursion
11204 (back-to-indentation)
11205 (js2-backward-sws)
11206 (back-to-indentation)
11207 (current-column))
11208 (* 2 js2-basic-offset)))
11209 positions)
11210
11211 ;; Second likely point: indent from assign-expr RHS. This
11212 ;; is just a crude guess based on finding " = " on the previous
11213 ;; line containing actual code.
11214 (setq pos (save-excursion
11215 (forward-line -1)
11216 (goto-char (point-at-bol))
11217 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11218 (point-at-eol) t)
11219 (goto-char (match-end 1))
11220 (skip-chars-forward " \t\r\n")
11221 (current-column))))
11222 (when pos
11223 (cl-incf pos js2-basic-offset)
11224 (push pos positions))
11225
11226 ;; Third likely point: same indent as previous line of code.
11227 ;; Make it the first likely point if we're not on an
11228 ;; arglist-close line and previous line ends in a comma, or
11229 ;; both this line and prev line look like object-literal
11230 ;; elements.
11231 (setq pos (save-excursion
11232 (goto-char (point-at-bol))
11233 (js2-backward-sws)
11234 (back-to-indentation)
11235 (prog1
11236 (current-column)
11237 ;; while we're here, look for trailing comma
11238 (if (save-excursion
11239 (goto-char (point-at-eol))
11240 (js2-backward-sws)
11241 (eq (char-before) ?,))
11242 (setq arglist-cont (1- (point)))))))
11243 (when pos
11244 (if (and (or arglist-cont
11245 (js2-indent-in-objlit-p parse-status))
11246 (not (js2-arglist-close)))
11247 (setq same-indent pos))
11248 (push pos positions))
11249
11250 ;; Fourth likely point: first preceding code with less indentation.
11251 ;; than the immediately preceding code line.
11252 (setq pos (save-excursion
11253 (back-to-indentation)
11254 (js2-backward-sws)
11255 (back-to-indentation)
11256 (setq anchor (current-column))
11257 (while (and (zerop (forward-line -1))
11258 (>= (progn
11259 (back-to-indentation)
11260 (current-column))
11261 anchor)))
11262 (setq pos (current-column))))
11263 (push pos positions)
11264
11265 ;; nesting-heuristic position, main by default
11266 (push (setq main-pos normal-col) positions)
11267
11268 ;; delete duplicates and sort positions list
11269 (setq positions (sort (delete-dups positions) '<))
11270
11271 ;; comma-list continuation lines: prev line indent takes precedence
11272 (if same-indent
11273 (setq main-pos same-indent))
11274
11275 ;; common special cases where we want to indent in from previous line
11276 (if (or (js2-indent-case-block-p)
11277 (js2-indent-objlit-arg-p parse-status))
11278 (setq main-pos basic-offset))
11279
11280 ;; if bouncing backward, reverse positions list
11281 (if backward
11282 (setq positions (reverse positions)))
11283
11284 ;; record whether we're already sitting on one of the alternatives
11285 (setq pos (member cur-indent positions))
11286
11287 (cond
11288 ;; case 0: we're one one of the alternatives and this is the
11289 ;; first time they've pressed TAB on this line (best-guess).
11290 ((and js2-mode-indent-ignore-first-tab
11291 pos
11292 ;; first time pressing TAB on this line?
11293 (not (eq js2-mode-last-indented-line current-line)))
11294 ;; do nothing
11295 (setq computed-pos nil))
11296 ;; case 1: only one computed position => use it
11297 ((null (cdr positions))
11298 (setq computed-pos 0))
11299 ;; case 2: not on any of the computed spots => use main spot
11300 ((not pos)
11301 (setq computed-pos (js2-position main-pos positions)))
11302 ;; case 3: on last position: cycle to first position
11303 ((null (cdr pos))
11304 (setq computed-pos 0))
11305 ;; case 4: on intermediate position: cycle to next position
11306 (t
11307 (setq computed-pos (js2-position (cl-second pos) positions))))
11308
11309 ;; see if any hooks want to indent; otherwise we do it
11310 (cl-loop with result = nil
11311 for hook in js2-indent-hook
11312 while (null result)
11313 do
11314 (setq result (funcall hook positions computed-pos))
11315 finally do
11316 (unless (or result (null computed-pos))
11317 (indent-line-to (nth computed-pos positions)))))
11318
11319 ;; finally
11320 (if js2-mode-indent-inhibit-undo
11321 (setq buffer-undo-list old-buffer-undo-list))
11322 ;; see commentary for `js2-mode-last-indented-line'
11323 (setq js2-mode-last-indented-line current-line))))
11324
11325 (defun js2-1-line-comment-continuation-p ()
11326 "Return t if we're in a 1-line comment continuation.
11327 If so, we don't ever want to use bounce-indent."
11328 (save-excursion
11329 (and (progn
11330 (forward-line 0)
11331 (looking-at "\\s-*//"))
11332 (progn
11333 (forward-line -1)
11334 (forward-line 0)
11335 (when (looking-at "\\s-*$")
11336 (js2-backward-sws)
11337 (forward-line 0))
11338 (looking-at "\\s-*//")))))
11339
11340 (defun js2-indent-bounce (&optional backward)
11341 "Indent the current line, bouncing between several positions."
11342 (interactive)
11343 (let (parse-status offset indent-col
11344 ;; Don't whine about errors/warnings when we're indenting.
11345 ;; This has to be set before calling parse-partial-sexp below.
11346 (inhibit-point-motion-hooks t))
11347 (setq parse-status (save-excursion
11348 (syntax-ppss (point-at-bol)))
11349 offset (- (point) (save-excursion
11350 (back-to-indentation)
11351 (point))))
11352 ;; Don't touch multiline strings.
11353 (unless (nth 3 parse-status)
11354 (setq indent-col (js2-proper-indentation parse-status))
11355 (cond
11356 ;; It doesn't work well on first line of buffer.
11357 ((and (not (nth 4 parse-status))
11358 (not (js2-same-line (point-min)))
11359 (not (js2-1-line-comment-continuation-p)))
11360 (js2-bounce-indent indent-col parse-status backward))
11361 ;; just indent to the guesser's likely spot
11362 (t (indent-line-to indent-col)))
11363 (when (cl-plusp offset)
11364 (forward-char offset)))))
11365
11366 (defun js2-indent-bounce-backward ()
11367 "Indent the current line, bouncing between positions in reverse."
11368 (interactive)
11369 (js2-indent-bounce t))
11370
11371 (defun js2-indent-region (start end)
11372 "Indent the region, but don't use bounce indenting."
11373 (let ((js2-bounce-indent-p nil)
11374 (indent-region-function nil)
11375 (after-change-functions (remq 'js2-mode-edit
11376 after-change-functions)))
11377 (indent-region start end nil) ; nil for byte-compiler
11378 (js2-mode-edit start end (- end start))))
11379
11380 (defvar js2-minor-mode-map
11381 (let ((map (make-sparse-keymap)))
11382 (define-key map (kbd "C-c C-`") #'js2-next-error)
11383 (define-key map [mouse-1] #'js2-mode-show-node)
11384 map)
11385 "Keymap used when `js2-minor-mode' is active.")
11386
11387 ;;;###autoload
11388 (define-minor-mode js2-minor-mode
11389 "Minor mode for running js2 as a background linter.
11390 This allows you to use a different major mode for JavaScript editing,
11391 such as `js-mode', while retaining the asynchronous error/warning
11392 highlighting features of `js2-mode'."
11393 :group 'js2-mode
11394 :lighter " js-lint"
11395 (if (derived-mode-p 'js2-mode)
11396 (setq js2-minor-mode nil)
11397 (if js2-minor-mode
11398 (js2-minor-mode-enter)
11399 (js2-minor-mode-exit))))
11400
11401 (defun js2-minor-mode-enter ()
11402 "Initialization for `js2-minor-mode'."
11403 (set (make-local-variable 'max-lisp-eval-depth)
11404 (max max-lisp-eval-depth 3000))
11405 (setq next-error-function #'js2-next-error)
11406 (js2-set-default-externs)
11407 ;; Experiment: make reparse-delay longer for longer files.
11408 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11409 (setq js2-idle-timer-delay
11410 (* js2-idle-timer-delay
11411 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11412 (setq js2-mode-buffer-dirty-p t
11413 js2-mode-parsing nil)
11414 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11415 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11416 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11417 (when js2-include-jslint-globals
11418 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11419 (run-hooks 'js2-init-hook)
11420 (js2-reparse))
11421
11422 (defun js2-minor-mode-exit ()
11423 "Turn off `js2-minor-mode'."
11424 (setq next-error-function nil)
11425 (remove-hook 'after-change-functions #'js2-mode-edit t)
11426 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11427 (when js2-mode-node-overlay
11428 (delete-overlay js2-mode-node-overlay)
11429 (setq js2-mode-node-overlay nil))
11430 (js2-remove-overlays)
11431 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11432 (setq js2-mode-ast nil))
11433
11434 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11435 (make-variable-buffer-local 'js2-source-buffer)
11436
11437 (cl-defun js2-display-error-list ()
11438 "Display a navigable buffer listing parse errors/warnings."
11439 (interactive)
11440 (unless (js2-have-errors-p)
11441 (message "No errors")
11442 (cl-return-from js2-display-error-list))
11443 (cl-labels ((annotate-list
11444 (lst type)
11445 "Add diagnostic TYPE and line number to errs list"
11446 (mapcar (lambda (err)
11447 (list err type (line-number-at-pos (nth 1 err))))
11448 lst)))
11449 (let* ((srcbuf (current-buffer))
11450 (errbuf (get-buffer-create "*js-lint*"))
11451 (errors (annotate-list
11452 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11453 'js2-error)) ; must be a valid face name
11454 (warnings (annotate-list
11455 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11456 'js2-warning)) ; must be a valid face name
11457 (all-errs (sort (append errors warnings)
11458 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11459 (with-current-buffer errbuf
11460 (let ((inhibit-read-only t))
11461 (erase-buffer)
11462 (dolist (err all-errs)
11463 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11464 (insert-text-button
11465 (format "line %d: %s" line (js2-get-msg msg-key))
11466 'face type
11467 'follow-link "\C-m"
11468 'action 'js2-error-buffer-jump
11469 'js2-msg (js2-get-msg msg-key)
11470 'js2-pos beg)
11471 (insert "\n"))))
11472 (js2-error-buffer-mode)
11473 (setq js2-source-buffer srcbuf)
11474 (pop-to-buffer errbuf)
11475 (goto-char (point-min))
11476 (unless (eobp)
11477 (js2-error-buffer-view))))))
11478
11479 (defvar js2-error-buffer-mode-map
11480 (let ((map (make-sparse-keymap)))
11481 (define-key map "n" #'js2-error-buffer-next)
11482 (define-key map "p" #'js2-error-buffer-prev)
11483 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11484 (define-key map "o" #'js2-error-buffer-view)
11485 (define-key map "q" #'js2-error-buffer-quit)
11486 map)
11487 "Keymap used for js2 diagnostics buffers.")
11488
11489 (defun js2-error-buffer-mode ()
11490 "Major mode for js2 diagnostics buffers.
11491 Selecting an error will jump it to the corresponding source-buffer error.
11492 \\{js2-error-buffer-mode-map}"
11493 (interactive)
11494 (setq major-mode 'js2-error-buffer-mode
11495 mode-name "JS Lint Diagnostics")
11496 (use-local-map js2-error-buffer-mode-map)
11497 (setq truncate-lines t)
11498 (set-buffer-modified-p nil)
11499 (setq buffer-read-only t)
11500 (run-hooks 'js2-error-buffer-mode-hook))
11501
11502 (defun js2-error-buffer-next ()
11503 "Move to next error and view it."
11504 (interactive)
11505 (when (zerop (forward-line 1))
11506 (js2-error-buffer-view)))
11507
11508 (defun js2-error-buffer-prev ()
11509 "Move to previous error and view it."
11510 (interactive)
11511 (when (zerop (forward-line -1))
11512 (js2-error-buffer-view)))
11513
11514 (defun js2-error-buffer-quit ()
11515 "Kill the current buffer."
11516 (interactive)
11517 (kill-buffer))
11518
11519 (defun js2-error-buffer-jump (&rest ignored)
11520 "Jump cursor to current error in source buffer."
11521 (interactive)
11522 (when (js2-error-buffer-view)
11523 (pop-to-buffer js2-source-buffer)))
11524
11525 (defun js2-error-buffer-view ()
11526 "Scroll source buffer to show error at current line."
11527 (interactive)
11528 (cond
11529 ((not (eq major-mode 'js2-error-buffer-mode))
11530 (message "Not in a js2 errors buffer"))
11531 ((not (buffer-live-p js2-source-buffer))
11532 (message "Source buffer has been killed"))
11533 ((not (wholenump (get-text-property (point) 'js2-pos)))
11534 (message "There does not seem to be an error here"))
11535 (t
11536 (let ((pos (get-text-property (point) 'js2-pos))
11537 (msg (get-text-property (point) 'js2-msg)))
11538 (save-selected-window
11539 (pop-to-buffer js2-source-buffer)
11540 (goto-char pos)
11541 (message msg))))))
11542
11543 ;;;###autoload
11544 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11545 "Major mode for editing JavaScript code."
11546 (set (make-local-variable 'max-lisp-eval-depth)
11547 (max max-lisp-eval-depth 3000))
11548 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11549 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11550 (set (make-local-variable 'syntax-propertize-function) nil)
11551 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11552 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11553 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11554 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11555 ;; for characters inside regexp literals.
11556 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11557 ;; this is necessary to make `show-paren-function' work properly
11558 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11559 ;; needed for M-x rgrep, among other things
11560 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11561
11562 (setq font-lock-defaults '(nil t))
11563
11564 ;; Experiment: make reparse-delay longer for longer files.
11565 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11566 (setq js2-idle-timer-delay
11567 (* js2-idle-timer-delay
11568 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11569
11570 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11571 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11572 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11573 (setq next-error-function #'js2-next-error)
11574 (imenu-add-to-menubar (concat "IM-" mode-name))
11575 (add-to-invisibility-spec '(js2-outline . t))
11576 (set (make-local-variable 'line-move-ignore-invisible) t)
11577 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11578 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11579
11580 (setq js2-mode-functions-hidden nil
11581 js2-mode-comments-hidden nil
11582 js2-mode-buffer-dirty-p t
11583 js2-mode-parsing nil)
11584
11585 (js2-set-default-externs)
11586
11587 (when js2-include-jslint-globals
11588 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11589
11590 (run-hooks 'js2-init-hook)
11591
11592 (let ((js2-idle-timer-delay 0))
11593 ;; Schedule parsing for after when the mode hooks run.
11594 (js2-mode-reset-timer)))
11595
11596 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11597 ;; a bit more complicated and it doesn't net us much yet.
11598 ;;;###autoload
11599 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11600 "Major mode for editing JSX code.
11601
11602 To customize the indentation for this mode, set the SGML offset
11603 variables (`sgml-basic-offset' et al) locally, like so:
11604
11605 (defun set-jsx-indentation ()
11606 (setq-local sgml-basic-offset js2-basic-offset))
11607 (add-hook 'js2-jsx-mode-hook #'set-jsx-indentation)"
11608 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11609
11610 (defun js2-mode-exit ()
11611 "Exit `js2-mode' and clean up."
11612 (interactive)
11613 (when js2-mode-node-overlay
11614 (delete-overlay js2-mode-node-overlay)
11615 (setq js2-mode-node-overlay nil))
11616 (js2-remove-overlays)
11617 (setq js2-mode-ast nil)
11618 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11619 (remove-from-invisibility-spec '(js2-outline . t))
11620 (js2-mode-show-all)
11621 (with-silent-modifications
11622 (js2-clear-face (point-min) (point-max))))
11623
11624 (defun js2-mode-reset-timer ()
11625 "Cancel any existing parse timer and schedule a new one."
11626 (if js2-mode-parse-timer
11627 (cancel-timer js2-mode-parse-timer))
11628 (setq js2-mode-parsing nil)
11629 (let ((timer (timer-create)))
11630 (setq js2-mode-parse-timer timer)
11631 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11632 (timer-set-idle-time timer js2-idle-timer-delay)
11633 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11634 (timer-activate-when-idle timer nil)))
11635
11636 (defun js2-mode-idle-reparse (buffer)
11637 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11638 it to be reparsed when the buffer is selected."
11639 (cond ((eq buffer (current-buffer))
11640 (js2-reparse))
11641 ((buffer-live-p buffer)
11642 ;; reparse when the buffer is selected again
11643 (with-current-buffer buffer
11644 (add-hook 'window-configuration-change-hook
11645 #'js2-mode-idle-reparse-inner
11646 nil t)))))
11647
11648 (defun js2-mode-idle-reparse-inner ()
11649 (remove-hook 'window-configuration-change-hook
11650 #'js2-mode-idle-reparse-inner
11651 t)
11652 (js2-reparse))
11653
11654 (defun js2-mode-edit (_beg _end _len)
11655 "Schedule a new parse after buffer is edited.
11656 Buffer edit spans from BEG to END and is of length LEN."
11657 (setq js2-mode-buffer-dirty-p t)
11658 (js2-mode-hide-overlay)
11659 (js2-mode-reset-timer))
11660
11661 (defun js2-minor-mode-edit (_beg _end _len)
11662 "Callback for buffer edits in `js2-mode'.
11663 Schedules a new parse after buffer is edited.
11664 Buffer edit spans from BEG to END and is of length LEN."
11665 (setq js2-mode-buffer-dirty-p t)
11666 (js2-mode-hide-overlay)
11667 (js2-mode-reset-timer))
11668
11669 (defun js2-reparse (&optional force)
11670 "Re-parse current buffer after user finishes some data entry.
11671 If we get any user input while parsing, including cursor motion,
11672 we discard the parse and reschedule it. If FORCE is nil, then the
11673 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11674 (let (time
11675 interrupted-p
11676 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11677 (unless js2-mode-parsing
11678 (setq js2-mode-parsing t)
11679 (unwind-protect
11680 (when (or js2-mode-buffer-dirty-p force)
11681 (js2-remove-overlays)
11682 (setq js2-mode-buffer-dirty-p nil
11683 js2-mode-fontifications nil
11684 js2-mode-deferred-properties nil)
11685 (if js2-mode-verbose-parse-p
11686 (message "parsing..."))
11687 (setq time
11688 (js2-time
11689 (setq interrupted-p
11690 (catch 'interrupted
11691 (js2-parse)
11692 (with-silent-modifications
11693 ;; if parsing is interrupted, comments and regex
11694 ;; literals stay ignored by `parse-partial-sexp'
11695 (remove-text-properties (point-min) (point-max)
11696 '(syntax-table))
11697 (js2-mode-apply-deferred-properties)
11698 (js2-mode-remove-suppressed-warnings)
11699 (js2-mode-show-warnings)
11700 (js2-mode-show-errors)
11701 (if (>= js2-highlight-level 1)
11702 (js2-highlight-jsdoc js2-mode-ast)))
11703 nil))))
11704 (if interrupted-p
11705 (progn
11706 ;; unfinished parse => try again
11707 (setq js2-mode-buffer-dirty-p t)
11708 (js2-mode-reset-timer))
11709 (if js2-mode-verbose-parse-p
11710 (message "Parse time: %s" time))))
11711 (setq js2-mode-parsing nil)
11712 (unless interrupted-p
11713 (setq js2-mode-parse-timer nil))))))
11714
11715 (defun js2-mode-show-node (event)
11716 "Debugging aid: highlight selected AST node on mouse click."
11717 (interactive "e")
11718 (mouse-set-point event)
11719 (setq deactivate-mark t)
11720 (when js2-mode-show-overlay
11721 (let ((node (js2-node-at-point))
11722 beg end)
11723 (if (null node)
11724 (message "No node found at location %s" (point))
11725 (setq beg (js2-node-abs-pos node)
11726 end (+ beg (js2-node-len node)))
11727 (if js2-mode-node-overlay
11728 (move-overlay js2-mode-node-overlay beg end)
11729 (setq js2-mode-node-overlay (make-overlay beg end))
11730 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11731 (with-silent-modifications
11732 (if (fboundp 'cursor-sensor-mode)
11733 (put-text-property beg end 'cursor-sensor-functions
11734 '(js2-mode-hide-overlay))
11735 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11736 (message "%s, parent: %s"
11737 (js2-node-short-name node)
11738 (if (js2-node-parent node)
11739 (js2-node-short-name (js2-node-parent node))
11740 "nil"))))))
11741
11742 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11743 "Remove the debugging overlay when point moves.
11744 ARG1, ARG2 and ARG3 have different values depending on whether this function
11745 was found on `point-left' or in `cursor-sensor-functions'."
11746 (when js2-mode-node-overlay
11747 (let ((beg (overlay-start js2-mode-node-overlay))
11748 (end (overlay-end js2-mode-node-overlay))
11749 (p2 (if (windowp arg1)
11750 ;; Called from cursor-sensor-functions.
11751 (window-point arg1)
11752 ;; Called from point-left.
11753 arg2)))
11754 ;; Sometimes we're called spuriously.
11755 (unless (and p2
11756 (>= p2 beg)
11757 (<= p2 end))
11758 (with-silent-modifications
11759 (remove-text-properties beg end
11760 '(point-left nil cursor-sensor-functions)))
11761 (delete-overlay js2-mode-node-overlay)
11762 (setq js2-mode-node-overlay nil)))))
11763
11764 (defun js2-mode-reset ()
11765 "Debugging helper: reset everything."
11766 (interactive)
11767 (js2-mode-exit)
11768 (js2-mode))
11769
11770 (defun js2-mode-show-warn-or-err (e face)
11771 "Highlight a warning or error E with FACE.
11772 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11773 The last element is optional. When present, use instead of FACE."
11774 (let* ((key (cl-first e))
11775 (beg (cl-second e))
11776 (end (+ beg (cl-third e)))
11777 ;; Don't inadvertently go out of bounds.
11778 (beg (max (point-min) (min beg (point-max))))
11779 (end (max (point-min) (min end (point-max))))
11780 (ovl (make-overlay beg end)))
11781 ;; FIXME: Why a mix of overlays and text-properties?
11782 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11783 (overlay-put ovl 'js2-error t)
11784 (put-text-property beg end 'help-echo (js2-get-msg key))
11785 (if (fboundp 'cursor-sensor-mode)
11786 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11787 (put-text-property beg end 'point-entered #'js2-echo-error))))
11788
11789 (defun js2-remove-overlays ()
11790 "Remove overlays from buffer that have a `js2-error' property."
11791 (let ((beg (point-min))
11792 (end (point-max)))
11793 (save-excursion
11794 (dolist (o (overlays-in beg end))
11795 (when (overlay-get o 'js2-error)
11796 (delete-overlay o))))))
11797
11798 (defun js2-mode-apply-deferred-properties ()
11799 "Apply fontifications and other text properties recorded during parsing."
11800 (when (cl-plusp js2-highlight-level)
11801 ;; We defer clearing faces as long as possible to eliminate flashing.
11802 (js2-clear-face (point-min) (point-max))
11803 ;; Have to reverse the recorded fontifications list so that errors
11804 ;; and warnings overwrite the normal fontifications.
11805 (dolist (f (nreverse js2-mode-fontifications))
11806 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11807 (setq js2-mode-fontifications nil))
11808 (dolist (p js2-mode-deferred-properties)
11809 (apply #'put-text-property p))
11810 (setq js2-mode-deferred-properties nil))
11811
11812 (defun js2-mode-show-errors ()
11813 "Highlight syntax errors."
11814 (when js2-mode-show-parse-errors
11815 (dolist (e (js2-ast-root-errors js2-mode-ast))
11816 (js2-mode-show-warn-or-err e 'js2-error))))
11817
11818 (defun js2-mode-remove-suppressed-warnings ()
11819 "Take suppressed warnings out of the AST warnings list.
11820 This ensures that the counts and `next-error' are correct."
11821 (setf (js2-ast-root-warnings js2-mode-ast)
11822 (js2-delete-if
11823 (lambda (e)
11824 (let ((key (caar e)))
11825 (or
11826 (and (not js2-strict-trailing-comma-warning)
11827 (string-match "trailing\\.comma" key))
11828 (and (not js2-strict-cond-assign-warning)
11829 (string= key "msg.equal.as.assign"))
11830 (and js2-missing-semi-one-line-override
11831 (string= key "msg.missing.semi")
11832 (let* ((beg (cl-second e))
11833 (node (js2-node-at-point beg))
11834 (fn (js2-mode-find-parent-fn node))
11835 (body (and fn (js2-function-node-body fn)))
11836 (lc (and body (js2-node-abs-pos body)))
11837 (rc (and lc (+ lc (js2-node-len body)))))
11838 (and fn
11839 (or (null body)
11840 (save-excursion
11841 (goto-char beg)
11842 (and (js2-same-line lc)
11843 (js2-same-line rc))))))))))
11844 (js2-ast-root-warnings js2-mode-ast))))
11845
11846 (defun js2-mode-show-warnings ()
11847 "Highlight strict-mode warnings."
11848 (when js2-mode-show-strict-warnings
11849 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11850 (js2-mode-show-warn-or-err e 'js2-warning))))
11851
11852 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11853 "Called by point-motion hooks.
11854 ARG1, ARG2 and ARG3 have different values depending on whether this function
11855 was found on `point-entered' or in `cursor-sensor-functions'."
11856 (let* ((new-point (if (windowp arg1)
11857 ;; Called from cursor-sensor-functions.
11858 (window-point arg1)
11859 ;; Called from point-left.
11860 arg2))
11861 (msg (get-text-property new-point 'help-echo)))
11862 (when (and (stringp msg)
11863 (not (active-minibuffer-window))
11864 (not (current-message)))
11865 (message msg))))
11866
11867 (defun js2-line-break (&optional _soft)
11868 "Break line at point and indent, continuing comment if within one.
11869 If inside a string, and `js2-concat-multiline-strings' is not
11870 nil, turn it into concatenation."
11871 (interactive)
11872 (let ((parse-status (syntax-ppss)))
11873 (cond
11874 ;; Check if we're inside a string.
11875 ((nth 3 parse-status)
11876 (if js2-concat-multiline-strings
11877 (js2-mode-split-string parse-status)
11878 (insert "\n")))
11879 ;; Check if inside a block comment.
11880 ((nth 4 parse-status)
11881 (js2-mode-extend-comment (nth 8 parse-status)))
11882 (t
11883 (newline-and-indent)))))
11884
11885 (defun js2-mode-split-string (parse-status)
11886 "Turn a newline in mid-string into a string concatenation.
11887 PARSE-STATUS is as documented in `parse-partial-sexp'."
11888 (let* ((quote-char (nth 3 parse-status))
11889 (at-eol (eq js2-concat-multiline-strings 'eol)))
11890 (insert quote-char)
11891 (insert (if at-eol " +\n" "\n"))
11892 (unless at-eol
11893 (insert "+ "))
11894 (js2-indent-line)
11895 (insert quote-char)
11896 (when (eolp)
11897 (insert quote-char)
11898 (backward-char 1))))
11899
11900 (defun js2-mode-extend-comment (start-pos)
11901 "Indent the line and, when inside a comment block, add comment prefix."
11902 (let (star single col first-line needs-close)
11903 (save-excursion
11904 (back-to-indentation)
11905 (when (< (point) start-pos)
11906 (goto-char start-pos))
11907 (cond
11908 ((looking-at "\\*[^/]")
11909 (setq star t
11910 col (current-column)))
11911 ((looking-at "/\\*")
11912 (setq star t
11913 first-line t
11914 col (1+ (current-column))))
11915 ((looking-at "//")
11916 (setq single t
11917 col (current-column)))))
11918 ;; Heuristic for whether we need to close the comment:
11919 ;; if we've got a parse error here, assume it's an unterminated
11920 ;; comment.
11921 (setq needs-close
11922 (or
11923 (get-char-property (1- (point)) 'js2-error)
11924 ;; The heuristic above doesn't work well when we're
11925 ;; creating a comment and there's another one downstream,
11926 ;; as our parser thinks this one ends at the end of the
11927 ;; next one. (You can have a /* inside a js block comment.)
11928 ;; So just close it if the next non-ws char isn't a *.
11929 (and first-line
11930 (eolp)
11931 (save-excursion
11932 (skip-chars-forward " \t\r\n")
11933 (not (eq (char-after) ?*))))))
11934 (delete-horizontal-space)
11935 (insert "\n")
11936 (cond
11937 (star
11938 (indent-to col)
11939 (insert "* ")
11940 (if (and first-line needs-close)
11941 (save-excursion
11942 (insert "\n")
11943 (indent-to col)
11944 (insert "*/"))))
11945 (single
11946 (indent-to col)
11947 (insert "// ")))
11948 ;; Don't need to extend the comment after all.
11949 (js2-indent-line)))
11950
11951 (defun js2-beginning-of-line ()
11952 "Toggle point between bol and first non-whitespace char in line.
11953 Also moves past comment delimiters when inside comments."
11954 (interactive)
11955 (let (node)
11956 (cond
11957 ((bolp)
11958 (back-to-indentation))
11959 ((looking-at "//")
11960 (skip-chars-forward "/ \t"))
11961 ((and (eq (char-after) ?*)
11962 (setq node (js2-comment-at-point))
11963 (memq (js2-comment-node-format node) '(jsdoc block))
11964 (save-excursion
11965 (skip-chars-backward " \t")
11966 (bolp)))
11967 (skip-chars-forward "\* \t"))
11968 (t
11969 (goto-char (point-at-bol))))))
11970
11971 (defun js2-end-of-line ()
11972 "Toggle point between eol and last non-whitespace char in line."
11973 (interactive)
11974 (if (eolp)
11975 (skip-chars-backward " \t")
11976 (goto-char (point-at-eol))))
11977
11978 (defun js2-mode-wait-for-parse (callback)
11979 "Invoke CALLBACK when parsing is finished.
11980 If parsing is already finished, calls CALLBACK immediately."
11981 (if (not js2-mode-buffer-dirty-p)
11982 (funcall callback)
11983 (push callback js2-mode-pending-parse-callbacks)
11984 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11985
11986 (defun js2-mode-parse-finished ()
11987 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11988 ;; We can't let errors propagate up, since it prevents the
11989 ;; `js2-parse' method from completing normally and returning
11990 ;; the ast, which makes things mysteriously not work right.
11991 (unwind-protect
11992 (dolist (cb js2-mode-pending-parse-callbacks)
11993 (condition-case err
11994 (funcall cb)
11995 (error (message "%s" err))))
11996 (setq js2-mode-pending-parse-callbacks nil)))
11997
11998 (defun js2-mode-flag-region (from to flag)
11999 "Hide or show text from FROM to TO, according to FLAG.
12000 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
12001 Returns the created overlay if FLAG is non-nil."
12002 (remove-overlays from to 'invisible 'js2-outline)
12003 (when flag
12004 (let ((o (make-overlay from to)))
12005 (overlay-put o 'invisible 'js2-outline)
12006 (overlay-put o 'isearch-open-invisible
12007 'js2-isearch-open-invisible)
12008 o)))
12009
12010 ;; Function to be set as an outline-isearch-open-invisible' property
12011 ;; to the overlay that makes the outline invisible (see
12012 ;; `js2-mode-flag-region').
12013 (defun js2-isearch-open-invisible (_overlay)
12014 ;; We rely on the fact that isearch places point on the matched text.
12015 (js2-mode-show-element))
12016
12017 (defun js2-mode-invisible-overlay-bounds (&optional pos)
12018 "Return cons cell of bounds of folding overlay at POS.
12019 Returns nil if not found."
12020 (let ((overlays (overlays-at (or pos (point))))
12021 o)
12022 (while (and overlays
12023 (not o))
12024 (if (overlay-get (car overlays) 'invisible)
12025 (setq o (car overlays))
12026 (setq overlays (cdr overlays))))
12027 (if o
12028 (cons (overlay-start o) (overlay-end o)))))
12029
12030 (defun js2-mode-function-at-point (&optional pos)
12031 "Return the innermost function node enclosing current point.
12032 Returns nil if point is not in a function."
12033 (let ((node (js2-node-at-point pos)))
12034 (while (and node (not (js2-function-node-p node)))
12035 (setq node (js2-node-parent node)))
12036 (if (js2-function-node-p node)
12037 node)))
12038
12039 (defun js2-mode-toggle-element ()
12040 "Hide or show the foldable element at the point."
12041 (interactive)
12042 (let (comment fn pos)
12043 (save-excursion
12044 (cond
12045 ;; /* ... */ comment?
12046 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
12047 (if (js2-mode-invisible-overlay-bounds
12048 (setq pos (+ 3 (js2-node-abs-pos comment))))
12049 (progn
12050 (goto-char pos)
12051 (js2-mode-show-element))
12052 (js2-mode-hide-element)))
12053 ;; //-comment?
12054 ((save-excursion
12055 (back-to-indentation)
12056 (looking-at js2-mode-//-comment-re))
12057 (js2-mode-toggle-//-comment))
12058 ;; function?
12059 ((setq fn (js2-mode-function-at-point))
12060 (setq pos (and (js2-function-node-body fn)
12061 (js2-node-abs-pos (js2-function-node-body fn))))
12062 (goto-char (1+ pos))
12063 (if (js2-mode-invisible-overlay-bounds)
12064 (js2-mode-show-element)
12065 (js2-mode-hide-element)))
12066 (t
12067 (message "Nothing at point to hide or show"))))))
12068
12069 (defun js2-mode-hide-element ()
12070 "Fold/hide contents of a block, showing ellipses.
12071 Show the hidden text with \\[js2-mode-show-element]."
12072 (interactive)
12073 (if js2-mode-buffer-dirty-p
12074 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12075 (let (node body beg end)
12076 (cond
12077 ((js2-mode-invisible-overlay-bounds)
12078 (message "already hidden"))
12079 (t
12080 (setq node (js2-node-at-point))
12081 (cond
12082 ((js2-block-comment-p node)
12083 (js2-mode-hide-comment node))
12084 (t
12085 (while (and node (not (js2-function-node-p node)))
12086 (setq node (js2-node-parent node)))
12087 (if (and node
12088 (setq body (js2-function-node-body node)))
12089 (progn
12090 (setq beg (js2-node-abs-pos body)
12091 end (+ beg (js2-node-len body)))
12092 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12093 (message "No collapsable element found at point"))))))))
12094
12095 (defun js2-mode-show-element ()
12096 "Show the hidden element at current point."
12097 (interactive)
12098 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12099 (if bounds
12100 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12101 (message "Nothing to un-hide"))))
12102
12103 (defun js2-mode-show-all ()
12104 "Show all of the text in the buffer."
12105 (interactive)
12106 (js2-mode-flag-region (point-min) (point-max) nil))
12107
12108 (defun js2-mode-toggle-hide-functions ()
12109 (interactive)
12110 (if js2-mode-functions-hidden
12111 (js2-mode-show-functions)
12112 (js2-mode-hide-functions)))
12113
12114 (defun js2-mode-hide-functions ()
12115 "Hides all non-nested function bodies in the buffer.
12116 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12117 to open an individual entry."
12118 (interactive)
12119 (if js2-mode-buffer-dirty-p
12120 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12121 (if (null js2-mode-ast)
12122 (message "Oops - parsing failed")
12123 (setq js2-mode-functions-hidden t)
12124 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12125
12126 (defun js2-mode-function-hider (n endp)
12127 (when (not endp)
12128 (let ((tt (js2-node-type n))
12129 body beg end)
12130 (cond
12131 ((and (= tt js2-FUNCTION)
12132 (setq body (js2-function-node-body n)))
12133 (setq beg (js2-node-abs-pos body)
12134 end (+ beg (js2-node-len body)))
12135 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12136 nil) ; don't process children of function
12137 (t
12138 t))))) ; keep processing other AST nodes
12139
12140 (defun js2-mode-show-functions ()
12141 "Un-hide any folded function bodies in the buffer."
12142 (interactive)
12143 (setq js2-mode-functions-hidden nil)
12144 (save-excursion
12145 (goto-char (point-min))
12146 (while (/= (goto-char (next-overlay-change (point)))
12147 (point-max))
12148 (dolist (o (overlays-at (point)))
12149 (when (and (overlay-get o 'invisible)
12150 (not (overlay-get o 'comment)))
12151 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12152
12153 (defun js2-mode-hide-comment (n)
12154 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12155 3 ; /**
12156 2)) ; /*
12157 (beg (+ (js2-node-abs-pos n) head))
12158 (end (- (+ beg (js2-node-len n)) head 2))
12159 (o (js2-mode-flag-region beg end 'hide)))
12160 (overlay-put o 'comment t)))
12161
12162 (defun js2-mode-toggle-hide-comments ()
12163 "Folds all block comments in the buffer.
12164 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12165 to open an individual entry."
12166 (interactive)
12167 (if js2-mode-comments-hidden
12168 (js2-mode-show-comments)
12169 (js2-mode-hide-comments)))
12170
12171 (defun js2-mode-hide-comments ()
12172 (interactive)
12173 (if js2-mode-buffer-dirty-p
12174 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12175 (if (null js2-mode-ast)
12176 (message "Oops - parsing failed")
12177 (setq js2-mode-comments-hidden t)
12178 (dolist (n (js2-ast-root-comments js2-mode-ast))
12179 (when (js2-block-comment-p n)
12180 (js2-mode-hide-comment n)))
12181 (js2-mode-hide-//-comments)))
12182
12183 (defun js2-mode-extend-//-comment (direction)
12184 "Find start or end of a block of similar //-comment lines.
12185 DIRECTION is -1 to look back, 1 to look forward.
12186 INDENT is the indentation level to match.
12187 Returns the end-of-line position of the furthest adjacent
12188 //-comment line with the same indentation as the current line.
12189 If there is no such matching line, returns current end of line."
12190 (let ((pos (point-at-eol))
12191 (indent (current-indentation)))
12192 (save-excursion
12193 (while (and (zerop (forward-line direction))
12194 (looking-at js2-mode-//-comment-re)
12195 (eq indent (length (match-string 1))))
12196 (setq pos (point-at-eol)))
12197 pos)))
12198
12199 (defun js2-mode-hide-//-comments ()
12200 "Fold adjacent 1-line comments, showing only snippet of first one."
12201 (let (beg end)
12202 (save-excursion
12203 (goto-char (point-min))
12204 (while (re-search-forward js2-mode-//-comment-re nil t)
12205 (setq beg (point)
12206 end (js2-mode-extend-//-comment 1))
12207 (unless (eq beg end)
12208 (overlay-put (js2-mode-flag-region beg end 'hide)
12209 'comment t))
12210 (goto-char end)
12211 (forward-char 1)))))
12212
12213 (defun js2-mode-toggle-//-comment ()
12214 "Fold or un-fold any multi-line //-comment at point.
12215 Caller should have determined that this line starts with a //-comment."
12216 (let* ((beg (point-at-eol))
12217 (end beg))
12218 (save-excursion
12219 (goto-char end)
12220 (if (js2-mode-invisible-overlay-bounds)
12221 (js2-mode-show-element)
12222 ;; else hide the comment
12223 (setq beg (js2-mode-extend-//-comment -1)
12224 end (js2-mode-extend-//-comment 1))
12225 (unless (eq beg end)
12226 (overlay-put (js2-mode-flag-region beg end 'hide)
12227 'comment t))))))
12228
12229 (defun js2-mode-show-comments ()
12230 "Un-hide any hidden comments, leaving other hidden elements alone."
12231 (interactive)
12232 (setq js2-mode-comments-hidden nil)
12233 (save-excursion
12234 (goto-char (point-min))
12235 (while (/= (goto-char (next-overlay-change (point)))
12236 (point-max))
12237 (dolist (o (overlays-at (point)))
12238 (when (overlay-get o 'comment)
12239 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12240
12241 (defun js2-mode-display-warnings-and-errors ()
12242 "Turn on display of warnings and errors."
12243 (interactive)
12244 (setq js2-mode-show-parse-errors t
12245 js2-mode-show-strict-warnings t)
12246 (js2-reparse 'force))
12247
12248 (defun js2-mode-hide-warnings-and-errors ()
12249 "Turn off display of warnings and errors."
12250 (interactive)
12251 (setq js2-mode-show-parse-errors nil
12252 js2-mode-show-strict-warnings nil)
12253 (js2-reparse 'force))
12254
12255 (defun js2-mode-toggle-warnings-and-errors ()
12256 "Toggle the display of warnings and errors.
12257 Some users don't like having warnings/errors reported while they type."
12258 (interactive)
12259 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12260 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12261 (if (called-interactively-p 'any)
12262 (message "warnings and errors %s"
12263 (if js2-mode-show-parse-errors
12264 "enabled"
12265 "disabled")))
12266 (js2-reparse 'force))
12267
12268 (defun js2-mode-customize ()
12269 (interactive)
12270 (customize-group 'js2-mode))
12271
12272 (defun js2-mode-forward-sexp (&optional arg)
12273 "Move forward across one statement or balanced expression.
12274 With ARG, do it that many times. Negative arg -N means
12275 move backward across N balanced expressions."
12276 (interactive "p")
12277 (setq arg (or arg 1))
12278 (save-restriction
12279 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12280 (js2-reparse)
12281 (let (forward-sexp-function
12282 node (start (point)) pos lp rp child)
12283 (cond
12284 ;; backward-sexp
12285 ;; could probably make this better for some cases:
12286 ;; - if in statement block (e.g. function body), go to parent
12287 ;; - infix exprs like (foo in bar) - maybe go to beginning
12288 ;; of infix expr if in the right-side expression?
12289 ((and arg (cl-minusp arg))
12290 (dotimes (_ (- arg))
12291 (js2-backward-sws)
12292 (forward-char -1) ; Enter the node we backed up to.
12293 (when (setq node (js2-node-at-point (point) t))
12294 (setq pos (js2-node-abs-pos node))
12295 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12296 (setq lp (car parens)
12297 rp (cdr parens)))
12298 (when (and lp (> start lp))
12299 (if (and rp (<= start rp))
12300 ;; Between parens, check if there's a child node we can jump.
12301 (when (setq child (js2-node-closest-child node (point) lp t))
12302 (setq pos (js2-node-abs-pos child)))
12303 ;; Before both parens.
12304 (setq pos lp)))
12305 (let ((state (parse-partial-sexp start pos)))
12306 (goto-char (if (not (zerop (car state)))
12307 ;; Stumble at the unbalanced paren if < 0, or
12308 ;; jump a bit further if > 0.
12309 (scan-sexps start -1)
12310 pos))))
12311 (unless pos (goto-char (point-min)))))
12312 (t
12313 ;; forward-sexp
12314 (dotimes (_ arg)
12315 (js2-forward-sws)
12316 (when (setq node (js2-node-at-point (point) t))
12317 (setq pos (js2-node-abs-pos node))
12318 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12319 (setq lp (car parens)
12320 rp (cdr parens)))
12321 (or
12322 (when (and rp (<= start rp))
12323 (if (> start lp)
12324 (when (setq child (js2-node-closest-child node (point) rp))
12325 (setq pos (js2-node-abs-end child)))
12326 (setq pos (1+ rp))))
12327 ;; No parens or child nodes, looks for the end of the current node.
12328 (cl-incf pos (js2-node-len
12329 (if (js2-expr-stmt-node-p (js2-node-parent node))
12330 ;; Stop after the semicolon.
12331 (js2-node-parent node)
12332 node))))
12333 (let ((state (save-excursion (parse-partial-sexp start pos))))
12334 (goto-char (if (not (zerop (car state)))
12335 (scan-sexps start 1)
12336 pos))))
12337 (unless pos (goto-char (point-max)))))))))
12338
12339 (defun js2-mode-forward-sexp-parens (node abs-pos)
12340 "Return a cons cell with positions of main parens in NODE."
12341 (cond
12342 ((or (js2-array-node-p node)
12343 (js2-object-node-p node)
12344 (js2-comp-node-p node)
12345 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12346 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12347 ((js2-paren-expr-node-p node)
12348 (let ((lp (js2-node-lp node))
12349 (rp (js2-node-rp node)))
12350 (cons (when lp (+ abs-pos lp))
12351 (when rp (+ abs-pos rp)))))))
12352
12353 (defun js2-node-closest-child (parent point limit &optional before)
12354 (let* ((parent-pos (js2-node-abs-pos parent))
12355 (rpoint (- point parent-pos))
12356 (rlimit (- limit parent-pos))
12357 (min (min rpoint rlimit))
12358 (max (max rpoint rlimit))
12359 found)
12360 (catch 'done
12361 (js2-visit-ast
12362 parent
12363 (lambda (node _end-p)
12364 (if (eq node parent)
12365 t
12366 (let ((pos (js2-node-pos node)) ;; Both relative values.
12367 (end (+ (js2-node-pos node) (js2-node-len node))))
12368 (when (and (>= pos min) (<= end max)
12369 (if before (< pos rpoint) (> end rpoint)))
12370 (setq found node))
12371 (when (> end rpoint)
12372 (throw 'done nil)))
12373 nil))))
12374 found))
12375
12376 (defun js2-errors ()
12377 "Return a list of errors found."
12378 (and js2-mode-ast
12379 (js2-ast-root-errors js2-mode-ast)))
12380
12381 (defun js2-warnings ()
12382 "Return a list of warnings found."
12383 (and js2-mode-ast
12384 (js2-ast-root-warnings js2-mode-ast)))
12385
12386 (defun js2-have-errors-p ()
12387 "Return non-nil if any parse errors or warnings were found."
12388 (or (js2-errors) (js2-warnings)))
12389
12390 (defun js2-errors-and-warnings ()
12391 "Return a copy of the concatenated errors and warnings lists.
12392 They are appended: first the errors, then the warnings.
12393 Entries are of the form (MSG BEG END)."
12394 (when js2-mode-ast
12395 (append (js2-ast-root-errors js2-mode-ast)
12396 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12397
12398 (defun js2-next-error (&optional arg reset)
12399 "Move to next parse error.
12400 Typically invoked via \\[next-error].
12401 ARG is the number of errors, forward or backward, to move.
12402 RESET means start over from the beginning."
12403 (interactive "p")
12404 (if (not (or (js2-errors) (js2-warnings)))
12405 (message "No errors")
12406 (when reset
12407 (goto-char (point-min)))
12408 (let* ((errs (js2-errors-and-warnings))
12409 (continue t)
12410 (start (point))
12411 (count (or arg 1))
12412 (backward (cl-minusp count))
12413 (sorter (if backward '> '<))
12414 (stopper (if backward '< '>))
12415 (count (abs count))
12416 all-errs err)
12417 ;; Sort by start position.
12418 (setq errs (sort errs (lambda (e1 e2)
12419 (funcall sorter (cl-second e1) (cl-second e2))))
12420 all-errs errs)
12421 ;; Find nth error with pos > start.
12422 (while (and errs continue)
12423 (when (funcall stopper (cl-cadar errs) start)
12424 (setq err (car errs))
12425 (if (zerop (cl-decf count))
12426 (setq continue nil)))
12427 (setq errs (cdr errs)))
12428 ;; Clear for `js2-echo-error'.
12429 (message nil)
12430 (if err
12431 (goto-char (cl-second err))
12432 ;; Wrap around to first error.
12433 (goto-char (cl-second (car all-errs)))
12434 ;; If we were already on it, echo msg again.
12435 (if (= (point) start)
12436 (js2-echo-error (point) (point)))))))
12437
12438 (defun js2-down-mouse-3 ()
12439 "Make right-click move the point to the click location.
12440 This makes right-click context menu operations a bit more intuitive.
12441 The point will not move if the region is active, however, to avoid
12442 destroying the region selection."
12443 (interactive)
12444 (when (and js2-move-point-on-right-click
12445 (not mark-active))
12446 (let ((e last-input-event))
12447 (ignore-errors
12448 (goto-char (cl-cadadr e))))))
12449
12450 (defun js2-mode-create-imenu-index ()
12451 "Return an alist for `imenu--index-alist'."
12452 ;; This is built up in `js2-parse-record-imenu' during parsing.
12453 (when js2-mode-ast
12454 ;; if we have an ast but no recorder, they're requesting a rescan
12455 (unless js2-imenu-recorder
12456 (js2-reparse 'force))
12457 (prog1
12458 (js2-build-imenu-index)
12459 (setq js2-imenu-recorder nil
12460 js2-imenu-function-map nil))))
12461
12462 (defun js2-mode-find-tag ()
12463 "Replacement for `find-tag-default'.
12464 `find-tag-default' returns a ridiculous answer inside comments."
12465 (let (beg end)
12466 (save-excursion
12467 (if (looking-at "\\_>")
12468 (setq beg (progn (forward-symbol -1) (point))
12469 end (progn (forward-symbol 1) (point)))
12470 (setq beg (progn (forward-symbol 1) (point))
12471 end (progn (forward-symbol -1) (point))))
12472 (replace-regexp-in-string
12473 "[\"']" ""
12474 (buffer-substring-no-properties beg end)))))
12475
12476 (defun js2-mode-forward-sibling ()
12477 "Move to the end of the sibling following point in parent.
12478 Returns non-nil if successful, or nil if there was no following sibling."
12479 (let* ((node (js2-node-at-point))
12480 (parent (js2-mode-find-enclosing-fn node))
12481 sib)
12482 (when (setq sib (js2-node-find-child-after (point) parent))
12483 (goto-char (+ (js2-node-abs-pos sib)
12484 (js2-node-len sib))))))
12485
12486 (defun js2-mode-backward-sibling ()
12487 "Move to the beginning of the sibling node preceding point in parent.
12488 Parent is defined as the enclosing script or function."
12489 (let* ((node (js2-node-at-point))
12490 (parent (js2-mode-find-enclosing-fn node))
12491 sib)
12492 (when (setq sib (js2-node-find-child-before (point) parent))
12493 (goto-char (js2-node-abs-pos sib)))))
12494
12495 (defun js2-beginning-of-defun (&optional arg)
12496 "Go to line on which current function starts, and return t on success.
12497 If we're not in a function or already at the beginning of one, go
12498 to beginning of previous script-level element.
12499 With ARG N, do that N times. If N is negative, move forward."
12500 (setq arg (or arg 1))
12501 (if (cl-plusp arg)
12502 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12503 (when (cond
12504 ((js2-function-node-p parent)
12505 (goto-char (js2-node-abs-pos parent)))
12506 (t
12507 (js2-mode-backward-sibling)))
12508 (if (> arg 1)
12509 (js2-beginning-of-defun (1- arg))
12510 t)))
12511 (when (js2-end-of-defun)
12512 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12513
12514 (defun js2-end-of-defun ()
12515 "Go to the char after the last position of the current function
12516 or script-level element."
12517 (let* ((node (js2-node-at-point))
12518 (parent (or (and (js2-function-node-p node) node)
12519 (js2-node-parent-script-or-fn node)))
12520 script)
12521 (unless (js2-function-node-p parent)
12522 ;; Use current script-level node, or, if none, the next one.
12523 (setq script (or parent node)
12524 parent (js2-node-find-child-before (point) script))
12525 (when (or (null parent)
12526 (>= (point) (+ (js2-node-abs-pos parent)
12527 (js2-node-len parent))))
12528 (setq parent (js2-node-find-child-after (point) script))))
12529 (when parent
12530 (goto-char (+ (js2-node-abs-pos parent)
12531 (js2-node-len parent))))))
12532
12533 (defun js2-mark-defun (&optional allow-extend)
12534 "Put mark at end of this function, point at beginning.
12535 The function marked is the one that contains point.
12536
12537 Interactively, if this command is repeated,
12538 or (in Transient Mark mode) if the mark is active,
12539 it marks the next defun after the ones already marked."
12540 (interactive "p")
12541 (let (extended)
12542 (when (and allow-extend
12543 (or (and (eq last-command this-command) (mark t))
12544 (and transient-mark-mode mark-active)))
12545 (let ((sib (save-excursion
12546 (goto-char (mark))
12547 (if (js2-mode-forward-sibling)
12548 (point)))))
12549 (if sib
12550 (progn
12551 (set-mark sib)
12552 (setq extended t))
12553 ;; no more siblings - try extending to enclosing node
12554 (goto-char (mark t)))))
12555 (when (not extended)
12556 (let ((node (js2-node-at-point (point) t)) ; skip comments
12557 ast fn stmt parent beg end)
12558 (when (js2-ast-root-p node)
12559 (setq ast node
12560 node (or (js2-node-find-child-after (point) node)
12561 (js2-node-find-child-before (point) node))))
12562 ;; only mark whole buffer if we can't find any children
12563 (if (null node)
12564 (setq node ast))
12565 (if (js2-function-node-p node)
12566 (setq parent node)
12567 (setq fn (js2-mode-find-enclosing-fn node)
12568 stmt (if (or (null fn)
12569 (js2-ast-root-p fn))
12570 (js2-mode-find-first-stmt node))
12571 parent (or stmt fn)))
12572 (setq beg (js2-node-abs-pos parent)
12573 end (+ beg (js2-node-len parent)))
12574 (push-mark beg)
12575 (goto-char end)
12576 (exchange-point-and-mark)))))
12577
12578 (defun js2-narrow-to-defun ()
12579 "Narrow to the function enclosing point."
12580 (interactive)
12581 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12582 (fn (if (js2-script-node-p node)
12583 node
12584 (js2-mode-find-enclosing-fn node)))
12585 (beg (js2-node-abs-pos fn)))
12586 (unless (js2-ast-root-p fn)
12587 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12588
12589 (defun js2-jump-to-definition (&optional arg)
12590 "Jump to the definition of an object's property, variable or function."
12591 (interactive "P")
12592 (if (eval-when-compile (fboundp 'xref-push-marker-stack))
12593 (xref-push-marker-stack)
12594 (ring-insert find-tag-marker-ring (point-marker)))
12595 (js2-reparse)
12596 (let* ((node (js2-node-at-point))
12597 (parent (js2-node-parent node))
12598 (names (if (js2-prop-get-node-p parent)
12599 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12600 (cl-loop for n in temp
12601 with result = '()
12602 do (push n result)
12603 until (equal node n)
12604 finally return result)))))
12605 node-init)
12606 (unless (and (js2-name-node-p node)
12607 (not (js2-var-init-node-p parent))
12608 (not (js2-function-node-p parent)))
12609 (error "Node is not a supported jump node"))
12610 (push (or (and names (pop names))
12611 (unless (and (js2-object-prop-node-p parent)
12612 (eq node (js2-object-prop-node-left parent)))
12613 node)) names)
12614 (setq node-init (js2-search-scope node names))
12615
12616 ;; todo: display list of results in buffer
12617 ;; todo: group found references by buffer
12618 (unless node-init
12619 (switch-to-buffer
12620 (catch 'found
12621 (unless arg
12622 (mapc (lambda (b)
12623 (with-current-buffer b
12624 (when (derived-mode-p 'js2-mode)
12625 (setq node-init (js2-search-scope js2-mode-ast names))
12626 (if node-init
12627 (throw 'found b)))))
12628 (buffer-list)))
12629 nil)))
12630 (setq node-init (if (listp node-init) (car node-init) node-init))
12631 (unless node-init
12632 (pop-tag-mark)
12633 (error "No jump location found"))
12634 (goto-char (js2-node-abs-pos node-init))))
12635
12636 (defun js2-search-object (node name-node)
12637 "Check if object NODE contains element with NAME-NODE."
12638 (cl-assert (js2-object-node-p node))
12639 ;; Only support name-node and nodes for the time being
12640 (cl-loop for elem in (js2-object-node-elems node)
12641 for left = (js2-object-prop-node-left elem)
12642 if (or (and (js2-name-node-p left)
12643 (equal (js2-name-node-name name-node)
12644 (js2-name-node-name left)))
12645 (and (js2-string-node-p left)
12646 (string= (js2-name-node-name name-node)
12647 (js2-string-node-value left))))
12648 return elem))
12649
12650 (defun js2-search-object-for-prop (object prop-names)
12651 "Return node in OBJECT that matches PROP-NAMES or nil.
12652 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12653 i.e. ('name' 'value') = {name : { value: 3}}"
12654 (let (node
12655 (temp-object object)
12656 (temp t) ;temporay node
12657 (names prop-names))
12658 (while (and temp names (js2-object-node-p temp-object))
12659 (setq temp (js2-search-object temp-object (pop names)))
12660 (and (setq node temp)
12661 (setq temp-object (js2-object-prop-node-right temp))))
12662 (unless names node)))
12663
12664 (defun js2-search-scope (node names)
12665 "Searches NODE scope for jump location matching NAMES.
12666 NAMES is a list of property values to search for. For functions
12667 and variables NAMES will contain one element."
12668 (let (node-init
12669 (val (js2-name-node-name (car names))))
12670 (setq node-init (js2-get-symbol-declaration node val))
12671
12672 (when (> (length names) 1)
12673
12674 ;; Check var declarations
12675 (when (and node-init (string= val (js2-name-node-name node-init)))
12676 (let ((parent (js2-node-parent node-init))
12677 (temp-names names))
12678 (pop temp-names) ;; First element is var name
12679 (setq node-init (when (js2-var-init-node-p parent)
12680 (js2-search-object-for-prop
12681 (js2-var-init-node-initializer parent)
12682 temp-names)))))
12683
12684 ;; Check all assign nodes
12685 (js2-visit-ast
12686 js2-mode-ast
12687 (lambda (node endp)
12688 (unless endp
12689 (if (js2-assign-node-p node)
12690 (let ((left (js2-assign-node-left node))
12691 (right (js2-assign-node-right node))
12692 (temp-names names))
12693 (when (js2-prop-get-node-p left)
12694 (let* ((prop-list (js2-compute-nested-prop-get left))
12695 (found (cl-loop for prop in prop-list
12696 until (not (string= (js2-name-node-name
12697 (pop temp-names))
12698 (js2-name-node-name prop)))
12699 if (not temp-names) return prop))
12700 (found-node (or found
12701 (when (js2-object-node-p right)
12702 (js2-search-object-for-prop right
12703 temp-names)))))
12704 (if found-node (push found-node node-init))))))
12705 t))))
12706 node-init))
12707
12708 (defun js2-get-symbol-declaration (node name)
12709 "Find scope for NAME from NODE."
12710 (let ((scope (js2-get-defining-scope
12711 (or (js2-node-get-enclosing-scope node)
12712 node) name)))
12713 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12714
12715 (provide 'js2-mode)
12716
12717 ;;; js2-mode.el ends here