]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Move method type handling to property METHOD_TYPE
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20150909
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; Support for JSX is available via the derived mode `js2-jsx-mode'. If you
64 ;; also want JSX support, use that mode instead:
65
66 ;; (add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
67 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-jsx-mode))
68
69 ;; To customize how it works:
70 ;; M-x customize-group RET js2-mode RET
71
72 ;; Notes:
73
74 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
75 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
76 ;; `js2-mode' current as the EcmaScript language standard evolves.
77
78 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
79 ;; customizable. It is a surprising amount of work to support customizable
80 ;; indentation. The current compromise is that the tab key lets you cycle among
81 ;; various likely indentation points, similar to the behavior of python-mode.
82
83 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
84 ;; and `mumamo', although it could be made to do so with some effort.
85 ;; This means that `js2-mode' is currently only useful for editing JavaScript
86 ;; files, and not for editing JavaScript within <script> tags or templates.
87
88 ;; The project page on GitHub is used for development and issue tracking.
89 ;; The original homepage at Google Code has outdated information and is mostly
90 ;; unmaintained.
91
92 ;;; Code:
93
94 (require 'cl-lib)
95 (require 'imenu)
96 (require 'js)
97 (require 'etags)
98
99 (eval-and-compile
100 (if (version< emacs-version "25.0")
101 (require 'js2-old-indent)
102 (defvaralias 'js2-basic-offset 'js-indent-level nil)
103 (defalias 'js2-proper-indentation 'js--proper-indentation)
104 (defalias 'js2-jsx-indent-line 'js-jsx-indent-line)
105 (defalias 'js2-indent-line 'js-indent-line)
106 (defalias 'js2-re-search-forward 'js--re-search-forward)))
107
108 ;;; Externs (variables presumed to be defined by the host system)
109
110 (defvar js2-ecma-262-externs
111 (mapcar 'symbol-name
112 '(Array Boolean Date Error EvalError Function Infinity JSON
113 Math NaN Number Object RangeError ReferenceError RegExp
114 String SyntaxError TypeError URIError
115 decodeURI decodeURIComponent encodeURI
116 encodeURIComponent escape eval isFinite isNaN
117 parseFloat parseInt undefined unescape))
118 "Ecma-262 externs. Included in `js2-externs' by default.")
119
120 (defvar js2-browser-externs
121 (mapcar 'symbol-name
122 '(;; DOM level 1
123 Attr CDATASection CharacterData Comment DOMException
124 DOMImplementation Document DocumentFragment
125 DocumentType Element Entity EntityReference
126 ExceptionCode NamedNodeMap Node NodeList Notation
127 ProcessingInstruction Text
128
129 ;; DOM level 2
130 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
131 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
132 HTMLBodyElement HTMLButtonElement HTMLCollection
133 HTMLDListElement HTMLDirectoryElement HTMLDivElement
134 HTMLDocument HTMLElement HTMLFieldSetElement
135 HTMLFontElement HTMLFormElement HTMLFrameElement
136 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
137 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
138 HTMLImageElement HTMLInputElement HTMLIsIndexElement
139 HTMLLIElement HTMLLabelElement HTMLLegendElement
140 HTMLLinkElement HTMLMapElement HTMLMenuElement
141 HTMLMetaElement HTMLModElement HTMLOListElement
142 HTMLObjectElement HTMLOptGroupElement
143 HTMLOptionElement HTMLOptionsCollection
144 HTMLParagraphElement HTMLParamElement HTMLPreElement
145 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
146 HTMLStyleElement HTMLTableCaptionElement
147 HTMLTableCellElement HTMLTableColElement
148 HTMLTableElement HTMLTableRowElement
149 HTMLTableSectionElement HTMLTextAreaElement
150 HTMLTitleElement HTMLUListElement
151
152 ;; DOM level 3
153 DOMConfiguration DOMError DOMException
154 DOMImplementationList DOMImplementationSource
155 DOMLocator DOMStringList NameList TypeInfo
156 UserDataHandler
157
158 ;; Window
159 window alert confirm document java navigator prompt screen
160 self top requestAnimationFrame cancelAnimationFrame
161
162 ;; W3C CSS
163 CSSCharsetRule CSSFontFace CSSFontFaceRule
164 CSSImportRule CSSMediaRule CSSPageRule
165 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
166 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
167 CSSValue CSSValueList Counter DOMImplementationCSS
168 DocumentCSS DocumentStyle ElementCSSInlineStyle
169 LinkStyle MediaList RGBColor Rect StyleSheet
170 StyleSheetList ViewCSS
171
172 ;; W3C Event
173 EventListener EventTarget Event DocumentEvent UIEvent
174 MouseEvent MutationEvent KeyboardEvent
175
176 ;; W3C Range
177 DocumentRange Range RangeException
178
179 ;; W3C XML
180 XPathResult XMLHttpRequest
181
182 ;; console object. Provided by at least Chrome and Firefox.
183 console))
184 "Browser externs.
185 You can cause these to be included or excluded with the custom
186 variable `js2-include-browser-externs'.")
187
188 (defvar js2-rhino-externs
189 (mapcar 'symbol-name
190 '(Packages importClass importPackage com org java
191 ;; Global object (shell) externs.
192 defineClass deserialize doctest gc help load
193 loadClass print quit readFile readUrl runCommand seal
194 serialize spawn sync toint32 version))
195 "Mozilla Rhino externs.
196 Set `js2-include-rhino-externs' to t to include them.")
197
198 (defvar js2-node-externs
199 (mapcar 'symbol-name
200 '(__dirname __filename Buffer clearInterval clearTimeout require
201 console exports global module process setInterval setTimeout
202 querystring))
203 "Node.js externs.
204 Set `js2-include-node-externs' to t to include them.")
205
206 (defvar js2-typed-array-externs
207 (mapcar 'symbol-name
208 '(ArrayBuffer Uint8ClampedArray DataView
209 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
210 Float32Array Float64Array))
211 "Khronos typed array externs. Available in most modern browsers and
212 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
213 are enabled, these will also be included.")
214
215 (defvar js2-harmony-externs
216 (mapcar 'symbol-name
217 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
218 "ES6 externs. If `js2-include-browser-externs' is enabled and
219 `js2-language-version' is sufficiently high, these will be included.")
220
221 ;;; Variables
222
223 (defun js2-mark-safe-local (name pred)
224 "Make the variable NAME buffer-local and mark it as safe file-local
225 variable with predicate PRED."
226 (make-variable-buffer-local name)
227 (put name 'safe-local-variable pred))
228
229 (defcustom js2-highlight-level 2
230 "Amount of syntax highlighting to perform.
231 0 or a negative value means none.
232 1 adds basic syntax highlighting.
233 2 adds highlighting of some Ecma built-in properties.
234 3 adds highlighting of many Ecma built-in functions."
235 :group 'js2-mode
236 :type '(choice (const :tag "None" 0)
237 (const :tag "Basic" 1)
238 (const :tag "Include Properties" 2)
239 (const :tag "Include Functions" 3)))
240
241 (defvar js2-mode-dev-mode-p nil
242 "Non-nil if running in development mode. Normally nil.")
243
244 (defgroup js2-mode nil
245 "An improved JavaScript mode."
246 :group 'languages)
247
248 (defcustom js2-idle-timer-delay 0.2
249 "Delay in secs before re-parsing after user makes changes.
250 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
251 :type 'number
252 :group 'js2-mode)
253 (make-variable-buffer-local 'js2-idle-timer-delay)
254
255 (defcustom js2-dynamic-idle-timer-adjust 0
256 "Positive to adjust `js2-idle-timer-delay' based on file size.
257 The idea is that for short files, parsing is faster so we can be
258 more responsive to user edits without interfering with editing.
259 The buffer length in characters (typically bytes) is divided by
260 this value and used to multiply `js2-idle-timer-delay' for the
261 buffer. For example, a 21k file and 10k adjust yields 21k/10k
262 == 2, so js2-idle-timer-delay is multiplied by 2.
263 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
264 `js2-idle-timer-delay' is not dependent on the file size."
265 :type 'number
266 :group 'js2-mode)
267
268 (defcustom js2-concat-multiline-strings t
269 "When non-nil, `js2-line-break' in mid-string will make it a
270 string concatenation. When `eol', the '+' will be inserted at the
271 end of the line, otherwise, at the beginning of the next line."
272 :type '(choice (const t) (const eol) (const nil))
273 :group 'js2-mode)
274
275 (defcustom js2-mode-show-parse-errors t
276 "True to highlight parse errors."
277 :type 'boolean
278 :group 'js2-mode)
279
280 (defcustom js2-mode-show-strict-warnings t
281 "Non-nil to emit Ecma strict-mode warnings.
282 Some of the warnings can be individually disabled by other flags,
283 even if this flag is non-nil."
284 :type 'boolean
285 :group 'js2-mode)
286
287 (defcustom js2-strict-trailing-comma-warning t
288 "Non-nil to warn about trailing commas in array literals.
289 Ecma-262-5.1 allows them, but older versions of IE raise an error."
290 :type 'boolean
291 :group 'js2-mode)
292
293 (defcustom js2-strict-missing-semi-warning t
294 "Non-nil to warn about semicolon auto-insertion after statement.
295 Technically this is legal per Ecma-262, but some style guides disallow
296 depending on it."
297 :type 'boolean
298 :group 'js2-mode)
299
300 (defcustom js2-missing-semi-one-line-override nil
301 "Non-nil to permit missing semicolons in one-line functions.
302 In one-liner functions such as `function identity(x) {return x}'
303 people often omit the semicolon for a cleaner look. If you are
304 such a person, you can suppress the missing-semicolon warning
305 by setting this variable to t."
306 :type 'boolean
307 :group 'js2-mode)
308
309 (defcustom js2-strict-inconsistent-return-warning t
310 "Non-nil to warn about mixing returns with value-returns.
311 It's perfectly legal to have a `return' and a `return foo' in the
312 same function, but it's often an indicator of a bug, and it also
313 interferes with type inference (in systems that support it.)"
314 :type 'boolean
315 :group 'js2-mode)
316
317 (defcustom js2-strict-cond-assign-warning t
318 "Non-nil to warn about expressions like if (a = b).
319 This often should have been '==' instead of '='. If the warning
320 is enabled, you can suppress it on a per-expression basis by
321 parenthesizing the expression, e.g. if ((a = b)) ..."
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-strict-var-redeclaration-warning t
326 "Non-nil to warn about redeclaring variables in a script or function."
327 :type 'boolean
328 :group 'js2-mode)
329
330 (defcustom js2-strict-var-hides-function-arg-warning t
331 "Non-nil to warn about a var decl hiding a function argument."
332 :type 'boolean
333 :group 'js2-mode)
334
335 (defcustom js2-skip-preprocessor-directives nil
336 "Non-nil to treat lines beginning with # as comments.
337 Useful for viewing Mozilla JavaScript source code."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-language-version 200
342 "Configures what JavaScript language version to recognize.
343 Currently versions 150, 160, 170, 180 and 200 are supported,
344 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
345 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
346 yield, and Array comprehensions, and 1.8 adds function closures."
347 :type 'integer
348 :group 'js2-mode)
349
350 (defcustom js2-instanceof-has-side-effects nil
351 "If non-nil, treats the instanceof operator as having side effects.
352 This is useful for xulrunner apps."
353 :type 'boolean
354 :group 'js2-mode)
355
356 (defcustom js2-move-point-on-right-click t
357 "Non-nil to move insertion point when you right-click.
358 This makes right-click context menu behavior a bit more intuitive,
359 since menu operations generally apply to the point. The exception
360 is if there is a region selection, in which case the point does -not-
361 move, so cut/copy/paste can work properly.
362
363 Note that IntelliJ moves the point, and Eclipse leaves it alone,
364 so this behavior is customizable."
365 :group 'js2-mode
366 :type 'boolean)
367
368 (defcustom js2-allow-rhino-new-expr-initializer t
369 "Non-nil to support a Rhino's experimental syntactic construct.
370
371 Rhino supports the ability to follow a `new' expression with an object
372 literal, which is used to set additional properties on the new object
373 after calling its constructor. Syntax:
374
375 new <expr> [ ( arglist ) ] [initializer]
376
377 Hence, this expression:
378
379 new Object {a: 1, b: 2}
380
381 results in an Object with properties a=1 and b=2. This syntax is
382 apparently not configurable in Rhino - it's currently always enabled,
383 as of Rhino version 1.7R2."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-allow-member-expr-as-function-name nil
388 "Non-nil to support experimental Rhino syntax for function names.
389
390 Rhino supports an experimental syntax configured via the Rhino Context
391 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
392
393 function <member-expr> ( [ arg-list ] ) { <body> }
394
395 Where member-expr is a non-parenthesized 'member expression', which
396 is anything at the grammar level of a new-expression or lower, meaning
397 any expression that does not involve infix or unary operators.
398
399 When <member-expr> is not a simple identifier, then it is syntactic
400 sugar for assigning the anonymous function to the <member-expr>. Hence,
401 this code:
402
403 function a.b().c[2] (x, y) { ... }
404
405 is rewritten as:
406
407 a.b().c[2] = function(x, y) {...}
408
409 which doesn't seem particularly useful, but Rhino permits it."
410 :type 'boolean
411 :group 'js2-mode)
412
413 ;; scanner variables
414
415 (defmacro js2-deflocal (name value &optional comment)
416 "Define a buffer-local variable NAME with VALUE and COMMENT."
417 (declare (debug defvar) (doc-string 3))
418 `(progn
419 (defvar ,name ,value ,comment)
420 (make-variable-buffer-local ',name)))
421
422 (defvar js2-EOF_CHAR -1
423 "Represents end of stream. Distinct from js2-EOF token type.")
424
425 ;; I originally used symbols to represent tokens, but Rhino uses
426 ;; ints and then sets various flag bits in them, so ints it is.
427 ;; The upshot is that we need a `js2-' prefix in front of each name.
428 (defvar js2-ERROR -1)
429 (defvar js2-EOF 0)
430 (defvar js2-EOL 1)
431 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
432 (defvar js2-LEAVEWITH 3)
433 (defvar js2-RETURN 4)
434 (defvar js2-GOTO 5)
435 (defvar js2-IFEQ 6)
436 (defvar js2-IFNE 7)
437 (defvar js2-SETNAME 8)
438 (defvar js2-BITOR 9)
439 (defvar js2-BITXOR 10)
440 (defvar js2-BITAND 11)
441 (defvar js2-EQ 12)
442 (defvar js2-NE 13)
443 (defvar js2-LT 14)
444 (defvar js2-LE 15)
445 (defvar js2-GT 16)
446 (defvar js2-GE 17)
447 (defvar js2-LSH 18)
448 (defvar js2-RSH 19)
449 (defvar js2-URSH 20)
450 (defvar js2-ADD 21) ; infix plus
451 (defvar js2-SUB 22) ; infix minus
452 (defvar js2-MUL 23)
453 (defvar js2-DIV 24)
454 (defvar js2-MOD 25)
455 (defvar js2-NOT 26)
456 (defvar js2-BITNOT 27)
457 (defvar js2-POS 28) ; unary plus
458 (defvar js2-NEG 29) ; unary minus
459 (defvar js2-NEW 30)
460 (defvar js2-DELPROP 31)
461 (defvar js2-TYPEOF 32)
462 (defvar js2-GETPROP 33)
463 (defvar js2-GETPROPNOWARN 34)
464 (defvar js2-SETPROP 35)
465 (defvar js2-GETELEM 36)
466 (defvar js2-SETELEM 37)
467 (defvar js2-CALL 38)
468 (defvar js2-NAME 39) ; an identifier
469 (defvar js2-NUMBER 40)
470 (defvar js2-STRING 41)
471 (defvar js2-NULL 42)
472 (defvar js2-THIS 43)
473 (defvar js2-FALSE 44)
474 (defvar js2-TRUE 45)
475 (defvar js2-SHEQ 46) ; shallow equality (===)
476 (defvar js2-SHNE 47) ; shallow inequality (!==)
477 (defvar js2-REGEXP 48)
478 (defvar js2-BINDNAME 49)
479 (defvar js2-THROW 50)
480 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
481 (defvar js2-IN 52)
482 (defvar js2-INSTANCEOF 53)
483 (defvar js2-LOCAL_LOAD 54)
484 (defvar js2-GETVAR 55)
485 (defvar js2-SETVAR 56)
486 (defvar js2-CATCH_SCOPE 57)
487 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
488 (defvar js2-ENUM_INIT_VALUES 59)
489 (defvar js2-ENUM_INIT_ARRAY 60)
490 (defvar js2-ENUM_NEXT 61)
491 (defvar js2-ENUM_ID 62)
492 (defvar js2-THISFN 63)
493 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
494 (defvar js2-ARRAYLIT 65) ; array literal
495 (defvar js2-OBJECTLIT 66) ; object literal
496 (defvar js2-GET_REF 67) ; *reference
497 (defvar js2-SET_REF 68) ; *reference = something
498 (defvar js2-DEL_REF 69) ; delete reference
499 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
500 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
501 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
502
503 ;; XML support
504 (defvar js2-DEFAULTNAMESPACE 73)
505 (defvar js2-ESCXMLATTR 74)
506 (defvar js2-ESCXMLTEXT 75)
507 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
508 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
509 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
510 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
511
512 (defvar js2-first-bytecode js2-ENTERWITH)
513 (defvar js2-last-bytecode js2-REF_NS_NAME)
514
515 (defvar js2-TRY 80)
516 (defvar js2-SEMI 81) ; semicolon
517 (defvar js2-LB 82) ; left and right brackets
518 (defvar js2-RB 83)
519 (defvar js2-LC 84) ; left and right curly-braces
520 (defvar js2-RC 85)
521 (defvar js2-LP 86) ; left and right parens
522 (defvar js2-RP 87)
523 (defvar js2-COMMA 88) ; comma operator
524
525 (defvar js2-ASSIGN 89) ; simple assignment (=)
526 (defvar js2-ASSIGN_BITOR 90) ; |=
527 (defvar js2-ASSIGN_BITXOR 91) ; ^=
528 (defvar js2-ASSIGN_BITAND 92) ; &=
529 (defvar js2-ASSIGN_LSH 93) ; <<=
530 (defvar js2-ASSIGN_RSH 94) ; >>=
531 (defvar js2-ASSIGN_URSH 95) ; >>>=
532 (defvar js2-ASSIGN_ADD 96) ; +=
533 (defvar js2-ASSIGN_SUB 97) ; -=
534 (defvar js2-ASSIGN_MUL 98) ; *=
535 (defvar js2-ASSIGN_DIV 99) ; /=
536 (defvar js2-ASSIGN_MOD 100) ; %=
537
538 (defvar js2-first-assign js2-ASSIGN)
539 (defvar js2-last-assign js2-ASSIGN_MOD)
540
541 (defvar js2-HOOK 101) ; conditional (?:)
542 (defvar js2-COLON 102)
543 (defvar js2-OR 103) ; logical or (||)
544 (defvar js2-AND 104) ; logical and (&&)
545 (defvar js2-INC 105) ; increment/decrement (++ --)
546 (defvar js2-DEC 106)
547 (defvar js2-DOT 107) ; member operator (.)
548 (defvar js2-FUNCTION 108) ; function keyword
549 (defvar js2-EXPORT 109) ; export keyword
550 (defvar js2-IMPORT 110) ; import keyword
551 (defvar js2-IF 111) ; if keyword
552 (defvar js2-ELSE 112) ; else keyword
553 (defvar js2-SWITCH 113) ; switch keyword
554 (defvar js2-CASE 114) ; case keyword
555 (defvar js2-DEFAULT 115) ; default keyword
556 (defvar js2-WHILE 116) ; while keyword
557 (defvar js2-DO 117) ; do keyword
558 (defvar js2-FOR 118) ; for keyword
559 (defvar js2-BREAK 119) ; break keyword
560 (defvar js2-CONTINUE 120) ; continue keyword
561 (defvar js2-VAR 121) ; var keyword
562 (defvar js2-WITH 122) ; with keyword
563 (defvar js2-CATCH 123) ; catch keyword
564 (defvar js2-FINALLY 124) ; finally keyword
565 (defvar js2-VOID 125) ; void keyword
566 (defvar js2-RESERVED 126) ; reserved keywords
567
568 (defvar js2-EMPTY 127)
569
570 ;; Types used for the parse tree - never returned by scanner.
571
572 (defvar js2-BLOCK 128) ; statement block
573 (defvar js2-LABEL 129) ; label
574 (defvar js2-TARGET 130)
575 (defvar js2-LOOP 131)
576 (defvar js2-EXPR_VOID 132) ; expression statement in functions
577 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
578 (defvar js2-JSR 134)
579 (defvar js2-SCRIPT 135) ; top-level node for entire script
580 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
581 (defvar js2-USE_STACK 137)
582 (defvar js2-SETPROP_OP 138) ; x.y op= something
583 (defvar js2-SETELEM_OP 139) ; x[y] op= something
584 (defvar js2-LOCAL_BLOCK 140)
585 (defvar js2-SET_REF_OP 141) ; *reference op= something
586
587 ;; For XML support:
588 (defvar js2-DOTDOT 142) ; member operator (..)
589 (defvar js2-COLONCOLON 143) ; namespace::name
590 (defvar js2-XML 144) ; XML type
591 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
592 (defvar js2-XMLATTR 146) ; @
593 (defvar js2-XMLEND 147)
594
595 ;; Optimizer-only tokens
596 (defvar js2-TO_OBJECT 148)
597 (defvar js2-TO_DOUBLE 149)
598
599 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
600 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
601 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
602 (defvar js2-CONST 153)
603 (defvar js2-SETCONST 154)
604 (defvar js2-SETCONSTVAR 155)
605 (defvar js2-ARRAYCOMP 156)
606 (defvar js2-LETEXPR 157)
607 (defvar js2-WITHEXPR 158)
608 (defvar js2-DEBUGGER 159)
609
610 (defvar js2-COMMENT 160)
611 (defvar js2-TRIPLEDOT 161) ; for rest parameter
612 (defvar js2-ARROW 162) ; function arrow (=>)
613 (defvar js2-CLASS 163)
614 (defvar js2-EXTENDS 164)
615 (defvar js2-SUPER 165)
616 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
617 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
618 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
619
620 (defvar js2-AWAIT 169) ; await (pseudo keyword)
621
622 (defconst js2-num-tokens (1+ js2-AWAIT))
623
624 (defconst js2-debug-print-trees nil)
625
626 ;; Rhino accepts any string or stream as input. Emacs character
627 ;; processing works best in buffers, so we'll assume the input is a
628 ;; buffer. JavaScript strings can be copied into temp buffers before
629 ;; scanning them.
630
631 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
632 ;; They're the Emacs equivalent of instance variables, more or less.
633
634 (js2-deflocal js2-ts-dirty-line nil
635 "Token stream buffer-local variable.
636 Indicates stuff other than whitespace since start of line.")
637
638 (js2-deflocal js2-ts-hit-eof nil
639 "Token stream buffer-local variable.")
640
641 ;; FIXME: Unused.
642 (js2-deflocal js2-ts-line-start 0
643 "Token stream buffer-local variable.")
644
645 (js2-deflocal js2-ts-lineno 1
646 "Token stream buffer-local variable.")
647
648 ;; FIXME: Unused.
649 (js2-deflocal js2-ts-line-end-char -1
650 "Token stream buffer-local variable.")
651
652 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
653 "Token stream buffer-local variable.
654 Current scan position.")
655
656 ;; FIXME: Unused.
657 (js2-deflocal js2-ts-is-xml-attribute nil
658 "Token stream buffer-local variable.")
659
660 (js2-deflocal js2-ts-xml-is-tag-content nil
661 "Token stream buffer-local variable.")
662
663 (js2-deflocal js2-ts-xml-open-tags-count 0
664 "Token stream buffer-local variable.")
665
666 (js2-deflocal js2-ts-string-buffer nil
667 "Token stream buffer-local variable.
668 List of chars built up while scanning various tokens.")
669
670 (cl-defstruct (js2-token
671 (:constructor nil)
672 (:constructor make-js2-token (beg)))
673 "Value returned from the token stream."
674 (type js2-EOF)
675 (beg 1)
676 (end -1)
677 (string "")
678 number
679 number-base
680 regexp-flags
681 comment-type
682 follows-eol-p)
683
684 ;; Have to call `js2-init-scanner' to initialize the values.
685 (js2-deflocal js2-ti-tokens nil)
686 (js2-deflocal js2-ti-tokens-cursor nil)
687 (js2-deflocal js2-ti-lookahead nil)
688
689 (cl-defstruct (js2-ts-state
690 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
691 (cursor js2-ts-cursor)
692 (tokens (copy-sequence js2-ti-tokens))
693 (tokens-cursor js2-ti-tokens-cursor)
694 (lookahead js2-ti-lookahead))))
695 lineno
696 cursor
697 tokens
698 tokens-cursor
699 lookahead)
700
701 ;;; Parser variables
702
703 (js2-deflocal js2-parsed-errors nil
704 "List of errors produced during scanning/parsing.")
705
706 (js2-deflocal js2-parsed-warnings nil
707 "List of warnings produced during scanning/parsing.")
708
709 (js2-deflocal js2-recover-from-parse-errors t
710 "Non-nil to continue parsing after a syntax error.
711
712 In recovery mode, the AST will be built in full, and any error
713 nodes will be flagged with appropriate error information. If
714 this flag is nil, a syntax error will result in an error being
715 signaled.
716
717 The variable is automatically buffer-local, because different
718 modes that use the parser will need different settings.")
719
720 (js2-deflocal js2-parse-hook nil
721 "List of callbacks for receiving parsing progress.")
722
723 (defvar js2-parse-finished-hook nil
724 "List of callbacks to notify when parsing finishes.
725 Not called if parsing was interrupted.")
726
727 (js2-deflocal js2-is-eval-code nil
728 "True if we're evaluating code in a string.
729 If non-nil, the tokenizer will record the token text, and the AST nodes
730 will record their source text. Off by default for IDE modes, since the
731 text is available in the buffer.")
732
733 (defvar js2-parse-ide-mode t
734 "Non-nil if the parser is being used for `js2-mode'.
735 If non-nil, the parser will set text properties for fontification
736 and the syntax table. The value should be nil when using the
737 parser as a frontend to an interpreter or byte compiler.")
738
739 ;;; Parser instance variables (buffer-local vars for js2-parse)
740
741 (defconst js2-ti-after-eol (lsh 1 16)
742 "Flag: first token of the source line.")
743
744 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
745
746 (js2-deflocal js2-compiler-generate-debug-info t)
747 (js2-deflocal js2-compiler-use-dynamic-scope nil)
748 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
749 (js2-deflocal js2-compiler-xml-available t)
750 (js2-deflocal js2-compiler-optimization-level 0)
751 (js2-deflocal js2-compiler-generating-source t)
752 (js2-deflocal js2-compiler-strict-mode nil)
753 (js2-deflocal js2-compiler-report-warning-as-error nil)
754 (js2-deflocal js2-compiler-generate-observer-count nil)
755 (js2-deflocal js2-compiler-activation-names nil)
756
757 ;; SKIP: sourceURI
758
759 ;; There's a compileFunction method in Context.java - may need it.
760 (js2-deflocal js2-called-by-compile-function nil
761 "True if `js2-parse' was called by `js2-compile-function'.
762 Will only be used when we finish implementing the interpreter.")
763
764 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
765
766 ;; SKIP: node factory - we're going to just call functions directly,
767 ;; and eventually go to a unified AST format.
768
769 (js2-deflocal js2-nesting-of-function 0)
770
771 (js2-deflocal js2-recorded-identifiers nil
772 "Tracks identifiers found during parsing.")
773
774 (js2-deflocal js2-is-in-destructuring nil
775 "True while parsing destructuring expression.")
776
777 (js2-deflocal js2-in-use-strict-directive nil
778 "True while inside a script or function under strict mode.")
779
780 (defcustom js2-global-externs nil
781 "A list of any extern names you'd like to consider always declared.
782 This list is global and is used by all `js2-mode' files.
783 You can create buffer-local externs list using `js2-additional-externs'.
784
785 There is also a buffer-local variable `js2-default-externs',
786 which is initialized by default to include the Ecma-262 externs
787 and the standard browser externs. The three lists are all
788 checked during highlighting."
789 :type 'list
790 :group 'js2-mode)
791
792 (js2-deflocal js2-default-externs nil
793 "Default external declarations.
794
795 These are currently only used for highlighting undeclared variables,
796 which only worries about top-level (unqualified) references.
797 As js2-mode's processing improves, we will flesh out this list.
798
799 The initial value is set to `js2-ecma-262-externs', unless some
800 of the `js2-include-?-externs' variables are set to t, in which
801 case the browser, Rhino and/or Node.js externs are also included.
802
803 See `js2-additional-externs' for more information.")
804
805 (defcustom js2-include-browser-externs t
806 "Non-nil to include browser externs in the master externs list.
807 If you work on JavaScript files that are not intended for browsers,
808 such as Mozilla Rhino server-side JavaScript, set this to nil.
809 See `js2-additional-externs' for more information about externs."
810 :type 'boolean
811 :group 'js2-mode)
812
813 (defcustom js2-include-rhino-externs nil
814 "Non-nil to include Mozilla Rhino externs in the master externs list.
815 See `js2-additional-externs' for more information about externs."
816 :type 'boolean
817 :group 'js2-mode)
818
819 (defcustom js2-include-node-externs nil
820 "Non-nil to include Node.js externs in the master externs list.
821 See `js2-additional-externs' for more information about externs."
822 :type 'boolean
823 :group 'js2-mode)
824
825 (js2-deflocal js2-additional-externs nil
826 "A buffer-local list of additional external declarations.
827 It is used to decide whether variables are considered undeclared
828 for purposes of highlighting.
829
830 Each entry is a Lisp string. The string should be the fully qualified
831 name of an external entity. All externs should be added to this list,
832 so that as js2-mode's processing improves it can take advantage of them.
833
834 You may want to declare your externs in three ways.
835 First, you can add externs that are valid for all your JavaScript files.
836 You should probably do this by adding them to `js2-global-externs', which
837 is a global list used for all js2-mode files.
838
839 Next, you can add a function to `js2-init-hook' that adds additional
840 externs appropriate for the specific file, perhaps based on its path.
841 These should go in `js2-additional-externs', which is buffer-local.
842
843 Third, you can use JSLint's global declaration, as long as
844 `js2-include-jslint-globals' is non-nil, which see.
845
846 Finally, you can add a function to `js2-post-parse-callbacks',
847 which is called after parsing completes, and `js2-mode-ast' is bound to
848 the root of the parse tree. At this stage you can set up an AST
849 node visitor using `js2-visit-ast' and examine the parse tree
850 for specific import patterns that may imply the existence of
851 other externs, possibly tied to your build system. These should also
852 be added to `js2-additional-externs'.
853
854 Your post-parse callback may of course also use the simpler and
855 faster (but perhaps less robust) approach of simply scanning the
856 buffer text for your imports, using regular expressions.")
857
858 ;; SKIP: decompiler
859 ;; SKIP: encoded-source
860
861 ;;; The following variables are per-function and should be saved/restored
862 ;;; during function parsing...
863
864 (js2-deflocal js2-current-script-or-fn nil)
865 (js2-deflocal js2-current-scope nil)
866 (js2-deflocal js2-nesting-of-with 0)
867 (js2-deflocal js2-label-set nil
868 "An alist mapping label names to nodes.")
869
870 (js2-deflocal js2-loop-set nil)
871 (js2-deflocal js2-loop-and-switch-set nil)
872 (js2-deflocal js2-has-return-value nil)
873 (js2-deflocal js2-end-flags 0)
874
875 ;;; ...end of per function variables
876
877 ;; These flags enumerate the possible ways a statement/function can
878 ;; terminate. These flags are used by endCheck() and by the Parser to
879 ;; detect inconsistent return usage.
880 ;;
881 ;; END_UNREACHED is reserved for code paths that are assumed to always be
882 ;; able to execute (example: throw, continue)
883 ;;
884 ;; END_DROPS_OFF indicates if the statement can transfer control to the
885 ;; next one. Statement such as return dont. A compound statement may have
886 ;; some branch that drops off control to the next statement.
887 ;;
888 ;; END_RETURNS indicates that the statement can return (without arguments)
889 ;; END_RETURNS_VALUE indicates that the statement can return a value.
890 ;;
891 ;; A compound statement such as
892 ;; if (condition) {
893 ;; return value;
894 ;; }
895 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
896
897 (defconst js2-end-unreached #x0)
898 (defconst js2-end-drops-off #x1)
899 (defconst js2-end-returns #x2)
900 (defconst js2-end-returns-value #x4)
901
902 ;; Rhino awkwardly passes a statementLabel parameter to the
903 ;; statementHelper() function, the main statement parser, which
904 ;; is then used by quite a few of the sub-parsers. We just make
905 ;; it a buffer-local variable and make sure it's cleaned up properly.
906 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
907
908 ;; Similarly, Rhino passes an inForInit boolean through about half
909 ;; the expression parsers. We use a dynamically-scoped variable,
910 ;; which makes it easier to funcall the parsers individually without
911 ;; worrying about whether they take the parameter or not.
912 (js2-deflocal js2-in-for-init nil)
913 (js2-deflocal js2-temp-name-counter 0)
914 (js2-deflocal js2-parse-stmt-count 0)
915
916 (defsubst js2-get-next-temp-name ()
917 (format "$%d" (cl-incf js2-temp-name-counter)))
918
919 (defvar js2-parse-interruptable-p t
920 "Set this to nil to force parse to continue until finished.
921 This will mostly be useful for interpreters.")
922
923 (defvar js2-statements-per-pause 50
924 "Pause after this many statements to check for user input.
925 If user input is pending, stop the parse and discard the tree.
926 This makes for a smoother user experience for large files.
927 You may have to wait a second or two before the highlighting
928 and error-reporting appear, but you can always type ahead if
929 you wish. This appears to be more or less how Eclipse, IntelliJ
930 and other editors work.")
931
932 (js2-deflocal js2-record-comments t
933 "Instructs the scanner to record comments in `js2-scanned-comments'.")
934
935 (js2-deflocal js2-scanned-comments nil
936 "List of all comments from the current parse.")
937
938 (defcustom js2-mode-indent-inhibit-undo nil
939 "Non-nil to disable collection of Undo information when indenting lines.
940 Some users have requested this behavior. It's nil by default because
941 other Emacs modes don't work this way."
942 :type 'boolean
943 :group 'js2-mode)
944
945 (defcustom js2-mode-indent-ignore-first-tab nil
946 "If non-nil, ignore first TAB keypress if we look indented properly.
947 It's fairly common for users to navigate to an already-indented line
948 and press TAB for reassurance that it's been indented. For this class
949 of users, we want the first TAB press on a line to be ignored if the
950 line is already indented to one of the precomputed alternatives.
951
952 This behavior is only partly implemented. If you TAB-indent a line,
953 navigate to another line, and then navigate back, it fails to clear
954 the last-indented variable, so it thinks you've already hit TAB once,
955 and performs the indent. A full solution would involve getting on the
956 point-motion hooks for the entire buffer. If we come across another
957 use cases that requires watching point motion, I'll consider doing it.
958
959 If you set this variable to nil, then the TAB key will always change
960 the indentation of the current line, if more than one alternative
961 indentation spot exists."
962 :type 'boolean
963 :group 'js2-mode)
964
965 (defvar js2-indent-hook nil
966 "A hook for user-defined indentation rules.
967
968 Functions on this hook should expect two arguments: (LIST INDEX)
969 The LIST argument is the list of computed indentation points for
970 the current line. INDEX is the list index of the indentation point
971 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
972 indent function is not going to change the current line indentation.
973
974 If a hook function on this list returns a non-nil value, then
975 `js2-bounce-indent' assumes the hook function has performed its own
976 indentation, and will do nothing. If all hook functions on the list
977 return nil, then `js2-bounce-indent' will use its computed indentation
978 and reindent the line.
979
980 When hook functions on this hook list are called, the variable
981 `js2-mode-ast' may or may not be set, depending on whether the
982 parse tree is available. If the variable is nil, you can pass a
983 callback to `js2-mode-wait-for-parse', and your callback will be
984 called after the new parse tree is built. This can take some time
985 in large files.")
986
987 (defface js2-warning
988 `((((class color) (background light))
989 (:underline "orange"))
990 (((class color) (background dark))
991 (:underline "orange"))
992 (t (:underline t)))
993 "Face for JavaScript warnings."
994 :group 'js2-mode)
995
996 (defface js2-error
997 `((((class color) (background light))
998 (:foreground "red"))
999 (((class color) (background dark))
1000 (:foreground "red"))
1001 (t (:foreground "red")))
1002 "Face for JavaScript errors."
1003 :group 'js2-mode)
1004
1005 (defface js2-jsdoc-tag
1006 '((t :foreground "SlateGray"))
1007 "Face used to highlight @whatever tags in jsdoc comments."
1008 :group 'js2-mode)
1009
1010 (defface js2-jsdoc-type
1011 '((t :foreground "SteelBlue"))
1012 "Face used to highlight {FooBar} types in jsdoc comments."
1013 :group 'js2-mode)
1014
1015 (defface js2-jsdoc-value
1016 '((t :foreground "PeachPuff3"))
1017 "Face used to highlight tag values in jsdoc comments."
1018 :group 'js2-mode)
1019
1020 (defface js2-function-param
1021 '((t :foreground "SeaGreen"))
1022 "Face used to highlight function parameters in javascript."
1023 :group 'js2-mode)
1024
1025 (defface js2-function-call
1026 '((t :inherit default))
1027 "Face used to highlight function name in calls."
1028 :group 'js2-mode)
1029
1030 (defface js2-object-property
1031 '((t :inherit default))
1032 "Face used to highlight named property in object literal."
1033 :group 'js2-mode)
1034
1035 (defface js2-instance-member
1036 '((t :foreground "DarkOrchid"))
1037 "Face used to highlight instance variables in javascript.
1038 Not currently used."
1039 :group 'js2-mode)
1040
1041 (defface js2-private-member
1042 '((t :foreground "PeachPuff3"))
1043 "Face used to highlight calls to private methods in javascript.
1044 Not currently used."
1045 :group 'js2-mode)
1046
1047 (defface js2-private-function-call
1048 '((t :foreground "goldenrod"))
1049 "Face used to highlight calls to private functions in javascript.
1050 Not currently used."
1051 :group 'js2-mode)
1052
1053 (defface js2-jsdoc-html-tag-name
1054 '((((class color) (min-colors 88) (background light))
1055 (:foreground "rosybrown"))
1056 (((class color) (min-colors 8) (background dark))
1057 (:foreground "yellow"))
1058 (((class color) (min-colors 8) (background light))
1059 (:foreground "magenta")))
1060 "Face used to highlight jsdoc html tag names"
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-html-tag-delimiter
1064 '((((class color) (min-colors 88) (background light))
1065 (:foreground "dark khaki"))
1066 (((class color) (min-colors 8) (background dark))
1067 (:foreground "green"))
1068 (((class color) (min-colors 8) (background light))
1069 (:foreground "green")))
1070 "Face used to highlight brackets in jsdoc html tags."
1071 :group 'js2-mode)
1072
1073 (defface js2-external-variable
1074 '((t :foreground "orange"))
1075 "Face used to highlight undeclared variable identifiers.")
1076
1077 (defcustom js2-init-hook nil
1078 "List of functions to be called after `js2-mode' or
1079 `js2-minor-mode' has initialized all variables, before parsing
1080 the buffer for the first time."
1081 :type 'hook
1082 :group 'js2-mode
1083 :version "20130608")
1084
1085 (defcustom js2-post-parse-callbacks nil
1086 "List of callback functions invoked after parsing finishes.
1087 Currently, the main use for this function is to add synthetic
1088 declarations to `js2-recorded-identifiers', which see."
1089 :type 'hook
1090 :group 'js2-mode)
1091
1092 (defcustom js2-build-imenu-callbacks nil
1093 "List of functions called during Imenu index generation.
1094 It's a good place to add additional entries to it, using
1095 `js2-record-imenu-entry'."
1096 :type 'hook
1097 :group 'js2-mode)
1098
1099 (defcustom js2-highlight-external-variables t
1100 "Non-nil to highlight undeclared variable identifiers.
1101 An undeclared variable is any variable not declared with var or let
1102 in the current scope or any lexically enclosing scope. If you use
1103 such a variable, then you are either expecting it to originate from
1104 another file, or you've got a potential bug."
1105 :type 'boolean
1106 :group 'js2-mode)
1107
1108 (defcustom js2-warn-about-unused-function-arguments nil
1109 "Non-nil to treat function arguments like declared-but-unused variables."
1110 :type 'booleanp
1111 :group 'js2-mode)
1112
1113 (defcustom js2-include-jslint-globals t
1114 "Non-nil to include the identifiers from JSLint global
1115 declaration (see http://www.jslint.com/lint.html#global) in the
1116 buffer-local externs list. See `js2-additional-externs' for more
1117 information."
1118 :type 'boolean
1119 :group 'js2-mode)
1120
1121 (defvar js2-mode-map
1122 (let ((map (make-sparse-keymap)))
1123 (define-key map [mouse-1] #'js2-mode-show-node)
1124 (define-key map (kbd "M-j") #'js2-line-break)
1125 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1126 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1127 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1128 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1129 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1130 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1131 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1132 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1133 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1134
1135 (define-key map [menu-bar javascript]
1136 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1137
1138 (define-key map [menu-bar javascript customize-js2-mode]
1139 '(menu-item "Customize js2-mode" js2-mode-customize
1140 :help "Customize the behavior of this mode"))
1141
1142 (define-key map [menu-bar javascript js2-force-refresh]
1143 '(menu-item "Force buffer refresh" js2-mode-reset
1144 :help "Re-parse the buffer from scratch"))
1145
1146 (define-key map [menu-bar javascript separator-2]
1147 '("--"))
1148
1149 (define-key map [menu-bar javascript next-error]
1150 '(menu-item "Next warning or error" next-error
1151 :enabled (and js2-mode-ast
1152 (or (js2-ast-root-errors js2-mode-ast)
1153 (js2-ast-root-warnings js2-mode-ast)))
1154 :help "Move to next warning or error"))
1155
1156 (define-key map [menu-bar javascript display-errors]
1157 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1158 :visible (not js2-mode-show-parse-errors)
1159 :help "Turn on display of warnings and errors"))
1160
1161 (define-key map [menu-bar javascript hide-errors]
1162 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1163 :visible js2-mode-show-parse-errors
1164 :help "Turn off display of warnings and errors"))
1165
1166 (define-key map [menu-bar javascript separator-1]
1167 '("--"))
1168
1169 (define-key map [menu-bar javascript js2-toggle-function]
1170 '(menu-item "Show/collapse element" js2-mode-toggle-element
1171 :help "Hide or show function body or comment"))
1172
1173 (define-key map [menu-bar javascript show-comments]
1174 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1175 :visible js2-mode-comments-hidden
1176 :help "Expand all hidden block comments"))
1177
1178 (define-key map [menu-bar javascript hide-comments]
1179 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1180 :visible (not js2-mode-comments-hidden)
1181 :help "Show block comments as /*...*/"))
1182
1183 (define-key map [menu-bar javascript show-all-functions]
1184 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1185 :visible js2-mode-functions-hidden
1186 :help "Expand all hidden function bodies"))
1187
1188 (define-key map [menu-bar javascript hide-all-functions]
1189 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1190 :visible (not js2-mode-functions-hidden)
1191 :help "Show {...} for all top-level function bodies"))
1192
1193 map)
1194 "Keymap used in `js2-mode' buffers.")
1195
1196 (defcustom js2-bounce-indent-p nil
1197 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1198 They will augment the default indent-line behavior with cycling
1199 among several computed alternatives. See the function
1200 `js2-bounce-indent' for details. The above commands will be
1201 bound to TAB and backtab."
1202 :type 'boolean
1203 :group 'js2-mode
1204 :set (lambda (sym value)
1205 (set-default sym value)
1206 (let ((map js2-mode-map))
1207 (if (not value)
1208 (progn
1209 (define-key map "\t" nil)
1210 (define-key map (kbd "<backtab>") nil))
1211 (define-key map "\t" #'js2-indent-bounce)
1212 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1213
1214 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1215
1216 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1217 "Matches a //-comment line. Must be first non-whitespace on line.
1218 First match-group is the leading whitespace.")
1219
1220 (defvar js2-mode-hook nil)
1221
1222 (js2-deflocal js2-mode-ast nil "Private variable.")
1223 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1224 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1225 (js2-deflocal js2-mode-parsing nil "Private variable.")
1226 (js2-deflocal js2-mode-node-overlay nil)
1227
1228 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1229 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1230
1231 (js2-deflocal js2-mode-fontifications nil "Private variable")
1232 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1233 (js2-deflocal js2-imenu-recorder nil "Private variable")
1234 (js2-deflocal js2-imenu-function-map nil "Private variable")
1235
1236 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1237 "Non-nil to emit status messages during parsing.")
1238
1239 (defvar js2-mode-functions-hidden nil "Private variable.")
1240 (defvar js2-mode-comments-hidden nil "Private variable.")
1241
1242 (defvar js2-mode-syntax-table
1243 (let ((table (make-syntax-table)))
1244 (c-populate-syntax-table table)
1245 (modify-syntax-entry ?` "\"" table)
1246 table)
1247 "Syntax table used in `js2-mode' buffers.")
1248
1249 (defvar js2-mode-abbrev-table nil
1250 "Abbrev table in use in `js2-mode' buffers.")
1251 (define-abbrev-table 'js2-mode-abbrev-table ())
1252
1253 (defvar js2-mode-pending-parse-callbacks nil
1254 "List of functions waiting to be notified that parse is finished.")
1255
1256 (defvar js2-mode-last-indented-line -1)
1257
1258 ;;; Localizable error and warning messages
1259
1260 ;; Messages are copied from Rhino's Messages.properties.
1261 ;; Many of the Java-specific messages have been elided.
1262 ;; Add any js2-specific ones at the end, so we can keep
1263 ;; this file synced with changes to Rhino's.
1264
1265 (defvar js2-message-table
1266 (make-hash-table :test 'equal :size 250)
1267 "Contains localized messages for `js2-mode'.")
1268
1269 ;; TODO(stevey): construct this table at compile-time.
1270 (defmacro js2-msg (key &rest strings)
1271 `(puthash ,key (concat ,@strings)
1272 js2-message-table))
1273
1274 (defun js2-get-msg (msg-key)
1275 "Look up a localized message.
1276 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1277 the correct number of ARGS must be provided."
1278 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1279 (args (if (listp msg-key) (cdr msg-key)))
1280 (msg (gethash key js2-message-table)))
1281 (if msg
1282 (apply #'format msg args)
1283 key))) ; default to showing the key
1284
1285 (js2-msg "msg.dup.parms"
1286 "Duplicate parameter name '%s'.")
1287
1288 (js2-msg "msg.too.big.jump"
1289 "Program too complex: jump offset too big.")
1290
1291 (js2-msg "msg.too.big.index"
1292 "Program too complex: internal index exceeds 64K limit.")
1293
1294 (js2-msg "msg.while.compiling.fn"
1295 "Encountered code generation error while compiling function '%s': %s")
1296
1297 (js2-msg "msg.while.compiling.script"
1298 "Encountered code generation error while compiling script: %s")
1299
1300 ;; Context
1301 (js2-msg "msg.ctor.not.found"
1302 "Constructor for '%s' not found.")
1303
1304 (js2-msg "msg.not.ctor"
1305 "'%s' is not a constructor.")
1306
1307 ;; FunctionObject
1308 (js2-msg "msg.varargs.ctor"
1309 "Method or constructor '%s' must be static "
1310 "with the signature (Context cx, Object[] args, "
1311 "Function ctorObj, boolean inNewExpr) "
1312 "to define a variable arguments constructor.")
1313
1314 (js2-msg "msg.varargs.fun"
1315 "Method '%s' must be static with the signature "
1316 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1317 "to define a variable arguments function.")
1318
1319 (js2-msg "msg.incompat.call"
1320 "Method '%s' called on incompatible object.")
1321
1322 (js2-msg "msg.bad.parms"
1323 "Unsupported parameter type '%s' in method '%s'.")
1324
1325 (js2-msg "msg.bad.method.return"
1326 "Unsupported return type '%s' in method '%s'.")
1327
1328 (js2-msg "msg.bad.ctor.return"
1329 "Construction of objects of type '%s' is not supported.")
1330
1331 (js2-msg "msg.no.overload"
1332 "Method '%s' occurs multiple times in class '%s'.")
1333
1334 (js2-msg "msg.method.not.found"
1335 "Method '%s' not found in '%s'.")
1336
1337 ;; IRFactory
1338
1339 (js2-msg "msg.bad.for.in.lhs"
1340 "Invalid left-hand side of for..in loop.")
1341
1342 (js2-msg "msg.mult.index"
1343 "Only one variable allowed in for..in loop.")
1344
1345 (js2-msg "msg.bad.for.in.destruct"
1346 "Left hand side of for..in loop must be an array of "
1347 "length 2 to accept key/value pair.")
1348
1349 (js2-msg "msg.cant.convert"
1350 "Can't convert to type '%s'.")
1351
1352 (js2-msg "msg.bad.assign.left"
1353 "Invalid assignment left-hand side.")
1354
1355 (js2-msg "msg.bad.decr"
1356 "Invalid decrement operand.")
1357
1358 (js2-msg "msg.bad.incr"
1359 "Invalid increment operand.")
1360
1361 (js2-msg "msg.bad.yield"
1362 "yield must be in a function.")
1363
1364 (js2-msg "msg.yield.parenthesized"
1365 "yield expression must be parenthesized.")
1366
1367 (js2-msg "msg.bad.await"
1368 "await must be in async functions.")
1369
1370 ;; NativeGlobal
1371 (js2-msg "msg.cant.call.indirect"
1372 "Function '%s' must be called directly, and not by way of a "
1373 "function of another name.")
1374
1375 (js2-msg "msg.eval.nonstring"
1376 "Calling eval() with anything other than a primitive "
1377 "string value will simply return the value. "
1378 "Is this what you intended?")
1379
1380 (js2-msg "msg.eval.nonstring.strict"
1381 "Calling eval() with anything other than a primitive "
1382 "string value is not allowed in strict mode.")
1383
1384 (js2-msg "msg.bad.destruct.op"
1385 "Invalid destructuring assignment operator")
1386
1387 ;; NativeCall
1388 (js2-msg "msg.only.from.new"
1389 "'%s' may only be invoked from a `new' expression.")
1390
1391 (js2-msg "msg.deprec.ctor"
1392 "The '%s' constructor is deprecated.")
1393
1394 ;; NativeFunction
1395 (js2-msg "msg.no.function.ref.found"
1396 "no source found to decompile function reference %s")
1397
1398 (js2-msg "msg.arg.isnt.array"
1399 "second argument to Function.prototype.apply must be an array")
1400
1401 ;; NativeGlobal
1402 (js2-msg "msg.bad.esc.mask"
1403 "invalid string escape mask")
1404
1405 ;; NativeRegExp
1406 (js2-msg "msg.bad.quant"
1407 "Invalid quantifier %s")
1408
1409 (js2-msg "msg.overlarge.backref"
1410 "Overly large back reference %s")
1411
1412 (js2-msg "msg.overlarge.min"
1413 "Overly large minimum %s")
1414
1415 (js2-msg "msg.overlarge.max"
1416 "Overly large maximum %s")
1417
1418 (js2-msg "msg.zero.quant"
1419 "Zero quantifier %s")
1420
1421 (js2-msg "msg.max.lt.min"
1422 "Maximum %s less than minimum")
1423
1424 (js2-msg "msg.unterm.quant"
1425 "Unterminated quantifier %s")
1426
1427 (js2-msg "msg.unterm.paren"
1428 "Unterminated parenthetical %s")
1429
1430 (js2-msg "msg.unterm.class"
1431 "Unterminated character class %s")
1432
1433 (js2-msg "msg.bad.range"
1434 "Invalid range in character class.")
1435
1436 (js2-msg "msg.trail.backslash"
1437 "Trailing \\ in regular expression.")
1438
1439 (js2-msg "msg.re.unmatched.right.paren"
1440 "unmatched ) in regular expression.")
1441
1442 (js2-msg "msg.no.regexp"
1443 "Regular expressions are not available.")
1444
1445 (js2-msg "msg.bad.backref"
1446 "back-reference exceeds number of capturing parentheses.")
1447
1448 (js2-msg "msg.bad.regexp.compile"
1449 "Only one argument may be specified if the first "
1450 "argument to RegExp.prototype.compile is a RegExp object.")
1451
1452 ;; Parser
1453 (js2-msg "msg.got.syntax.errors"
1454 "Compilation produced %s syntax errors.")
1455
1456 (js2-msg "msg.var.redecl"
1457 "TypeError: redeclaration of var %s.")
1458
1459 (js2-msg "msg.const.redecl"
1460 "TypeError: redeclaration of const %s.")
1461
1462 (js2-msg "msg.let.redecl"
1463 "TypeError: redeclaration of variable %s.")
1464
1465 (js2-msg "msg.parm.redecl"
1466 "TypeError: redeclaration of formal parameter %s.")
1467
1468 (js2-msg "msg.fn.redecl"
1469 "TypeError: redeclaration of function %s.")
1470
1471 (js2-msg "msg.let.decl.not.in.block"
1472 "SyntaxError: let declaration not directly within block")
1473
1474 (js2-msg "msg.mod.import.decl.at.top.level"
1475 "SyntaxError: import declarations may only appear at the top level")
1476
1477 (js2-msg "msg.mod.as.after.reserved.word"
1478 "SyntaxError: missing keyword 'as' after reserved word %s")
1479
1480 (js2-msg "msg.mod.rc.after.import.spec.list"
1481 "SyntaxError: missing '}' after module specifier list")
1482
1483 (js2-msg "msg.mod.from.after.import.spec.set"
1484 "SyntaxError: missing keyword 'from' after import specifier set")
1485
1486 (js2-msg "msg.mod.declaration.after.import"
1487 "SyntaxError: missing declaration after 'import' keyword")
1488
1489 (js2-msg "msg.mod.spec.after.from"
1490 "SyntaxError: missing module specifier after 'from' keyword")
1491
1492 (js2-msg "msg.mod.export.decl.at.top.level"
1493 "SyntaxError: export declarations may only appear at top level")
1494
1495 (js2-msg "msg.mod.rc.after.export.spec.list"
1496 "SyntaxError: missing '}' after export specifier list")
1497
1498 ;; NodeTransformer
1499 (js2-msg "msg.dup.label"
1500 "duplicated label")
1501
1502 (js2-msg "msg.undef.label"
1503 "undefined label")
1504
1505 (js2-msg "msg.bad.break"
1506 "unlabelled break must be inside loop or switch")
1507
1508 (js2-msg "msg.continue.outside"
1509 "continue must be inside loop")
1510
1511 (js2-msg "msg.continue.nonloop"
1512 "continue can only use labels of iteration statements")
1513
1514 (js2-msg "msg.bad.throw.eol"
1515 "Line terminator is not allowed between the throw "
1516 "keyword and throw expression.")
1517
1518 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1519 "function statement requires a name")
1520
1521 (js2-msg "msg.no.paren.parms"
1522 "missing ( before function parameters.")
1523
1524 (js2-msg "msg.no.parm"
1525 "missing formal parameter")
1526
1527 (js2-msg "msg.no.paren.after.parms"
1528 "missing ) after formal parameters")
1529
1530 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1531 "parameter without default follows parameter with default")
1532
1533 (js2-msg "msg.param.after.rest" ; added by js2-mode
1534 "parameter after rest parameter")
1535
1536 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1537 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1538
1539 (js2-msg "msg.no.brace.body"
1540 "missing '{' before function body")
1541
1542 (js2-msg "msg.no.brace.after.body"
1543 "missing } after function body")
1544
1545 (js2-msg "msg.no.paren.cond"
1546 "missing ( before condition")
1547
1548 (js2-msg "msg.no.paren.after.cond"
1549 "missing ) after condition")
1550
1551 (js2-msg "msg.no.semi.stmt"
1552 "missing ; before statement")
1553
1554 (js2-msg "msg.missing.semi"
1555 "missing ; after statement")
1556
1557 (js2-msg "msg.no.name.after.dot"
1558 "missing name after . operator")
1559
1560 (js2-msg "msg.no.name.after.coloncolon"
1561 "missing name after :: operator")
1562
1563 (js2-msg "msg.no.name.after.dotdot"
1564 "missing name after .. operator")
1565
1566 (js2-msg "msg.no.name.after.xmlAttr"
1567 "missing name after .@")
1568
1569 (js2-msg "msg.no.bracket.index"
1570 "missing ] in index expression")
1571
1572 (js2-msg "msg.no.paren.switch"
1573 "missing ( before switch expression")
1574
1575 (js2-msg "msg.no.paren.after.switch"
1576 "missing ) after switch expression")
1577
1578 (js2-msg "msg.no.brace.switch"
1579 "missing '{' before switch body")
1580
1581 (js2-msg "msg.bad.switch"
1582 "invalid switch statement")
1583
1584 (js2-msg "msg.no.colon.case"
1585 "missing : after case expression")
1586
1587 (js2-msg "msg.double.switch.default"
1588 "double default label in the switch statement")
1589
1590 (js2-msg "msg.no.while.do"
1591 "missing while after do-loop body")
1592
1593 (js2-msg "msg.no.paren.for"
1594 "missing ( after for")
1595
1596 (js2-msg "msg.no.semi.for"
1597 "missing ; after for-loop initializer")
1598
1599 (js2-msg "msg.no.semi.for.cond"
1600 "missing ; after for-loop condition")
1601
1602 (js2-msg "msg.in.after.for.name"
1603 "missing in or of after for")
1604
1605 (js2-msg "msg.no.paren.for.ctrl"
1606 "missing ) after for-loop control")
1607
1608 (js2-msg "msg.no.paren.with"
1609 "missing ( before with-statement object")
1610
1611 (js2-msg "msg.no.paren.after.with"
1612 "missing ) after with-statement object")
1613
1614 (js2-msg "msg.no.with.strict"
1615 "with statements not allowed in strict mode")
1616
1617 (js2-msg "msg.no.paren.after.let"
1618 "missing ( after let")
1619
1620 (js2-msg "msg.no.paren.let"
1621 "missing ) after variable list")
1622
1623 (js2-msg "msg.no.curly.let"
1624 "missing } after let statement")
1625
1626 (js2-msg "msg.bad.return"
1627 "invalid return")
1628
1629 (js2-msg "msg.no.brace.block"
1630 "missing } in compound statement")
1631
1632 (js2-msg "msg.bad.label"
1633 "invalid label")
1634
1635 (js2-msg "msg.bad.var"
1636 "missing variable name")
1637
1638 (js2-msg "msg.bad.var.init"
1639 "invalid variable initialization")
1640
1641 (js2-msg "msg.no.colon.cond"
1642 "missing : in conditional expression")
1643
1644 (js2-msg "msg.no.paren.arg"
1645 "missing ) after argument list")
1646
1647 (js2-msg "msg.no.bracket.arg"
1648 "missing ] after element list")
1649
1650 (js2-msg "msg.bad.prop"
1651 "invalid property id")
1652
1653 (js2-msg "msg.no.colon.prop"
1654 "missing : after property id")
1655
1656 (js2-msg "msg.no.brace.prop"
1657 "missing } after property list")
1658
1659 (js2-msg "msg.no.paren"
1660 "missing ) in parenthetical")
1661
1662 (js2-msg "msg.reserved.id"
1663 "'%s' is a reserved identifier")
1664
1665 (js2-msg "msg.no.paren.catch"
1666 "missing ( before catch-block condition")
1667
1668 (js2-msg "msg.bad.catchcond"
1669 "invalid catch block condition")
1670
1671 (js2-msg "msg.catch.unreachable"
1672 "any catch clauses following an unqualified catch are unreachable")
1673
1674 (js2-msg "msg.no.brace.try"
1675 "missing '{' before try block")
1676
1677 (js2-msg "msg.no.brace.catchblock"
1678 "missing '{' before catch-block body")
1679
1680 (js2-msg "msg.try.no.catchfinally"
1681 "'try' without 'catch' or 'finally'")
1682
1683 (js2-msg "msg.no.return.value"
1684 "function %s does not always return a value")
1685
1686 (js2-msg "msg.anon.no.return.value"
1687 "anonymous function does not always return a value")
1688
1689 (js2-msg "msg.return.inconsistent"
1690 "return statement is inconsistent with previous usage")
1691
1692 (js2-msg "msg.generator.returns"
1693 "TypeError: legacy generator function '%s' returns a value")
1694
1695 (js2-msg "msg.anon.generator.returns"
1696 "TypeError: anonymous legacy generator function returns a value")
1697
1698 (js2-msg "msg.syntax"
1699 "syntax error")
1700
1701 (js2-msg "msg.unexpected.eof"
1702 "Unexpected end of file")
1703
1704 (js2-msg "msg.XML.bad.form"
1705 "illegally formed XML syntax")
1706
1707 (js2-msg "msg.XML.not.available"
1708 "XML runtime not available")
1709
1710 (js2-msg "msg.too.deep.parser.recursion"
1711 "Too deep recursion while parsing")
1712
1713 (js2-msg "msg.no.side.effects"
1714 "Code has no side effects")
1715
1716 (js2-msg "msg.extra.trailing.comma"
1717 "Trailing comma is not supported in some browsers")
1718
1719 (js2-msg "msg.array.trailing.comma"
1720 "Trailing comma yields different behavior across browsers")
1721
1722 (js2-msg "msg.equal.as.assign"
1723 (concat "Test for equality (==) mistyped as assignment (=)?"
1724 " (parenthesize to suppress warning)"))
1725
1726 (js2-msg "msg.var.hides.arg"
1727 "Variable %s hides argument")
1728
1729 (js2-msg "msg.destruct.assign.no.init"
1730 "Missing = in destructuring declaration")
1731
1732 (js2-msg "msg.init.no.destruct"
1733 "Binding initializer not in destructuring assignment")
1734
1735 (js2-msg "msg.no.octal.strict"
1736 "Octal numbers prohibited in strict mode.")
1737
1738 (js2-msg "msg.dup.obj.lit.prop.strict"
1739 "Property '%s' already defined in this object literal.")
1740
1741 (js2-msg "msg.dup.param.strict"
1742 "Parameter '%s' already declared in this function.")
1743
1744 (js2-msg "msg.bad.id.strict"
1745 "'%s' is not a valid identifier for this use in strict mode.")
1746
1747 ;; ScriptRuntime
1748 (js2-msg "msg.no.properties"
1749 "%s has no properties.")
1750
1751 (js2-msg "msg.invalid.iterator"
1752 "Invalid iterator value")
1753
1754 (js2-msg "msg.iterator.primitive"
1755 "__iterator__ returned a primitive value")
1756
1757 (js2-msg "msg.assn.create.strict"
1758 "Assignment to undeclared variable %s")
1759
1760 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1761 "Undeclared variable or function '%s'")
1762
1763 (js2-msg "msg.unused.variable" ; added by js2-mode
1764 "Unused variable or function '%s'")
1765
1766 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1767 "Variable '%s' referenced but never initialized")
1768
1769 (js2-msg "msg.ref.undefined.prop"
1770 "Reference to undefined property '%s'")
1771
1772 (js2-msg "msg.prop.not.found"
1773 "Property %s not found.")
1774
1775 (js2-msg "msg.invalid.type"
1776 "Invalid JavaScript value of type %s")
1777
1778 (js2-msg "msg.primitive.expected"
1779 "Primitive type expected (had %s instead)")
1780
1781 (js2-msg "msg.namespace.expected"
1782 "Namespace object expected to left of :: (found %s instead)")
1783
1784 (js2-msg "msg.null.to.object"
1785 "Cannot convert null to an object.")
1786
1787 (js2-msg "msg.undef.to.object"
1788 "Cannot convert undefined to an object.")
1789
1790 (js2-msg "msg.cyclic.value"
1791 "Cyclic %s value not allowed.")
1792
1793 (js2-msg "msg.is.not.defined"
1794 "'%s' is not defined.")
1795
1796 (js2-msg "msg.undef.prop.read"
1797 "Cannot read property '%s' from %s")
1798
1799 (js2-msg "msg.undef.prop.write"
1800 "Cannot set property '%s' of %s to '%s'")
1801
1802 (js2-msg "msg.undef.prop.delete"
1803 "Cannot delete property '%s' of %s")
1804
1805 (js2-msg "msg.undef.method.call"
1806 "Cannot call method '%s' of %s")
1807
1808 (js2-msg "msg.undef.with"
1809 "Cannot apply 'with' to %s")
1810
1811 (js2-msg "msg.isnt.function"
1812 "%s is not a function, it is %s.")
1813
1814 (js2-msg "msg.isnt.function.in"
1815 "Cannot call property %s in object %s. "
1816 "It is not a function, it is '%s'.")
1817
1818 (js2-msg "msg.function.not.found"
1819 "Cannot find function %s.")
1820
1821 (js2-msg "msg.function.not.found.in"
1822 "Cannot find function %s in object %s.")
1823
1824 (js2-msg "msg.isnt.xml.object"
1825 "%s is not an xml object.")
1826
1827 (js2-msg "msg.no.ref.to.get"
1828 "%s is not a reference to read reference value.")
1829
1830 (js2-msg "msg.no.ref.to.set"
1831 "%s is not a reference to set reference value to %s.")
1832
1833 (js2-msg "msg.no.ref.from.function"
1834 "Function %s can not be used as the left-hand "
1835 "side of assignment or as an operand of ++ or -- operator.")
1836
1837 (js2-msg "msg.bad.default.value"
1838 "Object's getDefaultValue() method returned an object.")
1839
1840 (js2-msg "msg.instanceof.not.object"
1841 "Can't use instanceof on a non-object.")
1842
1843 (js2-msg "msg.instanceof.bad.prototype"
1844 "'prototype' property of %s is not an object.")
1845
1846 (js2-msg "msg.bad.radix"
1847 "illegal radix %s.")
1848
1849 ;; ScriptableObject
1850 (js2-msg "msg.default.value"
1851 "Cannot find default value for object.")
1852
1853 (js2-msg "msg.zero.arg.ctor"
1854 "Cannot load class '%s' which has no zero-parameter constructor.")
1855
1856 (js2-msg "msg.ctor.multiple.parms"
1857 "Can't define constructor or class %s since more than "
1858 "one constructor has multiple parameters.")
1859
1860 (js2-msg "msg.extend.scriptable"
1861 "%s must extend ScriptableObject in order to define property %s.")
1862
1863 (js2-msg "msg.bad.getter.parms"
1864 "In order to define a property, getter %s must have zero "
1865 "parameters or a single ScriptableObject parameter.")
1866
1867 (js2-msg "msg.obj.getter.parms"
1868 "Expected static or delegated getter %s to take "
1869 "a ScriptableObject parameter.")
1870
1871 (js2-msg "msg.getter.static"
1872 "Getter and setter must both be static or neither be static.")
1873
1874 (js2-msg "msg.setter.return"
1875 "Setter must have void return type: %s")
1876
1877 (js2-msg "msg.setter2.parms"
1878 "Two-parameter setter must take a ScriptableObject as "
1879 "its first parameter.")
1880
1881 (js2-msg "msg.setter1.parms"
1882 "Expected single parameter setter for %s")
1883
1884 (js2-msg "msg.setter2.expected"
1885 "Expected static or delegated setter %s to take two parameters.")
1886
1887 (js2-msg "msg.setter.parms"
1888 "Expected either one or two parameters for setter.")
1889
1890 (js2-msg "msg.setter.bad.type"
1891 "Unsupported parameter type '%s' in setter '%s'.")
1892
1893 (js2-msg "msg.add.sealed"
1894 "Cannot add a property to a sealed object: %s.")
1895
1896 (js2-msg "msg.remove.sealed"
1897 "Cannot remove a property from a sealed object: %s.")
1898
1899 (js2-msg "msg.modify.sealed"
1900 "Cannot modify a property of a sealed object: %s.")
1901
1902 (js2-msg "msg.modify.readonly"
1903 "Cannot modify readonly property: %s.")
1904
1905 ;; TokenStream
1906 (js2-msg "msg.missing.exponent"
1907 "missing exponent")
1908
1909 (js2-msg "msg.caught.nfe"
1910 "number format error")
1911
1912 (js2-msg "msg.unterminated.string.lit"
1913 "unterminated string literal")
1914
1915 (js2-msg "msg.unterminated.comment"
1916 "unterminated comment")
1917
1918 (js2-msg "msg.unterminated.re.lit"
1919 "unterminated regular expression literal")
1920
1921 (js2-msg "msg.invalid.re.flag"
1922 "invalid flag after regular expression")
1923
1924 (js2-msg "msg.no.re.input.for"
1925 "no input for %s")
1926
1927 (js2-msg "msg.illegal.character"
1928 "illegal character")
1929
1930 (js2-msg "msg.invalid.escape"
1931 "invalid Unicode escape sequence")
1932
1933 (js2-msg "msg.bad.namespace"
1934 "not a valid default namespace statement. "
1935 "Syntax is: default xml namespace = EXPRESSION;")
1936
1937 ;; TokensStream warnings
1938 (js2-msg "msg.bad.octal.literal"
1939 "illegal octal literal digit %s; "
1940 "interpreting it as a decimal digit")
1941
1942 (js2-msg "msg.missing.hex.digits"
1943 "missing hexadecimal digits after '0x'")
1944
1945 (js2-msg "msg.missing.binary.digits"
1946 "missing binary digits after '0b'")
1947
1948 (js2-msg "msg.missing.octal.digits"
1949 "missing octal digits after '0o'")
1950
1951 (js2-msg "msg.script.is.not.constructor"
1952 "Script objects are not constructors.")
1953
1954 ;; Arrays
1955 (js2-msg "msg.arraylength.bad"
1956 "Inappropriate array length.")
1957
1958 ;; Arrays
1959 (js2-msg "msg.arraylength.too.big"
1960 "Array length %s exceeds supported capacity limit.")
1961
1962 ;; URI
1963 (js2-msg "msg.bad.uri"
1964 "Malformed URI sequence.")
1965
1966 ;; Number
1967 (js2-msg "msg.bad.precision"
1968 "Precision %s out of range.")
1969
1970 ;; NativeGenerator
1971 (js2-msg "msg.send.newborn"
1972 "Attempt to send value to newborn generator")
1973
1974 (js2-msg "msg.already.exec.gen"
1975 "Already executing generator")
1976
1977 (js2-msg "msg.StopIteration.invalid"
1978 "StopIteration may not be changed to an arbitrary object.")
1979
1980 ;; Interpreter
1981 (js2-msg "msg.yield.closing"
1982 "Yield from closing generator")
1983
1984 ;; Classes
1985 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1986 "class statement requires a name")
1987
1988 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1989 "unexpected ',' between class properties")
1990
1991 (js2-msg "msg.unexpected.static" ; added by js2-mode
1992 "unexpected 'static'")
1993
1994 (js2-msg "msg.missing.extends" ; added by js2-mode
1995 "name is required after extends")
1996
1997 (js2-msg "msg.no.brace.class" ; added by js2-mode
1998 "missing '{' before class body")
1999
2000 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2001 "missing ']' after computed property expression")
2002
2003 ;;; Tokens Buffer
2004
2005 (defconst js2-ti-max-lookahead 2)
2006 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2007
2008 (defun js2-new-token (offset)
2009 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2010 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2011 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2012 token))
2013
2014 (defsubst js2-current-token ()
2015 (aref js2-ti-tokens js2-ti-tokens-cursor))
2016
2017 (defsubst js2-current-token-string ()
2018 (js2-token-string (js2-current-token)))
2019
2020 (defsubst js2-current-token-type ()
2021 (js2-token-type (js2-current-token)))
2022
2023 (defsubst js2-current-token-beg ()
2024 (js2-token-beg (js2-current-token)))
2025
2026 (defsubst js2-current-token-end ()
2027 (js2-token-end (js2-current-token)))
2028
2029 (defun js2-current-token-len ()
2030 (let ((token (js2-current-token)))
2031 (- (js2-token-end token)
2032 (js2-token-beg token))))
2033
2034 (defun js2-ts-seek (state)
2035 (setq js2-ts-lineno (js2-ts-state-lineno state)
2036 js2-ts-cursor (js2-ts-state-cursor state)
2037 js2-ti-tokens (js2-ts-state-tokens state)
2038 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2039 js2-ti-lookahead (js2-ts-state-lookahead state)))
2040
2041 ;;; Utilities
2042
2043 (defun js2-delete-if (predicate list)
2044 "Remove all items satisfying PREDICATE in LIST."
2045 (cl-loop for item in list
2046 if (not (funcall predicate item))
2047 collect item))
2048
2049 (defun js2-position (element list)
2050 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2051 Returns nil if element is not found in the list."
2052 (let ((count 0)
2053 found)
2054 (while (and list (not found))
2055 (if (eq element (car list))
2056 (setq found t)
2057 (setq count (1+ count)
2058 list (cdr list))))
2059 (if found count)))
2060
2061 (defun js2-find-if (predicate list)
2062 "Find first item satisfying PREDICATE in LIST."
2063 (let (result)
2064 (while (and list (not result))
2065 (if (funcall predicate (car list))
2066 (setq result (car list)))
2067 (setq list (cdr list)))
2068 result))
2069
2070 (defmacro js2-time (form)
2071 "Evaluate FORM, discard result, and return elapsed time in sec."
2072 (declare (debug t))
2073 (let ((beg (make-symbol "--js2-time-beg--")))
2074 `(let ((,beg (current-time)))
2075 ,form
2076 (/ (truncate (* (- (float-time (current-time))
2077 (float-time ,beg))
2078 10000))
2079 10000.0))))
2080
2081 (defsubst js2-same-line (pos)
2082 "Return t if POS is on the same line as current point."
2083 (and (>= pos (point-at-bol))
2084 (<= pos (point-at-eol))))
2085
2086 (defun js2-code-bug ()
2087 "Signal an error when we encounter an unexpected code path."
2088 (error "failed assertion"))
2089
2090 (defsubst js2-record-text-property (beg end prop value)
2091 "Record a text property to set when parsing finishes."
2092 (push (list beg end prop value) js2-mode-deferred-properties))
2093
2094 ;; I'd like to associate errors with nodes, but for now the
2095 ;; easiest thing to do is get the context info from the last token.
2096 (defun js2-record-parse-error (msg &optional arg pos len)
2097 (push (list (list msg arg)
2098 (or pos (js2-current-token-beg))
2099 (or len (js2-current-token-len)))
2100 js2-parsed-errors))
2101
2102 (defun js2-report-error (msg &optional msg-arg pos len)
2103 "Signal a syntax error or record a parse error."
2104 (if js2-recover-from-parse-errors
2105 (js2-record-parse-error msg msg-arg pos len)
2106 (signal 'js2-syntax-error
2107 (list msg
2108 js2-ts-lineno
2109 (save-excursion
2110 (goto-char js2-ts-cursor)
2111 (current-column))
2112 js2-ts-hit-eof))))
2113
2114 (defun js2-report-warning (msg &optional msg-arg pos len face)
2115 (if js2-compiler-report-warning-as-error
2116 (js2-report-error msg msg-arg pos len)
2117 (push (list (list msg msg-arg)
2118 (or pos (js2-current-token-beg))
2119 (or len (js2-current-token-len))
2120 face)
2121 js2-parsed-warnings)))
2122
2123 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2124 (if js2-compiler-strict-mode
2125 (js2-report-warning msg-id msg-arg beg
2126 (and beg end (- end beg)))))
2127
2128 (put 'js2-syntax-error 'error-conditions
2129 '(error syntax-error js2-syntax-error))
2130 (put 'js2-syntax-error 'error-message "Syntax error")
2131
2132 (put 'js2-parse-error 'error-conditions
2133 '(error parse-error js2-parse-error))
2134 (put 'js2-parse-error 'error-message "Parse error")
2135
2136 (defmacro js2-clear-flag (flags flag)
2137 `(setq ,flags (logand ,flags (lognot ,flag))))
2138
2139 (defmacro js2-set-flag (flags flag)
2140 "Logical-or FLAG into FLAGS."
2141 `(setq ,flags (logior ,flags ,flag)))
2142
2143 (defsubst js2-flag-set-p (flags flag)
2144 (/= 0 (logand flags flag)))
2145
2146 (defsubst js2-flag-not-set-p (flags flag)
2147 (zerop (logand flags flag)))
2148
2149 ;;; AST struct and function definitions
2150
2151 ;; flags for ast node property 'member-type (used for e4x operators)
2152 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2153 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2154 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2155
2156 (defsubst js2-relpos (pos anchor)
2157 "Convert POS to be relative to ANCHOR.
2158 If POS is nil, returns nil."
2159 (and pos (- pos anchor)))
2160
2161 (defun js2-make-pad (indent)
2162 (if (zerop indent)
2163 ""
2164 (make-string (* indent js2-basic-offset) ? )))
2165
2166 (defun js2-visit-ast (node callback)
2167 "Visit every node in ast NODE with visitor CALLBACK.
2168
2169 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2170 called twice: once to visit the node, and again after all the node's
2171 children have been processed. The END-P argument is nil on the first
2172 call and non-nil on the second call. The return value of the callback
2173 affects the traversal: if non-nil, the children of NODE are processed.
2174 If the callback returns nil, or if the node has no children, then the
2175 callback is called immediately with a non-nil END-P argument.
2176
2177 The node traversal is approximately lexical-order, although there
2178 are currently no guarantees around this."
2179 (when node
2180 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2181 ;; visit the node
2182 (when (funcall callback node nil)
2183 ;; visit the kids
2184 (cond
2185 ((eq vfunc 'js2-visit-none)
2186 nil) ; don't even bother calling it
2187 ;; Each AST node type has to define a `js2-visitor' function
2188 ;; that takes a node and a callback, and calls `js2-visit-ast'
2189 ;; on each child of the node.
2190 (vfunc
2191 (funcall vfunc node callback))
2192 (t
2193 (error "%s does not define a visitor-traversal function"
2194 (aref node 0)))))
2195 ;; call the end-visit
2196 (funcall callback node t))))
2197
2198 (cl-defstruct (js2-node
2199 (:constructor nil)) ; abstract
2200 "Base AST node type."
2201 (type -1) ; token type
2202 (pos -1) ; start position of this AST node in parsed input
2203 (len 1) ; num characters spanned by the node
2204 props ; optional node property list (an alist)
2205 parent) ; link to parent node; null for root
2206
2207 (defsubst js2-node-get-prop (node prop &optional default)
2208 (or (cadr (assoc prop (js2-node-props node))) default))
2209
2210 (defsubst js2-node-set-prop (node prop value)
2211 (setf (js2-node-props node)
2212 (cons (list prop value) (js2-node-props node))))
2213
2214 (defun js2-fixup-starts (n nodes)
2215 "Adjust the start positions of NODES to be relative to N.
2216 Any node in the list may be nil, for convenience."
2217 (dolist (node nodes)
2218 (when node
2219 (setf (js2-node-pos node) (- (js2-node-pos node)
2220 (js2-node-pos n))))))
2221
2222 (defun js2-node-add-children (parent &rest nodes)
2223 "Set parent node of NODES to PARENT, and return PARENT.
2224 Does nothing if we're not recording parent links.
2225 If any given node in NODES is nil, doesn't record that link."
2226 (js2-fixup-starts parent nodes)
2227 (dolist (node nodes)
2228 (and node
2229 (setf (js2-node-parent node) parent))))
2230
2231 ;; Non-recursive since it's called a frightening number of times.
2232 (defun js2-node-abs-pos (n)
2233 (let ((pos (js2-node-pos n)))
2234 (while (setq n (js2-node-parent n))
2235 (setq pos (+ pos (js2-node-pos n))))
2236 pos))
2237
2238 (defsubst js2-node-abs-end (n)
2239 "Return absolute buffer position of end of N."
2240 (+ (js2-node-abs-pos n) (js2-node-len n)))
2241
2242 ;; It's important to make sure block nodes have a Lisp list for the
2243 ;; child nodes, to limit printing recursion depth in an AST that
2244 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2245 ;; a sufficiently large vector tree.
2246
2247 (cl-defstruct (js2-block-node
2248 (:include js2-node)
2249 (:constructor nil)
2250 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2251 (pos (js2-current-token-beg))
2252 len
2253 props
2254 kids)))
2255 "A block of statements."
2256 kids) ; a Lisp list of the child statement nodes
2257
2258 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2259 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2260
2261 (defun js2-visit-block (ast callback)
2262 "Visit the `js2-block-node' children of AST."
2263 (dolist (kid (js2-block-node-kids ast))
2264 (js2-visit-ast kid callback)))
2265
2266 (defun js2-print-block (n i)
2267 (let ((pad (js2-make-pad i)))
2268 (insert pad "{\n")
2269 (dolist (kid (js2-block-node-kids n))
2270 (js2-print-ast kid (1+ i)))
2271 (insert pad "}")))
2272
2273 (cl-defstruct (js2-scope
2274 (:include js2-block-node)
2275 (:constructor nil)
2276 (:constructor make-js2-scope (&key (type js2-BLOCK)
2277 (pos (js2-current-token-beg))
2278 len
2279 kids)))
2280 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2281 ;; I don't have one of those handy, so I'll use an alist for now.
2282 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2283 ;; and is much lighter-weight to construct (both CPU and mem).
2284 ;; The keys are interned strings (symbols) for faster lookup.
2285 ;; Should switch to hybrid alist/hashtable eventually.
2286 symbol-table ; an alist of (symbol . js2-symbol)
2287 parent-scope ; a `js2-scope'
2288 top) ; top-level `js2-scope' (script/function)
2289
2290 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2291 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2292
2293 (defun js2-node-get-enclosing-scope (node)
2294 "Return the innermost `js2-scope' node surrounding NODE.
2295 Returns nil if there is no enclosing scope node."
2296 (while (and (setq node (js2-node-parent node))
2297 (not (js2-scope-p node))))
2298 node)
2299
2300 (defun js2-get-defining-scope (scope name &optional point)
2301 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2302 Returns `js2-scope' in which NAME is defined, or nil if not found.
2303
2304 If POINT is non-nil, and if the found declaration type is
2305 `js2-LET', also check that the declaration node is before POINT."
2306 (let ((sym (if (symbolp name)
2307 name
2308 (intern name)))
2309 result
2310 (continue t))
2311 (while (and scope continue)
2312 (if (or
2313 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2314 (and entry
2315 (or (not point)
2316 (not (eq js2-LET (js2-symbol-decl-type entry)))
2317 (>= point
2318 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2319 (and (eq sym 'arguments)
2320 (js2-function-node-p scope)))
2321 (setq continue nil
2322 result scope)
2323 (setq scope (js2-scope-parent-scope scope))))
2324 result))
2325
2326 (defun js2-scope-get-symbol (scope name)
2327 "Return symbol table entry for NAME in SCOPE.
2328 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2329 (and (js2-scope-symbol-table scope)
2330 (cdr (assq (if (symbolp name)
2331 name
2332 (intern name))
2333 (js2-scope-symbol-table scope)))))
2334
2335 (defun js2-scope-put-symbol (scope name symbol)
2336 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2337 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2338 (let* ((table (js2-scope-symbol-table scope))
2339 (sym (if (symbolp name) name (intern name)))
2340 (entry (assq sym table)))
2341 (if entry
2342 (setcdr entry symbol)
2343 (push (cons sym symbol)
2344 (js2-scope-symbol-table scope)))))
2345
2346 (cl-defstruct (js2-symbol
2347 (:constructor nil)
2348 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2349 "A symbol table entry."
2350 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2351 ;; js2-LET, or js2-CONST
2352 decl-type
2353 name ; string
2354 ast-node) ; a `js2-node'
2355
2356 (cl-defstruct (js2-error-node
2357 (:include js2-node)
2358 (:constructor nil) ; silence emacs21 byte-compiler
2359 (:constructor make-js2-error-node (&key (type js2-ERROR)
2360 (pos (js2-current-token-beg))
2361 len)))
2362 "AST node representing a parse error.")
2363
2364 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2365 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2366
2367 (cl-defstruct (js2-script-node
2368 (:include js2-scope)
2369 (:constructor nil)
2370 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2371 (pos (js2-current-token-beg))
2372 len
2373 ;; FIXME: What are those?
2374 var-decls
2375 fun-decls)))
2376 functions ; Lisp list of nested functions
2377 regexps ; Lisp list of (string . flags)
2378 symbols ; alist (every symbol gets unique index)
2379 (param-count 0)
2380 var-names ; vector of string names
2381 consts ; bool-vector matching var-decls
2382 (temp-number 0)) ; for generating temp variables
2383
2384 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2385 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2386
2387 (defun js2-print-script (node indent)
2388 (dolist (kid (js2-block-node-kids node))
2389 (js2-print-ast kid indent)))
2390
2391 (cl-defstruct (js2-ast-root
2392 (:include js2-script-node)
2393 (:constructor nil)
2394 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2395 (pos (js2-current-token-beg))
2396 len
2397 buffer)))
2398 "The root node of a js2 AST."
2399 buffer ; the source buffer from which the code was parsed
2400 comments ; a Lisp list of comments, ordered by start position
2401 errors ; a Lisp list of errors found during parsing
2402 warnings ; a Lisp list of warnings found during parsing
2403 node-count) ; number of nodes in the tree, including the root
2404
2405 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2406 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2407
2408 (defun js2-visit-ast-root (ast callback)
2409 (dolist (kid (js2-ast-root-kids ast))
2410 (js2-visit-ast kid callback))
2411 (dolist (comment (js2-ast-root-comments ast))
2412 (js2-visit-ast comment callback)))
2413
2414 (cl-defstruct (js2-comment-node
2415 (:include js2-node)
2416 (:constructor nil)
2417 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2418 (pos (js2-current-token-beg))
2419 len
2420 format)))
2421 format) ; 'line, 'block, 'jsdoc or 'html
2422
2423 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2424 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2425
2426 (defun js2-print-comment (n i)
2427 ;; We really ought to link end-of-line comments to their nodes.
2428 ;; Or maybe we could add a new comment type, 'endline.
2429 (insert (js2-make-pad i)
2430 (js2-node-string n)))
2431
2432 (cl-defstruct (js2-expr-stmt-node
2433 (:include js2-node)
2434 (:constructor nil)
2435 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2436 (pos js2-ts-cursor)
2437 len
2438 expr)))
2439 "An expression statement."
2440 expr)
2441
2442 (defsubst js2-expr-stmt-node-set-has-result (node)
2443 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2444 (setf (js2-node-type node) js2-EXPR_RESULT))
2445
2446 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2447 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2448
2449 (defun js2-visit-expr-stmt-node (n v)
2450 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2451
2452 (defun js2-print-expr-stmt-node (n indent)
2453 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2454 (insert ";\n"))
2455
2456 (cl-defstruct (js2-loop-node
2457 (:include js2-scope)
2458 (:constructor nil))
2459 "Abstract supertype of loop nodes."
2460 body ; a `js2-block-node'
2461 lp ; position of left-paren, nil if omitted
2462 rp) ; position of right-paren, nil if omitted
2463
2464 (cl-defstruct (js2-do-node
2465 (:include js2-loop-node)
2466 (:constructor nil)
2467 (:constructor make-js2-do-node (&key (type js2-DO)
2468 (pos (js2-current-token-beg))
2469 len
2470 body
2471 condition
2472 while-pos
2473 lp
2474 rp)))
2475 "AST node for do-loop."
2476 condition ; while (expression)
2477 while-pos) ; buffer position of 'while' keyword
2478
2479 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2480 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2481
2482 (defun js2-visit-do-node (n v)
2483 (js2-visit-ast (js2-do-node-body n) v)
2484 (js2-visit-ast (js2-do-node-condition n) v))
2485
2486 (defun js2-print-do-node (n i)
2487 (let ((pad (js2-make-pad i)))
2488 (insert pad "do {\n")
2489 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2490 (js2-print-ast kid (1+ i)))
2491 (insert pad "} while (")
2492 (js2-print-ast (js2-do-node-condition n) 0)
2493 (insert ");\n")))
2494
2495 (cl-defstruct (js2-export-node
2496 (:include js2-node)
2497 (:constructor nil)
2498 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2499 (pos (js2-current-token-beg))
2500 len
2501 exports-list
2502 from-clause
2503 declaration
2504 default)))
2505 "AST node for an export statement. There are many things that can be exported,
2506 so many of its properties will be nil.
2507 "
2508 exports-list ; lisp list of js2-export-binding-node to export
2509 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2510 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2511 default) ; js2-function-node or js2-assign-node
2512
2513 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2514 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2515
2516 (defun js2-visit-export-node (n v)
2517 (let ((exports-list (js2-export-node-exports-list n))
2518 (from (js2-export-node-from-clause n))
2519 (declaration (js2-export-node-declaration n))
2520 (default (js2-export-node-default n)))
2521 (when exports-list
2522 (dolist (export exports-list)
2523 (js2-visit-ast export v)))
2524 (when from
2525 (js2-visit-ast from v))
2526 (when declaration
2527 (js2-visit-ast declaration v))
2528 (when default
2529 (js2-visit-ast default v))))
2530
2531 (defun js2-print-export-node (n i)
2532 (let ((pad (js2-make-pad i))
2533 (exports-list (js2-export-node-exports-list n))
2534 (from (js2-export-node-from-clause n))
2535 (declaration (js2-export-node-declaration n))
2536 (default (js2-export-node-default n)))
2537 (insert pad "export ")
2538 (cond
2539 (default
2540 (insert "default ")
2541 (js2-print-ast default i))
2542 (declaration
2543 (js2-print-ast declaration i))
2544 ((and exports-list from)
2545 (js2-print-named-imports exports-list)
2546 (insert " ")
2547 (js2-print-from-clause from))
2548 (from
2549 (insert "* ")
2550 (js2-print-from-clause from))
2551 (exports-list
2552 (js2-print-named-imports exports-list)))
2553 (insert ";\n")))
2554
2555 (cl-defstruct (js2-while-node
2556 (:include js2-loop-node)
2557 (:constructor nil)
2558 (:constructor make-js2-while-node (&key (type js2-WHILE)
2559 (pos (js2-current-token-beg))
2560 len body
2561 condition lp
2562 rp)))
2563 "AST node for while-loop."
2564 condition) ; while-condition
2565
2566 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2567 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2568
2569 (defun js2-visit-while-node (n v)
2570 (js2-visit-ast (js2-while-node-condition n) v)
2571 (js2-visit-ast (js2-while-node-body n) v))
2572
2573 (defun js2-print-while-node (n i)
2574 (let ((pad (js2-make-pad i)))
2575 (insert pad "while (")
2576 (js2-print-ast (js2-while-node-condition n) 0)
2577 (insert ") {\n")
2578 (js2-print-body (js2-while-node-body n) (1+ i))
2579 (insert pad "}\n")))
2580
2581 (cl-defstruct (js2-for-node
2582 (:include js2-loop-node)
2583 (:constructor nil)
2584 (:constructor make-js2-for-node (&key (type js2-FOR)
2585 (pos js2-ts-cursor)
2586 len body init
2587 condition
2588 update lp rp)))
2589 "AST node for a C-style for-loop."
2590 init ; initialization expression
2591 condition ; loop condition
2592 update) ; update clause
2593
2594 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2595 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2596
2597 (defun js2-visit-for-node (n v)
2598 (js2-visit-ast (js2-for-node-init n) v)
2599 (js2-visit-ast (js2-for-node-condition n) v)
2600 (js2-visit-ast (js2-for-node-update n) v)
2601 (js2-visit-ast (js2-for-node-body n) v))
2602
2603 (defun js2-print-for-node (n i)
2604 (let ((pad (js2-make-pad i)))
2605 (insert pad "for (")
2606 (js2-print-ast (js2-for-node-init n) 0)
2607 (insert "; ")
2608 (js2-print-ast (js2-for-node-condition n) 0)
2609 (insert "; ")
2610 (js2-print-ast (js2-for-node-update n) 0)
2611 (insert ") {\n")
2612 (js2-print-body (js2-for-node-body n) (1+ i))
2613 (insert pad "}\n")))
2614
2615 (cl-defstruct (js2-for-in-node
2616 (:include js2-loop-node)
2617 (:constructor nil)
2618 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2619 (pos js2-ts-cursor)
2620 len body
2621 iterator
2622 object
2623 in-pos
2624 each-pos
2625 foreach-p forof-p
2626 lp rp)))
2627 "AST node for a for..in loop."
2628 iterator ; [var] foo in ...
2629 object ; object over which we're iterating
2630 in-pos ; buffer position of 'in' keyword
2631 each-pos ; buffer position of 'each' keyword, if foreach-p
2632 foreach-p ; t if it's a for-each loop
2633 forof-p) ; t if it's a for-of loop
2634
2635 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2636 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2637
2638 (defun js2-visit-for-in-node (n v)
2639 (js2-visit-ast (js2-for-in-node-iterator n) v)
2640 (js2-visit-ast (js2-for-in-node-object n) v)
2641 (js2-visit-ast (js2-for-in-node-body n) v))
2642
2643 (defun js2-print-for-in-node (n i)
2644 (let ((pad (js2-make-pad i))
2645 (foreach (js2-for-in-node-foreach-p n))
2646 (forof (js2-for-in-node-forof-p n)))
2647 (insert pad "for ")
2648 (if foreach
2649 (insert "each "))
2650 (insert "(")
2651 (js2-print-ast (js2-for-in-node-iterator n) 0)
2652 (insert (if forof " of " " in "))
2653 (js2-print-ast (js2-for-in-node-object n) 0)
2654 (insert ") {\n")
2655 (js2-print-body (js2-for-in-node-body n) (1+ i))
2656 (insert pad "}\n")))
2657
2658 (cl-defstruct (js2-return-node
2659 (:include js2-node)
2660 (:constructor nil)
2661 (:constructor make-js2-return-node (&key (type js2-RETURN)
2662 (pos js2-ts-cursor)
2663 len
2664 retval)))
2665 "AST node for a return statement."
2666 retval) ; expression to return, or 'undefined
2667
2668 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2669 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2670
2671 (defun js2-visit-return-node (n v)
2672 (js2-visit-ast (js2-return-node-retval n) v))
2673
2674 (defun js2-print-return-node (n i)
2675 (insert (js2-make-pad i) "return")
2676 (when (js2-return-node-retval n)
2677 (insert " ")
2678 (js2-print-ast (js2-return-node-retval n) 0))
2679 (insert ";\n"))
2680
2681 (cl-defstruct (js2-if-node
2682 (:include js2-node)
2683 (:constructor nil)
2684 (:constructor make-js2-if-node (&key (type js2-IF)
2685 (pos js2-ts-cursor)
2686 len condition
2687 then-part
2688 else-pos
2689 else-part lp
2690 rp)))
2691 "AST node for an if-statement."
2692 condition ; expression
2693 then-part ; statement or block
2694 else-pos ; optional buffer position of 'else' keyword
2695 else-part ; optional statement or block
2696 lp ; position of left-paren, nil if omitted
2697 rp) ; position of right-paren, nil if omitted
2698
2699 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2700 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2701
2702 (defun js2-visit-if-node (n v)
2703 (js2-visit-ast (js2-if-node-condition n) v)
2704 (js2-visit-ast (js2-if-node-then-part n) v)
2705 (js2-visit-ast (js2-if-node-else-part n) v))
2706
2707 (defun js2-print-if-node (n i)
2708 (let ((pad (js2-make-pad i))
2709 (then-part (js2-if-node-then-part n))
2710 (else-part (js2-if-node-else-part n)))
2711 (insert pad "if (")
2712 (js2-print-ast (js2-if-node-condition n) 0)
2713 (insert ") {\n")
2714 (js2-print-body then-part (1+ i))
2715 (insert pad "}")
2716 (cond
2717 ((not else-part)
2718 (insert "\n"))
2719 ((js2-if-node-p else-part)
2720 (insert " else ")
2721 (js2-print-body else-part i))
2722 (t
2723 (insert " else {\n")
2724 (js2-print-body else-part (1+ i))
2725 (insert pad "}\n")))))
2726
2727 (cl-defstruct (js2-export-binding-node
2728 (:include js2-node)
2729 (:constructor nil)
2730 (:constructor make-js2-export-binding-node (&key (type -1)
2731 pos
2732 len
2733 local-name
2734 extern-name)))
2735 "AST node for an external symbol binding.
2736 It contains a local-name node which is the name of the value in the
2737 current scope, and extern-name which is the name of the value in the
2738 imported or exported scope. By default these are the same, but if the
2739 name is aliased as in {foo as bar}, it would have an extern-name node
2740 containing 'foo' and a local-name node containing 'bar'."
2741 local-name ; js2-name-node with the variable name in this scope
2742 extern-name) ; js2-name-node with the value name in the exporting module
2743
2744 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2745 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2746
2747 (defun js2-visit-extern-binding (n v)
2748 "Visit an extern binding node. First visit the local-name, and, if
2749 different, visit the extern-name."
2750 (let ((local-name (js2-export-binding-node-local-name n))
2751 (extern-name (js2-export-binding-node-extern-name n)))
2752 (when local-name
2753 (js2-visit-ast local-name v))
2754 (when (not (equal local-name extern-name))
2755 (js2-visit-ast extern-name v))))
2756
2757 (defun js2-print-extern-binding (n _i)
2758 "Print a representation of a single extern binding. E.g. 'foo' or
2759 'foo as bar'."
2760 (let ((local-name (js2-export-binding-node-local-name n))
2761 (extern-name (js2-export-binding-node-extern-name n)))
2762 (insert (js2-name-node-name extern-name))
2763 (when (not (equal local-name extern-name))
2764 (insert " as ")
2765 (insert (js2-name-node-name local-name)))))
2766
2767
2768 (cl-defstruct (js2-import-node
2769 (:include js2-node)
2770 (:constructor nil)
2771 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2772 (pos (js2-current-token-beg))
2773 len
2774 import
2775 from
2776 module-id)))
2777 "AST node for an import statement. It follows the form
2778
2779 import ModuleSpecifier;
2780 import ImportClause FromClause;"
2781 import ; js2-import-clause-node specifying which names are to imported.
2782 from ; js2-from-clause-node indicating the module from which to import.
2783 module-id) ; module-id of the import. E.g. 'src/mylib'.
2784
2785 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2786 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2787
2788 (defun js2-visit-import (n v)
2789 (let ((import-clause (js2-import-node-import n))
2790 (from-clause (js2-import-node-from n)))
2791 (when import-clause
2792 (js2-visit-ast import-clause v))
2793 (when from-clause
2794 (js2-visit-ast from-clause v))))
2795
2796 (defun js2-print-import (n i)
2797 "Prints a representation of the import node"
2798 (let ((pad (js2-make-pad i))
2799 (import-clause (js2-import-node-import n))
2800 (from-clause (js2-import-node-from n))
2801 (module-id (js2-import-node-module-id n)))
2802 (insert pad "import ")
2803 (if import-clause
2804 (progn
2805 (js2-print-import-clause import-clause)
2806 (insert " ")
2807 (js2-print-from-clause from-clause))
2808 (insert "'")
2809 (insert module-id)
2810 (insert "'"))
2811 (insert ";\n")))
2812
2813 (cl-defstruct (js2-import-clause-node
2814 (:include js2-node)
2815 (:constructor nil)
2816 (:constructor make-js2-import-clause-node (&key (type -1)
2817 pos
2818 len
2819 namespace-import
2820 named-imports
2821 default-binding)))
2822 "AST node corresponding to the import clause of an import statement. This is
2823 the portion of the import that bindings names from the external context to the
2824 local context."
2825 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2826 named-imports ; lisp list of js2-export-binding-node for all named imports.
2827 default-binding) ; js2-export-binding-node for the default import binding
2828
2829 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2830 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2831
2832 (defun js2-visit-import-clause (n v)
2833 (let ((ns-import (js2-import-clause-node-namespace-import n))
2834 (named-imports (js2-import-clause-node-named-imports n))
2835 (default (js2-import-clause-node-default-binding n)))
2836 (when ns-import
2837 (js2-visit-ast ns-import v))
2838 (when named-imports
2839 (dolist (import named-imports)
2840 (js2-visit-ast import v)))
2841 (when default
2842 (js2-visit-ast default v))))
2843
2844 (defun js2-print-import-clause (n)
2845 (let ((ns-import (js2-import-clause-node-namespace-import n))
2846 (named-imports (js2-import-clause-node-named-imports n))
2847 (default (js2-import-clause-node-default-binding n)))
2848 (cond
2849 ((and default ns-import)
2850 (js2-print-ast default)
2851 (insert ", ")
2852 (js2-print-namespace-import ns-import))
2853 ((and default named-imports)
2854 (js2-print-ast default)
2855 (insert ", ")
2856 (js2-print-named-imports named-imports))
2857 (default
2858 (js2-print-ast default))
2859 (ns-import
2860 (js2-print-namespace-import ns-import))
2861 (named-imports
2862 (js2-print-named-imports named-imports)))))
2863
2864 (defun js2-print-namespace-import (node)
2865 (insert "* as ")
2866 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2867
2868 (defun js2-print-named-imports (imports)
2869 (insert "{")
2870 (let ((len (length imports))
2871 (n 0))
2872 (while (< n len)
2873 (js2-print-extern-binding (nth n imports) 0)
2874 (unless (= n (- len 1))
2875 (insert ", "))
2876 (setq n (+ n 1))))
2877 (insert "}"))
2878
2879 (cl-defstruct (js2-namespace-import-node
2880 (:include js2-node)
2881 (:constructor nil)
2882 (:constructor make-js2-namespace-import-node (&key (type -1)
2883 pos
2884 len
2885 name)))
2886 "AST node for a complete namespace import.
2887 E.g. the '* as lib' expression in:
2888
2889 import * as lib from 'src/lib'
2890
2891 It contains a single name node referring to the bound name."
2892 name) ; js2-name-node of the bound name.
2893
2894 (defun js2-visit-namespace-import (n v)
2895 (js2-visit-ast (js2-namespace-import-node-name n) v))
2896
2897 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2898 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2899
2900 (cl-defstruct (js2-from-clause-node
2901 (:include js2-node)
2902 (:constructor nil)
2903 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2904 pos
2905 len
2906 module-id
2907 metadata-p)))
2908 "AST node for the from clause in an import or export statement.
2909 E.g. from 'my/module'. It can refere to either an external module, or to the
2910 modules metadata itself."
2911 module-id ; string containing the module specifier.
2912 metadata-p) ; true if this clause refers to the module's metadata
2913
2914 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2915 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2916
2917 (defun js2-print-from-clause (n)
2918 (insert "from ")
2919 (if (js2-from-clause-node-metadata-p n)
2920 (insert "this module")
2921 (insert "'")
2922 (insert (js2-from-clause-node-module-id n))
2923 (insert "'")))
2924
2925 (cl-defstruct (js2-try-node
2926 (:include js2-node)
2927 (:constructor nil)
2928 (:constructor make-js2-try-node (&key (type js2-TRY)
2929 (pos js2-ts-cursor)
2930 len
2931 try-block
2932 catch-clauses
2933 finally-block)))
2934 "AST node for a try-statement."
2935 try-block
2936 catch-clauses ; a Lisp list of `js2-catch-node'
2937 finally-block) ; a `js2-finally-node'
2938
2939 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2940 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2941
2942 (defun js2-visit-try-node (n v)
2943 (js2-visit-ast (js2-try-node-try-block n) v)
2944 (dolist (clause (js2-try-node-catch-clauses n))
2945 (js2-visit-ast clause v))
2946 (js2-visit-ast (js2-try-node-finally-block n) v))
2947
2948 (defun js2-print-try-node (n i)
2949 (let ((pad (js2-make-pad i))
2950 (catches (js2-try-node-catch-clauses n))
2951 (finally (js2-try-node-finally-block n)))
2952 (insert pad "try {\n")
2953 (js2-print-body (js2-try-node-try-block n) (1+ i))
2954 (insert pad "}")
2955 (when catches
2956 (dolist (catch catches)
2957 (js2-print-ast catch i)))
2958 (if finally
2959 (js2-print-ast finally i)
2960 (insert "\n"))))
2961
2962 (cl-defstruct (js2-catch-node
2963 (:include js2-scope)
2964 (:constructor nil)
2965 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2966 (pos js2-ts-cursor)
2967 len
2968 param
2969 guard-kwd
2970 guard-expr
2971 lp rp)))
2972 "AST node for a catch clause."
2973 param ; destructuring form or simple name node
2974 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2975 guard-expr ; catch condition, a `js2-node'
2976 lp ; buffer position of left-paren, nil if omitted
2977 rp) ; buffer position of right-paren, nil if omitted
2978
2979 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2980 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2981
2982 (defun js2-visit-catch-node (n v)
2983 (js2-visit-ast (js2-catch-node-param n) v)
2984 (when (js2-catch-node-guard-kwd n)
2985 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2986 (js2-visit-block n v))
2987
2988 (defun js2-print-catch-node (n i)
2989 (let ((pad (js2-make-pad i))
2990 (guard-kwd (js2-catch-node-guard-kwd n))
2991 (guard-expr (js2-catch-node-guard-expr n)))
2992 (insert " catch (")
2993 (js2-print-ast (js2-catch-node-param n) 0)
2994 (when guard-kwd
2995 (insert " if ")
2996 (js2-print-ast guard-expr 0))
2997 (insert ") {\n")
2998 (js2-print-body n (1+ i))
2999 (insert pad "}")))
3000
3001 (cl-defstruct (js2-finally-node
3002 (:include js2-node)
3003 (:constructor nil)
3004 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3005 (pos js2-ts-cursor)
3006 len body)))
3007 "AST node for a finally clause."
3008 body) ; a `js2-node', often but not always a block node
3009
3010 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3011 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3012
3013 (defun js2-visit-finally-node (n v)
3014 (js2-visit-ast (js2-finally-node-body n) v))
3015
3016 (defun js2-print-finally-node (n i)
3017 (let ((pad (js2-make-pad i)))
3018 (insert " finally {\n")
3019 (js2-print-body (js2-finally-node-body n) (1+ i))
3020 (insert pad "}\n")))
3021
3022 (cl-defstruct (js2-switch-node
3023 (:include js2-node)
3024 (:constructor nil)
3025 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3026 (pos js2-ts-cursor)
3027 len
3028 discriminant
3029 cases lp
3030 rp)))
3031 "AST node for a switch statement."
3032 discriminant ; a `js2-node' (switch expression)
3033 cases ; a Lisp list of `js2-case-node'
3034 lp ; position of open-paren for discriminant, nil if omitted
3035 rp) ; position of close-paren for discriminant, nil if omitted
3036
3037 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3038 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3039
3040 (defun js2-visit-switch-node (n v)
3041 (js2-visit-ast (js2-switch-node-discriminant n) v)
3042 (dolist (c (js2-switch-node-cases n))
3043 (js2-visit-ast c v)))
3044
3045 (defun js2-print-switch-node (n i)
3046 (let ((pad (js2-make-pad i))
3047 (cases (js2-switch-node-cases n)))
3048 (insert pad "switch (")
3049 (js2-print-ast (js2-switch-node-discriminant n) 0)
3050 (insert ") {\n")
3051 (dolist (case cases)
3052 (js2-print-ast case i))
3053 (insert pad "}\n")))
3054
3055 (cl-defstruct (js2-case-node
3056 (:include js2-block-node)
3057 (:constructor nil)
3058 (:constructor make-js2-case-node (&key (type js2-CASE)
3059 (pos js2-ts-cursor)
3060 len kids expr)))
3061 "AST node for a case clause of a switch statement."
3062 expr) ; the case expression (nil for default)
3063
3064 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3065 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3066
3067 (defun js2-visit-case-node (n v)
3068 (js2-visit-ast (js2-case-node-expr n) v)
3069 (js2-visit-block n v))
3070
3071 (defun js2-print-case-node (n i)
3072 (let ((pad (js2-make-pad i))
3073 (expr (js2-case-node-expr n)))
3074 (insert pad)
3075 (if (null expr)
3076 (insert "default:\n")
3077 (insert "case ")
3078 (js2-print-ast expr 0)
3079 (insert ":\n"))
3080 (dolist (kid (js2-case-node-kids n))
3081 (js2-print-ast kid (1+ i)))))
3082
3083 (cl-defstruct (js2-throw-node
3084 (:include js2-node)
3085 (:constructor nil)
3086 (:constructor make-js2-throw-node (&key (type js2-THROW)
3087 (pos js2-ts-cursor)
3088 len expr)))
3089 "AST node for a throw statement."
3090 expr) ; the expression to throw
3091
3092 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3093 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3094
3095 (defun js2-visit-throw-node (n v)
3096 (js2-visit-ast (js2-throw-node-expr n) v))
3097
3098 (defun js2-print-throw-node (n i)
3099 (insert (js2-make-pad i) "throw ")
3100 (js2-print-ast (js2-throw-node-expr n) 0)
3101 (insert ";\n"))
3102
3103 (cl-defstruct (js2-with-node
3104 (:include js2-node)
3105 (:constructor nil)
3106 (:constructor make-js2-with-node (&key (type js2-WITH)
3107 (pos js2-ts-cursor)
3108 len object
3109 body lp rp)))
3110 "AST node for a with-statement."
3111 object
3112 body
3113 lp ; buffer position of left-paren around object, nil if omitted
3114 rp) ; buffer position of right-paren around object, nil if omitted
3115
3116 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3117 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3118
3119 (defun js2-visit-with-node (n v)
3120 (js2-visit-ast (js2-with-node-object n) v)
3121 (js2-visit-ast (js2-with-node-body n) v))
3122
3123 (defun js2-print-with-node (n i)
3124 (let ((pad (js2-make-pad i)))
3125 (insert pad "with (")
3126 (js2-print-ast (js2-with-node-object n) 0)
3127 (insert ") {\n")
3128 (js2-print-body (js2-with-node-body n) (1+ i))
3129 (insert pad "}\n")))
3130
3131 (cl-defstruct (js2-label-node
3132 (:include js2-node)
3133 (:constructor nil)
3134 (:constructor make-js2-label-node (&key (type js2-LABEL)
3135 (pos js2-ts-cursor)
3136 len name)))
3137 "AST node for a statement label or case label."
3138 name ; a string
3139 loop) ; for validating and code-generating continue-to-label
3140
3141 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3142 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3143
3144 (defun js2-print-label (n i)
3145 (insert (js2-make-pad i)
3146 (js2-label-node-name n)
3147 ":\n"))
3148
3149 (cl-defstruct (js2-labeled-stmt-node
3150 (:include js2-node)
3151 (:constructor nil)
3152 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3153 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3154 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3155 (pos js2-ts-cursor)
3156 len labels stmt)))
3157 "AST node for a statement with one or more labels.
3158 Multiple labels for a statement are collapsed into the labels field."
3159 labels ; Lisp list of `js2-label-node'
3160 stmt) ; the statement these labels are for
3161
3162 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3163 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3164
3165 (defun js2-get-label-by-name (lbl-stmt name)
3166 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3167 Returns nil if no such label is in the list."
3168 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3169 result)
3170 (while (and label-list (not result))
3171 (if (string= (js2-label-node-name (car label-list)) name)
3172 (setq result (car label-list))
3173 (setq label-list (cdr label-list))))
3174 result))
3175
3176 (defun js2-visit-labeled-stmt (n v)
3177 (dolist (label (js2-labeled-stmt-node-labels n))
3178 (js2-visit-ast label v))
3179 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3180
3181 (defun js2-print-labeled-stmt (n i)
3182 (dolist (label (js2-labeled-stmt-node-labels n))
3183 (js2-print-ast label i))
3184 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3185
3186 (defun js2-labeled-stmt-node-contains (node label)
3187 "Return t if NODE contains LABEL in its label set.
3188 NODE is a `js2-labels-node'. LABEL is an identifier."
3189 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3190 if (string= label (js2-label-node-name nl))
3191 return t
3192 finally return nil))
3193
3194 (defsubst js2-labeled-stmt-node-add-label (node label)
3195 "Add a `js2-label-node' to the label set for this statement."
3196 (setf (js2-labeled-stmt-node-labels node)
3197 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3198
3199 (cl-defstruct (js2-jump-node
3200 (:include js2-node)
3201 (:constructor nil))
3202 "Abstract supertype of break and continue nodes."
3203 label ; `js2-name-node' for location of label identifier, if present
3204 target) ; target js2-labels-node or loop/switch statement
3205
3206 (defun js2-visit-jump-node (n v)
3207 ;; We don't visit the target, since it's a back-link.
3208 (js2-visit-ast (js2-jump-node-label n) v))
3209
3210 (cl-defstruct (js2-break-node
3211 (:include js2-jump-node)
3212 (:constructor nil)
3213 (:constructor make-js2-break-node (&key (type js2-BREAK)
3214 (pos js2-ts-cursor)
3215 len label target)))
3216 "AST node for a break statement.
3217 The label field is a `js2-name-node', possibly nil, for the named label
3218 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3219 is the target of the break - a label node or enclosing loop/switch statement.")
3220
3221 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3222 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3223
3224 (defun js2-print-break-node (n i)
3225 (insert (js2-make-pad i) "break")
3226 (when (js2-break-node-label n)
3227 (insert " ")
3228 (js2-print-ast (js2-break-node-label n) 0))
3229 (insert ";\n"))
3230
3231 (cl-defstruct (js2-continue-node
3232 (:include js2-jump-node)
3233 (:constructor nil)
3234 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3235 (pos js2-ts-cursor)
3236 len label target)))
3237 "AST node for a continue statement.
3238 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3239 It is nil if continue specifies no label. The target field is the jump target:
3240 a `js2-label-node' or the innermost enclosing loop.")
3241
3242 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3243 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3244
3245 (defun js2-print-continue-node (n i)
3246 (insert (js2-make-pad i) "continue")
3247 (when (js2-continue-node-label n)
3248 (insert " ")
3249 (js2-print-ast (js2-continue-node-label n) 0))
3250 (insert ";\n"))
3251
3252 (cl-defstruct (js2-function-node
3253 (:include js2-script-node)
3254 (:constructor nil)
3255 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3256 (pos js2-ts-cursor)
3257 len
3258 (ftype 'FUNCTION)
3259 (form 'FUNCTION_STATEMENT)
3260 (name "")
3261 params rest-p
3262 body
3263 generator-type
3264 async
3265 lp rp)))
3266 "AST node for a function declaration.
3267 The `params' field is a Lisp list of nodes. Each node is either a simple
3268 `js2-name-node', or if it's a destructuring-assignment parameter, a
3269 `js2-array-node' or `js2-object-node'."
3270 ftype ; FUNCTION, GETTER or SETTER
3271 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3272 name ; function name (a `js2-name-node', or nil if anonymous)
3273 params ; a Lisp list of destructuring forms or simple name nodes
3274 rest-p ; if t, the last parameter is rest parameter
3275 body ; a `js2-block-node' or expression node (1.8 only)
3276 lp ; position of arg-list open-paren, or nil if omitted
3277 rp ; position of arg-list close-paren, or nil if omitted
3278 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3279 needs-activation ; t if we need an activation object for this frame
3280 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3281 async ; t if the function is defined as `async function`
3282 member-expr) ; nonstandard Ecma extension from Rhino
3283
3284 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3285 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3286
3287 (defun js2-visit-function-node (n v)
3288 (js2-visit-ast (js2-function-node-name n) v)
3289 (dolist (p (js2-function-node-params n))
3290 (js2-visit-ast p v))
3291 (js2-visit-ast (js2-function-node-body n) v))
3292
3293 (defun js2-print-function-node (n i)
3294 (let* ((pad (js2-make-pad i))
3295 (method (js2-node-get-prop n 'METHOD_TYPE))
3296 (name (or (js2-function-node-name n)
3297 (js2-function-node-member-expr n)))
3298 (params (js2-function-node-params n))
3299 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3300 (rest-p (js2-function-node-rest-p n))
3301 (body (js2-function-node-body n))
3302 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3303 (unless method
3304 (insert pad)
3305 (when (js2-function-node-async n) (insert "async "))
3306 (unless arrow (insert "function"))
3307 (when (eq (js2-function-node-generator-type n) 'STAR)
3308 (insert "*")))
3309 (when name
3310 (insert " ")
3311 (js2-print-ast name 0))
3312 (insert "(")
3313 (cl-loop with len = (length params)
3314 for param in params
3315 for count from 1
3316 do
3317 (when (and rest-p (= count len))
3318 (insert "..."))
3319 (js2-print-ast param 0)
3320 (when (< count len)
3321 (insert ", ")))
3322 (insert ") ")
3323 (when arrow
3324 (insert "=> "))
3325 (insert "{")
3326 ;; TODO: fix this to be smarter about indenting, etc.
3327 (unless expr
3328 (insert "\n"))
3329 (if (js2-block-node-p body)
3330 (js2-print-body body (1+ i))
3331 (js2-print-ast body 0))
3332 (insert pad "}")
3333 (unless expr
3334 (insert "\n"))))
3335
3336 (defun js2-function-name (node)
3337 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3338 (and (js2-function-node-name node)
3339 (js2-name-node-name (js2-function-node-name node))))
3340
3341 ;; Having this be an expression node makes it more flexible.
3342 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3343 ;; that work better if you assume it's an expression. Whenever we have
3344 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3345 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3346 (cl-defstruct (js2-var-decl-node
3347 (:include js2-node)
3348 (:constructor nil)
3349 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3350 (pos (js2-current-token-beg))
3351 len kids
3352 decl-type)))
3353 "AST node for a variable declaration list (VAR, CONST or LET).
3354 The node bounds differ depending on the declaration type. For VAR or
3355 CONST declarations, the bounds include the var/const keyword. For LET
3356 declarations, the node begins at the position of the first child."
3357 kids ; a Lisp list of `js2-var-init-node' structs.
3358 decl-type) ; js2-VAR, js2-CONST or js2-LET
3359
3360 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3361 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3362
3363 (defun js2-visit-var-decl (n v)
3364 (dolist (kid (js2-var-decl-node-kids n))
3365 (js2-visit-ast kid v)))
3366
3367 (defun js2-print-var-decl (n i)
3368 (let ((pad (js2-make-pad i))
3369 (tt (js2-var-decl-node-decl-type n)))
3370 (insert pad)
3371 (insert (cond
3372 ((= tt js2-VAR) "var ")
3373 ((= tt js2-LET) "let ")
3374 ((= tt js2-CONST) "const ")
3375 (t
3376 (error "malformed var-decl node"))))
3377 (cl-loop with kids = (js2-var-decl-node-kids n)
3378 with len = (length kids)
3379 for kid in kids
3380 for count from 1
3381 do
3382 (js2-print-ast kid 0)
3383 (if (< count len)
3384 (insert ", ")))))
3385
3386 (cl-defstruct (js2-var-init-node
3387 (:include js2-node)
3388 (:constructor nil)
3389 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3390 (pos js2-ts-cursor)
3391 len target
3392 initializer)))
3393 "AST node for a variable declaration.
3394 The type field will be js2-CONST for a const decl."
3395 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3396 initializer) ; initializer expression, a `js2-node'
3397
3398 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3399 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3400
3401 (defun js2-visit-var-init-node (n v)
3402 (js2-visit-ast (js2-var-init-node-target n) v)
3403 (js2-visit-ast (js2-var-init-node-initializer n) v))
3404
3405 (defun js2-print-var-init-node (n i)
3406 (let ((pad (js2-make-pad i))
3407 (name (js2-var-init-node-target n))
3408 (init (js2-var-init-node-initializer n)))
3409 (insert pad)
3410 (js2-print-ast name 0)
3411 (when init
3412 (insert " = ")
3413 (js2-print-ast init 0))))
3414
3415 (cl-defstruct (js2-cond-node
3416 (:include js2-node)
3417 (:constructor nil)
3418 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3419 (pos js2-ts-cursor)
3420 len
3421 test-expr
3422 true-expr
3423 false-expr
3424 q-pos c-pos)))
3425 "AST node for the ternary operator"
3426 test-expr
3427 true-expr
3428 false-expr
3429 q-pos ; buffer position of ?
3430 c-pos) ; buffer position of :
3431
3432 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3433 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3434
3435 (defun js2-visit-cond-node (n v)
3436 (js2-visit-ast (js2-cond-node-test-expr n) v)
3437 (js2-visit-ast (js2-cond-node-true-expr n) v)
3438 (js2-visit-ast (js2-cond-node-false-expr n) v))
3439
3440 (defun js2-print-cond-node (n i)
3441 (let ((pad (js2-make-pad i)))
3442 (insert pad)
3443 (js2-print-ast (js2-cond-node-test-expr n) 0)
3444 (insert " ? ")
3445 (js2-print-ast (js2-cond-node-true-expr n) 0)
3446 (insert " : ")
3447 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3448
3449 (cl-defstruct (js2-infix-node
3450 (:include js2-node)
3451 (:constructor nil)
3452 (:constructor make-js2-infix-node (&key type
3453 (pos js2-ts-cursor)
3454 len op-pos
3455 left right)))
3456 "Represents infix expressions.
3457 Includes assignment ops like `|=', and the comma operator.
3458 The type field inherited from `js2-node' holds the operator."
3459 op-pos ; buffer position where operator begins
3460 left ; any `js2-node'
3461 right) ; any `js2-node'
3462
3463 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3464 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3465
3466 (defun js2-visit-infix-node (n v)
3467 (js2-visit-ast (js2-infix-node-left n) v)
3468 (js2-visit-ast (js2-infix-node-right n) v))
3469
3470 (defconst js2-operator-tokens
3471 (let ((table (make-hash-table :test 'eq))
3472 (tokens
3473 (list (cons js2-IN "in")
3474 (cons js2-TYPEOF "typeof")
3475 (cons js2-INSTANCEOF "instanceof")
3476 (cons js2-DELPROP "delete")
3477 (cons js2-AWAIT "await")
3478 (cons js2-COMMA ",")
3479 (cons js2-COLON ":")
3480 (cons js2-OR "||")
3481 (cons js2-AND "&&")
3482 (cons js2-INC "++")
3483 (cons js2-DEC "--")
3484 (cons js2-BITOR "|")
3485 (cons js2-BITXOR "^")
3486 (cons js2-BITAND "&")
3487 (cons js2-EQ "==")
3488 (cons js2-NE "!=")
3489 (cons js2-LT "<")
3490 (cons js2-LE "<=")
3491 (cons js2-GT ">")
3492 (cons js2-GE ">=")
3493 (cons js2-LSH "<<")
3494 (cons js2-RSH ">>")
3495 (cons js2-URSH ">>>")
3496 (cons js2-ADD "+") ; infix plus
3497 (cons js2-SUB "-") ; infix minus
3498 (cons js2-MUL "*")
3499 (cons js2-DIV "/")
3500 (cons js2-MOD "%")
3501 (cons js2-NOT "!")
3502 (cons js2-BITNOT "~")
3503 (cons js2-POS "+") ; unary plus
3504 (cons js2-NEG "-") ; unary minus
3505 (cons js2-TRIPLEDOT "...")
3506 (cons js2-SHEQ "===") ; shallow equality
3507 (cons js2-SHNE "!==") ; shallow inequality
3508 (cons js2-ASSIGN "=")
3509 (cons js2-ASSIGN_BITOR "|=")
3510 (cons js2-ASSIGN_BITXOR "^=")
3511 (cons js2-ASSIGN_BITAND "&=")
3512 (cons js2-ASSIGN_LSH "<<=")
3513 (cons js2-ASSIGN_RSH ">>=")
3514 (cons js2-ASSIGN_URSH ">>>=")
3515 (cons js2-ASSIGN_ADD "+=")
3516 (cons js2-ASSIGN_SUB "-=")
3517 (cons js2-ASSIGN_MUL "*=")
3518 (cons js2-ASSIGN_DIV "/=")
3519 (cons js2-ASSIGN_MOD "%="))))
3520 (cl-loop for (k . v) in tokens do
3521 (puthash k v table))
3522 table))
3523
3524 (defun js2-print-infix-node (n i)
3525 (let* ((tt (js2-node-type n))
3526 (op (gethash tt js2-operator-tokens)))
3527 (unless op
3528 (error "unrecognized infix operator %s" (js2-node-type n)))
3529 (insert (js2-make-pad i))
3530 (js2-print-ast (js2-infix-node-left n) 0)
3531 (unless (= tt js2-COMMA)
3532 (insert " "))
3533 (insert op)
3534 (insert " ")
3535 (js2-print-ast (js2-infix-node-right n) 0)))
3536
3537 (cl-defstruct (js2-assign-node
3538 (:include js2-infix-node)
3539 (:constructor nil)
3540 (:constructor make-js2-assign-node (&key type
3541 (pos js2-ts-cursor)
3542 len op-pos
3543 left right)))
3544 "Represents any assignment.
3545 The type field holds the actual assignment operator.")
3546
3547 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3548 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3549
3550 (cl-defstruct (js2-unary-node
3551 (:include js2-node)
3552 (:constructor nil)
3553 (:constructor make-js2-unary-node (&key type ; required
3554 (pos js2-ts-cursor)
3555 len operand)))
3556 "AST node type for unary operator nodes.
3557 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3558 TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
3559 property is added if the operator follows the operand."
3560 operand) ; a `js2-node' expression
3561
3562 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3563 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3564
3565 (defun js2-visit-unary-node (n v)
3566 (js2-visit-ast (js2-unary-node-operand n) v))
3567
3568 (defun js2-print-unary-node (n i)
3569 (let* ((tt (js2-node-type n))
3570 (op (gethash tt js2-operator-tokens))
3571 (postfix (js2-node-get-prop n 'postfix)))
3572 (unless op
3573 (error "unrecognized unary operator %s" tt))
3574 (insert (js2-make-pad i))
3575 (unless postfix
3576 (insert op))
3577 (if (or (= tt js2-TYPEOF)
3578 (= tt js2-DELPROP)
3579 (= tt js2-AWAIT))
3580 (insert " "))
3581 (js2-print-ast (js2-unary-node-operand n) 0)
3582 (when postfix
3583 (insert op))))
3584
3585 (cl-defstruct (js2-let-node
3586 (:include js2-scope)
3587 (:constructor nil)
3588 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3589 (pos (js2-current-token-beg))
3590 len vars body
3591 lp rp)))
3592 "AST node for a let expression or a let statement.
3593 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3594 vars ; a `js2-var-decl-node'
3595 body ; a `js2-node' representing the expression or body block
3596 lp
3597 rp)
3598
3599 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3600 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3601
3602 (defun js2-visit-let-node (n v)
3603 (js2-visit-ast (js2-let-node-vars n) v)
3604 (js2-visit-ast (js2-let-node-body n) v))
3605
3606 (defun js2-print-let-node (n i)
3607 (insert (js2-make-pad i) "let (")
3608 (let ((p (point)))
3609 (js2-print-ast (js2-let-node-vars n) 0)
3610 (delete-region p (+ p 4)))
3611 (insert ") ")
3612 (js2-print-ast (js2-let-node-body n) i))
3613
3614 (cl-defstruct (js2-keyword-node
3615 (:include js2-node)
3616 (:constructor nil)
3617 (:constructor make-js2-keyword-node (&key type
3618 (pos (js2-current-token-beg))
3619 (len (- js2-ts-cursor pos)))))
3620 "AST node representing a literal keyword such as `null'.
3621 Used for `null', `this', `true', `false' and `debugger'.
3622 The node type is set to js2-NULL, js2-THIS, etc.")
3623
3624 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3625 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3626
3627 (defun js2-print-keyword-node (n i)
3628 (insert (js2-make-pad i)
3629 (let ((tt (js2-node-type n)))
3630 (cond
3631 ((= tt js2-THIS) "this")
3632 ((= tt js2-SUPER) "super")
3633 ((= tt js2-NULL) "null")
3634 ((= tt js2-TRUE) "true")
3635 ((= tt js2-FALSE) "false")
3636 ((= tt js2-DEBUGGER) "debugger")
3637 (t (error "Invalid keyword literal type: %d" tt))))))
3638
3639 (defsubst js2-this-or-super-node-p (node)
3640 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3641 (let ((type (js2-node-type node)))
3642 (or (eq type js2-THIS) (eq type js2-SUPER))))
3643
3644 (cl-defstruct (js2-new-node
3645 (:include js2-node)
3646 (:constructor nil)
3647 (:constructor make-js2-new-node (&key (type js2-NEW)
3648 (pos (js2-current-token-beg))
3649 len target
3650 args initializer
3651 lp rp)))
3652 "AST node for new-expression such as new Foo()."
3653 target ; an identifier or reference
3654 args ; a Lisp list of argument nodes
3655 lp ; position of left-paren, nil if omitted
3656 rp ; position of right-paren, nil if omitted
3657 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3658
3659 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3660 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3661
3662 (defun js2-visit-new-node (n v)
3663 (js2-visit-ast (js2-new-node-target n) v)
3664 (dolist (arg (js2-new-node-args n))
3665 (js2-visit-ast arg v))
3666 (js2-visit-ast (js2-new-node-initializer n) v))
3667
3668 (defun js2-print-new-node (n i)
3669 (insert (js2-make-pad i) "new ")
3670 (js2-print-ast (js2-new-node-target n))
3671 (insert "(")
3672 (js2-print-list (js2-new-node-args n))
3673 (insert ")")
3674 (when (js2-new-node-initializer n)
3675 (insert " ")
3676 (js2-print-ast (js2-new-node-initializer n))))
3677
3678 (cl-defstruct (js2-name-node
3679 (:include js2-node)
3680 (:constructor nil)
3681 (:constructor make-js2-name-node (&key (type js2-NAME)
3682 (pos (js2-current-token-beg))
3683 (len (- js2-ts-cursor
3684 (js2-current-token-beg)))
3685 (name (js2-current-token-string)))))
3686 "AST node for a JavaScript identifier"
3687 name ; a string
3688 scope) ; a `js2-scope' (optional, used for codegen)
3689
3690 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3691 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3692
3693 (defun js2-print-name-node (n i)
3694 (insert (js2-make-pad i)
3695 (js2-name-node-name n)))
3696
3697 (defsubst js2-name-node-length (node)
3698 "Return identifier length of NODE, a `js2-name-node'.
3699 Returns 0 if NODE is nil or its identifier field is nil."
3700 (if node
3701 (length (js2-name-node-name node))
3702 0))
3703
3704 (cl-defstruct (js2-number-node
3705 (:include js2-node)
3706 (:constructor nil)
3707 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3708 (pos (js2-current-token-beg))
3709 (len (- js2-ts-cursor
3710 (js2-current-token-beg)))
3711 (value (js2-current-token-string))
3712 (num-value (js2-token-number
3713 (js2-current-token)))
3714 (num-base (js2-token-number-base
3715 (js2-current-token))))))
3716 "AST node for a number literal."
3717 value ; the original string, e.g. "6.02e23"
3718 num-value ; the parsed number value
3719 num-base) ; the number's base
3720
3721 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3722 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3723
3724 (defun js2-print-number-node (n i)
3725 (insert (js2-make-pad i)
3726 (number-to-string (js2-number-node-num-value n))))
3727
3728 (cl-defstruct (js2-regexp-node
3729 (:include js2-node)
3730 (:constructor nil)
3731 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3732 (pos (js2-current-token-beg))
3733 (len (- js2-ts-cursor
3734 (js2-current-token-beg)))
3735 value flags)))
3736 "AST node for a regular expression literal."
3737 value ; the regexp string, without // delimiters
3738 flags) ; a string of flags, e.g. `mi'.
3739
3740 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3741 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3742
3743 (defun js2-print-regexp (n i)
3744 (insert (js2-make-pad i)
3745 "/"
3746 (js2-regexp-node-value n)
3747 "/")
3748 (if (js2-regexp-node-flags n)
3749 (insert (js2-regexp-node-flags n))))
3750
3751 (cl-defstruct (js2-string-node
3752 (:include js2-node)
3753 (:constructor nil)
3754 (:constructor make-js2-string-node (&key (type js2-STRING)
3755 (pos (js2-current-token-beg))
3756 (len (- js2-ts-cursor
3757 (js2-current-token-beg)))
3758 (value (js2-current-token-string)))))
3759 "String literal.
3760 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3761 You can tell the quote type by looking at the first character."
3762 value) ; the characters of the string, including the quotes
3763
3764 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3765 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3766
3767 (defun js2-print-string-node (n i)
3768 (insert (js2-make-pad i)
3769 (js2-node-string n)))
3770
3771 (cl-defstruct (js2-template-node
3772 (:include js2-node)
3773 (:constructor nil)
3774 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3775 beg len kids)))
3776 "Template literal."
3777 kids) ; `js2-string-node' is used for string segments, other nodes
3778 ; for substitutions inside.
3779
3780 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3781 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3782
3783 (defun js2-visit-template (n callback)
3784 (dolist (kid (js2-template-node-kids n))
3785 (js2-visit-ast kid callback)))
3786
3787 (defun js2-print-template (n i)
3788 (insert (js2-make-pad i))
3789 (dolist (kid (js2-template-node-kids n))
3790 (if (js2-string-node-p kid)
3791 (insert (js2-node-string kid))
3792 (js2-print-ast kid))))
3793
3794 (cl-defstruct (js2-tagged-template-node
3795 (:include js2-node)
3796 (:constructor nil)
3797 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3798 beg len tag template)))
3799 "Tagged template literal."
3800 tag ; `js2-node' with the tag expression.
3801 template) ; `js2-template-node' with the template.
3802
3803 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3804 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3805
3806 (defun js2-visit-tagged-template (n callback)
3807 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3808 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3809
3810 (defun js2-print-tagged-template (n i)
3811 (insert (js2-make-pad i))
3812 (js2-print-ast (js2-tagged-template-node-tag n))
3813 (js2-print-ast (js2-tagged-template-node-template n)))
3814
3815 (cl-defstruct (js2-array-node
3816 (:include js2-node)
3817 (:constructor nil)
3818 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3819 (pos js2-ts-cursor)
3820 len elems)))
3821 "AST node for an array literal."
3822 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3823
3824 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3825 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3826
3827 (defun js2-visit-array-node (n v)
3828 (dolist (e (js2-array-node-elems n))
3829 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3830
3831 (defun js2-print-array-node (n i)
3832 (insert (js2-make-pad i) "[")
3833 (let ((elems (js2-array-node-elems n)))
3834 (js2-print-list elems)
3835 (when (and elems (null (car (last elems))))
3836 (insert ",")))
3837 (insert "]"))
3838
3839 (cl-defstruct (js2-class-node
3840 (:include js2-node)
3841 (:constructor nil)
3842 (:constructor make-js2-class-node (&key (type js2-CLASS)
3843 (pos js2-ts-cursor)
3844 (form 'CLASS_STATEMENT)
3845 (name "")
3846 extends len elems)))
3847 "AST node for an class expression.
3848 `elems' is a list of `js2-object-prop-node', and `extends' is an
3849 optional `js2-expr-node'"
3850 form ; CLASS_{STATEMENT|EXPRESSION}
3851 name ; class name (a `js2-node-name', or nil if anonymous)
3852 extends ; class heritage (a `js2-expr-node', or nil if none)
3853 elems)
3854
3855 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3856 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3857
3858 (defun js2-visit-class-node (n v)
3859 (js2-visit-ast (js2-class-node-name n) v)
3860 (js2-visit-ast (js2-class-node-extends n) v)
3861 (dolist (e (js2-class-node-elems n))
3862 (js2-visit-ast e v)))
3863
3864 (defun js2-print-class-node (n i)
3865 (let* ((pad (js2-make-pad i))
3866 (name (js2-class-node-name n))
3867 (extends (js2-class-node-extends n))
3868 (elems (js2-class-node-elems n)))
3869 (insert pad "class")
3870 (when name
3871 (insert " ")
3872 (js2-print-ast name 0))
3873 (when extends
3874 (insert " extends ")
3875 (js2-print-ast extends))
3876 (insert " {")
3877 (dolist (elem elems)
3878 (insert "\n")
3879 (if (js2-node-get-prop elem 'STATIC)
3880 (progn (insert (js2-make-pad (1+ i)) "static ")
3881 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3882 (js2-print-ast elem (1+ i))))
3883 (insert "\n" pad "}")))
3884
3885 (cl-defstruct (js2-object-node
3886 (:include js2-node)
3887 (:constructor nil)
3888 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3889 (pos js2-ts-cursor)
3890 len
3891 elems)))
3892 "AST node for an object literal expression.
3893 `elems' is a list of `js2-object-prop-node'."
3894 elems)
3895
3896 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3897 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3898
3899 (defun js2-visit-object-node (n v)
3900 (dolist (e (js2-object-node-elems n))
3901 (js2-visit-ast e v)))
3902
3903 (defun js2-print-object-node (n i)
3904 (insert (js2-make-pad i) "{")
3905 (js2-print-list (js2-object-node-elems n))
3906 (insert "}"))
3907
3908 (cl-defstruct (js2-computed-prop-name-node
3909 (:include js2-node)
3910 (:constructor nil)
3911 (:constructor make-js2-computed-prop-name-node
3912 (&key
3913 (type js2-LB)
3914 expr
3915 (pos (js2-current-token-beg))
3916 (len (- js2-ts-cursor
3917 (js2-current-token-beg))))))
3918 "AST node for a `ComputedPropertyName'."
3919 expr)
3920
3921 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3922 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3923
3924 (defun js2-visit-computed-prop-name-node (n v)
3925 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3926
3927 (defun js2-print-computed-prop-name-node (n i)
3928 (insert (js2-make-pad i) "[")
3929 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3930 (insert "]"))
3931
3932 (cl-defstruct (js2-object-prop-node
3933 (:include js2-infix-node)
3934 (:constructor nil)
3935 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3936 (pos js2-ts-cursor)
3937 len left
3938 right op-pos)))
3939 "AST node for an object literal prop:value entry.
3940 The `left' field is the property: a name node, string node,
3941 number node or expression node. The `right' field is a
3942 `js2-node' representing the initializer value. If the property
3943 is abbreviated, the node's `SHORTHAND' property is non-nil and
3944 both fields have the same value.")
3945
3946 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3947 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3948
3949 (defun js2-print-object-prop-node (n i)
3950 (let* ((left (js2-object-prop-node-left n))
3951 (right (js2-object-prop-node-right n)))
3952 (js2-print-ast left i)
3953 (if (not (js2-node-get-prop n 'SHORTHAND))
3954 (progn
3955 (insert ": ")
3956 (js2-print-ast right 0)))))
3957
3958 (cl-defstruct (js2-method-node
3959 (:include js2-infix-node)
3960 (:constructor nil)
3961 (:constructor make-js2-method-node (&key (pos js2-ts-cursor)
3962 len left right)))
3963 "AST node for a method in an object literal or a class body.
3964 The `left' field is the `js2-name-node' naming the method.
3965 The `right' field is always an anonymous `js2-function-node' with a node
3966 property `METHOD_TYPE' set to 'GET or 'SET. ")
3967
3968 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3969 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3970
3971 (defun js2-print-method (n i)
3972 (let* ((pad (js2-make-pad i))
3973 (left (js2-method-node-left n))
3974 (right (js2-method-node-right n))
3975 (type (js2-node-get-prop right 'METHOD_TYPE)))
3976 (insert pad)
3977 (when type
3978 (insert (cdr (assoc type '((GET . "get ")
3979 (SET . "set ")
3980 (FUNCTION . ""))))))
3981 (when (and (js2-function-node-p right)
3982 (eq 'STAR (js2-function-node-generator-type right)))
3983 (insert "*"))
3984 (js2-print-ast left 0)
3985 (js2-print-ast right 0)))
3986
3987 (cl-defstruct (js2-prop-get-node
3988 (:include js2-infix-node)
3989 (:constructor nil)
3990 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3991 (pos js2-ts-cursor)
3992 len left right)))
3993 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3994
3995 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3996 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3997
3998 (defun js2-visit-prop-get-node (n v)
3999 (js2-visit-ast (js2-prop-get-node-left n) v)
4000 (js2-visit-ast (js2-prop-get-node-right n) v))
4001
4002 (defun js2-print-prop-get-node (n i)
4003 (insert (js2-make-pad i))
4004 (js2-print-ast (js2-prop-get-node-left n) 0)
4005 (insert ".")
4006 (js2-print-ast (js2-prop-get-node-right n) 0))
4007
4008 (cl-defstruct (js2-elem-get-node
4009 (:include js2-node)
4010 (:constructor nil)
4011 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4012 (pos js2-ts-cursor)
4013 len target element
4014 lb rb)))
4015 "AST node for an array index expression such as foo[bar]."
4016 target ; a `js2-node' - the expression preceding the "."
4017 element ; a `js2-node' - the expression in brackets
4018 lb ; position of left-bracket, nil if omitted
4019 rb) ; position of right-bracket, nil if omitted
4020
4021 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4022 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4023
4024 (defun js2-visit-elem-get-node (n v)
4025 (js2-visit-ast (js2-elem-get-node-target n) v)
4026 (js2-visit-ast (js2-elem-get-node-element n) v))
4027
4028 (defun js2-print-elem-get-node (n i)
4029 (insert (js2-make-pad i))
4030 (js2-print-ast (js2-elem-get-node-target n) 0)
4031 (insert "[")
4032 (js2-print-ast (js2-elem-get-node-element n) 0)
4033 (insert "]"))
4034
4035 (cl-defstruct (js2-call-node
4036 (:include js2-node)
4037 (:constructor nil)
4038 (:constructor make-js2-call-node (&key (type js2-CALL)
4039 (pos js2-ts-cursor)
4040 len target args
4041 lp rp)))
4042 "AST node for a JavaScript function call."
4043 target ; a `js2-node' evaluating to the function to call
4044 args ; a Lisp list of `js2-node' arguments
4045 lp ; position of open-paren, or nil if missing
4046 rp) ; position of close-paren, or nil if missing
4047
4048 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4049 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4050
4051 (defun js2-visit-call-node (n v)
4052 (js2-visit-ast (js2-call-node-target n) v)
4053 (dolist (arg (js2-call-node-args n))
4054 (js2-visit-ast arg v)))
4055
4056 (defun js2-print-call-node (n i)
4057 (insert (js2-make-pad i))
4058 (js2-print-ast (js2-call-node-target n) 0)
4059 (insert "(")
4060 (js2-print-list (js2-call-node-args n))
4061 (insert ")"))
4062
4063 (cl-defstruct (js2-yield-node
4064 (:include js2-node)
4065 (:constructor nil)
4066 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4067 (pos js2-ts-cursor)
4068 len value star-p)))
4069 "AST node for yield statement or expression."
4070 star-p ; whether it's yield*
4071 value) ; optional: value to be yielded
4072
4073 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4074 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4075
4076 (defun js2-visit-yield-node (n v)
4077 (js2-visit-ast (js2-yield-node-value n) v))
4078
4079 (defun js2-print-yield-node (n i)
4080 (insert (js2-make-pad i))
4081 (insert "yield")
4082 (when (js2-yield-node-star-p n)
4083 (insert "*"))
4084 (when (js2-yield-node-value n)
4085 (insert " ")
4086 (js2-print-ast (js2-yield-node-value n) 0)))
4087
4088 (cl-defstruct (js2-paren-node
4089 (:include js2-node)
4090 (:constructor nil)
4091 (:constructor make-js2-paren-node (&key (type js2-LP)
4092 (pos js2-ts-cursor)
4093 len expr)))
4094 "AST node for a parenthesized expression.
4095 In particular, used when the parens are syntactically optional,
4096 as opposed to required parens such as those enclosing an if-conditional."
4097 expr) ; `js2-node'
4098
4099 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4100 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4101
4102 (defun js2-visit-paren-node (n v)
4103 (js2-visit-ast (js2-paren-node-expr n) v))
4104
4105 (defun js2-print-paren-node (n i)
4106 (insert (js2-make-pad i))
4107 (insert "(")
4108 (js2-print-ast (js2-paren-node-expr n) 0)
4109 (insert ")"))
4110
4111 (cl-defstruct (js2-comp-node
4112 (:include js2-scope)
4113 (:constructor nil)
4114 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4115 (pos js2-ts-cursor)
4116 len result
4117 loops filters
4118 form)))
4119 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4120 result ; result expression (just after left-bracket)
4121 loops ; a Lisp list of `js2-comp-loop-node'
4122 filters ; a Lisp list of guard/filter expressions
4123 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4124 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4125 )
4126
4127 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4128 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4129
4130 (defun js2-visit-comp-node (n v)
4131 (js2-visit-ast (js2-comp-node-result n) v)
4132 (dolist (l (js2-comp-node-loops n))
4133 (js2-visit-ast l v))
4134 (dolist (f (js2-comp-node-filters n))
4135 (js2-visit-ast f v)))
4136
4137 (defun js2-print-comp-node (n i)
4138 (let ((pad (js2-make-pad i))
4139 (result (js2-comp-node-result n))
4140 (loops (js2-comp-node-loops n))
4141 (filters (js2-comp-node-filters n))
4142 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4143 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4144 (insert pad (if gen-p "(" "["))
4145 (when legacy-p
4146 (js2-print-ast result 0))
4147 (dolist (l loops)
4148 (when legacy-p
4149 (insert " "))
4150 (js2-print-ast l 0)
4151 (unless legacy-p
4152 (insert " ")))
4153 (dolist (f filters)
4154 (when legacy-p
4155 (insert " "))
4156 (insert "if (")
4157 (js2-print-ast f 0)
4158 (insert ")")
4159 (unless legacy-p
4160 (insert " ")))
4161 (unless legacy-p
4162 (js2-print-ast result 0))
4163 (insert (if gen-p ")" "]"))))
4164
4165 (cl-defstruct (js2-comp-loop-node
4166 (:include js2-for-in-node)
4167 (:constructor nil)
4168 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4169 (pos js2-ts-cursor)
4170 len iterator
4171 object in-pos
4172 foreach-p
4173 each-pos
4174 forof-p
4175 lp rp)))
4176 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4177
4178 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4179 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4180
4181 (defun js2-visit-comp-loop (n v)
4182 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4183 (js2-visit-ast (js2-comp-loop-node-object n) v))
4184
4185 (defun js2-print-comp-loop (n _i)
4186 (insert "for ")
4187 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4188 (insert "(")
4189 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4190 (insert (if (js2-comp-loop-node-forof-p n)
4191 " of " " in "))
4192 (js2-print-ast (js2-comp-loop-node-object n) 0)
4193 (insert ")"))
4194
4195 (cl-defstruct (js2-empty-expr-node
4196 (:include js2-node)
4197 (:constructor nil)
4198 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4199 (pos (js2-current-token-beg))
4200 len)))
4201 "AST node for an empty expression.")
4202
4203 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4204 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4205
4206 (cl-defstruct (js2-xml-node
4207 (:include js2-block-node)
4208 (:constructor nil)
4209 (:constructor make-js2-xml-node (&key (type js2-XML)
4210 (pos (js2-current-token-beg))
4211 len kids)))
4212 "AST node for initial parse of E4X literals.
4213 The kids field is a list of XML fragments, each a `js2-string-node' or
4214 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4215
4216 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4217 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4218
4219 (defun js2-print-xml-node (n i)
4220 (dolist (kid (js2-xml-node-kids n))
4221 (js2-print-ast kid i)))
4222
4223 (cl-defstruct (js2-xml-js-expr-node
4224 (:include js2-xml-node)
4225 (:constructor nil)
4226 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4227 (pos js2-ts-cursor)
4228 len expr)))
4229 "AST node for an embedded JavaScript {expression} in an E4X literal.
4230 The start and end fields correspond to the curly-braces."
4231 expr) ; a `js2-expr-node' of some sort
4232
4233 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4234 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4235
4236 (defun js2-visit-xml-js-expr (n v)
4237 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4238
4239 (defun js2-print-xml-js-expr (n i)
4240 (insert (js2-make-pad i))
4241 (insert "{")
4242 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4243 (insert "}"))
4244
4245 (cl-defstruct (js2-xml-dot-query-node
4246 (:include js2-infix-node)
4247 (:constructor nil)
4248 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4249 (pos js2-ts-cursor)
4250 op-pos len left
4251 right rp)))
4252 "AST node for an E4X foo.(bar) filter expression.
4253 Note that the left-paren is automatically the character immediately
4254 following the dot (.) in the operator. No whitespace is permitted
4255 between the dot and the lp by the scanner."
4256 rp)
4257
4258 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4259 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4260
4261 (defun js2-print-xml-dot-query (n i)
4262 (insert (js2-make-pad i))
4263 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4264 (insert ".(")
4265 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4266 (insert ")"))
4267
4268 (cl-defstruct (js2-xml-ref-node
4269 (:include js2-node)
4270 (:constructor nil)) ; abstract
4271 "Base type for E4X XML attribute-access or property-get expressions.
4272 Such expressions can take a variety of forms. The general syntax has
4273 three parts:
4274
4275 - (optional) an @ (specifying an attribute access)
4276 - (optional) a namespace (a `js2-name-node') and double-colon
4277 - (required) either a `js2-name-node' or a bracketed [expression]
4278
4279 The property-name expressions (examples: ns::name, @name) are
4280 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4281 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4282
4283 This node type (or more specifically, its subclasses) will sometimes
4284 be the right-hand child of a `js2-prop-get-node' or a
4285 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4286 The `js2-xml-ref-node' may also be a standalone primary expression with
4287 no explicit target, which is valid in certain expression contexts such as
4288
4289 company..employee.(@id < 100)
4290
4291 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4292 expression whose parent is a `js2-xml-dot-query-node'."
4293 namespace
4294 at-pos
4295 colon-pos)
4296
4297 (defsubst js2-xml-ref-node-attr-access-p (node)
4298 "Return non-nil if this expression began with an @-token."
4299 (and (numberp (js2-xml-ref-node-at-pos node))
4300 (cl-plusp (js2-xml-ref-node-at-pos node))))
4301
4302 (cl-defstruct (js2-xml-prop-ref-node
4303 (:include js2-xml-ref-node)
4304 (:constructor nil)
4305 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4306 (pos (js2-current-token-beg))
4307 len propname
4308 namespace at-pos
4309 colon-pos)))
4310 "AST node for an E4X XML [expr] property-ref expression.
4311 The JavaScript syntax is an optional @, an optional ns::, and a name.
4312
4313 [ '@' ] [ name '::' ] name
4314
4315 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4316 @ns::*, @*::attr, @*::*, and @*.
4317
4318 The node starts at the @ token, if present. Otherwise it starts at the
4319 namespace name. The node bounds extend through the closing right-bracket,
4320 or if it is missing due to a syntax error, through the end of the index
4321 expression."
4322 propname)
4323
4324 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4325 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4326
4327 (defun js2-visit-xml-prop-ref-node (n v)
4328 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4329 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4330
4331 (defun js2-print-xml-prop-ref-node (n i)
4332 (insert (js2-make-pad i))
4333 (if (js2-xml-ref-node-attr-access-p n)
4334 (insert "@"))
4335 (when (js2-xml-prop-ref-node-namespace n)
4336 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4337 (insert "::"))
4338 (if (js2-xml-prop-ref-node-propname n)
4339 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4340
4341 (cl-defstruct (js2-xml-elem-ref-node
4342 (:include js2-xml-ref-node)
4343 (:constructor nil)
4344 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4345 (pos (js2-current-token-beg))
4346 len expr lb rb
4347 namespace at-pos
4348 colon-pos)))
4349 "AST node for an E4X XML [expr] member-ref expression.
4350 Syntax:
4351
4352 [ '@' ] [ name '::' ] '[' expr ']'
4353
4354 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4355
4356 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4357 is not a legal E4X XML element-ref expression, since it's already used
4358 for standard JavaScript element-get array indexing. Hence, a
4359 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4360 non-nil namespace node, or both.
4361
4362 The node starts at the @ token, if present. Otherwise it starts
4363 at the namespace name. The node bounds extend through the closing
4364 right-bracket, or if it is missing due to a syntax error, through the
4365 end of the index expression."
4366 expr ; the bracketed index expression
4367 lb
4368 rb)
4369
4370 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4371 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4372
4373 (defun js2-visit-xml-elem-ref-node (n v)
4374 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4375 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4376
4377 (defun js2-print-xml-elem-ref-node (n i)
4378 (insert (js2-make-pad i))
4379 (if (js2-xml-ref-node-attr-access-p n)
4380 (insert "@"))
4381 (when (js2-xml-elem-ref-node-namespace n)
4382 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4383 (insert "::"))
4384 (insert "[")
4385 (if (js2-xml-elem-ref-node-expr n)
4386 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4387 (insert "]"))
4388
4389 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4390
4391 (cl-defstruct (js2-xml-start-tag-node
4392 (:include js2-xml-node)
4393 (:constructor nil)
4394 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4395 (pos js2-ts-cursor)
4396 len name attrs kids
4397 empty-p)))
4398 "AST node for an XML start-tag. Not currently used.
4399 The `kids' field is a Lisp list of child content nodes."
4400 name ; a `js2-xml-name-node'
4401 attrs ; a Lisp list of `js2-xml-attr-node'
4402 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4403
4404 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4405 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4406
4407 (defun js2-visit-xml-start-tag (n v)
4408 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4409 (dolist (attr (js2-xml-start-tag-node-attrs n))
4410 (js2-visit-ast attr v))
4411 (js2-visit-block n v))
4412
4413 (defun js2-print-xml-start-tag (n i)
4414 (insert (js2-make-pad i) "<")
4415 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4416 (when (js2-xml-start-tag-node-attrs n)
4417 (insert " ")
4418 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4419 (insert ">"))
4420
4421 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4422 ;; and add the end-tag to the kids list of the parent as well.
4423 (cl-defstruct (js2-xml-end-tag-node
4424 (:include js2-xml-node)
4425 (:constructor nil)
4426 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4427 (pos js2-ts-cursor)
4428 len name)))
4429 "AST node for an XML end-tag. Not currently used."
4430 name) ; a `js2-xml-name-node'
4431
4432 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4433 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4434
4435 (defun js2-visit-xml-end-tag (n v)
4436 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4437
4438 (defun js2-print-xml-end-tag (n i)
4439 (insert (js2-make-pad i))
4440 (insert "</")
4441 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4442 (insert ">"))
4443
4444 (cl-defstruct (js2-xml-name-node
4445 (:include js2-xml-node)
4446 (:constructor nil)
4447 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4448 (pos js2-ts-cursor)
4449 len namespace kids)))
4450 "AST node for an E4X XML name. Not currently used.
4451 Any XML name can be qualified with a namespace, hence the namespace field.
4452 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4453 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4454 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4455 namespace) ; a `js2-string-node'
4456
4457 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4458 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4459
4460 (defun js2-visit-xml-name-node (n v)
4461 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4462
4463 (defun js2-print-xml-name-node (n i)
4464 (insert (js2-make-pad i))
4465 (when (js2-xml-name-node-namespace n)
4466 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4467 (insert "::"))
4468 (dolist (kid (js2-xml-name-node-kids n))
4469 (js2-print-ast kid 0)))
4470
4471 (cl-defstruct (js2-xml-pi-node
4472 (:include js2-xml-node)
4473 (:constructor nil)
4474 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4475 (pos js2-ts-cursor)
4476 len name attrs)))
4477 "AST node for an E4X XML processing instruction. Not currently used."
4478 name ; a `js2-xml-name-node'
4479 attrs) ; a list of `js2-xml-attr-node'
4480
4481 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4482 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4483
4484 (defun js2-visit-xml-pi-node (n v)
4485 (js2-visit-ast (js2-xml-pi-node-name n) v)
4486 (dolist (attr (js2-xml-pi-node-attrs n))
4487 (js2-visit-ast attr v)))
4488
4489 (defun js2-print-xml-pi-node (n i)
4490 (insert (js2-make-pad i) "<?")
4491 (js2-print-ast (js2-xml-pi-node-name n))
4492 (when (js2-xml-pi-node-attrs n)
4493 (insert " ")
4494 (js2-print-list (js2-xml-pi-node-attrs n)))
4495 (insert "?>"))
4496
4497 (cl-defstruct (js2-xml-cdata-node
4498 (:include js2-xml-node)
4499 (:constructor nil)
4500 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4501 (pos js2-ts-cursor)
4502 len content)))
4503 "AST node for a CDATA escape section. Not currently used."
4504 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4505
4506 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4507 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4508
4509 (defun js2-visit-xml-cdata-node (n v)
4510 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4511
4512 (defun js2-print-xml-cdata-node (n i)
4513 (insert (js2-make-pad i))
4514 (js2-print-ast (js2-xml-cdata-node-content n)))
4515
4516 (cl-defstruct (js2-xml-attr-node
4517 (:include js2-xml-node)
4518 (:constructor nil)
4519 (:constructor make-js2-attr-node (&key (type js2-XML)
4520 (pos js2-ts-cursor)
4521 len name value
4522 eq-pos quote-type)))
4523 "AST node representing a foo='bar' XML attribute value. Not yet used."
4524 name ; a `js2-xml-name-node'
4525 value ; a `js2-xml-name-node'
4526 eq-pos ; buffer position of "=" sign
4527 quote-type) ; 'single or 'double
4528
4529 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4530 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4531
4532 (defun js2-visit-xml-attr-node (n v)
4533 (js2-visit-ast (js2-xml-attr-node-name n) v)
4534 (js2-visit-ast (js2-xml-attr-node-value n) v))
4535
4536 (defun js2-print-xml-attr-node (n i)
4537 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4538 "'"
4539 "\"")))
4540 (insert (js2-make-pad i))
4541 (js2-print-ast (js2-xml-attr-node-name n) 0)
4542 (insert "=" quote)
4543 (js2-print-ast (js2-xml-attr-node-value n) 0)
4544 (insert quote)))
4545
4546 (cl-defstruct (js2-xml-text-node
4547 (:include js2-xml-node)
4548 (:constructor nil)
4549 (:constructor make-js2-text-node (&key (type js2-XML)
4550 (pos js2-ts-cursor)
4551 len content)))
4552 "AST node for an E4X XML text node. Not currently used."
4553 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4554
4555 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4556 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4557
4558 (defun js2-visit-xml-text-node (n v)
4559 (js2-visit-ast (js2-xml-text-node-content n) v))
4560
4561 (defun js2-print-xml-text-node (n i)
4562 (insert (js2-make-pad i))
4563 (dolist (kid (js2-xml-text-node-content n))
4564 (js2-print-ast kid)))
4565
4566 (cl-defstruct (js2-xml-comment-node
4567 (:include js2-xml-node)
4568 (:constructor nil)
4569 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4570 (pos js2-ts-cursor)
4571 len)))
4572 "AST node for E4X XML comment. Not currently used.")
4573
4574 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4575 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4576
4577 (defun js2-print-xml-comment (n i)
4578 (insert (js2-make-pad i)
4579 (js2-node-string n)))
4580
4581 ;;; Node utilities
4582
4583 (defsubst js2-node-line (n)
4584 "Fetch the source line number at the start of node N.
4585 This is O(n) in the length of the source buffer; use prudently."
4586 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4587
4588 (defsubst js2-block-node-kid (n i)
4589 "Return child I of node N, or nil if there aren't that many."
4590 (nth i (js2-block-node-kids n)))
4591
4592 (defsubst js2-block-node-first (n)
4593 "Return first child of block node N, or nil if there is none."
4594 (cl-first (js2-block-node-kids n)))
4595
4596 (defun js2-node-root (n)
4597 "Return the root of the AST containing N.
4598 If N has no parent pointer, returns N."
4599 (let ((parent (js2-node-parent n)))
4600 (if parent
4601 (js2-node-root parent)
4602 n)))
4603
4604 (defsubst js2-node-short-name (n)
4605 "Return the short name of node N as a string, e.g. `js2-if-node'."
4606 (substring (symbol-name (aref n 0))
4607 (length "cl-struct-")))
4608
4609 (defun js2-node-child-list (node)
4610 "Return the child list for NODE, a Lisp list of nodes.
4611 Works for block nodes, array nodes, obj literals, funarg lists,
4612 var decls and try nodes (for catch clauses). Note that you should call
4613 `js2-block-node-kids' on the function body for the body statements.
4614 Returns nil for zero-length child lists or unsupported nodes."
4615 (cond
4616 ((js2-function-node-p node)
4617 (js2-function-node-params node))
4618 ((js2-block-node-p node)
4619 (js2-block-node-kids node))
4620 ((js2-try-node-p node)
4621 (js2-try-node-catch-clauses node))
4622 ((js2-array-node-p node)
4623 (js2-array-node-elems node))
4624 ((js2-object-node-p node)
4625 (js2-object-node-elems node))
4626 ((js2-call-node-p node)
4627 (js2-call-node-args node))
4628 ((js2-new-node-p node)
4629 (js2-new-node-args node))
4630 ((js2-var-decl-node-p node)
4631 (js2-var-decl-node-kids node))
4632 (t
4633 nil)))
4634
4635 (defun js2-node-set-child-list (node kids)
4636 "Set the child list for NODE to KIDS."
4637 (cond
4638 ((js2-function-node-p node)
4639 (setf (js2-function-node-params node) kids))
4640 ((js2-block-node-p node)
4641 (setf (js2-block-node-kids node) kids))
4642 ((js2-try-node-p node)
4643 (setf (js2-try-node-catch-clauses node) kids))
4644 ((js2-array-node-p node)
4645 (setf (js2-array-node-elems node) kids))
4646 ((js2-object-node-p node)
4647 (setf (js2-object-node-elems node) kids))
4648 ((js2-call-node-p node)
4649 (setf (js2-call-node-args node) kids))
4650 ((js2-new-node-p node)
4651 (setf (js2-new-node-args node) kids))
4652 ((js2-var-decl-node-p node)
4653 (setf (js2-var-decl-node-kids node) kids))
4654 (t
4655 (error "Unsupported node type: %s" (js2-node-short-name node))))
4656 kids)
4657
4658 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4659 (defconst js2-paren-expr-nodes
4660 '(cl-struct-js2-comp-loop-node
4661 cl-struct-js2-comp-node
4662 cl-struct-js2-call-node
4663 cl-struct-js2-catch-node
4664 cl-struct-js2-do-node
4665 cl-struct-js2-elem-get-node
4666 cl-struct-js2-for-in-node
4667 cl-struct-js2-for-node
4668 cl-struct-js2-function-node
4669 cl-struct-js2-if-node
4670 cl-struct-js2-let-node
4671 cl-struct-js2-new-node
4672 cl-struct-js2-paren-node
4673 cl-struct-js2-switch-node
4674 cl-struct-js2-while-node
4675 cl-struct-js2-with-node
4676 cl-struct-js2-xml-dot-query-node)
4677 "Node types that can have a parenthesized child expression.
4678 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4679
4680 (defsubst js2-paren-expr-node-p (node)
4681 "Return t for nodes that typically have a parenthesized child expression.
4682 Useful for computing the indentation anchors for arg-lists and conditions.
4683 Note that it may return a false positive, for instance when NODE is
4684 a `js2-new-node' and there are no arguments or parentheses."
4685 (memq (aref node 0) js2-paren-expr-nodes))
4686
4687 ;; Fake polymorphism... yech.
4688 (defun js2-node-lp (node)
4689 "Return relative left-paren position for NODE, if applicable.
4690 For `js2-elem-get-node' structs, returns left-bracket position.
4691 Note that the position may be nil in the case of a parse error."
4692 (cond
4693 ((js2-elem-get-node-p node)
4694 (js2-elem-get-node-lb node))
4695 ((js2-loop-node-p node)
4696 (js2-loop-node-lp node))
4697 ((js2-function-node-p node)
4698 (js2-function-node-lp node))
4699 ((js2-if-node-p node)
4700 (js2-if-node-lp node))
4701 ((js2-new-node-p node)
4702 (js2-new-node-lp node))
4703 ((js2-call-node-p node)
4704 (js2-call-node-lp node))
4705 ((js2-paren-node-p node)
4706 0)
4707 ((js2-switch-node-p node)
4708 (js2-switch-node-lp node))
4709 ((js2-catch-node-p node)
4710 (js2-catch-node-lp node))
4711 ((js2-let-node-p node)
4712 (js2-let-node-lp node))
4713 ((js2-comp-node-p node)
4714 0)
4715 ((js2-with-node-p node)
4716 (js2-with-node-lp node))
4717 ((js2-xml-dot-query-node-p node)
4718 (1+ (js2-infix-node-op-pos node)))
4719 (t
4720 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4721
4722 ;; Fake polymorphism... blech.
4723 (defun js2-node-rp (node)
4724 "Return relative right-paren position for NODE, if applicable.
4725 For `js2-elem-get-node' structs, returns right-bracket position.
4726 Note that the position may be nil in the case of a parse error."
4727 (cond
4728 ((js2-elem-get-node-p node)
4729 (js2-elem-get-node-rb node))
4730 ((js2-loop-node-p node)
4731 (js2-loop-node-rp node))
4732 ((js2-function-node-p node)
4733 (js2-function-node-rp node))
4734 ((js2-if-node-p node)
4735 (js2-if-node-rp node))
4736 ((js2-new-node-p node)
4737 (js2-new-node-rp node))
4738 ((js2-call-node-p node)
4739 (js2-call-node-rp node))
4740 ((js2-paren-node-p node)
4741 (1- (js2-node-len node)))
4742 ((js2-switch-node-p node)
4743 (js2-switch-node-rp node))
4744 ((js2-catch-node-p node)
4745 (js2-catch-node-rp node))
4746 ((js2-let-node-p node)
4747 (js2-let-node-rp node))
4748 ((js2-comp-node-p node)
4749 (1- (js2-node-len node)))
4750 ((js2-with-node-p node)
4751 (js2-with-node-rp node))
4752 ((js2-xml-dot-query-node-p node)
4753 (1+ (js2-xml-dot-query-node-rp node)))
4754 (t
4755 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4756
4757 (defsubst js2-node-first-child (node)
4758 "Return the first element of `js2-node-child-list' for NODE."
4759 (car (js2-node-child-list node)))
4760
4761 (defsubst js2-node-last-child (node)
4762 "Return the last element of `js2-node-last-child' for NODE."
4763 (car (last (js2-node-child-list node))))
4764
4765 (defun js2-node-prev-sibling (node)
4766 "Return the previous statement in parent.
4767 Works for parents supported by `js2-node-child-list'.
4768 Returns nil if NODE is not in the parent, or PARENT is
4769 not a supported node, or if NODE is the first child."
4770 (let* ((p (js2-node-parent node))
4771 (kids (js2-node-child-list p))
4772 (sib (car kids)))
4773 (while (and kids
4774 (not (eq node (cadr kids))))
4775 (setq kids (cdr kids)
4776 sib (car kids)))
4777 sib))
4778
4779 (defun js2-node-next-sibling (node)
4780 "Return the next statement in parent block.
4781 Returns nil if NODE is not in the block, or PARENT is not
4782 a block node, or if NODE is the last statement."
4783 (let* ((p (js2-node-parent node))
4784 (kids (js2-node-child-list p)))
4785 (while (and kids
4786 (not (eq node (car kids))))
4787 (setq kids (cdr kids)))
4788 (cadr kids)))
4789
4790 (defun js2-node-find-child-before (pos parent &optional after)
4791 "Find the last child that starts before POS in parent.
4792 If AFTER is non-nil, returns first child starting after POS.
4793 POS is an absolute buffer position. PARENT is any node
4794 supported by `js2-node-child-list'.
4795 Returns nil if no applicable child is found."
4796 (let ((kids (if (js2-function-node-p parent)
4797 (js2-block-node-kids (js2-function-node-body parent))
4798 (js2-node-child-list parent)))
4799 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4800 (js2-function-node-body parent)
4801 parent)))
4802 kid result fn
4803 (continue t))
4804 (setq fn (if after '>= '<))
4805 (while (and kids continue)
4806 (setq kid (car kids))
4807 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4808 (setq result kid
4809 continue (not after))
4810 (setq continue after))
4811 (setq kids (cdr kids)))
4812 result))
4813
4814 (defun js2-node-find-child-after (pos parent)
4815 "Find first child that starts after POS in parent.
4816 POS is an absolute buffer position. PARENT is any node
4817 supported by `js2-node-child-list'.
4818 Returns nil if no applicable child is found."
4819 (js2-node-find-child-before pos parent 'after))
4820
4821 (defun js2-node-replace-child (pos parent new-node)
4822 "Replace node at index POS in PARENT with NEW-NODE.
4823 Only works for parents supported by `js2-node-child-list'."
4824 (let ((kids (js2-node-child-list parent))
4825 (i 0))
4826 (while (< i pos)
4827 (setq kids (cdr kids)
4828 i (1+ i)))
4829 (setcar kids new-node)
4830 (js2-node-add-children parent new-node)))
4831
4832 (defun js2-node-buffer (n)
4833 "Return the buffer associated with AST N.
4834 Returns nil if the buffer is not set as a property on the root
4835 node, or if parent links were not recorded during parsing."
4836 (let ((root (js2-node-root n)))
4837 (and root
4838 (js2-ast-root-p root)
4839 (js2-ast-root-buffer root))))
4840
4841 (defun js2-block-node-push (n kid)
4842 "Push js2-node KID onto the end of js2-block-node N's child list.
4843 KID is always added to the -end- of the kids list.
4844 Function also calls `js2-node-add-children' to add the parent link."
4845 (let ((kids (js2-node-child-list n)))
4846 (if kids
4847 (setcdr kids (nconc (cdr kids) (list kid)))
4848 (js2-node-set-child-list n (list kid)))
4849 (js2-node-add-children n kid)))
4850
4851 (defun js2-node-string (node)
4852 (with-current-buffer (or (js2-node-buffer node)
4853 (error "No buffer available for node %s" node))
4854 (let ((pos (js2-node-abs-pos node)))
4855 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4856
4857 ;; Container for storing the node we're looking for in a traversal.
4858 (js2-deflocal js2-discovered-node nil)
4859
4860 ;; Keep track of absolute node position during traversals.
4861 (js2-deflocal js2-visitor-offset nil)
4862
4863 (js2-deflocal js2-node-search-point nil)
4864
4865 (when js2-mode-dev-mode-p
4866 (defun js2-find-node-at-point ()
4867 (interactive)
4868 (let ((node (js2-node-at-point)))
4869 (message "%s" (or node "No node found at point"))))
4870 (defun js2-node-name-at-point ()
4871 (interactive)
4872 (let ((node (js2-node-at-point)))
4873 (message "%s" (if node
4874 (js2-node-short-name node)
4875 "No node found at point.")))))
4876
4877 (defun js2-node-at-point (&optional pos skip-comments)
4878 "Return AST node at POS, a buffer position, defaulting to current point.
4879 The `js2-mode-ast' variable must be set to the current parse tree.
4880 Signals an error if the AST (`js2-mode-ast') is nil.
4881 Always returns a node - if it can't find one, it returns the root.
4882 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4883 (let ((ast js2-mode-ast)
4884 result)
4885 (unless ast
4886 (error "No JavaScript AST available"))
4887 ;; Look through comments first, since they may be inside nodes that
4888 ;; would otherwise report a match.
4889 (setq pos (or pos (point))
4890 result (if (> pos (js2-node-abs-end ast))
4891 ast
4892 (if (not skip-comments)
4893 (js2-comment-at-point pos))))
4894 (unless result
4895 (setq js2-discovered-node nil
4896 js2-visitor-offset 0
4897 js2-node-search-point pos)
4898 (unwind-protect
4899 (catch 'js2-visit-done
4900 (js2-visit-ast ast #'js2-node-at-point-visitor))
4901 (setq js2-visitor-offset nil
4902 js2-node-search-point nil))
4903 (setq result js2-discovered-node))
4904 ;; may have found a comment beyond end of last child node,
4905 ;; since visiting the ast-root looks at the comment-list last.
4906 (if (and skip-comments
4907 (js2-comment-node-p result))
4908 (setq result nil))
4909 (or result js2-mode-ast)))
4910
4911 (defun js2-node-at-point-visitor (node end-p)
4912 (let ((rel-pos (js2-node-pos node))
4913 abs-pos
4914 abs-end
4915 (point js2-node-search-point))
4916 (cond
4917 (end-p
4918 ;; this evaluates to a non-nil return value, even if it's zero
4919 (cl-decf js2-visitor-offset rel-pos))
4920 ;; we already looked for comments before visiting, and don't want them now
4921 ((js2-comment-node-p node)
4922 nil)
4923 (t
4924 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4925 ;; we only want to use the node if the point is before
4926 ;; the last character position in the node, so we decrement
4927 ;; the absolute end by 1.
4928 abs-end (+ abs-pos (js2-node-len node) -1))
4929 (cond
4930 ;; If this node starts after search-point, stop the search.
4931 ((> abs-pos point)
4932 (throw 'js2-visit-done nil))
4933 ;; If this node ends before the search-point, don't check kids.
4934 ((> point abs-end)
4935 nil)
4936 (t
4937 ;; Otherwise point is within this node, possibly in a child.
4938 (setq js2-discovered-node node)
4939 t)))))) ; keep processing kids to look for more specific match
4940
4941 (defsubst js2-block-comment-p (node)
4942 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4943 (and (js2-comment-node-p node)
4944 (memq (js2-comment-node-format node) '(jsdoc block))))
4945
4946 ;; TODO: put the comments in a vector and binary-search them instead
4947 (defun js2-comment-at-point (&optional pos)
4948 "Look through scanned comment nodes for one containing POS.
4949 POS is a buffer position that defaults to current point.
4950 Function returns nil if POS was not in any comment node."
4951 (let ((ast js2-mode-ast)
4952 (x (or pos (point)))
4953 beg end)
4954 (unless ast
4955 (error "No JavaScript AST available"))
4956 (catch 'done
4957 ;; Comments are stored in lexical order.
4958 (dolist (comment (js2-ast-root-comments ast) nil)
4959 (setq beg (js2-node-abs-pos comment)
4960 end (+ beg (js2-node-len comment)))
4961 (if (and (>= x beg)
4962 (<= x end))
4963 (throw 'done comment))))))
4964
4965 (defun js2-mode-find-parent-fn (node)
4966 "Find function enclosing NODE.
4967 Returns nil if NODE is not inside a function."
4968 (setq node (js2-node-parent node))
4969 (while (and node (not (js2-function-node-p node)))
4970 (setq node (js2-node-parent node)))
4971 (and (js2-function-node-p node) node))
4972
4973 (defun js2-mode-find-enclosing-fn (node)
4974 "Find function or root enclosing NODE."
4975 (if (js2-ast-root-p node)
4976 node
4977 (setq node (js2-node-parent node))
4978 (while (not (or (js2-ast-root-p node)
4979 (js2-function-node-p node)))
4980 (setq node (js2-node-parent node)))
4981 node))
4982
4983 (defun js2-mode-find-enclosing-node (beg end)
4984 "Find node fully enclosing BEG and END."
4985 (let ((node (js2-node-at-point beg))
4986 pos
4987 (continue t))
4988 (while continue
4989 (if (or (js2-ast-root-p node)
4990 (and
4991 (<= (setq pos (js2-node-abs-pos node)) beg)
4992 (>= (+ pos (js2-node-len node)) end)))
4993 (setq continue nil)
4994 (setq node (js2-node-parent node))))
4995 node))
4996
4997 (defun js2-node-parent-script-or-fn (node)
4998 "Find script or function immediately enclosing NODE.
4999 If NODE is the ast-root, returns nil."
5000 (if (js2-ast-root-p node)
5001 nil
5002 (setq node (js2-node-parent node))
5003 (while (and node (not (or (js2-function-node-p node)
5004 (js2-script-node-p node))))
5005 (setq node (js2-node-parent node)))
5006 node))
5007
5008 (defun js2-node-is-descendant (node ancestor)
5009 "Return t if NODE is a descendant of ANCESTOR."
5010 (while (and node
5011 (not (eq node ancestor)))
5012 (setq node (js2-node-parent node)))
5013 node)
5014
5015 ;;; visitor infrastructure
5016
5017 (defun js2-visit-none (_node _callback)
5018 "Visitor for AST node that have no node children."
5019 nil)
5020
5021 (defun js2-print-none (_node _indent)
5022 "Visitor for AST node with no printed representation.")
5023
5024 (defun js2-print-body (node indent)
5025 "Print a statement, or a block without braces."
5026 (if (js2-block-node-p node)
5027 (dolist (kid (js2-block-node-kids node))
5028 (js2-print-ast kid indent))
5029 (js2-print-ast node indent)))
5030
5031 (defun js2-print-list (args &optional delimiter)
5032 (cl-loop with len = (length args)
5033 for arg in args
5034 for count from 1
5035 do
5036 (when arg (js2-print-ast arg 0))
5037 (if (< count len)
5038 (insert (or delimiter ", ")))))
5039
5040 (defun js2-print-tree (ast)
5041 "Prints an AST to the current buffer.
5042 Makes `js2-ast-parent-nodes' available to the printer functions."
5043 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5044 (js2-print-ast ast)))
5045
5046 (defun js2-print-ast (node &optional indent)
5047 "Helper function for printing AST nodes.
5048 Requires `js2-ast-parent-nodes' to be non-nil.
5049 You should use `js2-print-tree' instead of this function."
5050 (let ((printer (get (aref node 0) 'js2-printer))
5051 (i (or indent 0)))
5052 ;; TODO: wedge comments in here somewhere
5053 (if printer
5054 (funcall printer node i))))
5055
5056 (defconst js2-side-effecting-tokens
5057 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5058 (dolist (tt (list js2-ASSIGN
5059 js2-ASSIGN_ADD
5060 js2-ASSIGN_BITAND
5061 js2-ASSIGN_BITOR
5062 js2-ASSIGN_BITXOR
5063 js2-ASSIGN_DIV
5064 js2-ASSIGN_LSH
5065 js2-ASSIGN_MOD
5066 js2-ASSIGN_MUL
5067 js2-ASSIGN_RSH
5068 js2-ASSIGN_SUB
5069 js2-ASSIGN_URSH
5070 js2-BLOCK
5071 js2-BREAK
5072 js2-CALL
5073 js2-CATCH
5074 js2-CATCH_SCOPE
5075 js2-CLASS
5076 js2-CONST
5077 js2-CONTINUE
5078 js2-DEBUGGER
5079 js2-DEC
5080 js2-DELPROP
5081 js2-DEL_REF
5082 js2-DO
5083 js2-ELSE
5084 js2-EMPTY
5085 js2-ENTERWITH
5086 js2-EXPORT
5087 js2-EXPR_RESULT
5088 js2-FINALLY
5089 js2-FOR
5090 js2-FUNCTION
5091 js2-GOTO
5092 js2-IF
5093 js2-IFEQ
5094 js2-IFNE
5095 js2-IMPORT
5096 js2-INC
5097 js2-JSR
5098 js2-LABEL
5099 js2-LEAVEWITH
5100 js2-LET
5101 js2-LETEXPR
5102 js2-LOCAL_BLOCK
5103 js2-LOOP
5104 js2-NEW
5105 js2-REF_CALL
5106 js2-RETHROW
5107 js2-RETURN
5108 js2-RETURN_RESULT
5109 js2-SEMI
5110 js2-SETELEM
5111 js2-SETELEM_OP
5112 js2-SETNAME
5113 js2-SETPROP
5114 js2-SETPROP_OP
5115 js2-SETVAR
5116 js2-SET_REF
5117 js2-SET_REF_OP
5118 js2-SWITCH
5119 js2-TARGET
5120 js2-THROW
5121 js2-TRY
5122 js2-VAR
5123 js2-WHILE
5124 js2-WITH
5125 js2-WITHEXPR
5126 js2-YIELD))
5127 (aset tokens tt t))
5128 (if js2-instanceof-has-side-effects
5129 (aset tokens js2-INSTANCEOF t))
5130 tokens))
5131
5132 (defun js2-node-has-side-effects (node)
5133 "Return t if NODE has side effects."
5134 (when node ; makes it easier to handle malformed expressions
5135 (let ((tt (js2-node-type node)))
5136 (cond
5137 ;; This doubtless needs some work, since EXPR_VOID is used
5138 ;; in several ways in Rhino and I may not have caught them all.
5139 ;; I'll wait for people to notice incorrect warnings.
5140 ((and (= tt js2-EXPR_VOID)
5141 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5142 (let ((expr (js2-expr-stmt-node-expr node)))
5143 (or (js2-node-has-side-effects expr)
5144 (when (js2-string-node-p expr)
5145 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5146 ((= tt js2-AWAIT)
5147 (js2-node-has-side-effects (js2-unary-node-operand node)))
5148 ((= tt js2-COMMA)
5149 (js2-node-has-side-effects (js2-infix-node-right node)))
5150 ((or (= tt js2-AND)
5151 (= tt js2-OR))
5152 (or (js2-node-has-side-effects (js2-infix-node-right node))
5153 (js2-node-has-side-effects (js2-infix-node-left node))))
5154 ((= tt js2-HOOK)
5155 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5156 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5157 ((js2-paren-node-p node)
5158 (js2-node-has-side-effects (js2-paren-node-expr node)))
5159 ((= tt js2-ERROR) ; avoid cascaded error messages
5160 nil)
5161 (t
5162 (aref js2-side-effecting-tokens tt))))))
5163
5164 (defconst js2-stmt-node-types
5165 (list js2-BLOCK
5166 js2-BREAK
5167 js2-CONTINUE
5168 js2-DEFAULT ; e4x "default xml namespace" statement
5169 js2-DO
5170 js2-EXPORT
5171 js2-EXPR_RESULT
5172 js2-EXPR_VOID
5173 js2-FOR
5174 js2-IF
5175 js2-IMPORT
5176 js2-RETURN
5177 js2-SWITCH
5178 js2-THROW
5179 js2-TRY
5180 js2-WHILE
5181 js2-WITH)
5182 "Node types that only appear in statement contexts.
5183 The list does not include nodes that always appear as the child
5184 of another specific statement type, such as switch-cases,
5185 catch and finally blocks, and else-clauses. The list also excludes
5186 nodes like yield, let and var, which may appear in either expression
5187 or statement context, and in the latter context always have a
5188 `js2-expr-stmt-node' parent. Finally, the list does not include
5189 functions or scripts, which are treated separately from statements
5190 by the JavaScript parser and runtime.")
5191
5192 (defun js2-stmt-node-p (node)
5193 "Heuristic for figuring out if NODE is a statement.
5194 Some node types can appear in either an expression context or a
5195 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5196 For these node types in a statement context, the parent will be a
5197 `js2-expr-stmt-node'.
5198 Functions aren't included in the check."
5199 (memq (js2-node-type node) js2-stmt-node-types))
5200
5201 (defun js2-mode-find-first-stmt (node)
5202 "Search upward starting from NODE looking for a statement.
5203 For purposes of this function, a `js2-function-node' counts."
5204 (while (not (or (js2-stmt-node-p node)
5205 (js2-function-node-p node)))
5206 (setq node (js2-node-parent node)))
5207 node)
5208
5209 (defun js2-node-parent-stmt (node)
5210 "Return the node's first ancestor that is a statement.
5211 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5212 appearing in a statement context will have a parent that is a
5213 `js2-expr-stmt-node' that will be returned by this function."
5214 (let ((parent (js2-node-parent node)))
5215 (if (or (null parent)
5216 (js2-stmt-node-p parent)
5217 (and (js2-function-node-p parent)
5218 (not (eq (js2-function-node-form parent)
5219 'FUNCTION_EXPRESSION))))
5220 parent
5221 (js2-node-parent-stmt parent))))
5222
5223 ;; In the Mozilla Rhino sources, Roshan James writes:
5224 ;; Does consistent-return analysis on the function body when strict mode is
5225 ;; enabled.
5226 ;;
5227 ;; function (x) { return (x+1) }
5228 ;;
5229 ;; is ok, but
5230 ;;
5231 ;; function (x) { if (x < 0) return (x+1); }
5232 ;;
5233 ;; is not because the function can potentially return a value when the
5234 ;; condition is satisfied and if not, the function does not explicitly
5235 ;; return a value.
5236 ;;
5237 ;; This extends to checking mismatches such as "return" and "return <value>"
5238 ;; used in the same function. Warnings are not emitted if inconsistent
5239 ;; returns exist in code that can be statically shown to be unreachable.
5240 ;; Ex.
5241 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5242 ;;
5243 ;; emits no warning. However if the loop had a break statement, then a
5244 ;; warning would be emitted.
5245 ;;
5246 ;; The consistency analysis looks at control structures such as loops, ifs,
5247 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5248 ;; warns the user about an inconsistent set of termination possibilities.
5249 ;;
5250 ;; These flags enumerate the possible ways a statement/function can
5251 ;; terminate. These flags are used by endCheck() and by the Parser to
5252 ;; detect inconsistent return usage.
5253 ;;
5254 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5255 ;; able to execute (example: throw, continue)
5256 ;;
5257 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5258 ;; next one. Statement such as return dont. A compound statement may have
5259 ;; some branch that drops off control to the next statement.
5260 ;;
5261 ;; END_RETURNS indicates that the statement can return with no value.
5262 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5263 ;;
5264 ;; A compound statement such as
5265 ;; if (condition) {
5266 ;; return value;
5267 ;; }
5268 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5269
5270 (defconst js2-END_UNREACHED 0)
5271 (defconst js2-END_DROPS_OFF 1)
5272 (defconst js2-END_RETURNS 2)
5273 (defconst js2-END_RETURNS_VALUE 4)
5274 (defconst js2-END_YIELDS 8)
5275
5276 (defun js2-has-consistent-return-usage (node)
5277 "Check that every return usage in a function body is consistent.
5278 Returns t if the function satisfies strict mode requirement."
5279 (let ((n (js2-end-check node)))
5280 ;; either it doesn't return a value in any branch...
5281 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5282 ;; or it returns a value (or is unreached) at every branch
5283 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5284 js2-END_RETURNS
5285 js2-END_YIELDS)))))
5286
5287 (defun js2-end-check-if (node)
5288 "Ensure that return usage in then/else blocks is consistent.
5289 If there is no else block, then the return statement can fall through.
5290 Returns logical OR of END_* flags"
5291 (let ((th (js2-if-node-then-part node))
5292 (el (js2-if-node-else-part node)))
5293 (if (null th)
5294 js2-END_UNREACHED
5295 (logior (js2-end-check th) (if el
5296 (js2-end-check el)
5297 js2-END_DROPS_OFF)))))
5298
5299 (defun js2-end-check-switch (node)
5300 "Consistency of return statements is checked between the case statements.
5301 If there is no default, then the switch can fall through. If there is a
5302 default, we check to see if all code paths in the default return or if
5303 there is a code path that can fall through.
5304 Returns logical OR of END_* flags."
5305 (let ((rv js2-END_UNREACHED)
5306 default-case)
5307 ;; examine the cases
5308 (catch 'break
5309 (dolist (c (js2-switch-node-cases node))
5310 (if (js2-case-node-expr c)
5311 (js2-set-flag rv (js2-end-check-block c))
5312 (setq default-case c)
5313 (throw 'break nil))))
5314 ;; we don't care how the cases drop into each other
5315 (js2-clear-flag rv js2-END_DROPS_OFF)
5316 ;; examine the default
5317 (js2-set-flag rv (if default-case
5318 (js2-end-check default-case)
5319 js2-END_DROPS_OFF))
5320 rv))
5321
5322 (defun js2-end-check-try (node)
5323 "If the block has a finally, return consistency is checked in the
5324 finally block. If all code paths in the finally return, then the
5325 returns in the try-catch blocks don't matter. If there is a code path
5326 that does not return or if there is no finally block, the returns
5327 of the try and catch blocks are checked for mismatch.
5328 Returns logical OR of END_* flags."
5329 (let ((finally (js2-try-node-finally-block node))
5330 rv)
5331 ;; check the finally if it exists
5332 (setq rv (if finally
5333 (js2-end-check (js2-finally-node-body finally))
5334 js2-END_DROPS_OFF))
5335 ;; If the finally block always returns, then none of the returns
5336 ;; in the try or catch blocks matter.
5337 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5338 (js2-clear-flag rv js2-END_DROPS_OFF)
5339 ;; examine the try block
5340 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5341 ;; check each catch block
5342 (dolist (cb (js2-try-node-catch-clauses node))
5343 (js2-set-flag rv (js2-end-check cb))))
5344 rv))
5345
5346 (defun js2-end-check-loop (node)
5347 "Return statement in the loop body must be consistent.
5348 The default assumption for any kind of a loop is that it will eventually
5349 terminate. The only exception is a loop with a constant true condition.
5350 Code that follows such a loop is examined only if one can determine
5351 statically that there is a break out of the loop.
5352
5353 for(... ; ... ; ...) {}
5354 for(... in ... ) {}
5355 while(...) { }
5356 do { } while(...)
5357
5358 Returns logical OR of END_* flags."
5359 (let ((rv (js2-end-check (js2-loop-node-body node)))
5360 (condition (cond
5361 ((js2-while-node-p node)
5362 (js2-while-node-condition node))
5363 ((js2-do-node-p node)
5364 (js2-do-node-condition node))
5365 ((js2-for-node-p node)
5366 (js2-for-node-condition node)))))
5367
5368 ;; check to see if the loop condition is always true
5369 (if (and condition
5370 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5371 (js2-clear-flag rv js2-END_DROPS_OFF))
5372
5373 ;; look for effect of breaks
5374 (js2-set-flag rv (js2-node-get-prop node
5375 'CONTROL_BLOCK_PROP
5376 js2-END_UNREACHED))
5377 rv))
5378
5379 (defun js2-end-check-block (node)
5380 "A general block of code is examined statement by statement.
5381 If any statement (even a compound one) returns in all branches, then
5382 subsequent statements are not examined.
5383 Returns logical OR of END_* flags."
5384 (let* ((rv js2-END_DROPS_OFF)
5385 (kids (js2-block-node-kids node))
5386 (n (car kids)))
5387 ;; Check each statement. If the statement can continue onto the next
5388 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5389 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5390 (js2-clear-flag rv js2-END_DROPS_OFF)
5391 (js2-set-flag rv (js2-end-check n))
5392 (setq kids (cdr kids)
5393 n (car kids)))
5394 rv))
5395
5396 (defun js2-end-check-label (node)
5397 "A labeled statement implies that there may be a break to the label.
5398 The function processes the labeled statement and then checks the
5399 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5400 particular label.
5401 Returns logical OR of END_* flags."
5402 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5403 (logior rv (js2-node-get-prop node
5404 'CONTROL_BLOCK_PROP
5405 js2-END_UNREACHED))))
5406
5407 (defun js2-end-check-break (node)
5408 "When a break is encountered annotate the statement being broken
5409 out of by setting its CONTROL_BLOCK_PROP property.
5410 Returns logical OR of END_* flags."
5411 (and (js2-break-node-target node)
5412 (js2-node-set-prop (js2-break-node-target node)
5413 'CONTROL_BLOCK_PROP
5414 js2-END_DROPS_OFF))
5415 js2-END_UNREACHED)
5416
5417 (defun js2-end-check (node)
5418 "Examine the body of a function, doing a basic reachability analysis.
5419 Returns a combination of flags END_* flags that indicate
5420 how the function execution can terminate. These constitute only the
5421 pessimistic set of termination conditions. It is possible that at
5422 runtime certain code paths will never be actually taken. Hence this
5423 analysis will flag errors in cases where there may not be errors.
5424 Returns logical OR of END_* flags"
5425 (let (kid)
5426 (cond
5427 ((js2-break-node-p node)
5428 (js2-end-check-break node))
5429 ((js2-expr-stmt-node-p node)
5430 (if (setq kid (js2-expr-stmt-node-expr node))
5431 (js2-end-check kid)
5432 js2-END_DROPS_OFF))
5433 ((or (js2-continue-node-p node)
5434 (js2-throw-node-p node))
5435 js2-END_UNREACHED)
5436 ((js2-return-node-p node)
5437 (if (setq kid (js2-return-node-retval node))
5438 js2-END_RETURNS_VALUE
5439 js2-END_RETURNS))
5440 ((js2-loop-node-p node)
5441 (js2-end-check-loop node))
5442 ((js2-switch-node-p node)
5443 (js2-end-check-switch node))
5444 ((js2-labeled-stmt-node-p node)
5445 (js2-end-check-label node))
5446 ((js2-if-node-p node)
5447 (js2-end-check-if node))
5448 ((js2-try-node-p node)
5449 (js2-end-check-try node))
5450 ((js2-block-node-p node)
5451 (if (null (js2-block-node-kids node))
5452 js2-END_DROPS_OFF
5453 (js2-end-check-block node)))
5454 ((js2-yield-node-p node)
5455 js2-END_YIELDS)
5456 (t
5457 js2-END_DROPS_OFF))))
5458
5459 (defun js2-always-defined-boolean-p (node)
5460 "Check if NODE always evaluates to true or false in boolean context.
5461 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5462 nor always false."
5463 (let ((tt (js2-node-type node))
5464 num)
5465 (cond
5466 ((or (= tt js2-FALSE) (= tt js2-NULL))
5467 'ALWAYS_FALSE)
5468 ((= tt js2-TRUE)
5469 'ALWAYS_TRUE)
5470 ((= tt js2-NUMBER)
5471 (setq num (js2-number-node-num-value node))
5472 (if (and (not (eq num 0.0e+NaN))
5473 (not (zerop num)))
5474 'ALWAYS_TRUE
5475 'ALWAYS_FALSE))
5476 (t
5477 nil))))
5478
5479 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5480 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5481
5482 (defvar js2-tokens nil
5483 "List of all defined token names.") ; initialized in `js2-token-names'
5484
5485 (defconst js2-token-names
5486 (let* ((names (make-vector js2-num-tokens -1))
5487 (case-fold-search nil) ; only match js2-UPPER_CASE
5488 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5489 (cl-loop for sym in syms
5490 for i from 0
5491 do
5492 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5493 (not (boundp sym)))
5494 (aset names (symbol-value sym) ; code, e.g. 152
5495 (downcase
5496 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5497 (push sym js2-tokens)))
5498 names)
5499 "Vector mapping int values to token string names, sans `js2-' prefix.")
5500
5501 (defun js2-tt-name (tok)
5502 "Return a string name for TOK, a token symbol or code.
5503 Signals an error if it's not a recognized token."
5504 (let ((code tok))
5505 (if (symbolp tok)
5506 (setq code (symbol-value tok)))
5507 (if (eq code -1)
5508 "ERROR"
5509 (if (and (numberp code)
5510 (not (cl-minusp code))
5511 (< code js2-num-tokens))
5512 (aref js2-token-names code)
5513 (error "Invalid token: %s" code)))))
5514
5515 (defsubst js2-tt-sym (tok)
5516 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5517 (intern (js2-tt-name tok)))
5518
5519 (defconst js2-token-codes
5520 (let ((table (make-hash-table :test 'eq :size 256)))
5521 (cl-loop for name across js2-token-names
5522 for sym = (intern (concat "js2-" (upcase name)))
5523 do
5524 (puthash sym (symbol-value sym) table))
5525 ;; clean up a few that are "wrong" in Rhino's token codes
5526 (puthash 'js2-DELETE js2-DELPROP table)
5527 table)
5528 "Hashtable mapping token type symbols to their bytecodes.")
5529
5530 (defsubst js2-tt-code (sym)
5531 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5532 (or (gethash sym js2-token-codes)
5533 (error "Invalid token symbol: %s " sym))) ; signal code bug
5534
5535 (defun js2-report-scan-error (msg &optional no-throw beg len)
5536 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5537 (js2-report-error msg nil
5538 (or beg (js2-current-token-beg))
5539 (or len (js2-current-token-len)))
5540 (unless no-throw
5541 (throw 'return js2-ERROR)))
5542
5543 (defun js2-set-string-from-buffer (token)
5544 "Set `string' and `end' slots for TOKEN, return the string."
5545 (setf (js2-token-end token) js2-ts-cursor
5546 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5547
5548 ;; TODO: could potentially avoid a lot of consing by allocating a
5549 ;; char buffer the way Rhino does.
5550 (defsubst js2-add-to-string (c)
5551 (push c js2-ts-string-buffer))
5552
5553 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5554 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5555 ;; any other character: when it's not part of the current token, we
5556 ;; unget it, allowing it to be read again by the following call.
5557 (defsubst js2-unget-char ()
5558 (cl-decf js2-ts-cursor))
5559
5560 ;; Rhino distinguishes \r and \n line endings. We don't need to
5561 ;; because we only scan from Emacs buffers, which always use \n.
5562 (defun js2-get-char ()
5563 "Read and return the next character from the input buffer.
5564 Increments `js2-ts-lineno' if the return value is a newline char.
5565 Updates `js2-ts-cursor' to the point after the returned char.
5566 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5567 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5568 (let (c)
5569 ;; check for end of buffer
5570 (if (>= js2-ts-cursor (point-max))
5571 (setq js2-ts-hit-eof t
5572 js2-ts-cursor (1+ js2-ts-cursor)
5573 c js2-EOF_CHAR) ; return value
5574 ;; otherwise read next char
5575 (setq c (char-before (cl-incf js2-ts-cursor)))
5576 ;; if we read a newline, update counters
5577 (if (= c ?\n)
5578 (setq js2-ts-line-start js2-ts-cursor
5579 js2-ts-lineno (1+ js2-ts-lineno)))
5580 ;; TODO: skip over format characters
5581 c)))
5582
5583 (defun js2-read-unicode-escape ()
5584 "Read a \\uNNNN sequence from the input.
5585 Assumes the ?\ and ?u have already been read.
5586 Returns the unicode character, or nil if it wasn't a valid character.
5587 Doesn't change the values of any scanner variables."
5588 ;; I really wish I knew a better way to do this, but I can't
5589 ;; find the Emacs function that takes a 16-bit int and converts
5590 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5591 ;; Have to first check that it's 4 hex characters or it may stop
5592 ;; the read early.
5593 (ignore-errors
5594 (let ((s (buffer-substring-no-properties js2-ts-cursor
5595 (+ 4 js2-ts-cursor))))
5596 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5597 (read (concat "?\\u" s))))))
5598
5599 (defun js2-match-char (test)
5600 "Consume and return next character if it matches TEST, a character.
5601 Returns nil and consumes nothing if TEST is not the next character."
5602 (let ((c (js2-get-char)))
5603 (if (eq c test)
5604 t
5605 (js2-unget-char)
5606 nil)))
5607
5608 (defun js2-peek-char ()
5609 (prog1
5610 (js2-get-char)
5611 (js2-unget-char)))
5612
5613 (defun js2-identifier-start-p (c)
5614 "Is C a valid start to an ES5 Identifier?
5615 See http://es5.github.io/#x7.6"
5616 (or
5617 (memq c '(?$ ?_))
5618 (memq (get-char-code-property c 'general-category)
5619 ;; Letters
5620 '(Lu Ll Lt Lm Lo Nl))))
5621
5622 (defun js2-identifier-part-p (c)
5623 "Is C a valid part of an ES5 Identifier?
5624 See http://es5.github.io/#x7.6"
5625 (or
5626 (memq c '(?$ ?_ ?\u200c ?\u200d))
5627 (memq (get-char-code-property c 'general-category)
5628 '(;; Letters
5629 Lu Ll Lt Lm Lo Nl
5630 ;; Combining Marks
5631 Mn Mc
5632 ;; Digits
5633 Nd
5634 ;; Connector Punctuation
5635 Pc))))
5636
5637 (defun js2-alpha-p (c)
5638 (cond ((and (<= ?A c) (<= c ?Z)) t)
5639 ((and (<= ?a c) (<= c ?z)) t)
5640 (t nil)))
5641
5642 (defsubst js2-digit-p (c)
5643 (and (<= ?0 c) (<= c ?9)))
5644
5645 (defun js2-js-space-p (c)
5646 (if (<= c 127)
5647 (memq c '(#x20 #x9 #xB #xC #xD))
5648 (or
5649 (eq c #xA0)
5650 ;; TODO: change this nil to check for Unicode space character
5651 nil)))
5652
5653 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5654
5655 (defun js2-skip-line ()
5656 "Skip to end of line."
5657 (while (not (memq (js2-get-char) js2-eol-chars)))
5658 (js2-unget-char)
5659 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5660
5661 (defun js2-init-scanner (&optional buf line)
5662 "Create token stream for BUF starting on LINE.
5663 BUF defaults to `current-buffer' and LINE defaults to 1.
5664
5665 A buffer can only have one scanner active at a time, which yields
5666 dramatically simpler code than using a defstruct. If you need to
5667 have simultaneous scanners in a buffer, copy the regions to scan
5668 into temp buffers."
5669 (with-current-buffer (or buf (current-buffer))
5670 (setq js2-ts-dirty-line nil
5671 js2-ts-hit-eof nil
5672 js2-ts-line-start 0
5673 js2-ts-lineno (or line 1)
5674 js2-ts-line-end-char -1
5675 js2-ts-cursor (point-min)
5676 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5677 js2-ti-tokens-cursor 0
5678 js2-ti-lookahead 0
5679 js2-ts-is-xml-attribute nil
5680 js2-ts-xml-is-tag-content nil
5681 js2-ts-xml-open-tags-count 0
5682 js2-ts-string-buffer nil)))
5683
5684 ;; This function uses the cached op, string and number fields in
5685 ;; TokenStream; if getToken has been called since the passed token
5686 ;; was scanned, the op or string printed may be incorrect.
5687 (defun js2-token-to-string (token)
5688 ;; Not sure where this function is used in Rhino. Not tested.
5689 (if (not js2-debug-print-trees)
5690 ""
5691 (let ((name (js2-tt-name token)))
5692 (cond
5693 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5694 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5695 (concat name " `" (js2-current-token-string) "'"))
5696 ((eq token js2-NUMBER)
5697 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5698 (t
5699 name)))))
5700
5701 (defconst js2-keywords
5702 '(break
5703 case catch class const continue
5704 debugger default delete do
5705 else extends export
5706 false finally for function
5707 if in instanceof import
5708 let
5709 new null
5710 return
5711 super switch
5712 this throw true try typeof
5713 var void
5714 while with
5715 yield))
5716
5717 ;; Token names aren't exactly the same as the keywords, unfortunately.
5718 ;; E.g. delete is js2-DELPROP.
5719 (defconst js2-kwd-tokens
5720 (let ((table (make-vector js2-num-tokens nil))
5721 (tokens
5722 (list js2-BREAK
5723 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5724 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5725 js2-ELSE js2-EXPORT
5726 js2-ELSE js2-EXTENDS js2-EXPORT
5727 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5728 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5729 js2-LET
5730 js2-NEW js2-NULL
5731 js2-RETURN
5732 js2-SUPER js2-SWITCH
5733 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5734 js2-VAR
5735 js2-WHILE js2-WITH
5736 js2-YIELD)))
5737 (dolist (i tokens)
5738 (aset table i 'font-lock-keyword-face))
5739 (aset table js2-STRING 'font-lock-string-face)
5740 (aset table js2-REGEXP 'font-lock-string-face)
5741 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5742 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5743 (aset table js2-COMMENT 'font-lock-comment-face)
5744 (aset table js2-THIS 'font-lock-builtin-face)
5745 (aset table js2-SUPER 'font-lock-builtin-face)
5746 (aset table js2-VOID 'font-lock-constant-face)
5747 (aset table js2-NULL 'font-lock-constant-face)
5748 (aset table js2-TRUE 'font-lock-constant-face)
5749 (aset table js2-FALSE 'font-lock-constant-face)
5750 (aset table js2-NOT 'font-lock-negation-char-face)
5751 table)
5752 "Vector whose values are non-nil for tokens that are keywords.
5753 The values are default faces to use for highlighting the keywords.")
5754
5755 ;; FIXME: Support strict mode-only future reserved words, after we know
5756 ;; which parts scopes are in strict mode, and which are not.
5757 (defconst js2-reserved-words '(class enum export extends import static super)
5758 "Future reserved keywords in ECMAScript 5.1.")
5759
5760 (defconst js2-keyword-names
5761 (let ((table (make-hash-table :test 'equal)))
5762 (cl-loop for k in js2-keywords
5763 do (puthash
5764 (symbol-name k) ; instanceof
5765 (intern (concat "js2-"
5766 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5767 table))
5768 table)
5769 "JavaScript keywords by name, mapped to their symbols.")
5770
5771 (defconst js2-reserved-word-names
5772 (let ((table (make-hash-table :test 'equal)))
5773 (cl-loop for k in js2-reserved-words
5774 do
5775 (puthash (symbol-name k) 'js2-RESERVED table))
5776 table)
5777 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5778
5779 (defun js2-collect-string (buf)
5780 "Convert BUF, a list of chars, to a string.
5781 Reverses BUF before converting."
5782 (if buf
5783 (apply #'string (nreverse buf))
5784 ""))
5785
5786 (defun js2-string-to-keyword (s)
5787 "Return token for S, a string, if S is a keyword or reserved word.
5788 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5789 (or (gethash s js2-keyword-names)
5790 (gethash s js2-reserved-word-names)))
5791
5792 (defsubst js2-ts-set-char-token-bounds (token)
5793 "Used when next token is one character."
5794 (setf (js2-token-beg token) (1- js2-ts-cursor)
5795 (js2-token-end token) js2-ts-cursor))
5796
5797 (defsubst js2-ts-return (token type)
5798 "Update the `end' and `type' slots of TOKEN,
5799 then throw `return' with value TYPE."
5800 (setf (js2-token-end token) js2-ts-cursor
5801 (js2-token-type token) type)
5802 (throw 'return type))
5803
5804 (defun js2-x-digit-to-int (c accumulator)
5805 "Build up a hex number.
5806 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5807 corresponding number. Otherwise return -1."
5808 (catch 'return
5809 (catch 'check
5810 ;; Use 0..9 < A..Z < a..z
5811 (cond
5812 ((<= c ?9)
5813 (cl-decf c ?0)
5814 (if (<= 0 c)
5815 (throw 'check nil)))
5816 ((<= c ?F)
5817 (when (<= ?A c)
5818 (cl-decf c (- ?A 10))
5819 (throw 'check nil)))
5820 ((<= c ?f)
5821 (when (<= ?a c)
5822 (cl-decf c (- ?a 10))
5823 (throw 'check nil))))
5824 (throw 'return -1))
5825 (logior c (lsh accumulator 4))))
5826
5827 (defun js2-get-token (&optional modifier)
5828 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5829 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5830 next saved token.
5831
5832 This function will not return a newline (js2-EOL) - instead, it
5833 gobbles newlines until it finds a non-newline token. Call
5834 `js2-peek-token-or-eol' when you care about newlines.
5835
5836 This function will also not return a js2-COMMENT. Instead, it
5837 records comments found in `js2-scanned-comments'. If the token
5838 returned by this function immediately follows a jsdoc comment,
5839 the token is flagged as such."
5840 (if (zerop js2-ti-lookahead)
5841 (js2-get-token-internal modifier)
5842 (cl-decf js2-ti-lookahead)
5843 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5844 (let ((tt (js2-current-token-type)))
5845 (cl-assert (not (= tt js2-EOL)))
5846 tt)))
5847
5848 (defun js2-unget-token ()
5849 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5850 (cl-incf js2-ti-lookahead)
5851 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5852
5853 (defun js2-get-token-internal (modifier)
5854 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5855 (tt (js2-token-type token))
5856 saw-eol
5857 face)
5858 ;; process comments
5859 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5860 (if (= tt js2-EOL)
5861 (setq saw-eol t)
5862 (setq saw-eol nil)
5863 (when js2-record-comments
5864 (js2-record-comment token)))
5865 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5866 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5867 tt (js2-token-type token)))
5868
5869 (when saw-eol
5870 (setf (js2-token-follows-eol-p token) t))
5871
5872 ;; perform lexical fontification as soon as token is scanned
5873 (when js2-parse-ide-mode
5874 (cond
5875 ((cl-minusp tt)
5876 (js2-record-face 'js2-error token))
5877 ((setq face (aref js2-kwd-tokens tt))
5878 (js2-record-face face token))
5879 ((and (= tt js2-NAME)
5880 (equal (js2-token-string token) "undefined"))
5881 (js2-record-face 'font-lock-constant-face token))))
5882 tt))
5883
5884 (defsubst js2-string-to-number (str base)
5885 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5886 (condition-case nil
5887 (string-to-number str base)
5888 (overflow-error -1)))
5889
5890 (defun js2-get-token-internal-1 (modifier)
5891 "Return next JavaScript token type, an int such as js2-RETURN.
5892 During operation, creates an instance of `js2-token' struct, sets
5893 its relevant fields and puts it into `js2-ti-tokens'."
5894 (let (identifier-start
5895 is-unicode-escape-start c
5896 contains-escape escape-val str result base
5897 look-for-slash continue tt
5898 (token (js2-new-token 0)))
5899 (setq
5900 tt
5901 (catch 'return
5902 (when (eq modifier 'TEMPLATE_TAIL)
5903 (setf (js2-token-beg token) (1- js2-ts-cursor))
5904 (throw 'return (js2-get-string-or-template-token ?` token)))
5905 (while t
5906 ;; Eat whitespace, possibly sensitive to newlines.
5907 (setq continue t)
5908 (while continue
5909 (setq c (js2-get-char))
5910 (cond
5911 ((eq c js2-EOF_CHAR)
5912 (js2-unget-char)
5913 (js2-ts-set-char-token-bounds token)
5914 (throw 'return js2-EOF))
5915 ((eq c ?\n)
5916 (js2-ts-set-char-token-bounds token)
5917 (setq js2-ts-dirty-line nil)
5918 (throw 'return js2-EOL))
5919 ((not (js2-js-space-p c))
5920 (if (/= c ?-) ; in case end of HTML comment
5921 (setq js2-ts-dirty-line t))
5922 (setq continue nil))))
5923 ;; Assume the token will be 1 char - fixed up below.
5924 (js2-ts-set-char-token-bounds token)
5925 (when (eq c ?@)
5926 (throw 'return js2-XMLATTR))
5927 ;; identifier/keyword/instanceof?
5928 ;; watch out for starting with a <backslash>
5929 (cond
5930 ((eq c ?\\)
5931 (setq c (js2-get-char))
5932 (if (eq c ?u)
5933 (setq identifier-start t
5934 is-unicode-escape-start t
5935 js2-ts-string-buffer nil)
5936 (setq identifier-start nil)
5937 (js2-unget-char)
5938 (setq c ?\\)))
5939 (t
5940 (when (setq identifier-start (js2-identifier-start-p c))
5941 (setq js2-ts-string-buffer nil)
5942 (js2-add-to-string c))))
5943 (when identifier-start
5944 (setq contains-escape is-unicode-escape-start)
5945 (catch 'break
5946 (while t
5947 (if is-unicode-escape-start
5948 ;; strictly speaking we should probably push-back
5949 ;; all the bad characters if the <backslash>uXXXX
5950 ;; sequence is malformed. But since there isn't a
5951 ;; correct context(is there?) for a bad Unicode
5952 ;; escape sequence in an identifier, we can report
5953 ;; an error here.
5954 (progn
5955 (setq escape-val 0)
5956 (dotimes (_ 4)
5957 (setq c (js2-get-char)
5958 escape-val (js2-x-digit-to-int c escape-val))
5959 ;; Next check takes care of c < 0 and bad escape
5960 (if (cl-minusp escape-val)
5961 (throw 'break nil)))
5962 (if (cl-minusp escape-val)
5963 (js2-report-scan-error "msg.invalid.escape" t))
5964 (js2-add-to-string escape-val)
5965 (setq is-unicode-escape-start nil))
5966 (setq c (js2-get-char))
5967 (cond
5968 ((eq c ?\\)
5969 (setq c (js2-get-char))
5970 (if (eq c ?u)
5971 (setq is-unicode-escape-start t
5972 contains-escape t)
5973 (js2-report-scan-error "msg.illegal.character" t)))
5974 (t
5975 (if (or (eq c js2-EOF_CHAR)
5976 (not (js2-identifier-part-p c)))
5977 (throw 'break nil))
5978 (js2-add-to-string c))))))
5979 (js2-unget-char)
5980 (setf str (js2-collect-string js2-ts-string-buffer)
5981 (js2-token-end token) js2-ts-cursor)
5982 ;; FIXME: Invalid in ES5 and ES6, see
5983 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5984 ;; Probably should just drop this conditional.
5985 (unless contains-escape
5986 ;; OPT we shouldn't have to make a string (object!) to
5987 ;; check if it's a keyword.
5988 ;; Return the corresponding token if it's a keyword
5989 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5990 (setq result (js2-string-to-keyword str)))
5991 (if (and (< js2-language-version 170)
5992 (memq result '(js2-LET js2-YIELD)))
5993 ;; LET and YIELD are tokens only in 1.7 and later
5994 (setq result 'js2-NAME))
5995 (when (eq result 'js2-RESERVED)
5996 (setf (js2-token-string token) str))
5997 (throw 'return (js2-tt-code result))))
5998 ;; If we want to intern these as Rhino does, just use (intern str)
5999 (setf (js2-token-string token) str)
6000 (throw 'return js2-NAME)) ; end identifier/kwd check
6001 ;; is it a number?
6002 (when (or (js2-digit-p c)
6003 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6004 (setq js2-ts-string-buffer nil
6005 base 10)
6006 (when (eq c ?0)
6007 (setq c (js2-get-char))
6008 (cond
6009 ((or (eq c ?x) (eq c ?X))
6010 (setq base 16)
6011 (setq c (js2-get-char)))
6012 ((and (or (eq c ?b) (eq c ?B))
6013 (>= js2-language-version 200))
6014 (setq base 2)
6015 (setq c (js2-get-char)))
6016 ((and (or (eq c ?o) (eq c ?O))
6017 (>= js2-language-version 200))
6018 (setq base 8)
6019 (setq c (js2-get-char)))
6020 ((js2-digit-p c)
6021 (setq base 'maybe-8))
6022 (t
6023 (js2-add-to-string ?0))))
6024 (cond
6025 ((eq base 16)
6026 (if (> 0 (js2-x-digit-to-int c 0))
6027 (js2-report-scan-error "msg.missing.hex.digits")
6028 (while (<= 0 (js2-x-digit-to-int c 0))
6029 (js2-add-to-string c)
6030 (setq c (js2-get-char)))))
6031 ((eq base 2)
6032 (if (not (memq c '(?0 ?1)))
6033 (js2-report-scan-error "msg.missing.binary.digits")
6034 (while (memq c '(?0 ?1))
6035 (js2-add-to-string c)
6036 (setq c (js2-get-char)))))
6037 ((eq base 8)
6038 (if (or (> ?0 c) (< ?7 c))
6039 (js2-report-scan-error "msg.missing.octal.digits")
6040 (while (and (<= ?0 c) (>= ?7 c))
6041 (js2-add-to-string c)
6042 (setq c (js2-get-char)))))
6043 (t
6044 (while (and (<= ?0 c) (<= c ?9))
6045 ;; We permit 08 and 09 as decimal numbers, which
6046 ;; makes our behavior a superset of the ECMA
6047 ;; numeric grammar. We might not always be so
6048 ;; permissive, so we warn about it.
6049 (when (and (eq base 'maybe-8) (>= c ?8))
6050 (js2-report-warning "msg.bad.octal.literal"
6051 (if (eq c ?8) "8" "9"))
6052 (setq base 10))
6053 (js2-add-to-string c)
6054 (setq c (js2-get-char)))
6055 (when (eq base 'maybe-8)
6056 (setq base 8))))
6057 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6058 (when (eq c ?.)
6059 (cl-loop do
6060 (js2-add-to-string c)
6061 (setq c (js2-get-char))
6062 while (js2-digit-p c)))
6063 (when (memq c '(?e ?E))
6064 (js2-add-to-string c)
6065 (setq c (js2-get-char))
6066 (when (memq c '(?+ ?-))
6067 (js2-add-to-string c)
6068 (setq c (js2-get-char)))
6069 (unless (js2-digit-p c)
6070 (js2-report-scan-error "msg.missing.exponent" t))
6071 (cl-loop do
6072 (js2-add-to-string c)
6073 (setq c (js2-get-char))
6074 while (js2-digit-p c))))
6075 (js2-unget-char)
6076 (let ((str (js2-set-string-from-buffer token)))
6077 (setf (js2-token-number token) (js2-string-to-number str base)
6078 (js2-token-number-base token) base))
6079 (throw 'return js2-NUMBER))
6080 ;; is it a string?
6081 (when (or (memq c '(?\" ?\'))
6082 (and (>= js2-language-version 200)
6083 (= c ?`)))
6084 (throw 'return
6085 (js2-get-string-or-template-token c token)))
6086 (js2-ts-return token
6087 (cl-case c
6088 (?\;
6089 (throw 'return js2-SEMI))
6090 (?\[
6091 (throw 'return js2-LB))
6092 (?\]
6093 (throw 'return js2-RB))
6094 (?{
6095 (throw 'return js2-LC))
6096 (?}
6097 (throw 'return js2-RC))
6098 (?\(
6099 (throw 'return js2-LP))
6100 (?\)
6101 (throw 'return js2-RP))
6102 (?,
6103 (throw 'return js2-COMMA))
6104 (??
6105 (throw 'return js2-HOOK))
6106 (?:
6107 (if (js2-match-char ?:)
6108 js2-COLONCOLON
6109 (throw 'return js2-COLON)))
6110 (?.
6111 (if (js2-match-char ?.)
6112 (if (js2-match-char ?.)
6113 js2-TRIPLEDOT js2-DOTDOT)
6114 (if (js2-match-char ?\()
6115 js2-DOTQUERY
6116 (throw 'return js2-DOT))))
6117 (?|
6118 (if (js2-match-char ?|)
6119 (throw 'return js2-OR)
6120 (if (js2-match-char ?=)
6121 js2-ASSIGN_BITOR
6122 (throw 'return js2-BITOR))))
6123 (?^
6124 (if (js2-match-char ?=)
6125 js2-ASSIGN_BITOR
6126 (throw 'return js2-BITXOR)))
6127 (?&
6128 (if (js2-match-char ?&)
6129 (throw 'return js2-AND)
6130 (if (js2-match-char ?=)
6131 js2-ASSIGN_BITAND
6132 (throw 'return js2-BITAND))))
6133 (?=
6134 (if (js2-match-char ?=)
6135 (if (js2-match-char ?=)
6136 js2-SHEQ
6137 (throw 'return js2-EQ))
6138 (if (js2-match-char ?>)
6139 (js2-ts-return token js2-ARROW)
6140 (throw 'return js2-ASSIGN))))
6141 (?!
6142 (if (js2-match-char ?=)
6143 (if (js2-match-char ?=)
6144 js2-SHNE
6145 js2-NE)
6146 (throw 'return js2-NOT)))
6147 (?<
6148 ;; NB:treat HTML begin-comment as comment-till-eol
6149 (when (js2-match-char ?!)
6150 (when (js2-match-char ?-)
6151 (when (js2-match-char ?-)
6152 (js2-skip-line)
6153 (setf (js2-token-comment-type (js2-current-token)) 'html)
6154 (throw 'return js2-COMMENT)))
6155 (js2-unget-char))
6156 (if (js2-match-char ?<)
6157 (if (js2-match-char ?=)
6158 js2-ASSIGN_LSH
6159 js2-LSH)
6160 (if (js2-match-char ?=)
6161 js2-LE
6162 (throw 'return js2-LT))))
6163 (?>
6164 (if (js2-match-char ?>)
6165 (if (js2-match-char ?>)
6166 (if (js2-match-char ?=)
6167 js2-ASSIGN_URSH
6168 js2-URSH)
6169 (if (js2-match-char ?=)
6170 js2-ASSIGN_RSH
6171 js2-RSH))
6172 (if (js2-match-char ?=)
6173 js2-GE
6174 (throw 'return js2-GT))))
6175 (?*
6176 (if (js2-match-char ?=)
6177 js2-ASSIGN_MUL
6178 (throw 'return js2-MUL)))
6179 (?/
6180 ;; is it a // comment?
6181 (when (js2-match-char ?/)
6182 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6183 (js2-skip-line)
6184 (setf (js2-token-comment-type token) 'line)
6185 ;; include newline so highlighting goes to end of
6186 ;; window, if there actually is a newline; if we
6187 ;; hit eof, then implicitly there isn't
6188 (unless js2-ts-hit-eof
6189 (cl-incf (js2-token-end token)))
6190 (throw 'return js2-COMMENT))
6191 ;; is it a /* comment?
6192 (when (js2-match-char ?*)
6193 (setf look-for-slash nil
6194 (js2-token-beg token) (- js2-ts-cursor 2)
6195 (js2-token-comment-type token)
6196 (if (js2-match-char ?*)
6197 (progn
6198 (setq look-for-slash t)
6199 'jsdoc)
6200 'block))
6201 (while t
6202 (setq c (js2-get-char))
6203 (cond
6204 ((eq c js2-EOF_CHAR)
6205 (setf (js2-token-end token) (1- js2-ts-cursor))
6206 (js2-report-error "msg.unterminated.comment")
6207 (throw 'return js2-COMMENT))
6208 ((eq c ?*)
6209 (setq look-for-slash t))
6210 ((eq c ?/)
6211 (if look-for-slash
6212 (js2-ts-return token js2-COMMENT)))
6213 (t
6214 (setf look-for-slash nil
6215 (js2-token-end token) js2-ts-cursor)))))
6216 (if (js2-match-char ?=)
6217 js2-ASSIGN_DIV
6218 (throw 'return js2-DIV)))
6219 (?#
6220 (when js2-skip-preprocessor-directives
6221 (js2-skip-line)
6222 (setf (js2-token-comment-type token) 'preprocessor
6223 (js2-token-end token) js2-ts-cursor)
6224 (throw 'return js2-COMMENT))
6225 (throw 'return js2-ERROR))
6226 (?%
6227 (if (js2-match-char ?=)
6228 js2-ASSIGN_MOD
6229 (throw 'return js2-MOD)))
6230 (?~
6231 (throw 'return js2-BITNOT))
6232 (?+
6233 (if (js2-match-char ?=)
6234 js2-ASSIGN_ADD
6235 (if (js2-match-char ?+)
6236 js2-INC
6237 (throw 'return js2-ADD))))
6238 (?-
6239 (cond
6240 ((js2-match-char ?=)
6241 (setq c js2-ASSIGN_SUB))
6242 ((js2-match-char ?-)
6243 (unless js2-ts-dirty-line
6244 ;; treat HTML end-comment after possible whitespace
6245 ;; after line start as comment-until-eol
6246 (when (js2-match-char ?>)
6247 (js2-skip-line)
6248 (setf (js2-token-comment-type (js2-current-token)) 'html)
6249 (throw 'return js2-COMMENT)))
6250 (setq c js2-DEC))
6251 (t
6252 (setq c js2-SUB)))
6253 (setq js2-ts-dirty-line t)
6254 c)
6255 (otherwise
6256 (js2-report-scan-error "msg.illegal.character")))))))
6257 (setf (js2-token-type token) tt)
6258 token))
6259
6260 (defun js2-get-string-or-template-token (quote-char token)
6261 ;; We attempt to accumulate a string the fast way, by
6262 ;; building it directly out of the reader. But if there
6263 ;; are any escaped characters in the string, we revert to
6264 ;; building it out of a string buffer.
6265 (let ((c (js2-get-char))
6266 js2-ts-string-buffer
6267 nc c1 val escape-val)
6268 (catch 'break
6269 (while (/= c quote-char)
6270 (catch 'continue
6271 (when (eq c js2-EOF_CHAR)
6272 (js2-unget-char)
6273 (js2-report-error "msg.unterminated.string.lit")
6274 (throw 'break nil))
6275 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6276 (js2-unget-char)
6277 (js2-report-error "msg.unterminated.string.lit")
6278 (throw 'break nil))
6279 (when (eq c ?\\)
6280 ;; We've hit an escaped character
6281 (setq c (js2-get-char))
6282 (cl-case c
6283 (?b (setq c ?\b))
6284 (?f (setq c ?\f))
6285 (?n (setq c ?\n))
6286 (?r (setq c ?\r))
6287 (?t (setq c ?\t))
6288 (?v (setq c ?\v))
6289 (?u
6290 (setq c1 (js2-read-unicode-escape))
6291 (if js2-parse-ide-mode
6292 (if c1
6293 (progn
6294 ;; just copy the string in IDE-mode
6295 (js2-add-to-string ?\\)
6296 (js2-add-to-string ?u)
6297 (dotimes (_ 3)
6298 (js2-add-to-string (js2-get-char)))
6299 (setq c (js2-get-char))) ; added at end of loop
6300 ;; flag it as an invalid escape
6301 (js2-report-warning "msg.invalid.escape"
6302 nil (- js2-ts-cursor 2) 6))
6303 ;; Get 4 hex digits; if the u escape is not
6304 ;; followed by 4 hex digits, use 'u' + the
6305 ;; literal character sequence that follows.
6306 (js2-add-to-string ?u)
6307 (setq escape-val 0)
6308 (dotimes (_ 4)
6309 (setq c (js2-get-char)
6310 escape-val (js2-x-digit-to-int c escape-val))
6311 (if (cl-minusp escape-val)
6312 (throw 'continue nil))
6313 (js2-add-to-string c))
6314 ;; prepare for replace of stored 'u' sequence by escape value
6315 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6316 c escape-val)))
6317 (?x
6318 ;; Get 2 hex digits, defaulting to 'x'+literal
6319 ;; sequence, as above.
6320 (setq c (js2-get-char)
6321 escape-val (js2-x-digit-to-int c 0))
6322 (if (cl-minusp escape-val)
6323 (progn
6324 (js2-add-to-string ?x)
6325 (throw 'continue nil))
6326 (setq c1 c
6327 c (js2-get-char)
6328 escape-val (js2-x-digit-to-int c escape-val))
6329 (if (cl-minusp escape-val)
6330 (progn
6331 (js2-add-to-string ?x)
6332 (js2-add-to-string c1)
6333 (throw 'continue nil))
6334 ;; got 2 hex digits
6335 (setq c escape-val))))
6336 (?\n
6337 ;; Remove line terminator after escape to follow
6338 ;; SpiderMonkey and C/C++
6339 (setq c (js2-get-char))
6340 (throw 'continue nil))
6341 (t
6342 (when (and (<= ?0 c) (< c ?8))
6343 (setq val (- c ?0)
6344 c (js2-get-char))
6345 (when (and (<= ?0 c) (< c ?8))
6346 (setq val (- (+ (* 8 val) c) ?0)
6347 c (js2-get-char))
6348 (when (and (<= ?0 c)
6349 (< c ?8)
6350 (< val #o37))
6351 ;; c is 3rd char of octal sequence only
6352 ;; if the resulting val <= 0377
6353 (setq val (- (+ (* 8 val) c) ?0)
6354 c (js2-get-char))))
6355 (js2-unget-char)
6356 (setq c val)))))
6357 (when (and (eq quote-char ?`) (eq c ?$))
6358 (when (eq (setq nc (js2-get-char)) ?\{)
6359 (throw 'break nil))
6360 (js2-unget-char))
6361 (js2-add-to-string c)
6362 (setq c (js2-get-char)))))
6363 (js2-set-string-from-buffer token)
6364 (if (not (eq quote-char ?`))
6365 js2-STRING
6366 (if (and (eq c ?$) (eq nc ?\{))
6367 js2-TEMPLATE_HEAD
6368 js2-NO_SUBS_TEMPLATE))))
6369
6370 (defun js2-read-regexp (start-tt)
6371 "Called by parser when it gets / or /= in literal context."
6372 (let (c err
6373 in-class ; inside a '[' .. ']' character-class
6374 flags
6375 (continue t)
6376 (token (js2-new-token 0)))
6377 (setq js2-ts-string-buffer nil)
6378 (if (eq start-tt js2-ASSIGN_DIV)
6379 ;; mis-scanned /=
6380 (js2-add-to-string ?=)
6381 (if (not (eq start-tt js2-DIV))
6382 (error "failed assertion")))
6383 (while (and (not err)
6384 (or (/= (setq c (js2-get-char)) ?/)
6385 in-class))
6386 (cond
6387 ((or (= c ?\n)
6388 (= c js2-EOF_CHAR))
6389 (setf (js2-token-end token) (1- js2-ts-cursor)
6390 err t
6391 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6392 (js2-report-error "msg.unterminated.re.lit"))
6393 (t (cond
6394 ((= c ?\\)
6395 (js2-add-to-string c)
6396 (setq c (js2-get-char)))
6397 ((= c ?\[)
6398 (setq in-class t))
6399 ((= c ?\])
6400 (setq in-class nil)))
6401 (js2-add-to-string c))))
6402 (unless err
6403 (while continue
6404 (cond
6405 ((js2-match-char ?g)
6406 (push ?g flags))
6407 ((js2-match-char ?i)
6408 (push ?i flags))
6409 ((js2-match-char ?m)
6410 (push ?m flags))
6411 ((and (js2-match-char ?u)
6412 (>= js2-language-version 200))
6413 (push ?u flags))
6414 ((and (js2-match-char ?y)
6415 (>= js2-language-version 200))
6416 (push ?y flags))
6417 (t
6418 (setq continue nil))))
6419 (if (js2-alpha-p (js2-peek-char))
6420 (js2-report-scan-error "msg.invalid.re.flag" t
6421 js2-ts-cursor 1))
6422 (js2-set-string-from-buffer token))
6423 (js2-collect-string flags)))
6424
6425 (defun js2-get-first-xml-token ()
6426 (setq js2-ts-xml-open-tags-count 0
6427 js2-ts-is-xml-attribute nil
6428 js2-ts-xml-is-tag-content nil)
6429 (js2-unget-char)
6430 (js2-get-next-xml-token))
6431
6432 (defun js2-xml-discard-string (token)
6433 "Throw away the string in progress and flag an XML parse error."
6434 (setf js2-ts-string-buffer nil
6435 (js2-token-string token) nil)
6436 (js2-report-scan-error "msg.XML.bad.form" t))
6437
6438 (defun js2-get-next-xml-token ()
6439 (setq js2-ts-string-buffer nil) ; for recording the XML
6440 (let ((token (js2-new-token 0))
6441 c result)
6442 (setq result
6443 (catch 'return
6444 (while t
6445 (setq c (js2-get-char))
6446 (cond
6447 ((= c js2-EOF_CHAR)
6448 (throw 'return js2-ERROR))
6449 (js2-ts-xml-is-tag-content
6450 (cl-case c
6451 (?>
6452 (js2-add-to-string c)
6453 (setq js2-ts-xml-is-tag-content nil
6454 js2-ts-is-xml-attribute nil))
6455 (?/
6456 (js2-add-to-string c)
6457 (when (eq ?> (js2-peek-char))
6458 (setq c (js2-get-char))
6459 (js2-add-to-string c)
6460 (setq js2-ts-xml-is-tag-content nil)
6461 (cl-decf js2-ts-xml-open-tags-count)))
6462 (?{
6463 (js2-unget-char)
6464 (js2-set-string-from-buffer token)
6465 (throw 'return js2-XML))
6466 ((?\' ?\")
6467 (js2-add-to-string c)
6468 (unless (js2-read-quoted-string c token)
6469 (throw 'return js2-ERROR)))
6470 (?=
6471 (js2-add-to-string c)
6472 (setq js2-ts-is-xml-attribute t))
6473 ((? ?\t ?\r ?\n)
6474 (js2-add-to-string c))
6475 (t
6476 (js2-add-to-string c)
6477 (setq js2-ts-is-xml-attribute nil)))
6478 (when (and (not js2-ts-xml-is-tag-content)
6479 (zerop js2-ts-xml-open-tags-count))
6480 (js2-set-string-from-buffer token)
6481 (throw 'return js2-XMLEND)))
6482 (t
6483 ;; else not tag content
6484 (cl-case c
6485 (?<
6486 (js2-add-to-string c)
6487 (setq c (js2-peek-char))
6488 (cl-case c
6489 (?!
6490 (setq c (js2-get-char)) ;; skip !
6491 (js2-add-to-string c)
6492 (setq c (js2-peek-char))
6493 (cl-case c
6494 (?-
6495 (setq c (js2-get-char)) ;; skip -
6496 (js2-add-to-string c)
6497 (if (eq c ?-)
6498 (progn
6499 (js2-add-to-string c)
6500 (unless (js2-read-xml-comment token)
6501 (throw 'return js2-ERROR)))
6502 (js2-xml-discard-string token)
6503 (throw 'return js2-ERROR)))
6504 (?\[
6505 (setq c (js2-get-char)) ;; skip [
6506 (js2-add-to-string c)
6507 (if (and (= (js2-get-char) ?C)
6508 (= (js2-get-char) ?D)
6509 (= (js2-get-char) ?A)
6510 (= (js2-get-char) ?T)
6511 (= (js2-get-char) ?A)
6512 (= (js2-get-char) ?\[))
6513 (progn
6514 (js2-add-to-string ?C)
6515 (js2-add-to-string ?D)
6516 (js2-add-to-string ?A)
6517 (js2-add-to-string ?T)
6518 (js2-add-to-string ?A)
6519 (js2-add-to-string ?\[)
6520 (unless (js2-read-cdata token)
6521 (throw 'return js2-ERROR)))
6522 (js2-xml-discard-string token)
6523 (throw 'return js2-ERROR)))
6524 (t
6525 (unless (js2-read-entity token)
6526 (throw 'return js2-ERROR))))
6527 ;; Allow bare CDATA section, e.g.:
6528 ;; let xml = <![CDATA[ foo bar baz ]]>;
6529 (when (zerop js2-ts-xml-open-tags-count)
6530 (throw 'return js2-XMLEND)))
6531 (??
6532 (setq c (js2-get-char)) ;; skip ?
6533 (js2-add-to-string c)
6534 (unless (js2-read-PI token)
6535 (throw 'return js2-ERROR)))
6536 (?/
6537 ;; end tag
6538 (setq c (js2-get-char)) ;; skip /
6539 (js2-add-to-string c)
6540 (when (zerop js2-ts-xml-open-tags-count)
6541 (js2-xml-discard-string token)
6542 (throw 'return js2-ERROR))
6543 (setq js2-ts-xml-is-tag-content t)
6544 (cl-decf js2-ts-xml-open-tags-count))
6545 (t
6546 ;; start tag
6547 (setq js2-ts-xml-is-tag-content t)
6548 (cl-incf js2-ts-xml-open-tags-count))))
6549 (?{
6550 (js2-unget-char)
6551 (js2-set-string-from-buffer token)
6552 (throw 'return js2-XML))
6553 (t
6554 (js2-add-to-string c))))))))
6555 (setf (js2-token-end token) js2-ts-cursor)
6556 (setf (js2-token-type token) result)
6557 result))
6558
6559 (defun js2-read-quoted-string (quote token)
6560 (let (c)
6561 (catch 'return
6562 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6563 (js2-add-to-string c)
6564 (if (eq c quote)
6565 (throw 'return t)))
6566 (js2-xml-discard-string token) ;; throw away string in progress
6567 nil)))
6568
6569 (defun js2-read-xml-comment (token)
6570 (let ((c (js2-get-char)))
6571 (catch 'return
6572 (while (/= c js2-EOF_CHAR)
6573 (catch 'continue
6574 (js2-add-to-string c)
6575 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6576 (setq c (js2-get-char))
6577 (js2-add-to-string c)
6578 (if (eq (js2-peek-char) ?>)
6579 (progn
6580 (setq c (js2-get-char)) ;; skip >
6581 (js2-add-to-string c)
6582 (throw 'return t))
6583 (throw 'continue nil)))
6584 (setq c (js2-get-char))))
6585 (js2-xml-discard-string token)
6586 nil)))
6587
6588 (defun js2-read-cdata (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-entity (token)
6608 (let ((decl-tags 1)
6609 c)
6610 (catch 'return
6611 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6612 (js2-add-to-string c)
6613 (cl-case c
6614 (?<
6615 (cl-incf decl-tags))
6616 (?>
6617 (cl-decf decl-tags)
6618 (if (zerop decl-tags)
6619 (throw 'return t)))))
6620 (js2-xml-discard-string token)
6621 nil)))
6622
6623 (defun js2-read-PI (token)
6624 "Scan an XML processing instruction."
6625 (let (c)
6626 (catch 'return
6627 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6628 (js2-add-to-string c)
6629 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6630 (setq c (js2-get-char)) ;; Skip >
6631 (js2-add-to-string c)
6632 (throw 'return t)))
6633 (js2-xml-discard-string token)
6634 nil)))
6635
6636 ;;; Highlighting
6637
6638 (defun js2-set-face (beg end face &optional record)
6639 "Fontify a region. If RECORD is non-nil, record for later."
6640 (when (cl-plusp js2-highlight-level)
6641 (setq beg (min (point-max) beg)
6642 beg (max (point-min) beg)
6643 end (min (point-max) end)
6644 end (max (point-min) end))
6645 (if record
6646 (push (list beg end face) js2-mode-fontifications)
6647 (put-text-property beg end 'font-lock-face face))))
6648
6649 (defsubst js2-clear-face (beg end)
6650 (remove-text-properties beg end '(font-lock-face nil
6651 help-echo nil
6652 point-entered nil
6653 cursor-sensor-functions nil
6654 c-in-sws nil)))
6655
6656 (defconst js2-ecma-global-props
6657 (concat "^"
6658 (regexp-opt
6659 '("Infinity" "NaN" "undefined" "arguments") t)
6660 "$")
6661 "Value properties of the Ecma-262 Global Object.
6662 Shown at or above `js2-highlight-level' 2.")
6663
6664 ;; might want to add the name "arguments" to this list?
6665 (defconst js2-ecma-object-props
6666 (concat "^"
6667 (regexp-opt
6668 '("prototype" "__proto__" "__parent__") t)
6669 "$")
6670 "Value properties of the Ecma-262 Object constructor.
6671 Shown at or above `js2-highlight-level' 2.")
6672
6673 (defconst js2-ecma-global-funcs
6674 (concat
6675 "^"
6676 (regexp-opt
6677 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6678 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6679 "$")
6680 "Function properties of the Ecma-262 Global object.
6681 Shown at or above `js2-highlight-level' 2.")
6682
6683 (defconst js2-ecma-number-props
6684 (concat "^"
6685 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6686 "NEGATIVE_INFINITY"
6687 "POSITIVE_INFINITY") t)
6688 "$")
6689 "Properties of the Ecma-262 Number constructor.
6690 Shown at or above `js2-highlight-level' 2.")
6691
6692 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6693 "Properties of the Ecma-262 Date constructor.
6694 Shown at or above `js2-highlight-level' 2.")
6695
6696 (defconst js2-ecma-math-props
6697 (concat "^"
6698 (regexp-opt
6699 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6700 t)
6701 "$")
6702 "Properties of the Ecma-262 Math object.
6703 Shown at or above `js2-highlight-level' 2.")
6704
6705 (defconst js2-ecma-math-funcs
6706 (concat "^"
6707 (regexp-opt
6708 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6709 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6710 "$")
6711 "Function properties of the Ecma-262 Math object.
6712 Shown at or above `js2-highlight-level' 2.")
6713
6714 (defconst js2-ecma-function-props
6715 (concat
6716 "^"
6717 (regexp-opt
6718 '(;; properties of the Object prototype object
6719 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6720 "toLocaleString" "toString" "valueOf"
6721 ;; properties of the Function prototype object
6722 "apply" "call"
6723 ;; properties of the Array prototype object
6724 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6725 "splice" "unshift"
6726 ;; properties of the String prototype object
6727 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6728 "localeCompare" "match" "replace" "search" "split" "substring"
6729 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6730 "toUpperCase"
6731 ;; properties of the Number prototype object
6732 "toExponential" "toFixed" "toPrecision"
6733 ;; properties of the Date prototype object
6734 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6735 "getMinutes" "getMonth" "getSeconds" "getTime"
6736 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6737 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6738 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6739 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6740 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6741 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6742 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6743 "toTimeString" "toUTCString"
6744 ;; properties of the RegExp prototype object
6745 "exec" "test"
6746 ;; properties of the JSON prototype object
6747 "parse" "stringify"
6748 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6749 "toSource" "__defineGetter__" "__defineSetter__"
6750 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6751 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6752 t)
6753 "$")
6754 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6755 Shown at or above `js2-highlight-level' 3.")
6756
6757 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6758 (let ((target-name (and target
6759 (js2-name-node-p target)
6760 (js2-name-node-name target)))
6761 (prop-name (if prop (js2-name-node-name prop)))
6762 (level2 (>= js2-highlight-level 2))
6763 (level3 (>= js2-highlight-level 3)))
6764 (when level2
6765 (let ((face
6766 (if call-p
6767 (cond
6768 ((and target prop)
6769 (cond
6770 ((and level3 (string-match js2-ecma-function-props prop-name))
6771 'font-lock-builtin-face)
6772 ((and target-name prop)
6773 (cond
6774 ((string= target-name "Date")
6775 (if (string-match js2-ecma-date-props prop-name)
6776 'font-lock-builtin-face))
6777 ((string= target-name "Math")
6778 (if (string-match js2-ecma-math-funcs prop-name)
6779 'font-lock-builtin-face))))))
6780 (prop
6781 (if (string-match js2-ecma-global-funcs prop-name)
6782 'font-lock-builtin-face)))
6783 (cond
6784 ((and target prop)
6785 (cond
6786 ((string= target-name "Number")
6787 (if (string-match js2-ecma-number-props prop-name)
6788 'font-lock-constant-face))
6789 ((string= target-name "Math")
6790 (if (string-match js2-ecma-math-props prop-name)
6791 'font-lock-constant-face))))
6792 (prop
6793 (if (string-match js2-ecma-object-props prop-name)
6794 'font-lock-constant-face))))))
6795 (when (and (not face) target (not call-p) prop-name)
6796 (setq face 'js2-object-property))
6797 (when face
6798 (let ((pos (+ (js2-node-pos parent) ; absolute
6799 (js2-node-pos prop)))) ; relative
6800 (js2-set-face pos
6801 (+ pos (js2-node-len prop))
6802 face 'record)))))))
6803
6804 (defun js2-parse-highlight-member-expr-node (node)
6805 "Perform syntax highlighting of EcmaScript built-in properties.
6806 The variable `js2-highlight-level' governs this highlighting."
6807 (let (face target prop name pos end parent call-p callee)
6808 (cond
6809 ;; case 1: simple name, e.g. foo
6810 ((js2-name-node-p node)
6811 (setq name (js2-name-node-name node))
6812 ;; possible for name to be nil in rare cases - saw it when
6813 ;; running js2-mode on an elisp buffer. Might as well try to
6814 ;; make it so js2-mode never barfs.
6815 (when name
6816 (setq face (if (string-match js2-ecma-global-props name)
6817 'font-lock-constant-face))
6818 (when face
6819 (setq pos (js2-node-pos node)
6820 end (+ pos (js2-node-len node)))
6821 (js2-set-face pos end face 'record))))
6822 ;; case 2: property access or function call
6823 ((or (js2-prop-get-node-p node)
6824 ;; highlight function call if expr is a prop-get node
6825 ;; or a plain name (i.e. unqualified function call)
6826 (and (setq call-p (js2-call-node-p node))
6827 (setq callee (js2-call-node-target node)) ; separate setq!
6828 (or (js2-prop-get-node-p callee)
6829 (js2-name-node-p callee))))
6830 (setq parent node
6831 node (if call-p callee node))
6832 (if (and call-p (js2-name-node-p callee))
6833 (setq prop callee)
6834 (setq target (js2-prop-get-node-left node)
6835 prop (js2-prop-get-node-right node)))
6836 (cond
6837 ((js2-name-node-p prop)
6838 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6839 (js2-parse-highlight-prop-get parent target prop call-p))
6840 ((js2-name-node-p target)
6841 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6842 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6843
6844 (defun js2-parse-highlight-member-expr-fn-name (expr)
6845 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6846 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6847 We currently only handle the case where the last component is a prop-get
6848 of a simple name. Called before EXPR has a parent node."
6849 (let (pos
6850 (name (and (js2-prop-get-node-p expr)
6851 (js2-prop-get-node-right expr))))
6852 (when (js2-name-node-p name)
6853 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6854 (js2-node-pos name)))
6855 (+ pos (js2-node-len name))
6856 'font-lock-function-name-face
6857 'record))))
6858
6859 ;; source: http://jsdoc.sourceforge.net/
6860 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6861 ;; allows type specifications, and needs work before entering the wild.
6862
6863 (defconst js2-jsdoc-param-tag-regexp
6864 (concat "^\\s-*\\*+\\s-*\\(@"
6865 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6866 "\\)"
6867 "\\s-*\\({[^}]+}\\)?" ; optional type
6868 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6869 "\\_>")
6870 "Matches jsdoc tags with optional type and optional param name.")
6871
6872 (defconst js2-jsdoc-typed-tag-regexp
6873 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6874 (regexp-opt
6875 '("enum"
6876 "extends"
6877 "field"
6878 "id"
6879 "implements"
6880 "lends"
6881 "mods"
6882 "requires"
6883 "return"
6884 "returns"
6885 "throw"
6886 "throws"))
6887 "\\)\\)\\s-*\\({[^}]+}\\)?")
6888 "Matches jsdoc tags with optional type.")
6889
6890 (defconst js2-jsdoc-arg-tag-regexp
6891 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6892 (regexp-opt
6893 '("alias"
6894 "augments"
6895 "borrows"
6896 "bug"
6897 "base"
6898 "config"
6899 "default"
6900 "define"
6901 "exception"
6902 "function"
6903 "member"
6904 "memberOf"
6905 "name"
6906 "namespace"
6907 "since"
6908 "suppress"
6909 "this"
6910 "throws"
6911 "type"
6912 "version"))
6913 "\\)\\)\\s-+\\([^ \t]+\\)")
6914 "Matches jsdoc tags with a single argument.")
6915
6916 (defconst js2-jsdoc-empty-tag-regexp
6917 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6918 (regexp-opt
6919 '("addon"
6920 "author"
6921 "class"
6922 "const"
6923 "constant"
6924 "constructor"
6925 "constructs"
6926 "deprecated"
6927 "desc"
6928 "description"
6929 "event"
6930 "example"
6931 "exec"
6932 "export"
6933 "fileoverview"
6934 "final"
6935 "function"
6936 "hidden"
6937 "ignore"
6938 "implicitCast"
6939 "inheritDoc"
6940 "inner"
6941 "interface"
6942 "license"
6943 "noalias"
6944 "noshadow"
6945 "notypecheck"
6946 "override"
6947 "owner"
6948 "preserve"
6949 "preserveTry"
6950 "private"
6951 "protected"
6952 "public"
6953 "static"
6954 "supported"
6955 ))
6956 "\\)\\)\\s-*")
6957 "Matches empty jsdoc tags.")
6958
6959 (defconst js2-jsdoc-link-tag-regexp
6960 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6961 "Matches a jsdoc link or code tag.")
6962
6963 (defconst js2-jsdoc-see-tag-regexp
6964 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6965 "Matches a jsdoc @see tag.")
6966
6967 (defconst js2-jsdoc-html-tag-regexp
6968 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6969 "Matches a simple (no attributes) html start- or end-tag.")
6970
6971 (defun js2-jsdoc-highlight-helper ()
6972 (js2-set-face (match-beginning 1)
6973 (match-end 1)
6974 'js2-jsdoc-tag)
6975 (if (match-beginning 2)
6976 (if (save-excursion
6977 (goto-char (match-beginning 2))
6978 (= (char-after) ?{))
6979 (js2-set-face (1+ (match-beginning 2))
6980 (1- (match-end 2))
6981 'js2-jsdoc-type)
6982 (js2-set-face (match-beginning 2)
6983 (match-end 2)
6984 'js2-jsdoc-value)))
6985 (if (match-beginning 3)
6986 (js2-set-face (match-beginning 3)
6987 (match-end 3)
6988 'js2-jsdoc-value)))
6989
6990 (defun js2-highlight-jsdoc (ast)
6991 "Highlight doc comment tags."
6992 (let ((comments (js2-ast-root-comments ast))
6993 beg end)
6994 (save-excursion
6995 (dolist (node comments)
6996 (when (eq (js2-comment-node-format node) 'jsdoc)
6997 (setq beg (js2-node-abs-pos node)
6998 end (+ beg (js2-node-len node)))
6999 (save-restriction
7000 (narrow-to-region beg end)
7001 (dolist (re (list js2-jsdoc-param-tag-regexp
7002 js2-jsdoc-typed-tag-regexp
7003 js2-jsdoc-arg-tag-regexp
7004 js2-jsdoc-link-tag-regexp
7005 js2-jsdoc-see-tag-regexp
7006 js2-jsdoc-empty-tag-regexp))
7007 (goto-char beg)
7008 (while (re-search-forward re nil t)
7009 (js2-jsdoc-highlight-helper)))
7010 ;; simple highlighting for html tags
7011 (goto-char beg)
7012 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7013 (js2-set-face (match-beginning 1)
7014 (match-end 1)
7015 'js2-jsdoc-html-tag-delimiter)
7016 (js2-set-face (match-beginning 2)
7017 (match-end 2)
7018 'js2-jsdoc-html-tag-name)
7019 (js2-set-face (match-beginning 3)
7020 (match-end 3)
7021 'js2-jsdoc-html-tag-delimiter))))))))
7022
7023 (defun js2-highlight-assign-targets (_node left right)
7024 "Highlight function properties and external variables."
7025 (let (leftpos name)
7026 ;; highlight vars and props assigned function values
7027 (when (or (js2-function-node-p right)
7028 (js2-class-node-p right))
7029 (cond
7030 ;; var foo = function() {...}
7031 ((js2-name-node-p left)
7032 (setq name left))
7033 ;; foo.bar.baz = function() {...}
7034 ((and (js2-prop-get-node-p left)
7035 (js2-name-node-p (js2-prop-get-node-right left)))
7036 (setq name (js2-prop-get-node-right left))))
7037 (when name
7038 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7039 (+ leftpos (js2-node-len name))
7040 'font-lock-function-name-face
7041 'record)))))
7042
7043 (defun js2-record-name-node (node)
7044 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7045 later. NODE must be a name node."
7046 (let ((leftpos (js2-node-abs-pos node)))
7047 (push (list node js2-current-scope
7048 leftpos
7049 (+ leftpos (js2-node-len node)))
7050 js2-recorded-identifiers)))
7051
7052 (defun js2-highlight-undeclared-vars ()
7053 "After entire parse is finished, look for undeclared variable references.
7054 We have to wait until entire buffer is parsed, since JavaScript permits var
7055 decls to occur after they're used.
7056
7057 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7058 it is considered declared."
7059 (let (name)
7060 (dolist (entry js2-recorded-identifiers)
7061 (cl-destructuring-bind (name-node scope pos end) entry
7062 (setq name (js2-name-node-name name-node))
7063 (unless (or (member name js2-global-externs)
7064 (member name js2-default-externs)
7065 (member name js2-additional-externs)
7066 (js2-get-defining-scope scope name pos))
7067 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7068 'js2-external-variable))))))
7069
7070 (defun js2--add-or-update-symbol (symbol inition used vars)
7071 "Add or update SYMBOL entry in VARS, an hash table.
7072 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7073 respectively meaning that SYMBOL is a mere declaration, an
7074 assignment or a function parameter; when USED is t, the symbol
7075 node is assumed to be an usage and thus added to the list stored
7076 in the cdr of the entry.
7077 "
7078 (let* ((nm (js2-name-node-name symbol))
7079 (es (js2-node-get-enclosing-scope symbol))
7080 (ds (js2-get-defining-scope es nm)))
7081 (when (and ds (not (equal nm "arguments")))
7082 (let* ((sym (js2-scope-get-symbol ds nm))
7083 (var (gethash sym vars))
7084 (err-var-p (js2-catch-node-p ds)))
7085 (unless inition
7086 (setq inition err-var-p))
7087 (if var
7088 (progn
7089 (when (and inition (not (equal (car var) ?P)))
7090 (setcar var inition))
7091 (when used
7092 (push symbol (cdr var))))
7093 ;; do not consider the declaration of catch parameter as an usage
7094 (when (and err-var-p used)
7095 (setq used nil))
7096 (puthash sym (cons inition (if used (list symbol))) vars))))))
7097
7098 (defun js2--classify-variables ()
7099 "Collect and classify variables declared or used within js2-mode-ast.
7100 Traverse the whole ast tree returning a summary of the variables
7101 usage as an hash-table, keyed by their corresponding symbol table
7102 entry.
7103 Each variable is described by a tuple where the car is a flag
7104 indicating whether the variable has been initialized and the cdr
7105 is a possibly empty list of name nodes where it is used. External
7106 symbols, i.e. those not present in the whole scopes hierarchy,
7107 are ignored."
7108 (let ((vars (make-hash-table :test #'eq :size 100)))
7109 (js2-visit-ast
7110 js2-mode-ast
7111 (lambda (node end-p)
7112 (when (null end-p)
7113 (cond
7114 ((js2-var-init-node-p node)
7115 ;; take note about possibly initialized declarations
7116 (let ((target (js2-var-init-node-target node))
7117 (initializer (js2-var-init-node-initializer node)))
7118 (when target
7119 (let* ((parent (js2-node-parent node))
7120 (grandparent (if parent (js2-node-parent parent)))
7121 (inited (not (null initializer))))
7122 (unless inited
7123 (setq inited
7124 (and grandparent
7125 (js2-for-in-node-p grandparent)
7126 (memq target
7127 (mapcar #'js2-var-init-node-target
7128 (js2-var-decl-node-kids
7129 (js2-for-in-node-iterator grandparent)))))))
7130 (js2--add-or-update-symbol target inited nil vars)))))
7131
7132 ((js2-assign-node-p node)
7133 ;; take note about assignments
7134 (let ((left (js2-assign-node-left node)))
7135 (when (js2-name-node-p left)
7136 (js2--add-or-update-symbol left t nil vars))))
7137
7138 ((js2-prop-get-node-p node)
7139 ;; handle x.y.z nodes, considering only x
7140 (let ((left (js2-prop-get-node-left node)))
7141 (when (js2-name-node-p left)
7142 (js2--add-or-update-symbol left nil t vars))))
7143
7144 ((js2-name-node-p node)
7145 ;; take note about used variables
7146 (let ((parent (js2-node-parent node)))
7147 (when parent
7148 (unless (or (and (js2-var-init-node-p parent) ; handled above
7149 (eq node (js2-var-init-node-target parent)))
7150 (and (js2-assign-node-p parent)
7151 (eq node (js2-assign-node-left parent)))
7152 (js2-prop-get-node-p parent))
7153 (let ((used t) inited)
7154 (cond
7155 ((and (js2-function-node-p parent)
7156 (js2-wrapper-function-p parent))
7157 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7158
7159 ((js2-for-in-node-p parent)
7160 (if (eq node (js2-for-in-node-iterator parent))
7161 (setq inited t used nil)))
7162
7163 ((js2-function-node-p parent)
7164 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7165 used nil)))
7166
7167 (unless used
7168 (let ((grandparent (js2-node-parent parent)))
7169 (when grandparent
7170 (setq used (js2-return-node-p grandparent)))))
7171
7172 (js2--add-or-update-symbol node inited used vars))))))))
7173 t))
7174 vars))
7175
7176 (defun js2--get-name-node (node)
7177 (cond
7178 ((js2-name-node-p node) node)
7179 ((js2-function-node-p node)
7180 (js2-function-node-name node))
7181 ((js2-class-node-p node)
7182 (js2-class-node-name node))
7183 ((js2-comp-loop-node-p node)
7184 (js2-comp-loop-node-iterator node))
7185 (t node)))
7186
7187 (defun js2--highlight-unused-variable (symbol info)
7188 (let ((name (js2-symbol-name symbol))
7189 (inited (car info))
7190 (refs (cdr info))
7191 pos len)
7192 (unless (and inited refs)
7193 (if refs
7194 (dolist (ref refs)
7195 (setq pos (js2-node-abs-pos ref))
7196 (setq len (js2-name-node-len ref))
7197 (js2-report-warning "msg.uninitialized.variable" name pos len
7198 'js2-warning))
7199 (when (or js2-warn-about-unused-function-arguments
7200 (not (eq inited ?P)))
7201 (let* ((symn (js2-symbol-ast-node symbol))
7202 (namen (js2--get-name-node symn)))
7203 (unless (js2-node-top-level-decl-p namen)
7204 (setq pos (js2-node-abs-pos namen))
7205 (setq len (js2-name-node-len namen))
7206 (js2-report-warning "msg.unused.variable" name pos len
7207 'js2-warning))))))))
7208
7209 (defun js2-highlight-unused-variables ()
7210 "Highlight unused variables."
7211 (let ((vars (js2--classify-variables)))
7212 (maphash #'js2--highlight-unused-variable vars)))
7213
7214 ;;;###autoload
7215 (define-minor-mode js2-highlight-unused-variables-mode
7216 "Toggle highlight of unused variables."
7217 :lighter ""
7218 (if js2-highlight-unused-variables-mode
7219 (add-hook 'js2-post-parse-callbacks
7220 #'js2-highlight-unused-variables nil t)
7221 (remove-hook 'js2-post-parse-callbacks
7222 #'js2-highlight-unused-variables t)))
7223
7224 (defun js2-set-default-externs ()
7225 "Set the value of `js2-default-externs' based on the various
7226 `js2-include-?-externs' variables."
7227 (setq js2-default-externs
7228 (append js2-ecma-262-externs
7229 (if js2-include-browser-externs js2-browser-externs)
7230 (if (and js2-include-browser-externs
7231 (>= js2-language-version 200)) js2-harmony-externs)
7232 (if js2-include-rhino-externs js2-rhino-externs)
7233 (if js2-include-node-externs js2-node-externs)
7234 (if (or js2-include-browser-externs js2-include-node-externs)
7235 js2-typed-array-externs))))
7236
7237 (defun js2-apply-jslint-globals ()
7238 (setq js2-additional-externs
7239 (nconc (js2-get-jslint-globals)
7240 js2-additional-externs)))
7241
7242 (defun js2-get-jslint-globals ()
7243 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7244 when (and (eq 'block (js2-comment-node-format node))
7245 (save-excursion
7246 (goto-char (js2-node-abs-pos node))
7247 (looking-at "/\\*global ")))
7248 append (js2-get-jslint-globals-in
7249 (match-end 0)
7250 (js2-node-abs-end node))))
7251
7252 (defun js2-get-jslint-globals-in (beg end)
7253 (let (res)
7254 (save-excursion
7255 (goto-char beg)
7256 (while (re-search-forward js2-mode-identifier-re end t)
7257 (let ((match (match-string 0)))
7258 (unless (member match '("true" "false"))
7259 (push match res)))))
7260 (nreverse res)))
7261
7262 ;;; IMenu support
7263
7264 ;; We currently only support imenu, but eventually should support speedbar and
7265 ;; possibly other browsing mechanisms.
7266
7267 ;; The basic strategy is to identify function assignment targets of the form
7268 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7269 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7270 ;; for imenu after parsing is finished.
7271
7272 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7273 ;; JavaScript, and the general problem is undecidable. However, several forms
7274 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7275 ;; include:
7276
7277 ;; function foo() -- function declaration
7278 ;; foo = function() -- function expression assigned to variable
7279 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7280 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7281 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7282 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7283 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7284 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7285 ;; function foo() {function bar() {...}} -- nested function
7286 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7287
7288 ;; This list boils down to a few forms that can be combined recursively.
7289 ;; Top-level named function declarations include both the left-hand (name)
7290 ;; and the right-hand (function value) expressions needed to produce an imenu
7291 ;; entry. The other "right-hand" forms we need to look for are:
7292 ;; - functions declared as props/getters/setters in object literals
7293 ;; - nested named function declarations
7294 ;; The "left-hand" expressions that functions can be assigned to include:
7295 ;; - local/global variables
7296 ;; - nested property-get expressions like a.b.c.d
7297 ;; - element gets like foo[10] or foo['bar'] where the index
7298 ;; expression can be trivially converted to a property name. They
7299 ;; effectively then become property gets.
7300
7301 ;; All the different definition types are canonicalized into the form
7302 ;; foo.bar.baz = position-of-function-keyword
7303
7304 ;; We need to build a trie-like structure for imenu. As an example,
7305 ;; consider the following JavaScript code:
7306
7307 ;; a = function() {...} // function at position 5
7308 ;; b = function() {...} // function at position 25
7309 ;; foo = function() {...} // function at position 100
7310 ;; foo.bar = function() {...} // function at position 200
7311 ;; foo.bar.baz = function() {...} // function at position 300
7312 ;; foo.bar.zab = function() {...} // function at position 400
7313
7314 ;; During parsing we accumulate an entry for each definition in
7315 ;; the variable `js2-imenu-recorder', like so:
7316
7317 ;; '((fn a 5)
7318 ;; (fn b 25)
7319 ;; (fn foo 100)
7320 ;; (fn foo bar 200)
7321 ;; (fn foo bar baz 300)
7322 ;; (fn foo bar zab 400))
7323
7324 ;; Where 'fn' is the respective function node.
7325 ;; After parsing these entries are merged into this alist-trie:
7326
7327 ;; '((a . 1)
7328 ;; (b . 2)
7329 ;; (foo (<definition> . 3)
7330 ;; (bar (<definition> . 6)
7331 ;; (baz . 100)
7332 ;; (zab . 200))))
7333
7334 ;; Note the wacky need for a <definition> name. The token can be anything
7335 ;; that isn't a valid JavaScript identifier, because you might make foo
7336 ;; a function and then start setting properties on it that are also functions.
7337
7338 (defun js2-prop-node-name (node)
7339 "Return the name of a node that may be a property-get/property-name.
7340 If NODE is not a valid name-node, string-node or integral number-node,
7341 returns nil. Otherwise returns the string name/value of the node."
7342 (cond
7343 ((js2-name-node-p node)
7344 (js2-name-node-name node))
7345 ((js2-string-node-p node)
7346 (js2-string-node-value node))
7347 ((and (js2-number-node-p node)
7348 (string-match "^[0-9]+$" (js2-number-node-value node)))
7349 (js2-number-node-value node))
7350 ((eq (js2-node-type node) js2-THIS)
7351 "this")
7352 ((eq (js2-node-type node) js2-SUPER)
7353 "super")))
7354
7355 (defun js2-node-qname-component (node)
7356 "Return the name of this node, if it contributes to a qname.
7357 Returns nil if the node doesn't contribute."
7358 (copy-sequence
7359 (or (js2-prop-node-name node)
7360 (if (and (js2-function-node-p node)
7361 (js2-function-node-name node))
7362 (js2-name-node-name (js2-function-node-name node))))))
7363
7364 (defun js2-record-imenu-entry (fn-node qname pos)
7365 "Add an entry to `js2-imenu-recorder'.
7366 FN-NODE should be the current item's function node.
7367
7368 Associate FN-NODE with its QNAME for later lookup.
7369 This is used in postprocessing the chain list. For each chain, we find
7370 the parent function, look up its qname, then prepend a copy of it to the chain."
7371 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7372 (unless js2-imenu-function-map
7373 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7374 (puthash fn-node qname js2-imenu-function-map))
7375
7376 (defun js2-record-imenu-functions (node &optional var)
7377 "Record function definitions for imenu.
7378 NODE is a function node or an object literal.
7379 VAR, if non-nil, is the expression that NODE is being assigned to.
7380 When passed arguments of wrong type, does nothing."
7381 (when js2-parse-ide-mode
7382 (let ((fun-p (js2-function-node-p node))
7383 qname fname-node)
7384 (cond
7385 ;; non-anonymous function declaration?
7386 ((and fun-p
7387 (not var)
7388 (setq fname-node (js2-function-node-name node)))
7389 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7390 ;; for remaining forms, compute left-side tree branch first
7391 ((and var (setq qname (js2-compute-nested-prop-get var)))
7392 (cond
7393 ;; foo.bar.baz = function
7394 (fun-p
7395 (js2-record-imenu-entry node qname (js2-node-pos node)))
7396 ;; foo.bar.baz = object-literal
7397 ;; look for nested functions: {a: {b: function() {...} }}
7398 ((js2-object-node-p node)
7399 ;; Node position here is still absolute, since the parser
7400 ;; passes the assignment target and value expressions
7401 ;; to us before they are added as children of the assignment node.
7402 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7403
7404 (defun js2-compute-nested-prop-get (node)
7405 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7406 component nodes as a list. Otherwise return nil. Element-gets are treated
7407 as property-gets if the index expression is a string, or a positive integer."
7408 (let (left right head)
7409 (cond
7410 ((or (js2-name-node-p node)
7411 (js2-this-or-super-node-p node))
7412 (list node))
7413 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7414 ((js2-prop-get-node-p node) ; foo.bar
7415 (setq left (js2-prop-get-node-left node)
7416 right (js2-prop-get-node-right node))
7417 (if (setq head (js2-compute-nested-prop-get left))
7418 (nconc head (list right))))
7419 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7420 (setq left (js2-elem-get-node-target node)
7421 right (js2-elem-get-node-element node))
7422 (if (or (js2-string-node-p right) ; ['bar']
7423 (and (js2-number-node-p right) ; [10]
7424 (string-match "^[0-9]+$"
7425 (js2-number-node-value right))))
7426 (if (setq head (js2-compute-nested-prop-get left))
7427 (nconc head (list right))))))))
7428
7429 (defun js2-record-object-literal (node qname pos)
7430 "Recursively process an object literal looking for functions.
7431 NODE is an object literal that is the right-hand child of an assignment
7432 expression. QNAME is a list of nodes representing the assignment target,
7433 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7434 POS is the absolute position of the node.
7435 We do a depth-first traversal of NODE. For any functions we find,
7436 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7437 (let (right)
7438 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7439 (let ((left (js2-infix-node-left e))
7440 ;; Element positions are relative to the parent position.
7441 (pos (+ pos (js2-node-pos e))))
7442 (cond
7443 ;; foo: function() {...}
7444 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7445 (when (js2-prop-node-name left)
7446 ;; As a policy decision, we record the position of the property,
7447 ;; not the position of the `function' keyword, since the property
7448 ;; is effectively the name of the function.
7449 (js2-record-imenu-entry right (append qname (list left)) pos)))
7450 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7451 ((js2-object-node-p right)
7452 (js2-record-object-literal right
7453 (append qname (list (js2-infix-node-left e)))
7454 (+ pos (js2-node-pos right)))))))))
7455
7456 (defun js2-node-top-level-decl-p (node)
7457 "Return t if NODE's name is defined in the top-level scope.
7458 Also returns t if NODE's name is not defined in any scope, since it implies
7459 that it's an external variable, which must also be in the top-level scope."
7460 (let* ((name (js2-prop-node-name node))
7461 (this-scope (js2-node-get-enclosing-scope node))
7462 defining-scope)
7463 (cond
7464 ((js2-this-or-super-node-p node)
7465 nil)
7466 ((null this-scope)
7467 t)
7468 ((setq defining-scope (js2-get-defining-scope this-scope name))
7469 (js2-ast-root-p defining-scope))
7470 (t t))))
7471
7472 (defun js2-wrapper-function-p (node)
7473 "Return t if NODE is a function expression that's immediately invoked.
7474 NODE must be `js2-function-node'."
7475 (let ((parent (js2-node-parent node)))
7476 (or
7477 ;; function(){...}();
7478 (and (js2-call-node-p parent)
7479 (eq node (js2-call-node-target parent)))
7480 (and (js2-paren-node-p parent)
7481 ;; (function(){...})();
7482 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7483 ;; (function(){...}).call(this);
7484 (and (js2-prop-get-node-p parent)
7485 (member (js2-name-node-name (js2-prop-get-node-right parent))
7486 '("call" "apply"))
7487 (js2-call-node-p (js2-node-parent parent))))))))
7488
7489 (defun js2-browse-postprocess-chains ()
7490 "Modify function-declaration name chains after parsing finishes.
7491 Some of the information is only available after the parse tree is complete.
7492 For instance, processing a nested scope requires a parent function node."
7493 (let (result fn parent-qname p elem)
7494 (dolist (entry js2-imenu-recorder)
7495 ;; function node goes first
7496 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7497 ;; Examine head's defining scope:
7498 ;; Pre-processed chain, or top-level/external, keep as-is.
7499 (if (or (stringp head) (js2-node-top-level-decl-p head))
7500 (push chain result)
7501 (when (js2-this-or-super-node-p head)
7502 (setq chain (cdr chain))) ; discard this-node
7503 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7504 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7505 (when (eq parent-qname 'not-found)
7506 ;; anonymous function expressions are not recorded
7507 ;; during the parse, so we need to handle this case here
7508 (setq parent-qname
7509 (if (js2-wrapper-function-p fn)
7510 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7511 (if (js2-ast-root-p grandparent)
7512 nil
7513 (gethash grandparent js2-imenu-function-map 'skip)))
7514 'skip))
7515 (puthash fn parent-qname js2-imenu-function-map))
7516 (if (eq parent-qname 'skip)
7517 ;; We don't show it, let's record that fact.
7518 (remhash current-fn js2-imenu-function-map)
7519 ;; Prepend parent fn qname to this chain.
7520 (let ((qname (append parent-qname chain)))
7521 (puthash current-fn (butlast qname) js2-imenu-function-map)
7522 (push qname result)))))))
7523 ;; Collect chains obtained by third-party code.
7524 (let (js2-imenu-recorder)
7525 (run-hooks 'js2-build-imenu-callbacks)
7526 (dolist (entry js2-imenu-recorder)
7527 (push (cdr entry) result)))
7528 ;; Finally replace each node in each chain with its name.
7529 (dolist (chain result)
7530 (setq p chain)
7531 (while p
7532 (if (js2-node-p (setq elem (car p)))
7533 (setcar p (js2-node-qname-component elem)))
7534 (setq p (cdr p))))
7535 result))
7536
7537 ;; Merge name chains into a trie-like tree structure of nested lists.
7538 ;; To simplify construction of the trie, we first build it out using the rule
7539 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7540 ;; [key, num-or-list]. The second element can be a number; if so, this key
7541 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7542 ;; associated with the key at this level.) Otherwise the second element is
7543 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7544 ;; a simple recursive formulation.
7545 ;;
7546 ;; js2-mode is building the data structure for imenu. The imenu documentation
7547 ;; claims that it's the structure above, but in practice it wants the children
7548 ;; at the same list level as the key for that level, which is how I've drawn
7549 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7550 ;; list wrapper around the children at each level.
7551 ;;
7552 ;; A completed nested imenu-alist entry looks like this:
7553 ;; '(("foo"
7554 ;; ("<definition>" . 7)
7555 ;; ("bar"
7556 ;; ("a" . 40)
7557 ;; ("b" . 60))))
7558 ;;
7559 ;; In particular, the documentation for `imenu--index-alist' says that
7560 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7561 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7562
7563 (defun js2-treeify (lst)
7564 "Convert (a b c d) to (a ((b ((c d)))))."
7565 (if (null (cddr lst)) ; list length <= 2
7566 lst
7567 (list (car lst) (list (js2-treeify (cdr lst))))))
7568
7569 (defun js2-build-alist-trie (chains trie)
7570 "Merge declaration name chains into a trie-like alist structure for imenu.
7571 CHAINS is the qname chain list produced during parsing. TRIE is a
7572 list of elements built up so far."
7573 (let (head tail pos branch kids)
7574 (dolist (chain chains)
7575 (setq head (car chain)
7576 tail (cdr chain)
7577 pos (if (numberp (car tail)) (car tail))
7578 branch (js2-find-if (lambda (n)
7579 (string= (car n) head))
7580 trie)
7581 kids (cl-second branch))
7582 (cond
7583 ;; case 1: this key isn't in the trie yet
7584 ((null branch)
7585 (if trie
7586 (setcdr (last trie) (list (js2-treeify chain)))
7587 (setq trie (list (js2-treeify chain)))))
7588 ;; case 2: key is present with a single number entry: replace w/ list
7589 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7590 ;; ("<definition>" 20)))
7591 ((numberp kids)
7592 (setcar (cdr branch)
7593 (list (list "<definition-1>" kids)
7594 (if pos
7595 (list "<definition-2>" pos)
7596 (js2-treeify tail)))))
7597 ;; case 3: key is there (with kids), and we're a number entry
7598 (pos
7599 (setcdr (last kids)
7600 (list
7601 (list (format "<definition-%d>"
7602 (1+ (cl-loop for kid in kids
7603 count (eq ?< (aref (car kid) 0)))))
7604 pos))))
7605 ;; case 4: key is there with kids, need to merge in our chain
7606 (t
7607 (js2-build-alist-trie (list tail) kids))))
7608 trie))
7609
7610 (defun js2-flatten-trie (trie)
7611 "Convert TRIE to imenu-format.
7612 Recurses through nodes, and for each one whose second element is a list,
7613 appends the list's flattened elements to the current element. Also
7614 changes the tails into conses. For instance, this pre-flattened trie
7615
7616 '(a ((b 20)
7617 (c ((d 30)
7618 (e 40)))))
7619
7620 becomes
7621
7622 '(a (b . 20)
7623 (c (d . 30)
7624 (e . 40)))
7625
7626 Note that the root of the trie has no key, just a list of chains.
7627 This is also true for the value of any key with multiple children,
7628 e.g. key 'c' in the example above."
7629 (cond
7630 ((listp (car trie))
7631 (mapcar #'js2-flatten-trie trie))
7632 (t
7633 (if (numberp (cl-second trie))
7634 (cons (car trie) (cl-second trie))
7635 ;; else pop list and append its kids
7636 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7637
7638 (defun js2-build-imenu-index ()
7639 "Turn `js2-imenu-recorder' into an imenu data structure."
7640 (when (eq js2-imenu-recorder 'empty)
7641 (setq js2-imenu-recorder nil))
7642 (let* ((chains (js2-browse-postprocess-chains))
7643 (result (js2-build-alist-trie chains nil)))
7644 (js2-flatten-trie result)))
7645
7646 (defun js2-test-print-chains (chains)
7647 "Print a list of qname chains.
7648 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7649 i.e. one or more nodes, and an integer position as the list tail."
7650 (mapconcat (lambda (chain)
7651 (concat "("
7652 (mapconcat (lambda (elem)
7653 (if (js2-node-p elem)
7654 (or (js2-node-qname-component elem)
7655 "nil")
7656 (number-to-string elem)))
7657 chain
7658 " ")
7659 ")"))
7660 chains
7661 "\n"))
7662
7663 ;;; Parser
7664
7665 (defconst js2-version "1.8.5"
7666 "Version of JavaScript supported.")
7667
7668 (defun js2-record-face (face &optional token)
7669 "Record a style run of FACE for TOKEN or the current token."
7670 (unless token (setq token (js2-current-token)))
7671 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7672
7673 (defsubst js2-node-end (n)
7674 "Computes the absolute end of node N.
7675 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7676 is only true until the node is added to its parent; i.e., while parsing."
7677 (+ (js2-node-pos n)
7678 (js2-node-len n)))
7679
7680 (defun js2-record-comment (token)
7681 "Record a comment in `js2-scanned-comments'."
7682 (let ((ct (js2-token-comment-type token))
7683 (beg (js2-token-beg token))
7684 (end (js2-token-end token)))
7685 (push (make-js2-comment-node :len (- end beg)
7686 :format ct)
7687 js2-scanned-comments)
7688 (when js2-parse-ide-mode
7689 (js2-record-face (if (eq ct 'jsdoc)
7690 'font-lock-doc-face
7691 'font-lock-comment-face)
7692 token)
7693 (when (memq ct '(html preprocessor))
7694 ;; Tell cc-engine the bounds of the comment.
7695 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7696
7697 (defun js2-peek-token ()
7698 "Return the next token type without consuming it.
7699 If `js2-ti-lookahead' is positive, return the type of next token
7700 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7701 (if (not (zerop js2-ti-lookahead))
7702 (js2-token-type
7703 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7704 (let ((tt (js2-get-token-internal nil)))
7705 (js2-unget-token)
7706 tt)))
7707
7708 (defalias 'js2-next-token 'js2-get-token)
7709
7710 (defun js2-match-token (match &optional dont-unget)
7711 "Get next token and return t if it matches MATCH, a bytecode.
7712 Returns nil and consumes nothing if MATCH is not the next token."
7713 (if (/= (js2-get-token) match)
7714 (ignore (unless dont-unget (js2-unget-token)))
7715 t))
7716
7717 (defun js2-match-contextual-kwd (name)
7718 "Consume and return t if next token is `js2-NAME', and its
7719 string is NAME. Returns nil and keeps current token otherwise."
7720 (if (js2-contextual-kwd-p (progn (js2-get-token)
7721 (js2-current-token))
7722 name)
7723 (progn (js2-record-face 'font-lock-keyword-face) t)
7724 (js2-unget-token)
7725 nil))
7726
7727 (defun js2-contextual-kwd-p (token name)
7728 "Return t if TOKEN is `js2-NAME', and its string is NAME."
7729 (and (= (js2-token-type token) js2-NAME)
7730 (string= (js2-token-string token) name)))
7731
7732 (defun js2-match-async-function ()
7733 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7734 (= (js2-peek-token) js2-FUNCTION))
7735 (js2-record-face 'font-lock-keyword-face)
7736 (js2-get-token)
7737 t))
7738
7739 (defun js2-match-async-arrow-function ()
7740 (when (and (js2-contextual-kwd-p (js2-current-token) "async")
7741 (/= (js2-peek-token) js2-FUNCTION))
7742 (js2-record-face 'font-lock-keyword-face)
7743 (js2-get-token)
7744 t))
7745
7746 (defun js2-match-await ()
7747 (when (and (= tt js2-NAME)
7748 (js2-contextual-kwd-p (js2-current-token) "await"))
7749 (js2-record-face 'font-lock-keyword-face)
7750 (let ((beg (js2-current-token-beg))
7751 (end (js2-current-token-end)))
7752 (js2-get-token)
7753 (unless (and (js2-inside-function)
7754 (js2-function-node-async js2-current-script-or-fn))
7755 (js2-report-error "msg.bad.await" nil
7756 beg (- end beg))))
7757 t))
7758
7759 (defun js2-get-prop-name-token ()
7760 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7761
7762 (defun js2-match-prop-name ()
7763 "Consume token and return t if next token is a valid property name.
7764 If `js2-language-version' is >= 180, a keyword or reserved word
7765 is considered valid name as well."
7766 (if (eq js2-NAME (js2-get-prop-name-token))
7767 t
7768 (js2-unget-token)
7769 nil))
7770
7771 (defun js2-must-match-prop-name (msg-id &optional pos len)
7772 (if (js2-match-prop-name)
7773 t
7774 (js2-report-error msg-id nil pos len)
7775 nil))
7776
7777 (defun js2-peek-token-or-eol ()
7778 "Return js2-EOL if the next token immediately follows a newline.
7779 Else returns the next token. Used in situations where we don't
7780 consider certain token types valid if they are preceded by a newline.
7781 One example is the postfix ++ or -- operator, which has to be on the
7782 same line as its operand."
7783 (let ((tt (js2-get-token))
7784 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7785 (js2-unget-token)
7786 (if follows-eol
7787 js2-EOL
7788 tt)))
7789
7790 (defun js2-must-match (token msg-id &optional pos len)
7791 "Match next token to token code TOKEN, or record a syntax error.
7792 MSG-ID is the error message to report if the match fails.
7793 Returns t on match, nil if no match."
7794 (if (js2-match-token token t)
7795 t
7796 (js2-report-error msg-id nil pos len)
7797 (js2-unget-token)
7798 nil))
7799
7800 (defun js2-must-match-name (msg-id)
7801 (if (js2-match-token js2-NAME t)
7802 t
7803 (if (eq (js2-current-token-type) js2-RESERVED)
7804 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7805 (js2-report-error msg-id)
7806 (js2-unget-token))
7807 nil))
7808
7809 (defsubst js2-inside-function ()
7810 (cl-plusp js2-nesting-of-function))
7811
7812 (defun js2-set-requires-activation ()
7813 (if (js2-function-node-p js2-current-script-or-fn)
7814 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7815
7816 (defun js2-check-activation-name (name _token)
7817 (when (js2-inside-function)
7818 ;; skip language-version 1.2 check from Rhino
7819 (if (or (string= "arguments" name)
7820 (and js2-compiler-activation-names ; only used in codegen
7821 (gethash name js2-compiler-activation-names)))
7822 (js2-set-requires-activation))))
7823
7824 (defun js2-set-is-generator ()
7825 (let ((fn-node js2-current-script-or-fn))
7826 (when (and (js2-function-node-p fn-node)
7827 (not (js2-function-node-generator-type fn-node)))
7828 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7829
7830 (defun js2-must-have-xml ()
7831 (unless js2-compiler-xml-available
7832 (js2-report-error "msg.XML.not.available")))
7833
7834 (defun js2-push-scope (scope)
7835 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7836 (cl-assert (js2-scope-p scope))
7837 (cl-assert (null (js2-scope-parent-scope scope)))
7838 (cl-assert (not (eq js2-current-scope scope)))
7839 (setf (js2-scope-parent-scope scope) js2-current-scope
7840 js2-current-scope scope))
7841
7842 (defsubst js2-pop-scope ()
7843 (setq js2-current-scope
7844 (js2-scope-parent-scope js2-current-scope)))
7845
7846 (defun js2-enter-loop (loop-node)
7847 (push loop-node js2-loop-set)
7848 (push loop-node js2-loop-and-switch-set)
7849 (js2-push-scope loop-node)
7850 ;; Tell the current labeled statement (if any) its statement,
7851 ;; and set the jump target of the first label to the loop.
7852 ;; These are used in `js2-parse-continue' to verify that the
7853 ;; continue target is an actual labeled loop. (And for codegen.)
7854 (when js2-labeled-stmt
7855 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7856 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7857 js2-labeled-stmt))) loop-node)))
7858
7859 (defun js2-exit-loop ()
7860 (pop js2-loop-set)
7861 (pop js2-loop-and-switch-set)
7862 (js2-pop-scope))
7863
7864 (defsubst js2-enter-switch (switch-node)
7865 (push switch-node js2-loop-and-switch-set))
7866
7867 (defsubst js2-exit-switch ()
7868 (pop js2-loop-and-switch-set))
7869
7870 (defsubst js2-get-directive (node)
7871 "Return NODE's value if it is a directive, nil otherwise.
7872
7873 A directive is an otherwise-meaningless expression statement
7874 consisting of a string literal, such as \"use strict\"."
7875 (and (js2-expr-stmt-node-p node)
7876 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7877 (js2-string-node-value node)))
7878
7879 (defun js2-parse (&optional buf cb)
7880 "Tell the js2 parser to parse a region of JavaScript.
7881
7882 BUF is a buffer or buffer name containing the code to parse.
7883 Call `narrow-to-region' first to parse only part of the buffer.
7884
7885 The returned AST root node is given some additional properties:
7886 `node-count' - total number of nodes in the AST
7887 `buffer' - BUF. The buffer it refers to may change or be killed,
7888 so the value is not necessarily reliable.
7889
7890 An optional callback CB can be specified to report parsing
7891 progress. If `(functionp CB)' returns t, it will be called with
7892 the current line number once before parsing begins, then again
7893 each time the lexer reaches a new line number.
7894
7895 CB can also be a list of the form `(symbol cb ...)' to specify
7896 multiple callbacks with different criteria. Each symbol is a
7897 criterion keyword, and the following element is the callback to
7898 call
7899
7900 :line - called whenever the line number changes
7901 :token - called for each new token consumed
7902
7903 The list of criteria could be extended to include entering or
7904 leaving a statement, an expression, or a function definition."
7905 (if (and cb (not (functionp cb)))
7906 (error "criteria callbacks not yet implemented"))
7907 (let ((inhibit-point-motion-hooks t)
7908 (js2-compiler-xml-available (>= js2-language-version 160))
7909 ;; This is a recursive-descent parser, so give it a big stack.
7910 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7911 (max-specpdl-size (max max-specpdl-size 3000))
7912 (case-fold-search nil)
7913 ast)
7914 (with-current-buffer (or buf (current-buffer))
7915 (setq js2-scanned-comments nil
7916 js2-parsed-errors nil
7917 js2-parsed-warnings nil
7918 js2-imenu-recorder nil
7919 js2-imenu-function-map nil
7920 js2-label-set nil)
7921 (js2-init-scanner)
7922 (setq ast (js2-do-parse))
7923 (unless js2-ts-hit-eof
7924 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7925 (setf (js2-ast-root-errors ast) js2-parsed-errors
7926 (js2-ast-root-warnings ast) js2-parsed-warnings)
7927 ;; if we didn't find any declarations, put a dummy in this list so we
7928 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7929 (unless js2-imenu-recorder
7930 (setq js2-imenu-recorder 'empty))
7931 (run-hooks 'js2-parse-finished-hook)
7932 ast)))
7933
7934 ;; Corresponds to Rhino's Parser.parse() method.
7935 (defun js2-do-parse ()
7936 "Parse current buffer starting from current point.
7937 Scanner should be initialized."
7938 (let ((pos js2-ts-cursor)
7939 (end js2-ts-cursor) ; in case file is empty
7940 root n tt
7941 (in-directive-prologue t)
7942 (js2-in-use-strict-directive js2-in-use-strict-directive)
7943 directive)
7944 ;; initialize buffer-local parsing vars
7945 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7946 js2-current-script-or-fn root
7947 js2-current-scope root
7948 js2-nesting-of-function 0
7949 js2-labeled-stmt nil
7950 js2-recorded-identifiers nil ; for js2-highlight
7951 js2-in-use-strict-directive nil)
7952 (while (/= (setq tt (js2-get-token)) js2-EOF)
7953 (if (= tt js2-FUNCTION)
7954 (progn
7955 (setq n (if js2-called-by-compile-function
7956 (js2-parse-function-expr)
7957 (js2-parse-function-stmt))))
7958 ;; not a function - parse a statement
7959 (js2-unget-token)
7960 (setq n (js2-parse-statement))
7961 (when in-directive-prologue
7962 (setq directive (js2-get-directive n))
7963 (cond
7964 ((null directive)
7965 (setq in-directive-prologue nil))
7966 ((string= directive "use strict")
7967 (setq js2-in-use-strict-directive t)))))
7968 ;; add function or statement to script
7969 (setq end (js2-node-end n))
7970 (js2-block-node-push root n))
7971 ;; add comments to root in lexical order
7972 (when js2-scanned-comments
7973 ;; if we find a comment beyond end of normal kids, use its end
7974 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7975 (dolist (comment js2-scanned-comments)
7976 (push comment (js2-ast-root-comments root))
7977 (js2-node-add-children root comment)))
7978 (setf (js2-node-len root) (- end pos))
7979 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7980 ;; Give extensions a chance to muck with things before highlighting starts.
7981 (let ((js2-additional-externs js2-additional-externs))
7982 (save-excursion
7983 (run-hooks 'js2-post-parse-callbacks))
7984 (js2-highlight-undeclared-vars))
7985 root))
7986
7987 (defun js2-parse-function-closure-body (fn-node)
7988 "Parse a JavaScript 1.8 function closure body."
7989 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7990 (if js2-ts-hit-eof
7991 (js2-report-error "msg.no.brace.body" nil
7992 (js2-node-pos fn-node)
7993 (- js2-ts-cursor (js2-node-pos fn-node)))
7994 (js2-node-add-children fn-node
7995 (setf (js2-function-node-body fn-node)
7996 (js2-parse-expr t))))))
7997
7998 (defun js2-parse-function-body (fn-node)
7999 (js2-must-match js2-LC "msg.no.brace.body"
8000 (js2-node-pos fn-node)
8001 (- js2-ts-cursor (js2-node-pos fn-node)))
8002 (let ((pos (js2-current-token-beg)) ; LC position
8003 (pn (make-js2-block-node)) ; starts at LC position
8004 tt
8005 end
8006 not-in-directive-prologue
8007 node
8008 directive)
8009 (cl-incf js2-nesting-of-function)
8010 (unwind-protect
8011 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8012 (= tt js2-EOF)
8013 (= tt js2-RC)))
8014 (js2-block-node-push
8015 pn
8016 (if (/= tt js2-FUNCTION)
8017 (if not-in-directive-prologue
8018 (js2-parse-statement)
8019 (setq node (js2-parse-statement)
8020 directive (js2-get-directive node))
8021 (cond
8022 ((null directive)
8023 (setq not-in-directive-prologue t))
8024 ((string= directive "use strict")
8025 ;; Back up and reparse the function, because new rules apply
8026 ;; to the function name and parameters.
8027 (when (not js2-in-use-strict-directive)
8028 (setq js2-in-use-strict-directive t)
8029 (throw 'reparse t))))
8030 node)
8031 (js2-get-token)
8032 (js2-parse-function-stmt))))
8033 (cl-decf js2-nesting-of-function))
8034 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8035 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8036 (setq end (js2-current-token-end)))
8037 (setf (js2-node-pos pn) pos
8038 (js2-node-len pn) (- end pos))
8039 (setf (js2-function-node-body fn-node) pn)
8040 (js2-node-add-children fn-node pn)
8041 pn))
8042
8043 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8044 "Declare and fontify destructuring parameters inside NODE.
8045 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8046
8047 Return a list of `js2-name-node' nodes representing the symbols
8048 declared; probably to check them for errors."
8049 (let (name-nodes)
8050 (cond
8051 ((js2-name-node-p node)
8052 (let (leftpos)
8053 (js2-define-symbol decl-type (js2-name-node-name node)
8054 node ignore-not-in-block)
8055 (when face
8056 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8057 (+ leftpos (js2-node-len node))
8058 face 'record))
8059 (list node)))
8060 ((js2-object-node-p node)
8061 (dolist (elem (js2-object-node-elems node))
8062 ;; js2-infix-node-p catches both object prop node and initialized
8063 ;; binding element (which is directly an infix node).
8064 (when (js2-infix-node-p elem)
8065 (push (js2-define-destruct-symbols
8066 (js2-infix-node-left elem)
8067 decl-type face ignore-not-in-block)
8068 name-nodes)))
8069 (apply #'append (nreverse name-nodes)))
8070 ((js2-array-node-p node)
8071 (dolist (elem (js2-array-node-elems node))
8072 (when elem
8073 (if (js2-infix-node-p elem) (setq elem (js2-infix-node-left elem)))
8074 (push (js2-define-destruct-symbols
8075 elem decl-type face ignore-not-in-block)
8076 name-nodes)))
8077 (apply #'append (nreverse name-nodes)))
8078 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8079 (js2-node-len node))
8080 nil))))
8081
8082 (defvar js2-illegal-strict-identifiers
8083 '("eval" "arguments")
8084 "Identifiers not allowed as variables in strict mode.")
8085
8086 (defun js2-check-strict-identifier (name-node)
8087 "Check that NAME-NODE makes a legal strict mode identifier."
8088 (when js2-in-use-strict-directive
8089 (let ((param-name (js2-name-node-name name-node)))
8090 (when (member param-name js2-illegal-strict-identifiers)
8091 (js2-report-error "msg.bad.id.strict" param-name
8092 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8093
8094 (defun js2-check-strict-function-params (preceding-params params)
8095 "Given PRECEDING-PARAMS in a function's parameter list, check
8096 for strict mode errors caused by PARAMS."
8097 (when js2-in-use-strict-directive
8098 (dolist (param params)
8099 (let ((param-name (js2-name-node-name param)))
8100 (js2-check-strict-identifier param)
8101 (when (cl-some (lambda (param)
8102 (string= (js2-name-node-name param) param-name))
8103 preceding-params)
8104 (js2-report-error "msg.dup.param.strict" param-name
8105 (js2-node-abs-pos param) (js2-node-len param)))))))
8106
8107 (defun js2-parse-function-params (function-type fn-node pos)
8108 "Parse the parameters of a function of FUNCTION-TYPE
8109 represented by FN-NODE at POS."
8110 (if (js2-match-token js2-RP)
8111 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8112 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8113 (eq (js2-current-token-type) js2-NAME)))
8114 params param
8115 param-name-nodes new-param-name-nodes
8116 rest-param-at)
8117 (when paren-free-arrow
8118 (js2-unget-token))
8119 (cl-loop for tt = (js2-peek-token)
8120 do
8121 (cond
8122 ;; destructuring param
8123 ((and (not paren-free-arrow)
8124 (or (= tt js2-LB) (= tt js2-LC)))
8125 (js2-get-token)
8126 (setq param (js2-parse-destruct-primary-expr)
8127 new-param-name-nodes (js2-define-destruct-symbols
8128 param js2-LP 'js2-function-param))
8129 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8130 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8131 (push param params))
8132 ;; variable name
8133 (t
8134 (when (and (>= js2-language-version 200)
8135 (not paren-free-arrow)
8136 (js2-match-token js2-TRIPLEDOT)
8137 (not rest-param-at))
8138 ;; to report errors if there are more parameters
8139 (setq rest-param-at (length params)))
8140 (js2-must-match-name "msg.no.parm")
8141 (js2-record-face 'js2-function-param)
8142 (setq param (js2-create-name-node))
8143 (js2-define-symbol js2-LP (js2-current-token-string) param)
8144 (js2-check-strict-function-params param-name-nodes (list param))
8145 (setq param-name-nodes (append param-name-nodes (list param)))
8146 ;; default parameter value
8147 (when (and (>= js2-language-version 200)
8148 (js2-match-token js2-ASSIGN))
8149 (cl-assert (not paren-free-arrow))
8150 (let* ((pos (js2-node-pos param))
8151 (tt (js2-current-token-type))
8152 (op-pos (- (js2-current-token-beg) pos))
8153 (left param)
8154 (right (js2-parse-assign-expr))
8155 (len (- (js2-node-end right) pos)))
8156 (setq param (make-js2-assign-node
8157 :type tt :pos pos :len len :op-pos op-pos
8158 :left left :right right))
8159 (js2-node-add-children param left right)))
8160 (push param params)))
8161 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8162 (js2-report-error "msg.param.after.rest" nil
8163 (js2-node-pos param) (js2-node-len param)))
8164 while
8165 (js2-match-token js2-COMMA))
8166 (when (and (not paren-free-arrow)
8167 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8168 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8169 (when rest-param-at
8170 (setf (js2-function-node-rest-p fn-node) t))
8171 (dolist (p params)
8172 (js2-node-add-children fn-node p)
8173 (push p (js2-function-node-params fn-node))))))
8174
8175 (defun js2-check-inconsistent-return-warning (fn-node name)
8176 "Possibly show inconsistent-return warning.
8177 Last token scanned is the close-curly for the function body."
8178 (when (and js2-mode-show-strict-warnings
8179 js2-strict-inconsistent-return-warning
8180 (not (js2-has-consistent-return-usage
8181 (js2-function-node-body fn-node))))
8182 ;; Have it extend from close-curly to bol or beginning of block.
8183 (let ((pos (save-excursion
8184 (goto-char (js2-current-token-end))
8185 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8186 (point-at-bol))))
8187 (end (js2-current-token-end)))
8188 (if (cl-plusp (js2-name-node-length name))
8189 (js2-add-strict-warning "msg.no.return.value"
8190 (js2-name-node-name name) pos end)
8191 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8192
8193 (defun js2-parse-function-stmt (&optional async-p)
8194 (let ((pos (js2-current-token-beg))
8195 (star-p (js2-match-token js2-MUL)))
8196 (js2-must-match-name "msg.unnamed.function.stmt")
8197 (let ((name (js2-create-name-node t))
8198 pn member-expr)
8199 (cond
8200 ((js2-match-token js2-LP)
8201 (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p name))
8202 (js2-allow-member-expr-as-function-name
8203 (setq member-expr (js2-parse-member-expr-tail nil name))
8204 (js2-parse-highlight-member-expr-fn-name member-expr)
8205 (js2-must-match js2-LP "msg.no.paren.parms")
8206 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p)
8207 (js2-function-node-member-expr pn) member-expr)
8208 pn)
8209 (t
8210 (js2-report-error "msg.no.paren.parms")
8211 (make-js2-error-node))))))
8212
8213 (defun js2-parse-async-function-stmt ()
8214 (js2-parse-function-stmt t))
8215
8216 (defun js2-parse-function-expr (&optional async-p)
8217 (let ((pos (js2-current-token-beg))
8218 (star-p (js2-match-token js2-MUL))
8219 name)
8220 (when (js2-match-token js2-NAME)
8221 (setq name (js2-create-name-node t)))
8222 (js2-must-match js2-LP "msg.no.paren.parms")
8223 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p async-p name)))
8224
8225 (defun js2-parse-function-internal (function-type pos star-p &optional async-p name)
8226 (let (fn-node lp)
8227 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8228 (setq lp (js2-current-token-beg)))
8229 (setf fn-node (make-js2-function-node :pos pos
8230 :name name
8231 :form function-type
8232 :lp (if lp (- lp pos))
8233 :generator-type (and star-p 'STAR)
8234 :async async-p))
8235 (when name
8236 (js2-set-face (js2-node-pos name) (js2-node-end name)
8237 'font-lock-function-name-face 'record)
8238 (when (and (eq function-type 'FUNCTION_STATEMENT)
8239 (cl-plusp (js2-name-node-length name)))
8240 ;; Function statements define a symbol in the enclosing scope
8241 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8242 (when js2-in-use-strict-directive
8243 (js2-check-strict-identifier name)))
8244 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8245 ;; 1. Nested functions are not affected by the dynamic scope flag
8246 ;; as dynamic scope is already a parent of their scope.
8247 ;; 2. Functions defined under the with statement also immune to
8248 ;; this setup, in which case dynamic scope is ignored in favor
8249 ;; of the with object.
8250 (setf (js2-function-node-ignore-dynamic fn-node) t))
8251 ;; dynamically bind all the per-function variables
8252 (let ((js2-current-script-or-fn fn-node)
8253 (js2-current-scope fn-node)
8254 (js2-nesting-of-with 0)
8255 (js2-end-flags 0)
8256 js2-label-set
8257 js2-loop-set
8258 js2-loop-and-switch-set)
8259 (js2-parse-function-params function-type fn-node pos)
8260 (when (eq function-type 'FUNCTION_ARROW)
8261 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8262 (if (and (>= js2-language-version 180)
8263 (/= (js2-peek-token) js2-LC))
8264 (js2-parse-function-closure-body fn-node)
8265 (js2-parse-function-body fn-node))
8266 (js2-check-inconsistent-return-warning fn-node name)
8267
8268 (when name
8269 (js2-node-add-children fn-node name)
8270 ;; Function expressions define a name only in the body of the
8271 ;; function, and only if not hidden by a parameter name
8272 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8273 (null (js2-scope-get-symbol js2-current-scope
8274 (js2-name-node-name name))))
8275 (js2-define-symbol js2-FUNCTION
8276 (js2-name-node-name name)
8277 fn-node))
8278 (when (eq function-type 'FUNCTION_STATEMENT)
8279 (js2-record-imenu-functions fn-node))))
8280
8281 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8282 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8283 ;; We wait until after parsing the function to set its parent scope,
8284 ;; since `js2-define-symbol' needs the defining-scope check to stop
8285 ;; at the function boundary when checking for redeclarations.
8286 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8287 fn-node))
8288
8289 (defun js2-parse-function (function-type pos star-p &optional async-p name)
8290 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8291 beginning of the first token (function keyword, unless it's an
8292 arrow function), NAME is js2-name-node."
8293 (let ((continue t)
8294 ts-state
8295 fn-node
8296 ;; Preserve strict state outside this function.
8297 (js2-in-use-strict-directive js2-in-use-strict-directive))
8298 ;; Parse multiple times if a new strict mode directive is discovered in the
8299 ;; function body, as new rules will be retroactively applied to the legality
8300 ;; of function names and parameters.
8301 (while continue
8302 (setq ts-state (make-js2-ts-state))
8303 (setq continue (catch 'reparse
8304 (setq fn-node (js2-parse-function-internal
8305 function-type pos star-p async-p name))
8306 ;; Don't continue.
8307 nil))
8308 (when continue
8309 (js2-ts-seek ts-state)))
8310 fn-node))
8311
8312 (defun js2-parse-statements (&optional parent)
8313 "Parse a statement list. Last token consumed must be js2-LC.
8314
8315 PARENT can be a `js2-block-node', in which case the statements are
8316 appended to PARENT. Otherwise a new `js2-block-node' is created
8317 and returned.
8318
8319 This function does not match the closing js2-RC: the caller
8320 matches the RC so it can provide a suitable error message if not
8321 matched. This means it's up to the caller to set the length of
8322 the node to include the closing RC. The node start pos is set to
8323 the absolute buffer start position, and the caller should fix it
8324 up to be relative to the parent node. All children of this block
8325 node are given relative start positions and correct lengths."
8326 (let ((pn (or parent (make-js2-block-node)))
8327 tt)
8328 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8329 (/= tt js2-RC))
8330 (js2-block-node-push pn (js2-parse-statement)))
8331 pn))
8332
8333 (defun js2-parse-statement ()
8334 (let (pn beg end)
8335 ;; coarse-grained user-interrupt check - needs work
8336 (and js2-parse-interruptable-p
8337 (zerop (% (cl-incf js2-parse-stmt-count)
8338 js2-statements-per-pause))
8339 (input-pending-p)
8340 (throw 'interrupted t))
8341 (setq pn (js2-statement-helper))
8342 ;; no-side-effects warning check
8343 (unless (js2-node-has-side-effects pn)
8344 (setq end (js2-node-end pn))
8345 (save-excursion
8346 (goto-char end)
8347 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8348 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8349 pn))
8350
8351 ;; These correspond to the switch cases in Parser.statementHelper
8352 (defconst js2-parsers
8353 (let ((parsers (make-vector js2-num-tokens
8354 #'js2-parse-expr-stmt)))
8355 (aset parsers js2-BREAK #'js2-parse-break)
8356 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8357 (aset parsers js2-CONST #'js2-parse-const-var)
8358 (aset parsers js2-CONTINUE #'js2-parse-continue)
8359 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8360 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8361 (aset parsers js2-DO #'js2-parse-do)
8362 (aset parsers js2-EXPORT #'js2-parse-export)
8363 (aset parsers js2-FOR #'js2-parse-for)
8364 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8365 (aset parsers js2-IF #'js2-parse-if)
8366 (aset parsers js2-IMPORT #'js2-parse-import)
8367 (aset parsers js2-LC #'js2-parse-block)
8368 (aset parsers js2-LET #'js2-parse-let-stmt)
8369 (aset parsers js2-NAME #'js2-parse-name-or-label)
8370 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8371 (aset parsers js2-SEMI #'js2-parse-semi)
8372 (aset parsers js2-SWITCH #'js2-parse-switch)
8373 (aset parsers js2-THROW #'js2-parse-throw)
8374 (aset parsers js2-TRY #'js2-parse-try)
8375 (aset parsers js2-VAR #'js2-parse-const-var)
8376 (aset parsers js2-WHILE #'js2-parse-while)
8377 (aset parsers js2-WITH #'js2-parse-with)
8378 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8379 parsers)
8380 "A vector mapping token types to parser functions.")
8381
8382 (defun js2-parse-warn-missing-semi (beg end)
8383 (and js2-mode-show-strict-warnings
8384 js2-strict-missing-semi-warning
8385 (js2-add-strict-warning
8386 "msg.missing.semi" nil
8387 ;; back up to beginning of statement or line
8388 (max beg (save-excursion
8389 (goto-char end)
8390 (point-at-bol)))
8391 end)))
8392
8393 (defconst js2-no-semi-insertion
8394 (list js2-IF
8395 js2-SWITCH
8396 js2-WHILE
8397 js2-DO
8398 js2-FOR
8399 js2-TRY
8400 js2-WITH
8401 js2-LC
8402 js2-ERROR
8403 js2-SEMI
8404 js2-CLASS
8405 js2-FUNCTION
8406 js2-EXPORT)
8407 "List of tokens that don't do automatic semicolon insertion.")
8408
8409 (defconst js2-autoinsert-semi-and-warn
8410 (list js2-ERROR js2-EOF js2-RC))
8411
8412 (defun js2-statement-helper ()
8413 (let* ((tt (js2-get-token))
8414 (first-tt tt)
8415 (async-stmt (js2-match-async-function))
8416 (parser (if (= tt js2-ERROR)
8417 #'js2-parse-semi
8418 (if async-stmt
8419 #'js2-parse-async-function-stmt
8420 (aref js2-parsers tt))))
8421 pn)
8422 ;; If the statement is set, then it's been told its label by now.
8423 (and js2-labeled-stmt
8424 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8425 (setq js2-labeled-stmt nil))
8426 (setq pn (funcall parser))
8427 ;; Don't do auto semi insertion for certain statement types.
8428 (unless (or (memq first-tt js2-no-semi-insertion)
8429 (js2-labeled-stmt-node-p pn)
8430 async-stmt)
8431 (js2-auto-insert-semicolon pn))
8432 pn))
8433
8434 (defun js2-auto-insert-semicolon (pn)
8435 (let* ((tt (js2-get-token))
8436 (pos (js2-node-pos pn)))
8437 (cond
8438 ((= tt js2-SEMI)
8439 ;; extend the node bounds to include the semicolon.
8440 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8441 ((memq tt js2-autoinsert-semi-and-warn)
8442 (js2-unget-token) ; Not ';', do not consume.
8443 ;; Autoinsert ;
8444 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8445 (t
8446 (if (not (js2-token-follows-eol-p (js2-current-token)))
8447 ;; Report error if no EOL or autoinsert ';' otherwise
8448 (js2-report-error "msg.no.semi.stmt")
8449 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8450 (js2-unget-token) ; Not ';', do not consume.
8451 ))))
8452
8453 (defun js2-parse-condition ()
8454 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8455 The parens are discarded and the expression node is returned.
8456 The `pos' field of the return value is set to an absolute position
8457 that must be fixed up by the caller.
8458 Return value is a list (EXPR LP RP), with absolute paren positions."
8459 (let (pn lp rp)
8460 (if (js2-must-match js2-LP "msg.no.paren.cond")
8461 (setq lp (js2-current-token-beg)))
8462 (setq pn (js2-parse-expr))
8463 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8464 (setq rp (js2-current-token-beg)))
8465 ;; Report strict warning on code like "if (a = 7) ..."
8466 (if (and js2-strict-cond-assign-warning
8467 (js2-assign-node-p pn))
8468 (js2-add-strict-warning "msg.equal.as.assign" nil
8469 (js2-node-pos pn)
8470 (+ (js2-node-pos pn)
8471 (js2-node-len pn))))
8472 (list pn lp rp)))
8473
8474 (defun js2-parse-if ()
8475 "Parser for if-statement. Last matched token must be js2-IF."
8476 (let ((pos (js2-current-token-beg))
8477 cond if-true if-false else-pos end pn)
8478 (setq cond (js2-parse-condition)
8479 if-true (js2-parse-statement)
8480 if-false (if (js2-match-token js2-ELSE)
8481 (progn
8482 (setq else-pos (- (js2-current-token-beg) pos))
8483 (js2-parse-statement)))
8484 end (js2-node-end (or if-false if-true))
8485 pn (make-js2-if-node :pos pos
8486 :len (- end pos)
8487 :condition (car cond)
8488 :then-part if-true
8489 :else-part if-false
8490 :else-pos else-pos
8491 :lp (js2-relpos (cl-second cond) pos)
8492 :rp (js2-relpos (cl-third cond) pos)))
8493 (js2-node-add-children pn (car cond) if-true if-false)
8494 pn))
8495
8496 (defun js2-parse-import ()
8497 "Parse import statement. The current token must be js2-IMPORT."
8498 (unless (js2-ast-root-p js2-current-scope)
8499 (js2-report-error "msg.mod.import.decl.at.top.level"))
8500 (let ((beg (js2-current-token-beg)))
8501 (cond ((js2-match-token js2-STRING)
8502 (make-js2-import-node
8503 :pos beg
8504 :len (- (js2-current-token-end) beg)
8505 :module-id (js2-current-token-string)))
8506 (t
8507 (let* ((import-clause (js2-parse-import-clause))
8508 (from-clause (and import-clause (js2-parse-from-clause)))
8509 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8510 (node (make-js2-import-node
8511 :pos beg
8512 :len (- (js2-current-token-end) beg)
8513 :import import-clause
8514 :from from-clause
8515 :module-id module-id)))
8516 (when import-clause
8517 (js2-node-add-children node import-clause))
8518 (when from-clause
8519 (js2-node-add-children node from-clause))
8520 node)))))
8521
8522 (defun js2-parse-import-clause ()
8523 "Parse the bindings in an import statement.
8524 This can take many forms:
8525
8526 ImportedDefaultBinding -> 'foo'
8527 NameSpaceImport -> '* as lib'
8528 NamedImports -> '{foo as bar, bang}'
8529 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8530 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8531
8532 Try to match namespace imports and named imports first because nothing can
8533 come after them. If it is an imported default binding, then it could have named
8534 imports or a namespace import that follows it.
8535 "
8536 (let* ((beg (js2-current-token-beg))
8537 (clause (make-js2-import-clause-node
8538 :pos beg))
8539 (children (list)))
8540 (cond
8541 ((js2-match-token js2-MUL)
8542 (let ((ns-import (js2-parse-namespace-import)))
8543 (when ns-import
8544 (let ((name-node (js2-namespace-import-node-name ns-import)))
8545 (js2-define-symbol
8546 js2-LET (js2-name-node-name name-node) name-node t)))
8547 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8548 (push ns-import children)))
8549 ((js2-match-token js2-LC)
8550 (let ((imports (js2-parse-export-bindings t)))
8551 (setf (js2-import-clause-node-named-imports clause) imports)
8552 (dolist (import imports)
8553 (push import children)
8554 (let ((name-node (js2-export-binding-node-local-name import)))
8555 (when name-node
8556 (js2-define-symbol
8557 js2-LET (js2-name-node-name name-node) name-node t))))))
8558 ((= (js2-peek-token) js2-NAME)
8559 (let ((binding (js2-maybe-parse-export-binding)))
8560 (let ((node-name (js2-export-binding-node-local-name binding)))
8561 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8562 (setf (js2-import-clause-node-default-binding clause) binding)
8563 (push binding children))
8564 (when (js2-match-token js2-COMMA)
8565 (cond
8566 ((js2-match-token js2-MUL)
8567 (let ((ns-import (js2-parse-namespace-import)))
8568 (let ((name-node (js2-namespace-import-node-name ns-import)))
8569 (js2-define-symbol
8570 js2-LET (js2-name-node-name name-node) name-node t))
8571 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8572 (push ns-import children)))
8573 ((js2-match-token js2-LC)
8574 (let ((imports (js2-parse-export-bindings t)))
8575 (setf (js2-import-clause-node-named-imports clause) imports)
8576 (dolist (import imports)
8577 (push import children)
8578 (let ((name-node (js2-export-binding-node-local-name import)))
8579 (when name-node
8580 (js2-define-symbol
8581 js2-LET (js2-name-node-name name-node) name-node t))))))
8582 (t (js2-report-error "msg.syntax")))))
8583 (t (js2-report-error "msg.mod.declaration.after.import")))
8584 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8585 (apply #'js2-node-add-children clause children)
8586 clause))
8587
8588 (defun js2-parse-namespace-import ()
8589 "Parse a namespace import expression such as '* as bar'.
8590 The current token must be js2-MUL."
8591 (let ((beg (js2-current-token-beg)))
8592 (when (js2-must-match js2-NAME "msg.syntax")
8593 (if (equal "as" (js2-current-token-string))
8594 (when (js2-must-match-prop-name "msg.syntax")
8595 (let ((node (make-js2-namespace-import-node
8596 :pos beg
8597 :len (- (js2-current-token-end) beg)
8598 :name (make-js2-name-node
8599 :pos (js2-current-token-beg)
8600 :len (js2-current-token-end)
8601 :name (js2-current-token-string)))))
8602 (js2-node-add-children node (js2-namespace-import-node-name node))
8603 node))
8604 (js2-unget-token)
8605 (js2-report-error "msg.syntax")))))
8606
8607
8608 (defun js2-parse-from-clause ()
8609 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8610 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8611 (let ((beg (js2-current-token-beg)))
8612 (if (equal "from" (js2-current-token-string))
8613 (cond
8614 ((js2-match-token js2-STRING)
8615 (make-js2-from-clause-node
8616 :pos beg
8617 :len (- (js2-current-token-end) beg)
8618 :module-id (js2-current-token-string)
8619 :metadata-p nil))
8620 ((js2-match-token js2-THIS)
8621 (when (js2-must-match-name "msg.mod.spec.after.from")
8622 (if (equal "module" (js2-current-token-string))
8623 (make-js2-from-clause-node
8624 :pos beg
8625 :len (- (js2-current-token-end) beg)
8626 :module-id "this"
8627 :metadata-p t)
8628 (js2-unget-token)
8629 (js2-unget-token)
8630 (js2-report-error "msg.mod.spec.after.from")
8631 nil)))
8632 (t (js2-report-error "msg.mod.spec.after.from") nil))
8633 (js2-unget-token)
8634 (js2-report-error "msg.mod.from.after.import.spec.set")
8635 nil))))
8636
8637 (defun js2-parse-export-bindings (&optional import-p)
8638 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8639 {foo as bar, baz as bang}. The current token must be
8640 js2-LC. Return a lisp list of js2-export-binding-node"
8641 (let ((bindings (list)))
8642 (while
8643 (let ((binding (js2-maybe-parse-export-binding)))
8644 (when binding
8645 (push binding bindings))
8646 (js2-match-token js2-COMMA)))
8647 (when (js2-must-match js2-RC (if import-p
8648 "msg.mod.rc.after.import.spec.list"
8649 "msg.mod.rc.after.export.spec.list"))
8650 (reverse bindings))))
8651
8652 (defun js2-maybe-parse-export-binding ()
8653 "Attempt to parse a binding expression found inside an import/export statement.
8654 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8655 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8656 js2-export-binding-node and consume all the tokens. If it does not match, it
8657 consumes no tokens."
8658 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8659 (beg (js2-current-token-beg))
8660 (extern-name-len (js2-current-token-len))
8661 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8662 (aref js2-kwd-tokens (js2-current-token-type)))))
8663 (if extern-name
8664 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8665 (if (and as (equal "as" (js2-current-token-string)))
8666 (let ((name
8667 (or
8668 (and (js2-match-token js2-DEFAULT) "default")
8669 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8670 (if name
8671 (let ((node (make-js2-export-binding-node
8672 :pos beg
8673 :len (- (js2-current-token-end) beg)
8674 :local-name (make-js2-name-node
8675 :name name
8676 :pos (js2-current-token-beg)
8677 :len (js2-current-token-len))
8678 :extern-name (make-js2-name-node
8679 :name extern-name
8680 :pos beg
8681 :len extern-name-len))))
8682 (js2-node-add-children
8683 node
8684 (js2-export-binding-node-local-name node)
8685 (js2-export-binding-node-extern-name node))
8686 node)
8687 (js2-unget-token)
8688 nil))
8689 (when as (js2-unget-token))
8690 (let* ((name-node (make-js2-name-node
8691 :name (js2-current-token-string)
8692 :pos (js2-current-token-beg)
8693 :len (js2-current-token-len)))
8694 (node (make-js2-export-binding-node
8695 :pos (js2-current-token-beg)
8696 :len (js2-current-token-len)
8697 :local-name name-node
8698 :extern-name name-node)))
8699 (when is-reserved-name
8700 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8701 (js2-node-add-children node name-node)
8702 node)))
8703 nil)))
8704
8705 (defun js2-parse-switch ()
8706 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8707 (let ((pos (js2-current-token-beg))
8708 tt pn discriminant has-default case-expr case-node
8709 case-pos cases stmt lp)
8710 (if (js2-must-match js2-LP "msg.no.paren.switch")
8711 (setq lp (js2-current-token-beg)))
8712 (setq discriminant (js2-parse-expr)
8713 pn (make-js2-switch-node :discriminant discriminant
8714 :pos pos
8715 :lp (js2-relpos lp pos)))
8716 (js2-node-add-children pn discriminant)
8717 (js2-enter-switch pn)
8718 (unwind-protect
8719 (progn
8720 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8721 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8722 (js2-must-match js2-LC "msg.no.brace.switch")
8723 (catch 'break
8724 (while t
8725 (setq tt (js2-next-token)
8726 case-pos (js2-current-token-beg))
8727 (cond
8728 ((= tt js2-RC)
8729 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8730 (throw 'break nil)) ; done
8731 ((= tt js2-CASE)
8732 (setq case-expr (js2-parse-expr))
8733 (js2-must-match js2-COLON "msg.no.colon.case"))
8734 ((= tt js2-DEFAULT)
8735 (if has-default
8736 (js2-report-error "msg.double.switch.default"))
8737 (setq has-default t
8738 case-expr nil)
8739 (js2-must-match js2-COLON "msg.no.colon.case"))
8740 (t
8741 (js2-report-error "msg.bad.switch")
8742 (throw 'break nil)))
8743 (setq case-node (make-js2-case-node :pos case-pos
8744 :len (- (js2-current-token-end) case-pos)
8745 :expr case-expr))
8746 (js2-node-add-children case-node case-expr)
8747 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8748 (/= tt js2-CASE)
8749 (/= tt js2-DEFAULT)
8750 (/= tt js2-EOF))
8751 (setf stmt (js2-parse-statement)
8752 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8753 (js2-block-node-push case-node stmt))
8754 (push case-node cases)))
8755 ;; add cases last, as pushing reverses the order to be correct
8756 (dolist (kid cases)
8757 (js2-node-add-children pn kid)
8758 (push kid (js2-switch-node-cases pn)))
8759 pn) ; return value
8760 (js2-exit-switch))))
8761
8762 (defun js2-parse-while ()
8763 "Parser for while-statement. Last matched token must be js2-WHILE."
8764 (let ((pos (js2-current-token-beg))
8765 (pn (make-js2-while-node))
8766 cond body)
8767 (js2-enter-loop pn)
8768 (unwind-protect
8769 (progn
8770 (setf cond (js2-parse-condition)
8771 (js2-while-node-condition pn) (car cond)
8772 body (js2-parse-statement)
8773 (js2-while-node-body pn) body
8774 (js2-node-len pn) (- (js2-node-end body) pos)
8775 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8776 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8777 (js2-node-add-children pn body (car cond)))
8778 (js2-exit-loop))
8779 pn))
8780
8781 (defun js2-parse-do ()
8782 "Parser for do-statement. Last matched token must be js2-DO."
8783 (let ((pos (js2-current-token-beg))
8784 (pn (make-js2-do-node))
8785 cond body end)
8786 (js2-enter-loop pn)
8787 (unwind-protect
8788 (progn
8789 (setq body (js2-parse-statement))
8790 (js2-must-match js2-WHILE "msg.no.while.do")
8791 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8792 cond (js2-parse-condition)
8793 (js2-do-node-condition pn) (car cond)
8794 (js2-do-node-body pn) body
8795 end js2-ts-cursor
8796 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8797 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8798 (js2-node-add-children pn (car cond) body))
8799 (js2-exit-loop))
8800 ;; Always auto-insert semicolon to follow SpiderMonkey:
8801 ;; It is required by ECMAScript but is ignored by the rest of
8802 ;; world; see bug 238945
8803 (if (js2-match-token js2-SEMI)
8804 (setq end js2-ts-cursor))
8805 (setf (js2-node-len pn) (- end pos))
8806 pn))
8807
8808 (defun js2-parse-export ()
8809 "Parse an export statement.
8810 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8811 expressions should only be either hoistable expressions (function or generator)
8812 or assignment expressions, but there is no checking to enforce that and so it
8813 will parse without error a small subset of
8814 invalid export statements."
8815 (unless (js2-ast-root-p js2-current-scope)
8816 (js2-report-error "msg.mod.export.decl.at.top.level"))
8817 (let ((beg (js2-current-token-beg))
8818 (children (list))
8819 exports-list from-clause declaration default)
8820 (cond
8821 ((js2-match-token js2-MUL)
8822 (setq from-clause (js2-parse-from-clause))
8823 (when from-clause
8824 (push from-clause children)))
8825 ((js2-match-token js2-LC)
8826 (setq exports-list (js2-parse-export-bindings))
8827 (when exports-list
8828 (dolist (export exports-list)
8829 (push export children)))
8830 (when (js2-match-token js2-NAME)
8831 (if (equal "from" (js2-current-token-string))
8832 (progn
8833 (js2-unget-token)
8834 (setq from-clause (js2-parse-from-clause)))
8835 (js2-unget-token))))
8836 ((js2-match-token js2-DEFAULT)
8837 (setq default (js2-parse-expr)))
8838 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8839 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8840 (t
8841 (setq declaration (js2-parse-expr))))
8842 (when from-clause
8843 (push from-clause children))
8844 (when declaration
8845 (push declaration children)
8846 (when (not (js2-function-node-p declaration))
8847 (js2-auto-insert-semicolon declaration)))
8848 (when default
8849 (push default children)
8850 (when (not (js2-function-node-p default))
8851 (js2-auto-insert-semicolon default)))
8852 (let ((node (make-js2-export-node
8853 :pos beg
8854 :len (- (js2-current-token-end) beg)
8855 :exports-list exports-list
8856 :from-clause from-clause
8857 :declaration declaration
8858 :default default)))
8859 (apply #'js2-node-add-children node children)
8860 node)))
8861
8862 (defun js2-parse-for ()
8863 "Parse a for, for-in or for each-in statement.
8864 Last matched token must be js2-FOR."
8865 (let ((for-pos (js2-current-token-beg))
8866 (tmp-scope (make-js2-scope))
8867 pn is-for-each is-for-in-or-of is-for-of
8868 in-pos each-pos tmp-pos
8869 init ; Node init is also foo in 'foo in object'.
8870 cond ; Node cond is also object in 'foo in object'.
8871 incr ; 3rd section of for-loop initializer.
8872 body tt lp rp)
8873 ;; See if this is a for each () instead of just a for ()
8874 (when (js2-match-token js2-NAME)
8875 (if (string= "each" (js2-current-token-string))
8876 (progn
8877 (setq is-for-each t
8878 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8879 (js2-record-face 'font-lock-keyword-face))
8880 (js2-report-error "msg.no.paren.for")))
8881 (if (js2-must-match js2-LP "msg.no.paren.for")
8882 (setq lp (- (js2-current-token-beg) for-pos)))
8883 (setq tt (js2-get-token))
8884 ;; Capture identifiers inside parens. We can't create the node
8885 ;; (and use it as the current scope) until we know its type.
8886 (js2-push-scope tmp-scope)
8887 (unwind-protect
8888 (progn
8889 ;; parse init clause
8890 (let ((js2-in-for-init t)) ; set as dynamic variable
8891 (cond
8892 ((= tt js2-SEMI)
8893 (js2-unget-token)
8894 (setq init (make-js2-empty-expr-node)))
8895 ((or (= tt js2-VAR) (= tt js2-LET))
8896 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8897 (t
8898 (js2-unget-token)
8899 (setq init (js2-parse-expr)))))
8900 (if (or (js2-match-token js2-IN)
8901 (and (>= js2-language-version 200)
8902 (js2-match-contextual-kwd "of")
8903 (setq is-for-of t)))
8904 (setq is-for-in-or-of t
8905 in-pos (- (js2-current-token-beg) for-pos)
8906 ;; scope of iteration target object is not the scope we've created above.
8907 ;; stash current scope temporary.
8908 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8909 (js2-parse-expr))) ; object over which we're iterating
8910 ;; else ordinary for loop - parse cond and incr
8911 (js2-must-match js2-SEMI "msg.no.semi.for")
8912 (setq cond (if (= (js2-peek-token) js2-SEMI)
8913 (make-js2-empty-expr-node) ; no loop condition
8914 (js2-parse-expr)))
8915 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8916 (setq tmp-pos (js2-current-token-end)
8917 incr (if (= (js2-peek-token) js2-RP)
8918 (make-js2-empty-expr-node :pos tmp-pos)
8919 (js2-parse-expr)))))
8920 (js2-pop-scope))
8921 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8922 (setq rp (- (js2-current-token-beg) for-pos)))
8923 (if (not is-for-in-or-of)
8924 (setq pn (make-js2-for-node :init init
8925 :condition cond
8926 :update incr
8927 :lp lp
8928 :rp rp))
8929 ;; cond could be null if 'in obj' got eaten by the init node.
8930 (if (js2-infix-node-p init)
8931 ;; it was (foo in bar) instead of (var foo in bar)
8932 (setq cond (js2-infix-node-right init)
8933 init (js2-infix-node-left init))
8934 (if (and (js2-var-decl-node-p init)
8935 (> (length (js2-var-decl-node-kids init)) 1))
8936 (js2-report-error "msg.mult.index")))
8937 (setq pn (make-js2-for-in-node :iterator init
8938 :object cond
8939 :in-pos in-pos
8940 :foreach-p is-for-each
8941 :each-pos each-pos
8942 :forof-p is-for-of
8943 :lp lp
8944 :rp rp)))
8945 ;; Transplant the declarations.
8946 (setf (js2-scope-symbol-table pn)
8947 (js2-scope-symbol-table tmp-scope))
8948 (unwind-protect
8949 (progn
8950 (js2-enter-loop pn)
8951 ;; We have to parse the body -after- creating the loop node,
8952 ;; so that the loop node appears in the js2-loop-set, allowing
8953 ;; break/continue statements to find the enclosing loop.
8954 (setf body (js2-parse-statement)
8955 (js2-loop-node-body pn) body
8956 (js2-node-pos pn) for-pos
8957 (js2-node-len pn) (- (js2-node-end body) for-pos))
8958 (js2-node-add-children pn init cond incr body))
8959 ;; finally
8960 (js2-exit-loop))
8961 pn))
8962
8963 (defun js2-parse-try ()
8964 "Parse a try statement. Last matched token must be js2-TRY."
8965 (let ((try-pos (js2-current-token-beg))
8966 try-end
8967 try-block
8968 catch-blocks
8969 finally-block
8970 saw-default-catch
8971 peek)
8972 (if (/= (js2-peek-token) js2-LC)
8973 (js2-report-error "msg.no.brace.try"))
8974 (setq try-block (js2-parse-statement)
8975 try-end (js2-node-end try-block)
8976 peek (js2-peek-token))
8977 (cond
8978 ((= peek js2-CATCH)
8979 (while (js2-match-token js2-CATCH)
8980 (let* ((catch-pos (js2-current-token-beg))
8981 (catch-node (make-js2-catch-node :pos catch-pos))
8982 param
8983 guard-kwd
8984 catch-cond
8985 lp rp)
8986 (if saw-default-catch
8987 (js2-report-error "msg.catch.unreachable"))
8988 (if (js2-must-match js2-LP "msg.no.paren.catch")
8989 (setq lp (- (js2-current-token-beg) catch-pos)))
8990 (js2-push-scope catch-node)
8991 (let ((tt (js2-peek-token)))
8992 (cond
8993 ;; Destructuring pattern:
8994 ;; catch ({ message, file }) { ... }
8995 ((or (= tt js2-LB) (= tt js2-LC))
8996 (js2-get-token)
8997 (setq param (js2-parse-destruct-primary-expr))
8998 (js2-define-destruct-symbols param js2-LET nil))
8999 ;; Simple name.
9000 (t
9001 (js2-must-match-name "msg.bad.catchcond")
9002 (setq param (js2-create-name-node))
9003 (js2-define-symbol js2-LET (js2-current-token-string) param)
9004 (js2-check-strict-identifier param))))
9005 ;; Catch condition.
9006 (if (js2-match-token js2-IF)
9007 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9008 catch-cond (js2-parse-expr))
9009 (setq saw-default-catch t))
9010 (if (js2-must-match js2-RP "msg.bad.catchcond")
9011 (setq rp (- (js2-current-token-beg) catch-pos)))
9012 (js2-must-match js2-LC "msg.no.brace.catchblock")
9013 (js2-parse-statements catch-node)
9014 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9015 (setq try-end (js2-current-token-end)))
9016 (js2-pop-scope)
9017 (setf (js2-node-len catch-node) (- try-end catch-pos)
9018 (js2-catch-node-param catch-node) param
9019 (js2-catch-node-guard-expr catch-node) catch-cond
9020 (js2-catch-node-guard-kwd catch-node) guard-kwd
9021 (js2-catch-node-lp catch-node) lp
9022 (js2-catch-node-rp catch-node) rp)
9023 (js2-node-add-children catch-node param catch-cond)
9024 (push catch-node catch-blocks))))
9025 ((/= peek js2-FINALLY)
9026 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9027 (js2-node-pos try-block)
9028 (- (setq try-end (js2-node-end try-block))
9029 (js2-node-pos try-block)))))
9030 (when (js2-match-token js2-FINALLY)
9031 (let ((finally-pos (js2-current-token-beg))
9032 (block (js2-parse-statement)))
9033 (setq try-end (js2-node-end block)
9034 finally-block (make-js2-finally-node :pos finally-pos
9035 :len (- try-end finally-pos)
9036 :body block))
9037 (js2-node-add-children finally-block block)))
9038 (let ((pn (make-js2-try-node :pos try-pos
9039 :len (- try-end try-pos)
9040 :try-block try-block
9041 :finally-block finally-block)))
9042 (js2-node-add-children pn try-block finally-block)
9043 ;; Push them onto the try-node, which reverses and corrects their order.
9044 (dolist (cb catch-blocks)
9045 (js2-node-add-children pn cb)
9046 (push cb (js2-try-node-catch-clauses pn)))
9047 pn)))
9048
9049 (defun js2-parse-throw ()
9050 "Parser for throw-statement. Last matched token must be js2-THROW."
9051 (let ((pos (js2-current-token-beg))
9052 expr pn)
9053 (if (= (js2-peek-token-or-eol) js2-EOL)
9054 ;; ECMAScript does not allow new lines before throw expression,
9055 ;; see bug 256617
9056 (js2-report-error "msg.bad.throw.eol"))
9057 (setq expr (js2-parse-expr)
9058 pn (make-js2-throw-node :pos pos
9059 :len (- (js2-node-end expr) pos)
9060 :expr expr))
9061 (js2-node-add-children pn expr)
9062 pn))
9063
9064 (defun js2-match-jump-label-name (label-name)
9065 "If break/continue specified a label, return that label's labeled stmt.
9066 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9067 does not match an existing label, reports an error and returns nil."
9068 (let ((bundle (cdr (assoc label-name js2-label-set))))
9069 (if (null bundle)
9070 (js2-report-error "msg.undef.label"))
9071 bundle))
9072
9073 (defun js2-parse-break ()
9074 "Parser for break-statement. Last matched token must be js2-BREAK."
9075 (let ((pos (js2-current-token-beg))
9076 (end (js2-current-token-end))
9077 break-target ; statement to break from
9078 break-label ; in "break foo", name-node representing the foo
9079 labels ; matching labeled statement to break to
9080 pn)
9081 (when (eq (js2-peek-token-or-eol) js2-NAME)
9082 (js2-get-token)
9083 (setq break-label (js2-create-name-node)
9084 end (js2-node-end break-label)
9085 ;; matchJumpLabelName only matches if there is one
9086 labels (js2-match-jump-label-name (js2-current-token-string))
9087 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9088 (unless (or break-target break-label)
9089 ;; no break target specified - try for innermost enclosing loop/switch
9090 (if (null js2-loop-and-switch-set)
9091 (unless break-label
9092 (js2-report-error "msg.bad.break" nil pos (length "break")))
9093 (setq break-target (car js2-loop-and-switch-set))))
9094 (setq pn (make-js2-break-node :pos pos
9095 :len (- end pos)
9096 :label break-label
9097 :target break-target))
9098 (js2-node-add-children pn break-label) ; but not break-target
9099 pn))
9100
9101 (defun js2-parse-continue ()
9102 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9103 (let ((pos (js2-current-token-beg))
9104 (end (js2-current-token-end))
9105 label ; optional user-specified label, a `js2-name-node'
9106 labels ; current matching labeled stmt, if any
9107 target ; the `js2-loop-node' target of this continue stmt
9108 pn)
9109 (when (= (js2-peek-token-or-eol) js2-NAME)
9110 (js2-get-token)
9111 (setq label (js2-create-name-node)
9112 end (js2-node-end label)
9113 ;; matchJumpLabelName only matches if there is one
9114 labels (js2-match-jump-label-name (js2-current-token-string))))
9115 (cond
9116 ((null labels) ; no current label to go to
9117 (if (null js2-loop-set) ; no loop to continue to
9118 (js2-report-error "msg.continue.outside" nil pos
9119 (length "continue"))
9120 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9121 (t
9122 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9123 (setq target (js2-labeled-stmt-node-stmt labels))
9124 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9125 (setq pn (make-js2-continue-node :pos pos
9126 :len (- end pos)
9127 :label label
9128 :target target))
9129 (js2-node-add-children pn label) ; but not target - it's not our child
9130 pn))
9131
9132 (defun js2-parse-with ()
9133 "Parser for with-statement. Last matched token must be js2-WITH."
9134 (when js2-in-use-strict-directive
9135 (js2-report-error "msg.no.with.strict"))
9136 (let ((pos (js2-current-token-beg))
9137 obj body pn lp rp)
9138 (if (js2-must-match js2-LP "msg.no.paren.with")
9139 (setq lp (js2-current-token-beg)))
9140 (setq obj (js2-parse-expr))
9141 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9142 (setq rp (js2-current-token-beg)))
9143 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9144 (setq body (js2-parse-statement)))
9145 (setq pn (make-js2-with-node :pos pos
9146 :len (- (js2-node-end body) pos)
9147 :object obj
9148 :body body
9149 :lp (js2-relpos lp pos)
9150 :rp (js2-relpos rp pos)))
9151 (js2-node-add-children pn obj body)
9152 pn))
9153
9154 (defun js2-parse-const-var ()
9155 "Parser for var- or const-statement.
9156 Last matched token must be js2-CONST or js2-VAR."
9157 (let ((tt (js2-current-token-type))
9158 (pos (js2-current-token-beg))
9159 expr pn)
9160 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9161 pn (make-js2-expr-stmt-node :pos pos
9162 :len (- (js2-node-end expr) pos)
9163 :expr expr))
9164 (js2-node-add-children pn expr)
9165 pn))
9166
9167 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9168 (let ((pn (make-js2-expr-stmt-node :pos pos
9169 :len (js2-node-len expr)
9170 :type (if (js2-inside-function)
9171 js2-EXPR_VOID
9172 js2-EXPR_RESULT)
9173 :expr expr)))
9174 (if add-child
9175 (js2-node-add-children pn expr))
9176 pn))
9177
9178 (defun js2-parse-let-stmt ()
9179 "Parser for let-statement. Last matched token must be js2-LET."
9180 (let ((pos (js2-current-token-beg))
9181 expr pn)
9182 (if (= (js2-peek-token) js2-LP)
9183 ;; let expression in statement context
9184 (setq expr (js2-parse-let pos 'statement)
9185 pn (js2-wrap-with-expr-stmt pos expr t))
9186 ;; else we're looking at a statement like let x=6, y=7;
9187 (setf expr (js2-parse-variables js2-LET pos)
9188 pn (js2-wrap-with-expr-stmt pos expr t)
9189 (js2-node-type pn) js2-EXPR_RESULT))
9190 pn))
9191
9192 (defun js2-parse-ret-yield ()
9193 (js2-parse-return-or-yield (js2-current-token-type) nil))
9194
9195 (defconst js2-parse-return-stmt-enders
9196 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9197
9198 (defsubst js2-now-all-set (before after mask)
9199 "Return whether or not the bits in the mask have changed to all set.
9200 BEFORE is bits before change, AFTER is bits after change, and MASK is
9201 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9202 but not BEFORE."
9203 (and (/= (logand before mask) mask)
9204 (= (logand after mask) mask)))
9205
9206 (defun js2-parse-return-or-yield (tt expr-context)
9207 (let* ((pos (js2-current-token-beg))
9208 (end (js2-current-token-end))
9209 (before js2-end-flags)
9210 (inside-function (js2-inside-function))
9211 (gen-type (and inside-function (js2-function-node-generator-type
9212 js2-current-script-or-fn)))
9213 e ret name yield-star-p)
9214 (unless inside-function
9215 (js2-report-error (if (eq tt js2-RETURN)
9216 "msg.bad.return"
9217 "msg.bad.yield")))
9218 (when (and inside-function
9219 (eq gen-type 'STAR)
9220 (js2-match-token js2-MUL))
9221 (setq yield-star-p t))
9222 ;; This is ugly, but we don't want to require a semicolon.
9223 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9224 (setq e (js2-parse-expr)
9225 end (js2-node-end e)))
9226 (cond
9227 ((eq tt js2-RETURN)
9228 (js2-set-flag js2-end-flags (if (null e)
9229 js2-end-returns
9230 js2-end-returns-value))
9231 (setq ret (make-js2-return-node :pos pos
9232 :len (- end pos)
9233 :retval e))
9234 (js2-node-add-children ret e)
9235 ;; See if we need a strict mode warning.
9236 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9237 ;; more thorough and accurate than this before/after flag check.
9238 ;; E.g. if there's a finally-block that always returns, we shouldn't
9239 ;; show a warning generated by inconsistent returns in the catch blocks.
9240 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9241 ;; so we know which returns/yields to highlight, and we should get rid of
9242 ;; all the checking in `js2-parse-return-or-yield'.
9243 (if (and js2-strict-inconsistent-return-warning
9244 (js2-now-all-set before js2-end-flags
9245 (logior js2-end-returns js2-end-returns-value)))
9246 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9247 ((eq gen-type 'COMPREHENSION)
9248 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9249 ;; like SpiderMonkey does.
9250 (js2-report-error "msg.syntax" nil pos 5))
9251 (t
9252 (setq ret (make-js2-yield-node :pos pos
9253 :len (- end pos)
9254 :value e
9255 :star-p yield-star-p))
9256 (js2-node-add-children ret e)
9257 (unless expr-context
9258 (setq e ret
9259 ret (js2-wrap-with-expr-stmt pos e t))
9260 (js2-set-requires-activation)
9261 (js2-set-is-generator))))
9262 ;; see if we are mixing yields and value returns.
9263 (when (and inside-function
9264 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9265 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9266 'LEGACY))
9267 (setq name (js2-function-name js2-current-script-or-fn))
9268 (if (zerop (length name))
9269 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9270 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9271 ret))
9272
9273 (defun js2-parse-debugger ()
9274 (make-js2-keyword-node :type js2-DEBUGGER))
9275
9276 (defun js2-parse-block ()
9277 "Parser for a curly-delimited statement block.
9278 Last token matched must be `js2-LC'."
9279 (let ((pos (js2-current-token-beg))
9280 (pn (make-js2-scope)))
9281 (js2-push-scope pn)
9282 (unwind-protect
9283 (progn
9284 (js2-parse-statements pn)
9285 (js2-must-match js2-RC "msg.no.brace.block")
9286 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9287 (js2-pop-scope))
9288 pn))
9289
9290 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9291 (defun js2-parse-semi ()
9292 "Parse a statement or handle an error.
9293 Current token type is `js2-SEMI' or `js2-ERROR'."
9294 (let ((tt (js2-current-token-type)) pos len)
9295 (if (eq tt js2-SEMI)
9296 (make-js2-empty-expr-node :len 1)
9297 (setq pos (js2-current-token-beg)
9298 len (- (js2-current-token-end) pos))
9299 (js2-report-error "msg.syntax" nil pos len)
9300 (make-js2-error-node :pos pos :len len))))
9301
9302 (defun js2-parse-default-xml-namespace ()
9303 "Parse a `default xml namespace = <expr>' e4x statement."
9304 (let ((pos (js2-current-token-beg))
9305 end len expr unary)
9306 (js2-must-have-xml)
9307 (js2-set-requires-activation)
9308 (setq len (- js2-ts-cursor pos))
9309 (unless (and (js2-match-token js2-NAME)
9310 (string= (js2-current-token-string) "xml"))
9311 (js2-report-error "msg.bad.namespace" nil pos len))
9312 (unless (and (js2-match-token js2-NAME)
9313 (string= (js2-current-token-string) "namespace"))
9314 (js2-report-error "msg.bad.namespace" nil pos len))
9315 (unless (js2-match-token js2-ASSIGN)
9316 (js2-report-error "msg.bad.namespace" nil pos len))
9317 (setq expr (js2-parse-expr)
9318 end (js2-node-end expr)
9319 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9320 :pos pos
9321 :len (- end pos)
9322 :operand expr))
9323 (js2-node-add-children unary expr)
9324 (make-js2-expr-stmt-node :pos pos
9325 :len (- end pos)
9326 :expr unary)))
9327
9328 (defun js2-record-label (label bundle)
9329 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9330 (js2-get-token)
9331 (let ((name (js2-label-node-name label))
9332 labeled-stmt
9333 dup)
9334 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9335 ;; flag both labels if possible when used in editing mode
9336 (if (and js2-parse-ide-mode
9337 (setq dup (js2-get-label-by-name labeled-stmt name)))
9338 (js2-report-error "msg.dup.label" nil
9339 (js2-node-abs-pos dup) (js2-node-len dup)))
9340 (js2-report-error "msg.dup.label" nil
9341 (js2-node-pos label) (js2-node-len label)))
9342 (js2-labeled-stmt-node-add-label bundle label)
9343 (js2-node-add-children bundle label)
9344 ;; Add one reference to the bundle per label in `js2-label-set'
9345 (push (cons name bundle) js2-label-set)))
9346
9347 (defun js2-parse-name-or-label ()
9348 "Parser for identifier or label. Last token matched must be js2-NAME.
9349 Called when we found a name in a statement context. If it's a label, we gather
9350 up any following labels and the next non-label statement into a
9351 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9352 expression and return it wrapped in a `js2-expr-stmt-node'."
9353 (let ((pos (js2-current-token-beg))
9354 expr stmt bundle
9355 (continue t))
9356 ;; set check for label and call down to `js2-parse-primary-expr'
9357 (setq expr (js2-maybe-parse-label))
9358 (if (null expr)
9359 ;; Parse the non-label expression and wrap with expression stmt.
9360 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9361 ;; else parsed a label
9362 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9363 (js2-record-label expr bundle)
9364 ;; look for more labels
9365 (while (and continue (= (js2-get-token) js2-NAME))
9366 (if (setq expr (js2-maybe-parse-label))
9367 (js2-record-label expr bundle)
9368 (setq expr (js2-parse-expr)
9369 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9370 continue nil)
9371 (js2-auto-insert-semicolon stmt)))
9372 ;; no more labels; now parse the labeled statement
9373 (unwind-protect
9374 (unless stmt
9375 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9376 (js2-unget-token)
9377 (setq stmt (js2-statement-helper))))
9378 ;; remove the labels for this statement from the global set
9379 (dolist (label (js2-labeled-stmt-node-labels bundle))
9380 (setq js2-label-set (remove label js2-label-set))))
9381 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9382 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9383 (js2-node-add-children bundle stmt)
9384 bundle)))
9385
9386 (defun js2-maybe-parse-label ()
9387 (cl-assert (= (js2-current-token-type) js2-NAME))
9388 (let (label-pos
9389 (next-tt (js2-get-token))
9390 (label-end (js2-current-token-end)))
9391 ;; Do not consume colon, it is used as unwind indicator
9392 ;; to return to statementHelper.
9393 (js2-unget-token)
9394 (if (= next-tt js2-COLON)
9395 (prog2
9396 (setq label-pos (js2-current-token-beg))
9397 (make-js2-label-node :pos label-pos
9398 :len (- label-end label-pos)
9399 :name (js2-current-token-string))
9400 (js2-set-face label-pos
9401 label-end
9402 'font-lock-variable-name-face 'record))
9403 ;; Backtrack from the name token, too.
9404 (js2-unget-token)
9405 nil)))
9406
9407 (defun js2-parse-expr-stmt ()
9408 "Default parser in statement context, if no recognized statement found."
9409 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9410 (progn
9411 (js2-unget-token)
9412 (js2-parse-expr)) t))
9413
9414 (defun js2-parse-variables (decl-type pos)
9415 "Parse a comma-separated list of variable declarations.
9416 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9417
9418 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9419 For 'var' or 'const', the keyword should be the token last scanned.
9420
9421 POS is the position where the node should start. It's sometimes the
9422 var/const/let keyword, and other times the beginning of the first token
9423 in the first variable declaration.
9424
9425 Returns the parsed `js2-var-decl-node' expression node."
9426 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9427 :pos pos))
9428 destructuring kid-pos tt init name end nbeg nend vi
9429 (continue t))
9430 ;; Example:
9431 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9432 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9433 ;; var {a, b} = baz;
9434 (while continue
9435 (setq destructuring nil
9436 name nil
9437 tt (js2-get-token)
9438 kid-pos (js2-current-token-beg)
9439 end (js2-current-token-end)
9440 init nil)
9441 (if (or (= tt js2-LB) (= tt js2-LC))
9442 ;; Destructuring assignment, e.g., var [a, b] = ...
9443 (setq destructuring (js2-parse-destruct-primary-expr)
9444 end (js2-node-end destructuring))
9445 ;; Simple variable name
9446 (js2-unget-token)
9447 (when (js2-must-match-name "msg.bad.var")
9448 (setq name (js2-create-name-node)
9449 nbeg (js2-current-token-beg)
9450 nend (js2-current-token-end)
9451 end nend)
9452 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9453 (js2-check-strict-identifier name)))
9454 (when (js2-match-token js2-ASSIGN)
9455 (setq init (js2-parse-assign-expr)
9456 end (js2-node-end init))
9457 (js2-record-imenu-functions init name))
9458 (when name
9459 (js2-set-face nbeg nend (if (js2-function-node-p init)
9460 'font-lock-function-name-face
9461 'font-lock-variable-name-face)
9462 'record))
9463 (setq vi (make-js2-var-init-node :pos kid-pos
9464 :len (- end kid-pos)
9465 :type decl-type))
9466 (if destructuring
9467 (progn
9468 (if (and (null init) (not js2-in-for-init))
9469 (js2-report-error "msg.destruct.assign.no.init"))
9470 (js2-define-destruct-symbols destructuring
9471 decl-type
9472 'font-lock-variable-name-face)
9473 (setf (js2-var-init-node-target vi) destructuring))
9474 (setf (js2-var-init-node-target vi) name))
9475 (setf (js2-var-init-node-initializer vi) init)
9476 (js2-node-add-children vi name destructuring init)
9477 (js2-block-node-push result vi)
9478 (unless (js2-match-token js2-COMMA)
9479 (setq continue nil)))
9480 (setf (js2-node-len result) (- end pos))
9481 result))
9482
9483 (defun js2-parse-let (pos &optional stmt-p)
9484 "Parse a let expression or statement.
9485 A let-expression is of the form `let (vars) expr'.
9486 A let-statement is of the form `let (vars) {statements}'.
9487 The third form of let is a variable declaration list, handled
9488 by `js2-parse-variables'."
9489 (let ((pn (make-js2-let-node :pos pos))
9490 beg vars body)
9491 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9492 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9493 (js2-push-scope pn)
9494 (unwind-protect
9495 (progn
9496 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9497 (if (js2-must-match js2-RP "msg.no.paren.let")
9498 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9499 (if (and stmt-p (js2-match-token js2-LC))
9500 ;; let statement
9501 (progn
9502 (setf beg (js2-current-token-beg) ; position stmt at LC
9503 body (js2-parse-statements))
9504 (js2-must-match js2-RC "msg.no.curly.let")
9505 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9506 (js2-node-len pn) (- (js2-current-token-end) pos)
9507 (js2-let-node-body pn) body
9508 (js2-node-type pn) js2-LET))
9509 ;; let expression
9510 (setf body (js2-parse-expr)
9511 (js2-node-len pn) (- (js2-node-end body) pos)
9512 (js2-let-node-body pn) body))
9513 (setf (js2-let-node-vars pn) vars)
9514 (js2-node-add-children pn vars body))
9515 (js2-pop-scope))
9516 pn))
9517
9518 (defun js2-define-new-symbol (decl-type name node &optional scope)
9519 (js2-scope-put-symbol (or scope js2-current-scope)
9520 name
9521 (make-js2-symbol decl-type name node)))
9522
9523 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9524 "Define a symbol in the current scope.
9525 If NODE is non-nil, it is the AST node associated with the symbol."
9526 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9527 (symbol (if defining-scope
9528 (js2-scope-get-symbol defining-scope name)))
9529 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9530 (pos (if node (js2-node-abs-pos node)))
9531 (len (if node (js2-node-len node))))
9532 (cond
9533 ((and symbol ; already defined
9534 (or (if js2-in-use-strict-directive
9535 ;; two const-bound vars in this block have same name
9536 (and (= sdt js2-CONST)
9537 (eq defining-scope js2-current-scope))
9538 (or (= sdt js2-CONST) ; old version is const
9539 (= decl-type js2-CONST))) ; new version is const
9540 ;; two let-bound vars in this block have same name
9541 (and (= sdt js2-LET)
9542 (eq defining-scope js2-current-scope))))
9543 (js2-report-error
9544 (cond
9545 ((= sdt js2-CONST) "msg.const.redecl")
9546 ((= sdt js2-LET) "msg.let.redecl")
9547 ((= sdt js2-VAR) "msg.var.redecl")
9548 ((= sdt js2-FUNCTION) "msg.function.redecl")
9549 (t "msg.parm.redecl"))
9550 name pos len))
9551 ((or (= decl-type js2-LET)
9552 ;; strict mode const is scoped to the current LexicalEnvironment
9553 (and js2-in-use-strict-directive
9554 (= decl-type js2-CONST)))
9555 (if (and (= decl-type js2-LET)
9556 (not ignore-not-in-block)
9557 (or (= (js2-node-type js2-current-scope) js2-IF)
9558 (js2-loop-node-p js2-current-scope)))
9559 (js2-report-error "msg.let.decl.not.in.block")
9560 (js2-define-new-symbol decl-type name node)))
9561 ((or (= decl-type js2-VAR)
9562 (= decl-type js2-FUNCTION)
9563 ;; sloppy mode const is scoped to the current VariableEnvironment
9564 (and (not js2-in-use-strict-directive)
9565 (= decl-type js2-CONST)))
9566 (if symbol
9567 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9568 (js2-add-strict-warning "msg.var.redecl" name)
9569 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9570 (js2-add-strict-warning "msg.var.hides.arg" name)))
9571 (js2-define-new-symbol decl-type name node
9572 js2-current-script-or-fn)))
9573 ((= decl-type js2-LP)
9574 (if symbol
9575 ;; must be duplicate parameter. Second parameter hides the
9576 ;; first, so go ahead and add the second pararameter
9577 (js2-report-warning "msg.dup.parms" name))
9578 (js2-define-new-symbol decl-type name node))
9579 (t (js2-code-bug)))))
9580
9581 (defun js2-parse-paren-expr-or-generator-comp ()
9582 (let ((px-pos (js2-current-token-beg)))
9583 (cond
9584 ((and (>= js2-language-version 200)
9585 (js2-match-token js2-FOR))
9586 (js2-parse-generator-comp px-pos))
9587 ((and (>= js2-language-version 200)
9588 (js2-match-token js2-RP))
9589 ;; Not valid expression syntax, but this is valid in an arrow
9590 ;; function with no params: () => body.
9591 (if (eq (js2-peek-token) js2-ARROW)
9592 ;; Return whatever, it will hopefully be rewinded and
9593 ;; reparsed when we reach the =>.
9594 (make-js2-keyword-node :type js2-NULL)
9595 (js2-report-error "msg.syntax")
9596 (make-js2-error-node)))
9597 (t
9598 (let* ((js2-in-for-init nil)
9599 (expr (js2-parse-expr))
9600 (pn (make-js2-paren-node :pos px-pos
9601 :expr expr)))
9602 (js2-node-add-children pn (js2-paren-node-expr pn))
9603 (js2-must-match js2-RP "msg.no.paren")
9604 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9605 pn)))))
9606
9607 (defun js2-parse-expr (&optional oneshot)
9608 (let* ((pn (js2-parse-assign-expr))
9609 (pos (js2-node-pos pn))
9610 left
9611 right
9612 op-pos)
9613 (while (and (not oneshot)
9614 (js2-match-token js2-COMMA))
9615 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9616 (if (= (js2-peek-token) js2-YIELD)
9617 (js2-report-error "msg.yield.parenthesized"))
9618 (setq right (js2-parse-assign-expr)
9619 left pn
9620 pn (make-js2-infix-node :type js2-COMMA
9621 :pos pos
9622 :len (- js2-ts-cursor pos)
9623 :op-pos op-pos
9624 :left left
9625 :right right))
9626 (js2-node-add-children pn left right))
9627 pn))
9628
9629 (defun js2-parse-assign-expr ()
9630 (let ((tt (js2-get-token))
9631 (pos (js2-current-token-beg))
9632 pn left right op-pos
9633 ts-state recorded-identifiers parsed-errors
9634 async-p)
9635 (if (= tt js2-YIELD)
9636 (js2-parse-return-or-yield tt t)
9637 ;; TODO(mooz): Bit confusing.
9638 ;; If we meet `async` token and it's not part of `async
9639 ;; function`, then this `async` is for a succeeding async arrow
9640 ;; function.
9641 ;; Since arrow function parsing doesn't rely on neither
9642 ;; `js2-parse-function-stmt' nor `js2-parse-function-expr' that
9643 ;; interpret `async` token, we trash `async` and just remember
9644 ;; we met `async` keyword to `async-p'.
9645 (when (js2-match-async-arrow-function)
9646 (setq async-p t))
9647 ;; Save the tokenizer state in case we find an arrow function
9648 ;; and have to rewind.
9649 (setq ts-state (make-js2-ts-state)
9650 recorded-identifiers js2-recorded-identifiers
9651 parsed-errors js2-parsed-errors)
9652 ;; not yield - parse assignment expression
9653 (setq pn (js2-parse-cond-expr)
9654 tt (js2-get-token))
9655 (cond
9656 ((and (<= js2-first-assign tt)
9657 (<= tt js2-last-assign))
9658 ;; tt express assignment (=, |=, ^=, ..., %=)
9659 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9660 left pn)
9661 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9662 ;; care about assignment to strict variable names.
9663 (when (js2-name-node-p left)
9664 (js2-check-strict-identifier left))
9665 (setq right (js2-parse-assign-expr)
9666 pn (make-js2-assign-node :type tt
9667 :pos pos
9668 :len (- (js2-node-end right) pos)
9669 :op-pos op-pos
9670 :left left
9671 :right right))
9672 (when js2-parse-ide-mode
9673 (js2-highlight-assign-targets pn left right)
9674 (js2-record-imenu-functions right left))
9675 ;; do this last so ide checks above can use absolute positions
9676 (js2-node-add-children pn left right))
9677 ((and (= tt js2-ARROW)
9678 (>= js2-language-version 200))
9679 (js2-ts-seek ts-state)
9680 (setq js2-recorded-identifiers recorded-identifiers
9681 js2-parsed-errors parsed-errors)
9682 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil async-p)))
9683 (t
9684 (js2-unget-token)))
9685 pn)))
9686
9687 (defun js2-parse-cond-expr ()
9688 (let ((pos (js2-current-token-beg))
9689 (pn (js2-parse-or-expr))
9690 test-expr
9691 if-true
9692 if-false
9693 q-pos
9694 c-pos)
9695 (when (js2-match-token js2-HOOK)
9696 (setq q-pos (- (js2-current-token-beg) pos)
9697 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9698 (js2-must-match js2-COLON "msg.no.colon.cond")
9699 (setq c-pos (- (js2-current-token-beg) pos)
9700 if-false (js2-parse-assign-expr)
9701 test-expr pn
9702 pn (make-js2-cond-node :pos pos
9703 :len (- (js2-node-end if-false) pos)
9704 :test-expr test-expr
9705 :true-expr if-true
9706 :false-expr if-false
9707 :q-pos q-pos
9708 :c-pos c-pos))
9709 (js2-node-add-children pn test-expr if-true if-false))
9710 pn))
9711
9712 (defun js2-make-binary (type left parser &optional no-get)
9713 "Helper for constructing a binary-operator AST node.
9714 LEFT is the left-side-expression, already parsed, and the
9715 binary operator should have just been matched.
9716 PARSER is a function to call to parse the right operand,
9717 or a `js2-node' struct if it has already been parsed.
9718 FIXME: The latter option is unused?"
9719 (let* ((pos (js2-node-pos left))
9720 (op-pos (- (js2-current-token-beg) pos))
9721 (right (if (js2-node-p parser)
9722 parser
9723 (unless no-get (js2-get-token))
9724 (funcall parser)))
9725 (pn (make-js2-infix-node :type type
9726 :pos pos
9727 :len (- (js2-node-end right) pos)
9728 :op-pos op-pos
9729 :left left
9730 :right right)))
9731 (js2-node-add-children pn left right)
9732 pn))
9733
9734 (defun js2-parse-or-expr ()
9735 (let ((pn (js2-parse-and-expr)))
9736 (when (js2-match-token js2-OR)
9737 (setq pn (js2-make-binary js2-OR
9738 pn
9739 'js2-parse-or-expr)))
9740 pn))
9741
9742 (defun js2-parse-and-expr ()
9743 (let ((pn (js2-parse-bit-or-expr)))
9744 (when (js2-match-token js2-AND)
9745 (setq pn (js2-make-binary js2-AND
9746 pn
9747 'js2-parse-and-expr)))
9748 pn))
9749
9750 (defun js2-parse-bit-or-expr ()
9751 (let ((pn (js2-parse-bit-xor-expr)))
9752 (while (js2-match-token js2-BITOR)
9753 (setq pn (js2-make-binary js2-BITOR
9754 pn
9755 'js2-parse-bit-xor-expr)))
9756 pn))
9757
9758 (defun js2-parse-bit-xor-expr ()
9759 (let ((pn (js2-parse-bit-and-expr)))
9760 (while (js2-match-token js2-BITXOR)
9761 (setq pn (js2-make-binary js2-BITXOR
9762 pn
9763 'js2-parse-bit-and-expr)))
9764 pn))
9765
9766 (defun js2-parse-bit-and-expr ()
9767 (let ((pn (js2-parse-eq-expr)))
9768 (while (js2-match-token js2-BITAND)
9769 (setq pn (js2-make-binary js2-BITAND
9770 pn
9771 'js2-parse-eq-expr)))
9772 pn))
9773
9774 (defconst js2-parse-eq-ops
9775 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9776
9777 (defun js2-parse-eq-expr ()
9778 (let ((pn (js2-parse-rel-expr))
9779 tt)
9780 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9781 (setq pn (js2-make-binary tt
9782 pn
9783 'js2-parse-rel-expr)))
9784 (js2-unget-token)
9785 pn))
9786
9787 (defconst js2-parse-rel-ops
9788 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9789
9790 (defun js2-parse-rel-expr ()
9791 (let ((pn (js2-parse-shift-expr))
9792 (continue t)
9793 tt)
9794 (while continue
9795 (setq tt (js2-get-token))
9796 (cond
9797 ((and js2-in-for-init (= tt js2-IN))
9798 (js2-unget-token)
9799 (setq continue nil))
9800 ((memq tt js2-parse-rel-ops)
9801 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9802 (t
9803 (js2-unget-token)
9804 (setq continue nil))))
9805 pn))
9806
9807 (defconst js2-parse-shift-ops
9808 (list js2-LSH js2-URSH js2-RSH))
9809
9810 (defun js2-parse-shift-expr ()
9811 (let ((pn (js2-parse-add-expr))
9812 tt
9813 (continue t))
9814 (while continue
9815 (setq tt (js2-get-token))
9816 (if (memq tt js2-parse-shift-ops)
9817 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9818 (js2-unget-token)
9819 (setq continue nil)))
9820 pn))
9821
9822 (defun js2-parse-add-expr ()
9823 (let ((pn (js2-parse-mul-expr))
9824 tt
9825 (continue t))
9826 (while continue
9827 (setq tt (js2-get-token))
9828 (if (or (= tt js2-ADD) (= tt js2-SUB))
9829 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9830 (js2-unget-token)
9831 (setq continue nil)))
9832 pn))
9833
9834 (defconst js2-parse-mul-ops
9835 (list js2-MUL js2-DIV js2-MOD))
9836
9837 (defun js2-parse-mul-expr ()
9838 (let ((pn (js2-parse-unary-expr))
9839 tt
9840 (continue t))
9841 (while continue
9842 (setq tt (js2-get-token))
9843 (if (memq tt js2-parse-mul-ops)
9844 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9845 (js2-unget-token)
9846 (setq continue nil)))
9847 pn))
9848
9849 (defun js2-make-unary (type parser &rest args)
9850 "Make a unary node of type TYPE.
9851 PARSER is either a node (for postfix operators) or a function to call
9852 to parse the operand (for prefix operators)."
9853 (let* ((pos (js2-current-token-beg))
9854 (postfix (js2-node-p parser))
9855 (expr (if postfix
9856 parser
9857 (apply parser args)))
9858 end
9859 pn)
9860 (if postfix ; e.g. i++
9861 (setq pos (js2-node-pos expr)
9862 end (js2-current-token-end))
9863 (setq end (js2-node-end expr)))
9864 (setq pn (make-js2-unary-node :type type
9865 :pos pos
9866 :len (- end pos)
9867 :operand expr))
9868 (js2-node-add-children pn expr)
9869 pn))
9870
9871 (defun js2-make-await ()
9872 "Make an await node."
9873 (let* ((pos (js2-current-token-beg))
9874 (expr (js2-parse-unary-expr))
9875 (end (js2-node-end expr))
9876 pn)
9877 (setq pn (make-js2-await-node :pos pos
9878 :len (- end pos)
9879 :operand expr))
9880 (js2-node-add-children pn expr)
9881 pn))
9882
9883 (defconst js2-incrementable-node-types
9884 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9885 "Node types that can be the operand of a ++ or -- operator.")
9886
9887 (defun js2-check-bad-inc-dec (tt beg end unary)
9888 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9889 js2-incrementable-node-types)
9890 (js2-report-error (if (= tt js2-INC)
9891 "msg.bad.incr"
9892 "msg.bad.decr")
9893 nil beg (- end beg))))
9894
9895 (defun js2-parse-unary-expr ()
9896 (let ((tt (js2-current-token-type))
9897 pn expr beg end)
9898 (cond
9899 ((or (= tt js2-VOID)
9900 (= tt js2-NOT)
9901 (= tt js2-BITNOT)
9902 (= tt js2-TYPEOF))
9903 (js2-get-token)
9904 (js2-make-unary tt 'js2-parse-unary-expr))
9905 ((= tt js2-ADD)
9906 (js2-get-token)
9907 ;; Convert to special POS token in decompiler and parse tree
9908 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9909 ((= tt js2-SUB)
9910 (js2-get-token)
9911 ;; Convert to special NEG token in decompiler and parse tree
9912 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9913 ((or (= tt js2-INC)
9914 (= tt js2-DEC))
9915 (js2-get-token)
9916 (prog1
9917 (setq beg (js2-current-token-beg)
9918 end (js2-current-token-end)
9919 expr (js2-make-unary tt 'js2-parse-member-expr t))
9920 (js2-check-bad-inc-dec tt beg end expr)))
9921 ((= tt js2-DELPROP)
9922 (js2-get-token)
9923 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9924 ((js2-match-await)
9925 (js2-make-unary js2-AWAIT 'js2-parse-unary-expr))
9926 ((= tt js2-ERROR)
9927 (js2-get-token)
9928 (make-js2-error-node)) ; try to continue
9929 ((and (= tt js2-LT)
9930 js2-compiler-xml-available)
9931 ;; XML stream encountered in expression.
9932 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9933 (t
9934 (setq pn (js2-parse-member-expr t)
9935 ;; Don't look across a newline boundary for a postfix incop.
9936 tt (js2-peek-token-or-eol))
9937 (when (or (= tt js2-INC) (= tt js2-DEC))
9938 (js2-get-token)
9939 (setf expr pn
9940 pn (js2-make-unary tt expr))
9941 (js2-node-set-prop pn 'postfix t)
9942 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9943 pn))))
9944
9945 (defun js2-parse-xml-initializer ()
9946 "Parse an E4X XML initializer.
9947 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9948 Then I'll postprocess the result, depending on whether we're in IDE
9949 mode or codegen mode, and generate the appropriate rewritten AST.
9950 IDE mode uses a rich AST that models the XML structure. Codegen mode
9951 just concatenates everything and makes a new XML or XMLList out of it."
9952 (let ((tt (js2-get-first-xml-token))
9953 pn-xml pn expr kids expr-pos
9954 (continue t)
9955 (first-token t))
9956 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9957 (js2-report-error "msg.syntax"))
9958 (setq pn-xml (make-js2-xml-node))
9959 (while continue
9960 (if first-token
9961 (setq first-token nil)
9962 (setq tt (js2-get-next-xml-token)))
9963 (cond
9964 ;; js2-XML means we found a {expr} in the XML stream.
9965 ;; The token string is the XML up to the left-curly.
9966 ((= tt js2-XML)
9967 (push (make-js2-string-node :pos (js2-current-token-beg)
9968 :len (- js2-ts-cursor (js2-current-token-beg)))
9969 kids)
9970 (js2-must-match js2-LC "msg.syntax")
9971 (setq expr-pos js2-ts-cursor
9972 expr (if (eq (js2-peek-token) js2-RC)
9973 (make-js2-empty-expr-node :pos expr-pos)
9974 (js2-parse-expr)))
9975 (js2-must-match js2-RC "msg.syntax")
9976 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9977 :len (js2-node-len expr)
9978 :expr expr))
9979 (js2-node-add-children pn expr)
9980 (push pn kids))
9981 ;; a js2-XMLEND token means we hit the final close-tag.
9982 ((= tt js2-XMLEND)
9983 (push (make-js2-string-node :pos (js2-current-token-beg)
9984 :len (- js2-ts-cursor (js2-current-token-beg)))
9985 kids)
9986 (dolist (kid (nreverse kids))
9987 (js2-block-node-push pn-xml kid))
9988 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9989 (js2-node-pos pn-xml))
9990 continue nil))
9991 (t
9992 (js2-report-error "msg.syntax")
9993 (setq continue nil))))
9994 pn-xml))
9995
9996
9997 (defun js2-parse-argument-list ()
9998 "Parse an argument list and return it as a Lisp list of nodes.
9999 Returns the list in reverse order. Consumes the right-paren token."
10000 (let (result)
10001 (unless (js2-match-token js2-RP)
10002 (cl-loop do
10003 (let ((tt (js2-get-token)))
10004 (if (= tt js2-YIELD)
10005 (js2-report-error "msg.yield.parenthesized"))
10006 (if (and (= tt js2-TRIPLEDOT)
10007 (>= js2-language-version 200))
10008 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
10009 (js2-unget-token)
10010 (push (js2-parse-assign-expr) result)))
10011 while
10012 (js2-match-token js2-COMMA))
10013 (js2-must-match js2-RP "msg.no.paren.arg")
10014 result)))
10015
10016 (defun js2-parse-member-expr (&optional allow-call-syntax)
10017 (let ((tt (js2-current-token-type))
10018 pn pos target args beg end init)
10019 (if (/= tt js2-NEW)
10020 (setq pn (js2-parse-primary-expr))
10021 ;; parse a 'new' expression
10022 (js2-get-token)
10023 (setq pos (js2-current-token-beg)
10024 beg pos
10025 target (js2-parse-member-expr)
10026 end (js2-node-end target)
10027 pn (make-js2-new-node :pos pos
10028 :target target
10029 :len (- end pos)))
10030 (js2-highlight-function-call (js2-current-token))
10031 (js2-node-add-children pn target)
10032 (when (js2-match-token js2-LP)
10033 ;; Add the arguments to pn, if any are supplied.
10034 (setf beg pos ; start of "new" keyword
10035 pos (js2-current-token-beg)
10036 args (nreverse (js2-parse-argument-list))
10037 (js2-new-node-args pn) args
10038 end (js2-current-token-end)
10039 (js2-new-node-lp pn) (- pos beg)
10040 (js2-new-node-rp pn) (- end 1 beg))
10041 (apply #'js2-node-add-children pn args))
10042 (when (and js2-allow-rhino-new-expr-initializer
10043 (js2-match-token js2-LC))
10044 (setf init (js2-parse-object-literal)
10045 end (js2-node-end init)
10046 (js2-new-node-initializer pn) init)
10047 (js2-node-add-children pn init))
10048 (setf (js2-node-len pn) (- end beg))) ; end outer if
10049 (js2-parse-member-expr-tail allow-call-syntax pn)))
10050
10051 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10052 "Parse a chain of property/array accesses or function calls.
10053 Includes parsing for E4X operators like `..' and `.@'.
10054 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10055 Returns an expression tree that includes PN, the parent node."
10056 (let (tt
10057 (continue t))
10058 (while continue
10059 (setq tt (js2-get-token))
10060 (cond
10061 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10062 (setq pn (js2-parse-property-access tt pn)))
10063 ((= tt js2-DOTQUERY)
10064 (setq pn (js2-parse-dot-query pn)))
10065 ((= tt js2-LB)
10066 (setq pn (js2-parse-element-get pn)))
10067 ((= tt js2-LP)
10068 (js2-unget-token)
10069 (if allow-call-syntax
10070 (setq pn (js2-parse-function-call pn))
10071 (setq continue nil)))
10072 ((= tt js2-TEMPLATE_HEAD)
10073 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10074 ((= tt js2-NO_SUBS_TEMPLATE)
10075 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10076 (t
10077 (js2-unget-token)
10078 (setq continue nil)))
10079 (if (>= js2-highlight-level 2)
10080 (js2-parse-highlight-member-expr-node pn)))
10081 pn))
10082
10083 (defun js2-parse-tagged-template (tag-node tpl-node)
10084 "Parse tagged template expression."
10085 (let* ((beg (js2-node-pos tag-node))
10086 (pn (make-js2-tagged-template-node :beg beg
10087 :len (- (js2-current-token-end) beg)
10088 :tag tag-node
10089 :template tpl-node)))
10090 (js2-node-add-children pn tag-node tpl-node)
10091 pn))
10092
10093 (defun js2-parse-dot-query (pn)
10094 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10095 Last token parsed must be `js2-DOTQUERY'."
10096 (let ((pos (js2-node-pos pn))
10097 op-pos expr end)
10098 (js2-must-have-xml)
10099 (js2-set-requires-activation)
10100 (setq op-pos (js2-current-token-beg)
10101 expr (js2-parse-expr)
10102 end (js2-node-end expr)
10103 pn (make-js2-xml-dot-query-node :left pn
10104 :pos pos
10105 :op-pos op-pos
10106 :right expr))
10107 (js2-node-add-children pn
10108 (js2-xml-dot-query-node-left pn)
10109 (js2-xml-dot-query-node-right pn))
10110 (if (js2-must-match js2-RP "msg.no.paren")
10111 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10112 end (js2-current-token-end)))
10113 (setf (js2-node-len pn) (- end pos))
10114 pn))
10115
10116 (defun js2-parse-element-get (pn)
10117 "Parse an element-get expression, e.g. foo[bar].
10118 Last token parsed must be `js2-RB'."
10119 (let ((lb (js2-current-token-beg))
10120 (pos (js2-node-pos pn))
10121 rb expr)
10122 (setq expr (js2-parse-expr))
10123 (if (js2-must-match js2-RB "msg.no.bracket.index")
10124 (setq rb (js2-current-token-beg)))
10125 (setq pn (make-js2-elem-get-node :target pn
10126 :pos pos
10127 :element expr
10128 :lb (js2-relpos lb pos)
10129 :rb (js2-relpos rb pos)
10130 :len (- (js2-current-token-end) pos)))
10131 (js2-node-add-children pn
10132 (js2-elem-get-node-target pn)
10133 (js2-elem-get-node-element pn))
10134 pn))
10135
10136 (defun js2-highlight-function-call (token)
10137 (when (eq (js2-token-type token) js2-NAME)
10138 (js2-record-face 'js2-function-call token)))
10139
10140 (defun js2-parse-function-call (pn)
10141 (js2-highlight-function-call (js2-current-token))
10142 (js2-get-token)
10143 (let (args
10144 (pos (js2-node-pos pn)))
10145 (setq pn (make-js2-call-node :pos pos
10146 :target pn
10147 :lp (- (js2-current-token-beg) pos)))
10148 (js2-node-add-children pn (js2-call-node-target pn))
10149 ;; Add the arguments to pn, if any are supplied.
10150 (setf args (nreverse (js2-parse-argument-list))
10151 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10152 (js2-call-node-args pn) args)
10153 (apply #'js2-node-add-children pn args)
10154 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10155 pn))
10156
10157 (defun js2-parse-property-access (tt pn)
10158 "Parse a property access, XML descendants access, or XML attr access."
10159 (let ((member-type-flags 0)
10160 (dot-pos (js2-current-token-beg))
10161 (dot-len (if (= tt js2-DOTDOT) 2 1))
10162 name
10163 ref ; right side of . or .. operator
10164 result)
10165 (when (= tt js2-DOTDOT)
10166 (js2-must-have-xml)
10167 (setq member-type-flags js2-descendants-flag))
10168 (if (not js2-compiler-xml-available)
10169 (progn
10170 (js2-must-match-prop-name "msg.no.name.after.dot")
10171 (setq name (js2-create-name-node t js2-GETPROP)
10172 result (make-js2-prop-get-node :left pn
10173 :pos (js2-current-token-beg)
10174 :right name
10175 :len (js2-current-token-len)))
10176 (js2-node-add-children result pn name)
10177 result)
10178 ;; otherwise look for XML operators
10179 (setf result (if (= tt js2-DOT)
10180 (make-js2-prop-get-node)
10181 (make-js2-infix-node :type js2-DOTDOT))
10182 (js2-node-pos result) (js2-node-pos pn)
10183 (js2-infix-node-op-pos result) dot-pos
10184 (js2-infix-node-left result) pn ; do this after setting position
10185 tt (js2-get-prop-name-token))
10186 (cond
10187 ;; handles: name, ns::name, ns::*, ns::[expr]
10188 ((= tt js2-NAME)
10189 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10190 ;; handles: *, *::name, *::*, *::[expr]
10191 ((= tt js2-MUL)
10192 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10193 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10194 ((= tt js2-XMLATTR)
10195 (setq result (js2-parse-attribute-access)))
10196 (t
10197 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10198 (if ref
10199 (setf (js2-node-len result) (- (js2-node-end ref)
10200 (js2-node-pos result))
10201 (js2-infix-node-right result) ref))
10202 (if (js2-infix-node-p result)
10203 (js2-node-add-children result
10204 (js2-infix-node-left result)
10205 (js2-infix-node-right result)))
10206 result)))
10207
10208 (defun js2-parse-attribute-access ()
10209 "Parse an E4X XML attribute expression.
10210 This includes expressions of the forms:
10211
10212 @attr @ns::attr @ns::*
10213 @* @*::attr @*::*
10214 @[expr] @*::[expr] @ns::[expr]
10215
10216 Called if we peeked an '@' token."
10217 (let ((tt (js2-get-prop-name-token))
10218 (at-pos (js2-current-token-beg)))
10219 (cond
10220 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10221 ((= tt js2-NAME)
10222 (js2-parse-property-name at-pos nil 0))
10223 ;; handles: @*, @*::name, @*::*, @*::[expr]
10224 ((= tt js2-MUL)
10225 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10226 ;; handles @[expr]
10227 ((= tt js2-LB)
10228 (js2-parse-xml-elem-ref at-pos))
10229 (t
10230 (js2-report-error "msg.no.name.after.xmlAttr")
10231 ;; Avoid cascaded errors that happen if we make an error node here.
10232 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10233
10234 (defun js2-parse-property-name (at-pos s member-type-flags)
10235 "Check if :: follows name in which case it becomes qualified name.
10236
10237 AT-POS is a natural number if we just read an '@' token, else nil.
10238 S is the name or string that was matched: an identifier, 'throw' or '*'.
10239 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10240
10241 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10242 operator, or the name is followed by ::. For a plain name, returns a
10243 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10244 (let ((pos (or at-pos (js2-current-token-beg)))
10245 colon-pos
10246 (name (js2-create-name-node t (js2-current-token-type) s))
10247 ns tt pn)
10248 (catch 'return
10249 (when (js2-match-token js2-COLONCOLON)
10250 (setq ns name
10251 colon-pos (js2-current-token-beg)
10252 tt (js2-get-prop-name-token))
10253 (cond
10254 ;; handles name::name
10255 ((= tt js2-NAME)
10256 (setq name (js2-create-name-node)))
10257 ;; handles name::*
10258 ((= tt js2-MUL)
10259 (setq name (js2-create-name-node nil nil "*")))
10260 ;; handles name::[expr]
10261 ((= tt js2-LB)
10262 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10263 (t
10264 (js2-report-error "msg.no.name.after.coloncolon"))))
10265 (if (and (null ns) (zerop member-type-flags))
10266 name
10267 (prog1
10268 (setq pn
10269 (make-js2-xml-prop-ref-node :pos pos
10270 :len (- (js2-node-end name) pos)
10271 :at-pos at-pos
10272 :colon-pos colon-pos
10273 :propname name))
10274 (js2-node-add-children pn name))))))
10275
10276 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10277 "Parse the [expr] portion of an xml element reference.
10278 For instance, @[expr], @*::[expr], or ns::[expr]."
10279 (let* ((lb (js2-current-token-beg))
10280 (pos (or at-pos lb))
10281 rb
10282 (expr (js2-parse-expr))
10283 (end (js2-node-end expr))
10284 pn)
10285 (if (js2-must-match js2-RB "msg.no.bracket.index")
10286 (setq rb (js2-current-token-beg)
10287 end (js2-current-token-end)))
10288 (prog1
10289 (setq pn
10290 (make-js2-xml-elem-ref-node :pos pos
10291 :len (- end pos)
10292 :namespace namespace
10293 :colon-pos colon-pos
10294 :at-pos at-pos
10295 :expr expr
10296 :lb (js2-relpos lb pos)
10297 :rb (js2-relpos rb pos)))
10298 (js2-node-add-children pn namespace expr))))
10299
10300 (defun js2-parse-destruct-primary-expr ()
10301 (let ((js2-is-in-destructuring t))
10302 (js2-parse-primary-expr)))
10303
10304 (defun js2-parse-primary-expr ()
10305 "Parse a literal (leaf) expression of some sort.
10306 Includes complex literals such as functions, object-literals,
10307 array-literals, array comprehensions and regular expressions."
10308 (let (tt node)
10309 (setq tt (js2-current-token-type))
10310 (cond
10311 ((= tt js2-CLASS)
10312 (js2-parse-class-expr))
10313 ((= tt js2-FUNCTION)
10314 (js2-parse-function-expr))
10315 ((js2-match-async-function)
10316 (js2-parse-function-expr t))
10317 ((= tt js2-LB)
10318 (js2-parse-array-comp-or-literal))
10319 ((= tt js2-LC)
10320 (js2-parse-object-literal))
10321 ((= tt js2-LET)
10322 (js2-parse-let (js2-current-token-beg)))
10323 ((= tt js2-LP)
10324 (js2-parse-paren-expr-or-generator-comp))
10325 ((= tt js2-XMLATTR)
10326 (js2-must-have-xml)
10327 (js2-parse-attribute-access))
10328 ((= tt js2-NAME)
10329 (js2-parse-name tt))
10330 ((= tt js2-NUMBER)
10331 (setq node (make-js2-number-node))
10332 (when (and js2-in-use-strict-directive
10333 (= (js2-number-node-num-base node) 8))
10334 (js2-report-error "msg.no.octal.strict"))
10335 node)
10336 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10337 (make-js2-string-node :type tt))
10338 ((= tt js2-TEMPLATE_HEAD)
10339 (js2-parse-template-literal))
10340 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10341 ;; Got / or /= which in this context means a regexp literal
10342 (let ((px-pos (js2-current-token-beg))
10343 (flags (js2-read-regexp tt))
10344 (end (js2-current-token-end)))
10345 (prog1
10346 (make-js2-regexp-node :pos px-pos
10347 :len (- end px-pos)
10348 :value (js2-current-token-string)
10349 :flags flags)
10350 (js2-set-face px-pos end 'font-lock-string-face 'record)
10351 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10352 ((or (= tt js2-NULL)
10353 (= tt js2-THIS)
10354 (= tt js2-SUPER)
10355 (= tt js2-FALSE)
10356 (= tt js2-TRUE))
10357 (make-js2-keyword-node :type tt))
10358 ((= tt js2-TRIPLEDOT)
10359 ;; Likewise, only valid in an arrow function with a rest param.
10360 (if (and (js2-match-token js2-NAME)
10361 (js2-match-token js2-RP)
10362 (eq (js2-peek-token) js2-ARROW))
10363 (progn
10364 (js2-unget-token) ; Put back the right paren.
10365 ;; See the previous case.
10366 (make-js2-keyword-node :type js2-NULL))
10367 (js2-report-error "msg.syntax")
10368 (make-js2-error-node)))
10369 ((= tt js2-RESERVED)
10370 (js2-report-error "msg.reserved.id")
10371 (make-js2-name-node))
10372 ((= tt js2-ERROR)
10373 ;; the scanner or one of its subroutines reported the error.
10374 (make-js2-error-node))
10375 ((= tt js2-EOF)
10376 (let* ((px-pos (point-at-bol))
10377 (len (- js2-ts-cursor px-pos)))
10378 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10379 (make-js2-error-node :pos (1- js2-ts-cursor)))
10380 (t
10381 (js2-report-error "msg.syntax")
10382 (make-js2-error-node)))))
10383
10384 (defun js2-parse-template-literal ()
10385 (let ((beg (js2-current-token-beg))
10386 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10387 (tt js2-TEMPLATE_HEAD))
10388 (while (eq tt js2-TEMPLATE_HEAD)
10389 (push (js2-parse-expr) kids)
10390 (js2-must-match js2-RC "msg.syntax")
10391 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10392 (push (make-js2-string-node :type tt) kids))
10393 (setq kids (nreverse kids))
10394 (let ((tpl (make-js2-template-node :beg beg
10395 :len (- (js2-current-token-end) beg)
10396 :kids kids)))
10397 (apply #'js2-node-add-children tpl kids)
10398 tpl)))
10399
10400 (defun js2-parse-name (_tt)
10401 (let ((name (js2-current-token-string))
10402 node)
10403 (setq node (if js2-compiler-xml-available
10404 (js2-parse-property-name nil name 0)
10405 (js2-create-name-node 'check-activation nil name)))
10406 (if js2-highlight-external-variables
10407 (js2-record-name-node node))
10408 node))
10409
10410 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10411 (js2-add-strict-warning
10412 msg nil
10413 ;; back up from comma to beginning of line or array/objlit
10414 (max (if elems
10415 (js2-node-pos (car elems))
10416 pos)
10417 (save-excursion
10418 (goto-char comma-pos)
10419 (back-to-indentation)
10420 (point)))
10421 comma-pos))
10422
10423 (defun js2-parse-array-comp-or-literal ()
10424 (let ((pos (js2-current-token-beg)))
10425 (if (and (>= js2-language-version 200)
10426 (js2-match-token js2-FOR))
10427 (js2-parse-array-comp pos)
10428 (js2-parse-array-literal pos))))
10429
10430 (defun js2-parse-array-literal (pos)
10431 (let ((after-lb-or-comma t)
10432 after-comma tt elems pn
10433 (continue t))
10434 (unless js2-is-in-destructuring
10435 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10436 (while continue
10437 (setq tt (js2-get-token))
10438 (cond
10439 ;; comma
10440 ((= tt js2-COMMA)
10441 (setq after-comma (js2-current-token-end))
10442 (if (not after-lb-or-comma)
10443 (setq after-lb-or-comma t)
10444 (push nil elems)))
10445 ;; end of array
10446 ((or (= tt js2-RB)
10447 (= tt js2-EOF)) ; prevent infinite loop
10448 (if (= tt js2-EOF)
10449 (js2-report-error "msg.no.bracket.arg" nil pos))
10450 (when (and after-comma (< js2-language-version 170))
10451 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10452 pos (remove nil elems) after-comma))
10453 (setq continue nil
10454 pn (make-js2-array-node :pos pos
10455 :len (- js2-ts-cursor pos)
10456 :elems (nreverse elems)))
10457 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10458 ;; destructuring binding
10459 (js2-is-in-destructuring
10460 (push (cond
10461 ((and (= tt js2-NAME)
10462 (= js2-ASSIGN (js2-peek-token)))
10463 ;; a=defaultValue
10464 (js2-parse-initialized-binding (js2-parse-name js2-NAME)))
10465 ((or (= tt js2-LC)
10466 (= tt js2-LB)
10467 (= tt js2-NAME))
10468 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10469 (js2-parse-destruct-primary-expr))
10470 ;; invalid pattern
10471 (t
10472 (js2-report-error "msg.bad.var")
10473 (make-js2-error-node)))
10474 elems)
10475 (setq after-lb-or-comma nil
10476 after-comma nil))
10477 ;; array comp
10478 ((and (>= js2-language-version 170)
10479 (= tt js2-FOR) ; check for array comprehension
10480 (not after-lb-or-comma) ; "for" can't follow a comma
10481 elems ; must have at least 1 element
10482 (not (cdr elems))) ; but no 2nd element
10483 (js2-unget-token)
10484 (setf continue nil
10485 pn (js2-parse-legacy-array-comp (car elems) pos)))
10486 ;; another element
10487 (t
10488 (unless after-lb-or-comma
10489 (js2-report-error "msg.no.bracket.arg"))
10490 (if (and (= tt js2-TRIPLEDOT)
10491 (>= js2-language-version 200))
10492 ;; spread operator
10493 (push (js2-make-unary tt 'js2-parse-assign-expr)
10494 elems)
10495 (js2-unget-token)
10496 (push (js2-parse-assign-expr) elems))
10497 (setq after-lb-or-comma nil
10498 after-comma nil))))
10499 (unless js2-is-in-destructuring
10500 (js2-pop-scope))
10501 pn))
10502
10503 (defun js2-parse-legacy-array-comp (expr pos)
10504 "Parse a legacy array comprehension (JavaScript 1.7).
10505 EXPR is the first expression after the opening left-bracket.
10506 POS is the beginning of the LB token preceding EXPR.
10507 We should have just parsed the 'for' keyword before calling this function."
10508 (let ((current-scope js2-current-scope)
10509 loops first filter result)
10510 (unwind-protect
10511 (progn
10512 (while (js2-match-token js2-FOR)
10513 (let ((loop (make-js2-comp-loop-node)))
10514 (js2-push-scope loop)
10515 (push loop loops)
10516 (js2-parse-comp-loop loop)))
10517 ;; First loop takes expr scope's parent.
10518 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10519 (js2-scope-parent-scope current-scope))
10520 ;; Set expr scope's parent to the last loop.
10521 (setf (js2-scope-parent-scope current-scope) (car loops))
10522 (if (/= (js2-get-token) js2-IF)
10523 (js2-unget-token)
10524 (setq filter (js2-parse-condition))))
10525 (dotimes (_ (1- (length loops)))
10526 (js2-pop-scope)))
10527 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10528 (setq result (make-js2-comp-node :pos pos
10529 :len (- js2-ts-cursor pos)
10530 :result expr
10531 :loops (nreverse loops)
10532 :filters (and filter (list (car filter)))
10533 :form 'LEGACY_ARRAY))
10534 ;; Set comp loop's parent to the last loop.
10535 ;; TODO: Get rid of the bogus expr scope.
10536 (setf (js2-scope-parent-scope result) first)
10537 (apply #'js2-node-add-children result expr (car filter)
10538 (js2-comp-node-loops result))
10539 result))
10540
10541 (defun js2-parse-array-comp (pos)
10542 "Parse an ES6 array comprehension.
10543 POS is the beginning of the LB token.
10544 We should have just parsed the 'for' keyword before calling this function."
10545 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10546 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10547 pn))
10548
10549 (defun js2-parse-generator-comp (pos)
10550 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10551 (js2-current-script-or-fn
10552 (make-js2-function-node :generator-type 'COMPREHENSION))
10553 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10554 (js2-must-match js2-RP "msg.no.paren" pos)
10555 pn))
10556
10557 (defun js2-parse-comprehension (pos form)
10558 (let (loops filters expr result last)
10559 (unwind-protect
10560 (progn
10561 (js2-unget-token)
10562 (while (js2-match-token js2-FOR)
10563 (let ((loop (make-js2-comp-loop-node)))
10564 (js2-push-scope loop)
10565 (push loop loops)
10566 (js2-parse-comp-loop loop)))
10567 (while (js2-match-token js2-IF)
10568 (push (car (js2-parse-condition)) filters))
10569 (setq expr (js2-parse-assign-expr))
10570 (setq last (car loops)))
10571 (dolist (_ loops)
10572 (js2-pop-scope)))
10573 (setq result (make-js2-comp-node :pos pos
10574 :len (- js2-ts-cursor pos)
10575 :result expr
10576 :loops (nreverse loops)
10577 :filters (nreverse filters)
10578 :form form))
10579 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10580 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10581 (setf (js2-scope-parent-scope result) last)
10582 result))
10583
10584 (defun js2-parse-comp-loop (pn &optional only-of-p)
10585 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10586 The current token should be the initial FOR.
10587 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10588 (let ((pos (js2-comp-loop-node-pos pn))
10589 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10590 (when (and (not only-of-p) (js2-match-token js2-NAME))
10591 (if (string= (js2-current-token-string) "each")
10592 (progn
10593 (setq foreach-p t
10594 each-pos (- (js2-current-token-beg) pos)) ; relative
10595 (js2-record-face 'font-lock-keyword-face))
10596 (js2-report-error "msg.no.paren.for")))
10597 (if (js2-must-match js2-LP "msg.no.paren.for")
10598 (setq lp (- (js2-current-token-beg) pos)))
10599 (setq tt (js2-peek-token))
10600 (cond
10601 ((or (= tt js2-LB)
10602 (= tt js2-LC))
10603 (js2-get-token)
10604 (setq iter (js2-parse-destruct-primary-expr))
10605 (js2-define-destruct-symbols iter js2-LET
10606 'font-lock-variable-name-face t))
10607 ((js2-match-token js2-NAME)
10608 (setq iter (js2-create-name-node)))
10609 (t
10610 (js2-report-error "msg.bad.var")))
10611 ;; Define as a let since we want the scope of the variable to
10612 ;; be restricted to the array comprehension
10613 (if (js2-name-node-p iter)
10614 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10615 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10616 (and (>= js2-language-version 200)
10617 (js2-match-contextual-kwd "of")
10618 (setq forof-p t)))
10619 (setq in-pos (- (js2-current-token-beg) pos))
10620 (js2-report-error "msg.in.after.for.name"))
10621 (setq obj (js2-parse-expr))
10622 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10623 (setq rp (- (js2-current-token-beg) pos)))
10624 (setf (js2-node-pos pn) pos
10625 (js2-node-len pn) (- js2-ts-cursor pos)
10626 (js2-comp-loop-node-iterator pn) iter
10627 (js2-comp-loop-node-object pn) obj
10628 (js2-comp-loop-node-in-pos pn) in-pos
10629 (js2-comp-loop-node-each-pos pn) each-pos
10630 (js2-comp-loop-node-foreach-p pn) foreach-p
10631 (js2-comp-loop-node-forof-p pn) forof-p
10632 (js2-comp-loop-node-lp pn) lp
10633 (js2-comp-loop-node-rp pn) rp)
10634 (js2-node-add-children pn iter obj)
10635 pn))
10636
10637 (defun js2-parse-class-stmt ()
10638 (let ((pos (js2-current-token-beg))
10639 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10640 (name (js2-create-name-node t)))
10641 (js2-set-face (js2-node-pos name) (js2-node-end name)
10642 'font-lock-function-name-face 'record)
10643 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10644 (js2-define-symbol js2-FUNCTION
10645 (js2-name-node-name name)
10646 node)
10647 node)))
10648
10649 (defun js2-parse-class-expr ()
10650 (let ((pos (js2-current-token-beg))
10651 name)
10652 (when (js2-match-token js2-NAME)
10653 (setq name (js2-create-name-node t)))
10654 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10655
10656 (defun js2-parse-class (pos form name)
10657 ;; class X [extends ...] {
10658 (let (pn elems extends)
10659 (if (js2-match-token js2-EXTENDS)
10660 (if (= (js2-peek-token) js2-LC)
10661 (js2-report-error "msg.missing.extends")
10662 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10663 (setq extends (js2-parse-assign-expr))
10664 (if (not extends)
10665 (js2-report-error "msg.bad.extends"))))
10666 (js2-must-match js2-LC "msg.no.brace.class")
10667 (setq elems (js2-parse-object-literal-elems t)
10668 pn (make-js2-class-node :pos pos
10669 :len (- js2-ts-cursor pos)
10670 :form form
10671 :name name
10672 :extends extends
10673 :elems elems))
10674 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10675 pn))
10676
10677 (defun js2-parse-object-literal ()
10678 (let* ((pos (js2-current-token-beg))
10679 (elems (js2-parse-object-literal-elems))
10680 (result (make-js2-object-node :pos pos
10681 :len (- js2-ts-cursor pos)
10682 :elems elems)))
10683 (apply #'js2-node-add-children result (js2-object-node-elems result))
10684 result))
10685
10686 (defun js2-property-key-string (property-node)
10687 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10688 `js2-method-node') as a string, or nil if it can't be
10689 represented as a string (e.g., the key is computed by an
10690 expression)."
10691 (let ((key (js2-infix-node-left property-node)))
10692 (when (js2-computed-prop-name-node-p key)
10693 (setq key (js2-computed-prop-name-node-expr key)))
10694 (cond
10695 ((js2-name-node-p key)
10696 (js2-name-node-name key))
10697 ((js2-string-node-p key)
10698 (js2-string-node-value key))
10699 ((js2-number-node-p key)
10700 (js2-number-node-value key)))))
10701
10702 (defun js2-parse-object-literal-elems (&optional class-p)
10703 (let ((pos (js2-current-token-beg))
10704 (static nil)
10705 (continue t)
10706 tt elems elem
10707 elem-key-string previous-elem-key-string
10708 after-comma previous-token)
10709 (while continue
10710 (setq tt (js2-get-prop-name-token)
10711 static nil
10712 elem nil
10713 previous-token nil)
10714 ;; Handle 'static' keyword only if we're in a class
10715 (when (and class-p (= js2-NAME tt)
10716 (string= "static" (js2-current-token-string)))
10717 (js2-record-face 'font-lock-keyword-face)
10718 (setq static t
10719 tt (js2-get-prop-name-token)))
10720 ;; Handle generator * before the property name for in-line functions
10721 (when (and (>= js2-language-version 200)
10722 (= js2-MUL tt))
10723 (setq previous-token (js2-current-token)
10724 tt (js2-get-prop-name-token)))
10725 ;; Handle 'get' or 'set' keywords
10726 (let ((prop (js2-current-token-string)))
10727 (when (and (>= js2-language-version 200)
10728 (= js2-NAME tt)
10729 (or (string= prop "get")
10730 (string= prop "set"))
10731 (member (js2-peek-token)
10732 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10733 (setq previous-token (js2-current-token)
10734 tt (js2-get-prop-name-token))))
10735 (cond
10736 ;; Found a property (of any sort)
10737 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10738 (setq after-comma nil
10739 elem (js2-parse-named-prop tt pos previous-token))
10740 (if (and (null elem)
10741 (not js2-recover-from-parse-errors))
10742 (setq continue nil)))
10743 ;; Break out of loop, and handle trailing commas.
10744 ((or (= tt js2-RC)
10745 (= tt js2-EOF))
10746 (js2-unget-token)
10747 (setq continue nil)
10748 (if after-comma
10749 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10750 pos elems after-comma)))
10751 ;; Skip semicolons in a class body
10752 ((and class-p
10753 (= tt js2-SEMI))
10754 nil)
10755 (t
10756 (js2-report-error "msg.bad.prop")
10757 (unless js2-recover-from-parse-errors
10758 (setq continue nil)))) ; end switch
10759 ;; Handle static for classes' codegen.
10760 (if static
10761 (if elem (js2-node-set-prop elem 'STATIC t)
10762 (js2-report-error "msg.unexpected.static")))
10763 ;; Handle commas, depending on class-p.
10764 (let ((tok (js2-get-prop-name-token)))
10765 (if (eq tok js2-COMMA)
10766 (if class-p
10767 (js2-report-error "msg.class.unexpected.comma")
10768 (setq after-comma (js2-current-token-end)))
10769 (js2-unget-token)
10770 (unless class-p (setq continue nil))))
10771 (when elem
10772 (when (and js2-in-use-strict-directive
10773 (setq elem-key-string (js2-property-key-string elem))
10774 (cl-some
10775 (lambda (previous-elem)
10776 (and (setq previous-elem-key-string
10777 (js2-property-key-string previous-elem))
10778 ;; Check if the property is a duplicate.
10779 (string= previous-elem-key-string elem-key-string)
10780 ;; But make an exception for getter / setter pairs.
10781 (not (and (js2-method-node-p elem)
10782 (js2-method-node-p previous-elem)
10783 (let ((type (js2-node-get-prop (js2-method-node-right elem) 'METHOD_TYPE))
10784 (previous-type (js2-node-get-prop (js2-method-node-right previous-elem) 'METHOD_TYPE)))
10785 (and (member type '(GET SET))
10786 (member previous-type '(GET SET))
10787 (not (eq type previous-type))))))))
10788 elems))
10789 (js2-report-error "msg.dup.obj.lit.prop.strict"
10790 elem-key-string
10791 (js2-node-abs-pos (js2-infix-node-left elem))
10792 (js2-node-len (js2-infix-node-left elem))))
10793 ;; Append any parsed element.
10794 (push elem elems))) ; end loop
10795 (js2-must-match js2-RC "msg.no.brace.prop")
10796 (nreverse elems)))
10797
10798 (defun js2-parse-named-prop (tt pos previous-token)
10799 "Parse a name, string, or getter/setter object property.
10800 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10801 (let ((key (js2-parse-prop-name tt))
10802 (prop (and previous-token (js2-token-string previous-token)))
10803 (property-type (when previous-token
10804 (if (= (js2-token-type previous-token) js2-MUL)
10805 "*"
10806 (js2-token-string previous-token)))))
10807 (when (or (string= prop "get")
10808 (string= prop "set"))
10809 (js2-set-face (js2-token-beg previous-token)
10810 (js2-token-end previous-token)
10811 'font-lock-keyword-face 'record)) ; get/set
10812 (cond
10813 ;; method definition: {f() {...}}
10814 ((and (= (js2-peek-token) js2-LP)
10815 (>= js2-language-version 200))
10816 (when (js2-name-node-p key) ; highlight function name properties
10817 (js2-record-face 'font-lock-function-name-face))
10818 (js2-parse-method-prop pos key property-type))
10819 ;; binding element with initializer
10820 ((and (= (js2-peek-token) js2-ASSIGN)
10821 (>= js2-language-version 200))
10822 (if (not js2-is-in-destructuring)
10823 (js2-report-error "msg.init.no.destruct"))
10824 (js2-parse-initialized-binding key))
10825 ;; regular prop
10826 (t
10827 (let ((beg (js2-current-token-beg))
10828 (end (js2-current-token-end))
10829 (expr (js2-parse-plain-property key)))
10830 (when (and (= tt js2-NAME)
10831 (not js2-is-in-destructuring)
10832 js2-highlight-external-variables
10833 (js2-node-get-prop expr 'SHORTHAND))
10834 (js2-record-name-node key))
10835 (js2-set-face beg end
10836 (if (js2-function-node-p
10837 (js2-object-prop-node-right expr))
10838 'font-lock-function-name-face
10839 'js2-object-property)
10840 'record)
10841 expr)))))
10842
10843 (defun js2-parse-initialized-binding (name)
10844 "Parse a `SingleNameBinding' with initializer.
10845
10846 `name' is the `BindingIdentifier'."
10847 (when (js2-match-token js2-ASSIGN)
10848 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10849
10850 (defun js2-parse-prop-name (tt)
10851 (cond
10852 ;; Literal string keys: {'foo': 'bar'}
10853 ((= tt js2-STRING)
10854 (make-js2-string-node))
10855 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10856 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10857 ((and (= tt js2-LB)
10858 (>= js2-language-version 200))
10859 (make-js2-computed-prop-name-node
10860 :expr (prog1 (js2-parse-assign-expr)
10861 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10862 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10863 ((= tt js2-NUMBER)
10864 (make-js2-number-node))
10865 ;; Unquoted names: {foo: 12}
10866 ((= tt js2-NAME)
10867 (js2-create-name-node))
10868 ;; Anything else is an error
10869 (t (js2-report-error "msg.bad.prop"))))
10870
10871 (defun js2-parse-plain-property (prop)
10872 "Parse a non-getter/setter property in an object literal.
10873 PROP is the node representing the property: a number, name,
10874 string or expression."
10875 (let* ((tt (js2-get-token))
10876 (pos (js2-node-pos prop))
10877 colon expr result)
10878 (cond
10879 ;; Abbreviated property, as in {foo, bar}
10880 ((and (>= js2-language-version 200)
10881 (or (= tt js2-COMMA)
10882 (= tt js2-RC))
10883 (not (js2-number-node-p prop)))
10884 (js2-unget-token)
10885 (setq result (make-js2-object-prop-node
10886 :pos pos
10887 :left prop
10888 :right prop
10889 :op-pos (js2-current-token-len)))
10890 (js2-node-add-children result prop)
10891 (js2-node-set-prop result 'SHORTHAND t)
10892 result)
10893 ;; Normal property
10894 (t
10895 (if (= tt js2-COLON)
10896 (setq colon (- (js2-current-token-beg) pos)
10897 expr (js2-parse-assign-expr))
10898 (js2-report-error "msg.no.colon.prop")
10899 (setq expr (make-js2-error-node)))
10900 (setq result (make-js2-object-prop-node
10901 :pos pos
10902 ;; don't include last consumed token in length
10903 :len (- (+ (js2-node-pos expr)
10904 (js2-node-len expr))
10905 pos)
10906 :left prop
10907 :right expr
10908 :op-pos colon))
10909 (js2-node-add-children result prop expr)
10910 result))))
10911
10912 (defun js2-parse-method-prop (pos prop type-string)
10913 "Parse method property in an object literal or a class body.
10914 JavaScript syntax is:
10915
10916 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...} }
10917
10918 and expression closure style is also supported
10919
10920 { get foo() x, set foo(x) _x = x }
10921
10922 POS is the start position of the `get' or `set' keyword.
10923 PROP is the `js2-name-node' representing the property name.
10924 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10925 (let ((type (or (cdr (assoc type-string '(("get" . GET)
10926 ("set" . SET))))
10927 'FUNCTION))
10928 result end
10929 (fn (js2-parse-function-expr)))
10930 ;; it has to be an anonymous function, as we already parsed the name
10931 (if (/= (js2-node-type fn) js2-FUNCTION)
10932 (js2-report-error "msg.bad.prop")
10933 (if (cl-plusp (length (js2-function-name fn)))
10934 (js2-report-error "msg.bad.prop")))
10935 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10936 (when (string= type-string "*")
10937 (setf (js2-function-node-generator-type fn) 'STAR))
10938 (setq end (js2-node-end fn)
10939 result (make-js2-method-node :pos pos
10940 :len (- end pos)
10941 :left prop
10942 :right fn))
10943 (js2-node-add-children result prop fn)
10944 result))
10945
10946 (defun js2-create-name-node (&optional check-activation-p token string)
10947 "Create a name node using the current token and, optionally, STRING.
10948 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10949 (let* ((beg (js2-current-token-beg))
10950 (tt (js2-current-token-type))
10951 (s (or string
10952 (if (= js2-NAME tt)
10953 (js2-current-token-string)
10954 (js2-tt-name tt))))
10955 name)
10956 (setq name (make-js2-name-node :pos beg
10957 :name s
10958 :len (length s)))
10959 (if check-activation-p
10960 (js2-check-activation-name s (or token js2-NAME)))
10961 name))
10962
10963 ;;; Use AST to extract semantic information
10964
10965 (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
10966 "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
10967 (let ((idx 0) elems (rlt hardcoded-array-index))
10968 (setq elems (js2-array-node-elems array-node))
10969 (if (and elem (not hardcoded-array-index))
10970 (setq rlt (catch 'nth-elt
10971 (dolist (x elems)
10972 ;; We know the ELEM does belong to ARRAY-NODE,
10973 (if (eq elem x) (throw 'nth-elt idx))
10974 (setq idx (1+ idx)))
10975 0)))
10976 (format "[%s]" rlt)))
10977
10978 (defun js2-print-json-path (&optional hardcoded-array-index)
10979 "Print the path to the JSON value under point, and save it in the kill ring.
10980 If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
10981 (interactive "P")
10982 (let (previous-node current-node
10983 key-name
10984 rlt)
10985
10986 ;; The `js2-node-at-point' starts scanning from AST root node.
10987 ;; So there is no way to optimize it.
10988 (setq current-node (js2-node-at-point))
10989
10990 (while (not (js2-ast-root-p current-node))
10991 (cond
10992 ;; JSON property node
10993 ((js2-object-prop-node-p current-node)
10994 (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
10995 (if rlt (setq rlt (concat "." key-name rlt))
10996 (setq rlt (concat "." key-name))))
10997
10998 ;; Array node
10999 ((or (js2-array-node-p current-node))
11000 (setq rlt (concat (js2-get-element-index-from-array-node previous-node
11001 current-node
11002 hardcoded-array-index)
11003 rlt)))
11004
11005 ;; Other nodes are ignored
11006 (t))
11007
11008 ;; current node is archived
11009 (setq previous-node current-node)
11010 ;; Get parent node and continue the loop
11011 (setq current-node (js2-node-parent current-node)))
11012
11013 (cond
11014 (rlt
11015 ;; Clean the final result
11016 (setq rlt (replace-regexp-in-string "^\\." "" rlt))
11017 (kill-new rlt)
11018 (message "%s => kill-ring" rlt))
11019 (t
11020 (message "No JSON path found!")))
11021
11022 rlt))
11023
11024 ;;; Indentation support (bouncing)
11025
11026 ;; In recent-enough Emacs, we reuse the indentation code from
11027 ;; `js-mode'. To continue support for the older versions, some code
11028 ;; that was here previously was moved to `js2-old-indent.el'.
11029
11030 ;; Whichever indenter is used, it's often "wrong", however, and needs
11031 ;; to be overridden. The right long-term solution is probably to
11032 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
11033 ;; of coding. Even when a parse tree from `js2-parse' is present,
11034 ;; which is not true at the moment the user is typing, computing
11035 ;; indentation is still thousands of lines of code to handle every
11036 ;; possible syntactic edge case.
11037
11038 ;; In the meantime, the compromise solution is that we offer a "bounce
11039 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
11040 ;; current line indent among various likely guess points. This approach
11041 ;; is far from perfect, but should at least make it slightly easier to
11042 ;; move the line towards its desired indentation when manually
11043 ;; overriding Karl's heuristic nesting guesser.
11044
11045 (defun js2-backward-sws ()
11046 "Move backward through whitespace and comments."
11047 (interactive)
11048 (while (forward-comment -1)))
11049
11050 (defun js2-forward-sws ()
11051 "Move forward through whitespace and comments."
11052 (interactive)
11053 (while (forward-comment 1)))
11054
11055 (defun js2-arglist-close ()
11056 "Return non-nil if we're on a line beginning with a close-paren/brace."
11057 (save-excursion
11058 (goto-char (point-at-bol))
11059 (js2-forward-sws)
11060 (looking-at "[])}]")))
11061
11062 (defun js2-indent-looks-like-label-p ()
11063 (goto-char (point-at-bol))
11064 (js2-forward-sws)
11065 (looking-at (concat js2-mode-identifier-re ":")))
11066
11067 (defun js2-indent-in-objlit-p (parse-status)
11068 "Return non-nil if this looks like an object-literal entry."
11069 (let ((start (nth 1 parse-status)))
11070 (and
11071 start
11072 (save-excursion
11073 (and (zerop (forward-line -1))
11074 (not (< (point) start)) ; crossed a {} boundary
11075 (js2-indent-looks-like-label-p)))
11076 (save-excursion
11077 (js2-indent-looks-like-label-p)))))
11078
11079 ;; If prev line looks like foobar({ then we're passing an object
11080 ;; literal to a function call, and people pretty much always want to
11081 ;; de-dent back to the previous line, so move the 'basic-offset'
11082 ;; position to the front.
11083 (defun js2-indent-objlit-arg-p (parse-status)
11084 (save-excursion
11085 (back-to-indentation)
11086 (js2-backward-sws)
11087 (and (eq (1- (point)) (nth 1 parse-status))
11088 (eq (char-before) ?{)
11089 (progn
11090 (forward-char -1)
11091 (skip-chars-backward " \t")
11092 (eq (char-before) ?\()))))
11093
11094 (defun js2-indent-case-block-p ()
11095 (save-excursion
11096 (back-to-indentation)
11097 (js2-backward-sws)
11098 (goto-char (point-at-bol))
11099 (skip-chars-forward " \t")
11100 (looking-at "case\\s-.+:")))
11101
11102 (defun js2-bounce-indent (normal-col parse-status &optional backward)
11103 "Cycle among alternate computed indentation positions.
11104 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11105 of the buffer to the current point. NORMAL-COL is the indentation
11106 column computed by the heuristic guesser based on current paren,
11107 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11108 in reverse."
11109 (let ((cur-indent (current-indentation))
11110 (old-buffer-undo-list buffer-undo-list)
11111 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11112 (current-line (save-excursion
11113 (forward-line 0) ; move to bol
11114 (1+ (count-lines (point-min) (point)))))
11115 positions pos main-pos anchor arglist-cont same-indent
11116 basic-offset computed-pos)
11117 ;; temporarily don't record undo info, if user requested this
11118 (when js2-mode-indent-inhibit-undo
11119 (setq buffer-undo-list t))
11120 (unwind-protect
11121 (progn
11122 ;; First likely point: indent from beginning of previous code line
11123 (push (setq basic-offset
11124 (+ (save-excursion
11125 (back-to-indentation)
11126 (js2-backward-sws)
11127 (back-to-indentation)
11128 (current-column))
11129 js2-basic-offset))
11130 positions)
11131
11132 ;; (First + epsilon) likely point: indent 2x from beginning of
11133 ;; previous code line. Google does it this way.
11134 (push (setq basic-offset
11135 (+ (save-excursion
11136 (back-to-indentation)
11137 (js2-backward-sws)
11138 (back-to-indentation)
11139 (current-column))
11140 (* 2 js2-basic-offset)))
11141 positions)
11142
11143 ;; Second likely point: indent from assign-expr RHS. This
11144 ;; is just a crude guess based on finding " = " on the previous
11145 ;; line containing actual code.
11146 (setq pos (save-excursion
11147 (forward-line -1)
11148 (goto-char (point-at-bol))
11149 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11150 (point-at-eol) t)
11151 (goto-char (match-end 1))
11152 (skip-chars-forward " \t\r\n")
11153 (current-column))))
11154 (when pos
11155 (cl-incf pos js2-basic-offset)
11156 (push pos positions))
11157
11158 ;; Third likely point: same indent as previous line of code.
11159 ;; Make it the first likely point if we're not on an
11160 ;; arglist-close line and previous line ends in a comma, or
11161 ;; both this line and prev line look like object-literal
11162 ;; elements.
11163 (setq pos (save-excursion
11164 (goto-char (point-at-bol))
11165 (js2-backward-sws)
11166 (back-to-indentation)
11167 (prog1
11168 (current-column)
11169 ;; while we're here, look for trailing comma
11170 (if (save-excursion
11171 (goto-char (point-at-eol))
11172 (js2-backward-sws)
11173 (eq (char-before) ?,))
11174 (setq arglist-cont (1- (point)))))))
11175 (when pos
11176 (if (and (or arglist-cont
11177 (js2-indent-in-objlit-p parse-status))
11178 (not (js2-arglist-close)))
11179 (setq same-indent pos))
11180 (push pos positions))
11181
11182 ;; Fourth likely point: first preceding code with less indentation.
11183 ;; than the immediately preceding code line.
11184 (setq pos (save-excursion
11185 (back-to-indentation)
11186 (js2-backward-sws)
11187 (back-to-indentation)
11188 (setq anchor (current-column))
11189 (while (and (zerop (forward-line -1))
11190 (>= (progn
11191 (back-to-indentation)
11192 (current-column))
11193 anchor)))
11194 (setq pos (current-column))))
11195 (push pos positions)
11196
11197 ;; nesting-heuristic position, main by default
11198 (push (setq main-pos normal-col) positions)
11199
11200 ;; delete duplicates and sort positions list
11201 (setq positions (sort (delete-dups positions) '<))
11202
11203 ;; comma-list continuation lines: prev line indent takes precedence
11204 (if same-indent
11205 (setq main-pos same-indent))
11206
11207 ;; common special cases where we want to indent in from previous line
11208 (if (or (js2-indent-case-block-p)
11209 (js2-indent-objlit-arg-p parse-status))
11210 (setq main-pos basic-offset))
11211
11212 ;; if bouncing backward, reverse positions list
11213 (if backward
11214 (setq positions (reverse positions)))
11215
11216 ;; record whether we're already sitting on one of the alternatives
11217 (setq pos (member cur-indent positions))
11218
11219 (cond
11220 ;; case 0: we're one one of the alternatives and this is the
11221 ;; first time they've pressed TAB on this line (best-guess).
11222 ((and js2-mode-indent-ignore-first-tab
11223 pos
11224 ;; first time pressing TAB on this line?
11225 (not (eq js2-mode-last-indented-line current-line)))
11226 ;; do nothing
11227 (setq computed-pos nil))
11228 ;; case 1: only one computed position => use it
11229 ((null (cdr positions))
11230 (setq computed-pos 0))
11231 ;; case 2: not on any of the computed spots => use main spot
11232 ((not pos)
11233 (setq computed-pos (js2-position main-pos positions)))
11234 ;; case 3: on last position: cycle to first position
11235 ((null (cdr pos))
11236 (setq computed-pos 0))
11237 ;; case 4: on intermediate position: cycle to next position
11238 (t
11239 (setq computed-pos (js2-position (cl-second pos) positions))))
11240
11241 ;; see if any hooks want to indent; otherwise we do it
11242 (cl-loop with result = nil
11243 for hook in js2-indent-hook
11244 while (null result)
11245 do
11246 (setq result (funcall hook positions computed-pos))
11247 finally do
11248 (unless (or result (null computed-pos))
11249 (indent-line-to (nth computed-pos positions)))))
11250
11251 ;; finally
11252 (if js2-mode-indent-inhibit-undo
11253 (setq buffer-undo-list old-buffer-undo-list))
11254 ;; see commentary for `js2-mode-last-indented-line'
11255 (setq js2-mode-last-indented-line current-line))))
11256
11257 (defun js2-1-line-comment-continuation-p ()
11258 "Return t if we're in a 1-line comment continuation.
11259 If so, we don't ever want to use bounce-indent."
11260 (save-excursion
11261 (and (progn
11262 (forward-line 0)
11263 (looking-at "\\s-*//"))
11264 (progn
11265 (forward-line -1)
11266 (forward-line 0)
11267 (when (looking-at "\\s-*$")
11268 (js2-backward-sws)
11269 (forward-line 0))
11270 (looking-at "\\s-*//")))))
11271
11272 (defun js2-indent-bounce (&optional backward)
11273 "Indent the current line, bouncing between several positions."
11274 (interactive)
11275 (let (parse-status offset indent-col
11276 ;; Don't whine about errors/warnings when we're indenting.
11277 ;; This has to be set before calling parse-partial-sexp below.
11278 (inhibit-point-motion-hooks t))
11279 (setq parse-status (save-excursion
11280 (syntax-ppss (point-at-bol)))
11281 offset (- (point) (save-excursion
11282 (back-to-indentation)
11283 (point))))
11284 ;; Don't touch multiline strings.
11285 (unless (nth 3 parse-status)
11286 (setq indent-col (js2-proper-indentation parse-status))
11287 (cond
11288 ;; It doesn't work well on first line of buffer.
11289 ((and (not (nth 4 parse-status))
11290 (not (js2-same-line (point-min)))
11291 (not (js2-1-line-comment-continuation-p)))
11292 (js2-bounce-indent indent-col parse-status backward))
11293 ;; just indent to the guesser's likely spot
11294 (t (indent-line-to indent-col)))
11295 (when (cl-plusp offset)
11296 (forward-char offset)))))
11297
11298 (defun js2-indent-bounce-backward ()
11299 "Indent the current line, bouncing between positions in reverse."
11300 (interactive)
11301 (js2-indent-bounce t))
11302
11303 (defun js2-indent-region (start end)
11304 "Indent the region, but don't use bounce indenting."
11305 (let ((js2-bounce-indent-p nil)
11306 (indent-region-function nil)
11307 (after-change-functions (remq 'js2-mode-edit
11308 after-change-functions)))
11309 (indent-region start end nil) ; nil for byte-compiler
11310 (js2-mode-edit start end (- end start))))
11311
11312 (defvar js2-minor-mode-map
11313 (let ((map (make-sparse-keymap)))
11314 (define-key map (kbd "C-c C-`") #'js2-next-error)
11315 (define-key map [mouse-1] #'js2-mode-show-node)
11316 map)
11317 "Keymap used when `js2-minor-mode' is active.")
11318
11319 ;;;###autoload
11320 (define-minor-mode js2-minor-mode
11321 "Minor mode for running js2 as a background linter.
11322 This allows you to use a different major mode for JavaScript editing,
11323 such as `js-mode', while retaining the asynchronous error/warning
11324 highlighting features of `js2-mode'."
11325 :group 'js2-mode
11326 :lighter " js-lint"
11327 (if (derived-mode-p 'js2-mode)
11328 (setq js2-minor-mode nil)
11329 (if js2-minor-mode
11330 (js2-minor-mode-enter)
11331 (js2-minor-mode-exit))))
11332
11333 (defun js2-minor-mode-enter ()
11334 "Initialization for `js2-minor-mode'."
11335 (set (make-local-variable 'max-lisp-eval-depth)
11336 (max max-lisp-eval-depth 3000))
11337 (setq next-error-function #'js2-next-error)
11338 (js2-set-default-externs)
11339 ;; Experiment: make reparse-delay longer for longer files.
11340 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11341 (setq js2-idle-timer-delay
11342 (* js2-idle-timer-delay
11343 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11344 (setq js2-mode-buffer-dirty-p t
11345 js2-mode-parsing nil)
11346 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11347 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11348 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11349 (when js2-include-jslint-globals
11350 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11351 (run-hooks 'js2-init-hook)
11352 (js2-reparse))
11353
11354 (defun js2-minor-mode-exit ()
11355 "Turn off `js2-minor-mode'."
11356 (setq next-error-function nil)
11357 (remove-hook 'after-change-functions #'js2-mode-edit t)
11358 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11359 (when js2-mode-node-overlay
11360 (delete-overlay js2-mode-node-overlay)
11361 (setq js2-mode-node-overlay nil))
11362 (js2-remove-overlays)
11363 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11364 (setq js2-mode-ast nil))
11365
11366 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11367 (make-variable-buffer-local 'js2-source-buffer)
11368
11369 (cl-defun js2-display-error-list ()
11370 "Display a navigable buffer listing parse errors/warnings."
11371 (interactive)
11372 (unless (js2-have-errors-p)
11373 (message "No errors")
11374 (cl-return-from js2-display-error-list))
11375 (cl-labels ((annotate-list
11376 (lst type)
11377 "Add diagnostic TYPE and line number to errs list"
11378 (mapcar (lambda (err)
11379 (list err type (line-number-at-pos (nth 1 err))))
11380 lst)))
11381 (let* ((srcbuf (current-buffer))
11382 (errbuf (get-buffer-create "*js-lint*"))
11383 (errors (annotate-list
11384 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11385 'js2-error)) ; must be a valid face name
11386 (warnings (annotate-list
11387 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11388 'js2-warning)) ; must be a valid face name
11389 (all-errs (sort (append errors warnings)
11390 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11391 (with-current-buffer errbuf
11392 (let ((inhibit-read-only t))
11393 (erase-buffer)
11394 (dolist (err all-errs)
11395 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11396 (insert-text-button
11397 (format "line %d: %s" line (js2-get-msg msg-key))
11398 'face type
11399 'follow-link "\C-m"
11400 'action 'js2-error-buffer-jump
11401 'js2-msg (js2-get-msg msg-key)
11402 'js2-pos beg)
11403 (insert "\n"))))
11404 (js2-error-buffer-mode)
11405 (setq js2-source-buffer srcbuf)
11406 (pop-to-buffer errbuf)
11407 (goto-char (point-min))
11408 (unless (eobp)
11409 (js2-error-buffer-view))))))
11410
11411 (defvar js2-error-buffer-mode-map
11412 (let ((map (make-sparse-keymap)))
11413 (define-key map "n" #'js2-error-buffer-next)
11414 (define-key map "p" #'js2-error-buffer-prev)
11415 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11416 (define-key map "o" #'js2-error-buffer-view)
11417 (define-key map "q" #'js2-error-buffer-quit)
11418 map)
11419 "Keymap used for js2 diagnostics buffers.")
11420
11421 (defun js2-error-buffer-mode ()
11422 "Major mode for js2 diagnostics buffers.
11423 Selecting an error will jump it to the corresponding source-buffer error.
11424 \\{js2-error-buffer-mode-map}"
11425 (interactive)
11426 (setq major-mode 'js2-error-buffer-mode
11427 mode-name "JS Lint Diagnostics")
11428 (use-local-map js2-error-buffer-mode-map)
11429 (setq truncate-lines t)
11430 (set-buffer-modified-p nil)
11431 (setq buffer-read-only t)
11432 (run-hooks 'js2-error-buffer-mode-hook))
11433
11434 (defun js2-error-buffer-next ()
11435 "Move to next error and view it."
11436 (interactive)
11437 (when (zerop (forward-line 1))
11438 (js2-error-buffer-view)))
11439
11440 (defun js2-error-buffer-prev ()
11441 "Move to previous error and view it."
11442 (interactive)
11443 (when (zerop (forward-line -1))
11444 (js2-error-buffer-view)))
11445
11446 (defun js2-error-buffer-quit ()
11447 "Kill the current buffer."
11448 (interactive)
11449 (kill-buffer))
11450
11451 (defun js2-error-buffer-jump (&rest ignored)
11452 "Jump cursor to current error in source buffer."
11453 (interactive)
11454 (when (js2-error-buffer-view)
11455 (pop-to-buffer js2-source-buffer)))
11456
11457 (defun js2-error-buffer-view ()
11458 "Scroll source buffer to show error at current line."
11459 (interactive)
11460 (cond
11461 ((not (eq major-mode 'js2-error-buffer-mode))
11462 (message "Not in a js2 errors buffer"))
11463 ((not (buffer-live-p js2-source-buffer))
11464 (message "Source buffer has been killed"))
11465 ((not (wholenump (get-text-property (point) 'js2-pos)))
11466 (message "There does not seem to be an error here"))
11467 (t
11468 (let ((pos (get-text-property (point) 'js2-pos))
11469 (msg (get-text-property (point) 'js2-msg)))
11470 (save-selected-window
11471 (pop-to-buffer js2-source-buffer)
11472 (goto-char pos)
11473 (message msg))))))
11474
11475 ;;;###autoload
11476 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11477 "Major mode for editing JavaScript code."
11478 (set (make-local-variable 'max-lisp-eval-depth)
11479 (max max-lisp-eval-depth 3000))
11480 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11481 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11482 (set (make-local-variable 'syntax-propertize-function) nil)
11483 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11484 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11485 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11486 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11487 ;; for characters inside regexp literals.
11488 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11489 ;; this is necessary to make `show-paren-function' work properly
11490 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11491 ;; needed for M-x rgrep, among other things
11492 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11493
11494 (setq font-lock-defaults '(nil t))
11495
11496 ;; Experiment: make reparse-delay longer for longer files.
11497 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11498 (setq js2-idle-timer-delay
11499 (* js2-idle-timer-delay
11500 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11501
11502 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11503 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11504 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11505 (setq next-error-function #'js2-next-error)
11506 (imenu-add-to-menubar (concat "IM-" mode-name))
11507 (add-to-invisibility-spec '(js2-outline . t))
11508 (set (make-local-variable 'line-move-ignore-invisible) t)
11509 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11510 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11511
11512 (setq js2-mode-functions-hidden nil
11513 js2-mode-comments-hidden nil
11514 js2-mode-buffer-dirty-p t
11515 js2-mode-parsing nil)
11516
11517 (js2-set-default-externs)
11518
11519 (when js2-include-jslint-globals
11520 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11521
11522 (run-hooks 'js2-init-hook)
11523
11524 (js2-reparse))
11525
11526 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11527 ;; a bit more complicated and it doesn't net us much yet.
11528 ;;;###autoload
11529 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11530 "Major mode for editing JSX code.
11531
11532 To customize the indentation for this mode, set the SGML offset
11533 variables (`sgml-basic-offset' et al) locally, like so:
11534
11535 (defun set-jsx-indentation ()
11536 (setq-local sgml-basic-offset js2-basic-offset))
11537 (add-hook 'js2-jsx-mode-hook #'set-jsx-indentation)"
11538 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11539
11540 (defun js2-mode-exit ()
11541 "Exit `js2-mode' and clean up."
11542 (interactive)
11543 (when js2-mode-node-overlay
11544 (delete-overlay js2-mode-node-overlay)
11545 (setq js2-mode-node-overlay nil))
11546 (js2-remove-overlays)
11547 (setq js2-mode-ast nil)
11548 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11549 (remove-from-invisibility-spec '(js2-outline . t))
11550 (js2-mode-show-all)
11551 (with-silent-modifications
11552 (js2-clear-face (point-min) (point-max))))
11553
11554 (defun js2-mode-reset-timer ()
11555 "Cancel any existing parse timer and schedule a new one."
11556 (if js2-mode-parse-timer
11557 (cancel-timer js2-mode-parse-timer))
11558 (setq js2-mode-parsing nil)
11559 (let ((timer (timer-create)))
11560 (setq js2-mode-parse-timer timer)
11561 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11562 (timer-set-idle-time timer js2-idle-timer-delay)
11563 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11564 (timer-activate-when-idle timer nil)))
11565
11566 (defun js2-mode-idle-reparse (buffer)
11567 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11568 it to be reparsed when the buffer is selected."
11569 (cond ((eq buffer (current-buffer))
11570 (js2-reparse))
11571 ((buffer-live-p buffer)
11572 ;; reparse when the buffer is selected again
11573 (with-current-buffer buffer
11574 (add-hook 'window-configuration-change-hook
11575 #'js2-mode-idle-reparse-inner
11576 nil t)))))
11577
11578 (defun js2-mode-idle-reparse-inner ()
11579 (remove-hook 'window-configuration-change-hook
11580 #'js2-mode-idle-reparse-inner
11581 t)
11582 (js2-reparse))
11583
11584 (defun js2-mode-edit (_beg _end _len)
11585 "Schedule a new parse after buffer is edited.
11586 Buffer edit spans from BEG to END and is of length LEN."
11587 (setq js2-mode-buffer-dirty-p t)
11588 (js2-mode-hide-overlay)
11589 (js2-mode-reset-timer))
11590
11591 (defun js2-minor-mode-edit (_beg _end _len)
11592 "Callback for buffer edits in `js2-mode'.
11593 Schedules a new parse after buffer is edited.
11594 Buffer edit spans from BEG to END and is of length LEN."
11595 (setq js2-mode-buffer-dirty-p t)
11596 (js2-mode-hide-overlay)
11597 (js2-mode-reset-timer))
11598
11599 (defun js2-reparse (&optional force)
11600 "Re-parse current buffer after user finishes some data entry.
11601 If we get any user input while parsing, including cursor motion,
11602 we discard the parse and reschedule it. If FORCE is nil, then the
11603 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11604 (let (time
11605 interrupted-p
11606 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11607 (unless js2-mode-parsing
11608 (setq js2-mode-parsing t)
11609 (unwind-protect
11610 (when (or js2-mode-buffer-dirty-p force)
11611 (js2-remove-overlays)
11612 (setq js2-mode-buffer-dirty-p nil
11613 js2-mode-fontifications nil
11614 js2-mode-deferred-properties nil)
11615 (if js2-mode-verbose-parse-p
11616 (message "parsing..."))
11617 (setq time
11618 (js2-time
11619 (setq interrupted-p
11620 (catch 'interrupted
11621 (js2-parse)
11622 (with-silent-modifications
11623 ;; if parsing is interrupted, comments and regex
11624 ;; literals stay ignored by `parse-partial-sexp'
11625 (remove-text-properties (point-min) (point-max)
11626 '(syntax-table))
11627 (js2-mode-apply-deferred-properties)
11628 (js2-mode-remove-suppressed-warnings)
11629 (js2-mode-show-warnings)
11630 (js2-mode-show-errors)
11631 (if (>= js2-highlight-level 1)
11632 (js2-highlight-jsdoc js2-mode-ast)))
11633 nil))))
11634 (if interrupted-p
11635 (progn
11636 ;; unfinished parse => try again
11637 (setq js2-mode-buffer-dirty-p t)
11638 (js2-mode-reset-timer))
11639 (if js2-mode-verbose-parse-p
11640 (message "Parse time: %s" time))))
11641 (setq js2-mode-parsing nil)
11642 (unless interrupted-p
11643 (setq js2-mode-parse-timer nil))))))
11644
11645 (defun js2-mode-show-node (event)
11646 "Debugging aid: highlight selected AST node on mouse click."
11647 (interactive "e")
11648 (mouse-set-point event)
11649 (setq deactivate-mark t)
11650 (when js2-mode-show-overlay
11651 (let ((node (js2-node-at-point))
11652 beg end)
11653 (if (null node)
11654 (message "No node found at location %s" (point))
11655 (setq beg (js2-node-abs-pos node)
11656 end (+ beg (js2-node-len node)))
11657 (if js2-mode-node-overlay
11658 (move-overlay js2-mode-node-overlay beg end)
11659 (setq js2-mode-node-overlay (make-overlay beg end))
11660 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11661 (with-silent-modifications
11662 (if (fboundp 'cursor-sensor-mode)
11663 (put-text-property beg end 'cursor-sensor-functions
11664 '(js2-mode-hide-overlay))
11665 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11666 (message "%s, parent: %s"
11667 (js2-node-short-name node)
11668 (if (js2-node-parent node)
11669 (js2-node-short-name (js2-node-parent node))
11670 "nil"))))))
11671
11672 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11673 "Remove the debugging overlay when point moves.
11674 ARG1, ARG2 and ARG3 have different values depending on whether this function
11675 was found on `point-left' or in `cursor-sensor-functions'."
11676 (when js2-mode-node-overlay
11677 (let ((beg (overlay-start js2-mode-node-overlay))
11678 (end (overlay-end js2-mode-node-overlay))
11679 (p2 (if (windowp arg1)
11680 ;; Called from cursor-sensor-functions.
11681 (window-point arg1)
11682 ;; Called from point-left.
11683 arg2)))
11684 ;; Sometimes we're called spuriously.
11685 (unless (and p2
11686 (>= p2 beg)
11687 (<= p2 end))
11688 (with-silent-modifications
11689 (remove-text-properties beg end
11690 '(point-left nil cursor-sensor-functions)))
11691 (delete-overlay js2-mode-node-overlay)
11692 (setq js2-mode-node-overlay nil)))))
11693
11694 (defun js2-mode-reset ()
11695 "Debugging helper: reset everything."
11696 (interactive)
11697 (js2-mode-exit)
11698 (js2-mode))
11699
11700 (defun js2-mode-show-warn-or-err (e face)
11701 "Highlight a warning or error E with FACE.
11702 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11703 The last element is optional. When present, use instead of FACE."
11704 (let* ((key (cl-first e))
11705 (beg (cl-second e))
11706 (end (+ beg (cl-third e)))
11707 ;; Don't inadvertently go out of bounds.
11708 (beg (max (point-min) (min beg (point-max))))
11709 (end (max (point-min) (min end (point-max))))
11710 (ovl (make-overlay beg end)))
11711 ;; FIXME: Why a mix of overlays and text-properties?
11712 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11713 (overlay-put ovl 'js2-error t)
11714 (put-text-property beg end 'help-echo (js2-get-msg key))
11715 (if (fboundp 'cursor-sensor-mode)
11716 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11717 (put-text-property beg end 'point-entered #'js2-echo-error))))
11718
11719 (defun js2-remove-overlays ()
11720 "Remove overlays from buffer that have a `js2-error' property."
11721 (let ((beg (point-min))
11722 (end (point-max)))
11723 (save-excursion
11724 (dolist (o (overlays-in beg end))
11725 (when (overlay-get o 'js2-error)
11726 (delete-overlay o))))))
11727
11728 (defun js2-mode-apply-deferred-properties ()
11729 "Apply fontifications and other text properties recorded during parsing."
11730 (when (cl-plusp js2-highlight-level)
11731 ;; We defer clearing faces as long as possible to eliminate flashing.
11732 (js2-clear-face (point-min) (point-max))
11733 ;; Have to reverse the recorded fontifications list so that errors
11734 ;; and warnings overwrite the normal fontifications.
11735 (dolist (f (nreverse js2-mode-fontifications))
11736 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11737 (setq js2-mode-fontifications nil))
11738 (dolist (p js2-mode-deferred-properties)
11739 (apply #'put-text-property p))
11740 (setq js2-mode-deferred-properties nil))
11741
11742 (defun js2-mode-show-errors ()
11743 "Highlight syntax errors."
11744 (when js2-mode-show-parse-errors
11745 (dolist (e (js2-ast-root-errors js2-mode-ast))
11746 (js2-mode-show-warn-or-err e 'js2-error))))
11747
11748 (defun js2-mode-remove-suppressed-warnings ()
11749 "Take suppressed warnings out of the AST warnings list.
11750 This ensures that the counts and `next-error' are correct."
11751 (setf (js2-ast-root-warnings js2-mode-ast)
11752 (js2-delete-if
11753 (lambda (e)
11754 (let ((key (caar e)))
11755 (or
11756 (and (not js2-strict-trailing-comma-warning)
11757 (string-match "trailing\\.comma" key))
11758 (and (not js2-strict-cond-assign-warning)
11759 (string= key "msg.equal.as.assign"))
11760 (and js2-missing-semi-one-line-override
11761 (string= key "msg.missing.semi")
11762 (let* ((beg (cl-second e))
11763 (node (js2-node-at-point beg))
11764 (fn (js2-mode-find-parent-fn node))
11765 (body (and fn (js2-function-node-body fn)))
11766 (lc (and body (js2-node-abs-pos body)))
11767 (rc (and lc (+ lc (js2-node-len body)))))
11768 (and fn
11769 (or (null body)
11770 (save-excursion
11771 (goto-char beg)
11772 (and (js2-same-line lc)
11773 (js2-same-line rc))))))))))
11774 (js2-ast-root-warnings js2-mode-ast))))
11775
11776 (defun js2-mode-show-warnings ()
11777 "Highlight strict-mode warnings."
11778 (when js2-mode-show-strict-warnings
11779 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11780 (js2-mode-show-warn-or-err e 'js2-warning))))
11781
11782 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11783 "Called by point-motion hooks.
11784 ARG1, ARG2 and ARG3 have different values depending on whether this function
11785 was found on `point-entered' or in `cursor-sensor-functions'."
11786 (let* ((new-point (if (windowp arg1)
11787 ;; Called from cursor-sensor-functions.
11788 (window-point arg1)
11789 ;; Called from point-left.
11790 arg2))
11791 (msg (get-text-property new-point 'help-echo)))
11792 (when (and (stringp msg)
11793 (not (active-minibuffer-window))
11794 (not (current-message)))
11795 (message msg))))
11796
11797 (defun js2-line-break (&optional _soft)
11798 "Break line at point and indent, continuing comment if within one.
11799 If inside a string, and `js2-concat-multiline-strings' is not
11800 nil, turn it into concatenation."
11801 (interactive)
11802 (let ((parse-status (syntax-ppss)))
11803 (cond
11804 ;; Check if we're inside a string.
11805 ((nth 3 parse-status)
11806 (if js2-concat-multiline-strings
11807 (js2-mode-split-string parse-status)
11808 (insert "\n")))
11809 ;; Check if inside a block comment.
11810 ((nth 4 parse-status)
11811 (js2-mode-extend-comment (nth 8 parse-status)))
11812 (t
11813 (newline-and-indent)))))
11814
11815 (defun js2-mode-split-string (parse-status)
11816 "Turn a newline in mid-string into a string concatenation.
11817 PARSE-STATUS is as documented in `parse-partial-sexp'."
11818 (let* ((quote-char (nth 3 parse-status))
11819 (at-eol (eq js2-concat-multiline-strings 'eol)))
11820 (insert quote-char)
11821 (insert (if at-eol " +\n" "\n"))
11822 (unless at-eol
11823 (insert "+ "))
11824 (js2-indent-line)
11825 (insert quote-char)
11826 (when (eolp)
11827 (insert quote-char)
11828 (backward-char 1))))
11829
11830 (defun js2-mode-extend-comment (start-pos)
11831 "Indent the line and, when inside a comment block, add comment prefix."
11832 (let (star single col first-line needs-close)
11833 (save-excursion
11834 (back-to-indentation)
11835 (when (< (point) start-pos)
11836 (goto-char start-pos))
11837 (cond
11838 ((looking-at "\\*[^/]")
11839 (setq star t
11840 col (current-column)))
11841 ((looking-at "/\\*")
11842 (setq star t
11843 first-line t
11844 col (1+ (current-column))))
11845 ((looking-at "//")
11846 (setq single t
11847 col (current-column)))))
11848 ;; Heuristic for whether we need to close the comment:
11849 ;; if we've got a parse error here, assume it's an unterminated
11850 ;; comment.
11851 (setq needs-close
11852 (or
11853 (get-char-property (1- (point)) 'js2-error)
11854 ;; The heuristic above doesn't work well when we're
11855 ;; creating a comment and there's another one downstream,
11856 ;; as our parser thinks this one ends at the end of the
11857 ;; next one. (You can have a /* inside a js block comment.)
11858 ;; So just close it if the next non-ws char isn't a *.
11859 (and first-line
11860 (eolp)
11861 (save-excursion
11862 (skip-chars-forward " \t\r\n")
11863 (not (eq (char-after) ?*))))))
11864 (delete-horizontal-space)
11865 (insert "\n")
11866 (cond
11867 (star
11868 (indent-to col)
11869 (insert "* ")
11870 (if (and first-line needs-close)
11871 (save-excursion
11872 (insert "\n")
11873 (indent-to col)
11874 (insert "*/"))))
11875 ((and single
11876 (save-excursion
11877 (and (zerop (forward-line 1))
11878 (looking-at "\\s-*//"))))
11879 (indent-to col)
11880 (insert "// ")))
11881 ;; Don't need to extend the comment after all.
11882 (js2-indent-line)))
11883
11884 (defun js2-beginning-of-line ()
11885 "Toggle point between bol and first non-whitespace char in line.
11886 Also moves past comment delimiters when inside comments."
11887 (interactive)
11888 (let (node)
11889 (cond
11890 ((bolp)
11891 (back-to-indentation))
11892 ((looking-at "//")
11893 (skip-chars-forward "/ \t"))
11894 ((and (eq (char-after) ?*)
11895 (setq node (js2-comment-at-point))
11896 (memq (js2-comment-node-format node) '(jsdoc block))
11897 (save-excursion
11898 (skip-chars-backward " \t")
11899 (bolp)))
11900 (skip-chars-forward "\* \t"))
11901 (t
11902 (goto-char (point-at-bol))))))
11903
11904 (defun js2-end-of-line ()
11905 "Toggle point between eol and last non-whitespace char in line."
11906 (interactive)
11907 (if (eolp)
11908 (skip-chars-backward " \t")
11909 (goto-char (point-at-eol))))
11910
11911 (defun js2-mode-wait-for-parse (callback)
11912 "Invoke CALLBACK when parsing is finished.
11913 If parsing is already finished, calls CALLBACK immediately."
11914 (if (not js2-mode-buffer-dirty-p)
11915 (funcall callback)
11916 (push callback js2-mode-pending-parse-callbacks)
11917 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11918
11919 (defun js2-mode-parse-finished ()
11920 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11921 ;; We can't let errors propagate up, since it prevents the
11922 ;; `js2-parse' method from completing normally and returning
11923 ;; the ast, which makes things mysteriously not work right.
11924 (unwind-protect
11925 (dolist (cb js2-mode-pending-parse-callbacks)
11926 (condition-case err
11927 (funcall cb)
11928 (error (message "%s" err))))
11929 (setq js2-mode-pending-parse-callbacks nil)))
11930
11931 (defun js2-mode-flag-region (from to flag)
11932 "Hide or show text from FROM to TO, according to FLAG.
11933 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11934 Returns the created overlay if FLAG is non-nil."
11935 (remove-overlays from to 'invisible 'js2-outline)
11936 (when flag
11937 (let ((o (make-overlay from to)))
11938 (overlay-put o 'invisible 'js2-outline)
11939 (overlay-put o 'isearch-open-invisible
11940 'js2-isearch-open-invisible)
11941 o)))
11942
11943 ;; Function to be set as an outline-isearch-open-invisible' property
11944 ;; to the overlay that makes the outline invisible (see
11945 ;; `js2-mode-flag-region').
11946 (defun js2-isearch-open-invisible (_overlay)
11947 ;; We rely on the fact that isearch places point on the matched text.
11948 (js2-mode-show-element))
11949
11950 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11951 "Return cons cell of bounds of folding overlay at POS.
11952 Returns nil if not found."
11953 (let ((overlays (overlays-at (or pos (point))))
11954 o)
11955 (while (and overlays
11956 (not o))
11957 (if (overlay-get (car overlays) 'invisible)
11958 (setq o (car overlays))
11959 (setq overlays (cdr overlays))))
11960 (if o
11961 (cons (overlay-start o) (overlay-end o)))))
11962
11963 (defun js2-mode-function-at-point (&optional pos)
11964 "Return the innermost function node enclosing current point.
11965 Returns nil if point is not in a function."
11966 (let ((node (js2-node-at-point pos)))
11967 (while (and node (not (js2-function-node-p node)))
11968 (setq node (js2-node-parent node)))
11969 (if (js2-function-node-p node)
11970 node)))
11971
11972 (defun js2-mode-toggle-element ()
11973 "Hide or show the foldable element at the point."
11974 (interactive)
11975 (let (comment fn pos)
11976 (save-excursion
11977 (cond
11978 ;; /* ... */ comment?
11979 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11980 (if (js2-mode-invisible-overlay-bounds
11981 (setq pos (+ 3 (js2-node-abs-pos comment))))
11982 (progn
11983 (goto-char pos)
11984 (js2-mode-show-element))
11985 (js2-mode-hide-element)))
11986 ;; //-comment?
11987 ((save-excursion
11988 (back-to-indentation)
11989 (looking-at js2-mode-//-comment-re))
11990 (js2-mode-toggle-//-comment))
11991 ;; function?
11992 ((setq fn (js2-mode-function-at-point))
11993 (setq pos (and (js2-function-node-body fn)
11994 (js2-node-abs-pos (js2-function-node-body fn))))
11995 (goto-char (1+ pos))
11996 (if (js2-mode-invisible-overlay-bounds)
11997 (js2-mode-show-element)
11998 (js2-mode-hide-element)))
11999 (t
12000 (message "Nothing at point to hide or show"))))))
12001
12002 (defun js2-mode-hide-element ()
12003 "Fold/hide contents of a block, showing ellipses.
12004 Show the hidden text with \\[js2-mode-show-element]."
12005 (interactive)
12006 (if js2-mode-buffer-dirty-p
12007 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12008 (let (node body beg end)
12009 (cond
12010 ((js2-mode-invisible-overlay-bounds)
12011 (message "already hidden"))
12012 (t
12013 (setq node (js2-node-at-point))
12014 (cond
12015 ((js2-block-comment-p node)
12016 (js2-mode-hide-comment node))
12017 (t
12018 (while (and node (not (js2-function-node-p node)))
12019 (setq node (js2-node-parent node)))
12020 (if (and node
12021 (setq body (js2-function-node-body node)))
12022 (progn
12023 (setq beg (js2-node-abs-pos body)
12024 end (+ beg (js2-node-len body)))
12025 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12026 (message "No collapsable element found at point"))))))))
12027
12028 (defun js2-mode-show-element ()
12029 "Show the hidden element at current point."
12030 (interactive)
12031 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12032 (if bounds
12033 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12034 (message "Nothing to un-hide"))))
12035
12036 (defun js2-mode-show-all ()
12037 "Show all of the text in the buffer."
12038 (interactive)
12039 (js2-mode-flag-region (point-min) (point-max) nil))
12040
12041 (defun js2-mode-toggle-hide-functions ()
12042 (interactive)
12043 (if js2-mode-functions-hidden
12044 (js2-mode-show-functions)
12045 (js2-mode-hide-functions)))
12046
12047 (defun js2-mode-hide-functions ()
12048 "Hides all non-nested function bodies in the buffer.
12049 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12050 to open an individual entry."
12051 (interactive)
12052 (if js2-mode-buffer-dirty-p
12053 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12054 (if (null js2-mode-ast)
12055 (message "Oops - parsing failed")
12056 (setq js2-mode-functions-hidden t)
12057 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12058
12059 (defun js2-mode-function-hider (n endp)
12060 (when (not endp)
12061 (let ((tt (js2-node-type n))
12062 body beg end)
12063 (cond
12064 ((and (= tt js2-FUNCTION)
12065 (setq body (js2-function-node-body n)))
12066 (setq beg (js2-node-abs-pos body)
12067 end (+ beg (js2-node-len body)))
12068 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12069 nil) ; don't process children of function
12070 (t
12071 t))))) ; keep processing other AST nodes
12072
12073 (defun js2-mode-show-functions ()
12074 "Un-hide any folded function bodies in the buffer."
12075 (interactive)
12076 (setq js2-mode-functions-hidden nil)
12077 (save-excursion
12078 (goto-char (point-min))
12079 (while (/= (goto-char (next-overlay-change (point)))
12080 (point-max))
12081 (dolist (o (overlays-at (point)))
12082 (when (and (overlay-get o 'invisible)
12083 (not (overlay-get o 'comment)))
12084 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12085
12086 (defun js2-mode-hide-comment (n)
12087 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12088 3 ; /**
12089 2)) ; /*
12090 (beg (+ (js2-node-abs-pos n) head))
12091 (end (- (+ beg (js2-node-len n)) head 2))
12092 (o (js2-mode-flag-region beg end 'hide)))
12093 (overlay-put o 'comment t)))
12094
12095 (defun js2-mode-toggle-hide-comments ()
12096 "Folds all block comments in the buffer.
12097 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12098 to open an individual entry."
12099 (interactive)
12100 (if js2-mode-comments-hidden
12101 (js2-mode-show-comments)
12102 (js2-mode-hide-comments)))
12103
12104 (defun js2-mode-hide-comments ()
12105 (interactive)
12106 (if js2-mode-buffer-dirty-p
12107 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12108 (if (null js2-mode-ast)
12109 (message "Oops - parsing failed")
12110 (setq js2-mode-comments-hidden t)
12111 (dolist (n (js2-ast-root-comments js2-mode-ast))
12112 (when (js2-block-comment-p n)
12113 (js2-mode-hide-comment n)))
12114 (js2-mode-hide-//-comments)))
12115
12116 (defun js2-mode-extend-//-comment (direction)
12117 "Find start or end of a block of similar //-comment lines.
12118 DIRECTION is -1 to look back, 1 to look forward.
12119 INDENT is the indentation level to match.
12120 Returns the end-of-line position of the furthest adjacent
12121 //-comment line with the same indentation as the current line.
12122 If there is no such matching line, returns current end of line."
12123 (let ((pos (point-at-eol))
12124 (indent (current-indentation)))
12125 (save-excursion
12126 (while (and (zerop (forward-line direction))
12127 (looking-at js2-mode-//-comment-re)
12128 (eq indent (length (match-string 1))))
12129 (setq pos (point-at-eol)))
12130 pos)))
12131
12132 (defun js2-mode-hide-//-comments ()
12133 "Fold adjacent 1-line comments, showing only snippet of first one."
12134 (let (beg end)
12135 (save-excursion
12136 (goto-char (point-min))
12137 (while (re-search-forward js2-mode-//-comment-re nil t)
12138 (setq beg (point)
12139 end (js2-mode-extend-//-comment 1))
12140 (unless (eq beg end)
12141 (overlay-put (js2-mode-flag-region beg end 'hide)
12142 'comment t))
12143 (goto-char end)
12144 (forward-char 1)))))
12145
12146 (defun js2-mode-toggle-//-comment ()
12147 "Fold or un-fold any multi-line //-comment at point.
12148 Caller should have determined that this line starts with a //-comment."
12149 (let* ((beg (point-at-eol))
12150 (end beg))
12151 (save-excursion
12152 (goto-char end)
12153 (if (js2-mode-invisible-overlay-bounds)
12154 (js2-mode-show-element)
12155 ;; else hide the comment
12156 (setq beg (js2-mode-extend-//-comment -1)
12157 end (js2-mode-extend-//-comment 1))
12158 (unless (eq beg end)
12159 (overlay-put (js2-mode-flag-region beg end 'hide)
12160 'comment t))))))
12161
12162 (defun js2-mode-show-comments ()
12163 "Un-hide any hidden comments, leaving other hidden elements alone."
12164 (interactive)
12165 (setq js2-mode-comments-hidden nil)
12166 (save-excursion
12167 (goto-char (point-min))
12168 (while (/= (goto-char (next-overlay-change (point)))
12169 (point-max))
12170 (dolist (o (overlays-at (point)))
12171 (when (overlay-get o 'comment)
12172 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12173
12174 (defun js2-mode-display-warnings-and-errors ()
12175 "Turn on display of warnings and errors."
12176 (interactive)
12177 (setq js2-mode-show-parse-errors t
12178 js2-mode-show-strict-warnings t)
12179 (js2-reparse 'force))
12180
12181 (defun js2-mode-hide-warnings-and-errors ()
12182 "Turn off display of warnings and errors."
12183 (interactive)
12184 (setq js2-mode-show-parse-errors nil
12185 js2-mode-show-strict-warnings nil)
12186 (js2-reparse 'force))
12187
12188 (defun js2-mode-toggle-warnings-and-errors ()
12189 "Toggle the display of warnings and errors.
12190 Some users don't like having warnings/errors reported while they type."
12191 (interactive)
12192 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12193 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12194 (if (called-interactively-p 'any)
12195 (message "warnings and errors %s"
12196 (if js2-mode-show-parse-errors
12197 "enabled"
12198 "disabled")))
12199 (js2-reparse 'force))
12200
12201 (defun js2-mode-customize ()
12202 (interactive)
12203 (customize-group 'js2-mode))
12204
12205 (defun js2-mode-forward-sexp (&optional arg)
12206 "Move forward across one statement or balanced expression.
12207 With ARG, do it that many times. Negative arg -N means
12208 move backward across N balanced expressions."
12209 (interactive "p")
12210 (setq arg (or arg 1))
12211 (save-restriction
12212 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12213 (js2-reparse)
12214 (let (forward-sexp-function
12215 node (start (point)) pos lp rp child)
12216 (cond
12217 ;; backward-sexp
12218 ;; could probably make this better for some cases:
12219 ;; - if in statement block (e.g. function body), go to parent
12220 ;; - infix exprs like (foo in bar) - maybe go to beginning
12221 ;; of infix expr if in the right-side expression?
12222 ((and arg (cl-minusp arg))
12223 (dotimes (_ (- arg))
12224 (js2-backward-sws)
12225 (forward-char -1) ; Enter the node we backed up to.
12226 (when (setq node (js2-node-at-point (point) t))
12227 (setq pos (js2-node-abs-pos node))
12228 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12229 (setq lp (car parens)
12230 rp (cdr parens)))
12231 (when (and lp (> start lp))
12232 (if (and rp (<= start rp))
12233 ;; Between parens, check if there's a child node we can jump.
12234 (when (setq child (js2-node-closest-child node (point) lp t))
12235 (setq pos (js2-node-abs-pos child)))
12236 ;; Before both parens.
12237 (setq pos lp)))
12238 (let ((state (parse-partial-sexp start pos)))
12239 (goto-char (if (not (zerop (car state)))
12240 ;; Stumble at the unbalanced paren if < 0, or
12241 ;; jump a bit further if > 0.
12242 (scan-sexps start -1)
12243 pos))))
12244 (unless pos (goto-char (point-min)))))
12245 (t
12246 ;; forward-sexp
12247 (dotimes (_ arg)
12248 (js2-forward-sws)
12249 (when (setq node (js2-node-at-point (point) t))
12250 (setq pos (js2-node-abs-pos node))
12251 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12252 (setq lp (car parens)
12253 rp (cdr parens)))
12254 (or
12255 (when (and rp (<= start rp))
12256 (if (> start lp)
12257 (when (setq child (js2-node-closest-child node (point) rp))
12258 (setq pos (js2-node-abs-end child)))
12259 (setq pos (1+ rp))))
12260 ;; No parens or child nodes, looks for the end of the current node.
12261 (cl-incf pos (js2-node-len
12262 (if (js2-expr-stmt-node-p (js2-node-parent node))
12263 ;; Stop after the semicolon.
12264 (js2-node-parent node)
12265 node))))
12266 (let ((state (save-excursion (parse-partial-sexp start pos))))
12267 (goto-char (if (not (zerop (car state)))
12268 (scan-sexps start 1)
12269 pos))))
12270 (unless pos (goto-char (point-max)))))))))
12271
12272 (defun js2-mode-forward-sexp-parens (node abs-pos)
12273 "Return a cons cell with positions of main parens in NODE."
12274 (cond
12275 ((or (js2-array-node-p node)
12276 (js2-object-node-p node)
12277 (js2-comp-node-p node)
12278 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12279 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12280 ((js2-paren-expr-node-p node)
12281 (let ((lp (js2-node-lp node))
12282 (rp (js2-node-rp node)))
12283 (cons (when lp (+ abs-pos lp))
12284 (when rp (+ abs-pos rp)))))))
12285
12286 (defun js2-node-closest-child (parent point limit &optional before)
12287 (let* ((parent-pos (js2-node-abs-pos parent))
12288 (rpoint (- point parent-pos))
12289 (rlimit (- limit parent-pos))
12290 (min (min rpoint rlimit))
12291 (max (max rpoint rlimit))
12292 found)
12293 (catch 'done
12294 (js2-visit-ast
12295 parent
12296 (lambda (node _end-p)
12297 (if (eq node parent)
12298 t
12299 (let ((pos (js2-node-pos node)) ;; Both relative values.
12300 (end (+ (js2-node-pos node) (js2-node-len node))))
12301 (when (and (>= pos min) (<= end max)
12302 (if before (< pos rpoint) (> end rpoint)))
12303 (setq found node))
12304 (when (> end rpoint)
12305 (throw 'done nil)))
12306 nil))))
12307 found))
12308
12309 (defun js2-errors ()
12310 "Return a list of errors found."
12311 (and js2-mode-ast
12312 (js2-ast-root-errors js2-mode-ast)))
12313
12314 (defun js2-warnings ()
12315 "Return a list of warnings found."
12316 (and js2-mode-ast
12317 (js2-ast-root-warnings js2-mode-ast)))
12318
12319 (defun js2-have-errors-p ()
12320 "Return non-nil if any parse errors or warnings were found."
12321 (or (js2-errors) (js2-warnings)))
12322
12323 (defun js2-errors-and-warnings ()
12324 "Return a copy of the concatenated errors and warnings lists.
12325 They are appended: first the errors, then the warnings.
12326 Entries are of the form (MSG BEG END)."
12327 (when js2-mode-ast
12328 (append (js2-ast-root-errors js2-mode-ast)
12329 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12330
12331 (defun js2-next-error (&optional arg reset)
12332 "Move to next parse error.
12333 Typically invoked via \\[next-error].
12334 ARG is the number of errors, forward or backward, to move.
12335 RESET means start over from the beginning."
12336 (interactive "p")
12337 (if (not (or (js2-errors) (js2-warnings)))
12338 (message "No errors")
12339 (when reset
12340 (goto-char (point-min)))
12341 (let* ((errs (js2-errors-and-warnings))
12342 (continue t)
12343 (start (point))
12344 (count (or arg 1))
12345 (backward (cl-minusp count))
12346 (sorter (if backward '> '<))
12347 (stopper (if backward '< '>))
12348 (count (abs count))
12349 all-errs err)
12350 ;; Sort by start position.
12351 (setq errs (sort errs (lambda (e1 e2)
12352 (funcall sorter (cl-second e1) (cl-second e2))))
12353 all-errs errs)
12354 ;; Find nth error with pos > start.
12355 (while (and errs continue)
12356 (when (funcall stopper (cl-cadar errs) start)
12357 (setq err (car errs))
12358 (if (zerop (cl-decf count))
12359 (setq continue nil)))
12360 (setq errs (cdr errs)))
12361 ;; Clear for `js2-echo-error'.
12362 (message nil)
12363 (if err
12364 (goto-char (cl-second err))
12365 ;; Wrap around to first error.
12366 (goto-char (cl-second (car all-errs)))
12367 ;; If we were already on it, echo msg again.
12368 (if (= (point) start)
12369 (js2-echo-error (point) (point)))))))
12370
12371 (defun js2-down-mouse-3 ()
12372 "Make right-click move the point to the click location.
12373 This makes right-click context menu operations a bit more intuitive.
12374 The point will not move if the region is active, however, to avoid
12375 destroying the region selection."
12376 (interactive)
12377 (when (and js2-move-point-on-right-click
12378 (not mark-active))
12379 (let ((e last-input-event))
12380 (ignore-errors
12381 (goto-char (cl-cadadr e))))))
12382
12383 (defun js2-mode-create-imenu-index ()
12384 "Return an alist for `imenu--index-alist'."
12385 ;; This is built up in `js2-parse-record-imenu' during parsing.
12386 (when js2-mode-ast
12387 ;; if we have an ast but no recorder, they're requesting a rescan
12388 (unless js2-imenu-recorder
12389 (js2-reparse 'force))
12390 (prog1
12391 (js2-build-imenu-index)
12392 (setq js2-imenu-recorder nil
12393 js2-imenu-function-map nil))))
12394
12395 (defun js2-mode-find-tag ()
12396 "Replacement for `find-tag-default'.
12397 `find-tag-default' returns a ridiculous answer inside comments."
12398 (let (beg end)
12399 (save-excursion
12400 (if (looking-at "\\_>")
12401 (setq beg (progn (forward-symbol -1) (point))
12402 end (progn (forward-symbol 1) (point)))
12403 (setq beg (progn (forward-symbol 1) (point))
12404 end (progn (forward-symbol -1) (point))))
12405 (replace-regexp-in-string
12406 "[\"']" ""
12407 (buffer-substring-no-properties beg end)))))
12408
12409 (defun js2-mode-forward-sibling ()
12410 "Move to the end of the sibling following point in parent.
12411 Returns non-nil if successful, or nil if there was no following sibling."
12412 (let* ((node (js2-node-at-point))
12413 (parent (js2-mode-find-enclosing-fn node))
12414 sib)
12415 (when (setq sib (js2-node-find-child-after (point) parent))
12416 (goto-char (+ (js2-node-abs-pos sib)
12417 (js2-node-len sib))))))
12418
12419 (defun js2-mode-backward-sibling ()
12420 "Move to the beginning of the sibling node preceding point in parent.
12421 Parent is defined as the enclosing script or function."
12422 (let* ((node (js2-node-at-point))
12423 (parent (js2-mode-find-enclosing-fn node))
12424 sib)
12425 (when (setq sib (js2-node-find-child-before (point) parent))
12426 (goto-char (js2-node-abs-pos sib)))))
12427
12428 (defun js2-beginning-of-defun (&optional arg)
12429 "Go to line on which current function starts, and return t on success.
12430 If we're not in a function or already at the beginning of one, go
12431 to beginning of previous script-level element.
12432 With ARG N, do that N times. If N is negative, move forward."
12433 (setq arg (or arg 1))
12434 (if (cl-plusp arg)
12435 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12436 (when (cond
12437 ((js2-function-node-p parent)
12438 (goto-char (js2-node-abs-pos parent)))
12439 (t
12440 (js2-mode-backward-sibling)))
12441 (if (> arg 1)
12442 (js2-beginning-of-defun (1- arg))
12443 t)))
12444 (when (js2-end-of-defun)
12445 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12446
12447 (defun js2-end-of-defun ()
12448 "Go to the char after the last position of the current function
12449 or script-level element."
12450 (let* ((node (js2-node-at-point))
12451 (parent (or (and (js2-function-node-p node) node)
12452 (js2-node-parent-script-or-fn node)))
12453 script)
12454 (unless (js2-function-node-p parent)
12455 ;; Use current script-level node, or, if none, the next one.
12456 (setq script (or parent node)
12457 parent (js2-node-find-child-before (point) script))
12458 (when (or (null parent)
12459 (>= (point) (+ (js2-node-abs-pos parent)
12460 (js2-node-len parent))))
12461 (setq parent (js2-node-find-child-after (point) script))))
12462 (when parent
12463 (goto-char (+ (js2-node-abs-pos parent)
12464 (js2-node-len parent))))))
12465
12466 (defun js2-mark-defun (&optional allow-extend)
12467 "Put mark at end of this function, point at beginning.
12468 The function marked is the one that contains point.
12469
12470 Interactively, if this command is repeated,
12471 or (in Transient Mark mode) if the mark is active,
12472 it marks the next defun after the ones already marked."
12473 (interactive "p")
12474 (let (extended)
12475 (when (and allow-extend
12476 (or (and (eq last-command this-command) (mark t))
12477 (and transient-mark-mode mark-active)))
12478 (let ((sib (save-excursion
12479 (goto-char (mark))
12480 (if (js2-mode-forward-sibling)
12481 (point)))))
12482 (if sib
12483 (progn
12484 (set-mark sib)
12485 (setq extended t))
12486 ;; no more siblings - try extending to enclosing node
12487 (goto-char (mark t)))))
12488 (when (not extended)
12489 (let ((node (js2-node-at-point (point) t)) ; skip comments
12490 ast fn stmt parent beg end)
12491 (when (js2-ast-root-p node)
12492 (setq ast node
12493 node (or (js2-node-find-child-after (point) node)
12494 (js2-node-find-child-before (point) node))))
12495 ;; only mark whole buffer if we can't find any children
12496 (if (null node)
12497 (setq node ast))
12498 (if (js2-function-node-p node)
12499 (setq parent node)
12500 (setq fn (js2-mode-find-enclosing-fn node)
12501 stmt (if (or (null fn)
12502 (js2-ast-root-p fn))
12503 (js2-mode-find-first-stmt node))
12504 parent (or stmt fn)))
12505 (setq beg (js2-node-abs-pos parent)
12506 end (+ beg (js2-node-len parent)))
12507 (push-mark beg)
12508 (goto-char end)
12509 (exchange-point-and-mark)))))
12510
12511 (defun js2-narrow-to-defun ()
12512 "Narrow to the function enclosing point."
12513 (interactive)
12514 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12515 (fn (if (js2-script-node-p node)
12516 node
12517 (js2-mode-find-enclosing-fn node)))
12518 (beg (js2-node-abs-pos fn)))
12519 (unless (js2-ast-root-p fn)
12520 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12521
12522 (defun js2-jump-to-definition (&optional arg)
12523 "Jump to the definition of an object's property, variable or function."
12524 (interactive "P")
12525 (ring-insert find-tag-marker-ring (point-marker))
12526 (let* ((node (js2-node-at-point))
12527 (parent (js2-node-parent node))
12528 (names (if (js2-prop-get-node-p parent)
12529 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12530 (cl-loop for n in temp
12531 with result = '()
12532 do (push n result)
12533 until (equal node n)
12534 finally return result)))))
12535 node-init)
12536 (unless (and (js2-name-node-p node)
12537 (not (js2-var-init-node-p parent))
12538 (not (js2-function-node-p parent)))
12539 (error "Node is not a supported jump node"))
12540 (push (or (and names (pop names))
12541 (unless (and (js2-object-prop-node-p parent)
12542 (eq node (js2-object-prop-node-left parent)))
12543 node)) names)
12544 (setq node-init (js2-search-scope node names))
12545
12546 ;; todo: display list of results in buffer
12547 ;; todo: group found references by buffer
12548 (unless node-init
12549 (switch-to-buffer
12550 (catch 'found
12551 (unless arg
12552 (mapc (lambda (b)
12553 (with-current-buffer b
12554 (when (derived-mode-p 'js2-mode)
12555 (setq node-init (js2-search-scope js2-mode-ast names))
12556 (if node-init
12557 (throw 'found b)))))
12558 (buffer-list)))
12559 nil)))
12560 (setq node-init (if (listp node-init) (car node-init) node-init))
12561 (unless node-init
12562 (pop-tag-mark)
12563 (error "No jump location found"))
12564 (goto-char (js2-node-abs-pos node-init))))
12565
12566 (defun js2-search-object (node name-node)
12567 "Check if object NODE contains element with NAME-NODE."
12568 (cl-assert (js2-object-node-p node))
12569 ;; Only support name-node and nodes for the time being
12570 (cl-loop for elem in (js2-object-node-elems node)
12571 for left = (js2-object-prop-node-left elem)
12572 if (or (and (js2-name-node-p left)
12573 (equal (js2-name-node-name name-node)
12574 (js2-name-node-name left)))
12575 (and (js2-string-node-p left)
12576 (string= (js2-name-node-name name-node)
12577 (js2-string-node-value left))))
12578 return elem))
12579
12580 (defun js2-search-object-for-prop (object prop-names)
12581 "Return node in OBJECT that matches PROP-NAMES or nil.
12582 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12583 i.e. ('name' 'value') = {name : { value: 3}}"
12584 (let (node
12585 (temp-object object)
12586 (temp t) ;temporay node
12587 (names prop-names))
12588 (while (and temp names (js2-object-node-p temp-object))
12589 (setq temp (js2-search-object temp-object (pop names)))
12590 (and (setq node temp)
12591 (setq temp-object (js2-object-prop-node-right temp))))
12592 (unless names node)))
12593
12594 (defun js2-search-scope (node names)
12595 "Searches NODE scope for jump location matching NAMES.
12596 NAMES is a list of property values to search for. For functions
12597 and variables NAMES will contain one element."
12598 (let (node-init
12599 (val (js2-name-node-name (car names))))
12600 (setq node-init (js2-get-symbol-declaration node val))
12601
12602 (when (> (length names) 1)
12603
12604 ;; Check var declarations
12605 (when (and node-init (string= val (js2-name-node-name node-init)))
12606 (let ((parent (js2-node-parent node-init))
12607 (temp-names names))
12608 (pop temp-names) ;; First element is var name
12609 (setq node-init (when (js2-var-init-node-p parent)
12610 (js2-search-object-for-prop
12611 (js2-var-init-node-initializer parent)
12612 temp-names)))))
12613
12614 ;; Check all assign nodes
12615 (js2-visit-ast
12616 js2-mode-ast
12617 (lambda (node endp)
12618 (unless endp
12619 (if (js2-assign-node-p node)
12620 (let ((left (js2-assign-node-left node))
12621 (right (js2-assign-node-right node))
12622 (temp-names names))
12623 (when (js2-prop-get-node-p left)
12624 (let* ((prop-list (js2-compute-nested-prop-get left))
12625 (found (cl-loop for prop in prop-list
12626 until (not (string= (js2-name-node-name
12627 (pop temp-names))
12628 (js2-name-node-name prop)))
12629 if (not temp-names) return prop))
12630 (found-node (or found
12631 (when (js2-object-node-p right)
12632 (js2-search-object-for-prop right
12633 temp-names)))))
12634 (if found-node (push found-node node-init))))))
12635 t))))
12636 node-init))
12637
12638 (defun js2-get-symbol-declaration (node name)
12639 "Find scope for NAME from NODE."
12640 (let ((scope (js2-get-defining-scope
12641 (or (js2-node-get-enclosing-scope node)
12642 node) name)))
12643 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12644
12645 (provide 'js2-mode)
12646
12647 ;;; js2-mode.el ends here