]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode/js2-mode.el
Fix some quoting problems in doc strings
[gnu-emacs-elpa] / packages / js2-mode / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2016 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: 20160623
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-assume-strict nil
281 "Non-nil to start files in strict mode automatically."
282 :type 'boolean
283 :group 'js2-mode)
284
285 (defcustom js2-mode-show-strict-warnings t
286 "Non-nil to emit Ecma strict-mode warnings.
287 Some of the warnings can be individually disabled by other flags,
288 even if this flag is non-nil."
289 :type 'boolean
290 :group 'js2-mode)
291
292 (defcustom js2-strict-trailing-comma-warning t
293 "Non-nil to warn about trailing commas in array literals.
294 Ecma-262-5.1 allows them, but older versions of IE raise an error."
295 :type 'boolean
296 :group 'js2-mode)
297
298 (defcustom js2-strict-missing-semi-warning t
299 "Non-nil to warn about semicolon auto-insertion after statement.
300 Technically this is legal per Ecma-262, but some style guides disallow
301 depending on it."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-missing-semi-one-line-override nil
306 "Non-nil to permit missing semicolons in one-line functions.
307 In one-liner functions such as `function identity(x) {return x}'
308 people often omit the semicolon for a cleaner look. If you are
309 such a person, you can suppress the missing-semicolon warning
310 by setting this variable to t."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-strict-inconsistent-return-warning t
315 "Non-nil to warn about mixing returns with value-returns.
316 It's perfectly legal to have a `return' and a `return foo' in the
317 same function, but it's often an indicator of a bug, and it also
318 interferes with type inference (in systems that support it.)"
319 :type 'boolean
320 :group 'js2-mode)
321
322 (defcustom js2-strict-cond-assign-warning t
323 "Non-nil to warn about usage like `if (a = b)'.
324 This often should have been `==' instead of `='. If the warning
325 is enabled, you can suppress it on a per-expression basis by
326 parenthesizing the expression, e.g., `if ((a = b)) ...'."
327 :type 'boolean
328 :group 'js2-mode)
329
330 (defcustom js2-strict-var-redeclaration-warning t
331 "Non-nil to warn about redeclaring variables in a script or function."
332 :type 'boolean
333 :group 'js2-mode)
334
335 (defcustom js2-strict-var-hides-function-arg-warning t
336 "Non-nil to warn about a var decl hiding a function argument."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-skip-preprocessor-directives nil
341 "Non-nil to treat lines beginning with # as comments.
342 Useful for viewing Mozilla JavaScript source code."
343 :type 'boolean
344 :group 'js2-mode)
345
346 (defcustom js2-language-version 200
347 "Configures what JavaScript language version to recognize.
348 Currently versions 150, 160, 170, 180 and 200 are supported,
349 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
350 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
351 yield, and Array comprehensions, and 1.8 adds function closures."
352 :type 'integer
353 :group 'js2-mode)
354
355 (defcustom js2-instanceof-has-side-effects nil
356 "If non-nil, treats the instanceof operator as having side effects.
357 This is useful for xulrunner apps."
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-move-point-on-right-click t
362 "Non-nil to move insertion point when you right-click.
363 This makes right-click context menu behavior a bit more intuitive,
364 since menu operations generally apply to the point. The exception
365 is if there is a region selection, in which case the point does -not-
366 move, so cut/copy/paste can work properly.
367
368 Note that IntelliJ moves the point, and Eclipse leaves it alone,
369 so this behavior is customizable."
370 :group 'js2-mode
371 :type 'boolean)
372
373 (defcustom js2-allow-rhino-new-expr-initializer t
374 "Non-nil to support a Rhino's experimental syntactic construct.
375
376 Rhino supports the ability to follow a `new' expression with an object
377 literal, which is used to set additional properties on the new object
378 after calling its constructor. Syntax:
379
380 new <expr> [ ( arglist ) ] [initializer]
381
382 Hence, this expression:
383
384 new Object {a: 1, b: 2}
385
386 results in an Object with properties a=1 and b=2. This syntax is
387 apparently not configurable in Rhino - it's currently always enabled,
388 as of Rhino version 1.7R2."
389 :type 'boolean
390 :group 'js2-mode)
391
392 (defcustom js2-allow-member-expr-as-function-name nil
393 "Non-nil to support experimental Rhino syntax for function names.
394
395 Rhino supports an experimental syntax configured via the Rhino Context
396 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
397
398 function <member-expr> ( [ arg-list ] ) { <body> }
399
400 Where member-expr is a non-parenthesized `member expression', which
401 is anything at the grammar level of a new-expression or lower, meaning
402 any expression that does not involve infix or unary operators.
403
404 When <member-expr> is not a simple identifier, then it is syntactic
405 sugar for assigning the anonymous function to the <member-expr>. Hence,
406 this code:
407
408 function a.b().c[2] (x, y) { ... }
409
410 is rewritten as:
411
412 a.b().c[2] = function(x, y) {...}
413
414 which doesn't seem particularly useful, but Rhino permits it."
415 :type 'boolean
416 :group 'js2-mode)
417
418 ;; scanner variables
419
420 (defmacro js2-deflocal (name value &optional comment)
421 "Define a buffer-local variable NAME with VALUE and COMMENT."
422 (declare (debug defvar) (doc-string 3))
423 `(progn
424 (defvar ,name ,value ,comment)
425 (make-variable-buffer-local ',name)))
426
427 (defvar js2-EOF_CHAR -1
428 "Represents end of stream. Distinct from js2-EOF token type.")
429
430 ;; I originally used symbols to represent tokens, but Rhino uses
431 ;; ints and then sets various flag bits in them, so ints it is.
432 ;; The upshot is that we need a `js2-' prefix in front of each name.
433 (defvar js2-ERROR -1)
434 (defvar js2-EOF 0)
435 (defvar js2-EOL 1)
436 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
437 (defvar js2-LEAVEWITH 3)
438 (defvar js2-RETURN 4)
439 (defvar js2-GOTO 5)
440 (defvar js2-IFEQ 6)
441 (defvar js2-IFNE 7)
442 (defvar js2-SETNAME 8)
443 (defvar js2-BITOR 9)
444 (defvar js2-BITXOR 10)
445 (defvar js2-BITAND 11)
446 (defvar js2-EQ 12)
447 (defvar js2-NE 13)
448 (defvar js2-LT 14)
449 (defvar js2-LE 15)
450 (defvar js2-GT 16)
451 (defvar js2-GE 17)
452 (defvar js2-LSH 18)
453 (defvar js2-RSH 19)
454 (defvar js2-URSH 20)
455 (defvar js2-ADD 21) ; infix plus
456 (defvar js2-SUB 22) ; infix minus
457 (defvar js2-MUL 23)
458 (defvar js2-DIV 24)
459 (defvar js2-MOD 25)
460 (defvar js2-NOT 26)
461 (defvar js2-BITNOT 27)
462 (defvar js2-POS 28) ; unary plus
463 (defvar js2-NEG 29) ; unary minus
464 (defvar js2-NEW 30)
465 (defvar js2-DELPROP 31)
466 (defvar js2-TYPEOF 32)
467 (defvar js2-GETPROP 33)
468 (defvar js2-GETPROPNOWARN 34)
469 (defvar js2-SETPROP 35)
470 (defvar js2-GETELEM 36)
471 (defvar js2-SETELEM 37)
472 (defvar js2-CALL 38)
473 (defvar js2-NAME 39) ; an identifier
474 (defvar js2-NUMBER 40)
475 (defvar js2-STRING 41)
476 (defvar js2-NULL 42)
477 (defvar js2-THIS 43)
478 (defvar js2-FALSE 44)
479 (defvar js2-TRUE 45)
480 (defvar js2-SHEQ 46) ; shallow equality (===)
481 (defvar js2-SHNE 47) ; shallow inequality (!==)
482 (defvar js2-REGEXP 48)
483 (defvar js2-BINDNAME 49)
484 (defvar js2-THROW 50)
485 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
486 (defvar js2-IN 52)
487 (defvar js2-INSTANCEOF 53)
488 (defvar js2-LOCAL_LOAD 54)
489 (defvar js2-GETVAR 55)
490 (defvar js2-SETVAR 56)
491 (defvar js2-CATCH_SCOPE 57)
492 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
493 (defvar js2-ENUM_INIT_VALUES 59)
494 (defvar js2-ENUM_INIT_ARRAY 60)
495 (defvar js2-ENUM_NEXT 61)
496 (defvar js2-ENUM_ID 62)
497 (defvar js2-THISFN 63)
498 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
499 (defvar js2-ARRAYLIT 65) ; array literal
500 (defvar js2-OBJECTLIT 66) ; object literal
501 (defvar js2-GET_REF 67) ; *reference
502 (defvar js2-SET_REF 68) ; *reference = something
503 (defvar js2-DEL_REF 69) ; delete reference
504 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
505 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
506 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
507
508 ;; XML support
509 (defvar js2-DEFAULTNAMESPACE 73)
510 (defvar js2-ESCXMLATTR 74)
511 (defvar js2-ESCXMLTEXT 75)
512 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
513 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
514 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
515 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
516
517 (defvar js2-first-bytecode js2-ENTERWITH)
518 (defvar js2-last-bytecode js2-REF_NS_NAME)
519
520 (defvar js2-TRY 80)
521 (defvar js2-SEMI 81) ; semicolon
522 (defvar js2-LB 82) ; left and right brackets
523 (defvar js2-RB 83)
524 (defvar js2-LC 84) ; left and right curly-braces
525 (defvar js2-RC 85)
526 (defvar js2-LP 86) ; left and right parens
527 (defvar js2-RP 87)
528 (defvar js2-COMMA 88) ; comma operator
529
530 (defvar js2-ASSIGN 89) ; simple assignment (=)
531 (defvar js2-ASSIGN_BITOR 90) ; |=
532 (defvar js2-ASSIGN_BITXOR 91) ; ^=
533 (defvar js2-ASSIGN_BITAND 92) ; &=
534 (defvar js2-ASSIGN_LSH 93) ; <<=
535 (defvar js2-ASSIGN_RSH 94) ; >>=
536 (defvar js2-ASSIGN_URSH 95) ; >>>=
537 (defvar js2-ASSIGN_ADD 96) ; +=
538 (defvar js2-ASSIGN_SUB 97) ; -=
539 (defvar js2-ASSIGN_MUL 98) ; *=
540 (defvar js2-ASSIGN_DIV 99) ; /=
541 (defvar js2-ASSIGN_MOD 100) ; %=
542
543 (defvar js2-first-assign js2-ASSIGN)
544 (defvar js2-last-assign js2-ASSIGN_MOD)
545
546 (defvar js2-HOOK 101) ; conditional (?:)
547 (defvar js2-COLON 102)
548 (defvar js2-OR 103) ; logical or (||)
549 (defvar js2-AND 104) ; logical and (&&)
550 (defvar js2-INC 105) ; increment/decrement (++ --)
551 (defvar js2-DEC 106)
552 (defvar js2-DOT 107) ; member operator (.)
553 (defvar js2-FUNCTION 108) ; function keyword
554 (defvar js2-EXPORT 109) ; export keyword
555 (defvar js2-IMPORT 110) ; import keyword
556 (defvar js2-IF 111) ; if keyword
557 (defvar js2-ELSE 112) ; else keyword
558 (defvar js2-SWITCH 113) ; switch keyword
559 (defvar js2-CASE 114) ; case keyword
560 (defvar js2-DEFAULT 115) ; default keyword
561 (defvar js2-WHILE 116) ; while keyword
562 (defvar js2-DO 117) ; do keyword
563 (defvar js2-FOR 118) ; for keyword
564 (defvar js2-BREAK 119) ; break keyword
565 (defvar js2-CONTINUE 120) ; continue keyword
566 (defvar js2-VAR 121) ; var keyword
567 (defvar js2-WITH 122) ; with keyword
568 (defvar js2-CATCH 123) ; catch keyword
569 (defvar js2-FINALLY 124) ; finally keyword
570 (defvar js2-VOID 125) ; void keyword
571 (defvar js2-RESERVED 126) ; reserved keywords
572
573 (defvar js2-EMPTY 127)
574
575 ;; Types used for the parse tree - never returned by scanner.
576
577 (defvar js2-BLOCK 128) ; statement block
578 (defvar js2-LABEL 129) ; label
579 (defvar js2-TARGET 130)
580 (defvar js2-LOOP 131)
581 (defvar js2-EXPR_VOID 132) ; expression statement in functions
582 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
583 (defvar js2-JSR 134)
584 (defvar js2-SCRIPT 135) ; top-level node for entire script
585 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
586 (defvar js2-USE_STACK 137)
587 (defvar js2-SETPROP_OP 138) ; x.y op= something
588 (defvar js2-SETELEM_OP 139) ; x[y] op= something
589 (defvar js2-LOCAL_BLOCK 140)
590 (defvar js2-SET_REF_OP 141) ; *reference op= something
591
592 ;; For XML support:
593 (defvar js2-DOTDOT 142) ; member operator (..)
594 (defvar js2-COLONCOLON 143) ; namespace::name
595 (defvar js2-XML 144) ; XML type
596 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
597 (defvar js2-XMLATTR 146) ; @
598 (defvar js2-XMLEND 147)
599
600 ;; Optimizer-only tokens
601 (defvar js2-TO_OBJECT 148)
602 (defvar js2-TO_DOUBLE 149)
603
604 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
605 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
606 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
607 (defvar js2-CONST 153)
608 (defvar js2-SETCONST 154)
609 (defvar js2-SETCONSTVAR 155)
610 (defvar js2-ARRAYCOMP 156)
611 (defvar js2-LETEXPR 157)
612 (defvar js2-WITHEXPR 158)
613 (defvar js2-DEBUGGER 159)
614
615 (defvar js2-COMMENT 160)
616 (defvar js2-TRIPLEDOT 161) ; for rest parameter
617 (defvar js2-ARROW 162) ; function arrow (=>)
618 (defvar js2-CLASS 163)
619 (defvar js2-EXTENDS 164)
620 (defvar js2-SUPER 165)
621 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
622 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
623 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
624
625 (defvar js2-AWAIT 169) ; await (pseudo keyword)
626
627 (defconst js2-num-tokens (1+ js2-AWAIT))
628
629 (defconst js2-debug-print-trees nil)
630
631 ;; Rhino accepts any string or stream as input. Emacs character
632 ;; processing works best in buffers, so we'll assume the input is a
633 ;; buffer. JavaScript strings can be copied into temp buffers before
634 ;; scanning them.
635
636 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
637 ;; They're the Emacs equivalent of instance variables, more or less.
638
639 (js2-deflocal js2-ts-dirty-line nil
640 "Token stream buffer-local variable.
641 Indicates stuff other than whitespace since start of line.")
642
643 (js2-deflocal js2-ts-hit-eof nil
644 "Token stream buffer-local variable.")
645
646 ;; FIXME: Unused.
647 (js2-deflocal js2-ts-line-start 0
648 "Token stream buffer-local variable.")
649
650 (js2-deflocal js2-ts-lineno 1
651 "Token stream buffer-local variable.")
652
653 ;; FIXME: Unused.
654 (js2-deflocal js2-ts-line-end-char -1
655 "Token stream buffer-local variable.")
656
657 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
658 "Token stream buffer-local variable.
659 Current scan position.")
660
661 ;; FIXME: Unused.
662 (js2-deflocal js2-ts-is-xml-attribute nil
663 "Token stream buffer-local variable.")
664
665 (js2-deflocal js2-ts-xml-is-tag-content nil
666 "Token stream buffer-local variable.")
667
668 (js2-deflocal js2-ts-xml-open-tags-count 0
669 "Token stream buffer-local variable.")
670
671 (js2-deflocal js2-ts-string-buffer nil
672 "Token stream buffer-local variable.
673 List of chars built up while scanning various tokens.")
674
675 (cl-defstruct (js2-token
676 (:constructor nil)
677 (:constructor make-js2-token (beg)))
678 "Value returned from the token stream."
679 (type js2-EOF)
680 (beg 1)
681 (end -1)
682 (string "")
683 number
684 number-base
685 number-legacy-octal-p
686 regexp-flags
687 comment-type
688 follows-eol-p)
689
690 ;; Have to call `js2-init-scanner' to initialize the values.
691 (js2-deflocal js2-ti-tokens nil)
692 (js2-deflocal js2-ti-tokens-cursor nil)
693 (js2-deflocal js2-ti-lookahead nil)
694
695 (cl-defstruct (js2-ts-state
696 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
697 (cursor js2-ts-cursor)
698 (tokens (copy-sequence js2-ti-tokens))
699 (tokens-cursor js2-ti-tokens-cursor)
700 (lookahead js2-ti-lookahead))))
701 lineno
702 cursor
703 tokens
704 tokens-cursor
705 lookahead)
706
707 ;;; Parser variables
708
709 (js2-deflocal js2-parsed-errors nil
710 "List of errors produced during scanning/parsing.")
711
712 (js2-deflocal js2-parsed-warnings nil
713 "List of warnings produced during scanning/parsing.")
714
715 (js2-deflocal js2-recover-from-parse-errors t
716 "Non-nil to continue parsing after a syntax error.
717
718 In recovery mode, the AST will be built in full, and any error
719 nodes will be flagged with appropriate error information. If
720 this flag is nil, a syntax error will result in an error being
721 signaled.
722
723 The variable is automatically buffer-local, because different
724 modes that use the parser will need different settings.")
725
726 (js2-deflocal js2-parse-hook nil
727 "List of callbacks for receiving parsing progress.")
728
729 (defvar js2-parse-finished-hook nil
730 "List of callbacks to notify when parsing finishes.
731 Not called if parsing was interrupted.")
732
733 (js2-deflocal js2-is-eval-code nil
734 "True if we're evaluating code in a string.
735 If non-nil, the tokenizer will record the token text, and the AST nodes
736 will record their source text. Off by default for IDE modes, since the
737 text is available in the buffer.")
738
739 (defvar js2-parse-ide-mode t
740 "Non-nil if the parser is being used for `js2-mode'.
741 If non-nil, the parser will set text properties for fontification
742 and the syntax table. The value should be nil when using the
743 parser as a frontend to an interpreter or byte compiler.")
744
745 ;;; Parser instance variables (buffer-local vars for js2-parse)
746
747 (defconst js2-ti-after-eol (lsh 1 16)
748 "Flag: first token of the source line.")
749
750 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
751
752 (js2-deflocal js2-compiler-generate-debug-info t)
753 (js2-deflocal js2-compiler-use-dynamic-scope nil)
754 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
755 (js2-deflocal js2-compiler-xml-available t)
756 (js2-deflocal js2-compiler-optimization-level 0)
757 (js2-deflocal js2-compiler-generating-source t)
758 (js2-deflocal js2-compiler-strict-mode nil)
759 (js2-deflocal js2-compiler-report-warning-as-error nil)
760 (js2-deflocal js2-compiler-generate-observer-count nil)
761 (js2-deflocal js2-compiler-activation-names nil)
762
763 ;; SKIP: sourceURI
764
765 ;; There's a compileFunction method in Context.java - may need it.
766 (js2-deflocal js2-called-by-compile-function nil
767 "True if `js2-parse' was called by `js2-compile-function'.
768 Will only be used when we finish implementing the interpreter.")
769
770 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
771
772 ;; SKIP: node factory - we're going to just call functions directly,
773 ;; and eventually go to a unified AST format.
774
775 (js2-deflocal js2-nesting-of-function 0)
776
777 (js2-deflocal js2-recorded-identifiers nil
778 "Tracks identifiers found during parsing.")
779
780 (js2-deflocal js2-is-in-destructuring nil
781 "True while parsing destructuring expression.")
782
783 (js2-deflocal js2-in-use-strict-directive nil
784 "True while inside a script or function under strict mode.")
785
786 (defcustom js2-global-externs nil
787 "A list of any extern names you'd like to consider always declared.
788 This list is global and is used by all `js2-mode' files.
789 You can create buffer-local externs list using `js2-additional-externs'.
790
791 There is also a buffer-local variable `js2-default-externs',
792 which is initialized by default to include the Ecma-262 externs
793 and the standard browser externs. The three lists are all
794 checked during highlighting."
795 :type 'list
796 :group 'js2-mode)
797
798 (js2-deflocal js2-default-externs nil
799 "Default external declarations.
800
801 These are currently only used for highlighting undeclared variables,
802 which only worries about top-level (unqualified) references.
803 As js2-mode's processing improves, we will flesh out this list.
804
805 The initial value is set to `js2-ecma-262-externs', unless some
806 of the `js2-include-?-externs' variables are set to t, in which
807 case the browser, Rhino and/or Node.js externs are also included.
808
809 See `js2-additional-externs' for more information.")
810
811 (defcustom js2-include-browser-externs t
812 "Non-nil to include browser externs in the master externs list.
813 If you work on JavaScript files that are not intended for browsers,
814 such as Mozilla Rhino server-side JavaScript, set this to nil.
815 See `js2-additional-externs' for more information about externs."
816 :type 'boolean
817 :group 'js2-mode)
818
819 (defcustom js2-include-rhino-externs nil
820 "Non-nil to include Mozilla Rhino externs in the master externs list.
821 See `js2-additional-externs' for more information about externs."
822 :type 'boolean
823 :group 'js2-mode)
824
825 (defcustom js2-include-node-externs nil
826 "Non-nil to include Node.js externs in the master externs list.
827 See `js2-additional-externs' for more information about externs."
828 :type 'boolean
829 :group 'js2-mode)
830
831 (js2-deflocal js2-additional-externs nil
832 "A buffer-local list of additional external declarations.
833 It is used to decide whether variables are considered undeclared
834 for purposes of highlighting.
835
836 Each entry is a Lisp string. The string should be the fully qualified
837 name of an external entity. All externs should be added to this list,
838 so that as js2-mode's processing improves it can take advantage of them.
839
840 You may want to declare your externs in three ways.
841 First, you can add externs that are valid for all your JavaScript files.
842 You should probably do this by adding them to `js2-global-externs', which
843 is a global list used for all js2-mode files.
844
845 Next, you can add a function to `js2-init-hook' that adds additional
846 externs appropriate for the specific file, perhaps based on its path.
847 These should go in `js2-additional-externs', which is buffer-local.
848
849 Third, you can use JSLint's global declaration, as long as
850 `js2-include-jslint-globals' is non-nil, which see.
851
852 Finally, you can add a function to `js2-post-parse-callbacks',
853 which is called after parsing completes, and `js2-mode-ast' is bound to
854 the root of the parse tree. At this stage you can set up an AST
855 node visitor using `js2-visit-ast' and examine the parse tree
856 for specific import patterns that may imply the existence of
857 other externs, possibly tied to your build system. These should also
858 be added to `js2-additional-externs'.
859
860 Your post-parse callback may of course also use the simpler and
861 faster (but perhaps less robust) approach of simply scanning the
862 buffer text for your imports, using regular expressions.")
863
864 ;; SKIP: decompiler
865 ;; SKIP: encoded-source
866
867 ;;; The following variables are per-function and should be saved/restored
868 ;;; during function parsing...
869
870 (js2-deflocal js2-current-script-or-fn nil)
871 (js2-deflocal js2-current-scope nil)
872 (js2-deflocal js2-nesting-of-with 0)
873 (js2-deflocal js2-label-set nil
874 "An alist mapping label names to nodes.")
875
876 (js2-deflocal js2-loop-set nil)
877 (js2-deflocal js2-loop-and-switch-set nil)
878 (js2-deflocal js2-has-return-value nil)
879 (js2-deflocal js2-end-flags 0)
880
881 ;;; ...end of per function variables
882
883 ;; These flags enumerate the possible ways a statement/function can
884 ;; terminate. These flags are used by endCheck() and by the Parser to
885 ;; detect inconsistent return usage.
886 ;;
887 ;; END_UNREACHED is reserved for code paths that are assumed to always be
888 ;; able to execute (example: throw, continue)
889 ;;
890 ;; END_DROPS_OFF indicates if the statement can transfer control to the
891 ;; next one. Statement such as return dont. A compound statement may have
892 ;; some branch that drops off control to the next statement.
893 ;;
894 ;; END_RETURNS indicates that the statement can return (without arguments)
895 ;; END_RETURNS_VALUE indicates that the statement can return a value.
896 ;;
897 ;; A compound statement such as
898 ;; if (condition) {
899 ;; return value;
900 ;; }
901 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
902
903 (defconst js2-end-unreached #x0)
904 (defconst js2-end-drops-off #x1)
905 (defconst js2-end-returns #x2)
906 (defconst js2-end-returns-value #x4)
907
908 ;; Rhino awkwardly passes a statementLabel parameter to the
909 ;; statementHelper() function, the main statement parser, which
910 ;; is then used by quite a few of the sub-parsers. We just make
911 ;; it a buffer-local variable and make sure it's cleaned up properly.
912 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
913
914 ;; Similarly, Rhino passes an inForInit boolean through about half
915 ;; the expression parsers. We use a dynamically-scoped variable,
916 ;; which makes it easier to funcall the parsers individually without
917 ;; worrying about whether they take the parameter or not.
918 (js2-deflocal js2-in-for-init nil)
919 (js2-deflocal js2-temp-name-counter 0)
920 (js2-deflocal js2-parse-stmt-count 0)
921
922 (defsubst js2-get-next-temp-name ()
923 (format "$%d" (cl-incf js2-temp-name-counter)))
924
925 (defvar js2-parse-interruptable-p t
926 "Set this to nil to force parse to continue until finished.
927 This will mostly be useful for interpreters.")
928
929 (defvar js2-statements-per-pause 50
930 "Pause after this many statements to check for user input.
931 If user input is pending, stop the parse and discard the tree.
932 This makes for a smoother user experience for large files.
933 You may have to wait a second or two before the highlighting
934 and error-reporting appear, but you can always type ahead if
935 you wish. This appears to be more or less how Eclipse, IntelliJ
936 and other editors work.")
937
938 (js2-deflocal js2-record-comments t
939 "Instructs the scanner to record comments in `js2-scanned-comments'.")
940
941 (js2-deflocal js2-scanned-comments nil
942 "List of all comments from the current parse.")
943
944 (defcustom js2-mode-indent-inhibit-undo nil
945 "Non-nil to disable collection of Undo information when indenting lines.
946 Some users have requested this behavior. It's nil by default because
947 other Emacs modes don't work this way."
948 :type 'boolean
949 :group 'js2-mode)
950
951 (defcustom js2-mode-indent-ignore-first-tab nil
952 "If non-nil, ignore first TAB keypress if we look indented properly.
953 It's fairly common for users to navigate to an already-indented line
954 and press TAB for reassurance that it's been indented. For this class
955 of users, we want the first TAB press on a line to be ignored if the
956 line is already indented to one of the precomputed alternatives.
957
958 This behavior is only partly implemented. If you TAB-indent a line,
959 navigate to another line, and then navigate back, it fails to clear
960 the last-indented variable, so it thinks you've already hit TAB once,
961 and performs the indent. A full solution would involve getting on the
962 point-motion hooks for the entire buffer. If we come across another
963 use cases that requires watching point motion, I'll consider doing it.
964
965 If you set this variable to nil, then the TAB key will always change
966 the indentation of the current line, if more than one alternative
967 indentation spot exists."
968 :type 'boolean
969 :group 'js2-mode)
970
971 (defvar js2-indent-hook nil
972 "A hook for user-defined indentation rules.
973
974 Functions on this hook should expect two arguments: (LIST INDEX)
975 The LIST argument is the list of computed indentation points for
976 the current line. INDEX is the list index of the indentation point
977 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
978 indent function is not going to change the current line indentation.
979
980 If a hook function on this list returns a non-nil value, then
981 `js2-bounce-indent' assumes the hook function has performed its own
982 indentation, and will do nothing. If all hook functions on the list
983 return nil, then `js2-bounce-indent' will use its computed indentation
984 and reindent the line.
985
986 When hook functions on this hook list are called, the variable
987 `js2-mode-ast' may or may not be set, depending on whether the
988 parse tree is available. If the variable is nil, you can pass a
989 callback to `js2-mode-wait-for-parse', and your callback will be
990 called after the new parse tree is built. This can take some time
991 in large files.")
992
993 (defface js2-warning
994 `((((class color) (background light))
995 (:underline "orange"))
996 (((class color) (background dark))
997 (:underline "orange"))
998 (t (:underline t)))
999 "Face for JavaScript warnings."
1000 :group 'js2-mode)
1001
1002 (defface js2-error
1003 `((((class color) (background light))
1004 (:foreground "red"))
1005 (((class color) (background dark))
1006 (:foreground "red"))
1007 (t (:foreground "red")))
1008 "Face for JavaScript errors."
1009 :group 'js2-mode)
1010
1011 (defface js2-jsdoc-tag
1012 '((t :foreground "SlateGray"))
1013 "Face used to highlight @whatever tags in jsdoc comments."
1014 :group 'js2-mode)
1015
1016 (defface js2-jsdoc-type
1017 '((t :foreground "SteelBlue"))
1018 "Face used to highlight {FooBar} types in jsdoc comments."
1019 :group 'js2-mode)
1020
1021 (defface js2-jsdoc-value
1022 '((t :foreground "PeachPuff3"))
1023 "Face used to highlight tag values in jsdoc comments."
1024 :group 'js2-mode)
1025
1026 (defface js2-function-param
1027 '((t :foreground "SeaGreen"))
1028 "Face used to highlight function parameters in javascript."
1029 :group 'js2-mode)
1030
1031 (defface js2-function-call
1032 '((t :inherit default))
1033 "Face used to highlight function name in calls."
1034 :group 'js2-mode)
1035
1036 (defface js2-object-property
1037 '((t :inherit default))
1038 "Face used to highlight named property in object literal."
1039 :group 'js2-mode)
1040
1041 (defface js2-instance-member
1042 '((t :foreground "DarkOrchid"))
1043 "Face used to highlight instance variables in javascript.
1044 Not currently used."
1045 :group 'js2-mode)
1046
1047 (defface js2-private-member
1048 '((t :foreground "PeachPuff3"))
1049 "Face used to highlight calls to private methods in javascript.
1050 Not currently used."
1051 :group 'js2-mode)
1052
1053 (defface js2-private-function-call
1054 '((t :foreground "goldenrod"))
1055 "Face used to highlight calls to private functions in javascript.
1056 Not currently used."
1057 :group 'js2-mode)
1058
1059 (defface js2-jsdoc-html-tag-name
1060 '((((class color) (min-colors 88) (background light))
1061 (:foreground "rosybrown"))
1062 (((class color) (min-colors 8) (background dark))
1063 (:foreground "yellow"))
1064 (((class color) (min-colors 8) (background light))
1065 (:foreground "magenta")))
1066 "Face used to highlight jsdoc html tag names"
1067 :group 'js2-mode)
1068
1069 (defface js2-jsdoc-html-tag-delimiter
1070 '((((class color) (min-colors 88) (background light))
1071 (:foreground "dark khaki"))
1072 (((class color) (min-colors 8) (background dark))
1073 (:foreground "green"))
1074 (((class color) (min-colors 8) (background light))
1075 (:foreground "green")))
1076 "Face used to highlight brackets in jsdoc html tags."
1077 :group 'js2-mode)
1078
1079 (defface js2-external-variable
1080 '((t :foreground "orange"))
1081 "Face used to highlight undeclared variable identifiers.")
1082
1083 (defcustom js2-init-hook nil
1084 ;; FIXME: We don't really need this anymore.
1085 "List of functions to be called after `js2-mode' or
1086 `js2-minor-mode' has initialized all variables, before parsing
1087 the buffer for the first time."
1088 :type 'hook
1089 :group 'js2-mode
1090 :version "20130608")
1091
1092 (defcustom js2-post-parse-callbacks nil
1093 "List of callback functions invoked after parsing finishes.
1094 Currently, the main use for this function is to add synthetic
1095 declarations to `js2-recorded-identifiers', which see."
1096 :type 'hook
1097 :group 'js2-mode)
1098
1099 (defcustom js2-build-imenu-callbacks nil
1100 "List of functions called during Imenu index generation.
1101 It's a good place to add additional entries to it, using
1102 `js2-record-imenu-entry'."
1103 :type 'hook
1104 :group 'js2-mode)
1105
1106 (defcustom js2-highlight-external-variables t
1107 "Non-nil to highlight undeclared variable identifiers.
1108 An undeclared variable is any variable not declared with var or let
1109 in the current scope or any lexically enclosing scope. If you use
1110 such a variable, then you are either expecting it to originate from
1111 another file, or you've got a potential bug."
1112 :type 'boolean
1113 :group 'js2-mode)
1114
1115 (defcustom js2-warn-about-unused-function-arguments nil
1116 "Non-nil to treat function arguments like declared-but-unused variables."
1117 :type 'booleanp
1118 :group 'js2-mode)
1119
1120 (defcustom js2-include-jslint-globals t
1121 "Non-nil to include the identifiers from JSLint global
1122 declaration (see http://www.jslint.com/lint.html#global) in the
1123 buffer-local externs list. See `js2-additional-externs' for more
1124 information."
1125 :type 'boolean
1126 :group 'js2-mode)
1127
1128 (defvar js2-mode-map
1129 (let ((map (make-sparse-keymap)))
1130 (define-key map [mouse-1] #'js2-mode-show-node)
1131 (define-key map (kbd "M-j") #'js2-line-break)
1132 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1133 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1134 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1135 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1136 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1137 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1138 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1139 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1140 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1141
1142 (define-key map [menu-bar javascript]
1143 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1144
1145 (define-key map [menu-bar javascript customize-js2-mode]
1146 '(menu-item "Customize js2-mode" js2-mode-customize
1147 :help "Customize the behavior of this mode"))
1148
1149 (define-key map [menu-bar javascript js2-force-refresh]
1150 '(menu-item "Force buffer refresh" js2-mode-reset
1151 :help "Re-parse the buffer from scratch"))
1152
1153 (define-key map [menu-bar javascript separator-2]
1154 '("--"))
1155
1156 (define-key map [menu-bar javascript next-error]
1157 '(menu-item "Next warning or error" next-error
1158 :enabled (and js2-mode-ast
1159 (or (js2-ast-root-errors js2-mode-ast)
1160 (js2-ast-root-warnings js2-mode-ast)))
1161 :help "Move to next warning or error"))
1162
1163 (define-key map [menu-bar javascript display-errors]
1164 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1165 :visible (not js2-mode-show-parse-errors)
1166 :help "Turn on display of warnings and errors"))
1167
1168 (define-key map [menu-bar javascript hide-errors]
1169 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1170 :visible js2-mode-show-parse-errors
1171 :help "Turn off display of warnings and errors"))
1172
1173 (define-key map [menu-bar javascript separator-1]
1174 '("--"))
1175
1176 (define-key map [menu-bar javascript js2-toggle-function]
1177 '(menu-item "Show/collapse element" js2-mode-toggle-element
1178 :help "Hide or show function body or comment"))
1179
1180 (define-key map [menu-bar javascript show-comments]
1181 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1182 :visible js2-mode-comments-hidden
1183 :help "Expand all hidden block comments"))
1184
1185 (define-key map [menu-bar javascript hide-comments]
1186 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1187 :visible (not js2-mode-comments-hidden)
1188 :help "Show block comments as /*...*/"))
1189
1190 (define-key map [menu-bar javascript show-all-functions]
1191 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1192 :visible js2-mode-functions-hidden
1193 :help "Expand all hidden function bodies"))
1194
1195 (define-key map [menu-bar javascript hide-all-functions]
1196 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1197 :visible (not js2-mode-functions-hidden)
1198 :help "Show {...} for all top-level function bodies"))
1199
1200 map)
1201 "Keymap used in `js2-mode' buffers.")
1202
1203 (defcustom js2-bounce-indent-p nil
1204 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1205 They will augment the default indent-line behavior with cycling
1206 among several computed alternatives. See the function
1207 `js2-bounce-indent' for details. The above commands will be
1208 bound to TAB and backtab."
1209 :type 'boolean
1210 :group 'js2-mode
1211 :set (lambda (sym value)
1212 (set-default sym value)
1213 (let ((map js2-mode-map))
1214 (if (not value)
1215 (progn
1216 (define-key map "\t" nil)
1217 (define-key map (kbd "<backtab>") nil))
1218 (define-key map "\t" #'js2-indent-bounce)
1219 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1220
1221 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1222
1223 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1224 "Matches a //-comment line. Must be first non-whitespace on line.
1225 First match-group is the leading whitespace.")
1226
1227 (defvar js2-mode-hook nil)
1228
1229 (js2-deflocal js2-mode-ast nil "Private variable.")
1230 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1231 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1232 (js2-deflocal js2-mode-parsing nil "Private variable.")
1233 (js2-deflocal js2-mode-node-overlay nil)
1234
1235 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1236 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1237
1238 (js2-deflocal js2-mode-fontifications nil "Private variable")
1239 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1240 (js2-deflocal js2-imenu-recorder nil "Private variable")
1241 (js2-deflocal js2-imenu-function-map nil "Private variable")
1242
1243 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1244 "Non-nil to emit status messages during parsing.")
1245
1246 (defvar js2-mode-functions-hidden nil "Private variable.")
1247 (defvar js2-mode-comments-hidden nil "Private variable.")
1248
1249 (defvar js2-mode-syntax-table
1250 (let ((table (make-syntax-table)))
1251 (c-populate-syntax-table table)
1252 (modify-syntax-entry ?` "\"" table)
1253 table)
1254 "Syntax table used in `js2-mode' buffers.")
1255
1256 (defvar js2-mode-abbrev-table nil
1257 "Abbrev table in use in `js2-mode' buffers.")
1258 (define-abbrev-table 'js2-mode-abbrev-table ())
1259
1260 (defvar js2-mode-pending-parse-callbacks nil
1261 "List of functions waiting to be notified that parse is finished.")
1262
1263 (defvar js2-mode-last-indented-line -1)
1264
1265 ;;; Localizable error and warning messages
1266
1267 ;; Messages are copied from Rhino's Messages.properties.
1268 ;; Many of the Java-specific messages have been elided.
1269 ;; Add any js2-specific ones at the end, so we can keep
1270 ;; this file synced with changes to Rhino's.
1271
1272 (defvar js2-message-table
1273 (make-hash-table :test 'equal :size 250)
1274 "Contains localized messages for `js2-mode'.")
1275
1276 ;; TODO(stevey): construct this table at compile-time.
1277 (defmacro js2-msg (key &rest strings)
1278 `(puthash ,key (concat ,@strings)
1279 js2-message-table))
1280
1281 (defun js2-get-msg (msg-key)
1282 "Look up a localized message.
1283 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1284 the correct number of ARGS must be provided."
1285 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1286 (args (if (listp msg-key) (cdr msg-key)))
1287 (msg (gethash key js2-message-table)))
1288 (if msg
1289 (apply #'format msg args)
1290 key))) ; default to showing the key
1291
1292 (js2-msg "msg.dup.parms"
1293 "Duplicate parameter name '%s'.")
1294
1295 (js2-msg "msg.too.big.jump"
1296 "Program too complex: jump offset too big.")
1297
1298 (js2-msg "msg.too.big.index"
1299 "Program too complex: internal index exceeds 64K limit.")
1300
1301 (js2-msg "msg.while.compiling.fn"
1302 "Encountered code generation error while compiling function '%s': %s")
1303
1304 (js2-msg "msg.while.compiling.script"
1305 "Encountered code generation error while compiling script: %s")
1306
1307 ;; Context
1308 (js2-msg "msg.ctor.not.found"
1309 "Constructor for '%s' not found.")
1310
1311 (js2-msg "msg.not.ctor"
1312 "'%s' is not a constructor.")
1313
1314 ;; FunctionObject
1315 (js2-msg "msg.varargs.ctor"
1316 "Method or constructor '%s' must be static "
1317 "with the signature (Context cx, Object[] args, "
1318 "Function ctorObj, boolean inNewExpr) "
1319 "to define a variable arguments constructor.")
1320
1321 (js2-msg "msg.varargs.fun"
1322 "Method '%s' must be static with the signature "
1323 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1324 "to define a variable arguments function.")
1325
1326 (js2-msg "msg.incompat.call"
1327 "Method '%s' called on incompatible object.")
1328
1329 (js2-msg "msg.bad.parms"
1330 "Unsupported parameter type '%s' in method '%s'.")
1331
1332 (js2-msg "msg.bad.method.return"
1333 "Unsupported return type '%s' in method '%s'.")
1334
1335 (js2-msg "msg.bad.ctor.return"
1336 "Construction of objects of type '%s' is not supported.")
1337
1338 (js2-msg "msg.no.overload"
1339 "Method '%s' occurs multiple times in class '%s'.")
1340
1341 (js2-msg "msg.method.not.found"
1342 "Method '%s' not found in '%s'.")
1343
1344 ;; IRFactory
1345
1346 (js2-msg "msg.bad.for.in.lhs"
1347 "Invalid left-hand side of for..in loop.")
1348
1349 (js2-msg "msg.mult.index"
1350 "Only one variable allowed in for..in loop.")
1351
1352 (js2-msg "msg.bad.for.in.destruct"
1353 "Left hand side of for..in loop must be an array of "
1354 "length 2 to accept key/value pair.")
1355
1356 (js2-msg "msg.cant.convert"
1357 "Can't convert to type '%s'.")
1358
1359 (js2-msg "msg.bad.assign.left"
1360 "Invalid assignment left-hand side.")
1361
1362 (js2-msg "msg.bad.decr"
1363 "Invalid decrement operand.")
1364
1365 (js2-msg "msg.bad.incr"
1366 "Invalid increment operand.")
1367
1368 (js2-msg "msg.bad.yield"
1369 "yield must be in a function.")
1370
1371 (js2-msg "msg.yield.parenthesized"
1372 "yield expression must be parenthesized.")
1373
1374 (js2-msg "msg.bad.await"
1375 "await must be in async functions.")
1376
1377 ;; NativeGlobal
1378 (js2-msg "msg.cant.call.indirect"
1379 "Function '%s' must be called directly, and not by way of a "
1380 "function of another name.")
1381
1382 (js2-msg "msg.eval.nonstring"
1383 "Calling eval() with anything other than a primitive "
1384 "string value will simply return the value. "
1385 "Is this what you intended?")
1386
1387 (js2-msg "msg.eval.nonstring.strict"
1388 "Calling eval() with anything other than a primitive "
1389 "string value is not allowed in strict mode.")
1390
1391 (js2-msg "msg.bad.destruct.op"
1392 "Invalid destructuring assignment operator")
1393
1394 ;; NativeCall
1395 (js2-msg "msg.only.from.new"
1396 "'%s' may only be invoked from a `new' expression.")
1397
1398 (js2-msg "msg.deprec.ctor"
1399 "The '%s' constructor is deprecated.")
1400
1401 ;; NativeFunction
1402 (js2-msg "msg.no.function.ref.found"
1403 "no source found to decompile function reference %s")
1404
1405 (js2-msg "msg.arg.isnt.array"
1406 "second argument to Function.prototype.apply must be an array")
1407
1408 ;; NativeGlobal
1409 (js2-msg "msg.bad.esc.mask"
1410 "invalid string escape mask")
1411
1412 ;; NativeRegExp
1413 (js2-msg "msg.bad.quant"
1414 "Invalid quantifier %s")
1415
1416 (js2-msg "msg.overlarge.backref"
1417 "Overly large back reference %s")
1418
1419 (js2-msg "msg.overlarge.min"
1420 "Overly large minimum %s")
1421
1422 (js2-msg "msg.overlarge.max"
1423 "Overly large maximum %s")
1424
1425 (js2-msg "msg.zero.quant"
1426 "Zero quantifier %s")
1427
1428 (js2-msg "msg.max.lt.min"
1429 "Maximum %s less than minimum")
1430
1431 (js2-msg "msg.unterm.quant"
1432 "Unterminated quantifier %s")
1433
1434 (js2-msg "msg.unterm.paren"
1435 "Unterminated parenthetical %s")
1436
1437 (js2-msg "msg.unterm.class"
1438 "Unterminated character class %s")
1439
1440 (js2-msg "msg.bad.range"
1441 "Invalid range in character class.")
1442
1443 (js2-msg "msg.trail.backslash"
1444 "Trailing \\ in regular expression.")
1445
1446 (js2-msg "msg.re.unmatched.right.paren"
1447 "unmatched ) in regular expression.")
1448
1449 (js2-msg "msg.no.regexp"
1450 "Regular expressions are not available.")
1451
1452 (js2-msg "msg.bad.backref"
1453 "back-reference exceeds number of capturing parentheses.")
1454
1455 (js2-msg "msg.bad.regexp.compile"
1456 "Only one argument may be specified if the first "
1457 "argument to RegExp.prototype.compile is a RegExp object.")
1458
1459 ;; Parser
1460 (js2-msg "msg.got.syntax.errors"
1461 "Compilation produced %s syntax errors.")
1462
1463 (js2-msg "msg.var.redecl"
1464 "Redeclaration of var %s.")
1465
1466 (js2-msg "msg.const.redecl"
1467 "TypeError: redeclaration of const %s.")
1468
1469 (js2-msg "msg.let.redecl"
1470 "TypeError: redeclaration of variable %s.")
1471
1472 (js2-msg "msg.parm.redecl"
1473 "TypeError: redeclaration of formal parameter %s.")
1474
1475 (js2-msg "msg.fn.redecl"
1476 "TypeError: redeclaration of function %s.")
1477
1478 (js2-msg "msg.let.decl.not.in.block"
1479 "SyntaxError: let declaration not directly within block")
1480
1481 (js2-msg "msg.mod.import.decl.at.top.level"
1482 "SyntaxError: import declarations may only appear at the top level")
1483
1484 (js2-msg "msg.mod.as.after.reserved.word"
1485 "SyntaxError: missing keyword 'as' after reserved word %s")
1486
1487 (js2-msg "msg.mod.rc.after.import.spec.list"
1488 "SyntaxError: missing '}' after module specifier list")
1489
1490 (js2-msg "msg.mod.from.after.import.spec.set"
1491 "SyntaxError: missing keyword 'from' after import specifier set")
1492
1493 (js2-msg "msg.mod.declaration.after.import"
1494 "SyntaxError: missing declaration after 'import' keyword")
1495
1496 (js2-msg "msg.mod.spec.after.from"
1497 "SyntaxError: missing module specifier after 'from' keyword")
1498
1499 (js2-msg "msg.mod.export.decl.at.top.level"
1500 "SyntaxError: export declarations may only appear at top level")
1501
1502 (js2-msg "msg.mod.rc.after.export.spec.list"
1503 "SyntaxError: missing '}' after export specifier list")
1504
1505 ;; NodeTransformer
1506 (js2-msg "msg.dup.label"
1507 "duplicated label")
1508
1509 (js2-msg "msg.undef.label"
1510 "undefined label")
1511
1512 (js2-msg "msg.bad.break"
1513 "unlabelled break must be inside loop or switch")
1514
1515 (js2-msg "msg.continue.outside"
1516 "continue must be inside loop")
1517
1518 (js2-msg "msg.continue.nonloop"
1519 "continue can only use labels of iteration statements")
1520
1521 (js2-msg "msg.bad.throw.eol"
1522 "Line terminator is not allowed between the throw "
1523 "keyword and throw expression.")
1524
1525 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1526 "function statement requires a name")
1527
1528 (js2-msg "msg.no.paren.parms"
1529 "missing ( before function parameters.")
1530
1531 (js2-msg "msg.no.parm"
1532 "missing formal parameter")
1533
1534 (js2-msg "msg.no.paren.after.parms"
1535 "missing ) after formal parameters")
1536
1537 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1538 "parameter without default follows parameter with default")
1539
1540 (js2-msg "msg.param.after.rest" ; added by js2-mode
1541 "parameter after rest parameter")
1542
1543 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1544 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1545
1546 (js2-msg "msg.no.brace.body"
1547 "missing '{' before function body")
1548
1549 (js2-msg "msg.no.brace.after.body"
1550 "missing } after function body")
1551
1552 (js2-msg "msg.no.paren.cond"
1553 "missing ( before condition")
1554
1555 (js2-msg "msg.no.paren.after.cond"
1556 "missing ) after condition")
1557
1558 (js2-msg "msg.no.semi.stmt"
1559 "missing ; before statement")
1560
1561 (js2-msg "msg.missing.semi"
1562 "missing ; after statement")
1563
1564 (js2-msg "msg.no.name.after.dot"
1565 "missing name after . operator")
1566
1567 (js2-msg "msg.no.name.after.coloncolon"
1568 "missing name after :: operator")
1569
1570 (js2-msg "msg.no.name.after.dotdot"
1571 "missing name after .. operator")
1572
1573 (js2-msg "msg.no.name.after.xmlAttr"
1574 "missing name after .@")
1575
1576 (js2-msg "msg.no.bracket.index"
1577 "missing ] in index expression")
1578
1579 (js2-msg "msg.no.paren.switch"
1580 "missing ( before switch expression")
1581
1582 (js2-msg "msg.no.paren.after.switch"
1583 "missing ) after switch expression")
1584
1585 (js2-msg "msg.no.brace.switch"
1586 "missing '{' before switch body")
1587
1588 (js2-msg "msg.bad.switch"
1589 "invalid switch statement")
1590
1591 (js2-msg "msg.no.colon.case"
1592 "missing : after case expression")
1593
1594 (js2-msg "msg.double.switch.default"
1595 "double default label in the switch statement")
1596
1597 (js2-msg "msg.no.while.do"
1598 "missing while after do-loop body")
1599
1600 (js2-msg "msg.no.paren.for"
1601 "missing ( after for")
1602
1603 (js2-msg "msg.no.semi.for"
1604 "missing ; after for-loop initializer")
1605
1606 (js2-msg "msg.no.semi.for.cond"
1607 "missing ; after for-loop condition")
1608
1609 (js2-msg "msg.in.after.for.name"
1610 "missing in or of after for")
1611
1612 (js2-msg "msg.no.paren.for.ctrl"
1613 "missing ) after for-loop control")
1614
1615 (js2-msg "msg.no.paren.with"
1616 "missing ( before with-statement object")
1617
1618 (js2-msg "msg.no.paren.after.with"
1619 "missing ) after with-statement object")
1620
1621 (js2-msg "msg.no.with.strict"
1622 "with statements not allowed in strict mode")
1623
1624 (js2-msg "msg.no.paren.after.let"
1625 "missing ( after let")
1626
1627 (js2-msg "msg.no.paren.let"
1628 "missing ) after variable list")
1629
1630 (js2-msg "msg.no.curly.let"
1631 "missing } after let statement")
1632
1633 (js2-msg "msg.bad.return"
1634 "invalid return")
1635
1636 (js2-msg "msg.no.brace.block"
1637 "missing } in compound statement")
1638
1639 (js2-msg "msg.bad.label"
1640 "invalid label")
1641
1642 (js2-msg "msg.bad.var"
1643 "missing variable name")
1644
1645 (js2-msg "msg.bad.var.init"
1646 "invalid variable initialization")
1647
1648 (js2-msg "msg.no.colon.cond"
1649 "missing : in conditional expression")
1650
1651 (js2-msg "msg.no.paren.arg"
1652 "missing ) after argument list")
1653
1654 (js2-msg "msg.no.bracket.arg"
1655 "missing ] after element list")
1656
1657 (js2-msg "msg.bad.prop"
1658 "invalid property id")
1659
1660 (js2-msg "msg.no.colon.prop"
1661 "missing : after property id")
1662
1663 (js2-msg "msg.no.brace.prop"
1664 "missing } after property list")
1665
1666 (js2-msg "msg.no.paren"
1667 "missing ) in parenthetical")
1668
1669 (js2-msg "msg.reserved.id"
1670 "'%s' is a reserved identifier")
1671
1672 (js2-msg "msg.no.paren.catch"
1673 "missing ( before catch-block condition")
1674
1675 (js2-msg "msg.bad.catchcond"
1676 "invalid catch block condition")
1677
1678 (js2-msg "msg.catch.unreachable"
1679 "any catch clauses following an unqualified catch are unreachable")
1680
1681 (js2-msg "msg.no.brace.try"
1682 "missing '{' before try block")
1683
1684 (js2-msg "msg.no.brace.catchblock"
1685 "missing '{' before catch-block body")
1686
1687 (js2-msg "msg.try.no.catchfinally"
1688 "'try' without 'catch' or 'finally'")
1689
1690 (js2-msg "msg.no.return.value"
1691 "function %s does not always return a value")
1692
1693 (js2-msg "msg.anon.no.return.value"
1694 "anonymous function does not always return a value")
1695
1696 (js2-msg "msg.return.inconsistent"
1697 "return statement is inconsistent with previous usage")
1698
1699 (js2-msg "msg.generator.returns"
1700 "TypeError: legacy generator function '%s' returns a value")
1701
1702 (js2-msg "msg.anon.generator.returns"
1703 "TypeError: anonymous legacy generator function returns a value")
1704
1705 (js2-msg "msg.syntax"
1706 "syntax error")
1707
1708 (js2-msg "msg.unexpected.eof"
1709 "Unexpected end of file")
1710
1711 (js2-msg "msg.XML.bad.form"
1712 "illegally formed XML syntax")
1713
1714 (js2-msg "msg.XML.not.available"
1715 "XML runtime not available")
1716
1717 (js2-msg "msg.too.deep.parser.recursion"
1718 "Too deep recursion while parsing")
1719
1720 (js2-msg "msg.no.side.effects"
1721 "Code has no side effects")
1722
1723 (js2-msg "msg.extra.trailing.comma"
1724 "Trailing comma is not supported in some browsers")
1725
1726 (js2-msg "msg.array.trailing.comma"
1727 "Trailing comma yields different behavior across browsers")
1728
1729 (js2-msg "msg.equal.as.assign"
1730 (concat "Test for equality (==) mistyped as assignment (=)?"
1731 " (parenthesize to suppress warning)"))
1732
1733 (js2-msg "msg.var.hides.arg"
1734 "Variable %s hides argument")
1735
1736 (js2-msg "msg.destruct.assign.no.init"
1737 "Missing = in destructuring declaration")
1738
1739 (js2-msg "msg.init.no.destruct"
1740 "Binding initializer not in destructuring assignment")
1741
1742 (js2-msg "msg.no.octal.strict"
1743 "Octal numbers prohibited in strict mode.")
1744
1745 (js2-msg "msg.dup.obj.lit.prop.strict"
1746 "Property '%s' already defined in this object literal.")
1747
1748 (js2-msg "msg.dup.param.strict"
1749 "Parameter '%s' already declared in this function.")
1750
1751 (js2-msg "msg.bad.id.strict"
1752 "'%s' is not a valid identifier for this use in strict mode.")
1753
1754 ;; ScriptRuntime
1755 (js2-msg "msg.no.properties"
1756 "%s has no properties.")
1757
1758 (js2-msg "msg.invalid.iterator"
1759 "Invalid iterator value")
1760
1761 (js2-msg "msg.iterator.primitive"
1762 "__iterator__ returned a primitive value")
1763
1764 (js2-msg "msg.assn.create.strict"
1765 "Assignment to undeclared variable %s")
1766
1767 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1768 "Undeclared variable or function '%s'")
1769
1770 (js2-msg "msg.unused.variable" ; added by js2-mode
1771 "Unused variable or function '%s'")
1772
1773 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1774 "Variable '%s' referenced but never initialized")
1775
1776 (js2-msg "msg.ref.undefined.prop"
1777 "Reference to undefined property '%s'")
1778
1779 (js2-msg "msg.prop.not.found"
1780 "Property %s not found.")
1781
1782 (js2-msg "msg.invalid.type"
1783 "Invalid JavaScript value of type %s")
1784
1785 (js2-msg "msg.primitive.expected"
1786 "Primitive type expected (had %s instead)")
1787
1788 (js2-msg "msg.namespace.expected"
1789 "Namespace object expected to left of :: (found %s instead)")
1790
1791 (js2-msg "msg.null.to.object"
1792 "Cannot convert null to an object.")
1793
1794 (js2-msg "msg.undef.to.object"
1795 "Cannot convert undefined to an object.")
1796
1797 (js2-msg "msg.cyclic.value"
1798 "Cyclic %s value not allowed.")
1799
1800 (js2-msg "msg.is.not.defined"
1801 "'%s' is not defined.")
1802
1803 (js2-msg "msg.undef.prop.read"
1804 "Cannot read property '%s' from %s")
1805
1806 (js2-msg "msg.undef.prop.write"
1807 "Cannot set property '%s' of %s to '%s'")
1808
1809 (js2-msg "msg.undef.prop.delete"
1810 "Cannot delete property '%s' of %s")
1811
1812 (js2-msg "msg.undef.method.call"
1813 "Cannot call method '%s' of %s")
1814
1815 (js2-msg "msg.undef.with"
1816 "Cannot apply 'with' to %s")
1817
1818 (js2-msg "msg.isnt.function"
1819 "%s is not a function, it is %s.")
1820
1821 (js2-msg "msg.isnt.function.in"
1822 "Cannot call property %s in object %s. "
1823 "It is not a function, it is '%s'.")
1824
1825 (js2-msg "msg.function.not.found"
1826 "Cannot find function %s.")
1827
1828 (js2-msg "msg.function.not.found.in"
1829 "Cannot find function %s in object %s.")
1830
1831 (js2-msg "msg.isnt.xml.object"
1832 "%s is not an xml object.")
1833
1834 (js2-msg "msg.no.ref.to.get"
1835 "%s is not a reference to read reference value.")
1836
1837 (js2-msg "msg.no.ref.to.set"
1838 "%s is not a reference to set reference value to %s.")
1839
1840 (js2-msg "msg.no.ref.from.function"
1841 "Function %s can not be used as the left-hand "
1842 "side of assignment or as an operand of ++ or -- operator.")
1843
1844 (js2-msg "msg.bad.default.value"
1845 "Object's getDefaultValue() method returned an object.")
1846
1847 (js2-msg "msg.instanceof.not.object"
1848 "Can't use instanceof on a non-object.")
1849
1850 (js2-msg "msg.instanceof.bad.prototype"
1851 "'prototype' property of %s is not an object.")
1852
1853 (js2-msg "msg.bad.radix"
1854 "illegal radix %s.")
1855
1856 ;; ScriptableObject
1857 (js2-msg "msg.default.value"
1858 "Cannot find default value for object.")
1859
1860 (js2-msg "msg.zero.arg.ctor"
1861 "Cannot load class '%s' which has no zero-parameter constructor.")
1862
1863 (js2-msg "msg.ctor.multiple.parms"
1864 "Can't define constructor or class %s since more than "
1865 "one constructor has multiple parameters.")
1866
1867 (js2-msg "msg.extend.scriptable"
1868 "%s must extend ScriptableObject in order to define property %s.")
1869
1870 (js2-msg "msg.bad.getter.parms"
1871 "In order to define a property, getter %s must have zero "
1872 "parameters or a single ScriptableObject parameter.")
1873
1874 (js2-msg "msg.obj.getter.parms"
1875 "Expected static or delegated getter %s to take "
1876 "a ScriptableObject parameter.")
1877
1878 (js2-msg "msg.getter.static"
1879 "Getter and setter must both be static or neither be static.")
1880
1881 (js2-msg "msg.setter.return"
1882 "Setter must have void return type: %s")
1883
1884 (js2-msg "msg.setter2.parms"
1885 "Two-parameter setter must take a ScriptableObject as "
1886 "its first parameter.")
1887
1888 (js2-msg "msg.setter1.parms"
1889 "Expected single parameter setter for %s")
1890
1891 (js2-msg "msg.setter2.expected"
1892 "Expected static or delegated setter %s to take two parameters.")
1893
1894 (js2-msg "msg.setter.parms"
1895 "Expected either one or two parameters for setter.")
1896
1897 (js2-msg "msg.setter.bad.type"
1898 "Unsupported parameter type '%s' in setter '%s'.")
1899
1900 (js2-msg "msg.add.sealed"
1901 "Cannot add a property to a sealed object: %s.")
1902
1903 (js2-msg "msg.remove.sealed"
1904 "Cannot remove a property from a sealed object: %s.")
1905
1906 (js2-msg "msg.modify.sealed"
1907 "Cannot modify a property of a sealed object: %s.")
1908
1909 (js2-msg "msg.modify.readonly"
1910 "Cannot modify readonly property: %s.")
1911
1912 ;; TokenStream
1913 (js2-msg "msg.missing.exponent"
1914 "missing exponent")
1915
1916 (js2-msg "msg.caught.nfe"
1917 "number format error")
1918
1919 (js2-msg "msg.unterminated.string.lit"
1920 "unterminated string literal")
1921
1922 (js2-msg "msg.unterminated.comment"
1923 "unterminated comment")
1924
1925 (js2-msg "msg.unterminated.re.lit"
1926 "unterminated regular expression literal")
1927
1928 (js2-msg "msg.invalid.re.flag"
1929 "invalid flag after regular expression")
1930
1931 (js2-msg "msg.no.re.input.for"
1932 "no input for %s")
1933
1934 (js2-msg "msg.illegal.character"
1935 "illegal character")
1936
1937 (js2-msg "msg.invalid.escape"
1938 "invalid Unicode escape sequence")
1939
1940 (js2-msg "msg.bad.namespace"
1941 "not a valid default namespace statement. "
1942 "Syntax is: default xml namespace = EXPRESSION;")
1943
1944 ;; TokensStream warnings
1945 (js2-msg "msg.bad.octal.literal"
1946 "illegal octal literal digit %s; "
1947 "interpreting it as a decimal digit")
1948
1949 (js2-msg "msg.missing.hex.digits"
1950 "missing hexadecimal digits after '0x'")
1951
1952 (js2-msg "msg.missing.binary.digits"
1953 "missing binary digits after '0b'")
1954
1955 (js2-msg "msg.missing.octal.digits"
1956 "missing octal digits after '0o'")
1957
1958 (js2-msg "msg.script.is.not.constructor"
1959 "Script objects are not constructors.")
1960
1961 ;; Arrays
1962 (js2-msg "msg.arraylength.bad"
1963 "Inappropriate array length.")
1964
1965 ;; Arrays
1966 (js2-msg "msg.arraylength.too.big"
1967 "Array length %s exceeds supported capacity limit.")
1968
1969 ;; URI
1970 (js2-msg "msg.bad.uri"
1971 "Malformed URI sequence.")
1972
1973 ;; Number
1974 (js2-msg "msg.bad.precision"
1975 "Precision %s out of range.")
1976
1977 ;; NativeGenerator
1978 (js2-msg "msg.send.newborn"
1979 "Attempt to send value to newborn generator")
1980
1981 (js2-msg "msg.already.exec.gen"
1982 "Already executing generator")
1983
1984 (js2-msg "msg.StopIteration.invalid"
1985 "StopIteration may not be changed to an arbitrary object.")
1986
1987 ;; Interpreter
1988 (js2-msg "msg.yield.closing"
1989 "Yield from closing generator")
1990
1991 ;; Classes
1992 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1993 "class statement requires a name")
1994
1995 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1996 "unexpected ',' between class properties")
1997
1998 (js2-msg "msg.unexpected.static" ; added by js2-mode
1999 "unexpected 'static'")
2000
2001 (js2-msg "msg.missing.extends" ; added by js2-mode
2002 "name is required after extends")
2003
2004 (js2-msg "msg.no.brace.class" ; added by js2-mode
2005 "missing '{' before class body")
2006
2007 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2008 "missing ']' after computed property expression")
2009
2010 ;;; Tokens Buffer
2011
2012 (defconst js2-ti-max-lookahead 2)
2013 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2014
2015 (defun js2-new-token (offset)
2016 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2017 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2018 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2019 token))
2020
2021 (defsubst js2-current-token ()
2022 (aref js2-ti-tokens js2-ti-tokens-cursor))
2023
2024 (defsubst js2-current-token-string ()
2025 (js2-token-string (js2-current-token)))
2026
2027 (defsubst js2-current-token-type ()
2028 (js2-token-type (js2-current-token)))
2029
2030 (defsubst js2-current-token-beg ()
2031 (js2-token-beg (js2-current-token)))
2032
2033 (defsubst js2-current-token-end ()
2034 (js2-token-end (js2-current-token)))
2035
2036 (defun js2-current-token-len ()
2037 (let ((token (js2-current-token)))
2038 (- (js2-token-end token)
2039 (js2-token-beg token))))
2040
2041 (defun js2-ts-seek (state)
2042 (setq js2-ts-lineno (js2-ts-state-lineno state)
2043 js2-ts-cursor (js2-ts-state-cursor state)
2044 js2-ti-tokens (js2-ts-state-tokens state)
2045 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2046 js2-ti-lookahead (js2-ts-state-lookahead state)))
2047
2048 ;;; Utilities
2049
2050 (defun js2-delete-if (predicate list)
2051 "Remove all items satisfying PREDICATE in LIST."
2052 (cl-loop for item in list
2053 if (not (funcall predicate item))
2054 collect item))
2055
2056 (defun js2-position (element list)
2057 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2058 Returns nil if element is not found in the list."
2059 (let ((count 0)
2060 found)
2061 (while (and list (not found))
2062 (if (eq element (car list))
2063 (setq found t)
2064 (setq count (1+ count)
2065 list (cdr list))))
2066 (if found count)))
2067
2068 (defun js2-find-if (predicate list)
2069 "Find first item satisfying PREDICATE in LIST."
2070 (let (result)
2071 (while (and list (not result))
2072 (if (funcall predicate (car list))
2073 (setq result (car list)))
2074 (setq list (cdr list)))
2075 result))
2076
2077 (defmacro js2-time (form)
2078 "Evaluate FORM, discard result, and return elapsed time in sec."
2079 (declare (debug t))
2080 (let ((beg (make-symbol "--js2-time-beg--")))
2081 `(let ((,beg (current-time)))
2082 ,form
2083 (/ (truncate (* (- (float-time (current-time))
2084 (float-time ,beg))
2085 10000))
2086 10000.0))))
2087
2088 (defsubst js2-same-line (pos)
2089 "Return t if POS is on the same line as current point."
2090 (and (>= pos (point-at-bol))
2091 (<= pos (point-at-eol))))
2092
2093 (defun js2-code-bug ()
2094 "Signal an error when we encounter an unexpected code path."
2095 (error "failed assertion"))
2096
2097 (defsubst js2-record-text-property (beg end prop value)
2098 "Record a text property to set when parsing finishes."
2099 (push (list beg end prop value) js2-mode-deferred-properties))
2100
2101 ;; I'd like to associate errors with nodes, but for now the
2102 ;; easiest thing to do is get the context info from the last token.
2103 (defun js2-record-parse-error (msg &optional arg pos len)
2104 (push (list (list msg arg)
2105 (or pos (js2-current-token-beg))
2106 (or len (js2-current-token-len)))
2107 js2-parsed-errors))
2108
2109 (defun js2-report-error (msg &optional msg-arg pos len)
2110 "Signal a syntax error or record a parse error."
2111 (if js2-recover-from-parse-errors
2112 (js2-record-parse-error msg msg-arg pos len)
2113 (signal 'js2-syntax-error
2114 (list msg
2115 js2-ts-lineno
2116 (save-excursion
2117 (goto-char js2-ts-cursor)
2118 (current-column))
2119 js2-ts-hit-eof))))
2120
2121 (defun js2-report-warning (msg &optional msg-arg pos len face)
2122 (if js2-compiler-report-warning-as-error
2123 (js2-report-error msg msg-arg pos len)
2124 (push (list (list msg msg-arg)
2125 (or pos (js2-current-token-beg))
2126 (or len (js2-current-token-len))
2127 face)
2128 js2-parsed-warnings)))
2129
2130 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2131 (if js2-compiler-strict-mode
2132 (js2-report-warning msg-id msg-arg beg
2133 (and beg end (- end beg)))))
2134
2135 (put 'js2-syntax-error 'error-conditions
2136 '(error syntax-error js2-syntax-error))
2137 (put 'js2-syntax-error 'error-message "Syntax error")
2138
2139 (put 'js2-parse-error 'error-conditions
2140 '(error parse-error js2-parse-error))
2141 (put 'js2-parse-error 'error-message "Parse error")
2142
2143 (defmacro js2-clear-flag (flags flag)
2144 `(setq ,flags (logand ,flags (lognot ,flag))))
2145
2146 (defmacro js2-set-flag (flags flag)
2147 "Logical-or FLAG into FLAGS."
2148 `(setq ,flags (logior ,flags ,flag)))
2149
2150 (defsubst js2-flag-set-p (flags flag)
2151 (/= 0 (logand flags flag)))
2152
2153 (defsubst js2-flag-not-set-p (flags flag)
2154 (zerop (logand flags flag)))
2155
2156 ;;; AST struct and function definitions
2157
2158 ;; flags for ast node property 'member-type (used for e4x operators)
2159 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2160 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2161 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2162
2163 (defsubst js2-relpos (pos anchor)
2164 "Convert POS to be relative to ANCHOR.
2165 If POS is nil, returns nil."
2166 (and pos (- pos anchor)))
2167
2168 (defun js2-make-pad (indent)
2169 (if (zerop indent)
2170 ""
2171 (make-string (* indent js2-basic-offset) ? )))
2172
2173 (defun js2-visit-ast (node callback)
2174 "Visit every node in ast NODE with visitor CALLBACK.
2175
2176 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2177 called twice: once to visit the node, and again after all the node's
2178 children have been processed. The END-P argument is nil on the first
2179 call and non-nil on the second call. The return value of the callback
2180 affects the traversal: if non-nil, the children of NODE are processed.
2181 If the callback returns nil, or if the node has no children, then the
2182 callback is called immediately with a non-nil END-P argument.
2183
2184 The node traversal is approximately lexical-order, although there
2185 are currently no guarantees around this."
2186 (when node
2187 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2188 ;; visit the node
2189 (when (funcall callback node nil)
2190 ;; visit the kids
2191 (cond
2192 ((eq vfunc 'js2-visit-none)
2193 nil) ; don't even bother calling it
2194 ;; Each AST node type has to define a `js2-visitor' function
2195 ;; that takes a node and a callback, and calls `js2-visit-ast'
2196 ;; on each child of the node.
2197 (vfunc
2198 (funcall vfunc node callback))
2199 (t
2200 (error "%s does not define a visitor-traversal function"
2201 (aref node 0)))))
2202 ;; call the end-visit
2203 (funcall callback node t))))
2204
2205 (cl-defstruct (js2-node
2206 (:constructor nil)) ; abstract
2207 "Base AST node type."
2208 (type -1) ; token type
2209 (pos -1) ; start position of this AST node in parsed input
2210 (len 1) ; num characters spanned by the node
2211 props ; optional node property list (an alist)
2212 parent) ; link to parent node; null for root
2213
2214 (defsubst js2-node-get-prop (node prop &optional default)
2215 (or (cadr (assoc prop (js2-node-props node))) default))
2216
2217 (defsubst js2-node-set-prop (node prop value)
2218 (setf (js2-node-props node)
2219 (cons (list prop value) (js2-node-props node))))
2220
2221 (defun js2-fixup-starts (n nodes)
2222 "Adjust the start positions of NODES to be relative to N.
2223 Any node in the list may be nil, for convenience."
2224 (dolist (node nodes)
2225 (when node
2226 (setf (js2-node-pos node) (- (js2-node-pos node)
2227 (js2-node-pos n))))))
2228
2229 (defun js2-node-add-children (parent &rest nodes)
2230 "Set parent node of NODES to PARENT, and return PARENT.
2231 Does nothing if we're not recording parent links.
2232 If any given node in NODES is nil, doesn't record that link."
2233 (js2-fixup-starts parent nodes)
2234 (dolist (node nodes)
2235 (and node
2236 (setf (js2-node-parent node) parent))))
2237
2238 ;; Non-recursive since it's called a frightening number of times.
2239 (defun js2-node-abs-pos (n)
2240 (let ((pos (js2-node-pos n)))
2241 (while (setq n (js2-node-parent n))
2242 (setq pos (+ pos (js2-node-pos n))))
2243 pos))
2244
2245 (defsubst js2-node-abs-end (n)
2246 "Return absolute buffer position of end of N."
2247 (+ (js2-node-abs-pos n) (js2-node-len n)))
2248
2249 ;; It's important to make sure block nodes have a Lisp list for the
2250 ;; child nodes, to limit printing recursion depth in an AST that
2251 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2252 ;; a sufficiently large vector tree.
2253
2254 (cl-defstruct (js2-block-node
2255 (:include js2-node)
2256 (:constructor nil)
2257 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2258 (pos (js2-current-token-beg))
2259 len
2260 props
2261 kids)))
2262 "A block of statements."
2263 kids) ; a Lisp list of the child statement nodes
2264
2265 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2266 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2267
2268 (defun js2-visit-block (ast callback)
2269 "Visit the `js2-block-node' children of AST."
2270 (dolist (kid (js2-block-node-kids ast))
2271 (js2-visit-ast kid callback)))
2272
2273 (defun js2-print-block (n i)
2274 (let ((pad (js2-make-pad i)))
2275 (insert pad "{\n")
2276 (dolist (kid (js2-block-node-kids n))
2277 (js2-print-ast kid (1+ i)))
2278 (insert pad "}")))
2279
2280 (cl-defstruct (js2-scope
2281 (:include js2-block-node)
2282 (:constructor nil)
2283 (:constructor make-js2-scope (&key (type js2-BLOCK)
2284 (pos (js2-current-token-beg))
2285 len
2286 kids)))
2287 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2288 ;; I don't have one of those handy, so I'll use an alist for now.
2289 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2290 ;; and is much lighter-weight to construct (both CPU and mem).
2291 ;; The keys are interned strings (symbols) for faster lookup.
2292 ;; Should switch to hybrid alist/hashtable eventually.
2293 symbol-table ; an alist of (symbol . js2-symbol)
2294 parent-scope ; a `js2-scope'
2295 top) ; top-level `js2-scope' (script/function)
2296
2297 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2298 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2299
2300 (defun js2-node-get-enclosing-scope (node)
2301 "Return the innermost `js2-scope' node surrounding NODE.
2302 Returns nil if there is no enclosing scope node."
2303 (while (and (setq node (js2-node-parent node))
2304 (not (js2-scope-p node))))
2305 node)
2306
2307 (defun js2-get-defining-scope (scope name &optional point)
2308 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2309 Returns `js2-scope' in which NAME is defined, or nil if not found.
2310
2311 If POINT is non-nil, and if the found declaration type is
2312 `js2-LET', also check that the declaration node is before POINT."
2313 (let ((sym (if (symbolp name)
2314 name
2315 (intern name)))
2316 result
2317 (continue t))
2318 (while (and scope continue)
2319 (if (or
2320 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2321 (and entry
2322 (or (not point)
2323 (not (eq js2-LET (js2-symbol-decl-type entry)))
2324 (>= point
2325 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2326 (and (eq sym 'arguments)
2327 (js2-function-node-p scope)))
2328 (setq continue nil
2329 result scope)
2330 (setq scope (js2-scope-parent-scope scope))))
2331 result))
2332
2333 (defun js2-scope-get-symbol (scope name)
2334 "Return symbol table entry for NAME in SCOPE.
2335 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2336 (and (js2-scope-symbol-table scope)
2337 (cdr (assq (if (symbolp name)
2338 name
2339 (intern name))
2340 (js2-scope-symbol-table scope)))))
2341
2342 (defun js2-scope-put-symbol (scope name symbol)
2343 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2344 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2345 (let* ((table (js2-scope-symbol-table scope))
2346 (sym (if (symbolp name) name (intern name)))
2347 (entry (assq sym table)))
2348 (if entry
2349 (setcdr entry symbol)
2350 (push (cons sym symbol)
2351 (js2-scope-symbol-table scope)))))
2352
2353 (cl-defstruct (js2-symbol
2354 (:constructor nil)
2355 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2356 "A symbol table entry."
2357 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2358 ;; js2-LET, or js2-CONST
2359 decl-type
2360 name ; string
2361 ast-node) ; a `js2-node'
2362
2363 (cl-defstruct (js2-error-node
2364 (:include js2-node)
2365 (:constructor nil) ; silence emacs21 byte-compiler
2366 (:constructor make-js2-error-node (&key (type js2-ERROR)
2367 (pos (js2-current-token-beg))
2368 len)))
2369 "AST node representing a parse error.")
2370
2371 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2372 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2373
2374 (cl-defstruct (js2-script-node
2375 (:include js2-scope)
2376 (:constructor nil)
2377 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2378 (pos (js2-current-token-beg))
2379 len
2380 ;; FIXME: What are those?
2381 var-decls
2382 fun-decls)))
2383 functions ; Lisp list of nested functions
2384 regexps ; Lisp list of (string . flags)
2385 symbols ; alist (every symbol gets unique index)
2386 (param-count 0)
2387 var-names ; vector of string names
2388 consts ; bool-vector matching var-decls
2389 (temp-number 0)) ; for generating temp variables
2390
2391 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2392 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2393
2394 (defun js2-print-script (node indent)
2395 (dolist (kid (js2-block-node-kids node))
2396 (js2-print-ast kid indent)))
2397
2398 (cl-defstruct (js2-ast-root
2399 (:include js2-script-node)
2400 (:constructor nil)
2401 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2402 (pos (js2-current-token-beg))
2403 len
2404 buffer)))
2405 "The root node of a js2 AST."
2406 buffer ; the source buffer from which the code was parsed
2407 comments ; a Lisp list of comments, ordered by start position
2408 errors ; a Lisp list of errors found during parsing
2409 warnings ; a Lisp list of warnings found during parsing
2410 node-count) ; number of nodes in the tree, including the root
2411
2412 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2413 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2414
2415 (defun js2-visit-ast-root (ast callback)
2416 (dolist (kid (js2-ast-root-kids ast))
2417 (js2-visit-ast kid callback))
2418 (dolist (comment (js2-ast-root-comments ast))
2419 (js2-visit-ast comment callback)))
2420
2421 (cl-defstruct (js2-comment-node
2422 (:include js2-node)
2423 (:constructor nil)
2424 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2425 (pos (js2-current-token-beg))
2426 len
2427 format)))
2428 format) ; 'line, 'block, 'jsdoc or 'html
2429
2430 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2431 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2432
2433 (defun js2-print-comment (n i)
2434 ;; We really ought to link end-of-line comments to their nodes.
2435 ;; Or maybe we could add a new comment type, 'endline.
2436 (insert (js2-make-pad i)
2437 (js2-node-string n)))
2438
2439 (cl-defstruct (js2-expr-stmt-node
2440 (:include js2-node)
2441 (:constructor nil)
2442 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2443 (pos js2-ts-cursor)
2444 len
2445 expr)))
2446 "An expression statement."
2447 expr)
2448
2449 (defsubst js2-expr-stmt-node-set-has-result (node)
2450 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2451 (setf (js2-node-type node) js2-EXPR_RESULT))
2452
2453 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2454 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2455
2456 (defun js2-visit-expr-stmt-node (n v)
2457 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2458
2459 (defun js2-print-expr-stmt-node (n indent)
2460 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2461 (insert ";\n"))
2462
2463 (cl-defstruct (js2-loop-node
2464 (:include js2-scope)
2465 (:constructor nil))
2466 "Abstract supertype of loop nodes."
2467 body ; a `js2-block-node'
2468 lp ; position of left-paren, nil if omitted
2469 rp) ; position of right-paren, nil if omitted
2470
2471 (cl-defstruct (js2-do-node
2472 (:include js2-loop-node)
2473 (:constructor nil)
2474 (:constructor make-js2-do-node (&key (type js2-DO)
2475 (pos (js2-current-token-beg))
2476 len
2477 body
2478 condition
2479 while-pos
2480 lp
2481 rp)))
2482 "AST node for do-loop."
2483 condition ; while (expression)
2484 while-pos) ; buffer position of 'while' keyword
2485
2486 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2487 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2488
2489 (defun js2-visit-do-node (n v)
2490 (js2-visit-ast (js2-do-node-body n) v)
2491 (js2-visit-ast (js2-do-node-condition n) v))
2492
2493 (defun js2-print-do-node (n i)
2494 (let ((pad (js2-make-pad i)))
2495 (insert pad "do {\n")
2496 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2497 (js2-print-ast kid (1+ i)))
2498 (insert pad "} while (")
2499 (js2-print-ast (js2-do-node-condition n) 0)
2500 (insert ");\n")))
2501
2502 (cl-defstruct (js2-export-node
2503 (:include js2-node)
2504 (:constructor nil)
2505 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2506 (pos (js2-current-token-beg))
2507 len
2508 exports-list
2509 from-clause
2510 declaration
2511 default)))
2512 "AST node for an export statement. There are many things that can be exported,
2513 so many of its properties will be nil.
2514 "
2515 exports-list ; lisp list of js2-export-binding-node to export
2516 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2517 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2518 default) ; js2-function-node or js2-assign-node
2519
2520 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2521 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2522
2523 (defun js2-visit-export-node (n v)
2524 (let ((exports-list (js2-export-node-exports-list n))
2525 (from (js2-export-node-from-clause n))
2526 (declaration (js2-export-node-declaration n))
2527 (default (js2-export-node-default n)))
2528 (when exports-list
2529 (dolist (export exports-list)
2530 (js2-visit-ast export v)))
2531 (when from
2532 (js2-visit-ast from v))
2533 (when declaration
2534 (js2-visit-ast declaration v))
2535 (when default
2536 (js2-visit-ast default v))))
2537
2538 (defun js2-print-export-node (n i)
2539 (let ((pad (js2-make-pad i))
2540 (exports-list (js2-export-node-exports-list n))
2541 (from (js2-export-node-from-clause n))
2542 (declaration (js2-export-node-declaration n))
2543 (default (js2-export-node-default n)))
2544 (insert pad "export ")
2545 (cond
2546 (default
2547 (insert "default ")
2548 (js2-print-ast default i))
2549 (declaration
2550 (js2-print-ast declaration i))
2551 ((and exports-list from)
2552 (js2-print-named-imports exports-list)
2553 (insert " ")
2554 (js2-print-from-clause from))
2555 (from
2556 (insert "* ")
2557 (js2-print-from-clause from))
2558 (exports-list
2559 (js2-print-named-imports exports-list)))
2560 (unless (or (and default (not (js2-assign-node-p default)))
2561 (and declaration (or (js2-function-node-p declaration)
2562 (js2-class-node-p declaration))))
2563 (insert ";\n"))))
2564
2565 (cl-defstruct (js2-while-node
2566 (:include js2-loop-node)
2567 (:constructor nil)
2568 (:constructor make-js2-while-node (&key (type js2-WHILE)
2569 (pos (js2-current-token-beg))
2570 len body
2571 condition lp
2572 rp)))
2573 "AST node for while-loop."
2574 condition) ; while-condition
2575
2576 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2577 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2578
2579 (defun js2-visit-while-node (n v)
2580 (js2-visit-ast (js2-while-node-condition n) v)
2581 (js2-visit-ast (js2-while-node-body n) v))
2582
2583 (defun js2-print-while-node (n i)
2584 (let ((pad (js2-make-pad i)))
2585 (insert pad "while (")
2586 (js2-print-ast (js2-while-node-condition n) 0)
2587 (insert ") {\n")
2588 (js2-print-body (js2-while-node-body n) (1+ i))
2589 (insert pad "}\n")))
2590
2591 (cl-defstruct (js2-for-node
2592 (:include js2-loop-node)
2593 (:constructor nil)
2594 (:constructor make-js2-for-node (&key (type js2-FOR)
2595 (pos js2-ts-cursor)
2596 len body init
2597 condition
2598 update lp rp)))
2599 "AST node for a C-style for-loop."
2600 init ; initialization expression
2601 condition ; loop condition
2602 update) ; update clause
2603
2604 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2605 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2606
2607 (defun js2-visit-for-node (n v)
2608 (js2-visit-ast (js2-for-node-init n) v)
2609 (js2-visit-ast (js2-for-node-condition n) v)
2610 (js2-visit-ast (js2-for-node-update n) v)
2611 (js2-visit-ast (js2-for-node-body n) v))
2612
2613 (defun js2-print-for-node (n i)
2614 (let ((pad (js2-make-pad i)))
2615 (insert pad "for (")
2616 (js2-print-ast (js2-for-node-init n) 0)
2617 (insert "; ")
2618 (js2-print-ast (js2-for-node-condition n) 0)
2619 (insert "; ")
2620 (js2-print-ast (js2-for-node-update n) 0)
2621 (insert ") {\n")
2622 (js2-print-body (js2-for-node-body n) (1+ i))
2623 (insert pad "}\n")))
2624
2625 (cl-defstruct (js2-for-in-node
2626 (:include js2-loop-node)
2627 (:constructor nil)
2628 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2629 (pos js2-ts-cursor)
2630 len body
2631 iterator
2632 object
2633 in-pos
2634 each-pos
2635 foreach-p forof-p
2636 lp rp)))
2637 "AST node for a for..in loop."
2638 iterator ; [var] foo in ...
2639 object ; object over which we're iterating
2640 in-pos ; buffer position of 'in' keyword
2641 each-pos ; buffer position of 'each' keyword, if foreach-p
2642 foreach-p ; t if it's a for-each loop
2643 forof-p) ; t if it's a for-of loop
2644
2645 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2646 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2647
2648 (defun js2-visit-for-in-node (n v)
2649 (js2-visit-ast (js2-for-in-node-iterator n) v)
2650 (js2-visit-ast (js2-for-in-node-object n) v)
2651 (js2-visit-ast (js2-for-in-node-body n) v))
2652
2653 (defun js2-print-for-in-node (n i)
2654 (let ((pad (js2-make-pad i))
2655 (foreach (js2-for-in-node-foreach-p n))
2656 (forof (js2-for-in-node-forof-p n)))
2657 (insert pad "for ")
2658 (if foreach
2659 (insert "each "))
2660 (insert "(")
2661 (js2-print-ast (js2-for-in-node-iterator n) 0)
2662 (insert (if forof " of " " in "))
2663 (js2-print-ast (js2-for-in-node-object n) 0)
2664 (insert ") {\n")
2665 (js2-print-body (js2-for-in-node-body n) (1+ i))
2666 (insert pad "}\n")))
2667
2668 (cl-defstruct (js2-return-node
2669 (:include js2-node)
2670 (:constructor nil)
2671 (:constructor make-js2-return-node (&key (type js2-RETURN)
2672 (pos js2-ts-cursor)
2673 len
2674 retval)))
2675 "AST node for a return statement."
2676 retval) ; expression to return, or 'undefined
2677
2678 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2679 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2680
2681 (defun js2-visit-return-node (n v)
2682 (js2-visit-ast (js2-return-node-retval n) v))
2683
2684 (defun js2-print-return-node (n i)
2685 (insert (js2-make-pad i) "return")
2686 (when (js2-return-node-retval n)
2687 (insert " ")
2688 (js2-print-ast (js2-return-node-retval n) 0))
2689 (insert ";\n"))
2690
2691 (cl-defstruct (js2-if-node
2692 (:include js2-node)
2693 (:constructor nil)
2694 (:constructor make-js2-if-node (&key (type js2-IF)
2695 (pos js2-ts-cursor)
2696 len condition
2697 then-part
2698 else-pos
2699 else-part lp
2700 rp)))
2701 "AST node for an if-statement."
2702 condition ; expression
2703 then-part ; statement or block
2704 else-pos ; optional buffer position of 'else' keyword
2705 else-part ; optional statement or block
2706 lp ; position of left-paren, nil if omitted
2707 rp) ; position of right-paren, nil if omitted
2708
2709 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2710 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2711
2712 (defun js2-visit-if-node (n v)
2713 (js2-visit-ast (js2-if-node-condition n) v)
2714 (js2-visit-ast (js2-if-node-then-part n) v)
2715 (js2-visit-ast (js2-if-node-else-part n) v))
2716
2717 (defun js2-print-if-node (n i)
2718 (let ((pad (js2-make-pad i))
2719 (then-part (js2-if-node-then-part n))
2720 (else-part (js2-if-node-else-part n)))
2721 (insert pad "if (")
2722 (js2-print-ast (js2-if-node-condition n) 0)
2723 (insert ") {\n")
2724 (js2-print-body then-part (1+ i))
2725 (insert pad "}")
2726 (cond
2727 ((not else-part)
2728 (insert "\n"))
2729 ((js2-if-node-p else-part)
2730 (insert " else ")
2731 (js2-print-body else-part i))
2732 (t
2733 (insert " else {\n")
2734 (js2-print-body else-part (1+ i))
2735 (insert pad "}\n")))))
2736
2737 (cl-defstruct (js2-export-binding-node
2738 (:include js2-node)
2739 (:constructor nil)
2740 (:constructor make-js2-export-binding-node (&key (type -1)
2741 pos
2742 len
2743 local-name
2744 extern-name)))
2745 "AST node for an external symbol binding.
2746 It contains a local-name node which is the name of the value in the
2747 current scope, and extern-name which is the name of the value in the
2748 imported or exported scope. By default these are the same, but if the
2749 name is aliased as in {foo as bar}, it would have an extern-name node
2750 containing `foo' and a local-name node containing `bar'."
2751 local-name ; js2-name-node with the variable name in this scope
2752 extern-name) ; js2-name-node with the value name in the exporting module
2753
2754 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2755 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2756
2757 (defun js2-visit-extern-binding (n v)
2758 "Visit an extern binding node. First visit the local-name, and, if
2759 different, visit the extern-name."
2760 (let ((local-name (js2-export-binding-node-local-name n))
2761 (extern-name (js2-export-binding-node-extern-name n)))
2762 (when local-name
2763 (js2-visit-ast local-name v))
2764 (when (not (equal local-name extern-name))
2765 (js2-visit-ast extern-name v))))
2766
2767 (defun js2-print-extern-binding (n _i)
2768 "Print a representation of a single extern binding. E.g. `foo' or
2769 `foo as bar'."
2770 (let ((local-name (js2-export-binding-node-local-name n))
2771 (extern-name (js2-export-binding-node-extern-name n)))
2772 (insert (js2-name-node-name extern-name))
2773 (when (not (equal local-name extern-name))
2774 (insert " as ")
2775 (insert (js2-name-node-name local-name)))))
2776
2777
2778 (cl-defstruct (js2-import-node
2779 (:include js2-node)
2780 (:constructor nil)
2781 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2782 (pos (js2-current-token-beg))
2783 len
2784 import
2785 from
2786 module-id)))
2787 "AST node for an import statement. It follows the form
2788
2789 import ModuleSpecifier;
2790 import ImportClause FromClause;"
2791 import ; js2-import-clause-node specifying which names are to imported.
2792 from ; js2-from-clause-node indicating the module from which to import.
2793 module-id) ; module-id of the import. E.g. 'src/mylib'.
2794
2795 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2796 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2797
2798 (defun js2-visit-import (n v)
2799 (let ((import-clause (js2-import-node-import n))
2800 (from-clause (js2-import-node-from n)))
2801 (when import-clause
2802 (js2-visit-ast import-clause v))
2803 (when from-clause
2804 (js2-visit-ast from-clause v))))
2805
2806 (defun js2-print-import (n i)
2807 "Prints a representation of the import node"
2808 (let ((pad (js2-make-pad i))
2809 (import-clause (js2-import-node-import n))
2810 (from-clause (js2-import-node-from n))
2811 (module-id (js2-import-node-module-id n)))
2812 (insert pad "import ")
2813 (if import-clause
2814 (progn
2815 (js2-print-import-clause import-clause)
2816 (insert " ")
2817 (js2-print-from-clause from-clause))
2818 (insert "'")
2819 (insert module-id)
2820 (insert "'"))
2821 (insert ";\n")))
2822
2823 (cl-defstruct (js2-import-clause-node
2824 (:include js2-node)
2825 (:constructor nil)
2826 (:constructor make-js2-import-clause-node (&key (type -1)
2827 pos
2828 len
2829 namespace-import
2830 named-imports
2831 default-binding)))
2832 "AST node corresponding to the import clause of an import statement. This is
2833 the portion of the import that bindings names from the external context to the
2834 local context."
2835 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2836 named-imports ; lisp list of js2-export-binding-node for all named imports.
2837 default-binding) ; js2-export-binding-node for the default import binding
2838
2839 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2840 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2841
2842 (defun js2-visit-import-clause (n v)
2843 (let ((ns-import (js2-import-clause-node-namespace-import n))
2844 (named-imports (js2-import-clause-node-named-imports n))
2845 (default (js2-import-clause-node-default-binding n)))
2846 (when ns-import
2847 (js2-visit-ast ns-import v))
2848 (when named-imports
2849 (dolist (import named-imports)
2850 (js2-visit-ast import v)))
2851 (when default
2852 (js2-visit-ast default v))))
2853
2854 (defun js2-print-import-clause (n)
2855 (let ((ns-import (js2-import-clause-node-namespace-import n))
2856 (named-imports (js2-import-clause-node-named-imports n))
2857 (default (js2-import-clause-node-default-binding n)))
2858 (cond
2859 ((and default ns-import)
2860 (js2-print-ast default)
2861 (insert ", ")
2862 (js2-print-namespace-import ns-import))
2863 ((and default named-imports)
2864 (js2-print-ast default)
2865 (insert ", ")
2866 (js2-print-named-imports named-imports))
2867 (default
2868 (js2-print-ast default))
2869 (ns-import
2870 (js2-print-namespace-import ns-import))
2871 (named-imports
2872 (js2-print-named-imports named-imports)))))
2873
2874 (defun js2-print-namespace-import (node)
2875 (insert "* as ")
2876 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2877
2878 (defun js2-print-named-imports (imports)
2879 (insert "{")
2880 (let ((len (length imports))
2881 (n 0))
2882 (while (< n len)
2883 (js2-print-extern-binding (nth n imports) 0)
2884 (unless (= n (- len 1))
2885 (insert ", "))
2886 (setq n (+ n 1))))
2887 (insert "}"))
2888
2889 (cl-defstruct (js2-namespace-import-node
2890 (:include js2-node)
2891 (:constructor nil)
2892 (:constructor make-js2-namespace-import-node (&key (type -1)
2893 pos
2894 len
2895 name)))
2896 "AST node for a complete namespace import.
2897 E.g. the `* as lib' expression in:
2898
2899 import * as lib from \\='src/lib\\='
2900
2901 It contains a single name node referring to the bound name."
2902 name) ; js2-name-node of the bound name.
2903
2904 (defun js2-visit-namespace-import (n v)
2905 (js2-visit-ast (js2-namespace-import-node-name n) v))
2906
2907 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2908 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2909
2910 (cl-defstruct (js2-from-clause-node
2911 (:include js2-node)
2912 (:constructor nil)
2913 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2914 pos
2915 len
2916 module-id
2917 metadata-p)))
2918 "AST node for the from clause in an import or export statement.
2919 E.g. from \\='my/module\\='. It can refere to either an external module, or to the
2920 modules metadata itself."
2921 module-id ; string containing the module specifier.
2922 metadata-p) ; true if this clause refers to the module's metadata
2923
2924 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2925 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2926
2927 (defun js2-print-from-clause (n)
2928 (insert "from ")
2929 (if (js2-from-clause-node-metadata-p n)
2930 (insert "this module")
2931 (insert "'")
2932 (insert (js2-from-clause-node-module-id n))
2933 (insert "'")))
2934
2935 (cl-defstruct (js2-try-node
2936 (:include js2-node)
2937 (:constructor nil)
2938 (:constructor make-js2-try-node (&key (type js2-TRY)
2939 (pos js2-ts-cursor)
2940 len
2941 try-block
2942 catch-clauses
2943 finally-block)))
2944 "AST node for a try-statement."
2945 try-block
2946 catch-clauses ; a Lisp list of `js2-catch-node'
2947 finally-block) ; a `js2-finally-node'
2948
2949 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2950 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2951
2952 (defun js2-visit-try-node (n v)
2953 (js2-visit-ast (js2-try-node-try-block n) v)
2954 (dolist (clause (js2-try-node-catch-clauses n))
2955 (js2-visit-ast clause v))
2956 (js2-visit-ast (js2-try-node-finally-block n) v))
2957
2958 (defun js2-print-try-node (n i)
2959 (let ((pad (js2-make-pad i))
2960 (catches (js2-try-node-catch-clauses n))
2961 (finally (js2-try-node-finally-block n)))
2962 (insert pad "try {\n")
2963 (js2-print-body (js2-try-node-try-block n) (1+ i))
2964 (insert pad "}")
2965 (when catches
2966 (dolist (catch catches)
2967 (js2-print-ast catch i)))
2968 (if finally
2969 (js2-print-ast finally i)
2970 (insert "\n"))))
2971
2972 (cl-defstruct (js2-catch-node
2973 (:include js2-scope)
2974 (:constructor nil)
2975 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2976 (pos js2-ts-cursor)
2977 len
2978 param
2979 guard-kwd
2980 guard-expr
2981 lp rp)))
2982 "AST node for a catch clause."
2983 param ; destructuring form or simple name node
2984 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2985 guard-expr ; catch condition, a `js2-node'
2986 lp ; buffer position of left-paren, nil if omitted
2987 rp) ; buffer position of right-paren, nil if omitted
2988
2989 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2990 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2991
2992 (defun js2-visit-catch-node (n v)
2993 (js2-visit-ast (js2-catch-node-param n) v)
2994 (when (js2-catch-node-guard-kwd n)
2995 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2996 (js2-visit-block n v))
2997
2998 (defun js2-print-catch-node (n i)
2999 (let ((pad (js2-make-pad i))
3000 (guard-kwd (js2-catch-node-guard-kwd n))
3001 (guard-expr (js2-catch-node-guard-expr n)))
3002 (insert " catch (")
3003 (js2-print-ast (js2-catch-node-param n) 0)
3004 (when guard-kwd
3005 (insert " if ")
3006 (js2-print-ast guard-expr 0))
3007 (insert ") {\n")
3008 (js2-print-body n (1+ i))
3009 (insert pad "}")))
3010
3011 (cl-defstruct (js2-finally-node
3012 (:include js2-node)
3013 (:constructor nil)
3014 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3015 (pos js2-ts-cursor)
3016 len body)))
3017 "AST node for a finally clause."
3018 body) ; a `js2-node', often but not always a block node
3019
3020 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3021 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3022
3023 (defun js2-visit-finally-node (n v)
3024 (js2-visit-ast (js2-finally-node-body n) v))
3025
3026 (defun js2-print-finally-node (n i)
3027 (let ((pad (js2-make-pad i)))
3028 (insert " finally {\n")
3029 (js2-print-body (js2-finally-node-body n) (1+ i))
3030 (insert pad "}\n")))
3031
3032 (cl-defstruct (js2-switch-node
3033 (:include js2-node)
3034 (:constructor nil)
3035 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3036 (pos js2-ts-cursor)
3037 len
3038 discriminant
3039 cases lp
3040 rp)))
3041 "AST node for a switch statement."
3042 discriminant ; a `js2-node' (switch expression)
3043 cases ; a Lisp list of `js2-case-node'
3044 lp ; position of open-paren for discriminant, nil if omitted
3045 rp) ; position of close-paren for discriminant, nil if omitted
3046
3047 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3048 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3049
3050 (defun js2-visit-switch-node (n v)
3051 (js2-visit-ast (js2-switch-node-discriminant n) v)
3052 (dolist (c (js2-switch-node-cases n))
3053 (js2-visit-ast c v)))
3054
3055 (defun js2-print-switch-node (n i)
3056 (let ((pad (js2-make-pad i))
3057 (cases (js2-switch-node-cases n)))
3058 (insert pad "switch (")
3059 (js2-print-ast (js2-switch-node-discriminant n) 0)
3060 (insert ") {\n")
3061 (dolist (case cases)
3062 (js2-print-ast case i))
3063 (insert pad "}\n")))
3064
3065 (cl-defstruct (js2-case-node
3066 (:include js2-block-node)
3067 (:constructor nil)
3068 (:constructor make-js2-case-node (&key (type js2-CASE)
3069 (pos js2-ts-cursor)
3070 len kids expr)))
3071 "AST node for a case clause of a switch statement."
3072 expr) ; the case expression (nil for default)
3073
3074 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3075 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3076
3077 (defun js2-visit-case-node (n v)
3078 (js2-visit-ast (js2-case-node-expr n) v)
3079 (js2-visit-block n v))
3080
3081 (defun js2-print-case-node (n i)
3082 (let ((pad (js2-make-pad i))
3083 (expr (js2-case-node-expr n)))
3084 (insert pad)
3085 (if (null expr)
3086 (insert "default:\n")
3087 (insert "case ")
3088 (js2-print-ast expr 0)
3089 (insert ":\n"))
3090 (dolist (kid (js2-case-node-kids n))
3091 (js2-print-ast kid (1+ i)))))
3092
3093 (cl-defstruct (js2-throw-node
3094 (:include js2-node)
3095 (:constructor nil)
3096 (:constructor make-js2-throw-node (&key (type js2-THROW)
3097 (pos js2-ts-cursor)
3098 len expr)))
3099 "AST node for a throw statement."
3100 expr) ; the expression to throw
3101
3102 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3103 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3104
3105 (defun js2-visit-throw-node (n v)
3106 (js2-visit-ast (js2-throw-node-expr n) v))
3107
3108 (defun js2-print-throw-node (n i)
3109 (insert (js2-make-pad i) "throw ")
3110 (js2-print-ast (js2-throw-node-expr n) 0)
3111 (insert ";\n"))
3112
3113 (cl-defstruct (js2-with-node
3114 (:include js2-node)
3115 (:constructor nil)
3116 (:constructor make-js2-with-node (&key (type js2-WITH)
3117 (pos js2-ts-cursor)
3118 len object
3119 body lp rp)))
3120 "AST node for a with-statement."
3121 object
3122 body
3123 lp ; buffer position of left-paren around object, nil if omitted
3124 rp) ; buffer position of right-paren around object, nil if omitted
3125
3126 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3127 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3128
3129 (defun js2-visit-with-node (n v)
3130 (js2-visit-ast (js2-with-node-object n) v)
3131 (js2-visit-ast (js2-with-node-body n) v))
3132
3133 (defun js2-print-with-node (n i)
3134 (let ((pad (js2-make-pad i)))
3135 (insert pad "with (")
3136 (js2-print-ast (js2-with-node-object n) 0)
3137 (insert ") {\n")
3138 (js2-print-body (js2-with-node-body n) (1+ i))
3139 (insert pad "}\n")))
3140
3141 (cl-defstruct (js2-label-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-label-node (&key (type js2-LABEL)
3145 (pos js2-ts-cursor)
3146 len name)))
3147 "AST node for a statement label or case label."
3148 name ; a string
3149 loop) ; for validating and code-generating continue-to-label
3150
3151 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3152 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3153
3154 (defun js2-print-label (n i)
3155 (insert (js2-make-pad i)
3156 (js2-label-node-name n)
3157 ":\n"))
3158
3159 (cl-defstruct (js2-labeled-stmt-node
3160 (:include js2-node)
3161 (:constructor nil)
3162 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3163 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3164 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3165 (pos js2-ts-cursor)
3166 len labels stmt)))
3167 "AST node for a statement with one or more labels.
3168 Multiple labels for a statement are collapsed into the labels field."
3169 labels ; Lisp list of `js2-label-node'
3170 stmt) ; the statement these labels are for
3171
3172 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3173 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3174
3175 (defun js2-get-label-by-name (lbl-stmt name)
3176 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3177 Returns nil if no such label is in the list."
3178 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3179 result)
3180 (while (and label-list (not result))
3181 (if (string= (js2-label-node-name (car label-list)) name)
3182 (setq result (car label-list))
3183 (setq label-list (cdr label-list))))
3184 result))
3185
3186 (defun js2-visit-labeled-stmt (n v)
3187 (dolist (label (js2-labeled-stmt-node-labels n))
3188 (js2-visit-ast label v))
3189 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3190
3191 (defun js2-print-labeled-stmt (n i)
3192 (dolist (label (js2-labeled-stmt-node-labels n))
3193 (js2-print-ast label i))
3194 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3195
3196 (defun js2-labeled-stmt-node-contains (node label)
3197 "Return t if NODE contains LABEL in its label set.
3198 NODE is a `js2-labels-node'. LABEL is an identifier."
3199 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3200 if (string= label (js2-label-node-name nl))
3201 return t
3202 finally return nil))
3203
3204 (defsubst js2-labeled-stmt-node-add-label (node label)
3205 "Add a `js2-label-node' to the label set for this statement."
3206 (setf (js2-labeled-stmt-node-labels node)
3207 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3208
3209 (cl-defstruct (js2-jump-node
3210 (:include js2-node)
3211 (:constructor nil))
3212 "Abstract supertype of break and continue nodes."
3213 label ; `js2-name-node' for location of label identifier, if present
3214 target) ; target js2-labels-node or loop/switch statement
3215
3216 (defun js2-visit-jump-node (n v)
3217 ;; We don't visit the target, since it's a back-link.
3218 (js2-visit-ast (js2-jump-node-label n) v))
3219
3220 (cl-defstruct (js2-break-node
3221 (:include js2-jump-node)
3222 (:constructor nil)
3223 (:constructor make-js2-break-node (&key (type js2-BREAK)
3224 (pos js2-ts-cursor)
3225 len label target)))
3226 "AST node for a break statement.
3227 The label field is a `js2-name-node', possibly nil, for the named label
3228 if provided. E.g. in `break foo', it represents `foo'. The target field
3229 is the target of the break - a label node or enclosing loop/switch statement.")
3230
3231 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3232 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3233
3234 (defun js2-print-break-node (n i)
3235 (insert (js2-make-pad i) "break")
3236 (when (js2-break-node-label n)
3237 (insert " ")
3238 (js2-print-ast (js2-break-node-label n) 0))
3239 (insert ";\n"))
3240
3241 (cl-defstruct (js2-continue-node
3242 (:include js2-jump-node)
3243 (:constructor nil)
3244 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3245 (pos js2-ts-cursor)
3246 len label target)))
3247 "AST node for a continue statement.
3248 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3249 It is nil if continue specifies no label. The target field is the jump target:
3250 a `js2-label-node' or the innermost enclosing loop.")
3251
3252 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3253 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3254
3255 (defun js2-print-continue-node (n i)
3256 (insert (js2-make-pad i) "continue")
3257 (when (js2-continue-node-label n)
3258 (insert " ")
3259 (js2-print-ast (js2-continue-node-label n) 0))
3260 (insert ";\n"))
3261
3262 (cl-defstruct (js2-function-node
3263 (:include js2-script-node)
3264 (:constructor nil)
3265 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3266 (pos js2-ts-cursor)
3267 len
3268 (ftype 'FUNCTION)
3269 (form 'FUNCTION_STATEMENT)
3270 (name "")
3271 params rest-p
3272 body
3273 generator-type
3274 async
3275 lp rp)))
3276 "AST node for a function declaration.
3277 The `params' field is a Lisp list of nodes. Each node is either a simple
3278 `js2-name-node', or if it's a destructuring-assignment parameter, a
3279 `js2-array-node' or `js2-object-node'."
3280 ftype ; FUNCTION, GETTER or SETTER
3281 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3282 name ; function name (a `js2-name-node', or nil if anonymous)
3283 params ; a Lisp list of destructuring forms or simple name nodes
3284 rest-p ; if t, the last parameter is rest parameter
3285 body ; a `js2-block-node' or expression node (1.8 only)
3286 lp ; position of arg-list open-paren, or nil if omitted
3287 rp ; position of arg-list close-paren, or nil if omitted
3288 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3289 needs-activation ; t if we need an activation object for this frame
3290 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3291 async ; t if the function is defined as `async function`
3292 member-expr) ; nonstandard Ecma extension from Rhino
3293
3294 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3295 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3296
3297 (defun js2-visit-function-node (n v)
3298 (js2-visit-ast (js2-function-node-name n) v)
3299 (dolist (p (js2-function-node-params n))
3300 (js2-visit-ast p v))
3301 (js2-visit-ast (js2-function-node-body n) v))
3302
3303 (defun js2-print-function-node (n i)
3304 (let* ((pad (js2-make-pad i))
3305 (method (js2-node-get-prop n 'METHOD_TYPE))
3306 (name (or (js2-function-node-name n)
3307 (js2-function-node-member-expr n)))
3308 (params (js2-function-node-params n))
3309 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3310 (rest-p (js2-function-node-rest-p n))
3311 (body (js2-function-node-body n))
3312 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3313 (unless method
3314 (insert pad)
3315 (when (js2-function-node-async n) (insert "async "))
3316 (unless arrow (insert "function"))
3317 (when (eq (js2-function-node-generator-type n) 'STAR)
3318 (insert "*")))
3319 (when name
3320 (insert " ")
3321 (js2-print-ast name 0))
3322 (insert "(")
3323 (cl-loop with len = (length params)
3324 for param in params
3325 for count from 1
3326 do
3327 (when (and rest-p (= count len))
3328 (insert "..."))
3329 (js2-print-ast param 0)
3330 (when (< count len)
3331 (insert ", ")))
3332 (insert ") ")
3333 (when arrow
3334 (insert "=> "))
3335 (insert "{")
3336 ;; TODO: fix this to be smarter about indenting, etc.
3337 (unless expr
3338 (insert "\n"))
3339 (if (js2-block-node-p body)
3340 (js2-print-body body (1+ i))
3341 (js2-print-ast body 0))
3342 (insert pad "}")
3343 (unless expr
3344 (insert "\n"))))
3345
3346 (defun js2-function-name (node)
3347 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3348 (and (js2-function-node-name node)
3349 (js2-name-node-name (js2-function-node-name node))))
3350
3351 ;; Having this be an expression node makes it more flexible.
3352 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3353 ;; that work better if you assume it's an expression. Whenever we have
3354 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3355 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3356 (cl-defstruct (js2-var-decl-node
3357 (:include js2-node)
3358 (:constructor nil)
3359 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3360 (pos (js2-current-token-beg))
3361 len kids
3362 decl-type)))
3363 "AST node for a variable declaration list (VAR, CONST or LET).
3364 The node bounds differ depending on the declaration type. For VAR or
3365 CONST declarations, the bounds include the var/const keyword. For LET
3366 declarations, the node begins at the position of the first child."
3367 kids ; a Lisp list of `js2-var-init-node' structs.
3368 decl-type) ; js2-VAR, js2-CONST or js2-LET
3369
3370 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3371 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3372
3373 (defun js2-visit-var-decl (n v)
3374 (dolist (kid (js2-var-decl-node-kids n))
3375 (js2-visit-ast kid v)))
3376
3377 (defun js2-print-var-decl (n i)
3378 (let ((pad (js2-make-pad i))
3379 (tt (js2-var-decl-node-decl-type n)))
3380 (insert pad)
3381 (insert (cond
3382 ((= tt js2-VAR) "var ")
3383 ((= tt js2-LET) "let ")
3384 ((= tt js2-CONST) "const ")
3385 (t
3386 (error "malformed var-decl node"))))
3387 (cl-loop with kids = (js2-var-decl-node-kids n)
3388 with len = (length kids)
3389 for kid in kids
3390 for count from 1
3391 do
3392 (js2-print-ast kid 0)
3393 (if (< count len)
3394 (insert ", ")))))
3395
3396 (cl-defstruct (js2-var-init-node
3397 (:include js2-node)
3398 (:constructor nil)
3399 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3400 (pos js2-ts-cursor)
3401 len target
3402 initializer)))
3403 "AST node for a variable declaration.
3404 The type field will be js2-CONST for a const decl."
3405 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3406 initializer) ; initializer expression, a `js2-node'
3407
3408 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3409 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3410
3411 (defun js2-visit-var-init-node (n v)
3412 (js2-visit-ast (js2-var-init-node-target n) v)
3413 (js2-visit-ast (js2-var-init-node-initializer n) v))
3414
3415 (defun js2-print-var-init-node (n i)
3416 (let ((pad (js2-make-pad i))
3417 (name (js2-var-init-node-target n))
3418 (init (js2-var-init-node-initializer n)))
3419 (insert pad)
3420 (js2-print-ast name 0)
3421 (when init
3422 (insert " = ")
3423 (js2-print-ast init 0))))
3424
3425 (cl-defstruct (js2-cond-node
3426 (:include js2-node)
3427 (:constructor nil)
3428 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3429 (pos js2-ts-cursor)
3430 len
3431 test-expr
3432 true-expr
3433 false-expr
3434 q-pos c-pos)))
3435 "AST node for the ternary operator"
3436 test-expr
3437 true-expr
3438 false-expr
3439 q-pos ; buffer position of ?
3440 c-pos) ; buffer position of :
3441
3442 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3443 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3444
3445 (defun js2-visit-cond-node (n v)
3446 (js2-visit-ast (js2-cond-node-test-expr n) v)
3447 (js2-visit-ast (js2-cond-node-true-expr n) v)
3448 (js2-visit-ast (js2-cond-node-false-expr n) v))
3449
3450 (defun js2-print-cond-node (n i)
3451 (let ((pad (js2-make-pad i)))
3452 (insert pad)
3453 (js2-print-ast (js2-cond-node-test-expr n) 0)
3454 (insert " ? ")
3455 (js2-print-ast (js2-cond-node-true-expr n) 0)
3456 (insert " : ")
3457 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3458
3459 (cl-defstruct (js2-infix-node
3460 (:include js2-node)
3461 (:constructor nil)
3462 (:constructor make-js2-infix-node (&key type
3463 (pos js2-ts-cursor)
3464 len op-pos
3465 left right)))
3466 "Represents infix expressions.
3467 Includes assignment ops like `|=', and the comma operator.
3468 The type field inherited from `js2-node' holds the operator."
3469 op-pos ; buffer position where operator begins
3470 left ; any `js2-node'
3471 right) ; any `js2-node'
3472
3473 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3474 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3475
3476 (defun js2-visit-infix-node (n v)
3477 (js2-visit-ast (js2-infix-node-left n) v)
3478 (js2-visit-ast (js2-infix-node-right n) v))
3479
3480 (defconst js2-operator-tokens
3481 (let ((table (make-hash-table :test 'eq))
3482 (tokens
3483 (list (cons js2-IN "in")
3484 (cons js2-TYPEOF "typeof")
3485 (cons js2-INSTANCEOF "instanceof")
3486 (cons js2-DELPROP "delete")
3487 (cons js2-AWAIT "await")
3488 (cons js2-VOID "void")
3489 (cons js2-COMMA ",")
3490 (cons js2-COLON ":")
3491 (cons js2-OR "||")
3492 (cons js2-AND "&&")
3493 (cons js2-INC "++")
3494 (cons js2-DEC "--")
3495 (cons js2-BITOR "|")
3496 (cons js2-BITXOR "^")
3497 (cons js2-BITAND "&")
3498 (cons js2-EQ "==")
3499 (cons js2-NE "!=")
3500 (cons js2-LT "<")
3501 (cons js2-LE "<=")
3502 (cons js2-GT ">")
3503 (cons js2-GE ">=")
3504 (cons js2-LSH "<<")
3505 (cons js2-RSH ">>")
3506 (cons js2-URSH ">>>")
3507 (cons js2-ADD "+") ; infix plus
3508 (cons js2-SUB "-") ; infix minus
3509 (cons js2-MUL "*")
3510 (cons js2-DIV "/")
3511 (cons js2-MOD "%")
3512 (cons js2-NOT "!")
3513 (cons js2-BITNOT "~")
3514 (cons js2-POS "+") ; unary plus
3515 (cons js2-NEG "-") ; unary minus
3516 (cons js2-TRIPLEDOT "...")
3517 (cons js2-SHEQ "===") ; shallow equality
3518 (cons js2-SHNE "!==") ; shallow inequality
3519 (cons js2-ASSIGN "=")
3520 (cons js2-ASSIGN_BITOR "|=")
3521 (cons js2-ASSIGN_BITXOR "^=")
3522 (cons js2-ASSIGN_BITAND "&=")
3523 (cons js2-ASSIGN_LSH "<<=")
3524 (cons js2-ASSIGN_RSH ">>=")
3525 (cons js2-ASSIGN_URSH ">>>=")
3526 (cons js2-ASSIGN_ADD "+=")
3527 (cons js2-ASSIGN_SUB "-=")
3528 (cons js2-ASSIGN_MUL "*=")
3529 (cons js2-ASSIGN_DIV "/=")
3530 (cons js2-ASSIGN_MOD "%="))))
3531 (cl-loop for (k . v) in tokens do
3532 (puthash k v table))
3533 table))
3534
3535 (defun js2-print-infix-node (n i)
3536 (let* ((tt (js2-node-type n))
3537 (op (gethash tt js2-operator-tokens)))
3538 (unless op
3539 (error "unrecognized infix operator %s" (js2-node-type n)))
3540 (insert (js2-make-pad i))
3541 (js2-print-ast (js2-infix-node-left n) 0)
3542 (unless (= tt js2-COMMA)
3543 (insert " "))
3544 (insert op)
3545 (insert " ")
3546 (js2-print-ast (js2-infix-node-right n) 0)))
3547
3548 (cl-defstruct (js2-assign-node
3549 (:include js2-infix-node)
3550 (:constructor nil)
3551 (:constructor make-js2-assign-node (&key type
3552 (pos js2-ts-cursor)
3553 len op-pos
3554 left right)))
3555 "Represents any assignment.
3556 The type field holds the actual assignment operator.")
3557
3558 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3559 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3560
3561 (cl-defstruct (js2-unary-node
3562 (:include js2-node)
3563 (:constructor nil)
3564 (:constructor make-js2-unary-node (&key type ; required
3565 (pos js2-ts-cursor)
3566 len operand)))
3567 "AST node type for unary operator nodes.
3568 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3569 TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
3570 property is added if the operator follows the operand."
3571 operand) ; a `js2-node' expression
3572
3573 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3574 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3575
3576 (defun js2-visit-unary-node (n v)
3577 (js2-visit-ast (js2-unary-node-operand n) v))
3578
3579 (defun js2-print-unary-node (n i)
3580 (let* ((tt (js2-node-type n))
3581 (op (gethash tt js2-operator-tokens))
3582 (postfix (js2-node-get-prop n 'postfix)))
3583 (unless op
3584 (error "unrecognized unary operator %s" tt))
3585 (insert (js2-make-pad i))
3586 (unless postfix
3587 (insert op))
3588 (if (or (= tt js2-TYPEOF)
3589 (= tt js2-DELPROP)
3590 (= tt js2-AWAIT)
3591 (= tt js2-VOID))
3592 (insert " "))
3593 (js2-print-ast (js2-unary-node-operand n) 0)
3594 (when postfix
3595 (insert op))))
3596
3597 (cl-defstruct (js2-let-node
3598 (:include js2-scope)
3599 (:constructor nil)
3600 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3601 (pos (js2-current-token-beg))
3602 len vars body
3603 lp rp)))
3604 "AST node for a let expression or a let statement.
3605 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3606 vars ; a `js2-var-decl-node'
3607 body ; a `js2-node' representing the expression or body block
3608 lp
3609 rp)
3610
3611 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3612 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3613
3614 (defun js2-visit-let-node (n v)
3615 (js2-visit-ast (js2-let-node-vars n) v)
3616 (js2-visit-ast (js2-let-node-body n) v))
3617
3618 (defun js2-print-let-node (n i)
3619 (insert (js2-make-pad i) "let (")
3620 (let ((p (point)))
3621 (js2-print-ast (js2-let-node-vars n) 0)
3622 (delete-region p (+ p 4)))
3623 (insert ") ")
3624 (js2-print-ast (js2-let-node-body n) i))
3625
3626 (cl-defstruct (js2-keyword-node
3627 (:include js2-node)
3628 (:constructor nil)
3629 (:constructor make-js2-keyword-node (&key type
3630 (pos (js2-current-token-beg))
3631 (len (- js2-ts-cursor pos)))))
3632 "AST node representing a literal keyword such as `null'.
3633 Used for `null', `this', `true', `false' and `debugger'.
3634 The node type is set to js2-NULL, js2-THIS, etc.")
3635
3636 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3637 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3638
3639 (defun js2-print-keyword-node (n i)
3640 (insert (js2-make-pad i)
3641 (let ((tt (js2-node-type n)))
3642 (cond
3643 ((= tt js2-THIS) "this")
3644 ((= tt js2-SUPER) "super")
3645 ((= tt js2-NULL) "null")
3646 ((= tt js2-TRUE) "true")
3647 ((= tt js2-FALSE) "false")
3648 ((= tt js2-DEBUGGER) "debugger")
3649 (t (error "Invalid keyword literal type: %d" tt))))))
3650
3651 (defsubst js2-this-or-super-node-p (node)
3652 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3653 (let ((type (js2-node-type node)))
3654 (or (eq type js2-THIS) (eq type js2-SUPER))))
3655
3656 (cl-defstruct (js2-new-node
3657 (:include js2-node)
3658 (:constructor nil)
3659 (:constructor make-js2-new-node (&key (type js2-NEW)
3660 (pos (js2-current-token-beg))
3661 len target
3662 args initializer
3663 lp rp)))
3664 "AST node for new-expression such as new Foo()."
3665 target ; an identifier or reference
3666 args ; a Lisp list of argument nodes
3667 lp ; position of left-paren, nil if omitted
3668 rp ; position of right-paren, nil if omitted
3669 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3670
3671 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3672 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3673
3674 (defun js2-visit-new-node (n v)
3675 (js2-visit-ast (js2-new-node-target n) v)
3676 (dolist (arg (js2-new-node-args n))
3677 (js2-visit-ast arg v))
3678 (js2-visit-ast (js2-new-node-initializer n) v))
3679
3680 (defun js2-print-new-node (n i)
3681 (insert (js2-make-pad i) "new ")
3682 (js2-print-ast (js2-new-node-target n))
3683 (insert "(")
3684 (js2-print-list (js2-new-node-args n))
3685 (insert ")")
3686 (when (js2-new-node-initializer n)
3687 (insert " ")
3688 (js2-print-ast (js2-new-node-initializer n))))
3689
3690 (cl-defstruct (js2-name-node
3691 (:include js2-node)
3692 (:constructor nil)
3693 (:constructor make-js2-name-node (&key (type js2-NAME)
3694 (pos (js2-current-token-beg))
3695 (len (- js2-ts-cursor
3696 (js2-current-token-beg)))
3697 (name (js2-current-token-string)))))
3698 "AST node for a JavaScript identifier"
3699 name ; a string
3700 scope) ; a `js2-scope' (optional, used for codegen)
3701
3702 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3703 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3704
3705 (defun js2-print-name-node (n i)
3706 (insert (js2-make-pad i)
3707 (js2-name-node-name n)))
3708
3709 (defsubst js2-name-node-length (node)
3710 "Return identifier length of NODE, a `js2-name-node'.
3711 Returns 0 if NODE is nil or its identifier field is nil."
3712 (if node
3713 (length (js2-name-node-name node))
3714 0))
3715
3716 (cl-defstruct (js2-number-node
3717 (:include js2-node)
3718 (:constructor nil)
3719 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3720 (pos (js2-current-token-beg))
3721 (len (- js2-ts-cursor
3722 (js2-current-token-beg)))
3723 (value (js2-current-token-string))
3724 (num-value (js2-token-number
3725 (js2-current-token)))
3726 (num-base (js2-token-number-base
3727 (js2-current-token)))
3728 (legacy-octal-p (js2-token-number-legacy-octal-p
3729 (js2-current-token))))))
3730 "AST node for a number literal."
3731 value ; the original string, e.g. "6.02e23"
3732 num-value ; the parsed number value
3733 num-base ; the number's base
3734 legacy-octal-p) ; whether the number is a legacy octal (0123 instead of 0o123)
3735
3736 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3737 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3738
3739 (defun js2-print-number-node (n i)
3740 (insert (js2-make-pad i)
3741 (number-to-string (js2-number-node-num-value n))))
3742
3743 (cl-defstruct (js2-regexp-node
3744 (:include js2-node)
3745 (:constructor nil)
3746 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3747 (pos (js2-current-token-beg))
3748 (len (- js2-ts-cursor
3749 (js2-current-token-beg)))
3750 value flags)))
3751 "AST node for a regular expression literal."
3752 value ; the regexp string, without // delimiters
3753 flags) ; a string of flags, e.g. `mi'.
3754
3755 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3756 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3757
3758 (defun js2-print-regexp (n i)
3759 (insert (js2-make-pad i)
3760 "/"
3761 (js2-regexp-node-value n)
3762 "/")
3763 (if (js2-regexp-node-flags n)
3764 (insert (js2-regexp-node-flags n))))
3765
3766 (cl-defstruct (js2-string-node
3767 (:include js2-node)
3768 (:constructor nil)
3769 (:constructor make-js2-string-node (&key (type js2-STRING)
3770 (pos (js2-current-token-beg))
3771 (len (- js2-ts-cursor
3772 (js2-current-token-beg)))
3773 (value (js2-current-token-string)))))
3774 "String literal.
3775 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3776 You can tell the quote type by looking at the first character."
3777 value) ; the characters of the string, including the quotes
3778
3779 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3780 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3781
3782 (defun js2-print-string-node (n i)
3783 (insert (js2-make-pad i)
3784 (js2-node-string n)))
3785
3786 (cl-defstruct (js2-template-node
3787 (:include js2-node)
3788 (:constructor nil)
3789 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3790 beg len kids)))
3791 "Template literal."
3792 kids) ; `js2-string-node' is used for string segments, other nodes
3793 ; for substitutions inside.
3794
3795 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3796 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3797
3798 (defun js2-visit-template (n callback)
3799 (dolist (kid (js2-template-node-kids n))
3800 (js2-visit-ast kid callback)))
3801
3802 (defun js2-print-template (n i)
3803 (insert (js2-make-pad i))
3804 (dolist (kid (js2-template-node-kids n))
3805 (if (js2-string-node-p kid)
3806 (insert (js2-node-string kid))
3807 (js2-print-ast kid))))
3808
3809 (cl-defstruct (js2-tagged-template-node
3810 (:include js2-node)
3811 (:constructor nil)
3812 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3813 beg len tag template)))
3814 "Tagged template literal."
3815 tag ; `js2-node' with the tag expression.
3816 template) ; `js2-template-node' with the template.
3817
3818 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3819 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3820
3821 (defun js2-visit-tagged-template (n callback)
3822 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3823 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3824
3825 (defun js2-print-tagged-template (n i)
3826 (insert (js2-make-pad i))
3827 (js2-print-ast (js2-tagged-template-node-tag n))
3828 (js2-print-ast (js2-tagged-template-node-template n)))
3829
3830 (cl-defstruct (js2-array-node
3831 (:include js2-node)
3832 (:constructor nil)
3833 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3834 (pos js2-ts-cursor)
3835 len elems)))
3836 "AST node for an array literal."
3837 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3838
3839 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3840 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3841
3842 (defun js2-visit-array-node (n v)
3843 (dolist (e (js2-array-node-elems n))
3844 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3845
3846 (defun js2-print-array-node (n i)
3847 (insert (js2-make-pad i) "[")
3848 (let ((elems (js2-array-node-elems n)))
3849 (js2-print-list elems)
3850 (when (and elems (null (car (last elems))))
3851 (insert ",")))
3852 (insert "]"))
3853
3854 (cl-defstruct (js2-object-node
3855 (:include js2-node)
3856 (:constructor nil)
3857 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3858 (pos js2-ts-cursor)
3859 len
3860 elems)))
3861 "AST node for an object literal expression.
3862 `elems' is a list of `js2-object-prop-node'."
3863 elems)
3864
3865 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3866 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3867
3868 (defun js2-visit-object-node (n v)
3869 (dolist (e (js2-object-node-elems n))
3870 (js2-visit-ast e v)))
3871
3872 (defun js2-print-object-node (n i)
3873 (insert (js2-make-pad i) "{")
3874 (js2-print-list (js2-object-node-elems n))
3875 (insert "}"))
3876
3877 (cl-defstruct (js2-class-node
3878 (:include js2-object-node)
3879 (:constructor nil)
3880 (:constructor make-js2-class-node (&key (type js2-CLASS)
3881 (pos js2-ts-cursor)
3882 (form 'CLASS_STATEMENT)
3883 (name "")
3884 extends len elems)))
3885 "AST node for an class expression.
3886 `elems' is a list of `js2-object-prop-node', and `extends' is an
3887 optional `js2-expr-node'"
3888 form ; CLASS_{STATEMENT|EXPRESSION}
3889 name ; class name (a `js2-node-name', or nil if anonymous)
3890 extends ; class heritage (a `js2-expr-node', or nil if none)
3891 )
3892
3893 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3894 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3895
3896 (defun js2-visit-class-node (n v)
3897 (js2-visit-ast (js2-class-node-name n) v)
3898 (js2-visit-ast (js2-class-node-extends n) v)
3899 (dolist (e (js2-class-node-elems n))
3900 (js2-visit-ast e v)))
3901
3902 (defun js2-print-class-node (n i)
3903 (let* ((pad (js2-make-pad i))
3904 (name (js2-class-node-name n))
3905 (extends (js2-class-node-extends n))
3906 (elems (js2-class-node-elems n)))
3907 (insert pad "class")
3908 (when name
3909 (insert " ")
3910 (js2-print-ast name 0))
3911 (when extends
3912 (insert " extends ")
3913 (js2-print-ast extends))
3914 (insert " {")
3915 (dolist (elem elems)
3916 (insert "\n")
3917 (if (js2-node-get-prop elem 'STATIC)
3918 (progn (insert (js2-make-pad (1+ i)) "static ")
3919 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3920 (js2-print-ast elem (1+ i))))
3921 (insert "\n" pad "}")))
3922
3923 (cl-defstruct (js2-computed-prop-name-node
3924 (:include js2-node)
3925 (:constructor nil)
3926 (:constructor make-js2-computed-prop-name-node
3927 (&key
3928 (type js2-LB)
3929 expr
3930 (pos (js2-current-token-beg))
3931 (len (- js2-ts-cursor
3932 (js2-current-token-beg))))))
3933 "AST node for a `ComputedPropertyName'."
3934 expr)
3935
3936 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3937 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3938
3939 (defun js2-visit-computed-prop-name-node (n v)
3940 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3941
3942 (defun js2-print-computed-prop-name-node (n i)
3943 (insert (js2-make-pad i) "[")
3944 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3945 (insert "]"))
3946
3947 (cl-defstruct (js2-object-prop-node
3948 (:include js2-infix-node)
3949 (:constructor nil)
3950 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3951 (pos js2-ts-cursor)
3952 len left
3953 right op-pos)))
3954 "AST node for an object literal prop:value entry.
3955 The `left' field is the property: a name node, string node,
3956 number node or expression node. The `right' field is a
3957 `js2-node' representing the initializer value. If the property
3958 is abbreviated, the node's `SHORTHAND' property is non-nil and
3959 both fields have the same value.")
3960
3961 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3962 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3963
3964 (defun js2-print-object-prop-node (n i)
3965 (let* ((left (js2-object-prop-node-left n))
3966 (right (js2-object-prop-node-right n)))
3967 (js2-print-ast left i)
3968 (if (not (js2-node-get-prop n 'SHORTHAND))
3969 (progn
3970 (insert ": ")
3971 (js2-print-ast right 0)))))
3972
3973 (cl-defstruct (js2-method-node
3974 (:include js2-infix-node)
3975 (:constructor nil)
3976 (:constructor make-js2-method-node (&key (pos js2-ts-cursor)
3977 len left right)))
3978 "AST node for a method in an object literal or a class body.
3979 The `left' field is the `js2-name-node' naming the method.
3980 The `right' field is always an anonymous `js2-function-node' with a node
3981 property `METHOD_TYPE' set to 'GET or 'SET. ")
3982
3983 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3984 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3985
3986 (defun js2-print-method (n i)
3987 (let* ((pad (js2-make-pad i))
3988 (left (js2-method-node-left n))
3989 (right (js2-method-node-right n))
3990 (type (js2-node-get-prop right 'METHOD_TYPE)))
3991 (insert pad)
3992 (when type
3993 (insert (cdr (assoc type '((GET . "get ")
3994 (SET . "set ")
3995 (ASYNC . "async ")
3996 (FUNCTION . ""))))))
3997 (when (and (js2-function-node-p right)
3998 (eq 'STAR (js2-function-node-generator-type right)))
3999 (insert "*"))
4000 (js2-print-ast left 0)
4001 (js2-print-ast right 0)))
4002
4003 (cl-defstruct (js2-prop-get-node
4004 (:include js2-infix-node)
4005 (:constructor nil)
4006 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4007 (pos js2-ts-cursor)
4008 len left right)))
4009 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4010
4011 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4012 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4013
4014 (defun js2-visit-prop-get-node (n v)
4015 (js2-visit-ast (js2-prop-get-node-left n) v)
4016 (js2-visit-ast (js2-prop-get-node-right n) v))
4017
4018 (defun js2-print-prop-get-node (n i)
4019 (insert (js2-make-pad i))
4020 (js2-print-ast (js2-prop-get-node-left n) 0)
4021 (insert ".")
4022 (js2-print-ast (js2-prop-get-node-right n) 0))
4023
4024 (cl-defstruct (js2-elem-get-node
4025 (:include js2-node)
4026 (:constructor nil)
4027 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4028 (pos js2-ts-cursor)
4029 len target element
4030 lb rb)))
4031 "AST node for an array index expression such as foo[bar]."
4032 target ; a `js2-node' - the expression preceding the "."
4033 element ; a `js2-node' - the expression in brackets
4034 lb ; position of left-bracket, nil if omitted
4035 rb) ; position of right-bracket, nil if omitted
4036
4037 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4038 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4039
4040 (defun js2-visit-elem-get-node (n v)
4041 (js2-visit-ast (js2-elem-get-node-target n) v)
4042 (js2-visit-ast (js2-elem-get-node-element n) v))
4043
4044 (defun js2-print-elem-get-node (n i)
4045 (insert (js2-make-pad i))
4046 (js2-print-ast (js2-elem-get-node-target n) 0)
4047 (insert "[")
4048 (js2-print-ast (js2-elem-get-node-element n) 0)
4049 (insert "]"))
4050
4051 (cl-defstruct (js2-call-node
4052 (:include js2-node)
4053 (:constructor nil)
4054 (:constructor make-js2-call-node (&key (type js2-CALL)
4055 (pos js2-ts-cursor)
4056 len target args
4057 lp rp)))
4058 "AST node for a JavaScript function call."
4059 target ; a `js2-node' evaluating to the function to call
4060 args ; a Lisp list of `js2-node' arguments
4061 lp ; position of open-paren, or nil if missing
4062 rp) ; position of close-paren, or nil if missing
4063
4064 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4065 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4066
4067 (defun js2-visit-call-node (n v)
4068 (js2-visit-ast (js2-call-node-target n) v)
4069 (dolist (arg (js2-call-node-args n))
4070 (js2-visit-ast arg v)))
4071
4072 (defun js2-print-call-node (n i)
4073 (insert (js2-make-pad i))
4074 (js2-print-ast (js2-call-node-target n) 0)
4075 (insert "(")
4076 (js2-print-list (js2-call-node-args n))
4077 (insert ")"))
4078
4079 (cl-defstruct (js2-yield-node
4080 (:include js2-node)
4081 (:constructor nil)
4082 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4083 (pos js2-ts-cursor)
4084 len value star-p)))
4085 "AST node for yield statement or expression."
4086 star-p ; whether it's yield*
4087 value) ; optional: value to be yielded
4088
4089 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4090 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4091
4092 (defun js2-visit-yield-node (n v)
4093 (js2-visit-ast (js2-yield-node-value n) v))
4094
4095 (defun js2-print-yield-node (n i)
4096 (insert (js2-make-pad i))
4097 (insert "yield")
4098 (when (js2-yield-node-star-p n)
4099 (insert "*"))
4100 (when (js2-yield-node-value n)
4101 (insert " ")
4102 (js2-print-ast (js2-yield-node-value n) 0)))
4103
4104 (cl-defstruct (js2-paren-node
4105 (:include js2-node)
4106 (:constructor nil)
4107 (:constructor make-js2-paren-node (&key (type js2-LP)
4108 (pos js2-ts-cursor)
4109 len expr)))
4110 "AST node for a parenthesized expression.
4111 In particular, used when the parens are syntactically optional,
4112 as opposed to required parens such as those enclosing an if-conditional."
4113 expr) ; `js2-node'
4114
4115 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4116 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4117
4118 (defun js2-visit-paren-node (n v)
4119 (js2-visit-ast (js2-paren-node-expr n) v))
4120
4121 (defun js2-print-paren-node (n i)
4122 (insert (js2-make-pad i))
4123 (insert "(")
4124 (js2-print-ast (js2-paren-node-expr n) 0)
4125 (insert ")"))
4126
4127 (cl-defstruct (js2-comp-node
4128 (:include js2-scope)
4129 (:constructor nil)
4130 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4131 (pos js2-ts-cursor)
4132 len result
4133 loops filters
4134 form)))
4135 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4136 result ; result expression (just after left-bracket)
4137 loops ; a Lisp list of `js2-comp-loop-node'
4138 filters ; a Lisp list of guard/filter expressions
4139 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4140 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4141 )
4142
4143 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4144 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4145
4146 (defun js2-visit-comp-node (n v)
4147 (js2-visit-ast (js2-comp-node-result n) v)
4148 (dolist (l (js2-comp-node-loops n))
4149 (js2-visit-ast l v))
4150 (dolist (f (js2-comp-node-filters n))
4151 (js2-visit-ast f v)))
4152
4153 (defun js2-print-comp-node (n i)
4154 (let ((pad (js2-make-pad i))
4155 (result (js2-comp-node-result n))
4156 (loops (js2-comp-node-loops n))
4157 (filters (js2-comp-node-filters n))
4158 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4159 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4160 (insert pad (if gen-p "(" "["))
4161 (when legacy-p
4162 (js2-print-ast result 0))
4163 (dolist (l loops)
4164 (when legacy-p
4165 (insert " "))
4166 (js2-print-ast l 0)
4167 (unless legacy-p
4168 (insert " ")))
4169 (dolist (f filters)
4170 (when legacy-p
4171 (insert " "))
4172 (insert "if (")
4173 (js2-print-ast f 0)
4174 (insert ")")
4175 (unless legacy-p
4176 (insert " ")))
4177 (unless legacy-p
4178 (js2-print-ast result 0))
4179 (insert (if gen-p ")" "]"))))
4180
4181 (cl-defstruct (js2-comp-loop-node
4182 (:include js2-for-in-node)
4183 (:constructor nil)
4184 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4185 (pos js2-ts-cursor)
4186 len iterator
4187 object in-pos
4188 foreach-p
4189 each-pos
4190 forof-p
4191 lp rp)))
4192 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4193
4194 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4195 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4196
4197 (defun js2-visit-comp-loop (n v)
4198 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4199 (js2-visit-ast (js2-comp-loop-node-object n) v))
4200
4201 (defun js2-print-comp-loop (n _i)
4202 (insert "for ")
4203 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4204 (insert "(")
4205 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4206 (insert (if (js2-comp-loop-node-forof-p n)
4207 " of " " in "))
4208 (js2-print-ast (js2-comp-loop-node-object n) 0)
4209 (insert ")"))
4210
4211 (cl-defstruct (js2-empty-expr-node
4212 (:include js2-node)
4213 (:constructor nil)
4214 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4215 (pos (js2-current-token-beg))
4216 len)))
4217 "AST node for an empty expression.")
4218
4219 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4220 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4221
4222 (cl-defstruct (js2-xml-node
4223 (:include js2-block-node)
4224 (:constructor nil)
4225 (:constructor make-js2-xml-node (&key (type js2-XML)
4226 (pos (js2-current-token-beg))
4227 len kids)))
4228 "AST node for initial parse of E4X literals.
4229 The kids field is a list of XML fragments, each a `js2-string-node' or
4230 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4231
4232 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4233 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4234
4235 (defun js2-print-xml-node (n i)
4236 (dolist (kid (js2-xml-node-kids n))
4237 (js2-print-ast kid i)))
4238
4239 (cl-defstruct (js2-xml-js-expr-node
4240 (:include js2-xml-node)
4241 (:constructor nil)
4242 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4243 (pos js2-ts-cursor)
4244 len expr)))
4245 "AST node for an embedded JavaScript {expression} in an E4X literal.
4246 The start and end fields correspond to the curly-braces."
4247 expr) ; a `js2-expr-node' of some sort
4248
4249 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4250 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4251
4252 (defun js2-visit-xml-js-expr (n v)
4253 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4254
4255 (defun js2-print-xml-js-expr (n i)
4256 (insert (js2-make-pad i))
4257 (insert "{")
4258 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4259 (insert "}"))
4260
4261 (cl-defstruct (js2-xml-dot-query-node
4262 (:include js2-infix-node)
4263 (:constructor nil)
4264 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4265 (pos js2-ts-cursor)
4266 op-pos len left
4267 right rp)))
4268 "AST node for an E4X foo.(bar) filter expression.
4269 Note that the left-paren is automatically the character immediately
4270 following the dot (.) in the operator. No whitespace is permitted
4271 between the dot and the lp by the scanner."
4272 rp)
4273
4274 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4275 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4276
4277 (defun js2-print-xml-dot-query (n i)
4278 (insert (js2-make-pad i))
4279 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4280 (insert ".(")
4281 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4282 (insert ")"))
4283
4284 (cl-defstruct (js2-xml-ref-node
4285 (:include js2-node)
4286 (:constructor nil)) ; abstract
4287 "Base type for E4X XML attribute-access or property-get expressions.
4288 Such expressions can take a variety of forms. The general syntax has
4289 three parts:
4290
4291 - (optional) an @ (specifying an attribute access)
4292 - (optional) a namespace (a `js2-name-node') and double-colon
4293 - (required) either a `js2-name-node' or a bracketed [expression]
4294
4295 The property-name expressions (examples: ns::name, @name) are
4296 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4297 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4298
4299 This node type (or more specifically, its subclasses) will sometimes
4300 be the right-hand child of a `js2-prop-get-node' or a
4301 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4302 The `js2-xml-ref-node' may also be a standalone primary expression with
4303 no explicit target, which is valid in certain expression contexts such as
4304
4305 company..employee.(@id < 100)
4306
4307 in this case, the @id is a `js2-xml-ref' that is part of an infix `<'
4308 expression whose parent is a `js2-xml-dot-query-node'."
4309 namespace
4310 at-pos
4311 colon-pos)
4312
4313 (defsubst js2-xml-ref-node-attr-access-p (node)
4314 "Return non-nil if this expression began with an @-token."
4315 (and (numberp (js2-xml-ref-node-at-pos node))
4316 (cl-plusp (js2-xml-ref-node-at-pos node))))
4317
4318 (cl-defstruct (js2-xml-prop-ref-node
4319 (:include js2-xml-ref-node)
4320 (:constructor nil)
4321 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4322 (pos (js2-current-token-beg))
4323 len propname
4324 namespace at-pos
4325 colon-pos)))
4326 "AST node for an E4X XML [expr] property-ref expression.
4327 The JavaScript syntax is an optional @, an optional ns::, and a name.
4328
4329 [ `@' ] [ name `::' ] name
4330
4331 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4332 @ns::*, @*::attr, @*::*, and @*.
4333
4334 The node starts at the @ token, if present. Otherwise it starts at the
4335 namespace name. The node bounds extend through the closing right-bracket,
4336 or if it is missing due to a syntax error, through the end of the index
4337 expression."
4338 propname)
4339
4340 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4341 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4342
4343 (defun js2-visit-xml-prop-ref-node (n v)
4344 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4345 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4346
4347 (defun js2-print-xml-prop-ref-node (n i)
4348 (insert (js2-make-pad i))
4349 (if (js2-xml-ref-node-attr-access-p n)
4350 (insert "@"))
4351 (when (js2-xml-prop-ref-node-namespace n)
4352 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4353 (insert "::"))
4354 (if (js2-xml-prop-ref-node-propname n)
4355 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4356
4357 (cl-defstruct (js2-xml-elem-ref-node
4358 (:include js2-xml-ref-node)
4359 (:constructor nil)
4360 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4361 (pos (js2-current-token-beg))
4362 len expr lb rb
4363 namespace at-pos
4364 colon-pos)))
4365 "AST node for an E4X XML [expr] member-ref expression.
4366 Syntax:
4367
4368 [ `@' ] [ name `::' ] `[' expr `]'
4369
4370 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4371
4372 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4373 is not a legal E4X XML element-ref expression, since it's already used
4374 for standard JavaScript element-get array indexing. Hence, a
4375 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4376 non-nil namespace node, or both.
4377
4378 The node starts at the @ token, if present. Otherwise it starts
4379 at the namespace name. The node bounds extend through the closing
4380 right-bracket, or if it is missing due to a syntax error, through the
4381 end of the index expression."
4382 expr ; the bracketed index expression
4383 lb
4384 rb)
4385
4386 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4387 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4388
4389 (defun js2-visit-xml-elem-ref-node (n v)
4390 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4391 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4392
4393 (defun js2-print-xml-elem-ref-node (n i)
4394 (insert (js2-make-pad i))
4395 (if (js2-xml-ref-node-attr-access-p n)
4396 (insert "@"))
4397 (when (js2-xml-elem-ref-node-namespace n)
4398 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4399 (insert "::"))
4400 (insert "[")
4401 (if (js2-xml-elem-ref-node-expr n)
4402 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4403 (insert "]"))
4404
4405 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4406
4407 (cl-defstruct (js2-xml-start-tag-node
4408 (:include js2-xml-node)
4409 (:constructor nil)
4410 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4411 (pos js2-ts-cursor)
4412 len name attrs kids
4413 empty-p)))
4414 "AST node for an XML start-tag. Not currently used.
4415 The `kids' field is a Lisp list of child content nodes."
4416 name ; a `js2-xml-name-node'
4417 attrs ; a Lisp list of `js2-xml-attr-node'
4418 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4419
4420 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4421 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4422
4423 (defun js2-visit-xml-start-tag (n v)
4424 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4425 (dolist (attr (js2-xml-start-tag-node-attrs n))
4426 (js2-visit-ast attr v))
4427 (js2-visit-block n v))
4428
4429 (defun js2-print-xml-start-tag (n i)
4430 (insert (js2-make-pad i) "<")
4431 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4432 (when (js2-xml-start-tag-node-attrs n)
4433 (insert " ")
4434 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4435 (insert ">"))
4436
4437 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4438 ;; and add the end-tag to the kids list of the parent as well.
4439 (cl-defstruct (js2-xml-end-tag-node
4440 (:include js2-xml-node)
4441 (:constructor nil)
4442 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4443 (pos js2-ts-cursor)
4444 len name)))
4445 "AST node for an XML end-tag. Not currently used."
4446 name) ; a `js2-xml-name-node'
4447
4448 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4449 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4450
4451 (defun js2-visit-xml-end-tag (n v)
4452 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4453
4454 (defun js2-print-xml-end-tag (n i)
4455 (insert (js2-make-pad i))
4456 (insert "</")
4457 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4458 (insert ">"))
4459
4460 (cl-defstruct (js2-xml-name-node
4461 (:include js2-xml-node)
4462 (:constructor nil)
4463 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4464 (pos js2-ts-cursor)
4465 len namespace kids)))
4466 "AST node for an E4X XML name. Not currently used.
4467 Any XML name can be qualified with a namespace, hence the namespace field.
4468 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4469 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4470 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4471 namespace) ; a `js2-string-node'
4472
4473 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4474 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4475
4476 (defun js2-visit-xml-name-node (n v)
4477 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4478
4479 (defun js2-print-xml-name-node (n i)
4480 (insert (js2-make-pad i))
4481 (when (js2-xml-name-node-namespace n)
4482 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4483 (insert "::"))
4484 (dolist (kid (js2-xml-name-node-kids n))
4485 (js2-print-ast kid 0)))
4486
4487 (cl-defstruct (js2-xml-pi-node
4488 (:include js2-xml-node)
4489 (:constructor nil)
4490 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4491 (pos js2-ts-cursor)
4492 len name attrs)))
4493 "AST node for an E4X XML processing instruction. Not currently used."
4494 name ; a `js2-xml-name-node'
4495 attrs) ; a list of `js2-xml-attr-node'
4496
4497 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4498 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4499
4500 (defun js2-visit-xml-pi-node (n v)
4501 (js2-visit-ast (js2-xml-pi-node-name n) v)
4502 (dolist (attr (js2-xml-pi-node-attrs n))
4503 (js2-visit-ast attr v)))
4504
4505 (defun js2-print-xml-pi-node (n i)
4506 (insert (js2-make-pad i) "<?")
4507 (js2-print-ast (js2-xml-pi-node-name n))
4508 (when (js2-xml-pi-node-attrs n)
4509 (insert " ")
4510 (js2-print-list (js2-xml-pi-node-attrs n)))
4511 (insert "?>"))
4512
4513 (cl-defstruct (js2-xml-cdata-node
4514 (:include js2-xml-node)
4515 (:constructor nil)
4516 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4517 (pos js2-ts-cursor)
4518 len content)))
4519 "AST node for a CDATA escape section. Not currently used."
4520 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4521
4522 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4523 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4524
4525 (defun js2-visit-xml-cdata-node (n v)
4526 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4527
4528 (defun js2-print-xml-cdata-node (n i)
4529 (insert (js2-make-pad i))
4530 (js2-print-ast (js2-xml-cdata-node-content n)))
4531
4532 (cl-defstruct (js2-xml-attr-node
4533 (:include js2-xml-node)
4534 (:constructor nil)
4535 (:constructor make-js2-attr-node (&key (type js2-XML)
4536 (pos js2-ts-cursor)
4537 len name value
4538 eq-pos quote-type)))
4539 "AST node representing a foo=\\='bar\\=' XML attribute value. Not yet used."
4540 name ; a `js2-xml-name-node'
4541 value ; a `js2-xml-name-node'
4542 eq-pos ; buffer position of "=" sign
4543 quote-type) ; 'single or 'double
4544
4545 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4546 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4547
4548 (defun js2-visit-xml-attr-node (n v)
4549 (js2-visit-ast (js2-xml-attr-node-name n) v)
4550 (js2-visit-ast (js2-xml-attr-node-value n) v))
4551
4552 (defun js2-print-xml-attr-node (n i)
4553 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4554 "'"
4555 "\"")))
4556 (insert (js2-make-pad i))
4557 (js2-print-ast (js2-xml-attr-node-name n) 0)
4558 (insert "=" quote)
4559 (js2-print-ast (js2-xml-attr-node-value n) 0)
4560 (insert quote)))
4561
4562 (cl-defstruct (js2-xml-text-node
4563 (:include js2-xml-node)
4564 (:constructor nil)
4565 (:constructor make-js2-text-node (&key (type js2-XML)
4566 (pos js2-ts-cursor)
4567 len content)))
4568 "AST node for an E4X XML text node. Not currently used."
4569 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4570
4571 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4572 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4573
4574 (defun js2-visit-xml-text-node (n v)
4575 (js2-visit-ast (js2-xml-text-node-content n) v))
4576
4577 (defun js2-print-xml-text-node (n i)
4578 (insert (js2-make-pad i))
4579 (dolist (kid (js2-xml-text-node-content n))
4580 (js2-print-ast kid)))
4581
4582 (cl-defstruct (js2-xml-comment-node
4583 (:include js2-xml-node)
4584 (:constructor nil)
4585 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4586 (pos js2-ts-cursor)
4587 len)))
4588 "AST node for E4X XML comment. Not currently used.")
4589
4590 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4591 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4592
4593 (defun js2-print-xml-comment (n i)
4594 (insert (js2-make-pad i)
4595 (js2-node-string n)))
4596
4597 ;;; Node utilities
4598
4599 (defsubst js2-node-line (n)
4600 "Fetch the source line number at the start of node N.
4601 This is O(n) in the length of the source buffer; use prudently."
4602 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4603
4604 (defsubst js2-block-node-kid (n i)
4605 "Return child I of node N, or nil if there aren't that many."
4606 (nth i (js2-block-node-kids n)))
4607
4608 (defsubst js2-block-node-first (n)
4609 "Return first child of block node N, or nil if there is none."
4610 (cl-first (js2-block-node-kids n)))
4611
4612 (defun js2-node-root (n)
4613 "Return the root of the AST containing N.
4614 If N has no parent pointer, returns N."
4615 (let ((parent (js2-node-parent n)))
4616 (if parent
4617 (js2-node-root parent)
4618 n)))
4619
4620 (defsubst js2-node-short-name (n)
4621 "Return the short name of node N as a string, e.g. `js2-if-node'."
4622 (substring (symbol-name (aref n 0))
4623 (length "cl-struct-")))
4624
4625 (defun js2-node-child-list (node)
4626 "Return the child list for NODE, a Lisp list of nodes.
4627 Works for block nodes, array nodes, obj literals, funarg lists,
4628 var decls and try nodes (for catch clauses). Note that you should call
4629 `js2-block-node-kids' on the function body for the body statements.
4630 Returns nil for zero-length child lists or unsupported nodes."
4631 (cond
4632 ((js2-function-node-p node)
4633 (js2-function-node-params node))
4634 ((js2-block-node-p node)
4635 (js2-block-node-kids node))
4636 ((js2-try-node-p node)
4637 (js2-try-node-catch-clauses node))
4638 ((js2-array-node-p node)
4639 (js2-array-node-elems node))
4640 ((js2-object-node-p node)
4641 (js2-object-node-elems node))
4642 ((js2-call-node-p node)
4643 (js2-call-node-args node))
4644 ((js2-new-node-p node)
4645 (js2-new-node-args node))
4646 ((js2-var-decl-node-p node)
4647 (js2-var-decl-node-kids node))
4648 (t
4649 nil)))
4650
4651 (defun js2-node-set-child-list (node kids)
4652 "Set the child list for NODE to KIDS."
4653 (cond
4654 ((js2-function-node-p node)
4655 (setf (js2-function-node-params node) kids))
4656 ((js2-block-node-p node)
4657 (setf (js2-block-node-kids node) kids))
4658 ((js2-try-node-p node)
4659 (setf (js2-try-node-catch-clauses node) kids))
4660 ((js2-array-node-p node)
4661 (setf (js2-array-node-elems node) kids))
4662 ((js2-object-node-p node)
4663 (setf (js2-object-node-elems node) kids))
4664 ((js2-call-node-p node)
4665 (setf (js2-call-node-args node) kids))
4666 ((js2-new-node-p node)
4667 (setf (js2-new-node-args node) kids))
4668 ((js2-var-decl-node-p node)
4669 (setf (js2-var-decl-node-kids node) kids))
4670 (t
4671 (error "Unsupported node type: %s" (js2-node-short-name node))))
4672 kids)
4673
4674 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4675 (defconst js2-paren-expr-nodes
4676 '(cl-struct-js2-comp-loop-node
4677 cl-struct-js2-comp-node
4678 cl-struct-js2-call-node
4679 cl-struct-js2-catch-node
4680 cl-struct-js2-do-node
4681 cl-struct-js2-elem-get-node
4682 cl-struct-js2-for-in-node
4683 cl-struct-js2-for-node
4684 cl-struct-js2-function-node
4685 cl-struct-js2-if-node
4686 cl-struct-js2-let-node
4687 cl-struct-js2-new-node
4688 cl-struct-js2-paren-node
4689 cl-struct-js2-switch-node
4690 cl-struct-js2-while-node
4691 cl-struct-js2-with-node
4692 cl-struct-js2-xml-dot-query-node)
4693 "Node types that can have a parenthesized child expression.
4694 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4695
4696 (defsubst js2-paren-expr-node-p (node)
4697 "Return t for nodes that typically have a parenthesized child expression.
4698 Useful for computing the indentation anchors for arg-lists and conditions.
4699 Note that it may return a false positive, for instance when NODE is
4700 a `js2-new-node' and there are no arguments or parentheses."
4701 (memq (aref node 0) js2-paren-expr-nodes))
4702
4703 ;; Fake polymorphism... yech.
4704 (defun js2-node-lp (node)
4705 "Return relative left-paren position for NODE, if applicable.
4706 For `js2-elem-get-node' structs, returns left-bracket position.
4707 Note that the position may be nil in the case of a parse error."
4708 (cond
4709 ((js2-elem-get-node-p node)
4710 (js2-elem-get-node-lb node))
4711 ((js2-loop-node-p node)
4712 (js2-loop-node-lp node))
4713 ((js2-function-node-p node)
4714 (js2-function-node-lp node))
4715 ((js2-if-node-p node)
4716 (js2-if-node-lp node))
4717 ((js2-new-node-p node)
4718 (js2-new-node-lp node))
4719 ((js2-call-node-p node)
4720 (js2-call-node-lp node))
4721 ((js2-paren-node-p node)
4722 0)
4723 ((js2-switch-node-p node)
4724 (js2-switch-node-lp node))
4725 ((js2-catch-node-p node)
4726 (js2-catch-node-lp node))
4727 ((js2-let-node-p node)
4728 (js2-let-node-lp node))
4729 ((js2-comp-node-p node)
4730 0)
4731 ((js2-with-node-p node)
4732 (js2-with-node-lp node))
4733 ((js2-xml-dot-query-node-p node)
4734 (1+ (js2-infix-node-op-pos node)))
4735 (t
4736 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4737
4738 ;; Fake polymorphism... blech.
4739 (defun js2-node-rp (node)
4740 "Return relative right-paren position for NODE, if applicable.
4741 For `js2-elem-get-node' structs, returns right-bracket position.
4742 Note that the position may be nil in the case of a parse error."
4743 (cond
4744 ((js2-elem-get-node-p node)
4745 (js2-elem-get-node-rb node))
4746 ((js2-loop-node-p node)
4747 (js2-loop-node-rp node))
4748 ((js2-function-node-p node)
4749 (js2-function-node-rp node))
4750 ((js2-if-node-p node)
4751 (js2-if-node-rp node))
4752 ((js2-new-node-p node)
4753 (js2-new-node-rp node))
4754 ((js2-call-node-p node)
4755 (js2-call-node-rp node))
4756 ((js2-paren-node-p node)
4757 (1- (js2-node-len node)))
4758 ((js2-switch-node-p node)
4759 (js2-switch-node-rp node))
4760 ((js2-catch-node-p node)
4761 (js2-catch-node-rp node))
4762 ((js2-let-node-p node)
4763 (js2-let-node-rp node))
4764 ((js2-comp-node-p node)
4765 (1- (js2-node-len node)))
4766 ((js2-with-node-p node)
4767 (js2-with-node-rp node))
4768 ((js2-xml-dot-query-node-p node)
4769 (1+ (js2-xml-dot-query-node-rp node)))
4770 (t
4771 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4772
4773 (defsubst js2-node-first-child (node)
4774 "Return the first element of `js2-node-child-list' for NODE."
4775 (car (js2-node-child-list node)))
4776
4777 (defsubst js2-node-last-child (node)
4778 "Return the last element of `js2-node-last-child' for NODE."
4779 (car (last (js2-node-child-list node))))
4780
4781 (defun js2-node-prev-sibling (node)
4782 "Return the previous statement in parent.
4783 Works for parents supported by `js2-node-child-list'.
4784 Returns nil if NODE is not in the parent, or PARENT is
4785 not a supported node, or if NODE is the first child."
4786 (let* ((p (js2-node-parent node))
4787 (kids (js2-node-child-list p))
4788 (sib (car kids)))
4789 (while (and kids
4790 (not (eq node (cadr kids))))
4791 (setq kids (cdr kids)
4792 sib (car kids)))
4793 sib))
4794
4795 (defun js2-node-next-sibling (node)
4796 "Return the next statement in parent block.
4797 Returns nil if NODE is not in the block, or PARENT is not
4798 a block node, or if NODE is the last statement."
4799 (let* ((p (js2-node-parent node))
4800 (kids (js2-node-child-list p)))
4801 (while (and kids
4802 (not (eq node (car kids))))
4803 (setq kids (cdr kids)))
4804 (cadr kids)))
4805
4806 (defun js2-node-find-child-before (pos parent &optional after)
4807 "Find the last child that starts before POS in parent.
4808 If AFTER is non-nil, returns first child starting after POS.
4809 POS is an absolute buffer position. PARENT is any node
4810 supported by `js2-node-child-list'.
4811 Returns nil if no applicable child is found."
4812 (let ((kids (if (js2-function-node-p parent)
4813 (js2-block-node-kids (js2-function-node-body parent))
4814 (js2-node-child-list parent)))
4815 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4816 (js2-function-node-body parent)
4817 parent)))
4818 kid result fn
4819 (continue t))
4820 (setq fn (if after '>= '<))
4821 (while (and kids continue)
4822 (setq kid (car kids))
4823 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4824 (setq result kid
4825 continue (not after))
4826 (setq continue after))
4827 (setq kids (cdr kids)))
4828 result))
4829
4830 (defun js2-node-find-child-after (pos parent)
4831 "Find first child that starts after POS in parent.
4832 POS is an absolute buffer position. PARENT is any node
4833 supported by `js2-node-child-list'.
4834 Returns nil if no applicable child is found."
4835 (js2-node-find-child-before pos parent 'after))
4836
4837 (defun js2-node-replace-child (pos parent new-node)
4838 "Replace node at index POS in PARENT with NEW-NODE.
4839 Only works for parents supported by `js2-node-child-list'."
4840 (let ((kids (js2-node-child-list parent))
4841 (i 0))
4842 (while (< i pos)
4843 (setq kids (cdr kids)
4844 i (1+ i)))
4845 (setcar kids new-node)
4846 (js2-node-add-children parent new-node)))
4847
4848 (defun js2-node-buffer (n)
4849 "Return the buffer associated with AST N.
4850 Returns nil if the buffer is not set as a property on the root
4851 node, or if parent links were not recorded during parsing."
4852 (let ((root (js2-node-root n)))
4853 (and root
4854 (js2-ast-root-p root)
4855 (js2-ast-root-buffer root))))
4856
4857 (defun js2-block-node-push (n kid)
4858 "Push js2-node KID onto the end of js2-block-node N's child list.
4859 KID is always added to the -end- of the kids list.
4860 Function also calls `js2-node-add-children' to add the parent link."
4861 (let ((kids (js2-node-child-list n)))
4862 (if kids
4863 (setcdr kids (nconc (cdr kids) (list kid)))
4864 (js2-node-set-child-list n (list kid)))
4865 (js2-node-add-children n kid)))
4866
4867 (defun js2-node-string (node)
4868 (with-current-buffer (or (js2-node-buffer node)
4869 (error "No buffer available for node %s" node))
4870 (let ((pos (js2-node-abs-pos node)))
4871 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4872
4873 ;; Container for storing the node we're looking for in a traversal.
4874 (js2-deflocal js2-discovered-node nil)
4875
4876 ;; Keep track of absolute node position during traversals.
4877 (js2-deflocal js2-visitor-offset nil)
4878
4879 (js2-deflocal js2-node-search-point nil)
4880
4881 (when js2-mode-dev-mode-p
4882 (defun js2-find-node-at-point ()
4883 (interactive)
4884 (let ((node (js2-node-at-point)))
4885 (message "%s" (or node "No node found at point"))))
4886 (defun js2-node-name-at-point ()
4887 (interactive)
4888 (let ((node (js2-node-at-point)))
4889 (message "%s" (if node
4890 (js2-node-short-name node)
4891 "No node found at point.")))))
4892
4893 (defun js2-node-at-point (&optional pos skip-comments)
4894 "Return AST node at POS, a buffer position, defaulting to current point.
4895 The `js2-mode-ast' variable must be set to the current parse tree.
4896 Signals an error if the AST (`js2-mode-ast') is nil.
4897 Always returns a node - if it can't find one, it returns the root.
4898 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4899 (let ((ast js2-mode-ast)
4900 result)
4901 (unless ast
4902 (error "No JavaScript AST available"))
4903 ;; Look through comments first, since they may be inside nodes that
4904 ;; would otherwise report a match.
4905 (setq pos (or pos (point))
4906 result (if (> pos (js2-node-abs-end ast))
4907 ast
4908 (if (not skip-comments)
4909 (js2-comment-at-point pos))))
4910 (unless result
4911 (setq js2-discovered-node nil
4912 js2-visitor-offset 0
4913 js2-node-search-point pos)
4914 (unwind-protect
4915 (catch 'js2-visit-done
4916 (js2-visit-ast ast #'js2-node-at-point-visitor))
4917 (setq js2-visitor-offset nil
4918 js2-node-search-point nil))
4919 (setq result js2-discovered-node))
4920 ;; may have found a comment beyond end of last child node,
4921 ;; since visiting the ast-root looks at the comment-list last.
4922 (if (and skip-comments
4923 (js2-comment-node-p result))
4924 (setq result nil))
4925 (or result js2-mode-ast)))
4926
4927 (defun js2-node-at-point-visitor (node end-p)
4928 (let ((rel-pos (js2-node-pos node))
4929 abs-pos
4930 abs-end
4931 (point js2-node-search-point))
4932 (cond
4933 (end-p
4934 ;; this evaluates to a non-nil return value, even if it's zero
4935 (cl-decf js2-visitor-offset rel-pos))
4936 ;; we already looked for comments before visiting, and don't want them now
4937 ((js2-comment-node-p node)
4938 nil)
4939 (t
4940 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4941 ;; we only want to use the node if the point is before
4942 ;; the last character position in the node, so we decrement
4943 ;; the absolute end by 1.
4944 abs-end (+ abs-pos (js2-node-len node) -1))
4945 (cond
4946 ;; If this node starts after search-point, stop the search.
4947 ((> abs-pos point)
4948 (throw 'js2-visit-done nil))
4949 ;; If this node ends before the search-point, don't check kids.
4950 ((> point abs-end)
4951 nil)
4952 (t
4953 ;; Otherwise point is within this node, possibly in a child.
4954 (setq js2-discovered-node node)
4955 t)))))) ; keep processing kids to look for more specific match
4956
4957 (defsubst js2-block-comment-p (node)
4958 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4959 (and (js2-comment-node-p node)
4960 (memq (js2-comment-node-format node) '(jsdoc block))))
4961
4962 ;; TODO: put the comments in a vector and binary-search them instead
4963 (defun js2-comment-at-point (&optional pos)
4964 "Look through scanned comment nodes for one containing POS.
4965 POS is a buffer position that defaults to current point.
4966 Function returns nil if POS was not in any comment node."
4967 (let ((ast js2-mode-ast)
4968 (x (or pos (point)))
4969 beg end)
4970 (unless ast
4971 (error "No JavaScript AST available"))
4972 (catch 'done
4973 ;; Comments are stored in lexical order.
4974 (dolist (comment (js2-ast-root-comments ast) nil)
4975 (setq beg (js2-node-abs-pos comment)
4976 end (+ beg (js2-node-len comment)))
4977 (if (and (>= x beg)
4978 (<= x end))
4979 (throw 'done comment))))))
4980
4981 (defun js2-mode-find-parent-fn (node)
4982 "Find function enclosing NODE.
4983 Returns nil if NODE is not inside a function."
4984 (setq node (js2-node-parent node))
4985 (while (and node (not (js2-function-node-p node)))
4986 (setq node (js2-node-parent node)))
4987 (and (js2-function-node-p node) node))
4988
4989 (defun js2-mode-find-enclosing-fn (node)
4990 "Find function or root enclosing NODE."
4991 (if (js2-ast-root-p node)
4992 node
4993 (setq node (js2-node-parent node))
4994 (while (not (or (js2-ast-root-p node)
4995 (js2-function-node-p node)))
4996 (setq node (js2-node-parent node)))
4997 node))
4998
4999 (defun js2-mode-find-enclosing-node (beg end)
5000 "Find node fully enclosing BEG and END."
5001 (let ((node (js2-node-at-point beg))
5002 pos
5003 (continue t))
5004 (while continue
5005 (if (or (js2-ast-root-p node)
5006 (and
5007 (<= (setq pos (js2-node-abs-pos node)) beg)
5008 (>= (+ pos (js2-node-len node)) end)))
5009 (setq continue nil)
5010 (setq node (js2-node-parent node))))
5011 node))
5012
5013 (defun js2-node-parent-script-or-fn (node)
5014 "Find script or function immediately enclosing NODE.
5015 If NODE is the ast-root, returns nil."
5016 (if (js2-ast-root-p node)
5017 nil
5018 (setq node (js2-node-parent node))
5019 (while (and node (not (or (js2-function-node-p node)
5020 (js2-script-node-p node))))
5021 (setq node (js2-node-parent node)))
5022 node))
5023
5024 (defun js2-node-is-descendant (node ancestor)
5025 "Return t if NODE is a descendant of ANCESTOR."
5026 (while (and node
5027 (not (eq node ancestor)))
5028 (setq node (js2-node-parent node)))
5029 node)
5030
5031 ;;; visitor infrastructure
5032
5033 (defun js2-visit-none (_node _callback)
5034 "Visitor for AST node that have no node children."
5035 nil)
5036
5037 (defun js2-print-none (_node _indent)
5038 "Visitor for AST node with no printed representation.")
5039
5040 (defun js2-print-body (node indent)
5041 "Print a statement, or a block without braces."
5042 (if (js2-block-node-p node)
5043 (dolist (kid (js2-block-node-kids node))
5044 (js2-print-ast kid indent))
5045 (js2-print-ast node indent)))
5046
5047 (defun js2-print-list (args &optional delimiter)
5048 (cl-loop with len = (length args)
5049 for arg in args
5050 for count from 1
5051 do
5052 (when arg (js2-print-ast arg 0))
5053 (if (< count len)
5054 (insert (or delimiter ", ")))))
5055
5056 (defun js2-print-tree (ast)
5057 "Prints an AST to the current buffer.
5058 Makes `js2-ast-parent-nodes' available to the printer functions."
5059 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5060 (js2-print-ast ast)))
5061
5062 (defun js2-print-ast (node &optional indent)
5063 "Helper function for printing AST nodes.
5064 Requires `js2-ast-parent-nodes' to be non-nil.
5065 You should use `js2-print-tree' instead of this function."
5066 (let ((printer (get (aref node 0) 'js2-printer))
5067 (i (or indent 0)))
5068 ;; TODO: wedge comments in here somewhere
5069 (if printer
5070 (funcall printer node i))))
5071
5072 (defconst js2-side-effecting-tokens
5073 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5074 (dolist (tt (list js2-ASSIGN
5075 js2-ASSIGN_ADD
5076 js2-ASSIGN_BITAND
5077 js2-ASSIGN_BITOR
5078 js2-ASSIGN_BITXOR
5079 js2-ASSIGN_DIV
5080 js2-ASSIGN_LSH
5081 js2-ASSIGN_MOD
5082 js2-ASSIGN_MUL
5083 js2-ASSIGN_RSH
5084 js2-ASSIGN_SUB
5085 js2-ASSIGN_URSH
5086 js2-BLOCK
5087 js2-BREAK
5088 js2-CALL
5089 js2-CATCH
5090 js2-CATCH_SCOPE
5091 js2-CLASS
5092 js2-CONST
5093 js2-CONTINUE
5094 js2-DEBUGGER
5095 js2-DEC
5096 js2-DELPROP
5097 js2-DEL_REF
5098 js2-DO
5099 js2-ELSE
5100 js2-EMPTY
5101 js2-ENTERWITH
5102 js2-EXPORT
5103 js2-EXPR_RESULT
5104 js2-FINALLY
5105 js2-FOR
5106 js2-FUNCTION
5107 js2-GOTO
5108 js2-IF
5109 js2-IFEQ
5110 js2-IFNE
5111 js2-IMPORT
5112 js2-INC
5113 js2-JSR
5114 js2-LABEL
5115 js2-LEAVEWITH
5116 js2-LET
5117 js2-LETEXPR
5118 js2-LOCAL_BLOCK
5119 js2-LOOP
5120 js2-NEW
5121 js2-REF_CALL
5122 js2-RETHROW
5123 js2-RETURN
5124 js2-RETURN_RESULT
5125 js2-SEMI
5126 js2-SETELEM
5127 js2-SETELEM_OP
5128 js2-SETNAME
5129 js2-SETPROP
5130 js2-SETPROP_OP
5131 js2-SETVAR
5132 js2-SET_REF
5133 js2-SET_REF_OP
5134 js2-SWITCH
5135 js2-TARGET
5136 js2-THROW
5137 js2-TRY
5138 js2-VAR
5139 js2-WHILE
5140 js2-WITH
5141 js2-WITHEXPR
5142 js2-YIELD))
5143 (aset tokens tt t))
5144 (if js2-instanceof-has-side-effects
5145 (aset tokens js2-INSTANCEOF t))
5146 tokens))
5147
5148 (defun js2-node-has-side-effects (node)
5149 "Return t if NODE has side effects."
5150 (when node ; makes it easier to handle malformed expressions
5151 (let ((tt (js2-node-type node)))
5152 (cond
5153 ;; This doubtless needs some work, since EXPR_VOID is used
5154 ;; in several ways in Rhino and I may not have caught them all.
5155 ;; I'll wait for people to notice incorrect warnings.
5156 ((and (= tt js2-EXPR_VOID)
5157 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5158 (let ((expr (js2-expr-stmt-node-expr node)))
5159 (or (js2-node-has-side-effects expr)
5160 (when (js2-string-node-p expr)
5161 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5162 ((= tt js2-AWAIT)
5163 (js2-node-has-side-effects (js2-unary-node-operand node)))
5164 ((= tt js2-COMMA)
5165 (js2-node-has-side-effects (js2-infix-node-right node)))
5166 ((or (= tt js2-AND)
5167 (= tt js2-OR))
5168 (or (js2-node-has-side-effects (js2-infix-node-right node))
5169 (js2-node-has-side-effects (js2-infix-node-left node))))
5170 ((= tt js2-HOOK)
5171 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5172 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5173 ((js2-paren-node-p node)
5174 (js2-node-has-side-effects (js2-paren-node-expr node)))
5175 ((= tt js2-ERROR) ; avoid cascaded error messages
5176 nil)
5177 (t
5178 (aref js2-side-effecting-tokens tt))))))
5179
5180 (defconst js2-stmt-node-types
5181 (list js2-BLOCK
5182 js2-BREAK
5183 js2-CONTINUE
5184 js2-DEFAULT ; e4x "default xml namespace" statement
5185 js2-DO
5186 js2-EXPORT
5187 js2-EXPR_RESULT
5188 js2-EXPR_VOID
5189 js2-FOR
5190 js2-IF
5191 js2-IMPORT
5192 js2-RETURN
5193 js2-SWITCH
5194 js2-THROW
5195 js2-TRY
5196 js2-WHILE
5197 js2-WITH)
5198 "Node types that only appear in statement contexts.
5199 The list does not include nodes that always appear as the child
5200 of another specific statement type, such as switch-cases,
5201 catch and finally blocks, and else-clauses. The list also excludes
5202 nodes like yield, let and var, which may appear in either expression
5203 or statement context, and in the latter context always have a
5204 `js2-expr-stmt-node' parent. Finally, the list does not include
5205 functions or scripts, which are treated separately from statements
5206 by the JavaScript parser and runtime.")
5207
5208 (defun js2-stmt-node-p (node)
5209 "Heuristic for figuring out if NODE is a statement.
5210 Some node types can appear in either an expression context or a
5211 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5212 For these node types in a statement context, the parent will be a
5213 `js2-expr-stmt-node'.
5214 Functions aren't included in the check."
5215 (memq (js2-node-type node) js2-stmt-node-types))
5216
5217 (defun js2-mode-find-first-stmt (node)
5218 "Search upward starting from NODE looking for a statement.
5219 For purposes of this function, a `js2-function-node' counts."
5220 (while (not (or (js2-stmt-node-p node)
5221 (js2-function-node-p node)))
5222 (setq node (js2-node-parent node)))
5223 node)
5224
5225 (defun js2-node-parent-stmt (node)
5226 "Return the node's first ancestor that is a statement.
5227 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5228 appearing in a statement context will have a parent that is a
5229 `js2-expr-stmt-node' that will be returned by this function."
5230 (let ((parent (js2-node-parent node)))
5231 (if (or (null parent)
5232 (js2-stmt-node-p parent)
5233 (and (js2-function-node-p parent)
5234 (not (eq (js2-function-node-form parent)
5235 'FUNCTION_EXPRESSION))))
5236 parent
5237 (js2-node-parent-stmt parent))))
5238
5239 ;; In the Mozilla Rhino sources, Roshan James writes:
5240 ;; Does consistent-return analysis on the function body when strict mode is
5241 ;; enabled.
5242 ;;
5243 ;; function (x) { return (x+1) }
5244 ;;
5245 ;; is ok, but
5246 ;;
5247 ;; function (x) { if (x < 0) return (x+1); }
5248 ;;
5249 ;; is not because the function can potentially return a value when the
5250 ;; condition is satisfied and if not, the function does not explicitly
5251 ;; return a value.
5252 ;;
5253 ;; This extends to checking mismatches such as "return" and "return <value>"
5254 ;; used in the same function. Warnings are not emitted if inconsistent
5255 ;; returns exist in code that can be statically shown to be unreachable.
5256 ;; Ex.
5257 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5258 ;;
5259 ;; emits no warning. However if the loop had a break statement, then a
5260 ;; warning would be emitted.
5261 ;;
5262 ;; The consistency analysis looks at control structures such as loops, ifs,
5263 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5264 ;; warns the user about an inconsistent set of termination possibilities.
5265 ;;
5266 ;; These flags enumerate the possible ways a statement/function can
5267 ;; terminate. These flags are used by endCheck() and by the Parser to
5268 ;; detect inconsistent return usage.
5269 ;;
5270 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5271 ;; able to execute (example: throw, continue)
5272 ;;
5273 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5274 ;; next one. Statement such as return dont. A compound statement may have
5275 ;; some branch that drops off control to the next statement.
5276 ;;
5277 ;; END_RETURNS indicates that the statement can return with no value.
5278 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5279 ;;
5280 ;; A compound statement such as
5281 ;; if (condition) {
5282 ;; return value;
5283 ;; }
5284 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5285
5286 (defconst js2-END_UNREACHED 0)
5287 (defconst js2-END_DROPS_OFF 1)
5288 (defconst js2-END_RETURNS 2)
5289 (defconst js2-END_RETURNS_VALUE 4)
5290 (defconst js2-END_YIELDS 8)
5291
5292 (defun js2-has-consistent-return-usage (node)
5293 "Check that every return usage in a function body is consistent.
5294 Returns t if the function satisfies strict mode requirement."
5295 (let ((n (js2-end-check node)))
5296 ;; either it doesn't return a value in any branch...
5297 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5298 ;; or it returns a value (or is unreached) at every branch
5299 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5300 js2-END_RETURNS
5301 js2-END_YIELDS)))))
5302
5303 (defun js2-end-check-if (node)
5304 "Ensure that return usage in then/else blocks is consistent.
5305 If there is no else block, then the return statement can fall through.
5306 Returns logical OR of END_* flags"
5307 (let ((th (js2-if-node-then-part node))
5308 (el (js2-if-node-else-part node)))
5309 (if (null th)
5310 js2-END_UNREACHED
5311 (logior (js2-end-check th) (if el
5312 (js2-end-check el)
5313 js2-END_DROPS_OFF)))))
5314
5315 (defun js2-end-check-switch (node)
5316 "Consistency of return statements is checked between the case statements.
5317 If there is no default, then the switch can fall through. If there is a
5318 default, we check to see if all code paths in the default return or if
5319 there is a code path that can fall through.
5320 Returns logical OR of END_* flags."
5321 (let ((rv js2-END_UNREACHED)
5322 default-case)
5323 ;; examine the cases
5324 (catch 'break
5325 (dolist (c (js2-switch-node-cases node))
5326 (if (js2-case-node-expr c)
5327 (js2-set-flag rv (js2-end-check-block c))
5328 (setq default-case c)
5329 (throw 'break nil))))
5330 ;; we don't care how the cases drop into each other
5331 (js2-clear-flag rv js2-END_DROPS_OFF)
5332 ;; examine the default
5333 (js2-set-flag rv (if default-case
5334 (js2-end-check default-case)
5335 js2-END_DROPS_OFF))
5336 rv))
5337
5338 (defun js2-end-check-try (node)
5339 "If the block has a finally, return consistency is checked in the
5340 finally block. If all code paths in the finally return, then the
5341 returns in the try-catch blocks don't matter. If there is a code path
5342 that does not return or if there is no finally block, the returns
5343 of the try and catch blocks are checked for mismatch.
5344 Returns logical OR of END_* flags."
5345 (let ((finally (js2-try-node-finally-block node))
5346 rv)
5347 ;; check the finally if it exists
5348 (setq rv (if finally
5349 (js2-end-check (js2-finally-node-body finally))
5350 js2-END_DROPS_OFF))
5351 ;; If the finally block always returns, then none of the returns
5352 ;; in the try or catch blocks matter.
5353 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5354 (js2-clear-flag rv js2-END_DROPS_OFF)
5355 ;; examine the try block
5356 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5357 ;; check each catch block
5358 (dolist (cb (js2-try-node-catch-clauses node))
5359 (js2-set-flag rv (js2-end-check cb))))
5360 rv))
5361
5362 (defun js2-end-check-loop (node)
5363 "Return statement in the loop body must be consistent.
5364 The default assumption for any kind of a loop is that it will eventually
5365 terminate. The only exception is a loop with a constant true condition.
5366 Code that follows such a loop is examined only if one can determine
5367 statically that there is a break out of the loop.
5368
5369 for(... ; ... ; ...) {}
5370 for(... in ... ) {}
5371 while(...) { }
5372 do { } while(...)
5373
5374 Returns logical OR of END_* flags."
5375 (let ((rv (js2-end-check (js2-loop-node-body node)))
5376 (condition (cond
5377 ((js2-while-node-p node)
5378 (js2-while-node-condition node))
5379 ((js2-do-node-p node)
5380 (js2-do-node-condition node))
5381 ((js2-for-node-p node)
5382 (js2-for-node-condition node)))))
5383
5384 ;; check to see if the loop condition is always true
5385 (if (and condition
5386 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5387 (js2-clear-flag rv js2-END_DROPS_OFF))
5388
5389 ;; look for effect of breaks
5390 (js2-set-flag rv (js2-node-get-prop node
5391 'CONTROL_BLOCK_PROP
5392 js2-END_UNREACHED))
5393 rv))
5394
5395 (defun js2-end-check-block (node)
5396 "A general block of code is examined statement by statement.
5397 If any statement (even a compound one) returns in all branches, then
5398 subsequent statements are not examined.
5399 Returns logical OR of END_* flags."
5400 (let* ((rv js2-END_DROPS_OFF)
5401 (kids (js2-block-node-kids node))
5402 (n (car kids)))
5403 ;; Check each statement. If the statement can continue onto the next
5404 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5405 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5406 (js2-clear-flag rv js2-END_DROPS_OFF)
5407 (js2-set-flag rv (js2-end-check n))
5408 (setq kids (cdr kids)
5409 n (car kids)))
5410 rv))
5411
5412 (defun js2-end-check-label (node)
5413 "A labeled statement implies that there may be a break to the label.
5414 The function processes the labeled statement and then checks the
5415 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5416 particular label.
5417 Returns logical OR of END_* flags."
5418 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5419 (logior rv (js2-node-get-prop node
5420 'CONTROL_BLOCK_PROP
5421 js2-END_UNREACHED))))
5422
5423 (defun js2-end-check-break (node)
5424 "When a break is encountered annotate the statement being broken
5425 out of by setting its CONTROL_BLOCK_PROP property.
5426 Returns logical OR of END_* flags."
5427 (and (js2-break-node-target node)
5428 (js2-node-set-prop (js2-break-node-target node)
5429 'CONTROL_BLOCK_PROP
5430 js2-END_DROPS_OFF))
5431 js2-END_UNREACHED)
5432
5433 (defun js2-end-check (node)
5434 "Examine the body of a function, doing a basic reachability analysis.
5435 Returns a combination of flags END_* flags that indicate
5436 how the function execution can terminate. These constitute only the
5437 pessimistic set of termination conditions. It is possible that at
5438 runtime certain code paths will never be actually taken. Hence this
5439 analysis will flag errors in cases where there may not be errors.
5440 Returns logical OR of END_* flags"
5441 (let (kid)
5442 (cond
5443 ((js2-break-node-p node)
5444 (js2-end-check-break node))
5445 ((js2-expr-stmt-node-p node)
5446 (if (setq kid (js2-expr-stmt-node-expr node))
5447 (js2-end-check kid)
5448 js2-END_DROPS_OFF))
5449 ((or (js2-continue-node-p node)
5450 (js2-throw-node-p node))
5451 js2-END_UNREACHED)
5452 ((js2-return-node-p node)
5453 (if (setq kid (js2-return-node-retval node))
5454 js2-END_RETURNS_VALUE
5455 js2-END_RETURNS))
5456 ((js2-loop-node-p node)
5457 (js2-end-check-loop node))
5458 ((js2-switch-node-p node)
5459 (js2-end-check-switch node))
5460 ((js2-labeled-stmt-node-p node)
5461 (js2-end-check-label node))
5462 ((js2-if-node-p node)
5463 (js2-end-check-if node))
5464 ((js2-try-node-p node)
5465 (js2-end-check-try node))
5466 ((js2-block-node-p node)
5467 (if (null (js2-block-node-kids node))
5468 js2-END_DROPS_OFF
5469 (js2-end-check-block node)))
5470 ((js2-yield-node-p node)
5471 js2-END_YIELDS)
5472 (t
5473 js2-END_DROPS_OFF))))
5474
5475 (defun js2-always-defined-boolean-p (node)
5476 "Check if NODE always evaluates to true or false in boolean context.
5477 Returns `ALWAYS_TRUE', `ALWAYS_FALSE', or nil if it's neither always true
5478 nor always false."
5479 (let ((tt (js2-node-type node))
5480 num)
5481 (cond
5482 ((or (= tt js2-FALSE) (= tt js2-NULL))
5483 'ALWAYS_FALSE)
5484 ((= tt js2-TRUE)
5485 'ALWAYS_TRUE)
5486 ((= tt js2-NUMBER)
5487 (setq num (js2-number-node-num-value node))
5488 (if (and (not (eq num 0.0e+NaN))
5489 (not (zerop num)))
5490 'ALWAYS_TRUE
5491 'ALWAYS_FALSE))
5492 (t
5493 nil))))
5494
5495 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5496 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5497
5498 (defvar js2-tokens nil
5499 "List of all defined token names.") ; initialized in `js2-token-names'
5500
5501 (defconst js2-token-names
5502 (let* ((names (make-vector js2-num-tokens -1))
5503 (case-fold-search nil) ; only match js2-UPPER_CASE
5504 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5505 (cl-loop for sym in syms
5506 for i from 0
5507 do
5508 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5509 (not (boundp sym)))
5510 (aset names (symbol-value sym) ; code, e.g. 152
5511 (downcase
5512 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5513 (push sym js2-tokens)))
5514 names)
5515 "Vector mapping int values to token string names, sans `js2-' prefix.")
5516
5517 (defun js2-tt-name (tok)
5518 "Return a string name for TOK, a token symbol or code.
5519 Signals an error if it's not a recognized token."
5520 (let ((code tok))
5521 (if (symbolp tok)
5522 (setq code (symbol-value tok)))
5523 (if (eq code -1)
5524 "ERROR"
5525 (if (and (numberp code)
5526 (not (cl-minusp code))
5527 (< code js2-num-tokens))
5528 (aref js2-token-names code)
5529 (error "Invalid token: %s" code)))))
5530
5531 (defsubst js2-tt-sym (tok)
5532 "Return symbol for TOK given its code, e.g. `js2-LP' for code 86."
5533 (intern (js2-tt-name tok)))
5534
5535 (defconst js2-token-codes
5536 (let ((table (make-hash-table :test 'eq :size 256)))
5537 (cl-loop for name across js2-token-names
5538 for sym = (intern (concat "js2-" (upcase name)))
5539 do
5540 (puthash sym (symbol-value sym) table))
5541 ;; clean up a few that are "wrong" in Rhino's token codes
5542 (puthash 'js2-DELETE js2-DELPROP table)
5543 table)
5544 "Hashtable mapping token type symbols to their bytecodes.")
5545
5546 (defsubst js2-tt-code (sym)
5547 "Return code for token symbol SYM, e.g. 86 for `js2-LP'."
5548 (or (gethash sym js2-token-codes)
5549 (error "Invalid token symbol: %s " sym))) ; signal code bug
5550
5551 (defun js2-report-scan-error (msg &optional no-throw beg len)
5552 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5553 (js2-report-error msg nil
5554 (or beg (js2-current-token-beg))
5555 (or len (js2-current-token-len)))
5556 (unless no-throw
5557 (throw 'return js2-ERROR)))
5558
5559 (defun js2-set-string-from-buffer (token)
5560 "Set `string' and `end' slots for TOKEN, return the string."
5561 (setf (js2-token-end token) js2-ts-cursor
5562 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5563
5564 ;; TODO: could potentially avoid a lot of consing by allocating a
5565 ;; char buffer the way Rhino does.
5566 (defsubst js2-add-to-string (c)
5567 (push c js2-ts-string-buffer))
5568
5569 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5570 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5571 ;; any other character: when it's not part of the current token, we
5572 ;; unget it, allowing it to be read again by the following call.
5573 (defsubst js2-unget-char ()
5574 (cl-decf js2-ts-cursor))
5575
5576 ;; Rhino distinguishes \r and \n line endings. We don't need to
5577 ;; because we only scan from Emacs buffers, which always use \n.
5578 (defun js2-get-char ()
5579 "Read and return the next character from the input buffer.
5580 Increments `js2-ts-lineno' if the return value is a newline char.
5581 Updates `js2-ts-cursor' to the point after the returned char.
5582 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5583 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5584 (let (c)
5585 ;; check for end of buffer
5586 (if (>= js2-ts-cursor (point-max))
5587 (setq js2-ts-hit-eof t
5588 js2-ts-cursor (1+ js2-ts-cursor)
5589 c js2-EOF_CHAR) ; return value
5590 ;; otherwise read next char
5591 (setq c (char-before (cl-incf js2-ts-cursor)))
5592 ;; if we read a newline, update counters
5593 (if (= c ?\n)
5594 (setq js2-ts-line-start js2-ts-cursor
5595 js2-ts-lineno (1+ js2-ts-lineno)))
5596 ;; TODO: skip over format characters
5597 c)))
5598
5599 (defun js2-read-unicode-escape ()
5600 "Read a \\uNNNN sequence from the input.
5601 Assumes the ?\\ and ?u have already been read.
5602 Returns the unicode character, or nil if it wasn't a valid character.
5603 Doesn't change the values of any scanner variables."
5604 ;; I really wish I knew a better way to do this, but I can't
5605 ;; find the Emacs function that takes a 16-bit int and converts
5606 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5607 ;; Have to first check that it's 4 hex characters or it may stop
5608 ;; the read early.
5609 (ignore-errors
5610 (let ((s (buffer-substring-no-properties js2-ts-cursor
5611 (+ 4 js2-ts-cursor))))
5612 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5613 (read (concat "?\\u" s))))))
5614
5615 (defun js2-match-char (test)
5616 "Consume and return next character if it matches TEST, a character.
5617 Returns nil and consumes nothing if TEST is not the next character."
5618 (let ((c (js2-get-char)))
5619 (if (eq c test)
5620 t
5621 (js2-unget-char)
5622 nil)))
5623
5624 (defun js2-peek-char ()
5625 (prog1
5626 (js2-get-char)
5627 (js2-unget-char)))
5628
5629 (defun js2-identifier-start-p (c)
5630 "Is C a valid start to an ES5 Identifier?
5631 See http://es5.github.io/#x7.6"
5632 (or
5633 (memq c '(?$ ?_))
5634 (memq (get-char-code-property c 'general-category)
5635 ;; Letters
5636 '(Lu Ll Lt Lm Lo Nl))))
5637
5638 (defun js2-identifier-part-p (c)
5639 "Is C a valid part of an ES5 Identifier?
5640 See http://es5.github.io/#x7.6"
5641 (or
5642 (memq c '(?$ ?_ ?\u200c ?\u200d))
5643 (memq (get-char-code-property c 'general-category)
5644 '(;; Letters
5645 Lu Ll Lt Lm Lo Nl
5646 ;; Combining Marks
5647 Mn Mc
5648 ;; Digits
5649 Nd
5650 ;; Connector Punctuation
5651 Pc))))
5652
5653 (defun js2-alpha-p (c)
5654 (cond ((and (<= ?A c) (<= c ?Z)) t)
5655 ((and (<= ?a c) (<= c ?z)) t)
5656 (t nil)))
5657
5658 (defsubst js2-digit-p (c)
5659 (and (<= ?0 c) (<= c ?9)))
5660
5661 (defun js2-js-space-p (c)
5662 (if (<= c 127)
5663 (memq c '(#x20 #x9 #xB #xC #xD))
5664 (or
5665 (eq c #xA0)
5666 ;; TODO: change this nil to check for Unicode space character
5667 nil)))
5668
5669 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5670
5671 (defun js2-skip-line ()
5672 "Skip to end of line."
5673 (while (not (memq (js2-get-char) js2-eol-chars)))
5674 (js2-unget-char)
5675 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5676
5677 (defun js2-init-scanner (&optional buf line)
5678 "Create token stream for BUF starting on LINE.
5679 BUF defaults to `current-buffer' and LINE defaults to 1.
5680
5681 A buffer can only have one scanner active at a time, which yields
5682 dramatically simpler code than using a defstruct. If you need to
5683 have simultaneous scanners in a buffer, copy the regions to scan
5684 into temp buffers."
5685 (with-current-buffer (or buf (current-buffer))
5686 (setq js2-ts-dirty-line nil
5687 js2-ts-hit-eof nil
5688 js2-ts-line-start 0
5689 js2-ts-lineno (or line 1)
5690 js2-ts-line-end-char -1
5691 js2-ts-cursor (point-min)
5692 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5693 js2-ti-tokens-cursor 0
5694 js2-ti-lookahead 0
5695 js2-ts-is-xml-attribute nil
5696 js2-ts-xml-is-tag-content nil
5697 js2-ts-xml-open-tags-count 0
5698 js2-ts-string-buffer nil)))
5699
5700 ;; This function uses the cached op, string and number fields in
5701 ;; TokenStream; if getToken has been called since the passed token
5702 ;; was scanned, the op or string printed may be incorrect.
5703 (defun js2-token-to-string (token)
5704 ;; Not sure where this function is used in Rhino. Not tested.
5705 (if (not js2-debug-print-trees)
5706 ""
5707 (let ((name (js2-tt-name token)))
5708 (cond
5709 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5710 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5711 (concat name " `" (js2-current-token-string) "'"))
5712 ((eq token js2-NUMBER)
5713 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5714 (t
5715 name)))))
5716
5717 (defconst js2-keywords
5718 '(break
5719 case catch class const continue
5720 debugger default delete do
5721 else extends export
5722 false finally for function
5723 if in instanceof import
5724 let
5725 new null
5726 return
5727 super switch
5728 this throw true try typeof
5729 var void
5730 while with
5731 yield))
5732
5733 ;; Token names aren't exactly the same as the keywords, unfortunately.
5734 ;; E.g. delete is js2-DELPROP.
5735 (defconst js2-kwd-tokens
5736 (let ((table (make-vector js2-num-tokens nil))
5737 (tokens
5738 (list js2-BREAK
5739 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5740 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5741 js2-ELSE js2-EXPORT
5742 js2-ELSE js2-EXTENDS js2-EXPORT
5743 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5744 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5745 js2-LET
5746 js2-NEW js2-NULL
5747 js2-RETURN
5748 js2-SUPER js2-SWITCH
5749 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5750 js2-VAR
5751 js2-WHILE js2-WITH
5752 js2-YIELD)))
5753 (dolist (i tokens)
5754 (aset table i 'font-lock-keyword-face))
5755 (aset table js2-STRING 'font-lock-string-face)
5756 (aset table js2-REGEXP 'font-lock-string-face)
5757 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5758 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5759 (aset table js2-COMMENT 'font-lock-comment-face)
5760 (aset table js2-THIS 'font-lock-builtin-face)
5761 (aset table js2-SUPER 'font-lock-builtin-face)
5762 (aset table js2-VOID 'font-lock-constant-face)
5763 (aset table js2-NULL 'font-lock-constant-face)
5764 (aset table js2-TRUE 'font-lock-constant-face)
5765 (aset table js2-FALSE 'font-lock-constant-face)
5766 (aset table js2-NOT 'font-lock-negation-char-face)
5767 table)
5768 "Vector whose values are non-nil for tokens that are keywords.
5769 The values are default faces to use for highlighting the keywords.")
5770
5771 ;; FIXME: Support strict mode-only future reserved words, after we know
5772 ;; which parts scopes are in strict mode, and which are not.
5773 (defconst js2-reserved-words '(class enum export extends import static super)
5774 "Future reserved keywords in ECMAScript 5.1.")
5775
5776 (defconst js2-keyword-names
5777 (let ((table (make-hash-table :test 'equal)))
5778 (cl-loop for k in js2-keywords
5779 do (puthash
5780 (symbol-name k) ; instanceof
5781 (intern (concat "js2-"
5782 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5783 table))
5784 table)
5785 "JavaScript keywords by name, mapped to their symbols.")
5786
5787 (defconst js2-reserved-word-names
5788 (let ((table (make-hash-table :test 'equal)))
5789 (cl-loop for k in js2-reserved-words
5790 do
5791 (puthash (symbol-name k) 'js2-RESERVED table))
5792 table)
5793 "JavaScript reserved words by name, mapped to `js2-RESERVED'.")
5794
5795 (defun js2-collect-string (buf)
5796 "Convert BUF, a list of chars, to a string.
5797 Reverses BUF before converting."
5798 (if buf
5799 (apply #'string (nreverse buf))
5800 ""))
5801
5802 (defun js2-string-to-keyword (s)
5803 "Return token for S, a string, if S is a keyword or reserved word.
5804 Returns a symbol such as `js2-BREAK', or nil if not keyword/reserved."
5805 (or (gethash s js2-keyword-names)
5806 (gethash s js2-reserved-word-names)))
5807
5808 (defsubst js2-ts-set-char-token-bounds (token)
5809 "Used when next token is one character."
5810 (setf (js2-token-beg token) (1- js2-ts-cursor)
5811 (js2-token-end token) js2-ts-cursor))
5812
5813 (defsubst js2-ts-return (token type)
5814 "Update the `end' and `type' slots of TOKEN,
5815 then throw `return' with value TYPE."
5816 (setf (js2-token-end token) js2-ts-cursor
5817 (js2-token-type token) type)
5818 (throw 'return type))
5819
5820 (defun js2-x-digit-to-int (c accumulator)
5821 "Build up a hex number.
5822 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5823 corresponding number. Otherwise return -1."
5824 (catch 'return
5825 (catch 'check
5826 ;; Use 0..9 < A..Z < a..z
5827 (cond
5828 ((<= c ?9)
5829 (cl-decf c ?0)
5830 (if (<= 0 c)
5831 (throw 'check nil)))
5832 ((<= c ?F)
5833 (when (<= ?A c)
5834 (cl-decf c (- ?A 10))
5835 (throw 'check nil)))
5836 ((<= c ?f)
5837 (when (<= ?a c)
5838 (cl-decf c (- ?a 10))
5839 (throw 'check nil))))
5840 (throw 'return -1))
5841 (logior c (lsh accumulator 4))))
5842
5843 (defun js2-get-token (&optional modifier)
5844 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5845 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5846 next saved token.
5847
5848 This function will not return a newline (js2-EOL) - instead, it
5849 gobbles newlines until it finds a non-newline token. Call
5850 `js2-peek-token-or-eol' when you care about newlines.
5851
5852 This function will also not return a js2-COMMENT. Instead, it
5853 records comments found in `js2-scanned-comments'. If the token
5854 returned by this function immediately follows a jsdoc comment,
5855 the token is flagged as such."
5856 (if (zerop js2-ti-lookahead)
5857 (js2-get-token-internal modifier)
5858 (cl-decf js2-ti-lookahead)
5859 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5860 (let ((tt (js2-current-token-type)))
5861 (cl-assert (not (= tt js2-EOL)))
5862 tt)))
5863
5864 (defun js2-unget-token ()
5865 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5866 (cl-incf js2-ti-lookahead)
5867 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5868
5869 (defun js2-get-token-internal (modifier)
5870 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5871 (tt (js2-token-type token))
5872 saw-eol
5873 face)
5874 ;; process comments
5875 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5876 (if (= tt js2-EOL)
5877 (setq saw-eol t)
5878 (setq saw-eol nil)
5879 (when js2-record-comments
5880 (js2-record-comment token)))
5881 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5882 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5883 tt (js2-token-type token)))
5884
5885 (when saw-eol
5886 (setf (js2-token-follows-eol-p token) t))
5887
5888 ;; perform lexical fontification as soon as token is scanned
5889 (when js2-parse-ide-mode
5890 (cond
5891 ((cl-minusp tt)
5892 (js2-record-face 'js2-error token))
5893 ((setq face (aref js2-kwd-tokens tt))
5894 (js2-record-face face token))
5895 ((and (= tt js2-NAME)
5896 (equal (js2-token-string token) "undefined"))
5897 (js2-record-face 'font-lock-constant-face token))))
5898 tt))
5899
5900 (defsubst js2-string-to-number (str base)
5901 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5902 (condition-case nil
5903 (string-to-number str base)
5904 (overflow-error -1)))
5905
5906 (defun js2-get-token-internal-1 (modifier)
5907 "Return next JavaScript token type, an int such as js2-RETURN.
5908 During operation, creates an instance of `js2-token' struct, sets
5909 its relevant fields and puts it into `js2-ti-tokens'."
5910 (let (identifier-start
5911 is-unicode-escape-start c
5912 contains-escape escape-val str result base
5913 look-for-slash continue tt legacy-octal
5914 (token (js2-new-token 0)))
5915 (setq
5916 tt
5917 (catch 'return
5918 (when (eq modifier 'TEMPLATE_TAIL)
5919 (setf (js2-token-beg token) (1- js2-ts-cursor))
5920 (throw 'return (js2-get-string-or-template-token ?` token)))
5921 (while t
5922 ;; Eat whitespace, possibly sensitive to newlines.
5923 (setq continue t)
5924 (while continue
5925 (setq c (js2-get-char))
5926 (cond
5927 ((eq c js2-EOF_CHAR)
5928 (js2-unget-char)
5929 (js2-ts-set-char-token-bounds token)
5930 (throw 'return js2-EOF))
5931 ((eq c ?\n)
5932 (js2-ts-set-char-token-bounds token)
5933 (setq js2-ts-dirty-line nil)
5934 (throw 'return js2-EOL))
5935 ((not (js2-js-space-p c))
5936 (if (/= c ?-) ; in case end of HTML comment
5937 (setq js2-ts-dirty-line t))
5938 (setq continue nil))))
5939 ;; Assume the token will be 1 char - fixed up below.
5940 (js2-ts-set-char-token-bounds token)
5941 (when (eq c ?@)
5942 (throw 'return js2-XMLATTR))
5943 ;; identifier/keyword/instanceof?
5944 ;; watch out for starting with a <backslash>
5945 (cond
5946 ((eq c ?\\)
5947 (setq c (js2-get-char))
5948 (if (eq c ?u)
5949 (setq identifier-start t
5950 is-unicode-escape-start t
5951 js2-ts-string-buffer nil)
5952 (setq identifier-start nil)
5953 (js2-unget-char)
5954 (setq c ?\\)))
5955 (t
5956 (when (setq identifier-start (js2-identifier-start-p c))
5957 (setq js2-ts-string-buffer nil)
5958 (js2-add-to-string c))))
5959 (when identifier-start
5960 (setq contains-escape is-unicode-escape-start)
5961 (catch 'break
5962 (while t
5963 (if is-unicode-escape-start
5964 ;; strictly speaking we should probably push-back
5965 ;; all the bad characters if the <backslash>uXXXX
5966 ;; sequence is malformed. But since there isn't a
5967 ;; correct context(is there?) for a bad Unicode
5968 ;; escape sequence in an identifier, we can report
5969 ;; an error here.
5970 (progn
5971 (setq escape-val 0)
5972 (dotimes (_ 4)
5973 (setq c (js2-get-char)
5974 escape-val (js2-x-digit-to-int c escape-val))
5975 ;; Next check takes care of c < 0 and bad escape
5976 (if (cl-minusp escape-val)
5977 (throw 'break nil)))
5978 (if (cl-minusp escape-val)
5979 (js2-report-scan-error "msg.invalid.escape" t))
5980 (js2-add-to-string escape-val)
5981 (setq is-unicode-escape-start nil))
5982 (setq c (js2-get-char))
5983 (cond
5984 ((eq c ?\\)
5985 (setq c (js2-get-char))
5986 (if (eq c ?u)
5987 (setq is-unicode-escape-start t
5988 contains-escape t)
5989 (js2-report-scan-error "msg.illegal.character" t)))
5990 (t
5991 (if (or (eq c js2-EOF_CHAR)
5992 (not (js2-identifier-part-p c)))
5993 (throw 'break nil))
5994 (js2-add-to-string c))))))
5995 (js2-unget-char)
5996 (setf str (js2-collect-string js2-ts-string-buffer)
5997 (js2-token-end token) js2-ts-cursor)
5998 ;; FIXME: Invalid in ES5 and ES6, see
5999 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
6000 ;; Probably should just drop this conditional.
6001 (unless contains-escape
6002 ;; OPT we shouldn't have to make a string (object!) to
6003 ;; check if it's a keyword.
6004 ;; Return the corresponding token if it's a keyword
6005 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6006 (setq result (js2-string-to-keyword str)))
6007 (if (and (< js2-language-version 170)
6008 (memq result '(js2-LET js2-YIELD)))
6009 ;; LET and YIELD are tokens only in 1.7 and later
6010 (setq result 'js2-NAME))
6011 (when (eq result 'js2-RESERVED)
6012 (setf (js2-token-string token) str))
6013 (throw 'return (js2-tt-code result))))
6014 ;; If we want to intern these as Rhino does, just use (intern str)
6015 (setf (js2-token-string token) str)
6016 (throw 'return js2-NAME)) ; end identifier/kwd check
6017 ;; is it a number?
6018 (when (or (js2-digit-p c)
6019 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6020 (setq js2-ts-string-buffer nil
6021 base 10)
6022 (when (eq c ?0)
6023 (setq c (js2-get-char))
6024 (cond
6025 ((or (eq c ?x) (eq c ?X))
6026 (setq base 16)
6027 (setq c (js2-get-char)))
6028 ((and (or (eq c ?b) (eq c ?B))
6029 (>= js2-language-version 200))
6030 (setq base 2)
6031 (setq c (js2-get-char)))
6032 ((and (or (eq c ?o) (eq c ?O))
6033 (>= js2-language-version 200))
6034 (setq base 8)
6035 (setq legacy-octal nil)
6036 (setq c (js2-get-char)))
6037 ((js2-digit-p c)
6038 (setq base 'maybe-8))
6039 (t
6040 (js2-add-to-string ?0))))
6041 (cond
6042 ((eq base 16)
6043 (if (> 0 (js2-x-digit-to-int c 0))
6044 (js2-report-scan-error "msg.missing.hex.digits")
6045 (while (<= 0 (js2-x-digit-to-int c 0))
6046 (js2-add-to-string c)
6047 (setq c (js2-get-char)))))
6048 ((eq base 2)
6049 (if (not (memq c '(?0 ?1)))
6050 (js2-report-scan-error "msg.missing.binary.digits")
6051 (while (memq c '(?0 ?1))
6052 (js2-add-to-string c)
6053 (setq c (js2-get-char)))))
6054 ((eq base 8)
6055 (if (or (> ?0 c) (< ?7 c))
6056 (js2-report-scan-error "msg.missing.octal.digits")
6057 (while (and (<= ?0 c) (>= ?7 c))
6058 (js2-add-to-string c)
6059 (setq c (js2-get-char)))))
6060 (t
6061 (while (and (<= ?0 c) (<= c ?9))
6062 ;; We permit 08 and 09 as decimal numbers, which
6063 ;; makes our behavior a superset of the ECMA
6064 ;; numeric grammar. We might not always be so
6065 ;; permissive, so we warn about it.
6066 (when (and (eq base 'maybe-8) (>= c ?8))
6067 (js2-report-warning "msg.bad.octal.literal"
6068 (if (eq c ?8) "8" "9"))
6069 (setq base 10))
6070 (js2-add-to-string c)
6071 (setq c (js2-get-char)))
6072 (when (eq base 'maybe-8)
6073 (setq base 8
6074 legacy-octal t))))
6075 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6076 (when (eq c ?.)
6077 (cl-loop do
6078 (js2-add-to-string c)
6079 (setq c (js2-get-char))
6080 while (js2-digit-p c)))
6081 (when (memq c '(?e ?E))
6082 (js2-add-to-string c)
6083 (setq c (js2-get-char))
6084 (when (memq c '(?+ ?-))
6085 (js2-add-to-string c)
6086 (setq c (js2-get-char)))
6087 (unless (js2-digit-p c)
6088 (js2-report-scan-error "msg.missing.exponent" t))
6089 (cl-loop do
6090 (js2-add-to-string c)
6091 (setq c (js2-get-char))
6092 while (js2-digit-p c))))
6093 (js2-unget-char)
6094 (let ((str (js2-set-string-from-buffer token)))
6095 (setf (js2-token-number token) (js2-string-to-number str base)
6096 (js2-token-number-base token) base
6097 (js2-token-number-legacy-octal-p token) (and (= base 8) legacy-octal)))
6098 (throw 'return js2-NUMBER))
6099 ;; is it a string?
6100 (when (or (memq c '(?\" ?\'))
6101 (and (>= js2-language-version 200)
6102 (= c ?`)))
6103 (throw 'return
6104 (js2-get-string-or-template-token c token)))
6105 (js2-ts-return token
6106 (cl-case c
6107 (?\;
6108 (throw 'return js2-SEMI))
6109 (?\[
6110 (throw 'return js2-LB))
6111 (?\]
6112 (throw 'return js2-RB))
6113 (?{
6114 (throw 'return js2-LC))
6115 (?}
6116 (throw 'return js2-RC))
6117 (?\(
6118 (throw 'return js2-LP))
6119 (?\)
6120 (throw 'return js2-RP))
6121 (?,
6122 (throw 'return js2-COMMA))
6123 (??
6124 (throw 'return js2-HOOK))
6125 (?:
6126 (if (js2-match-char ?:)
6127 js2-COLONCOLON
6128 (throw 'return js2-COLON)))
6129 (?.
6130 (if (js2-match-char ?.)
6131 (if (js2-match-char ?.)
6132 js2-TRIPLEDOT js2-DOTDOT)
6133 (if (js2-match-char ?\()
6134 js2-DOTQUERY
6135 (throw 'return js2-DOT))))
6136 (?|
6137 (if (js2-match-char ?|)
6138 (throw 'return js2-OR)
6139 (if (js2-match-char ?=)
6140 js2-ASSIGN_BITOR
6141 (throw 'return js2-BITOR))))
6142 (?^
6143 (if (js2-match-char ?=)
6144 js2-ASSIGN_BITOR
6145 (throw 'return js2-BITXOR)))
6146 (?&
6147 (if (js2-match-char ?&)
6148 (throw 'return js2-AND)
6149 (if (js2-match-char ?=)
6150 js2-ASSIGN_BITAND
6151 (throw 'return js2-BITAND))))
6152 (?=
6153 (if (js2-match-char ?=)
6154 (if (js2-match-char ?=)
6155 js2-SHEQ
6156 (throw 'return js2-EQ))
6157 (if (js2-match-char ?>)
6158 (js2-ts-return token js2-ARROW)
6159 (throw 'return js2-ASSIGN))))
6160 (?!
6161 (if (js2-match-char ?=)
6162 (if (js2-match-char ?=)
6163 js2-SHNE
6164 js2-NE)
6165 (throw 'return js2-NOT)))
6166 (?<
6167 ;; NB:treat HTML begin-comment as comment-till-eol
6168 (when (js2-match-char ?!)
6169 (when (js2-match-char ?-)
6170 (when (js2-match-char ?-)
6171 (js2-skip-line)
6172 (setf (js2-token-comment-type (js2-current-token)) 'html)
6173 (throw 'return js2-COMMENT)))
6174 (js2-unget-char))
6175 (if (js2-match-char ?<)
6176 (if (js2-match-char ?=)
6177 js2-ASSIGN_LSH
6178 js2-LSH)
6179 (if (js2-match-char ?=)
6180 js2-LE
6181 (throw 'return js2-LT))))
6182 (?>
6183 (if (js2-match-char ?>)
6184 (if (js2-match-char ?>)
6185 (if (js2-match-char ?=)
6186 js2-ASSIGN_URSH
6187 js2-URSH)
6188 (if (js2-match-char ?=)
6189 js2-ASSIGN_RSH
6190 js2-RSH))
6191 (if (js2-match-char ?=)
6192 js2-GE
6193 (throw 'return js2-GT))))
6194 (?*
6195 (if (js2-match-char ?=)
6196 js2-ASSIGN_MUL
6197 (throw 'return js2-MUL)))
6198 (?/
6199 ;; is it a // comment?
6200 (when (js2-match-char ?/)
6201 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6202 (js2-skip-line)
6203 (setf (js2-token-comment-type token) 'line)
6204 ;; include newline so highlighting goes to end of
6205 ;; window, if there actually is a newline; if we
6206 ;; hit eof, then implicitly there isn't
6207 (unless js2-ts-hit-eof
6208 (cl-incf (js2-token-end token)))
6209 (throw 'return js2-COMMENT))
6210 ;; is it a /* comment?
6211 (when (js2-match-char ?*)
6212 (setf look-for-slash nil
6213 (js2-token-beg token) (- js2-ts-cursor 2)
6214 (js2-token-comment-type token)
6215 (if (js2-match-char ?*)
6216 (progn
6217 (setq look-for-slash t)
6218 'jsdoc)
6219 'block))
6220 (while t
6221 (setq c (js2-get-char))
6222 (cond
6223 ((eq c js2-EOF_CHAR)
6224 (setf (js2-token-end token) (1- js2-ts-cursor))
6225 (js2-report-error "msg.unterminated.comment")
6226 (throw 'return js2-COMMENT))
6227 ((eq c ?*)
6228 (setq look-for-slash t))
6229 ((eq c ?/)
6230 (if look-for-slash
6231 (js2-ts-return token js2-COMMENT)))
6232 (t
6233 (setf look-for-slash nil
6234 (js2-token-end token) js2-ts-cursor)))))
6235 (if (js2-match-char ?=)
6236 js2-ASSIGN_DIV
6237 (throw 'return js2-DIV)))
6238 (?#
6239 (when js2-skip-preprocessor-directives
6240 (js2-skip-line)
6241 (setf (js2-token-comment-type token) 'preprocessor
6242 (js2-token-end token) js2-ts-cursor)
6243 (throw 'return js2-COMMENT))
6244 (throw 'return js2-ERROR))
6245 (?%
6246 (if (js2-match-char ?=)
6247 js2-ASSIGN_MOD
6248 (throw 'return js2-MOD)))
6249 (?~
6250 (throw 'return js2-BITNOT))
6251 (?+
6252 (if (js2-match-char ?=)
6253 js2-ASSIGN_ADD
6254 (if (js2-match-char ?+)
6255 js2-INC
6256 (throw 'return js2-ADD))))
6257 (?-
6258 (cond
6259 ((js2-match-char ?=)
6260 (setq c js2-ASSIGN_SUB))
6261 ((js2-match-char ?-)
6262 (unless js2-ts-dirty-line
6263 ;; treat HTML end-comment after possible whitespace
6264 ;; after line start as comment-until-eol
6265 (when (js2-match-char ?>)
6266 (js2-skip-line)
6267 (setf (js2-token-comment-type (js2-current-token)) 'html)
6268 (throw 'return js2-COMMENT)))
6269 (setq c js2-DEC))
6270 (t
6271 (setq c js2-SUB)))
6272 (setq js2-ts-dirty-line t)
6273 c)
6274 (otherwise
6275 (js2-report-scan-error "msg.illegal.character")))))))
6276 (setf (js2-token-type token) tt)
6277 token))
6278
6279 (defun js2-get-string-or-template-token (quote-char token)
6280 ;; We attempt to accumulate a string the fast way, by
6281 ;; building it directly out of the reader. But if there
6282 ;; are any escaped characters in the string, we revert to
6283 ;; building it out of a string buffer.
6284 (let ((c (js2-get-char))
6285 js2-ts-string-buffer
6286 nc c1 val escape-val)
6287 (catch 'break
6288 (while (/= c quote-char)
6289 (catch 'continue
6290 (when (eq c js2-EOF_CHAR)
6291 (js2-unget-char)
6292 (js2-report-error "msg.unterminated.string.lit")
6293 (throw 'break nil))
6294 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6295 (js2-unget-char)
6296 (js2-report-error "msg.unterminated.string.lit")
6297 (throw 'break nil))
6298 (when (eq c ?\\)
6299 ;; We've hit an escaped character
6300 (setq c (js2-get-char))
6301 (cl-case c
6302 (?b (setq c ?\b))
6303 (?f (setq c ?\f))
6304 (?n (setq c ?\n))
6305 (?r (setq c ?\r))
6306 (?t (setq c ?\t))
6307 (?v (setq c ?\v))
6308 (?u
6309 (setq c1 (js2-read-unicode-escape))
6310 (if js2-parse-ide-mode
6311 (if c1
6312 (progn
6313 ;; just copy the string in IDE-mode
6314 (js2-add-to-string ?\\)
6315 (js2-add-to-string ?u)
6316 (dotimes (_ 3)
6317 (js2-add-to-string (js2-get-char)))
6318 (setq c (js2-get-char))) ; added at end of loop
6319 ;; flag it as an invalid escape
6320 (js2-report-warning "msg.invalid.escape"
6321 nil (- js2-ts-cursor 2) 6))
6322 ;; Get 4 hex digits; if the u escape is not
6323 ;; followed by 4 hex digits, use 'u' + the
6324 ;; literal character sequence that follows.
6325 (js2-add-to-string ?u)
6326 (setq escape-val 0)
6327 (dotimes (_ 4)
6328 (setq c (js2-get-char)
6329 escape-val (js2-x-digit-to-int c escape-val))
6330 (if (cl-minusp escape-val)
6331 (throw 'continue nil))
6332 (js2-add-to-string c))
6333 ;; prepare for replace of stored 'u' sequence by escape value
6334 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6335 c escape-val)))
6336 (?x
6337 ;; Get 2 hex digits, defaulting to 'x'+literal
6338 ;; sequence, as above.
6339 (setq c (js2-get-char)
6340 escape-val (js2-x-digit-to-int c 0))
6341 (if (cl-minusp escape-val)
6342 (progn
6343 (js2-add-to-string ?x)
6344 (throw 'continue nil))
6345 (setq c1 c
6346 c (js2-get-char)
6347 escape-val (js2-x-digit-to-int c escape-val))
6348 (if (cl-minusp escape-val)
6349 (progn
6350 (js2-add-to-string ?x)
6351 (js2-add-to-string c1)
6352 (throw 'continue nil))
6353 ;; got 2 hex digits
6354 (setq c escape-val))))
6355 (?\n
6356 ;; Remove line terminator after escape to follow
6357 ;; SpiderMonkey and C/C++
6358 (setq c (js2-get-char))
6359 (throw 'continue nil))
6360 (t
6361 (when (and (<= ?0 c) (< c ?8))
6362 (setq val (- c ?0)
6363 c (js2-get-char))
6364 (when (and (<= ?0 c) (< c ?8))
6365 (setq val (- (+ (* 8 val) c) ?0)
6366 c (js2-get-char))
6367 (when (and (<= ?0 c)
6368 (< c ?8)
6369 (< val #o37))
6370 ;; c is 3rd char of octal sequence only
6371 ;; if the resulting val <= 0377
6372 (setq val (- (+ (* 8 val) c) ?0)
6373 c (js2-get-char))))
6374 (js2-unget-char)
6375 (setq c val)))))
6376 (when (and (eq quote-char ?`) (eq c ?$))
6377 (when (eq (setq nc (js2-get-char)) ?\{)
6378 (throw 'break nil))
6379 (js2-unget-char))
6380 (js2-add-to-string c)
6381 (setq c (js2-get-char)))))
6382 (js2-set-string-from-buffer token)
6383 (if (not (eq quote-char ?`))
6384 js2-STRING
6385 (if (and (eq c ?$) (eq nc ?\{))
6386 js2-TEMPLATE_HEAD
6387 js2-NO_SUBS_TEMPLATE))))
6388
6389 (defun js2-read-regexp (start-tt)
6390 "Called by parser when it gets / or /= in literal context."
6391 (let (c err
6392 in-class ; inside a '[' .. ']' character-class
6393 flags
6394 (continue t)
6395 (token (js2-new-token 0)))
6396 (setq js2-ts-string-buffer nil)
6397 (if (eq start-tt js2-ASSIGN_DIV)
6398 ;; mis-scanned /=
6399 (js2-add-to-string ?=)
6400 (if (not (eq start-tt js2-DIV))
6401 (error "failed assertion")))
6402 (while (and (not err)
6403 (or (/= (setq c (js2-get-char)) ?/)
6404 in-class))
6405 (cond
6406 ((or (= c ?\n)
6407 (= c js2-EOF_CHAR))
6408 (setf (js2-token-end token) (1- js2-ts-cursor)
6409 err t
6410 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6411 (js2-report-error "msg.unterminated.re.lit"))
6412 (t (cond
6413 ((= c ?\\)
6414 (js2-add-to-string c)
6415 (setq c (js2-get-char)))
6416 ((= c ?\[)
6417 (setq in-class t))
6418 ((= c ?\])
6419 (setq in-class nil)))
6420 (js2-add-to-string c))))
6421 (unless err
6422 (while continue
6423 (cond
6424 ((js2-match-char ?g)
6425 (push ?g flags))
6426 ((js2-match-char ?i)
6427 (push ?i flags))
6428 ((js2-match-char ?m)
6429 (push ?m flags))
6430 ((and (js2-match-char ?u)
6431 (>= js2-language-version 200))
6432 (push ?u flags))
6433 ((and (js2-match-char ?y)
6434 (>= js2-language-version 200))
6435 (push ?y flags))
6436 (t
6437 (setq continue nil))))
6438 (if (js2-alpha-p (js2-peek-char))
6439 (js2-report-scan-error "msg.invalid.re.flag" t
6440 js2-ts-cursor 1))
6441 (js2-set-string-from-buffer token))
6442 (js2-collect-string flags)))
6443
6444 (defun js2-get-first-xml-token ()
6445 (setq js2-ts-xml-open-tags-count 0
6446 js2-ts-is-xml-attribute nil
6447 js2-ts-xml-is-tag-content nil)
6448 (js2-unget-char)
6449 (js2-get-next-xml-token))
6450
6451 (defun js2-xml-discard-string (token)
6452 "Throw away the string in progress and flag an XML parse error."
6453 (setf js2-ts-string-buffer nil
6454 (js2-token-string token) nil)
6455 (js2-report-scan-error "msg.XML.bad.form" t))
6456
6457 (defun js2-get-next-xml-token ()
6458 (setq js2-ts-string-buffer nil) ; for recording the XML
6459 (let ((token (js2-new-token 0))
6460 c result)
6461 (setq result
6462 (catch 'return
6463 (while t
6464 (setq c (js2-get-char))
6465 (cond
6466 ((= c js2-EOF_CHAR)
6467 (throw 'return js2-ERROR))
6468 (js2-ts-xml-is-tag-content
6469 (cl-case c
6470 (?>
6471 (js2-add-to-string c)
6472 (setq js2-ts-xml-is-tag-content nil
6473 js2-ts-is-xml-attribute nil))
6474 (?/
6475 (js2-add-to-string c)
6476 (when (eq ?> (js2-peek-char))
6477 (setq c (js2-get-char))
6478 (js2-add-to-string c)
6479 (setq js2-ts-xml-is-tag-content nil)
6480 (cl-decf js2-ts-xml-open-tags-count)))
6481 (?{
6482 (js2-unget-char)
6483 (js2-set-string-from-buffer token)
6484 (throw 'return js2-XML))
6485 ((?\' ?\")
6486 (js2-add-to-string c)
6487 (unless (js2-read-quoted-string c token)
6488 (throw 'return js2-ERROR)))
6489 (?=
6490 (js2-add-to-string c)
6491 (setq js2-ts-is-xml-attribute t))
6492 ((? ?\t ?\r ?\n)
6493 (js2-add-to-string c))
6494 (t
6495 (js2-add-to-string c)
6496 (setq js2-ts-is-xml-attribute nil)))
6497 (when (and (not js2-ts-xml-is-tag-content)
6498 (zerop js2-ts-xml-open-tags-count))
6499 (js2-set-string-from-buffer token)
6500 (throw 'return js2-XMLEND)))
6501 (t
6502 ;; else not tag content
6503 (cl-case c
6504 (?<
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 (setq c (js2-peek-char))
6512 (cl-case c
6513 (?-
6514 (setq c (js2-get-char)) ;; skip -
6515 (js2-add-to-string c)
6516 (if (eq c ?-)
6517 (progn
6518 (js2-add-to-string c)
6519 (unless (js2-read-xml-comment token)
6520 (throw 'return js2-ERROR)))
6521 (js2-xml-discard-string token)
6522 (throw 'return js2-ERROR)))
6523 (?\[
6524 (setq c (js2-get-char)) ;; skip [
6525 (js2-add-to-string c)
6526 (if (and (= (js2-get-char) ?C)
6527 (= (js2-get-char) ?D)
6528 (= (js2-get-char) ?A)
6529 (= (js2-get-char) ?T)
6530 (= (js2-get-char) ?A)
6531 (= (js2-get-char) ?\[))
6532 (progn
6533 (js2-add-to-string ?C)
6534 (js2-add-to-string ?D)
6535 (js2-add-to-string ?A)
6536 (js2-add-to-string ?T)
6537 (js2-add-to-string ?A)
6538 (js2-add-to-string ?\[)
6539 (unless (js2-read-cdata token)
6540 (throw 'return js2-ERROR)))
6541 (js2-xml-discard-string token)
6542 (throw 'return js2-ERROR)))
6543 (t
6544 (unless (js2-read-entity token)
6545 (throw 'return js2-ERROR))))
6546 ;; Allow bare CDATA section, e.g.:
6547 ;; let xml = <![CDATA[ foo bar baz ]]>;
6548 (when (zerop js2-ts-xml-open-tags-count)
6549 (throw 'return js2-XMLEND)))
6550 (??
6551 (setq c (js2-get-char)) ;; skip ?
6552 (js2-add-to-string c)
6553 (unless (js2-read-PI token)
6554 (throw 'return js2-ERROR)))
6555 (?/
6556 ;; end tag
6557 (setq c (js2-get-char)) ;; skip /
6558 (js2-add-to-string c)
6559 (when (zerop js2-ts-xml-open-tags-count)
6560 (js2-xml-discard-string token)
6561 (throw 'return js2-ERROR))
6562 (setq js2-ts-xml-is-tag-content t)
6563 (cl-decf js2-ts-xml-open-tags-count))
6564 (t
6565 ;; start tag
6566 (setq js2-ts-xml-is-tag-content t)
6567 (cl-incf js2-ts-xml-open-tags-count))))
6568 (?{
6569 (js2-unget-char)
6570 (js2-set-string-from-buffer token)
6571 (throw 'return js2-XML))
6572 (t
6573 (js2-add-to-string c))))))))
6574 (setf (js2-token-end token) js2-ts-cursor)
6575 (setf (js2-token-type token) result)
6576 result))
6577
6578 (defun js2-read-quoted-string (quote token)
6579 (let (c)
6580 (catch 'return
6581 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6582 (js2-add-to-string c)
6583 (if (eq c quote)
6584 (throw 'return t)))
6585 (js2-xml-discard-string token) ;; throw away string in progress
6586 nil)))
6587
6588 (defun js2-read-xml-comment (token)
6589 (let ((c (js2-get-char)))
6590 (catch 'return
6591 (while (/= c js2-EOF_CHAR)
6592 (catch 'continue
6593 (js2-add-to-string c)
6594 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6595 (setq c (js2-get-char))
6596 (js2-add-to-string c)
6597 (if (eq (js2-peek-char) ?>)
6598 (progn
6599 (setq c (js2-get-char)) ;; skip >
6600 (js2-add-to-string c)
6601 (throw 'return t))
6602 (throw 'continue nil)))
6603 (setq c (js2-get-char))))
6604 (js2-xml-discard-string token)
6605 nil)))
6606
6607 (defun js2-read-cdata (token)
6608 (let ((c (js2-get-char)))
6609 (catch 'return
6610 (while (/= c js2-EOF_CHAR)
6611 (catch 'continue
6612 (js2-add-to-string c)
6613 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6614 (setq c (js2-get-char))
6615 (js2-add-to-string c)
6616 (if (eq (js2-peek-char) ?>)
6617 (progn
6618 (setq c (js2-get-char)) ;; Skip >
6619 (js2-add-to-string c)
6620 (throw 'return t))
6621 (throw 'continue nil)))
6622 (setq c (js2-get-char))))
6623 (js2-xml-discard-string token)
6624 nil)))
6625
6626 (defun js2-read-entity (token)
6627 (let ((decl-tags 1)
6628 c)
6629 (catch 'return
6630 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6631 (js2-add-to-string c)
6632 (cl-case c
6633 (?<
6634 (cl-incf decl-tags))
6635 (?>
6636 (cl-decf decl-tags)
6637 (if (zerop decl-tags)
6638 (throw 'return t)))))
6639 (js2-xml-discard-string token)
6640 nil)))
6641
6642 (defun js2-read-PI (token)
6643 "Scan an XML processing instruction."
6644 (let (c)
6645 (catch 'return
6646 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6647 (js2-add-to-string c)
6648 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6649 (setq c (js2-get-char)) ;; Skip >
6650 (js2-add-to-string c)
6651 (throw 'return t)))
6652 (js2-xml-discard-string token)
6653 nil)))
6654
6655 ;;; Highlighting
6656
6657 (defun js2-set-face (beg end face &optional record)
6658 "Fontify a region. If RECORD is non-nil, record for later."
6659 (when (cl-plusp js2-highlight-level)
6660 (setq beg (min (point-max) beg)
6661 beg (max (point-min) beg)
6662 end (min (point-max) end)
6663 end (max (point-min) end))
6664 (if record
6665 (push (list beg end face) js2-mode-fontifications)
6666 (put-text-property beg end 'font-lock-face face))))
6667
6668 (defsubst js2-clear-face (beg end)
6669 (remove-text-properties beg end '(font-lock-face nil
6670 help-echo nil
6671 point-entered nil
6672 cursor-sensor-functions nil
6673 c-in-sws nil)))
6674
6675 (defconst js2-ecma-global-props
6676 (concat "^"
6677 (regexp-opt
6678 '("Infinity" "NaN" "undefined" "arguments") t)
6679 "$")
6680 "Value properties of the Ecma-262 Global Object.
6681 Shown at or above `js2-highlight-level' 2.")
6682
6683 ;; might want to add the name "arguments" to this list?
6684 (defconst js2-ecma-object-props
6685 (concat "^"
6686 (regexp-opt
6687 '("prototype" "__proto__" "__parent__") t)
6688 "$")
6689 "Value properties of the Ecma-262 Object constructor.
6690 Shown at or above `js2-highlight-level' 2.")
6691
6692 (defconst js2-ecma-global-funcs
6693 (concat
6694 "^"
6695 (regexp-opt
6696 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6697 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6698 "$")
6699 "Function properties of the Ecma-262 Global object.
6700 Shown at or above `js2-highlight-level' 2.")
6701
6702 (defconst js2-ecma-number-props
6703 (concat "^"
6704 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6705 "NEGATIVE_INFINITY"
6706 "POSITIVE_INFINITY") t)
6707 "$")
6708 "Properties of the Ecma-262 Number constructor.
6709 Shown at or above `js2-highlight-level' 2.")
6710
6711 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6712 "Properties of the Ecma-262 Date constructor.
6713 Shown at or above `js2-highlight-level' 2.")
6714
6715 (defconst js2-ecma-math-props
6716 (concat "^"
6717 (regexp-opt
6718 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6719 t)
6720 "$")
6721 "Properties of the Ecma-262 Math object.
6722 Shown at or above `js2-highlight-level' 2.")
6723
6724 (defconst js2-ecma-math-funcs
6725 (concat "^"
6726 (regexp-opt
6727 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6728 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6729 "$")
6730 "Function properties of the Ecma-262 Math object.
6731 Shown at or above `js2-highlight-level' 2.")
6732
6733 (defconst js2-ecma-function-props
6734 (concat
6735 "^"
6736 (regexp-opt
6737 '(;; properties of the Object prototype object
6738 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6739 "toLocaleString" "toString" "valueOf"
6740 ;; properties of the Function prototype object
6741 "apply" "call"
6742 ;; properties of the Array prototype object
6743 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6744 "splice" "unshift"
6745 ;; properties of the String prototype object
6746 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6747 "localeCompare" "match" "replace" "search" "split" "substring"
6748 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6749 "toUpperCase"
6750 ;; properties of the Number prototype object
6751 "toExponential" "toFixed" "toPrecision"
6752 ;; properties of the Date prototype object
6753 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6754 "getMinutes" "getMonth" "getSeconds" "getTime"
6755 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6756 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6757 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6758 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6759 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6760 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6761 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6762 "toTimeString" "toUTCString"
6763 ;; properties of the RegExp prototype object
6764 "exec" "test"
6765 ;; properties of the JSON prototype object
6766 "parse" "stringify"
6767 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6768 "toSource" "__defineGetter__" "__defineSetter__"
6769 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6770 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6771 t)
6772 "$")
6773 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6774 Shown at or above `js2-highlight-level' 3.")
6775
6776 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6777 (let ((target-name (and target
6778 (js2-name-node-p target)
6779 (js2-name-node-name target)))
6780 (prop-name (if prop (js2-name-node-name prop)))
6781 (level2 (>= js2-highlight-level 2))
6782 (level3 (>= js2-highlight-level 3)))
6783 (when level2
6784 (let ((face
6785 (if call-p
6786 (cond
6787 ((and target prop)
6788 (cond
6789 ((and level3 (string-match js2-ecma-function-props prop-name))
6790 'font-lock-builtin-face)
6791 ((and target-name prop)
6792 (cond
6793 ((string= target-name "Date")
6794 (if (string-match js2-ecma-date-props prop-name)
6795 'font-lock-builtin-face))
6796 ((string= target-name "Math")
6797 (if (string-match js2-ecma-math-funcs prop-name)
6798 'font-lock-builtin-face))))))
6799 (prop
6800 (if (string-match js2-ecma-global-funcs prop-name)
6801 'font-lock-builtin-face)))
6802 (cond
6803 ((and target prop)
6804 (cond
6805 ((string= target-name "Number")
6806 (if (string-match js2-ecma-number-props prop-name)
6807 'font-lock-constant-face))
6808 ((string= target-name "Math")
6809 (if (string-match js2-ecma-math-props prop-name)
6810 'font-lock-constant-face))))
6811 (prop
6812 (if (string-match js2-ecma-object-props prop-name)
6813 'font-lock-constant-face))))))
6814 (when (and (not face) target (not call-p) prop-name)
6815 (setq face 'js2-object-property))
6816 (when face
6817 (let ((pos (+ (js2-node-pos parent) ; absolute
6818 (js2-node-pos prop)))) ; relative
6819 (js2-set-face pos
6820 (+ pos (js2-node-len prop))
6821 face 'record)))))))
6822
6823 (defun js2-parse-highlight-member-expr-node (node)
6824 "Perform syntax highlighting of EcmaScript built-in properties.
6825 The variable `js2-highlight-level' governs this highlighting."
6826 (let (face target prop name pos end parent call-p callee)
6827 (cond
6828 ;; case 1: simple name, e.g. foo
6829 ((js2-name-node-p node)
6830 (setq name (js2-name-node-name node))
6831 ;; possible for name to be nil in rare cases - saw it when
6832 ;; running js2-mode on an elisp buffer. Might as well try to
6833 ;; make it so js2-mode never barfs.
6834 (when name
6835 (setq face (if (string-match js2-ecma-global-props name)
6836 'font-lock-constant-face))
6837 (when face
6838 (setq pos (js2-node-pos node)
6839 end (+ pos (js2-node-len node)))
6840 (js2-set-face pos end face 'record))))
6841 ;; case 2: property access or function call
6842 ((or (js2-prop-get-node-p node)
6843 ;; highlight function call if expr is a prop-get node
6844 ;; or a plain name (i.e. unqualified function call)
6845 (and (setq call-p (js2-call-node-p node))
6846 (setq callee (js2-call-node-target node)) ; separate setq!
6847 (or (js2-prop-get-node-p callee)
6848 (js2-name-node-p callee))))
6849 (setq parent node
6850 node (if call-p callee node))
6851 (if (and call-p (js2-name-node-p callee))
6852 (setq prop callee)
6853 (setq target (js2-prop-get-node-left node)
6854 prop (js2-prop-get-node-right node)))
6855 (cond
6856 ((js2-name-node-p prop)
6857 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6858 (js2-parse-highlight-prop-get parent target prop call-p))
6859 ((js2-name-node-p target)
6860 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6861 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6862
6863 (defun js2-parse-highlight-member-expr-fn-name (expr)
6864 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6865 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6866 We currently only handle the case where the last component is a prop-get
6867 of a simple name. Called before EXPR has a parent node."
6868 (let (pos
6869 (name (and (js2-prop-get-node-p expr)
6870 (js2-prop-get-node-right expr))))
6871 (when (js2-name-node-p name)
6872 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6873 (js2-node-pos name)))
6874 (+ pos (js2-node-len name))
6875 'font-lock-function-name-face
6876 'record))))
6877
6878 ;; source: http://jsdoc.sourceforge.net/
6879 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6880 ;; allows type specifications, and needs work before entering the wild.
6881
6882 (defconst js2-jsdoc-param-tag-regexp
6883 (concat "^\\s-*\\*+\\s-*\\(@"
6884 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6885 "\\)"
6886 "\\s-*\\({[^}]+}\\)?" ; optional type
6887 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6888 "\\_>")
6889 "Matches jsdoc tags with optional type and optional param name.")
6890
6891 (defconst js2-jsdoc-typed-tag-regexp
6892 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6893 (regexp-opt
6894 '("enum"
6895 "extends"
6896 "field"
6897 "id"
6898 "implements"
6899 "lends"
6900 "mods"
6901 "requires"
6902 "return"
6903 "returns"
6904 "throw"
6905 "throws"))
6906 "\\)\\)\\s-*\\({[^}]+}\\)?")
6907 "Matches jsdoc tags with optional type.")
6908
6909 (defconst js2-jsdoc-arg-tag-regexp
6910 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6911 (regexp-opt
6912 '("alias"
6913 "augments"
6914 "borrows"
6915 "callback"
6916 "bug"
6917 "base"
6918 "config"
6919 "default"
6920 "define"
6921 "exception"
6922 "func"
6923 "function"
6924 "member"
6925 "memberOf"
6926 "method"
6927 "name"
6928 "namespace"
6929 "since"
6930 "suppress"
6931 "this"
6932 "throws"
6933 "type"
6934 "version"))
6935 "\\)\\)\\s-+\\([^ \t]+\\)")
6936 "Matches jsdoc tags with a single argument.")
6937
6938 (defconst js2-jsdoc-empty-tag-regexp
6939 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6940 (regexp-opt
6941 '("addon"
6942 "author"
6943 "class"
6944 "const"
6945 "constant"
6946 "constructor"
6947 "constructs"
6948 "deprecated"
6949 "desc"
6950 "description"
6951 "event"
6952 "example"
6953 "exec"
6954 "export"
6955 "fileoverview"
6956 "final"
6957 "func"
6958 "function"
6959 "hidden"
6960 "ignore"
6961 "implicitCast"
6962 "inheritDoc"
6963 "inner"
6964 "interface"
6965 "license"
6966 "method"
6967 "noalias"
6968 "noshadow"
6969 "notypecheck"
6970 "override"
6971 "owner"
6972 "preserve"
6973 "preserveTry"
6974 "private"
6975 "protected"
6976 "public"
6977 "static"
6978 "supported"
6979 ))
6980 "\\)\\)\\s-*")
6981 "Matches empty jsdoc tags.")
6982
6983 (defconst js2-jsdoc-link-tag-regexp
6984 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6985 "Matches a jsdoc link or code tag.")
6986
6987 (defconst js2-jsdoc-see-tag-regexp
6988 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6989 "Matches a jsdoc @see tag.")
6990
6991 (defconst js2-jsdoc-html-tag-regexp
6992 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6993 "Matches a simple (no attributes) html start- or end-tag.")
6994
6995 (defun js2-jsdoc-highlight-helper ()
6996 (js2-set-face (match-beginning 1)
6997 (match-end 1)
6998 'js2-jsdoc-tag)
6999 (if (match-beginning 2)
7000 (if (save-excursion
7001 (goto-char (match-beginning 2))
7002 (= (char-after) ?{))
7003 (js2-set-face (1+ (match-beginning 2))
7004 (1- (match-end 2))
7005 'js2-jsdoc-type)
7006 (js2-set-face (match-beginning 2)
7007 (match-end 2)
7008 'js2-jsdoc-value)))
7009 (if (match-beginning 3)
7010 (js2-set-face (match-beginning 3)
7011 (match-end 3)
7012 'js2-jsdoc-value)))
7013
7014 (defun js2-highlight-jsdoc (ast)
7015 "Highlight doc comment tags."
7016 (let ((comments (js2-ast-root-comments ast))
7017 beg end)
7018 (save-excursion
7019 (dolist (node comments)
7020 (when (eq (js2-comment-node-format node) 'jsdoc)
7021 (setq beg (js2-node-abs-pos node)
7022 end (+ beg (js2-node-len node)))
7023 (save-restriction
7024 (narrow-to-region beg end)
7025 (dolist (re (list js2-jsdoc-param-tag-regexp
7026 js2-jsdoc-typed-tag-regexp
7027 js2-jsdoc-arg-tag-regexp
7028 js2-jsdoc-link-tag-regexp
7029 js2-jsdoc-see-tag-regexp
7030 js2-jsdoc-empty-tag-regexp))
7031 (goto-char beg)
7032 (while (re-search-forward re nil t)
7033 (js2-jsdoc-highlight-helper)))
7034 ;; simple highlighting for html tags
7035 (goto-char beg)
7036 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7037 (js2-set-face (match-beginning 1)
7038 (match-end 1)
7039 'js2-jsdoc-html-tag-delimiter)
7040 (js2-set-face (match-beginning 2)
7041 (match-end 2)
7042 'js2-jsdoc-html-tag-name)
7043 (js2-set-face (match-beginning 3)
7044 (match-end 3)
7045 'js2-jsdoc-html-tag-delimiter))))))))
7046
7047 (defun js2-highlight-assign-targets (_node left right)
7048 "Highlight function properties and external variables."
7049 (let (leftpos name)
7050 ;; highlight vars and props assigned function values
7051 (when (or (js2-function-node-p right)
7052 (js2-class-node-p right))
7053 (cond
7054 ;; var foo = function() {...}
7055 ((js2-name-node-p left)
7056 (setq name left))
7057 ;; foo.bar.baz = function() {...}
7058 ((and (js2-prop-get-node-p left)
7059 (js2-name-node-p (js2-prop-get-node-right left)))
7060 (setq name (js2-prop-get-node-right left))))
7061 (when name
7062 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7063 (+ leftpos (js2-node-len name))
7064 'font-lock-function-name-face
7065 'record)))))
7066
7067 (defun js2-record-name-node (node)
7068 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7069 later. NODE must be a name node."
7070 (let ((leftpos (js2-node-abs-pos node)))
7071 (push (list node js2-current-scope
7072 leftpos
7073 (+ leftpos (js2-node-len node)))
7074 js2-recorded-identifiers)))
7075
7076 (defun js2-highlight-undeclared-vars ()
7077 "After entire parse is finished, look for undeclared variable references.
7078 We have to wait until entire buffer is parsed, since JavaScript permits var
7079 decls to occur after they're used.
7080
7081 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7082 it is considered declared."
7083 (let (name)
7084 (dolist (entry js2-recorded-identifiers)
7085 (cl-destructuring-bind (name-node scope pos end) entry
7086 (setq name (js2-name-node-name name-node))
7087 (unless (or (member name js2-global-externs)
7088 (member name js2-default-externs)
7089 (member name js2-additional-externs)
7090 (js2-get-defining-scope scope name pos))
7091 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7092 'js2-external-variable))))))
7093
7094 (defun js2--add-or-update-symbol (symbol inition used vars)
7095 "Add or update SYMBOL entry in VARS, an hash table.
7096 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7097 respectively meaning that SYMBOL is a mere declaration, an
7098 assignment or a function parameter; when USED is t, the symbol
7099 node is assumed to be an usage and thus added to the list stored
7100 in the cdr of the entry.
7101 "
7102 (let* ((nm (js2-name-node-name symbol))
7103 (es (js2-node-get-enclosing-scope symbol))
7104 (ds (js2-get-defining-scope es nm)))
7105 (when (and ds (not (equal nm "arguments")))
7106 (let* ((sym (js2-scope-get-symbol ds nm))
7107 (var (gethash sym vars))
7108 (err-var-p (js2-catch-node-p ds)))
7109 (unless inition
7110 (setq inition err-var-p))
7111 (if var
7112 (progn
7113 (when (and inition (not (equal (car var) ?P)))
7114 (setcar var inition))
7115 (when used
7116 (push symbol (cdr var))))
7117 ;; do not consider the declaration of catch parameter as an usage
7118 (when (and err-var-p used)
7119 (setq used nil))
7120 (puthash sym (cons inition (if used (list symbol))) vars))))))
7121
7122 (defun js2--classify-variables ()
7123 "Collect and classify variables declared or used within js2-mode-ast.
7124 Traverse the whole ast tree returning a summary of the variables
7125 usage as an hash-table, keyed by their corresponding symbol table
7126 entry.
7127 Each variable is described by a tuple where the car is a flag
7128 indicating whether the variable has been initialized and the cdr
7129 is a possibly empty list of name nodes where it is used. External
7130 symbols, i.e. those not present in the whole scopes hierarchy,
7131 are ignored."
7132 (let ((vars (make-hash-table :test #'eq :size 100)))
7133 (js2-visit-ast
7134 js2-mode-ast
7135 (lambda (node end-p)
7136 (when (null end-p)
7137 (cond
7138 ((js2-var-init-node-p node)
7139 ;; take note about possibly initialized declarations
7140 (let ((target (js2-var-init-node-target node))
7141 (initializer (js2-var-init-node-initializer node)))
7142 (when target
7143 (let* ((parent (js2-node-parent node))
7144 (grandparent (if parent (js2-node-parent parent)))
7145 (inited (not (null initializer))))
7146 (unless inited
7147 (setq inited
7148 (and grandparent
7149 (js2-for-in-node-p grandparent)
7150 (memq target
7151 (mapcar #'js2-var-init-node-target
7152 (js2-var-decl-node-kids
7153 (js2-for-in-node-iterator grandparent)))))))
7154 (js2--add-or-update-symbol target inited nil vars)))))
7155
7156 ((js2-assign-node-p node)
7157 ;; take note about assignments
7158 (let ((left (js2-assign-node-left node)))
7159 (when (js2-name-node-p left)
7160 (js2--add-or-update-symbol left t nil vars))))
7161
7162 ((js2-prop-get-node-p node)
7163 ;; handle x.y.z nodes, considering only x
7164 (let ((left (js2-prop-get-node-left node)))
7165 (when (js2-name-node-p left)
7166 (js2--add-or-update-symbol left nil t vars))))
7167
7168 ((js2-name-node-p node)
7169 ;; take note about used variables
7170 (let ((parent (js2-node-parent node)))
7171 (when parent
7172 (unless (or (and (js2-var-init-node-p parent) ; handled above
7173 (eq node (js2-var-init-node-target parent)))
7174 (and (js2-assign-node-p parent)
7175 (eq node (js2-assign-node-left parent)))
7176 (js2-prop-get-node-p parent))
7177 (let ((used t) inited)
7178 (cond
7179 ((and (js2-function-node-p parent)
7180 (js2-wrapper-function-p parent))
7181 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7182
7183 ((js2-for-in-node-p parent)
7184 (if (eq node (js2-for-in-node-iterator parent))
7185 (setq inited t used nil)))
7186
7187 ((js2-function-node-p parent)
7188 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7189 used nil)))
7190
7191 (unless used
7192 (let ((grandparent (js2-node-parent parent)))
7193 (when grandparent
7194 (setq used (js2-return-node-p grandparent)))))
7195
7196 (js2--add-or-update-symbol node inited used vars))))))))
7197 t))
7198 vars))
7199
7200 (defun js2--get-name-node (node)
7201 (cond
7202 ((js2-name-node-p node) node)
7203 ((js2-function-node-p node)
7204 (js2-function-node-name node))
7205 ((js2-class-node-p node)
7206 (js2-class-node-name node))
7207 ((js2-comp-loop-node-p node)
7208 (js2-comp-loop-node-iterator node))
7209 (t node)))
7210
7211 (defun js2--highlight-unused-variable (symbol info)
7212 (let ((name (js2-symbol-name symbol))
7213 (inited (car info))
7214 (refs (cdr info))
7215 pos len)
7216 (unless (and inited refs)
7217 (if refs
7218 (dolist (ref refs)
7219 (setq pos (js2-node-abs-pos ref))
7220 (setq len (js2-name-node-len ref))
7221 (js2-report-warning "msg.uninitialized.variable" name pos len
7222 'js2-warning))
7223 (when (or js2-warn-about-unused-function-arguments
7224 (not (eq inited ?P)))
7225 (let* ((symn (js2-symbol-ast-node symbol))
7226 (namen (js2--get-name-node symn)))
7227 (unless (js2-node-top-level-decl-p namen)
7228 (setq pos (js2-node-abs-pos namen))
7229 (setq len (js2-name-node-len namen))
7230 (js2-report-warning "msg.unused.variable" name pos len
7231 'js2-warning))))))))
7232
7233 (defun js2-highlight-unused-variables ()
7234 "Highlight unused variables."
7235 (let ((vars (js2--classify-variables)))
7236 (maphash #'js2--highlight-unused-variable vars)))
7237
7238 ;;;###autoload
7239 (define-minor-mode js2-highlight-unused-variables-mode
7240 "Toggle highlight of unused variables."
7241 :lighter ""
7242 (if js2-highlight-unused-variables-mode
7243 (add-hook 'js2-post-parse-callbacks
7244 #'js2-highlight-unused-variables nil t)
7245 (remove-hook 'js2-post-parse-callbacks
7246 #'js2-highlight-unused-variables t)))
7247
7248 (defun js2-set-default-externs ()
7249 "Set the value of `js2-default-externs' based on the various
7250 `js2-include-?-externs' variables."
7251 (setq js2-default-externs
7252 (append js2-ecma-262-externs
7253 (if js2-include-browser-externs js2-browser-externs)
7254 (if (and js2-include-browser-externs
7255 (>= js2-language-version 200)) js2-harmony-externs)
7256 (if js2-include-rhino-externs js2-rhino-externs)
7257 (if js2-include-node-externs js2-node-externs)
7258 (if (or js2-include-browser-externs js2-include-node-externs)
7259 js2-typed-array-externs))))
7260
7261 (defun js2-apply-jslint-globals ()
7262 (setq js2-additional-externs
7263 (nconc (js2-get-jslint-globals)
7264 js2-additional-externs)))
7265
7266 (defun js2-get-jslint-globals ()
7267 (js2-reparse)
7268 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7269 when (and (eq 'block (js2-comment-node-format node))
7270 (save-excursion
7271 (goto-char (js2-node-abs-pos node))
7272 (looking-at "/\\* *global ")))
7273 append (js2-get-jslint-globals-in
7274 (match-end 0)
7275 (js2-node-abs-end node))))
7276
7277 (defun js2-get-jslint-globals-in (beg end)
7278 (let (res)
7279 (save-excursion
7280 (goto-char beg)
7281 (while (re-search-forward js2-mode-identifier-re end t)
7282 (let ((match (match-string 0)))
7283 (unless (member match '("true" "false"))
7284 (push match res)))))
7285 (nreverse res)))
7286
7287 ;;; IMenu support
7288
7289 ;; We currently only support imenu, but eventually should support speedbar and
7290 ;; possibly other browsing mechanisms.
7291
7292 ;; The basic strategy is to identify function assignment targets of the form
7293 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7294 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7295 ;; for imenu after parsing is finished.
7296
7297 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7298 ;; JavaScript, and the general problem is undecidable. However, several forms
7299 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7300 ;; include:
7301
7302 ;; function foo() -- function declaration
7303 ;; foo = function() -- function expression assigned to variable
7304 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7305 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7306 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7307 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7308 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7309 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7310 ;; function foo() {function bar() {...}} -- nested function
7311 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7312
7313 ;; This list boils down to a few forms that can be combined recursively.
7314 ;; Top-level named function declarations include both the left-hand (name)
7315 ;; and the right-hand (function value) expressions needed to produce an imenu
7316 ;; entry. The other "right-hand" forms we need to look for are:
7317 ;; - functions declared as props/getters/setters in object literals
7318 ;; - nested named function declarations
7319 ;; The "left-hand" expressions that functions can be assigned to include:
7320 ;; - local/global variables
7321 ;; - nested property-get expressions like a.b.c.d
7322 ;; - element gets like foo[10] or foo['bar'] where the index
7323 ;; expression can be trivially converted to a property name. They
7324 ;; effectively then become property gets.
7325
7326 ;; All the different definition types are canonicalized into the form
7327 ;; foo.bar.baz = position-of-function-keyword
7328
7329 ;; We need to build a trie-like structure for imenu. As an example,
7330 ;; consider the following JavaScript code:
7331
7332 ;; a = function() {...} // function at position 5
7333 ;; b = function() {...} // function at position 25
7334 ;; foo = function() {...} // function at position 100
7335 ;; foo.bar = function() {...} // function at position 200
7336 ;; foo.bar.baz = function() {...} // function at position 300
7337 ;; foo.bar.zab = function() {...} // function at position 400
7338
7339 ;; During parsing we accumulate an entry for each definition in
7340 ;; the variable `js2-imenu-recorder', like so:
7341
7342 ;; '((fn a 5)
7343 ;; (fn b 25)
7344 ;; (fn foo 100)
7345 ;; (fn foo bar 200)
7346 ;; (fn foo bar baz 300)
7347 ;; (fn foo bar zab 400))
7348
7349 ;; Where 'fn' is the respective function node.
7350 ;; After parsing these entries are merged into this alist-trie:
7351
7352 ;; '((a . 1)
7353 ;; (b . 2)
7354 ;; (foo (<definition> . 3)
7355 ;; (bar (<definition> . 6)
7356 ;; (baz . 100)
7357 ;; (zab . 200))))
7358
7359 ;; Note the wacky need for a <definition> name. The token can be anything
7360 ;; that isn't a valid JavaScript identifier, because you might make foo
7361 ;; a function and then start setting properties on it that are also functions.
7362
7363 (defun js2-prop-node-name (node)
7364 "Return the name of a node that may be a property-get/property-name.
7365 If NODE is not a valid name-node, string-node or integral number-node,
7366 returns nil. Otherwise returns the string name/value of the node."
7367 (cond
7368 ((js2-name-node-p node)
7369 (js2-name-node-name node))
7370 ((js2-string-node-p node)
7371 (js2-string-node-value node))
7372 ((and (js2-number-node-p node)
7373 (string-match "^[0-9]+$" (js2-number-node-value node)))
7374 (js2-number-node-value node))
7375 ((eq (js2-node-type node) js2-THIS)
7376 "this")
7377 ((eq (js2-node-type node) js2-SUPER)
7378 "super")))
7379
7380 (defun js2-node-qname-component (node)
7381 "Return the name of this node, if it contributes to a qname.
7382 Returns nil if the node doesn't contribute."
7383 (copy-sequence
7384 (or (js2-prop-node-name node)
7385 (if (and (js2-function-node-p node)
7386 (js2-function-node-name node))
7387 (js2-name-node-name (js2-function-node-name node))))))
7388
7389 (defun js2-record-imenu-entry (fn-node qname pos)
7390 "Add an entry to `js2-imenu-recorder'.
7391 FN-NODE should be the current item's function node.
7392
7393 Associate FN-NODE with its QNAME for later lookup.
7394 This is used in postprocessing the chain list. For each chain, we find
7395 the parent function, look up its qname, then prepend a copy of it to the chain."
7396 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7397 (unless js2-imenu-function-map
7398 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7399 (puthash fn-node qname js2-imenu-function-map))
7400
7401 (defun js2-record-imenu-functions (node &optional var)
7402 "Record function definitions for imenu.
7403 NODE is a function node or an object literal.
7404 VAR, if non-nil, is the expression that NODE is being assigned to.
7405 When passed arguments of wrong type, does nothing."
7406 (when js2-parse-ide-mode
7407 (let ((fun-p (js2-function-node-p node))
7408 qname fname-node)
7409 (cond
7410 ;; non-anonymous function declaration?
7411 ((and fun-p
7412 (not var)
7413 (setq fname-node (js2-function-node-name node)))
7414 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7415 ;; for remaining forms, compute left-side tree branch first
7416 ((and var (setq qname (js2-compute-nested-prop-get var)))
7417 (cond
7418 ;; foo.bar.baz = function
7419 (fun-p
7420 (js2-record-imenu-entry node qname (js2-node-pos node)))
7421 ;; foo.bar.baz = object-literal
7422 ;; look for nested functions: {a: {b: function() {...} }}
7423 ((js2-object-node-p node)
7424 ;; Node position here is still absolute, since the parser
7425 ;; passes the assignment target and value expressions
7426 ;; to us before they are added as children of the assignment node.
7427 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7428
7429 (defun js2-compute-nested-prop-get (node)
7430 "If NODE is of form foo.bar, foo[\\='bar\\='], or any nested combination, return
7431 component nodes as a list. Otherwise return nil. Element-gets are treated
7432 as property-gets if the index expression is a string, or a positive integer."
7433 (let (left right head)
7434 (cond
7435 ((or (js2-name-node-p node)
7436 (js2-this-or-super-node-p node))
7437 (list node))
7438 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7439 ((js2-prop-get-node-p node) ; foo.bar
7440 (setq left (js2-prop-get-node-left node)
7441 right (js2-prop-get-node-right node))
7442 (if (setq head (js2-compute-nested-prop-get left))
7443 (nconc head (list right))))
7444 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7445 (setq left (js2-elem-get-node-target node)
7446 right (js2-elem-get-node-element node))
7447 (if (or (js2-string-node-p right) ; ['bar']
7448 (and (js2-number-node-p right) ; [10]
7449 (string-match "^[0-9]+$"
7450 (js2-number-node-value right))))
7451 (if (setq head (js2-compute-nested-prop-get left))
7452 (nconc head (list right))))))))
7453
7454 (defun js2-record-object-literal (node qname pos)
7455 "Recursively process an object literal looking for functions.
7456 NODE is an object literal that is the right-hand child of an assignment
7457 expression. QNAME is a list of nodes representing the assignment target,
7458 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7459 POS is the absolute position of the node.
7460 We do a depth-first traversal of NODE. For any functions we find,
7461 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7462 (let (right)
7463 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7464 (when (js2-infix-node-p e)
7465 (let ((left (js2-infix-node-left e))
7466 ;; Element positions are relative to the parent position.
7467 (pos (+ pos (js2-node-pos e))))
7468 (cond
7469 ;; foo: function() {...}
7470 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7471 (when (js2-prop-node-name left)
7472 ;; As a policy decision, we record the position of the property,
7473 ;; not the position of the `function' keyword, since the property
7474 ;; is effectively the name of the function.
7475 (js2-record-imenu-entry right (append qname (list left)) pos)))
7476 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7477 ((js2-object-node-p right)
7478 (js2-record-object-literal right
7479 (append qname (list (js2-infix-node-left e)))
7480 (+ pos (js2-node-pos right))))))))))
7481
7482 (defun js2-node-top-level-decl-p (node)
7483 "Return t if NODE's name is defined in the top-level scope.
7484 Also returns t if NODE's name is not defined in any scope, since it implies
7485 that it's an external variable, which must also be in the top-level scope."
7486 (let* ((name (js2-prop-node-name node))
7487 (this-scope (js2-node-get-enclosing-scope node))
7488 defining-scope)
7489 (cond
7490 ((js2-this-or-super-node-p node)
7491 nil)
7492 ((null this-scope)
7493 t)
7494 ((setq defining-scope (js2-get-defining-scope this-scope name))
7495 (js2-ast-root-p defining-scope))
7496 (t t))))
7497
7498 (defun js2-wrapper-function-p (node)
7499 "Return t if NODE is a function expression that's immediately invoked.
7500 NODE must be `js2-function-node'."
7501 (let ((parent (js2-node-parent node)))
7502 (or
7503 ;; function(){...}();
7504 (and (js2-call-node-p parent)
7505 (eq node (js2-call-node-target parent)))
7506 (and (js2-paren-node-p parent)
7507 ;; (function(){...})();
7508 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7509 ;; (function(){...}).call(this);
7510 (and (js2-prop-get-node-p parent)
7511 (member (js2-name-node-name (js2-prop-get-node-right parent))
7512 '("call" "apply"))
7513 (js2-call-node-p (js2-node-parent parent))))))))
7514
7515 (defun js2-browse-postprocess-chains ()
7516 "Modify function-declaration name chains after parsing finishes.
7517 Some of the information is only available after the parse tree is complete.
7518 For instance, processing a nested scope requires a parent function node."
7519 (let (result fn parent-qname p elem)
7520 (dolist (entry js2-imenu-recorder)
7521 ;; function node goes first
7522 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest _)) entry
7523 ;; Examine head's defining scope:
7524 ;; Pre-processed chain, or top-level/external, keep as-is.
7525 (if (or (stringp head) (js2-node-top-level-decl-p head))
7526 (push chain result)
7527 (when (js2-this-or-super-node-p head)
7528 (setq chain (cdr chain))) ; discard this-node
7529 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7530 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7531 (when (eq parent-qname 'not-found)
7532 ;; anonymous function expressions are not recorded
7533 ;; during the parse, so we need to handle this case here
7534 (setq parent-qname
7535 (if (js2-wrapper-function-p fn)
7536 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7537 (if (js2-ast-root-p grandparent)
7538 nil
7539 (gethash grandparent js2-imenu-function-map 'skip)))
7540 'skip))
7541 (puthash fn parent-qname js2-imenu-function-map))
7542 (if (eq parent-qname 'skip)
7543 ;; We don't show it, let's record that fact.
7544 (remhash current-fn js2-imenu-function-map)
7545 ;; Prepend parent fn qname to this chain.
7546 (let ((qname (append parent-qname chain)))
7547 (puthash current-fn (butlast qname) js2-imenu-function-map)
7548 (push qname result)))))))
7549 ;; Collect chains obtained by third-party code.
7550 (let (js2-imenu-recorder)
7551 (run-hooks 'js2-build-imenu-callbacks)
7552 (dolist (entry js2-imenu-recorder)
7553 (push (cdr entry) result)))
7554 ;; Finally replace each node in each chain with its name.
7555 (dolist (chain result)
7556 (setq p chain)
7557 (while p
7558 (if (js2-node-p (setq elem (car p)))
7559 (setcar p (js2-node-qname-component elem)))
7560 (setq p (cdr p))))
7561 result))
7562
7563 ;; Merge name chains into a trie-like tree structure of nested lists.
7564 ;; To simplify construction of the trie, we first build it out using the rule
7565 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7566 ;; [key, num-or-list]. The second element can be a number; if so, this key
7567 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7568 ;; associated with the key at this level.) Otherwise the second element is
7569 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7570 ;; a simple recursive formulation.
7571 ;;
7572 ;; js2-mode is building the data structure for imenu. The imenu documentation
7573 ;; claims that it's the structure above, but in practice it wants the children
7574 ;; at the same list level as the key for that level, which is how I've drawn
7575 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7576 ;; list wrapper around the children at each level.
7577 ;;
7578 ;; A completed nested imenu-alist entry looks like this:
7579 ;; '(("foo"
7580 ;; ("<definition>" . 7)
7581 ;; ("bar"
7582 ;; ("a" . 40)
7583 ;; ("b" . 60))))
7584 ;;
7585 ;; In particular, the documentation for `imenu--index-alist' says that
7586 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7587 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7588
7589 (defun js2-treeify (lst)
7590 "Convert (a b c d) to (a ((b ((c d)))))."
7591 (if (null (cddr lst)) ; list length <= 2
7592 lst
7593 (list (car lst) (list (js2-treeify (cdr lst))))))
7594
7595 (defun js2-build-alist-trie (chains trie)
7596 "Merge declaration name chains into a trie-like alist structure for imenu.
7597 CHAINS is the qname chain list produced during parsing. TRIE is a
7598 list of elements built up so far."
7599 (let (head tail pos branch kids)
7600 (dolist (chain chains)
7601 (setq head (car chain)
7602 tail (cdr chain)
7603 pos (if (numberp (car tail)) (car tail))
7604 branch (js2-find-if (lambda (n)
7605 (string= (car n) head))
7606 trie)
7607 kids (cl-second branch))
7608 (cond
7609 ;; case 1: this key isn't in the trie yet
7610 ((null branch)
7611 (if trie
7612 (setcdr (last trie) (list (js2-treeify chain)))
7613 (setq trie (list (js2-treeify chain)))))
7614 ;; case 2: key is present with a single number entry: replace w/ list
7615 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7616 ;; ("<definition>" 20)))
7617 ((numberp kids)
7618 (setcar (cdr branch)
7619 (list (list "<definition-1>" kids)
7620 (if pos
7621 (list "<definition-2>" pos)
7622 (js2-treeify tail)))))
7623 ;; case 3: key is there (with kids), and we're a number entry
7624 (pos
7625 (setcdr (last kids)
7626 (list
7627 (list (format "<definition-%d>"
7628 (1+ (cl-loop for kid in kids
7629 count (eq ?< (aref (car kid) 0)))))
7630 pos))))
7631 ;; case 4: key is there with kids, need to merge in our chain
7632 (t
7633 (js2-build-alist-trie (list tail) kids))))
7634 trie))
7635
7636 (defun js2-flatten-trie (trie)
7637 "Convert TRIE to imenu-format.
7638 Recurses through nodes, and for each one whose second element is a list,
7639 appends the list's flattened elements to the current element. Also
7640 changes the tails into conses. For instance, this pre-flattened trie
7641
7642 (a ((b 20)
7643 (c ((d 30)
7644 (e 40)))))
7645
7646 becomes
7647
7648 (a (b . 20)
7649 (c (d . 30)
7650 (e . 40)))
7651
7652 Note that the root of the trie has no key, just a list of chains.
7653 This is also true for the value of any key with multiple children,
7654 e.g. key `c' in the example above."
7655 (cond
7656 ((listp (car trie))
7657 (mapcar #'js2-flatten-trie trie))
7658 (t
7659 (if (numberp (cl-second trie))
7660 (cons (car trie) (cl-second trie))
7661 ;; else pop list and append its kids
7662 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7663
7664 (defun js2-build-imenu-index ()
7665 "Turn `js2-imenu-recorder' into an imenu data structure."
7666 (when (eq js2-imenu-recorder 'empty)
7667 (setq js2-imenu-recorder nil))
7668 (let* ((chains (js2-browse-postprocess-chains))
7669 (result (js2-build-alist-trie chains nil)))
7670 (js2-flatten-trie result)))
7671
7672 (defun js2-test-print-chains (chains)
7673 "Print a list of qname chains.
7674 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7675 i.e. one or more nodes, and an integer position as the list tail."
7676 (mapconcat (lambda (chain)
7677 (concat "("
7678 (mapconcat (lambda (elem)
7679 (if (js2-node-p elem)
7680 (or (js2-node-qname-component elem)
7681 "nil")
7682 (number-to-string elem)))
7683 chain
7684 " ")
7685 ")"))
7686 chains
7687 "\n"))
7688
7689 ;;; Parser
7690
7691 (defconst js2-version "1.8.5"
7692 "Version of JavaScript supported.")
7693
7694 (defun js2-record-face (face &optional token)
7695 "Record a style run of FACE for TOKEN or the current token."
7696 (unless token (setq token (js2-current-token)))
7697 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7698
7699 (defsubst js2-node-end (n)
7700 "Computes the absolute end of node N.
7701 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7702 is only true until the node is added to its parent; i.e., while parsing."
7703 (+ (js2-node-pos n)
7704 (js2-node-len n)))
7705
7706 (defun js2-record-comment (token)
7707 "Record a comment in `js2-scanned-comments'."
7708 (let ((ct (js2-token-comment-type token))
7709 (beg (js2-token-beg token))
7710 (end (js2-token-end token)))
7711 (push (make-js2-comment-node :len (- end beg)
7712 :format ct)
7713 js2-scanned-comments)
7714 (when js2-parse-ide-mode
7715 (js2-record-face (if (eq ct 'jsdoc)
7716 'font-lock-doc-face
7717 'font-lock-comment-face)
7718 token)
7719 (when (memq ct '(html preprocessor))
7720 ;; Tell cc-engine the bounds of the comment.
7721 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7722
7723 (defun js2-peek-token ()
7724 "Return the next token type without consuming it.
7725 If `js2-ti-lookahead' is positive, return the type of next token
7726 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7727 (if (not (zerop js2-ti-lookahead))
7728 (js2-token-type
7729 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7730 (let ((tt (js2-get-token-internal nil)))
7731 (js2-unget-token)
7732 tt)))
7733
7734 (defalias 'js2-next-token 'js2-get-token)
7735
7736 (defun js2-match-token (match &optional dont-unget)
7737 "Get next token and return t if it matches MATCH, a bytecode.
7738 Returns nil and consumes nothing if MATCH is not the next token."
7739 (if (/= (js2-get-token) match)
7740 (ignore (unless dont-unget (js2-unget-token)))
7741 t))
7742
7743 (defun js2-match-contextual-kwd (name)
7744 "Consume and return t if next token is `js2-NAME', and its
7745 string is NAME. Returns nil and keeps current token otherwise."
7746 (if (js2-contextual-kwd-p (progn (js2-get-token)
7747 (js2-current-token))
7748 name)
7749 (progn (js2-record-face 'font-lock-keyword-face) t)
7750 (js2-unget-token)
7751 nil))
7752
7753 (defun js2-contextual-kwd-p (token name)
7754 "Return t if TOKEN is `js2-NAME', and its string is NAME."
7755 (and (= (js2-token-type token) js2-NAME)
7756 (string= (js2-token-string token) name)))
7757
7758 (defun js2-match-async-function ()
7759 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7760 (= (js2-peek-token) js2-FUNCTION))
7761 (js2-record-face 'font-lock-keyword-face)
7762 (js2-get-token)
7763 t))
7764
7765 (defun js2-match-async-arrow-function ()
7766 (and (js2-contextual-kwd-p (js2-current-token) "async")
7767 (/= (js2-peek-token) js2-FUNCTION)))
7768
7769 (defsubst js2-inside-function ()
7770 (cl-plusp js2-nesting-of-function))
7771
7772 (defsubst js2-inside-async-function ()
7773 (and (js2-inside-function)
7774 (js2-function-node-async js2-current-script-or-fn)))
7775
7776 (defun js2-parse-await-maybe (tt)
7777 "Parse \"await\" as an AwaitExpression, if it is one."
7778 (and (= tt js2-NAME)
7779 (js2-contextual-kwd-p (js2-current-token) "await")
7780 ;; Per the proposal, AwaitExpression consists of "await"
7781 ;; followed by a UnaryExpression. So look ahead for one.
7782 (let ((ts-state (make-js2-ts-state))
7783 (recorded-identifiers js2-recorded-identifiers)
7784 (parsed-errors js2-parsed-errors)
7785 (current-token (js2-current-token))
7786 (beg (js2-current-token-beg))
7787 (end (js2-current-token-end))
7788 pn)
7789 (js2-get-token)
7790 (setq pn (js2-make-unary js2-AWAIT 'js2-parse-unary-expr))
7791 (if (= (js2-node-type (js2-unary-node-operand pn)) js2-ERROR)
7792 ;; The parse failed, so pretend like nothing happened and restore
7793 ;; the previous parsing state.
7794 (progn
7795 (js2-ts-seek ts-state)
7796 (setq js2-recorded-identifiers recorded-identifiers
7797 js2-parsed-errors parsed-errors)
7798 ;; And ensure the caller knows about the failure.
7799 nil)
7800 ;; The parse was successful, so process and return the "await".
7801 (js2-record-face 'font-lock-keyword-face current-token)
7802 (unless (js2-inside-async-function)
7803 (js2-report-error "msg.bad.await" nil
7804 beg (- end beg)))
7805 pn))))
7806
7807 (defun js2-get-prop-name-token ()
7808 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7809
7810 (defun js2-match-prop-name ()
7811 "Consume token and return t if next token is a valid property name.
7812 If `js2-language-version' is >= 180, a keyword or reserved word
7813 is considered valid name as well."
7814 (if (eq js2-NAME (js2-get-prop-name-token))
7815 t
7816 (js2-unget-token)
7817 nil))
7818
7819 (defun js2-must-match-prop-name (msg-id &optional pos len)
7820 (if (js2-match-prop-name)
7821 t
7822 (js2-report-error msg-id nil pos len)
7823 nil))
7824
7825 (defun js2-peek-token-or-eol ()
7826 "Return js2-EOL if the next token immediately follows a newline.
7827 Else returns the next token. Used in situations where we don't
7828 consider certain token types valid if they are preceded by a newline.
7829 One example is the postfix ++ or -- operator, which has to be on the
7830 same line as its operand."
7831 (let ((tt (js2-get-token))
7832 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7833 (js2-unget-token)
7834 (if follows-eol
7835 js2-EOL
7836 tt)))
7837
7838 (defun js2-must-match (token msg-id &optional pos len)
7839 "Match next token to token code TOKEN, or record a syntax error.
7840 MSG-ID is the error message to report if the match fails.
7841 Returns t on match, nil if no match."
7842 (if (js2-match-token token t)
7843 t
7844 (js2-report-error msg-id nil pos len)
7845 (js2-unget-token)
7846 nil))
7847
7848 (defun js2-must-match-name (msg-id)
7849 (if (js2-match-token js2-NAME t)
7850 t
7851 (if (eq (js2-current-token-type) js2-RESERVED)
7852 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7853 (js2-report-error msg-id)
7854 (js2-unget-token))
7855 nil))
7856
7857 (defun js2-set-requires-activation ()
7858 (if (js2-function-node-p js2-current-script-or-fn)
7859 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7860
7861 (defun js2-check-activation-name (name _token)
7862 (when (js2-inside-function)
7863 ;; skip language-version 1.2 check from Rhino
7864 (if (or (string= "arguments" name)
7865 (and js2-compiler-activation-names ; only used in codegen
7866 (gethash name js2-compiler-activation-names)))
7867 (js2-set-requires-activation))))
7868
7869 (defun js2-set-is-generator ()
7870 (let ((fn-node js2-current-script-or-fn))
7871 (when (and (js2-function-node-p fn-node)
7872 (not (js2-function-node-generator-type fn-node)))
7873 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7874
7875 (defun js2-must-have-xml ()
7876 (unless js2-compiler-xml-available
7877 (js2-report-error "msg.XML.not.available")))
7878
7879 (defun js2-push-scope (scope)
7880 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7881 (cl-assert (js2-scope-p scope))
7882 (cl-assert (null (js2-scope-parent-scope scope)))
7883 (cl-assert (not (eq js2-current-scope scope)))
7884 (setf (js2-scope-parent-scope scope) js2-current-scope
7885 js2-current-scope scope))
7886
7887 (defsubst js2-pop-scope ()
7888 (setq js2-current-scope
7889 (js2-scope-parent-scope js2-current-scope)))
7890
7891 (defun js2-enter-loop (loop-node)
7892 (push loop-node js2-loop-set)
7893 (push loop-node js2-loop-and-switch-set)
7894 (js2-push-scope loop-node)
7895 ;; Tell the current labeled statement (if any) its statement,
7896 ;; and set the jump target of the first label to the loop.
7897 ;; These are used in `js2-parse-continue' to verify that the
7898 ;; continue target is an actual labeled loop. (And for codegen.)
7899 (when js2-labeled-stmt
7900 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7901 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7902 js2-labeled-stmt))) loop-node)))
7903
7904 (defun js2-exit-loop ()
7905 (pop js2-loop-set)
7906 (pop js2-loop-and-switch-set)
7907 (js2-pop-scope))
7908
7909 (defsubst js2-enter-switch (switch-node)
7910 (push switch-node js2-loop-and-switch-set))
7911
7912 (defsubst js2-exit-switch ()
7913 (pop js2-loop-and-switch-set))
7914
7915 (defsubst js2-get-directive (node)
7916 "Return NODE's value if it is a directive, nil otherwise.
7917
7918 A directive is an otherwise-meaningless expression statement
7919 consisting of a string literal, such as \"use strict\"."
7920 (and (js2-expr-stmt-node-p node)
7921 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7922 (js2-string-node-value node)))
7923
7924 (defun js2-parse (&optional buf cb)
7925 "Tell the js2 parser to parse a region of JavaScript.
7926
7927 BUF is a buffer or buffer name containing the code to parse.
7928 Call `narrow-to-region' first to parse only part of the buffer.
7929
7930 The returned AST root node is given some additional properties:
7931 `node-count' - total number of nodes in the AST
7932 `buffer' - BUF. The buffer it refers to may change or be killed,
7933 so the value is not necessarily reliable.
7934
7935 An optional callback CB can be specified to report parsing
7936 progress. If (functionp CB) returns t, it will be called with
7937 the current line number once before parsing begins, then again
7938 each time the lexer reaches a new line number.
7939
7940 CB can also be a list of the form (symbol cb ...) to specify
7941 multiple callbacks with different criteria. Each symbol is a
7942 criterion keyword, and the following element is the callback to
7943 call
7944
7945 :line - called whenever the line number changes
7946 :token - called for each new token consumed
7947
7948 The list of criteria could be extended to include entering or
7949 leaving a statement, an expression, or a function definition."
7950 (if (and cb (not (functionp cb)))
7951 (error "criteria callbacks not yet implemented"))
7952 (let ((inhibit-point-motion-hooks t)
7953 (js2-compiler-xml-available (>= js2-language-version 160))
7954 ;; This is a recursive-descent parser, so give it a big stack.
7955 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7956 (max-specpdl-size (max max-specpdl-size 3000))
7957 (case-fold-search nil)
7958 ast)
7959 (with-current-buffer (or buf (current-buffer))
7960 (setq js2-scanned-comments nil
7961 js2-parsed-errors nil
7962 js2-parsed-warnings nil
7963 js2-imenu-recorder nil
7964 js2-imenu-function-map nil
7965 js2-label-set nil)
7966 (js2-init-scanner)
7967 (setq ast (js2-do-parse))
7968 (unless js2-ts-hit-eof
7969 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7970 (setf (js2-ast-root-errors ast) js2-parsed-errors
7971 (js2-ast-root-warnings ast) js2-parsed-warnings)
7972 ;; if we didn't find any declarations, put a dummy in this list so we
7973 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7974 (unless js2-imenu-recorder
7975 (setq js2-imenu-recorder 'empty))
7976 (run-hooks 'js2-parse-finished-hook)
7977 ast)))
7978
7979 ;; Corresponds to Rhino's Parser.parse() method.
7980 (defun js2-do-parse ()
7981 "Parse current buffer starting from current point.
7982 Scanner should be initialized."
7983 (let ((pos js2-ts-cursor)
7984 (end js2-ts-cursor) ; in case file is empty
7985 root n tt
7986 (in-directive-prologue t)
7987 (js2-in-use-strict-directive js2-in-use-strict-directive)
7988 directive)
7989 ;; initialize buffer-local parsing vars
7990 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7991 js2-current-script-or-fn root
7992 js2-current-scope root
7993 js2-nesting-of-function 0
7994 js2-labeled-stmt nil
7995 js2-recorded-identifiers nil ; for js2-highlight
7996 js2-in-use-strict-directive js2-mode-assume-strict)
7997 (while (/= (setq tt (js2-get-token)) js2-EOF)
7998 (if (= tt js2-FUNCTION)
7999 (progn
8000 (setq n (if js2-called-by-compile-function
8001 (js2-parse-function-expr)
8002 (js2-parse-function-stmt))))
8003 ;; not a function - parse a statement
8004 (js2-unget-token)
8005 (setq n (js2-parse-statement))
8006 (when in-directive-prologue
8007 (setq directive (js2-get-directive n))
8008 (cond
8009 ((null directive)
8010 (setq in-directive-prologue nil))
8011 ((string= directive "use strict")
8012 (setq js2-in-use-strict-directive t)))))
8013 ;; add function or statement to script
8014 (setq end (js2-node-end n))
8015 (js2-block-node-push root n))
8016 ;; add comments to root in lexical order
8017 (when js2-scanned-comments
8018 ;; if we find a comment beyond end of normal kids, use its end
8019 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
8020 (dolist (comment js2-scanned-comments)
8021 (push comment (js2-ast-root-comments root))
8022 (js2-node-add-children root comment)))
8023 (setf (js2-node-len root) (- end pos))
8024 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
8025 ;; Give extensions a chance to muck with things before highlighting starts.
8026 (let ((js2-additional-externs js2-additional-externs))
8027 (save-excursion
8028 (run-hooks 'js2-post-parse-callbacks))
8029 (js2-highlight-undeclared-vars))
8030 root))
8031
8032 (defun js2-parse-function-closure-body (fn-node)
8033 "Parse a JavaScript 1.8 function closure body."
8034 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
8035 (if js2-ts-hit-eof
8036 (js2-report-error "msg.no.brace.body" nil
8037 (js2-node-pos fn-node)
8038 (- js2-ts-cursor (js2-node-pos fn-node)))
8039 (js2-node-add-children fn-node
8040 (setf (js2-function-node-body fn-node)
8041 (js2-parse-expr t))))))
8042
8043 (defun js2-parse-function-body (fn-node)
8044 (js2-must-match js2-LC "msg.no.brace.body"
8045 (js2-node-pos fn-node)
8046 (- js2-ts-cursor (js2-node-pos fn-node)))
8047 (let ((pos (js2-current-token-beg)) ; LC position
8048 (pn (make-js2-block-node)) ; starts at LC position
8049 tt
8050 end
8051 not-in-directive-prologue
8052 node
8053 directive)
8054 (cl-incf js2-nesting-of-function)
8055 (unwind-protect
8056 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8057 (= tt js2-EOF)
8058 (= tt js2-RC)))
8059 (js2-block-node-push
8060 pn
8061 (if (/= tt js2-FUNCTION)
8062 (if not-in-directive-prologue
8063 (js2-parse-statement)
8064 (setq node (js2-parse-statement)
8065 directive (js2-get-directive node))
8066 (cond
8067 ((null directive)
8068 (setq not-in-directive-prologue t))
8069 ((string= directive "use strict")
8070 ;; Back up and reparse the function, because new rules apply
8071 ;; to the function name and parameters.
8072 (when (not js2-in-use-strict-directive)
8073 (setq js2-in-use-strict-directive t)
8074 (throw 'reparse t))))
8075 node)
8076 (js2-get-token)
8077 (js2-parse-function-stmt))))
8078 (cl-decf js2-nesting-of-function))
8079 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8080 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8081 (setq end (js2-current-token-end)))
8082 (setf (js2-node-pos pn) pos
8083 (js2-node-len pn) (- end pos))
8084 (setf (js2-function-node-body fn-node) pn)
8085 (js2-node-add-children fn-node pn)
8086 pn))
8087
8088 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8089 "Declare and fontify destructuring parameters inside NODE.
8090 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8091
8092 Return a list of `js2-name-node' nodes representing the symbols
8093 declared; probably to check them for errors."
8094 (let (name-nodes)
8095 (cond
8096 ((js2-name-node-p node)
8097 (let (leftpos)
8098 (js2-define-symbol decl-type (js2-name-node-name node)
8099 node ignore-not-in-block)
8100 (when face
8101 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8102 (+ leftpos (js2-node-len node))
8103 face 'record))
8104 (list node)))
8105 ((js2-object-node-p node)
8106 (dolist (elem (js2-object-node-elems node))
8107 (let ((subexpr (cond
8108 ((and (js2-infix-node-p elem)
8109 (= js2-ASSIGN (js2-infix-node-type elem)))
8110 ;; Destructuring with default argument.
8111 (js2-infix-node-left elem))
8112 ((and (js2-infix-node-p elem)
8113 (= js2-COLON (js2-infix-node-type elem)))
8114 ;; In regular destructuring {a: aa, b: bb},
8115 ;; the var is on the right. In abbreviated
8116 ;; destructuring {a, b}, right == left.
8117 (js2-infix-node-right elem))
8118 ((and (js2-unary-node-p elem)
8119 (= js2-TRIPLEDOT (js2-unary-node-type elem)))
8120 ;; Destructuring with spread.
8121 (js2-unary-node-operand elem)))))
8122 (when subexpr
8123 (push (js2-define-destruct-symbols
8124 subexpr decl-type face ignore-not-in-block)
8125 name-nodes))))
8126 (apply #'append (nreverse name-nodes)))
8127 ((js2-array-node-p node)
8128 (dolist (elem (js2-array-node-elems node))
8129 (when elem
8130 (setq elem (cond ((js2-infix-node-p elem) ;; default (=)
8131 (js2-infix-node-left elem))
8132 ((js2-unary-node-p elem) ;; rest (...)
8133 (js2-unary-node-operand elem))
8134 (t elem)))
8135 (push (js2-define-destruct-symbols
8136 elem decl-type face ignore-not-in-block)
8137 name-nodes)))
8138 (apply #'append (nreverse name-nodes)))
8139 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8140 (js2-node-len node))
8141 nil))))
8142
8143 (defvar js2-illegal-strict-identifiers
8144 '("eval" "arguments")
8145 "Identifiers not allowed as variables in strict mode.")
8146
8147 (defun js2-check-strict-identifier (name-node)
8148 "Check that NAME-NODE makes a legal strict mode identifier."
8149 (when js2-in-use-strict-directive
8150 (let ((param-name (js2-name-node-name name-node)))
8151 (when (member param-name js2-illegal-strict-identifiers)
8152 (js2-report-error "msg.bad.id.strict" param-name
8153 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8154
8155 (defun js2-check-strict-function-params (preceding-params params)
8156 "Given PRECEDING-PARAMS in a function's parameter list, check
8157 for strict mode errors caused by PARAMS."
8158 (when js2-in-use-strict-directive
8159 (dolist (param params)
8160 (let ((param-name (js2-name-node-name param)))
8161 (js2-check-strict-identifier param)
8162 (when (cl-some (lambda (param)
8163 (string= (js2-name-node-name param) param-name))
8164 preceding-params)
8165 (js2-report-error "msg.dup.param.strict" param-name
8166 (js2-node-abs-pos param) (js2-node-len param)))))))
8167
8168 (defun js2-parse-function-params (function-type fn-node pos)
8169 "Parse the parameters of a function of FUNCTION-TYPE
8170 represented by FN-NODE at POS."
8171 (if (js2-match-token js2-RP)
8172 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8173 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8174 (eq (js2-current-token-type) js2-NAME)))
8175 params param
8176 param-name-nodes new-param-name-nodes
8177 rest-param-at)
8178 (when paren-free-arrow
8179 (js2-unget-token))
8180 (cl-loop for tt = (js2-peek-token)
8181 do
8182 (cond
8183 ;; destructuring param
8184 ((and (not paren-free-arrow)
8185 (or (= tt js2-LB) (= tt js2-LC)))
8186 (js2-get-token)
8187 (setq param (js2-parse-destruct-primary-expr)
8188 new-param-name-nodes (js2-define-destruct-symbols
8189 param js2-LP 'js2-function-param))
8190 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8191 (setq param-name-nodes (append param-name-nodes new-param-name-nodes)))
8192 ;; variable name
8193 (t
8194 (when (and (>= js2-language-version 200)
8195 (not paren-free-arrow)
8196 (js2-match-token js2-TRIPLEDOT)
8197 (not rest-param-at))
8198 ;; to report errors if there are more parameters
8199 (setq rest-param-at (length params)))
8200 (js2-must-match-name "msg.no.parm")
8201 (js2-record-face 'js2-function-param)
8202 (setq param (js2-create-name-node))
8203 (js2-define-symbol js2-LP (js2-current-token-string) param)
8204 (js2-check-strict-function-params param-name-nodes (list param))
8205 (setq param-name-nodes (append param-name-nodes (list param)))))
8206 ;; default parameter value
8207 (when (and (not rest-param-at)
8208 (>= js2-language-version 200)
8209 (js2-match-token js2-ASSIGN))
8210 (cl-assert (not paren-free-arrow))
8211 (let* ((pos (js2-node-pos param))
8212 (tt (js2-current-token-type))
8213 (op-pos (- (js2-current-token-beg) pos))
8214 (left param)
8215 (right (js2-parse-assign-expr))
8216 (len (- (js2-node-end right) pos)))
8217 (setq param (make-js2-assign-node
8218 :type tt :pos pos :len len :op-pos op-pos
8219 :left left :right right))
8220 (js2-node-add-children param left right)))
8221 (push param params)
8222 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8223 (js2-report-error "msg.param.after.rest" nil
8224 (js2-node-pos param) (js2-node-len param)))
8225 while
8226 (js2-match-token js2-COMMA))
8227 (when (and (not paren-free-arrow)
8228 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8229 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8230 (when rest-param-at
8231 (setf (js2-function-node-rest-p fn-node) t))
8232 (dolist (p params)
8233 (js2-node-add-children fn-node p)
8234 (push p (js2-function-node-params fn-node))))))
8235
8236 (defun js2-check-inconsistent-return-warning (fn-node name)
8237 "Possibly show inconsistent-return warning.
8238 Last token scanned is the close-curly for the function body."
8239 (when (and js2-mode-show-strict-warnings
8240 js2-strict-inconsistent-return-warning
8241 (not (js2-has-consistent-return-usage
8242 (js2-function-node-body fn-node))))
8243 ;; Have it extend from close-curly to bol or beginning of block.
8244 (let ((pos (save-excursion
8245 (goto-char (js2-current-token-end))
8246 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8247 (point-at-bol))))
8248 (end (js2-current-token-end)))
8249 (if (cl-plusp (js2-name-node-length name))
8250 (js2-add-strict-warning "msg.no.return.value"
8251 (js2-name-node-name name) pos end)
8252 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8253
8254 (defun js2-parse-function-stmt (&optional async-p)
8255 (let ((pos (js2-current-token-beg))
8256 (star-p (js2-match-token js2-MUL)))
8257 (js2-must-match-name "msg.unnamed.function.stmt")
8258 (let ((name (js2-create-name-node t))
8259 pn member-expr)
8260 (cond
8261 ((js2-match-token js2-LP)
8262 (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p name))
8263 (js2-allow-member-expr-as-function-name
8264 (setq member-expr (js2-parse-member-expr-tail nil name))
8265 (js2-parse-highlight-member-expr-fn-name member-expr)
8266 (js2-must-match js2-LP "msg.no.paren.parms")
8267 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p)
8268 (js2-function-node-member-expr pn) member-expr)
8269 pn)
8270 (t
8271 (js2-report-error "msg.no.paren.parms")
8272 (make-js2-error-node))))))
8273
8274 (defun js2-parse-async-function-stmt ()
8275 (js2-parse-function-stmt t))
8276
8277 (defun js2-parse-function-expr (&optional async-p)
8278 (let ((pos (js2-current-token-beg))
8279 (star-p (js2-match-token js2-MUL))
8280 name)
8281 (when (js2-match-token js2-NAME)
8282 (setq name (js2-create-name-node t)))
8283 (js2-must-match js2-LP "msg.no.paren.parms")
8284 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p async-p name)))
8285
8286 (defun js2-parse-function-internal (function-type pos star-p &optional async-p name)
8287 (let (fn-node lp)
8288 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8289 (setq lp (js2-current-token-beg)))
8290 (setf fn-node (make-js2-function-node :pos pos
8291 :name name
8292 :form function-type
8293 :lp (if lp (- lp pos))
8294 :generator-type (and star-p 'STAR)
8295 :async async-p))
8296 (when name
8297 (js2-set-face (js2-node-pos name) (js2-node-end name)
8298 'font-lock-function-name-face 'record)
8299 (when (and (eq function-type 'FUNCTION_STATEMENT)
8300 (cl-plusp (js2-name-node-length name)))
8301 ;; Function statements define a symbol in the enclosing scope
8302 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8303 (when js2-in-use-strict-directive
8304 (js2-check-strict-identifier name)))
8305 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8306 ;; 1. Nested functions are not affected by the dynamic scope flag
8307 ;; as dynamic scope is already a parent of their scope.
8308 ;; 2. Functions defined under the with statement also immune to
8309 ;; this setup, in which case dynamic scope is ignored in favor
8310 ;; of the with object.
8311 (setf (js2-function-node-ignore-dynamic fn-node) t))
8312 ;; dynamically bind all the per-function variables
8313 (let ((js2-current-script-or-fn fn-node)
8314 (js2-current-scope fn-node)
8315 (js2-nesting-of-with 0)
8316 (js2-end-flags 0)
8317 js2-label-set
8318 js2-loop-set
8319 js2-loop-and-switch-set)
8320 (js2-parse-function-params function-type fn-node pos)
8321 (when (eq function-type 'FUNCTION_ARROW)
8322 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8323 (if (and (>= js2-language-version 180)
8324 (/= (js2-peek-token) js2-LC))
8325 (js2-parse-function-closure-body fn-node)
8326 (js2-parse-function-body fn-node))
8327 (js2-check-inconsistent-return-warning fn-node name)
8328
8329 (when name
8330 (js2-node-add-children fn-node name)
8331 ;; Function expressions define a name only in the body of the
8332 ;; function, and only if not hidden by a parameter name
8333 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8334 (null (js2-scope-get-symbol js2-current-scope
8335 (js2-name-node-name name))))
8336 (js2-define-symbol js2-FUNCTION
8337 (js2-name-node-name name)
8338 fn-node))
8339 (when (eq function-type 'FUNCTION_STATEMENT)
8340 (js2-record-imenu-functions fn-node))))
8341
8342 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8343 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8344 ;; We wait until after parsing the function to set its parent scope,
8345 ;; since `js2-define-symbol' needs the defining-scope check to stop
8346 ;; at the function boundary when checking for redeclarations.
8347 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8348 fn-node))
8349
8350 (defun js2-parse-function (function-type pos star-p &optional async-p name)
8351 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8352 beginning of the first token (function keyword, unless it's an
8353 arrow function), NAME is js2-name-node."
8354 (let ((continue t)
8355 ts-state
8356 fn-node
8357 ;; Preserve strict state outside this function.
8358 (js2-in-use-strict-directive js2-in-use-strict-directive))
8359 ;; Parse multiple times if a new strict mode directive is discovered in the
8360 ;; function body, as new rules will be retroactively applied to the legality
8361 ;; of function names and parameters.
8362 (while continue
8363 (setq ts-state (make-js2-ts-state))
8364 (setq continue (catch 'reparse
8365 (setq fn-node (js2-parse-function-internal
8366 function-type pos star-p async-p name))
8367 ;; Don't continue.
8368 nil))
8369 (when continue
8370 (js2-ts-seek ts-state)))
8371 fn-node))
8372
8373 (defun js2-parse-statements (&optional parent)
8374 "Parse a statement list. Last token consumed must be js2-LC.
8375
8376 PARENT can be a `js2-block-node', in which case the statements are
8377 appended to PARENT. Otherwise a new `js2-block-node' is created
8378 and returned.
8379
8380 This function does not match the closing js2-RC: the caller
8381 matches the RC so it can provide a suitable error message if not
8382 matched. This means it's up to the caller to set the length of
8383 the node to include the closing RC. The node start pos is set to
8384 the absolute buffer start position, and the caller should fix it
8385 up to be relative to the parent node. All children of this block
8386 node are given relative start positions and correct lengths."
8387 (let ((pn (or parent (make-js2-block-node)))
8388 tt)
8389 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8390 (/= tt js2-RC))
8391 (js2-block-node-push pn (js2-parse-statement)))
8392 pn))
8393
8394 (defun js2-parse-statement ()
8395 (let (pn beg end)
8396 ;; coarse-grained user-interrupt check - needs work
8397 (and js2-parse-interruptable-p
8398 (zerop (% (cl-incf js2-parse-stmt-count)
8399 js2-statements-per-pause))
8400 (input-pending-p)
8401 (throw 'interrupted t))
8402 (setq pn (js2-statement-helper))
8403 ;; no-side-effects warning check
8404 (unless (js2-node-has-side-effects pn)
8405 (setq end (js2-node-end pn))
8406 (save-excursion
8407 (goto-char end)
8408 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8409 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8410 pn))
8411
8412 ;; These correspond to the switch cases in Parser.statementHelper
8413 (defconst js2-parsers
8414 (let ((parsers (make-vector js2-num-tokens
8415 #'js2-parse-expr-stmt)))
8416 (aset parsers js2-BREAK #'js2-parse-break)
8417 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8418 (aset parsers js2-CONST #'js2-parse-const-var)
8419 (aset parsers js2-CONTINUE #'js2-parse-continue)
8420 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8421 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8422 (aset parsers js2-DO #'js2-parse-do)
8423 (aset parsers js2-EXPORT #'js2-parse-export)
8424 (aset parsers js2-FOR #'js2-parse-for)
8425 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8426 (aset parsers js2-IF #'js2-parse-if)
8427 (aset parsers js2-IMPORT #'js2-parse-import)
8428 (aset parsers js2-LC #'js2-parse-block)
8429 (aset parsers js2-LET #'js2-parse-let-stmt)
8430 (aset parsers js2-NAME #'js2-parse-name-or-label)
8431 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8432 (aset parsers js2-SEMI #'js2-parse-semi)
8433 (aset parsers js2-SWITCH #'js2-parse-switch)
8434 (aset parsers js2-THROW #'js2-parse-throw)
8435 (aset parsers js2-TRY #'js2-parse-try)
8436 (aset parsers js2-VAR #'js2-parse-const-var)
8437 (aset parsers js2-WHILE #'js2-parse-while)
8438 (aset parsers js2-WITH #'js2-parse-with)
8439 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8440 parsers)
8441 "A vector mapping token types to parser functions.")
8442
8443 (defun js2-parse-warn-missing-semi (beg end)
8444 (and js2-mode-show-strict-warnings
8445 js2-strict-missing-semi-warning
8446 (js2-add-strict-warning
8447 "msg.missing.semi" nil
8448 ;; back up to beginning of statement or line
8449 (max beg (save-excursion
8450 (goto-char end)
8451 (point-at-bol)))
8452 end)))
8453
8454 (defconst js2-no-semi-insertion
8455 (list js2-IF
8456 js2-SWITCH
8457 js2-WHILE
8458 js2-DO
8459 js2-FOR
8460 js2-TRY
8461 js2-WITH
8462 js2-LC
8463 js2-ERROR
8464 js2-SEMI
8465 js2-CLASS
8466 js2-FUNCTION
8467 js2-EXPORT)
8468 "List of tokens that don't do automatic semicolon insertion.")
8469
8470 (defconst js2-autoinsert-semi-and-warn
8471 (list js2-ERROR js2-EOF js2-RC))
8472
8473 (defun js2-statement-helper ()
8474 (let* ((tt (js2-get-token))
8475 (first-tt tt)
8476 (async-stmt (js2-match-async-function))
8477 (parser (if (= tt js2-ERROR)
8478 #'js2-parse-semi
8479 (if async-stmt
8480 #'js2-parse-async-function-stmt
8481 (aref js2-parsers tt))))
8482 pn)
8483 ;; If the statement is set, then it's been told its label by now.
8484 (and js2-labeled-stmt
8485 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8486 (setq js2-labeled-stmt nil))
8487 (setq pn (funcall parser))
8488 ;; Don't do auto semi insertion for certain statement types.
8489 (unless (or (memq first-tt js2-no-semi-insertion)
8490 (js2-labeled-stmt-node-p pn)
8491 async-stmt)
8492 (js2-auto-insert-semicolon pn))
8493 pn))
8494
8495 (defun js2-auto-insert-semicolon (pn)
8496 (let* ((tt (js2-get-token))
8497 (pos (js2-node-pos pn)))
8498 (cond
8499 ((= tt js2-SEMI)
8500 ;; extend the node bounds to include the semicolon.
8501 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8502 ((memq tt js2-autoinsert-semi-and-warn)
8503 (js2-unget-token) ; Not ';', do not consume.
8504 ;; Autoinsert ;
8505 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8506 (t
8507 (if (not (js2-token-follows-eol-p (js2-current-token)))
8508 ;; Report error if no EOL or autoinsert ';' otherwise
8509 (js2-report-error "msg.no.semi.stmt")
8510 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8511 (js2-unget-token) ; Not ';', do not consume.
8512 ))))
8513
8514 (defun js2-parse-condition ()
8515 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8516 The parens are discarded and the expression node is returned.
8517 The `pos' field of the return value is set to an absolute position
8518 that must be fixed up by the caller.
8519 Return value is a list (EXPR LP RP), with absolute paren positions."
8520 (let (pn lp rp)
8521 (if (js2-must-match js2-LP "msg.no.paren.cond")
8522 (setq lp (js2-current-token-beg)))
8523 (setq pn (js2-parse-expr))
8524 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8525 (setq rp (js2-current-token-beg)))
8526 ;; Report strict warning on code like "if (a = 7) ..."
8527 (if (and js2-strict-cond-assign-warning
8528 (js2-assign-node-p pn))
8529 (js2-add-strict-warning "msg.equal.as.assign" nil
8530 (js2-node-pos pn)
8531 (+ (js2-node-pos pn)
8532 (js2-node-len pn))))
8533 (list pn lp rp)))
8534
8535 (defun js2-parse-if ()
8536 "Parser for if-statement. Last matched token must be js2-IF."
8537 (let ((pos (js2-current-token-beg))
8538 cond if-true if-false else-pos end pn)
8539 (setq cond (js2-parse-condition)
8540 if-true (js2-parse-statement)
8541 if-false (if (js2-match-token js2-ELSE)
8542 (progn
8543 (setq else-pos (- (js2-current-token-beg) pos))
8544 (js2-parse-statement)))
8545 end (js2-node-end (or if-false if-true))
8546 pn (make-js2-if-node :pos pos
8547 :len (- end pos)
8548 :condition (car cond)
8549 :then-part if-true
8550 :else-part if-false
8551 :else-pos else-pos
8552 :lp (js2-relpos (cl-second cond) pos)
8553 :rp (js2-relpos (cl-third cond) pos)))
8554 (js2-node-add-children pn (car cond) if-true if-false)
8555 pn))
8556
8557 (defun js2-parse-import ()
8558 "Parse import statement. The current token must be js2-IMPORT."
8559 (unless (js2-ast-root-p js2-current-scope)
8560 (js2-report-error "msg.mod.import.decl.at.top.level"))
8561 (let ((beg (js2-current-token-beg)))
8562 (cond ((js2-match-token js2-STRING)
8563 (make-js2-import-node
8564 :pos beg
8565 :len (- (js2-current-token-end) beg)
8566 :module-id (js2-current-token-string)))
8567 (t
8568 (let* ((import-clause (js2-parse-import-clause))
8569 (from-clause (and import-clause (js2-parse-from-clause)))
8570 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8571 (node (make-js2-import-node
8572 :pos beg
8573 :len (- (js2-current-token-end) beg)
8574 :import import-clause
8575 :from from-clause
8576 :module-id module-id)))
8577 (when import-clause
8578 (js2-node-add-children node import-clause))
8579 (when from-clause
8580 (js2-node-add-children node from-clause))
8581 node)))))
8582
8583 (defun js2-parse-import-clause ()
8584 "Parse the bindings in an import statement.
8585 This can take many forms:
8586
8587 ImportedDefaultBinding -> `foo'
8588 NameSpaceImport -> `* as lib'
8589 NamedImports -> `{foo as bar, bang}'
8590 ImportedDefaultBinding , NameSpaceImport -> `foo, * as lib'
8591 ImportedDefaultBinding , NamedImports -> `foo, {bar, baz as bif}'
8592
8593 Try to match namespace imports and named imports first because nothing can
8594 come after them. If it is an imported default binding, then it could have named
8595 imports or a namespace import that follows it.
8596 "
8597 (let* ((beg (js2-current-token-beg))
8598 (clause (make-js2-import-clause-node
8599 :pos beg))
8600 (children (list)))
8601 (cond
8602 ((js2-match-token js2-MUL)
8603 (let ((ns-import (js2-parse-namespace-import)))
8604 (when ns-import
8605 (let ((name-node (js2-namespace-import-node-name ns-import)))
8606 (js2-define-symbol
8607 js2-LET (js2-name-node-name name-node) name-node t)))
8608 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8609 (push ns-import children)))
8610 ((js2-match-token js2-LC)
8611 (let ((imports (js2-parse-export-bindings t)))
8612 (setf (js2-import-clause-node-named-imports clause) imports)
8613 (dolist (import imports)
8614 (push import children)
8615 (let ((name-node (js2-export-binding-node-local-name import)))
8616 (when name-node
8617 (js2-define-symbol
8618 js2-LET (js2-name-node-name name-node) name-node t))))))
8619 ((= (js2-peek-token) js2-NAME)
8620 (let ((binding (js2-maybe-parse-export-binding t)))
8621 (let ((node-name (js2-export-binding-node-local-name binding)))
8622 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8623 (setf (js2-import-clause-node-default-binding clause) binding)
8624 (push binding children))
8625 (when (js2-match-token js2-COMMA)
8626 (cond
8627 ((js2-match-token js2-MUL)
8628 (let ((ns-import (js2-parse-namespace-import)))
8629 (let ((name-node (js2-namespace-import-node-name ns-import)))
8630 (js2-define-symbol
8631 js2-LET (js2-name-node-name name-node) name-node t))
8632 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8633 (push ns-import children)))
8634 ((js2-match-token js2-LC)
8635 (let ((imports (js2-parse-export-bindings t)))
8636 (setf (js2-import-clause-node-named-imports clause) imports)
8637 (dolist (import imports)
8638 (push import children)
8639 (let ((name-node (js2-export-binding-node-local-name import)))
8640 (when name-node
8641 (js2-define-symbol
8642 js2-LET (js2-name-node-name name-node) name-node t))))))
8643 (t (js2-report-error "msg.syntax")))))
8644 (t (js2-report-error "msg.mod.declaration.after.import")))
8645 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8646 (apply #'js2-node-add-children clause children)
8647 clause))
8648
8649 (defun js2-parse-namespace-import ()
8650 "Parse a namespace import expression such as `* as bar'.
8651 The current token must be js2-MUL."
8652 (let ((beg (js2-current-token-beg)))
8653 (if (js2-match-contextual-kwd "as")
8654 (when (js2-must-match-prop-name "msg.syntax")
8655 (let ((node (make-js2-namespace-import-node
8656 :pos beg
8657 :len (- (js2-current-token-end) beg)
8658 :name (make-js2-name-node
8659 :pos (js2-current-token-beg)
8660 :len (js2-current-token-end)
8661 :name (js2-current-token-string)))))
8662 (js2-node-add-children node (js2-namespace-import-node-name node))
8663 node))
8664 (js2-unget-token)
8665 (js2-report-error "msg.syntax"))))
8666
8667
8668 (defun js2-parse-from-clause ()
8669 "Parse the from clause in an import or export statement.
8670 E.g., \"from \\='src/lib\\='\"."
8671 (if (js2-match-contextual-kwd "from")
8672 (let ((beg (js2-current-token-beg)))
8673 (cond
8674 ((js2-match-token js2-STRING)
8675 (make-js2-from-clause-node
8676 :pos beg
8677 :len (- (js2-current-token-end) beg)
8678 :module-id (js2-current-token-string)
8679 :metadata-p nil))
8680 ((js2-match-token js2-THIS)
8681 (when (js2-must-match-name "msg.mod.spec.after.from")
8682 (if (equal "module" (js2-current-token-string))
8683 (make-js2-from-clause-node
8684 :pos beg
8685 :len (- (js2-current-token-end) beg)
8686 :module-id "this"
8687 :metadata-p t)
8688 (js2-unget-token)
8689 (js2-unget-token)
8690 (js2-report-error "msg.mod.spec.after.from")
8691 nil)))
8692 (t (js2-report-error "msg.mod.spec.after.from") nil)))
8693 (js2-report-error "msg.mod.from.after.import.spec.set")
8694 nil))
8695
8696 (defun js2-parse-export-bindings (&optional import-p)
8697 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8698 {foo as bar, baz as bang}. The current token must be
8699 js2-LC. Return a lisp list of js2-export-binding-node"
8700 (let ((bindings (list)))
8701 (while
8702 (let ((binding (js2-maybe-parse-export-binding import-p)))
8703 (when binding
8704 (push binding bindings))
8705 (js2-match-token js2-COMMA)))
8706 (when (js2-must-match js2-RC (if import-p
8707 "msg.mod.rc.after.import.spec.list"
8708 "msg.mod.rc.after.export.spec.list"))
8709 (reverse bindings))))
8710
8711 (defun js2-maybe-parse-export-binding (&optional import-p)
8712 "Attempt to parse a binding expression found inside an import/export statement.
8713 This can take the form of either as single js2-NAME token as in `foo' or as in a
8714 rebinding expression `bar as foo'. If it matches, it will return an instance of
8715 js2-export-binding-node and consume all the tokens. If it does not match, it
8716 consumes no tokens."
8717 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8718 (beg (js2-current-token-beg))
8719 (extern-name-len (js2-current-token-len))
8720 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8721 (aref js2-kwd-tokens (js2-current-token-type)))))
8722 (if extern-name
8723 (if (js2-match-contextual-kwd "as")
8724 (let ((name
8725 (or
8726 (and (js2-match-token js2-DEFAULT) "default")
8727 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8728 (if name
8729 (let ((node (make-js2-export-binding-node
8730 :pos beg
8731 :len (- (js2-current-token-end) beg)
8732 :local-name (make-js2-name-node
8733 :name name
8734 :pos (js2-current-token-beg)
8735 :len (js2-current-token-len))
8736 :extern-name (make-js2-name-node
8737 :name extern-name
8738 :pos beg
8739 :len extern-name-len))))
8740 (js2-node-add-children
8741 node
8742 (js2-export-binding-node-local-name node)
8743 (js2-export-binding-node-extern-name node))
8744 (if import-p
8745 (js2-set-face (js2-current-token-beg) (js2-current-token-end)
8746 'font-lock-variable-name-face 'record))
8747 node)
8748 (js2-unget-token)
8749 nil))
8750 (let* ((name-node (make-js2-name-node
8751 :name (js2-current-token-string)
8752 :pos (js2-current-token-beg)
8753 :len (js2-current-token-len)))
8754 (node (make-js2-export-binding-node
8755 :pos (js2-current-token-beg)
8756 :len (js2-current-token-len)
8757 :local-name name-node
8758 :extern-name name-node)))
8759 (when is-reserved-name
8760 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8761 (js2-node-add-children node name-node)
8762 (if import-p
8763 (js2-set-face (js2-current-token-beg) (js2-current-token-end)
8764 'font-lock-variable-name-face 'record))
8765 node))
8766 nil)))
8767
8768 (defun js2-parse-switch ()
8769 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8770 (let ((pos (js2-current-token-beg))
8771 tt pn discriminant has-default case-expr case-node
8772 case-pos cases stmt lp)
8773 (if (js2-must-match js2-LP "msg.no.paren.switch")
8774 (setq lp (js2-current-token-beg)))
8775 (setq discriminant (js2-parse-expr)
8776 pn (make-js2-switch-node :discriminant discriminant
8777 :pos pos
8778 :lp (js2-relpos lp pos)))
8779 (js2-node-add-children pn discriminant)
8780 (js2-enter-switch pn)
8781 (unwind-protect
8782 (progn
8783 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8784 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8785 (js2-must-match js2-LC "msg.no.brace.switch")
8786 (catch 'break
8787 (while t
8788 (setq tt (js2-next-token)
8789 case-pos (js2-current-token-beg))
8790 (cond
8791 ((= tt js2-RC)
8792 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8793 (throw 'break nil)) ; done
8794 ((= tt js2-CASE)
8795 (setq case-expr (js2-parse-expr))
8796 (js2-must-match js2-COLON "msg.no.colon.case"))
8797 ((= tt js2-DEFAULT)
8798 (if has-default
8799 (js2-report-error "msg.double.switch.default"))
8800 (setq has-default t
8801 case-expr nil)
8802 (js2-must-match js2-COLON "msg.no.colon.case"))
8803 (t
8804 (js2-report-error "msg.bad.switch")
8805 (throw 'break nil)))
8806 (setq case-node (make-js2-case-node :pos case-pos
8807 :len (- (js2-current-token-end) case-pos)
8808 :expr case-expr))
8809 (js2-node-add-children case-node case-expr)
8810 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8811 (/= tt js2-CASE)
8812 (/= tt js2-DEFAULT)
8813 (/= tt js2-EOF))
8814 (setf stmt (js2-parse-statement)
8815 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8816 (js2-block-node-push case-node stmt))
8817 (push case-node cases)))
8818 ;; add cases last, as pushing reverses the order to be correct
8819 (dolist (kid cases)
8820 (js2-node-add-children pn kid)
8821 (push kid (js2-switch-node-cases pn)))
8822 pn) ; return value
8823 (js2-exit-switch))))
8824
8825 (defun js2-parse-while ()
8826 "Parser for while-statement. Last matched token must be js2-WHILE."
8827 (let ((pos (js2-current-token-beg))
8828 (pn (make-js2-while-node))
8829 cond body)
8830 (js2-enter-loop pn)
8831 (unwind-protect
8832 (progn
8833 (setf cond (js2-parse-condition)
8834 (js2-while-node-condition pn) (car cond)
8835 body (js2-parse-statement)
8836 (js2-while-node-body pn) body
8837 (js2-node-len pn) (- (js2-node-end body) pos)
8838 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8839 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8840 (js2-node-add-children pn body (car cond)))
8841 (js2-exit-loop))
8842 pn))
8843
8844 (defun js2-parse-do ()
8845 "Parser for do-statement. Last matched token must be js2-DO."
8846 (let ((pos (js2-current-token-beg))
8847 (pn (make-js2-do-node))
8848 cond body end)
8849 (js2-enter-loop pn)
8850 (unwind-protect
8851 (progn
8852 (setq body (js2-parse-statement))
8853 (js2-must-match js2-WHILE "msg.no.while.do")
8854 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8855 cond (js2-parse-condition)
8856 (js2-do-node-condition pn) (car cond)
8857 (js2-do-node-body pn) body
8858 end js2-ts-cursor
8859 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8860 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8861 (js2-node-add-children pn (car cond) body))
8862 (js2-exit-loop))
8863 ;; Always auto-insert semicolon to follow SpiderMonkey:
8864 ;; It is required by ECMAScript but is ignored by the rest of
8865 ;; world; see bug 238945
8866 (if (js2-match-token js2-SEMI)
8867 (setq end js2-ts-cursor))
8868 (setf (js2-node-len pn) (- end pos))
8869 pn))
8870
8871 (defun js2-parse-export ()
8872 "Parse an export statement.
8873 The Last matched token must be js2-EXPORT. Currently, the `default' and `expr'
8874 expressions should only be either hoistable expressions (function or generator)
8875 or assignment expressions, but there is no checking to enforce that and so it
8876 will parse without error a small subset of
8877 invalid export statements."
8878 (unless (js2-ast-root-p js2-current-scope)
8879 (js2-report-error "msg.mod.export.decl.at.top.level"))
8880 (let ((beg (js2-current-token-beg))
8881 (children (list))
8882 exports-list from-clause declaration default)
8883 (cond
8884 ((js2-match-token js2-MUL)
8885 (setq from-clause (js2-parse-from-clause))
8886 (when from-clause
8887 (push from-clause children)))
8888 ((js2-match-token js2-LC)
8889 (setq exports-list (js2-parse-export-bindings))
8890 (when exports-list
8891 (dolist (export exports-list)
8892 (push export children)))
8893 (when (js2-match-contextual-kwd "from")
8894 (js2-unget-token)
8895 (setq from-clause (js2-parse-from-clause))))
8896 ((js2-match-token js2-DEFAULT)
8897 (setq default (cond ((js2-match-token js2-CLASS)
8898 (js2-parse-class-stmt))
8899 ((js2-match-token js2-NAME)
8900 (if (js2-match-async-function)
8901 (js2-parse-async-function-stmt)
8902 (js2-unget-token)
8903 (js2-parse-expr)))
8904 ((js2-match-token js2-FUNCTION)
8905 (js2-parse-function-stmt))
8906 (t (js2-parse-expr)))))
8907 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8908 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8909 ((js2-match-token js2-CLASS)
8910 (setq declaration (js2-parse-class-stmt)))
8911 ((js2-match-token js2-NAME)
8912 (setq declaration
8913 (if (js2-match-async-function)
8914 (js2-parse-async-function-stmt)
8915 (js2-unget-token)
8916 (js2-parse-expr))))
8917 ((js2-match-token js2-FUNCTION)
8918 (setq declaration (js2-parse-function-stmt)))
8919 (t
8920 (setq declaration (js2-parse-expr))))
8921 (when from-clause
8922 (push from-clause children))
8923 (when declaration
8924 (push declaration children)
8925 (when (not (or (js2-function-node-p declaration)
8926 (js2-class-node-p declaration)))
8927 (js2-auto-insert-semicolon declaration)))
8928 (when default
8929 (push default children)
8930 (when (not (or (js2-function-node-p default)
8931 (js2-class-node-p default)))
8932 (js2-auto-insert-semicolon default)))
8933 (let ((node (make-js2-export-node
8934 :pos beg
8935 :len (- (js2-current-token-end) beg)
8936 :exports-list exports-list
8937 :from-clause from-clause
8938 :declaration declaration
8939 :default default)))
8940 (apply #'js2-node-add-children node children)
8941 node)))
8942
8943 (defun js2-parse-for ()
8944 "Parse a for, for-in or for each-in statement.
8945 Last matched token must be js2-FOR."
8946 (let ((for-pos (js2-current-token-beg))
8947 (tmp-scope (make-js2-scope))
8948 pn is-for-each is-for-in-or-of is-for-of
8949 in-pos each-pos tmp-pos
8950 init ; Node init is also foo in 'foo in object'.
8951 cond ; Node cond is also object in 'foo in object'.
8952 incr ; 3rd section of for-loop initializer.
8953 body tt lp rp)
8954 ;; See if this is a for each () instead of just a for ()
8955 (when (js2-match-token js2-NAME)
8956 (if (string= "each" (js2-current-token-string))
8957 (progn
8958 (setq is-for-each t
8959 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8960 (js2-record-face 'font-lock-keyword-face))
8961 (js2-report-error "msg.no.paren.for")))
8962 (if (js2-must-match js2-LP "msg.no.paren.for")
8963 (setq lp (- (js2-current-token-beg) for-pos)))
8964 (setq tt (js2-get-token))
8965 ;; Capture identifiers inside parens. We can't create the node
8966 ;; (and use it as the current scope) until we know its type.
8967 (js2-push-scope tmp-scope)
8968 (unwind-protect
8969 (progn
8970 ;; parse init clause
8971 (let ((js2-in-for-init t)) ; set as dynamic variable
8972 (cond
8973 ((= tt js2-SEMI)
8974 (js2-unget-token)
8975 (setq init (make-js2-empty-expr-node)))
8976 ((or (= tt js2-VAR) (= tt js2-LET) (= tt js2-CONST))
8977 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8978 (t
8979 (js2-unget-token)
8980 (setq init (js2-parse-expr)))))
8981 (if (or (js2-match-token js2-IN)
8982 (and (>= js2-language-version 200)
8983 (js2-match-contextual-kwd "of")
8984 (setq is-for-of t)))
8985 (setq is-for-in-or-of t
8986 in-pos (- (js2-current-token-beg) for-pos)
8987 ;; scope of iteration target object is not the scope we've created above.
8988 ;; stash current scope temporary.
8989 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8990 (js2-parse-expr))) ; object over which we're iterating
8991 ;; else ordinary for loop - parse cond and incr
8992 (js2-must-match js2-SEMI "msg.no.semi.for")
8993 (setq cond (if (= (js2-peek-token) js2-SEMI)
8994 (make-js2-empty-expr-node) ; no loop condition
8995 (js2-parse-expr)))
8996 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8997 (setq tmp-pos (js2-current-token-end)
8998 incr (if (= (js2-peek-token) js2-RP)
8999 (make-js2-empty-expr-node :pos tmp-pos)
9000 (js2-parse-expr)))))
9001 (js2-pop-scope))
9002 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9003 (setq rp (- (js2-current-token-beg) for-pos)))
9004 (if (not is-for-in-or-of)
9005 (setq pn (make-js2-for-node :init init
9006 :condition cond
9007 :update incr
9008 :lp lp
9009 :rp rp))
9010 ;; cond could be null if 'in obj' got eaten by the init node.
9011 (if (js2-infix-node-p init)
9012 ;; it was (foo in bar) instead of (var foo in bar)
9013 (setq cond (js2-infix-node-right init)
9014 init (js2-infix-node-left init))
9015 (if (and (js2-var-decl-node-p init)
9016 (> (length (js2-var-decl-node-kids init)) 1))
9017 (js2-report-error "msg.mult.index")))
9018 (setq pn (make-js2-for-in-node :iterator init
9019 :object cond
9020 :in-pos in-pos
9021 :foreach-p is-for-each
9022 :each-pos each-pos
9023 :forof-p is-for-of
9024 :lp lp
9025 :rp rp)))
9026 ;; Transplant the declarations.
9027 (setf (js2-scope-symbol-table pn)
9028 (js2-scope-symbol-table tmp-scope))
9029 (unwind-protect
9030 (progn
9031 (js2-enter-loop pn)
9032 ;; We have to parse the body -after- creating the loop node,
9033 ;; so that the loop node appears in the js2-loop-set, allowing
9034 ;; break/continue statements to find the enclosing loop.
9035 (setf body (js2-parse-statement)
9036 (js2-loop-node-body pn) body
9037 (js2-node-pos pn) for-pos
9038 (js2-node-len pn) (- (js2-node-end body) for-pos))
9039 (js2-node-add-children pn init cond incr body))
9040 ;; finally
9041 (js2-exit-loop))
9042 pn))
9043
9044 (defun js2-parse-try ()
9045 "Parse a try statement. Last matched token must be js2-TRY."
9046 (let ((try-pos (js2-current-token-beg))
9047 try-end
9048 try-block
9049 catch-blocks
9050 finally-block
9051 saw-default-catch
9052 peek)
9053 (if (/= (js2-peek-token) js2-LC)
9054 (js2-report-error "msg.no.brace.try"))
9055 (setq try-block (js2-parse-statement)
9056 try-end (js2-node-end try-block)
9057 peek (js2-peek-token))
9058 (cond
9059 ((= peek js2-CATCH)
9060 (while (js2-match-token js2-CATCH)
9061 (let* ((catch-pos (js2-current-token-beg))
9062 (catch-node (make-js2-catch-node :pos catch-pos))
9063 param
9064 guard-kwd
9065 catch-cond
9066 lp rp)
9067 (if saw-default-catch
9068 (js2-report-error "msg.catch.unreachable"))
9069 (if (js2-must-match js2-LP "msg.no.paren.catch")
9070 (setq lp (- (js2-current-token-beg) catch-pos)))
9071 (js2-push-scope catch-node)
9072 (let ((tt (js2-peek-token)))
9073 (cond
9074 ;; Destructuring pattern:
9075 ;; catch ({ message, file }) { ... }
9076 ((or (= tt js2-LB) (= tt js2-LC))
9077 (js2-get-token)
9078 (setq param (js2-parse-destruct-primary-expr))
9079 (js2-define-destruct-symbols param js2-LET nil))
9080 ;; Simple name.
9081 (t
9082 (js2-must-match-name "msg.bad.catchcond")
9083 (setq param (js2-create-name-node))
9084 (js2-define-symbol js2-LET (js2-current-token-string) param)
9085 (js2-check-strict-identifier param))))
9086 ;; Catch condition.
9087 (if (js2-match-token js2-IF)
9088 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9089 catch-cond (js2-parse-expr))
9090 (setq saw-default-catch t))
9091 (if (js2-must-match js2-RP "msg.bad.catchcond")
9092 (setq rp (- (js2-current-token-beg) catch-pos)))
9093 (js2-must-match js2-LC "msg.no.brace.catchblock")
9094 (js2-parse-statements catch-node)
9095 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9096 (setq try-end (js2-current-token-end)))
9097 (js2-pop-scope)
9098 (setf (js2-node-len catch-node) (- try-end catch-pos)
9099 (js2-catch-node-param catch-node) param
9100 (js2-catch-node-guard-expr catch-node) catch-cond
9101 (js2-catch-node-guard-kwd catch-node) guard-kwd
9102 (js2-catch-node-lp catch-node) lp
9103 (js2-catch-node-rp catch-node) rp)
9104 (js2-node-add-children catch-node param catch-cond)
9105 (push catch-node catch-blocks))))
9106 ((/= peek js2-FINALLY)
9107 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9108 (js2-node-pos try-block)
9109 (- (setq try-end (js2-node-end try-block))
9110 (js2-node-pos try-block)))))
9111 (when (js2-match-token js2-FINALLY)
9112 (let ((finally-pos (js2-current-token-beg))
9113 (block (js2-parse-statement)))
9114 (setq try-end (js2-node-end block)
9115 finally-block (make-js2-finally-node :pos finally-pos
9116 :len (- try-end finally-pos)
9117 :body block))
9118 (js2-node-add-children finally-block block)))
9119 (let ((pn (make-js2-try-node :pos try-pos
9120 :len (- try-end try-pos)
9121 :try-block try-block
9122 :finally-block finally-block)))
9123 (js2-node-add-children pn try-block finally-block)
9124 ;; Push them onto the try-node, which reverses and corrects their order.
9125 (dolist (cb catch-blocks)
9126 (js2-node-add-children pn cb)
9127 (push cb (js2-try-node-catch-clauses pn)))
9128 pn)))
9129
9130 (defun js2-parse-throw ()
9131 "Parser for throw-statement. Last matched token must be js2-THROW."
9132 (let ((pos (js2-current-token-beg))
9133 expr pn)
9134 (if (= (js2-peek-token-or-eol) js2-EOL)
9135 ;; ECMAScript does not allow new lines before throw expression,
9136 ;; see bug 256617
9137 (js2-report-error "msg.bad.throw.eol"))
9138 (setq expr (js2-parse-expr)
9139 pn (make-js2-throw-node :pos pos
9140 :len (- (js2-node-end expr) pos)
9141 :expr expr))
9142 (js2-node-add-children pn expr)
9143 pn))
9144
9145 (defun js2-match-jump-label-name (label-name)
9146 "If break/continue specified a label, return that label's labeled stmt.
9147 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9148 does not match an existing label, reports an error and returns nil."
9149 (let ((bundle (cdr (assoc label-name js2-label-set))))
9150 (if (null bundle)
9151 (js2-report-error "msg.undef.label"))
9152 bundle))
9153
9154 (defun js2-parse-break ()
9155 "Parser for break-statement. Last matched token must be js2-BREAK."
9156 (let ((pos (js2-current-token-beg))
9157 (end (js2-current-token-end))
9158 break-target ; statement to break from
9159 break-label ; in "break foo", name-node representing the foo
9160 labels ; matching labeled statement to break to
9161 pn)
9162 (when (eq (js2-peek-token-or-eol) js2-NAME)
9163 (js2-get-token)
9164 (setq break-label (js2-create-name-node)
9165 end (js2-node-end break-label)
9166 ;; matchJumpLabelName only matches if there is one
9167 labels (js2-match-jump-label-name (js2-current-token-string))
9168 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9169 (unless (or break-target break-label)
9170 ;; no break target specified - try for innermost enclosing loop/switch
9171 (if (null js2-loop-and-switch-set)
9172 (unless break-label
9173 (js2-report-error "msg.bad.break" nil pos (length "break")))
9174 (setq break-target (car js2-loop-and-switch-set))))
9175 (setq pn (make-js2-break-node :pos pos
9176 :len (- end pos)
9177 :label break-label
9178 :target break-target))
9179 (js2-node-add-children pn break-label) ; but not break-target
9180 pn))
9181
9182 (defun js2-parse-continue ()
9183 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9184 (let ((pos (js2-current-token-beg))
9185 (end (js2-current-token-end))
9186 label ; optional user-specified label, a `js2-name-node'
9187 labels ; current matching labeled stmt, if any
9188 target ; the `js2-loop-node' target of this continue stmt
9189 pn)
9190 (when (= (js2-peek-token-or-eol) js2-NAME)
9191 (js2-get-token)
9192 (setq label (js2-create-name-node)
9193 end (js2-node-end label)
9194 ;; matchJumpLabelName only matches if there is one
9195 labels (js2-match-jump-label-name (js2-current-token-string))))
9196 (cond
9197 ((null labels) ; no current label to go to
9198 (if (null js2-loop-set) ; no loop to continue to
9199 (js2-report-error "msg.continue.outside" nil pos
9200 (length "continue"))
9201 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9202 (t
9203 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9204 (setq target (js2-labeled-stmt-node-stmt labels))
9205 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9206 (setq pn (make-js2-continue-node :pos pos
9207 :len (- end pos)
9208 :label label
9209 :target target))
9210 (js2-node-add-children pn label) ; but not target - it's not our child
9211 pn))
9212
9213 (defun js2-parse-with ()
9214 "Parser for with-statement. Last matched token must be js2-WITH."
9215 (when js2-in-use-strict-directive
9216 (js2-report-error "msg.no.with.strict"))
9217 (let ((pos (js2-current-token-beg))
9218 obj body pn lp rp)
9219 (if (js2-must-match js2-LP "msg.no.paren.with")
9220 (setq lp (js2-current-token-beg)))
9221 (setq obj (js2-parse-expr))
9222 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9223 (setq rp (js2-current-token-beg)))
9224 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9225 (setq body (js2-parse-statement)))
9226 (setq pn (make-js2-with-node :pos pos
9227 :len (- (js2-node-end body) pos)
9228 :object obj
9229 :body body
9230 :lp (js2-relpos lp pos)
9231 :rp (js2-relpos rp pos)))
9232 (js2-node-add-children pn obj body)
9233 pn))
9234
9235 (defun js2-parse-const-var ()
9236 "Parser for var- or const-statement.
9237 Last matched token must be js2-CONST or js2-VAR."
9238 (let ((tt (js2-current-token-type))
9239 (pos (js2-current-token-beg))
9240 expr pn)
9241 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9242 pn (make-js2-expr-stmt-node :pos pos
9243 :len (- (js2-node-end expr) pos)
9244 :expr expr))
9245 (js2-node-add-children pn expr)
9246 pn))
9247
9248 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9249 (let ((pn (make-js2-expr-stmt-node :pos pos
9250 :len (js2-node-len expr)
9251 :type (if (js2-inside-function)
9252 js2-EXPR_VOID
9253 js2-EXPR_RESULT)
9254 :expr expr)))
9255 (if add-child
9256 (js2-node-add-children pn expr))
9257 pn))
9258
9259 (defun js2-parse-let-stmt ()
9260 "Parser for let-statement. Last matched token must be js2-LET."
9261 (let ((pos (js2-current-token-beg))
9262 expr pn)
9263 (if (= (js2-peek-token) js2-LP)
9264 ;; let expression in statement context
9265 (setq expr (js2-parse-let pos 'statement)
9266 pn (js2-wrap-with-expr-stmt pos expr t))
9267 ;; else we're looking at a statement like let x=6, y=7;
9268 (setf expr (js2-parse-variables js2-LET pos)
9269 pn (js2-wrap-with-expr-stmt pos expr t)
9270 (js2-node-type pn) js2-EXPR_RESULT))
9271 pn))
9272
9273 (defun js2-parse-ret-yield ()
9274 (js2-parse-return-or-yield (js2-current-token-type) nil))
9275
9276 (defconst js2-parse-return-stmt-enders
9277 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9278
9279 (defsubst js2-now-all-set (before after mask)
9280 "Return whether or not the bits in the mask have changed to all set.
9281 BEFORE is bits before change, AFTER is bits after change, and MASK is
9282 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9283 but not BEFORE."
9284 (and (/= (logand before mask) mask)
9285 (= (logand after mask) mask)))
9286
9287 (defun js2-parse-return-or-yield (tt expr-context)
9288 (let* ((pos (js2-current-token-beg))
9289 (end (js2-current-token-end))
9290 (before js2-end-flags)
9291 (inside-function (js2-inside-function))
9292 (gen-type (and inside-function (js2-function-node-generator-type
9293 js2-current-script-or-fn)))
9294 e ret name yield-star-p)
9295 (unless inside-function
9296 (js2-report-error (if (eq tt js2-RETURN)
9297 "msg.bad.return"
9298 "msg.bad.yield")))
9299 (when (and inside-function
9300 (eq gen-type 'STAR)
9301 (js2-match-token js2-MUL))
9302 (setq yield-star-p t))
9303 ;; This is ugly, but we don't want to require a semicolon.
9304 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9305 (setq e (js2-parse-expr)
9306 end (js2-node-end e)))
9307 (cond
9308 ((eq tt js2-RETURN)
9309 (js2-set-flag js2-end-flags (if (null e)
9310 js2-end-returns
9311 js2-end-returns-value))
9312 (setq ret (make-js2-return-node :pos pos
9313 :len (- end pos)
9314 :retval e))
9315 (js2-node-add-children ret e)
9316 ;; See if we need a strict mode warning.
9317 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9318 ;; more thorough and accurate than this before/after flag check.
9319 ;; E.g. if there's a finally-block that always returns, we shouldn't
9320 ;; show a warning generated by inconsistent returns in the catch blocks.
9321 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9322 ;; so we know which returns/yields to highlight, and we should get rid of
9323 ;; all the checking in `js2-parse-return-or-yield'.
9324 (if (and js2-strict-inconsistent-return-warning
9325 (js2-now-all-set before js2-end-flags
9326 (logior js2-end-returns js2-end-returns-value)))
9327 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9328 ((eq gen-type 'COMPREHENSION)
9329 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9330 ;; like SpiderMonkey does.
9331 (js2-report-error "msg.syntax" nil pos 5))
9332 (t
9333 (setq ret (make-js2-yield-node :pos pos
9334 :len (- end pos)
9335 :value e
9336 :star-p yield-star-p))
9337 (js2-node-add-children ret e)
9338 (unless expr-context
9339 (setq e ret
9340 ret (js2-wrap-with-expr-stmt pos e t))
9341 (js2-set-requires-activation)
9342 (js2-set-is-generator))))
9343 ;; see if we are mixing yields and value returns.
9344 (when (and inside-function
9345 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9346 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9347 'LEGACY))
9348 (setq name (js2-function-name js2-current-script-or-fn))
9349 (if (zerop (length name))
9350 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9351 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9352 ret))
9353
9354 (defun js2-parse-debugger ()
9355 (make-js2-keyword-node :type js2-DEBUGGER))
9356
9357 (defun js2-parse-block ()
9358 "Parser for a curly-delimited statement block.
9359 Last token matched must be `js2-LC'."
9360 (let ((pos (js2-current-token-beg))
9361 (pn (make-js2-scope)))
9362 (js2-push-scope pn)
9363 (unwind-protect
9364 (progn
9365 (js2-parse-statements pn)
9366 (js2-must-match js2-RC "msg.no.brace.block")
9367 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9368 (js2-pop-scope))
9369 pn))
9370
9371 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9372 (defun js2-parse-semi ()
9373 "Parse a statement or handle an error.
9374 Current token type is `js2-SEMI' or `js2-ERROR'."
9375 (let ((tt (js2-current-token-type)) pos len)
9376 (if (eq tt js2-SEMI)
9377 (make-js2-empty-expr-node :len 1)
9378 (setq pos (js2-current-token-beg)
9379 len (- (js2-current-token-end) pos))
9380 (js2-report-error "msg.syntax" nil pos len)
9381 (make-js2-error-node :pos pos :len len))))
9382
9383 (defun js2-parse-default-xml-namespace ()
9384 "Parse a `default xml namespace = <expr>' e4x statement."
9385 (let ((pos (js2-current-token-beg))
9386 end len expr unary)
9387 (js2-must-have-xml)
9388 (js2-set-requires-activation)
9389 (setq len (- js2-ts-cursor pos))
9390 (unless (and (js2-match-token js2-NAME)
9391 (string= (js2-current-token-string) "xml"))
9392 (js2-report-error "msg.bad.namespace" nil pos len))
9393 (unless (and (js2-match-token js2-NAME)
9394 (string= (js2-current-token-string) "namespace"))
9395 (js2-report-error "msg.bad.namespace" nil pos len))
9396 (unless (js2-match-token js2-ASSIGN)
9397 (js2-report-error "msg.bad.namespace" nil pos len))
9398 (setq expr (js2-parse-expr)
9399 end (js2-node-end expr)
9400 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9401 :pos pos
9402 :len (- end pos)
9403 :operand expr))
9404 (js2-node-add-children unary expr)
9405 (make-js2-expr-stmt-node :pos pos
9406 :len (- end pos)
9407 :expr unary)))
9408
9409 (defun js2-record-label (label bundle)
9410 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9411 (js2-get-token)
9412 (let ((name (js2-label-node-name label))
9413 labeled-stmt
9414 dup)
9415 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9416 ;; flag both labels if possible when used in editing mode
9417 (if (and js2-parse-ide-mode
9418 (setq dup (js2-get-label-by-name labeled-stmt name)))
9419 (js2-report-error "msg.dup.label" nil
9420 (js2-node-abs-pos dup) (js2-node-len dup)))
9421 (js2-report-error "msg.dup.label" nil
9422 (js2-node-pos label) (js2-node-len label)))
9423 (js2-labeled-stmt-node-add-label bundle label)
9424 (js2-node-add-children bundle label)
9425 ;; Add one reference to the bundle per label in `js2-label-set'
9426 (push (cons name bundle) js2-label-set)))
9427
9428 (defun js2-parse-name-or-label ()
9429 "Parser for identifier or label. Last token matched must be js2-NAME.
9430 Called when we found a name in a statement context. If it's a label, we gather
9431 up any following labels and the next non-label statement into a
9432 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9433 expression and return it wrapped in a `js2-expr-stmt-node'."
9434 (let ((pos (js2-current-token-beg))
9435 expr stmt bundle
9436 (continue t))
9437 ;; set check for label and call down to `js2-parse-primary-expr'
9438 (setq expr (js2-maybe-parse-label))
9439 (if (null expr)
9440 ;; Parse the non-label expression and wrap with expression stmt.
9441 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9442 ;; else parsed a label
9443 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9444 (js2-record-label expr bundle)
9445 ;; look for more labels
9446 (while (and continue (= (js2-get-token) js2-NAME))
9447 (if (setq expr (js2-maybe-parse-label))
9448 (js2-record-label expr bundle)
9449 (setq expr (js2-parse-expr)
9450 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9451 continue nil)
9452 (js2-auto-insert-semicolon stmt)))
9453 ;; no more labels; now parse the labeled statement
9454 (unwind-protect
9455 (unless stmt
9456 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9457 (js2-unget-token)
9458 (setq stmt (js2-statement-helper))))
9459 ;; remove the labels for this statement from the global set
9460 (dolist (label (js2-labeled-stmt-node-labels bundle))
9461 (setq js2-label-set (remove label js2-label-set))))
9462 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9463 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9464 (js2-node-add-children bundle stmt)
9465 bundle)))
9466
9467 (defun js2-maybe-parse-label ()
9468 (cl-assert (= (js2-current-token-type) js2-NAME))
9469 (let (label-pos
9470 (next-tt (js2-get-token))
9471 (label-end (js2-current-token-end)))
9472 ;; Do not consume colon, it is used as unwind indicator
9473 ;; to return to statementHelper.
9474 (js2-unget-token)
9475 (if (= next-tt js2-COLON)
9476 (prog2
9477 (setq label-pos (js2-current-token-beg))
9478 (make-js2-label-node :pos label-pos
9479 :len (- label-end label-pos)
9480 :name (js2-current-token-string))
9481 (js2-set-face label-pos
9482 label-end
9483 'font-lock-variable-name-face 'record))
9484 ;; Backtrack from the name token, too.
9485 (js2-unget-token)
9486 nil)))
9487
9488 (defun js2-parse-expr-stmt ()
9489 "Default parser in statement context, if no recognized statement found."
9490 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9491 (progn
9492 (js2-unget-token)
9493 (js2-parse-expr)) t))
9494
9495 (defun js2-parse-variables (decl-type pos)
9496 "Parse a comma-separated list of variable declarations.
9497 Could be a `var', `const' or `let' expression, possibly in a for-loop initializer.
9498
9499 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9500 For `var' or `const', the keyword should be the token last scanned.
9501
9502 POS is the position where the node should start. It's sometimes the
9503 var/const/let keyword, and other times the beginning of the first token
9504 in the first variable declaration.
9505
9506 Returns the parsed `js2-var-decl-node' expression node."
9507 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9508 :pos pos))
9509 destructuring kid-pos tt init name end nbeg nend vi
9510 (continue t))
9511 ;; Example:
9512 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9513 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9514 ;; var {a, b} = baz;
9515 (while continue
9516 (setq destructuring nil
9517 name nil
9518 tt (js2-get-token)
9519 kid-pos (js2-current-token-beg)
9520 end (js2-current-token-end)
9521 init nil)
9522 (if (or (= tt js2-LB) (= tt js2-LC))
9523 ;; Destructuring assignment, e.g., var [a, b] = ...
9524 (setq destructuring (js2-parse-destruct-primary-expr)
9525 end (js2-node-end destructuring))
9526 ;; Simple variable name
9527 (js2-unget-token)
9528 (when (js2-must-match-name "msg.bad.var")
9529 (setq name (js2-create-name-node)
9530 nbeg (js2-current-token-beg)
9531 nend (js2-current-token-end)
9532 end nend)
9533 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9534 (js2-check-strict-identifier name)))
9535 (when (js2-match-token js2-ASSIGN)
9536 (setq init (js2-parse-assign-expr)
9537 end (js2-node-end init))
9538 (js2-record-imenu-functions init name))
9539 (when name
9540 (js2-set-face nbeg nend (if (js2-function-node-p init)
9541 'font-lock-function-name-face
9542 'font-lock-variable-name-face)
9543 'record))
9544 (setq vi (make-js2-var-init-node :pos kid-pos
9545 :len (- end kid-pos)
9546 :type decl-type))
9547 (if destructuring
9548 (progn
9549 (if (and (null init) (not js2-in-for-init))
9550 (js2-report-error "msg.destruct.assign.no.init"))
9551 (js2-define-destruct-symbols destructuring
9552 decl-type
9553 'font-lock-variable-name-face)
9554 (setf (js2-var-init-node-target vi) destructuring))
9555 (setf (js2-var-init-node-target vi) name))
9556 (setf (js2-var-init-node-initializer vi) init)
9557 (js2-node-add-children vi name destructuring init)
9558 (js2-block-node-push result vi)
9559 (unless (js2-match-token js2-COMMA)
9560 (setq continue nil)))
9561 (setf (js2-node-len result) (- end pos))
9562 result))
9563
9564 (defun js2-parse-let (pos &optional stmt-p)
9565 "Parse a let expression or statement.
9566 A let-expression is of the form `let (vars) expr'.
9567 A let-statement is of the form `let (vars) {statements}'.
9568 The third form of let is a variable declaration list, handled
9569 by `js2-parse-variables'."
9570 (let ((pn (make-js2-let-node :pos pos))
9571 beg vars body)
9572 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9573 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9574 (js2-push-scope pn)
9575 (unwind-protect
9576 (progn
9577 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9578 (if (js2-must-match js2-RP "msg.no.paren.let")
9579 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9580 (if (and stmt-p (js2-match-token js2-LC))
9581 ;; let statement
9582 (progn
9583 (setf beg (js2-current-token-beg) ; position stmt at LC
9584 body (js2-parse-statements))
9585 (js2-must-match js2-RC "msg.no.curly.let")
9586 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9587 (js2-node-len pn) (- (js2-current-token-end) pos)
9588 (js2-let-node-body pn) body
9589 (js2-node-type pn) js2-LET))
9590 ;; let expression
9591 (setf body (js2-parse-expr)
9592 (js2-node-len pn) (- (js2-node-end body) pos)
9593 (js2-let-node-body pn) body))
9594 (setf (js2-let-node-vars pn) vars)
9595 (js2-node-add-children pn vars body))
9596 (js2-pop-scope))
9597 pn))
9598
9599 (defun js2-define-new-symbol (decl-type name node &optional scope)
9600 (js2-scope-put-symbol (or scope js2-current-scope)
9601 name
9602 (make-js2-symbol decl-type name node)))
9603
9604 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9605 "Define a symbol in the current scope.
9606 If NODE is non-nil, it is the AST node associated with the symbol."
9607 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9608 (symbol (if defining-scope
9609 (js2-scope-get-symbol defining-scope name)))
9610 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9611 (pos (if node (js2-node-abs-pos node)))
9612 (len (if node (js2-node-len node))))
9613 (cond
9614 ((and symbol ; already defined in this block
9615 (or (= sdt js2-LET)
9616 (= sdt js2-CONST))
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 (= decl-type js2-CONST))
9628 (if (and (= decl-type js2-LET)
9629 (not ignore-not-in-block)
9630 (or (= (js2-node-type js2-current-scope) js2-IF)
9631 (js2-loop-node-p js2-current-scope)))
9632 (js2-report-error "msg.let.decl.not.in.block")
9633 (js2-define-new-symbol decl-type name node)))
9634 ((or (= decl-type js2-VAR)
9635 (= decl-type js2-FUNCTION))
9636 (if symbol
9637 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9638 (js2-add-strict-warning "msg.var.redecl" name)
9639 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9640 (js2-add-strict-warning "msg.var.hides.arg" name)))
9641 (js2-define-new-symbol decl-type name node
9642 js2-current-script-or-fn)))
9643 ((= decl-type js2-LP)
9644 (if symbol
9645 ;; must be duplicate parameter. Second parameter hides the
9646 ;; first, so go ahead and add the second pararameter
9647 (js2-report-warning "msg.dup.parms" name))
9648 (js2-define-new-symbol decl-type name node))
9649 (t (js2-code-bug)))))
9650
9651 (defun js2-parse-paren-expr-or-generator-comp ()
9652 (let ((px-pos (js2-current-token-beg)))
9653 (cond
9654 ((and (>= js2-language-version 200)
9655 (js2-match-token js2-FOR))
9656 (js2-parse-generator-comp px-pos))
9657 ((and (>= js2-language-version 200)
9658 (js2-match-token js2-RP))
9659 ;; Not valid expression syntax, but this is valid in an arrow
9660 ;; function with no params: () => body.
9661 (if (eq (js2-peek-token) js2-ARROW)
9662 ;; Return whatever, it will hopefully be rewinded and
9663 ;; reparsed when we reach the =>.
9664 (make-js2-keyword-node :type js2-NULL)
9665 (js2-report-error "msg.syntax")
9666 (make-js2-error-node)))
9667 (t
9668 (let* ((js2-in-for-init nil)
9669 (expr (js2-parse-expr))
9670 (pn (make-js2-paren-node :pos px-pos
9671 :expr expr)))
9672 (js2-node-add-children pn (js2-paren-node-expr pn))
9673 (js2-must-match js2-RP "msg.no.paren")
9674 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9675 pn)))))
9676
9677 (defun js2-parse-expr (&optional oneshot)
9678 (let* ((pn (js2-parse-assign-expr))
9679 (pos (js2-node-pos pn))
9680 left
9681 right
9682 op-pos)
9683 (while (and (not oneshot)
9684 (js2-match-token js2-COMMA))
9685 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9686 (if (= (js2-peek-token) js2-YIELD)
9687 (js2-report-error "msg.yield.parenthesized"))
9688 (setq right (js2-parse-assign-expr)
9689 left pn
9690 pn (make-js2-infix-node :type js2-COMMA
9691 :pos pos
9692 :len (- js2-ts-cursor pos)
9693 :op-pos op-pos
9694 :left left
9695 :right right))
9696 (js2-node-add-children pn left right))
9697 pn))
9698
9699 (defun js2-parse-assign-expr ()
9700 (let ((tt (js2-get-token))
9701 (pos (js2-current-token-beg))
9702 pn left right op-pos
9703 ts-state recorded-identifiers parsed-errors
9704 async-p)
9705 (if (= tt js2-YIELD)
9706 (js2-parse-return-or-yield tt t)
9707 ;; TODO(mooz): Bit confusing.
9708 ;; If we meet `async` token and it's not part of `async
9709 ;; function`, then this `async` is for a succeeding async arrow
9710 ;; function.
9711 ;; Since arrow function parsing doesn't rely on neither
9712 ;; `js2-parse-function-stmt' nor `js2-parse-function-expr' that
9713 ;; interpret `async` token, we trash `async` and just remember
9714 ;; we met `async` keyword to `async-p'.
9715 (when (js2-match-async-arrow-function)
9716 (setq async-p t))
9717 ;; Save the tokenizer state in case we find an arrow function
9718 ;; and have to rewind.
9719 (setq ts-state (make-js2-ts-state)
9720 recorded-identifiers js2-recorded-identifiers
9721 parsed-errors js2-parsed-errors)
9722 ;; not yield - parse assignment expression
9723 (setq pn (js2-parse-cond-expr)
9724 tt (js2-get-token))
9725 (cond
9726 ((and (<= js2-first-assign tt)
9727 (<= tt js2-last-assign))
9728 ;; tt express assignment (=, |=, ^=, ..., %=)
9729 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9730 left pn)
9731 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9732 ;; care about assignment to strict variable names.
9733 (when (js2-name-node-p left)
9734 (js2-check-strict-identifier left))
9735 (setq right (js2-parse-assign-expr)
9736 pn (make-js2-assign-node :type tt
9737 :pos pos
9738 :len (- (js2-node-end right) pos)
9739 :op-pos op-pos
9740 :left left
9741 :right right))
9742 (when js2-parse-ide-mode
9743 (js2-highlight-assign-targets pn left right)
9744 (js2-record-imenu-functions right left))
9745 ;; do this last so ide checks above can use absolute positions
9746 (js2-node-add-children pn left right))
9747 ((and (= tt js2-ARROW)
9748 (>= js2-language-version 200))
9749 (js2-ts-seek ts-state)
9750 (when async-p
9751 (js2-record-face 'font-lock-keyword-face)
9752 (js2-get-token))
9753 (setq js2-recorded-identifiers recorded-identifiers
9754 js2-parsed-errors parsed-errors)
9755 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil async-p)))
9756 (t
9757 (js2-unget-token)))
9758 pn)))
9759
9760 (defun js2-parse-cond-expr ()
9761 (let ((pos (js2-current-token-beg))
9762 (pn (js2-parse-or-expr))
9763 test-expr
9764 if-true
9765 if-false
9766 q-pos
9767 c-pos)
9768 (when (js2-match-token js2-HOOK)
9769 (setq q-pos (- (js2-current-token-beg) pos)
9770 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9771 (js2-must-match js2-COLON "msg.no.colon.cond")
9772 (setq c-pos (- (js2-current-token-beg) pos)
9773 if-false (js2-parse-assign-expr)
9774 test-expr pn
9775 pn (make-js2-cond-node :pos pos
9776 :len (- (js2-node-end if-false) pos)
9777 :test-expr test-expr
9778 :true-expr if-true
9779 :false-expr if-false
9780 :q-pos q-pos
9781 :c-pos c-pos))
9782 (js2-node-add-children pn test-expr if-true if-false))
9783 pn))
9784
9785 (defun js2-make-binary (type left parser &optional no-get)
9786 "Helper for constructing a binary-operator AST node.
9787 LEFT is the left-side-expression, already parsed, and the
9788 binary operator should have just been matched.
9789 PARSER is a function to call to parse the right operand,
9790 or a `js2-node' struct if it has already been parsed.
9791 FIXME: The latter option is unused?"
9792 (let* ((pos (js2-node-pos left))
9793 (op-pos (- (js2-current-token-beg) pos))
9794 (right (if (js2-node-p parser)
9795 parser
9796 (unless no-get (js2-get-token))
9797 (funcall parser)))
9798 (pn (make-js2-infix-node :type type
9799 :pos pos
9800 :len (- (js2-node-end right) pos)
9801 :op-pos op-pos
9802 :left left
9803 :right right)))
9804 (js2-node-add-children pn left right)
9805 pn))
9806
9807 (defun js2-parse-or-expr ()
9808 (let ((pn (js2-parse-and-expr)))
9809 (when (js2-match-token js2-OR)
9810 (setq pn (js2-make-binary js2-OR
9811 pn
9812 'js2-parse-or-expr)))
9813 pn))
9814
9815 (defun js2-parse-and-expr ()
9816 (let ((pn (js2-parse-bit-or-expr)))
9817 (when (js2-match-token js2-AND)
9818 (setq pn (js2-make-binary js2-AND
9819 pn
9820 'js2-parse-and-expr)))
9821 pn))
9822
9823 (defun js2-parse-bit-or-expr ()
9824 (let ((pn (js2-parse-bit-xor-expr)))
9825 (while (js2-match-token js2-BITOR)
9826 (setq pn (js2-make-binary js2-BITOR
9827 pn
9828 'js2-parse-bit-xor-expr)))
9829 pn))
9830
9831 (defun js2-parse-bit-xor-expr ()
9832 (let ((pn (js2-parse-bit-and-expr)))
9833 (while (js2-match-token js2-BITXOR)
9834 (setq pn (js2-make-binary js2-BITXOR
9835 pn
9836 'js2-parse-bit-and-expr)))
9837 pn))
9838
9839 (defun js2-parse-bit-and-expr ()
9840 (let ((pn (js2-parse-eq-expr)))
9841 (while (js2-match-token js2-BITAND)
9842 (setq pn (js2-make-binary js2-BITAND
9843 pn
9844 'js2-parse-eq-expr)))
9845 pn))
9846
9847 (defconst js2-parse-eq-ops
9848 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9849
9850 (defun js2-parse-eq-expr ()
9851 (let ((pn (js2-parse-rel-expr))
9852 tt)
9853 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9854 (setq pn (js2-make-binary tt
9855 pn
9856 'js2-parse-rel-expr)))
9857 (js2-unget-token)
9858 pn))
9859
9860 (defconst js2-parse-rel-ops
9861 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9862
9863 (defun js2-parse-rel-expr ()
9864 (let ((pn (js2-parse-shift-expr))
9865 (continue t)
9866 tt)
9867 (while continue
9868 (setq tt (js2-get-token))
9869 (cond
9870 ((and js2-in-for-init (= tt js2-IN))
9871 (js2-unget-token)
9872 (setq continue nil))
9873 ((memq tt js2-parse-rel-ops)
9874 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9875 (t
9876 (js2-unget-token)
9877 (setq continue nil))))
9878 pn))
9879
9880 (defconst js2-parse-shift-ops
9881 (list js2-LSH js2-URSH js2-RSH))
9882
9883 (defun js2-parse-shift-expr ()
9884 (let ((pn (js2-parse-add-expr))
9885 tt
9886 (continue t))
9887 (while continue
9888 (setq tt (js2-get-token))
9889 (if (memq tt js2-parse-shift-ops)
9890 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9891 (js2-unget-token)
9892 (setq continue nil)))
9893 pn))
9894
9895 (defun js2-parse-add-expr ()
9896 (let ((pn (js2-parse-mul-expr))
9897 tt
9898 (continue t))
9899 (while continue
9900 (setq tt (js2-get-token))
9901 (if (or (= tt js2-ADD) (= tt js2-SUB))
9902 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9903 (js2-unget-token)
9904 (setq continue nil)))
9905 pn))
9906
9907 (defconst js2-parse-mul-ops
9908 (list js2-MUL js2-DIV js2-MOD))
9909
9910 (defun js2-parse-mul-expr ()
9911 (let ((pn (js2-parse-unary-expr))
9912 tt
9913 (continue t))
9914 (while continue
9915 (setq tt (js2-get-token))
9916 (if (memq tt js2-parse-mul-ops)
9917 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9918 (js2-unget-token)
9919 (setq continue nil)))
9920 pn))
9921
9922 (defun js2-make-unary (type parser &rest args)
9923 "Make a unary node of type TYPE.
9924 PARSER is either a node (for postfix operators) or a function to call
9925 to parse the operand (for prefix operators)."
9926 (let* ((pos (js2-current-token-beg))
9927 (postfix (js2-node-p parser))
9928 (expr (if postfix
9929 parser
9930 (apply parser args)))
9931 end
9932 pn)
9933 (if postfix ; e.g. i++
9934 (setq pos (js2-node-pos expr)
9935 end (js2-current-token-end))
9936 (setq end (js2-node-end expr)))
9937 (setq pn (make-js2-unary-node :type type
9938 :pos pos
9939 :len (- end pos)
9940 :operand expr))
9941 (js2-node-add-children pn expr)
9942 pn))
9943
9944 (defconst js2-incrementable-node-types
9945 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9946 "Node types that can be the operand of a ++ or -- operator.")
9947
9948 (defun js2-check-bad-inc-dec (tt beg end unary)
9949 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9950 js2-incrementable-node-types)
9951 (js2-report-error (if (= tt js2-INC)
9952 "msg.bad.incr"
9953 "msg.bad.decr")
9954 nil beg (- end beg))))
9955
9956 (defun js2-parse-unary-expr ()
9957 (let ((tt (js2-current-token-type))
9958 pn expr beg end)
9959 (cond
9960 ((or (= tt js2-VOID)
9961 (= tt js2-NOT)
9962 (= tt js2-BITNOT)
9963 (= tt js2-TYPEOF))
9964 (js2-get-token)
9965 (js2-make-unary tt 'js2-parse-unary-expr))
9966 ((= tt js2-ADD)
9967 (js2-get-token)
9968 ;; Convert to special POS token in decompiler and parse tree
9969 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9970 ((= tt js2-SUB)
9971 (js2-get-token)
9972 ;; Convert to special NEG token in decompiler and parse tree
9973 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9974 ((or (= tt js2-INC)
9975 (= tt js2-DEC))
9976 (js2-get-token)
9977 (prog1
9978 (setq beg (js2-current-token-beg)
9979 end (js2-current-token-end)
9980 expr (js2-make-unary tt 'js2-parse-member-expr t))
9981 (js2-check-bad-inc-dec tt beg end expr)))
9982 ((= tt js2-DELPROP)
9983 (js2-get-token)
9984 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9985 ((js2-parse-await-maybe tt))
9986 ((= tt js2-ERROR)
9987 (js2-get-token)
9988 (make-js2-error-node)) ; try to continue
9989 ((and (= tt js2-LT)
9990 js2-compiler-xml-available)
9991 ;; XML stream encountered in expression.
9992 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9993 (t
9994 (setq pn (js2-parse-member-expr t)
9995 ;; Don't look across a newline boundary for a postfix incop.
9996 tt (js2-peek-token-or-eol))
9997 (when (or (= tt js2-INC) (= tt js2-DEC))
9998 (js2-get-token)
9999 (setf expr pn
10000 pn (js2-make-unary tt expr))
10001 (js2-node-set-prop pn 'postfix t)
10002 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
10003 pn))))
10004
10005 (defun js2-parse-xml-initializer ()
10006 "Parse an E4X XML initializer.
10007 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
10008 Then I'll postprocess the result, depending on whether we're in IDE
10009 mode or codegen mode, and generate the appropriate rewritten AST.
10010 IDE mode uses a rich AST that models the XML structure. Codegen mode
10011 just concatenates everything and makes a new XML or XMLList out of it."
10012 (let ((tt (js2-get-first-xml-token))
10013 pn-xml pn expr kids expr-pos
10014 (continue t)
10015 (first-token t))
10016 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
10017 (js2-report-error "msg.syntax"))
10018 (setq pn-xml (make-js2-xml-node))
10019 (while continue
10020 (if first-token
10021 (setq first-token nil)
10022 (setq tt (js2-get-next-xml-token)))
10023 (cond
10024 ;; js2-XML means we found a {expr} in the XML stream.
10025 ;; The token string is the XML up to the left-curly.
10026 ((= tt js2-XML)
10027 (push (make-js2-string-node :pos (js2-current-token-beg)
10028 :len (- js2-ts-cursor (js2-current-token-beg)))
10029 kids)
10030 (js2-must-match js2-LC "msg.syntax")
10031 (setq expr-pos js2-ts-cursor
10032 expr (if (eq (js2-peek-token) js2-RC)
10033 (make-js2-empty-expr-node :pos expr-pos)
10034 (js2-parse-expr)))
10035 (js2-must-match js2-RC "msg.syntax")
10036 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
10037 :len (js2-node-len expr)
10038 :expr expr))
10039 (js2-node-add-children pn expr)
10040 (push pn kids))
10041 ;; a js2-XMLEND token means we hit the final close-tag.
10042 ((= tt js2-XMLEND)
10043 (push (make-js2-string-node :pos (js2-current-token-beg)
10044 :len (- js2-ts-cursor (js2-current-token-beg)))
10045 kids)
10046 (dolist (kid (nreverse kids))
10047 (js2-block-node-push pn-xml kid))
10048 (setf (js2-node-len pn-xml) (- js2-ts-cursor
10049 (js2-node-pos pn-xml))
10050 continue nil))
10051 (t
10052 (js2-report-error "msg.syntax")
10053 (setq continue nil))))
10054 pn-xml))
10055
10056
10057 (defun js2-parse-argument-list ()
10058 "Parse an argument list and return it as a Lisp list of nodes.
10059 Returns the list in reverse order. Consumes the right-paren token."
10060 (let (result)
10061 (unless (js2-match-token js2-RP)
10062 (cl-loop do
10063 (let ((tt (js2-get-token)))
10064 (if (= tt js2-YIELD)
10065 (js2-report-error "msg.yield.parenthesized"))
10066 (if (and (= tt js2-TRIPLEDOT)
10067 (>= js2-language-version 200))
10068 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
10069 (js2-unget-token)
10070 (push (js2-parse-assign-expr) result)))
10071 while
10072 (js2-match-token js2-COMMA))
10073 (js2-must-match js2-RP "msg.no.paren.arg")
10074 result)))
10075
10076 (defun js2-parse-member-expr (&optional allow-call-syntax)
10077 (let ((tt (js2-current-token-type))
10078 pn pos target args beg end init)
10079 (if (/= tt js2-NEW)
10080 (setq pn (js2-parse-primary-expr))
10081 ;; parse a 'new' expression
10082 (js2-get-token)
10083 (setq pos (js2-current-token-beg)
10084 beg pos
10085 target (js2-parse-member-expr)
10086 end (js2-node-end target)
10087 pn (make-js2-new-node :pos pos
10088 :target target
10089 :len (- end pos)))
10090 (js2-highlight-function-call (js2-current-token))
10091 (js2-node-add-children pn target)
10092 (when (js2-match-token js2-LP)
10093 ;; Add the arguments to pn, if any are supplied.
10094 (setf beg pos ; start of "new" keyword
10095 pos (js2-current-token-beg)
10096 args (nreverse (js2-parse-argument-list))
10097 (js2-new-node-args pn) args
10098 end (js2-current-token-end)
10099 (js2-new-node-lp pn) (- pos beg)
10100 (js2-new-node-rp pn) (- end 1 beg))
10101 (apply #'js2-node-add-children pn args))
10102 (when (and js2-allow-rhino-new-expr-initializer
10103 (js2-match-token js2-LC))
10104 (setf init (js2-parse-object-literal)
10105 end (js2-node-end init)
10106 (js2-new-node-initializer pn) init)
10107 (js2-node-add-children pn init))
10108 (setf (js2-node-len pn) (- end beg))) ; end outer if
10109 (js2-parse-member-expr-tail allow-call-syntax pn)))
10110
10111 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10112 "Parse a chain of property/array accesses or function calls.
10113 Includes parsing for E4X operators like `..' and `.@'.
10114 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10115 Returns an expression tree that includes PN, the parent node."
10116 (let (tt
10117 (continue t))
10118 (while continue
10119 (setq tt (js2-get-token))
10120 (cond
10121 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10122 (setq pn (js2-parse-property-access tt pn)))
10123 ((= tt js2-DOTQUERY)
10124 (setq pn (js2-parse-dot-query pn)))
10125 ((= tt js2-LB)
10126 (setq pn (js2-parse-element-get pn)))
10127 ((= tt js2-LP)
10128 (js2-unget-token)
10129 (if allow-call-syntax
10130 (setq pn (js2-parse-function-call pn))
10131 (setq continue nil)))
10132 ((= tt js2-TEMPLATE_HEAD)
10133 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10134 ((= tt js2-NO_SUBS_TEMPLATE)
10135 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10136 (t
10137 (js2-unget-token)
10138 (setq continue nil)))
10139 (if (>= js2-highlight-level 2)
10140 (js2-parse-highlight-member-expr-node pn)))
10141 pn))
10142
10143 (defun js2-parse-tagged-template (tag-node tpl-node)
10144 "Parse tagged template expression."
10145 (let* ((beg (js2-node-pos tag-node))
10146 (pn (make-js2-tagged-template-node :beg beg
10147 :len (- (js2-current-token-end) beg)
10148 :tag tag-node
10149 :template tpl-node)))
10150 (js2-node-add-children pn tag-node tpl-node)
10151 pn))
10152
10153 (defun js2-parse-dot-query (pn)
10154 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10155 Last token parsed must be `js2-DOTQUERY'."
10156 (let ((pos (js2-node-pos pn))
10157 op-pos expr end)
10158 (js2-must-have-xml)
10159 (js2-set-requires-activation)
10160 (setq op-pos (js2-current-token-beg)
10161 expr (js2-parse-expr)
10162 end (js2-node-end expr)
10163 pn (make-js2-xml-dot-query-node :left pn
10164 :pos pos
10165 :op-pos op-pos
10166 :right expr))
10167 (js2-node-add-children pn
10168 (js2-xml-dot-query-node-left pn)
10169 (js2-xml-dot-query-node-right pn))
10170 (if (js2-must-match js2-RP "msg.no.paren")
10171 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10172 end (js2-current-token-end)))
10173 (setf (js2-node-len pn) (- end pos))
10174 pn))
10175
10176 (defun js2-parse-element-get (pn)
10177 "Parse an element-get expression, e.g. foo[bar].
10178 Last token parsed must be `js2-RB'."
10179 (let ((lb (js2-current-token-beg))
10180 (pos (js2-node-pos pn))
10181 rb expr)
10182 (setq expr (js2-parse-expr))
10183 (if (js2-must-match js2-RB "msg.no.bracket.index")
10184 (setq rb (js2-current-token-beg)))
10185 (setq pn (make-js2-elem-get-node :target pn
10186 :pos pos
10187 :element expr
10188 :lb (js2-relpos lb pos)
10189 :rb (js2-relpos rb pos)
10190 :len (- (js2-current-token-end) pos)))
10191 (js2-node-add-children pn
10192 (js2-elem-get-node-target pn)
10193 (js2-elem-get-node-element pn))
10194 pn))
10195
10196 (defun js2-highlight-function-call (token)
10197 (when (eq (js2-token-type token) js2-NAME)
10198 (js2-record-face 'js2-function-call token)))
10199
10200 (defun js2-parse-function-call (pn)
10201 (js2-highlight-function-call (js2-current-token))
10202 (js2-get-token)
10203 (let (args
10204 (pos (js2-node-pos pn)))
10205 (setq pn (make-js2-call-node :pos pos
10206 :target pn
10207 :lp (- (js2-current-token-beg) pos)))
10208 (js2-node-add-children pn (js2-call-node-target pn))
10209 ;; Add the arguments to pn, if any are supplied.
10210 (setf args (nreverse (js2-parse-argument-list))
10211 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10212 (js2-call-node-args pn) args)
10213 (apply #'js2-node-add-children pn args)
10214 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10215 pn))
10216
10217 (defun js2-parse-property-access (tt pn)
10218 "Parse a property access, XML descendants access, or XML attr access."
10219 (let ((member-type-flags 0)
10220 (dot-pos (js2-current-token-beg))
10221 (dot-len (if (= tt js2-DOTDOT) 2 1))
10222 name
10223 ref ; right side of . or .. operator
10224 result)
10225 (when (= tt js2-DOTDOT)
10226 (js2-must-have-xml)
10227 (setq member-type-flags js2-descendants-flag))
10228 (if (not js2-compiler-xml-available)
10229 (progn
10230 (js2-must-match-prop-name "msg.no.name.after.dot")
10231 (setq name (js2-create-name-node t js2-GETPROP)
10232 result (make-js2-prop-get-node :left pn
10233 :pos (js2-current-token-beg)
10234 :right name
10235 :len (js2-current-token-len)))
10236 (js2-node-add-children result pn name)
10237 result)
10238 ;; otherwise look for XML operators
10239 (setf result (if (= tt js2-DOT)
10240 (make-js2-prop-get-node)
10241 (make-js2-infix-node :type js2-DOTDOT))
10242 (js2-node-pos result) (js2-node-pos pn)
10243 (js2-infix-node-op-pos result) dot-pos
10244 (js2-infix-node-left result) pn ; do this after setting position
10245 tt (js2-get-prop-name-token))
10246 (cond
10247 ;; handles: name, ns::name, ns::*, ns::[expr]
10248 ((= tt js2-NAME)
10249 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10250 ;; handles: *, *::name, *::*, *::[expr]
10251 ((= tt js2-MUL)
10252 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10253 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10254 ((= tt js2-XMLATTR)
10255 (setq result (js2-parse-attribute-access)))
10256 (t
10257 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10258 (if ref
10259 (setf (js2-node-len result) (- (js2-node-end ref)
10260 (js2-node-pos result))
10261 (js2-infix-node-right result) ref))
10262 (if (js2-infix-node-p result)
10263 (js2-node-add-children result
10264 (js2-infix-node-left result)
10265 (js2-infix-node-right result)))
10266 result)))
10267
10268 (defun js2-parse-attribute-access ()
10269 "Parse an E4X XML attribute expression.
10270 This includes expressions of the forms:
10271
10272 @attr @ns::attr @ns::*
10273 @* @*::attr @*::*
10274 @[expr] @*::[expr] @ns::[expr]
10275
10276 Called if we peeked an `@' token."
10277 (let ((tt (js2-get-prop-name-token))
10278 (at-pos (js2-current-token-beg)))
10279 (cond
10280 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10281 ((= tt js2-NAME)
10282 (js2-parse-property-name at-pos nil 0))
10283 ;; handles: @*, @*::name, @*::*, @*::[expr]
10284 ((= tt js2-MUL)
10285 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10286 ;; handles @[expr]
10287 ((= tt js2-LB)
10288 (js2-parse-xml-elem-ref at-pos))
10289 (t
10290 (js2-report-error "msg.no.name.after.xmlAttr")
10291 ;; Avoid cascaded errors that happen if we make an error node here.
10292 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10293
10294 (defun js2-parse-property-name (at-pos s member-type-flags)
10295 "Check if :: follows name in which case it becomes qualified name.
10296
10297 AT-POS is a natural number if we just read an `@' token, else nil.
10298 S is the name or string that was matched: an identifier, `throw' or `*'.
10299 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a `.' or `..' child.
10300
10301 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a `..'
10302 operator, or the name is followed by ::. For a plain name, returns a
10303 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10304 (let ((pos (or at-pos (js2-current-token-beg)))
10305 colon-pos
10306 (name (js2-create-name-node t (js2-current-token-type) s))
10307 ns tt pn)
10308 (catch 'return
10309 (when (js2-match-token js2-COLONCOLON)
10310 (setq ns name
10311 colon-pos (js2-current-token-beg)
10312 tt (js2-get-prop-name-token))
10313 (cond
10314 ;; handles name::name
10315 ((= tt js2-NAME)
10316 (setq name (js2-create-name-node)))
10317 ;; handles name::*
10318 ((= tt js2-MUL)
10319 (setq name (js2-create-name-node nil nil "*")))
10320 ;; handles name::[expr]
10321 ((= tt js2-LB)
10322 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10323 (t
10324 (js2-report-error "msg.no.name.after.coloncolon"))))
10325 (if (and (null ns) (zerop member-type-flags))
10326 name
10327 (prog1
10328 (setq pn
10329 (make-js2-xml-prop-ref-node :pos pos
10330 :len (- (js2-node-end name) pos)
10331 :at-pos at-pos
10332 :colon-pos colon-pos
10333 :propname name))
10334 (js2-node-add-children pn name))))))
10335
10336 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10337 "Parse the [expr] portion of an xml element reference.
10338 For instance, @[expr], @*::[expr], or ns::[expr]."
10339 (let* ((lb (js2-current-token-beg))
10340 (pos (or at-pos lb))
10341 rb
10342 (expr (js2-parse-expr))
10343 (end (js2-node-end expr))
10344 pn)
10345 (if (js2-must-match js2-RB "msg.no.bracket.index")
10346 (setq rb (js2-current-token-beg)
10347 end (js2-current-token-end)))
10348 (prog1
10349 (setq pn
10350 (make-js2-xml-elem-ref-node :pos pos
10351 :len (- end pos)
10352 :namespace namespace
10353 :colon-pos colon-pos
10354 :at-pos at-pos
10355 :expr expr
10356 :lb (js2-relpos lb pos)
10357 :rb (js2-relpos rb pos)))
10358 (js2-node-add-children pn namespace expr))))
10359
10360 (defun js2-parse-destruct-primary-expr ()
10361 (let ((js2-is-in-destructuring t))
10362 (js2-parse-primary-expr)))
10363
10364 (defun js2-parse-primary-expr ()
10365 "Parse a literal (leaf) expression of some sort.
10366 Includes complex literals such as functions, object-literals,
10367 array-literals, array comprehensions and regular expressions."
10368 (let (tt node)
10369 (setq tt (js2-current-token-type))
10370 (cond
10371 ((= tt js2-CLASS)
10372 (js2-parse-class-expr))
10373 ((= tt js2-FUNCTION)
10374 (js2-parse-function-expr))
10375 ((js2-match-async-function)
10376 (js2-parse-function-expr t))
10377 ((= tt js2-LB)
10378 (js2-parse-array-comp-or-literal))
10379 ((= tt js2-LC)
10380 (js2-parse-object-literal))
10381 ((= tt js2-LET)
10382 (js2-parse-let (js2-current-token-beg)))
10383 ((= tt js2-LP)
10384 (js2-parse-paren-expr-or-generator-comp))
10385 ((= tt js2-XMLATTR)
10386 (js2-must-have-xml)
10387 (js2-parse-attribute-access))
10388 ((= tt js2-NAME)
10389 (js2-parse-name tt))
10390 ((= tt js2-NUMBER)
10391 (setq node (make-js2-number-node))
10392 (when (and js2-in-use-strict-directive
10393 (= (js2-number-node-num-base node) 8)
10394 (js2-number-node-legacy-octal-p node))
10395 (js2-report-error "msg.no.octal.strict"))
10396 node)
10397 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10398 (make-js2-string-node :type tt))
10399 ((= tt js2-TEMPLATE_HEAD)
10400 (js2-parse-template-literal))
10401 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10402 ;; Got / or /= which in this context means a regexp literal
10403 (let ((px-pos (js2-current-token-beg))
10404 (flags (js2-read-regexp tt))
10405 (end (js2-current-token-end)))
10406 (prog1
10407 (make-js2-regexp-node :pos px-pos
10408 :len (- end px-pos)
10409 :value (js2-current-token-string)
10410 :flags flags)
10411 (js2-set-face px-pos end 'font-lock-string-face 'record)
10412 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10413 ((or (= tt js2-NULL)
10414 (= tt js2-THIS)
10415 (= tt js2-SUPER)
10416 (= tt js2-FALSE)
10417 (= tt js2-TRUE))
10418 (make-js2-keyword-node :type tt))
10419 ((= tt js2-TRIPLEDOT)
10420 ;; Likewise, only valid in an arrow function with a rest param.
10421 (if (and (js2-match-token js2-NAME)
10422 (js2-match-token js2-RP)
10423 (eq (js2-peek-token) js2-ARROW))
10424 (progn
10425 (js2-unget-token) ; Put back the right paren.
10426 ;; See the previous case.
10427 (make-js2-keyword-node :type js2-NULL))
10428 (js2-report-error "msg.syntax")
10429 (make-js2-error-node)))
10430 ((= tt js2-RESERVED)
10431 (js2-report-error "msg.reserved.id")
10432 (make-js2-name-node))
10433 ((= tt js2-ERROR)
10434 ;; the scanner or one of its subroutines reported the error.
10435 (make-js2-error-node))
10436 ((= tt js2-EOF)
10437 (let* ((px-pos (point-at-bol))
10438 (len (- js2-ts-cursor px-pos)))
10439 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10440 (make-js2-error-node :pos (1- js2-ts-cursor)))
10441 (t
10442 (js2-report-error "msg.syntax")
10443 (make-js2-error-node)))))
10444
10445 (defun js2-parse-template-literal ()
10446 (let ((beg (js2-current-token-beg))
10447 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10448 (tt js2-TEMPLATE_HEAD))
10449 (while (eq tt js2-TEMPLATE_HEAD)
10450 (push (js2-parse-expr) kids)
10451 (js2-must-match js2-RC "msg.syntax")
10452 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10453 (push (make-js2-string-node :type tt) kids))
10454 (setq kids (nreverse kids))
10455 (let ((tpl (make-js2-template-node :beg beg
10456 :len (- (js2-current-token-end) beg)
10457 :kids kids)))
10458 (apply #'js2-node-add-children tpl kids)
10459 tpl)))
10460
10461 (defun js2-parse-name (_tt)
10462 (let ((name (js2-current-token-string))
10463 node)
10464 (setq node (if js2-compiler-xml-available
10465 (js2-parse-property-name nil name 0)
10466 (js2-create-name-node 'check-activation nil name)))
10467 (if js2-highlight-external-variables
10468 (js2-record-name-node node))
10469 node))
10470
10471 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10472 (js2-add-strict-warning
10473 msg nil
10474 ;; back up from comma to beginning of line or array/objlit
10475 (max (if elems
10476 (js2-node-pos (car elems))
10477 pos)
10478 (save-excursion
10479 (goto-char comma-pos)
10480 (back-to-indentation)
10481 (point)))
10482 comma-pos))
10483
10484 (defun js2-parse-array-comp-or-literal ()
10485 (let ((pos (js2-current-token-beg)))
10486 (if (and (>= js2-language-version 200)
10487 (js2-match-token js2-FOR))
10488 (js2-parse-array-comp pos)
10489 (js2-parse-array-literal pos))))
10490
10491 (defun js2-parse-array-literal (pos)
10492 (let ((after-lb-or-comma t)
10493 after-comma tt elems pn was-rest
10494 (continue t))
10495 (unless js2-is-in-destructuring
10496 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10497 (while continue
10498 (setq tt (js2-get-token))
10499 (cond
10500 ;; end of array
10501 ((or (= tt js2-RB)
10502 (= tt js2-EOF)) ; prevent infinite loop
10503 (if (= tt js2-EOF)
10504 (js2-report-error "msg.no.bracket.arg" nil pos))
10505 (when (and after-comma (< js2-language-version 170))
10506 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10507 pos (remove nil elems) after-comma))
10508 (setq continue nil
10509 pn (make-js2-array-node :pos pos
10510 :len (- js2-ts-cursor pos)
10511 :elems (nreverse elems)))
10512 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10513 ;; anything after rest element (...foo)
10514 (was-rest
10515 (js2-report-error "msg.param.after.rest"))
10516 ;; comma
10517 ((= tt js2-COMMA)
10518 (setq after-comma (js2-current-token-end))
10519 (if (not after-lb-or-comma)
10520 (setq after-lb-or-comma t)
10521 (push nil elems)))
10522 ;; array comp
10523 ((and (>= js2-language-version 170)
10524 (not js2-is-in-destructuring)
10525 (= tt js2-FOR) ; check for array comprehension
10526 (not after-lb-or-comma) ; "for" can't follow a comma
10527 elems ; must have at least 1 element
10528 (not (cdr elems))) ; but no 2nd element
10529 (js2-unget-token)
10530 (setf continue nil
10531 pn (js2-parse-legacy-array-comp (car elems) pos)))
10532 ;; another element
10533 (t
10534 (unless after-lb-or-comma
10535 (js2-report-error "msg.no.bracket.arg"))
10536 (if (and (= tt js2-TRIPLEDOT)
10537 (>= js2-language-version 200))
10538 ;; rest/spread operator
10539 (progn
10540 (push (js2-make-unary tt 'js2-parse-assign-expr)
10541 elems)
10542 (if js2-is-in-destructuring
10543 (setq was-rest t)))
10544 (js2-unget-token)
10545 (push (js2-parse-assign-expr) elems))
10546 (setq after-lb-or-comma nil
10547 after-comma nil))))
10548 (unless js2-is-in-destructuring
10549 (js2-pop-scope))
10550 pn))
10551
10552 (defun js2-parse-legacy-array-comp (expr pos)
10553 "Parse a legacy array comprehension (JavaScript 1.7).
10554 EXPR is the first expression after the opening left-bracket.
10555 POS is the beginning of the LB token preceding EXPR.
10556 We should have just parsed the `for' keyword before calling this function."
10557 (let ((current-scope js2-current-scope)
10558 loops first filter result)
10559 (unwind-protect
10560 (progn
10561 (while (js2-match-token js2-FOR)
10562 (let ((loop (make-js2-comp-loop-node)))
10563 (js2-push-scope loop)
10564 (push loop loops)
10565 (js2-parse-comp-loop loop)))
10566 ;; First loop takes expr scope's parent.
10567 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10568 (js2-scope-parent-scope current-scope))
10569 ;; Set expr scope's parent to the last loop.
10570 (setf (js2-scope-parent-scope current-scope) (car loops))
10571 (if (/= (js2-get-token) js2-IF)
10572 (js2-unget-token)
10573 (setq filter (js2-parse-condition))))
10574 (dotimes (_ (1- (length loops)))
10575 (js2-pop-scope)))
10576 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10577 (setq result (make-js2-comp-node :pos pos
10578 :len (- js2-ts-cursor pos)
10579 :result expr
10580 :loops (nreverse loops)
10581 :filters (and filter (list (car filter)))
10582 :form 'LEGACY_ARRAY))
10583 ;; Set comp loop's parent to the last loop.
10584 ;; TODO: Get rid of the bogus expr scope.
10585 (setf (js2-scope-parent-scope result) first)
10586 (apply #'js2-node-add-children result expr (car filter)
10587 (js2-comp-node-loops result))
10588 result))
10589
10590 (defun js2-parse-array-comp (pos)
10591 "Parse an ES6 array comprehension.
10592 POS is the beginning of the LB token.
10593 We should have just parsed the `for' keyword before calling this function."
10594 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10595 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10596 pn))
10597
10598 (defun js2-parse-generator-comp (pos)
10599 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10600 (js2-current-script-or-fn
10601 (make-js2-function-node :generator-type 'COMPREHENSION))
10602 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10603 (js2-must-match js2-RP "msg.no.paren" pos)
10604 pn))
10605
10606 (defun js2-parse-comprehension (pos form)
10607 (let (loops filters expr result last)
10608 (unwind-protect
10609 (progn
10610 (js2-unget-token)
10611 (while (js2-match-token js2-FOR)
10612 (let ((loop (make-js2-comp-loop-node)))
10613 (js2-push-scope loop)
10614 (push loop loops)
10615 (js2-parse-comp-loop loop)))
10616 (while (js2-match-token js2-IF)
10617 (push (car (js2-parse-condition)) filters))
10618 (setq expr (js2-parse-assign-expr))
10619 (setq last (car loops)))
10620 (dolist (_ loops)
10621 (js2-pop-scope)))
10622 (setq result (make-js2-comp-node :pos pos
10623 :len (- js2-ts-cursor pos)
10624 :result expr
10625 :loops (nreverse loops)
10626 :filters (nreverse filters)
10627 :form form))
10628 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10629 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10630 (setf (js2-scope-parent-scope result) last)
10631 result))
10632
10633 (defun js2-parse-comp-loop (pn &optional only-of-p)
10634 "Parse a `for [each] (foo [in|of] bar)' expression in an Array comprehension.
10635 The current token should be the initial FOR.
10636 If ONLY-OF-P is non-nil, only the `for (foo of bar)' form is allowed."
10637 (let ((pos (js2-comp-loop-node-pos pn))
10638 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10639 (when (and (not only-of-p) (js2-match-token js2-NAME))
10640 (if (string= (js2-current-token-string) "each")
10641 (progn
10642 (setq foreach-p t
10643 each-pos (- (js2-current-token-beg) pos)) ; relative
10644 (js2-record-face 'font-lock-keyword-face))
10645 (js2-report-error "msg.no.paren.for")))
10646 (if (js2-must-match js2-LP "msg.no.paren.for")
10647 (setq lp (- (js2-current-token-beg) pos)))
10648 (setq tt (js2-peek-token))
10649 (cond
10650 ((or (= tt js2-LB)
10651 (= tt js2-LC))
10652 (js2-get-token)
10653 (setq iter (js2-parse-destruct-primary-expr))
10654 (js2-define-destruct-symbols iter js2-LET
10655 'font-lock-variable-name-face t))
10656 ((js2-match-token js2-NAME)
10657 (setq iter (js2-create-name-node)))
10658 (t
10659 (js2-report-error "msg.bad.var")))
10660 ;; Define as a let since we want the scope of the variable to
10661 ;; be restricted to the array comprehension
10662 (if (js2-name-node-p iter)
10663 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10664 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10665 (and (>= js2-language-version 200)
10666 (js2-match-contextual-kwd "of")
10667 (setq forof-p t)))
10668 (setq in-pos (- (js2-current-token-beg) pos))
10669 (js2-report-error "msg.in.after.for.name"))
10670 (setq obj (js2-parse-expr))
10671 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10672 (setq rp (- (js2-current-token-beg) pos)))
10673 (setf (js2-node-pos pn) pos
10674 (js2-node-len pn) (- js2-ts-cursor pos)
10675 (js2-comp-loop-node-iterator pn) iter
10676 (js2-comp-loop-node-object pn) obj
10677 (js2-comp-loop-node-in-pos pn) in-pos
10678 (js2-comp-loop-node-each-pos pn) each-pos
10679 (js2-comp-loop-node-foreach-p pn) foreach-p
10680 (js2-comp-loop-node-forof-p pn) forof-p
10681 (js2-comp-loop-node-lp pn) lp
10682 (js2-comp-loop-node-rp pn) rp)
10683 (js2-node-add-children pn iter obj)
10684 pn))
10685
10686 (defun js2-parse-class-stmt ()
10687 (let ((pos (js2-current-token-beg))
10688 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10689 (name (js2-create-name-node t)))
10690 (js2-set-face (js2-node-pos name) (js2-node-end name)
10691 'font-lock-function-name-face 'record)
10692 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10693 (js2-record-imenu-functions node name)
10694 (js2-define-symbol js2-FUNCTION
10695 (js2-name-node-name name)
10696 node)
10697 node)))
10698
10699 (defun js2-parse-class-expr ()
10700 (let ((pos (js2-current-token-beg))
10701 name)
10702 (when (js2-match-token js2-NAME)
10703 (setq name (js2-create-name-node t)))
10704 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10705
10706 (defun js2-parse-class (pos form name)
10707 ;; class X [extends ...] {
10708 (let (pn elems extends)
10709 (if (js2-match-token js2-EXTENDS)
10710 (if (= (js2-peek-token) js2-LC)
10711 (js2-report-error "msg.missing.extends")
10712 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10713 (setq extends (js2-parse-assign-expr))
10714 (if (not extends)
10715 (js2-report-error "msg.bad.extends"))))
10716 (js2-must-match js2-LC "msg.no.brace.class")
10717 (setq elems (js2-parse-object-literal-elems t)
10718 pn (make-js2-class-node :pos pos
10719 :len (- js2-ts-cursor pos)
10720 :form form
10721 :name name
10722 :extends extends
10723 :elems elems))
10724 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10725 pn))
10726
10727 (defun js2-parse-object-literal ()
10728 (let* ((pos (js2-current-token-beg))
10729 (elems (js2-parse-object-literal-elems))
10730 (result (make-js2-object-node :pos pos
10731 :len (- js2-ts-cursor pos)
10732 :elems elems)))
10733 (apply #'js2-node-add-children result (js2-object-node-elems result))
10734 result))
10735
10736 (defun js2-property-key-string (property-node)
10737 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10738 `js2-method-node') as a string, or nil if it can't be
10739 represented as a string (e.g., the key is computed by an
10740 expression)."
10741 (cond
10742 ((js2-unary-node-p property-node) nil) ;; {...foo}
10743 (t
10744 (let ((key (js2-infix-node-left property-node)))
10745 (when (js2-computed-prop-name-node-p key)
10746 (setq key (js2-computed-prop-name-node-expr key)))
10747 (cond
10748 ((js2-name-node-p key)
10749 (js2-name-node-name key))
10750 ((js2-string-node-p key)
10751 (js2-string-node-value key))
10752 ((js2-number-node-p key)
10753 (js2-number-node-value key)))))))
10754
10755 (defun js2-parse-object-literal-elems (&optional class-p)
10756 (let ((pos (js2-current-token-beg))
10757 (static nil)
10758 (continue t)
10759 tt elems elem
10760 elem-key-string previous-elem-key-string
10761 after-comma previous-token)
10762 (while continue
10763 (setq tt (js2-get-prop-name-token)
10764 static nil
10765 elem nil
10766 previous-token nil)
10767 ;; Handle 'static' keyword only if we're in a class
10768 (when (and class-p (= js2-NAME tt)
10769 (string= "static" (js2-current-token-string)))
10770 (js2-record-face 'font-lock-keyword-face)
10771 (setq static t
10772 tt (js2-get-prop-name-token)))
10773 ;; Handle generator * before the property name for in-line functions
10774 (when (and (>= js2-language-version 200)
10775 (= js2-MUL tt))
10776 (setq previous-token (js2-current-token)
10777 tt (js2-get-prop-name-token)))
10778 ;; Handle getter, setter and async methods
10779 (let ((prop (js2-current-token-string)))
10780 (when (and (>= js2-language-version 200)
10781 (= js2-NAME tt)
10782 (member prop '("get" "set" "async"))
10783 (member (js2-peek-token)
10784 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10785 (setq previous-token (js2-current-token)
10786 tt (js2-get-prop-name-token))))
10787 (cond
10788 ;; Rest/spread (...expr)
10789 ((and (>= js2-language-version 200)
10790 (not class-p) (not static) (not previous-token)
10791 (= js2-TRIPLEDOT tt))
10792 (setq after-comma nil
10793 elem (js2-make-unary js2-TRIPLEDOT 'js2-parse-assign-expr)))
10794 ;; Found a key/value property (of any sort)
10795 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10796 (setq after-comma nil
10797 elem (js2-parse-named-prop tt previous-token))
10798 (if (and (null elem)
10799 (not js2-recover-from-parse-errors))
10800 (setq continue nil)))
10801 ;; Break out of loop, and handle trailing commas.
10802 ((or (= tt js2-RC)
10803 (= tt js2-EOF))
10804 (js2-unget-token)
10805 (setq continue nil)
10806 (if after-comma
10807 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10808 pos elems after-comma)))
10809 ;; Skip semicolons in a class body
10810 ((and class-p
10811 (= tt js2-SEMI))
10812 nil)
10813 (t
10814 (js2-report-error "msg.bad.prop")
10815 (unless js2-recover-from-parse-errors
10816 (setq continue nil)))) ; end switch
10817 ;; Handle static for classes' codegen.
10818 (if static
10819 (if elem (js2-node-set-prop elem 'STATIC t)
10820 (js2-report-error "msg.unexpected.static")))
10821 ;; Handle commas, depending on class-p.
10822 (let ((tok (js2-get-prop-name-token)))
10823 (if (eq tok js2-COMMA)
10824 (if class-p
10825 (js2-report-error "msg.class.unexpected.comma")
10826 (setq after-comma (js2-current-token-end)))
10827 (js2-unget-token)
10828 (unless class-p (setq continue nil))))
10829 (when elem
10830 (when (and js2-in-use-strict-directive
10831 (setq elem-key-string (js2-property-key-string elem))
10832 (cl-some
10833 (lambda (previous-elem)
10834 (and (setq previous-elem-key-string
10835 (js2-property-key-string previous-elem))
10836 ;; Check if the property is a duplicate.
10837 (string= previous-elem-key-string elem-key-string)
10838 ;; But make an exception for getter / setter pairs.
10839 (not (and (js2-method-node-p elem)
10840 (js2-method-node-p previous-elem)
10841 (let ((type (js2-node-get-prop (js2-method-node-right elem) 'METHOD_TYPE))
10842 (previous-type (js2-node-get-prop (js2-method-node-right previous-elem) 'METHOD_TYPE)))
10843 (and (member type '(GET SET))
10844 (member previous-type '(GET SET))
10845 (not (eq type previous-type))))))))
10846 elems))
10847 (js2-report-error "msg.dup.obj.lit.prop.strict"
10848 elem-key-string
10849 (js2-node-abs-pos (js2-infix-node-left elem))
10850 (js2-node-len (js2-infix-node-left elem))))
10851 ;; Append any parsed element.
10852 (push elem elems))) ; end loop
10853 (js2-must-match js2-RC "msg.no.brace.prop")
10854 (nreverse elems)))
10855
10856 (defun js2-parse-named-prop (tt previous-token)
10857 "Parse a name, string, or getter/setter object property.
10858 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10859 (let ((key (js2-parse-prop-name tt))
10860 (prop (and previous-token (js2-token-string previous-token)))
10861 (property-type (when previous-token
10862 (if (= (js2-token-type previous-token) js2-MUL)
10863 "*"
10864 (js2-token-string previous-token))))
10865 pos)
10866 (when (member prop '("get" "set" "async"))
10867 (setq pos (js2-token-beg previous-token))
10868 (js2-set-face (js2-token-beg previous-token)
10869 (js2-token-end previous-token)
10870 'font-lock-keyword-face 'record)) ; get/set/async
10871 (cond
10872 ;; method definition: {f() {...}}
10873 ((and (= (js2-peek-token) js2-LP)
10874 (>= js2-language-version 200))
10875 (when (js2-name-node-p key) ; highlight function name properties
10876 (js2-record-face 'font-lock-function-name-face))
10877 (js2-parse-method-prop pos key property-type))
10878 ;; binding element with initializer
10879 ((and (= (js2-peek-token) js2-ASSIGN)
10880 (>= js2-language-version 200))
10881 (if (not js2-is-in-destructuring)
10882 (js2-report-error "msg.init.no.destruct"))
10883 (js2-parse-initialized-binding key))
10884 ;; regular prop
10885 (t
10886 (let ((beg (js2-current-token-beg))
10887 (end (js2-current-token-end))
10888 (expr (js2-parse-plain-property key)))
10889 (when (and (= tt js2-NAME)
10890 (not js2-is-in-destructuring)
10891 js2-highlight-external-variables
10892 (js2-node-get-prop expr 'SHORTHAND))
10893 (js2-record-name-node key))
10894 (js2-set-face beg end
10895 (if (js2-function-node-p
10896 (js2-object-prop-node-right expr))
10897 'font-lock-function-name-face
10898 'js2-object-property)
10899 'record)
10900 expr)))))
10901
10902 (defun js2-parse-initialized-binding (name)
10903 "Parse a `SingleNameBinding' with initializer.
10904
10905 `name' is the `BindingIdentifier'."
10906 (when (js2-match-token js2-ASSIGN)
10907 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10908
10909 (defun js2-parse-prop-name (tt)
10910 (cond
10911 ;; Literal string keys: {'foo': 'bar'}
10912 ((= tt js2-STRING)
10913 (make-js2-string-node))
10914 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10915 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10916 ((and (= tt js2-LB)
10917 (>= js2-language-version 200))
10918 (make-js2-computed-prop-name-node
10919 :expr (prog1 (js2-parse-assign-expr)
10920 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10921 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10922 ((= tt js2-NUMBER)
10923 (make-js2-number-node))
10924 ;; Unquoted names: {foo: 12}
10925 ((= tt js2-NAME)
10926 (js2-create-name-node))
10927 ;; Anything else is an error
10928 (t (js2-report-error "msg.bad.prop"))))
10929
10930 (defun js2-parse-plain-property (prop)
10931 "Parse a non-getter/setter property in an object literal.
10932 PROP is the node representing the property: a number, name,
10933 string or expression."
10934 (let* ((tt (js2-get-token))
10935 (pos (js2-node-pos prop))
10936 colon expr result)
10937 (cond
10938 ;; Abbreviated property, as in {foo, bar}
10939 ((and (>= js2-language-version 200)
10940 (or (= tt js2-COMMA)
10941 (= tt js2-RC))
10942 (not (js2-number-node-p prop)))
10943 (js2-unget-token)
10944 (setq result (make-js2-object-prop-node
10945 :pos pos
10946 :left prop
10947 :right prop
10948 :op-pos (js2-current-token-len)))
10949 (js2-node-add-children result prop)
10950 (js2-node-set-prop result 'SHORTHAND t)
10951 result)
10952 ;; Normal property
10953 (t
10954 (if (= tt js2-COLON)
10955 (setq colon (- (js2-current-token-beg) pos)
10956 expr (js2-parse-assign-expr))
10957 (js2-report-error "msg.no.colon.prop")
10958 (setq expr (make-js2-error-node)))
10959 (setq result (make-js2-object-prop-node
10960 :pos pos
10961 ;; don't include last consumed token in length
10962 :len (- (+ (js2-node-pos expr)
10963 (js2-node-len expr))
10964 pos)
10965 :left prop
10966 :right expr
10967 :op-pos colon))
10968 (js2-node-add-children result prop expr)
10969 result))))
10970
10971 (defun js2-parse-method-prop (pos prop type-string)
10972 "Parse method property in an object literal or a class body.
10973 JavaScript syntax is:
10974
10975 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...},
10976 async foo(...) {...} }
10977
10978 and expression closure style is also supported
10979
10980 { get foo() x, set foo(x) _x = x }
10981
10982 POS is the start position of the `get' or `set' keyword.
10983 PROP is the `js2-name-node' representing the property name.
10984 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10985 (let* ((type (or (cdr (assoc type-string '(("get" . GET)
10986 ("set" . SET)
10987 ("async" . ASYNC))))
10988 'FUNCTION))
10989 result end
10990 (pos (js2-current-token-beg))
10991 (_ (js2-must-match js2-LP "msg.no.paren.parms"))
10992 (fn (js2-parse-function 'FUNCTION_EXPRESSION pos
10993 (string= type-string "*")
10994 (eq type 'ASYNC)
10995 nil)))
10996 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10997 (unless pos (setq pos (js2-node-pos prop)))
10998 (setq end (js2-node-end fn)
10999 result (make-js2-method-node :pos pos
11000 :len (- end pos)
11001 :left prop
11002 :right fn))
11003 (js2-node-add-children result prop fn)
11004 result))
11005
11006 (defun js2-create-name-node (&optional check-activation-p token string)
11007 "Create a name node using the current token and, optionally, STRING.
11008 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
11009 (let* ((beg (js2-current-token-beg))
11010 (tt (js2-current-token-type))
11011 (s (or string
11012 (if (= js2-NAME tt)
11013 (js2-current-token-string)
11014 (js2-tt-name tt))))
11015 name)
11016 (setq name (make-js2-name-node :pos beg
11017 :name s
11018 :len (length s)))
11019 (if check-activation-p
11020 (js2-check-activation-name s (or token js2-NAME)))
11021 name))
11022
11023 ;;; Use AST to extract semantic information
11024
11025 (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
11026 "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
11027 (let ((idx 0) elems (rlt hardcoded-array-index))
11028 (setq elems (js2-array-node-elems array-node))
11029 (if (and elem (not hardcoded-array-index))
11030 (setq rlt (catch 'nth-elt
11031 (dolist (x elems)
11032 ;; We know the ELEM does belong to ARRAY-NODE,
11033 (if (eq elem x) (throw 'nth-elt idx))
11034 (setq idx (1+ idx)))
11035 0)))
11036 (format "[%s]" rlt)))
11037
11038 (defun js2-print-json-path (&optional hardcoded-array-index)
11039 "Print the path to the JSON value under point, and save it in the kill ring.
11040 If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
11041 (interactive "P")
11042 (js2-reparse)
11043 (let (previous-node current-node
11044 key-name
11045 rlt)
11046
11047 ;; The `js2-node-at-point' starts scanning from AST root node.
11048 ;; So there is no way to optimize it.
11049 (setq current-node (js2-node-at-point))
11050
11051 (while (not (js2-ast-root-p current-node))
11052 (cond
11053 ;; JSON property node
11054 ((js2-object-prop-node-p current-node)
11055 (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
11056 (if rlt (setq rlt (concat "." key-name rlt))
11057 (setq rlt (concat "." key-name))))
11058
11059 ;; Array node
11060 ((or (js2-array-node-p current-node))
11061 (setq rlt (concat (js2-get-element-index-from-array-node previous-node
11062 current-node
11063 hardcoded-array-index)
11064 rlt)))
11065
11066 ;; Other nodes are ignored
11067 (t))
11068
11069 ;; current node is archived
11070 (setq previous-node current-node)
11071 ;; Get parent node and continue the loop
11072 (setq current-node (js2-node-parent current-node)))
11073
11074 (cond
11075 (rlt
11076 ;; Clean the final result
11077 (setq rlt (replace-regexp-in-string "^\\." "" rlt))
11078 (kill-new rlt)
11079 (message "%s => kill-ring" rlt))
11080 (t
11081 (message "No JSON path found!")))
11082
11083 rlt))
11084
11085 ;;; Indentation support (bouncing)
11086
11087 ;; In recent-enough Emacs, we reuse the indentation code from
11088 ;; `js-mode'. To continue support for the older versions, some code
11089 ;; that was here previously was moved to `js2-old-indent.el'.
11090
11091 ;; Whichever indenter is used, it's often "wrong", however, and needs
11092 ;; to be overridden. The right long-term solution is probably to
11093 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
11094 ;; of coding. Even when a parse tree from `js2-parse' is present,
11095 ;; which is not true at the moment the user is typing, computing
11096 ;; indentation is still thousands of lines of code to handle every
11097 ;; possible syntactic edge case.
11098
11099 ;; In the meantime, the compromise solution is that we offer a "bounce
11100 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
11101 ;; current line indent among various likely guess points. This approach
11102 ;; is far from perfect, but should at least make it slightly easier to
11103 ;; move the line towards its desired indentation when manually
11104 ;; overriding Karl's heuristic nesting guesser.
11105
11106 (defun js2-backward-sws ()
11107 "Move backward through whitespace and comments."
11108 (interactive)
11109 (while (forward-comment -1)))
11110
11111 (defun js2-forward-sws ()
11112 "Move forward through whitespace and comments."
11113 (interactive)
11114 (while (forward-comment 1)))
11115
11116 (defun js2-arglist-close ()
11117 "Return non-nil if we're on a line beginning with a close-paren/brace."
11118 (save-excursion
11119 (goto-char (point-at-bol))
11120 (js2-forward-sws)
11121 (looking-at "[])}]")))
11122
11123 (defun js2-indent-looks-like-label-p ()
11124 (goto-char (point-at-bol))
11125 (js2-forward-sws)
11126 (looking-at (concat js2-mode-identifier-re ":")))
11127
11128 (defun js2-indent-in-objlit-p (parse-status)
11129 "Return non-nil if this looks like an object-literal entry."
11130 (let ((start (nth 1 parse-status)))
11131 (and
11132 start
11133 (save-excursion
11134 (and (zerop (forward-line -1))
11135 (not (< (point) start)) ; crossed a {} boundary
11136 (js2-indent-looks-like-label-p)))
11137 (save-excursion
11138 (js2-indent-looks-like-label-p)))))
11139
11140 ;; If prev line looks like foobar({ then we're passing an object
11141 ;; literal to a function call, and people pretty much always want to
11142 ;; de-dent back to the previous line, so move the 'basic-offset'
11143 ;; position to the front.
11144 (defun js2-indent-objlit-arg-p (parse-status)
11145 (save-excursion
11146 (back-to-indentation)
11147 (js2-backward-sws)
11148 (and (eq (1- (point)) (nth 1 parse-status))
11149 (eq (char-before) ?{)
11150 (progn
11151 (forward-char -1)
11152 (skip-chars-backward " \t")
11153 (eq (char-before) ?\()))))
11154
11155 (defun js2-indent-case-block-p ()
11156 (save-excursion
11157 (back-to-indentation)
11158 (js2-backward-sws)
11159 (goto-char (point-at-bol))
11160 (skip-chars-forward " \t")
11161 (looking-at "case\\s-.+:")))
11162
11163 (defun js2-bounce-indent (normal-col parse-status &optional backward)
11164 "Cycle among alternate computed indentation positions.
11165 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11166 of the buffer to the current point. NORMAL-COL is the indentation
11167 column computed by the heuristic guesser based on current paren,
11168 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11169 in reverse."
11170 (let ((cur-indent (current-indentation))
11171 (old-buffer-undo-list buffer-undo-list)
11172 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11173 (current-line (save-excursion
11174 (forward-line 0) ; move to bol
11175 (1+ (count-lines (point-min) (point)))))
11176 positions pos main-pos anchor arglist-cont same-indent
11177 basic-offset computed-pos)
11178 ;; temporarily don't record undo info, if user requested this
11179 (when js2-mode-indent-inhibit-undo
11180 (setq buffer-undo-list t))
11181 (unwind-protect
11182 (progn
11183 ;; First likely point: indent from beginning of previous code line
11184 (push (setq basic-offset
11185 (+ (save-excursion
11186 (back-to-indentation)
11187 (js2-backward-sws)
11188 (back-to-indentation)
11189 (current-column))
11190 js2-basic-offset))
11191 positions)
11192
11193 ;; (First + epsilon) likely point: indent 2x from beginning of
11194 ;; previous code line. Google does it this way.
11195 (push (setq basic-offset
11196 (+ (save-excursion
11197 (back-to-indentation)
11198 (js2-backward-sws)
11199 (back-to-indentation)
11200 (current-column))
11201 (* 2 js2-basic-offset)))
11202 positions)
11203
11204 ;; Second likely point: indent from assign-expr RHS. This
11205 ;; is just a crude guess based on finding " = " on the previous
11206 ;; line containing actual code.
11207 (setq pos (save-excursion
11208 (forward-line -1)
11209 (goto-char (point-at-bol))
11210 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11211 (point-at-eol) t)
11212 (goto-char (match-end 1))
11213 (skip-chars-forward " \t\r\n")
11214 (current-column))))
11215 (when pos
11216 (cl-incf pos js2-basic-offset)
11217 (push pos positions))
11218
11219 ;; Third likely point: same indent as previous line of code.
11220 ;; Make it the first likely point if we're not on an
11221 ;; arglist-close line and previous line ends in a comma, or
11222 ;; both this line and prev line look like object-literal
11223 ;; elements.
11224 (setq pos (save-excursion
11225 (goto-char (point-at-bol))
11226 (js2-backward-sws)
11227 (back-to-indentation)
11228 (prog1
11229 (current-column)
11230 ;; while we're here, look for trailing comma
11231 (if (save-excursion
11232 (goto-char (point-at-eol))
11233 (js2-backward-sws)
11234 (eq (char-before) ?,))
11235 (setq arglist-cont (1- (point)))))))
11236 (when pos
11237 (if (and (or arglist-cont
11238 (js2-indent-in-objlit-p parse-status))
11239 (not (js2-arglist-close)))
11240 (setq same-indent pos))
11241 (push pos positions))
11242
11243 ;; Fourth likely point: first preceding code with less indentation.
11244 ;; than the immediately preceding code line.
11245 (setq pos (save-excursion
11246 (back-to-indentation)
11247 (js2-backward-sws)
11248 (back-to-indentation)
11249 (setq anchor (current-column))
11250 (while (and (zerop (forward-line -1))
11251 (>= (progn
11252 (back-to-indentation)
11253 (current-column))
11254 anchor)))
11255 (setq pos (current-column))))
11256 (push pos positions)
11257
11258 ;; nesting-heuristic position, main by default
11259 (push (setq main-pos normal-col) positions)
11260
11261 ;; delete duplicates and sort positions list
11262 (setq positions (sort (delete-dups positions) '<))
11263
11264 ;; comma-list continuation lines: prev line indent takes precedence
11265 (if same-indent
11266 (setq main-pos same-indent))
11267
11268 ;; common special cases where we want to indent in from previous line
11269 (if (or (js2-indent-case-block-p)
11270 (js2-indent-objlit-arg-p parse-status))
11271 (setq main-pos basic-offset))
11272
11273 ;; if bouncing backward, reverse positions list
11274 (if backward
11275 (setq positions (reverse positions)))
11276
11277 ;; record whether we're already sitting on one of the alternatives
11278 (setq pos (member cur-indent positions))
11279
11280 (cond
11281 ;; case 0: we're one one of the alternatives and this is the
11282 ;; first time they've pressed TAB on this line (best-guess).
11283 ((and js2-mode-indent-ignore-first-tab
11284 pos
11285 ;; first time pressing TAB on this line?
11286 (not (eq js2-mode-last-indented-line current-line)))
11287 ;; do nothing
11288 (setq computed-pos nil))
11289 ;; case 1: only one computed position => use it
11290 ((null (cdr positions))
11291 (setq computed-pos 0))
11292 ;; case 2: not on any of the computed spots => use main spot
11293 ((not pos)
11294 (setq computed-pos (js2-position main-pos positions)))
11295 ;; case 3: on last position: cycle to first position
11296 ((null (cdr pos))
11297 (setq computed-pos 0))
11298 ;; case 4: on intermediate position: cycle to next position
11299 (t
11300 (setq computed-pos (js2-position (cl-second pos) positions))))
11301
11302 ;; see if any hooks want to indent; otherwise we do it
11303 (cl-loop with result = nil
11304 for hook in js2-indent-hook
11305 while (null result)
11306 do
11307 (setq result (funcall hook positions computed-pos))
11308 finally do
11309 (unless (or result (null computed-pos))
11310 (indent-line-to (nth computed-pos positions)))))
11311
11312 ;; finally
11313 (if js2-mode-indent-inhibit-undo
11314 (setq buffer-undo-list old-buffer-undo-list))
11315 ;; see commentary for `js2-mode-last-indented-line'
11316 (setq js2-mode-last-indented-line current-line))))
11317
11318 (defun js2-1-line-comment-continuation-p ()
11319 "Return t if we're in a 1-line comment continuation.
11320 If so, we don't ever want to use bounce-indent."
11321 (save-excursion
11322 (and (progn
11323 (forward-line 0)
11324 (looking-at "\\s-*//"))
11325 (progn
11326 (forward-line -1)
11327 (forward-line 0)
11328 (when (looking-at "\\s-*$")
11329 (js2-backward-sws)
11330 (forward-line 0))
11331 (looking-at "\\s-*//")))))
11332
11333 (defun js2-indent-bounce (&optional backward)
11334 "Indent the current line, bouncing between several positions."
11335 (interactive)
11336 (let (parse-status offset indent-col
11337 ;; Don't whine about errors/warnings when we're indenting.
11338 ;; This has to be set before calling parse-partial-sexp below.
11339 (inhibit-point-motion-hooks t))
11340 (setq parse-status (save-excursion
11341 (syntax-ppss (point-at-bol)))
11342 offset (- (point) (save-excursion
11343 (back-to-indentation)
11344 (point))))
11345 ;; Don't touch multiline strings.
11346 (unless (nth 3 parse-status)
11347 (setq indent-col (js2-proper-indentation parse-status))
11348 (cond
11349 ;; It doesn't work well on first line of buffer.
11350 ((and (not (nth 4 parse-status))
11351 (not (js2-same-line (point-min)))
11352 (not (js2-1-line-comment-continuation-p)))
11353 (js2-bounce-indent indent-col parse-status backward))
11354 ;; just indent to the guesser's likely spot
11355 (t (indent-line-to indent-col)))
11356 (when (cl-plusp offset)
11357 (forward-char offset)))))
11358
11359 (defun js2-indent-bounce-backward ()
11360 "Indent the current line, bouncing between positions in reverse."
11361 (interactive)
11362 (js2-indent-bounce t))
11363
11364 (defun js2-indent-region (start end)
11365 "Indent the region, but don't use bounce indenting."
11366 (let ((js2-bounce-indent-p nil)
11367 (indent-region-function nil)
11368 (after-change-functions (remq 'js2-mode-edit
11369 after-change-functions)))
11370 (indent-region start end nil) ; nil for byte-compiler
11371 (js2-mode-edit start end (- end start))))
11372
11373 (defvar js2-minor-mode-map
11374 (let ((map (make-sparse-keymap)))
11375 (define-key map (kbd "C-c C-`") #'js2-next-error)
11376 (define-key map [mouse-1] #'js2-mode-show-node)
11377 map)
11378 "Keymap used when `js2-minor-mode' is active.")
11379
11380 ;;;###autoload
11381 (define-minor-mode js2-minor-mode
11382 "Minor mode for running js2 as a background linter.
11383 This allows you to use a different major mode for JavaScript editing,
11384 such as `js-mode', while retaining the asynchronous error/warning
11385 highlighting features of `js2-mode'."
11386 :group 'js2-mode
11387 :lighter " js-lint"
11388 (if (derived-mode-p 'js2-mode)
11389 (setq js2-minor-mode nil)
11390 (if js2-minor-mode
11391 (js2-minor-mode-enter)
11392 (js2-minor-mode-exit))))
11393
11394 (defun js2-minor-mode-enter ()
11395 "Initialization for `js2-minor-mode'."
11396 (set (make-local-variable 'max-lisp-eval-depth)
11397 (max max-lisp-eval-depth 3000))
11398 (setq next-error-function #'js2-next-error)
11399 (js2-set-default-externs)
11400 ;; Experiment: make reparse-delay longer for longer files.
11401 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11402 (setq js2-idle-timer-delay
11403 (* js2-idle-timer-delay
11404 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11405 (setq js2-mode-buffer-dirty-p t
11406 js2-mode-parsing nil)
11407 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11408 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11409 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11410 (when js2-include-jslint-globals
11411 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11412 (run-hooks 'js2-init-hook)
11413 (js2-reparse))
11414
11415 (defun js2-minor-mode-exit ()
11416 "Turn off `js2-minor-mode'."
11417 (setq next-error-function nil)
11418 (remove-hook 'after-change-functions #'js2-mode-edit t)
11419 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11420 (when js2-mode-node-overlay
11421 (delete-overlay js2-mode-node-overlay)
11422 (setq js2-mode-node-overlay nil))
11423 (js2-remove-overlays)
11424 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11425 (setq js2-mode-ast nil))
11426
11427 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11428 (make-variable-buffer-local 'js2-source-buffer)
11429
11430 (cl-defun js2-display-error-list ()
11431 "Display a navigable buffer listing parse errors/warnings."
11432 (interactive)
11433 (unless (js2-have-errors-p)
11434 (message "No errors")
11435 (cl-return-from js2-display-error-list))
11436 (cl-labels ((annotate-list
11437 (lst type)
11438 "Add diagnostic TYPE and line number to errs list"
11439 (mapcar (lambda (err)
11440 (list err type (line-number-at-pos (nth 1 err))))
11441 lst)))
11442 (let* ((srcbuf (current-buffer))
11443 (errbuf (get-buffer-create "*js-lint*"))
11444 (errors (annotate-list
11445 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11446 'js2-error)) ; must be a valid face name
11447 (warnings (annotate-list
11448 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11449 'js2-warning)) ; must be a valid face name
11450 (all-errs (sort (append errors warnings)
11451 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11452 (with-current-buffer errbuf
11453 (let ((inhibit-read-only t))
11454 (erase-buffer)
11455 (dolist (err all-errs)
11456 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11457 (insert-text-button
11458 (format "line %d: %s" line (js2-get-msg msg-key))
11459 'face type
11460 'follow-link "\C-m"
11461 'action 'js2-error-buffer-jump
11462 'js2-msg (js2-get-msg msg-key)
11463 'js2-pos beg)
11464 (insert "\n"))))
11465 (js2-error-buffer-mode)
11466 (setq js2-source-buffer srcbuf)
11467 (pop-to-buffer errbuf)
11468 (goto-char (point-min))
11469 (unless (eobp)
11470 (js2-error-buffer-view))))))
11471
11472 (defvar js2-error-buffer-mode-map
11473 (let ((map (make-sparse-keymap)))
11474 (define-key map "n" #'js2-error-buffer-next)
11475 (define-key map "p" #'js2-error-buffer-prev)
11476 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11477 (define-key map "o" #'js2-error-buffer-view)
11478 (define-key map "q" #'js2-error-buffer-quit)
11479 map)
11480 "Keymap used for js2 diagnostics buffers.")
11481
11482 (define-derived-mode js2-error-buffer-mode special-mode "JS Lint Diagnostics"
11483 "Major mode for js2 diagnostics buffers.
11484 Selecting an error will jump it to the corresponding source-buffer error.
11485 \\{js2-error-buffer-mode-map}"
11486 (setq truncate-lines t)
11487 (set-buffer-modified-p nil)
11488 (setq buffer-read-only t))
11489
11490 (defun js2-error-buffer-next ()
11491 "Move to next error and view it."
11492 (interactive)
11493 (when (zerop (forward-line 1))
11494 (js2-error-buffer-view)))
11495
11496 (defun js2-error-buffer-prev ()
11497 "Move to previous error and view it."
11498 (interactive)
11499 (when (zerop (forward-line -1))
11500 (js2-error-buffer-view)))
11501
11502 (defun js2-error-buffer-quit ()
11503 "Kill the current buffer."
11504 (interactive)
11505 (kill-buffer))
11506
11507 (defun js2-error-buffer-jump (&rest ignored)
11508 "Jump cursor to current error in source buffer."
11509 (interactive)
11510 (when (js2-error-buffer-view)
11511 (pop-to-buffer js2-source-buffer)))
11512
11513 (defun js2-error-buffer-view ()
11514 "Scroll source buffer to show error at current line."
11515 (interactive)
11516 (cond
11517 ((not (derived-mode-p 'js2-error-buffer-mode))
11518 (message "Not in a js2 errors buffer"))
11519 ((not (buffer-live-p js2-source-buffer))
11520 (message "Source buffer has been killed"))
11521 ((not (wholenump (get-text-property (point) 'js2-pos)))
11522 (message "There does not seem to be an error here"))
11523 (t
11524 (let ((pos (get-text-property (point) 'js2-pos))
11525 (msg (get-text-property (point) 'js2-msg)))
11526 (save-selected-window
11527 (pop-to-buffer js2-source-buffer)
11528 (goto-char pos)
11529 (message msg))))))
11530
11531 ;;;###autoload
11532 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11533 "Major mode for editing JavaScript code."
11534 (set (make-local-variable 'max-lisp-eval-depth)
11535 (max max-lisp-eval-depth 3000))
11536 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11537 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11538 (set (make-local-variable 'syntax-propertize-function) nil)
11539 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11540 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11541 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11542 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11543 ;; for characters inside regexp literals.
11544 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11545 ;; this is necessary to make `show-paren-function' work properly
11546 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11547 ;; needed for M-x rgrep, among other things
11548 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11549
11550 (setq font-lock-defaults '(nil t))
11551
11552 ;; Experiment: make reparse-delay longer for longer files.
11553 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11554 (setq js2-idle-timer-delay
11555 (* js2-idle-timer-delay
11556 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11557
11558 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11559 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11560 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11561 (setq next-error-function #'js2-next-error)
11562 (imenu-add-to-menubar (concat "IM-" mode-name))
11563 (add-to-invisibility-spec '(js2-outline . t))
11564 (set (make-local-variable 'line-move-ignore-invisible) t)
11565 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11566 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11567
11568 (setq js2-mode-functions-hidden nil
11569 js2-mode-comments-hidden nil
11570 js2-mode-buffer-dirty-p t
11571 js2-mode-parsing nil)
11572
11573 (js2-set-default-externs)
11574
11575 (when js2-include-jslint-globals
11576 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11577
11578 (run-hooks 'js2-init-hook)
11579
11580 (let ((js2-idle-timer-delay 0))
11581 ;; Schedule parsing for after when the mode hooks run.
11582 (js2-mode-reset-timer)))
11583
11584 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11585 ;; a bit more complicated and it doesn't net us much yet.
11586 ;;;###autoload
11587 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11588 "Major mode for editing JSX code.
11589
11590 To customize the indentation for this mode, set the SGML offset
11591 variables (`sgml-basic-offset' et al) locally, like so:
11592
11593 (defun set-jsx-indentation ()
11594 (setq-local sgml-basic-offset js2-basic-offset))
11595 (add-hook \\='js2-jsx-mode-hook #\\='set-jsx-indentation)"
11596 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11597
11598 (defun js2-mode-exit ()
11599 "Exit `js2-mode' and clean up."
11600 (interactive)
11601 (when js2-mode-node-overlay
11602 (delete-overlay js2-mode-node-overlay)
11603 (setq js2-mode-node-overlay nil))
11604 (js2-remove-overlays)
11605 (setq js2-mode-ast nil)
11606 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11607 (remove-from-invisibility-spec '(js2-outline . t))
11608 (js2-mode-show-all)
11609 (with-silent-modifications
11610 (js2-clear-face (point-min) (point-max))))
11611
11612 (defun js2-mode-reset-timer ()
11613 "Cancel any existing parse timer and schedule a new one."
11614 (if js2-mode-parse-timer
11615 (cancel-timer js2-mode-parse-timer))
11616 (setq js2-mode-parsing nil)
11617 (let ((timer (timer-create)))
11618 (setq js2-mode-parse-timer timer)
11619 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11620 (timer-set-idle-time timer js2-idle-timer-delay)
11621 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11622 (timer-activate-when-idle timer nil)))
11623
11624 (defun js2-mode-idle-reparse (buffer)
11625 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11626 it to be reparsed when the buffer is selected."
11627 (cond ((eq buffer (current-buffer))
11628 (js2-reparse))
11629 ((buffer-live-p buffer)
11630 ;; reparse when the buffer is selected again
11631 (with-current-buffer buffer
11632 (add-hook 'window-configuration-change-hook
11633 #'js2-mode-idle-reparse-inner
11634 nil t)))))
11635
11636 (defun js2-mode-idle-reparse-inner ()
11637 (remove-hook 'window-configuration-change-hook
11638 #'js2-mode-idle-reparse-inner
11639 t)
11640 (js2-reparse))
11641
11642 (defun js2-mode-edit (_beg _end _len)
11643 "Schedule a new parse after buffer is edited.
11644 Buffer edit spans from BEG to END and is of length LEN."
11645 (setq js2-mode-buffer-dirty-p t)
11646 (js2-mode-hide-overlay)
11647 (js2-mode-reset-timer))
11648
11649 (defun js2-minor-mode-edit (_beg _end _len)
11650 "Callback for buffer edits in `js2-mode'.
11651 Schedules a new parse after buffer is edited.
11652 Buffer edit spans from BEG to END and is of length LEN."
11653 (setq js2-mode-buffer-dirty-p t)
11654 (js2-mode-hide-overlay)
11655 (js2-mode-reset-timer))
11656
11657 (defun js2-reparse (&optional force)
11658 "Re-parse current buffer after user finishes some data entry.
11659 If we get any user input while parsing, including cursor motion,
11660 we discard the parse and reschedule it. If FORCE is nil, then the
11661 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11662 (let (time
11663 interrupted-p
11664 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11665 (unless js2-mode-parsing
11666 (setq js2-mode-parsing t)
11667 (unwind-protect
11668 (when (or js2-mode-buffer-dirty-p force)
11669 (js2-remove-overlays)
11670 (setq js2-mode-buffer-dirty-p nil
11671 js2-mode-fontifications nil
11672 js2-mode-deferred-properties nil)
11673 (if js2-mode-verbose-parse-p
11674 (message "parsing..."))
11675 (setq time
11676 (js2-time
11677 (setq interrupted-p
11678 (catch 'interrupted
11679 (js2-parse)
11680 (with-silent-modifications
11681 ;; if parsing is interrupted, comments and regex
11682 ;; literals stay ignored by `parse-partial-sexp'
11683 (remove-text-properties (point-min) (point-max)
11684 '(syntax-table))
11685 (js2-mode-apply-deferred-properties)
11686 (js2-mode-remove-suppressed-warnings)
11687 (js2-mode-show-warnings)
11688 (js2-mode-show-errors)
11689 (if (>= js2-highlight-level 1)
11690 (js2-highlight-jsdoc js2-mode-ast)))
11691 nil))))
11692 (if interrupted-p
11693 (progn
11694 ;; unfinished parse => try again
11695 (setq js2-mode-buffer-dirty-p t)
11696 (js2-mode-reset-timer))
11697 (if js2-mode-verbose-parse-p
11698 (message "Parse time: %s" time))))
11699 (setq js2-mode-parsing nil)
11700 (unless interrupted-p
11701 (setq js2-mode-parse-timer nil))))))
11702
11703 (defun js2-mode-show-node (event)
11704 "Debugging aid: highlight selected AST node on mouse click."
11705 (interactive "e")
11706 (mouse-set-point event)
11707 (setq deactivate-mark t)
11708 (when js2-mode-show-overlay
11709 (let ((node (js2-node-at-point))
11710 beg end)
11711 (if (null node)
11712 (message "No node found at location %s" (point))
11713 (setq beg (js2-node-abs-pos node)
11714 end (+ beg (js2-node-len node)))
11715 (if js2-mode-node-overlay
11716 (move-overlay js2-mode-node-overlay beg end)
11717 (setq js2-mode-node-overlay (make-overlay beg end))
11718 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11719 (with-silent-modifications
11720 (if (fboundp 'cursor-sensor-mode)
11721 (put-text-property beg end 'cursor-sensor-functions
11722 '(js2-mode-hide-overlay))
11723 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11724 (message "%s, parent: %s"
11725 (js2-node-short-name node)
11726 (if (js2-node-parent node)
11727 (js2-node-short-name (js2-node-parent node))
11728 "nil"))))))
11729
11730 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11731 "Remove the debugging overlay when point moves.
11732 ARG1, ARG2 and ARG3 have different values depending on whether this function
11733 was found on `point-left' or in `cursor-sensor-functions'."
11734 (when js2-mode-node-overlay
11735 (let ((beg (overlay-start js2-mode-node-overlay))
11736 (end (overlay-end js2-mode-node-overlay))
11737 (p2 (if (windowp arg1)
11738 ;; Called from cursor-sensor-functions.
11739 (window-point arg1)
11740 ;; Called from point-left.
11741 arg2)))
11742 ;; Sometimes we're called spuriously.
11743 (unless (and p2
11744 (>= p2 beg)
11745 (<= p2 end))
11746 (with-silent-modifications
11747 (remove-text-properties beg end
11748 '(point-left nil cursor-sensor-functions)))
11749 (delete-overlay js2-mode-node-overlay)
11750 (setq js2-mode-node-overlay nil)))))
11751
11752 (defun js2-mode-reset ()
11753 "Debugging helper: reset everything."
11754 (interactive)
11755 (js2-mode-exit)
11756 (js2-mode))
11757
11758 (defun js2-mode-show-warn-or-err (e face)
11759 "Highlight a warning or error E with FACE.
11760 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11761 The last element is optional. When present, use instead of FACE."
11762 (let* ((key (cl-first e))
11763 (beg (cl-second e))
11764 (end (+ beg (cl-third e)))
11765 ;; Don't inadvertently go out of bounds.
11766 (beg (max (point-min) (min beg (point-max))))
11767 (end (max (point-min) (min end (point-max))))
11768 (ovl (make-overlay beg end)))
11769 ;; FIXME: Why a mix of overlays and text-properties?
11770 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11771 (overlay-put ovl 'js2-error t)
11772 (put-text-property beg end 'help-echo (js2-get-msg key))
11773 (if (fboundp 'cursor-sensor-mode)
11774 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11775 (put-text-property beg end 'point-entered #'js2-echo-error))))
11776
11777 (defun js2-remove-overlays ()
11778 "Remove overlays from buffer that have a `js2-error' property."
11779 (let ((beg (point-min))
11780 (end (point-max)))
11781 (save-excursion
11782 (dolist (o (overlays-in beg end))
11783 (when (overlay-get o 'js2-error)
11784 (delete-overlay o))))))
11785
11786 (defun js2-mode-apply-deferred-properties ()
11787 "Apply fontifications and other text properties recorded during parsing."
11788 (when (cl-plusp js2-highlight-level)
11789 ;; We defer clearing faces as long as possible to eliminate flashing.
11790 (js2-clear-face (point-min) (point-max))
11791 ;; Have to reverse the recorded fontifications list so that errors
11792 ;; and warnings overwrite the normal fontifications.
11793 (dolist (f (nreverse js2-mode-fontifications))
11794 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11795 (setq js2-mode-fontifications nil))
11796 (dolist (p js2-mode-deferred-properties)
11797 (apply #'put-text-property p))
11798 (setq js2-mode-deferred-properties nil))
11799
11800 (defun js2-mode-show-errors ()
11801 "Highlight syntax errors."
11802 (when js2-mode-show-parse-errors
11803 (dolist (e (js2-ast-root-errors js2-mode-ast))
11804 (js2-mode-show-warn-or-err e 'js2-error))))
11805
11806 (defun js2-mode-remove-suppressed-warnings ()
11807 "Take suppressed warnings out of the AST warnings list.
11808 This ensures that the counts and `next-error' are correct."
11809 (setf (js2-ast-root-warnings js2-mode-ast)
11810 (js2-delete-if
11811 (lambda (e)
11812 (let ((key (caar e)))
11813 (or
11814 (and (not js2-strict-trailing-comma-warning)
11815 (string-match "trailing\\.comma" key))
11816 (and (not js2-strict-cond-assign-warning)
11817 (string= key "msg.equal.as.assign"))
11818 (and js2-missing-semi-one-line-override
11819 (string= key "msg.missing.semi")
11820 (let* ((beg (cl-second e))
11821 (node (js2-node-at-point beg))
11822 (fn (js2-mode-find-parent-fn node))
11823 (body (and fn (js2-function-node-body fn)))
11824 (lc (and body (js2-node-abs-pos body)))
11825 (rc (and lc (+ lc (js2-node-len body)))))
11826 (and fn
11827 (or (null body)
11828 (save-excursion
11829 (goto-char beg)
11830 (and (js2-same-line lc)
11831 (js2-same-line rc))))))))))
11832 (js2-ast-root-warnings js2-mode-ast))))
11833
11834 (defun js2-mode-show-warnings ()
11835 "Highlight strict-mode warnings."
11836 (when js2-mode-show-strict-warnings
11837 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11838 (js2-mode-show-warn-or-err e 'js2-warning))))
11839
11840 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11841 "Called by point-motion hooks.
11842 ARG1, ARG2 and ARG3 have different values depending on whether this function
11843 was found on `point-entered' or in `cursor-sensor-functions'."
11844 (let* ((new-point (if (windowp arg1)
11845 ;; Called from cursor-sensor-functions.
11846 (window-point arg1)
11847 ;; Called from point-left.
11848 arg2))
11849 (msg (get-text-property new-point 'help-echo)))
11850 (when (and (stringp msg)
11851 (not (active-minibuffer-window))
11852 (not (current-message)))
11853 (message msg))))
11854
11855 (defun js2-line-break (&optional _soft)
11856 "Break line at point and indent, continuing comment if within one.
11857 If inside a string, and `js2-concat-multiline-strings' is not
11858 nil, turn it into concatenation."
11859 (interactive)
11860 (let ((parse-status (syntax-ppss)))
11861 (cond
11862 ;; Check if we're inside a string.
11863 ((nth 3 parse-status)
11864 (if js2-concat-multiline-strings
11865 (js2-mode-split-string parse-status)
11866 (insert "\n")))
11867 ;; Check if inside a block comment.
11868 ((nth 4 parse-status)
11869 (js2-mode-extend-comment (nth 8 parse-status)))
11870 (t
11871 (newline-and-indent)))))
11872
11873 (defun js2-mode-split-string (parse-status)
11874 "Turn a newline in mid-string into a string concatenation.
11875 PARSE-STATUS is as documented in `parse-partial-sexp'."
11876 (let* ((quote-char (nth 3 parse-status))
11877 (at-eol (eq js2-concat-multiline-strings 'eol)))
11878 (insert quote-char)
11879 (insert (if at-eol " +\n" "\n"))
11880 (unless at-eol
11881 (insert "+ "))
11882 (js2-indent-line)
11883 (insert quote-char)
11884 (when (eolp)
11885 (insert quote-char)
11886 (backward-char 1))))
11887
11888 (defun js2-mode-extend-comment (start-pos)
11889 "Indent the line and, when inside a comment block, add comment prefix."
11890 (let (star single col first-line needs-close)
11891 (save-excursion
11892 (back-to-indentation)
11893 (when (< (point) start-pos)
11894 (goto-char start-pos))
11895 (cond
11896 ((looking-at "\\*[^/]")
11897 (setq star t
11898 col (current-column)))
11899 ((looking-at "/\\*")
11900 (setq star t
11901 first-line t
11902 col (1+ (current-column))))
11903 ((looking-at "//")
11904 (setq single t
11905 col (current-column)))))
11906 ;; Heuristic for whether we need to close the comment:
11907 ;; if we've got a parse error here, assume it's an unterminated
11908 ;; comment.
11909 (setq needs-close
11910 (or
11911 (get-char-property (1- (point)) 'js2-error)
11912 ;; The heuristic above doesn't work well when we're
11913 ;; creating a comment and there's another one downstream,
11914 ;; as our parser thinks this one ends at the end of the
11915 ;; next one. (You can have a /* inside a js block comment.)
11916 ;; So just close it if the next non-ws char isn't a *.
11917 (and first-line
11918 (eolp)
11919 (save-excursion
11920 (skip-chars-forward " \t\r\n")
11921 (not (eq (char-after) ?*))))))
11922 (delete-horizontal-space)
11923 (insert "\n")
11924 (cond
11925 (star
11926 (indent-to col)
11927 (insert "* ")
11928 (if (and first-line needs-close)
11929 (save-excursion
11930 (insert "\n")
11931 (indent-to col)
11932 (insert "*/"))))
11933 (single
11934 (indent-to col)
11935 (insert "// ")))
11936 ;; Don't need to extend the comment after all.
11937 (js2-indent-line)))
11938
11939 (defun js2-beginning-of-line ()
11940 "Toggle point between bol and first non-whitespace char in line.
11941 Also moves past comment delimiters when inside comments."
11942 (interactive)
11943 (let (node)
11944 (cond
11945 ((bolp)
11946 (back-to-indentation))
11947 ((looking-at "//")
11948 (skip-chars-forward "/ \t"))
11949 ((and (eq (char-after) ?*)
11950 (setq node (js2-comment-at-point))
11951 (memq (js2-comment-node-format node) '(jsdoc block))
11952 (save-excursion
11953 (skip-chars-backward " \t")
11954 (bolp)))
11955 (skip-chars-forward "\* \t"))
11956 (t
11957 (goto-char (point-at-bol))))))
11958
11959 (defun js2-end-of-line ()
11960 "Toggle point between eol and last non-whitespace char in line."
11961 (interactive)
11962 (if (eolp)
11963 (skip-chars-backward " \t")
11964 (goto-char (point-at-eol))))
11965
11966 (defun js2-mode-wait-for-parse (callback)
11967 "Invoke CALLBACK when parsing is finished.
11968 If parsing is already finished, calls CALLBACK immediately."
11969 (if (not js2-mode-buffer-dirty-p)
11970 (funcall callback)
11971 (push callback js2-mode-pending-parse-callbacks)
11972 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11973
11974 (defun js2-mode-parse-finished ()
11975 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11976 ;; We can't let errors propagate up, since it prevents the
11977 ;; `js2-parse' method from completing normally and returning
11978 ;; the ast, which makes things mysteriously not work right.
11979 (unwind-protect
11980 (dolist (cb js2-mode-pending-parse-callbacks)
11981 (condition-case err
11982 (funcall cb)
11983 (error (message "%s" err))))
11984 (setq js2-mode-pending-parse-callbacks nil)))
11985
11986 (defun js2-mode-flag-region (from to flag)
11987 "Hide or show text from FROM to TO, according to FLAG.
11988 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11989 Returns the created overlay if FLAG is non-nil."
11990 (remove-overlays from to 'invisible 'js2-outline)
11991 (when flag
11992 (let ((o (make-overlay from to)))
11993 (overlay-put o 'invisible 'js2-outline)
11994 (overlay-put o 'isearch-open-invisible
11995 'js2-isearch-open-invisible)
11996 o)))
11997
11998 ;; Function to be set as an outline-isearch-open-invisible' property
11999 ;; to the overlay that makes the outline invisible (see
12000 ;; `js2-mode-flag-region').
12001 (defun js2-isearch-open-invisible (_overlay)
12002 ;; We rely on the fact that isearch places point on the matched text.
12003 (js2-mode-show-element))
12004
12005 (defun js2-mode-invisible-overlay-bounds (&optional pos)
12006 "Return cons cell of bounds of folding overlay at POS.
12007 Returns nil if not found."
12008 (let ((overlays (overlays-at (or pos (point))))
12009 o)
12010 (while (and overlays
12011 (not o))
12012 (if (overlay-get (car overlays) 'invisible)
12013 (setq o (car overlays))
12014 (setq overlays (cdr overlays))))
12015 (if o
12016 (cons (overlay-start o) (overlay-end o)))))
12017
12018 (defun js2-mode-function-at-point (&optional pos)
12019 "Return the innermost function node enclosing current point.
12020 Returns nil if point is not in a function."
12021 (let ((node (js2-node-at-point pos)))
12022 (while (and node (not (js2-function-node-p node)))
12023 (setq node (js2-node-parent node)))
12024 (if (js2-function-node-p node)
12025 node)))
12026
12027 (defun js2-mode-toggle-element ()
12028 "Hide or show the foldable element at the point."
12029 (interactive)
12030 (let (comment fn pos)
12031 (save-excursion
12032 (cond
12033 ;; /* ... */ comment?
12034 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
12035 (if (js2-mode-invisible-overlay-bounds
12036 (setq pos (+ 3 (js2-node-abs-pos comment))))
12037 (progn
12038 (goto-char pos)
12039 (js2-mode-show-element))
12040 (js2-mode-hide-element)))
12041 ;; //-comment?
12042 ((save-excursion
12043 (back-to-indentation)
12044 (looking-at js2-mode-//-comment-re))
12045 (js2-mode-toggle-//-comment))
12046 ;; function?
12047 ((setq fn (js2-mode-function-at-point))
12048 (setq pos (and (js2-function-node-body fn)
12049 (js2-node-abs-pos (js2-function-node-body fn))))
12050 (goto-char (1+ pos))
12051 (if (js2-mode-invisible-overlay-bounds)
12052 (js2-mode-show-element)
12053 (js2-mode-hide-element)))
12054 (t
12055 (message "Nothing at point to hide or show"))))))
12056
12057 (defun js2-mode-hide-element ()
12058 "Fold/hide contents of a block, showing ellipses.
12059 Show the hidden text with \\[js2-mode-show-element]."
12060 (interactive)
12061 (if js2-mode-buffer-dirty-p
12062 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12063 (let (node body beg end)
12064 (cond
12065 ((js2-mode-invisible-overlay-bounds)
12066 (message "already hidden"))
12067 (t
12068 (setq node (js2-node-at-point))
12069 (cond
12070 ((js2-block-comment-p node)
12071 (js2-mode-hide-comment node))
12072 (t
12073 (while (and node (not (js2-function-node-p node)))
12074 (setq node (js2-node-parent node)))
12075 (if (and node
12076 (setq body (js2-function-node-body node)))
12077 (progn
12078 (setq beg (js2-node-abs-pos body)
12079 end (+ beg (js2-node-len body)))
12080 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12081 (message "No collapsable element found at point"))))))))
12082
12083 (defun js2-mode-show-element ()
12084 "Show the hidden element at current point."
12085 (interactive)
12086 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12087 (if bounds
12088 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12089 (message "Nothing to un-hide"))))
12090
12091 (defun js2-mode-show-all ()
12092 "Show all of the text in the buffer."
12093 (interactive)
12094 (js2-mode-flag-region (point-min) (point-max) nil))
12095
12096 (defun js2-mode-toggle-hide-functions ()
12097 (interactive)
12098 (if js2-mode-functions-hidden
12099 (js2-mode-show-functions)
12100 (js2-mode-hide-functions)))
12101
12102 (defun js2-mode-hide-functions ()
12103 "Hides all non-nested function bodies in the buffer.
12104 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12105 to open an individual entry."
12106 (interactive)
12107 (if js2-mode-buffer-dirty-p
12108 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12109 (if (null js2-mode-ast)
12110 (message "Oops - parsing failed")
12111 (setq js2-mode-functions-hidden t)
12112 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12113
12114 (defun js2-mode-function-hider (n endp)
12115 (when (not endp)
12116 (let ((tt (js2-node-type n))
12117 body beg end)
12118 (cond
12119 ((and (= tt js2-FUNCTION)
12120 (setq body (js2-function-node-body n)))
12121 (setq beg (js2-node-abs-pos body)
12122 end (+ beg (js2-node-len body)))
12123 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12124 nil) ; don't process children of function
12125 (t
12126 t))))) ; keep processing other AST nodes
12127
12128 (defun js2-mode-show-functions ()
12129 "Un-hide any folded function bodies in the buffer."
12130 (interactive)
12131 (setq js2-mode-functions-hidden nil)
12132 (save-excursion
12133 (goto-char (point-min))
12134 (while (/= (goto-char (next-overlay-change (point)))
12135 (point-max))
12136 (dolist (o (overlays-at (point)))
12137 (when (and (overlay-get o 'invisible)
12138 (not (overlay-get o 'comment)))
12139 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12140
12141 (defun js2-mode-hide-comment (n)
12142 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12143 3 ; /**
12144 2)) ; /*
12145 (beg (+ (js2-node-abs-pos n) head))
12146 (end (- (+ beg (js2-node-len n)) head 2))
12147 (o (js2-mode-flag-region beg end 'hide)))
12148 (overlay-put o 'comment t)))
12149
12150 (defun js2-mode-toggle-hide-comments ()
12151 "Folds all block comments in the buffer.
12152 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12153 to open an individual entry."
12154 (interactive)
12155 (if js2-mode-comments-hidden
12156 (js2-mode-show-comments)
12157 (js2-mode-hide-comments)))
12158
12159 (defun js2-mode-hide-comments ()
12160 (interactive)
12161 (if js2-mode-buffer-dirty-p
12162 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12163 (if (null js2-mode-ast)
12164 (message "Oops - parsing failed")
12165 (setq js2-mode-comments-hidden t)
12166 (dolist (n (js2-ast-root-comments js2-mode-ast))
12167 (when (js2-block-comment-p n)
12168 (js2-mode-hide-comment n)))
12169 (js2-mode-hide-//-comments)))
12170
12171 (defun js2-mode-extend-//-comment (direction)
12172 "Find start or end of a block of similar //-comment lines.
12173 DIRECTION is -1 to look back, 1 to look forward.
12174 INDENT is the indentation level to match.
12175 Returns the end-of-line position of the furthest adjacent
12176 //-comment line with the same indentation as the current line.
12177 If there is no such matching line, returns current end of line."
12178 (let ((pos (point-at-eol))
12179 (indent (current-indentation)))
12180 (save-excursion
12181 (while (and (zerop (forward-line direction))
12182 (looking-at js2-mode-//-comment-re)
12183 (eq indent (length (match-string 1))))
12184 (setq pos (point-at-eol)))
12185 pos)))
12186
12187 (defun js2-mode-hide-//-comments ()
12188 "Fold adjacent 1-line comments, showing only snippet of first one."
12189 (let (beg end)
12190 (save-excursion
12191 (goto-char (point-min))
12192 (while (re-search-forward js2-mode-//-comment-re nil t)
12193 (setq beg (point)
12194 end (js2-mode-extend-//-comment 1))
12195 (unless (eq beg end)
12196 (overlay-put (js2-mode-flag-region beg end 'hide)
12197 'comment t))
12198 (goto-char end)
12199 (forward-char 1)))))
12200
12201 (defun js2-mode-toggle-//-comment ()
12202 "Fold or un-fold any multi-line //-comment at point.
12203 Caller should have determined that this line starts with a //-comment."
12204 (let* ((beg (point-at-eol))
12205 (end beg))
12206 (save-excursion
12207 (goto-char end)
12208 (if (js2-mode-invisible-overlay-bounds)
12209 (js2-mode-show-element)
12210 ;; else hide the comment
12211 (setq beg (js2-mode-extend-//-comment -1)
12212 end (js2-mode-extend-//-comment 1))
12213 (unless (eq beg end)
12214 (overlay-put (js2-mode-flag-region beg end 'hide)
12215 'comment t))))))
12216
12217 (defun js2-mode-show-comments ()
12218 "Un-hide any hidden comments, leaving other hidden elements alone."
12219 (interactive)
12220 (setq js2-mode-comments-hidden nil)
12221 (save-excursion
12222 (goto-char (point-min))
12223 (while (/= (goto-char (next-overlay-change (point)))
12224 (point-max))
12225 (dolist (o (overlays-at (point)))
12226 (when (overlay-get o 'comment)
12227 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12228
12229 (defun js2-mode-display-warnings-and-errors ()
12230 "Turn on display of warnings and errors."
12231 (interactive)
12232 (setq js2-mode-show-parse-errors t
12233 js2-mode-show-strict-warnings t)
12234 (js2-reparse 'force))
12235
12236 (defun js2-mode-hide-warnings-and-errors ()
12237 "Turn off display of warnings and errors."
12238 (interactive)
12239 (setq js2-mode-show-parse-errors nil
12240 js2-mode-show-strict-warnings nil)
12241 (js2-reparse 'force))
12242
12243 (defun js2-mode-toggle-warnings-and-errors ()
12244 "Toggle the display of warnings and errors.
12245 Some users don't like having warnings/errors reported while they type."
12246 (interactive)
12247 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12248 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12249 (if (called-interactively-p 'any)
12250 (message "warnings and errors %s"
12251 (if js2-mode-show-parse-errors
12252 "enabled"
12253 "disabled")))
12254 (js2-reparse 'force))
12255
12256 (defun js2-mode-customize ()
12257 (interactive)
12258 (customize-group 'js2-mode))
12259
12260 (defun js2-mode-forward-sexp (&optional arg)
12261 "Move forward across one statement or balanced expression.
12262 With ARG, do it that many times. Negative arg -N means
12263 move backward across N balanced expressions."
12264 (interactive "p")
12265 (setq arg (or arg 1))
12266 (save-restriction
12267 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12268 (js2-reparse)
12269 (let (forward-sexp-function
12270 node (start (point)) pos lp rp child)
12271 (cond
12272 ;; backward-sexp
12273 ;; could probably make this better for some cases:
12274 ;; - if in statement block (e.g. function body), go to parent
12275 ;; - infix exprs like (foo in bar) - maybe go to beginning
12276 ;; of infix expr if in the right-side expression?
12277 ((and arg (cl-minusp arg))
12278 (dotimes (_ (- arg))
12279 (js2-backward-sws)
12280 (forward-char -1) ; Enter the node we backed up to.
12281 (when (setq node (js2-node-at-point (point) t))
12282 (setq pos (js2-node-abs-pos node))
12283 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12284 (setq lp (car parens)
12285 rp (cdr parens)))
12286 (when (and lp (> start lp))
12287 (if (and rp (<= start rp))
12288 ;; Between parens, check if there's a child node we can jump.
12289 (when (setq child (js2-node-closest-child node (point) lp t))
12290 (setq pos (js2-node-abs-pos child)))
12291 ;; Before both parens.
12292 (setq pos lp)))
12293 (let ((state (parse-partial-sexp start pos)))
12294 (goto-char (if (not (zerop (car state)))
12295 ;; Stumble at the unbalanced paren if < 0, or
12296 ;; jump a bit further if > 0.
12297 (scan-sexps start -1)
12298 pos))))
12299 (unless pos (goto-char (point-min)))))
12300 (t
12301 ;; forward-sexp
12302 (dotimes (_ arg)
12303 (js2-forward-sws)
12304 (when (setq node (js2-node-at-point (point) t))
12305 (setq pos (js2-node-abs-pos node))
12306 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12307 (setq lp (car parens)
12308 rp (cdr parens)))
12309 (or
12310 (when (and rp (<= start rp))
12311 (if (> start lp)
12312 (when (setq child (js2-node-closest-child node (point) rp))
12313 (setq pos (js2-node-abs-end child)))
12314 (setq pos (1+ rp))))
12315 ;; No parens or child nodes, looks for the end of the current node.
12316 (cl-incf pos (js2-node-len
12317 (if (js2-expr-stmt-node-p (js2-node-parent node))
12318 ;; Stop after the semicolon.
12319 (js2-node-parent node)
12320 node))))
12321 (let ((state (save-excursion (parse-partial-sexp start pos))))
12322 (goto-char (if (not (zerop (car state)))
12323 (scan-sexps start 1)
12324 pos))))
12325 (unless pos (goto-char (point-max)))))))))
12326
12327 (defun js2-mode-forward-sexp-parens (node abs-pos)
12328 "Return a cons cell with positions of main parens in NODE."
12329 (cond
12330 ((or (js2-array-node-p node)
12331 (js2-object-node-p node)
12332 (js2-comp-node-p node)
12333 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12334 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12335 ((js2-paren-expr-node-p node)
12336 (let ((lp (js2-node-lp node))
12337 (rp (js2-node-rp node)))
12338 (cons (when lp (+ abs-pos lp))
12339 (when rp (+ abs-pos rp)))))))
12340
12341 (defun js2-node-closest-child (parent point limit &optional before)
12342 (let* ((parent-pos (js2-node-abs-pos parent))
12343 (rpoint (- point parent-pos))
12344 (rlimit (- limit parent-pos))
12345 (min (min rpoint rlimit))
12346 (max (max rpoint rlimit))
12347 found)
12348 (catch 'done
12349 (js2-visit-ast
12350 parent
12351 (lambda (node _end-p)
12352 (if (eq node parent)
12353 t
12354 (let ((pos (js2-node-pos node)) ;; Both relative values.
12355 (end (+ (js2-node-pos node) (js2-node-len node))))
12356 (when (and (>= pos min) (<= end max)
12357 (if before (< pos rpoint) (> end rpoint)))
12358 (setq found node))
12359 (when (> end rpoint)
12360 (throw 'done nil)))
12361 nil))))
12362 found))
12363
12364 (defun js2-errors ()
12365 "Return a list of errors found."
12366 (and js2-mode-ast
12367 (js2-ast-root-errors js2-mode-ast)))
12368
12369 (defun js2-warnings ()
12370 "Return a list of warnings found."
12371 (and js2-mode-ast
12372 (js2-ast-root-warnings js2-mode-ast)))
12373
12374 (defun js2-have-errors-p ()
12375 "Return non-nil if any parse errors or warnings were found."
12376 (or (js2-errors) (js2-warnings)))
12377
12378 (defun js2-errors-and-warnings ()
12379 "Return a copy of the concatenated errors and warnings lists.
12380 They are appended: first the errors, then the warnings.
12381 Entries are of the form (MSG BEG END)."
12382 (when js2-mode-ast
12383 (append (js2-ast-root-errors js2-mode-ast)
12384 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12385
12386 (defun js2-next-error (&optional arg reset)
12387 "Move to next parse error.
12388 Typically invoked via \\[next-error].
12389 ARG is the number of errors, forward or backward, to move.
12390 RESET means start over from the beginning."
12391 (interactive "p")
12392 (if (not (or (js2-errors) (js2-warnings)))
12393 (message "No errors")
12394 (when reset
12395 (goto-char (point-min)))
12396 (let* ((errs (js2-errors-and-warnings))
12397 (continue t)
12398 (start (point))
12399 (count (or arg 1))
12400 (backward (cl-minusp count))
12401 (sorter (if backward '> '<))
12402 (stopper (if backward '< '>))
12403 (count (abs count))
12404 all-errs err)
12405 ;; Sort by start position.
12406 (setq errs (sort errs (lambda (e1 e2)
12407 (funcall sorter (cl-second e1) (cl-second e2))))
12408 all-errs errs)
12409 ;; Find nth error with pos > start.
12410 (while (and errs continue)
12411 (when (funcall stopper (cl-cadar errs) start)
12412 (setq err (car errs))
12413 (if (zerop (cl-decf count))
12414 (setq continue nil)))
12415 (setq errs (cdr errs)))
12416 ;; Clear for `js2-echo-error'.
12417 (message nil)
12418 (if err
12419 (goto-char (cl-second err))
12420 ;; Wrap around to first error.
12421 (goto-char (cl-second (car all-errs)))
12422 ;; If we were already on it, echo msg again.
12423 (if (= (point) start)
12424 (js2-echo-error (point) (point)))))))
12425
12426 (defun js2-down-mouse-3 ()
12427 "Make right-click move the point to the click location.
12428 This makes right-click context menu operations a bit more intuitive.
12429 The point will not move if the region is active, however, to avoid
12430 destroying the region selection."
12431 (interactive)
12432 (when (and js2-move-point-on-right-click
12433 (not mark-active))
12434 (let ((e last-input-event))
12435 (ignore-errors
12436 (goto-char (cl-cadadr e))))))
12437
12438 (defun js2-mode-create-imenu-index ()
12439 "Return an alist for `imenu--index-alist'."
12440 ;; This is built up in `js2-parse-record-imenu' during parsing.
12441 (when js2-mode-ast
12442 ;; if we have an ast but no recorder, they're requesting a rescan
12443 (unless js2-imenu-recorder
12444 (js2-reparse 'force))
12445 (prog1
12446 (js2-build-imenu-index)
12447 (setq js2-imenu-recorder nil
12448 js2-imenu-function-map nil))))
12449
12450 (defun js2-mode-find-tag ()
12451 "Replacement for `find-tag-default'.
12452 `find-tag-default' returns a ridiculous answer inside comments."
12453 (let (beg end)
12454 (save-excursion
12455 (if (looking-at "\\_>")
12456 (setq beg (progn (forward-symbol -1) (point))
12457 end (progn (forward-symbol 1) (point)))
12458 (setq beg (progn (forward-symbol 1) (point))
12459 end (progn (forward-symbol -1) (point))))
12460 (replace-regexp-in-string
12461 "[\"']" ""
12462 (buffer-substring-no-properties beg end)))))
12463
12464 (defun js2-mode-forward-sibling ()
12465 "Move to the end of the sibling following point in parent.
12466 Returns non-nil if successful, or nil if there was no following sibling."
12467 (let* ((node (js2-node-at-point))
12468 (parent (js2-mode-find-enclosing-fn node))
12469 sib)
12470 (when (setq sib (js2-node-find-child-after (point) parent))
12471 (goto-char (+ (js2-node-abs-pos sib)
12472 (js2-node-len sib))))))
12473
12474 (defun js2-mode-backward-sibling ()
12475 "Move to the beginning of the sibling node preceding point in parent.
12476 Parent is defined as the enclosing script or function."
12477 (let* ((node (js2-node-at-point))
12478 (parent (js2-mode-find-enclosing-fn node))
12479 sib)
12480 (when (setq sib (js2-node-find-child-before (point) parent))
12481 (goto-char (js2-node-abs-pos sib)))))
12482
12483 (defun js2-beginning-of-defun (&optional arg)
12484 "Go to line on which current function starts, and return t on success.
12485 If we're not in a function or already at the beginning of one, go
12486 to beginning of previous script-level element.
12487 With ARG N, do that N times. If N is negative, move forward."
12488 (setq arg (or arg 1))
12489 (if (cl-plusp arg)
12490 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12491 (when (cond
12492 ((js2-function-node-p parent)
12493 (goto-char (js2-node-abs-pos parent)))
12494 (t
12495 (js2-mode-backward-sibling)))
12496 (if (> arg 1)
12497 (js2-beginning-of-defun (1- arg))
12498 t)))
12499 (when (js2-end-of-defun)
12500 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12501
12502 (defun js2-end-of-defun ()
12503 "Go to the char after the last position of the current function
12504 or script-level element."
12505 (let* ((node (js2-node-at-point))
12506 (parent (or (and (js2-function-node-p node) node)
12507 (js2-node-parent-script-or-fn node)))
12508 script)
12509 (unless (js2-function-node-p parent)
12510 ;; Use current script-level node, or, if none, the next one.
12511 (setq script (or parent node)
12512 parent (js2-node-find-child-before (point) script))
12513 (when (or (null parent)
12514 (>= (point) (+ (js2-node-abs-pos parent)
12515 (js2-node-len parent))))
12516 (setq parent (js2-node-find-child-after (point) script))))
12517 (when parent
12518 (goto-char (+ (js2-node-abs-pos parent)
12519 (js2-node-len parent))))))
12520
12521 (defun js2-mark-defun (&optional allow-extend)
12522 "Put mark at end of this function, point at beginning.
12523 The function marked is the one that contains point.
12524
12525 Interactively, if this command is repeated,
12526 or (in Transient Mark mode) if the mark is active,
12527 it marks the next defun after the ones already marked."
12528 (interactive "p")
12529 (let (extended)
12530 (when (and allow-extend
12531 (or (and (eq last-command this-command) (mark t))
12532 (and transient-mark-mode mark-active)))
12533 (let ((sib (save-excursion
12534 (goto-char (mark))
12535 (if (js2-mode-forward-sibling)
12536 (point)))))
12537 (if sib
12538 (progn
12539 (set-mark sib)
12540 (setq extended t))
12541 ;; no more siblings - try extending to enclosing node
12542 (goto-char (mark t)))))
12543 (when (not extended)
12544 (let ((node (js2-node-at-point (point) t)) ; skip comments
12545 ast fn stmt parent beg end)
12546 (when (js2-ast-root-p node)
12547 (setq ast node
12548 node (or (js2-node-find-child-after (point) node)
12549 (js2-node-find-child-before (point) node))))
12550 ;; only mark whole buffer if we can't find any children
12551 (if (null node)
12552 (setq node ast))
12553 (if (js2-function-node-p node)
12554 (setq parent node)
12555 (setq fn (js2-mode-find-enclosing-fn node)
12556 stmt (if (or (null fn)
12557 (js2-ast-root-p fn))
12558 (js2-mode-find-first-stmt node))
12559 parent (or stmt fn)))
12560 (setq beg (js2-node-abs-pos parent)
12561 end (+ beg (js2-node-len parent)))
12562 (push-mark beg)
12563 (goto-char end)
12564 (exchange-point-and-mark)))))
12565
12566 (defun js2-narrow-to-defun ()
12567 "Narrow to the function enclosing point."
12568 (interactive)
12569 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12570 (fn (if (js2-script-node-p node)
12571 node
12572 (js2-mode-find-enclosing-fn node)))
12573 (beg (js2-node-abs-pos fn)))
12574 (unless (js2-ast-root-p fn)
12575 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12576
12577 (defun js2-jump-to-definition (&optional arg)
12578 "Jump to the definition of an object's property, variable or function."
12579 (interactive "P")
12580 (if (eval-when-compile (fboundp 'xref-push-marker-stack))
12581 (xref-push-marker-stack)
12582 (ring-insert find-tag-marker-ring (point-marker)))
12583 (js2-reparse)
12584 (let* ((node (js2-node-at-point))
12585 (parent (js2-node-parent node))
12586 (names (if (js2-prop-get-node-p parent)
12587 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12588 (cl-loop for n in temp
12589 with result = '()
12590 do (push n result)
12591 until (equal node n)
12592 finally return result)))))
12593 node-init)
12594 (unless (and (js2-name-node-p node)
12595 (not (js2-var-init-node-p parent))
12596 (not (js2-function-node-p parent)))
12597 (error "Node is not a supported jump node"))
12598 (push (or (and names (pop names))
12599 (unless (and (js2-object-prop-node-p parent)
12600 (eq node (js2-object-prop-node-left parent)))
12601 node)) names)
12602 (setq node-init (js2-search-scope node names))
12603
12604 ;; todo: display list of results in buffer
12605 ;; todo: group found references by buffer
12606 (unless node-init
12607 (switch-to-buffer
12608 (catch 'found
12609 (unless arg
12610 (mapc (lambda (b)
12611 (with-current-buffer b
12612 (when (derived-mode-p 'js2-mode)
12613 (setq node-init (js2-search-scope js2-mode-ast names))
12614 (if node-init
12615 (throw 'found b)))))
12616 (buffer-list)))
12617 nil)))
12618 (setq node-init (if (listp node-init) (car node-init) node-init))
12619 (unless node-init
12620 (pop-tag-mark)
12621 (error "No jump location found"))
12622 (goto-char (js2-node-abs-pos node-init))))
12623
12624 (defun js2-search-object (node name-node)
12625 "Check if object NODE contains element with NAME-NODE."
12626 (cl-assert (js2-object-node-p node))
12627 ;; Only support name-node and nodes for the time being
12628 (cl-loop for elem in (js2-object-node-elems node)
12629 for left = (js2-object-prop-node-left elem)
12630 if (or (and (js2-name-node-p left)
12631 (equal (js2-name-node-name name-node)
12632 (js2-name-node-name left)))
12633 (and (js2-string-node-p left)
12634 (string= (js2-name-node-name name-node)
12635 (js2-string-node-value left))))
12636 return elem))
12637
12638 (defun js2-search-object-for-prop (object prop-names)
12639 "Return node in OBJECT that matches PROP-NAMES or nil.
12640 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12641 i.e. (\\='name\\=' \\='value\\=') = {name : { value: 3}}"
12642 (let (node
12643 (temp-object object)
12644 (temp t) ;temporay node
12645 (names prop-names))
12646 (while (and temp names (js2-object-node-p temp-object))
12647 (setq temp (js2-search-object temp-object (pop names)))
12648 (and (setq node temp)
12649 (setq temp-object (js2-object-prop-node-right temp))))
12650 (unless names node)))
12651
12652 (defun js2-search-scope (node names)
12653 "Searches NODE scope for jump location matching NAMES.
12654 NAMES is a list of property values to search for. For functions
12655 and variables NAMES will contain one element."
12656 (let (node-init
12657 (val (js2-name-node-name (car names))))
12658 (setq node-init (js2-get-symbol-declaration node val))
12659
12660 (when (> (length names) 1)
12661
12662 ;; Check var declarations
12663 (when (and node-init (string= val (js2-name-node-name node-init)))
12664 (let ((parent (js2-node-parent node-init))
12665 (temp-names names))
12666 (pop temp-names) ;; First element is var name
12667 (setq node-init (when (js2-var-init-node-p parent)
12668 (js2-search-object-for-prop
12669 (js2-var-init-node-initializer parent)
12670 temp-names)))))
12671
12672 ;; Check all assign nodes
12673 (js2-visit-ast
12674 js2-mode-ast
12675 (lambda (node endp)
12676 (unless endp
12677 (if (js2-assign-node-p node)
12678 (let ((left (js2-assign-node-left node))
12679 (right (js2-assign-node-right node))
12680 (temp-names names))
12681 (when (js2-prop-get-node-p left)
12682 (let* ((prop-list (js2-compute-nested-prop-get left))
12683 (found (cl-loop for prop in prop-list
12684 until (not (string= (js2-name-node-name
12685 (pop temp-names))
12686 (js2-name-node-name prop)))
12687 if (not temp-names) return prop))
12688 (found-node (or found
12689 (when (js2-object-node-p right)
12690 (js2-search-object-for-prop right
12691 temp-names)))))
12692 (if found-node (push found-node node-init))))))
12693 t))))
12694 node-init))
12695
12696 (defun js2-get-symbol-declaration (node name)
12697 "Find scope for NAME from NODE."
12698 (let ((scope (js2-get-defining-scope
12699 (or (js2-node-get-enclosing-scope node)
12700 node) name)))
12701 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12702
12703 (provide 'js2-mode)
12704
12705 ;;; js2-mode.el ends here