]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
js2-define-destruct-symbols-internal: Anticipate js2-getter-setter-node
[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: 20150713
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 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require 'js)
91
92 (eval-and-compile
93 (if (version< emacs-version "25.0")
94 (require 'js2-old-indent)
95 (defvaralias 'js2-basic-offset 'js-indent-level nil)
96 (defalias 'js2-proper-indentation 'js--proper-indentation)
97 (defalias 'js2-indent-line 'js-indent-line)
98 (defalias 'js2-re-search-forward 'js--re-search-forward)))
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top requestAnimationFrame cancelAnimationFrame
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout
194 querystring))
195 "Node.js externs.
196 Set `js2-include-node-externs' to t to include them.")
197
198 (defvar js2-typed-array-externs
199 (mapcar 'symbol-name
200 '(ArrayBuffer Uint8ClampedArray DataView
201 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
202 Float32Array Float64Array))
203 "Khronos typed array externs. Available in most modern browsers and
204 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
205 are enabled, these will also be included.")
206
207 (defvar js2-harmony-externs
208 (mapcar 'symbol-name
209 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
210 "ES6 externs. If `js2-include-browser-externs' is enabled and
211 `js2-language-version' is sufficiently high, these will be included.")
212
213 ;;; Variables
214
215 (defun js2-mark-safe-local (name pred)
216 "Make the variable NAME buffer-local and mark it as safe file-local
217 variable with predicate PRED."
218 (make-variable-buffer-local name)
219 (put name 'safe-local-variable pred))
220
221 (defcustom js2-highlight-level 2
222 "Amount of syntax highlighting to perform.
223 0 or a negative value means none.
224 1 adds basic syntax highlighting.
225 2 adds highlighting of some Ecma built-in properties.
226 3 adds highlighting of many Ecma built-in functions."
227 :group 'js2-mode
228 :type '(choice (const :tag "None" 0)
229 (const :tag "Basic" 1)
230 (const :tag "Include Properties" 2)
231 (const :tag "Include Functions" 3)))
232
233 (defvar js2-mode-dev-mode-p nil
234 "Non-nil if running in development mode. Normally nil.")
235
236 (defgroup js2-mode nil
237 "An improved JavaScript mode."
238 :group 'languages)
239
240 (defcustom js2-idle-timer-delay 0.2
241 "Delay in secs before re-parsing after user makes changes.
242 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
243 :type 'number
244 :group 'js2-mode)
245 (make-variable-buffer-local 'js2-idle-timer-delay)
246
247 (defcustom js2-dynamic-idle-timer-adjust 0
248 "Positive to adjust `js2-idle-timer-delay' based on file size.
249 The idea is that for short files, parsing is faster so we can be
250 more responsive to user edits without interfering with editing.
251 The buffer length in characters (typically bytes) is divided by
252 this value and used to multiply `js2-idle-timer-delay' for the
253 buffer. For example, a 21k file and 10k adjust yields 21k/10k
254 == 2, so js2-idle-timer-delay is multiplied by 2.
255 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
256 `js2-idle-timer-delay' is not dependent on the file size."
257 :type 'number
258 :group 'js2-mode)
259
260 (defcustom js2-concat-multiline-strings t
261 "When non-nil, `js2-line-break' in mid-string will make it a
262 string concatenation. When `eol', the '+' will be inserted at the
263 end of the line, otherwise, at the beginning of the next line."
264 :type '(choice (const t) (const eol) (const nil))
265 :group 'js2-mode)
266
267 (defcustom js2-mode-show-parse-errors t
268 "True to highlight parse errors."
269 :type 'boolean
270 :group 'js2-mode)
271
272 (defcustom js2-mode-show-strict-warnings t
273 "Non-nil to emit Ecma strict-mode warnings.
274 Some of the warnings can be individually disabled by other flags,
275 even if this flag is non-nil."
276 :type 'boolean
277 :group 'js2-mode)
278
279 (defcustom js2-strict-trailing-comma-warning t
280 "Non-nil to warn about trailing commas in array literals.
281 Ecma-262-5.1 allows them, but older versions of IE raise an error."
282 :type 'boolean
283 :group 'js2-mode)
284
285 (defcustom js2-strict-missing-semi-warning t
286 "Non-nil to warn about semicolon auto-insertion after statement.
287 Technically this is legal per Ecma-262, but some style guides disallow
288 depending on it."
289 :type 'boolean
290 :group 'js2-mode)
291
292 (defcustom js2-missing-semi-one-line-override nil
293 "Non-nil to permit missing semicolons in one-line functions.
294 In one-liner functions such as `function identity(x) {return x}'
295 people often omit the semicolon for a cleaner look. If you are
296 such a person, you can suppress the missing-semicolon warning
297 by setting this variable to t."
298 :type 'boolean
299 :group 'js2-mode)
300
301 (defcustom js2-strict-inconsistent-return-warning t
302 "Non-nil to warn about mixing returns with value-returns.
303 It's perfectly legal to have a `return' and a `return foo' in the
304 same function, but it's often an indicator of a bug, and it also
305 interferes with type inference (in systems that support it.)"
306 :type 'boolean
307 :group 'js2-mode)
308
309 (defcustom js2-strict-cond-assign-warning t
310 "Non-nil to warn about expressions like if (a = b).
311 This often should have been '==' instead of '='. If the warning
312 is enabled, you can suppress it on a per-expression basis by
313 parenthesizing the expression, e.g. if ((a = b)) ..."
314 :type 'boolean
315 :group 'js2-mode)
316
317 (defcustom js2-strict-var-redeclaration-warning t
318 "Non-nil to warn about redeclaring variables in a script or function."
319 :type 'boolean
320 :group 'js2-mode)
321
322 (defcustom js2-strict-var-hides-function-arg-warning t
323 "Non-nil to warn about a var decl hiding a function argument."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-skip-preprocessor-directives nil
328 "Non-nil to treat lines beginning with # as comments.
329 Useful for viewing Mozilla JavaScript source code."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-language-version 200
334 "Configures what JavaScript language version to recognize.
335 Currently versions 150, 160, 170, 180 and 200 are supported,
336 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
337 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
338 yield, and Array comprehensions, and 1.8 adds function closures."
339 :type 'integer
340 :group 'js2-mode)
341
342 (defcustom js2-instanceof-has-side-effects nil
343 "If non-nil, treats the instanceof operator as having side effects.
344 This is useful for xulrunner apps."
345 :type 'boolean
346 :group 'js2-mode)
347
348 (defcustom js2-move-point-on-right-click t
349 "Non-nil to move insertion point when you right-click.
350 This makes right-click context menu behavior a bit more intuitive,
351 since menu operations generally apply to the point. The exception
352 is if there is a region selection, in which case the point does -not-
353 move, so cut/copy/paste can work properly.
354
355 Note that IntelliJ moves the point, and Eclipse leaves it alone,
356 so this behavior is customizable."
357 :group 'js2-mode
358 :type 'boolean)
359
360 (defcustom js2-allow-rhino-new-expr-initializer t
361 "Non-nil to support a Rhino's experimental syntactic construct.
362
363 Rhino supports the ability to follow a `new' expression with an object
364 literal, which is used to set additional properties on the new object
365 after calling its constructor. Syntax:
366
367 new <expr> [ ( arglist ) ] [initializer]
368
369 Hence, this expression:
370
371 new Object {a: 1, b: 2}
372
373 results in an Object with properties a=1 and b=2. This syntax is
374 apparently not configurable in Rhino - it's currently always enabled,
375 as of Rhino version 1.7R2."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-allow-member-expr-as-function-name nil
380 "Non-nil to support experimental Rhino syntax for function names.
381
382 Rhino supports an experimental syntax configured via the Rhino Context
383 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
384
385 function <member-expr> ( [ arg-list ] ) { <body> }
386
387 Where member-expr is a non-parenthesized 'member expression', which
388 is anything at the grammar level of a new-expression or lower, meaning
389 any expression that does not involve infix or unary operators.
390
391 When <member-expr> is not a simple identifier, then it is syntactic
392 sugar for assigning the anonymous function to the <member-expr>. Hence,
393 this code:
394
395 function a.b().c[2] (x, y) { ... }
396
397 is rewritten as:
398
399 a.b().c[2] = function(x, y) {...}
400
401 which doesn't seem particularly useful, but Rhino permits it."
402 :type 'boolean
403 :group 'js2-mode)
404
405 ;; scanner variables
406
407 (defmacro js2-deflocal (name value &optional comment)
408 "Define a buffer-local variable NAME with VALUE and COMMENT."
409 (declare (debug defvar) (doc-string 3))
410 `(progn
411 (defvar ,name ,value ,comment)
412 (make-variable-buffer-local ',name)))
413
414 (defvar js2-EOF_CHAR -1
415 "Represents end of stream. Distinct from js2-EOF token type.")
416
417 ;; I originally used symbols to represent tokens, but Rhino uses
418 ;; ints and then sets various flag bits in them, so ints it is.
419 ;; The upshot is that we need a `js2-' prefix in front of each name.
420 (defvar js2-ERROR -1)
421 (defvar js2-EOF 0)
422 (defvar js2-EOL 1)
423 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
424 (defvar js2-LEAVEWITH 3)
425 (defvar js2-RETURN 4)
426 (defvar js2-GOTO 5)
427 (defvar js2-IFEQ 6)
428 (defvar js2-IFNE 7)
429 (defvar js2-SETNAME 8)
430 (defvar js2-BITOR 9)
431 (defvar js2-BITXOR 10)
432 (defvar js2-BITAND 11)
433 (defvar js2-EQ 12)
434 (defvar js2-NE 13)
435 (defvar js2-LT 14)
436 (defvar js2-LE 15)
437 (defvar js2-GT 16)
438 (defvar js2-GE 17)
439 (defvar js2-LSH 18)
440 (defvar js2-RSH 19)
441 (defvar js2-URSH 20)
442 (defvar js2-ADD 21) ; infix plus
443 (defvar js2-SUB 22) ; infix minus
444 (defvar js2-MUL 23)
445 (defvar js2-DIV 24)
446 (defvar js2-MOD 25)
447 (defvar js2-NOT 26)
448 (defvar js2-BITNOT 27)
449 (defvar js2-POS 28) ; unary plus
450 (defvar js2-NEG 29) ; unary minus
451 (defvar js2-NEW 30)
452 (defvar js2-DELPROP 31)
453 (defvar js2-TYPEOF 32)
454 (defvar js2-GETPROP 33)
455 (defvar js2-GETPROPNOWARN 34)
456 (defvar js2-SETPROP 35)
457 (defvar js2-GETELEM 36)
458 (defvar js2-SETELEM 37)
459 (defvar js2-CALL 38)
460 (defvar js2-NAME 39) ; an identifier
461 (defvar js2-NUMBER 40)
462 (defvar js2-STRING 41)
463 (defvar js2-NULL 42)
464 (defvar js2-THIS 43)
465 (defvar js2-FALSE 44)
466 (defvar js2-TRUE 45)
467 (defvar js2-SHEQ 46) ; shallow equality (===)
468 (defvar js2-SHNE 47) ; shallow inequality (!==)
469 (defvar js2-REGEXP 48)
470 (defvar js2-BINDNAME 49)
471 (defvar js2-THROW 50)
472 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
473 (defvar js2-IN 52)
474 (defvar js2-INSTANCEOF 53)
475 (defvar js2-LOCAL_LOAD 54)
476 (defvar js2-GETVAR 55)
477 (defvar js2-SETVAR 56)
478 (defvar js2-CATCH_SCOPE 57)
479 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
480 (defvar js2-ENUM_INIT_VALUES 59)
481 (defvar js2-ENUM_INIT_ARRAY 60)
482 (defvar js2-ENUM_NEXT 61)
483 (defvar js2-ENUM_ID 62)
484 (defvar js2-THISFN 63)
485 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
486 (defvar js2-ARRAYLIT 65) ; array literal
487 (defvar js2-OBJECTLIT 66) ; object literal
488 (defvar js2-GET_REF 67) ; *reference
489 (defvar js2-SET_REF 68) ; *reference = something
490 (defvar js2-DEL_REF 69) ; delete reference
491 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
492 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
493 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
494
495 ;; XML support
496 (defvar js2-DEFAULTNAMESPACE 73)
497 (defvar js2-ESCXMLATTR 74)
498 (defvar js2-ESCXMLTEXT 75)
499 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
500 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
501 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
502 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
503
504 (defvar js2-first-bytecode js2-ENTERWITH)
505 (defvar js2-last-bytecode js2-REF_NS_NAME)
506
507 (defvar js2-TRY 80)
508 (defvar js2-SEMI 81) ; semicolon
509 (defvar js2-LB 82) ; left and right brackets
510 (defvar js2-RB 83)
511 (defvar js2-LC 84) ; left and right curly-braces
512 (defvar js2-RC 85)
513 (defvar js2-LP 86) ; left and right parens
514 (defvar js2-RP 87)
515 (defvar js2-COMMA 88) ; comma operator
516
517 (defvar js2-ASSIGN 89) ; simple assignment (=)
518 (defvar js2-ASSIGN_BITOR 90) ; |=
519 (defvar js2-ASSIGN_BITXOR 91) ; ^=
520 (defvar js2-ASSIGN_BITAND 92) ; &=
521 (defvar js2-ASSIGN_LSH 93) ; <<=
522 (defvar js2-ASSIGN_RSH 94) ; >>=
523 (defvar js2-ASSIGN_URSH 95) ; >>>=
524 (defvar js2-ASSIGN_ADD 96) ; +=
525 (defvar js2-ASSIGN_SUB 97) ; -=
526 (defvar js2-ASSIGN_MUL 98) ; *=
527 (defvar js2-ASSIGN_DIV 99) ; /=
528 (defvar js2-ASSIGN_MOD 100) ; %=
529
530 (defvar js2-first-assign js2-ASSIGN)
531 (defvar js2-last-assign js2-ASSIGN_MOD)
532
533 (defvar js2-HOOK 101) ; conditional (?:)
534 (defvar js2-COLON 102)
535 (defvar js2-OR 103) ; logical or (||)
536 (defvar js2-AND 104) ; logical and (&&)
537 (defvar js2-INC 105) ; increment/decrement (++ --)
538 (defvar js2-DEC 106)
539 (defvar js2-DOT 107) ; member operator (.)
540 (defvar js2-FUNCTION 108) ; function keyword
541 (defvar js2-EXPORT 109) ; export keyword
542 (defvar js2-IMPORT 110) ; import keyword
543 (defvar js2-IF 111) ; if keyword
544 (defvar js2-ELSE 112) ; else keyword
545 (defvar js2-SWITCH 113) ; switch keyword
546 (defvar js2-CASE 114) ; case keyword
547 (defvar js2-DEFAULT 115) ; default keyword
548 (defvar js2-WHILE 116) ; while keyword
549 (defvar js2-DO 117) ; do keyword
550 (defvar js2-FOR 118) ; for keyword
551 (defvar js2-BREAK 119) ; break keyword
552 (defvar js2-CONTINUE 120) ; continue keyword
553 (defvar js2-VAR 121) ; var keyword
554 (defvar js2-WITH 122) ; with keyword
555 (defvar js2-CATCH 123) ; catch keyword
556 (defvar js2-FINALLY 124) ; finally keyword
557 (defvar js2-VOID 125) ; void keyword
558 (defvar js2-RESERVED 126) ; reserved keywords
559
560 (defvar js2-EMPTY 127)
561
562 ;; Types used for the parse tree - never returned by scanner.
563
564 (defvar js2-BLOCK 128) ; statement block
565 (defvar js2-LABEL 129) ; label
566 (defvar js2-TARGET 130)
567 (defvar js2-LOOP 131)
568 (defvar js2-EXPR_VOID 132) ; expression statement in functions
569 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
570 (defvar js2-JSR 134)
571 (defvar js2-SCRIPT 135) ; top-level node for entire script
572 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
573 (defvar js2-USE_STACK 137)
574 (defvar js2-SETPROP_OP 138) ; x.y op= something
575 (defvar js2-SETELEM_OP 139) ; x[y] op= something
576 (defvar js2-LOCAL_BLOCK 140)
577 (defvar js2-SET_REF_OP 141) ; *reference op= something
578
579 ;; For XML support:
580 (defvar js2-DOTDOT 142) ; member operator (..)
581 (defvar js2-COLONCOLON 143) ; namespace::name
582 (defvar js2-XML 144) ; XML type
583 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
584 (defvar js2-XMLATTR 146) ; @
585 (defvar js2-XMLEND 147)
586
587 ;; Optimizer-only tokens
588 (defvar js2-TO_OBJECT 148)
589 (defvar js2-TO_DOUBLE 149)
590
591 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
592 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
593 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
594 (defvar js2-CONST 153)
595 (defvar js2-SETCONST 154)
596 (defvar js2-SETCONSTVAR 155)
597 (defvar js2-ARRAYCOMP 156)
598 (defvar js2-LETEXPR 157)
599 (defvar js2-WITHEXPR 158)
600 (defvar js2-DEBUGGER 159)
601
602 (defvar js2-COMMENT 160)
603 (defvar js2-TRIPLEDOT 161) ; for rest parameter
604 (defvar js2-ARROW 162) ; function arrow (=>)
605 (defvar js2-CLASS 163)
606 (defvar js2-EXTENDS 164)
607 (defvar js2-SUPER 165)
608 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
609 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
610 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
611
612 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
613
614 (defconst js2-debug-print-trees nil)
615
616 ;; Rhino accepts any string or stream as input. Emacs character
617 ;; processing works best in buffers, so we'll assume the input is a
618 ;; buffer. JavaScript strings can be copied into temp buffers before
619 ;; scanning them.
620
621 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
622 ;; They're the Emacs equivalent of instance variables, more or less.
623
624 (js2-deflocal js2-ts-dirty-line nil
625 "Token stream buffer-local variable.
626 Indicates stuff other than whitespace since start of line.")
627
628 (js2-deflocal js2-ts-hit-eof nil
629 "Token stream buffer-local variable.")
630
631 ;; FIXME: Unused.
632 (js2-deflocal js2-ts-line-start 0
633 "Token stream buffer-local variable.")
634
635 (js2-deflocal js2-ts-lineno 1
636 "Token stream buffer-local variable.")
637
638 ;; FIXME: Unused.
639 (js2-deflocal js2-ts-line-end-char -1
640 "Token stream buffer-local variable.")
641
642 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
643 "Token stream buffer-local variable.
644 Current scan position.")
645
646 ;; FIXME: Unused.
647 (js2-deflocal js2-ts-is-xml-attribute nil
648 "Token stream buffer-local variable.")
649
650 (js2-deflocal js2-ts-xml-is-tag-content nil
651 "Token stream buffer-local variable.")
652
653 (js2-deflocal js2-ts-xml-open-tags-count 0
654 "Token stream buffer-local variable.")
655
656 (js2-deflocal js2-ts-string-buffer nil
657 "Token stream buffer-local variable.
658 List of chars built up while scanning various tokens.")
659
660 (cl-defstruct (js2-token
661 (:constructor nil)
662 (:constructor make-js2-token (beg)))
663 "Value returned from the token stream."
664 (type js2-EOF)
665 (beg 1)
666 (end -1)
667 (string "")
668 number
669 number-base
670 regexp-flags
671 comment-type
672 follows-eol-p)
673
674 ;; Have to call `js2-init-scanner' to initialize the values.
675 (js2-deflocal js2-ti-tokens nil)
676 (js2-deflocal js2-ti-tokens-cursor nil)
677 (js2-deflocal js2-ti-lookahead nil)
678
679 (cl-defstruct (js2-ts-state
680 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
681 (cursor js2-ts-cursor)
682 (tokens (copy-sequence js2-ti-tokens))
683 (tokens-cursor js2-ti-tokens-cursor)
684 (lookahead js2-ti-lookahead))))
685 lineno
686 cursor
687 tokens
688 tokens-cursor
689 lookahead)
690
691 ;;; Parser variables
692
693 (js2-deflocal js2-parsed-errors nil
694 "List of errors produced during scanning/parsing.")
695
696 (js2-deflocal js2-parsed-warnings nil
697 "List of warnings produced during scanning/parsing.")
698
699 (js2-deflocal js2-recover-from-parse-errors t
700 "Non-nil to continue parsing after a syntax error.
701
702 In recovery mode, the AST will be built in full, and any error
703 nodes will be flagged with appropriate error information. If
704 this flag is nil, a syntax error will result in an error being
705 signaled.
706
707 The variable is automatically buffer-local, because different
708 modes that use the parser will need different settings.")
709
710 (js2-deflocal js2-parse-hook nil
711 "List of callbacks for receiving parsing progress.")
712
713 (defvar js2-parse-finished-hook nil
714 "List of callbacks to notify when parsing finishes.
715 Not called if parsing was interrupted.")
716
717 (js2-deflocal js2-is-eval-code nil
718 "True if we're evaluating code in a string.
719 If non-nil, the tokenizer will record the token text, and the AST nodes
720 will record their source text. Off by default for IDE modes, since the
721 text is available in the buffer.")
722
723 (defvar js2-parse-ide-mode t
724 "Non-nil if the parser is being used for `js2-mode'.
725 If non-nil, the parser will set text properties for fontification
726 and the syntax table. The value should be nil when using the
727 parser as a frontend to an interpreter or byte compiler.")
728
729 ;;; Parser instance variables (buffer-local vars for js2-parse)
730
731 (defconst js2-ti-after-eol (lsh 1 16)
732 "Flag: first token of the source line.")
733
734 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
735
736 (js2-deflocal js2-compiler-generate-debug-info t)
737 (js2-deflocal js2-compiler-use-dynamic-scope nil)
738 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
739 (js2-deflocal js2-compiler-xml-available t)
740 (js2-deflocal js2-compiler-optimization-level 0)
741 (js2-deflocal js2-compiler-generating-source t)
742 (js2-deflocal js2-compiler-strict-mode nil)
743 (js2-deflocal js2-compiler-report-warning-as-error nil)
744 (js2-deflocal js2-compiler-generate-observer-count nil)
745 (js2-deflocal js2-compiler-activation-names nil)
746
747 ;; SKIP: sourceURI
748
749 ;; There's a compileFunction method in Context.java - may need it.
750 (js2-deflocal js2-called-by-compile-function nil
751 "True if `js2-parse' was called by `js2-compile-function'.
752 Will only be used when we finish implementing the interpreter.")
753
754 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
755
756 ;; SKIP: node factory - we're going to just call functions directly,
757 ;; and eventually go to a unified AST format.
758
759 (js2-deflocal js2-nesting-of-function 0)
760
761 (js2-deflocal js2-recorded-identifiers nil
762 "Tracks identifiers found during parsing.")
763
764 (js2-deflocal js2-is-in-destructuring nil
765 "True while parsing destructuring expression.")
766
767 (js2-deflocal js2-in-use-strict-directive nil
768 "True while inside a script or function under strict mode.")
769
770 (defcustom js2-global-externs nil
771 "A list of any extern names you'd like to consider always declared.
772 This list is global and is used by all `js2-mode' files.
773 You can create buffer-local externs list using `js2-additional-externs'.
774
775 There is also a buffer-local variable `js2-default-externs',
776 which is initialized by default to include the Ecma-262 externs
777 and the standard browser externs. The three lists are all
778 checked during highlighting."
779 :type 'list
780 :group 'js2-mode)
781
782 (js2-deflocal js2-default-externs nil
783 "Default external declarations.
784
785 These are currently only used for highlighting undeclared variables,
786 which only worries about top-level (unqualified) references.
787 As js2-mode's processing improves, we will flesh out this list.
788
789 The initial value is set to `js2-ecma-262-externs', unless some
790 of the `js2-include-?-externs' variables are set to t, in which
791 case the browser, Rhino and/or Node.js externs are also included.
792
793 See `js2-additional-externs' for more information.")
794
795 (defcustom js2-include-browser-externs t
796 "Non-nil to include browser externs in the master externs list.
797 If you work on JavaScript files that are not intended for browsers,
798 such as Mozilla Rhino server-side JavaScript, set this to nil.
799 See `js2-additional-externs' for more information about externs."
800 :type 'boolean
801 :group 'js2-mode)
802
803 (defcustom js2-include-rhino-externs nil
804 "Non-nil to include Mozilla Rhino externs in the master externs list.
805 See `js2-additional-externs' for more information about externs."
806 :type 'boolean
807 :group 'js2-mode)
808
809 (defcustom js2-include-node-externs nil
810 "Non-nil to include Node.js externs in the master externs list.
811 See `js2-additional-externs' for more information about externs."
812 :type 'boolean
813 :group 'js2-mode)
814
815 (js2-deflocal js2-additional-externs nil
816 "A buffer-local list of additional external declarations.
817 It is used to decide whether variables are considered undeclared
818 for purposes of highlighting.
819
820 Each entry is a Lisp string. The string should be the fully qualified
821 name of an external entity. All externs should be added to this list,
822 so that as js2-mode's processing improves it can take advantage of them.
823
824 You may want to declare your externs in three ways.
825 First, you can add externs that are valid for all your JavaScript files.
826 You should probably do this by adding them to `js2-global-externs', which
827 is a global list used for all js2-mode files.
828
829 Next, you can add a function to `js2-init-hook' that adds additional
830 externs appropriate for the specific file, perhaps based on its path.
831 These should go in `js2-additional-externs', which is buffer-local.
832
833 Third, you can use JSLint's global declaration, as long as
834 `js2-include-jslint-globals' is non-nil, which see.
835
836 Finally, you can add a function to `js2-post-parse-callbacks',
837 which is called after parsing completes, and `js2-mode-ast' is bound to
838 the root of the parse tree. At this stage you can set up an AST
839 node visitor using `js2-visit-ast' and examine the parse tree
840 for specific import patterns that may imply the existence of
841 other externs, possibly tied to your build system. These should also
842 be added to `js2-additional-externs'.
843
844 Your post-parse callback may of course also use the simpler and
845 faster (but perhaps less robust) approach of simply scanning the
846 buffer text for your imports, using regular expressions.")
847
848 ;; SKIP: decompiler
849 ;; SKIP: encoded-source
850
851 ;;; The following variables are per-function and should be saved/restored
852 ;;; during function parsing...
853
854 (js2-deflocal js2-current-script-or-fn nil)
855 (js2-deflocal js2-current-scope nil)
856 (js2-deflocal js2-nesting-of-with 0)
857 (js2-deflocal js2-label-set nil
858 "An alist mapping label names to nodes.")
859
860 (js2-deflocal js2-loop-set nil)
861 (js2-deflocal js2-loop-and-switch-set nil)
862 (js2-deflocal js2-has-return-value nil)
863 (js2-deflocal js2-end-flags 0)
864
865 ;;; ...end of per function variables
866
867 ;; These flags enumerate the possible ways a statement/function can
868 ;; terminate. These flags are used by endCheck() and by the Parser to
869 ;; detect inconsistent return usage.
870 ;;
871 ;; END_UNREACHED is reserved for code paths that are assumed to always be
872 ;; able to execute (example: throw, continue)
873 ;;
874 ;; END_DROPS_OFF indicates if the statement can transfer control to the
875 ;; next one. Statement such as return dont. A compound statement may have
876 ;; some branch that drops off control to the next statement.
877 ;;
878 ;; END_RETURNS indicates that the statement can return (without arguments)
879 ;; END_RETURNS_VALUE indicates that the statement can return a value.
880 ;;
881 ;; A compound statement such as
882 ;; if (condition) {
883 ;; return value;
884 ;; }
885 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
886
887 (defconst js2-end-unreached #x0)
888 (defconst js2-end-drops-off #x1)
889 (defconst js2-end-returns #x2)
890 (defconst js2-end-returns-value #x4)
891
892 ;; Rhino awkwardly passes a statementLabel parameter to the
893 ;; statementHelper() function, the main statement parser, which
894 ;; is then used by quite a few of the sub-parsers. We just make
895 ;; it a buffer-local variable and make sure it's cleaned up properly.
896 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
897
898 ;; Similarly, Rhino passes an inForInit boolean through about half
899 ;; the expression parsers. We use a dynamically-scoped variable,
900 ;; which makes it easier to funcall the parsers individually without
901 ;; worrying about whether they take the parameter or not.
902 (js2-deflocal js2-in-for-init nil)
903 (js2-deflocal js2-temp-name-counter 0)
904 (js2-deflocal js2-parse-stmt-count 0)
905
906 (defsubst js2-get-next-temp-name ()
907 (format "$%d" (cl-incf js2-temp-name-counter)))
908
909 (defvar js2-parse-interruptable-p t
910 "Set this to nil to force parse to continue until finished.
911 This will mostly be useful for interpreters.")
912
913 (defvar js2-statements-per-pause 50
914 "Pause after this many statements to check for user input.
915 If user input is pending, stop the parse and discard the tree.
916 This makes for a smoother user experience for large files.
917 You may have to wait a second or two before the highlighting
918 and error-reporting appear, but you can always type ahead if
919 you wish. This appears to be more or less how Eclipse, IntelliJ
920 and other editors work.")
921
922 (js2-deflocal js2-record-comments t
923 "Instructs the scanner to record comments in `js2-scanned-comments'.")
924
925 (js2-deflocal js2-scanned-comments nil
926 "List of all comments from the current parse.")
927
928 (defcustom js2-mode-indent-inhibit-undo nil
929 "Non-nil to disable collection of Undo information when indenting lines.
930 Some users have requested this behavior. It's nil by default because
931 other Emacs modes don't work this way."
932 :type 'boolean
933 :group 'js2-mode)
934
935 (defcustom js2-mode-indent-ignore-first-tab nil
936 "If non-nil, ignore first TAB keypress if we look indented properly.
937 It's fairly common for users to navigate to an already-indented line
938 and press TAB for reassurance that it's been indented. For this class
939 of users, we want the first TAB press on a line to be ignored if the
940 line is already indented to one of the precomputed alternatives.
941
942 This behavior is only partly implemented. If you TAB-indent a line,
943 navigate to another line, and then navigate back, it fails to clear
944 the last-indented variable, so it thinks you've already hit TAB once,
945 and performs the indent. A full solution would involve getting on the
946 point-motion hooks for the entire buffer. If we come across another
947 use cases that requires watching point motion, I'll consider doing it.
948
949 If you set this variable to nil, then the TAB key will always change
950 the indentation of the current line, if more than one alternative
951 indentation spot exists."
952 :type 'boolean
953 :group 'js2-mode)
954
955 (defvar js2-indent-hook nil
956 "A hook for user-defined indentation rules.
957
958 Functions on this hook should expect two arguments: (LIST INDEX)
959 The LIST argument is the list of computed indentation points for
960 the current line. INDEX is the list index of the indentation point
961 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
962 indent function is not going to change the current line indentation.
963
964 If a hook function on this list returns a non-nil value, then
965 `js2-bounce-indent' assumes the hook function has performed its own
966 indentation, and will do nothing. If all hook functions on the list
967 return nil, then `js2-bounce-indent' will use its computed indentation
968 and reindent the line.
969
970 When hook functions on this hook list are called, the variable
971 `js2-mode-ast' may or may not be set, depending on whether the
972 parse tree is available. If the variable is nil, you can pass a
973 callback to `js2-mode-wait-for-parse', and your callback will be
974 called after the new parse tree is built. This can take some time
975 in large files.")
976
977 (defface js2-warning
978 `((((class color) (background light))
979 (:underline "orange"))
980 (((class color) (background dark))
981 (:underline "orange"))
982 (t (:underline t)))
983 "Face for JavaScript warnings."
984 :group 'js2-mode)
985
986 (defface js2-error
987 `((((class color) (background light))
988 (:foreground "red"))
989 (((class color) (background dark))
990 (:foreground "red"))
991 (t (:foreground "red")))
992 "Face for JavaScript errors."
993 :group 'js2-mode)
994
995 (defface js2-jsdoc-tag
996 '((t :foreground "SlateGray"))
997 "Face used to highlight @whatever tags in jsdoc comments."
998 :group 'js2-mode)
999
1000 (defface js2-jsdoc-type
1001 '((t :foreground "SteelBlue"))
1002 "Face used to highlight {FooBar} types in jsdoc comments."
1003 :group 'js2-mode)
1004
1005 (defface js2-jsdoc-value
1006 '((t :foreground "PeachPuff3"))
1007 "Face used to highlight tag values in jsdoc comments."
1008 :group 'js2-mode)
1009
1010 (defface js2-function-param
1011 '((t :foreground "SeaGreen"))
1012 "Face used to highlight function parameters in javascript."
1013 :group 'js2-mode)
1014
1015 (defface js2-function-call
1016 '((t :inherit default))
1017 "Face used to highlight function name in calls."
1018 :group 'js2-mode)
1019
1020 (defface js2-instance-member
1021 '((t :foreground "DarkOrchid"))
1022 "Face used to highlight instance variables in javascript.
1023 Not currently used."
1024 :group 'js2-mode)
1025
1026 (defface js2-private-member
1027 '((t :foreground "PeachPuff3"))
1028 "Face used to highlight calls to private methods in javascript.
1029 Not currently used."
1030 :group 'js2-mode)
1031
1032 (defface js2-private-function-call
1033 '((t :foreground "goldenrod"))
1034 "Face used to highlight calls to private functions in javascript.
1035 Not currently used."
1036 :group 'js2-mode)
1037
1038 (defface js2-jsdoc-html-tag-name
1039 '((((class color) (min-colors 88) (background light))
1040 (:foreground "rosybrown"))
1041 (((class color) (min-colors 8) (background dark))
1042 (:foreground "yellow"))
1043 (((class color) (min-colors 8) (background light))
1044 (:foreground "magenta")))
1045 "Face used to highlight jsdoc html tag names"
1046 :group 'js2-mode)
1047
1048 (defface js2-jsdoc-html-tag-delimiter
1049 '((((class color) (min-colors 88) (background light))
1050 (:foreground "dark khaki"))
1051 (((class color) (min-colors 8) (background dark))
1052 (:foreground "green"))
1053 (((class color) (min-colors 8) (background light))
1054 (:foreground "green")))
1055 "Face used to highlight brackets in jsdoc html tags."
1056 :group 'js2-mode)
1057
1058 (defface js2-external-variable
1059 '((t :foreground "orange"))
1060 "Face used to highlight undeclared variable identifiers.")
1061
1062 (defcustom js2-init-hook nil
1063 "List of functions to be called after `js2-mode' or
1064 `js2-minor-mode' has initialized all variables, before parsing
1065 the buffer for the first time."
1066 :type 'hook
1067 :group 'js2-mode
1068 :version "20130608")
1069
1070 (defcustom js2-post-parse-callbacks nil
1071 "List of callback functions invoked after parsing finishes.
1072 Currently, the main use for this function is to add synthetic
1073 declarations to `js2-recorded-identifiers', which see."
1074 :type 'hook
1075 :group 'js2-mode)
1076
1077 (defcustom js2-build-imenu-callbacks nil
1078 "List of functions called during Imenu index generation.
1079 It's a good place to add additional entries to it, using
1080 `js2-record-imenu-entry'."
1081 :type 'hook
1082 :group 'js2-mode)
1083
1084 (defcustom js2-highlight-external-variables t
1085 "Non-nil to highlight undeclared variable identifiers.
1086 An undeclared variable is any variable not declared with var or let
1087 in the current scope or any lexically enclosing scope. If you use
1088 such a variable, then you are either expecting it to originate from
1089 another file, or you've got a potential bug."
1090 :type 'boolean
1091 :group 'js2-mode)
1092
1093 (defcustom js2-warn-about-unused-function-arguments nil
1094 "Non-nil to treat function arguments like declared-but-unused variables."
1095 :type 'booleanp
1096 :group 'js2-mode)
1097
1098 (defcustom js2-include-jslint-globals t
1099 "Non-nil to include the identifiers from JSLint global
1100 declaration (see http://www.jslint.com/lint.html#global) in the
1101 buffer-local externs list. See `js2-additional-externs' for more
1102 information."
1103 :type 'boolean
1104 :group 'js2-mode)
1105
1106 (defvar js2-mode-map
1107 (let ((map (make-sparse-keymap)))
1108 (define-key map [mouse-1] #'js2-mode-show-node)
1109 (define-key map (kbd "M-j") #'js2-line-break)
1110 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1111 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1112 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1113 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1114 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1115 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1116 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1117 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1118
1119 (define-key map [menu-bar javascript]
1120 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1121
1122 (define-key map [menu-bar javascript customize-js2-mode]
1123 '(menu-item "Customize js2-mode" js2-mode-customize
1124 :help "Customize the behavior of this mode"))
1125
1126 (define-key map [menu-bar javascript js2-force-refresh]
1127 '(menu-item "Force buffer refresh" js2-mode-reset
1128 :help "Re-parse the buffer from scratch"))
1129
1130 (define-key map [menu-bar javascript separator-2]
1131 '("--"))
1132
1133 (define-key map [menu-bar javascript next-error]
1134 '(menu-item "Next warning or error" next-error
1135 :enabled (and js2-mode-ast
1136 (or (js2-ast-root-errors js2-mode-ast)
1137 (js2-ast-root-warnings js2-mode-ast)))
1138 :help "Move to next warning or error"))
1139
1140 (define-key map [menu-bar javascript display-errors]
1141 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1142 :visible (not js2-mode-show-parse-errors)
1143 :help "Turn on display of warnings and errors"))
1144
1145 (define-key map [menu-bar javascript hide-errors]
1146 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1147 :visible js2-mode-show-parse-errors
1148 :help "Turn off display of warnings and errors"))
1149
1150 (define-key map [menu-bar javascript separator-1]
1151 '("--"))
1152
1153 (define-key map [menu-bar javascript js2-toggle-function]
1154 '(menu-item "Show/collapse element" js2-mode-toggle-element
1155 :help "Hide or show function body or comment"))
1156
1157 (define-key map [menu-bar javascript show-comments]
1158 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1159 :visible js2-mode-comments-hidden
1160 :help "Expand all hidden block comments"))
1161
1162 (define-key map [menu-bar javascript hide-comments]
1163 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1164 :visible (not js2-mode-comments-hidden)
1165 :help "Show block comments as /*...*/"))
1166
1167 (define-key map [menu-bar javascript show-all-functions]
1168 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1169 :visible js2-mode-functions-hidden
1170 :help "Expand all hidden function bodies"))
1171
1172 (define-key map [menu-bar javascript hide-all-functions]
1173 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1174 :visible (not js2-mode-functions-hidden)
1175 :help "Show {...} for all top-level function bodies"))
1176
1177 map)
1178 "Keymap used in `js2-mode' buffers.")
1179
1180 (defcustom js2-bounce-indent-p nil
1181 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1182 They will augment the default indent-line behavior with cycling
1183 among several computed alternatives. See the function
1184 `js2-bounce-indent' for details. The above commands will be
1185 bound to TAB and backtab."
1186 :type 'boolean
1187 :group 'js2-mode
1188 :set (lambda (sym value)
1189 (set-default sym value)
1190 (let ((map js2-mode-map))
1191 (if (not value)
1192 (progn
1193 (define-key map "\t" nil)
1194 (define-key map (kbd "<backtab>") nil))
1195 (define-key map "\t" #'js2-indent-bounce)
1196 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1197
1198 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1199
1200 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1201 "Matches a //-comment line. Must be first non-whitespace on line.
1202 First match-group is the leading whitespace.")
1203
1204 (defvar js2-mode-hook nil)
1205
1206 (js2-deflocal js2-mode-ast nil "Private variable.")
1207 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1208 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1209 (js2-deflocal js2-mode-parsing nil "Private variable.")
1210 (js2-deflocal js2-mode-node-overlay nil)
1211
1212 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1213 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1214
1215 (js2-deflocal js2-mode-fontifications nil "Private variable")
1216 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1217 (js2-deflocal js2-imenu-recorder nil "Private variable")
1218 (js2-deflocal js2-imenu-function-map nil "Private variable")
1219
1220 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1221 "Non-nil to emit status messages during parsing.")
1222
1223 (defvar js2-mode-functions-hidden nil "Private variable.")
1224 (defvar js2-mode-comments-hidden nil "Private variable.")
1225
1226 (defvar js2-mode-syntax-table
1227 (let ((table (make-syntax-table)))
1228 (c-populate-syntax-table table)
1229 (modify-syntax-entry ?` "\"" table)
1230 table)
1231 "Syntax table used in `js2-mode' buffers.")
1232
1233 (defvar js2-mode-abbrev-table nil
1234 "Abbrev table in use in `js2-mode' buffers.")
1235 (define-abbrev-table 'js2-mode-abbrev-table ())
1236
1237 (defvar js2-mode-pending-parse-callbacks nil
1238 "List of functions waiting to be notified that parse is finished.")
1239
1240 (defvar js2-mode-last-indented-line -1)
1241
1242 ;;; Localizable error and warning messages
1243
1244 ;; Messages are copied from Rhino's Messages.properties.
1245 ;; Many of the Java-specific messages have been elided.
1246 ;; Add any js2-specific ones at the end, so we can keep
1247 ;; this file synced with changes to Rhino's.
1248
1249 (defvar js2-message-table
1250 (make-hash-table :test 'equal :size 250)
1251 "Contains localized messages for `js2-mode'.")
1252
1253 ;; TODO(stevey): construct this table at compile-time.
1254 (defmacro js2-msg (key &rest strings)
1255 `(puthash ,key (concat ,@strings)
1256 js2-message-table))
1257
1258 (defun js2-get-msg (msg-key)
1259 "Look up a localized message.
1260 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1261 the correct number of ARGS must be provided."
1262 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1263 (args (if (listp msg-key) (cdr msg-key)))
1264 (msg (gethash key js2-message-table)))
1265 (if msg
1266 (apply #'format msg args)
1267 key))) ; default to showing the key
1268
1269 (js2-msg "msg.dup.parms"
1270 "Duplicate parameter name '%s'.")
1271
1272 (js2-msg "msg.too.big.jump"
1273 "Program too complex: jump offset too big.")
1274
1275 (js2-msg "msg.too.big.index"
1276 "Program too complex: internal index exceeds 64K limit.")
1277
1278 (js2-msg "msg.while.compiling.fn"
1279 "Encountered code generation error while compiling function '%s': %s")
1280
1281 (js2-msg "msg.while.compiling.script"
1282 "Encountered code generation error while compiling script: %s")
1283
1284 ;; Context
1285 (js2-msg "msg.ctor.not.found"
1286 "Constructor for '%s' not found.")
1287
1288 (js2-msg "msg.not.ctor"
1289 "'%s' is not a constructor.")
1290
1291 ;; FunctionObject
1292 (js2-msg "msg.varargs.ctor"
1293 "Method or constructor '%s' must be static "
1294 "with the signature (Context cx, Object[] args, "
1295 "Function ctorObj, boolean inNewExpr) "
1296 "to define a variable arguments constructor.")
1297
1298 (js2-msg "msg.varargs.fun"
1299 "Method '%s' must be static with the signature "
1300 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1301 "to define a variable arguments function.")
1302
1303 (js2-msg "msg.incompat.call"
1304 "Method '%s' called on incompatible object.")
1305
1306 (js2-msg "msg.bad.parms"
1307 "Unsupported parameter type '%s' in method '%s'.")
1308
1309 (js2-msg "msg.bad.method.return"
1310 "Unsupported return type '%s' in method '%s'.")
1311
1312 (js2-msg "msg.bad.ctor.return"
1313 "Construction of objects of type '%s' is not supported.")
1314
1315 (js2-msg "msg.no.overload"
1316 "Method '%s' occurs multiple times in class '%s'.")
1317
1318 (js2-msg "msg.method.not.found"
1319 "Method '%s' not found in '%s'.")
1320
1321 ;; IRFactory
1322
1323 (js2-msg "msg.bad.for.in.lhs"
1324 "Invalid left-hand side of for..in loop.")
1325
1326 (js2-msg "msg.mult.index"
1327 "Only one variable allowed in for..in loop.")
1328
1329 (js2-msg "msg.bad.for.in.destruct"
1330 "Left hand side of for..in loop must be an array of "
1331 "length 2 to accept key/value pair.")
1332
1333 (js2-msg "msg.cant.convert"
1334 "Can't convert to type '%s'.")
1335
1336 (js2-msg "msg.bad.assign.left"
1337 "Invalid assignment left-hand side.")
1338
1339 (js2-msg "msg.bad.decr"
1340 "Invalid decrement operand.")
1341
1342 (js2-msg "msg.bad.incr"
1343 "Invalid increment operand.")
1344
1345 (js2-msg "msg.bad.yield"
1346 "yield must be in a function.")
1347
1348 (js2-msg "msg.yield.parenthesized"
1349 "yield expression must be parenthesized.")
1350
1351 ;; NativeGlobal
1352 (js2-msg "msg.cant.call.indirect"
1353 "Function '%s' must be called directly, and not by way of a "
1354 "function of another name.")
1355
1356 (js2-msg "msg.eval.nonstring"
1357 "Calling eval() with anything other than a primitive "
1358 "string value will simply return the value. "
1359 "Is this what you intended?")
1360
1361 (js2-msg "msg.eval.nonstring.strict"
1362 "Calling eval() with anything other than a primitive "
1363 "string value is not allowed in strict mode.")
1364
1365 (js2-msg "msg.bad.destruct.op"
1366 "Invalid destructuring assignment operator")
1367
1368 ;; NativeCall
1369 (js2-msg "msg.only.from.new"
1370 "'%s' may only be invoked from a `new' expression.")
1371
1372 (js2-msg "msg.deprec.ctor"
1373 "The '%s' constructor is deprecated.")
1374
1375 ;; NativeFunction
1376 (js2-msg "msg.no.function.ref.found"
1377 "no source found to decompile function reference %s")
1378
1379 (js2-msg "msg.arg.isnt.array"
1380 "second argument to Function.prototype.apply must be an array")
1381
1382 ;; NativeGlobal
1383 (js2-msg "msg.bad.esc.mask"
1384 "invalid string escape mask")
1385
1386 ;; NativeRegExp
1387 (js2-msg "msg.bad.quant"
1388 "Invalid quantifier %s")
1389
1390 (js2-msg "msg.overlarge.backref"
1391 "Overly large back reference %s")
1392
1393 (js2-msg "msg.overlarge.min"
1394 "Overly large minimum %s")
1395
1396 (js2-msg "msg.overlarge.max"
1397 "Overly large maximum %s")
1398
1399 (js2-msg "msg.zero.quant"
1400 "Zero quantifier %s")
1401
1402 (js2-msg "msg.max.lt.min"
1403 "Maximum %s less than minimum")
1404
1405 (js2-msg "msg.unterm.quant"
1406 "Unterminated quantifier %s")
1407
1408 (js2-msg "msg.unterm.paren"
1409 "Unterminated parenthetical %s")
1410
1411 (js2-msg "msg.unterm.class"
1412 "Unterminated character class %s")
1413
1414 (js2-msg "msg.bad.range"
1415 "Invalid range in character class.")
1416
1417 (js2-msg "msg.trail.backslash"
1418 "Trailing \\ in regular expression.")
1419
1420 (js2-msg "msg.re.unmatched.right.paren"
1421 "unmatched ) in regular expression.")
1422
1423 (js2-msg "msg.no.regexp"
1424 "Regular expressions are not available.")
1425
1426 (js2-msg "msg.bad.backref"
1427 "back-reference exceeds number of capturing parentheses.")
1428
1429 (js2-msg "msg.bad.regexp.compile"
1430 "Only one argument may be specified if the first "
1431 "argument to RegExp.prototype.compile is a RegExp object.")
1432
1433 ;; Parser
1434 (js2-msg "msg.got.syntax.errors"
1435 "Compilation produced %s syntax errors.")
1436
1437 (js2-msg "msg.var.redecl"
1438 "TypeError: redeclaration of var %s.")
1439
1440 (js2-msg "msg.const.redecl"
1441 "TypeError: redeclaration of const %s.")
1442
1443 (js2-msg "msg.let.redecl"
1444 "TypeError: redeclaration of variable %s.")
1445
1446 (js2-msg "msg.parm.redecl"
1447 "TypeError: redeclaration of formal parameter %s.")
1448
1449 (js2-msg "msg.fn.redecl"
1450 "TypeError: redeclaration of function %s.")
1451
1452 (js2-msg "msg.let.decl.not.in.block"
1453 "SyntaxError: let declaration not directly within block")
1454
1455 (js2-msg "msg.mod.import.decl.at.top.level"
1456 "SyntaxError: import declarations may only appear at the top level")
1457
1458 (js2-msg "msg.mod.as.after.reserved.word"
1459 "SyntaxError: missing keyword 'as' after reserved word %s")
1460
1461 (js2-msg "msg.mod.rc.after.import.spec.list"
1462 "SyntaxError: missing '}' after module specifier list")
1463
1464 (js2-msg "msg.mod.from.after.import.spec.set"
1465 "SyntaxError: missing keyword 'from' after import specifier set")
1466
1467 (js2-msg "msg.mod.declaration.after.import"
1468 "SyntaxError: missing declaration after 'import' keyword")
1469
1470 (js2-msg "msg.mod.spec.after.from"
1471 "SyntaxError: missing module specifier after 'from' keyword")
1472
1473 (js2-msg "msg.mod.export.decl.at.top.level"
1474 "SyntaxError: export declarations may only appear at top level")
1475
1476 (js2-msg "msg.mod.rc.after.export.spec.list"
1477 "SyntaxError: missing '}' after export specifier list")
1478
1479 ;; NodeTransformer
1480 (js2-msg "msg.dup.label"
1481 "duplicated label")
1482
1483 (js2-msg "msg.undef.label"
1484 "undefined label")
1485
1486 (js2-msg "msg.bad.break"
1487 "unlabelled break must be inside loop or switch")
1488
1489 (js2-msg "msg.continue.outside"
1490 "continue must be inside loop")
1491
1492 (js2-msg "msg.continue.nonloop"
1493 "continue can only use labels of iteration statements")
1494
1495 (js2-msg "msg.bad.throw.eol"
1496 "Line terminator is not allowed between the throw "
1497 "keyword and throw expression.")
1498
1499 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1500 "function statement requires a name")
1501
1502 (js2-msg "msg.no.paren.parms"
1503 "missing ( before function parameters.")
1504
1505 (js2-msg "msg.no.parm"
1506 "missing formal parameter")
1507
1508 (js2-msg "msg.no.paren.after.parms"
1509 "missing ) after formal parameters")
1510
1511 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1512 "parameter without default follows parameter with default")
1513
1514 (js2-msg "msg.param.after.rest" ; added by js2-mode
1515 "parameter after rest parameter")
1516
1517 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1518 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1519
1520 (js2-msg "msg.no.brace.body"
1521 "missing '{' before function body")
1522
1523 (js2-msg "msg.no.brace.after.body"
1524 "missing } after function body")
1525
1526 (js2-msg "msg.no.paren.cond"
1527 "missing ( before condition")
1528
1529 (js2-msg "msg.no.paren.after.cond"
1530 "missing ) after condition")
1531
1532 (js2-msg "msg.no.semi.stmt"
1533 "missing ; before statement")
1534
1535 (js2-msg "msg.missing.semi"
1536 "missing ; after statement")
1537
1538 (js2-msg "msg.no.name.after.dot"
1539 "missing name after . operator")
1540
1541 (js2-msg "msg.no.name.after.coloncolon"
1542 "missing name after :: operator")
1543
1544 (js2-msg "msg.no.name.after.dotdot"
1545 "missing name after .. operator")
1546
1547 (js2-msg "msg.no.name.after.xmlAttr"
1548 "missing name after .@")
1549
1550 (js2-msg "msg.no.bracket.index"
1551 "missing ] in index expression")
1552
1553 (js2-msg "msg.no.paren.switch"
1554 "missing ( before switch expression")
1555
1556 (js2-msg "msg.no.paren.after.switch"
1557 "missing ) after switch expression")
1558
1559 (js2-msg "msg.no.brace.switch"
1560 "missing '{' before switch body")
1561
1562 (js2-msg "msg.bad.switch"
1563 "invalid switch statement")
1564
1565 (js2-msg "msg.no.colon.case"
1566 "missing : after case expression")
1567
1568 (js2-msg "msg.double.switch.default"
1569 "double default label in the switch statement")
1570
1571 (js2-msg "msg.no.while.do"
1572 "missing while after do-loop body")
1573
1574 (js2-msg "msg.no.paren.for"
1575 "missing ( after for")
1576
1577 (js2-msg "msg.no.semi.for"
1578 "missing ; after for-loop initializer")
1579
1580 (js2-msg "msg.no.semi.for.cond"
1581 "missing ; after for-loop condition")
1582
1583 (js2-msg "msg.in.after.for.name"
1584 "missing in or of after for")
1585
1586 (js2-msg "msg.no.paren.for.ctrl"
1587 "missing ) after for-loop control")
1588
1589 (js2-msg "msg.no.paren.with"
1590 "missing ( before with-statement object")
1591
1592 (js2-msg "msg.no.paren.after.with"
1593 "missing ) after with-statement object")
1594
1595 (js2-msg "msg.no.with.strict"
1596 "with statements not allowed in strict mode")
1597
1598 (js2-msg "msg.no.paren.after.let"
1599 "missing ( after let")
1600
1601 (js2-msg "msg.no.paren.let"
1602 "missing ) after variable list")
1603
1604 (js2-msg "msg.no.curly.let"
1605 "missing } after let statement")
1606
1607 (js2-msg "msg.bad.return"
1608 "invalid return")
1609
1610 (js2-msg "msg.no.brace.block"
1611 "missing } in compound statement")
1612
1613 (js2-msg "msg.bad.label"
1614 "invalid label")
1615
1616 (js2-msg "msg.bad.var"
1617 "missing variable name")
1618
1619 (js2-msg "msg.bad.var.init"
1620 "invalid variable initialization")
1621
1622 (js2-msg "msg.no.colon.cond"
1623 "missing : in conditional expression")
1624
1625 (js2-msg "msg.no.paren.arg"
1626 "missing ) after argument list")
1627
1628 (js2-msg "msg.no.bracket.arg"
1629 "missing ] after element list")
1630
1631 (js2-msg "msg.bad.prop"
1632 "invalid property id")
1633
1634 (js2-msg "msg.no.colon.prop"
1635 "missing : after property id")
1636
1637 (js2-msg "msg.no.brace.prop"
1638 "missing } after property list")
1639
1640 (js2-msg "msg.no.paren"
1641 "missing ) in parenthetical")
1642
1643 (js2-msg "msg.reserved.id"
1644 "'%s' is a reserved identifier")
1645
1646 (js2-msg "msg.no.paren.catch"
1647 "missing ( before catch-block condition")
1648
1649 (js2-msg "msg.bad.catchcond"
1650 "invalid catch block condition")
1651
1652 (js2-msg "msg.catch.unreachable"
1653 "any catch clauses following an unqualified catch are unreachable")
1654
1655 (js2-msg "msg.no.brace.try"
1656 "missing '{' before try block")
1657
1658 (js2-msg "msg.no.brace.catchblock"
1659 "missing '{' before catch-block body")
1660
1661 (js2-msg "msg.try.no.catchfinally"
1662 "'try' without 'catch' or 'finally'")
1663
1664 (js2-msg "msg.no.return.value"
1665 "function %s does not always return a value")
1666
1667 (js2-msg "msg.anon.no.return.value"
1668 "anonymous function does not always return a value")
1669
1670 (js2-msg "msg.return.inconsistent"
1671 "return statement is inconsistent with previous usage")
1672
1673 (js2-msg "msg.generator.returns"
1674 "TypeError: legacy generator function '%s' returns a value")
1675
1676 (js2-msg "msg.anon.generator.returns"
1677 "TypeError: anonymous legacy generator function returns a value")
1678
1679 (js2-msg "msg.syntax"
1680 "syntax error")
1681
1682 (js2-msg "msg.unexpected.eof"
1683 "Unexpected end of file")
1684
1685 (js2-msg "msg.XML.bad.form"
1686 "illegally formed XML syntax")
1687
1688 (js2-msg "msg.XML.not.available"
1689 "XML runtime not available")
1690
1691 (js2-msg "msg.too.deep.parser.recursion"
1692 "Too deep recursion while parsing")
1693
1694 (js2-msg "msg.no.side.effects"
1695 "Code has no side effects")
1696
1697 (js2-msg "msg.extra.trailing.comma"
1698 "Trailing comma is not supported in some browsers")
1699
1700 (js2-msg "msg.array.trailing.comma"
1701 "Trailing comma yields different behavior across browsers")
1702
1703 (js2-msg "msg.equal.as.assign"
1704 (concat "Test for equality (==) mistyped as assignment (=)?"
1705 " (parenthesize to suppress warning)"))
1706
1707 (js2-msg "msg.var.hides.arg"
1708 "Variable %s hides argument")
1709
1710 (js2-msg "msg.destruct.assign.no.init"
1711 "Missing = in destructuring declaration")
1712
1713 (js2-msg "msg.no.octal.strict"
1714 "Octal numbers prohibited in strict mode.")
1715
1716 (js2-msg "msg.dup.obj.lit.prop.strict"
1717 "Property '%s' already defined in this object literal.")
1718
1719 (js2-msg "msg.dup.param.strict"
1720 "Parameter '%s' already declared in this function.")
1721
1722 (js2-msg "msg.bad.id.strict"
1723 "'%s' is not a valid identifier for this use in strict mode.")
1724
1725 ;; ScriptRuntime
1726 (js2-msg "msg.no.properties"
1727 "%s has no properties.")
1728
1729 (js2-msg "msg.invalid.iterator"
1730 "Invalid iterator value")
1731
1732 (js2-msg "msg.iterator.primitive"
1733 "__iterator__ returned a primitive value")
1734
1735 (js2-msg "msg.assn.create.strict"
1736 "Assignment to undeclared variable %s")
1737
1738 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1739 "Undeclared variable or function '%s'")
1740
1741 (js2-msg "msg.unused.variable" ; added by js2-mode
1742 "Unused variable or function '%s'")
1743
1744 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1745 "Variable '%s' referenced but never initialized")
1746
1747 (js2-msg "msg.ref.undefined.prop"
1748 "Reference to undefined property '%s'")
1749
1750 (js2-msg "msg.prop.not.found"
1751 "Property %s not found.")
1752
1753 (js2-msg "msg.invalid.type"
1754 "Invalid JavaScript value of type %s")
1755
1756 (js2-msg "msg.primitive.expected"
1757 "Primitive type expected (had %s instead)")
1758
1759 (js2-msg "msg.namespace.expected"
1760 "Namespace object expected to left of :: (found %s instead)")
1761
1762 (js2-msg "msg.null.to.object"
1763 "Cannot convert null to an object.")
1764
1765 (js2-msg "msg.undef.to.object"
1766 "Cannot convert undefined to an object.")
1767
1768 (js2-msg "msg.cyclic.value"
1769 "Cyclic %s value not allowed.")
1770
1771 (js2-msg "msg.is.not.defined"
1772 "'%s' is not defined.")
1773
1774 (js2-msg "msg.undef.prop.read"
1775 "Cannot read property '%s' from %s")
1776
1777 (js2-msg "msg.undef.prop.write"
1778 "Cannot set property '%s' of %s to '%s'")
1779
1780 (js2-msg "msg.undef.prop.delete"
1781 "Cannot delete property '%s' of %s")
1782
1783 (js2-msg "msg.undef.method.call"
1784 "Cannot call method '%s' of %s")
1785
1786 (js2-msg "msg.undef.with"
1787 "Cannot apply 'with' to %s")
1788
1789 (js2-msg "msg.isnt.function"
1790 "%s is not a function, it is %s.")
1791
1792 (js2-msg "msg.isnt.function.in"
1793 "Cannot call property %s in object %s. "
1794 "It is not a function, it is '%s'.")
1795
1796 (js2-msg "msg.function.not.found"
1797 "Cannot find function %s.")
1798
1799 (js2-msg "msg.function.not.found.in"
1800 "Cannot find function %s in object %s.")
1801
1802 (js2-msg "msg.isnt.xml.object"
1803 "%s is not an xml object.")
1804
1805 (js2-msg "msg.no.ref.to.get"
1806 "%s is not a reference to read reference value.")
1807
1808 (js2-msg "msg.no.ref.to.set"
1809 "%s is not a reference to set reference value to %s.")
1810
1811 (js2-msg "msg.no.ref.from.function"
1812 "Function %s can not be used as the left-hand "
1813 "side of assignment or as an operand of ++ or -- operator.")
1814
1815 (js2-msg "msg.bad.default.value"
1816 "Object's getDefaultValue() method returned an object.")
1817
1818 (js2-msg "msg.instanceof.not.object"
1819 "Can't use instanceof on a non-object.")
1820
1821 (js2-msg "msg.instanceof.bad.prototype"
1822 "'prototype' property of %s is not an object.")
1823
1824 (js2-msg "msg.bad.radix"
1825 "illegal radix %s.")
1826
1827 ;; ScriptableObject
1828 (js2-msg "msg.default.value"
1829 "Cannot find default value for object.")
1830
1831 (js2-msg "msg.zero.arg.ctor"
1832 "Cannot load class '%s' which has no zero-parameter constructor.")
1833
1834 (js2-msg "msg.ctor.multiple.parms"
1835 "Can't define constructor or class %s since more than "
1836 "one constructor has multiple parameters.")
1837
1838 (js2-msg "msg.extend.scriptable"
1839 "%s must extend ScriptableObject in order to define property %s.")
1840
1841 (js2-msg "msg.bad.getter.parms"
1842 "In order to define a property, getter %s must have zero "
1843 "parameters or a single ScriptableObject parameter.")
1844
1845 (js2-msg "msg.obj.getter.parms"
1846 "Expected static or delegated getter %s to take "
1847 "a ScriptableObject parameter.")
1848
1849 (js2-msg "msg.getter.static"
1850 "Getter and setter must both be static or neither be static.")
1851
1852 (js2-msg "msg.setter.return"
1853 "Setter must have void return type: %s")
1854
1855 (js2-msg "msg.setter2.parms"
1856 "Two-parameter setter must take a ScriptableObject as "
1857 "its first parameter.")
1858
1859 (js2-msg "msg.setter1.parms"
1860 "Expected single parameter setter for %s")
1861
1862 (js2-msg "msg.setter2.expected"
1863 "Expected static or delegated setter %s to take two parameters.")
1864
1865 (js2-msg "msg.setter.parms"
1866 "Expected either one or two parameters for setter.")
1867
1868 (js2-msg "msg.setter.bad.type"
1869 "Unsupported parameter type '%s' in setter '%s'.")
1870
1871 (js2-msg "msg.add.sealed"
1872 "Cannot add a property to a sealed object: %s.")
1873
1874 (js2-msg "msg.remove.sealed"
1875 "Cannot remove a property from a sealed object: %s.")
1876
1877 (js2-msg "msg.modify.sealed"
1878 "Cannot modify a property of a sealed object: %s.")
1879
1880 (js2-msg "msg.modify.readonly"
1881 "Cannot modify readonly property: %s.")
1882
1883 ;; TokenStream
1884 (js2-msg "msg.missing.exponent"
1885 "missing exponent")
1886
1887 (js2-msg "msg.caught.nfe"
1888 "number format error")
1889
1890 (js2-msg "msg.unterminated.string.lit"
1891 "unterminated string literal")
1892
1893 (js2-msg "msg.unterminated.comment"
1894 "unterminated comment")
1895
1896 (js2-msg "msg.unterminated.re.lit"
1897 "unterminated regular expression literal")
1898
1899 (js2-msg "msg.invalid.re.flag"
1900 "invalid flag after regular expression")
1901
1902 (js2-msg "msg.no.re.input.for"
1903 "no input for %s")
1904
1905 (js2-msg "msg.illegal.character"
1906 "illegal character")
1907
1908 (js2-msg "msg.invalid.escape"
1909 "invalid Unicode escape sequence")
1910
1911 (js2-msg "msg.bad.namespace"
1912 "not a valid default namespace statement. "
1913 "Syntax is: default xml namespace = EXPRESSION;")
1914
1915 ;; TokensStream warnings
1916 (js2-msg "msg.bad.octal.literal"
1917 "illegal octal literal digit %s; "
1918 "interpreting it as a decimal digit")
1919
1920 (js2-msg "msg.missing.hex.digits"
1921 "missing hexadecimal digits after '0x'")
1922
1923 (js2-msg "msg.missing.binary.digits"
1924 "missing binary digits after '0b'")
1925
1926 (js2-msg "msg.missing.octal.digits"
1927 "missing octal digits after '0o'")
1928
1929 (js2-msg "msg.script.is.not.constructor"
1930 "Script objects are not constructors.")
1931
1932 ;; Arrays
1933 (js2-msg "msg.arraylength.bad"
1934 "Inappropriate array length.")
1935
1936 ;; Arrays
1937 (js2-msg "msg.arraylength.too.big"
1938 "Array length %s exceeds supported capacity limit.")
1939
1940 ;; URI
1941 (js2-msg "msg.bad.uri"
1942 "Malformed URI sequence.")
1943
1944 ;; Number
1945 (js2-msg "msg.bad.precision"
1946 "Precision %s out of range.")
1947
1948 ;; NativeGenerator
1949 (js2-msg "msg.send.newborn"
1950 "Attempt to send value to newborn generator")
1951
1952 (js2-msg "msg.already.exec.gen"
1953 "Already executing generator")
1954
1955 (js2-msg "msg.StopIteration.invalid"
1956 "StopIteration may not be changed to an arbitrary object.")
1957
1958 ;; Interpreter
1959 (js2-msg "msg.yield.closing"
1960 "Yield from closing generator")
1961
1962 ;; Classes
1963 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1964 "class statement requires a name")
1965
1966 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1967 "unexpected ',' between class properties")
1968
1969 (js2-msg "msg.unexpected.static" ; added by js2-mode
1970 "unexpected 'static'")
1971
1972 (js2-msg "msg.missing.extends" ; added by js2-mode
1973 "name is required after extends")
1974
1975 (js2-msg "msg.no.brace.class" ; added by js2-mode
1976 "missing '{' before class body")
1977
1978 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1979 "missing ']' after computed property expression")
1980
1981 ;;; Tokens Buffer
1982
1983 (defconst js2-ti-max-lookahead 2)
1984 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1985
1986 (defun js2-new-token (offset)
1987 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1988 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1989 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1990 token))
1991
1992 (defsubst js2-current-token ()
1993 (aref js2-ti-tokens js2-ti-tokens-cursor))
1994
1995 (defsubst js2-current-token-string ()
1996 (js2-token-string (js2-current-token)))
1997
1998 (defsubst js2-current-token-type ()
1999 (js2-token-type (js2-current-token)))
2000
2001 (defsubst js2-current-token-beg ()
2002 (js2-token-beg (js2-current-token)))
2003
2004 (defsubst js2-current-token-end ()
2005 (js2-token-end (js2-current-token)))
2006
2007 (defun js2-current-token-len ()
2008 (let ((token (js2-current-token)))
2009 (- (js2-token-end token)
2010 (js2-token-beg token))))
2011
2012 (defun js2-ts-seek (state)
2013 (setq js2-ts-lineno (js2-ts-state-lineno state)
2014 js2-ts-cursor (js2-ts-state-cursor state)
2015 js2-ti-tokens (js2-ts-state-tokens state)
2016 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2017 js2-ti-lookahead (js2-ts-state-lookahead state)))
2018
2019 ;;; Utilities
2020
2021 (defun js2-delete-if (predicate list)
2022 "Remove all items satisfying PREDICATE in LIST."
2023 (cl-loop for item in list
2024 if (not (funcall predicate item))
2025 collect item))
2026
2027 (defun js2-position (element list)
2028 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2029 Returns nil if element is not found in the list."
2030 (let ((count 0)
2031 found)
2032 (while (and list (not found))
2033 (if (eq element (car list))
2034 (setq found t)
2035 (setq count (1+ count)
2036 list (cdr list))))
2037 (if found count)))
2038
2039 (defun js2-find-if (predicate list)
2040 "Find first item satisfying PREDICATE in LIST."
2041 (let (result)
2042 (while (and list (not result))
2043 (if (funcall predicate (car list))
2044 (setq result (car list)))
2045 (setq list (cdr list)))
2046 result))
2047
2048 (defmacro js2-time (form)
2049 "Evaluate FORM, discard result, and return elapsed time in sec."
2050 (declare (debug t))
2051 (let ((beg (make-symbol "--js2-time-beg--")))
2052 `(let ((,beg (current-time)))
2053 ,form
2054 (/ (truncate (* (- (float-time (current-time))
2055 (float-time ,beg))
2056 10000))
2057 10000.0))))
2058
2059 (defsubst js2-same-line (pos)
2060 "Return t if POS is on the same line as current point."
2061 (and (>= pos (point-at-bol))
2062 (<= pos (point-at-eol))))
2063
2064 (defun js2-code-bug ()
2065 "Signal an error when we encounter an unexpected code path."
2066 (error "failed assertion"))
2067
2068 (defsubst js2-record-text-property (beg end prop value)
2069 "Record a text property to set when parsing finishes."
2070 (push (list beg end prop value) js2-mode-deferred-properties))
2071
2072 ;; I'd like to associate errors with nodes, but for now the
2073 ;; easiest thing to do is get the context info from the last token.
2074 (defun js2-record-parse-error (msg &optional arg pos len)
2075 (push (list (list msg arg)
2076 (or pos (js2-current-token-beg))
2077 (or len (js2-current-token-len)))
2078 js2-parsed-errors))
2079
2080 (defun js2-report-error (msg &optional msg-arg pos len)
2081 "Signal a syntax error or record a parse error."
2082 (if js2-recover-from-parse-errors
2083 (js2-record-parse-error msg msg-arg pos len)
2084 (signal 'js2-syntax-error
2085 (list msg
2086 js2-ts-lineno
2087 (save-excursion
2088 (goto-char js2-ts-cursor)
2089 (current-column))
2090 js2-ts-hit-eof))))
2091
2092 (defun js2-report-warning (msg &optional msg-arg pos len face)
2093 (if js2-compiler-report-warning-as-error
2094 (js2-report-error msg msg-arg pos len)
2095 (push (list (list msg msg-arg)
2096 (or pos (js2-current-token-beg))
2097 (or len (js2-current-token-len))
2098 face)
2099 js2-parsed-warnings)))
2100
2101 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2102 (if js2-compiler-strict-mode
2103 (js2-report-warning msg-id msg-arg beg
2104 (and beg end (- end beg)))))
2105
2106 (put 'js2-syntax-error 'error-conditions
2107 '(error syntax-error js2-syntax-error))
2108 (put 'js2-syntax-error 'error-message "Syntax error")
2109
2110 (put 'js2-parse-error 'error-conditions
2111 '(error parse-error js2-parse-error))
2112 (put 'js2-parse-error 'error-message "Parse error")
2113
2114 (defmacro js2-clear-flag (flags flag)
2115 `(setq ,flags (logand ,flags (lognot ,flag))))
2116
2117 (defmacro js2-set-flag (flags flag)
2118 "Logical-or FLAG into FLAGS."
2119 `(setq ,flags (logior ,flags ,flag)))
2120
2121 (defsubst js2-flag-set-p (flags flag)
2122 (/= 0 (logand flags flag)))
2123
2124 (defsubst js2-flag-not-set-p (flags flag)
2125 (zerop (logand flags flag)))
2126
2127 ;;; AST struct and function definitions
2128
2129 ;; flags for ast node property 'member-type (used for e4x operators)
2130 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2131 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2132 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2133
2134 (defsubst js2-relpos (pos anchor)
2135 "Convert POS to be relative to ANCHOR.
2136 If POS is nil, returns nil."
2137 (and pos (- pos anchor)))
2138
2139 (defun js2-make-pad (indent)
2140 (if (zerop indent)
2141 ""
2142 (make-string (* indent js2-basic-offset) ? )))
2143
2144 (defun js2-visit-ast (node callback)
2145 "Visit every node in ast NODE with visitor CALLBACK.
2146
2147 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2148 called twice: once to visit the node, and again after all the node's
2149 children have been processed. The END-P argument is nil on the first
2150 call and non-nil on the second call. The return value of the callback
2151 affects the traversal: if non-nil, the children of NODE are processed.
2152 If the callback returns nil, or if the node has no children, then the
2153 callback is called immediately with a non-nil END-P argument.
2154
2155 The node traversal is approximately lexical-order, although there
2156 are currently no guarantees around this."
2157 (when node
2158 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2159 ;; visit the node
2160 (when (funcall callback node nil)
2161 ;; visit the kids
2162 (cond
2163 ((eq vfunc 'js2-visit-none)
2164 nil) ; don't even bother calling it
2165 ;; Each AST node type has to define a `js2-visitor' function
2166 ;; that takes a node and a callback, and calls `js2-visit-ast'
2167 ;; on each child of the node.
2168 (vfunc
2169 (funcall vfunc node callback))
2170 (t
2171 (error "%s does not define a visitor-traversal function"
2172 (aref node 0)))))
2173 ;; call the end-visit
2174 (funcall callback node t))))
2175
2176 (cl-defstruct (js2-node
2177 (:constructor nil)) ; abstract
2178 "Base AST node type."
2179 (type -1) ; token type
2180 (pos -1) ; start position of this AST node in parsed input
2181 (len 1) ; num characters spanned by the node
2182 props ; optional node property list (an alist)
2183 parent) ; link to parent node; null for root
2184
2185 (defsubst js2-node-get-prop (node prop &optional default)
2186 (or (cadr (assoc prop (js2-node-props node))) default))
2187
2188 (defsubst js2-node-set-prop (node prop value)
2189 (setf (js2-node-props node)
2190 (cons (list prop value) (js2-node-props node))))
2191
2192 (defun js2-fixup-starts (n nodes)
2193 "Adjust the start positions of NODES to be relative to N.
2194 Any node in the list may be nil, for convenience."
2195 (dolist (node nodes)
2196 (when node
2197 (setf (js2-node-pos node) (- (js2-node-pos node)
2198 (js2-node-pos n))))))
2199
2200 (defun js2-node-add-children (parent &rest nodes)
2201 "Set parent node of NODES to PARENT, and return PARENT.
2202 Does nothing if we're not recording parent links.
2203 If any given node in NODES is nil, doesn't record that link."
2204 (js2-fixup-starts parent nodes)
2205 (dolist (node nodes)
2206 (and node
2207 (setf (js2-node-parent node) parent))))
2208
2209 ;; Non-recursive since it's called a frightening number of times.
2210 (defun js2-node-abs-pos (n)
2211 (let ((pos (js2-node-pos n)))
2212 (while (setq n (js2-node-parent n))
2213 (setq pos (+ pos (js2-node-pos n))))
2214 pos))
2215
2216 (defsubst js2-node-abs-end (n)
2217 "Return absolute buffer position of end of N."
2218 (+ (js2-node-abs-pos n) (js2-node-len n)))
2219
2220 ;; It's important to make sure block nodes have a Lisp list for the
2221 ;; child nodes, to limit printing recursion depth in an AST that
2222 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2223 ;; a sufficiently large vector tree.
2224
2225 (cl-defstruct (js2-block-node
2226 (:include js2-node)
2227 (:constructor nil)
2228 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2229 (pos (js2-current-token-beg))
2230 len
2231 props
2232 kids)))
2233 "A block of statements."
2234 kids) ; a Lisp list of the child statement nodes
2235
2236 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2237 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2238
2239 (defun js2-visit-block (ast callback)
2240 "Visit the `js2-block-node' children of AST."
2241 (dolist (kid (js2-block-node-kids ast))
2242 (js2-visit-ast kid callback)))
2243
2244 (defun js2-print-block (n i)
2245 (let ((pad (js2-make-pad i)))
2246 (insert pad "{\n")
2247 (dolist (kid (js2-block-node-kids n))
2248 (js2-print-ast kid (1+ i)))
2249 (insert pad "}")))
2250
2251 (cl-defstruct (js2-scope
2252 (:include js2-block-node)
2253 (:constructor nil)
2254 (:constructor make-js2-scope (&key (type js2-BLOCK)
2255 (pos (js2-current-token-beg))
2256 len
2257 kids)))
2258 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2259 ;; I don't have one of those handy, so I'll use an alist for now.
2260 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2261 ;; and is much lighter-weight to construct (both CPU and mem).
2262 ;; The keys are interned strings (symbols) for faster lookup.
2263 ;; Should switch to hybrid alist/hashtable eventually.
2264 symbol-table ; an alist of (symbol . js2-symbol)
2265 parent-scope ; a `js2-scope'
2266 top) ; top-level `js2-scope' (script/function)
2267
2268 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2269 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2270
2271 (defun js2-node-get-enclosing-scope (node)
2272 "Return the innermost `js2-scope' node surrounding NODE.
2273 Returns nil if there is no enclosing scope node."
2274 (while (and (setq node (js2-node-parent node))
2275 (not (js2-scope-p node))))
2276 node)
2277
2278 (defun js2-get-defining-scope (scope name &optional point)
2279 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2280 Returns `js2-scope' in which NAME is defined, or nil if not found.
2281
2282 If POINT is non-nil, and if the found declaration type is
2283 `js2-LET', also check that the declaration node is before POINT."
2284 (let ((sym (if (symbolp name)
2285 name
2286 (intern name)))
2287 result
2288 (continue t))
2289 (while (and scope continue)
2290 (if (or
2291 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2292 (and entry
2293 (or (not point)
2294 (not (eq js2-LET (js2-symbol-decl-type entry)))
2295 (>= point
2296 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2297 (and (eq sym 'arguments)
2298 (js2-function-node-p scope)))
2299 (setq continue nil
2300 result scope)
2301 (setq scope (js2-scope-parent-scope scope))))
2302 result))
2303
2304 (defun js2-scope-get-symbol (scope name)
2305 "Return symbol table entry for NAME in SCOPE.
2306 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2307 (and (js2-scope-symbol-table scope)
2308 (cdr (assq (if (symbolp name)
2309 name
2310 (intern name))
2311 (js2-scope-symbol-table scope)))))
2312
2313 (defun js2-scope-put-symbol (scope name symbol)
2314 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2315 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2316 (let* ((table (js2-scope-symbol-table scope))
2317 (sym (if (symbolp name) name (intern name)))
2318 (entry (assq sym table)))
2319 (if entry
2320 (setcdr entry symbol)
2321 (push (cons sym symbol)
2322 (js2-scope-symbol-table scope)))))
2323
2324 (cl-defstruct (js2-symbol
2325 (:constructor nil)
2326 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2327 "A symbol table entry."
2328 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2329 ;; js2-LET, or js2-CONST
2330 decl-type
2331 name ; string
2332 ast-node) ; a `js2-node'
2333
2334 (cl-defstruct (js2-error-node
2335 (:include js2-node)
2336 (:constructor nil) ; silence emacs21 byte-compiler
2337 (:constructor make-js2-error-node (&key (type js2-ERROR)
2338 (pos (js2-current-token-beg))
2339 len)))
2340 "AST node representing a parse error.")
2341
2342 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2343 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2344
2345 (cl-defstruct (js2-script-node
2346 (:include js2-scope)
2347 (:constructor nil)
2348 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2349 (pos (js2-current-token-beg))
2350 len
2351 ;; FIXME: What are those?
2352 var-decls
2353 fun-decls)))
2354 functions ; Lisp list of nested functions
2355 regexps ; Lisp list of (string . flags)
2356 symbols ; alist (every symbol gets unique index)
2357 (param-count 0)
2358 var-names ; vector of string names
2359 consts ; bool-vector matching var-decls
2360 (temp-number 0)) ; for generating temp variables
2361
2362 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2363 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2364
2365 (defun js2-print-script (node indent)
2366 (dolist (kid (js2-block-node-kids node))
2367 (js2-print-ast kid indent)))
2368
2369 (cl-defstruct (js2-ast-root
2370 (:include js2-script-node)
2371 (:constructor nil)
2372 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2373 (pos (js2-current-token-beg))
2374 len
2375 buffer)))
2376 "The root node of a js2 AST."
2377 buffer ; the source buffer from which the code was parsed
2378 comments ; a Lisp list of comments, ordered by start position
2379 errors ; a Lisp list of errors found during parsing
2380 warnings ; a Lisp list of warnings found during parsing
2381 node-count) ; number of nodes in the tree, including the root
2382
2383 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2384 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2385
2386 (defun js2-visit-ast-root (ast callback)
2387 (dolist (kid (js2-ast-root-kids ast))
2388 (js2-visit-ast kid callback))
2389 (dolist (comment (js2-ast-root-comments ast))
2390 (js2-visit-ast comment callback)))
2391
2392 (cl-defstruct (js2-comment-node
2393 (:include js2-node)
2394 (:constructor nil)
2395 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2396 (pos (js2-current-token-beg))
2397 len
2398 format)))
2399 format) ; 'line, 'block, 'jsdoc or 'html
2400
2401 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2402 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2403
2404 (defun js2-print-comment (n i)
2405 ;; We really ought to link end-of-line comments to their nodes.
2406 ;; Or maybe we could add a new comment type, 'endline.
2407 (insert (js2-make-pad i)
2408 (js2-node-string n)))
2409
2410 (cl-defstruct (js2-expr-stmt-node
2411 (:include js2-node)
2412 (:constructor nil)
2413 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2414 (pos js2-ts-cursor)
2415 len
2416 expr)))
2417 "An expression statement."
2418 expr)
2419
2420 (defsubst js2-expr-stmt-node-set-has-result (node)
2421 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2422 (setf (js2-node-type node) js2-EXPR_RESULT))
2423
2424 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2425 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2426
2427 (defun js2-visit-expr-stmt-node (n v)
2428 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2429
2430 (defun js2-print-expr-stmt-node (n indent)
2431 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2432 (insert ";\n"))
2433
2434 (cl-defstruct (js2-loop-node
2435 (:include js2-scope)
2436 (:constructor nil))
2437 "Abstract supertype of loop nodes."
2438 body ; a `js2-block-node'
2439 lp ; position of left-paren, nil if omitted
2440 rp) ; position of right-paren, nil if omitted
2441
2442 (cl-defstruct (js2-do-node
2443 (:include js2-loop-node)
2444 (:constructor nil)
2445 (:constructor make-js2-do-node (&key (type js2-DO)
2446 (pos (js2-current-token-beg))
2447 len
2448 body
2449 condition
2450 while-pos
2451 lp
2452 rp)))
2453 "AST node for do-loop."
2454 condition ; while (expression)
2455 while-pos) ; buffer position of 'while' keyword
2456
2457 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2458 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2459
2460 (defun js2-visit-do-node (n v)
2461 (js2-visit-ast (js2-do-node-body n) v)
2462 (js2-visit-ast (js2-do-node-condition n) v))
2463
2464 (defun js2-print-do-node (n i)
2465 (let ((pad (js2-make-pad i)))
2466 (insert pad "do {\n")
2467 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2468 (js2-print-ast kid (1+ i)))
2469 (insert pad "} while (")
2470 (js2-print-ast (js2-do-node-condition n) 0)
2471 (insert ");\n")))
2472
2473 (cl-defstruct (js2-export-node
2474 (:include js2-node)
2475 (:constructor nil)
2476 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2477 (pos (js2-current-token-beg))
2478 len
2479 exports-list
2480 from-clause
2481 declaration
2482 default)))
2483 "AST node for an export statement. There are many things that can be exported,
2484 so many of its properties will be nil.
2485 "
2486 exports-list ; lisp list of js2-export-binding-node to export
2487 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2488 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2489 default) ; js2-function-node or js2-assign-node
2490
2491 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2492 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2493
2494 (defun js2-visit-export-node (n v)
2495 (let ((exports-list (js2-export-node-exports-list n))
2496 (from (js2-export-node-from-clause n))
2497 (declaration (js2-export-node-declaration n))
2498 (default (js2-export-node-default n)))
2499 (when exports-list
2500 (dolist (export exports-list)
2501 (js2-visit-ast export v)))
2502 (when from
2503 (js2-visit-ast from v))
2504 (when declaration
2505 (js2-visit-ast declaration v))
2506 (when default
2507 (js2-visit-ast default v))))
2508
2509 (defun js2-print-export-node (n i)
2510 (let ((pad (js2-make-pad i))
2511 (exports-list (js2-export-node-exports-list n))
2512 (from (js2-export-node-from-clause n))
2513 (declaration (js2-export-node-declaration n))
2514 (default (js2-export-node-default n)))
2515 (insert pad "export ")
2516 (cond
2517 (default
2518 (insert "default ")
2519 (js2-print-ast default i))
2520 (declaration
2521 (js2-print-ast declaration i))
2522 ((and exports-list from)
2523 (js2-print-named-imports exports-list)
2524 (insert " ")
2525 (js2-print-from-clause from))
2526 (from
2527 (insert "* ")
2528 (js2-print-from-clause from))
2529 (exports-list
2530 (js2-print-named-imports exports-list)))
2531 (insert ";\n")))
2532
2533 (cl-defstruct (js2-while-node
2534 (:include js2-loop-node)
2535 (:constructor nil)
2536 (:constructor make-js2-while-node (&key (type js2-WHILE)
2537 (pos (js2-current-token-beg))
2538 len body
2539 condition lp
2540 rp)))
2541 "AST node for while-loop."
2542 condition) ; while-condition
2543
2544 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2545 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2546
2547 (defun js2-visit-while-node (n v)
2548 (js2-visit-ast (js2-while-node-condition n) v)
2549 (js2-visit-ast (js2-while-node-body n) v))
2550
2551 (defun js2-print-while-node (n i)
2552 (let ((pad (js2-make-pad i)))
2553 (insert pad "while (")
2554 (js2-print-ast (js2-while-node-condition n) 0)
2555 (insert ") {\n")
2556 (js2-print-body (js2-while-node-body n) (1+ i))
2557 (insert pad "}\n")))
2558
2559 (cl-defstruct (js2-for-node
2560 (:include js2-loop-node)
2561 (:constructor nil)
2562 (:constructor make-js2-for-node (&key (type js2-FOR)
2563 (pos js2-ts-cursor)
2564 len body init
2565 condition
2566 update lp rp)))
2567 "AST node for a C-style for-loop."
2568 init ; initialization expression
2569 condition ; loop condition
2570 update) ; update clause
2571
2572 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2573 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2574
2575 (defun js2-visit-for-node (n v)
2576 (js2-visit-ast (js2-for-node-init n) v)
2577 (js2-visit-ast (js2-for-node-condition n) v)
2578 (js2-visit-ast (js2-for-node-update n) v)
2579 (js2-visit-ast (js2-for-node-body n) v))
2580
2581 (defun js2-print-for-node (n i)
2582 (let ((pad (js2-make-pad i)))
2583 (insert pad "for (")
2584 (js2-print-ast (js2-for-node-init n) 0)
2585 (insert "; ")
2586 (js2-print-ast (js2-for-node-condition n) 0)
2587 (insert "; ")
2588 (js2-print-ast (js2-for-node-update n) 0)
2589 (insert ") {\n")
2590 (js2-print-body (js2-for-node-body n) (1+ i))
2591 (insert pad "}\n")))
2592
2593 (cl-defstruct (js2-for-in-node
2594 (:include js2-loop-node)
2595 (:constructor nil)
2596 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2597 (pos js2-ts-cursor)
2598 len body
2599 iterator
2600 object
2601 in-pos
2602 each-pos
2603 foreach-p forof-p
2604 lp rp)))
2605 "AST node for a for..in loop."
2606 iterator ; [var] foo in ...
2607 object ; object over which we're iterating
2608 in-pos ; buffer position of 'in' keyword
2609 each-pos ; buffer position of 'each' keyword, if foreach-p
2610 foreach-p ; t if it's a for-each loop
2611 forof-p) ; t if it's a for-of loop
2612
2613 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2614 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2615
2616 (defun js2-visit-for-in-node (n v)
2617 (js2-visit-ast (js2-for-in-node-iterator n) v)
2618 (js2-visit-ast (js2-for-in-node-object n) v)
2619 (js2-visit-ast (js2-for-in-node-body n) v))
2620
2621 (defun js2-print-for-in-node (n i)
2622 (let ((pad (js2-make-pad i))
2623 (foreach (js2-for-in-node-foreach-p n))
2624 (forof (js2-for-in-node-forof-p n)))
2625 (insert pad "for ")
2626 (if foreach
2627 (insert "each "))
2628 (insert "(")
2629 (js2-print-ast (js2-for-in-node-iterator n) 0)
2630 (insert (if forof " of " " in "))
2631 (js2-print-ast (js2-for-in-node-object n) 0)
2632 (insert ") {\n")
2633 (js2-print-body (js2-for-in-node-body n) (1+ i))
2634 (insert pad "}\n")))
2635
2636 (cl-defstruct (js2-return-node
2637 (:include js2-node)
2638 (:constructor nil)
2639 (:constructor make-js2-return-node (&key (type js2-RETURN)
2640 (pos js2-ts-cursor)
2641 len
2642 retval)))
2643 "AST node for a return statement."
2644 retval) ; expression to return, or 'undefined
2645
2646 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2647 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2648
2649 (defun js2-visit-return-node (n v)
2650 (js2-visit-ast (js2-return-node-retval n) v))
2651
2652 (defun js2-print-return-node (n i)
2653 (insert (js2-make-pad i) "return")
2654 (when (js2-return-node-retval n)
2655 (insert " ")
2656 (js2-print-ast (js2-return-node-retval n) 0))
2657 (insert ";\n"))
2658
2659 (cl-defstruct (js2-if-node
2660 (:include js2-node)
2661 (:constructor nil)
2662 (:constructor make-js2-if-node (&key (type js2-IF)
2663 (pos js2-ts-cursor)
2664 len condition
2665 then-part
2666 else-pos
2667 else-part lp
2668 rp)))
2669 "AST node for an if-statement."
2670 condition ; expression
2671 then-part ; statement or block
2672 else-pos ; optional buffer position of 'else' keyword
2673 else-part ; optional statement or block
2674 lp ; position of left-paren, nil if omitted
2675 rp) ; position of right-paren, nil if omitted
2676
2677 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2678 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2679
2680 (defun js2-visit-if-node (n v)
2681 (js2-visit-ast (js2-if-node-condition n) v)
2682 (js2-visit-ast (js2-if-node-then-part n) v)
2683 (js2-visit-ast (js2-if-node-else-part n) v))
2684
2685 (defun js2-print-if-node (n i)
2686 (let ((pad (js2-make-pad i))
2687 (then-part (js2-if-node-then-part n))
2688 (else-part (js2-if-node-else-part n)))
2689 (insert pad "if (")
2690 (js2-print-ast (js2-if-node-condition n) 0)
2691 (insert ") {\n")
2692 (js2-print-body then-part (1+ i))
2693 (insert pad "}")
2694 (cond
2695 ((not else-part)
2696 (insert "\n"))
2697 ((js2-if-node-p else-part)
2698 (insert " else ")
2699 (js2-print-body else-part i))
2700 (t
2701 (insert " else {\n")
2702 (js2-print-body else-part (1+ i))
2703 (insert pad "}\n")))))
2704
2705 (cl-defstruct (js2-export-binding-node
2706 (:include js2-node)
2707 (:constructor nil)
2708 (:constructor make-js2-export-binding-node (&key (type -1)
2709 pos
2710 len
2711 local-name
2712 extern-name)))
2713 "AST node for an external symbol binding.
2714 It contains a local-name node which is the name of the value in the
2715 current scope, and extern-name which is the name of the value in the
2716 imported or exported scope. By default these are the same, but if the
2717 name is aliased as in {foo as bar}, it would have an extern-name node
2718 containing 'foo' and a local-name node containing 'bar'."
2719 local-name ; js2-name-node with the variable name in this scope
2720 extern-name) ; js2-name-node with the value name in the exporting module
2721
2722 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2723 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2724
2725 (defun js2-visit-extern-binding (n v)
2726 "Visit an extern binding node. First visit the local-name, and, if
2727 different, visit the extern-name."
2728 (let ((local-name (js2-export-binding-node-local-name n))
2729 (extern-name (js2-export-binding-node-extern-name n)))
2730 (when local-name
2731 (js2-visit-ast local-name v))
2732 (when (not (equal local-name extern-name))
2733 (js2-visit-ast extern-name v))))
2734
2735 (defun js2-print-extern-binding (n _i)
2736 "Print a representation of a single extern binding. E.g. 'foo' or
2737 'foo as bar'."
2738 (let ((local-name (js2-export-binding-node-local-name n))
2739 (extern-name (js2-export-binding-node-extern-name n)))
2740 (insert (js2-name-node-name extern-name))
2741 (when (not (equal local-name extern-name))
2742 (insert " as ")
2743 (insert (js2-name-node-name local-name)))))
2744
2745
2746 (cl-defstruct (js2-import-node
2747 (:include js2-node)
2748 (:constructor nil)
2749 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2750 (pos (js2-current-token-beg))
2751 len
2752 import
2753 from
2754 module-id)))
2755 "AST node for an import statement. It follows the form
2756
2757 import ModuleSpecifier;
2758 import ImportClause FromClause;"
2759 import ; js2-import-clause-node specifying which names are to imported.
2760 from ; js2-from-clause-node indicating the module from which to import.
2761 module-id) ; module-id of the import. E.g. 'src/mylib'.
2762
2763 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2764 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2765
2766 (defun js2-visit-import (n v)
2767 (let ((import-clause (js2-import-node-import n))
2768 (from-clause (js2-import-node-from n)))
2769 (when import-clause
2770 (js2-visit-ast import-clause v))
2771 (when from-clause
2772 (js2-visit-ast from-clause v))))
2773
2774 (defun js2-print-import (n i)
2775 "Prints a representation of the import node"
2776 (let ((pad (js2-make-pad i))
2777 (import-clause (js2-import-node-import n))
2778 (from-clause (js2-import-node-from n))
2779 (module-id (js2-import-node-module-id n)))
2780 (insert pad "import ")
2781 (if import-clause
2782 (progn
2783 (js2-print-import-clause import-clause)
2784 (insert " ")
2785 (js2-print-from-clause from-clause))
2786 (insert "'")
2787 (insert module-id)
2788 (insert "'"))
2789 (insert ";\n")))
2790
2791 (cl-defstruct (js2-import-clause-node
2792 (:include js2-node)
2793 (:constructor nil)
2794 (:constructor make-js2-import-clause-node (&key (type -1)
2795 pos
2796 len
2797 namespace-import
2798 named-imports
2799 default-binding)))
2800 "AST node corresponding to the import clause of an import statement. This is
2801 the portion of the import that bindings names from the external context to the
2802 local context."
2803 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2804 named-imports ; lisp list of js2-export-binding-node for all named imports.
2805 default-binding) ; js2-export-binding-node for the default import binding
2806
2807 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2808 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2809
2810 (defun js2-visit-import-clause (n v)
2811 (let ((ns-import (js2-import-clause-node-namespace-import n))
2812 (named-imports (js2-import-clause-node-named-imports n))
2813 (default (js2-import-clause-node-default-binding n)))
2814 (when ns-import
2815 (js2-visit-ast ns-import v))
2816 (when named-imports
2817 (dolist (import named-imports)
2818 (js2-visit-ast import v)))
2819 (when default
2820 (js2-visit-ast default v))))
2821
2822 (defun js2-print-import-clause (n)
2823 (let ((ns-import (js2-import-clause-node-namespace-import n))
2824 (named-imports (js2-import-clause-node-named-imports n))
2825 (default (js2-import-clause-node-default-binding n)))
2826 (cond
2827 ((and default ns-import)
2828 (js2-print-ast default)
2829 (insert ", ")
2830 (js2-print-namespace-import ns-import))
2831 ((and default named-imports)
2832 (js2-print-ast default)
2833 (insert ", ")
2834 (js2-print-named-imports named-imports))
2835 (default
2836 (js2-print-ast default))
2837 (ns-import
2838 (js2-print-namespace-import ns-import))
2839 (named-imports
2840 (js2-print-named-imports named-imports)))))
2841
2842 (defun js2-print-namespace-import (node)
2843 (insert "* as ")
2844 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2845
2846 (defun js2-print-named-imports (imports)
2847 (insert "{")
2848 (let ((len (length imports))
2849 (n 0))
2850 (while (< n len)
2851 (js2-print-extern-binding (nth n imports) 0)
2852 (unless (= n (- len 1))
2853 (insert ", "))
2854 (setq n (+ n 1))))
2855 (insert "}"))
2856
2857 (cl-defstruct (js2-namespace-import-node
2858 (:include js2-node)
2859 (:constructor nil)
2860 (:constructor make-js2-namespace-import-node (&key (type -1)
2861 pos
2862 len
2863 name)))
2864 "AST node for a complete namespace import.
2865 E.g. the '* as lib' expression in:
2866
2867 import * as lib from 'src/lib'
2868
2869 It contains a single name node referring to the bound name."
2870 name) ; js2-name-node of the bound name.
2871
2872 (defun js2-visit-namespace-import (n v)
2873 (js2-visit-ast (js2-namespace-import-node-name n) v))
2874
2875 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2876 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2877
2878 (cl-defstruct (js2-from-clause-node
2879 (:include js2-node)
2880 (:constructor nil)
2881 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2882 pos
2883 len
2884 module-id
2885 metadata-p)))
2886 "AST node for the from clause in an import or export statement.
2887 E.g. from 'my/module'. It can refere to either an external module, or to the
2888 modules metadata itself."
2889 module-id ; string containing the module specifier.
2890 metadata-p) ; true if this clause refers to the module's metadata
2891
2892 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2893 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2894
2895 (defun js2-print-from-clause (n)
2896 (insert "from ")
2897 (if (js2-from-clause-node-metadata-p n)
2898 (insert "this module")
2899 (insert "'")
2900 (insert (js2-from-clause-node-module-id n))
2901 (insert "'")))
2902
2903 (cl-defstruct (js2-try-node
2904 (:include js2-node)
2905 (:constructor nil)
2906 (:constructor make-js2-try-node (&key (type js2-TRY)
2907 (pos js2-ts-cursor)
2908 len
2909 try-block
2910 catch-clauses
2911 finally-block)))
2912 "AST node for a try-statement."
2913 try-block
2914 catch-clauses ; a Lisp list of `js2-catch-node'
2915 finally-block) ; a `js2-finally-node'
2916
2917 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2918 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2919
2920 (defun js2-visit-try-node (n v)
2921 (js2-visit-ast (js2-try-node-try-block n) v)
2922 (dolist (clause (js2-try-node-catch-clauses n))
2923 (js2-visit-ast clause v))
2924 (js2-visit-ast (js2-try-node-finally-block n) v))
2925
2926 (defun js2-print-try-node (n i)
2927 (let ((pad (js2-make-pad i))
2928 (catches (js2-try-node-catch-clauses n))
2929 (finally (js2-try-node-finally-block n)))
2930 (insert pad "try {\n")
2931 (js2-print-body (js2-try-node-try-block n) (1+ i))
2932 (insert pad "}")
2933 (when catches
2934 (dolist (catch catches)
2935 (js2-print-ast catch i)))
2936 (if finally
2937 (js2-print-ast finally i)
2938 (insert "\n"))))
2939
2940 (cl-defstruct (js2-catch-node
2941 (:include js2-scope)
2942 (:constructor nil)
2943 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2944 (pos js2-ts-cursor)
2945 len
2946 param
2947 guard-kwd
2948 guard-expr
2949 lp rp)))
2950 "AST node for a catch clause."
2951 param ; destructuring form or simple name node
2952 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2953 guard-expr ; catch condition, a `js2-node'
2954 lp ; buffer position of left-paren, nil if omitted
2955 rp) ; buffer position of right-paren, nil if omitted
2956
2957 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2958 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2959
2960 (defun js2-visit-catch-node (n v)
2961 (js2-visit-ast (js2-catch-node-param n) v)
2962 (when (js2-catch-node-guard-kwd n)
2963 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2964 (js2-visit-block n v))
2965
2966 (defun js2-print-catch-node (n i)
2967 (let ((pad (js2-make-pad i))
2968 (guard-kwd (js2-catch-node-guard-kwd n))
2969 (guard-expr (js2-catch-node-guard-expr n)))
2970 (insert " catch (")
2971 (js2-print-ast (js2-catch-node-param n) 0)
2972 (when guard-kwd
2973 (insert " if ")
2974 (js2-print-ast guard-expr 0))
2975 (insert ") {\n")
2976 (js2-print-body n (1+ i))
2977 (insert pad "}")))
2978
2979 (cl-defstruct (js2-finally-node
2980 (:include js2-node)
2981 (:constructor nil)
2982 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2983 (pos js2-ts-cursor)
2984 len body)))
2985 "AST node for a finally clause."
2986 body) ; a `js2-node', often but not always a block node
2987
2988 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2989 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2990
2991 (defun js2-visit-finally-node (n v)
2992 (js2-visit-ast (js2-finally-node-body n) v))
2993
2994 (defun js2-print-finally-node (n i)
2995 (let ((pad (js2-make-pad i)))
2996 (insert " finally {\n")
2997 (js2-print-body (js2-finally-node-body n) (1+ i))
2998 (insert pad "}\n")))
2999
3000 (cl-defstruct (js2-switch-node
3001 (:include js2-node)
3002 (:constructor nil)
3003 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3004 (pos js2-ts-cursor)
3005 len
3006 discriminant
3007 cases lp
3008 rp)))
3009 "AST node for a switch statement."
3010 discriminant ; a `js2-node' (switch expression)
3011 cases ; a Lisp list of `js2-case-node'
3012 lp ; position of open-paren for discriminant, nil if omitted
3013 rp) ; position of close-paren for discriminant, nil if omitted
3014
3015 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3016 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3017
3018 (defun js2-visit-switch-node (n v)
3019 (js2-visit-ast (js2-switch-node-discriminant n) v)
3020 (dolist (c (js2-switch-node-cases n))
3021 (js2-visit-ast c v)))
3022
3023 (defun js2-print-switch-node (n i)
3024 (let ((pad (js2-make-pad i))
3025 (cases (js2-switch-node-cases n)))
3026 (insert pad "switch (")
3027 (js2-print-ast (js2-switch-node-discriminant n) 0)
3028 (insert ") {\n")
3029 (dolist (case cases)
3030 (js2-print-ast case i))
3031 (insert pad "}\n")))
3032
3033 (cl-defstruct (js2-case-node
3034 (:include js2-block-node)
3035 (:constructor nil)
3036 (:constructor make-js2-case-node (&key (type js2-CASE)
3037 (pos js2-ts-cursor)
3038 len kids expr)))
3039 "AST node for a case clause of a switch statement."
3040 expr) ; the case expression (nil for default)
3041
3042 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3043 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3044
3045 (defun js2-visit-case-node (n v)
3046 (js2-visit-ast (js2-case-node-expr n) v)
3047 (js2-visit-block n v))
3048
3049 (defun js2-print-case-node (n i)
3050 (let ((pad (js2-make-pad i))
3051 (expr (js2-case-node-expr n)))
3052 (insert pad)
3053 (if (null expr)
3054 (insert "default:\n")
3055 (insert "case ")
3056 (js2-print-ast expr 0)
3057 (insert ":\n"))
3058 (dolist (kid (js2-case-node-kids n))
3059 (js2-print-ast kid (1+ i)))))
3060
3061 (cl-defstruct (js2-throw-node
3062 (:include js2-node)
3063 (:constructor nil)
3064 (:constructor make-js2-throw-node (&key (type js2-THROW)
3065 (pos js2-ts-cursor)
3066 len expr)))
3067 "AST node for a throw statement."
3068 expr) ; the expression to throw
3069
3070 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3071 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3072
3073 (defun js2-visit-throw-node (n v)
3074 (js2-visit-ast (js2-throw-node-expr n) v))
3075
3076 (defun js2-print-throw-node (n i)
3077 (insert (js2-make-pad i) "throw ")
3078 (js2-print-ast (js2-throw-node-expr n) 0)
3079 (insert ";\n"))
3080
3081 (cl-defstruct (js2-with-node
3082 (:include js2-node)
3083 (:constructor nil)
3084 (:constructor make-js2-with-node (&key (type js2-WITH)
3085 (pos js2-ts-cursor)
3086 len object
3087 body lp rp)))
3088 "AST node for a with-statement."
3089 object
3090 body
3091 lp ; buffer position of left-paren around object, nil if omitted
3092 rp) ; buffer position of right-paren around object, nil if omitted
3093
3094 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3095 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3096
3097 (defun js2-visit-with-node (n v)
3098 (js2-visit-ast (js2-with-node-object n) v)
3099 (js2-visit-ast (js2-with-node-body n) v))
3100
3101 (defun js2-print-with-node (n i)
3102 (let ((pad (js2-make-pad i)))
3103 (insert pad "with (")
3104 (js2-print-ast (js2-with-node-object n) 0)
3105 (insert ") {\n")
3106 (js2-print-body (js2-with-node-body n) (1+ i))
3107 (insert pad "}\n")))
3108
3109 (cl-defstruct (js2-label-node
3110 (:include js2-node)
3111 (:constructor nil)
3112 (:constructor make-js2-label-node (&key (type js2-LABEL)
3113 (pos js2-ts-cursor)
3114 len name)))
3115 "AST node for a statement label or case label."
3116 name ; a string
3117 loop) ; for validating and code-generating continue-to-label
3118
3119 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3120 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3121
3122 (defun js2-print-label (n i)
3123 (insert (js2-make-pad i)
3124 (js2-label-node-name n)
3125 ":\n"))
3126
3127 (cl-defstruct (js2-labeled-stmt-node
3128 (:include js2-node)
3129 (:constructor nil)
3130 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3131 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3132 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3133 (pos js2-ts-cursor)
3134 len labels stmt)))
3135 "AST node for a statement with one or more labels.
3136 Multiple labels for a statement are collapsed into the labels field."
3137 labels ; Lisp list of `js2-label-node'
3138 stmt) ; the statement these labels are for
3139
3140 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3141 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3142
3143 (defun js2-get-label-by-name (lbl-stmt name)
3144 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3145 Returns nil if no such label is in the list."
3146 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3147 result)
3148 (while (and label-list (not result))
3149 (if (string= (js2-label-node-name (car label-list)) name)
3150 (setq result (car label-list))
3151 (setq label-list (cdr label-list))))
3152 result))
3153
3154 (defun js2-visit-labeled-stmt (n v)
3155 (dolist (label (js2-labeled-stmt-node-labels n))
3156 (js2-visit-ast label v))
3157 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3158
3159 (defun js2-print-labeled-stmt (n i)
3160 (dolist (label (js2-labeled-stmt-node-labels n))
3161 (js2-print-ast label i))
3162 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3163
3164 (defun js2-labeled-stmt-node-contains (node label)
3165 "Return t if NODE contains LABEL in its label set.
3166 NODE is a `js2-labels-node'. LABEL is an identifier."
3167 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3168 if (string= label (js2-label-node-name nl))
3169 return t
3170 finally return nil))
3171
3172 (defsubst js2-labeled-stmt-node-add-label (node label)
3173 "Add a `js2-label-node' to the label set for this statement."
3174 (setf (js2-labeled-stmt-node-labels node)
3175 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3176
3177 (cl-defstruct (js2-jump-node
3178 (:include js2-node)
3179 (:constructor nil))
3180 "Abstract supertype of break and continue nodes."
3181 label ; `js2-name-node' for location of label identifier, if present
3182 target) ; target js2-labels-node or loop/switch statement
3183
3184 (defun js2-visit-jump-node (n v)
3185 ;; We don't visit the target, since it's a back-link.
3186 (js2-visit-ast (js2-jump-node-label n) v))
3187
3188 (cl-defstruct (js2-break-node
3189 (:include js2-jump-node)
3190 (:constructor nil)
3191 (:constructor make-js2-break-node (&key (type js2-BREAK)
3192 (pos js2-ts-cursor)
3193 len label target)))
3194 "AST node for a break statement.
3195 The label field is a `js2-name-node', possibly nil, for the named label
3196 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3197 is the target of the break - a label node or enclosing loop/switch statement.")
3198
3199 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3200 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3201
3202 (defun js2-print-break-node (n i)
3203 (insert (js2-make-pad i) "break")
3204 (when (js2-break-node-label n)
3205 (insert " ")
3206 (js2-print-ast (js2-break-node-label n) 0))
3207 (insert ";\n"))
3208
3209 (cl-defstruct (js2-continue-node
3210 (:include js2-jump-node)
3211 (:constructor nil)
3212 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3213 (pos js2-ts-cursor)
3214 len label target)))
3215 "AST node for a continue statement.
3216 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3217 It is nil if continue specifies no label. The target field is the jump target:
3218 a `js2-label-node' or the innermost enclosing loop.")
3219
3220 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3221 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3222
3223 (defun js2-print-continue-node (n i)
3224 (insert (js2-make-pad i) "continue")
3225 (when (js2-continue-node-label n)
3226 (insert " ")
3227 (js2-print-ast (js2-continue-node-label n) 0))
3228 (insert ";\n"))
3229
3230 (cl-defstruct (js2-function-node
3231 (:include js2-script-node)
3232 (:constructor nil)
3233 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3234 (pos js2-ts-cursor)
3235 len
3236 (ftype 'FUNCTION)
3237 (form 'FUNCTION_STATEMENT)
3238 (name "")
3239 params rest-p
3240 body
3241 generator-type
3242 lp rp)))
3243 "AST node for a function declaration.
3244 The `params' field is a Lisp list of nodes. Each node is either a simple
3245 `js2-name-node', or if it's a destructuring-assignment parameter, a
3246 `js2-array-node' or `js2-object-node'."
3247 ftype ; FUNCTION, GETTER or SETTER
3248 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3249 name ; function name (a `js2-name-node', or nil if anonymous)
3250 params ; a Lisp list of destructuring forms or simple name nodes
3251 rest-p ; if t, the last parameter is rest parameter
3252 body ; a `js2-block-node' or expression node (1.8 only)
3253 lp ; position of arg-list open-paren, or nil if omitted
3254 rp ; position of arg-list close-paren, or nil if omitted
3255 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3256 needs-activation ; t if we need an activation object for this frame
3257 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3258 member-expr) ; nonstandard Ecma extension from Rhino
3259
3260 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3261 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3262
3263 (defun js2-visit-function-node (n v)
3264 (js2-visit-ast (js2-function-node-name n) v)
3265 (dolist (p (js2-function-node-params n))
3266 (js2-visit-ast p v))
3267 (js2-visit-ast (js2-function-node-body n) v))
3268
3269 (defun js2-print-function-node (n i)
3270 (let* ((pad (js2-make-pad i))
3271 (getter (js2-node-get-prop n 'GETTER_SETTER))
3272 (name (or (js2-function-node-name n)
3273 (js2-function-node-member-expr n)))
3274 (params (js2-function-node-params n))
3275 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3276 (rest-p (js2-function-node-rest-p n))
3277 (body (js2-function-node-body n))
3278 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3279 (unless (or getter arrow)
3280 (insert pad "function")
3281 (when (eq (js2-function-node-generator-type n) 'STAR)
3282 (insert "*")))
3283 (when name
3284 (insert " ")
3285 (js2-print-ast name 0))
3286 (insert "(")
3287 (cl-loop with len = (length params)
3288 for param in params
3289 for count from 1
3290 do
3291 (when (and rest-p (= count len))
3292 (insert "..."))
3293 (js2-print-ast param 0)
3294 (when (< count len)
3295 (insert ", ")))
3296 (insert ") ")
3297 (when arrow
3298 (insert "=> "))
3299 (insert "{")
3300 ;; TODO: fix this to be smarter about indenting, etc.
3301 (unless expr
3302 (insert "\n"))
3303 (if (js2-block-node-p body)
3304 (js2-print-body body (1+ i))
3305 (js2-print-ast body 0))
3306 (insert pad "}")
3307 (unless expr
3308 (insert "\n"))))
3309
3310 (defun js2-function-name (node)
3311 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3312 (and (js2-function-node-name node)
3313 (js2-name-node-name (js2-function-node-name node))))
3314
3315 ;; Having this be an expression node makes it more flexible.
3316 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3317 ;; that work better if you assume it's an expression. Whenever we have
3318 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3319 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3320 (cl-defstruct (js2-var-decl-node
3321 (:include js2-node)
3322 (:constructor nil)
3323 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3324 (pos (js2-current-token-beg))
3325 len kids
3326 decl-type)))
3327 "AST node for a variable declaration list (VAR, CONST or LET).
3328 The node bounds differ depending on the declaration type. For VAR or
3329 CONST declarations, the bounds include the var/const keyword. For LET
3330 declarations, the node begins at the position of the first child."
3331 kids ; a Lisp list of `js2-var-init-node' structs.
3332 decl-type) ; js2-VAR, js2-CONST or js2-LET
3333
3334 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3335 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3336
3337 (defun js2-visit-var-decl (n v)
3338 (dolist (kid (js2-var-decl-node-kids n))
3339 (js2-visit-ast kid v)))
3340
3341 (defun js2-print-var-decl (n i)
3342 (let ((pad (js2-make-pad i))
3343 (tt (js2-var-decl-node-decl-type n)))
3344 (insert pad)
3345 (insert (cond
3346 ((= tt js2-VAR) "var ")
3347 ((= tt js2-LET) "let ")
3348 ((= tt js2-CONST) "const ")
3349 (t
3350 (error "malformed var-decl node"))))
3351 (cl-loop with kids = (js2-var-decl-node-kids n)
3352 with len = (length kids)
3353 for kid in kids
3354 for count from 1
3355 do
3356 (js2-print-ast kid 0)
3357 (if (< count len)
3358 (insert ", ")))))
3359
3360 (cl-defstruct (js2-var-init-node
3361 (:include js2-node)
3362 (:constructor nil)
3363 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3364 (pos js2-ts-cursor)
3365 len target
3366 initializer)))
3367 "AST node for a variable declaration.
3368 The type field will be js2-CONST for a const decl."
3369 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3370 initializer) ; initializer expression, a `js2-node'
3371
3372 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3373 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3374
3375 (defun js2-visit-var-init-node (n v)
3376 (js2-visit-ast (js2-var-init-node-target n) v)
3377 (js2-visit-ast (js2-var-init-node-initializer n) v))
3378
3379 (defun js2-print-var-init-node (n i)
3380 (let ((pad (js2-make-pad i))
3381 (name (js2-var-init-node-target n))
3382 (init (js2-var-init-node-initializer n)))
3383 (insert pad)
3384 (js2-print-ast name 0)
3385 (when init
3386 (insert " = ")
3387 (js2-print-ast init 0))))
3388
3389 (cl-defstruct (js2-cond-node
3390 (:include js2-node)
3391 (:constructor nil)
3392 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3393 (pos js2-ts-cursor)
3394 len
3395 test-expr
3396 true-expr
3397 false-expr
3398 q-pos c-pos)))
3399 "AST node for the ternary operator"
3400 test-expr
3401 true-expr
3402 false-expr
3403 q-pos ; buffer position of ?
3404 c-pos) ; buffer position of :
3405
3406 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3407 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3408
3409 (defun js2-visit-cond-node (n v)
3410 (js2-visit-ast (js2-cond-node-test-expr n) v)
3411 (js2-visit-ast (js2-cond-node-true-expr n) v)
3412 (js2-visit-ast (js2-cond-node-false-expr n) v))
3413
3414 (defun js2-print-cond-node (n i)
3415 (let ((pad (js2-make-pad i)))
3416 (insert pad)
3417 (js2-print-ast (js2-cond-node-test-expr n) 0)
3418 (insert " ? ")
3419 (js2-print-ast (js2-cond-node-true-expr n) 0)
3420 (insert " : ")
3421 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3422
3423 (cl-defstruct (js2-infix-node
3424 (:include js2-node)
3425 (:constructor nil)
3426 (:constructor make-js2-infix-node (&key type
3427 (pos js2-ts-cursor)
3428 len op-pos
3429 left right)))
3430 "Represents infix expressions.
3431 Includes assignment ops like `|=', and the comma operator.
3432 The type field inherited from `js2-node' holds the operator."
3433 op-pos ; buffer position where operator begins
3434 left ; any `js2-node'
3435 right) ; any `js2-node'
3436
3437 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3438 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3439
3440 (defun js2-visit-infix-node (n v)
3441 (js2-visit-ast (js2-infix-node-left n) v)
3442 (js2-visit-ast (js2-infix-node-right n) v))
3443
3444 (defconst js2-operator-tokens
3445 (let ((table (make-hash-table :test 'eq))
3446 (tokens
3447 (list (cons js2-IN "in")
3448 (cons js2-TYPEOF "typeof")
3449 (cons js2-INSTANCEOF "instanceof")
3450 (cons js2-DELPROP "delete")
3451 (cons js2-COMMA ",")
3452 (cons js2-COLON ":")
3453 (cons js2-OR "||")
3454 (cons js2-AND "&&")
3455 (cons js2-INC "++")
3456 (cons js2-DEC "--")
3457 (cons js2-BITOR "|")
3458 (cons js2-BITXOR "^")
3459 (cons js2-BITAND "&")
3460 (cons js2-EQ "==")
3461 (cons js2-NE "!=")
3462 (cons js2-LT "<")
3463 (cons js2-LE "<=")
3464 (cons js2-GT ">")
3465 (cons js2-GE ">=")
3466 (cons js2-LSH "<<")
3467 (cons js2-RSH ">>")
3468 (cons js2-URSH ">>>")
3469 (cons js2-ADD "+") ; infix plus
3470 (cons js2-SUB "-") ; infix minus
3471 (cons js2-MUL "*")
3472 (cons js2-DIV "/")
3473 (cons js2-MOD "%")
3474 (cons js2-NOT "!")
3475 (cons js2-BITNOT "~")
3476 (cons js2-POS "+") ; unary plus
3477 (cons js2-NEG "-") ; unary minus
3478 (cons js2-TRIPLEDOT "...")
3479 (cons js2-SHEQ "===") ; shallow equality
3480 (cons js2-SHNE "!==") ; shallow inequality
3481 (cons js2-ASSIGN "=")
3482 (cons js2-ASSIGN_BITOR "|=")
3483 (cons js2-ASSIGN_BITXOR "^=")
3484 (cons js2-ASSIGN_BITAND "&=")
3485 (cons js2-ASSIGN_LSH "<<=")
3486 (cons js2-ASSIGN_RSH ">>=")
3487 (cons js2-ASSIGN_URSH ">>>=")
3488 (cons js2-ASSIGN_ADD "+=")
3489 (cons js2-ASSIGN_SUB "-=")
3490 (cons js2-ASSIGN_MUL "*=")
3491 (cons js2-ASSIGN_DIV "/=")
3492 (cons js2-ASSIGN_MOD "%="))))
3493 (cl-loop for (k . v) in tokens do
3494 (puthash k v table))
3495 table))
3496
3497 (defun js2-print-infix-node (n i)
3498 (let* ((tt (js2-node-type n))
3499 (op (gethash tt js2-operator-tokens)))
3500 (unless op
3501 (error "unrecognized infix operator %s" (js2-node-type n)))
3502 (insert (js2-make-pad i))
3503 (js2-print-ast (js2-infix-node-left n) 0)
3504 (unless (= tt js2-COMMA)
3505 (insert " "))
3506 (insert op)
3507 (insert " ")
3508 (js2-print-ast (js2-infix-node-right n) 0)))
3509
3510 (cl-defstruct (js2-assign-node
3511 (:include js2-infix-node)
3512 (:constructor nil)
3513 (:constructor make-js2-assign-node (&key type
3514 (pos js2-ts-cursor)
3515 len op-pos
3516 left right)))
3517 "Represents any assignment.
3518 The type field holds the actual assignment operator.")
3519
3520 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3521 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3522
3523 (cl-defstruct (js2-unary-node
3524 (:include js2-node)
3525 (:constructor nil)
3526 (:constructor make-js2-unary-node (&key type ; required
3527 (pos js2-ts-cursor)
3528 len operand)))
3529 "AST node type for unary operator nodes.
3530 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3531 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3532 property is added if the operator follows the operand."
3533 operand) ; a `js2-node' expression
3534
3535 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3536 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3537
3538 (defun js2-visit-unary-node (n v)
3539 (js2-visit-ast (js2-unary-node-operand n) v))
3540
3541 (defun js2-print-unary-node (n i)
3542 (let* ((tt (js2-node-type n))
3543 (op (gethash tt js2-operator-tokens))
3544 (postfix (js2-node-get-prop n 'postfix)))
3545 (unless op
3546 (error "unrecognized unary operator %s" tt))
3547 (insert (js2-make-pad i))
3548 (unless postfix
3549 (insert op))
3550 (if (or (= tt js2-TYPEOF)
3551 (= tt js2-DELPROP))
3552 (insert " "))
3553 (js2-print-ast (js2-unary-node-operand n) 0)
3554 (when postfix
3555 (insert op))))
3556
3557 (cl-defstruct (js2-let-node
3558 (:include js2-scope)
3559 (:constructor nil)
3560 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3561 (pos (js2-current-token-beg))
3562 len vars body
3563 lp rp)))
3564 "AST node for a let expression or a let statement.
3565 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3566 vars ; a `js2-var-decl-node'
3567 body ; a `js2-node' representing the expression or body block
3568 lp
3569 rp)
3570
3571 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3572 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3573
3574 (defun js2-visit-let-node (n v)
3575 (js2-visit-ast (js2-let-node-vars n) v)
3576 (js2-visit-ast (js2-let-node-body n) v))
3577
3578 (defun js2-print-let-node (n i)
3579 (insert (js2-make-pad i) "let (")
3580 (let ((p (point)))
3581 (js2-print-ast (js2-let-node-vars n) 0)
3582 (delete-region p (+ p 4)))
3583 (insert ") ")
3584 (js2-print-ast (js2-let-node-body n) i))
3585
3586 (cl-defstruct (js2-keyword-node
3587 (:include js2-node)
3588 (:constructor nil)
3589 (:constructor make-js2-keyword-node (&key type
3590 (pos (js2-current-token-beg))
3591 (len (- js2-ts-cursor pos)))))
3592 "AST node representing a literal keyword such as `null'.
3593 Used for `null', `this', `true', `false' and `debugger'.
3594 The node type is set to js2-NULL, js2-THIS, etc.")
3595
3596 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3597 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3598
3599 (defun js2-print-keyword-node (n i)
3600 (insert (js2-make-pad i)
3601 (let ((tt (js2-node-type n)))
3602 (cond
3603 ((= tt js2-THIS) "this")
3604 ((= tt js2-SUPER) "super")
3605 ((= tt js2-NULL) "null")
3606 ((= tt js2-TRUE) "true")
3607 ((= tt js2-FALSE) "false")
3608 ((= tt js2-DEBUGGER) "debugger")
3609 (t (error "Invalid keyword literal type: %d" tt))))))
3610
3611 (defsubst js2-this-or-super-node-p (node)
3612 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3613 (let ((type (js2-node-type node)))
3614 (or (eq type js2-THIS) (eq type js2-SUPER))))
3615
3616 (cl-defstruct (js2-new-node
3617 (:include js2-node)
3618 (:constructor nil)
3619 (:constructor make-js2-new-node (&key (type js2-NEW)
3620 (pos (js2-current-token-beg))
3621 len target
3622 args initializer
3623 lp rp)))
3624 "AST node for new-expression such as new Foo()."
3625 target ; an identifier or reference
3626 args ; a Lisp list of argument nodes
3627 lp ; position of left-paren, nil if omitted
3628 rp ; position of right-paren, nil if omitted
3629 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3630
3631 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3632 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3633
3634 (defun js2-visit-new-node (n v)
3635 (js2-visit-ast (js2-new-node-target n) v)
3636 (dolist (arg (js2-new-node-args n))
3637 (js2-visit-ast arg v))
3638 (js2-visit-ast (js2-new-node-initializer n) v))
3639
3640 (defun js2-print-new-node (n i)
3641 (insert (js2-make-pad i) "new ")
3642 (js2-print-ast (js2-new-node-target n))
3643 (insert "(")
3644 (js2-print-list (js2-new-node-args n))
3645 (insert ")")
3646 (when (js2-new-node-initializer n)
3647 (insert " ")
3648 (js2-print-ast (js2-new-node-initializer n))))
3649
3650 (cl-defstruct (js2-name-node
3651 (:include js2-node)
3652 (:constructor nil)
3653 (:constructor make-js2-name-node (&key (type js2-NAME)
3654 (pos (js2-current-token-beg))
3655 (len (- js2-ts-cursor
3656 (js2-current-token-beg)))
3657 (name (js2-current-token-string)))))
3658 "AST node for a JavaScript identifier"
3659 name ; a string
3660 scope) ; a `js2-scope' (optional, used for codegen)
3661
3662 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3663 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3664
3665 (defun js2-print-name-node (n i)
3666 (insert (js2-make-pad i)
3667 (js2-name-node-name n)))
3668
3669 (defsubst js2-name-node-length (node)
3670 "Return identifier length of NODE, a `js2-name-node'.
3671 Returns 0 if NODE is nil or its identifier field is nil."
3672 (if node
3673 (length (js2-name-node-name node))
3674 0))
3675
3676 (cl-defstruct (js2-number-node
3677 (:include js2-node)
3678 (:constructor nil)
3679 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3680 (pos (js2-current-token-beg))
3681 (len (- js2-ts-cursor
3682 (js2-current-token-beg)))
3683 (value (js2-current-token-string))
3684 (num-value (js2-token-number
3685 (js2-current-token)))
3686 (num-base (js2-token-number-base
3687 (js2-current-token))))))
3688 "AST node for a number literal."
3689 value ; the original string, e.g. "6.02e23"
3690 num-value ; the parsed number value
3691 num-base) ; the number's base
3692
3693 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3694 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3695
3696 (defun js2-print-number-node (n i)
3697 (insert (js2-make-pad i)
3698 (number-to-string (js2-number-node-num-value n))))
3699
3700 (cl-defstruct (js2-regexp-node
3701 (:include js2-node)
3702 (:constructor nil)
3703 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3704 (pos (js2-current-token-beg))
3705 (len (- js2-ts-cursor
3706 (js2-current-token-beg)))
3707 value flags)))
3708 "AST node for a regular expression literal."
3709 value ; the regexp string, without // delimiters
3710 flags) ; a string of flags, e.g. `mi'.
3711
3712 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3713 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3714
3715 (defun js2-print-regexp (n i)
3716 (insert (js2-make-pad i)
3717 "/"
3718 (js2-regexp-node-value n)
3719 "/")
3720 (if (js2-regexp-node-flags n)
3721 (insert (js2-regexp-node-flags n))))
3722
3723 (cl-defstruct (js2-string-node
3724 (:include js2-node)
3725 (:constructor nil)
3726 (:constructor make-js2-string-node (&key (type js2-STRING)
3727 (pos (js2-current-token-beg))
3728 (len (- js2-ts-cursor
3729 (js2-current-token-beg)))
3730 (value (js2-current-token-string)))))
3731 "String literal.
3732 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3733 You can tell the quote type by looking at the first character."
3734 value) ; the characters of the string, including the quotes
3735
3736 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3737 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3738
3739 (defun js2-print-string-node (n i)
3740 (insert (js2-make-pad i)
3741 (js2-node-string n)))
3742
3743 (cl-defstruct (js2-template-node
3744 (:include js2-node)
3745 (:constructor nil)
3746 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3747 beg len kids)))
3748 "Template literal."
3749 kids) ; `js2-string-node' is used for string segments, other nodes
3750 ; for substitutions inside.
3751
3752 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3753 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3754
3755 (defun js2-visit-template (n callback)
3756 (dolist (kid (js2-template-node-kids n))
3757 (js2-visit-ast kid callback)))
3758
3759 (defun js2-print-template (n i)
3760 (insert (js2-make-pad i))
3761 (dolist (kid (js2-template-node-kids n))
3762 (if (js2-string-node-p kid)
3763 (insert (js2-node-string kid))
3764 (js2-print-ast kid))))
3765
3766 (cl-defstruct (js2-tagged-template-node
3767 (:include js2-node)
3768 (:constructor nil)
3769 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3770 beg len tag template)))
3771 "Tagged template literal."
3772 tag ; `js2-node' with the tag expression.
3773 template) ; `js2-template-node' with the template.
3774
3775 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3776 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3777
3778 (defun js2-visit-tagged-template (n callback)
3779 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3780 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3781
3782 (defun js2-print-tagged-template (n i)
3783 (insert (js2-make-pad i))
3784 (js2-print-ast (js2-tagged-template-node-tag n))
3785 (js2-print-ast (js2-tagged-template-node-template n)))
3786
3787 (cl-defstruct (js2-array-node
3788 (:include js2-node)
3789 (:constructor nil)
3790 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3791 (pos js2-ts-cursor)
3792 len elems)))
3793 "AST node for an array literal."
3794 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3795
3796 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3797 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3798
3799 (defun js2-visit-array-node (n v)
3800 (dolist (e (js2-array-node-elems n))
3801 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3802
3803 (defun js2-print-array-node (n i)
3804 (insert (js2-make-pad i) "[")
3805 (let ((elems (js2-array-node-elems n)))
3806 (js2-print-list elems)
3807 (when (and elems (null (car (last elems))))
3808 (insert ",")))
3809 (insert "]"))
3810
3811 (cl-defstruct (js2-class-node
3812 (:include js2-node)
3813 (:constructor nil)
3814 (:constructor make-js2-class-node (&key (type js2-CLASS)
3815 (pos js2-ts-cursor)
3816 (form 'CLASS_STATEMENT)
3817 (name "")
3818 extends len elems)))
3819 "AST node for an class expression.
3820 `elems' is a list of `js2-object-prop-node', and `extends' is an
3821 optional `js2-expr-node'"
3822 form ; CLASS_{STATEMENT|EXPRESSION}
3823 name ; class name (a `js2-node-name', or nil if anonymous)
3824 extends ; class heritage (a `js2-expr-node', or nil if none)
3825 elems)
3826
3827 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3828 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3829
3830 (defun js2-visit-class-node (n v)
3831 (js2-visit-ast (js2-class-node-name n) v)
3832 (js2-visit-ast (js2-class-node-extends n) v)
3833 (dolist (e (js2-class-node-elems n))
3834 (js2-visit-ast e v)))
3835
3836 (defun js2-print-class-node (n i)
3837 (let* ((pad (js2-make-pad i))
3838 (name (js2-class-node-name n))
3839 (extends (js2-class-node-extends n))
3840 (elems (js2-class-node-elems n)))
3841 (insert pad "class")
3842 (when name
3843 (insert " ")
3844 (js2-print-ast name 0))
3845 (when extends
3846 (insert " extends ")
3847 (js2-print-ast extends))
3848 (insert " {")
3849 (dolist (elem elems)
3850 (insert "\n")
3851 (if (js2-node-get-prop elem 'STATIC)
3852 (progn (insert (js2-make-pad (1+ i)) "static ")
3853 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3854 (js2-print-ast elem (1+ i))))
3855 (insert "\n" pad "}")))
3856
3857 (cl-defstruct (js2-object-node
3858 (:include js2-node)
3859 (:constructor nil)
3860 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3861 (pos js2-ts-cursor)
3862 len
3863 elems)))
3864 "AST node for an object literal expression.
3865 `elems' is a list of `js2-object-prop-node'."
3866 elems)
3867
3868 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3869 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3870
3871 (defun js2-visit-object-node (n v)
3872 (dolist (e (js2-object-node-elems n))
3873 (js2-visit-ast e v)))
3874
3875 (defun js2-print-object-node (n i)
3876 (insert (js2-make-pad i) "{")
3877 (js2-print-list (js2-object-node-elems n))
3878 (insert "}"))
3879
3880 (cl-defstruct (js2-object-prop-node
3881 (:include js2-infix-node)
3882 (:constructor nil)
3883 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3884 (pos js2-ts-cursor)
3885 len left
3886 right op-pos)))
3887 "AST node for an object literal prop:value entry.
3888 The `left' field is the property: a name node, string node,
3889 number node or expression node. The `right' field is a
3890 `js2-node' representing the initializer value. If the property
3891 is abbreviated, the node's `SHORTHAND' property is non-nil and
3892 both fields have the same value.")
3893
3894 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3895 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3896
3897 (defun js2-print-object-prop-node (n i)
3898 (let* ((left (js2-object-prop-node-left n))
3899 (right (js2-object-prop-node-right n))
3900 (computed (not (or (js2-string-node-p left)
3901 (js2-number-node-p left)
3902 (js2-name-node-p left)))))
3903 (insert (js2-make-pad i))
3904 (if computed
3905 (insert "["))
3906 (js2-print-ast left 0)
3907 (if computed
3908 (insert "]"))
3909 (if (not (js2-node-get-prop n 'SHORTHAND))
3910 (progn
3911 (insert ": ")
3912 (js2-print-ast right 0)))))
3913
3914 (cl-defstruct (js2-getter-setter-node
3915 (:include js2-infix-node)
3916 (:constructor nil)
3917 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3918 (pos js2-ts-cursor)
3919 len left right)))
3920 "AST node for a getter/setter property in an object literal.
3921 The `left' field is the `js2-name-node' naming the getter/setter prop.
3922 The `right' field is always an anonymous `js2-function-node' with a node
3923 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3924
3925 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3926 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3927
3928 (defun js2-print-getter-setter (n i)
3929 (let* ((pad (js2-make-pad i))
3930 (left (js2-getter-setter-node-left n))
3931 (right (js2-getter-setter-node-right n))
3932 (computed (not (or (js2-string-node-p left)
3933 (js2-number-node-p left)
3934 (js2-name-node-p left)))))
3935 (insert pad)
3936 (if (/= (js2-node-type n) js2-FUNCTION)
3937 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3938 (when (and (js2-function-node-p right)
3939 (eq 'STAR (js2-function-node-generator-type right)))
3940 (insert "*"))
3941 (when computed
3942 (insert "["))
3943 (js2-print-ast left 0)
3944 (when computed
3945 (insert "]"))
3946 (js2-print-ast right 0)))
3947
3948 (cl-defstruct (js2-prop-get-node
3949 (:include js2-infix-node)
3950 (:constructor nil)
3951 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3952 (pos js2-ts-cursor)
3953 len left right)))
3954 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3955
3956 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3957 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3958
3959 (defun js2-visit-prop-get-node (n v)
3960 (js2-visit-ast (js2-prop-get-node-left n) v)
3961 (js2-visit-ast (js2-prop-get-node-right n) v))
3962
3963 (defun js2-print-prop-get-node (n i)
3964 (insert (js2-make-pad i))
3965 (js2-print-ast (js2-prop-get-node-left n) 0)
3966 (insert ".")
3967 (js2-print-ast (js2-prop-get-node-right n) 0))
3968
3969 (cl-defstruct (js2-elem-get-node
3970 (:include js2-node)
3971 (:constructor nil)
3972 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3973 (pos js2-ts-cursor)
3974 len target element
3975 lb rb)))
3976 "AST node for an array index expression such as foo[bar]."
3977 target ; a `js2-node' - the expression preceding the "."
3978 element ; a `js2-node' - the expression in brackets
3979 lb ; position of left-bracket, nil if omitted
3980 rb) ; position of right-bracket, nil if omitted
3981
3982 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3983 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3984
3985 (defun js2-visit-elem-get-node (n v)
3986 (js2-visit-ast (js2-elem-get-node-target n) v)
3987 (js2-visit-ast (js2-elem-get-node-element n) v))
3988
3989 (defun js2-print-elem-get-node (n i)
3990 (insert (js2-make-pad i))
3991 (js2-print-ast (js2-elem-get-node-target n) 0)
3992 (insert "[")
3993 (js2-print-ast (js2-elem-get-node-element n) 0)
3994 (insert "]"))
3995
3996 (cl-defstruct (js2-call-node
3997 (:include js2-node)
3998 (:constructor nil)
3999 (:constructor make-js2-call-node (&key (type js2-CALL)
4000 (pos js2-ts-cursor)
4001 len target args
4002 lp rp)))
4003 "AST node for a JavaScript function call."
4004 target ; a `js2-node' evaluating to the function to call
4005 args ; a Lisp list of `js2-node' arguments
4006 lp ; position of open-paren, or nil if missing
4007 rp) ; position of close-paren, or nil if missing
4008
4009 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4010 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4011
4012 (defun js2-visit-call-node (n v)
4013 (js2-visit-ast (js2-call-node-target n) v)
4014 (dolist (arg (js2-call-node-args n))
4015 (js2-visit-ast arg v)))
4016
4017 (defun js2-print-call-node (n i)
4018 (insert (js2-make-pad i))
4019 (js2-print-ast (js2-call-node-target n) 0)
4020 (insert "(")
4021 (js2-print-list (js2-call-node-args n))
4022 (insert ")"))
4023
4024 (cl-defstruct (js2-yield-node
4025 (:include js2-node)
4026 (:constructor nil)
4027 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4028 (pos js2-ts-cursor)
4029 len value star-p)))
4030 "AST node for yield statement or expression."
4031 star-p ; whether it's yield*
4032 value) ; optional: value to be yielded
4033
4034 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4035 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4036
4037 (defun js2-visit-yield-node (n v)
4038 (js2-visit-ast (js2-yield-node-value n) v))
4039
4040 (defun js2-print-yield-node (n i)
4041 (insert (js2-make-pad i))
4042 (insert "yield")
4043 (when (js2-yield-node-star-p n)
4044 (insert "*"))
4045 (when (js2-yield-node-value n)
4046 (insert " ")
4047 (js2-print-ast (js2-yield-node-value n) 0)))
4048
4049 (cl-defstruct (js2-paren-node
4050 (:include js2-node)
4051 (:constructor nil)
4052 (:constructor make-js2-paren-node (&key (type js2-LP)
4053 (pos js2-ts-cursor)
4054 len expr)))
4055 "AST node for a parenthesized expression.
4056 In particular, used when the parens are syntactically optional,
4057 as opposed to required parens such as those enclosing an if-conditional."
4058 expr) ; `js2-node'
4059
4060 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4061 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4062
4063 (defun js2-visit-paren-node (n v)
4064 (js2-visit-ast (js2-paren-node-expr n) v))
4065
4066 (defun js2-print-paren-node (n i)
4067 (insert (js2-make-pad i))
4068 (insert "(")
4069 (js2-print-ast (js2-paren-node-expr n) 0)
4070 (insert ")"))
4071
4072 (cl-defstruct (js2-comp-node
4073 (:include js2-scope)
4074 (:constructor nil)
4075 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4076 (pos js2-ts-cursor)
4077 len result
4078 loops filters
4079 form)))
4080 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4081 result ; result expression (just after left-bracket)
4082 loops ; a Lisp list of `js2-comp-loop-node'
4083 filters ; a Lisp list of guard/filter expressions
4084 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4085 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4086 )
4087
4088 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4089 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4090
4091 (defun js2-visit-comp-node (n v)
4092 (js2-visit-ast (js2-comp-node-result n) v)
4093 (dolist (l (js2-comp-node-loops n))
4094 (js2-visit-ast l v))
4095 (dolist (f (js2-comp-node-filters n))
4096 (js2-visit-ast f v)))
4097
4098 (defun js2-print-comp-node (n i)
4099 (let ((pad (js2-make-pad i))
4100 (result (js2-comp-node-result n))
4101 (loops (js2-comp-node-loops n))
4102 (filters (js2-comp-node-filters n))
4103 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4104 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4105 (insert pad (if gen-p "(" "["))
4106 (when legacy-p
4107 (js2-print-ast result 0))
4108 (dolist (l loops)
4109 (when legacy-p
4110 (insert " "))
4111 (js2-print-ast l 0)
4112 (unless legacy-p
4113 (insert " ")))
4114 (dolist (f filters)
4115 (when legacy-p
4116 (insert " "))
4117 (insert "if (")
4118 (js2-print-ast f 0)
4119 (insert ")")
4120 (unless legacy-p
4121 (insert " ")))
4122 (unless legacy-p
4123 (js2-print-ast result 0))
4124 (insert (if gen-p ")" "]"))))
4125
4126 (cl-defstruct (js2-comp-loop-node
4127 (:include js2-for-in-node)
4128 (:constructor nil)
4129 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4130 (pos js2-ts-cursor)
4131 len iterator
4132 object in-pos
4133 foreach-p
4134 each-pos
4135 forof-p
4136 lp rp)))
4137 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4138
4139 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4140 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4141
4142 (defun js2-visit-comp-loop (n v)
4143 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4144 (js2-visit-ast (js2-comp-loop-node-object n) v))
4145
4146 (defun js2-print-comp-loop (n _i)
4147 (insert "for ")
4148 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4149 (insert "(")
4150 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4151 (insert (if (js2-comp-loop-node-forof-p n)
4152 " of " " in "))
4153 (js2-print-ast (js2-comp-loop-node-object n) 0)
4154 (insert ")"))
4155
4156 (cl-defstruct (js2-empty-expr-node
4157 (:include js2-node)
4158 (:constructor nil)
4159 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4160 (pos (js2-current-token-beg))
4161 len)))
4162 "AST node for an empty expression.")
4163
4164 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4165 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4166
4167 (cl-defstruct (js2-xml-node
4168 (:include js2-block-node)
4169 (:constructor nil)
4170 (:constructor make-js2-xml-node (&key (type js2-XML)
4171 (pos (js2-current-token-beg))
4172 len kids)))
4173 "AST node for initial parse of E4X literals.
4174 The kids field is a list of XML fragments, each a `js2-string-node' or
4175 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4176
4177 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4178 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4179
4180 (defun js2-print-xml-node (n i)
4181 (dolist (kid (js2-xml-node-kids n))
4182 (js2-print-ast kid i)))
4183
4184 (cl-defstruct (js2-xml-js-expr-node
4185 (:include js2-xml-node)
4186 (:constructor nil)
4187 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4188 (pos js2-ts-cursor)
4189 len expr)))
4190 "AST node for an embedded JavaScript {expression} in an E4X literal.
4191 The start and end fields correspond to the curly-braces."
4192 expr) ; a `js2-expr-node' of some sort
4193
4194 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4195 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4196
4197 (defun js2-visit-xml-js-expr (n v)
4198 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4199
4200 (defun js2-print-xml-js-expr (n i)
4201 (insert (js2-make-pad i))
4202 (insert "{")
4203 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4204 (insert "}"))
4205
4206 (cl-defstruct (js2-xml-dot-query-node
4207 (:include js2-infix-node)
4208 (:constructor nil)
4209 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4210 (pos js2-ts-cursor)
4211 op-pos len left
4212 right rp)))
4213 "AST node for an E4X foo.(bar) filter expression.
4214 Note that the left-paren is automatically the character immediately
4215 following the dot (.) in the operator. No whitespace is permitted
4216 between the dot and the lp by the scanner."
4217 rp)
4218
4219 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4220 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4221
4222 (defun js2-print-xml-dot-query (n i)
4223 (insert (js2-make-pad i))
4224 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4225 (insert ".(")
4226 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4227 (insert ")"))
4228
4229 (cl-defstruct (js2-xml-ref-node
4230 (:include js2-node)
4231 (:constructor nil)) ; abstract
4232 "Base type for E4X XML attribute-access or property-get expressions.
4233 Such expressions can take a variety of forms. The general syntax has
4234 three parts:
4235
4236 - (optional) an @ (specifying an attribute access)
4237 - (optional) a namespace (a `js2-name-node') and double-colon
4238 - (required) either a `js2-name-node' or a bracketed [expression]
4239
4240 The property-name expressions (examples: ns::name, @name) are
4241 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4242 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4243
4244 This node type (or more specifically, its subclasses) will sometimes
4245 be the right-hand child of a `js2-prop-get-node' or a
4246 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4247 The `js2-xml-ref-node' may also be a standalone primary expression with
4248 no explicit target, which is valid in certain expression contexts such as
4249
4250 company..employee.(@id < 100)
4251
4252 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4253 expression whose parent is a `js2-xml-dot-query-node'."
4254 namespace
4255 at-pos
4256 colon-pos)
4257
4258 (defsubst js2-xml-ref-node-attr-access-p (node)
4259 "Return non-nil if this expression began with an @-token."
4260 (and (numberp (js2-xml-ref-node-at-pos node))
4261 (cl-plusp (js2-xml-ref-node-at-pos node))))
4262
4263 (cl-defstruct (js2-xml-prop-ref-node
4264 (:include js2-xml-ref-node)
4265 (:constructor nil)
4266 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4267 (pos (js2-current-token-beg))
4268 len propname
4269 namespace at-pos
4270 colon-pos)))
4271 "AST node for an E4X XML [expr] property-ref expression.
4272 The JavaScript syntax is an optional @, an optional ns::, and a name.
4273
4274 [ '@' ] [ name '::' ] name
4275
4276 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4277 @ns::*, @*::attr, @*::*, and @*.
4278
4279 The node starts at the @ token, if present. Otherwise it starts at the
4280 namespace name. The node bounds extend through the closing right-bracket,
4281 or if it is missing due to a syntax error, through the end of the index
4282 expression."
4283 propname)
4284
4285 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4286 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4287
4288 (defun js2-visit-xml-prop-ref-node (n v)
4289 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4290 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4291
4292 (defun js2-print-xml-prop-ref-node (n i)
4293 (insert (js2-make-pad i))
4294 (if (js2-xml-ref-node-attr-access-p n)
4295 (insert "@"))
4296 (when (js2-xml-prop-ref-node-namespace n)
4297 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4298 (insert "::"))
4299 (if (js2-xml-prop-ref-node-propname n)
4300 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4301
4302 (cl-defstruct (js2-xml-elem-ref-node
4303 (:include js2-xml-ref-node)
4304 (:constructor nil)
4305 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4306 (pos (js2-current-token-beg))
4307 len expr lb rb
4308 namespace at-pos
4309 colon-pos)))
4310 "AST node for an E4X XML [expr] member-ref expression.
4311 Syntax:
4312
4313 [ '@' ] [ name '::' ] '[' expr ']'
4314
4315 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4316
4317 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4318 is not a legal E4X XML element-ref expression, since it's already used
4319 for standard JavaScript element-get array indexing. Hence, a
4320 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4321 non-nil namespace node, or both.
4322
4323 The node starts at the @ token, if present. Otherwise it starts
4324 at the namespace name. The node bounds extend through the closing
4325 right-bracket, or if it is missing due to a syntax error, through the
4326 end of the index expression."
4327 expr ; the bracketed index expression
4328 lb
4329 rb)
4330
4331 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4332 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4333
4334 (defun js2-visit-xml-elem-ref-node (n v)
4335 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4336 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4337
4338 (defun js2-print-xml-elem-ref-node (n i)
4339 (insert (js2-make-pad i))
4340 (if (js2-xml-ref-node-attr-access-p n)
4341 (insert "@"))
4342 (when (js2-xml-elem-ref-node-namespace n)
4343 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4344 (insert "::"))
4345 (insert "[")
4346 (if (js2-xml-elem-ref-node-expr n)
4347 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4348 (insert "]"))
4349
4350 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4351
4352 (cl-defstruct (js2-xml-start-tag-node
4353 (:include js2-xml-node)
4354 (:constructor nil)
4355 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4356 (pos js2-ts-cursor)
4357 len name attrs kids
4358 empty-p)))
4359 "AST node for an XML start-tag. Not currently used.
4360 The `kids' field is a Lisp list of child content nodes."
4361 name ; a `js2-xml-name-node'
4362 attrs ; a Lisp list of `js2-xml-attr-node'
4363 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4364
4365 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4366 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4367
4368 (defun js2-visit-xml-start-tag (n v)
4369 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4370 (dolist (attr (js2-xml-start-tag-node-attrs n))
4371 (js2-visit-ast attr v))
4372 (js2-visit-block n v))
4373
4374 (defun js2-print-xml-start-tag (n i)
4375 (insert (js2-make-pad i) "<")
4376 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4377 (when (js2-xml-start-tag-node-attrs n)
4378 (insert " ")
4379 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4380 (insert ">"))
4381
4382 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4383 ;; and add the end-tag to the kids list of the parent as well.
4384 (cl-defstruct (js2-xml-end-tag-node
4385 (:include js2-xml-node)
4386 (:constructor nil)
4387 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4388 (pos js2-ts-cursor)
4389 len name)))
4390 "AST node for an XML end-tag. Not currently used."
4391 name) ; a `js2-xml-name-node'
4392
4393 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4394 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4395
4396 (defun js2-visit-xml-end-tag (n v)
4397 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4398
4399 (defun js2-print-xml-end-tag (n i)
4400 (insert (js2-make-pad i))
4401 (insert "</")
4402 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4403 (insert ">"))
4404
4405 (cl-defstruct (js2-xml-name-node
4406 (:include js2-xml-node)
4407 (:constructor nil)
4408 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4409 (pos js2-ts-cursor)
4410 len namespace kids)))
4411 "AST node for an E4X XML name. Not currently used.
4412 Any XML name can be qualified with a namespace, hence the namespace field.
4413 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4414 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4415 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4416 namespace) ; a `js2-string-node'
4417
4418 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4419 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4420
4421 (defun js2-visit-xml-name-node (n v)
4422 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4423
4424 (defun js2-print-xml-name-node (n i)
4425 (insert (js2-make-pad i))
4426 (when (js2-xml-name-node-namespace n)
4427 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4428 (insert "::"))
4429 (dolist (kid (js2-xml-name-node-kids n))
4430 (js2-print-ast kid 0)))
4431
4432 (cl-defstruct (js2-xml-pi-node
4433 (:include js2-xml-node)
4434 (:constructor nil)
4435 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4436 (pos js2-ts-cursor)
4437 len name attrs)))
4438 "AST node for an E4X XML processing instruction. Not currently used."
4439 name ; a `js2-xml-name-node'
4440 attrs) ; a list of `js2-xml-attr-node'
4441
4442 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4443 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4444
4445 (defun js2-visit-xml-pi-node (n v)
4446 (js2-visit-ast (js2-xml-pi-node-name n) v)
4447 (dolist (attr (js2-xml-pi-node-attrs n))
4448 (js2-visit-ast attr v)))
4449
4450 (defun js2-print-xml-pi-node (n i)
4451 (insert (js2-make-pad i) "<?")
4452 (js2-print-ast (js2-xml-pi-node-name n))
4453 (when (js2-xml-pi-node-attrs n)
4454 (insert " ")
4455 (js2-print-list (js2-xml-pi-node-attrs n)))
4456 (insert "?>"))
4457
4458 (cl-defstruct (js2-xml-cdata-node
4459 (:include js2-xml-node)
4460 (:constructor nil)
4461 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4462 (pos js2-ts-cursor)
4463 len content)))
4464 "AST node for a CDATA escape section. Not currently used."
4465 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4466
4467 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4468 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4469
4470 (defun js2-visit-xml-cdata-node (n v)
4471 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4472
4473 (defun js2-print-xml-cdata-node (n i)
4474 (insert (js2-make-pad i))
4475 (js2-print-ast (js2-xml-cdata-node-content n)))
4476
4477 (cl-defstruct (js2-xml-attr-node
4478 (:include js2-xml-node)
4479 (:constructor nil)
4480 (:constructor make-js2-attr-node (&key (type js2-XML)
4481 (pos js2-ts-cursor)
4482 len name value
4483 eq-pos quote-type)))
4484 "AST node representing a foo='bar' XML attribute value. Not yet used."
4485 name ; a `js2-xml-name-node'
4486 value ; a `js2-xml-name-node'
4487 eq-pos ; buffer position of "=" sign
4488 quote-type) ; 'single or 'double
4489
4490 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4491 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4492
4493 (defun js2-visit-xml-attr-node (n v)
4494 (js2-visit-ast (js2-xml-attr-node-name n) v)
4495 (js2-visit-ast (js2-xml-attr-node-value n) v))
4496
4497 (defun js2-print-xml-attr-node (n i)
4498 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4499 "'"
4500 "\"")))
4501 (insert (js2-make-pad i))
4502 (js2-print-ast (js2-xml-attr-node-name n) 0)
4503 (insert "=" quote)
4504 (js2-print-ast (js2-xml-attr-node-value n) 0)
4505 (insert quote)))
4506
4507 (cl-defstruct (js2-xml-text-node
4508 (:include js2-xml-node)
4509 (:constructor nil)
4510 (:constructor make-js2-text-node (&key (type js2-XML)
4511 (pos js2-ts-cursor)
4512 len content)))
4513 "AST node for an E4X XML text node. Not currently used."
4514 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4515
4516 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4517 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4518
4519 (defun js2-visit-xml-text-node (n v)
4520 (js2-visit-ast (js2-xml-text-node-content n) v))
4521
4522 (defun js2-print-xml-text-node (n i)
4523 (insert (js2-make-pad i))
4524 (dolist (kid (js2-xml-text-node-content n))
4525 (js2-print-ast kid)))
4526
4527 (cl-defstruct (js2-xml-comment-node
4528 (:include js2-xml-node)
4529 (:constructor nil)
4530 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4531 (pos js2-ts-cursor)
4532 len)))
4533 "AST node for E4X XML comment. Not currently used.")
4534
4535 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4536 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4537
4538 (defun js2-print-xml-comment (n i)
4539 (insert (js2-make-pad i)
4540 (js2-node-string n)))
4541
4542 ;;; Node utilities
4543
4544 (defsubst js2-node-line (n)
4545 "Fetch the source line number at the start of node N.
4546 This is O(n) in the length of the source buffer; use prudently."
4547 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4548
4549 (defsubst js2-block-node-kid (n i)
4550 "Return child I of node N, or nil if there aren't that many."
4551 (nth i (js2-block-node-kids n)))
4552
4553 (defsubst js2-block-node-first (n)
4554 "Return first child of block node N, or nil if there is none."
4555 (cl-first (js2-block-node-kids n)))
4556
4557 (defun js2-node-root (n)
4558 "Return the root of the AST containing N.
4559 If N has no parent pointer, returns N."
4560 (let ((parent (js2-node-parent n)))
4561 (if parent
4562 (js2-node-root parent)
4563 n)))
4564
4565 (defsubst js2-node-short-name (n)
4566 "Return the short name of node N as a string, e.g. `js2-if-node'."
4567 (substring (symbol-name (aref n 0))
4568 (length "cl-struct-")))
4569
4570 (defun js2-node-child-list (node)
4571 "Return the child list for NODE, a Lisp list of nodes.
4572 Works for block nodes, array nodes, obj literals, funarg lists,
4573 var decls and try nodes (for catch clauses). Note that you should call
4574 `js2-block-node-kids' on the function body for the body statements.
4575 Returns nil for zero-length child lists or unsupported nodes."
4576 (cond
4577 ((js2-function-node-p node)
4578 (js2-function-node-params node))
4579 ((js2-block-node-p node)
4580 (js2-block-node-kids node))
4581 ((js2-try-node-p node)
4582 (js2-try-node-catch-clauses node))
4583 ((js2-array-node-p node)
4584 (js2-array-node-elems node))
4585 ((js2-object-node-p node)
4586 (js2-object-node-elems node))
4587 ((js2-call-node-p node)
4588 (js2-call-node-args node))
4589 ((js2-new-node-p node)
4590 (js2-new-node-args node))
4591 ((js2-var-decl-node-p node)
4592 (js2-var-decl-node-kids node))
4593 (t
4594 nil)))
4595
4596 (defun js2-node-set-child-list (node kids)
4597 "Set the child list for NODE to KIDS."
4598 (cond
4599 ((js2-function-node-p node)
4600 (setf (js2-function-node-params node) kids))
4601 ((js2-block-node-p node)
4602 (setf (js2-block-node-kids node) kids))
4603 ((js2-try-node-p node)
4604 (setf (js2-try-node-catch-clauses node) kids))
4605 ((js2-array-node-p node)
4606 (setf (js2-array-node-elems node) kids))
4607 ((js2-object-node-p node)
4608 (setf (js2-object-node-elems node) kids))
4609 ((js2-call-node-p node)
4610 (setf (js2-call-node-args node) kids))
4611 ((js2-new-node-p node)
4612 (setf (js2-new-node-args node) kids))
4613 ((js2-var-decl-node-p node)
4614 (setf (js2-var-decl-node-kids node) kids))
4615 (t
4616 (error "Unsupported node type: %s" (js2-node-short-name node))))
4617 kids)
4618
4619 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4620 (defconst js2-paren-expr-nodes
4621 '(cl-struct-js2-comp-loop-node
4622 cl-struct-js2-comp-node
4623 cl-struct-js2-call-node
4624 cl-struct-js2-catch-node
4625 cl-struct-js2-do-node
4626 cl-struct-js2-elem-get-node
4627 cl-struct-js2-for-in-node
4628 cl-struct-js2-for-node
4629 cl-struct-js2-function-node
4630 cl-struct-js2-if-node
4631 cl-struct-js2-let-node
4632 cl-struct-js2-new-node
4633 cl-struct-js2-paren-node
4634 cl-struct-js2-switch-node
4635 cl-struct-js2-while-node
4636 cl-struct-js2-with-node
4637 cl-struct-js2-xml-dot-query-node)
4638 "Node types that can have a parenthesized child expression.
4639 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4640
4641 (defsubst js2-paren-expr-node-p (node)
4642 "Return t for nodes that typically have a parenthesized child expression.
4643 Useful for computing the indentation anchors for arg-lists and conditions.
4644 Note that it may return a false positive, for instance when NODE is
4645 a `js2-new-node' and there are no arguments or parentheses."
4646 (memq (aref node 0) js2-paren-expr-nodes))
4647
4648 ;; Fake polymorphism... yech.
4649 (defun js2-node-lp (node)
4650 "Return relative left-paren position for NODE, if applicable.
4651 For `js2-elem-get-node' structs, returns left-bracket position.
4652 Note that the position may be nil in the case of a parse error."
4653 (cond
4654 ((js2-elem-get-node-p node)
4655 (js2-elem-get-node-lb node))
4656 ((js2-loop-node-p node)
4657 (js2-loop-node-lp node))
4658 ((js2-function-node-p node)
4659 (js2-function-node-lp node))
4660 ((js2-if-node-p node)
4661 (js2-if-node-lp node))
4662 ((js2-new-node-p node)
4663 (js2-new-node-lp node))
4664 ((js2-call-node-p node)
4665 (js2-call-node-lp node))
4666 ((js2-paren-node-p node)
4667 0)
4668 ((js2-switch-node-p node)
4669 (js2-switch-node-lp node))
4670 ((js2-catch-node-p node)
4671 (js2-catch-node-lp node))
4672 ((js2-let-node-p node)
4673 (js2-let-node-lp node))
4674 ((js2-comp-node-p node)
4675 0)
4676 ((js2-with-node-p node)
4677 (js2-with-node-lp node))
4678 ((js2-xml-dot-query-node-p node)
4679 (1+ (js2-infix-node-op-pos node)))
4680 (t
4681 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4682
4683 ;; Fake polymorphism... blech.
4684 (defun js2-node-rp (node)
4685 "Return relative right-paren position for NODE, if applicable.
4686 For `js2-elem-get-node' structs, returns right-bracket position.
4687 Note that the position may be nil in the case of a parse error."
4688 (cond
4689 ((js2-elem-get-node-p node)
4690 (js2-elem-get-node-rb node))
4691 ((js2-loop-node-p node)
4692 (js2-loop-node-rp node))
4693 ((js2-function-node-p node)
4694 (js2-function-node-rp node))
4695 ((js2-if-node-p node)
4696 (js2-if-node-rp node))
4697 ((js2-new-node-p node)
4698 (js2-new-node-rp node))
4699 ((js2-call-node-p node)
4700 (js2-call-node-rp node))
4701 ((js2-paren-node-p node)
4702 (1- (js2-node-len node)))
4703 ((js2-switch-node-p node)
4704 (js2-switch-node-rp node))
4705 ((js2-catch-node-p node)
4706 (js2-catch-node-rp node))
4707 ((js2-let-node-p node)
4708 (js2-let-node-rp node))
4709 ((js2-comp-node-p node)
4710 (1- (js2-node-len node)))
4711 ((js2-with-node-p node)
4712 (js2-with-node-rp node))
4713 ((js2-xml-dot-query-node-p node)
4714 (1+ (js2-xml-dot-query-node-rp node)))
4715 (t
4716 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4717
4718 (defsubst js2-node-first-child (node)
4719 "Return the first element of `js2-node-child-list' for NODE."
4720 (car (js2-node-child-list node)))
4721
4722 (defsubst js2-node-last-child (node)
4723 "Return the last element of `js2-node-last-child' for NODE."
4724 (car (last (js2-node-child-list node))))
4725
4726 (defun js2-node-prev-sibling (node)
4727 "Return the previous statement in parent.
4728 Works for parents supported by `js2-node-child-list'.
4729 Returns nil if NODE is not in the parent, or PARENT is
4730 not a supported node, or if NODE is the first child."
4731 (let* ((p (js2-node-parent node))
4732 (kids (js2-node-child-list p))
4733 (sib (car kids)))
4734 (while (and kids
4735 (not (eq node (cadr kids))))
4736 (setq kids (cdr kids)
4737 sib (car kids)))
4738 sib))
4739
4740 (defun js2-node-next-sibling (node)
4741 "Return the next statement in parent block.
4742 Returns nil if NODE is not in the block, or PARENT is not
4743 a block node, or if NODE is the last statement."
4744 (let* ((p (js2-node-parent node))
4745 (kids (js2-node-child-list p)))
4746 (while (and kids
4747 (not (eq node (car kids))))
4748 (setq kids (cdr kids)))
4749 (cadr kids)))
4750
4751 (defun js2-node-find-child-before (pos parent &optional after)
4752 "Find the last child that starts before POS in parent.
4753 If AFTER is non-nil, returns first child starting after POS.
4754 POS is an absolute buffer position. PARENT is any node
4755 supported by `js2-node-child-list'.
4756 Returns nil if no applicable child is found."
4757 (let ((kids (if (js2-function-node-p parent)
4758 (js2-block-node-kids (js2-function-node-body parent))
4759 (js2-node-child-list parent)))
4760 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4761 (js2-function-node-body parent)
4762 parent)))
4763 kid result fn
4764 (continue t))
4765 (setq fn (if after '>= '<))
4766 (while (and kids continue)
4767 (setq kid (car kids))
4768 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4769 (setq result kid
4770 continue (not after))
4771 (setq continue after))
4772 (setq kids (cdr kids)))
4773 result))
4774
4775 (defun js2-node-find-child-after (pos parent)
4776 "Find first child that starts after POS in parent.
4777 POS is an absolute buffer position. PARENT is any node
4778 supported by `js2-node-child-list'.
4779 Returns nil if no applicable child is found."
4780 (js2-node-find-child-before pos parent 'after))
4781
4782 (defun js2-node-replace-child (pos parent new-node)
4783 "Replace node at index POS in PARENT with NEW-NODE.
4784 Only works for parents supported by `js2-node-child-list'."
4785 (let ((kids (js2-node-child-list parent))
4786 (i 0))
4787 (while (< i pos)
4788 (setq kids (cdr kids)
4789 i (1+ i)))
4790 (setcar kids new-node)
4791 (js2-node-add-children parent new-node)))
4792
4793 (defun js2-node-buffer (n)
4794 "Return the buffer associated with AST N.
4795 Returns nil if the buffer is not set as a property on the root
4796 node, or if parent links were not recorded during parsing."
4797 (let ((root (js2-node-root n)))
4798 (and root
4799 (js2-ast-root-p root)
4800 (js2-ast-root-buffer root))))
4801
4802 (defun js2-block-node-push (n kid)
4803 "Push js2-node KID onto the end of js2-block-node N's child list.
4804 KID is always added to the -end- of the kids list.
4805 Function also calls `js2-node-add-children' to add the parent link."
4806 (let ((kids (js2-node-child-list n)))
4807 (if kids
4808 (setcdr kids (nconc (cdr kids) (list kid)))
4809 (js2-node-set-child-list n (list kid)))
4810 (js2-node-add-children n kid)))
4811
4812 (defun js2-node-string (node)
4813 (with-current-buffer (or (js2-node-buffer node)
4814 (error "No buffer available for node %s" node))
4815 (let ((pos (js2-node-abs-pos node)))
4816 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4817
4818 ;; Container for storing the node we're looking for in a traversal.
4819 (js2-deflocal js2-discovered-node nil)
4820
4821 ;; Keep track of absolute node position during traversals.
4822 (js2-deflocal js2-visitor-offset nil)
4823
4824 (js2-deflocal js2-node-search-point nil)
4825
4826 (when js2-mode-dev-mode-p
4827 (defun js2-find-node-at-point ()
4828 (interactive)
4829 (let ((node (js2-node-at-point)))
4830 (message "%s" (or node "No node found at point"))))
4831 (defun js2-node-name-at-point ()
4832 (interactive)
4833 (let ((node (js2-node-at-point)))
4834 (message "%s" (if node
4835 (js2-node-short-name node)
4836 "No node found at point.")))))
4837
4838 (defun js2-node-at-point (&optional pos skip-comments)
4839 "Return AST node at POS, a buffer position, defaulting to current point.
4840 The `js2-mode-ast' variable must be set to the current parse tree.
4841 Signals an error if the AST (`js2-mode-ast') is nil.
4842 Always returns a node - if it can't find one, it returns the root.
4843 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4844 (let ((ast js2-mode-ast)
4845 result)
4846 (unless ast
4847 (error "No JavaScript AST available"))
4848 ;; Look through comments first, since they may be inside nodes that
4849 ;; would otherwise report a match.
4850 (setq pos (or pos (point))
4851 result (if (> pos (js2-node-abs-end ast))
4852 ast
4853 (if (not skip-comments)
4854 (js2-comment-at-point pos))))
4855 (unless result
4856 (setq js2-discovered-node nil
4857 js2-visitor-offset 0
4858 js2-node-search-point pos)
4859 (unwind-protect
4860 (catch 'js2-visit-done
4861 (js2-visit-ast ast #'js2-node-at-point-visitor))
4862 (setq js2-visitor-offset nil
4863 js2-node-search-point nil))
4864 (setq result js2-discovered-node))
4865 ;; may have found a comment beyond end of last child node,
4866 ;; since visiting the ast-root looks at the comment-list last.
4867 (if (and skip-comments
4868 (js2-comment-node-p result))
4869 (setq result nil))
4870 (or result js2-mode-ast)))
4871
4872 (defun js2-node-at-point-visitor (node end-p)
4873 (let ((rel-pos (js2-node-pos node))
4874 abs-pos
4875 abs-end
4876 (point js2-node-search-point))
4877 (cond
4878 (end-p
4879 ;; this evaluates to a non-nil return value, even if it's zero
4880 (cl-decf js2-visitor-offset rel-pos))
4881 ;; we already looked for comments before visiting, and don't want them now
4882 ((js2-comment-node-p node)
4883 nil)
4884 (t
4885 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4886 ;; we only want to use the node if the point is before
4887 ;; the last character position in the node, so we decrement
4888 ;; the absolute end by 1.
4889 abs-end (+ abs-pos (js2-node-len node) -1))
4890 (cond
4891 ;; If this node starts after search-point, stop the search.
4892 ((> abs-pos point)
4893 (throw 'js2-visit-done nil))
4894 ;; If this node ends before the search-point, don't check kids.
4895 ((> point abs-end)
4896 nil)
4897 (t
4898 ;; Otherwise point is within this node, possibly in a child.
4899 (setq js2-discovered-node node)
4900 t)))))) ; keep processing kids to look for more specific match
4901
4902 (defsubst js2-block-comment-p (node)
4903 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4904 (and (js2-comment-node-p node)
4905 (memq (js2-comment-node-format node) '(jsdoc block))))
4906
4907 ;; TODO: put the comments in a vector and binary-search them instead
4908 (defun js2-comment-at-point (&optional pos)
4909 "Look through scanned comment nodes for one containing POS.
4910 POS is a buffer position that defaults to current point.
4911 Function returns nil if POS was not in any comment node."
4912 (let ((ast js2-mode-ast)
4913 (x (or pos (point)))
4914 beg end)
4915 (unless ast
4916 (error "No JavaScript AST available"))
4917 (catch 'done
4918 ;; Comments are stored in lexical order.
4919 (dolist (comment (js2-ast-root-comments ast) nil)
4920 (setq beg (js2-node-abs-pos comment)
4921 end (+ beg (js2-node-len comment)))
4922 (if (and (>= x beg)
4923 (<= x end))
4924 (throw 'done comment))))))
4925
4926 (defun js2-mode-find-parent-fn (node)
4927 "Find function enclosing NODE.
4928 Returns nil if NODE is not inside a function."
4929 (setq node (js2-node-parent node))
4930 (while (and node (not (js2-function-node-p node)))
4931 (setq node (js2-node-parent node)))
4932 (and (js2-function-node-p node) node))
4933
4934 (defun js2-mode-find-enclosing-fn (node)
4935 "Find function or root enclosing NODE."
4936 (if (js2-ast-root-p node)
4937 node
4938 (setq node (js2-node-parent node))
4939 (while (not (or (js2-ast-root-p node)
4940 (js2-function-node-p node)))
4941 (setq node (js2-node-parent node)))
4942 node))
4943
4944 (defun js2-mode-find-enclosing-node (beg end)
4945 "Find node fully enclosing BEG and END."
4946 (let ((node (js2-node-at-point beg))
4947 pos
4948 (continue t))
4949 (while continue
4950 (if (or (js2-ast-root-p node)
4951 (and
4952 (<= (setq pos (js2-node-abs-pos node)) beg)
4953 (>= (+ pos (js2-node-len node)) end)))
4954 (setq continue nil)
4955 (setq node (js2-node-parent node))))
4956 node))
4957
4958 (defun js2-node-parent-script-or-fn (node)
4959 "Find script or function immediately enclosing NODE.
4960 If NODE is the ast-root, returns nil."
4961 (if (js2-ast-root-p node)
4962 nil
4963 (setq node (js2-node-parent node))
4964 (while (and node (not (or (js2-function-node-p node)
4965 (js2-script-node-p node))))
4966 (setq node (js2-node-parent node)))
4967 node))
4968
4969 (defun js2-node-is-descendant (node ancestor)
4970 "Return t if NODE is a descendant of ANCESTOR."
4971 (while (and node
4972 (not (eq node ancestor)))
4973 (setq node (js2-node-parent node)))
4974 node)
4975
4976 ;;; visitor infrastructure
4977
4978 (defun js2-visit-none (_node _callback)
4979 "Visitor for AST node that have no node children."
4980 nil)
4981
4982 (defun js2-print-none (_node _indent)
4983 "Visitor for AST node with no printed representation.")
4984
4985 (defun js2-print-body (node indent)
4986 "Print a statement, or a block without braces."
4987 (if (js2-block-node-p node)
4988 (dolist (kid (js2-block-node-kids node))
4989 (js2-print-ast kid indent))
4990 (js2-print-ast node indent)))
4991
4992 (defun js2-print-list (args &optional delimiter)
4993 (cl-loop with len = (length args)
4994 for arg in args
4995 for count from 1
4996 do
4997 (when arg (js2-print-ast arg 0))
4998 (if (< count len)
4999 (insert (or delimiter ", ")))))
5000
5001 (defun js2-print-tree (ast)
5002 "Prints an AST to the current buffer.
5003 Makes `js2-ast-parent-nodes' available to the printer functions."
5004 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5005 (js2-print-ast ast)))
5006
5007 (defun js2-print-ast (node &optional indent)
5008 "Helper function for printing AST nodes.
5009 Requires `js2-ast-parent-nodes' to be non-nil.
5010 You should use `js2-print-tree' instead of this function."
5011 (let ((printer (get (aref node 0) 'js2-printer))
5012 (i (or indent 0)))
5013 ;; TODO: wedge comments in here somewhere
5014 (if printer
5015 (funcall printer node i))))
5016
5017 (defconst js2-side-effecting-tokens
5018 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5019 (dolist (tt (list js2-ASSIGN
5020 js2-ASSIGN_ADD
5021 js2-ASSIGN_BITAND
5022 js2-ASSIGN_BITOR
5023 js2-ASSIGN_BITXOR
5024 js2-ASSIGN_DIV
5025 js2-ASSIGN_LSH
5026 js2-ASSIGN_MOD
5027 js2-ASSIGN_MUL
5028 js2-ASSIGN_RSH
5029 js2-ASSIGN_SUB
5030 js2-ASSIGN_URSH
5031 js2-BLOCK
5032 js2-BREAK
5033 js2-CALL
5034 js2-CATCH
5035 js2-CATCH_SCOPE
5036 js2-CLASS
5037 js2-CONST
5038 js2-CONTINUE
5039 js2-DEBUGGER
5040 js2-DEC
5041 js2-DELPROP
5042 js2-DEL_REF
5043 js2-DO
5044 js2-ELSE
5045 js2-EMPTY
5046 js2-ENTERWITH
5047 js2-EXPORT
5048 js2-EXPR_RESULT
5049 js2-FINALLY
5050 js2-FOR
5051 js2-FUNCTION
5052 js2-GOTO
5053 js2-IF
5054 js2-IFEQ
5055 js2-IFNE
5056 js2-IMPORT
5057 js2-INC
5058 js2-JSR
5059 js2-LABEL
5060 js2-LEAVEWITH
5061 js2-LET
5062 js2-LETEXPR
5063 js2-LOCAL_BLOCK
5064 js2-LOOP
5065 js2-NEW
5066 js2-REF_CALL
5067 js2-RETHROW
5068 js2-RETURN
5069 js2-RETURN_RESULT
5070 js2-SEMI
5071 js2-SETELEM
5072 js2-SETELEM_OP
5073 js2-SETNAME
5074 js2-SETPROP
5075 js2-SETPROP_OP
5076 js2-SETVAR
5077 js2-SET_REF
5078 js2-SET_REF_OP
5079 js2-SWITCH
5080 js2-TARGET
5081 js2-THROW
5082 js2-TRY
5083 js2-VAR
5084 js2-WHILE
5085 js2-WITH
5086 js2-WITHEXPR
5087 js2-YIELD))
5088 (aset tokens tt t))
5089 (if js2-instanceof-has-side-effects
5090 (aset tokens js2-INSTANCEOF t))
5091 tokens))
5092
5093 (defun js2-node-has-side-effects (node)
5094 "Return t if NODE has side effects."
5095 (when node ; makes it easier to handle malformed expressions
5096 (let ((tt (js2-node-type node)))
5097 (cond
5098 ;; This doubtless needs some work, since EXPR_VOID is used
5099 ;; in several ways in Rhino and I may not have caught them all.
5100 ;; I'll wait for people to notice incorrect warnings.
5101 ((and (= tt js2-EXPR_VOID)
5102 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5103 (let ((expr (js2-expr-stmt-node-expr node)))
5104 (or (js2-node-has-side-effects expr)
5105 (when (js2-string-node-p expr)
5106 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5107 ((= tt js2-COMMA)
5108 (js2-node-has-side-effects (js2-infix-node-right node)))
5109 ((or (= tt js2-AND)
5110 (= tt js2-OR))
5111 (or (js2-node-has-side-effects (js2-infix-node-right node))
5112 (js2-node-has-side-effects (js2-infix-node-left node))))
5113 ((= tt js2-HOOK)
5114 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5115 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5116 ((js2-paren-node-p node)
5117 (js2-node-has-side-effects (js2-paren-node-expr node)))
5118 ((= tt js2-ERROR) ; avoid cascaded error messages
5119 nil)
5120 (t
5121 (aref js2-side-effecting-tokens tt))))))
5122
5123 (defconst js2-stmt-node-types
5124 (list js2-BLOCK
5125 js2-BREAK
5126 js2-CONTINUE
5127 js2-DEFAULT ; e4x "default xml namespace" statement
5128 js2-DO
5129 js2-EXPORT
5130 js2-EXPR_RESULT
5131 js2-EXPR_VOID
5132 js2-FOR
5133 js2-IF
5134 js2-IMPORT
5135 js2-RETURN
5136 js2-SWITCH
5137 js2-THROW
5138 js2-TRY
5139 js2-WHILE
5140 js2-WITH)
5141 "Node types that only appear in statement contexts.
5142 The list does not include nodes that always appear as the child
5143 of another specific statement type, such as switch-cases,
5144 catch and finally blocks, and else-clauses. The list also excludes
5145 nodes like yield, let and var, which may appear in either expression
5146 or statement context, and in the latter context always have a
5147 `js2-expr-stmt-node' parent. Finally, the list does not include
5148 functions or scripts, which are treated separately from statements
5149 by the JavaScript parser and runtime.")
5150
5151 (defun js2-stmt-node-p (node)
5152 "Heuristic for figuring out if NODE is a statement.
5153 Some node types can appear in either an expression context or a
5154 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5155 For these node types in a statement context, the parent will be a
5156 `js2-expr-stmt-node'.
5157 Functions aren't included in the check."
5158 (memq (js2-node-type node) js2-stmt-node-types))
5159
5160 (defun js2-mode-find-first-stmt (node)
5161 "Search upward starting from NODE looking for a statement.
5162 For purposes of this function, a `js2-function-node' counts."
5163 (while (not (or (js2-stmt-node-p node)
5164 (js2-function-node-p node)))
5165 (setq node (js2-node-parent node)))
5166 node)
5167
5168 (defun js2-node-parent-stmt (node)
5169 "Return the node's first ancestor that is a statement.
5170 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5171 appearing in a statement context will have a parent that is a
5172 `js2-expr-stmt-node' that will be returned by this function."
5173 (let ((parent (js2-node-parent node)))
5174 (if (or (null parent)
5175 (js2-stmt-node-p parent)
5176 (and (js2-function-node-p parent)
5177 (not (eq (js2-function-node-form parent)
5178 'FUNCTION_EXPRESSION))))
5179 parent
5180 (js2-node-parent-stmt parent))))
5181
5182 ;; In the Mozilla Rhino sources, Roshan James writes:
5183 ;; Does consistent-return analysis on the function body when strict mode is
5184 ;; enabled.
5185 ;;
5186 ;; function (x) { return (x+1) }
5187 ;;
5188 ;; is ok, but
5189 ;;
5190 ;; function (x) { if (x < 0) return (x+1); }
5191 ;;
5192 ;; is not because the function can potentially return a value when the
5193 ;; condition is satisfied and if not, the function does not explicitly
5194 ;; return a value.
5195 ;;
5196 ;; This extends to checking mismatches such as "return" and "return <value>"
5197 ;; used in the same function. Warnings are not emitted if inconsistent
5198 ;; returns exist in code that can be statically shown to be unreachable.
5199 ;; Ex.
5200 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5201 ;;
5202 ;; emits no warning. However if the loop had a break statement, then a
5203 ;; warning would be emitted.
5204 ;;
5205 ;; The consistency analysis looks at control structures such as loops, ifs,
5206 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5207 ;; warns the user about an inconsistent set of termination possibilities.
5208 ;;
5209 ;; These flags enumerate the possible ways a statement/function can
5210 ;; terminate. These flags are used by endCheck() and by the Parser to
5211 ;; detect inconsistent return usage.
5212 ;;
5213 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5214 ;; able to execute (example: throw, continue)
5215 ;;
5216 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5217 ;; next one. Statement such as return dont. A compound statement may have
5218 ;; some branch that drops off control to the next statement.
5219 ;;
5220 ;; END_RETURNS indicates that the statement can return with no value.
5221 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5222 ;;
5223 ;; A compound statement such as
5224 ;; if (condition) {
5225 ;; return value;
5226 ;; }
5227 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5228
5229 (defconst js2-END_UNREACHED 0)
5230 (defconst js2-END_DROPS_OFF 1)
5231 (defconst js2-END_RETURNS 2)
5232 (defconst js2-END_RETURNS_VALUE 4)
5233 (defconst js2-END_YIELDS 8)
5234
5235 (defun js2-has-consistent-return-usage (node)
5236 "Check that every return usage in a function body is consistent.
5237 Returns t if the function satisfies strict mode requirement."
5238 (let ((n (js2-end-check node)))
5239 ;; either it doesn't return a value in any branch...
5240 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5241 ;; or it returns a value (or is unreached) at every branch
5242 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5243 js2-END_RETURNS
5244 js2-END_YIELDS)))))
5245
5246 (defun js2-end-check-if (node)
5247 "Ensure that return usage in then/else blocks is consistent.
5248 If there is no else block, then the return statement can fall through.
5249 Returns logical OR of END_* flags"
5250 (let ((th (js2-if-node-then-part node))
5251 (el (js2-if-node-else-part node)))
5252 (if (null th)
5253 js2-END_UNREACHED
5254 (logior (js2-end-check th) (if el
5255 (js2-end-check el)
5256 js2-END_DROPS_OFF)))))
5257
5258 (defun js2-end-check-switch (node)
5259 "Consistency of return statements is checked between the case statements.
5260 If there is no default, then the switch can fall through. If there is a
5261 default, we check to see if all code paths in the default return or if
5262 there is a code path that can fall through.
5263 Returns logical OR of END_* flags."
5264 (let ((rv js2-END_UNREACHED)
5265 default-case)
5266 ;; examine the cases
5267 (catch 'break
5268 (dolist (c (js2-switch-node-cases node))
5269 (if (js2-case-node-expr c)
5270 (js2-set-flag rv (js2-end-check-block c))
5271 (setq default-case c)
5272 (throw 'break nil))))
5273 ;; we don't care how the cases drop into each other
5274 (js2-clear-flag rv js2-END_DROPS_OFF)
5275 ;; examine the default
5276 (js2-set-flag rv (if default-case
5277 (js2-end-check default-case)
5278 js2-END_DROPS_OFF))
5279 rv))
5280
5281 (defun js2-end-check-try (node)
5282 "If the block has a finally, return consistency is checked in the
5283 finally block. If all code paths in the finally return, then the
5284 returns in the try-catch blocks don't matter. If there is a code path
5285 that does not return or if there is no finally block, the returns
5286 of the try and catch blocks are checked for mismatch.
5287 Returns logical OR of END_* flags."
5288 (let ((finally (js2-try-node-finally-block node))
5289 rv)
5290 ;; check the finally if it exists
5291 (setq rv (if finally
5292 (js2-end-check (js2-finally-node-body finally))
5293 js2-END_DROPS_OFF))
5294 ;; If the finally block always returns, then none of the returns
5295 ;; in the try or catch blocks matter.
5296 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5297 (js2-clear-flag rv js2-END_DROPS_OFF)
5298 ;; examine the try block
5299 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5300 ;; check each catch block
5301 (dolist (cb (js2-try-node-catch-clauses node))
5302 (js2-set-flag rv (js2-end-check cb))))
5303 rv))
5304
5305 (defun js2-end-check-loop (node)
5306 "Return statement in the loop body must be consistent.
5307 The default assumption for any kind of a loop is that it will eventually
5308 terminate. The only exception is a loop with a constant true condition.
5309 Code that follows such a loop is examined only if one can determine
5310 statically that there is a break out of the loop.
5311
5312 for(... ; ... ; ...) {}
5313 for(... in ... ) {}
5314 while(...) { }
5315 do { } while(...)
5316
5317 Returns logical OR of END_* flags."
5318 (let ((rv (js2-end-check (js2-loop-node-body node)))
5319 (condition (cond
5320 ((js2-while-node-p node)
5321 (js2-while-node-condition node))
5322 ((js2-do-node-p node)
5323 (js2-do-node-condition node))
5324 ((js2-for-node-p node)
5325 (js2-for-node-condition node)))))
5326
5327 ;; check to see if the loop condition is always true
5328 (if (and condition
5329 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5330 (js2-clear-flag rv js2-END_DROPS_OFF))
5331
5332 ;; look for effect of breaks
5333 (js2-set-flag rv (js2-node-get-prop node
5334 'CONTROL_BLOCK_PROP
5335 js2-END_UNREACHED))
5336 rv))
5337
5338 (defun js2-end-check-block (node)
5339 "A general block of code is examined statement by statement.
5340 If any statement (even a compound one) returns in all branches, then
5341 subsequent statements are not examined.
5342 Returns logical OR of END_* flags."
5343 (let* ((rv js2-END_DROPS_OFF)
5344 (kids (js2-block-node-kids node))
5345 (n (car kids)))
5346 ;; Check each statement. If the statement can continue onto the next
5347 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5348 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5349 (js2-clear-flag rv js2-END_DROPS_OFF)
5350 (js2-set-flag rv (js2-end-check n))
5351 (setq kids (cdr kids)
5352 n (car kids)))
5353 rv))
5354
5355 (defun js2-end-check-label (node)
5356 "A labeled statement implies that there may be a break to the label.
5357 The function processes the labeled statement and then checks the
5358 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5359 particular label.
5360 Returns logical OR of END_* flags."
5361 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5362 (logior rv (js2-node-get-prop node
5363 'CONTROL_BLOCK_PROP
5364 js2-END_UNREACHED))))
5365
5366 (defun js2-end-check-break (node)
5367 "When a break is encountered annotate the statement being broken
5368 out of by setting its CONTROL_BLOCK_PROP property.
5369 Returns logical OR of END_* flags."
5370 (and (js2-break-node-target node)
5371 (js2-node-set-prop (js2-break-node-target node)
5372 'CONTROL_BLOCK_PROP
5373 js2-END_DROPS_OFF))
5374 js2-END_UNREACHED)
5375
5376 (defun js2-end-check (node)
5377 "Examine the body of a function, doing a basic reachability analysis.
5378 Returns a combination of flags END_* flags that indicate
5379 how the function execution can terminate. These constitute only the
5380 pessimistic set of termination conditions. It is possible that at
5381 runtime certain code paths will never be actually taken. Hence this
5382 analysis will flag errors in cases where there may not be errors.
5383 Returns logical OR of END_* flags"
5384 (let (kid)
5385 (cond
5386 ((js2-break-node-p node)
5387 (js2-end-check-break node))
5388 ((js2-expr-stmt-node-p node)
5389 (if (setq kid (js2-expr-stmt-node-expr node))
5390 (js2-end-check kid)
5391 js2-END_DROPS_OFF))
5392 ((or (js2-continue-node-p node)
5393 (js2-throw-node-p node))
5394 js2-END_UNREACHED)
5395 ((js2-return-node-p node)
5396 (if (setq kid (js2-return-node-retval node))
5397 js2-END_RETURNS_VALUE
5398 js2-END_RETURNS))
5399 ((js2-loop-node-p node)
5400 (js2-end-check-loop node))
5401 ((js2-switch-node-p node)
5402 (js2-end-check-switch node))
5403 ((js2-labeled-stmt-node-p node)
5404 (js2-end-check-label node))
5405 ((js2-if-node-p node)
5406 (js2-end-check-if node))
5407 ((js2-try-node-p node)
5408 (js2-end-check-try node))
5409 ((js2-block-node-p node)
5410 (if (null (js2-block-node-kids node))
5411 js2-END_DROPS_OFF
5412 (js2-end-check-block node)))
5413 ((js2-yield-node-p node)
5414 js2-END_YIELDS)
5415 (t
5416 js2-END_DROPS_OFF))))
5417
5418 (defun js2-always-defined-boolean-p (node)
5419 "Check if NODE always evaluates to true or false in boolean context.
5420 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5421 nor always false."
5422 (let ((tt (js2-node-type node))
5423 num)
5424 (cond
5425 ((or (= tt js2-FALSE) (= tt js2-NULL))
5426 'ALWAYS_FALSE)
5427 ((= tt js2-TRUE)
5428 'ALWAYS_TRUE)
5429 ((= tt js2-NUMBER)
5430 (setq num (js2-number-node-num-value node))
5431 (if (and (not (eq num 0.0e+NaN))
5432 (not (zerop num)))
5433 'ALWAYS_TRUE
5434 'ALWAYS_FALSE))
5435 (t
5436 nil))))
5437
5438 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5439 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5440
5441 (defvar js2-tokens nil
5442 "List of all defined token names.") ; initialized in `js2-token-names'
5443
5444 (defconst js2-token-names
5445 (let* ((names (make-vector js2-num-tokens -1))
5446 (case-fold-search nil) ; only match js2-UPPER_CASE
5447 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5448 (cl-loop for sym in syms
5449 for i from 0
5450 do
5451 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5452 (not (boundp sym)))
5453 (aset names (symbol-value sym) ; code, e.g. 152
5454 (downcase
5455 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5456 (push sym js2-tokens)))
5457 names)
5458 "Vector mapping int values to token string names, sans `js2-' prefix.")
5459
5460 (defun js2-tt-name (tok)
5461 "Return a string name for TOK, a token symbol or code.
5462 Signals an error if it's not a recognized token."
5463 (let ((code tok))
5464 (if (symbolp tok)
5465 (setq code (symbol-value tok)))
5466 (if (eq code -1)
5467 "ERROR"
5468 (if (and (numberp code)
5469 (not (cl-minusp code))
5470 (< code js2-num-tokens))
5471 (aref js2-token-names code)
5472 (error "Invalid token: %s" code)))))
5473
5474 (defsubst js2-tt-sym (tok)
5475 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5476 (intern (js2-tt-name tok)))
5477
5478 (defconst js2-token-codes
5479 (let ((table (make-hash-table :test 'eq :size 256)))
5480 (cl-loop for name across js2-token-names
5481 for sym = (intern (concat "js2-" (upcase name)))
5482 do
5483 (puthash sym (symbol-value sym) table))
5484 ;; clean up a few that are "wrong" in Rhino's token codes
5485 (puthash 'js2-DELETE js2-DELPROP table)
5486 table)
5487 "Hashtable mapping token type symbols to their bytecodes.")
5488
5489 (defsubst js2-tt-code (sym)
5490 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5491 (or (gethash sym js2-token-codes)
5492 (error "Invalid token symbol: %s " sym))) ; signal code bug
5493
5494 (defun js2-report-scan-error (msg &optional no-throw beg len)
5495 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5496 (js2-report-error msg nil
5497 (or beg (js2-current-token-beg))
5498 (or len (js2-current-token-len)))
5499 (unless no-throw
5500 (throw 'return js2-ERROR)))
5501
5502 (defun js2-set-string-from-buffer (token)
5503 "Set `string' and `end' slots for TOKEN, return the string."
5504 (setf (js2-token-end token) js2-ts-cursor
5505 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5506
5507 ;; TODO: could potentially avoid a lot of consing by allocating a
5508 ;; char buffer the way Rhino does.
5509 (defsubst js2-add-to-string (c)
5510 (push c js2-ts-string-buffer))
5511
5512 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5513 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5514 ;; any other character: when it's not part of the current token, we
5515 ;; unget it, allowing it to be read again by the following call.
5516 (defsubst js2-unget-char ()
5517 (cl-decf js2-ts-cursor))
5518
5519 ;; Rhino distinguishes \r and \n line endings. We don't need to
5520 ;; because we only scan from Emacs buffers, which always use \n.
5521 (defun js2-get-char ()
5522 "Read and return the next character from the input buffer.
5523 Increments `js2-ts-lineno' if the return value is a newline char.
5524 Updates `js2-ts-cursor' to the point after the returned char.
5525 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5526 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5527 (let (c)
5528 ;; check for end of buffer
5529 (if (>= js2-ts-cursor (point-max))
5530 (setq js2-ts-hit-eof t
5531 js2-ts-cursor (1+ js2-ts-cursor)
5532 c js2-EOF_CHAR) ; return value
5533 ;; otherwise read next char
5534 (setq c (char-before (cl-incf js2-ts-cursor)))
5535 ;; if we read a newline, update counters
5536 (if (= c ?\n)
5537 (setq js2-ts-line-start js2-ts-cursor
5538 js2-ts-lineno (1+ js2-ts-lineno)))
5539 ;; TODO: skip over format characters
5540 c)))
5541
5542 (defun js2-read-unicode-escape ()
5543 "Read a \\uNNNN sequence from the input.
5544 Assumes the ?\ and ?u have already been read.
5545 Returns the unicode character, or nil if it wasn't a valid character.
5546 Doesn't change the values of any scanner variables."
5547 ;; I really wish I knew a better way to do this, but I can't
5548 ;; find the Emacs function that takes a 16-bit int and converts
5549 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5550 ;; Have to first check that it's 4 hex characters or it may stop
5551 ;; the read early.
5552 (ignore-errors
5553 (let ((s (buffer-substring-no-properties js2-ts-cursor
5554 (+ 4 js2-ts-cursor))))
5555 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5556 (read (concat "?\\u" s))))))
5557
5558 (defun js2-match-char (test)
5559 "Consume and return next character if it matches TEST, a character.
5560 Returns nil and consumes nothing if TEST is not the next character."
5561 (let ((c (js2-get-char)))
5562 (if (eq c test)
5563 t
5564 (js2-unget-char)
5565 nil)))
5566
5567 (defun js2-peek-char ()
5568 (prog1
5569 (js2-get-char)
5570 (js2-unget-char)))
5571
5572 (defun js2-identifier-start-p (c)
5573 "Is C a valid start to an ES5 Identifier?
5574 See http://es5.github.io/#x7.6"
5575 (or
5576 (memq c '(?$ ?_))
5577 (memq (get-char-code-property c 'general-category)
5578 ;; Letters
5579 '(Lu Ll Lt Lm Lo Nl))))
5580
5581 (defun js2-identifier-part-p (c)
5582 "Is C a valid part of an ES5 Identifier?
5583 See http://es5.github.io/#x7.6"
5584 (or
5585 (memq c '(?$ ?_ ?\u200c ?\u200d))
5586 (memq (get-char-code-property c 'general-category)
5587 '(;; Letters
5588 Lu Ll Lt Lm Lo Nl
5589 ;; Combining Marks
5590 Mn Mc
5591 ;; Digits
5592 Nd
5593 ;; Connector Punctuation
5594 Pc))))
5595
5596 (defun js2-alpha-p (c)
5597 (cond ((and (<= ?A c) (<= c ?Z)) t)
5598 ((and (<= ?a c) (<= c ?z)) t)
5599 (t nil)))
5600
5601 (defsubst js2-digit-p (c)
5602 (and (<= ?0 c) (<= c ?9)))
5603
5604 (defun js2-js-space-p (c)
5605 (if (<= c 127)
5606 (memq c '(#x20 #x9 #xB #xC #xD))
5607 (or
5608 (eq c #xA0)
5609 ;; TODO: change this nil to check for Unicode space character
5610 nil)))
5611
5612 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5613
5614 (defun js2-skip-line ()
5615 "Skip to end of line."
5616 (while (not (memq (js2-get-char) js2-eol-chars)))
5617 (js2-unget-char)
5618 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5619
5620 (defun js2-init-scanner (&optional buf line)
5621 "Create token stream for BUF starting on LINE.
5622 BUF defaults to `current-buffer' and LINE defaults to 1.
5623
5624 A buffer can only have one scanner active at a time, which yields
5625 dramatically simpler code than using a defstruct. If you need to
5626 have simultaneous scanners in a buffer, copy the regions to scan
5627 into temp buffers."
5628 (with-current-buffer (or buf (current-buffer))
5629 (setq js2-ts-dirty-line nil
5630 js2-ts-hit-eof nil
5631 js2-ts-line-start 0
5632 js2-ts-lineno (or line 1)
5633 js2-ts-line-end-char -1
5634 js2-ts-cursor (point-min)
5635 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5636 js2-ti-tokens-cursor 0
5637 js2-ti-lookahead 0
5638 js2-ts-is-xml-attribute nil
5639 js2-ts-xml-is-tag-content nil
5640 js2-ts-xml-open-tags-count 0
5641 js2-ts-string-buffer nil)))
5642
5643 ;; This function uses the cached op, string and number fields in
5644 ;; TokenStream; if getToken has been called since the passed token
5645 ;; was scanned, the op or string printed may be incorrect.
5646 (defun js2-token-to-string (token)
5647 ;; Not sure where this function is used in Rhino. Not tested.
5648 (if (not js2-debug-print-trees)
5649 ""
5650 (let ((name (js2-tt-name token)))
5651 (cond
5652 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5653 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5654 (concat name " `" (js2-current-token-string) "'"))
5655 ((eq token js2-NUMBER)
5656 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5657 (t
5658 name)))))
5659
5660 (defconst js2-keywords
5661 '(break
5662 case catch class const continue
5663 debugger default delete do
5664 else extends export
5665 false finally for function
5666 if in instanceof import
5667 let
5668 new null
5669 return
5670 super switch
5671 this throw true try typeof
5672 var void
5673 while with
5674 yield))
5675
5676 ;; Token names aren't exactly the same as the keywords, unfortunately.
5677 ;; E.g. delete is js2-DELPROP.
5678 (defconst js2-kwd-tokens
5679 (let ((table (make-vector js2-num-tokens nil))
5680 (tokens
5681 (list js2-BREAK
5682 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5683 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5684 js2-ELSE js2-EXPORT
5685 js2-ELSE js2-EXTENDS js2-EXPORT
5686 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5687 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5688 js2-LET
5689 js2-NEW js2-NULL
5690 js2-RETURN
5691 js2-SUPER js2-SWITCH
5692 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5693 js2-VAR
5694 js2-WHILE js2-WITH
5695 js2-YIELD)))
5696 (dolist (i tokens)
5697 (aset table i 'font-lock-keyword-face))
5698 (aset table js2-STRING 'font-lock-string-face)
5699 (aset table js2-REGEXP 'font-lock-string-face)
5700 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5701 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5702 (aset table js2-COMMENT 'font-lock-comment-face)
5703 (aset table js2-THIS 'font-lock-builtin-face)
5704 (aset table js2-SUPER 'font-lock-builtin-face)
5705 (aset table js2-VOID 'font-lock-constant-face)
5706 (aset table js2-NULL 'font-lock-constant-face)
5707 (aset table js2-TRUE 'font-lock-constant-face)
5708 (aset table js2-FALSE 'font-lock-constant-face)
5709 (aset table js2-NOT 'font-lock-negation-char-face)
5710 table)
5711 "Vector whose values are non-nil for tokens that are keywords.
5712 The values are default faces to use for highlighting the keywords.")
5713
5714 ;; FIXME: Support strict mode-only future reserved words, after we know
5715 ;; which parts scopes are in strict mode, and which are not.
5716 (defconst js2-reserved-words '(class enum export extends import static super)
5717 "Future reserved keywords in ECMAScript 5.1.")
5718
5719 (defconst js2-keyword-names
5720 (let ((table (make-hash-table :test 'equal)))
5721 (cl-loop for k in js2-keywords
5722 do (puthash
5723 (symbol-name k) ; instanceof
5724 (intern (concat "js2-"
5725 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5726 table))
5727 table)
5728 "JavaScript keywords by name, mapped to their symbols.")
5729
5730 (defconst js2-reserved-word-names
5731 (let ((table (make-hash-table :test 'equal)))
5732 (cl-loop for k in js2-reserved-words
5733 do
5734 (puthash (symbol-name k) 'js2-RESERVED table))
5735 table)
5736 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5737
5738 (defun js2-collect-string (buf)
5739 "Convert BUF, a list of chars, to a string.
5740 Reverses BUF before converting."
5741 (if buf
5742 (apply #'string (nreverse buf))
5743 ""))
5744
5745 (defun js2-string-to-keyword (s)
5746 "Return token for S, a string, if S is a keyword or reserved word.
5747 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5748 (or (gethash s js2-keyword-names)
5749 (gethash s js2-reserved-word-names)))
5750
5751 (defsubst js2-ts-set-char-token-bounds (token)
5752 "Used when next token is one character."
5753 (setf (js2-token-beg token) (1- js2-ts-cursor)
5754 (js2-token-end token) js2-ts-cursor))
5755
5756 (defsubst js2-ts-return (token type)
5757 "Update the `end' and `type' slots of TOKEN,
5758 then throw `return' with value TYPE."
5759 (setf (js2-token-end token) js2-ts-cursor
5760 (js2-token-type token) type)
5761 (throw 'return type))
5762
5763 (defun js2-x-digit-to-int (c accumulator)
5764 "Build up a hex number.
5765 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5766 corresponding number. Otherwise return -1."
5767 (catch 'return
5768 (catch 'check
5769 ;; Use 0..9 < A..Z < a..z
5770 (cond
5771 ((<= c ?9)
5772 (cl-decf c ?0)
5773 (if (<= 0 c)
5774 (throw 'check nil)))
5775 ((<= c ?F)
5776 (when (<= ?A c)
5777 (cl-decf c (- ?A 10))
5778 (throw 'check nil)))
5779 ((<= c ?f)
5780 (when (<= ?a c)
5781 (cl-decf c (- ?a 10))
5782 (throw 'check nil))))
5783 (throw 'return -1))
5784 (logior c (lsh accumulator 4))))
5785
5786 (defun js2-get-token (&optional modifier)
5787 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5788 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5789 next saved token.
5790
5791 This function will not return a newline (js2-EOL) - instead, it
5792 gobbles newlines until it finds a non-newline token. Call
5793 `js2-peek-token-or-eol' when you care about newlines.
5794
5795 This function will also not return a js2-COMMENT. Instead, it
5796 records comments found in `js2-scanned-comments'. If the token
5797 returned by this function immediately follows a jsdoc comment,
5798 the token is flagged as such."
5799 (if (zerop js2-ti-lookahead)
5800 (js2-get-token-internal modifier)
5801 (cl-decf js2-ti-lookahead)
5802 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5803 (let ((tt (js2-current-token-type)))
5804 (cl-assert (not (= tt js2-EOL)))
5805 tt)))
5806
5807 (defun js2-unget-token ()
5808 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5809 (cl-incf js2-ti-lookahead)
5810 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5811
5812 (defun js2-get-token-internal (modifier)
5813 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5814 (tt (js2-token-type token))
5815 saw-eol
5816 face)
5817 ;; process comments
5818 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5819 (if (= tt js2-EOL)
5820 (setq saw-eol t)
5821 (setq saw-eol nil)
5822 (when js2-record-comments
5823 (js2-record-comment token)))
5824 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5825 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5826 tt (js2-token-type token)))
5827
5828 (when saw-eol
5829 (setf (js2-token-follows-eol-p token) t))
5830
5831 ;; perform lexical fontification as soon as token is scanned
5832 (when js2-parse-ide-mode
5833 (cond
5834 ((cl-minusp tt)
5835 (js2-record-face 'js2-error token))
5836 ((setq face (aref js2-kwd-tokens tt))
5837 (js2-record-face face token))
5838 ((and (= tt js2-NAME)
5839 (equal (js2-token-string token) "undefined"))
5840 (js2-record-face 'font-lock-constant-face token))))
5841 tt))
5842
5843 (defsubst js2-string-to-number (str base)
5844 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5845 (condition-case nil
5846 (string-to-number str base)
5847 (overflow-error -1)))
5848
5849 (defun js2-get-token-internal-1 (modifier)
5850 "Return next JavaScript token type, an int such as js2-RETURN.
5851 During operation, creates an instance of `js2-token' struct, sets
5852 its relevant fields and puts it into `js2-ti-tokens'."
5853 (let (identifier-start
5854 is-unicode-escape-start c
5855 contains-escape escape-val str result base
5856 look-for-slash continue tt
5857 (token (js2-new-token 0)))
5858 (setq
5859 tt
5860 (catch 'return
5861 (when (eq modifier 'TEMPLATE_TAIL)
5862 (setf (js2-token-beg token) (1- js2-ts-cursor))
5863 (throw 'return (js2-get-string-or-template-token ?` token)))
5864 (while t
5865 ;; Eat whitespace, possibly sensitive to newlines.
5866 (setq continue t)
5867 (while continue
5868 (setq c (js2-get-char))
5869 (cond
5870 ((eq c js2-EOF_CHAR)
5871 (js2-unget-char)
5872 (js2-ts-set-char-token-bounds token)
5873 (throw 'return js2-EOF))
5874 ((eq c ?\n)
5875 (js2-ts-set-char-token-bounds token)
5876 (setq js2-ts-dirty-line nil)
5877 (throw 'return js2-EOL))
5878 ((not (js2-js-space-p c))
5879 (if (/= c ?-) ; in case end of HTML comment
5880 (setq js2-ts-dirty-line t))
5881 (setq continue nil))))
5882 ;; Assume the token will be 1 char - fixed up below.
5883 (js2-ts-set-char-token-bounds token)
5884 (when (eq c ?@)
5885 (throw 'return js2-XMLATTR))
5886 ;; identifier/keyword/instanceof?
5887 ;; watch out for starting with a <backslash>
5888 (cond
5889 ((eq c ?\\)
5890 (setq c (js2-get-char))
5891 (if (eq c ?u)
5892 (setq identifier-start t
5893 is-unicode-escape-start t
5894 js2-ts-string-buffer nil)
5895 (setq identifier-start nil)
5896 (js2-unget-char)
5897 (setq c ?\\)))
5898 (t
5899 (when (setq identifier-start (js2-identifier-start-p c))
5900 (setq js2-ts-string-buffer nil)
5901 (js2-add-to-string c))))
5902 (when identifier-start
5903 (setq contains-escape is-unicode-escape-start)
5904 (catch 'break
5905 (while t
5906 (if is-unicode-escape-start
5907 ;; strictly speaking we should probably push-back
5908 ;; all the bad characters if the <backslash>uXXXX
5909 ;; sequence is malformed. But since there isn't a
5910 ;; correct context(is there?) for a bad Unicode
5911 ;; escape sequence in an identifier, we can report
5912 ;; an error here.
5913 (progn
5914 (setq escape-val 0)
5915 (dotimes (_ 4)
5916 (setq c (js2-get-char)
5917 escape-val (js2-x-digit-to-int c escape-val))
5918 ;; Next check takes care of c < 0 and bad escape
5919 (if (cl-minusp escape-val)
5920 (throw 'break nil)))
5921 (if (cl-minusp escape-val)
5922 (js2-report-scan-error "msg.invalid.escape" t))
5923 (js2-add-to-string escape-val)
5924 (setq is-unicode-escape-start nil))
5925 (setq c (js2-get-char))
5926 (cond
5927 ((eq c ?\\)
5928 (setq c (js2-get-char))
5929 (if (eq c ?u)
5930 (setq is-unicode-escape-start t
5931 contains-escape t)
5932 (js2-report-scan-error "msg.illegal.character" t)))
5933 (t
5934 (if (or (eq c js2-EOF_CHAR)
5935 (not (js2-identifier-part-p c)))
5936 (throw 'break nil))
5937 (js2-add-to-string c))))))
5938 (js2-unget-char)
5939 (setf str (js2-collect-string js2-ts-string-buffer)
5940 (js2-token-end token) js2-ts-cursor)
5941 ;; FIXME: Invalid in ES5 and ES6, see
5942 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5943 ;; Probably should just drop this conditional.
5944 (unless contains-escape
5945 ;; OPT we shouldn't have to make a string (object!) to
5946 ;; check if it's a keyword.
5947 ;; Return the corresponding token if it's a keyword
5948 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5949 (setq result (js2-string-to-keyword str)))
5950 (if (and (< js2-language-version 170)
5951 (memq result '(js2-LET js2-YIELD)))
5952 ;; LET and YIELD are tokens only in 1.7 and later
5953 (setq result 'js2-NAME))
5954 (when (eq result 'js2-RESERVED)
5955 (setf (js2-token-string token) str))
5956 (throw 'return (js2-tt-code result))))
5957 ;; If we want to intern these as Rhino does, just use (intern str)
5958 (setf (js2-token-string token) str)
5959 (throw 'return js2-NAME)) ; end identifier/kwd check
5960 ;; is it a number?
5961 (when (or (js2-digit-p c)
5962 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5963 (setq js2-ts-string-buffer nil
5964 base 10)
5965 (when (eq c ?0)
5966 (setq c (js2-get-char))
5967 (cond
5968 ((or (eq c ?x) (eq c ?X))
5969 (setq base 16)
5970 (setq c (js2-get-char)))
5971 ((and (or (eq c ?b) (eq c ?B))
5972 (>= js2-language-version 200))
5973 (setq base 2)
5974 (setq c (js2-get-char)))
5975 ((and (or (eq c ?o) (eq c ?O))
5976 (>= js2-language-version 200))
5977 (setq base 8)
5978 (setq c (js2-get-char)))
5979 ((js2-digit-p c)
5980 (setq base 'maybe-8))
5981 (t
5982 (js2-add-to-string ?0))))
5983 (cond
5984 ((eq base 16)
5985 (if (> 0 (js2-x-digit-to-int c 0))
5986 (js2-report-scan-error "msg.missing.hex.digits")
5987 (while (<= 0 (js2-x-digit-to-int c 0))
5988 (js2-add-to-string c)
5989 (setq c (js2-get-char)))))
5990 ((eq base 2)
5991 (if (not (memq c '(?0 ?1)))
5992 (js2-report-scan-error "msg.missing.binary.digits")
5993 (while (memq c '(?0 ?1))
5994 (js2-add-to-string c)
5995 (setq c (js2-get-char)))))
5996 ((eq base 8)
5997 (if (or (> ?0 c) (< ?7 c))
5998 (js2-report-scan-error "msg.missing.octal.digits")
5999 (while (and (<= ?0 c) (>= ?7 c))
6000 (js2-add-to-string c)
6001 (setq c (js2-get-char)))))
6002 (t
6003 (while (and (<= ?0 c) (<= c ?9))
6004 ;; We permit 08 and 09 as decimal numbers, which
6005 ;; makes our behavior a superset of the ECMA
6006 ;; numeric grammar. We might not always be so
6007 ;; permissive, so we warn about it.
6008 (when (and (eq base 'maybe-8) (>= c ?8))
6009 (js2-report-warning "msg.bad.octal.literal"
6010 (if (eq c ?8) "8" "9"))
6011 (setq base 10))
6012 (js2-add-to-string c)
6013 (setq c (js2-get-char)))
6014 (when (eq base 'maybe-8)
6015 (setq base 8))))
6016 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6017 (when (eq c ?.)
6018 (cl-loop do
6019 (js2-add-to-string c)
6020 (setq c (js2-get-char))
6021 while (js2-digit-p c)))
6022 (when (memq c '(?e ?E))
6023 (js2-add-to-string c)
6024 (setq c (js2-get-char))
6025 (when (memq c '(?+ ?-))
6026 (js2-add-to-string c)
6027 (setq c (js2-get-char)))
6028 (unless (js2-digit-p c)
6029 (js2-report-scan-error "msg.missing.exponent" t))
6030 (cl-loop do
6031 (js2-add-to-string c)
6032 (setq c (js2-get-char))
6033 while (js2-digit-p c))))
6034 (js2-unget-char)
6035 (let ((str (js2-set-string-from-buffer token)))
6036 (setf (js2-token-number token) (js2-string-to-number str base)
6037 (js2-token-number-base token) base))
6038 (throw 'return js2-NUMBER))
6039 ;; is it a string?
6040 (when (or (memq c '(?\" ?\'))
6041 (and (>= js2-language-version 200)
6042 (= c ?`)))
6043 (throw 'return
6044 (js2-get-string-or-template-token c token)))
6045 (js2-ts-return token
6046 (cl-case c
6047 (?\;
6048 (throw 'return js2-SEMI))
6049 (?\[
6050 (throw 'return js2-LB))
6051 (?\]
6052 (throw 'return js2-RB))
6053 (?{
6054 (throw 'return js2-LC))
6055 (?}
6056 (throw 'return js2-RC))
6057 (?\(
6058 (throw 'return js2-LP))
6059 (?\)
6060 (throw 'return js2-RP))
6061 (?,
6062 (throw 'return js2-COMMA))
6063 (??
6064 (throw 'return js2-HOOK))
6065 (?:
6066 (if (js2-match-char ?:)
6067 js2-COLONCOLON
6068 (throw 'return js2-COLON)))
6069 (?.
6070 (if (js2-match-char ?.)
6071 (if (js2-match-char ?.)
6072 js2-TRIPLEDOT js2-DOTDOT)
6073 (if (js2-match-char ?\()
6074 js2-DOTQUERY
6075 (throw 'return js2-DOT))))
6076 (?|
6077 (if (js2-match-char ?|)
6078 (throw 'return js2-OR)
6079 (if (js2-match-char ?=)
6080 js2-ASSIGN_BITOR
6081 (throw 'return js2-BITOR))))
6082 (?^
6083 (if (js2-match-char ?=)
6084 js2-ASSIGN_BITOR
6085 (throw 'return js2-BITXOR)))
6086 (?&
6087 (if (js2-match-char ?&)
6088 (throw 'return js2-AND)
6089 (if (js2-match-char ?=)
6090 js2-ASSIGN_BITAND
6091 (throw 'return js2-BITAND))))
6092 (?=
6093 (if (js2-match-char ?=)
6094 (if (js2-match-char ?=)
6095 js2-SHEQ
6096 (throw 'return js2-EQ))
6097 (if (js2-match-char ?>)
6098 (js2-ts-return token js2-ARROW)
6099 (throw 'return js2-ASSIGN))))
6100 (?!
6101 (if (js2-match-char ?=)
6102 (if (js2-match-char ?=)
6103 js2-SHNE
6104 js2-NE)
6105 (throw 'return js2-NOT)))
6106 (?<
6107 ;; NB:treat HTML begin-comment as comment-till-eol
6108 (when (js2-match-char ?!)
6109 (when (js2-match-char ?-)
6110 (when (js2-match-char ?-)
6111 (js2-skip-line)
6112 (setf (js2-token-comment-type (js2-current-token)) 'html)
6113 (throw 'return js2-COMMENT)))
6114 (js2-unget-char))
6115 (if (js2-match-char ?<)
6116 (if (js2-match-char ?=)
6117 js2-ASSIGN_LSH
6118 js2-LSH)
6119 (if (js2-match-char ?=)
6120 js2-LE
6121 (throw 'return js2-LT))))
6122 (?>
6123 (if (js2-match-char ?>)
6124 (if (js2-match-char ?>)
6125 (if (js2-match-char ?=)
6126 js2-ASSIGN_URSH
6127 js2-URSH)
6128 (if (js2-match-char ?=)
6129 js2-ASSIGN_RSH
6130 js2-RSH))
6131 (if (js2-match-char ?=)
6132 js2-GE
6133 (throw 'return js2-GT))))
6134 (?*
6135 (if (js2-match-char ?=)
6136 js2-ASSIGN_MUL
6137 (throw 'return js2-MUL)))
6138 (?/
6139 ;; is it a // comment?
6140 (when (js2-match-char ?/)
6141 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6142 (js2-skip-line)
6143 (setf (js2-token-comment-type token) 'line)
6144 ;; include newline so highlighting goes to end of
6145 ;; window, if there actually is a newline; if we
6146 ;; hit eof, then implicitly there isn't
6147 (unless js2-ts-hit-eof
6148 (cl-incf (js2-token-end token)))
6149 (throw 'return js2-COMMENT))
6150 ;; is it a /* comment?
6151 (when (js2-match-char ?*)
6152 (setf look-for-slash nil
6153 (js2-token-beg token) (- js2-ts-cursor 2)
6154 (js2-token-comment-type token)
6155 (if (js2-match-char ?*)
6156 (progn
6157 (setq look-for-slash t)
6158 'jsdoc)
6159 'block))
6160 (while t
6161 (setq c (js2-get-char))
6162 (cond
6163 ((eq c js2-EOF_CHAR)
6164 (setf (js2-token-end token) (1- js2-ts-cursor))
6165 (js2-report-error "msg.unterminated.comment")
6166 (throw 'return js2-COMMENT))
6167 ((eq c ?*)
6168 (setq look-for-slash t))
6169 ((eq c ?/)
6170 (if look-for-slash
6171 (js2-ts-return token js2-COMMENT)))
6172 (t
6173 (setf look-for-slash nil
6174 (js2-token-end token) js2-ts-cursor)))))
6175 (if (js2-match-char ?=)
6176 js2-ASSIGN_DIV
6177 (throw 'return js2-DIV)))
6178 (?#
6179 (when js2-skip-preprocessor-directives
6180 (js2-skip-line)
6181 (setf (js2-token-comment-type token) 'preprocessor
6182 (js2-token-end token) js2-ts-cursor)
6183 (throw 'return js2-COMMENT))
6184 (throw 'return js2-ERROR))
6185 (?%
6186 (if (js2-match-char ?=)
6187 js2-ASSIGN_MOD
6188 (throw 'return js2-MOD)))
6189 (?~
6190 (throw 'return js2-BITNOT))
6191 (?+
6192 (if (js2-match-char ?=)
6193 js2-ASSIGN_ADD
6194 (if (js2-match-char ?+)
6195 js2-INC
6196 (throw 'return js2-ADD))))
6197 (?-
6198 (cond
6199 ((js2-match-char ?=)
6200 (setq c js2-ASSIGN_SUB))
6201 ((js2-match-char ?-)
6202 (unless js2-ts-dirty-line
6203 ;; treat HTML end-comment after possible whitespace
6204 ;; after line start as comment-until-eol
6205 (when (js2-match-char ?>)
6206 (js2-skip-line)
6207 (setf (js2-token-comment-type (js2-current-token)) 'html)
6208 (throw 'return js2-COMMENT)))
6209 (setq c js2-DEC))
6210 (t
6211 (setq c js2-SUB)))
6212 (setq js2-ts-dirty-line t)
6213 c)
6214 (otherwise
6215 (js2-report-scan-error "msg.illegal.character")))))))
6216 (setf (js2-token-type token) tt)
6217 token))
6218
6219 (defun js2-get-string-or-template-token (quote-char token)
6220 ;; We attempt to accumulate a string the fast way, by
6221 ;; building it directly out of the reader. But if there
6222 ;; are any escaped characters in the string, we revert to
6223 ;; building it out of a string buffer.
6224 (let ((c (js2-get-char))
6225 js2-ts-string-buffer
6226 nc c1 val escape-val)
6227 (catch 'break
6228 (while (/= c quote-char)
6229 (catch 'continue
6230 (when (eq c js2-EOF_CHAR)
6231 (js2-unget-char)
6232 (js2-report-error "msg.unterminated.string.lit")
6233 (throw 'break nil))
6234 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6235 (js2-unget-char)
6236 (js2-report-error "msg.unterminated.string.lit")
6237 (throw 'break nil))
6238 (when (eq c ?\\)
6239 ;; We've hit an escaped character
6240 (setq c (js2-get-char))
6241 (cl-case c
6242 (?b (setq c ?\b))
6243 (?f (setq c ?\f))
6244 (?n (setq c ?\n))
6245 (?r (setq c ?\r))
6246 (?t (setq c ?\t))
6247 (?v (setq c ?\v))
6248 (?u
6249 (setq c1 (js2-read-unicode-escape))
6250 (if js2-parse-ide-mode
6251 (if c1
6252 (progn
6253 ;; just copy the string in IDE-mode
6254 (js2-add-to-string ?\\)
6255 (js2-add-to-string ?u)
6256 (dotimes (_ 3)
6257 (js2-add-to-string (js2-get-char)))
6258 (setq c (js2-get-char))) ; added at end of loop
6259 ;; flag it as an invalid escape
6260 (js2-report-warning "msg.invalid.escape"
6261 nil (- js2-ts-cursor 2) 6))
6262 ;; Get 4 hex digits; if the u escape is not
6263 ;; followed by 4 hex digits, use 'u' + the
6264 ;; literal character sequence that follows.
6265 (js2-add-to-string ?u)
6266 (setq escape-val 0)
6267 (dotimes (_ 4)
6268 (setq c (js2-get-char)
6269 escape-val (js2-x-digit-to-int c escape-val))
6270 (if (cl-minusp escape-val)
6271 (throw 'continue nil))
6272 (js2-add-to-string c))
6273 ;; prepare for replace of stored 'u' sequence by escape value
6274 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6275 c escape-val)))
6276 (?x
6277 ;; Get 2 hex digits, defaulting to 'x'+literal
6278 ;; sequence, as above.
6279 (setq c (js2-get-char)
6280 escape-val (js2-x-digit-to-int c 0))
6281 (if (cl-minusp escape-val)
6282 (progn
6283 (js2-add-to-string ?x)
6284 (throw 'continue nil))
6285 (setq c1 c
6286 c (js2-get-char)
6287 escape-val (js2-x-digit-to-int c escape-val))
6288 (if (cl-minusp escape-val)
6289 (progn
6290 (js2-add-to-string ?x)
6291 (js2-add-to-string c1)
6292 (throw 'continue nil))
6293 ;; got 2 hex digits
6294 (setq c escape-val))))
6295 (?\n
6296 ;; Remove line terminator after escape to follow
6297 ;; SpiderMonkey and C/C++
6298 (setq c (js2-get-char))
6299 (throw 'continue nil))
6300 (t
6301 (when (and (<= ?0 c) (< c ?8))
6302 (setq val (- c ?0)
6303 c (js2-get-char))
6304 (when (and (<= ?0 c) (< c ?8))
6305 (setq val (- (+ (* 8 val) c) ?0)
6306 c (js2-get-char))
6307 (when (and (<= ?0 c)
6308 (< c ?8)
6309 (< val #o37))
6310 ;; c is 3rd char of octal sequence only
6311 ;; if the resulting val <= 0377
6312 (setq val (- (+ (* 8 val) c) ?0)
6313 c (js2-get-char))))
6314 (js2-unget-char)
6315 (setq c val)))))
6316 (when (and (eq quote-char ?`) (eq c ?$))
6317 (when (eq (setq nc (js2-get-char)) ?\{)
6318 (throw 'break nil))
6319 (js2-unget-char))
6320 (js2-add-to-string c)
6321 (setq c (js2-get-char)))))
6322 (js2-set-string-from-buffer token)
6323 (if (not (eq quote-char ?`))
6324 js2-STRING
6325 (if (and (eq c ?$) (eq nc ?\{))
6326 js2-TEMPLATE_HEAD
6327 js2-NO_SUBS_TEMPLATE))))
6328
6329 (defun js2-read-regexp (start-tt)
6330 "Called by parser when it gets / or /= in literal context."
6331 (let (c err
6332 in-class ; inside a '[' .. ']' character-class
6333 flags
6334 (continue t)
6335 (token (js2-new-token 0)))
6336 (setq js2-ts-string-buffer nil)
6337 (if (eq start-tt js2-ASSIGN_DIV)
6338 ;; mis-scanned /=
6339 (js2-add-to-string ?=)
6340 (if (not (eq start-tt js2-DIV))
6341 (error "failed assertion")))
6342 (while (and (not err)
6343 (or (/= (setq c (js2-get-char)) ?/)
6344 in-class))
6345 (cond
6346 ((or (= c ?\n)
6347 (= c js2-EOF_CHAR))
6348 (setf (js2-token-end token) (1- js2-ts-cursor)
6349 err t
6350 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6351 (js2-report-error "msg.unterminated.re.lit"))
6352 (t (cond
6353 ((= c ?\\)
6354 (js2-add-to-string c)
6355 (setq c (js2-get-char)))
6356 ((= c ?\[)
6357 (setq in-class t))
6358 ((= c ?\])
6359 (setq in-class nil)))
6360 (js2-add-to-string c))))
6361 (unless err
6362 (while continue
6363 (cond
6364 ((js2-match-char ?g)
6365 (push ?g flags))
6366 ((js2-match-char ?i)
6367 (push ?i flags))
6368 ((js2-match-char ?m)
6369 (push ?m flags))
6370 ((and (js2-match-char ?u)
6371 (>= js2-language-version 200))
6372 (push ?u flags))
6373 ((and (js2-match-char ?y)
6374 (>= js2-language-version 200))
6375 (push ?y flags))
6376 (t
6377 (setq continue nil))))
6378 (if (js2-alpha-p (js2-peek-char))
6379 (js2-report-scan-error "msg.invalid.re.flag" t
6380 js2-ts-cursor 1))
6381 (js2-set-string-from-buffer token))
6382 (js2-collect-string flags)))
6383
6384 (defun js2-get-first-xml-token ()
6385 (setq js2-ts-xml-open-tags-count 0
6386 js2-ts-is-xml-attribute nil
6387 js2-ts-xml-is-tag-content nil)
6388 (js2-unget-char)
6389 (js2-get-next-xml-token))
6390
6391 (defun js2-xml-discard-string (token)
6392 "Throw away the string in progress and flag an XML parse error."
6393 (setf js2-ts-string-buffer nil
6394 (js2-token-string token) nil)
6395 (js2-report-scan-error "msg.XML.bad.form" t))
6396
6397 (defun js2-get-next-xml-token ()
6398 (setq js2-ts-string-buffer nil) ; for recording the XML
6399 (let ((token (js2-new-token 0))
6400 c result)
6401 (setq result
6402 (catch 'return
6403 (while t
6404 (setq c (js2-get-char))
6405 (cond
6406 ((= c js2-EOF_CHAR)
6407 (throw 'return js2-ERROR))
6408 (js2-ts-xml-is-tag-content
6409 (cl-case c
6410 (?>
6411 (js2-add-to-string c)
6412 (setq js2-ts-xml-is-tag-content nil
6413 js2-ts-is-xml-attribute nil))
6414 (?/
6415 (js2-add-to-string c)
6416 (when (eq ?> (js2-peek-char))
6417 (setq c (js2-get-char))
6418 (js2-add-to-string c)
6419 (setq js2-ts-xml-is-tag-content nil)
6420 (cl-decf js2-ts-xml-open-tags-count)))
6421 (?{
6422 (js2-unget-char)
6423 (js2-set-string-from-buffer token)
6424 (throw 'return js2-XML))
6425 ((?\' ?\")
6426 (js2-add-to-string c)
6427 (unless (js2-read-quoted-string c token)
6428 (throw 'return js2-ERROR)))
6429 (?=
6430 (js2-add-to-string c)
6431 (setq js2-ts-is-xml-attribute t))
6432 ((? ?\t ?\r ?\n)
6433 (js2-add-to-string c))
6434 (t
6435 (js2-add-to-string c)
6436 (setq js2-ts-is-xml-attribute nil)))
6437 (when (and (not js2-ts-xml-is-tag-content)
6438 (zerop js2-ts-xml-open-tags-count))
6439 (js2-set-string-from-buffer token)
6440 (throw 'return js2-XMLEND)))
6441 (t
6442 ;; else not tag content
6443 (cl-case c
6444 (?<
6445 (js2-add-to-string c)
6446 (setq c (js2-peek-char))
6447 (cl-case c
6448 (?!
6449 (setq c (js2-get-char)) ;; skip !
6450 (js2-add-to-string c)
6451 (setq c (js2-peek-char))
6452 (cl-case c
6453 (?-
6454 (setq c (js2-get-char)) ;; skip -
6455 (js2-add-to-string c)
6456 (if (eq c ?-)
6457 (progn
6458 (js2-add-to-string c)
6459 (unless (js2-read-xml-comment token)
6460 (throw 'return js2-ERROR)))
6461 (js2-xml-discard-string token)
6462 (throw 'return js2-ERROR)))
6463 (?\[
6464 (setq c (js2-get-char)) ;; skip [
6465 (js2-add-to-string c)
6466 (if (and (= (js2-get-char) ?C)
6467 (= (js2-get-char) ?D)
6468 (= (js2-get-char) ?A)
6469 (= (js2-get-char) ?T)
6470 (= (js2-get-char) ?A)
6471 (= (js2-get-char) ?\[))
6472 (progn
6473 (js2-add-to-string ?C)
6474 (js2-add-to-string ?D)
6475 (js2-add-to-string ?A)
6476 (js2-add-to-string ?T)
6477 (js2-add-to-string ?A)
6478 (js2-add-to-string ?\[)
6479 (unless (js2-read-cdata token)
6480 (throw 'return js2-ERROR)))
6481 (js2-xml-discard-string token)
6482 (throw 'return js2-ERROR)))
6483 (t
6484 (unless (js2-read-entity token)
6485 (throw 'return js2-ERROR))))
6486 ;; Allow bare CDATA section, e.g.:
6487 ;; let xml = <![CDATA[ foo bar baz ]]>;
6488 (when (zerop js2-ts-xml-open-tags-count)
6489 (throw 'return js2-XMLEND)))
6490 (??
6491 (setq c (js2-get-char)) ;; skip ?
6492 (js2-add-to-string c)
6493 (unless (js2-read-PI token)
6494 (throw 'return js2-ERROR)))
6495 (?/
6496 ;; end tag
6497 (setq c (js2-get-char)) ;; skip /
6498 (js2-add-to-string c)
6499 (when (zerop js2-ts-xml-open-tags-count)
6500 (js2-xml-discard-string token)
6501 (throw 'return js2-ERROR))
6502 (setq js2-ts-xml-is-tag-content t)
6503 (cl-decf js2-ts-xml-open-tags-count))
6504 (t
6505 ;; start tag
6506 (setq js2-ts-xml-is-tag-content t)
6507 (cl-incf js2-ts-xml-open-tags-count))))
6508 (?{
6509 (js2-unget-char)
6510 (js2-set-string-from-buffer token)
6511 (throw 'return js2-XML))
6512 (t
6513 (js2-add-to-string c))))))))
6514 (setf (js2-token-end token) js2-ts-cursor)
6515 (setf (js2-token-type token) result)
6516 result))
6517
6518 (defun js2-read-quoted-string (quote token)
6519 (let (c)
6520 (catch 'return
6521 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6522 (js2-add-to-string c)
6523 (if (eq c quote)
6524 (throw 'return t)))
6525 (js2-xml-discard-string token) ;; throw away string in progress
6526 nil)))
6527
6528 (defun js2-read-xml-comment (token)
6529 (let ((c (js2-get-char)))
6530 (catch 'return
6531 (while (/= c js2-EOF_CHAR)
6532 (catch 'continue
6533 (js2-add-to-string c)
6534 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6535 (setq c (js2-get-char))
6536 (js2-add-to-string c)
6537 (if (eq (js2-peek-char) ?>)
6538 (progn
6539 (setq c (js2-get-char)) ;; skip >
6540 (js2-add-to-string c)
6541 (throw 'return t))
6542 (throw 'continue nil)))
6543 (setq c (js2-get-char))))
6544 (js2-xml-discard-string token)
6545 nil)))
6546
6547 (defun js2-read-cdata (token)
6548 (let ((c (js2-get-char)))
6549 (catch 'return
6550 (while (/= c js2-EOF_CHAR)
6551 (catch 'continue
6552 (js2-add-to-string c)
6553 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6554 (setq c (js2-get-char))
6555 (js2-add-to-string c)
6556 (if (eq (js2-peek-char) ?>)
6557 (progn
6558 (setq c (js2-get-char)) ;; Skip >
6559 (js2-add-to-string c)
6560 (throw 'return t))
6561 (throw 'continue nil)))
6562 (setq c (js2-get-char))))
6563 (js2-xml-discard-string token)
6564 nil)))
6565
6566 (defun js2-read-entity (token)
6567 (let ((decl-tags 1)
6568 c)
6569 (catch 'return
6570 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6571 (js2-add-to-string c)
6572 (cl-case c
6573 (?<
6574 (cl-incf decl-tags))
6575 (?>
6576 (cl-decf decl-tags)
6577 (if (zerop decl-tags)
6578 (throw 'return t)))))
6579 (js2-xml-discard-string token)
6580 nil)))
6581
6582 (defun js2-read-PI (token)
6583 "Scan an XML processing instruction."
6584 (let (c)
6585 (catch 'return
6586 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6587 (js2-add-to-string c)
6588 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6589 (setq c (js2-get-char)) ;; Skip >
6590 (js2-add-to-string c)
6591 (throw 'return t)))
6592 (js2-xml-discard-string token)
6593 nil)))
6594
6595 ;;; Highlighting
6596
6597 (defun js2-set-face (beg end face &optional record)
6598 "Fontify a region. If RECORD is non-nil, record for later."
6599 (when (cl-plusp js2-highlight-level)
6600 (setq beg (min (point-max) beg)
6601 beg (max (point-min) beg)
6602 end (min (point-max) end)
6603 end (max (point-min) end))
6604 (if record
6605 (push (list beg end face) js2-mode-fontifications)
6606 (put-text-property beg end 'font-lock-face face))))
6607
6608 (defsubst js2-clear-face (beg end)
6609 (remove-text-properties beg end '(font-lock-face nil
6610 help-echo nil
6611 point-entered nil
6612 cursor-sensor-functions nil
6613 c-in-sws nil)))
6614
6615 (defconst js2-ecma-global-props
6616 (concat "^"
6617 (regexp-opt
6618 '("Infinity" "NaN" "undefined" "arguments") t)
6619 "$")
6620 "Value properties of the Ecma-262 Global Object.
6621 Shown at or above `js2-highlight-level' 2.")
6622
6623 ;; might want to add the name "arguments" to this list?
6624 (defconst js2-ecma-object-props
6625 (concat "^"
6626 (regexp-opt
6627 '("prototype" "__proto__" "__parent__") t)
6628 "$")
6629 "Value properties of the Ecma-262 Object constructor.
6630 Shown at or above `js2-highlight-level' 2.")
6631
6632 (defconst js2-ecma-global-funcs
6633 (concat
6634 "^"
6635 (regexp-opt
6636 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6637 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6638 "$")
6639 "Function properties of the Ecma-262 Global object.
6640 Shown at or above `js2-highlight-level' 2.")
6641
6642 (defconst js2-ecma-number-props
6643 (concat "^"
6644 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6645 "NEGATIVE_INFINITY"
6646 "POSITIVE_INFINITY") t)
6647 "$")
6648 "Properties of the Ecma-262 Number constructor.
6649 Shown at or above `js2-highlight-level' 2.")
6650
6651 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6652 "Properties of the Ecma-262 Date constructor.
6653 Shown at or above `js2-highlight-level' 2.")
6654
6655 (defconst js2-ecma-math-props
6656 (concat "^"
6657 (regexp-opt
6658 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6659 t)
6660 "$")
6661 "Properties of the Ecma-262 Math object.
6662 Shown at or above `js2-highlight-level' 2.")
6663
6664 (defconst js2-ecma-math-funcs
6665 (concat "^"
6666 (regexp-opt
6667 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6668 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6669 "$")
6670 "Function properties of the Ecma-262 Math object.
6671 Shown at or above `js2-highlight-level' 2.")
6672
6673 (defconst js2-ecma-function-props
6674 (concat
6675 "^"
6676 (regexp-opt
6677 '(;; properties of the Object prototype object
6678 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6679 "toLocaleString" "toString" "valueOf"
6680 ;; properties of the Function prototype object
6681 "apply" "call"
6682 ;; properties of the Array prototype object
6683 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6684 "splice" "unshift"
6685 ;; properties of the String prototype object
6686 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6687 "localeCompare" "match" "replace" "search" "split" "substring"
6688 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6689 "toUpperCase"
6690 ;; properties of the Number prototype object
6691 "toExponential" "toFixed" "toPrecision"
6692 ;; properties of the Date prototype object
6693 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6694 "getMinutes" "getMonth" "getSeconds" "getTime"
6695 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6696 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6697 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6698 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6699 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6700 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6701 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6702 "toTimeString" "toUTCString"
6703 ;; properties of the RegExp prototype object
6704 "exec" "test"
6705 ;; properties of the JSON prototype object
6706 "parse" "stringify"
6707 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6708 "toSource" "__defineGetter__" "__defineSetter__"
6709 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6710 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6711 t)
6712 "$")
6713 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6714 Shown at or above `js2-highlight-level' 3.")
6715
6716 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6717 (let ((target-name (and target
6718 (js2-name-node-p target)
6719 (js2-name-node-name target)))
6720 (prop-name (if prop (js2-name-node-name prop)))
6721 (level2 (>= js2-highlight-level 2))
6722 (level3 (>= js2-highlight-level 3)))
6723 (when level2
6724 (let ((face
6725 (if call-p
6726 (cond
6727 ((and target prop)
6728 (cond
6729 ((and level3 (string-match js2-ecma-function-props prop-name))
6730 'font-lock-builtin-face)
6731 ((and target-name prop)
6732 (cond
6733 ((string= target-name "Date")
6734 (if (string-match js2-ecma-date-props prop-name)
6735 'font-lock-builtin-face))
6736 ((string= target-name "Math")
6737 (if (string-match js2-ecma-math-funcs prop-name)
6738 'font-lock-builtin-face))))))
6739 (prop
6740 (if (string-match js2-ecma-global-funcs prop-name)
6741 'font-lock-builtin-face)))
6742 (cond
6743 ((and target prop)
6744 (cond
6745 ((string= target-name "Number")
6746 (if (string-match js2-ecma-number-props prop-name)
6747 'font-lock-constant-face))
6748 ((string= target-name "Math")
6749 (if (string-match js2-ecma-math-props prop-name)
6750 'font-lock-constant-face))))
6751 (prop
6752 (if (string-match js2-ecma-object-props prop-name)
6753 'font-lock-constant-face))))))
6754 (when face
6755 (let ((pos (+ (js2-node-pos parent) ; absolute
6756 (js2-node-pos prop)))) ; relative
6757 (js2-set-face pos
6758 (+ pos (js2-node-len prop))
6759 face 'record)))))))
6760
6761 (defun js2-parse-highlight-member-expr-node (node)
6762 "Perform syntax highlighting of EcmaScript built-in properties.
6763 The variable `js2-highlight-level' governs this highlighting."
6764 (let (face target prop name pos end parent call-p callee)
6765 (cond
6766 ;; case 1: simple name, e.g. foo
6767 ((js2-name-node-p node)
6768 (setq name (js2-name-node-name node))
6769 ;; possible for name to be nil in rare cases - saw it when
6770 ;; running js2-mode on an elisp buffer. Might as well try to
6771 ;; make it so js2-mode never barfs.
6772 (when name
6773 (setq face (if (string-match js2-ecma-global-props name)
6774 'font-lock-constant-face))
6775 (when face
6776 (setq pos (js2-node-pos node)
6777 end (+ pos (js2-node-len node)))
6778 (js2-set-face pos end face 'record))))
6779 ;; case 2: property access or function call
6780 ((or (js2-prop-get-node-p node)
6781 ;; highlight function call if expr is a prop-get node
6782 ;; or a plain name (i.e. unqualified function call)
6783 (and (setq call-p (js2-call-node-p node))
6784 (setq callee (js2-call-node-target node)) ; separate setq!
6785 (or (js2-prop-get-node-p callee)
6786 (js2-name-node-p callee))))
6787 (setq parent node
6788 node (if call-p callee node))
6789 (if (and call-p (js2-name-node-p callee))
6790 (setq prop callee)
6791 (setq target (js2-prop-get-node-left node)
6792 prop (js2-prop-get-node-right node)))
6793 (cond
6794 ((js2-name-node-p prop)
6795 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6796 (js2-parse-highlight-prop-get parent target prop call-p))
6797 ((js2-name-node-p target)
6798 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6799 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6800
6801 (defun js2-parse-highlight-member-expr-fn-name (expr)
6802 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6803 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6804 We currently only handle the case where the last component is a prop-get
6805 of a simple name. Called before EXPR has a parent node."
6806 (let (pos
6807 (name (and (js2-prop-get-node-p expr)
6808 (js2-prop-get-node-right expr))))
6809 (when (js2-name-node-p name)
6810 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6811 (js2-node-pos name)))
6812 (+ pos (js2-node-len name))
6813 'font-lock-function-name-face
6814 'record))))
6815
6816 ;; source: http://jsdoc.sourceforge.net/
6817 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6818 ;; allows type specifications, and needs work before entering the wild.
6819
6820 (defconst js2-jsdoc-param-tag-regexp
6821 (concat "^\\s-*\\*+\\s-*\\(@"
6822 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6823 "\\)"
6824 "\\s-*\\({[^}]+}\\)?" ; optional type
6825 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6826 "\\_>")
6827 "Matches jsdoc tags with optional type and optional param name.")
6828
6829 (defconst js2-jsdoc-typed-tag-regexp
6830 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6831 (regexp-opt
6832 '("enum"
6833 "extends"
6834 "field"
6835 "id"
6836 "implements"
6837 "lends"
6838 "mods"
6839 "requires"
6840 "return"
6841 "returns"
6842 "throw"
6843 "throws"))
6844 "\\)\\)\\s-*\\({[^}]+}\\)?")
6845 "Matches jsdoc tags with optional type.")
6846
6847 (defconst js2-jsdoc-arg-tag-regexp
6848 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6849 (regexp-opt
6850 '("alias"
6851 "augments"
6852 "borrows"
6853 "bug"
6854 "base"
6855 "config"
6856 "default"
6857 "define"
6858 "exception"
6859 "function"
6860 "member"
6861 "memberOf"
6862 "name"
6863 "namespace"
6864 "since"
6865 "suppress"
6866 "this"
6867 "throws"
6868 "type"
6869 "version"))
6870 "\\)\\)\\s-+\\([^ \t]+\\)")
6871 "Matches jsdoc tags with a single argument.")
6872
6873 (defconst js2-jsdoc-empty-tag-regexp
6874 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6875 (regexp-opt
6876 '("addon"
6877 "author"
6878 "class"
6879 "const"
6880 "constant"
6881 "constructor"
6882 "constructs"
6883 "deprecated"
6884 "desc"
6885 "description"
6886 "event"
6887 "example"
6888 "exec"
6889 "export"
6890 "fileoverview"
6891 "final"
6892 "function"
6893 "hidden"
6894 "ignore"
6895 "implicitCast"
6896 "inheritDoc"
6897 "inner"
6898 "interface"
6899 "license"
6900 "noalias"
6901 "noshadow"
6902 "notypecheck"
6903 "override"
6904 "owner"
6905 "preserve"
6906 "preserveTry"
6907 "private"
6908 "protected"
6909 "public"
6910 "static"
6911 "supported"
6912 ))
6913 "\\)\\)\\s-*")
6914 "Matches empty jsdoc tags.")
6915
6916 (defconst js2-jsdoc-link-tag-regexp
6917 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6918 "Matches a jsdoc link or code tag.")
6919
6920 (defconst js2-jsdoc-see-tag-regexp
6921 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6922 "Matches a jsdoc @see tag.")
6923
6924 (defconst js2-jsdoc-html-tag-regexp
6925 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6926 "Matches a simple (no attributes) html start- or end-tag.")
6927
6928 (defun js2-jsdoc-highlight-helper ()
6929 (js2-set-face (match-beginning 1)
6930 (match-end 1)
6931 'js2-jsdoc-tag)
6932 (if (match-beginning 2)
6933 (if (save-excursion
6934 (goto-char (match-beginning 2))
6935 (= (char-after) ?{))
6936 (js2-set-face (1+ (match-beginning 2))
6937 (1- (match-end 2))
6938 'js2-jsdoc-type)
6939 (js2-set-face (match-beginning 2)
6940 (match-end 2)
6941 'js2-jsdoc-value)))
6942 (if (match-beginning 3)
6943 (js2-set-face (match-beginning 3)
6944 (match-end 3)
6945 'js2-jsdoc-value)))
6946
6947 (defun js2-highlight-jsdoc (ast)
6948 "Highlight doc comment tags."
6949 (let ((comments (js2-ast-root-comments ast))
6950 beg end)
6951 (save-excursion
6952 (dolist (node comments)
6953 (when (eq (js2-comment-node-format node) 'jsdoc)
6954 (setq beg (js2-node-abs-pos node)
6955 end (+ beg (js2-node-len node)))
6956 (save-restriction
6957 (narrow-to-region beg end)
6958 (dolist (re (list js2-jsdoc-param-tag-regexp
6959 js2-jsdoc-typed-tag-regexp
6960 js2-jsdoc-arg-tag-regexp
6961 js2-jsdoc-link-tag-regexp
6962 js2-jsdoc-see-tag-regexp
6963 js2-jsdoc-empty-tag-regexp))
6964 (goto-char beg)
6965 (while (re-search-forward re nil t)
6966 (js2-jsdoc-highlight-helper)))
6967 ;; simple highlighting for html tags
6968 (goto-char beg)
6969 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6970 (js2-set-face (match-beginning 1)
6971 (match-end 1)
6972 'js2-jsdoc-html-tag-delimiter)
6973 (js2-set-face (match-beginning 2)
6974 (match-end 2)
6975 'js2-jsdoc-html-tag-name)
6976 (js2-set-face (match-beginning 3)
6977 (match-end 3)
6978 'js2-jsdoc-html-tag-delimiter))))))))
6979
6980 (defun js2-highlight-assign-targets (_node left right)
6981 "Highlight function properties and external variables."
6982 (let (leftpos name)
6983 ;; highlight vars and props assigned function values
6984 (when (or (js2-function-node-p right)
6985 (js2-class-node-p right))
6986 (cond
6987 ;; var foo = function() {...}
6988 ((js2-name-node-p left)
6989 (setq name left))
6990 ;; foo.bar.baz = function() {...}
6991 ((and (js2-prop-get-node-p left)
6992 (js2-name-node-p (js2-prop-get-node-right left)))
6993 (setq name (js2-prop-get-node-right left))))
6994 (when name
6995 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6996 (+ leftpos (js2-node-len name))
6997 'font-lock-function-name-face
6998 'record)))))
6999
7000 (defun js2-record-name-node (node)
7001 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7002 later. NODE must be a name node."
7003 (let ((leftpos (js2-node-abs-pos node)))
7004 (push (list node js2-current-scope
7005 leftpos
7006 (+ leftpos (js2-node-len node)))
7007 js2-recorded-identifiers)))
7008
7009 (defun js2-highlight-undeclared-vars ()
7010 "After entire parse is finished, look for undeclared variable references.
7011 We have to wait until entire buffer is parsed, since JavaScript permits var
7012 decls to occur after they're used.
7013
7014 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7015 it is considered declared."
7016 (let (name)
7017 (dolist (entry js2-recorded-identifiers)
7018 (cl-destructuring-bind (name-node scope pos end) entry
7019 (setq name (js2-name-node-name name-node))
7020 (unless (or (member name js2-global-externs)
7021 (member name js2-default-externs)
7022 (member name js2-additional-externs)
7023 (js2-get-defining-scope scope name pos))
7024 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7025 'js2-external-variable))))))
7026
7027 (defun js2--add-or-update-symbol (symbol inition used vars)
7028 "Add or update SYMBOL entry in VARS, an hash table.
7029 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7030 respectively meaning that SYMBOL is a mere declaration, an
7031 assignment or a function parameter; when USED is t, the symbol
7032 node is assumed to be an usage and thus added to the list stored
7033 in the cdr of the entry.
7034 "
7035 (let* ((nm (js2-name-node-name symbol))
7036 (es (js2-node-get-enclosing-scope symbol))
7037 (ds (js2-get-defining-scope es nm)))
7038 (when (and ds (not (equal nm "arguments")))
7039 (let* ((sym (js2-scope-get-symbol ds nm))
7040 (var (gethash sym vars))
7041 (err-var-p (js2-catch-node-p ds)))
7042 (unless inition
7043 (setq inition err-var-p))
7044 (if var
7045 (progn
7046 (when (and inition (not (equal (car var) ?P)))
7047 (setcar var inition))
7048 (when used
7049 (push symbol (cdr var))))
7050 ;; do not consider the declaration of catch parameter as an usage
7051 (when (and err-var-p used)
7052 (setq used nil))
7053 (puthash sym (cons inition (if used (list symbol))) vars))))))
7054
7055 (defun js2--classify-variables ()
7056 "Collect and classify variables declared or used within js2-mode-ast.
7057 Traverse the whole ast tree returning a summary of the variables
7058 usage as an hash-table, keyed by their corresponding symbol table
7059 entry.
7060 Each variable is described by a tuple where the car is a flag
7061 indicating whether the variable has been initialized and the cdr
7062 is a possibly empty list of name nodes where it is used. External
7063 symbols, i.e. those not present in the whole scopes hierarchy,
7064 are ignored."
7065 (let ((vars (make-hash-table :test #'eq :size 100)))
7066 (js2-visit-ast
7067 js2-mode-ast
7068 (lambda (node end-p)
7069 (when (null end-p)
7070 (cond
7071 ((js2-var-init-node-p node)
7072 ;; take note about possibly initialized declarations
7073 (let ((target (js2-var-init-node-target node))
7074 (initializer (js2-var-init-node-initializer node)))
7075 (when target
7076 (let* ((parent (js2-node-parent node))
7077 (grandparent (if parent (js2-node-parent parent)))
7078 (inited (not (null initializer))))
7079 (unless inited
7080 (setq inited
7081 (and grandparent
7082 (js2-for-in-node-p grandparent)
7083 (memq target
7084 (mapcar #'js2-var-init-node-target
7085 (js2-var-decl-node-kids
7086 (js2-for-in-node-iterator grandparent)))))))
7087 (js2--add-or-update-symbol target inited nil vars)))))
7088
7089 ((js2-assign-node-p node)
7090 ;; take note about assignments
7091 (let ((left (js2-assign-node-left node)))
7092 (when (js2-name-node-p left)
7093 (js2--add-or-update-symbol left t nil vars))))
7094
7095 ((js2-prop-get-node-p node)
7096 ;; handle x.y.z nodes, considering only x
7097 (let ((left (js2-prop-get-node-left node)))
7098 (when (js2-name-node-p left)
7099 (js2--add-or-update-symbol left nil t vars))))
7100
7101 ((js2-name-node-p node)
7102 ;; take note about used variables
7103 (let ((parent (js2-node-parent node)))
7104 (when parent
7105 (unless (or (and (js2-var-init-node-p parent) ; handled above
7106 (eq node (js2-var-init-node-target parent)))
7107 (and (js2-assign-node-p parent)
7108 (eq node (js2-assign-node-left parent)))
7109 (js2-prop-get-node-p parent))
7110 (let ((used t) inited)
7111 (cond
7112 ((and (js2-function-node-p parent)
7113 (js2-wrapper-function-p parent))
7114 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7115
7116 ((js2-for-in-node-p parent)
7117 (if (eq node (js2-for-in-node-iterator parent))
7118 (setq inited t used nil)))
7119
7120 ((js2-function-node-p parent)
7121 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7122 used nil)))
7123
7124 (unless used
7125 (let ((grandparent (js2-node-parent parent)))
7126 (when grandparent
7127 (setq used (js2-return-node-p grandparent)))))
7128
7129 (js2--add-or-update-symbol node inited used vars))))))))
7130 t))
7131 vars))
7132
7133 (defun js2--get-name-node (node)
7134 (cond
7135 ((js2-name-node-p node) node)
7136 ((js2-function-node-p node)
7137 (js2-function-node-name node))
7138 ((js2-class-node-p node)
7139 (js2-class-node-name node))
7140 ((js2-comp-loop-node-p node)
7141 (js2-comp-loop-node-iterator node))
7142 (t node)))
7143
7144 (defun js2--highlight-unused-variable (symbol info)
7145 (let ((name (js2-symbol-name symbol))
7146 (inited (car info))
7147 (refs (cdr info))
7148 pos len)
7149 (unless (and inited refs)
7150 (if refs
7151 (dolist (ref refs)
7152 (setq pos (js2-node-abs-pos ref))
7153 (setq len (js2-name-node-len ref))
7154 (js2-report-warning "msg.uninitialized.variable" name pos len
7155 'js2-warning))
7156 (when (or js2-warn-about-unused-function-arguments
7157 (not (eq inited ?P)))
7158 (let* ((symn (js2-symbol-ast-node symbol))
7159 (namen (js2--get-name-node symn)))
7160 (unless (js2-node-top-level-decl-p namen)
7161 (setq pos (js2-node-abs-pos namen))
7162 (setq len (js2-name-node-len namen))
7163 (js2-report-warning "msg.unused.variable" name pos len
7164 'js2-warning))))))))
7165
7166 (defun js2-highlight-unused-variables ()
7167 "Highlight unused variables."
7168 (let ((vars (js2--classify-variables)))
7169 (maphash #'js2--highlight-unused-variable vars)))
7170
7171 ;;;###autoload
7172 (define-minor-mode js2-highlight-unused-variables-mode
7173 "Toggle highlight of unused variables."
7174 :lighter ""
7175 (if js2-highlight-unused-variables-mode
7176 (add-hook 'js2-post-parse-callbacks
7177 #'js2-highlight-unused-variables nil t)
7178 (remove-hook 'js2-post-parse-callbacks
7179 #'js2-highlight-unused-variables t)))
7180
7181 (defun js2-set-default-externs ()
7182 "Set the value of `js2-default-externs' based on the various
7183 `js2-include-?-externs' variables."
7184 (setq js2-default-externs
7185 (append js2-ecma-262-externs
7186 (if js2-include-browser-externs js2-browser-externs)
7187 (if (and js2-include-browser-externs
7188 (>= js2-language-version 200)) js2-harmony-externs)
7189 (if js2-include-rhino-externs js2-rhino-externs)
7190 (if js2-include-node-externs js2-node-externs)
7191 (if (or js2-include-browser-externs js2-include-node-externs)
7192 js2-typed-array-externs))))
7193
7194 (defun js2-apply-jslint-globals ()
7195 (setq js2-additional-externs
7196 (nconc (js2-get-jslint-globals)
7197 js2-additional-externs)))
7198
7199 (defun js2-get-jslint-globals ()
7200 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7201 when (and (eq 'block (js2-comment-node-format node))
7202 (save-excursion
7203 (goto-char (js2-node-abs-pos node))
7204 (looking-at "/\\*global ")))
7205 append (js2-get-jslint-globals-in
7206 (match-end 0)
7207 (js2-node-abs-end node))))
7208
7209 (defun js2-get-jslint-globals-in (beg end)
7210 (let (res)
7211 (save-excursion
7212 (goto-char beg)
7213 (while (re-search-forward js2-mode-identifier-re end t)
7214 (let ((match (match-string 0)))
7215 (unless (member match '("true" "false"))
7216 (push match res)))))
7217 (nreverse res)))
7218
7219 ;;; IMenu support
7220
7221 ;; We currently only support imenu, but eventually should support speedbar and
7222 ;; possibly other browsing mechanisms.
7223
7224 ;; The basic strategy is to identify function assignment targets of the form
7225 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7226 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7227 ;; for imenu after parsing is finished.
7228
7229 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7230 ;; JavaScript, and the general problem is undecidable. However, several forms
7231 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7232 ;; include:
7233
7234 ;; function foo() -- function declaration
7235 ;; foo = function() -- function expression assigned to variable
7236 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7237 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7238 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7239 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7240 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7241 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7242 ;; function foo() {function bar() {...}} -- nested function
7243 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7244
7245 ;; This list boils down to a few forms that can be combined recursively.
7246 ;; Top-level named function declarations include both the left-hand (name)
7247 ;; and the right-hand (function value) expressions needed to produce an imenu
7248 ;; entry. The other "right-hand" forms we need to look for are:
7249 ;; - functions declared as props/getters/setters in object literals
7250 ;; - nested named function declarations
7251 ;; The "left-hand" expressions that functions can be assigned to include:
7252 ;; - local/global variables
7253 ;; - nested property-get expressions like a.b.c.d
7254 ;; - element gets like foo[10] or foo['bar'] where the index
7255 ;; expression can be trivially converted to a property name. They
7256 ;; effectively then become property gets.
7257
7258 ;; All the different definition types are canonicalized into the form
7259 ;; foo.bar.baz = position-of-function-keyword
7260
7261 ;; We need to build a trie-like structure for imenu. As an example,
7262 ;; consider the following JavaScript code:
7263
7264 ;; a = function() {...} // function at position 5
7265 ;; b = function() {...} // function at position 25
7266 ;; foo = function() {...} // function at position 100
7267 ;; foo.bar = function() {...} // function at position 200
7268 ;; foo.bar.baz = function() {...} // function at position 300
7269 ;; foo.bar.zab = function() {...} // function at position 400
7270
7271 ;; During parsing we accumulate an entry for each definition in
7272 ;; the variable `js2-imenu-recorder', like so:
7273
7274 ;; '((fn a 5)
7275 ;; (fn b 25)
7276 ;; (fn foo 100)
7277 ;; (fn foo bar 200)
7278 ;; (fn foo bar baz 300)
7279 ;; (fn foo bar zab 400))
7280
7281 ;; Where 'fn' is the respective function node.
7282 ;; After parsing these entries are merged into this alist-trie:
7283
7284 ;; '((a . 1)
7285 ;; (b . 2)
7286 ;; (foo (<definition> . 3)
7287 ;; (bar (<definition> . 6)
7288 ;; (baz . 100)
7289 ;; (zab . 200))))
7290
7291 ;; Note the wacky need for a <definition> name. The token can be anything
7292 ;; that isn't a valid JavaScript identifier, because you might make foo
7293 ;; a function and then start setting properties on it that are also functions.
7294
7295 (defun js2-prop-node-name (node)
7296 "Return the name of a node that may be a property-get/property-name.
7297 If NODE is not a valid name-node, string-node or integral number-node,
7298 returns nil. Otherwise returns the string name/value of the node."
7299 (cond
7300 ((js2-name-node-p node)
7301 (js2-name-node-name node))
7302 ((js2-string-node-p node)
7303 (js2-string-node-value node))
7304 ((and (js2-number-node-p node)
7305 (string-match "^[0-9]+$" (js2-number-node-value node)))
7306 (js2-number-node-value node))
7307 ((eq (js2-node-type node) js2-THIS)
7308 "this")
7309 ((eq (js2-node-type node) js2-SUPER)
7310 "super")))
7311
7312 (defun js2-node-qname-component (node)
7313 "Return the name of this node, if it contributes to a qname.
7314 Returns nil if the node doesn't contribute."
7315 (copy-sequence
7316 (or (js2-prop-node-name node)
7317 (if (and (js2-function-node-p node)
7318 (js2-function-node-name node))
7319 (js2-name-node-name (js2-function-node-name node))))))
7320
7321 (defun js2-record-imenu-entry (fn-node qname pos)
7322 "Add an entry to `js2-imenu-recorder'.
7323 FN-NODE should be the current item's function node.
7324
7325 Associate FN-NODE with its QNAME for later lookup.
7326 This is used in postprocessing the chain list. For each chain, we find
7327 the parent function, look up its qname, then prepend a copy of it to the chain."
7328 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7329 (unless js2-imenu-function-map
7330 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7331 (puthash fn-node qname js2-imenu-function-map))
7332
7333 (defun js2-record-imenu-functions (node &optional var)
7334 "Record function definitions for imenu.
7335 NODE is a function node or an object literal.
7336 VAR, if non-nil, is the expression that NODE is being assigned to.
7337 When passed arguments of wrong type, does nothing."
7338 (when js2-parse-ide-mode
7339 (let ((fun-p (js2-function-node-p node))
7340 qname fname-node)
7341 (cond
7342 ;; non-anonymous function declaration?
7343 ((and fun-p
7344 (not var)
7345 (setq fname-node (js2-function-node-name node)))
7346 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7347 ;; for remaining forms, compute left-side tree branch first
7348 ((and var (setq qname (js2-compute-nested-prop-get var)))
7349 (cond
7350 ;; foo.bar.baz = function
7351 (fun-p
7352 (js2-record-imenu-entry node qname (js2-node-pos node)))
7353 ;; foo.bar.baz = object-literal
7354 ;; look for nested functions: {a: {b: function() {...} }}
7355 ((js2-object-node-p node)
7356 ;; Node position here is still absolute, since the parser
7357 ;; passes the assignment target and value expressions
7358 ;; to us before they are added as children of the assignment node.
7359 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7360
7361 (defun js2-compute-nested-prop-get (node)
7362 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7363 component nodes as a list. Otherwise return nil. Element-gets are treated
7364 as property-gets if the index expression is a string, or a positive integer."
7365 (let (left right head)
7366 (cond
7367 ((or (js2-name-node-p node)
7368 (js2-this-or-super-node-p node))
7369 (list node))
7370 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7371 ((js2-prop-get-node-p node) ; foo.bar
7372 (setq left (js2-prop-get-node-left node)
7373 right (js2-prop-get-node-right node))
7374 (if (setq head (js2-compute-nested-prop-get left))
7375 (nconc head (list right))))
7376 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7377 (setq left (js2-elem-get-node-target node)
7378 right (js2-elem-get-node-element node))
7379 (if (or (js2-string-node-p right) ; ['bar']
7380 (and (js2-number-node-p right) ; [10]
7381 (string-match "^[0-9]+$"
7382 (js2-number-node-value right))))
7383 (if (setq head (js2-compute-nested-prop-get left))
7384 (nconc head (list right))))))))
7385
7386 (defun js2-record-object-literal (node qname pos)
7387 "Recursively process an object literal looking for functions.
7388 NODE is an object literal that is the right-hand child of an assignment
7389 expression. QNAME is a list of nodes representing the assignment target,
7390 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7391 POS is the absolute position of the node.
7392 We do a depth-first traversal of NODE. For any functions we find,
7393 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7394 (let (right)
7395 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7396 (let ((left (js2-infix-node-left e))
7397 ;; Element positions are relative to the parent position.
7398 (pos (+ pos (js2-node-pos e))))
7399 (cond
7400 ;; foo: function() {...}
7401 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7402 (when (js2-prop-node-name left)
7403 ;; As a policy decision, we record the position of the property,
7404 ;; not the position of the `function' keyword, since the property
7405 ;; is effectively the name of the function.
7406 (js2-record-imenu-entry right (append qname (list left)) pos)))
7407 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7408 ((js2-object-node-p right)
7409 (js2-record-object-literal right
7410 (append qname (list (js2-infix-node-left e)))
7411 (+ pos (js2-node-pos right)))))))))
7412
7413 (defun js2-node-top-level-decl-p (node)
7414 "Return t if NODE's name is defined in the top-level scope.
7415 Also returns t if NODE's name is not defined in any scope, since it implies
7416 that it's an external variable, which must also be in the top-level scope."
7417 (let* ((name (js2-prop-node-name node))
7418 (this-scope (js2-node-get-enclosing-scope node))
7419 defining-scope)
7420 (cond
7421 ((js2-this-or-super-node-p node)
7422 nil)
7423 ((null this-scope)
7424 t)
7425 ((setq defining-scope (js2-get-defining-scope this-scope name))
7426 (js2-ast-root-p defining-scope))
7427 (t t))))
7428
7429 (defun js2-wrapper-function-p (node)
7430 "Return t if NODE is a function expression that's immediately invoked.
7431 NODE must be `js2-function-node'."
7432 (let ((parent (js2-node-parent node)))
7433 (or
7434 ;; function(){...}();
7435 (and (js2-call-node-p parent)
7436 (eq node (js2-call-node-target parent)))
7437 (and (js2-paren-node-p parent)
7438 ;; (function(){...})();
7439 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7440 ;; (function(){...}).call(this);
7441 (and (js2-prop-get-node-p parent)
7442 (member (js2-name-node-name (js2-prop-get-node-right parent))
7443 '("call" "apply"))
7444 (js2-call-node-p (js2-node-parent parent))))))))
7445
7446 (defun js2-browse-postprocess-chains ()
7447 "Modify function-declaration name chains after parsing finishes.
7448 Some of the information is only available after the parse tree is complete.
7449 For instance, processing a nested scope requires a parent function node."
7450 (let (result fn parent-qname p elem)
7451 (dolist (entry js2-imenu-recorder)
7452 ;; function node goes first
7453 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7454 ;; Examine head's defining scope:
7455 ;; Pre-processed chain, or top-level/external, keep as-is.
7456 (if (or (stringp head) (js2-node-top-level-decl-p head))
7457 (push chain result)
7458 (when (js2-this-or-super-node-p head)
7459 (setq chain (cdr chain))) ; discard this-node
7460 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7461 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7462 (when (eq parent-qname 'not-found)
7463 ;; anonymous function expressions are not recorded
7464 ;; during the parse, so we need to handle this case here
7465 (setq parent-qname
7466 (if (js2-wrapper-function-p fn)
7467 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7468 (if (js2-ast-root-p grandparent)
7469 nil
7470 (gethash grandparent js2-imenu-function-map 'skip)))
7471 'skip))
7472 (puthash fn parent-qname js2-imenu-function-map))
7473 (if (eq parent-qname 'skip)
7474 ;; We don't show it, let's record that fact.
7475 (remhash current-fn js2-imenu-function-map)
7476 ;; Prepend parent fn qname to this chain.
7477 (let ((qname (append parent-qname chain)))
7478 (puthash current-fn (butlast qname) js2-imenu-function-map)
7479 (push qname result)))))))
7480 ;; Collect chains obtained by third-party code.
7481 (let (js2-imenu-recorder)
7482 (run-hooks 'js2-build-imenu-callbacks)
7483 (dolist (entry js2-imenu-recorder)
7484 (push (cdr entry) result)))
7485 ;; Finally replace each node in each chain with its name.
7486 (dolist (chain result)
7487 (setq p chain)
7488 (while p
7489 (if (js2-node-p (setq elem (car p)))
7490 (setcar p (js2-node-qname-component elem)))
7491 (setq p (cdr p))))
7492 result))
7493
7494 ;; Merge name chains into a trie-like tree structure of nested lists.
7495 ;; To simplify construction of the trie, we first build it out using the rule
7496 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7497 ;; [key, num-or-list]. The second element can be a number; if so, this key
7498 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7499 ;; associated with the key at this level.) Otherwise the second element is
7500 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7501 ;; a simple recursive formulation.
7502 ;;
7503 ;; js2-mode is building the data structure for imenu. The imenu documentation
7504 ;; claims that it's the structure above, but in practice it wants the children
7505 ;; at the same list level as the key for that level, which is how I've drawn
7506 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7507 ;; list wrapper around the children at each level.
7508 ;;
7509 ;; A completed nested imenu-alist entry looks like this:
7510 ;; '(("foo"
7511 ;; ("<definition>" . 7)
7512 ;; ("bar"
7513 ;; ("a" . 40)
7514 ;; ("b" . 60))))
7515 ;;
7516 ;; In particular, the documentation for `imenu--index-alist' says that
7517 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7518 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7519
7520 (defun js2-treeify (lst)
7521 "Convert (a b c d) to (a ((b ((c d)))))."
7522 (if (null (cddr lst)) ; list length <= 2
7523 lst
7524 (list (car lst) (list (js2-treeify (cdr lst))))))
7525
7526 (defun js2-build-alist-trie (chains trie)
7527 "Merge declaration name chains into a trie-like alist structure for imenu.
7528 CHAINS is the qname chain list produced during parsing. TRIE is a
7529 list of elements built up so far."
7530 (let (head tail pos branch kids)
7531 (dolist (chain chains)
7532 (setq head (car chain)
7533 tail (cdr chain)
7534 pos (if (numberp (car tail)) (car tail))
7535 branch (js2-find-if (lambda (n)
7536 (string= (car n) head))
7537 trie)
7538 kids (cl-second branch))
7539 (cond
7540 ;; case 1: this key isn't in the trie yet
7541 ((null branch)
7542 (if trie
7543 (setcdr (last trie) (list (js2-treeify chain)))
7544 (setq trie (list (js2-treeify chain)))))
7545 ;; case 2: key is present with a single number entry: replace w/ list
7546 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7547 ;; ("<definition>" 20)))
7548 ((numberp kids)
7549 (setcar (cdr branch)
7550 (list (list "<definition-1>" kids)
7551 (if pos
7552 (list "<definition-2>" pos)
7553 (js2-treeify tail)))))
7554 ;; case 3: key is there (with kids), and we're a number entry
7555 (pos
7556 (setcdr (last kids)
7557 (list
7558 (list (format "<definition-%d>"
7559 (1+ (cl-loop for kid in kids
7560 count (eq ?< (aref (car kid) 0)))))
7561 pos))))
7562 ;; case 4: key is there with kids, need to merge in our chain
7563 (t
7564 (js2-build-alist-trie (list tail) kids))))
7565 trie))
7566
7567 (defun js2-flatten-trie (trie)
7568 "Convert TRIE to imenu-format.
7569 Recurses through nodes, and for each one whose second element is a list,
7570 appends the list's flattened elements to the current element. Also
7571 changes the tails into conses. For instance, this pre-flattened trie
7572
7573 '(a ((b 20)
7574 (c ((d 30)
7575 (e 40)))))
7576
7577 becomes
7578
7579 '(a (b . 20)
7580 (c (d . 30)
7581 (e . 40)))
7582
7583 Note that the root of the trie has no key, just a list of chains.
7584 This is also true for the value of any key with multiple children,
7585 e.g. key 'c' in the example above."
7586 (cond
7587 ((listp (car trie))
7588 (mapcar #'js2-flatten-trie trie))
7589 (t
7590 (if (numberp (cl-second trie))
7591 (cons (car trie) (cl-second trie))
7592 ;; else pop list and append its kids
7593 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7594
7595 (defun js2-build-imenu-index ()
7596 "Turn `js2-imenu-recorder' into an imenu data structure."
7597 (when (eq js2-imenu-recorder 'empty)
7598 (setq js2-imenu-recorder nil))
7599 (let* ((chains (js2-browse-postprocess-chains))
7600 (result (js2-build-alist-trie chains nil)))
7601 (js2-flatten-trie result)))
7602
7603 (defun js2-test-print-chains (chains)
7604 "Print a list of qname chains.
7605 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7606 i.e. one or more nodes, and an integer position as the list tail."
7607 (mapconcat (lambda (chain)
7608 (concat "("
7609 (mapconcat (lambda (elem)
7610 (if (js2-node-p elem)
7611 (or (js2-node-qname-component elem)
7612 "nil")
7613 (number-to-string elem)))
7614 chain
7615 " ")
7616 ")"))
7617 chains
7618 "\n"))
7619
7620 ;;; Parser
7621
7622 (defconst js2-version "1.8.5"
7623 "Version of JavaScript supported.")
7624
7625 (defun js2-record-face (face &optional token)
7626 "Record a style run of FACE for TOKEN or the current token."
7627 (unless token (setq token (js2-current-token)))
7628 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7629
7630 (defsubst js2-node-end (n)
7631 "Computes the absolute end of node N.
7632 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7633 is only true until the node is added to its parent; i.e., while parsing."
7634 (+ (js2-node-pos n)
7635 (js2-node-len n)))
7636
7637 (defun js2-record-comment (token)
7638 "Record a comment in `js2-scanned-comments'."
7639 (let ((ct (js2-token-comment-type token))
7640 (beg (js2-token-beg token))
7641 (end (js2-token-end token)))
7642 (push (make-js2-comment-node :len (- end beg)
7643 :format ct)
7644 js2-scanned-comments)
7645 (when js2-parse-ide-mode
7646 (js2-record-face (if (eq ct 'jsdoc)
7647 'font-lock-doc-face
7648 'font-lock-comment-face)
7649 token)
7650 (when (memq ct '(html preprocessor))
7651 ;; Tell cc-engine the bounds of the comment.
7652 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7653
7654 (defun js2-peek-token ()
7655 "Return the next token type without consuming it.
7656 If `js2-ti-lookahead' is positive, return the type of next token
7657 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7658 (if (not (zerop js2-ti-lookahead))
7659 (js2-token-type
7660 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7661 (let ((tt (js2-get-token-internal nil)))
7662 (js2-unget-token)
7663 tt)))
7664
7665 (defalias 'js2-next-token 'js2-get-token)
7666
7667 (defun js2-match-token (match &optional dont-unget)
7668 "Get next token and return t if it matches MATCH, a bytecode.
7669 Returns nil and consumes nothing if MATCH is not the next token."
7670 (if (/= (js2-get-token) match)
7671 (ignore (unless dont-unget (js2-unget-token)))
7672 t))
7673
7674 (defun js2-match-contextual-kwd (name)
7675 "Consume and return t if next token is `js2-NAME', and its
7676 string is NAME. Returns nil and keeps current token otherwise."
7677 (if (or (/= (js2-get-token) js2-NAME)
7678 (not (string= (js2-current-token-string) name)))
7679 (progn
7680 (js2-unget-token)
7681 nil)
7682 (js2-record-face 'font-lock-keyword-face)
7683 t))
7684
7685 (defun js2-get-prop-name-token ()
7686 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7687
7688 (defun js2-match-prop-name ()
7689 "Consume token and return t if next token is a valid property name.
7690 If `js2-language-version' is >= 180, a keyword or reserved word
7691 is considered valid name as well."
7692 (if (eq js2-NAME (js2-get-prop-name-token))
7693 t
7694 (js2-unget-token)
7695 nil))
7696
7697 (defun js2-must-match-prop-name (msg-id &optional pos len)
7698 (if (js2-match-prop-name)
7699 t
7700 (js2-report-error msg-id nil pos len)
7701 nil))
7702
7703 (defun js2-peek-token-or-eol ()
7704 "Return js2-EOL if the next token immediately follows a newline.
7705 Else returns the next token. Used in situations where we don't
7706 consider certain token types valid if they are preceded by a newline.
7707 One example is the postfix ++ or -- operator, which has to be on the
7708 same line as its operand."
7709 (let ((tt (js2-get-token))
7710 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7711 (js2-unget-token)
7712 (if follows-eol
7713 js2-EOL
7714 tt)))
7715
7716 (defun js2-must-match (token msg-id &optional pos len)
7717 "Match next token to token code TOKEN, or record a syntax error.
7718 MSG-ID is the error message to report if the match fails.
7719 Returns t on match, nil if no match."
7720 (if (js2-match-token token t)
7721 t
7722 (js2-report-error msg-id nil pos len)
7723 (js2-unget-token)
7724 nil))
7725
7726 (defun js2-must-match-name (msg-id)
7727 (if (js2-match-token js2-NAME t)
7728 t
7729 (if (eq (js2-current-token-type) js2-RESERVED)
7730 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7731 (js2-report-error msg-id)
7732 (js2-unget-token))
7733 nil))
7734
7735 (defsubst js2-inside-function ()
7736 (cl-plusp js2-nesting-of-function))
7737
7738 (defun js2-set-requires-activation ()
7739 (if (js2-function-node-p js2-current-script-or-fn)
7740 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7741
7742 (defun js2-check-activation-name (name _token)
7743 (when (js2-inside-function)
7744 ;; skip language-version 1.2 check from Rhino
7745 (if (or (string= "arguments" name)
7746 (and js2-compiler-activation-names ; only used in codegen
7747 (gethash name js2-compiler-activation-names)))
7748 (js2-set-requires-activation))))
7749
7750 (defun js2-set-is-generator ()
7751 (let ((fn-node js2-current-script-or-fn))
7752 (when (and (js2-function-node-p fn-node)
7753 (not (js2-function-node-generator-type fn-node)))
7754 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7755
7756 (defun js2-must-have-xml ()
7757 (unless js2-compiler-xml-available
7758 (js2-report-error "msg.XML.not.available")))
7759
7760 (defun js2-push-scope (scope)
7761 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7762 (cl-assert (js2-scope-p scope))
7763 (cl-assert (null (js2-scope-parent-scope scope)))
7764 (cl-assert (not (eq js2-current-scope scope)))
7765 (setf (js2-scope-parent-scope scope) js2-current-scope
7766 js2-current-scope scope))
7767
7768 (defsubst js2-pop-scope ()
7769 (setq js2-current-scope
7770 (js2-scope-parent-scope js2-current-scope)))
7771
7772 (defun js2-enter-loop (loop-node)
7773 (push loop-node js2-loop-set)
7774 (push loop-node js2-loop-and-switch-set)
7775 (js2-push-scope loop-node)
7776 ;; Tell the current labeled statement (if any) its statement,
7777 ;; and set the jump target of the first label to the loop.
7778 ;; These are used in `js2-parse-continue' to verify that the
7779 ;; continue target is an actual labeled loop. (And for codegen.)
7780 (when js2-labeled-stmt
7781 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7782 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7783 js2-labeled-stmt))) loop-node)))
7784
7785 (defun js2-exit-loop ()
7786 (pop js2-loop-set)
7787 (pop js2-loop-and-switch-set)
7788 (js2-pop-scope))
7789
7790 (defsubst js2-enter-switch (switch-node)
7791 (push switch-node js2-loop-and-switch-set))
7792
7793 (defsubst js2-exit-switch ()
7794 (pop js2-loop-and-switch-set))
7795
7796 (defsubst js2-get-directive (node)
7797 "Return NODE's value if it is a directive, nil otherwise.
7798
7799 A directive is an otherwise-meaningless expression statement
7800 consisting of a string literal, such as \"use strict\"."
7801 (and (js2-expr-stmt-node-p node)
7802 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7803 (js2-string-node-value node)))
7804
7805 (defun js2-parse (&optional buf cb)
7806 "Tell the js2 parser to parse a region of JavaScript.
7807
7808 BUF is a buffer or buffer name containing the code to parse.
7809 Call `narrow-to-region' first to parse only part of the buffer.
7810
7811 The returned AST root node is given some additional properties:
7812 `node-count' - total number of nodes in the AST
7813 `buffer' - BUF. The buffer it refers to may change or be killed,
7814 so the value is not necessarily reliable.
7815
7816 An optional callback CB can be specified to report parsing
7817 progress. If `(functionp CB)' returns t, it will be called with
7818 the current line number once before parsing begins, then again
7819 each time the lexer reaches a new line number.
7820
7821 CB can also be a list of the form `(symbol cb ...)' to specify
7822 multiple callbacks with different criteria. Each symbol is a
7823 criterion keyword, and the following element is the callback to
7824 call
7825
7826 :line - called whenever the line number changes
7827 :token - called for each new token consumed
7828
7829 The list of criteria could be extended to include entering or
7830 leaving a statement, an expression, or a function definition."
7831 (if (and cb (not (functionp cb)))
7832 (error "criteria callbacks not yet implemented"))
7833 (let ((inhibit-point-motion-hooks t)
7834 (js2-compiler-xml-available (>= js2-language-version 160))
7835 ;; This is a recursive-descent parser, so give it a big stack.
7836 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7837 (max-specpdl-size (max max-specpdl-size 3000))
7838 (case-fold-search nil)
7839 ast)
7840 (with-current-buffer (or buf (current-buffer))
7841 (setq js2-scanned-comments nil
7842 js2-parsed-errors nil
7843 js2-parsed-warnings nil
7844 js2-imenu-recorder nil
7845 js2-imenu-function-map nil
7846 js2-label-set nil)
7847 (js2-init-scanner)
7848 (setq ast (js2-do-parse))
7849 (unless js2-ts-hit-eof
7850 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7851 (setf (js2-ast-root-errors ast) js2-parsed-errors
7852 (js2-ast-root-warnings ast) js2-parsed-warnings)
7853 ;; if we didn't find any declarations, put a dummy in this list so we
7854 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7855 (unless js2-imenu-recorder
7856 (setq js2-imenu-recorder 'empty))
7857 (run-hooks 'js2-parse-finished-hook)
7858 ast)))
7859
7860 ;; Corresponds to Rhino's Parser.parse() method.
7861 (defun js2-do-parse ()
7862 "Parse current buffer starting from current point.
7863 Scanner should be initialized."
7864 (let ((pos js2-ts-cursor)
7865 (end js2-ts-cursor) ; in case file is empty
7866 root n tt
7867 (in-directive-prologue t)
7868 (js2-in-use-strict-directive js2-in-use-strict-directive)
7869 directive)
7870 ;; initialize buffer-local parsing vars
7871 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7872 js2-current-script-or-fn root
7873 js2-current-scope root
7874 js2-nesting-of-function 0
7875 js2-labeled-stmt nil
7876 js2-recorded-identifiers nil ; for js2-highlight
7877 js2-in-use-strict-directive nil)
7878 (while (/= (setq tt (js2-get-token)) js2-EOF)
7879 (if (= tt js2-FUNCTION)
7880 (progn
7881 (setq n (if js2-called-by-compile-function
7882 (js2-parse-function-expr)
7883 (js2-parse-function-stmt))))
7884 ;; not a function - parse a statement
7885 (js2-unget-token)
7886 (setq n (js2-parse-statement))
7887 (when in-directive-prologue
7888 (setq directive (js2-get-directive n))
7889 (cond
7890 ((null directive)
7891 (setq in-directive-prologue nil))
7892 ((string= directive "use strict")
7893 (setq js2-in-use-strict-directive t)))))
7894 ;; add function or statement to script
7895 (setq end (js2-node-end n))
7896 (js2-block-node-push root n))
7897 ;; add comments to root in lexical order
7898 (when js2-scanned-comments
7899 ;; if we find a comment beyond end of normal kids, use its end
7900 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7901 (dolist (comment js2-scanned-comments)
7902 (push comment (js2-ast-root-comments root))
7903 (js2-node-add-children root comment)))
7904 (setf (js2-node-len root) (- end pos))
7905 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7906 ;; Give extensions a chance to muck with things before highlighting starts.
7907 (let ((js2-additional-externs js2-additional-externs))
7908 (save-excursion
7909 (run-hooks 'js2-post-parse-callbacks))
7910 (js2-highlight-undeclared-vars))
7911 root))
7912
7913 (defun js2-parse-function-closure-body (fn-node)
7914 "Parse a JavaScript 1.8 function closure body."
7915 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7916 (if js2-ts-hit-eof
7917 (js2-report-error "msg.no.brace.body" nil
7918 (js2-node-pos fn-node)
7919 (- js2-ts-cursor (js2-node-pos fn-node)))
7920 (js2-node-add-children fn-node
7921 (setf (js2-function-node-body fn-node)
7922 (js2-parse-expr t))))))
7923
7924 (defun js2-parse-function-body (fn-node)
7925 (js2-must-match js2-LC "msg.no.brace.body"
7926 (js2-node-pos fn-node)
7927 (- js2-ts-cursor (js2-node-pos fn-node)))
7928 (let ((pos (js2-current-token-beg)) ; LC position
7929 (pn (make-js2-block-node)) ; starts at LC position
7930 tt
7931 end
7932 not-in-directive-prologue
7933 node
7934 directive)
7935 (cl-incf js2-nesting-of-function)
7936 (unwind-protect
7937 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7938 (= tt js2-EOF)
7939 (= tt js2-RC)))
7940 (js2-block-node-push
7941 pn
7942 (if (/= tt js2-FUNCTION)
7943 (if not-in-directive-prologue
7944 (js2-parse-statement)
7945 (setq node (js2-parse-statement)
7946 directive (js2-get-directive node))
7947 (cond
7948 ((null directive)
7949 (setq not-in-directive-prologue t))
7950 ((string= directive "use strict")
7951 ;; Back up and reparse the function, because new rules apply
7952 ;; to the function name and parameters.
7953 (when (not js2-in-use-strict-directive)
7954 (setq js2-in-use-strict-directive t)
7955 (throw 'reparse t))))
7956 node)
7957 (js2-get-token)
7958 (js2-parse-function-stmt))))
7959 (cl-decf js2-nesting-of-function))
7960 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7961 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7962 (setq end (js2-current-token-end)))
7963 (setf (js2-node-pos pn) pos
7964 (js2-node-len pn) (- end pos))
7965 (setf (js2-function-node-body fn-node) pn)
7966 (js2-node-add-children fn-node pn)
7967 pn))
7968
7969 (defun js2-define-destruct-symbols-internal
7970 (node decl-type face &optional ignore-not-in-block name-nodes)
7971 "Internal version of `js2-define-destruct-symbols'. The only
7972 difference is that NAME-NODES is passed down recursively."
7973 (cond
7974 ((js2-name-node-p node)
7975 (let (leftpos)
7976 (js2-define-symbol decl-type (js2-name-node-name node)
7977 node ignore-not-in-block)
7978 (when face
7979 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7980 (+ leftpos (js2-node-len node))
7981 face 'record))
7982 (setq name-nodes (append name-nodes (list node)))))
7983 ((js2-object-node-p node)
7984 (dolist (elem (js2-object-node-elems node))
7985 (when (js2-object-prop-node-p elem)
7986 (setq name-nodes
7987 (append name-nodes
7988 (js2-define-destruct-symbols-internal
7989 ;; In abbreviated destructuring {a, b}, right == left.
7990 (js2-object-prop-node-right elem)
7991 decl-type face ignore-not-in-block name-nodes))))))
7992 ((js2-array-node-p node)
7993 (dolist (elem (js2-array-node-elems node))
7994 (when elem
7995 (setq name-nodes
7996 (append name-nodes
7997 (js2-define-destruct-symbols-internal
7998 elem decl-type face ignore-not-in-block name-nodes))))))
7999 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8000 (js2-node-len node))))
8001 name-nodes)
8002
8003 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8004 "Declare and fontify destructuring parameters inside NODE.
8005 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8006
8007 Return a list of `js2-name-node' nodes representing the symbols
8008 declared; probably to check them for errors."
8009 (js2-define-destruct-symbols-internal node decl-type face ignore-not-in-block))
8010
8011 (defvar js2-illegal-strict-identifiers
8012 '("eval" "arguments")
8013 "Identifiers not allowed as variables in strict mode.")
8014
8015 (defun js2-check-strict-identifier (name-node)
8016 "Check that NAME-NODE makes a legal strict mode identifier."
8017 (when js2-in-use-strict-directive
8018 (let ((param-name (js2-name-node-name name-node)))
8019 (when (member param-name js2-illegal-strict-identifiers)
8020 (js2-report-error "msg.bad.id.strict" param-name
8021 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8022
8023 (defun js2-check-strict-function-params (preceding-params params)
8024 "Given PRECEDING-PARAMS in a function's parameter list, check
8025 for strict mode errors caused by PARAMS."
8026 (when js2-in-use-strict-directive
8027 (dolist (param params)
8028 (let ((param-name (js2-name-node-name param)))
8029 (js2-check-strict-identifier param)
8030 (when (cl-some (lambda (param)
8031 (string= (js2-name-node-name param) param-name))
8032 preceding-params)
8033 (js2-report-error "msg.dup.param.strict" param-name
8034 (js2-node-abs-pos param) (js2-node-len param)))))))
8035
8036 (defun js2-parse-function-params (function-type fn-node pos)
8037 "Parse the parameters of a function of FUNCTION-TYPE
8038 represented by FN-NODE at POS."
8039 (if (js2-match-token js2-RP)
8040 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8041 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8042 (eq (js2-current-token-type) js2-NAME)))
8043 params param
8044 param-name-nodes new-param-name-nodes
8045 rest-param-at)
8046 (when paren-free-arrow
8047 (js2-unget-token))
8048 (cl-loop for tt = (js2-peek-token)
8049 do
8050 (cond
8051 ;; destructuring param
8052 ((and (not paren-free-arrow)
8053 (or (= tt js2-LB) (= tt js2-LC)))
8054 (js2-get-token)
8055 (setq param (js2-parse-destruct-primary-expr)
8056 new-param-name-nodes (js2-define-destruct-symbols
8057 param js2-LP 'js2-function-param))
8058 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8059 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8060 (push param params))
8061 ;; variable name
8062 (t
8063 (when (and (>= js2-language-version 200)
8064 (not paren-free-arrow)
8065 (js2-match-token js2-TRIPLEDOT)
8066 (not rest-param-at))
8067 ;; to report errors if there are more parameters
8068 (setq rest-param-at (length params)))
8069 (js2-must-match-name "msg.no.parm")
8070 (js2-record-face 'js2-function-param)
8071 (setq param (js2-create-name-node))
8072 (js2-define-symbol js2-LP (js2-current-token-string) param)
8073 (js2-check-strict-function-params param-name-nodes (list param))
8074 (setq param-name-nodes (append param-name-nodes (list param)))
8075 ;; default parameter value
8076 (when (and (>= js2-language-version 200)
8077 (js2-match-token js2-ASSIGN))
8078 (cl-assert (not paren-free-arrow))
8079 (let* ((pos (js2-node-pos param))
8080 (tt (js2-current-token-type))
8081 (op-pos (- (js2-current-token-beg) pos))
8082 (left param)
8083 (right (js2-parse-assign-expr))
8084 (len (- (js2-node-end right) pos)))
8085 (setq param (make-js2-assign-node
8086 :type tt :pos pos :len len :op-pos op-pos
8087 :left left :right right))
8088 (js2-node-add-children param left right)))
8089 (push param params)))
8090 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8091 (js2-report-error "msg.param.after.rest" nil
8092 (js2-node-pos param) (js2-node-len param)))
8093 while
8094 (js2-match-token js2-COMMA))
8095 (when (and (not paren-free-arrow)
8096 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8097 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8098 (when rest-param-at
8099 (setf (js2-function-node-rest-p fn-node) t))
8100 (dolist (p params)
8101 (js2-node-add-children fn-node p)
8102 (push p (js2-function-node-params fn-node))))))
8103
8104 (defun js2-check-inconsistent-return-warning (fn-node name)
8105 "Possibly show inconsistent-return warning.
8106 Last token scanned is the close-curly for the function body."
8107 (when (and js2-mode-show-strict-warnings
8108 js2-strict-inconsistent-return-warning
8109 (not (js2-has-consistent-return-usage
8110 (js2-function-node-body fn-node))))
8111 ;; Have it extend from close-curly to bol or beginning of block.
8112 (let ((pos (save-excursion
8113 (goto-char (js2-current-token-end))
8114 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8115 (point-at-bol))))
8116 (end (js2-current-token-end)))
8117 (if (cl-plusp (js2-name-node-length name))
8118 (js2-add-strict-warning "msg.no.return.value"
8119 (js2-name-node-name name) pos end)
8120 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8121
8122 (defun js2-parse-function-stmt ()
8123 (let ((pos (js2-current-token-beg))
8124 (star-p (js2-match-token js2-MUL)))
8125 (js2-must-match-name "msg.unnamed.function.stmt")
8126 (let ((name (js2-create-name-node t))
8127 pn member-expr)
8128 (cond
8129 ((js2-match-token js2-LP)
8130 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8131 (js2-allow-member-expr-as-function-name
8132 (setq member-expr (js2-parse-member-expr-tail nil name))
8133 (js2-parse-highlight-member-expr-fn-name member-expr)
8134 (js2-must-match js2-LP "msg.no.paren.parms")
8135 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8136 (js2-function-node-member-expr pn) member-expr)
8137 pn)
8138 (t
8139 (js2-report-error "msg.no.paren.parms")
8140 (make-js2-error-node))))))
8141
8142 (defun js2-parse-function-expr ()
8143 (let ((pos (js2-current-token-beg))
8144 (star-p (js2-match-token js2-MUL))
8145 name)
8146 (when (js2-match-token js2-NAME)
8147 (setq name (js2-create-name-node t)))
8148 (js2-must-match js2-LP "msg.no.paren.parms")
8149 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8150
8151 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8152 (let (fn-node lp)
8153 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8154 (setq lp (js2-current-token-beg)))
8155 (setf fn-node (make-js2-function-node :pos pos
8156 :name name
8157 :form function-type
8158 :lp (if lp (- lp pos))
8159 :generator-type (and star-p 'STAR)))
8160 (when name
8161 (js2-set-face (js2-node-pos name) (js2-node-end name)
8162 'font-lock-function-name-face 'record)
8163 (when (and (eq function-type 'FUNCTION_STATEMENT)
8164 (cl-plusp (js2-name-node-length name)))
8165 ;; Function statements define a symbol in the enclosing scope
8166 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8167 (when js2-in-use-strict-directive
8168 (js2-check-strict-identifier name)))
8169 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8170 ;; 1. Nested functions are not affected by the dynamic scope flag
8171 ;; as dynamic scope is already a parent of their scope.
8172 ;; 2. Functions defined under the with statement also immune to
8173 ;; this setup, in which case dynamic scope is ignored in favor
8174 ;; of the with object.
8175 (setf (js2-function-node-ignore-dynamic fn-node) t))
8176 ;; dynamically bind all the per-function variables
8177 (let ((js2-current-script-or-fn fn-node)
8178 (js2-current-scope fn-node)
8179 (js2-nesting-of-with 0)
8180 (js2-end-flags 0)
8181 js2-label-set
8182 js2-loop-set
8183 js2-loop-and-switch-set)
8184 (js2-parse-function-params function-type fn-node pos)
8185 (when (eq function-type 'FUNCTION_ARROW)
8186 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8187 (if (and (>= js2-language-version 180)
8188 (/= (js2-peek-token) js2-LC))
8189 (js2-parse-function-closure-body fn-node)
8190 (js2-parse-function-body fn-node))
8191 (js2-check-inconsistent-return-warning fn-node name)
8192
8193 (when name
8194 (js2-node-add-children fn-node name)
8195 ;; Function expressions define a name only in the body of the
8196 ;; function, and only if not hidden by a parameter name
8197 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8198 (null (js2-scope-get-symbol js2-current-scope
8199 (js2-name-node-name name))))
8200 (js2-define-symbol js2-FUNCTION
8201 (js2-name-node-name name)
8202 fn-node))
8203 (when (eq function-type 'FUNCTION_STATEMENT)
8204 (js2-record-imenu-functions fn-node))))
8205
8206 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8207 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8208 ;; We wait until after parsing the function to set its parent scope,
8209 ;; since `js2-define-symbol' needs the defining-scope check to stop
8210 ;; at the function boundary when checking for redeclarations.
8211 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8212 fn-node))
8213
8214 (defun js2-parse-function (function-type pos star-p &optional name)
8215 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8216 beginning of the first token (function keyword, unless it's an
8217 arrow function), NAME is js2-name-node."
8218 (let ((continue t)
8219 ts-state
8220 fn-node
8221 ;; Preserve strict state outside this function.
8222 (js2-in-use-strict-directive js2-in-use-strict-directive))
8223 ;; Parse multiple times if a new strict mode directive is discovered in the
8224 ;; function body, as new rules will be retroactively applied to the legality
8225 ;; of function names and parameters.
8226 (while continue
8227 (setq ts-state (make-js2-ts-state))
8228 (setq continue (catch 'reparse
8229 (setq fn-node (js2-parse-function-internal
8230 function-type pos star-p name))
8231 ;; Don't continue.
8232 nil))
8233 (when continue
8234 (js2-ts-seek ts-state)))
8235 fn-node))
8236
8237 (defun js2-parse-statements (&optional parent)
8238 "Parse a statement list. Last token consumed must be js2-LC.
8239
8240 PARENT can be a `js2-block-node', in which case the statements are
8241 appended to PARENT. Otherwise a new `js2-block-node' is created
8242 and returned.
8243
8244 This function does not match the closing js2-RC: the caller
8245 matches the RC so it can provide a suitable error message if not
8246 matched. This means it's up to the caller to set the length of
8247 the node to include the closing RC. The node start pos is set to
8248 the absolute buffer start position, and the caller should fix it
8249 up to be relative to the parent node. All children of this block
8250 node are given relative start positions and correct lengths."
8251 (let ((pn (or parent (make-js2-block-node)))
8252 tt)
8253 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8254 (/= tt js2-RC))
8255 (js2-block-node-push pn (js2-parse-statement)))
8256 pn))
8257
8258 (defun js2-parse-statement ()
8259 (let (pn beg end)
8260 ;; coarse-grained user-interrupt check - needs work
8261 (and js2-parse-interruptable-p
8262 (zerop (% (cl-incf js2-parse-stmt-count)
8263 js2-statements-per-pause))
8264 (input-pending-p)
8265 (throw 'interrupted t))
8266 (setq pn (js2-statement-helper))
8267 ;; no-side-effects warning check
8268 (unless (js2-node-has-side-effects pn)
8269 (setq end (js2-node-end pn))
8270 (save-excursion
8271 (goto-char end)
8272 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8273 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8274 pn))
8275
8276 ;; These correspond to the switch cases in Parser.statementHelper
8277 (defconst js2-parsers
8278 (let ((parsers (make-vector js2-num-tokens
8279 #'js2-parse-expr-stmt)))
8280 (aset parsers js2-BREAK #'js2-parse-break)
8281 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8282 (aset parsers js2-CONST #'js2-parse-const-var)
8283 (aset parsers js2-CONTINUE #'js2-parse-continue)
8284 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8285 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8286 (aset parsers js2-DO #'js2-parse-do)
8287 (aset parsers js2-EXPORT #'js2-parse-export)
8288 (aset parsers js2-FOR #'js2-parse-for)
8289 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8290 (aset parsers js2-IF #'js2-parse-if)
8291 (aset parsers js2-IMPORT #'js2-parse-import)
8292 (aset parsers js2-LC #'js2-parse-block)
8293 (aset parsers js2-LET #'js2-parse-let-stmt)
8294 (aset parsers js2-NAME #'js2-parse-name-or-label)
8295 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8296 (aset parsers js2-SEMI #'js2-parse-semi)
8297 (aset parsers js2-SWITCH #'js2-parse-switch)
8298 (aset parsers js2-THROW #'js2-parse-throw)
8299 (aset parsers js2-TRY #'js2-parse-try)
8300 (aset parsers js2-VAR #'js2-parse-const-var)
8301 (aset parsers js2-WHILE #'js2-parse-while)
8302 (aset parsers js2-WITH #'js2-parse-with)
8303 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8304 parsers)
8305 "A vector mapping token types to parser functions.")
8306
8307 (defun js2-parse-warn-missing-semi (beg end)
8308 (and js2-mode-show-strict-warnings
8309 js2-strict-missing-semi-warning
8310 (js2-add-strict-warning
8311 "msg.missing.semi" nil
8312 ;; back up to beginning of statement or line
8313 (max beg (save-excursion
8314 (goto-char end)
8315 (point-at-bol)))
8316 end)))
8317
8318 (defconst js2-no-semi-insertion
8319 (list js2-IF
8320 js2-SWITCH
8321 js2-WHILE
8322 js2-DO
8323 js2-FOR
8324 js2-TRY
8325 js2-WITH
8326 js2-LC
8327 js2-ERROR
8328 js2-SEMI
8329 js2-CLASS
8330 js2-FUNCTION
8331 js2-EXPORT)
8332 "List of tokens that don't do automatic semicolon insertion.")
8333
8334 (defconst js2-autoinsert-semi-and-warn
8335 (list js2-ERROR js2-EOF js2-RC))
8336
8337 (defun js2-statement-helper ()
8338 (let* ((tt (js2-get-token))
8339 (first-tt tt)
8340 (parser (if (= tt js2-ERROR)
8341 #'js2-parse-semi
8342 (aref js2-parsers tt)))
8343 pn)
8344 ;; If the statement is set, then it's been told its label by now.
8345 (and js2-labeled-stmt
8346 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8347 (setq js2-labeled-stmt nil))
8348 (setq pn (funcall parser))
8349 ;; Don't do auto semi insertion for certain statement types.
8350 (unless (or (memq first-tt js2-no-semi-insertion)
8351 (js2-labeled-stmt-node-p pn))
8352 (js2-auto-insert-semicolon pn))
8353 pn))
8354
8355 (defun js2-auto-insert-semicolon (pn)
8356 (let* ((tt (js2-get-token))
8357 (pos (js2-node-pos pn)))
8358 (cond
8359 ((= tt js2-SEMI)
8360 ;; extend the node bounds to include the semicolon.
8361 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8362 ((memq tt js2-autoinsert-semi-and-warn)
8363 (js2-unget-token) ; Not ';', do not consume.
8364 ;; Autoinsert ;
8365 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8366 (t
8367 (if (not (js2-token-follows-eol-p (js2-current-token)))
8368 ;; Report error if no EOL or autoinsert ';' otherwise
8369 (js2-report-error "msg.no.semi.stmt")
8370 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8371 (js2-unget-token) ; Not ';', do not consume.
8372 ))))
8373
8374 (defun js2-parse-condition ()
8375 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8376 The parens are discarded and the expression node is returned.
8377 The `pos' field of the return value is set to an absolute position
8378 that must be fixed up by the caller.
8379 Return value is a list (EXPR LP RP), with absolute paren positions."
8380 (let (pn lp rp)
8381 (if (js2-must-match js2-LP "msg.no.paren.cond")
8382 (setq lp (js2-current-token-beg)))
8383 (setq pn (js2-parse-expr))
8384 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8385 (setq rp (js2-current-token-beg)))
8386 ;; Report strict warning on code like "if (a = 7) ..."
8387 (if (and js2-strict-cond-assign-warning
8388 (js2-assign-node-p pn))
8389 (js2-add-strict-warning "msg.equal.as.assign" nil
8390 (js2-node-pos pn)
8391 (+ (js2-node-pos pn)
8392 (js2-node-len pn))))
8393 (list pn lp rp)))
8394
8395 (defun js2-parse-if ()
8396 "Parser for if-statement. Last matched token must be js2-IF."
8397 (let ((pos (js2-current-token-beg))
8398 cond if-true if-false else-pos end pn)
8399 (setq cond (js2-parse-condition)
8400 if-true (js2-parse-statement)
8401 if-false (if (js2-match-token js2-ELSE)
8402 (progn
8403 (setq else-pos (- (js2-current-token-beg) pos))
8404 (js2-parse-statement)))
8405 end (js2-node-end (or if-false if-true))
8406 pn (make-js2-if-node :pos pos
8407 :len (- end pos)
8408 :condition (car cond)
8409 :then-part if-true
8410 :else-part if-false
8411 :else-pos else-pos
8412 :lp (js2-relpos (cl-second cond) pos)
8413 :rp (js2-relpos (cl-third cond) pos)))
8414 (js2-node-add-children pn (car cond) if-true if-false)
8415 pn))
8416
8417 (defun js2-parse-import ()
8418 "Parse import statement. The current token must be js2-IMPORT."
8419 (unless (js2-ast-root-p js2-current-scope)
8420 (js2-report-error "msg.mod.import.decl.at.top.level"))
8421 (let ((beg (js2-current-token-beg)))
8422 (cond ((js2-match-token js2-STRING)
8423 (make-js2-import-node
8424 :pos beg
8425 :len (- (js2-current-token-end) beg)
8426 :module-id (js2-current-token-string)))
8427 (t
8428 (let* ((import-clause (js2-parse-import-clause))
8429 (from-clause (and import-clause (js2-parse-from-clause)))
8430 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8431 (node (make-js2-import-node
8432 :pos beg
8433 :len (- (js2-current-token-end) beg)
8434 :import import-clause
8435 :from from-clause
8436 :module-id module-id)))
8437 (when import-clause
8438 (js2-node-add-children node import-clause))
8439 (when from-clause
8440 (js2-node-add-children node from-clause))
8441 node)))))
8442
8443 (defun js2-parse-import-clause ()
8444 "Parse the bindings in an import statement.
8445 This can take many forms:
8446
8447 ImportedDefaultBinding -> 'foo'
8448 NameSpaceImport -> '* as lib'
8449 NamedImports -> '{foo as bar, bang}'
8450 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8451 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8452
8453 Try to match namespace imports and named imports first because nothing can
8454 come after them. If it is an imported default binding, then it could have named
8455 imports or a namespace import that follows it.
8456 "
8457 (let* ((beg (js2-current-token-beg))
8458 (clause (make-js2-import-clause-node
8459 :pos beg))
8460 (children (list)))
8461 (cond
8462 ((js2-match-token js2-MUL)
8463 (let ((ns-import (js2-parse-namespace-import)))
8464 (when ns-import
8465 (let ((name-node (js2-namespace-import-node-name ns-import)))
8466 (js2-define-symbol
8467 js2-LET (js2-name-node-name name-node) name-node t)))
8468 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8469 (push ns-import children)))
8470 ((js2-match-token js2-LC)
8471 (let ((imports (js2-parse-export-bindings t)))
8472 (setf (js2-import-clause-node-named-imports clause) imports)
8473 (dolist (import imports)
8474 (push import children)
8475 (let ((name-node (js2-export-binding-node-local-name import)))
8476 (when name-node
8477 (js2-define-symbol
8478 js2-LET (js2-name-node-name name-node) name-node t))))))
8479 ((= (js2-peek-token) js2-NAME)
8480 (let ((binding (js2-maybe-parse-export-binding)))
8481 (let ((node-name (js2-export-binding-node-local-name binding)))
8482 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8483 (setf (js2-import-clause-node-default-binding clause) binding)
8484 (push binding children))
8485 (when (js2-match-token js2-COMMA)
8486 (cond
8487 ((js2-match-token js2-MUL)
8488 (let ((ns-import (js2-parse-namespace-import)))
8489 (let ((name-node (js2-namespace-import-node-name ns-import)))
8490 (js2-define-symbol
8491 js2-LET (js2-name-node-name name-node) name-node t))
8492 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8493 (push ns-import children)))
8494 ((js2-match-token js2-LC)
8495 (let ((imports (js2-parse-export-bindings t)))
8496 (setf (js2-import-clause-node-named-imports clause) imports)
8497 (dolist (import imports)
8498 (push import children)
8499 (let ((name-node (js2-export-binding-node-local-name import)))
8500 (when name-node
8501 (js2-define-symbol
8502 js2-LET (js2-name-node-name name-node) name-node t))))))
8503 (t (js2-report-error "msg.syntax")))))
8504 (t (js2-report-error "msg.mod.declaration.after.import")))
8505 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8506 (apply #'js2-node-add-children clause children)
8507 clause))
8508
8509 (defun js2-parse-namespace-import ()
8510 "Parse a namespace import expression such as '* as bar'.
8511 The current token must be js2-MUL."
8512 (let ((beg (js2-current-token-beg)))
8513 (when (js2-must-match js2-NAME "msg.syntax")
8514 (if (equal "as" (js2-current-token-string))
8515 (when (js2-must-match-prop-name "msg.syntax")
8516 (let ((node (make-js2-namespace-import-node
8517 :pos beg
8518 :len (- (js2-current-token-end) beg)
8519 :name (make-js2-name-node
8520 :pos (js2-current-token-beg)
8521 :len (js2-current-token-end)
8522 :name (js2-current-token-string)))))
8523 (js2-node-add-children node (js2-namespace-import-node-name node))
8524 node))
8525 (js2-unget-token)
8526 (js2-report-error "msg.syntax")))))
8527
8528
8529 (defun js2-parse-from-clause ()
8530 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8531 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8532 (let ((beg (js2-current-token-beg)))
8533 (if (equal "from" (js2-current-token-string))
8534 (cond
8535 ((js2-match-token js2-STRING)
8536 (make-js2-from-clause-node
8537 :pos beg
8538 :len (- (js2-current-token-end) beg)
8539 :module-id (js2-current-token-string)
8540 :metadata-p nil))
8541 ((js2-match-token js2-THIS)
8542 (when (js2-must-match-name "msg.mod.spec.after.from")
8543 (if (equal "module" (js2-current-token-string))
8544 (make-js2-from-clause-node
8545 :pos beg
8546 :len (- (js2-current-token-end) beg)
8547 :module-id "this"
8548 :metadata-p t)
8549 (js2-unget-token)
8550 (js2-unget-token)
8551 (js2-report-error "msg.mod.spec.after.from")
8552 nil)))
8553 (t (js2-report-error "msg.mod.spec.after.from") nil))
8554 (js2-unget-token)
8555 (js2-report-error "msg.mod.from.after.import.spec.set")
8556 nil))))
8557
8558 (defun js2-parse-export-bindings (&optional import-p)
8559 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8560 {foo as bar, baz as bang}. The current token must be
8561 js2-LC. Return a lisp list of js2-export-binding-node"
8562 (let ((bindings (list)))
8563 (while
8564 (let ((binding (js2-maybe-parse-export-binding)))
8565 (when binding
8566 (push binding bindings))
8567 (js2-match-token js2-COMMA)))
8568 (when (js2-must-match js2-RC (if import-p
8569 "msg.mod.rc.after.import.spec.list"
8570 "msg.mod.rc.after.export.spec.list"))
8571 (reverse bindings))))
8572
8573 (defun js2-maybe-parse-export-binding ()
8574 "Attempt to parse a binding expression found inside an import/export statement.
8575 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8576 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8577 js2-export-binding-node and consume all the tokens. If it does not match, it
8578 consumes no tokens."
8579 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8580 (beg (js2-current-token-beg))
8581 (extern-name-len (js2-current-token-len))
8582 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8583 (aref js2-kwd-tokens (js2-current-token-type)))))
8584 (if extern-name
8585 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8586 (if (and as (equal "as" (js2-current-token-string)))
8587 (let ((name
8588 (or
8589 (and (js2-match-token js2-DEFAULT) "default")
8590 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8591 (if name
8592 (let ((node (make-js2-export-binding-node
8593 :pos beg
8594 :len (- (js2-current-token-end) beg)
8595 :local-name (make-js2-name-node
8596 :name name
8597 :pos (js2-current-token-beg)
8598 :len (js2-current-token-len))
8599 :extern-name (make-js2-name-node
8600 :name extern-name
8601 :pos beg
8602 :len extern-name-len))))
8603 (js2-node-add-children
8604 node
8605 (js2-export-binding-node-local-name node)
8606 (js2-export-binding-node-extern-name node))
8607 node)
8608 (js2-unget-token)
8609 nil))
8610 (when as (js2-unget-token))
8611 (let* ((name-node (make-js2-name-node
8612 :name (js2-current-token-string)
8613 :pos (js2-current-token-beg)
8614 :len (js2-current-token-len)))
8615 (node (make-js2-export-binding-node
8616 :pos (js2-current-token-beg)
8617 :len (js2-current-token-len)
8618 :local-name name-node
8619 :extern-name name-node)))
8620 (when is-reserved-name
8621 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8622 (js2-node-add-children node name-node)
8623 node)))
8624 nil)))
8625
8626 (defun js2-parse-switch ()
8627 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8628 (let ((pos (js2-current-token-beg))
8629 tt pn discriminant has-default case-expr case-node
8630 case-pos cases stmt lp)
8631 (if (js2-must-match js2-LP "msg.no.paren.switch")
8632 (setq lp (js2-current-token-beg)))
8633 (setq discriminant (js2-parse-expr)
8634 pn (make-js2-switch-node :discriminant discriminant
8635 :pos pos
8636 :lp (js2-relpos lp pos)))
8637 (js2-node-add-children pn discriminant)
8638 (js2-enter-switch pn)
8639 (unwind-protect
8640 (progn
8641 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8642 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8643 (js2-must-match js2-LC "msg.no.brace.switch")
8644 (catch 'break
8645 (while t
8646 (setq tt (js2-next-token)
8647 case-pos (js2-current-token-beg))
8648 (cond
8649 ((= tt js2-RC)
8650 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8651 (throw 'break nil)) ; done
8652 ((= tt js2-CASE)
8653 (setq case-expr (js2-parse-expr))
8654 (js2-must-match js2-COLON "msg.no.colon.case"))
8655 ((= tt js2-DEFAULT)
8656 (if has-default
8657 (js2-report-error "msg.double.switch.default"))
8658 (setq has-default t
8659 case-expr nil)
8660 (js2-must-match js2-COLON "msg.no.colon.case"))
8661 (t
8662 (js2-report-error "msg.bad.switch")
8663 (throw 'break nil)))
8664 (setq case-node (make-js2-case-node :pos case-pos
8665 :len (- (js2-current-token-end) case-pos)
8666 :expr case-expr))
8667 (js2-node-add-children case-node case-expr)
8668 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8669 (/= tt js2-CASE)
8670 (/= tt js2-DEFAULT)
8671 (/= tt js2-EOF))
8672 (setf stmt (js2-parse-statement)
8673 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8674 (js2-block-node-push case-node stmt))
8675 (push case-node cases)))
8676 ;; add cases last, as pushing reverses the order to be correct
8677 (dolist (kid cases)
8678 (js2-node-add-children pn kid)
8679 (push kid (js2-switch-node-cases pn)))
8680 pn) ; return value
8681 (js2-exit-switch))))
8682
8683 (defun js2-parse-while ()
8684 "Parser for while-statement. Last matched token must be js2-WHILE."
8685 (let ((pos (js2-current-token-beg))
8686 (pn (make-js2-while-node))
8687 cond body)
8688 (js2-enter-loop pn)
8689 (unwind-protect
8690 (progn
8691 (setf cond (js2-parse-condition)
8692 (js2-while-node-condition pn) (car cond)
8693 body (js2-parse-statement)
8694 (js2-while-node-body pn) body
8695 (js2-node-len pn) (- (js2-node-end body) pos)
8696 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8697 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8698 (js2-node-add-children pn body (car cond)))
8699 (js2-exit-loop))
8700 pn))
8701
8702 (defun js2-parse-do ()
8703 "Parser for do-statement. Last matched token must be js2-DO."
8704 (let ((pos (js2-current-token-beg))
8705 (pn (make-js2-do-node))
8706 cond body end)
8707 (js2-enter-loop pn)
8708 (unwind-protect
8709 (progn
8710 (setq body (js2-parse-statement))
8711 (js2-must-match js2-WHILE "msg.no.while.do")
8712 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8713 cond (js2-parse-condition)
8714 (js2-do-node-condition pn) (car cond)
8715 (js2-do-node-body pn) body
8716 end js2-ts-cursor
8717 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8718 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8719 (js2-node-add-children pn (car cond) body))
8720 (js2-exit-loop))
8721 ;; Always auto-insert semicolon to follow SpiderMonkey:
8722 ;; It is required by ECMAScript but is ignored by the rest of
8723 ;; world; see bug 238945
8724 (if (js2-match-token js2-SEMI)
8725 (setq end js2-ts-cursor))
8726 (setf (js2-node-len pn) (- end pos))
8727 pn))
8728
8729 (defun js2-parse-export ()
8730 "Parse an export statement.
8731 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8732 expressions should only be either hoistable expressions (function or generator)
8733 or assignment expressions, but there is no checking to enforce that and so it
8734 will parse without error a small subset of
8735 invalid export statements."
8736 (unless (js2-ast-root-p js2-current-scope)
8737 (js2-report-error "msg.mod.export.decl.at.top.level"))
8738 (let ((beg (js2-current-token-beg))
8739 (children (list))
8740 exports-list from-clause declaration default)
8741 (cond
8742 ((js2-match-token js2-MUL)
8743 (setq from-clause (js2-parse-from-clause))
8744 (when from-clause
8745 (push from-clause children)))
8746 ((js2-match-token js2-LC)
8747 (setq exports-list (js2-parse-export-bindings))
8748 (when exports-list
8749 (dolist (export exports-list)
8750 (push export children)))
8751 (when (js2-match-token js2-NAME)
8752 (if (equal "from" (js2-current-token-string))
8753 (progn
8754 (js2-unget-token)
8755 (setq from-clause (js2-parse-from-clause)))
8756 (js2-unget-token))))
8757 ((js2-match-token js2-DEFAULT)
8758 (setq default (js2-parse-expr)))
8759 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8760 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8761 (t
8762 (setq declaration (js2-parse-expr))))
8763 (when from-clause
8764 (push from-clause children))
8765 (when declaration
8766 (push declaration children)
8767 (when (not (js2-function-node-p declaration))
8768 (js2-auto-insert-semicolon declaration)))
8769 (when default
8770 (push default children)
8771 (when (not (js2-function-node-p default))
8772 (js2-auto-insert-semicolon default)))
8773 (let ((node (make-js2-export-node
8774 :pos beg
8775 :len (- (js2-current-token-end) beg)
8776 :exports-list exports-list
8777 :from-clause from-clause
8778 :declaration declaration
8779 :default default)))
8780 (apply #'js2-node-add-children node children)
8781 node)))
8782
8783 (defun js2-parse-for ()
8784 "Parse a for, for-in or for each-in statement.
8785 Last matched token must be js2-FOR."
8786 (let ((for-pos (js2-current-token-beg))
8787 (tmp-scope (make-js2-scope))
8788 pn is-for-each is-for-in-or-of is-for-of
8789 in-pos each-pos tmp-pos
8790 init ; Node init is also foo in 'foo in object'.
8791 cond ; Node cond is also object in 'foo in object'.
8792 incr ; 3rd section of for-loop initializer.
8793 body tt lp rp)
8794 ;; See if this is a for each () instead of just a for ()
8795 (when (js2-match-token js2-NAME)
8796 (if (string= "each" (js2-current-token-string))
8797 (progn
8798 (setq is-for-each t
8799 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8800 (js2-record-face 'font-lock-keyword-face))
8801 (js2-report-error "msg.no.paren.for")))
8802 (if (js2-must-match js2-LP "msg.no.paren.for")
8803 (setq lp (- (js2-current-token-beg) for-pos)))
8804 (setq tt (js2-get-token))
8805 ;; Capture identifiers inside parens. We can't create the node
8806 ;; (and use it as the current scope) until we know its type.
8807 (js2-push-scope tmp-scope)
8808 (unwind-protect
8809 (progn
8810 ;; parse init clause
8811 (let ((js2-in-for-init t)) ; set as dynamic variable
8812 (cond
8813 ((= tt js2-SEMI)
8814 (js2-unget-token)
8815 (setq init (make-js2-empty-expr-node)))
8816 ((or (= tt js2-VAR) (= tt js2-LET))
8817 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8818 (t
8819 (js2-unget-token)
8820 (setq init (js2-parse-expr)))))
8821 (if (or (js2-match-token js2-IN)
8822 (and (>= js2-language-version 200)
8823 (js2-match-contextual-kwd "of")
8824 (setq is-for-of t)))
8825 (setq is-for-in-or-of t
8826 in-pos (- (js2-current-token-beg) for-pos)
8827 ;; scope of iteration target object is not the scope we've created above.
8828 ;; stash current scope temporary.
8829 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8830 (js2-parse-expr))) ; object over which we're iterating
8831 ;; else ordinary for loop - parse cond and incr
8832 (js2-must-match js2-SEMI "msg.no.semi.for")
8833 (setq cond (if (= (js2-peek-token) js2-SEMI)
8834 (make-js2-empty-expr-node) ; no loop condition
8835 (js2-parse-expr)))
8836 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8837 (setq tmp-pos (js2-current-token-end)
8838 incr (if (= (js2-peek-token) js2-RP)
8839 (make-js2-empty-expr-node :pos tmp-pos)
8840 (js2-parse-expr)))))
8841 (js2-pop-scope))
8842 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8843 (setq rp (- (js2-current-token-beg) for-pos)))
8844 (if (not is-for-in-or-of)
8845 (setq pn (make-js2-for-node :init init
8846 :condition cond
8847 :update incr
8848 :lp lp
8849 :rp rp))
8850 ;; cond could be null if 'in obj' got eaten by the init node.
8851 (if (js2-infix-node-p init)
8852 ;; it was (foo in bar) instead of (var foo in bar)
8853 (setq cond (js2-infix-node-right init)
8854 init (js2-infix-node-left init))
8855 (if (and (js2-var-decl-node-p init)
8856 (> (length (js2-var-decl-node-kids init)) 1))
8857 (js2-report-error "msg.mult.index")))
8858 (setq pn (make-js2-for-in-node :iterator init
8859 :object cond
8860 :in-pos in-pos
8861 :foreach-p is-for-each
8862 :each-pos each-pos
8863 :forof-p is-for-of
8864 :lp lp
8865 :rp rp)))
8866 ;; Transplant the declarations.
8867 (setf (js2-scope-symbol-table pn)
8868 (js2-scope-symbol-table tmp-scope))
8869 (unwind-protect
8870 (progn
8871 (js2-enter-loop pn)
8872 ;; We have to parse the body -after- creating the loop node,
8873 ;; so that the loop node appears in the js2-loop-set, allowing
8874 ;; break/continue statements to find the enclosing loop.
8875 (setf body (js2-parse-statement)
8876 (js2-loop-node-body pn) body
8877 (js2-node-pos pn) for-pos
8878 (js2-node-len pn) (- (js2-node-end body) for-pos))
8879 (js2-node-add-children pn init cond incr body))
8880 ;; finally
8881 (js2-exit-loop))
8882 pn))
8883
8884 (defun js2-parse-try ()
8885 "Parse a try statement. Last matched token must be js2-TRY."
8886 (let ((try-pos (js2-current-token-beg))
8887 try-end
8888 try-block
8889 catch-blocks
8890 finally-block
8891 saw-default-catch
8892 peek)
8893 (if (/= (js2-peek-token) js2-LC)
8894 (js2-report-error "msg.no.brace.try"))
8895 (setq try-block (js2-parse-statement)
8896 try-end (js2-node-end try-block)
8897 peek (js2-peek-token))
8898 (cond
8899 ((= peek js2-CATCH)
8900 (while (js2-match-token js2-CATCH)
8901 (let* ((catch-pos (js2-current-token-beg))
8902 (catch-node (make-js2-catch-node :pos catch-pos))
8903 param
8904 guard-kwd
8905 catch-cond
8906 lp rp)
8907 (if saw-default-catch
8908 (js2-report-error "msg.catch.unreachable"))
8909 (if (js2-must-match js2-LP "msg.no.paren.catch")
8910 (setq lp (- (js2-current-token-beg) catch-pos)))
8911 (js2-push-scope catch-node)
8912 (let ((tt (js2-peek-token)))
8913 (cond
8914 ;; Destructuring pattern:
8915 ;; catch ({ message, file }) { ... }
8916 ((or (= tt js2-LB) (= tt js2-LC))
8917 (js2-get-token)
8918 (setq param (js2-parse-destruct-primary-expr))
8919 (js2-define-destruct-symbols param js2-LET nil))
8920 ;; Simple name.
8921 (t
8922 (js2-must-match-name "msg.bad.catchcond")
8923 (setq param (js2-create-name-node))
8924 (js2-define-symbol js2-LET (js2-current-token-string) param)
8925 (js2-check-strict-identifier param))))
8926 ;; Catch condition.
8927 (if (js2-match-token js2-IF)
8928 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8929 catch-cond (js2-parse-expr))
8930 (setq saw-default-catch t))
8931 (if (js2-must-match js2-RP "msg.bad.catchcond")
8932 (setq rp (- (js2-current-token-beg) catch-pos)))
8933 (js2-must-match js2-LC "msg.no.brace.catchblock")
8934 (js2-parse-statements catch-node)
8935 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8936 (setq try-end (js2-current-token-end)))
8937 (js2-pop-scope)
8938 (setf (js2-node-len catch-node) (- try-end catch-pos)
8939 (js2-catch-node-param catch-node) param
8940 (js2-catch-node-guard-expr catch-node) catch-cond
8941 (js2-catch-node-guard-kwd catch-node) guard-kwd
8942 (js2-catch-node-lp catch-node) lp
8943 (js2-catch-node-rp catch-node) rp)
8944 (js2-node-add-children catch-node param catch-cond)
8945 (push catch-node catch-blocks))))
8946 ((/= peek js2-FINALLY)
8947 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8948 (js2-node-pos try-block)
8949 (- (setq try-end (js2-node-end try-block))
8950 (js2-node-pos try-block)))))
8951 (when (js2-match-token js2-FINALLY)
8952 (let ((finally-pos (js2-current-token-beg))
8953 (block (js2-parse-statement)))
8954 (setq try-end (js2-node-end block)
8955 finally-block (make-js2-finally-node :pos finally-pos
8956 :len (- try-end finally-pos)
8957 :body block))
8958 (js2-node-add-children finally-block block)))
8959 (let ((pn (make-js2-try-node :pos try-pos
8960 :len (- try-end try-pos)
8961 :try-block try-block
8962 :finally-block finally-block)))
8963 (js2-node-add-children pn try-block finally-block)
8964 ;; Push them onto the try-node, which reverses and corrects their order.
8965 (dolist (cb catch-blocks)
8966 (js2-node-add-children pn cb)
8967 (push cb (js2-try-node-catch-clauses pn)))
8968 pn)))
8969
8970 (defun js2-parse-throw ()
8971 "Parser for throw-statement. Last matched token must be js2-THROW."
8972 (let ((pos (js2-current-token-beg))
8973 expr pn)
8974 (if (= (js2-peek-token-or-eol) js2-EOL)
8975 ;; ECMAScript does not allow new lines before throw expression,
8976 ;; see bug 256617
8977 (js2-report-error "msg.bad.throw.eol"))
8978 (setq expr (js2-parse-expr)
8979 pn (make-js2-throw-node :pos pos
8980 :len (- (js2-node-end expr) pos)
8981 :expr expr))
8982 (js2-node-add-children pn expr)
8983 pn))
8984
8985 (defun js2-match-jump-label-name (label-name)
8986 "If break/continue specified a label, return that label's labeled stmt.
8987 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8988 does not match an existing label, reports an error and returns nil."
8989 (let ((bundle (cdr (assoc label-name js2-label-set))))
8990 (if (null bundle)
8991 (js2-report-error "msg.undef.label"))
8992 bundle))
8993
8994 (defun js2-parse-break ()
8995 "Parser for break-statement. Last matched token must be js2-BREAK."
8996 (let ((pos (js2-current-token-beg))
8997 (end (js2-current-token-end))
8998 break-target ; statement to break from
8999 break-label ; in "break foo", name-node representing the foo
9000 labels ; matching labeled statement to break to
9001 pn)
9002 (when (eq (js2-peek-token-or-eol) js2-NAME)
9003 (js2-get-token)
9004 (setq break-label (js2-create-name-node)
9005 end (js2-node-end break-label)
9006 ;; matchJumpLabelName only matches if there is one
9007 labels (js2-match-jump-label-name (js2-current-token-string))
9008 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9009 (unless (or break-target break-label)
9010 ;; no break target specified - try for innermost enclosing loop/switch
9011 (if (null js2-loop-and-switch-set)
9012 (unless break-label
9013 (js2-report-error "msg.bad.break" nil pos (length "break")))
9014 (setq break-target (car js2-loop-and-switch-set))))
9015 (setq pn (make-js2-break-node :pos pos
9016 :len (- end pos)
9017 :label break-label
9018 :target break-target))
9019 (js2-node-add-children pn break-label) ; but not break-target
9020 pn))
9021
9022 (defun js2-parse-continue ()
9023 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9024 (let ((pos (js2-current-token-beg))
9025 (end (js2-current-token-end))
9026 label ; optional user-specified label, a `js2-name-node'
9027 labels ; current matching labeled stmt, if any
9028 target ; the `js2-loop-node' target of this continue stmt
9029 pn)
9030 (when (= (js2-peek-token-or-eol) js2-NAME)
9031 (js2-get-token)
9032 (setq label (js2-create-name-node)
9033 end (js2-node-end label)
9034 ;; matchJumpLabelName only matches if there is one
9035 labels (js2-match-jump-label-name (js2-current-token-string))))
9036 (cond
9037 ((null labels) ; no current label to go to
9038 (if (null js2-loop-set) ; no loop to continue to
9039 (js2-report-error "msg.continue.outside" nil pos
9040 (length "continue"))
9041 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9042 (t
9043 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9044 (setq target (js2-labeled-stmt-node-stmt labels))
9045 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9046 (setq pn (make-js2-continue-node :pos pos
9047 :len (- end pos)
9048 :label label
9049 :target target))
9050 (js2-node-add-children pn label) ; but not target - it's not our child
9051 pn))
9052
9053 (defun js2-parse-with ()
9054 "Parser for with-statement. Last matched token must be js2-WITH."
9055 (when js2-in-use-strict-directive
9056 (js2-report-error "msg.no.with.strict"))
9057 (let ((pos (js2-current-token-beg))
9058 obj body pn lp rp)
9059 (if (js2-must-match js2-LP "msg.no.paren.with")
9060 (setq lp (js2-current-token-beg)))
9061 (setq obj (js2-parse-expr))
9062 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9063 (setq rp (js2-current-token-beg)))
9064 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9065 (setq body (js2-parse-statement)))
9066 (setq pn (make-js2-with-node :pos pos
9067 :len (- (js2-node-end body) pos)
9068 :object obj
9069 :body body
9070 :lp (js2-relpos lp pos)
9071 :rp (js2-relpos rp pos)))
9072 (js2-node-add-children pn obj body)
9073 pn))
9074
9075 (defun js2-parse-const-var ()
9076 "Parser for var- or const-statement.
9077 Last matched token must be js2-CONST or js2-VAR."
9078 (let ((tt (js2-current-token-type))
9079 (pos (js2-current-token-beg))
9080 expr pn)
9081 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9082 pn (make-js2-expr-stmt-node :pos pos
9083 :len (- (js2-node-end expr) pos)
9084 :expr expr))
9085 (js2-node-add-children pn expr)
9086 pn))
9087
9088 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9089 (let ((pn (make-js2-expr-stmt-node :pos pos
9090 :len (js2-node-len expr)
9091 :type (if (js2-inside-function)
9092 js2-EXPR_VOID
9093 js2-EXPR_RESULT)
9094 :expr expr)))
9095 (if add-child
9096 (js2-node-add-children pn expr))
9097 pn))
9098
9099 (defun js2-parse-let-stmt ()
9100 "Parser for let-statement. Last matched token must be js2-LET."
9101 (let ((pos (js2-current-token-beg))
9102 expr pn)
9103 (if (= (js2-peek-token) js2-LP)
9104 ;; let expression in statement context
9105 (setq expr (js2-parse-let pos 'statement)
9106 pn (js2-wrap-with-expr-stmt pos expr t))
9107 ;; else we're looking at a statement like let x=6, y=7;
9108 (setf expr (js2-parse-variables js2-LET pos)
9109 pn (js2-wrap-with-expr-stmt pos expr t)
9110 (js2-node-type pn) js2-EXPR_RESULT))
9111 pn))
9112
9113 (defun js2-parse-ret-yield ()
9114 (js2-parse-return-or-yield (js2-current-token-type) nil))
9115
9116 (defconst js2-parse-return-stmt-enders
9117 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9118
9119 (defsubst js2-now-all-set (before after mask)
9120 "Return whether or not the bits in the mask have changed to all set.
9121 BEFORE is bits before change, AFTER is bits after change, and MASK is
9122 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9123 but not BEFORE."
9124 (and (/= (logand before mask) mask)
9125 (= (logand after mask) mask)))
9126
9127 (defun js2-parse-return-or-yield (tt expr-context)
9128 (let* ((pos (js2-current-token-beg))
9129 (end (js2-current-token-end))
9130 (before js2-end-flags)
9131 (inside-function (js2-inside-function))
9132 (gen-type (and inside-function (js2-function-node-generator-type
9133 js2-current-script-or-fn)))
9134 e ret name yield-star-p)
9135 (unless inside-function
9136 (js2-report-error (if (eq tt js2-RETURN)
9137 "msg.bad.return"
9138 "msg.bad.yield")))
9139 (when (and inside-function
9140 (eq gen-type 'STAR)
9141 (js2-match-token js2-MUL))
9142 (setq yield-star-p t))
9143 ;; This is ugly, but we don't want to require a semicolon.
9144 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9145 (setq e (js2-parse-expr)
9146 end (js2-node-end e)))
9147 (cond
9148 ((eq tt js2-RETURN)
9149 (js2-set-flag js2-end-flags (if (null e)
9150 js2-end-returns
9151 js2-end-returns-value))
9152 (setq ret (make-js2-return-node :pos pos
9153 :len (- end pos)
9154 :retval e))
9155 (js2-node-add-children ret e)
9156 ;; See if we need a strict mode warning.
9157 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9158 ;; more thorough and accurate than this before/after flag check.
9159 ;; E.g. if there's a finally-block that always returns, we shouldn't
9160 ;; show a warning generated by inconsistent returns in the catch blocks.
9161 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9162 ;; so we know which returns/yields to highlight, and we should get rid of
9163 ;; all the checking in `js2-parse-return-or-yield'.
9164 (if (and js2-strict-inconsistent-return-warning
9165 (js2-now-all-set before js2-end-flags
9166 (logior js2-end-returns js2-end-returns-value)))
9167 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9168 ((eq gen-type 'COMPREHENSION)
9169 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9170 ;; like SpiderMonkey does.
9171 (js2-report-error "msg.syntax" nil pos 5))
9172 (t
9173 (setq ret (make-js2-yield-node :pos pos
9174 :len (- end pos)
9175 :value e
9176 :star-p yield-star-p))
9177 (js2-node-add-children ret e)
9178 (unless expr-context
9179 (setq e ret
9180 ret (js2-wrap-with-expr-stmt pos e t))
9181 (js2-set-requires-activation)
9182 (js2-set-is-generator))))
9183 ;; see if we are mixing yields and value returns.
9184 (when (and inside-function
9185 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9186 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9187 'LEGACY))
9188 (setq name (js2-function-name js2-current-script-or-fn))
9189 (if (zerop (length name))
9190 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9191 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9192 ret))
9193
9194 (defun js2-parse-debugger ()
9195 (make-js2-keyword-node :type js2-DEBUGGER))
9196
9197 (defun js2-parse-block ()
9198 "Parser for a curly-delimited statement block.
9199 Last token matched must be `js2-LC'."
9200 (let ((pos (js2-current-token-beg))
9201 (pn (make-js2-scope)))
9202 (js2-push-scope pn)
9203 (unwind-protect
9204 (progn
9205 (js2-parse-statements pn)
9206 (js2-must-match js2-RC "msg.no.brace.block")
9207 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9208 (js2-pop-scope))
9209 pn))
9210
9211 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9212 (defun js2-parse-semi ()
9213 "Parse a statement or handle an error.
9214 Current token type is `js2-SEMI' or `js2-ERROR'."
9215 (let ((tt (js2-current-token-type)) pos len)
9216 (if (eq tt js2-SEMI)
9217 (make-js2-empty-expr-node :len 1)
9218 (setq pos (js2-current-token-beg)
9219 len (- (js2-current-token-end) pos))
9220 (js2-report-error "msg.syntax" nil pos len)
9221 (make-js2-error-node :pos pos :len len))))
9222
9223 (defun js2-parse-default-xml-namespace ()
9224 "Parse a `default xml namespace = <expr>' e4x statement."
9225 (let ((pos (js2-current-token-beg))
9226 end len expr unary)
9227 (js2-must-have-xml)
9228 (js2-set-requires-activation)
9229 (setq len (- js2-ts-cursor pos))
9230 (unless (and (js2-match-token js2-NAME)
9231 (string= (js2-current-token-string) "xml"))
9232 (js2-report-error "msg.bad.namespace" nil pos len))
9233 (unless (and (js2-match-token js2-NAME)
9234 (string= (js2-current-token-string) "namespace"))
9235 (js2-report-error "msg.bad.namespace" nil pos len))
9236 (unless (js2-match-token js2-ASSIGN)
9237 (js2-report-error "msg.bad.namespace" nil pos len))
9238 (setq expr (js2-parse-expr)
9239 end (js2-node-end expr)
9240 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9241 :pos pos
9242 :len (- end pos)
9243 :operand expr))
9244 (js2-node-add-children unary expr)
9245 (make-js2-expr-stmt-node :pos pos
9246 :len (- end pos)
9247 :expr unary)))
9248
9249 (defun js2-record-label (label bundle)
9250 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9251 (js2-get-token)
9252 (let ((name (js2-label-node-name label))
9253 labeled-stmt
9254 dup)
9255 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9256 ;; flag both labels if possible when used in editing mode
9257 (if (and js2-parse-ide-mode
9258 (setq dup (js2-get-label-by-name labeled-stmt name)))
9259 (js2-report-error "msg.dup.label" nil
9260 (js2-node-abs-pos dup) (js2-node-len dup)))
9261 (js2-report-error "msg.dup.label" nil
9262 (js2-node-pos label) (js2-node-len label)))
9263 (js2-labeled-stmt-node-add-label bundle label)
9264 (js2-node-add-children bundle label)
9265 ;; Add one reference to the bundle per label in `js2-label-set'
9266 (push (cons name bundle) js2-label-set)))
9267
9268 (defun js2-parse-name-or-label ()
9269 "Parser for identifier or label. Last token matched must be js2-NAME.
9270 Called when we found a name in a statement context. If it's a label, we gather
9271 up any following labels and the next non-label statement into a
9272 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9273 expression and return it wrapped in a `js2-expr-stmt-node'."
9274 (let ((pos (js2-current-token-beg))
9275 expr stmt bundle
9276 (continue t))
9277 ;; set check for label and call down to `js2-parse-primary-expr'
9278 (setq expr (js2-maybe-parse-label))
9279 (if (null expr)
9280 ;; Parse the non-label expression and wrap with expression stmt.
9281 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9282 ;; else parsed a label
9283 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9284 (js2-record-label expr bundle)
9285 ;; look for more labels
9286 (while (and continue (= (js2-get-token) js2-NAME))
9287 (if (setq expr (js2-maybe-parse-label))
9288 (js2-record-label expr bundle)
9289 (setq expr (js2-parse-expr)
9290 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9291 continue nil)
9292 (js2-auto-insert-semicolon stmt)))
9293 ;; no more labels; now parse the labeled statement
9294 (unwind-protect
9295 (unless stmt
9296 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9297 (js2-unget-token)
9298 (setq stmt (js2-statement-helper))))
9299 ;; remove the labels for this statement from the global set
9300 (dolist (label (js2-labeled-stmt-node-labels bundle))
9301 (setq js2-label-set (remove label js2-label-set))))
9302 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9303 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9304 (js2-node-add-children bundle stmt)
9305 bundle)))
9306
9307 (defun js2-maybe-parse-label ()
9308 (cl-assert (= (js2-current-token-type) js2-NAME))
9309 (let (label-pos
9310 (next-tt (js2-get-token))
9311 (label-end (js2-current-token-end)))
9312 ;; Do not consume colon, it is used as unwind indicator
9313 ;; to return to statementHelper.
9314 (js2-unget-token)
9315 (if (= next-tt js2-COLON)
9316 (prog2
9317 (setq label-pos (js2-current-token-beg))
9318 (make-js2-label-node :pos label-pos
9319 :len (- label-end label-pos)
9320 :name (js2-current-token-string))
9321 (js2-set-face label-pos
9322 label-end
9323 'font-lock-variable-name-face 'record))
9324 ;; Backtrack from the name token, too.
9325 (js2-unget-token)
9326 nil)))
9327
9328 (defun js2-parse-expr-stmt ()
9329 "Default parser in statement context, if no recognized statement found."
9330 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9331 (progn
9332 (js2-unget-token)
9333 (js2-parse-expr)) t))
9334
9335 (defun js2-parse-variables (decl-type pos)
9336 "Parse a comma-separated list of variable declarations.
9337 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9338
9339 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9340 For 'var' or 'const', the keyword should be the token last scanned.
9341
9342 POS is the position where the node should start. It's sometimes the
9343 var/const/let keyword, and other times the beginning of the first token
9344 in the first variable declaration.
9345
9346 Returns the parsed `js2-var-decl-node' expression node."
9347 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9348 :pos pos))
9349 destructuring kid-pos tt init name end nbeg nend vi
9350 (continue t))
9351 ;; Example:
9352 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9353 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9354 ;; var {a, b} = baz;
9355 (while continue
9356 (setq destructuring nil
9357 name nil
9358 tt (js2-get-token)
9359 kid-pos (js2-current-token-beg)
9360 end (js2-current-token-end)
9361 init nil)
9362 (if (or (= tt js2-LB) (= tt js2-LC))
9363 ;; Destructuring assignment, e.g., var [a, b] = ...
9364 (setq destructuring (js2-parse-destruct-primary-expr)
9365 end (js2-node-end destructuring))
9366 ;; Simple variable name
9367 (js2-unget-token)
9368 (when (js2-must-match-name "msg.bad.var")
9369 (setq name (js2-create-name-node)
9370 nbeg (js2-current-token-beg)
9371 nend (js2-current-token-end)
9372 end nend)
9373 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9374 (js2-check-strict-identifier name)))
9375 (when (js2-match-token js2-ASSIGN)
9376 (setq init (js2-parse-assign-expr)
9377 end (js2-node-end init))
9378 (js2-record-imenu-functions init name))
9379 (when name
9380 (js2-set-face nbeg nend (if (js2-function-node-p init)
9381 'font-lock-function-name-face
9382 'font-lock-variable-name-face)
9383 'record))
9384 (setq vi (make-js2-var-init-node :pos kid-pos
9385 :len (- end kid-pos)
9386 :type decl-type))
9387 (if destructuring
9388 (progn
9389 (if (and (null init) (not js2-in-for-init))
9390 (js2-report-error "msg.destruct.assign.no.init"))
9391 (js2-define-destruct-symbols destructuring
9392 decl-type
9393 'font-lock-variable-name-face)
9394 (setf (js2-var-init-node-target vi) destructuring))
9395 (setf (js2-var-init-node-target vi) name))
9396 (setf (js2-var-init-node-initializer vi) init)
9397 (js2-node-add-children vi name destructuring init)
9398 (js2-block-node-push result vi)
9399 (unless (js2-match-token js2-COMMA)
9400 (setq continue nil)))
9401 (setf (js2-node-len result) (- end pos))
9402 result))
9403
9404 (defun js2-parse-let (pos &optional stmt-p)
9405 "Parse a let expression or statement.
9406 A let-expression is of the form `let (vars) expr'.
9407 A let-statement is of the form `let (vars) {statements}'.
9408 The third form of let is a variable declaration list, handled
9409 by `js2-parse-variables'."
9410 (let ((pn (make-js2-let-node :pos pos))
9411 beg vars body)
9412 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9413 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9414 (js2-push-scope pn)
9415 (unwind-protect
9416 (progn
9417 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9418 (if (js2-must-match js2-RP "msg.no.paren.let")
9419 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9420 (if (and stmt-p (js2-match-token js2-LC))
9421 ;; let statement
9422 (progn
9423 (setf beg (js2-current-token-beg) ; position stmt at LC
9424 body (js2-parse-statements))
9425 (js2-must-match js2-RC "msg.no.curly.let")
9426 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9427 (js2-node-len pn) (- (js2-current-token-end) pos)
9428 (js2-let-node-body pn) body
9429 (js2-node-type pn) js2-LET))
9430 ;; let expression
9431 (setf body (js2-parse-expr)
9432 (js2-node-len pn) (- (js2-node-end body) pos)
9433 (js2-let-node-body pn) body))
9434 (setf (js2-let-node-vars pn) vars)
9435 (js2-node-add-children pn vars body))
9436 (js2-pop-scope))
9437 pn))
9438
9439 (defun js2-define-new-symbol (decl-type name node &optional scope)
9440 (js2-scope-put-symbol (or scope js2-current-scope)
9441 name
9442 (make-js2-symbol decl-type name node)))
9443
9444 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9445 "Define a symbol in the current scope.
9446 If NODE is non-nil, it is the AST node associated with the symbol."
9447 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9448 (symbol (if defining-scope
9449 (js2-scope-get-symbol defining-scope name)))
9450 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9451 (pos (if node (js2-node-abs-pos node)))
9452 (len (if node (js2-node-len node))))
9453 (cond
9454 ((and symbol ; already defined
9455 (or (if js2-in-use-strict-directive
9456 ;; two const-bound vars in this block have same name
9457 (and (= sdt js2-CONST)
9458 (eq defining-scope js2-current-scope))
9459 (or (= sdt js2-CONST) ; old version is const
9460 (= decl-type js2-CONST))) ; new version is const
9461 ;; two let-bound vars in this block have same name
9462 (and (= sdt js2-LET)
9463 (eq defining-scope js2-current-scope))))
9464 (js2-report-error
9465 (cond
9466 ((= sdt js2-CONST) "msg.const.redecl")
9467 ((= sdt js2-LET) "msg.let.redecl")
9468 ((= sdt js2-VAR) "msg.var.redecl")
9469 ((= sdt js2-FUNCTION) "msg.function.redecl")
9470 (t "msg.parm.redecl"))
9471 name pos len))
9472 ((or (= decl-type js2-LET)
9473 ;; strict mode const is scoped to the current LexicalEnvironment
9474 (and js2-in-use-strict-directive
9475 (= decl-type js2-CONST)))
9476 (if (and (= decl-type js2-LET)
9477 (not ignore-not-in-block)
9478 (or (= (js2-node-type js2-current-scope) js2-IF)
9479 (js2-loop-node-p js2-current-scope)))
9480 (js2-report-error "msg.let.decl.not.in.block")
9481 (js2-define-new-symbol decl-type name node)))
9482 ((or (= decl-type js2-VAR)
9483 (= decl-type js2-FUNCTION)
9484 ;; sloppy mode const is scoped to the current VariableEnvironment
9485 (and (not js2-in-use-strict-directive)
9486 (= decl-type js2-CONST)))
9487 (if symbol
9488 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9489 (js2-add-strict-warning "msg.var.redecl" name)
9490 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9491 (js2-add-strict-warning "msg.var.hides.arg" name)))
9492 (js2-define-new-symbol decl-type name node
9493 js2-current-script-or-fn)))
9494 ((= decl-type js2-LP)
9495 (if symbol
9496 ;; must be duplicate parameter. Second parameter hides the
9497 ;; first, so go ahead and add the second pararameter
9498 (js2-report-warning "msg.dup.parms" name))
9499 (js2-define-new-symbol decl-type name node))
9500 (t (js2-code-bug)))))
9501
9502 (defun js2-parse-paren-expr-or-generator-comp ()
9503 (let ((px-pos (js2-current-token-beg)))
9504 (cond
9505 ((and (>= js2-language-version 200)
9506 (js2-match-token js2-FOR))
9507 (js2-parse-generator-comp px-pos))
9508 ((and (>= js2-language-version 200)
9509 (js2-match-token js2-RP))
9510 ;; Not valid expression syntax, but this is valid in an arrow
9511 ;; function with no params: () => body.
9512 (if (eq (js2-peek-token) js2-ARROW)
9513 ;; Return whatever, it will hopefully be rewinded and
9514 ;; reparsed when we reach the =>.
9515 (make-js2-keyword-node :type js2-NULL)
9516 (js2-report-error "msg.syntax")
9517 (make-js2-error-node)))
9518 (t
9519 (let* ((js2-in-for-init nil)
9520 (expr (js2-parse-expr))
9521 (pn (make-js2-paren-node :pos px-pos
9522 :expr expr)))
9523 (js2-node-add-children pn (js2-paren-node-expr pn))
9524 (js2-must-match js2-RP "msg.no.paren")
9525 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9526 pn)))))
9527
9528 (defun js2-parse-expr (&optional oneshot)
9529 (let* ((pn (js2-parse-assign-expr))
9530 (pos (js2-node-pos pn))
9531 left
9532 right
9533 op-pos)
9534 (while (and (not oneshot)
9535 (js2-match-token js2-COMMA))
9536 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9537 (if (= (js2-peek-token) js2-YIELD)
9538 (js2-report-error "msg.yield.parenthesized"))
9539 (setq right (js2-parse-assign-expr)
9540 left pn
9541 pn (make-js2-infix-node :type js2-COMMA
9542 :pos pos
9543 :len (- js2-ts-cursor pos)
9544 :op-pos op-pos
9545 :left left
9546 :right right))
9547 (js2-node-add-children pn left right))
9548 pn))
9549
9550 (defun js2-parse-assign-expr ()
9551 (let ((tt (js2-get-token))
9552 (pos (js2-current-token-beg))
9553 pn left right op-pos
9554 ts-state recorded-identifiers parsed-errors)
9555 (if (= tt js2-YIELD)
9556 (js2-parse-return-or-yield tt t)
9557 ;; Save the tokenizer state in case we find an arrow function
9558 ;; and have to rewind.
9559 (setq ts-state (make-js2-ts-state)
9560 recorded-identifiers js2-recorded-identifiers
9561 parsed-errors js2-parsed-errors)
9562 ;; not yield - parse assignment expression
9563 (setq pn (js2-parse-cond-expr)
9564 tt (js2-get-token))
9565 (cond
9566 ((and (<= js2-first-assign tt)
9567 (<= tt js2-last-assign))
9568 ;; tt express assignment (=, |=, ^=, ..., %=)
9569 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9570 left pn)
9571 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9572 ;; care about assignment to strict variable names.
9573 (when (js2-name-node-p left)
9574 (js2-check-strict-identifier left))
9575 (setq right (js2-parse-assign-expr)
9576 pn (make-js2-assign-node :type tt
9577 :pos pos
9578 :len (- (js2-node-end right) pos)
9579 :op-pos op-pos
9580 :left left
9581 :right right))
9582 (when js2-parse-ide-mode
9583 (js2-highlight-assign-targets pn left right)
9584 (js2-record-imenu-functions right left))
9585 ;; do this last so ide checks above can use absolute positions
9586 (js2-node-add-children pn left right))
9587 ((and (= tt js2-ARROW)
9588 (>= js2-language-version 200))
9589 (js2-ts-seek ts-state)
9590 (setq js2-recorded-identifiers recorded-identifiers
9591 js2-parsed-errors parsed-errors)
9592 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9593 (t
9594 (js2-unget-token)))
9595 pn)))
9596
9597 (defun js2-parse-cond-expr ()
9598 (let ((pos (js2-current-token-beg))
9599 (pn (js2-parse-or-expr))
9600 test-expr
9601 if-true
9602 if-false
9603 q-pos
9604 c-pos)
9605 (when (js2-match-token js2-HOOK)
9606 (setq q-pos (- (js2-current-token-beg) pos)
9607 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9608 (js2-must-match js2-COLON "msg.no.colon.cond")
9609 (setq c-pos (- (js2-current-token-beg) pos)
9610 if-false (js2-parse-assign-expr)
9611 test-expr pn
9612 pn (make-js2-cond-node :pos pos
9613 :len (- (js2-node-end if-false) pos)
9614 :test-expr test-expr
9615 :true-expr if-true
9616 :false-expr if-false
9617 :q-pos q-pos
9618 :c-pos c-pos))
9619 (js2-node-add-children pn test-expr if-true if-false))
9620 pn))
9621
9622 (defun js2-make-binary (type left parser)
9623 "Helper for constructing a binary-operator AST node.
9624 LEFT is the left-side-expression, already parsed, and the
9625 binary operator should have just been matched.
9626 PARSER is a function to call to parse the right operand,
9627 or a `js2-node' struct if it has already been parsed.
9628 FIXME: The latter option is unused?"
9629 (let* ((pos (js2-node-pos left))
9630 (op-pos (- (js2-current-token-beg) pos))
9631 (right (if (js2-node-p parser)
9632 parser
9633 (js2-get-token)
9634 (funcall parser)))
9635 (pn (make-js2-infix-node :type type
9636 :pos pos
9637 :len (- (js2-node-end right) pos)
9638 :op-pos op-pos
9639 :left left
9640 :right right)))
9641 (js2-node-add-children pn left right)
9642 pn))
9643
9644 (defun js2-parse-or-expr ()
9645 (let ((pn (js2-parse-and-expr)))
9646 (when (js2-match-token js2-OR)
9647 (setq pn (js2-make-binary js2-OR
9648 pn
9649 'js2-parse-or-expr)))
9650 pn))
9651
9652 (defun js2-parse-and-expr ()
9653 (let ((pn (js2-parse-bit-or-expr)))
9654 (when (js2-match-token js2-AND)
9655 (setq pn (js2-make-binary js2-AND
9656 pn
9657 'js2-parse-and-expr)))
9658 pn))
9659
9660 (defun js2-parse-bit-or-expr ()
9661 (let ((pn (js2-parse-bit-xor-expr)))
9662 (while (js2-match-token js2-BITOR)
9663 (setq pn (js2-make-binary js2-BITOR
9664 pn
9665 'js2-parse-bit-xor-expr)))
9666 pn))
9667
9668 (defun js2-parse-bit-xor-expr ()
9669 (let ((pn (js2-parse-bit-and-expr)))
9670 (while (js2-match-token js2-BITXOR)
9671 (setq pn (js2-make-binary js2-BITXOR
9672 pn
9673 'js2-parse-bit-and-expr)))
9674 pn))
9675
9676 (defun js2-parse-bit-and-expr ()
9677 (let ((pn (js2-parse-eq-expr)))
9678 (while (js2-match-token js2-BITAND)
9679 (setq pn (js2-make-binary js2-BITAND
9680 pn
9681 'js2-parse-eq-expr)))
9682 pn))
9683
9684 (defconst js2-parse-eq-ops
9685 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9686
9687 (defun js2-parse-eq-expr ()
9688 (let ((pn (js2-parse-rel-expr))
9689 tt)
9690 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9691 (setq pn (js2-make-binary tt
9692 pn
9693 'js2-parse-rel-expr)))
9694 (js2-unget-token)
9695 pn))
9696
9697 (defconst js2-parse-rel-ops
9698 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9699
9700 (defun js2-parse-rel-expr ()
9701 (let ((pn (js2-parse-shift-expr))
9702 (continue t)
9703 tt)
9704 (while continue
9705 (setq tt (js2-get-token))
9706 (cond
9707 ((and js2-in-for-init (= tt js2-IN))
9708 (js2-unget-token)
9709 (setq continue nil))
9710 ((memq tt js2-parse-rel-ops)
9711 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9712 (t
9713 (js2-unget-token)
9714 (setq continue nil))))
9715 pn))
9716
9717 (defconst js2-parse-shift-ops
9718 (list js2-LSH js2-URSH js2-RSH))
9719
9720 (defun js2-parse-shift-expr ()
9721 (let ((pn (js2-parse-add-expr))
9722 tt
9723 (continue t))
9724 (while continue
9725 (setq tt (js2-get-token))
9726 (if (memq tt js2-parse-shift-ops)
9727 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9728 (js2-unget-token)
9729 (setq continue nil)))
9730 pn))
9731
9732 (defun js2-parse-add-expr ()
9733 (let ((pn (js2-parse-mul-expr))
9734 tt
9735 (continue t))
9736 (while continue
9737 (setq tt (js2-get-token))
9738 (if (or (= tt js2-ADD) (= tt js2-SUB))
9739 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9740 (js2-unget-token)
9741 (setq continue nil)))
9742 pn))
9743
9744 (defconst js2-parse-mul-ops
9745 (list js2-MUL js2-DIV js2-MOD))
9746
9747 (defun js2-parse-mul-expr ()
9748 (let ((pn (js2-parse-unary-expr))
9749 tt
9750 (continue t))
9751 (while continue
9752 (setq tt (js2-get-token))
9753 (if (memq tt js2-parse-mul-ops)
9754 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9755 (js2-unget-token)
9756 (setq continue nil)))
9757 pn))
9758
9759 (defun js2-make-unary (type parser &rest args)
9760 "Make a unary node of type TYPE.
9761 PARSER is either a node (for postfix operators) or a function to call
9762 to parse the operand (for prefix operators)."
9763 (let* ((pos (js2-current-token-beg))
9764 (postfix (js2-node-p parser))
9765 (expr (if postfix
9766 parser
9767 (apply parser args)))
9768 end
9769 pn)
9770 (if postfix ; e.g. i++
9771 (setq pos (js2-node-pos expr)
9772 end (js2-current-token-end))
9773 (setq end (js2-node-end expr)))
9774 (setq pn (make-js2-unary-node :type type
9775 :pos pos
9776 :len (- end pos)
9777 :operand expr))
9778 (js2-node-add-children pn expr)
9779 pn))
9780
9781 (defconst js2-incrementable-node-types
9782 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9783 "Node types that can be the operand of a ++ or -- operator.")
9784
9785 (defun js2-check-bad-inc-dec (tt beg end unary)
9786 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9787 js2-incrementable-node-types)
9788 (js2-report-error (if (= tt js2-INC)
9789 "msg.bad.incr"
9790 "msg.bad.decr")
9791 nil beg (- end beg))))
9792
9793 (defun js2-parse-unary-expr ()
9794 (let ((tt (js2-current-token-type))
9795 pn expr beg end)
9796 (cond
9797 ((or (= tt js2-VOID)
9798 (= tt js2-NOT)
9799 (= tt js2-BITNOT)
9800 (= tt js2-TYPEOF))
9801 (js2-get-token)
9802 (js2-make-unary tt 'js2-parse-unary-expr))
9803 ((= tt js2-ADD)
9804 (js2-get-token)
9805 ;; Convert to special POS token in decompiler and parse tree
9806 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9807 ((= tt js2-SUB)
9808 (js2-get-token)
9809 ;; Convert to special NEG token in decompiler and parse tree
9810 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9811 ((or (= tt js2-INC)
9812 (= tt js2-DEC))
9813 (js2-get-token)
9814 (prog1
9815 (setq beg (js2-current-token-beg)
9816 end (js2-current-token-end)
9817 expr (js2-make-unary tt 'js2-parse-member-expr t))
9818 (js2-check-bad-inc-dec tt beg end expr)))
9819 ((= tt js2-DELPROP)
9820 (js2-get-token)
9821 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9822 ((= tt js2-ERROR)
9823 (js2-get-token)
9824 (make-js2-error-node)) ; try to continue
9825 ((and (= tt js2-LT)
9826 js2-compiler-xml-available)
9827 ;; XML stream encountered in expression.
9828 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9829 (t
9830 (setq pn (js2-parse-member-expr t)
9831 ;; Don't look across a newline boundary for a postfix incop.
9832 tt (js2-peek-token-or-eol))
9833 (when (or (= tt js2-INC) (= tt js2-DEC))
9834 (js2-get-token)
9835 (setf expr pn
9836 pn (js2-make-unary tt expr))
9837 (js2-node-set-prop pn 'postfix t)
9838 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9839 pn))))
9840
9841 (defun js2-parse-xml-initializer ()
9842 "Parse an E4X XML initializer.
9843 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9844 Then I'll postprocess the result, depending on whether we're in IDE
9845 mode or codegen mode, and generate the appropriate rewritten AST.
9846 IDE mode uses a rich AST that models the XML structure. Codegen mode
9847 just concatenates everything and makes a new XML or XMLList out of it."
9848 (let ((tt (js2-get-first-xml-token))
9849 pn-xml pn expr kids expr-pos
9850 (continue t)
9851 (first-token t))
9852 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9853 (js2-report-error "msg.syntax"))
9854 (setq pn-xml (make-js2-xml-node))
9855 (while continue
9856 (if first-token
9857 (setq first-token nil)
9858 (setq tt (js2-get-next-xml-token)))
9859 (cond
9860 ;; js2-XML means we found a {expr} in the XML stream.
9861 ;; The token string is the XML up to the left-curly.
9862 ((= tt js2-XML)
9863 (push (make-js2-string-node :pos (js2-current-token-beg)
9864 :len (- js2-ts-cursor (js2-current-token-beg)))
9865 kids)
9866 (js2-must-match js2-LC "msg.syntax")
9867 (setq expr-pos js2-ts-cursor
9868 expr (if (eq (js2-peek-token) js2-RC)
9869 (make-js2-empty-expr-node :pos expr-pos)
9870 (js2-parse-expr)))
9871 (js2-must-match js2-RC "msg.syntax")
9872 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9873 :len (js2-node-len expr)
9874 :expr expr))
9875 (js2-node-add-children pn expr)
9876 (push pn kids))
9877 ;; a js2-XMLEND token means we hit the final close-tag.
9878 ((= tt js2-XMLEND)
9879 (push (make-js2-string-node :pos (js2-current-token-beg)
9880 :len (- js2-ts-cursor (js2-current-token-beg)))
9881 kids)
9882 (dolist (kid (nreverse kids))
9883 (js2-block-node-push pn-xml kid))
9884 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9885 (js2-node-pos pn-xml))
9886 continue nil))
9887 (t
9888 (js2-report-error "msg.syntax")
9889 (setq continue nil))))
9890 pn-xml))
9891
9892
9893 (defun js2-parse-argument-list ()
9894 "Parse an argument list and return it as a Lisp list of nodes.
9895 Returns the list in reverse order. Consumes the right-paren token."
9896 (let (result)
9897 (unless (js2-match-token js2-RP)
9898 (cl-loop do
9899 (let ((tt (js2-get-token)))
9900 (if (= tt js2-YIELD)
9901 (js2-report-error "msg.yield.parenthesized"))
9902 (if (and (= tt js2-TRIPLEDOT)
9903 (>= js2-language-version 200))
9904 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9905 (js2-unget-token)
9906 (push (js2-parse-assign-expr) result)))
9907 while
9908 (js2-match-token js2-COMMA))
9909 (js2-must-match js2-RP "msg.no.paren.arg")
9910 result)))
9911
9912 (defun js2-parse-member-expr (&optional allow-call-syntax)
9913 (let ((tt (js2-current-token-type))
9914 pn pos target args beg end init)
9915 (if (/= tt js2-NEW)
9916 (setq pn (js2-parse-primary-expr))
9917 ;; parse a 'new' expression
9918 (js2-get-token)
9919 (setq pos (js2-current-token-beg)
9920 beg pos
9921 target (js2-parse-member-expr)
9922 end (js2-node-end target)
9923 pn (make-js2-new-node :pos pos
9924 :target target
9925 :len (- end pos)))
9926 (js2-highlight-function-call (js2-current-token))
9927 (js2-node-add-children pn target)
9928 (when (js2-match-token js2-LP)
9929 ;; Add the arguments to pn, if any are supplied.
9930 (setf beg pos ; start of "new" keyword
9931 pos (js2-current-token-beg)
9932 args (nreverse (js2-parse-argument-list))
9933 (js2-new-node-args pn) args
9934 end (js2-current-token-end)
9935 (js2-new-node-lp pn) (- pos beg)
9936 (js2-new-node-rp pn) (- end 1 beg))
9937 (apply #'js2-node-add-children pn args))
9938 (when (and js2-allow-rhino-new-expr-initializer
9939 (js2-match-token js2-LC))
9940 (setf init (js2-parse-object-literal)
9941 end (js2-node-end init)
9942 (js2-new-node-initializer pn) init)
9943 (js2-node-add-children pn init))
9944 (setf (js2-node-len pn) (- end beg))) ; end outer if
9945 (js2-parse-member-expr-tail allow-call-syntax pn)))
9946
9947 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9948 "Parse a chain of property/array accesses or function calls.
9949 Includes parsing for E4X operators like `..' and `.@'.
9950 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9951 Returns an expression tree that includes PN, the parent node."
9952 (let (tt
9953 (continue t))
9954 (while continue
9955 (setq tt (js2-get-token))
9956 (cond
9957 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9958 (setq pn (js2-parse-property-access tt pn)))
9959 ((= tt js2-DOTQUERY)
9960 (setq pn (js2-parse-dot-query pn)))
9961 ((= tt js2-LB)
9962 (setq pn (js2-parse-element-get pn)))
9963 ((= tt js2-LP)
9964 (js2-unget-token)
9965 (if allow-call-syntax
9966 (setq pn (js2-parse-function-call pn))
9967 (setq continue nil)))
9968 ((= tt js2-TEMPLATE_HEAD)
9969 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9970 ((= tt js2-NO_SUBS_TEMPLATE)
9971 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9972 (t
9973 (js2-unget-token)
9974 (setq continue nil))))
9975 (if (>= js2-highlight-level 2)
9976 (js2-parse-highlight-member-expr-node pn))
9977 pn))
9978
9979 (defun js2-parse-tagged-template (tag-node tpl-node)
9980 "Parse tagged template expression."
9981 (let* ((beg (js2-node-pos tag-node))
9982 (pn (make-js2-tagged-template-node :beg beg
9983 :len (- (js2-current-token-end) beg)
9984 :tag tag-node
9985 :template tpl-node)))
9986 (js2-node-add-children pn tag-node tpl-node)
9987 pn))
9988
9989 (defun js2-parse-dot-query (pn)
9990 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9991 Last token parsed must be `js2-DOTQUERY'."
9992 (let ((pos (js2-node-pos pn))
9993 op-pos expr end)
9994 (js2-must-have-xml)
9995 (js2-set-requires-activation)
9996 (setq op-pos (js2-current-token-beg)
9997 expr (js2-parse-expr)
9998 end (js2-node-end expr)
9999 pn (make-js2-xml-dot-query-node :left pn
10000 :pos pos
10001 :op-pos op-pos
10002 :right expr))
10003 (js2-node-add-children pn
10004 (js2-xml-dot-query-node-left pn)
10005 (js2-xml-dot-query-node-right pn))
10006 (if (js2-must-match js2-RP "msg.no.paren")
10007 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10008 end (js2-current-token-end)))
10009 (setf (js2-node-len pn) (- end pos))
10010 pn))
10011
10012 (defun js2-parse-element-get (pn)
10013 "Parse an element-get expression, e.g. foo[bar].
10014 Last token parsed must be `js2-RB'."
10015 (let ((lb (js2-current-token-beg))
10016 (pos (js2-node-pos pn))
10017 rb expr)
10018 (setq expr (js2-parse-expr))
10019 (if (js2-must-match js2-RB "msg.no.bracket.index")
10020 (setq rb (js2-current-token-beg)))
10021 (setq pn (make-js2-elem-get-node :target pn
10022 :pos pos
10023 :element expr
10024 :lb (js2-relpos lb pos)
10025 :rb (js2-relpos rb pos)
10026 :len (- (js2-current-token-end) pos)))
10027 (js2-node-add-children pn
10028 (js2-elem-get-node-target pn)
10029 (js2-elem-get-node-element pn))
10030 pn))
10031
10032 (defun js2-highlight-function-call (token)
10033 (when (eq (js2-token-type token) js2-NAME)
10034 (js2-record-face 'js2-function-call token)))
10035
10036 (defun js2-parse-function-call (pn)
10037 (js2-highlight-function-call (js2-current-token))
10038 (js2-get-token)
10039 (let (args
10040 (pos (js2-node-pos pn)))
10041 (setq pn (make-js2-call-node :pos pos
10042 :target pn
10043 :lp (- (js2-current-token-beg) pos)))
10044 (js2-node-add-children pn (js2-call-node-target pn))
10045 ;; Add the arguments to pn, if any are supplied.
10046 (setf args (nreverse (js2-parse-argument-list))
10047 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10048 (js2-call-node-args pn) args)
10049 (apply #'js2-node-add-children pn args)
10050 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10051 pn))
10052
10053 (defun js2-parse-property-access (tt pn)
10054 "Parse a property access, XML descendants access, or XML attr access."
10055 (let ((member-type-flags 0)
10056 (dot-pos (js2-current-token-beg))
10057 (dot-len (if (= tt js2-DOTDOT) 2 1))
10058 name
10059 ref ; right side of . or .. operator
10060 result)
10061 (when (= tt js2-DOTDOT)
10062 (js2-must-have-xml)
10063 (setq member-type-flags js2-descendants-flag))
10064 (if (not js2-compiler-xml-available)
10065 (progn
10066 (js2-must-match-prop-name "msg.no.name.after.dot")
10067 (setq name (js2-create-name-node t js2-GETPROP)
10068 result (make-js2-prop-get-node :left pn
10069 :pos (js2-current-token-beg)
10070 :right name
10071 :len (js2-current-token-len)))
10072 (js2-node-add-children result pn name)
10073 result)
10074 ;; otherwise look for XML operators
10075 (setf result (if (= tt js2-DOT)
10076 (make-js2-prop-get-node)
10077 (make-js2-infix-node :type js2-DOTDOT))
10078 (js2-node-pos result) (js2-node-pos pn)
10079 (js2-infix-node-op-pos result) dot-pos
10080 (js2-infix-node-left result) pn ; do this after setting position
10081 tt (js2-get-prop-name-token))
10082 (cond
10083 ;; handles: name, ns::name, ns::*, ns::[expr]
10084 ((= tt js2-NAME)
10085 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10086 ;; handles: *, *::name, *::*, *::[expr]
10087 ((= tt js2-MUL)
10088 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10089 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10090 ((= tt js2-XMLATTR)
10091 (setq result (js2-parse-attribute-access)))
10092 (t
10093 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10094 (if ref
10095 (setf (js2-node-len result) (- (js2-node-end ref)
10096 (js2-node-pos result))
10097 (js2-infix-node-right result) ref))
10098 (if (js2-infix-node-p result)
10099 (js2-node-add-children result
10100 (js2-infix-node-left result)
10101 (js2-infix-node-right result)))
10102 result)))
10103
10104 (defun js2-parse-attribute-access ()
10105 "Parse an E4X XML attribute expression.
10106 This includes expressions of the forms:
10107
10108 @attr @ns::attr @ns::*
10109 @* @*::attr @*::*
10110 @[expr] @*::[expr] @ns::[expr]
10111
10112 Called if we peeked an '@' token."
10113 (let ((tt (js2-get-prop-name-token))
10114 (at-pos (js2-current-token-beg)))
10115 (cond
10116 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10117 ((= tt js2-NAME)
10118 (js2-parse-property-name at-pos nil 0))
10119 ;; handles: @*, @*::name, @*::*, @*::[expr]
10120 ((= tt js2-MUL)
10121 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10122 ;; handles @[expr]
10123 ((= tt js2-LB)
10124 (js2-parse-xml-elem-ref at-pos))
10125 (t
10126 (js2-report-error "msg.no.name.after.xmlAttr")
10127 ;; Avoid cascaded errors that happen if we make an error node here.
10128 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10129
10130 (defun js2-parse-property-name (at-pos s member-type-flags)
10131 "Check if :: follows name in which case it becomes qualified name.
10132
10133 AT-POS is a natural number if we just read an '@' token, else nil.
10134 S is the name or string that was matched: an identifier, 'throw' or '*'.
10135 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10136
10137 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10138 operator, or the name is followed by ::. For a plain name, returns a
10139 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10140 (let ((pos (or at-pos (js2-current-token-beg)))
10141 colon-pos
10142 (name (js2-create-name-node t (js2-current-token-type) s))
10143 ns tt pn)
10144 (catch 'return
10145 (when (js2-match-token js2-COLONCOLON)
10146 (setq ns name
10147 colon-pos (js2-current-token-beg)
10148 tt (js2-get-prop-name-token))
10149 (cond
10150 ;; handles name::name
10151 ((= tt js2-NAME)
10152 (setq name (js2-create-name-node)))
10153 ;; handles name::*
10154 ((= tt js2-MUL)
10155 (setq name (js2-create-name-node nil nil "*")))
10156 ;; handles name::[expr]
10157 ((= tt js2-LB)
10158 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10159 (t
10160 (js2-report-error "msg.no.name.after.coloncolon"))))
10161 (if (and (null ns) (zerop member-type-flags))
10162 name
10163 (prog1
10164 (setq pn
10165 (make-js2-xml-prop-ref-node :pos pos
10166 :len (- (js2-node-end name) pos)
10167 :at-pos at-pos
10168 :colon-pos colon-pos
10169 :propname name))
10170 (js2-node-add-children pn name))))))
10171
10172 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10173 "Parse the [expr] portion of an xml element reference.
10174 For instance, @[expr], @*::[expr], or ns::[expr]."
10175 (let* ((lb (js2-current-token-beg))
10176 (pos (or at-pos lb))
10177 rb
10178 (expr (js2-parse-expr))
10179 (end (js2-node-end expr))
10180 pn)
10181 (if (js2-must-match js2-RB "msg.no.bracket.index")
10182 (setq rb (js2-current-token-beg)
10183 end (js2-current-token-end)))
10184 (prog1
10185 (setq pn
10186 (make-js2-xml-elem-ref-node :pos pos
10187 :len (- end pos)
10188 :namespace namespace
10189 :colon-pos colon-pos
10190 :at-pos at-pos
10191 :expr expr
10192 :lb (js2-relpos lb pos)
10193 :rb (js2-relpos rb pos)))
10194 (js2-node-add-children pn namespace expr))))
10195
10196 (defun js2-parse-destruct-primary-expr ()
10197 (let ((js2-is-in-destructuring t))
10198 (js2-parse-primary-expr)))
10199
10200 (defun js2-parse-primary-expr ()
10201 "Parse a literal (leaf) expression of some sort.
10202 Includes complex literals such as functions, object-literals,
10203 array-literals, array comprehensions and regular expressions."
10204 (let (tt node)
10205 (setq tt (js2-current-token-type))
10206 (cond
10207 ((= tt js2-CLASS)
10208 (js2-parse-class-expr))
10209 ((= tt js2-FUNCTION)
10210 (js2-parse-function-expr))
10211 ((= tt js2-LB)
10212 (js2-parse-array-comp-or-literal))
10213 ((= tt js2-LC)
10214 (js2-parse-object-literal))
10215 ((= tt js2-LET)
10216 (js2-parse-let (js2-current-token-beg)))
10217 ((= tt js2-LP)
10218 (js2-parse-paren-expr-or-generator-comp))
10219 ((= tt js2-XMLATTR)
10220 (js2-must-have-xml)
10221 (js2-parse-attribute-access))
10222 ((= tt js2-NAME)
10223 (js2-parse-name tt))
10224 ((= tt js2-NUMBER)
10225 (setq node (make-js2-number-node))
10226 (when (and js2-in-use-strict-directive
10227 (= (js2-number-node-num-base node) 8))
10228 (js2-report-error "msg.no.octal.strict"))
10229 node)
10230 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10231 (make-js2-string-node :type tt))
10232 ((= tt js2-TEMPLATE_HEAD)
10233 (js2-parse-template-literal))
10234 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10235 ;; Got / or /= which in this context means a regexp literal
10236 (let ((px-pos (js2-current-token-beg))
10237 (flags (js2-read-regexp tt))
10238 (end (js2-current-token-end)))
10239 (prog1
10240 (make-js2-regexp-node :pos px-pos
10241 :len (- end px-pos)
10242 :value (js2-current-token-string)
10243 :flags flags)
10244 (js2-set-face px-pos end 'font-lock-string-face 'record)
10245 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10246 ((or (= tt js2-NULL)
10247 (= tt js2-THIS)
10248 (= tt js2-SUPER)
10249 (= tt js2-FALSE)
10250 (= tt js2-TRUE))
10251 (make-js2-keyword-node :type tt))
10252 ((= tt js2-TRIPLEDOT)
10253 ;; Likewise, only valid in an arrow function with a rest param.
10254 (if (and (js2-match-token js2-NAME)
10255 (js2-match-token js2-RP)
10256 (eq (js2-peek-token) js2-ARROW))
10257 (progn
10258 (js2-unget-token) ; Put back the right paren.
10259 ;; See the previous case.
10260 (make-js2-keyword-node :type js2-NULL))
10261 (js2-report-error "msg.syntax")
10262 (make-js2-error-node)))
10263 ((= tt js2-RESERVED)
10264 (js2-report-error "msg.reserved.id")
10265 (make-js2-name-node))
10266 ((= tt js2-ERROR)
10267 ;; the scanner or one of its subroutines reported the error.
10268 (make-js2-error-node))
10269 ((= tt js2-EOF)
10270 (let* ((px-pos (point-at-bol))
10271 (len (- js2-ts-cursor px-pos)))
10272 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10273 (make-js2-error-node :pos (1- js2-ts-cursor)))
10274 (t
10275 (js2-report-error "msg.syntax")
10276 (make-js2-error-node)))))
10277
10278 (defun js2-parse-template-literal ()
10279 (let ((beg (js2-current-token-beg))
10280 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10281 (tt js2-TEMPLATE_HEAD))
10282 (while (eq tt js2-TEMPLATE_HEAD)
10283 (push (js2-parse-expr) kids)
10284 (js2-must-match js2-RC "msg.syntax")
10285 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10286 (push (make-js2-string-node :type tt) kids))
10287 (setq kids (nreverse kids))
10288 (let ((tpl (make-js2-template-node :beg beg
10289 :len (- (js2-current-token-end) beg)
10290 :kids kids)))
10291 (apply #'js2-node-add-children tpl kids)
10292 tpl)))
10293
10294 (defun js2-parse-name (_tt)
10295 (let ((name (js2-current-token-string))
10296 node)
10297 (setq node (if js2-compiler-xml-available
10298 (js2-parse-property-name nil name 0)
10299 (js2-create-name-node 'check-activation nil name)))
10300 (if js2-highlight-external-variables
10301 (js2-record-name-node node))
10302 node))
10303
10304 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10305 (js2-add-strict-warning
10306 msg nil
10307 ;; back up from comma to beginning of line or array/objlit
10308 (max (if elems
10309 (js2-node-pos (car elems))
10310 pos)
10311 (save-excursion
10312 (goto-char comma-pos)
10313 (back-to-indentation)
10314 (point)))
10315 comma-pos))
10316
10317 (defun js2-parse-array-comp-or-literal ()
10318 (let ((pos (js2-current-token-beg)))
10319 (if (and (>= js2-language-version 200)
10320 (js2-match-token js2-FOR))
10321 (js2-parse-array-comp pos)
10322 (js2-parse-array-literal pos))))
10323
10324 (defun js2-parse-array-literal (pos)
10325 (let ((after-lb-or-comma t)
10326 after-comma tt elems pn
10327 (continue t))
10328 (unless js2-is-in-destructuring
10329 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10330 (while continue
10331 (setq tt (js2-get-token))
10332 (cond
10333 ;; comma
10334 ((= tt js2-COMMA)
10335 (setq after-comma (js2-current-token-end))
10336 (if (not after-lb-or-comma)
10337 (setq after-lb-or-comma t)
10338 (push nil elems)))
10339 ;; end of array
10340 ((or (= tt js2-RB)
10341 (= tt js2-EOF)) ; prevent infinite loop
10342 (if (= tt js2-EOF)
10343 (js2-report-error "msg.no.bracket.arg" nil pos))
10344 (when (and after-comma (< js2-language-version 170))
10345 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10346 pos (remove nil elems) after-comma))
10347 (setq continue nil
10348 pn (make-js2-array-node :pos pos
10349 :len (- js2-ts-cursor pos)
10350 :elems (nreverse elems)))
10351 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10352 ;; destructuring binding
10353 (js2-is-in-destructuring
10354 (push (if (or (= tt js2-LC)
10355 (= tt js2-LB)
10356 (= tt js2-NAME))
10357 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10358 (js2-parse-destruct-primary-expr)
10359 ;; invalid pattern
10360 (js2-report-error "msg.bad.var")
10361 (make-js2-error-node))
10362 elems)
10363 (setq after-lb-or-comma nil
10364 after-comma nil))
10365 ;; array comp
10366 ((and (>= js2-language-version 170)
10367 (= tt js2-FOR) ; check for array comprehension
10368 (not after-lb-or-comma) ; "for" can't follow a comma
10369 elems ; must have at least 1 element
10370 (not (cdr elems))) ; but no 2nd element
10371 (js2-unget-token)
10372 (setf continue nil
10373 pn (js2-parse-legacy-array-comp (car elems) pos)))
10374 ;; another element
10375 (t
10376 (unless after-lb-or-comma
10377 (js2-report-error "msg.no.bracket.arg"))
10378 (if (and (= tt js2-TRIPLEDOT)
10379 (>= js2-language-version 200))
10380 ;; spread operator
10381 (push (js2-make-unary tt 'js2-parse-assign-expr)
10382 elems)
10383 (js2-unget-token)
10384 (push (js2-parse-assign-expr) elems))
10385 (setq after-lb-or-comma nil
10386 after-comma nil))))
10387 (unless js2-is-in-destructuring
10388 (js2-pop-scope))
10389 pn))
10390
10391 (defun js2-parse-legacy-array-comp (expr pos)
10392 "Parse a legacy array comprehension (JavaScript 1.7).
10393 EXPR is the first expression after the opening left-bracket.
10394 POS is the beginning of the LB token preceding EXPR.
10395 We should have just parsed the 'for' keyword before calling this function."
10396 (let ((current-scope js2-current-scope)
10397 loops first filter result)
10398 (unwind-protect
10399 (progn
10400 (while (js2-match-token js2-FOR)
10401 (let ((loop (make-js2-comp-loop-node)))
10402 (js2-push-scope loop)
10403 (push loop loops)
10404 (js2-parse-comp-loop loop)))
10405 ;; First loop takes expr scope's parent.
10406 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10407 (js2-scope-parent-scope current-scope))
10408 ;; Set expr scope's parent to the last loop.
10409 (setf (js2-scope-parent-scope current-scope) (car loops))
10410 (if (/= (js2-get-token) js2-IF)
10411 (js2-unget-token)
10412 (setq filter (js2-parse-condition))))
10413 (dotimes (_ (1- (length loops)))
10414 (js2-pop-scope)))
10415 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10416 (setq result (make-js2-comp-node :pos pos
10417 :len (- js2-ts-cursor pos)
10418 :result expr
10419 :loops (nreverse loops)
10420 :filters (and filter (list (car filter)))
10421 :form 'LEGACY_ARRAY))
10422 ;; Set comp loop's parent to the last loop.
10423 ;; TODO: Get rid of the bogus expr scope.
10424 (setf (js2-scope-parent-scope result) first)
10425 (apply #'js2-node-add-children result expr (car filter)
10426 (js2-comp-node-loops result))
10427 result))
10428
10429 (defun js2-parse-array-comp (pos)
10430 "Parse an ES6 array comprehension.
10431 POS is the beginning of the LB token.
10432 We should have just parsed the 'for' keyword before calling this function."
10433 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10434 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10435 pn))
10436
10437 (defun js2-parse-generator-comp (pos)
10438 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10439 (js2-current-script-or-fn
10440 (make-js2-function-node :generator-type 'COMPREHENSION))
10441 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10442 (js2-must-match js2-RP "msg.no.paren" pos)
10443 pn))
10444
10445 (defun js2-parse-comprehension (pos form)
10446 (let (loops filters expr result last)
10447 (unwind-protect
10448 (progn
10449 (js2-unget-token)
10450 (while (js2-match-token js2-FOR)
10451 (let ((loop (make-js2-comp-loop-node)))
10452 (js2-push-scope loop)
10453 (push loop loops)
10454 (js2-parse-comp-loop loop)))
10455 (while (js2-match-token js2-IF)
10456 (push (car (js2-parse-condition)) filters))
10457 (setq expr (js2-parse-assign-expr))
10458 (setq last (car loops)))
10459 (dolist (_ loops)
10460 (js2-pop-scope)))
10461 (setq result (make-js2-comp-node :pos pos
10462 :len (- js2-ts-cursor pos)
10463 :result expr
10464 :loops (nreverse loops)
10465 :filters (nreverse filters)
10466 :form form))
10467 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10468 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10469 (setf (js2-scope-parent-scope result) last)
10470 result))
10471
10472 (defun js2-parse-comp-loop (pn &optional only-of-p)
10473 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10474 The current token should be the initial FOR.
10475 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10476 (let ((pos (js2-comp-loop-node-pos pn))
10477 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10478 (when (and (not only-of-p) (js2-match-token js2-NAME))
10479 (if (string= (js2-current-token-string) "each")
10480 (progn
10481 (setq foreach-p t
10482 each-pos (- (js2-current-token-beg) pos)) ; relative
10483 (js2-record-face 'font-lock-keyword-face))
10484 (js2-report-error "msg.no.paren.for")))
10485 (if (js2-must-match js2-LP "msg.no.paren.for")
10486 (setq lp (- (js2-current-token-beg) pos)))
10487 (setq tt (js2-peek-token))
10488 (cond
10489 ((or (= tt js2-LB)
10490 (= tt js2-LC))
10491 (js2-get-token)
10492 (setq iter (js2-parse-destruct-primary-expr))
10493 (js2-define-destruct-symbols iter js2-LET
10494 'font-lock-variable-name-face t))
10495 ((js2-match-token js2-NAME)
10496 (setq iter (js2-create-name-node)))
10497 (t
10498 (js2-report-error "msg.bad.var")))
10499 ;; Define as a let since we want the scope of the variable to
10500 ;; be restricted to the array comprehension
10501 (if (js2-name-node-p iter)
10502 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10503 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10504 (and (>= js2-language-version 200)
10505 (js2-match-contextual-kwd "of")
10506 (setq forof-p t)))
10507 (setq in-pos (- (js2-current-token-beg) pos))
10508 (js2-report-error "msg.in.after.for.name"))
10509 (setq obj (js2-parse-expr))
10510 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10511 (setq rp (- (js2-current-token-beg) pos)))
10512 (setf (js2-node-pos pn) pos
10513 (js2-node-len pn) (- js2-ts-cursor pos)
10514 (js2-comp-loop-node-iterator pn) iter
10515 (js2-comp-loop-node-object pn) obj
10516 (js2-comp-loop-node-in-pos pn) in-pos
10517 (js2-comp-loop-node-each-pos pn) each-pos
10518 (js2-comp-loop-node-foreach-p pn) foreach-p
10519 (js2-comp-loop-node-forof-p pn) forof-p
10520 (js2-comp-loop-node-lp pn) lp
10521 (js2-comp-loop-node-rp pn) rp)
10522 (js2-node-add-children pn iter obj)
10523 pn))
10524
10525 (defun js2-parse-class-stmt ()
10526 (let ((pos (js2-current-token-beg))
10527 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10528 (name (js2-create-name-node t)))
10529 (js2-set-face (js2-node-pos name) (js2-node-end name)
10530 'font-lock-function-name-face 'record)
10531 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10532 (js2-define-symbol js2-FUNCTION
10533 (js2-name-node-name name)
10534 node)
10535 node)))
10536
10537 (defun js2-parse-class-expr ()
10538 (let ((pos (js2-current-token-beg))
10539 name)
10540 (when (js2-match-token js2-NAME)
10541 (setq name (js2-create-name-node t)))
10542 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10543
10544 (defun js2-parse-class (pos form name)
10545 ;; class X [extends ...] {
10546 (let (pn elems extends)
10547 (if (js2-match-token js2-EXTENDS)
10548 (if (= (js2-peek-token) js2-LC)
10549 (js2-report-error "msg.missing.extends")
10550 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10551 (setq extends (js2-parse-assign-expr))
10552 (if (not extends)
10553 (js2-report-error "msg.bad.extends"))))
10554 (js2-must-match js2-LC "msg.no.brace.class")
10555 (setq elems (js2-parse-object-literal-elems t)
10556 pn (make-js2-class-node :pos pos
10557 :len (- js2-ts-cursor pos)
10558 :form form
10559 :name name
10560 :extends extends
10561 :elems elems))
10562 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10563 pn))
10564
10565 (defun js2-parse-object-literal ()
10566 (let* ((pos (js2-current-token-beg))
10567 (elems (js2-parse-object-literal-elems))
10568 (result (make-js2-object-node :pos pos
10569 :len (- js2-ts-cursor pos)
10570 :elems elems)))
10571 (apply #'js2-node-add-children result (js2-object-node-elems result))
10572 result))
10573
10574 (defun js2-property-key-string (property-node)
10575 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10576 `js2-getter-setter-node') as a string, or nil if it can't be
10577 represented as a string (e.g., the key is computed by an
10578 expression)."
10579 (let ((key (js2-infix-node-left property-node)))
10580 (cond
10581 ((js2-name-node-p key)
10582 (js2-name-node-name key))
10583 ((js2-string-node-p key)
10584 (js2-string-node-value key))
10585 ((js2-number-node-p key)
10586 (js2-number-node-value key)))))
10587
10588 (defun js2-parse-object-literal-elems (&optional class-p)
10589 (let ((pos (js2-current-token-beg))
10590 (static nil)
10591 (continue t)
10592 tt elems elem
10593 elem-key-string previous-elem-key-string
10594 after-comma previous-token)
10595 (while continue
10596 (setq tt (js2-get-prop-name-token)
10597 static nil
10598 elem nil
10599 previous-token nil)
10600 ;; Handle 'static' keyword only if we're in a class
10601 (when (and class-p (= js2-NAME tt)
10602 (string= "static" (js2-current-token-string)))
10603 (js2-record-face 'font-lock-keyword-face)
10604 (setq static t
10605 tt (js2-get-prop-name-token)))
10606 ;; Handle generator * before the property name for in-line functions
10607 (when (and (>= js2-language-version 200)
10608 (= js2-MUL tt))
10609 (setq previous-token (js2-current-token)
10610 tt (js2-get-prop-name-token)))
10611 ;; Handle 'get' or 'set' keywords
10612 (let ((prop (js2-current-token-string)))
10613 (when (and (>= js2-language-version 200)
10614 (= js2-NAME tt)
10615 (or (string= prop "get")
10616 (string= prop "set"))
10617 (member (js2-peek-token)
10618 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10619 (setq previous-token (js2-current-token)
10620 tt (js2-get-prop-name-token))))
10621 (cond
10622 ;; Found a property (of any sort)
10623 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10624 (setq after-comma nil
10625 elem (js2-parse-named-prop tt pos previous-token))
10626 (if (and (null elem)
10627 (not js2-recover-from-parse-errors))
10628 (setq continue nil)))
10629 ;; Break out of loop, and handle trailing commas.
10630 ((or (= tt js2-RC)
10631 (= tt js2-EOF))
10632 (js2-unget-token)
10633 (setq continue nil)
10634 (if after-comma
10635 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10636 pos elems after-comma)))
10637 (t
10638 (js2-report-error "msg.bad.prop")
10639 (unless js2-recover-from-parse-errors
10640 (setq continue nil)))) ; end switch
10641 ;; Handle static for classes' codegen.
10642 (if static
10643 (if elem (js2-node-set-prop elem 'STATIC t)
10644 (js2-report-error "msg.unexpected.static")))
10645 ;; Handle commas, depending on class-p.
10646 (let ((tok (js2-get-prop-name-token)))
10647 (if (eq tok js2-COMMA)
10648 (if class-p
10649 (js2-report-error "msg.class.unexpected.comma")
10650 (setq after-comma (js2-current-token-end)))
10651 (js2-unget-token)
10652 (unless class-p (setq continue nil))))
10653 (when elem
10654 (when (and js2-in-use-strict-directive
10655 (setq elem-key-string (js2-property-key-string elem))
10656 (cl-some
10657 (lambda (previous-elem)
10658 (and (setq previous-elem-key-string
10659 (js2-property-key-string previous-elem))
10660 (string= previous-elem-key-string elem-key-string)))
10661 elems))
10662 (js2-report-error "msg.dup.obj.lit.prop.strict"
10663 elem-key-string
10664 (js2-node-abs-pos (js2-infix-node-left elem))
10665 (js2-node-len (js2-infix-node-left elem))))
10666 ;; Append any parsed element.
10667 (push elem elems))) ; end loop
10668 (js2-must-match js2-RC "msg.no.brace.prop")
10669 (nreverse elems)))
10670
10671 (defun js2-parse-named-prop (tt pos previous-token)
10672 "Parse a name, string, or getter/setter object property.
10673 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10674 (let ((key (cond
10675 ;; Literal string keys: {'foo': 'bar'}
10676 ((= tt js2-STRING)
10677 (make-js2-string-node))
10678 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10679 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10680 ((and (= tt js2-LB)
10681 (>= js2-language-version 200))
10682 (prog1 (js2-parse-expr)
10683 (js2-must-match js2-RB "msg.missing.computed.rb")))
10684 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10685 ((= tt js2-NUMBER)
10686 (make-js2-number-node))
10687 ;; Unquoted names: {foo: 12}
10688 ((= tt js2-NAME)
10689 (js2-create-name-node))
10690 ;; Anything else is an error
10691 (t (js2-report-error "msg.bad.prop"))))
10692 (prop (and previous-token (js2-token-string previous-token)))
10693 (property-type (when previous-token
10694 (if (= (js2-token-type previous-token) js2-MUL)
10695 "*"
10696 (js2-token-string previous-token)))))
10697 (when (or (string= prop "get")
10698 (string= prop "set"))
10699 (js2-set-face (js2-token-beg previous-token)
10700 (js2-token-end previous-token)
10701 'font-lock-keyword-face 'record)) ; get/set
10702 (cond
10703 ;; method definition: {f() {...}}
10704 ((and (= (js2-peek-token) js2-LP)
10705 (>= js2-language-version 200))
10706 (when (js2-name-node-p key) ; highlight function name properties
10707 (js2-record-face 'font-lock-function-name-face))
10708 (js2-parse-getter-setter-prop pos key property-type))
10709 ;; regular prop
10710 (t
10711 (let ((beg (js2-current-token-beg))
10712 (end (js2-current-token-end))
10713 (expr (js2-parse-plain-property key)))
10714 (when (and (= tt js2-NAME)
10715 (not js2-is-in-destructuring)
10716 js2-highlight-external-variables
10717 (js2-node-get-prop expr 'SHORTHAND))
10718 (js2-record-name-node key))
10719 (js2-set-face beg end
10720 (if (js2-function-node-p
10721 (js2-object-prop-node-right expr))
10722 'font-lock-function-name-face
10723 'font-lock-variable-name-face)
10724 'record)
10725 expr)))))
10726
10727 (defun js2-parse-plain-property (prop)
10728 "Parse a non-getter/setter property in an object literal.
10729 PROP is the node representing the property: a number, name,
10730 string or expression."
10731 (let* ((tt (js2-get-token))
10732 (pos (js2-node-pos prop))
10733 colon expr result)
10734 (cond
10735 ;; Abbreviated property, as in {foo, bar}
10736 ((and (>= js2-language-version 200)
10737 (or (= tt js2-COMMA)
10738 (= tt js2-RC))
10739 (not (js2-number-node-p prop)))
10740 (js2-unget-token)
10741 (setq result (make-js2-object-prop-node
10742 :pos pos
10743 :left prop
10744 :right prop
10745 :op-pos (js2-current-token-len)))
10746 (js2-node-add-children result prop)
10747 (js2-node-set-prop result 'SHORTHAND t)
10748 result)
10749 ;; Normal property
10750 (t
10751 (if (= tt js2-COLON)
10752 (setq colon (- (js2-current-token-beg) pos)
10753 expr (js2-parse-assign-expr))
10754 (js2-report-error "msg.no.colon.prop")
10755 (setq expr (make-js2-error-node)))
10756 (setq result (make-js2-object-prop-node
10757 :pos pos
10758 ;; don't include last consumed token in length
10759 :len (- (+ (js2-node-pos expr)
10760 (js2-node-len expr))
10761 pos)
10762 :left prop
10763 :right expr
10764 :op-pos colon))
10765 (js2-node-add-children result prop expr)
10766 result))))
10767
10768 (defun js2-parse-getter-setter-prop (pos prop type-string)
10769 "Parse getter or setter property in an object literal.
10770 JavaScript syntax is:
10771
10772 { get foo() {...}, set foo(x) {...} }
10773
10774 and expression closure style is also supported
10775
10776 { get foo() x, set foo(x) _x = x }
10777
10778 POS is the start position of the `get' or `set' keyword.
10779 PROP is the `js2-name-node' representing the property name.
10780 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10781 (let ((type (cond
10782 ((string= "get" type-string) js2-GET)
10783 ((string= "set" type-string) js2-SET)
10784 (t js2-FUNCTION)))
10785 result end
10786 (fn (js2-parse-function-expr)))
10787 ;; it has to be an anonymous function, as we already parsed the name
10788 (if (/= (js2-node-type fn) js2-FUNCTION)
10789 (js2-report-error "msg.bad.prop")
10790 (if (cl-plusp (length (js2-function-name fn)))
10791 (js2-report-error "msg.bad.prop")))
10792 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10793 (when (string= type-string "*")
10794 (setf (js2-function-node-generator-type fn) 'STAR))
10795 (setq end (js2-node-end fn)
10796 result (make-js2-getter-setter-node :type type
10797 :pos pos
10798 :len (- end pos)
10799 :left prop
10800 :right fn))
10801 (js2-node-add-children result prop fn)
10802 result))
10803
10804 (defun js2-create-name-node (&optional check-activation-p token string)
10805 "Create a name node using the current token and, optionally, STRING.
10806 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10807 (let* ((beg (js2-current-token-beg))
10808 (tt (js2-current-token-type))
10809 (s (or string
10810 (if (= js2-NAME tt)
10811 (js2-current-token-string)
10812 (js2-tt-name tt))))
10813 name)
10814 (setq name (make-js2-name-node :pos beg
10815 :name s
10816 :len (length s)))
10817 (if check-activation-p
10818 (js2-check-activation-name s (or token js2-NAME)))
10819 name))
10820
10821 ;;; Indentation support (bouncing)
10822
10823 ;; In recent-enough Emacs, we reuse the indentation code from
10824 ;; `js-mode'. To continue support for the older versions, some code
10825 ;; that was here previously was moved to `js2-old-indent.el'.
10826
10827 ;; Whichever indenter is used, it's often "wrong", however, and needs
10828 ;; to be overridden. The right long-term solution is probably to
10829 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
10830 ;; of coding. Even when a parse tree from `js2-parse' is present,
10831 ;; which is not true at the moment the user is typing, computing
10832 ;; indentation is still thousands of lines of code to handle every
10833 ;; possible syntactic edge case.
10834
10835 ;; In the meantime, the compromise solution is that we offer a "bounce
10836 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10837 ;; current line indent among various likely guess points. This approach
10838 ;; is far from perfect, but should at least make it slightly easier to
10839 ;; move the line towards its desired indentation when manually
10840 ;; overriding Karl's heuristic nesting guesser.
10841
10842 (defun js2-backward-sws ()
10843 "Move backward through whitespace and comments."
10844 (interactive)
10845 (while (forward-comment -1)))
10846
10847 (defun js2-forward-sws ()
10848 "Move forward through whitespace and comments."
10849 (interactive)
10850 (while (forward-comment 1)))
10851
10852 (defun js2-arglist-close ()
10853 "Return non-nil if we're on a line beginning with a close-paren/brace."
10854 (save-excursion
10855 (goto-char (point-at-bol))
10856 (js2-forward-sws)
10857 (looking-at "[])}]")))
10858
10859 (defun js2-indent-looks-like-label-p ()
10860 (goto-char (point-at-bol))
10861 (js2-forward-sws)
10862 (looking-at (concat js2-mode-identifier-re ":")))
10863
10864 (defun js2-indent-in-objlit-p (parse-status)
10865 "Return non-nil if this looks like an object-literal entry."
10866 (let ((start (nth 1 parse-status)))
10867 (and
10868 start
10869 (save-excursion
10870 (and (zerop (forward-line -1))
10871 (not (< (point) start)) ; crossed a {} boundary
10872 (js2-indent-looks-like-label-p)))
10873 (save-excursion
10874 (js2-indent-looks-like-label-p)))))
10875
10876 ;; If prev line looks like foobar({ then we're passing an object
10877 ;; literal to a function call, and people pretty much always want to
10878 ;; de-dent back to the previous line, so move the 'basic-offset'
10879 ;; position to the front.
10880 (defun js2-indent-objlit-arg-p (parse-status)
10881 (save-excursion
10882 (back-to-indentation)
10883 (js2-backward-sws)
10884 (and (eq (1- (point)) (nth 1 parse-status))
10885 (eq (char-before) ?{)
10886 (progn
10887 (forward-char -1)
10888 (skip-chars-backward " \t")
10889 (eq (char-before) ?\()))))
10890
10891 (defun js2-indent-case-block-p ()
10892 (save-excursion
10893 (back-to-indentation)
10894 (js2-backward-sws)
10895 (goto-char (point-at-bol))
10896 (skip-chars-forward " \t")
10897 (looking-at "case\\s-.+:")))
10898
10899 (defun js2-bounce-indent (normal-col parse-status &optional backward)
10900 "Cycle among alternate computed indentation positions.
10901 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10902 of the buffer to the current point. NORMAL-COL is the indentation
10903 column computed by the heuristic guesser based on current paren,
10904 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10905 in reverse."
10906 (let ((cur-indent (current-indentation))
10907 (old-buffer-undo-list buffer-undo-list)
10908 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10909 (current-line (save-excursion
10910 (forward-line 0) ; move to bol
10911 (1+ (count-lines (point-min) (point)))))
10912 positions pos main-pos anchor arglist-cont same-indent
10913 basic-offset computed-pos)
10914 ;; temporarily don't record undo info, if user requested this
10915 (when js2-mode-indent-inhibit-undo
10916 (setq buffer-undo-list t))
10917 (unwind-protect
10918 (progn
10919 ;; First likely point: indent from beginning of previous code line
10920 (push (setq basic-offset
10921 (+ (save-excursion
10922 (back-to-indentation)
10923 (js2-backward-sws)
10924 (back-to-indentation)
10925 (current-column))
10926 js2-basic-offset))
10927 positions)
10928
10929 ;; (First + epsilon) likely point: indent 2x from beginning of
10930 ;; previous code line. Google does it this way.
10931 (push (setq basic-offset
10932 (+ (save-excursion
10933 (back-to-indentation)
10934 (js2-backward-sws)
10935 (back-to-indentation)
10936 (current-column))
10937 (* 2 js2-basic-offset)))
10938 positions)
10939
10940 ;; Second likely point: indent from assign-expr RHS. This
10941 ;; is just a crude guess based on finding " = " on the previous
10942 ;; line containing actual code.
10943 (setq pos (save-excursion
10944 (forward-line -1)
10945 (goto-char (point-at-bol))
10946 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10947 (point-at-eol) t)
10948 (goto-char (match-end 1))
10949 (skip-chars-forward " \t\r\n")
10950 (current-column))))
10951 (when pos
10952 (cl-incf pos js2-basic-offset)
10953 (push pos positions))
10954
10955 ;; Third likely point: same indent as previous line of code.
10956 ;; Make it the first likely point if we're not on an
10957 ;; arglist-close line and previous line ends in a comma, or
10958 ;; both this line and prev line look like object-literal
10959 ;; elements.
10960 (setq pos (save-excursion
10961 (goto-char (point-at-bol))
10962 (js2-backward-sws)
10963 (back-to-indentation)
10964 (prog1
10965 (current-column)
10966 ;; while we're here, look for trailing comma
10967 (if (save-excursion
10968 (goto-char (point-at-eol))
10969 (js2-backward-sws)
10970 (eq (char-before) ?,))
10971 (setq arglist-cont (1- (point)))))))
10972 (when pos
10973 (if (and (or arglist-cont
10974 (js2-indent-in-objlit-p parse-status))
10975 (not (js2-arglist-close)))
10976 (setq same-indent pos))
10977 (push pos positions))
10978
10979 ;; Fourth likely point: first preceding code with less indentation.
10980 ;; than the immediately preceding code line.
10981 (setq pos (save-excursion
10982 (back-to-indentation)
10983 (js2-backward-sws)
10984 (back-to-indentation)
10985 (setq anchor (current-column))
10986 (while (and (zerop (forward-line -1))
10987 (>= (progn
10988 (back-to-indentation)
10989 (current-column))
10990 anchor)))
10991 (setq pos (current-column))))
10992 (push pos positions)
10993
10994 ;; nesting-heuristic position, main by default
10995 (push (setq main-pos normal-col) positions)
10996
10997 ;; delete duplicates and sort positions list
10998 (setq positions (sort (delete-dups positions) '<))
10999
11000 ;; comma-list continuation lines: prev line indent takes precedence
11001 (if same-indent
11002 (setq main-pos same-indent))
11003
11004 ;; common special cases where we want to indent in from previous line
11005 (if (or (js2-indent-case-block-p)
11006 (js2-indent-objlit-arg-p parse-status))
11007 (setq main-pos basic-offset))
11008
11009 ;; if bouncing backward, reverse positions list
11010 (if backward
11011 (setq positions (reverse positions)))
11012
11013 ;; record whether we're already sitting on one of the alternatives
11014 (setq pos (member cur-indent positions))
11015
11016 (cond
11017 ;; case 0: we're one one of the alternatives and this is the
11018 ;; first time they've pressed TAB on this line (best-guess).
11019 ((and js2-mode-indent-ignore-first-tab
11020 pos
11021 ;; first time pressing TAB on this line?
11022 (not (eq js2-mode-last-indented-line current-line)))
11023 ;; do nothing
11024 (setq computed-pos nil))
11025 ;; case 1: only one computed position => use it
11026 ((null (cdr positions))
11027 (setq computed-pos 0))
11028 ;; case 2: not on any of the computed spots => use main spot
11029 ((not pos)
11030 (setq computed-pos (js2-position main-pos positions)))
11031 ;; case 3: on last position: cycle to first position
11032 ((null (cdr pos))
11033 (setq computed-pos 0))
11034 ;; case 4: on intermediate position: cycle to next position
11035 (t
11036 (setq computed-pos (js2-position (cl-second pos) positions))))
11037
11038 ;; see if any hooks want to indent; otherwise we do it
11039 (cl-loop with result = nil
11040 for hook in js2-indent-hook
11041 while (null result)
11042 do
11043 (setq result (funcall hook positions computed-pos))
11044 finally do
11045 (unless (or result (null computed-pos))
11046 (indent-line-to (nth computed-pos positions)))))
11047
11048 ;; finally
11049 (if js2-mode-indent-inhibit-undo
11050 (setq buffer-undo-list old-buffer-undo-list))
11051 ;; see commentary for `js2-mode-last-indented-line'
11052 (setq js2-mode-last-indented-line current-line))))
11053
11054 (defun js2-1-line-comment-continuation-p ()
11055 "Return t if we're in a 1-line comment continuation.
11056 If so, we don't ever want to use bounce-indent."
11057 (save-excursion
11058 (and (progn
11059 (forward-line 0)
11060 (looking-at "\\s-*//"))
11061 (progn
11062 (forward-line -1)
11063 (forward-line 0)
11064 (when (looking-at "\\s-*$")
11065 (js2-backward-sws)
11066 (forward-line 0))
11067 (looking-at "\\s-*//")))))
11068
11069 (defun js2-indent-bounce (&optional backward)
11070 "Indent the current line, bouncing between several positions."
11071 (interactive)
11072 (let (parse-status offset indent-col
11073 ;; Don't whine about errors/warnings when we're indenting.
11074 ;; This has to be set before calling parse-partial-sexp below.
11075 (inhibit-point-motion-hooks t))
11076 (setq parse-status (save-excursion
11077 (syntax-ppss (point-at-bol)))
11078 offset (- (point) (save-excursion
11079 (back-to-indentation)
11080 (point))))
11081 ;; Don't touch multiline strings.
11082 (unless (nth 3 parse-status)
11083 (setq indent-col (js2-proper-indentation parse-status))
11084 (cond
11085 ;; It doesn't work well on first line of buffer.
11086 ((and (not (nth 4 parse-status))
11087 (not (js2-same-line (point-min)))
11088 (not (js2-1-line-comment-continuation-p)))
11089 (js2-bounce-indent indent-col parse-status backward))
11090 ;; just indent to the guesser's likely spot
11091 (t (indent-line-to indent-col)))
11092 (when (cl-plusp offset)
11093 (forward-char offset)))))
11094
11095 (defun js2-indent-bounce-backward ()
11096 "Indent the current line, bouncing between positions in reverse."
11097 (interactive)
11098 (js2-indent-bounce t))
11099
11100 (defun js2-indent-region (start end)
11101 "Indent the region, but don't use bounce indenting."
11102 (let ((js2-bounce-indent-p nil)
11103 (indent-region-function nil)
11104 (after-change-functions (remq 'js2-mode-edit
11105 after-change-functions)))
11106 (indent-region start end nil) ; nil for byte-compiler
11107 (js2-mode-edit start end (- end start))))
11108
11109 (defvar js2-minor-mode-map
11110 (let ((map (make-sparse-keymap)))
11111 (define-key map (kbd "C-c C-`") #'js2-next-error)
11112 (define-key map [mouse-1] #'js2-mode-show-node)
11113 map)
11114 "Keymap used when `js2-minor-mode' is active.")
11115
11116 ;;;###autoload
11117 (define-minor-mode js2-minor-mode
11118 "Minor mode for running js2 as a background linter.
11119 This allows you to use a different major mode for JavaScript editing,
11120 such as `js-mode', while retaining the asynchronous error/warning
11121 highlighting features of `js2-mode'."
11122 :group 'js2-mode
11123 :lighter " js-lint"
11124 (if (derived-mode-p 'js2-mode)
11125 (setq js2-minor-mode nil)
11126 (if js2-minor-mode
11127 (js2-minor-mode-enter)
11128 (js2-minor-mode-exit))))
11129
11130 (defun js2-minor-mode-enter ()
11131 "Initialization for `js2-minor-mode'."
11132 (set (make-local-variable 'max-lisp-eval-depth)
11133 (max max-lisp-eval-depth 3000))
11134 (setq next-error-function #'js2-next-error)
11135 (js2-set-default-externs)
11136 ;; Experiment: make reparse-delay longer for longer files.
11137 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11138 (setq js2-idle-timer-delay
11139 (* js2-idle-timer-delay
11140 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11141 (setq js2-mode-buffer-dirty-p t
11142 js2-mode-parsing nil)
11143 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11144 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11145 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11146 (when js2-include-jslint-globals
11147 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11148 (run-hooks 'js2-init-hook)
11149 (js2-reparse))
11150
11151 (defun js2-minor-mode-exit ()
11152 "Turn off `js2-minor-mode'."
11153 (setq next-error-function nil)
11154 (remove-hook 'after-change-functions #'js2-mode-edit t)
11155 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11156 (when js2-mode-node-overlay
11157 (delete-overlay js2-mode-node-overlay)
11158 (setq js2-mode-node-overlay nil))
11159 (js2-remove-overlays)
11160 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11161 (setq js2-mode-ast nil))
11162
11163 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11164 (make-variable-buffer-local 'js2-source-buffer)
11165
11166 (cl-defun js2-display-error-list ()
11167 "Display a navigable buffer listing parse errors/warnings."
11168 (interactive)
11169 (unless (js2-have-errors-p)
11170 (message "No errors")
11171 (cl-return-from js2-display-error-list))
11172 (cl-labels ((annotate-list
11173 (lst type)
11174 "Add diagnostic TYPE and line number to errs list"
11175 (mapcar (lambda (err)
11176 (list err type (line-number-at-pos (nth 1 err))))
11177 lst)))
11178 (let* ((srcbuf (current-buffer))
11179 (errbuf (get-buffer-create "*js-lint*"))
11180 (errors (annotate-list
11181 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11182 'js2-error)) ; must be a valid face name
11183 (warnings (annotate-list
11184 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11185 'js2-warning)) ; must be a valid face name
11186 (all-errs (sort (append errors warnings)
11187 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11188 (with-current-buffer errbuf
11189 (let ((inhibit-read-only t))
11190 (erase-buffer)
11191 (dolist (err all-errs)
11192 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11193 (insert-text-button
11194 (format "line %d: %s" line (js2-get-msg msg-key))
11195 'face type
11196 'follow-link "\C-m"
11197 'action 'js2-error-buffer-jump
11198 'js2-msg (js2-get-msg msg-key)
11199 'js2-pos beg)
11200 (insert "\n"))))
11201 (js2-error-buffer-mode)
11202 (setq js2-source-buffer srcbuf)
11203 (pop-to-buffer errbuf)
11204 (goto-char (point-min))
11205 (unless (eobp)
11206 (js2-error-buffer-view))))))
11207
11208 (defvar js2-error-buffer-mode-map
11209 (let ((map (make-sparse-keymap)))
11210 (define-key map "n" #'js2-error-buffer-next)
11211 (define-key map "p" #'js2-error-buffer-prev)
11212 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11213 (define-key map "o" #'js2-error-buffer-view)
11214 (define-key map "q" #'js2-error-buffer-quit)
11215 map)
11216 "Keymap used for js2 diagnostics buffers.")
11217
11218 (defun js2-error-buffer-mode ()
11219 "Major mode for js2 diagnostics buffers.
11220 Selecting an error will jump it to the corresponding source-buffer error.
11221 \\{js2-error-buffer-mode-map}"
11222 (interactive)
11223 (setq major-mode 'js2-error-buffer-mode
11224 mode-name "JS Lint Diagnostics")
11225 (use-local-map js2-error-buffer-mode-map)
11226 (setq truncate-lines t)
11227 (set-buffer-modified-p nil)
11228 (setq buffer-read-only t)
11229 (run-hooks 'js2-error-buffer-mode-hook))
11230
11231 (defun js2-error-buffer-next ()
11232 "Move to next error and view it."
11233 (interactive)
11234 (when (zerop (forward-line 1))
11235 (js2-error-buffer-view)))
11236
11237 (defun js2-error-buffer-prev ()
11238 "Move to previous error and view it."
11239 (interactive)
11240 (when (zerop (forward-line -1))
11241 (js2-error-buffer-view)))
11242
11243 (defun js2-error-buffer-quit ()
11244 "Kill the current buffer."
11245 (interactive)
11246 (kill-buffer))
11247
11248 (defun js2-error-buffer-jump (&rest ignored)
11249 "Jump cursor to current error in source buffer."
11250 (interactive)
11251 (when (js2-error-buffer-view)
11252 (pop-to-buffer js2-source-buffer)))
11253
11254 (defun js2-error-buffer-view ()
11255 "Scroll source buffer to show error at current line."
11256 (interactive)
11257 (cond
11258 ((not (eq major-mode 'js2-error-buffer-mode))
11259 (message "Not in a js2 errors buffer"))
11260 ((not (buffer-live-p js2-source-buffer))
11261 (message "Source buffer has been killed"))
11262 ((not (wholenump (get-text-property (point) 'js2-pos)))
11263 (message "There does not seem to be an error here"))
11264 (t
11265 (let ((pos (get-text-property (point) 'js2-pos))
11266 (msg (get-text-property (point) 'js2-msg)))
11267 (save-selected-window
11268 (pop-to-buffer js2-source-buffer)
11269 (goto-char pos)
11270 (message msg))))))
11271
11272 ;;;###autoload
11273 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11274 "Major mode for editing JavaScript code."
11275 (set (make-local-variable 'max-lisp-eval-depth)
11276 (max max-lisp-eval-depth 3000))
11277 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11278 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11279 (set (make-local-variable 'syntax-propertize-function) nil)
11280 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11281 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11282 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11283 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11284 ;; for characters inside regexp literals.
11285 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11286 ;; this is necessary to make `show-paren-function' work properly
11287 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11288 ;; needed for M-x rgrep, among other things
11289 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11290
11291 (setq font-lock-defaults '(nil t))
11292
11293 ;; Experiment: make reparse-delay longer for longer files.
11294 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11295 (setq js2-idle-timer-delay
11296 (* js2-idle-timer-delay
11297 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11298
11299 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11300 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11301 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11302 (setq next-error-function #'js2-next-error)
11303 (imenu-add-to-menubar (concat "IM-" mode-name))
11304 (add-to-invisibility-spec '(js2-outline . t))
11305 (set (make-local-variable 'line-move-ignore-invisible) t)
11306 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11307 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11308
11309 (setq js2-mode-functions-hidden nil
11310 js2-mode-comments-hidden nil
11311 js2-mode-buffer-dirty-p t
11312 js2-mode-parsing nil)
11313
11314 (js2-set-default-externs)
11315
11316 (when js2-include-jslint-globals
11317 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11318
11319 (run-hooks 'js2-init-hook)
11320
11321 (js2-reparse))
11322
11323 (defun js2-mode-exit ()
11324 "Exit `js2-mode' and clean up."
11325 (interactive)
11326 (when js2-mode-node-overlay
11327 (delete-overlay js2-mode-node-overlay)
11328 (setq js2-mode-node-overlay nil))
11329 (js2-remove-overlays)
11330 (setq js2-mode-ast nil)
11331 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11332 (remove-from-invisibility-spec '(js2-outline . t))
11333 (js2-mode-show-all)
11334 (with-silent-modifications
11335 (js2-clear-face (point-min) (point-max))))
11336
11337 (defun js2-mode-reset-timer ()
11338 "Cancel any existing parse timer and schedule a new one."
11339 (if js2-mode-parse-timer
11340 (cancel-timer js2-mode-parse-timer))
11341 (setq js2-mode-parsing nil)
11342 (let ((timer (timer-create)))
11343 (setq js2-mode-parse-timer timer)
11344 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11345 (timer-set-idle-time timer js2-idle-timer-delay)
11346 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11347 (timer-activate-when-idle timer nil)))
11348
11349 (defun js2-mode-idle-reparse (buffer)
11350 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11351 it to be reparsed when the buffer is selected."
11352 (cond ((eq buffer (current-buffer))
11353 (js2-reparse))
11354 ((buffer-live-p buffer)
11355 ;; reparse when the buffer is selected again
11356 (with-current-buffer buffer
11357 (add-hook 'window-configuration-change-hook
11358 #'js2-mode-idle-reparse-inner
11359 nil t)))))
11360
11361 (defun js2-mode-idle-reparse-inner ()
11362 (remove-hook 'window-configuration-change-hook
11363 #'js2-mode-idle-reparse-inner
11364 t)
11365 (js2-reparse))
11366
11367 (defun js2-mode-edit (_beg _end _len)
11368 "Schedule a new parse after buffer is edited.
11369 Buffer edit spans from BEG to END and is of length LEN."
11370 (setq js2-mode-buffer-dirty-p t)
11371 (js2-mode-hide-overlay)
11372 (js2-mode-reset-timer))
11373
11374 (defun js2-minor-mode-edit (_beg _end _len)
11375 "Callback for buffer edits in `js2-mode'.
11376 Schedules a new parse after buffer is edited.
11377 Buffer edit spans from BEG to END and is of length LEN."
11378 (setq js2-mode-buffer-dirty-p t)
11379 (js2-mode-hide-overlay)
11380 (js2-mode-reset-timer))
11381
11382 (defun js2-reparse (&optional force)
11383 "Re-parse current buffer after user finishes some data entry.
11384 If we get any user input while parsing, including cursor motion,
11385 we discard the parse and reschedule it. If FORCE is nil, then the
11386 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11387 (let (time
11388 interrupted-p
11389 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11390 (unless js2-mode-parsing
11391 (setq js2-mode-parsing t)
11392 (unwind-protect
11393 (when (or js2-mode-buffer-dirty-p force)
11394 (js2-remove-overlays)
11395 (setq js2-mode-buffer-dirty-p nil
11396 js2-mode-fontifications nil
11397 js2-mode-deferred-properties nil)
11398 (if js2-mode-verbose-parse-p
11399 (message "parsing..."))
11400 (setq time
11401 (js2-time
11402 (setq interrupted-p
11403 (catch 'interrupted
11404 (js2-parse)
11405 (with-silent-modifications
11406 ;; if parsing is interrupted, comments and regex
11407 ;; literals stay ignored by `parse-partial-sexp'
11408 (remove-text-properties (point-min) (point-max)
11409 '(syntax-table))
11410 (js2-mode-apply-deferred-properties)
11411 (js2-mode-remove-suppressed-warnings)
11412 (js2-mode-show-warnings)
11413 (js2-mode-show-errors)
11414 (if (>= js2-highlight-level 1)
11415 (js2-highlight-jsdoc js2-mode-ast)))
11416 nil))))
11417 (if interrupted-p
11418 (progn
11419 ;; unfinished parse => try again
11420 (setq js2-mode-buffer-dirty-p t)
11421 (js2-mode-reset-timer))
11422 (if js2-mode-verbose-parse-p
11423 (message "Parse time: %s" time))))
11424 (setq js2-mode-parsing nil)
11425 (unless interrupted-p
11426 (setq js2-mode-parse-timer nil))))))
11427
11428 (defun js2-mode-show-node (event)
11429 "Debugging aid: highlight selected AST node on mouse click."
11430 (interactive "e")
11431 (mouse-set-point event)
11432 (setq deactivate-mark t)
11433 (when js2-mode-show-overlay
11434 (let ((node (js2-node-at-point))
11435 beg end)
11436 (if (null node)
11437 (message "No node found at location %s" (point))
11438 (setq beg (js2-node-abs-pos node)
11439 end (+ beg (js2-node-len node)))
11440 (if js2-mode-node-overlay
11441 (move-overlay js2-mode-node-overlay beg end)
11442 (setq js2-mode-node-overlay (make-overlay beg end))
11443 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11444 (with-silent-modifications
11445 (if (fboundp 'cursor-sensor-mode)
11446 (put-text-property beg end 'cursor-sensor-functions
11447 '(js2-mode-hide-overlay))
11448 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11449 (message "%s, parent: %s"
11450 (js2-node-short-name node)
11451 (if (js2-node-parent node)
11452 (js2-node-short-name (js2-node-parent node))
11453 "nil"))))))
11454
11455 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11456 "Remove the debugging overlay when point moves.
11457 ARG1, ARG2 and ARG3 have different values depending on whether this function
11458 was found on `point-left' or in `cursor-sensor-functions'."
11459 (when js2-mode-node-overlay
11460 (let ((beg (overlay-start js2-mode-node-overlay))
11461 (end (overlay-end js2-mode-node-overlay))
11462 (p2 (if (windowp arg1)
11463 ;; Called from cursor-sensor-functions.
11464 (window-point arg1)
11465 ;; Called from point-left.
11466 arg2)))
11467 ;; Sometimes we're called spuriously.
11468 (unless (and p2
11469 (>= p2 beg)
11470 (<= p2 end))
11471 (with-silent-modifications
11472 (remove-text-properties beg end
11473 '(point-left nil cursor-sensor-functions)))
11474 (delete-overlay js2-mode-node-overlay)
11475 (setq js2-mode-node-overlay nil)))))
11476
11477 (defun js2-mode-reset ()
11478 "Debugging helper: reset everything."
11479 (interactive)
11480 (js2-mode-exit)
11481 (js2-mode))
11482
11483 (defun js2-mode-show-warn-or-err (e face)
11484 "Highlight a warning or error E with FACE.
11485 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11486 The last element is optional. When present, use instead of FACE."
11487 (let* ((key (cl-first e))
11488 (beg (cl-second e))
11489 (end (+ beg (cl-third e)))
11490 ;; Don't inadvertently go out of bounds.
11491 (beg (max (point-min) (min beg (point-max))))
11492 (end (max (point-min) (min end (point-max))))
11493 (ovl (make-overlay beg end)))
11494 ;; FIXME: Why a mix of overlays and text-properties?
11495 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11496 (overlay-put ovl 'js2-error t)
11497 (put-text-property beg end 'help-echo (js2-get-msg key))
11498 (if (fboundp 'cursor-sensor-mode)
11499 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11500 (put-text-property beg end 'point-entered #'js2-echo-error))))
11501
11502 (defun js2-remove-overlays ()
11503 "Remove overlays from buffer that have a `js2-error' property."
11504 (let ((beg (point-min))
11505 (end (point-max)))
11506 (save-excursion
11507 (dolist (o (overlays-in beg end))
11508 (when (overlay-get o 'js2-error)
11509 (delete-overlay o))))))
11510
11511 (defun js2-mode-apply-deferred-properties ()
11512 "Apply fontifications and other text properties recorded during parsing."
11513 (when (cl-plusp js2-highlight-level)
11514 ;; We defer clearing faces as long as possible to eliminate flashing.
11515 (js2-clear-face (point-min) (point-max))
11516 ;; Have to reverse the recorded fontifications list so that errors
11517 ;; and warnings overwrite the normal fontifications.
11518 (dolist (f (nreverse js2-mode-fontifications))
11519 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11520 (setq js2-mode-fontifications nil))
11521 (dolist (p js2-mode-deferred-properties)
11522 (apply #'put-text-property p))
11523 (setq js2-mode-deferred-properties nil))
11524
11525 (defun js2-mode-show-errors ()
11526 "Highlight syntax errors."
11527 (when js2-mode-show-parse-errors
11528 (dolist (e (js2-ast-root-errors js2-mode-ast))
11529 (js2-mode-show-warn-or-err e 'js2-error))))
11530
11531 (defun js2-mode-remove-suppressed-warnings ()
11532 "Take suppressed warnings out of the AST warnings list.
11533 This ensures that the counts and `next-error' are correct."
11534 (setf (js2-ast-root-warnings js2-mode-ast)
11535 (js2-delete-if
11536 (lambda (e)
11537 (let ((key (caar e)))
11538 (or
11539 (and (not js2-strict-trailing-comma-warning)
11540 (string-match "trailing\\.comma" key))
11541 (and (not js2-strict-cond-assign-warning)
11542 (string= key "msg.equal.as.assign"))
11543 (and js2-missing-semi-one-line-override
11544 (string= key "msg.missing.semi")
11545 (let* ((beg (cl-second e))
11546 (node (js2-node-at-point beg))
11547 (fn (js2-mode-find-parent-fn node))
11548 (body (and fn (js2-function-node-body fn)))
11549 (lc (and body (js2-node-abs-pos body)))
11550 (rc (and lc (+ lc (js2-node-len body)))))
11551 (and fn
11552 (or (null body)
11553 (save-excursion
11554 (goto-char beg)
11555 (and (js2-same-line lc)
11556 (js2-same-line rc))))))))))
11557 (js2-ast-root-warnings js2-mode-ast))))
11558
11559 (defun js2-mode-show-warnings ()
11560 "Highlight strict-mode warnings."
11561 (when js2-mode-show-strict-warnings
11562 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11563 (js2-mode-show-warn-or-err e 'js2-warning))))
11564
11565 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11566 "Called by point-motion hooks.
11567 ARG1, ARG2 and ARG3 have different values depending on whether this function
11568 was found on `point-entered' or in `cursor-sensor-functions'."
11569 (let* ((new-point (if (windowp arg1)
11570 ;; Called from cursor-sensor-functions.
11571 (window-point arg1)
11572 ;; Called from point-left.
11573 arg2))
11574 (msg (get-text-property new-point 'help-echo)))
11575 (when (and (stringp msg)
11576 (not (active-minibuffer-window))
11577 (not (current-message)))
11578 (message msg))))
11579
11580 (defun js2-line-break (&optional _soft)
11581 "Break line at point and indent, continuing comment if within one.
11582 If inside a string, and `js2-concat-multiline-strings' is not
11583 nil, turn it into concatenation."
11584 (interactive)
11585 (let ((parse-status (syntax-ppss)))
11586 (cond
11587 ;; Check if we're inside a string.
11588 ((nth 3 parse-status)
11589 (if js2-concat-multiline-strings
11590 (js2-mode-split-string parse-status)
11591 (insert "\n")))
11592 ;; Check if inside a block comment.
11593 ((nth 4 parse-status)
11594 (js2-mode-extend-comment (nth 8 parse-status)))
11595 (t
11596 (newline-and-indent)))))
11597
11598 (defun js2-mode-split-string (parse-status)
11599 "Turn a newline in mid-string into a string concatenation.
11600 PARSE-STATUS is as documented in `parse-partial-sexp'."
11601 (let* ((quote-char (nth 3 parse-status))
11602 (at-eol (eq js2-concat-multiline-strings 'eol)))
11603 (insert quote-char)
11604 (insert (if at-eol " +\n" "\n"))
11605 (unless at-eol
11606 (insert "+ "))
11607 (js2-indent-line)
11608 (insert quote-char)
11609 (when (eolp)
11610 (insert quote-char)
11611 (backward-char 1))))
11612
11613 (defun js2-mode-extend-comment (start-pos)
11614 "Indent the line and, when inside a comment block, add comment prefix."
11615 (let (star single col first-line needs-close)
11616 (save-excursion
11617 (back-to-indentation)
11618 (when (< (point) start-pos)
11619 (goto-char start-pos))
11620 (cond
11621 ((looking-at "\\*[^/]")
11622 (setq star t
11623 col (current-column)))
11624 ((looking-at "/\\*")
11625 (setq star t
11626 first-line t
11627 col (1+ (current-column))))
11628 ((looking-at "//")
11629 (setq single t
11630 col (current-column)))))
11631 ;; Heuristic for whether we need to close the comment:
11632 ;; if we've got a parse error here, assume it's an unterminated
11633 ;; comment.
11634 (setq needs-close
11635 (or
11636 (get-char-property (1- (point)) 'js2-error)
11637 ;; The heuristic above doesn't work well when we're
11638 ;; creating a comment and there's another one downstream,
11639 ;; as our parser thinks this one ends at the end of the
11640 ;; next one. (You can have a /* inside a js block comment.)
11641 ;; So just close it if the next non-ws char isn't a *.
11642 (and first-line
11643 (eolp)
11644 (save-excursion
11645 (skip-chars-forward " \t\r\n")
11646 (not (eq (char-after) ?*))))))
11647 (delete-horizontal-space)
11648 (insert "\n")
11649 (cond
11650 (star
11651 (indent-to col)
11652 (insert "* ")
11653 (if (and first-line needs-close)
11654 (save-excursion
11655 (insert "\n")
11656 (indent-to col)
11657 (insert "*/"))))
11658 ((and single
11659 (save-excursion
11660 (and (zerop (forward-line 1))
11661 (looking-at "\\s-*//"))))
11662 (indent-to col)
11663 (insert "// ")))
11664 ;; Don't need to extend the comment after all.
11665 (js2-indent-line)))
11666
11667 (defun js2-beginning-of-line ()
11668 "Toggle point between bol and first non-whitespace char in line.
11669 Also moves past comment delimiters when inside comments."
11670 (interactive)
11671 (let (node)
11672 (cond
11673 ((bolp)
11674 (back-to-indentation))
11675 ((looking-at "//")
11676 (skip-chars-forward "/ \t"))
11677 ((and (eq (char-after) ?*)
11678 (setq node (js2-comment-at-point))
11679 (memq (js2-comment-node-format node) '(jsdoc block))
11680 (save-excursion
11681 (skip-chars-backward " \t")
11682 (bolp)))
11683 (skip-chars-forward "\* \t"))
11684 (t
11685 (goto-char (point-at-bol))))))
11686
11687 (defun js2-end-of-line ()
11688 "Toggle point between eol and last non-whitespace char in line."
11689 (interactive)
11690 (if (eolp)
11691 (skip-chars-backward " \t")
11692 (goto-char (point-at-eol))))
11693
11694 (defun js2-mode-wait-for-parse (callback)
11695 "Invoke CALLBACK when parsing is finished.
11696 If parsing is already finished, calls CALLBACK immediately."
11697 (if (not js2-mode-buffer-dirty-p)
11698 (funcall callback)
11699 (push callback js2-mode-pending-parse-callbacks)
11700 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11701
11702 (defun js2-mode-parse-finished ()
11703 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11704 ;; We can't let errors propagate up, since it prevents the
11705 ;; `js2-parse' method from completing normally and returning
11706 ;; the ast, which makes things mysteriously not work right.
11707 (unwind-protect
11708 (dolist (cb js2-mode-pending-parse-callbacks)
11709 (condition-case err
11710 (funcall cb)
11711 (error (message "%s" err))))
11712 (setq js2-mode-pending-parse-callbacks nil)))
11713
11714 (defun js2-mode-flag-region (from to flag)
11715 "Hide or show text from FROM to TO, according to FLAG.
11716 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11717 Returns the created overlay if FLAG is non-nil."
11718 (remove-overlays from to 'invisible 'js2-outline)
11719 (when flag
11720 (let ((o (make-overlay from to)))
11721 (overlay-put o 'invisible 'js2-outline)
11722 (overlay-put o 'isearch-open-invisible
11723 'js2-isearch-open-invisible)
11724 o)))
11725
11726 ;; Function to be set as an outline-isearch-open-invisible' property
11727 ;; to the overlay that makes the outline invisible (see
11728 ;; `js2-mode-flag-region').
11729 (defun js2-isearch-open-invisible (_overlay)
11730 ;; We rely on the fact that isearch places point on the matched text.
11731 (js2-mode-show-element))
11732
11733 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11734 "Return cons cell of bounds of folding overlay at POS.
11735 Returns nil if not found."
11736 (let ((overlays (overlays-at (or pos (point))))
11737 o)
11738 (while (and overlays
11739 (not o))
11740 (if (overlay-get (car overlays) 'invisible)
11741 (setq o (car overlays))
11742 (setq overlays (cdr overlays))))
11743 (if o
11744 (cons (overlay-start o) (overlay-end o)))))
11745
11746 (defun js2-mode-function-at-point (&optional pos)
11747 "Return the innermost function node enclosing current point.
11748 Returns nil if point is not in a function."
11749 (let ((node (js2-node-at-point pos)))
11750 (while (and node (not (js2-function-node-p node)))
11751 (setq node (js2-node-parent node)))
11752 (if (js2-function-node-p node)
11753 node)))
11754
11755 (defun js2-mode-toggle-element ()
11756 "Hide or show the foldable element at the point."
11757 (interactive)
11758 (let (comment fn pos)
11759 (save-excursion
11760 (cond
11761 ;; /* ... */ comment?
11762 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11763 (if (js2-mode-invisible-overlay-bounds
11764 (setq pos (+ 3 (js2-node-abs-pos comment))))
11765 (progn
11766 (goto-char pos)
11767 (js2-mode-show-element))
11768 (js2-mode-hide-element)))
11769 ;; //-comment?
11770 ((save-excursion
11771 (back-to-indentation)
11772 (looking-at js2-mode-//-comment-re))
11773 (js2-mode-toggle-//-comment))
11774 ;; function?
11775 ((setq fn (js2-mode-function-at-point))
11776 (setq pos (and (js2-function-node-body fn)
11777 (js2-node-abs-pos (js2-function-node-body fn))))
11778 (goto-char (1+ pos))
11779 (if (js2-mode-invisible-overlay-bounds)
11780 (js2-mode-show-element)
11781 (js2-mode-hide-element)))
11782 (t
11783 (message "Nothing at point to hide or show"))))))
11784
11785 (defun js2-mode-hide-element ()
11786 "Fold/hide contents of a block, showing ellipses.
11787 Show the hidden text with \\[js2-mode-show-element]."
11788 (interactive)
11789 (if js2-mode-buffer-dirty-p
11790 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11791 (let (node body beg end)
11792 (cond
11793 ((js2-mode-invisible-overlay-bounds)
11794 (message "already hidden"))
11795 (t
11796 (setq node (js2-node-at-point))
11797 (cond
11798 ((js2-block-comment-p node)
11799 (js2-mode-hide-comment node))
11800 (t
11801 (while (and node (not (js2-function-node-p node)))
11802 (setq node (js2-node-parent node)))
11803 (if (and node
11804 (setq body (js2-function-node-body node)))
11805 (progn
11806 (setq beg (js2-node-abs-pos body)
11807 end (+ beg (js2-node-len body)))
11808 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11809 (message "No collapsable element found at point"))))))))
11810
11811 (defun js2-mode-show-element ()
11812 "Show the hidden element at current point."
11813 (interactive)
11814 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11815 (if bounds
11816 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11817 (message "Nothing to un-hide"))))
11818
11819 (defun js2-mode-show-all ()
11820 "Show all of the text in the buffer."
11821 (interactive)
11822 (js2-mode-flag-region (point-min) (point-max) nil))
11823
11824 (defun js2-mode-toggle-hide-functions ()
11825 (interactive)
11826 (if js2-mode-functions-hidden
11827 (js2-mode-show-functions)
11828 (js2-mode-hide-functions)))
11829
11830 (defun js2-mode-hide-functions ()
11831 "Hides all non-nested function bodies in the buffer.
11832 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11833 to open an individual entry."
11834 (interactive)
11835 (if js2-mode-buffer-dirty-p
11836 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11837 (if (null js2-mode-ast)
11838 (message "Oops - parsing failed")
11839 (setq js2-mode-functions-hidden t)
11840 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11841
11842 (defun js2-mode-function-hider (n endp)
11843 (when (not endp)
11844 (let ((tt (js2-node-type n))
11845 body beg end)
11846 (cond
11847 ((and (= tt js2-FUNCTION)
11848 (setq body (js2-function-node-body n)))
11849 (setq beg (js2-node-abs-pos body)
11850 end (+ beg (js2-node-len body)))
11851 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11852 nil) ; don't process children of function
11853 (t
11854 t))))) ; keep processing other AST nodes
11855
11856 (defun js2-mode-show-functions ()
11857 "Un-hide any folded function bodies in the buffer."
11858 (interactive)
11859 (setq js2-mode-functions-hidden nil)
11860 (save-excursion
11861 (goto-char (point-min))
11862 (while (/= (goto-char (next-overlay-change (point)))
11863 (point-max))
11864 (dolist (o (overlays-at (point)))
11865 (when (and (overlay-get o 'invisible)
11866 (not (overlay-get o 'comment)))
11867 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11868
11869 (defun js2-mode-hide-comment (n)
11870 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11871 3 ; /**
11872 2)) ; /*
11873 (beg (+ (js2-node-abs-pos n) head))
11874 (end (- (+ beg (js2-node-len n)) head 2))
11875 (o (js2-mode-flag-region beg end 'hide)))
11876 (overlay-put o 'comment t)))
11877
11878 (defun js2-mode-toggle-hide-comments ()
11879 "Folds all block comments in the buffer.
11880 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11881 to open an individual entry."
11882 (interactive)
11883 (if js2-mode-comments-hidden
11884 (js2-mode-show-comments)
11885 (js2-mode-hide-comments)))
11886
11887 (defun js2-mode-hide-comments ()
11888 (interactive)
11889 (if js2-mode-buffer-dirty-p
11890 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11891 (if (null js2-mode-ast)
11892 (message "Oops - parsing failed")
11893 (setq js2-mode-comments-hidden t)
11894 (dolist (n (js2-ast-root-comments js2-mode-ast))
11895 (when (js2-block-comment-p n)
11896 (js2-mode-hide-comment n)))
11897 (js2-mode-hide-//-comments)))
11898
11899 (defun js2-mode-extend-//-comment (direction)
11900 "Find start or end of a block of similar //-comment lines.
11901 DIRECTION is -1 to look back, 1 to look forward.
11902 INDENT is the indentation level to match.
11903 Returns the end-of-line position of the furthest adjacent
11904 //-comment line with the same indentation as the current line.
11905 If there is no such matching line, returns current end of line."
11906 (let ((pos (point-at-eol))
11907 (indent (current-indentation)))
11908 (save-excursion
11909 (while (and (zerop (forward-line direction))
11910 (looking-at js2-mode-//-comment-re)
11911 (eq indent (length (match-string 1))))
11912 (setq pos (point-at-eol)))
11913 pos)))
11914
11915 (defun js2-mode-hide-//-comments ()
11916 "Fold adjacent 1-line comments, showing only snippet of first one."
11917 (let (beg end)
11918 (save-excursion
11919 (goto-char (point-min))
11920 (while (re-search-forward js2-mode-//-comment-re nil t)
11921 (setq beg (point)
11922 end (js2-mode-extend-//-comment 1))
11923 (unless (eq beg end)
11924 (overlay-put (js2-mode-flag-region beg end 'hide)
11925 'comment t))
11926 (goto-char end)
11927 (forward-char 1)))))
11928
11929 (defun js2-mode-toggle-//-comment ()
11930 "Fold or un-fold any multi-line //-comment at point.
11931 Caller should have determined that this line starts with a //-comment."
11932 (let* ((beg (point-at-eol))
11933 (end beg))
11934 (save-excursion
11935 (goto-char end)
11936 (if (js2-mode-invisible-overlay-bounds)
11937 (js2-mode-show-element)
11938 ;; else hide the comment
11939 (setq beg (js2-mode-extend-//-comment -1)
11940 end (js2-mode-extend-//-comment 1))
11941 (unless (eq beg end)
11942 (overlay-put (js2-mode-flag-region beg end 'hide)
11943 'comment t))))))
11944
11945 (defun js2-mode-show-comments ()
11946 "Un-hide any hidden comments, leaving other hidden elements alone."
11947 (interactive)
11948 (setq js2-mode-comments-hidden nil)
11949 (save-excursion
11950 (goto-char (point-min))
11951 (while (/= (goto-char (next-overlay-change (point)))
11952 (point-max))
11953 (dolist (o (overlays-at (point)))
11954 (when (overlay-get o 'comment)
11955 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11956
11957 (defun js2-mode-display-warnings-and-errors ()
11958 "Turn on display of warnings and errors."
11959 (interactive)
11960 (setq js2-mode-show-parse-errors t
11961 js2-mode-show-strict-warnings t)
11962 (js2-reparse 'force))
11963
11964 (defun js2-mode-hide-warnings-and-errors ()
11965 "Turn off display of warnings and errors."
11966 (interactive)
11967 (setq js2-mode-show-parse-errors nil
11968 js2-mode-show-strict-warnings nil)
11969 (js2-reparse 'force))
11970
11971 (defun js2-mode-toggle-warnings-and-errors ()
11972 "Toggle the display of warnings and errors.
11973 Some users don't like having warnings/errors reported while they type."
11974 (interactive)
11975 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11976 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11977 (if (called-interactively-p 'any)
11978 (message "warnings and errors %s"
11979 (if js2-mode-show-parse-errors
11980 "enabled"
11981 "disabled")))
11982 (js2-reparse 'force))
11983
11984 (defun js2-mode-customize ()
11985 (interactive)
11986 (customize-group 'js2-mode))
11987
11988 (defun js2-mode-forward-sexp (&optional arg)
11989 "Move forward across one statement or balanced expression.
11990 With ARG, do it that many times. Negative arg -N means
11991 move backward across N balanced expressions."
11992 (interactive "p")
11993 (setq arg (or arg 1))
11994 (save-restriction
11995 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11996 (js2-reparse)
11997 (let (forward-sexp-function
11998 node (start (point)) pos lp rp child)
11999 (cond
12000 ;; backward-sexp
12001 ;; could probably make this better for some cases:
12002 ;; - if in statement block (e.g. function body), go to parent
12003 ;; - infix exprs like (foo in bar) - maybe go to beginning
12004 ;; of infix expr if in the right-side expression?
12005 ((and arg (cl-minusp arg))
12006 (dotimes (_ (- arg))
12007 (js2-backward-sws)
12008 (forward-char -1) ; Enter the node we backed up to.
12009 (when (setq node (js2-node-at-point (point) t))
12010 (setq pos (js2-node-abs-pos node))
12011 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12012 (setq lp (car parens)
12013 rp (cdr parens)))
12014 (when (and lp (> start lp))
12015 (if (and rp (<= start rp))
12016 ;; Between parens, check if there's a child node we can jump.
12017 (when (setq child (js2-node-closest-child node (point) lp t))
12018 (setq pos (js2-node-abs-pos child)))
12019 ;; Before both parens.
12020 (setq pos lp)))
12021 (let ((state (parse-partial-sexp start pos)))
12022 (goto-char (if (not (zerop (car state)))
12023 ;; Stumble at the unbalanced paren if < 0, or
12024 ;; jump a bit further if > 0.
12025 (scan-sexps start -1)
12026 pos))))
12027 (unless pos (goto-char (point-min)))))
12028 (t
12029 ;; forward-sexp
12030 (dotimes (_ arg)
12031 (js2-forward-sws)
12032 (when (setq node (js2-node-at-point (point) t))
12033 (setq pos (js2-node-abs-pos node))
12034 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12035 (setq lp (car parens)
12036 rp (cdr parens)))
12037 (or
12038 (when (and rp (<= start rp))
12039 (if (> start lp)
12040 (when (setq child (js2-node-closest-child node (point) rp))
12041 (setq pos (js2-node-abs-end child)))
12042 (setq pos (1+ rp))))
12043 ;; No parens or child nodes, looks for the end of the current node.
12044 (cl-incf pos (js2-node-len
12045 (if (js2-expr-stmt-node-p (js2-node-parent node))
12046 ;; Stop after the semicolon.
12047 (js2-node-parent node)
12048 node))))
12049 (let ((state (save-excursion (parse-partial-sexp start pos))))
12050 (goto-char (if (not (zerop (car state)))
12051 (scan-sexps start 1)
12052 pos))))
12053 (unless pos (goto-char (point-max)))))))))
12054
12055 (defun js2-mode-forward-sexp-parens (node abs-pos)
12056 "Return a cons cell with positions of main parens in NODE."
12057 (cond
12058 ((or (js2-array-node-p node)
12059 (js2-object-node-p node)
12060 (js2-comp-node-p node)
12061 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12062 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12063 ((js2-paren-expr-node-p node)
12064 (let ((lp (js2-node-lp node))
12065 (rp (js2-node-rp node)))
12066 (cons (when lp (+ abs-pos lp))
12067 (when rp (+ abs-pos rp)))))))
12068
12069 (defun js2-node-closest-child (parent point limit &optional before)
12070 (let* ((parent-pos (js2-node-abs-pos parent))
12071 (rpoint (- point parent-pos))
12072 (rlimit (- limit parent-pos))
12073 (min (min rpoint rlimit))
12074 (max (max rpoint rlimit))
12075 found)
12076 (catch 'done
12077 (js2-visit-ast
12078 parent
12079 (lambda (node _end-p)
12080 (if (eq node parent)
12081 t
12082 (let ((pos (js2-node-pos node)) ;; Both relative values.
12083 (end (+ (js2-node-pos node) (js2-node-len node))))
12084 (when (and (>= pos min) (<= end max)
12085 (if before (< pos rpoint) (> end rpoint)))
12086 (setq found node))
12087 (when (> end rpoint)
12088 (throw 'done nil)))
12089 nil))))
12090 found))
12091
12092 (defun js2-errors ()
12093 "Return a list of errors found."
12094 (and js2-mode-ast
12095 (js2-ast-root-errors js2-mode-ast)))
12096
12097 (defun js2-warnings ()
12098 "Return a list of warnings found."
12099 (and js2-mode-ast
12100 (js2-ast-root-warnings js2-mode-ast)))
12101
12102 (defun js2-have-errors-p ()
12103 "Return non-nil if any parse errors or warnings were found."
12104 (or (js2-errors) (js2-warnings)))
12105
12106 (defun js2-errors-and-warnings ()
12107 "Return a copy of the concatenated errors and warnings lists.
12108 They are appended: first the errors, then the warnings.
12109 Entries are of the form (MSG BEG END)."
12110 (when js2-mode-ast
12111 (append (js2-ast-root-errors js2-mode-ast)
12112 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12113
12114 (defun js2-next-error (&optional arg reset)
12115 "Move to next parse error.
12116 Typically invoked via \\[next-error].
12117 ARG is the number of errors, forward or backward, to move.
12118 RESET means start over from the beginning."
12119 (interactive "p")
12120 (if (not (or (js2-errors) (js2-warnings)))
12121 (message "No errors")
12122 (when reset
12123 (goto-char (point-min)))
12124 (let* ((errs (js2-errors-and-warnings))
12125 (continue t)
12126 (start (point))
12127 (count (or arg 1))
12128 (backward (cl-minusp count))
12129 (sorter (if backward '> '<))
12130 (stopper (if backward '< '>))
12131 (count (abs count))
12132 all-errs err)
12133 ;; Sort by start position.
12134 (setq errs (sort errs (lambda (e1 e2)
12135 (funcall sorter (cl-second e1) (cl-second e2))))
12136 all-errs errs)
12137 ;; Find nth error with pos > start.
12138 (while (and errs continue)
12139 (when (funcall stopper (cl-cadar errs) start)
12140 (setq err (car errs))
12141 (if (zerop (cl-decf count))
12142 (setq continue nil)))
12143 (setq errs (cdr errs)))
12144 ;; Clear for `js2-echo-error'.
12145 (message nil)
12146 (if err
12147 (goto-char (cl-second err))
12148 ;; Wrap around to first error.
12149 (goto-char (cl-second (car all-errs)))
12150 ;; If we were already on it, echo msg again.
12151 (if (= (point) start)
12152 (js2-echo-error (point) (point)))))))
12153
12154 (defun js2-down-mouse-3 ()
12155 "Make right-click move the point to the click location.
12156 This makes right-click context menu operations a bit more intuitive.
12157 The point will not move if the region is active, however, to avoid
12158 destroying the region selection."
12159 (interactive)
12160 (when (and js2-move-point-on-right-click
12161 (not mark-active))
12162 (let ((e last-input-event))
12163 (ignore-errors
12164 (goto-char (cl-cadadr e))))))
12165
12166 (defun js2-mode-create-imenu-index ()
12167 "Return an alist for `imenu--index-alist'."
12168 ;; This is built up in `js2-parse-record-imenu' during parsing.
12169 (when js2-mode-ast
12170 ;; if we have an ast but no recorder, they're requesting a rescan
12171 (unless js2-imenu-recorder
12172 (js2-reparse 'force))
12173 (prog1
12174 (js2-build-imenu-index)
12175 (setq js2-imenu-recorder nil
12176 js2-imenu-function-map nil))))
12177
12178 (defun js2-mode-find-tag ()
12179 "Replacement for `find-tag-default'.
12180 `find-tag-default' returns a ridiculous answer inside comments."
12181 (let (beg end)
12182 (save-excursion
12183 (if (looking-at "\\_>")
12184 (setq beg (progn (forward-symbol -1) (point))
12185 end (progn (forward-symbol 1) (point)))
12186 (setq beg (progn (forward-symbol 1) (point))
12187 end (progn (forward-symbol -1) (point))))
12188 (replace-regexp-in-string
12189 "[\"']" ""
12190 (buffer-substring-no-properties beg end)))))
12191
12192 (defun js2-mode-forward-sibling ()
12193 "Move to the end of the sibling following point in parent.
12194 Returns non-nil if successful, or nil if there was no following sibling."
12195 (let* ((node (js2-node-at-point))
12196 (parent (js2-mode-find-enclosing-fn node))
12197 sib)
12198 (when (setq sib (js2-node-find-child-after (point) parent))
12199 (goto-char (+ (js2-node-abs-pos sib)
12200 (js2-node-len sib))))))
12201
12202 (defun js2-mode-backward-sibling ()
12203 "Move to the beginning of the sibling node preceding point in parent.
12204 Parent is defined as the enclosing script or function."
12205 (let* ((node (js2-node-at-point))
12206 (parent (js2-mode-find-enclosing-fn node))
12207 sib)
12208 (when (setq sib (js2-node-find-child-before (point) parent))
12209 (goto-char (js2-node-abs-pos sib)))))
12210
12211 (defun js2-beginning-of-defun (&optional arg)
12212 "Go to line on which current function starts, and return t on success.
12213 If we're not in a function or already at the beginning of one, go
12214 to beginning of previous script-level element.
12215 With ARG N, do that N times. If N is negative, move forward."
12216 (setq arg (or arg 1))
12217 (if (cl-plusp arg)
12218 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12219 (when (cond
12220 ((js2-function-node-p parent)
12221 (goto-char (js2-node-abs-pos parent)))
12222 (t
12223 (js2-mode-backward-sibling)))
12224 (if (> arg 1)
12225 (js2-beginning-of-defun (1- arg))
12226 t)))
12227 (when (js2-end-of-defun)
12228 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12229
12230 (defun js2-end-of-defun ()
12231 "Go to the char after the last position of the current function
12232 or script-level element."
12233 (let* ((node (js2-node-at-point))
12234 (parent (or (and (js2-function-node-p node) node)
12235 (js2-node-parent-script-or-fn node)))
12236 script)
12237 (unless (js2-function-node-p parent)
12238 ;; Use current script-level node, or, if none, the next one.
12239 (setq script (or parent node)
12240 parent (js2-node-find-child-before (point) script))
12241 (when (or (null parent)
12242 (>= (point) (+ (js2-node-abs-pos parent)
12243 (js2-node-len parent))))
12244 (setq parent (js2-node-find-child-after (point) script))))
12245 (when parent
12246 (goto-char (+ (js2-node-abs-pos parent)
12247 (js2-node-len parent))))))
12248
12249 (defun js2-mark-defun (&optional allow-extend)
12250 "Put mark at end of this function, point at beginning.
12251 The function marked is the one that contains point.
12252
12253 Interactively, if this command is repeated,
12254 or (in Transient Mark mode) if the mark is active,
12255 it marks the next defun after the ones already marked."
12256 (interactive "p")
12257 (let (extended)
12258 (when (and allow-extend
12259 (or (and (eq last-command this-command) (mark t))
12260 (and transient-mark-mode mark-active)))
12261 (let ((sib (save-excursion
12262 (goto-char (mark))
12263 (if (js2-mode-forward-sibling)
12264 (point)))))
12265 (if sib
12266 (progn
12267 (set-mark sib)
12268 (setq extended t))
12269 ;; no more siblings - try extending to enclosing node
12270 (goto-char (mark t)))))
12271 (when (not extended)
12272 (let ((node (js2-node-at-point (point) t)) ; skip comments
12273 ast fn stmt parent beg end)
12274 (when (js2-ast-root-p node)
12275 (setq ast node
12276 node (or (js2-node-find-child-after (point) node)
12277 (js2-node-find-child-before (point) node))))
12278 ;; only mark whole buffer if we can't find any children
12279 (if (null node)
12280 (setq node ast))
12281 (if (js2-function-node-p node)
12282 (setq parent node)
12283 (setq fn (js2-mode-find-enclosing-fn node)
12284 stmt (if (or (null fn)
12285 (js2-ast-root-p fn))
12286 (js2-mode-find-first-stmt node))
12287 parent (or stmt fn)))
12288 (setq beg (js2-node-abs-pos parent)
12289 end (+ beg (js2-node-len parent)))
12290 (push-mark beg)
12291 (goto-char end)
12292 (exchange-point-and-mark)))))
12293
12294 (defun js2-narrow-to-defun ()
12295 "Narrow to the function enclosing point."
12296 (interactive)
12297 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12298 (fn (if (js2-script-node-p node)
12299 node
12300 (js2-mode-find-enclosing-fn node)))
12301 (beg (js2-node-abs-pos fn)))
12302 (unless (js2-ast-root-p fn)
12303 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12304
12305 (provide 'js2-mode)
12306
12307 ;;; js2-mode.el ends here