]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode/js2-mode.el
Merge commit '212c8fc3101781a2f1c55ca61772eb75a2046e87' from company
[gnu-emacs-elpa] / packages / js2-mode / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20150909
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; 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 (require 'etags)
92
93 (eval-and-compile
94 (if (version< emacs-version "25.0")
95 (require 'js2-old-indent)
96 (defvaralias 'js2-basic-offset 'js-indent-level nil)
97 (defalias 'js2-proper-indentation 'js--proper-indentation)
98 (defalias 'js2-indent-line 'js-indent-line)
99 (defalias 'js2-re-search-forward 'js--re-search-forward)))
100
101 ;;; Externs (variables presumed to be defined by the host system)
102
103 (defvar js2-ecma-262-externs
104 (mapcar 'symbol-name
105 '(Array Boolean Date Error EvalError Function Infinity JSON
106 Math NaN Number Object RangeError ReferenceError RegExp
107 String SyntaxError TypeError URIError
108 decodeURI decodeURIComponent encodeURI
109 encodeURIComponent escape eval isFinite isNaN
110 parseFloat parseInt undefined unescape))
111 "Ecma-262 externs. Included in `js2-externs' by default.")
112
113 (defvar js2-browser-externs
114 (mapcar 'symbol-name
115 '(;; DOM level 1
116 Attr CDATASection CharacterData Comment DOMException
117 DOMImplementation Document DocumentFragment
118 DocumentType Element Entity EntityReference
119 ExceptionCode NamedNodeMap Node NodeList Notation
120 ProcessingInstruction Text
121
122 ;; DOM level 2
123 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
124 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
125 HTMLBodyElement HTMLButtonElement HTMLCollection
126 HTMLDListElement HTMLDirectoryElement HTMLDivElement
127 HTMLDocument HTMLElement HTMLFieldSetElement
128 HTMLFontElement HTMLFormElement HTMLFrameElement
129 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
130 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
131 HTMLImageElement HTMLInputElement HTMLIsIndexElement
132 HTMLLIElement HTMLLabelElement HTMLLegendElement
133 HTMLLinkElement HTMLMapElement HTMLMenuElement
134 HTMLMetaElement HTMLModElement HTMLOListElement
135 HTMLObjectElement HTMLOptGroupElement
136 HTMLOptionElement HTMLOptionsCollection
137 HTMLParagraphElement HTMLParamElement HTMLPreElement
138 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
139 HTMLStyleElement HTMLTableCaptionElement
140 HTMLTableCellElement HTMLTableColElement
141 HTMLTableElement HTMLTableRowElement
142 HTMLTableSectionElement HTMLTextAreaElement
143 HTMLTitleElement HTMLUListElement
144
145 ;; DOM level 3
146 DOMConfiguration DOMError DOMException
147 DOMImplementationList DOMImplementationSource
148 DOMLocator DOMStringList NameList TypeInfo
149 UserDataHandler
150
151 ;; Window
152 window alert confirm document java navigator prompt screen
153 self top requestAnimationFrame cancelAnimationFrame
154
155 ;; W3C CSS
156 CSSCharsetRule CSSFontFace CSSFontFaceRule
157 CSSImportRule CSSMediaRule CSSPageRule
158 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
159 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
160 CSSValue CSSValueList Counter DOMImplementationCSS
161 DocumentCSS DocumentStyle ElementCSSInlineStyle
162 LinkStyle MediaList RGBColor Rect StyleSheet
163 StyleSheetList ViewCSS
164
165 ;; W3C Event
166 EventListener EventTarget Event DocumentEvent UIEvent
167 MouseEvent MutationEvent KeyboardEvent
168
169 ;; W3C Range
170 DocumentRange Range RangeException
171
172 ;; W3C XML
173 XPathResult XMLHttpRequest
174
175 ;; console object. Provided by at least Chrome and Firefox.
176 console))
177 "Browser externs.
178 You can cause these to be included or excluded with the custom
179 variable `js2-include-browser-externs'.")
180
181 (defvar js2-rhino-externs
182 (mapcar 'symbol-name
183 '(Packages importClass importPackage com org java
184 ;; Global object (shell) externs.
185 defineClass deserialize doctest gc help load
186 loadClass print quit readFile readUrl runCommand seal
187 serialize spawn sync toint32 version))
188 "Mozilla Rhino externs.
189 Set `js2-include-rhino-externs' to t to include them.")
190
191 (defvar js2-node-externs
192 (mapcar 'symbol-name
193 '(__dirname __filename Buffer clearInterval clearTimeout require
194 console exports global module process setInterval setTimeout
195 querystring))
196 "Node.js externs.
197 Set `js2-include-node-externs' to t to include them.")
198
199 (defvar js2-typed-array-externs
200 (mapcar 'symbol-name
201 '(ArrayBuffer Uint8ClampedArray DataView
202 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
203 Float32Array Float64Array))
204 "Khronos typed array externs. Available in most modern browsers and
205 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
206 are enabled, these will also be included.")
207
208 (defvar js2-harmony-externs
209 (mapcar 'symbol-name
210 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
211 "ES6 externs. If `js2-include-browser-externs' is enabled and
212 `js2-language-version' is sufficiently high, these will be included.")
213
214 ;;; Variables
215
216 (defun js2-mark-safe-local (name pred)
217 "Make the variable NAME buffer-local and mark it as safe file-local
218 variable with predicate PRED."
219 (make-variable-buffer-local name)
220 (put name 'safe-local-variable pred))
221
222 (defcustom js2-highlight-level 2
223 "Amount of syntax highlighting to perform.
224 0 or a negative value means none.
225 1 adds basic syntax highlighting.
226 2 adds highlighting of some Ecma built-in properties.
227 3 adds highlighting of many Ecma built-in functions."
228 :group 'js2-mode
229 :type '(choice (const :tag "None" 0)
230 (const :tag "Basic" 1)
231 (const :tag "Include Properties" 2)
232 (const :tag "Include Functions" 3)))
233
234 (defvar js2-mode-dev-mode-p nil
235 "Non-nil if running in development mode. Normally nil.")
236
237 (defgroup js2-mode nil
238 "An improved JavaScript mode."
239 :group 'languages)
240
241 (defcustom js2-idle-timer-delay 0.2
242 "Delay in secs before re-parsing after user makes changes.
243 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
244 :type 'number
245 :group 'js2-mode)
246 (make-variable-buffer-local 'js2-idle-timer-delay)
247
248 (defcustom js2-dynamic-idle-timer-adjust 0
249 "Positive to adjust `js2-idle-timer-delay' based on file size.
250 The idea is that for short files, parsing is faster so we can be
251 more responsive to user edits without interfering with editing.
252 The buffer length in characters (typically bytes) is divided by
253 this value and used to multiply `js2-idle-timer-delay' for the
254 buffer. For example, a 21k file and 10k adjust yields 21k/10k
255 == 2, so js2-idle-timer-delay is multiplied by 2.
256 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
257 `js2-idle-timer-delay' is not dependent on the file size."
258 :type 'number
259 :group 'js2-mode)
260
261 (defcustom js2-concat-multiline-strings t
262 "When non-nil, `js2-line-break' in mid-string will make it a
263 string concatenation. When `eol', the '+' will be inserted at the
264 end of the line, otherwise, at the beginning of the next line."
265 :type '(choice (const t) (const eol) (const nil))
266 :group 'js2-mode)
267
268 (defcustom js2-mode-show-parse-errors t
269 "True to highlight parse errors."
270 :type 'boolean
271 :group 'js2-mode)
272
273 (defcustom js2-mode-show-strict-warnings t
274 "Non-nil to emit Ecma strict-mode warnings.
275 Some of the warnings can be individually disabled by other flags,
276 even if this flag is non-nil."
277 :type 'boolean
278 :group 'js2-mode)
279
280 (defcustom js2-strict-trailing-comma-warning t
281 "Non-nil to warn about trailing commas in array literals.
282 Ecma-262-5.1 allows them, but older versions of IE raise an error."
283 :type 'boolean
284 :group 'js2-mode)
285
286 (defcustom js2-strict-missing-semi-warning t
287 "Non-nil to warn about semicolon auto-insertion after statement.
288 Technically this is legal per Ecma-262, but some style guides disallow
289 depending on it."
290 :type 'boolean
291 :group 'js2-mode)
292
293 (defcustom js2-missing-semi-one-line-override nil
294 "Non-nil to permit missing semicolons in one-line functions.
295 In one-liner functions such as `function identity(x) {return x}'
296 people often omit the semicolon for a cleaner look. If you are
297 such a person, you can suppress the missing-semicolon warning
298 by setting this variable to t."
299 :type 'boolean
300 :group 'js2-mode)
301
302 (defcustom js2-strict-inconsistent-return-warning t
303 "Non-nil to warn about mixing returns with value-returns.
304 It's perfectly legal to have a `return' and a `return foo' in the
305 same function, but it's often an indicator of a bug, and it also
306 interferes with type inference (in systems that support it.)"
307 :type 'boolean
308 :group 'js2-mode)
309
310 (defcustom js2-strict-cond-assign-warning t
311 "Non-nil to warn about expressions like if (a = b).
312 This often should have been '==' instead of '='. If the warning
313 is enabled, you can suppress it on a per-expression basis by
314 parenthesizing the expression, e.g. if ((a = b)) ..."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-strict-var-redeclaration-warning t
319 "Non-nil to warn about redeclaring variables in a script or function."
320 :type 'boolean
321 :group 'js2-mode)
322
323 (defcustom js2-strict-var-hides-function-arg-warning t
324 "Non-nil to warn about a var decl hiding a function argument."
325 :type 'boolean
326 :group 'js2-mode)
327
328 (defcustom js2-skip-preprocessor-directives nil
329 "Non-nil to treat lines beginning with # as comments.
330 Useful for viewing Mozilla JavaScript source code."
331 :type 'boolean
332 :group 'js2-mode)
333
334 (defcustom js2-language-version 200
335 "Configures what JavaScript language version to recognize.
336 Currently versions 150, 160, 170, 180 and 200 are supported,
337 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
338 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
339 yield, and Array comprehensions, and 1.8 adds function closures."
340 :type 'integer
341 :group 'js2-mode)
342
343 (defcustom js2-instanceof-has-side-effects nil
344 "If non-nil, treats the instanceof operator as having side effects.
345 This is useful for xulrunner apps."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-move-point-on-right-click t
350 "Non-nil to move insertion point when you right-click.
351 This makes right-click context menu behavior a bit more intuitive,
352 since menu operations generally apply to the point. The exception
353 is if there is a region selection, in which case the point does -not-
354 move, so cut/copy/paste can work properly.
355
356 Note that IntelliJ moves the point, and Eclipse leaves it alone,
357 so this behavior is customizable."
358 :group 'js2-mode
359 :type 'boolean)
360
361 (defcustom js2-allow-rhino-new-expr-initializer t
362 "Non-nil to support a Rhino's experimental syntactic construct.
363
364 Rhino supports the ability to follow a `new' expression with an object
365 literal, which is used to set additional properties on the new object
366 after calling its constructor. Syntax:
367
368 new <expr> [ ( arglist ) ] [initializer]
369
370 Hence, this expression:
371
372 new Object {a: 1, b: 2}
373
374 results in an Object with properties a=1 and b=2. This syntax is
375 apparently not configurable in Rhino - it's currently always enabled,
376 as of Rhino version 1.7R2."
377 :type 'boolean
378 :group 'js2-mode)
379
380 (defcustom js2-allow-member-expr-as-function-name nil
381 "Non-nil to support experimental Rhino syntax for function names.
382
383 Rhino supports an experimental syntax configured via the Rhino Context
384 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
385
386 function <member-expr> ( [ arg-list ] ) { <body> }
387
388 Where member-expr is a non-parenthesized 'member expression', which
389 is anything at the grammar level of a new-expression or lower, meaning
390 any expression that does not involve infix or unary operators.
391
392 When <member-expr> is not a simple identifier, then it is syntactic
393 sugar for assigning the anonymous function to the <member-expr>. Hence,
394 this code:
395
396 function a.b().c[2] (x, y) { ... }
397
398 is rewritten as:
399
400 a.b().c[2] = function(x, y) {...}
401
402 which doesn't seem particularly useful, but Rhino permits it."
403 :type 'boolean
404 :group 'js2-mode)
405
406 ;; scanner variables
407
408 (defmacro js2-deflocal (name value &optional comment)
409 "Define a buffer-local variable NAME with VALUE and COMMENT."
410 (declare (debug defvar) (doc-string 3))
411 `(progn
412 (defvar ,name ,value ,comment)
413 (make-variable-buffer-local ',name)))
414
415 (defvar js2-EOF_CHAR -1
416 "Represents end of stream. Distinct from js2-EOF token type.")
417
418 ;; I originally used symbols to represent tokens, but Rhino uses
419 ;; ints and then sets various flag bits in them, so ints it is.
420 ;; The upshot is that we need a `js2-' prefix in front of each name.
421 (defvar js2-ERROR -1)
422 (defvar js2-EOF 0)
423 (defvar js2-EOL 1)
424 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
425 (defvar js2-LEAVEWITH 3)
426 (defvar js2-RETURN 4)
427 (defvar js2-GOTO 5)
428 (defvar js2-IFEQ 6)
429 (defvar js2-IFNE 7)
430 (defvar js2-SETNAME 8)
431 (defvar js2-BITOR 9)
432 (defvar js2-BITXOR 10)
433 (defvar js2-BITAND 11)
434 (defvar js2-EQ 12)
435 (defvar js2-NE 13)
436 (defvar js2-LT 14)
437 (defvar js2-LE 15)
438 (defvar js2-GT 16)
439 (defvar js2-GE 17)
440 (defvar js2-LSH 18)
441 (defvar js2-RSH 19)
442 (defvar js2-URSH 20)
443 (defvar js2-ADD 21) ; infix plus
444 (defvar js2-SUB 22) ; infix minus
445 (defvar js2-MUL 23)
446 (defvar js2-DIV 24)
447 (defvar js2-MOD 25)
448 (defvar js2-NOT 26)
449 (defvar js2-BITNOT 27)
450 (defvar js2-POS 28) ; unary plus
451 (defvar js2-NEG 29) ; unary minus
452 (defvar js2-NEW 30)
453 (defvar js2-DELPROP 31)
454 (defvar js2-TYPEOF 32)
455 (defvar js2-GETPROP 33)
456 (defvar js2-GETPROPNOWARN 34)
457 (defvar js2-SETPROP 35)
458 (defvar js2-GETELEM 36)
459 (defvar js2-SETELEM 37)
460 (defvar js2-CALL 38)
461 (defvar js2-NAME 39) ; an identifier
462 (defvar js2-NUMBER 40)
463 (defvar js2-STRING 41)
464 (defvar js2-NULL 42)
465 (defvar js2-THIS 43)
466 (defvar js2-FALSE 44)
467 (defvar js2-TRUE 45)
468 (defvar js2-SHEQ 46) ; shallow equality (===)
469 (defvar js2-SHNE 47) ; shallow inequality (!==)
470 (defvar js2-REGEXP 48)
471 (defvar js2-BINDNAME 49)
472 (defvar js2-THROW 50)
473 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
474 (defvar js2-IN 52)
475 (defvar js2-INSTANCEOF 53)
476 (defvar js2-LOCAL_LOAD 54)
477 (defvar js2-GETVAR 55)
478 (defvar js2-SETVAR 56)
479 (defvar js2-CATCH_SCOPE 57)
480 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
481 (defvar js2-ENUM_INIT_VALUES 59)
482 (defvar js2-ENUM_INIT_ARRAY 60)
483 (defvar js2-ENUM_NEXT 61)
484 (defvar js2-ENUM_ID 62)
485 (defvar js2-THISFN 63)
486 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
487 (defvar js2-ARRAYLIT 65) ; array literal
488 (defvar js2-OBJECTLIT 66) ; object literal
489 (defvar js2-GET_REF 67) ; *reference
490 (defvar js2-SET_REF 68) ; *reference = something
491 (defvar js2-DEL_REF 69) ; delete reference
492 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
493 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
494 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
495
496 ;; XML support
497 (defvar js2-DEFAULTNAMESPACE 73)
498 (defvar js2-ESCXMLATTR 74)
499 (defvar js2-ESCXMLTEXT 75)
500 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
501 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
502 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
503 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
504
505 (defvar js2-first-bytecode js2-ENTERWITH)
506 (defvar js2-last-bytecode js2-REF_NS_NAME)
507
508 (defvar js2-TRY 80)
509 (defvar js2-SEMI 81) ; semicolon
510 (defvar js2-LB 82) ; left and right brackets
511 (defvar js2-RB 83)
512 (defvar js2-LC 84) ; left and right curly-braces
513 (defvar js2-RC 85)
514 (defvar js2-LP 86) ; left and right parens
515 (defvar js2-RP 87)
516 (defvar js2-COMMA 88) ; comma operator
517
518 (defvar js2-ASSIGN 89) ; simple assignment (=)
519 (defvar js2-ASSIGN_BITOR 90) ; |=
520 (defvar js2-ASSIGN_BITXOR 91) ; ^=
521 (defvar js2-ASSIGN_BITAND 92) ; &=
522 (defvar js2-ASSIGN_LSH 93) ; <<=
523 (defvar js2-ASSIGN_RSH 94) ; >>=
524 (defvar js2-ASSIGN_URSH 95) ; >>>=
525 (defvar js2-ASSIGN_ADD 96) ; +=
526 (defvar js2-ASSIGN_SUB 97) ; -=
527 (defvar js2-ASSIGN_MUL 98) ; *=
528 (defvar js2-ASSIGN_DIV 99) ; /=
529 (defvar js2-ASSIGN_MOD 100) ; %=
530
531 (defvar js2-first-assign js2-ASSIGN)
532 (defvar js2-last-assign js2-ASSIGN_MOD)
533
534 (defvar js2-HOOK 101) ; conditional (?:)
535 (defvar js2-COLON 102)
536 (defvar js2-OR 103) ; logical or (||)
537 (defvar js2-AND 104) ; logical and (&&)
538 (defvar js2-INC 105) ; increment/decrement (++ --)
539 (defvar js2-DEC 106)
540 (defvar js2-DOT 107) ; member operator (.)
541 (defvar js2-FUNCTION 108) ; function keyword
542 (defvar js2-EXPORT 109) ; export keyword
543 (defvar js2-IMPORT 110) ; import keyword
544 (defvar js2-IF 111) ; if keyword
545 (defvar js2-ELSE 112) ; else keyword
546 (defvar js2-SWITCH 113) ; switch keyword
547 (defvar js2-CASE 114) ; case keyword
548 (defvar js2-DEFAULT 115) ; default keyword
549 (defvar js2-WHILE 116) ; while keyword
550 (defvar js2-DO 117) ; do keyword
551 (defvar js2-FOR 118) ; for keyword
552 (defvar js2-BREAK 119) ; break keyword
553 (defvar js2-CONTINUE 120) ; continue keyword
554 (defvar js2-VAR 121) ; var keyword
555 (defvar js2-WITH 122) ; with keyword
556 (defvar js2-CATCH 123) ; catch keyword
557 (defvar js2-FINALLY 124) ; finally keyword
558 (defvar js2-VOID 125) ; void keyword
559 (defvar js2-RESERVED 126) ; reserved keywords
560
561 (defvar js2-EMPTY 127)
562
563 ;; Types used for the parse tree - never returned by scanner.
564
565 (defvar js2-BLOCK 128) ; statement block
566 (defvar js2-LABEL 129) ; label
567 (defvar js2-TARGET 130)
568 (defvar js2-LOOP 131)
569 (defvar js2-EXPR_VOID 132) ; expression statement in functions
570 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
571 (defvar js2-JSR 134)
572 (defvar js2-SCRIPT 135) ; top-level node for entire script
573 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
574 (defvar js2-USE_STACK 137)
575 (defvar js2-SETPROP_OP 138) ; x.y op= something
576 (defvar js2-SETELEM_OP 139) ; x[y] op= something
577 (defvar js2-LOCAL_BLOCK 140)
578 (defvar js2-SET_REF_OP 141) ; *reference op= something
579
580 ;; For XML support:
581 (defvar js2-DOTDOT 142) ; member operator (..)
582 (defvar js2-COLONCOLON 143) ; namespace::name
583 (defvar js2-XML 144) ; XML type
584 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
585 (defvar js2-XMLATTR 146) ; @
586 (defvar js2-XMLEND 147)
587
588 ;; Optimizer-only tokens
589 (defvar js2-TO_OBJECT 148)
590 (defvar js2-TO_DOUBLE 149)
591
592 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
593 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
594 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
595 (defvar js2-CONST 153)
596 (defvar js2-SETCONST 154)
597 (defvar js2-SETCONSTVAR 155)
598 (defvar js2-ARRAYCOMP 156)
599 (defvar js2-LETEXPR 157)
600 (defvar js2-WITHEXPR 158)
601 (defvar js2-DEBUGGER 159)
602
603 (defvar js2-COMMENT 160)
604 (defvar js2-TRIPLEDOT 161) ; for rest parameter
605 (defvar js2-ARROW 162) ; function arrow (=>)
606 (defvar js2-CLASS 163)
607 (defvar js2-EXTENDS 164)
608 (defvar js2-SUPER 165)
609 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
610 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
611 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
612
613 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
614
615 (defconst js2-debug-print-trees nil)
616
617 ;; Rhino accepts any string or stream as input. Emacs character
618 ;; processing works best in buffers, so we'll assume the input is a
619 ;; buffer. JavaScript strings can be copied into temp buffers before
620 ;; scanning them.
621
622 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
623 ;; They're the Emacs equivalent of instance variables, more or less.
624
625 (js2-deflocal js2-ts-dirty-line nil
626 "Token stream buffer-local variable.
627 Indicates stuff other than whitespace since start of line.")
628
629 (js2-deflocal js2-ts-hit-eof nil
630 "Token stream buffer-local variable.")
631
632 ;; FIXME: Unused.
633 (js2-deflocal js2-ts-line-start 0
634 "Token stream buffer-local variable.")
635
636 (js2-deflocal js2-ts-lineno 1
637 "Token stream buffer-local variable.")
638
639 ;; FIXME: Unused.
640 (js2-deflocal js2-ts-line-end-char -1
641 "Token stream buffer-local variable.")
642
643 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
644 "Token stream buffer-local variable.
645 Current scan position.")
646
647 ;; FIXME: Unused.
648 (js2-deflocal js2-ts-is-xml-attribute nil
649 "Token stream buffer-local variable.")
650
651 (js2-deflocal js2-ts-xml-is-tag-content nil
652 "Token stream buffer-local variable.")
653
654 (js2-deflocal js2-ts-xml-open-tags-count 0
655 "Token stream buffer-local variable.")
656
657 (js2-deflocal js2-ts-string-buffer nil
658 "Token stream buffer-local variable.
659 List of chars built up while scanning various tokens.")
660
661 (cl-defstruct (js2-token
662 (:constructor nil)
663 (:constructor make-js2-token (beg)))
664 "Value returned from the token stream."
665 (type js2-EOF)
666 (beg 1)
667 (end -1)
668 (string "")
669 number
670 number-base
671 regexp-flags
672 comment-type
673 follows-eol-p)
674
675 ;; Have to call `js2-init-scanner' to initialize the values.
676 (js2-deflocal js2-ti-tokens nil)
677 (js2-deflocal js2-ti-tokens-cursor nil)
678 (js2-deflocal js2-ti-lookahead nil)
679
680 (cl-defstruct (js2-ts-state
681 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
682 (cursor js2-ts-cursor)
683 (tokens (copy-sequence js2-ti-tokens))
684 (tokens-cursor js2-ti-tokens-cursor)
685 (lookahead js2-ti-lookahead))))
686 lineno
687 cursor
688 tokens
689 tokens-cursor
690 lookahead)
691
692 ;;; Parser variables
693
694 (js2-deflocal js2-parsed-errors nil
695 "List of errors produced during scanning/parsing.")
696
697 (js2-deflocal js2-parsed-warnings nil
698 "List of warnings produced during scanning/parsing.")
699
700 (js2-deflocal js2-recover-from-parse-errors t
701 "Non-nil to continue parsing after a syntax error.
702
703 In recovery mode, the AST will be built in full, and any error
704 nodes will be flagged with appropriate error information. If
705 this flag is nil, a syntax error will result in an error being
706 signaled.
707
708 The variable is automatically buffer-local, because different
709 modes that use the parser will need different settings.")
710
711 (js2-deflocal js2-parse-hook nil
712 "List of callbacks for receiving parsing progress.")
713
714 (defvar js2-parse-finished-hook nil
715 "List of callbacks to notify when parsing finishes.
716 Not called if parsing was interrupted.")
717
718 (js2-deflocal js2-is-eval-code nil
719 "True if we're evaluating code in a string.
720 If non-nil, the tokenizer will record the token text, and the AST nodes
721 will record their source text. Off by default for IDE modes, since the
722 text is available in the buffer.")
723
724 (defvar js2-parse-ide-mode t
725 "Non-nil if the parser is being used for `js2-mode'.
726 If non-nil, the parser will set text properties for fontification
727 and the syntax table. The value should be nil when using the
728 parser as a frontend to an interpreter or byte compiler.")
729
730 ;;; Parser instance variables (buffer-local vars for js2-parse)
731
732 (defconst js2-ti-after-eol (lsh 1 16)
733 "Flag: first token of the source line.")
734
735 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
736
737 (js2-deflocal js2-compiler-generate-debug-info t)
738 (js2-deflocal js2-compiler-use-dynamic-scope nil)
739 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
740 (js2-deflocal js2-compiler-xml-available t)
741 (js2-deflocal js2-compiler-optimization-level 0)
742 (js2-deflocal js2-compiler-generating-source t)
743 (js2-deflocal js2-compiler-strict-mode nil)
744 (js2-deflocal js2-compiler-report-warning-as-error nil)
745 (js2-deflocal js2-compiler-generate-observer-count nil)
746 (js2-deflocal js2-compiler-activation-names nil)
747
748 ;; SKIP: sourceURI
749
750 ;; There's a compileFunction method in Context.java - may need it.
751 (js2-deflocal js2-called-by-compile-function nil
752 "True if `js2-parse' was called by `js2-compile-function'.
753 Will only be used when we finish implementing the interpreter.")
754
755 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
756
757 ;; SKIP: node factory - we're going to just call functions directly,
758 ;; and eventually go to a unified AST format.
759
760 (js2-deflocal js2-nesting-of-function 0)
761
762 (js2-deflocal js2-recorded-identifiers nil
763 "Tracks identifiers found during parsing.")
764
765 (js2-deflocal js2-is-in-destructuring nil
766 "True while parsing destructuring expression.")
767
768 (js2-deflocal js2-in-use-strict-directive nil
769 "True while inside a script or function under strict mode.")
770
771 (defcustom js2-global-externs nil
772 "A list of any extern names you'd like to consider always declared.
773 This list is global and is used by all `js2-mode' files.
774 You can create buffer-local externs list using `js2-additional-externs'.
775
776 There is also a buffer-local variable `js2-default-externs',
777 which is initialized by default to include the Ecma-262 externs
778 and the standard browser externs. The three lists are all
779 checked during highlighting."
780 :type 'list
781 :group 'js2-mode)
782
783 (js2-deflocal js2-default-externs nil
784 "Default external declarations.
785
786 These are currently only used for highlighting undeclared variables,
787 which only worries about top-level (unqualified) references.
788 As js2-mode's processing improves, we will flesh out this list.
789
790 The initial value is set to `js2-ecma-262-externs', unless some
791 of the `js2-include-?-externs' variables are set to t, in which
792 case the browser, Rhino and/or Node.js externs are also included.
793
794 See `js2-additional-externs' for more information.")
795
796 (defcustom js2-include-browser-externs t
797 "Non-nil to include browser externs in the master externs list.
798 If you work on JavaScript files that are not intended for browsers,
799 such as Mozilla Rhino server-side JavaScript, set this to nil.
800 See `js2-additional-externs' for more information about externs."
801 :type 'boolean
802 :group 'js2-mode)
803
804 (defcustom js2-include-rhino-externs nil
805 "Non-nil to include Mozilla Rhino externs in the master externs list.
806 See `js2-additional-externs' for more information about externs."
807 :type 'boolean
808 :group 'js2-mode)
809
810 (defcustom js2-include-node-externs nil
811 "Non-nil to include Node.js externs in the master externs list.
812 See `js2-additional-externs' for more information about externs."
813 :type 'boolean
814 :group 'js2-mode)
815
816 (js2-deflocal js2-additional-externs nil
817 "A buffer-local list of additional external declarations.
818 It is used to decide whether variables are considered undeclared
819 for purposes of highlighting.
820
821 Each entry is a Lisp string. The string should be the fully qualified
822 name of an external entity. All externs should be added to this list,
823 so that as js2-mode's processing improves it can take advantage of them.
824
825 You may want to declare your externs in three ways.
826 First, you can add externs that are valid for all your JavaScript files.
827 You should probably do this by adding them to `js2-global-externs', which
828 is a global list used for all js2-mode files.
829
830 Next, you can add a function to `js2-init-hook' that adds additional
831 externs appropriate for the specific file, perhaps based on its path.
832 These should go in `js2-additional-externs', which is buffer-local.
833
834 Third, you can use JSLint's global declaration, as long as
835 `js2-include-jslint-globals' is non-nil, which see.
836
837 Finally, you can add a function to `js2-post-parse-callbacks',
838 which is called after parsing completes, and `js2-mode-ast' is bound to
839 the root of the parse tree. At this stage you can set up an AST
840 node visitor using `js2-visit-ast' and examine the parse tree
841 for specific import patterns that may imply the existence of
842 other externs, possibly tied to your build system. These should also
843 be added to `js2-additional-externs'.
844
845 Your post-parse callback may of course also use the simpler and
846 faster (but perhaps less robust) approach of simply scanning the
847 buffer text for your imports, using regular expressions.")
848
849 ;; SKIP: decompiler
850 ;; SKIP: encoded-source
851
852 ;;; The following variables are per-function and should be saved/restored
853 ;;; during function parsing...
854
855 (js2-deflocal js2-current-script-or-fn nil)
856 (js2-deflocal js2-current-scope nil)
857 (js2-deflocal js2-nesting-of-with 0)
858 (js2-deflocal js2-label-set nil
859 "An alist mapping label names to nodes.")
860
861 (js2-deflocal js2-loop-set nil)
862 (js2-deflocal js2-loop-and-switch-set nil)
863 (js2-deflocal js2-has-return-value nil)
864 (js2-deflocal js2-end-flags 0)
865
866 ;;; ...end of per function variables
867
868 ;; These flags enumerate the possible ways a statement/function can
869 ;; terminate. These flags are used by endCheck() and by the Parser to
870 ;; detect inconsistent return usage.
871 ;;
872 ;; END_UNREACHED is reserved for code paths that are assumed to always be
873 ;; able to execute (example: throw, continue)
874 ;;
875 ;; END_DROPS_OFF indicates if the statement can transfer control to the
876 ;; next one. Statement such as return dont. A compound statement may have
877 ;; some branch that drops off control to the next statement.
878 ;;
879 ;; END_RETURNS indicates that the statement can return (without arguments)
880 ;; END_RETURNS_VALUE indicates that the statement can return a value.
881 ;;
882 ;; A compound statement such as
883 ;; if (condition) {
884 ;; return value;
885 ;; }
886 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
887
888 (defconst js2-end-unreached #x0)
889 (defconst js2-end-drops-off #x1)
890 (defconst js2-end-returns #x2)
891 (defconst js2-end-returns-value #x4)
892
893 ;; Rhino awkwardly passes a statementLabel parameter to the
894 ;; statementHelper() function, the main statement parser, which
895 ;; is then used by quite a few of the sub-parsers. We just make
896 ;; it a buffer-local variable and make sure it's cleaned up properly.
897 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
898
899 ;; Similarly, Rhino passes an inForInit boolean through about half
900 ;; the expression parsers. We use a dynamically-scoped variable,
901 ;; which makes it easier to funcall the parsers individually without
902 ;; worrying about whether they take the parameter or not.
903 (js2-deflocal js2-in-for-init nil)
904 (js2-deflocal js2-temp-name-counter 0)
905 (js2-deflocal js2-parse-stmt-count 0)
906
907 (defsubst js2-get-next-temp-name ()
908 (format "$%d" (cl-incf js2-temp-name-counter)))
909
910 (defvar js2-parse-interruptable-p t
911 "Set this to nil to force parse to continue until finished.
912 This will mostly be useful for interpreters.")
913
914 (defvar js2-statements-per-pause 50
915 "Pause after this many statements to check for user input.
916 If user input is pending, stop the parse and discard the tree.
917 This makes for a smoother user experience for large files.
918 You may have to wait a second or two before the highlighting
919 and error-reporting appear, but you can always type ahead if
920 you wish. This appears to be more or less how Eclipse, IntelliJ
921 and other editors work.")
922
923 (js2-deflocal js2-record-comments t
924 "Instructs the scanner to record comments in `js2-scanned-comments'.")
925
926 (js2-deflocal js2-scanned-comments nil
927 "List of all comments from the current parse.")
928
929 (defcustom js2-mode-indent-inhibit-undo nil
930 "Non-nil to disable collection of Undo information when indenting lines.
931 Some users have requested this behavior. It's nil by default because
932 other Emacs modes don't work this way."
933 :type 'boolean
934 :group 'js2-mode)
935
936 (defcustom js2-mode-indent-ignore-first-tab nil
937 "If non-nil, ignore first TAB keypress if we look indented properly.
938 It's fairly common for users to navigate to an already-indented line
939 and press TAB for reassurance that it's been indented. For this class
940 of users, we want the first TAB press on a line to be ignored if the
941 line is already indented to one of the precomputed alternatives.
942
943 This behavior is only partly implemented. If you TAB-indent a line,
944 navigate to another line, and then navigate back, it fails to clear
945 the last-indented variable, so it thinks you've already hit TAB once,
946 and performs the indent. A full solution would involve getting on the
947 point-motion hooks for the entire buffer. If we come across another
948 use cases that requires watching point motion, I'll consider doing it.
949
950 If you set this variable to nil, then the TAB key will always change
951 the indentation of the current line, if more than one alternative
952 indentation spot exists."
953 :type 'boolean
954 :group 'js2-mode)
955
956 (defvar js2-indent-hook nil
957 "A hook for user-defined indentation rules.
958
959 Functions on this hook should expect two arguments: (LIST INDEX)
960 The LIST argument is the list of computed indentation points for
961 the current line. INDEX is the list index of the indentation point
962 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
963 indent function is not going to change the current line indentation.
964
965 If a hook function on this list returns a non-nil value, then
966 `js2-bounce-indent' assumes the hook function has performed its own
967 indentation, and will do nothing. If all hook functions on the list
968 return nil, then `js2-bounce-indent' will use its computed indentation
969 and reindent the line.
970
971 When hook functions on this hook list are called, the variable
972 `js2-mode-ast' may or may not be set, depending on whether the
973 parse tree is available. If the variable is nil, you can pass a
974 callback to `js2-mode-wait-for-parse', and your callback will be
975 called after the new parse tree is built. This can take some time
976 in large files.")
977
978 (defface js2-warning
979 `((((class color) (background light))
980 (:underline "orange"))
981 (((class color) (background dark))
982 (:underline "orange"))
983 (t (:underline t)))
984 "Face for JavaScript warnings."
985 :group 'js2-mode)
986
987 (defface js2-error
988 `((((class color) (background light))
989 (:foreground "red"))
990 (((class color) (background dark))
991 (:foreground "red"))
992 (t (:foreground "red")))
993 "Face for JavaScript errors."
994 :group 'js2-mode)
995
996 (defface js2-jsdoc-tag
997 '((t :foreground "SlateGray"))
998 "Face used to highlight @whatever tags in jsdoc comments."
999 :group 'js2-mode)
1000
1001 (defface js2-jsdoc-type
1002 '((t :foreground "SteelBlue"))
1003 "Face used to highlight {FooBar} types in jsdoc comments."
1004 :group 'js2-mode)
1005
1006 (defface js2-jsdoc-value
1007 '((t :foreground "PeachPuff3"))
1008 "Face used to highlight tag values in jsdoc comments."
1009 :group 'js2-mode)
1010
1011 (defface js2-function-param
1012 '((t :foreground "SeaGreen"))
1013 "Face used to highlight function parameters in javascript."
1014 :group 'js2-mode)
1015
1016 (defface js2-function-call
1017 '((t :inherit default))
1018 "Face used to highlight function name in calls."
1019 :group 'js2-mode)
1020
1021 (defface js2-instance-member
1022 '((t :foreground "DarkOrchid"))
1023 "Face used to highlight instance variables in javascript.
1024 Not currently used."
1025 :group 'js2-mode)
1026
1027 (defface js2-private-member
1028 '((t :foreground "PeachPuff3"))
1029 "Face used to highlight calls to private methods in javascript.
1030 Not currently used."
1031 :group 'js2-mode)
1032
1033 (defface js2-private-function-call
1034 '((t :foreground "goldenrod"))
1035 "Face used to highlight calls to private functions in javascript.
1036 Not currently used."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-html-tag-name
1040 '((((class color) (min-colors 88) (background light))
1041 (:foreground "rosybrown"))
1042 (((class color) (min-colors 8) (background dark))
1043 (:foreground "yellow"))
1044 (((class color) (min-colors 8) (background light))
1045 (:foreground "magenta")))
1046 "Face used to highlight jsdoc html tag names"
1047 :group 'js2-mode)
1048
1049 (defface js2-jsdoc-html-tag-delimiter
1050 '((((class color) (min-colors 88) (background light))
1051 (:foreground "dark khaki"))
1052 (((class color) (min-colors 8) (background dark))
1053 (:foreground "green"))
1054 (((class color) (min-colors 8) (background light))
1055 (:foreground "green")))
1056 "Face used to highlight brackets in jsdoc html tags."
1057 :group 'js2-mode)
1058
1059 (defface js2-external-variable
1060 '((t :foreground "orange"))
1061 "Face used to highlight undeclared variable identifiers.")
1062
1063 (defcustom js2-init-hook nil
1064 "List of functions to be called after `js2-mode' or
1065 `js2-minor-mode' has initialized all variables, before parsing
1066 the buffer for the first time."
1067 :type 'hook
1068 :group 'js2-mode
1069 :version "20130608")
1070
1071 (defcustom js2-post-parse-callbacks nil
1072 "List of callback functions invoked after parsing finishes.
1073 Currently, the main use for this function is to add synthetic
1074 declarations to `js2-recorded-identifiers', which see."
1075 :type 'hook
1076 :group 'js2-mode)
1077
1078 (defcustom js2-build-imenu-callbacks nil
1079 "List of functions called during Imenu index generation.
1080 It's a good place to add additional entries to it, using
1081 `js2-record-imenu-entry'."
1082 :type 'hook
1083 :group 'js2-mode)
1084
1085 (defcustom js2-highlight-external-variables t
1086 "Non-nil to highlight undeclared variable identifiers.
1087 An undeclared variable is any variable not declared with var or let
1088 in the current scope or any lexically enclosing scope. If you use
1089 such a variable, then you are either expecting it to originate from
1090 another file, or you've got a potential bug."
1091 :type 'boolean
1092 :group 'js2-mode)
1093
1094 (defcustom js2-warn-about-unused-function-arguments nil
1095 "Non-nil to treat function arguments like declared-but-unused variables."
1096 :type 'booleanp
1097 :group 'js2-mode)
1098
1099 (defcustom js2-include-jslint-globals t
1100 "Non-nil to include the identifiers from JSLint global
1101 declaration (see http://www.jslint.com/lint.html#global) in the
1102 buffer-local externs list. See `js2-additional-externs' for more
1103 information."
1104 :type 'boolean
1105 :group 'js2-mode)
1106
1107 (defvar js2-mode-map
1108 (let ((map (make-sparse-keymap)))
1109 (define-key map [mouse-1] #'js2-mode-show-node)
1110 (define-key map (kbd "M-j") #'js2-line-break)
1111 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1112 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1113 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1114 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1115 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1116 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1117 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1118 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1119 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1120
1121 (define-key map [menu-bar javascript]
1122 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1123
1124 (define-key map [menu-bar javascript customize-js2-mode]
1125 '(menu-item "Customize js2-mode" js2-mode-customize
1126 :help "Customize the behavior of this mode"))
1127
1128 (define-key map [menu-bar javascript js2-force-refresh]
1129 '(menu-item "Force buffer refresh" js2-mode-reset
1130 :help "Re-parse the buffer from scratch"))
1131
1132 (define-key map [menu-bar javascript separator-2]
1133 '("--"))
1134
1135 (define-key map [menu-bar javascript next-error]
1136 '(menu-item "Next warning or error" next-error
1137 :enabled (and js2-mode-ast
1138 (or (js2-ast-root-errors js2-mode-ast)
1139 (js2-ast-root-warnings js2-mode-ast)))
1140 :help "Move to next warning or error"))
1141
1142 (define-key map [menu-bar javascript display-errors]
1143 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1144 :visible (not js2-mode-show-parse-errors)
1145 :help "Turn on display of warnings and errors"))
1146
1147 (define-key map [menu-bar javascript hide-errors]
1148 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1149 :visible js2-mode-show-parse-errors
1150 :help "Turn off display of warnings and errors"))
1151
1152 (define-key map [menu-bar javascript separator-1]
1153 '("--"))
1154
1155 (define-key map [menu-bar javascript js2-toggle-function]
1156 '(menu-item "Show/collapse element" js2-mode-toggle-element
1157 :help "Hide or show function body or comment"))
1158
1159 (define-key map [menu-bar javascript show-comments]
1160 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1161 :visible js2-mode-comments-hidden
1162 :help "Expand all hidden block comments"))
1163
1164 (define-key map [menu-bar javascript hide-comments]
1165 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1166 :visible (not js2-mode-comments-hidden)
1167 :help "Show block comments as /*...*/"))
1168
1169 (define-key map [menu-bar javascript show-all-functions]
1170 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1171 :visible js2-mode-functions-hidden
1172 :help "Expand all hidden function bodies"))
1173
1174 (define-key map [menu-bar javascript hide-all-functions]
1175 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1176 :visible (not js2-mode-functions-hidden)
1177 :help "Show {...} for all top-level function bodies"))
1178
1179 map)
1180 "Keymap used in `js2-mode' buffers.")
1181
1182 (defcustom js2-bounce-indent-p nil
1183 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1184 They will augment the default indent-line behavior with cycling
1185 among several computed alternatives. See the function
1186 `js2-bounce-indent' for details. The above commands will be
1187 bound to TAB and backtab."
1188 :type 'boolean
1189 :group 'js2-mode
1190 :set (lambda (sym value)
1191 (set-default sym value)
1192 (let ((map js2-mode-map))
1193 (if (not value)
1194 (progn
1195 (define-key map "\t" nil)
1196 (define-key map (kbd "<backtab>") nil))
1197 (define-key map "\t" #'js2-indent-bounce)
1198 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1199
1200 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1201
1202 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1203 "Matches a //-comment line. Must be first non-whitespace on line.
1204 First match-group is the leading whitespace.")
1205
1206 (defvar js2-mode-hook nil)
1207
1208 (js2-deflocal js2-mode-ast nil "Private variable.")
1209 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1210 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1211 (js2-deflocal js2-mode-parsing nil "Private variable.")
1212 (js2-deflocal js2-mode-node-overlay nil)
1213
1214 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1215 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1216
1217 (js2-deflocal js2-mode-fontifications nil "Private variable")
1218 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1219 (js2-deflocal js2-imenu-recorder nil "Private variable")
1220 (js2-deflocal js2-imenu-function-map nil "Private variable")
1221
1222 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1223 "Non-nil to emit status messages during parsing.")
1224
1225 (defvar js2-mode-functions-hidden nil "Private variable.")
1226 (defvar js2-mode-comments-hidden nil "Private variable.")
1227
1228 (defvar js2-mode-syntax-table
1229 (let ((table (make-syntax-table)))
1230 (c-populate-syntax-table table)
1231 (modify-syntax-entry ?` "\"" table)
1232 table)
1233 "Syntax table used in `js2-mode' buffers.")
1234
1235 (defvar js2-mode-abbrev-table nil
1236 "Abbrev table in use in `js2-mode' buffers.")
1237 (define-abbrev-table 'js2-mode-abbrev-table ())
1238
1239 (defvar js2-mode-pending-parse-callbacks nil
1240 "List of functions waiting to be notified that parse is finished.")
1241
1242 (defvar js2-mode-last-indented-line -1)
1243
1244 ;;; Localizable error and warning messages
1245
1246 ;; Messages are copied from Rhino's Messages.properties.
1247 ;; Many of the Java-specific messages have been elided.
1248 ;; Add any js2-specific ones at the end, so we can keep
1249 ;; this file synced with changes to Rhino's.
1250
1251 (defvar js2-message-table
1252 (make-hash-table :test 'equal :size 250)
1253 "Contains localized messages for `js2-mode'.")
1254
1255 ;; TODO(stevey): construct this table at compile-time.
1256 (defmacro js2-msg (key &rest strings)
1257 `(puthash ,key (concat ,@strings)
1258 js2-message-table))
1259
1260 (defun js2-get-msg (msg-key)
1261 "Look up a localized message.
1262 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1263 the correct number of ARGS must be provided."
1264 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1265 (args (if (listp msg-key) (cdr msg-key)))
1266 (msg (gethash key js2-message-table)))
1267 (if msg
1268 (apply #'format msg args)
1269 key))) ; default to showing the key
1270
1271 (js2-msg "msg.dup.parms"
1272 "Duplicate parameter name '%s'.")
1273
1274 (js2-msg "msg.too.big.jump"
1275 "Program too complex: jump offset too big.")
1276
1277 (js2-msg "msg.too.big.index"
1278 "Program too complex: internal index exceeds 64K limit.")
1279
1280 (js2-msg "msg.while.compiling.fn"
1281 "Encountered code generation error while compiling function '%s': %s")
1282
1283 (js2-msg "msg.while.compiling.script"
1284 "Encountered code generation error while compiling script: %s")
1285
1286 ;; Context
1287 (js2-msg "msg.ctor.not.found"
1288 "Constructor for '%s' not found.")
1289
1290 (js2-msg "msg.not.ctor"
1291 "'%s' is not a constructor.")
1292
1293 ;; FunctionObject
1294 (js2-msg "msg.varargs.ctor"
1295 "Method or constructor '%s' must be static "
1296 "with the signature (Context cx, Object[] args, "
1297 "Function ctorObj, boolean inNewExpr) "
1298 "to define a variable arguments constructor.")
1299
1300 (js2-msg "msg.varargs.fun"
1301 "Method '%s' must be static with the signature "
1302 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1303 "to define a variable arguments function.")
1304
1305 (js2-msg "msg.incompat.call"
1306 "Method '%s' called on incompatible object.")
1307
1308 (js2-msg "msg.bad.parms"
1309 "Unsupported parameter type '%s' in method '%s'.")
1310
1311 (js2-msg "msg.bad.method.return"
1312 "Unsupported return type '%s' in method '%s'.")
1313
1314 (js2-msg "msg.bad.ctor.return"
1315 "Construction of objects of type '%s' is not supported.")
1316
1317 (js2-msg "msg.no.overload"
1318 "Method '%s' occurs multiple times in class '%s'.")
1319
1320 (js2-msg "msg.method.not.found"
1321 "Method '%s' not found in '%s'.")
1322
1323 ;; IRFactory
1324
1325 (js2-msg "msg.bad.for.in.lhs"
1326 "Invalid left-hand side of for..in loop.")
1327
1328 (js2-msg "msg.mult.index"
1329 "Only one variable allowed in for..in loop.")
1330
1331 (js2-msg "msg.bad.for.in.destruct"
1332 "Left hand side of for..in loop must be an array of "
1333 "length 2 to accept key/value pair.")
1334
1335 (js2-msg "msg.cant.convert"
1336 "Can't convert to type '%s'.")
1337
1338 (js2-msg "msg.bad.assign.left"
1339 "Invalid assignment left-hand side.")
1340
1341 (js2-msg "msg.bad.decr"
1342 "Invalid decrement operand.")
1343
1344 (js2-msg "msg.bad.incr"
1345 "Invalid increment operand.")
1346
1347 (js2-msg "msg.bad.yield"
1348 "yield must be in a function.")
1349
1350 (js2-msg "msg.yield.parenthesized"
1351 "yield expression must be parenthesized.")
1352
1353 ;; NativeGlobal
1354 (js2-msg "msg.cant.call.indirect"
1355 "Function '%s' must be called directly, and not by way of a "
1356 "function of another name.")
1357
1358 (js2-msg "msg.eval.nonstring"
1359 "Calling eval() with anything other than a primitive "
1360 "string value will simply return the value. "
1361 "Is this what you intended?")
1362
1363 (js2-msg "msg.eval.nonstring.strict"
1364 "Calling eval() with anything other than a primitive "
1365 "string value is not allowed in strict mode.")
1366
1367 (js2-msg "msg.bad.destruct.op"
1368 "Invalid destructuring assignment operator")
1369
1370 ;; NativeCall
1371 (js2-msg "msg.only.from.new"
1372 "'%s' may only be invoked from a `new' expression.")
1373
1374 (js2-msg "msg.deprec.ctor"
1375 "The '%s' constructor is deprecated.")
1376
1377 ;; NativeFunction
1378 (js2-msg "msg.no.function.ref.found"
1379 "no source found to decompile function reference %s")
1380
1381 (js2-msg "msg.arg.isnt.array"
1382 "second argument to Function.prototype.apply must be an array")
1383
1384 ;; NativeGlobal
1385 (js2-msg "msg.bad.esc.mask"
1386 "invalid string escape mask")
1387
1388 ;; NativeRegExp
1389 (js2-msg "msg.bad.quant"
1390 "Invalid quantifier %s")
1391
1392 (js2-msg "msg.overlarge.backref"
1393 "Overly large back reference %s")
1394
1395 (js2-msg "msg.overlarge.min"
1396 "Overly large minimum %s")
1397
1398 (js2-msg "msg.overlarge.max"
1399 "Overly large maximum %s")
1400
1401 (js2-msg "msg.zero.quant"
1402 "Zero quantifier %s")
1403
1404 (js2-msg "msg.max.lt.min"
1405 "Maximum %s less than minimum")
1406
1407 (js2-msg "msg.unterm.quant"
1408 "Unterminated quantifier %s")
1409
1410 (js2-msg "msg.unterm.paren"
1411 "Unterminated parenthetical %s")
1412
1413 (js2-msg "msg.unterm.class"
1414 "Unterminated character class %s")
1415
1416 (js2-msg "msg.bad.range"
1417 "Invalid range in character class.")
1418
1419 (js2-msg "msg.trail.backslash"
1420 "Trailing \\ in regular expression.")
1421
1422 (js2-msg "msg.re.unmatched.right.paren"
1423 "unmatched ) in regular expression.")
1424
1425 (js2-msg "msg.no.regexp"
1426 "Regular expressions are not available.")
1427
1428 (js2-msg "msg.bad.backref"
1429 "back-reference exceeds number of capturing parentheses.")
1430
1431 (js2-msg "msg.bad.regexp.compile"
1432 "Only one argument may be specified if the first "
1433 "argument to RegExp.prototype.compile is a RegExp object.")
1434
1435 ;; Parser
1436 (js2-msg "msg.got.syntax.errors"
1437 "Compilation produced %s syntax errors.")
1438
1439 (js2-msg "msg.var.redecl"
1440 "TypeError: redeclaration of var %s.")
1441
1442 (js2-msg "msg.const.redecl"
1443 "TypeError: redeclaration of const %s.")
1444
1445 (js2-msg "msg.let.redecl"
1446 "TypeError: redeclaration of variable %s.")
1447
1448 (js2-msg "msg.parm.redecl"
1449 "TypeError: redeclaration of formal parameter %s.")
1450
1451 (js2-msg "msg.fn.redecl"
1452 "TypeError: redeclaration of function %s.")
1453
1454 (js2-msg "msg.let.decl.not.in.block"
1455 "SyntaxError: let declaration not directly within block")
1456
1457 (js2-msg "msg.mod.import.decl.at.top.level"
1458 "SyntaxError: import declarations may only appear at the top level")
1459
1460 (js2-msg "msg.mod.as.after.reserved.word"
1461 "SyntaxError: missing keyword 'as' after reserved word %s")
1462
1463 (js2-msg "msg.mod.rc.after.import.spec.list"
1464 "SyntaxError: missing '}' after module specifier list")
1465
1466 (js2-msg "msg.mod.from.after.import.spec.set"
1467 "SyntaxError: missing keyword 'from' after import specifier set")
1468
1469 (js2-msg "msg.mod.declaration.after.import"
1470 "SyntaxError: missing declaration after 'import' keyword")
1471
1472 (js2-msg "msg.mod.spec.after.from"
1473 "SyntaxError: missing module specifier after 'from' keyword")
1474
1475 (js2-msg "msg.mod.export.decl.at.top.level"
1476 "SyntaxError: export declarations may only appear at top level")
1477
1478 (js2-msg "msg.mod.rc.after.export.spec.list"
1479 "SyntaxError: missing '}' after export specifier list")
1480
1481 ;; NodeTransformer
1482 (js2-msg "msg.dup.label"
1483 "duplicated label")
1484
1485 (js2-msg "msg.undef.label"
1486 "undefined label")
1487
1488 (js2-msg "msg.bad.break"
1489 "unlabelled break must be inside loop or switch")
1490
1491 (js2-msg "msg.continue.outside"
1492 "continue must be inside loop")
1493
1494 (js2-msg "msg.continue.nonloop"
1495 "continue can only use labels of iteration statements")
1496
1497 (js2-msg "msg.bad.throw.eol"
1498 "Line terminator is not allowed between the throw "
1499 "keyword and throw expression.")
1500
1501 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1502 "function statement requires a name")
1503
1504 (js2-msg "msg.no.paren.parms"
1505 "missing ( before function parameters.")
1506
1507 (js2-msg "msg.no.parm"
1508 "missing formal parameter")
1509
1510 (js2-msg "msg.no.paren.after.parms"
1511 "missing ) after formal parameters")
1512
1513 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1514 "parameter without default follows parameter with default")
1515
1516 (js2-msg "msg.param.after.rest" ; added by js2-mode
1517 "parameter after rest parameter")
1518
1519 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1520 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1521
1522 (js2-msg "msg.no.brace.body"
1523 "missing '{' before function body")
1524
1525 (js2-msg "msg.no.brace.after.body"
1526 "missing } after function body")
1527
1528 (js2-msg "msg.no.paren.cond"
1529 "missing ( before condition")
1530
1531 (js2-msg "msg.no.paren.after.cond"
1532 "missing ) after condition")
1533
1534 (js2-msg "msg.no.semi.stmt"
1535 "missing ; before statement")
1536
1537 (js2-msg "msg.missing.semi"
1538 "missing ; after statement")
1539
1540 (js2-msg "msg.no.name.after.dot"
1541 "missing name after . operator")
1542
1543 (js2-msg "msg.no.name.after.coloncolon"
1544 "missing name after :: operator")
1545
1546 (js2-msg "msg.no.name.after.dotdot"
1547 "missing name after .. operator")
1548
1549 (js2-msg "msg.no.name.after.xmlAttr"
1550 "missing name after .@")
1551
1552 (js2-msg "msg.no.bracket.index"
1553 "missing ] in index expression")
1554
1555 (js2-msg "msg.no.paren.switch"
1556 "missing ( before switch expression")
1557
1558 (js2-msg "msg.no.paren.after.switch"
1559 "missing ) after switch expression")
1560
1561 (js2-msg "msg.no.brace.switch"
1562 "missing '{' before switch body")
1563
1564 (js2-msg "msg.bad.switch"
1565 "invalid switch statement")
1566
1567 (js2-msg "msg.no.colon.case"
1568 "missing : after case expression")
1569
1570 (js2-msg "msg.double.switch.default"
1571 "double default label in the switch statement")
1572
1573 (js2-msg "msg.no.while.do"
1574 "missing while after do-loop body")
1575
1576 (js2-msg "msg.no.paren.for"
1577 "missing ( after for")
1578
1579 (js2-msg "msg.no.semi.for"
1580 "missing ; after for-loop initializer")
1581
1582 (js2-msg "msg.no.semi.for.cond"
1583 "missing ; after for-loop condition")
1584
1585 (js2-msg "msg.in.after.for.name"
1586 "missing in or of after for")
1587
1588 (js2-msg "msg.no.paren.for.ctrl"
1589 "missing ) after for-loop control")
1590
1591 (js2-msg "msg.no.paren.with"
1592 "missing ( before with-statement object")
1593
1594 (js2-msg "msg.no.paren.after.with"
1595 "missing ) after with-statement object")
1596
1597 (js2-msg "msg.no.with.strict"
1598 "with statements not allowed in strict mode")
1599
1600 (js2-msg "msg.no.paren.after.let"
1601 "missing ( after let")
1602
1603 (js2-msg "msg.no.paren.let"
1604 "missing ) after variable list")
1605
1606 (js2-msg "msg.no.curly.let"
1607 "missing } after let statement")
1608
1609 (js2-msg "msg.bad.return"
1610 "invalid return")
1611
1612 (js2-msg "msg.no.brace.block"
1613 "missing } in compound statement")
1614
1615 (js2-msg "msg.bad.label"
1616 "invalid label")
1617
1618 (js2-msg "msg.bad.var"
1619 "missing variable name")
1620
1621 (js2-msg "msg.bad.var.init"
1622 "invalid variable initialization")
1623
1624 (js2-msg "msg.no.colon.cond"
1625 "missing : in conditional expression")
1626
1627 (js2-msg "msg.no.paren.arg"
1628 "missing ) after argument list")
1629
1630 (js2-msg "msg.no.bracket.arg"
1631 "missing ] after element list")
1632
1633 (js2-msg "msg.bad.prop"
1634 "invalid property id")
1635
1636 (js2-msg "msg.no.colon.prop"
1637 "missing : after property id")
1638
1639 (js2-msg "msg.no.brace.prop"
1640 "missing } after property list")
1641
1642 (js2-msg "msg.no.paren"
1643 "missing ) in parenthetical")
1644
1645 (js2-msg "msg.reserved.id"
1646 "'%s' is a reserved identifier")
1647
1648 (js2-msg "msg.no.paren.catch"
1649 "missing ( before catch-block condition")
1650
1651 (js2-msg "msg.bad.catchcond"
1652 "invalid catch block condition")
1653
1654 (js2-msg "msg.catch.unreachable"
1655 "any catch clauses following an unqualified catch are unreachable")
1656
1657 (js2-msg "msg.no.brace.try"
1658 "missing '{' before try block")
1659
1660 (js2-msg "msg.no.brace.catchblock"
1661 "missing '{' before catch-block body")
1662
1663 (js2-msg "msg.try.no.catchfinally"
1664 "'try' without 'catch' or 'finally'")
1665
1666 (js2-msg "msg.no.return.value"
1667 "function %s does not always return a value")
1668
1669 (js2-msg "msg.anon.no.return.value"
1670 "anonymous function does not always return a value")
1671
1672 (js2-msg "msg.return.inconsistent"
1673 "return statement is inconsistent with previous usage")
1674
1675 (js2-msg "msg.generator.returns"
1676 "TypeError: legacy generator function '%s' returns a value")
1677
1678 (js2-msg "msg.anon.generator.returns"
1679 "TypeError: anonymous legacy generator function returns a value")
1680
1681 (js2-msg "msg.syntax"
1682 "syntax error")
1683
1684 (js2-msg "msg.unexpected.eof"
1685 "Unexpected end of file")
1686
1687 (js2-msg "msg.XML.bad.form"
1688 "illegally formed XML syntax")
1689
1690 (js2-msg "msg.XML.not.available"
1691 "XML runtime not available")
1692
1693 (js2-msg "msg.too.deep.parser.recursion"
1694 "Too deep recursion while parsing")
1695
1696 (js2-msg "msg.no.side.effects"
1697 "Code has no side effects")
1698
1699 (js2-msg "msg.extra.trailing.comma"
1700 "Trailing comma is not supported in some browsers")
1701
1702 (js2-msg "msg.array.trailing.comma"
1703 "Trailing comma yields different behavior across browsers")
1704
1705 (js2-msg "msg.equal.as.assign"
1706 (concat "Test for equality (==) mistyped as assignment (=)?"
1707 " (parenthesize to suppress warning)"))
1708
1709 (js2-msg "msg.var.hides.arg"
1710 "Variable %s hides argument")
1711
1712 (js2-msg "msg.destruct.assign.no.init"
1713 "Missing = in destructuring declaration")
1714
1715 (js2-msg "msg.no.octal.strict"
1716 "Octal numbers prohibited in strict mode.")
1717
1718 (js2-msg "msg.dup.obj.lit.prop.strict"
1719 "Property '%s' already defined in this object literal.")
1720
1721 (js2-msg "msg.dup.param.strict"
1722 "Parameter '%s' already declared in this function.")
1723
1724 (js2-msg "msg.bad.id.strict"
1725 "'%s' is not a valid identifier for this use in strict mode.")
1726
1727 ;; ScriptRuntime
1728 (js2-msg "msg.no.properties"
1729 "%s has no properties.")
1730
1731 (js2-msg "msg.invalid.iterator"
1732 "Invalid iterator value")
1733
1734 (js2-msg "msg.iterator.primitive"
1735 "__iterator__ returned a primitive value")
1736
1737 (js2-msg "msg.assn.create.strict"
1738 "Assignment to undeclared variable %s")
1739
1740 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1741 "Undeclared variable or function '%s'")
1742
1743 (js2-msg "msg.unused.variable" ; added by js2-mode
1744 "Unused variable or function '%s'")
1745
1746 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1747 "Variable '%s' referenced but never initialized")
1748
1749 (js2-msg "msg.ref.undefined.prop"
1750 "Reference to undefined property '%s'")
1751
1752 (js2-msg "msg.prop.not.found"
1753 "Property %s not found.")
1754
1755 (js2-msg "msg.invalid.type"
1756 "Invalid JavaScript value of type %s")
1757
1758 (js2-msg "msg.primitive.expected"
1759 "Primitive type expected (had %s instead)")
1760
1761 (js2-msg "msg.namespace.expected"
1762 "Namespace object expected to left of :: (found %s instead)")
1763
1764 (js2-msg "msg.null.to.object"
1765 "Cannot convert null to an object.")
1766
1767 (js2-msg "msg.undef.to.object"
1768 "Cannot convert undefined to an object.")
1769
1770 (js2-msg "msg.cyclic.value"
1771 "Cyclic %s value not allowed.")
1772
1773 (js2-msg "msg.is.not.defined"
1774 "'%s' is not defined.")
1775
1776 (js2-msg "msg.undef.prop.read"
1777 "Cannot read property '%s' from %s")
1778
1779 (js2-msg "msg.undef.prop.write"
1780 "Cannot set property '%s' of %s to '%s'")
1781
1782 (js2-msg "msg.undef.prop.delete"
1783 "Cannot delete property '%s' of %s")
1784
1785 (js2-msg "msg.undef.method.call"
1786 "Cannot call method '%s' of %s")
1787
1788 (js2-msg "msg.undef.with"
1789 "Cannot apply 'with' to %s")
1790
1791 (js2-msg "msg.isnt.function"
1792 "%s is not a function, it is %s.")
1793
1794 (js2-msg "msg.isnt.function.in"
1795 "Cannot call property %s in object %s. "
1796 "It is not a function, it is '%s'.")
1797
1798 (js2-msg "msg.function.not.found"
1799 "Cannot find function %s.")
1800
1801 (js2-msg "msg.function.not.found.in"
1802 "Cannot find function %s in object %s.")
1803
1804 (js2-msg "msg.isnt.xml.object"
1805 "%s is not an xml object.")
1806
1807 (js2-msg "msg.no.ref.to.get"
1808 "%s is not a reference to read reference value.")
1809
1810 (js2-msg "msg.no.ref.to.set"
1811 "%s is not a reference to set reference value to %s.")
1812
1813 (js2-msg "msg.no.ref.from.function"
1814 "Function %s can not be used as the left-hand "
1815 "side of assignment or as an operand of ++ or -- operator.")
1816
1817 (js2-msg "msg.bad.default.value"
1818 "Object's getDefaultValue() method returned an object.")
1819
1820 (js2-msg "msg.instanceof.not.object"
1821 "Can't use instanceof on a non-object.")
1822
1823 (js2-msg "msg.instanceof.bad.prototype"
1824 "'prototype' property of %s is not an object.")
1825
1826 (js2-msg "msg.bad.radix"
1827 "illegal radix %s.")
1828
1829 ;; ScriptableObject
1830 (js2-msg "msg.default.value"
1831 "Cannot find default value for object.")
1832
1833 (js2-msg "msg.zero.arg.ctor"
1834 "Cannot load class '%s' which has no zero-parameter constructor.")
1835
1836 (js2-msg "msg.ctor.multiple.parms"
1837 "Can't define constructor or class %s since more than "
1838 "one constructor has multiple parameters.")
1839
1840 (js2-msg "msg.extend.scriptable"
1841 "%s must extend ScriptableObject in order to define property %s.")
1842
1843 (js2-msg "msg.bad.getter.parms"
1844 "In order to define a property, getter %s must have zero "
1845 "parameters or a single ScriptableObject parameter.")
1846
1847 (js2-msg "msg.obj.getter.parms"
1848 "Expected static or delegated getter %s to take "
1849 "a ScriptableObject parameter.")
1850
1851 (js2-msg "msg.getter.static"
1852 "Getter and setter must both be static or neither be static.")
1853
1854 (js2-msg "msg.setter.return"
1855 "Setter must have void return type: %s")
1856
1857 (js2-msg "msg.setter2.parms"
1858 "Two-parameter setter must take a ScriptableObject as "
1859 "its first parameter.")
1860
1861 (js2-msg "msg.setter1.parms"
1862 "Expected single parameter setter for %s")
1863
1864 (js2-msg "msg.setter2.expected"
1865 "Expected static or delegated setter %s to take two parameters.")
1866
1867 (js2-msg "msg.setter.parms"
1868 "Expected either one or two parameters for setter.")
1869
1870 (js2-msg "msg.setter.bad.type"
1871 "Unsupported parameter type '%s' in setter '%s'.")
1872
1873 (js2-msg "msg.add.sealed"
1874 "Cannot add a property to a sealed object: %s.")
1875
1876 (js2-msg "msg.remove.sealed"
1877 "Cannot remove a property from a sealed object: %s.")
1878
1879 (js2-msg "msg.modify.sealed"
1880 "Cannot modify a property of a sealed object: %s.")
1881
1882 (js2-msg "msg.modify.readonly"
1883 "Cannot modify readonly property: %s.")
1884
1885 ;; TokenStream
1886 (js2-msg "msg.missing.exponent"
1887 "missing exponent")
1888
1889 (js2-msg "msg.caught.nfe"
1890 "number format error")
1891
1892 (js2-msg "msg.unterminated.string.lit"
1893 "unterminated string literal")
1894
1895 (js2-msg "msg.unterminated.comment"
1896 "unterminated comment")
1897
1898 (js2-msg "msg.unterminated.re.lit"
1899 "unterminated regular expression literal")
1900
1901 (js2-msg "msg.invalid.re.flag"
1902 "invalid flag after regular expression")
1903
1904 (js2-msg "msg.no.re.input.for"
1905 "no input for %s")
1906
1907 (js2-msg "msg.illegal.character"
1908 "illegal character")
1909
1910 (js2-msg "msg.invalid.escape"
1911 "invalid Unicode escape sequence")
1912
1913 (js2-msg "msg.bad.namespace"
1914 "not a valid default namespace statement. "
1915 "Syntax is: default xml namespace = EXPRESSION;")
1916
1917 ;; TokensStream warnings
1918 (js2-msg "msg.bad.octal.literal"
1919 "illegal octal literal digit %s; "
1920 "interpreting it as a decimal digit")
1921
1922 (js2-msg "msg.missing.hex.digits"
1923 "missing hexadecimal digits after '0x'")
1924
1925 (js2-msg "msg.missing.binary.digits"
1926 "missing binary digits after '0b'")
1927
1928 (js2-msg "msg.missing.octal.digits"
1929 "missing octal digits after '0o'")
1930
1931 (js2-msg "msg.script.is.not.constructor"
1932 "Script objects are not constructors.")
1933
1934 ;; Arrays
1935 (js2-msg "msg.arraylength.bad"
1936 "Inappropriate array length.")
1937
1938 ;; Arrays
1939 (js2-msg "msg.arraylength.too.big"
1940 "Array length %s exceeds supported capacity limit.")
1941
1942 ;; URI
1943 (js2-msg "msg.bad.uri"
1944 "Malformed URI sequence.")
1945
1946 ;; Number
1947 (js2-msg "msg.bad.precision"
1948 "Precision %s out of range.")
1949
1950 ;; NativeGenerator
1951 (js2-msg "msg.send.newborn"
1952 "Attempt to send value to newborn generator")
1953
1954 (js2-msg "msg.already.exec.gen"
1955 "Already executing generator")
1956
1957 (js2-msg "msg.StopIteration.invalid"
1958 "StopIteration may not be changed to an arbitrary object.")
1959
1960 ;; Interpreter
1961 (js2-msg "msg.yield.closing"
1962 "Yield from closing generator")
1963
1964 ;; Classes
1965 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1966 "class statement requires a name")
1967
1968 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1969 "unexpected ',' between class properties")
1970
1971 (js2-msg "msg.unexpected.static" ; added by js2-mode
1972 "unexpected 'static'")
1973
1974 (js2-msg "msg.missing.extends" ; added by js2-mode
1975 "name is required after extends")
1976
1977 (js2-msg "msg.no.brace.class" ; added by js2-mode
1978 "missing '{' before class body")
1979
1980 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1981 "missing ']' after computed property expression")
1982
1983 ;;; Tokens Buffer
1984
1985 (defconst js2-ti-max-lookahead 2)
1986 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1987
1988 (defun js2-new-token (offset)
1989 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1990 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1991 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1992 token))
1993
1994 (defsubst js2-current-token ()
1995 (aref js2-ti-tokens js2-ti-tokens-cursor))
1996
1997 (defsubst js2-current-token-string ()
1998 (js2-token-string (js2-current-token)))
1999
2000 (defsubst js2-current-token-type ()
2001 (js2-token-type (js2-current-token)))
2002
2003 (defsubst js2-current-token-beg ()
2004 (js2-token-beg (js2-current-token)))
2005
2006 (defsubst js2-current-token-end ()
2007 (js2-token-end (js2-current-token)))
2008
2009 (defun js2-current-token-len ()
2010 (let ((token (js2-current-token)))
2011 (- (js2-token-end token)
2012 (js2-token-beg token))))
2013
2014 (defun js2-ts-seek (state)
2015 (setq js2-ts-lineno (js2-ts-state-lineno state)
2016 js2-ts-cursor (js2-ts-state-cursor state)
2017 js2-ti-tokens (js2-ts-state-tokens state)
2018 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2019 js2-ti-lookahead (js2-ts-state-lookahead state)))
2020
2021 ;;; Utilities
2022
2023 (defun js2-delete-if (predicate list)
2024 "Remove all items satisfying PREDICATE in LIST."
2025 (cl-loop for item in list
2026 if (not (funcall predicate item))
2027 collect item))
2028
2029 (defun js2-position (element list)
2030 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2031 Returns nil if element is not found in the list."
2032 (let ((count 0)
2033 found)
2034 (while (and list (not found))
2035 (if (eq element (car list))
2036 (setq found t)
2037 (setq count (1+ count)
2038 list (cdr list))))
2039 (if found count)))
2040
2041 (defun js2-find-if (predicate list)
2042 "Find first item satisfying PREDICATE in LIST."
2043 (let (result)
2044 (while (and list (not result))
2045 (if (funcall predicate (car list))
2046 (setq result (car list)))
2047 (setq list (cdr list)))
2048 result))
2049
2050 (defmacro js2-time (form)
2051 "Evaluate FORM, discard result, and return elapsed time in sec."
2052 (declare (debug t))
2053 (let ((beg (make-symbol "--js2-time-beg--")))
2054 `(let ((,beg (current-time)))
2055 ,form
2056 (/ (truncate (* (- (float-time (current-time))
2057 (float-time ,beg))
2058 10000))
2059 10000.0))))
2060
2061 (defsubst js2-same-line (pos)
2062 "Return t if POS is on the same line as current point."
2063 (and (>= pos (point-at-bol))
2064 (<= pos (point-at-eol))))
2065
2066 (defun js2-code-bug ()
2067 "Signal an error when we encounter an unexpected code path."
2068 (error "failed assertion"))
2069
2070 (defsubst js2-record-text-property (beg end prop value)
2071 "Record a text property to set when parsing finishes."
2072 (push (list beg end prop value) js2-mode-deferred-properties))
2073
2074 ;; I'd like to associate errors with nodes, but for now the
2075 ;; easiest thing to do is get the context info from the last token.
2076 (defun js2-record-parse-error (msg &optional arg pos len)
2077 (push (list (list msg arg)
2078 (or pos (js2-current-token-beg))
2079 (or len (js2-current-token-len)))
2080 js2-parsed-errors))
2081
2082 (defun js2-report-error (msg &optional msg-arg pos len)
2083 "Signal a syntax error or record a parse error."
2084 (if js2-recover-from-parse-errors
2085 (js2-record-parse-error msg msg-arg pos len)
2086 (signal 'js2-syntax-error
2087 (list msg
2088 js2-ts-lineno
2089 (save-excursion
2090 (goto-char js2-ts-cursor)
2091 (current-column))
2092 js2-ts-hit-eof))))
2093
2094 (defun js2-report-warning (msg &optional msg-arg pos len face)
2095 (if js2-compiler-report-warning-as-error
2096 (js2-report-error msg msg-arg pos len)
2097 (push (list (list msg msg-arg)
2098 (or pos (js2-current-token-beg))
2099 (or len (js2-current-token-len))
2100 face)
2101 js2-parsed-warnings)))
2102
2103 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2104 (if js2-compiler-strict-mode
2105 (js2-report-warning msg-id msg-arg beg
2106 (and beg end (- end beg)))))
2107
2108 (put 'js2-syntax-error 'error-conditions
2109 '(error syntax-error js2-syntax-error))
2110 (put 'js2-syntax-error 'error-message "Syntax error")
2111
2112 (put 'js2-parse-error 'error-conditions
2113 '(error parse-error js2-parse-error))
2114 (put 'js2-parse-error 'error-message "Parse error")
2115
2116 (defmacro js2-clear-flag (flags flag)
2117 `(setq ,flags (logand ,flags (lognot ,flag))))
2118
2119 (defmacro js2-set-flag (flags flag)
2120 "Logical-or FLAG into FLAGS."
2121 `(setq ,flags (logior ,flags ,flag)))
2122
2123 (defsubst js2-flag-set-p (flags flag)
2124 (/= 0 (logand flags flag)))
2125
2126 (defsubst js2-flag-not-set-p (flags flag)
2127 (zerop (logand flags flag)))
2128
2129 ;;; AST struct and function definitions
2130
2131 ;; flags for ast node property 'member-type (used for e4x operators)
2132 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2133 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2134 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2135
2136 (defsubst js2-relpos (pos anchor)
2137 "Convert POS to be relative to ANCHOR.
2138 If POS is nil, returns nil."
2139 (and pos (- pos anchor)))
2140
2141 (defun js2-make-pad (indent)
2142 (if (zerop indent)
2143 ""
2144 (make-string (* indent js2-basic-offset) ? )))
2145
2146 (defun js2-visit-ast (node callback)
2147 "Visit every node in ast NODE with visitor CALLBACK.
2148
2149 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2150 called twice: once to visit the node, and again after all the node's
2151 children have been processed. The END-P argument is nil on the first
2152 call and non-nil on the second call. The return value of the callback
2153 affects the traversal: if non-nil, the children of NODE are processed.
2154 If the callback returns nil, or if the node has no children, then the
2155 callback is called immediately with a non-nil END-P argument.
2156
2157 The node traversal is approximately lexical-order, although there
2158 are currently no guarantees around this."
2159 (when node
2160 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2161 ;; visit the node
2162 (when (funcall callback node nil)
2163 ;; visit the kids
2164 (cond
2165 ((eq vfunc 'js2-visit-none)
2166 nil) ; don't even bother calling it
2167 ;; Each AST node type has to define a `js2-visitor' function
2168 ;; that takes a node and a callback, and calls `js2-visit-ast'
2169 ;; on each child of the node.
2170 (vfunc
2171 (funcall vfunc node callback))
2172 (t
2173 (error "%s does not define a visitor-traversal function"
2174 (aref node 0)))))
2175 ;; call the end-visit
2176 (funcall callback node t))))
2177
2178 (cl-defstruct (js2-node
2179 (:constructor nil)) ; abstract
2180 "Base AST node type."
2181 (type -1) ; token type
2182 (pos -1) ; start position of this AST node in parsed input
2183 (len 1) ; num characters spanned by the node
2184 props ; optional node property list (an alist)
2185 parent) ; link to parent node; null for root
2186
2187 (defsubst js2-node-get-prop (node prop &optional default)
2188 (or (cadr (assoc prop (js2-node-props node))) default))
2189
2190 (defsubst js2-node-set-prop (node prop value)
2191 (setf (js2-node-props node)
2192 (cons (list prop value) (js2-node-props node))))
2193
2194 (defun js2-fixup-starts (n nodes)
2195 "Adjust the start positions of NODES to be relative to N.
2196 Any node in the list may be nil, for convenience."
2197 (dolist (node nodes)
2198 (when node
2199 (setf (js2-node-pos node) (- (js2-node-pos node)
2200 (js2-node-pos n))))))
2201
2202 (defun js2-node-add-children (parent &rest nodes)
2203 "Set parent node of NODES to PARENT, and return PARENT.
2204 Does nothing if we're not recording parent links.
2205 If any given node in NODES is nil, doesn't record that link."
2206 (js2-fixup-starts parent nodes)
2207 (dolist (node nodes)
2208 (and node
2209 (setf (js2-node-parent node) parent))))
2210
2211 ;; Non-recursive since it's called a frightening number of times.
2212 (defun js2-node-abs-pos (n)
2213 (let ((pos (js2-node-pos n)))
2214 (while (setq n (js2-node-parent n))
2215 (setq pos (+ pos (js2-node-pos n))))
2216 pos))
2217
2218 (defsubst js2-node-abs-end (n)
2219 "Return absolute buffer position of end of N."
2220 (+ (js2-node-abs-pos n) (js2-node-len n)))
2221
2222 ;; It's important to make sure block nodes have a Lisp list for the
2223 ;; child nodes, to limit printing recursion depth in an AST that
2224 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2225 ;; a sufficiently large vector tree.
2226
2227 (cl-defstruct (js2-block-node
2228 (:include js2-node)
2229 (:constructor nil)
2230 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2231 (pos (js2-current-token-beg))
2232 len
2233 props
2234 kids)))
2235 "A block of statements."
2236 kids) ; a Lisp list of the child statement nodes
2237
2238 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2239 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2240
2241 (defun js2-visit-block (ast callback)
2242 "Visit the `js2-block-node' children of AST."
2243 (dolist (kid (js2-block-node-kids ast))
2244 (js2-visit-ast kid callback)))
2245
2246 (defun js2-print-block (n i)
2247 (let ((pad (js2-make-pad i)))
2248 (insert pad "{\n")
2249 (dolist (kid (js2-block-node-kids n))
2250 (js2-print-ast kid (1+ i)))
2251 (insert pad "}")))
2252
2253 (cl-defstruct (js2-scope
2254 (:include js2-block-node)
2255 (:constructor nil)
2256 (:constructor make-js2-scope (&key (type js2-BLOCK)
2257 (pos (js2-current-token-beg))
2258 len
2259 kids)))
2260 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2261 ;; I don't have one of those handy, so I'll use an alist for now.
2262 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2263 ;; and is much lighter-weight to construct (both CPU and mem).
2264 ;; The keys are interned strings (symbols) for faster lookup.
2265 ;; Should switch to hybrid alist/hashtable eventually.
2266 symbol-table ; an alist of (symbol . js2-symbol)
2267 parent-scope ; a `js2-scope'
2268 top) ; top-level `js2-scope' (script/function)
2269
2270 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2271 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2272
2273 (defun js2-node-get-enclosing-scope (node)
2274 "Return the innermost `js2-scope' node surrounding NODE.
2275 Returns nil if there is no enclosing scope node."
2276 (while (and (setq node (js2-node-parent node))
2277 (not (js2-scope-p node))))
2278 node)
2279
2280 (defun js2-get-defining-scope (scope name &optional point)
2281 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2282 Returns `js2-scope' in which NAME is defined, or nil if not found.
2283
2284 If POINT is non-nil, and if the found declaration type is
2285 `js2-LET', also check that the declaration node is before POINT."
2286 (let ((sym (if (symbolp name)
2287 name
2288 (intern name)))
2289 result
2290 (continue t))
2291 (while (and scope continue)
2292 (if (or
2293 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2294 (and entry
2295 (or (not point)
2296 (not (eq js2-LET (js2-symbol-decl-type entry)))
2297 (>= point
2298 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2299 (and (eq sym 'arguments)
2300 (js2-function-node-p scope)))
2301 (setq continue nil
2302 result scope)
2303 (setq scope (js2-scope-parent-scope scope))))
2304 result))
2305
2306 (defun js2-scope-get-symbol (scope name)
2307 "Return symbol table entry for NAME in SCOPE.
2308 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2309 (and (js2-scope-symbol-table scope)
2310 (cdr (assq (if (symbolp name)
2311 name
2312 (intern name))
2313 (js2-scope-symbol-table scope)))))
2314
2315 (defun js2-scope-put-symbol (scope name symbol)
2316 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2317 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2318 (let* ((table (js2-scope-symbol-table scope))
2319 (sym (if (symbolp name) name (intern name)))
2320 (entry (assq sym table)))
2321 (if entry
2322 (setcdr entry symbol)
2323 (push (cons sym symbol)
2324 (js2-scope-symbol-table scope)))))
2325
2326 (cl-defstruct (js2-symbol
2327 (:constructor nil)
2328 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2329 "A symbol table entry."
2330 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2331 ;; js2-LET, or js2-CONST
2332 decl-type
2333 name ; string
2334 ast-node) ; a `js2-node'
2335
2336 (cl-defstruct (js2-error-node
2337 (:include js2-node)
2338 (:constructor nil) ; silence emacs21 byte-compiler
2339 (:constructor make-js2-error-node (&key (type js2-ERROR)
2340 (pos (js2-current-token-beg))
2341 len)))
2342 "AST node representing a parse error.")
2343
2344 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2345 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2346
2347 (cl-defstruct (js2-script-node
2348 (:include js2-scope)
2349 (:constructor nil)
2350 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2351 (pos (js2-current-token-beg))
2352 len
2353 ;; FIXME: What are those?
2354 var-decls
2355 fun-decls)))
2356 functions ; Lisp list of nested functions
2357 regexps ; Lisp list of (string . flags)
2358 symbols ; alist (every symbol gets unique index)
2359 (param-count 0)
2360 var-names ; vector of string names
2361 consts ; bool-vector matching var-decls
2362 (temp-number 0)) ; for generating temp variables
2363
2364 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2365 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2366
2367 (defun js2-print-script (node indent)
2368 (dolist (kid (js2-block-node-kids node))
2369 (js2-print-ast kid indent)))
2370
2371 (cl-defstruct (js2-ast-root
2372 (:include js2-script-node)
2373 (:constructor nil)
2374 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2375 (pos (js2-current-token-beg))
2376 len
2377 buffer)))
2378 "The root node of a js2 AST."
2379 buffer ; the source buffer from which the code was parsed
2380 comments ; a Lisp list of comments, ordered by start position
2381 errors ; a Lisp list of errors found during parsing
2382 warnings ; a Lisp list of warnings found during parsing
2383 node-count) ; number of nodes in the tree, including the root
2384
2385 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2386 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2387
2388 (defun js2-visit-ast-root (ast callback)
2389 (dolist (kid (js2-ast-root-kids ast))
2390 (js2-visit-ast kid callback))
2391 (dolist (comment (js2-ast-root-comments ast))
2392 (js2-visit-ast comment callback)))
2393
2394 (cl-defstruct (js2-comment-node
2395 (:include js2-node)
2396 (:constructor nil)
2397 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2398 (pos (js2-current-token-beg))
2399 len
2400 format)))
2401 format) ; 'line, 'block, 'jsdoc or 'html
2402
2403 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2404 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2405
2406 (defun js2-print-comment (n i)
2407 ;; We really ought to link end-of-line comments to their nodes.
2408 ;; Or maybe we could add a new comment type, 'endline.
2409 (insert (js2-make-pad i)
2410 (js2-node-string n)))
2411
2412 (cl-defstruct (js2-expr-stmt-node
2413 (:include js2-node)
2414 (:constructor nil)
2415 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2416 (pos js2-ts-cursor)
2417 len
2418 expr)))
2419 "An expression statement."
2420 expr)
2421
2422 (defsubst js2-expr-stmt-node-set-has-result (node)
2423 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2424 (setf (js2-node-type node) js2-EXPR_RESULT))
2425
2426 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2427 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2428
2429 (defun js2-visit-expr-stmt-node (n v)
2430 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2431
2432 (defun js2-print-expr-stmt-node (n indent)
2433 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2434 (insert ";\n"))
2435
2436 (cl-defstruct (js2-loop-node
2437 (:include js2-scope)
2438 (:constructor nil))
2439 "Abstract supertype of loop nodes."
2440 body ; a `js2-block-node'
2441 lp ; position of left-paren, nil if omitted
2442 rp) ; position of right-paren, nil if omitted
2443
2444 (cl-defstruct (js2-do-node
2445 (:include js2-loop-node)
2446 (:constructor nil)
2447 (:constructor make-js2-do-node (&key (type js2-DO)
2448 (pos (js2-current-token-beg))
2449 len
2450 body
2451 condition
2452 while-pos
2453 lp
2454 rp)))
2455 "AST node for do-loop."
2456 condition ; while (expression)
2457 while-pos) ; buffer position of 'while' keyword
2458
2459 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2460 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2461
2462 (defun js2-visit-do-node (n v)
2463 (js2-visit-ast (js2-do-node-body n) v)
2464 (js2-visit-ast (js2-do-node-condition n) v))
2465
2466 (defun js2-print-do-node (n i)
2467 (let ((pad (js2-make-pad i)))
2468 (insert pad "do {\n")
2469 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2470 (js2-print-ast kid (1+ i)))
2471 (insert pad "} while (")
2472 (js2-print-ast (js2-do-node-condition n) 0)
2473 (insert ");\n")))
2474
2475 (cl-defstruct (js2-export-node
2476 (:include js2-node)
2477 (:constructor nil)
2478 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2479 (pos (js2-current-token-beg))
2480 len
2481 exports-list
2482 from-clause
2483 declaration
2484 default)))
2485 "AST node for an export statement. There are many things that can be exported,
2486 so many of its properties will be nil.
2487 "
2488 exports-list ; lisp list of js2-export-binding-node to export
2489 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2490 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2491 default) ; js2-function-node or js2-assign-node
2492
2493 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2494 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2495
2496 (defun js2-visit-export-node (n v)
2497 (let ((exports-list (js2-export-node-exports-list n))
2498 (from (js2-export-node-from-clause n))
2499 (declaration (js2-export-node-declaration n))
2500 (default (js2-export-node-default n)))
2501 (when exports-list
2502 (dolist (export exports-list)
2503 (js2-visit-ast export v)))
2504 (when from
2505 (js2-visit-ast from v))
2506 (when declaration
2507 (js2-visit-ast declaration v))
2508 (when default
2509 (js2-visit-ast default v))))
2510
2511 (defun js2-print-export-node (n i)
2512 (let ((pad (js2-make-pad i))
2513 (exports-list (js2-export-node-exports-list n))
2514 (from (js2-export-node-from-clause n))
2515 (declaration (js2-export-node-declaration n))
2516 (default (js2-export-node-default n)))
2517 (insert pad "export ")
2518 (cond
2519 (default
2520 (insert "default ")
2521 (js2-print-ast default i))
2522 (declaration
2523 (js2-print-ast declaration i))
2524 ((and exports-list from)
2525 (js2-print-named-imports exports-list)
2526 (insert " ")
2527 (js2-print-from-clause from))
2528 (from
2529 (insert "* ")
2530 (js2-print-from-clause from))
2531 (exports-list
2532 (js2-print-named-imports exports-list)))
2533 (insert ";\n")))
2534
2535 (cl-defstruct (js2-while-node
2536 (:include js2-loop-node)
2537 (:constructor nil)
2538 (:constructor make-js2-while-node (&key (type js2-WHILE)
2539 (pos (js2-current-token-beg))
2540 len body
2541 condition lp
2542 rp)))
2543 "AST node for while-loop."
2544 condition) ; while-condition
2545
2546 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2547 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2548
2549 (defun js2-visit-while-node (n v)
2550 (js2-visit-ast (js2-while-node-condition n) v)
2551 (js2-visit-ast (js2-while-node-body n) v))
2552
2553 (defun js2-print-while-node (n i)
2554 (let ((pad (js2-make-pad i)))
2555 (insert pad "while (")
2556 (js2-print-ast (js2-while-node-condition n) 0)
2557 (insert ") {\n")
2558 (js2-print-body (js2-while-node-body n) (1+ i))
2559 (insert pad "}\n")))
2560
2561 (cl-defstruct (js2-for-node
2562 (:include js2-loop-node)
2563 (:constructor nil)
2564 (:constructor make-js2-for-node (&key (type js2-FOR)
2565 (pos js2-ts-cursor)
2566 len body init
2567 condition
2568 update lp rp)))
2569 "AST node for a C-style for-loop."
2570 init ; initialization expression
2571 condition ; loop condition
2572 update) ; update clause
2573
2574 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2575 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2576
2577 (defun js2-visit-for-node (n v)
2578 (js2-visit-ast (js2-for-node-init n) v)
2579 (js2-visit-ast (js2-for-node-condition n) v)
2580 (js2-visit-ast (js2-for-node-update n) v)
2581 (js2-visit-ast (js2-for-node-body n) v))
2582
2583 (defun js2-print-for-node (n i)
2584 (let ((pad (js2-make-pad i)))
2585 (insert pad "for (")
2586 (js2-print-ast (js2-for-node-init n) 0)
2587 (insert "; ")
2588 (js2-print-ast (js2-for-node-condition n) 0)
2589 (insert "; ")
2590 (js2-print-ast (js2-for-node-update n) 0)
2591 (insert ") {\n")
2592 (js2-print-body (js2-for-node-body n) (1+ i))
2593 (insert pad "}\n")))
2594
2595 (cl-defstruct (js2-for-in-node
2596 (:include js2-loop-node)
2597 (:constructor nil)
2598 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2599 (pos js2-ts-cursor)
2600 len body
2601 iterator
2602 object
2603 in-pos
2604 each-pos
2605 foreach-p forof-p
2606 lp rp)))
2607 "AST node for a for..in loop."
2608 iterator ; [var] foo in ...
2609 object ; object over which we're iterating
2610 in-pos ; buffer position of 'in' keyword
2611 each-pos ; buffer position of 'each' keyword, if foreach-p
2612 foreach-p ; t if it's a for-each loop
2613 forof-p) ; t if it's a for-of loop
2614
2615 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2616 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2617
2618 (defun js2-visit-for-in-node (n v)
2619 (js2-visit-ast (js2-for-in-node-iterator n) v)
2620 (js2-visit-ast (js2-for-in-node-object n) v)
2621 (js2-visit-ast (js2-for-in-node-body n) v))
2622
2623 (defun js2-print-for-in-node (n i)
2624 (let ((pad (js2-make-pad i))
2625 (foreach (js2-for-in-node-foreach-p n))
2626 (forof (js2-for-in-node-forof-p n)))
2627 (insert pad "for ")
2628 (if foreach
2629 (insert "each "))
2630 (insert "(")
2631 (js2-print-ast (js2-for-in-node-iterator n) 0)
2632 (insert (if forof " of " " in "))
2633 (js2-print-ast (js2-for-in-node-object n) 0)
2634 (insert ") {\n")
2635 (js2-print-body (js2-for-in-node-body n) (1+ i))
2636 (insert pad "}\n")))
2637
2638 (cl-defstruct (js2-return-node
2639 (:include js2-node)
2640 (:constructor nil)
2641 (:constructor make-js2-return-node (&key (type js2-RETURN)
2642 (pos js2-ts-cursor)
2643 len
2644 retval)))
2645 "AST node for a return statement."
2646 retval) ; expression to return, or 'undefined
2647
2648 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2649 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2650
2651 (defun js2-visit-return-node (n v)
2652 (js2-visit-ast (js2-return-node-retval n) v))
2653
2654 (defun js2-print-return-node (n i)
2655 (insert (js2-make-pad i) "return")
2656 (when (js2-return-node-retval n)
2657 (insert " ")
2658 (js2-print-ast (js2-return-node-retval n) 0))
2659 (insert ";\n"))
2660
2661 (cl-defstruct (js2-if-node
2662 (:include js2-node)
2663 (:constructor nil)
2664 (:constructor make-js2-if-node (&key (type js2-IF)
2665 (pos js2-ts-cursor)
2666 len condition
2667 then-part
2668 else-pos
2669 else-part lp
2670 rp)))
2671 "AST node for an if-statement."
2672 condition ; expression
2673 then-part ; statement or block
2674 else-pos ; optional buffer position of 'else' keyword
2675 else-part ; optional statement or block
2676 lp ; position of left-paren, nil if omitted
2677 rp) ; position of right-paren, nil if omitted
2678
2679 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2680 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2681
2682 (defun js2-visit-if-node (n v)
2683 (js2-visit-ast (js2-if-node-condition n) v)
2684 (js2-visit-ast (js2-if-node-then-part n) v)
2685 (js2-visit-ast (js2-if-node-else-part n) v))
2686
2687 (defun js2-print-if-node (n i)
2688 (let ((pad (js2-make-pad i))
2689 (then-part (js2-if-node-then-part n))
2690 (else-part (js2-if-node-else-part n)))
2691 (insert pad "if (")
2692 (js2-print-ast (js2-if-node-condition n) 0)
2693 (insert ") {\n")
2694 (js2-print-body then-part (1+ i))
2695 (insert pad "}")
2696 (cond
2697 ((not else-part)
2698 (insert "\n"))
2699 ((js2-if-node-p else-part)
2700 (insert " else ")
2701 (js2-print-body else-part i))
2702 (t
2703 (insert " else {\n")
2704 (js2-print-body else-part (1+ i))
2705 (insert pad "}\n")))))
2706
2707 (cl-defstruct (js2-export-binding-node
2708 (:include js2-node)
2709 (:constructor nil)
2710 (:constructor make-js2-export-binding-node (&key (type -1)
2711 pos
2712 len
2713 local-name
2714 extern-name)))
2715 "AST node for an external symbol binding.
2716 It contains a local-name node which is the name of the value in the
2717 current scope, and extern-name which is the name of the value in the
2718 imported or exported scope. By default these are the same, but if the
2719 name is aliased as in {foo as bar}, it would have an extern-name node
2720 containing 'foo' and a local-name node containing 'bar'."
2721 local-name ; js2-name-node with the variable name in this scope
2722 extern-name) ; js2-name-node with the value name in the exporting module
2723
2724 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2725 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2726
2727 (defun js2-visit-extern-binding (n v)
2728 "Visit an extern binding node. First visit the local-name, and, if
2729 different, visit the extern-name."
2730 (let ((local-name (js2-export-binding-node-local-name n))
2731 (extern-name (js2-export-binding-node-extern-name n)))
2732 (when local-name
2733 (js2-visit-ast local-name v))
2734 (when (not (equal local-name extern-name))
2735 (js2-visit-ast extern-name v))))
2736
2737 (defun js2-print-extern-binding (n _i)
2738 "Print a representation of a single extern binding. E.g. 'foo' or
2739 'foo as bar'."
2740 (let ((local-name (js2-export-binding-node-local-name n))
2741 (extern-name (js2-export-binding-node-extern-name n)))
2742 (insert (js2-name-node-name extern-name))
2743 (when (not (equal local-name extern-name))
2744 (insert " as ")
2745 (insert (js2-name-node-name local-name)))))
2746
2747
2748 (cl-defstruct (js2-import-node
2749 (:include js2-node)
2750 (:constructor nil)
2751 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2752 (pos (js2-current-token-beg))
2753 len
2754 import
2755 from
2756 module-id)))
2757 "AST node for an import statement. It follows the form
2758
2759 import ModuleSpecifier;
2760 import ImportClause FromClause;"
2761 import ; js2-import-clause-node specifying which names are to imported.
2762 from ; js2-from-clause-node indicating the module from which to import.
2763 module-id) ; module-id of the import. E.g. 'src/mylib'.
2764
2765 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2766 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2767
2768 (defun js2-visit-import (n v)
2769 (let ((import-clause (js2-import-node-import n))
2770 (from-clause (js2-import-node-from n)))
2771 (when import-clause
2772 (js2-visit-ast import-clause v))
2773 (when from-clause
2774 (js2-visit-ast from-clause v))))
2775
2776 (defun js2-print-import (n i)
2777 "Prints a representation of the import node"
2778 (let ((pad (js2-make-pad i))
2779 (import-clause (js2-import-node-import n))
2780 (from-clause (js2-import-node-from n))
2781 (module-id (js2-import-node-module-id n)))
2782 (insert pad "import ")
2783 (if import-clause
2784 (progn
2785 (js2-print-import-clause import-clause)
2786 (insert " ")
2787 (js2-print-from-clause from-clause))
2788 (insert "'")
2789 (insert module-id)
2790 (insert "'"))
2791 (insert ";\n")))
2792
2793 (cl-defstruct (js2-import-clause-node
2794 (:include js2-node)
2795 (:constructor nil)
2796 (:constructor make-js2-import-clause-node (&key (type -1)
2797 pos
2798 len
2799 namespace-import
2800 named-imports
2801 default-binding)))
2802 "AST node corresponding to the import clause of an import statement. This is
2803 the portion of the import that bindings names from the external context to the
2804 local context."
2805 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2806 named-imports ; lisp list of js2-export-binding-node for all named imports.
2807 default-binding) ; js2-export-binding-node for the default import binding
2808
2809 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2810 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2811
2812 (defun js2-visit-import-clause (n v)
2813 (let ((ns-import (js2-import-clause-node-namespace-import n))
2814 (named-imports (js2-import-clause-node-named-imports n))
2815 (default (js2-import-clause-node-default-binding n)))
2816 (when ns-import
2817 (js2-visit-ast ns-import v))
2818 (when named-imports
2819 (dolist (import named-imports)
2820 (js2-visit-ast import v)))
2821 (when default
2822 (js2-visit-ast default v))))
2823
2824 (defun js2-print-import-clause (n)
2825 (let ((ns-import (js2-import-clause-node-namespace-import n))
2826 (named-imports (js2-import-clause-node-named-imports n))
2827 (default (js2-import-clause-node-default-binding n)))
2828 (cond
2829 ((and default ns-import)
2830 (js2-print-ast default)
2831 (insert ", ")
2832 (js2-print-namespace-import ns-import))
2833 ((and default named-imports)
2834 (js2-print-ast default)
2835 (insert ", ")
2836 (js2-print-named-imports named-imports))
2837 (default
2838 (js2-print-ast default))
2839 (ns-import
2840 (js2-print-namespace-import ns-import))
2841 (named-imports
2842 (js2-print-named-imports named-imports)))))
2843
2844 (defun js2-print-namespace-import (node)
2845 (insert "* as ")
2846 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2847
2848 (defun js2-print-named-imports (imports)
2849 (insert "{")
2850 (let ((len (length imports))
2851 (n 0))
2852 (while (< n len)
2853 (js2-print-extern-binding (nth n imports) 0)
2854 (unless (= n (- len 1))
2855 (insert ", "))
2856 (setq n (+ n 1))))
2857 (insert "}"))
2858
2859 (cl-defstruct (js2-namespace-import-node
2860 (:include js2-node)
2861 (:constructor nil)
2862 (:constructor make-js2-namespace-import-node (&key (type -1)
2863 pos
2864 len
2865 name)))
2866 "AST node for a complete namespace import.
2867 E.g. the '* as lib' expression in:
2868
2869 import * as lib from 'src/lib'
2870
2871 It contains a single name node referring to the bound name."
2872 name) ; js2-name-node of the bound name.
2873
2874 (defun js2-visit-namespace-import (n v)
2875 (js2-visit-ast (js2-namespace-import-node-name n) v))
2876
2877 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2878 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2879
2880 (cl-defstruct (js2-from-clause-node
2881 (:include js2-node)
2882 (:constructor nil)
2883 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2884 pos
2885 len
2886 module-id
2887 metadata-p)))
2888 "AST node for the from clause in an import or export statement.
2889 E.g. from 'my/module'. It can refere to either an external module, or to the
2890 modules metadata itself."
2891 module-id ; string containing the module specifier.
2892 metadata-p) ; true if this clause refers to the module's metadata
2893
2894 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2895 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2896
2897 (defun js2-print-from-clause (n)
2898 (insert "from ")
2899 (if (js2-from-clause-node-metadata-p n)
2900 (insert "this module")
2901 (insert "'")
2902 (insert (js2-from-clause-node-module-id n))
2903 (insert "'")))
2904
2905 (cl-defstruct (js2-try-node
2906 (:include js2-node)
2907 (:constructor nil)
2908 (:constructor make-js2-try-node (&key (type js2-TRY)
2909 (pos js2-ts-cursor)
2910 len
2911 try-block
2912 catch-clauses
2913 finally-block)))
2914 "AST node for a try-statement."
2915 try-block
2916 catch-clauses ; a Lisp list of `js2-catch-node'
2917 finally-block) ; a `js2-finally-node'
2918
2919 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2920 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2921
2922 (defun js2-visit-try-node (n v)
2923 (js2-visit-ast (js2-try-node-try-block n) v)
2924 (dolist (clause (js2-try-node-catch-clauses n))
2925 (js2-visit-ast clause v))
2926 (js2-visit-ast (js2-try-node-finally-block n) v))
2927
2928 (defun js2-print-try-node (n i)
2929 (let ((pad (js2-make-pad i))
2930 (catches (js2-try-node-catch-clauses n))
2931 (finally (js2-try-node-finally-block n)))
2932 (insert pad "try {\n")
2933 (js2-print-body (js2-try-node-try-block n) (1+ i))
2934 (insert pad "}")
2935 (when catches
2936 (dolist (catch catches)
2937 (js2-print-ast catch i)))
2938 (if finally
2939 (js2-print-ast finally i)
2940 (insert "\n"))))
2941
2942 (cl-defstruct (js2-catch-node
2943 (:include js2-scope)
2944 (:constructor nil)
2945 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2946 (pos js2-ts-cursor)
2947 len
2948 param
2949 guard-kwd
2950 guard-expr
2951 lp rp)))
2952 "AST node for a catch clause."
2953 param ; destructuring form or simple name node
2954 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2955 guard-expr ; catch condition, a `js2-node'
2956 lp ; buffer position of left-paren, nil if omitted
2957 rp) ; buffer position of right-paren, nil if omitted
2958
2959 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2960 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2961
2962 (defun js2-visit-catch-node (n v)
2963 (js2-visit-ast (js2-catch-node-param n) v)
2964 (when (js2-catch-node-guard-kwd n)
2965 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2966 (js2-visit-block n v))
2967
2968 (defun js2-print-catch-node (n i)
2969 (let ((pad (js2-make-pad i))
2970 (guard-kwd (js2-catch-node-guard-kwd n))
2971 (guard-expr (js2-catch-node-guard-expr n)))
2972 (insert " catch (")
2973 (js2-print-ast (js2-catch-node-param n) 0)
2974 (when guard-kwd
2975 (insert " if ")
2976 (js2-print-ast guard-expr 0))
2977 (insert ") {\n")
2978 (js2-print-body n (1+ i))
2979 (insert pad "}")))
2980
2981 (cl-defstruct (js2-finally-node
2982 (:include js2-node)
2983 (:constructor nil)
2984 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2985 (pos js2-ts-cursor)
2986 len body)))
2987 "AST node for a finally clause."
2988 body) ; a `js2-node', often but not always a block node
2989
2990 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2991 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2992
2993 (defun js2-visit-finally-node (n v)
2994 (js2-visit-ast (js2-finally-node-body n) v))
2995
2996 (defun js2-print-finally-node (n i)
2997 (let ((pad (js2-make-pad i)))
2998 (insert " finally {\n")
2999 (js2-print-body (js2-finally-node-body n) (1+ i))
3000 (insert pad "}\n")))
3001
3002 (cl-defstruct (js2-switch-node
3003 (:include js2-node)
3004 (:constructor nil)
3005 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3006 (pos js2-ts-cursor)
3007 len
3008 discriminant
3009 cases lp
3010 rp)))
3011 "AST node for a switch statement."
3012 discriminant ; a `js2-node' (switch expression)
3013 cases ; a Lisp list of `js2-case-node'
3014 lp ; position of open-paren for discriminant, nil if omitted
3015 rp) ; position of close-paren for discriminant, nil if omitted
3016
3017 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3018 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3019
3020 (defun js2-visit-switch-node (n v)
3021 (js2-visit-ast (js2-switch-node-discriminant n) v)
3022 (dolist (c (js2-switch-node-cases n))
3023 (js2-visit-ast c v)))
3024
3025 (defun js2-print-switch-node (n i)
3026 (let ((pad (js2-make-pad i))
3027 (cases (js2-switch-node-cases n)))
3028 (insert pad "switch (")
3029 (js2-print-ast (js2-switch-node-discriminant n) 0)
3030 (insert ") {\n")
3031 (dolist (case cases)
3032 (js2-print-ast case i))
3033 (insert pad "}\n")))
3034
3035 (cl-defstruct (js2-case-node
3036 (:include js2-block-node)
3037 (:constructor nil)
3038 (:constructor make-js2-case-node (&key (type js2-CASE)
3039 (pos js2-ts-cursor)
3040 len kids expr)))
3041 "AST node for a case clause of a switch statement."
3042 expr) ; the case expression (nil for default)
3043
3044 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3045 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3046
3047 (defun js2-visit-case-node (n v)
3048 (js2-visit-ast (js2-case-node-expr n) v)
3049 (js2-visit-block n v))
3050
3051 (defun js2-print-case-node (n i)
3052 (let ((pad (js2-make-pad i))
3053 (expr (js2-case-node-expr n)))
3054 (insert pad)
3055 (if (null expr)
3056 (insert "default:\n")
3057 (insert "case ")
3058 (js2-print-ast expr 0)
3059 (insert ":\n"))
3060 (dolist (kid (js2-case-node-kids n))
3061 (js2-print-ast kid (1+ i)))))
3062
3063 (cl-defstruct (js2-throw-node
3064 (:include js2-node)
3065 (:constructor nil)
3066 (:constructor make-js2-throw-node (&key (type js2-THROW)
3067 (pos js2-ts-cursor)
3068 len expr)))
3069 "AST node for a throw statement."
3070 expr) ; the expression to throw
3071
3072 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3073 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3074
3075 (defun js2-visit-throw-node (n v)
3076 (js2-visit-ast (js2-throw-node-expr n) v))
3077
3078 (defun js2-print-throw-node (n i)
3079 (insert (js2-make-pad i) "throw ")
3080 (js2-print-ast (js2-throw-node-expr n) 0)
3081 (insert ";\n"))
3082
3083 (cl-defstruct (js2-with-node
3084 (:include js2-node)
3085 (:constructor nil)
3086 (:constructor make-js2-with-node (&key (type js2-WITH)
3087 (pos js2-ts-cursor)
3088 len object
3089 body lp rp)))
3090 "AST node for a with-statement."
3091 object
3092 body
3093 lp ; buffer position of left-paren around object, nil if omitted
3094 rp) ; buffer position of right-paren around object, nil if omitted
3095
3096 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3097 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3098
3099 (defun js2-visit-with-node (n v)
3100 (js2-visit-ast (js2-with-node-object n) v)
3101 (js2-visit-ast (js2-with-node-body n) v))
3102
3103 (defun js2-print-with-node (n i)
3104 (let ((pad (js2-make-pad i)))
3105 (insert pad "with (")
3106 (js2-print-ast (js2-with-node-object n) 0)
3107 (insert ") {\n")
3108 (js2-print-body (js2-with-node-body n) (1+ i))
3109 (insert pad "}\n")))
3110
3111 (cl-defstruct (js2-label-node
3112 (:include js2-node)
3113 (:constructor nil)
3114 (:constructor make-js2-label-node (&key (type js2-LABEL)
3115 (pos js2-ts-cursor)
3116 len name)))
3117 "AST node for a statement label or case label."
3118 name ; a string
3119 loop) ; for validating and code-generating continue-to-label
3120
3121 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3122 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3123
3124 (defun js2-print-label (n i)
3125 (insert (js2-make-pad i)
3126 (js2-label-node-name n)
3127 ":\n"))
3128
3129 (cl-defstruct (js2-labeled-stmt-node
3130 (:include js2-node)
3131 (:constructor nil)
3132 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3133 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3134 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3135 (pos js2-ts-cursor)
3136 len labels stmt)))
3137 "AST node for a statement with one or more labels.
3138 Multiple labels for a statement are collapsed into the labels field."
3139 labels ; Lisp list of `js2-label-node'
3140 stmt) ; the statement these labels are for
3141
3142 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3143 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3144
3145 (defun js2-get-label-by-name (lbl-stmt name)
3146 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3147 Returns nil if no such label is in the list."
3148 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3149 result)
3150 (while (and label-list (not result))
3151 (if (string= (js2-label-node-name (car label-list)) name)
3152 (setq result (car label-list))
3153 (setq label-list (cdr label-list))))
3154 result))
3155
3156 (defun js2-visit-labeled-stmt (n v)
3157 (dolist (label (js2-labeled-stmt-node-labels n))
3158 (js2-visit-ast label v))
3159 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3160
3161 (defun js2-print-labeled-stmt (n i)
3162 (dolist (label (js2-labeled-stmt-node-labels n))
3163 (js2-print-ast label i))
3164 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3165
3166 (defun js2-labeled-stmt-node-contains (node label)
3167 "Return t if NODE contains LABEL in its label set.
3168 NODE is a `js2-labels-node'. LABEL is an identifier."
3169 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3170 if (string= label (js2-label-node-name nl))
3171 return t
3172 finally return nil))
3173
3174 (defsubst js2-labeled-stmt-node-add-label (node label)
3175 "Add a `js2-label-node' to the label set for this statement."
3176 (setf (js2-labeled-stmt-node-labels node)
3177 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3178
3179 (cl-defstruct (js2-jump-node
3180 (:include js2-node)
3181 (:constructor nil))
3182 "Abstract supertype of break and continue nodes."
3183 label ; `js2-name-node' for location of label identifier, if present
3184 target) ; target js2-labels-node or loop/switch statement
3185
3186 (defun js2-visit-jump-node (n v)
3187 ;; We don't visit the target, since it's a back-link.
3188 (js2-visit-ast (js2-jump-node-label n) v))
3189
3190 (cl-defstruct (js2-break-node
3191 (:include js2-jump-node)
3192 (:constructor nil)
3193 (:constructor make-js2-break-node (&key (type js2-BREAK)
3194 (pos js2-ts-cursor)
3195 len label target)))
3196 "AST node for a break statement.
3197 The label field is a `js2-name-node', possibly nil, for the named label
3198 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3199 is the target of the break - a label node or enclosing loop/switch statement.")
3200
3201 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3202 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3203
3204 (defun js2-print-break-node (n i)
3205 (insert (js2-make-pad i) "break")
3206 (when (js2-break-node-label n)
3207 (insert " ")
3208 (js2-print-ast (js2-break-node-label n) 0))
3209 (insert ";\n"))
3210
3211 (cl-defstruct (js2-continue-node
3212 (:include js2-jump-node)
3213 (:constructor nil)
3214 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3215 (pos js2-ts-cursor)
3216 len label target)))
3217 "AST node for a continue statement.
3218 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3219 It is nil if continue specifies no label. The target field is the jump target:
3220 a `js2-label-node' or the innermost enclosing loop.")
3221
3222 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3223 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3224
3225 (defun js2-print-continue-node (n i)
3226 (insert (js2-make-pad i) "continue")
3227 (when (js2-continue-node-label n)
3228 (insert " ")
3229 (js2-print-ast (js2-continue-node-label n) 0))
3230 (insert ";\n"))
3231
3232 (cl-defstruct (js2-function-node
3233 (:include js2-script-node)
3234 (:constructor nil)
3235 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3236 (pos js2-ts-cursor)
3237 len
3238 (ftype 'FUNCTION)
3239 (form 'FUNCTION_STATEMENT)
3240 (name "")
3241 params rest-p
3242 body
3243 generator-type
3244 lp rp)))
3245 "AST node for a function declaration.
3246 The `params' field is a Lisp list of nodes. Each node is either a simple
3247 `js2-name-node', or if it's a destructuring-assignment parameter, a
3248 `js2-array-node' or `js2-object-node'."
3249 ftype ; FUNCTION, GETTER or SETTER
3250 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3251 name ; function name (a `js2-name-node', or nil if anonymous)
3252 params ; a Lisp list of destructuring forms or simple name nodes
3253 rest-p ; if t, the last parameter is rest parameter
3254 body ; a `js2-block-node' or expression node (1.8 only)
3255 lp ; position of arg-list open-paren, or nil if omitted
3256 rp ; position of arg-list close-paren, or nil if omitted
3257 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3258 needs-activation ; t if we need an activation object for this frame
3259 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3260 member-expr) ; nonstandard Ecma extension from Rhino
3261
3262 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3263 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3264
3265 (defun js2-visit-function-node (n v)
3266 (js2-visit-ast (js2-function-node-name n) v)
3267 (dolist (p (js2-function-node-params n))
3268 (js2-visit-ast p v))
3269 (js2-visit-ast (js2-function-node-body n) v))
3270
3271 (defun js2-print-function-node (n i)
3272 (let* ((pad (js2-make-pad i))
3273 (getter (js2-node-get-prop n 'GETTER_SETTER))
3274 (name (or (js2-function-node-name n)
3275 (js2-function-node-member-expr n)))
3276 (params (js2-function-node-params n))
3277 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3278 (rest-p (js2-function-node-rest-p n))
3279 (body (js2-function-node-body n))
3280 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3281 (unless (or getter arrow)
3282 (insert pad "function")
3283 (when (eq (js2-function-node-generator-type n) 'STAR)
3284 (insert "*")))
3285 (when name
3286 (insert " ")
3287 (js2-print-ast name 0))
3288 (insert "(")
3289 (cl-loop with len = (length params)
3290 for param in params
3291 for count from 1
3292 do
3293 (when (and rest-p (= count len))
3294 (insert "..."))
3295 (js2-print-ast param 0)
3296 (when (< count len)
3297 (insert ", ")))
3298 (insert ") ")
3299 (when arrow
3300 (insert "=> "))
3301 (insert "{")
3302 ;; TODO: fix this to be smarter about indenting, etc.
3303 (unless expr
3304 (insert "\n"))
3305 (if (js2-block-node-p body)
3306 (js2-print-body body (1+ i))
3307 (js2-print-ast body 0))
3308 (insert pad "}")
3309 (unless expr
3310 (insert "\n"))))
3311
3312 (defun js2-function-name (node)
3313 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3314 (and (js2-function-node-name node)
3315 (js2-name-node-name (js2-function-node-name node))))
3316
3317 ;; Having this be an expression node makes it more flexible.
3318 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3319 ;; that work better if you assume it's an expression. Whenever we have
3320 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3321 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3322 (cl-defstruct (js2-var-decl-node
3323 (:include js2-node)
3324 (:constructor nil)
3325 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3326 (pos (js2-current-token-beg))
3327 len kids
3328 decl-type)))
3329 "AST node for a variable declaration list (VAR, CONST or LET).
3330 The node bounds differ depending on the declaration type. For VAR or
3331 CONST declarations, the bounds include the var/const keyword. For LET
3332 declarations, the node begins at the position of the first child."
3333 kids ; a Lisp list of `js2-var-init-node' structs.
3334 decl-type) ; js2-VAR, js2-CONST or js2-LET
3335
3336 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3337 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3338
3339 (defun js2-visit-var-decl (n v)
3340 (dolist (kid (js2-var-decl-node-kids n))
3341 (js2-visit-ast kid v)))
3342
3343 (defun js2-print-var-decl (n i)
3344 (let ((pad (js2-make-pad i))
3345 (tt (js2-var-decl-node-decl-type n)))
3346 (insert pad)
3347 (insert (cond
3348 ((= tt js2-VAR) "var ")
3349 ((= tt js2-LET) "let ")
3350 ((= tt js2-CONST) "const ")
3351 (t
3352 (error "malformed var-decl node"))))
3353 (cl-loop with kids = (js2-var-decl-node-kids n)
3354 with len = (length kids)
3355 for kid in kids
3356 for count from 1
3357 do
3358 (js2-print-ast kid 0)
3359 (if (< count len)
3360 (insert ", ")))))
3361
3362 (cl-defstruct (js2-var-init-node
3363 (:include js2-node)
3364 (:constructor nil)
3365 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3366 (pos js2-ts-cursor)
3367 len target
3368 initializer)))
3369 "AST node for a variable declaration.
3370 The type field will be js2-CONST for a const decl."
3371 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3372 initializer) ; initializer expression, a `js2-node'
3373
3374 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3375 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3376
3377 (defun js2-visit-var-init-node (n v)
3378 (js2-visit-ast (js2-var-init-node-target n) v)
3379 (js2-visit-ast (js2-var-init-node-initializer n) v))
3380
3381 (defun js2-print-var-init-node (n i)
3382 (let ((pad (js2-make-pad i))
3383 (name (js2-var-init-node-target n))
3384 (init (js2-var-init-node-initializer n)))
3385 (insert pad)
3386 (js2-print-ast name 0)
3387 (when init
3388 (insert " = ")
3389 (js2-print-ast init 0))))
3390
3391 (cl-defstruct (js2-cond-node
3392 (:include js2-node)
3393 (:constructor nil)
3394 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3395 (pos js2-ts-cursor)
3396 len
3397 test-expr
3398 true-expr
3399 false-expr
3400 q-pos c-pos)))
3401 "AST node for the ternary operator"
3402 test-expr
3403 true-expr
3404 false-expr
3405 q-pos ; buffer position of ?
3406 c-pos) ; buffer position of :
3407
3408 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3409 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3410
3411 (defun js2-visit-cond-node (n v)
3412 (js2-visit-ast (js2-cond-node-test-expr n) v)
3413 (js2-visit-ast (js2-cond-node-true-expr n) v)
3414 (js2-visit-ast (js2-cond-node-false-expr n) v))
3415
3416 (defun js2-print-cond-node (n i)
3417 (let ((pad (js2-make-pad i)))
3418 (insert pad)
3419 (js2-print-ast (js2-cond-node-test-expr n) 0)
3420 (insert " ? ")
3421 (js2-print-ast (js2-cond-node-true-expr n) 0)
3422 (insert " : ")
3423 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3424
3425 (cl-defstruct (js2-infix-node
3426 (:include js2-node)
3427 (:constructor nil)
3428 (:constructor make-js2-infix-node (&key type
3429 (pos js2-ts-cursor)
3430 len op-pos
3431 left right)))
3432 "Represents infix expressions.
3433 Includes assignment ops like `|=', and the comma operator.
3434 The type field inherited from `js2-node' holds the operator."
3435 op-pos ; buffer position where operator begins
3436 left ; any `js2-node'
3437 right) ; any `js2-node'
3438
3439 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3440 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3441
3442 (defun js2-visit-infix-node (n v)
3443 (js2-visit-ast (js2-infix-node-left n) v)
3444 (js2-visit-ast (js2-infix-node-right n) v))
3445
3446 (defconst js2-operator-tokens
3447 (let ((table (make-hash-table :test 'eq))
3448 (tokens
3449 (list (cons js2-IN "in")
3450 (cons js2-TYPEOF "typeof")
3451 (cons js2-INSTANCEOF "instanceof")
3452 (cons js2-DELPROP "delete")
3453 (cons js2-COMMA ",")
3454 (cons js2-COLON ":")
3455 (cons js2-OR "||")
3456 (cons js2-AND "&&")
3457 (cons js2-INC "++")
3458 (cons js2-DEC "--")
3459 (cons js2-BITOR "|")
3460 (cons js2-BITXOR "^")
3461 (cons js2-BITAND "&")
3462 (cons js2-EQ "==")
3463 (cons js2-NE "!=")
3464 (cons js2-LT "<")
3465 (cons js2-LE "<=")
3466 (cons js2-GT ">")
3467 (cons js2-GE ">=")
3468 (cons js2-LSH "<<")
3469 (cons js2-RSH ">>")
3470 (cons js2-URSH ">>>")
3471 (cons js2-ADD "+") ; infix plus
3472 (cons js2-SUB "-") ; infix minus
3473 (cons js2-MUL "*")
3474 (cons js2-DIV "/")
3475 (cons js2-MOD "%")
3476 (cons js2-NOT "!")
3477 (cons js2-BITNOT "~")
3478 (cons js2-POS "+") ; unary plus
3479 (cons js2-NEG "-") ; unary minus
3480 (cons js2-TRIPLEDOT "...")
3481 (cons js2-SHEQ "===") ; shallow equality
3482 (cons js2-SHNE "!==") ; shallow inequality
3483 (cons js2-ASSIGN "=")
3484 (cons js2-ASSIGN_BITOR "|=")
3485 (cons js2-ASSIGN_BITXOR "^=")
3486 (cons js2-ASSIGN_BITAND "&=")
3487 (cons js2-ASSIGN_LSH "<<=")
3488 (cons js2-ASSIGN_RSH ">>=")
3489 (cons js2-ASSIGN_URSH ">>>=")
3490 (cons js2-ASSIGN_ADD "+=")
3491 (cons js2-ASSIGN_SUB "-=")
3492 (cons js2-ASSIGN_MUL "*=")
3493 (cons js2-ASSIGN_DIV "/=")
3494 (cons js2-ASSIGN_MOD "%="))))
3495 (cl-loop for (k . v) in tokens do
3496 (puthash k v table))
3497 table))
3498
3499 (defun js2-print-infix-node (n i)
3500 (let* ((tt (js2-node-type n))
3501 (op (gethash tt js2-operator-tokens)))
3502 (unless op
3503 (error "unrecognized infix operator %s" (js2-node-type n)))
3504 (insert (js2-make-pad i))
3505 (js2-print-ast (js2-infix-node-left n) 0)
3506 (unless (= tt js2-COMMA)
3507 (insert " "))
3508 (insert op)
3509 (insert " ")
3510 (js2-print-ast (js2-infix-node-right n) 0)))
3511
3512 (cl-defstruct (js2-assign-node
3513 (:include js2-infix-node)
3514 (:constructor nil)
3515 (:constructor make-js2-assign-node (&key type
3516 (pos js2-ts-cursor)
3517 len op-pos
3518 left right)))
3519 "Represents any assignment.
3520 The type field holds the actual assignment operator.")
3521
3522 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3523 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3524
3525 (cl-defstruct (js2-unary-node
3526 (:include js2-node)
3527 (:constructor nil)
3528 (:constructor make-js2-unary-node (&key type ; required
3529 (pos js2-ts-cursor)
3530 len operand)))
3531 "AST node type for unary operator nodes.
3532 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3533 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3534 property is added if the operator follows the operand."
3535 operand) ; a `js2-node' expression
3536
3537 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3538 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3539
3540 (defun js2-visit-unary-node (n v)
3541 (js2-visit-ast (js2-unary-node-operand n) v))
3542
3543 (defun js2-print-unary-node (n i)
3544 (let* ((tt (js2-node-type n))
3545 (op (gethash tt js2-operator-tokens))
3546 (postfix (js2-node-get-prop n 'postfix)))
3547 (unless op
3548 (error "unrecognized unary operator %s" tt))
3549 (insert (js2-make-pad i))
3550 (unless postfix
3551 (insert op))
3552 (if (or (= tt js2-TYPEOF)
3553 (= tt js2-DELPROP))
3554 (insert " "))
3555 (js2-print-ast (js2-unary-node-operand n) 0)
3556 (when postfix
3557 (insert op))))
3558
3559 (cl-defstruct (js2-let-node
3560 (:include js2-scope)
3561 (:constructor nil)
3562 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3563 (pos (js2-current-token-beg))
3564 len vars body
3565 lp rp)))
3566 "AST node for a let expression or a let statement.
3567 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3568 vars ; a `js2-var-decl-node'
3569 body ; a `js2-node' representing the expression or body block
3570 lp
3571 rp)
3572
3573 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3574 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3575
3576 (defun js2-visit-let-node (n v)
3577 (js2-visit-ast (js2-let-node-vars n) v)
3578 (js2-visit-ast (js2-let-node-body n) v))
3579
3580 (defun js2-print-let-node (n i)
3581 (insert (js2-make-pad i) "let (")
3582 (let ((p (point)))
3583 (js2-print-ast (js2-let-node-vars n) 0)
3584 (delete-region p (+ p 4)))
3585 (insert ") ")
3586 (js2-print-ast (js2-let-node-body n) i))
3587
3588 (cl-defstruct (js2-keyword-node
3589 (:include js2-node)
3590 (:constructor nil)
3591 (:constructor make-js2-keyword-node (&key type
3592 (pos (js2-current-token-beg))
3593 (len (- js2-ts-cursor pos)))))
3594 "AST node representing a literal keyword such as `null'.
3595 Used for `null', `this', `true', `false' and `debugger'.
3596 The node type is set to js2-NULL, js2-THIS, etc.")
3597
3598 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3599 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3600
3601 (defun js2-print-keyword-node (n i)
3602 (insert (js2-make-pad i)
3603 (let ((tt (js2-node-type n)))
3604 (cond
3605 ((= tt js2-THIS) "this")
3606 ((= tt js2-SUPER) "super")
3607 ((= tt js2-NULL) "null")
3608 ((= tt js2-TRUE) "true")
3609 ((= tt js2-FALSE) "false")
3610 ((= tt js2-DEBUGGER) "debugger")
3611 (t (error "Invalid keyword literal type: %d" tt))))))
3612
3613 (defsubst js2-this-or-super-node-p (node)
3614 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3615 (let ((type (js2-node-type node)))
3616 (or (eq type js2-THIS) (eq type js2-SUPER))))
3617
3618 (cl-defstruct (js2-new-node
3619 (:include js2-node)
3620 (:constructor nil)
3621 (:constructor make-js2-new-node (&key (type js2-NEW)
3622 (pos (js2-current-token-beg))
3623 len target
3624 args initializer
3625 lp rp)))
3626 "AST node for new-expression such as new Foo()."
3627 target ; an identifier or reference
3628 args ; a Lisp list of argument nodes
3629 lp ; position of left-paren, nil if omitted
3630 rp ; position of right-paren, nil if omitted
3631 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3632
3633 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3634 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3635
3636 (defun js2-visit-new-node (n v)
3637 (js2-visit-ast (js2-new-node-target n) v)
3638 (dolist (arg (js2-new-node-args n))
3639 (js2-visit-ast arg v))
3640 (js2-visit-ast (js2-new-node-initializer n) v))
3641
3642 (defun js2-print-new-node (n i)
3643 (insert (js2-make-pad i) "new ")
3644 (js2-print-ast (js2-new-node-target n))
3645 (insert "(")
3646 (js2-print-list (js2-new-node-args n))
3647 (insert ")")
3648 (when (js2-new-node-initializer n)
3649 (insert " ")
3650 (js2-print-ast (js2-new-node-initializer n))))
3651
3652 (cl-defstruct (js2-name-node
3653 (:include js2-node)
3654 (:constructor nil)
3655 (:constructor make-js2-name-node (&key (type js2-NAME)
3656 (pos (js2-current-token-beg))
3657 (len (- js2-ts-cursor
3658 (js2-current-token-beg)))
3659 (name (js2-current-token-string)))))
3660 "AST node for a JavaScript identifier"
3661 name ; a string
3662 scope) ; a `js2-scope' (optional, used for codegen)
3663
3664 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3665 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3666
3667 (defun js2-print-name-node (n i)
3668 (insert (js2-make-pad i)
3669 (js2-name-node-name n)))
3670
3671 (defsubst js2-name-node-length (node)
3672 "Return identifier length of NODE, a `js2-name-node'.
3673 Returns 0 if NODE is nil or its identifier field is nil."
3674 (if node
3675 (length (js2-name-node-name node))
3676 0))
3677
3678 (cl-defstruct (js2-number-node
3679 (:include js2-node)
3680 (:constructor nil)
3681 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3682 (pos (js2-current-token-beg))
3683 (len (- js2-ts-cursor
3684 (js2-current-token-beg)))
3685 (value (js2-current-token-string))
3686 (num-value (js2-token-number
3687 (js2-current-token)))
3688 (num-base (js2-token-number-base
3689 (js2-current-token))))))
3690 "AST node for a number literal."
3691 value ; the original string, e.g. "6.02e23"
3692 num-value ; the parsed number value
3693 num-base) ; the number's base
3694
3695 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3696 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3697
3698 (defun js2-print-number-node (n i)
3699 (insert (js2-make-pad i)
3700 (number-to-string (js2-number-node-num-value n))))
3701
3702 (cl-defstruct (js2-regexp-node
3703 (:include js2-node)
3704 (:constructor nil)
3705 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3706 (pos (js2-current-token-beg))
3707 (len (- js2-ts-cursor
3708 (js2-current-token-beg)))
3709 value flags)))
3710 "AST node for a regular expression literal."
3711 value ; the regexp string, without // delimiters
3712 flags) ; a string of flags, e.g. `mi'.
3713
3714 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3715 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3716
3717 (defun js2-print-regexp (n i)
3718 (insert (js2-make-pad i)
3719 "/"
3720 (js2-regexp-node-value n)
3721 "/")
3722 (if (js2-regexp-node-flags n)
3723 (insert (js2-regexp-node-flags n))))
3724
3725 (cl-defstruct (js2-string-node
3726 (:include js2-node)
3727 (:constructor nil)
3728 (:constructor make-js2-string-node (&key (type js2-STRING)
3729 (pos (js2-current-token-beg))
3730 (len (- js2-ts-cursor
3731 (js2-current-token-beg)))
3732 (value (js2-current-token-string)))))
3733 "String literal.
3734 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3735 You can tell the quote type by looking at the first character."
3736 value) ; the characters of the string, including the quotes
3737
3738 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3739 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3740
3741 (defun js2-print-string-node (n i)
3742 (insert (js2-make-pad i)
3743 (js2-node-string n)))
3744
3745 (cl-defstruct (js2-template-node
3746 (:include js2-node)
3747 (:constructor nil)
3748 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3749 beg len kids)))
3750 "Template literal."
3751 kids) ; `js2-string-node' is used for string segments, other nodes
3752 ; for substitutions inside.
3753
3754 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3755 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3756
3757 (defun js2-visit-template (n callback)
3758 (dolist (kid (js2-template-node-kids n))
3759 (js2-visit-ast kid callback)))
3760
3761 (defun js2-print-template (n i)
3762 (insert (js2-make-pad i))
3763 (dolist (kid (js2-template-node-kids n))
3764 (if (js2-string-node-p kid)
3765 (insert (js2-node-string kid))
3766 (js2-print-ast kid))))
3767
3768 (cl-defstruct (js2-tagged-template-node
3769 (:include js2-node)
3770 (:constructor nil)
3771 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3772 beg len tag template)))
3773 "Tagged template literal."
3774 tag ; `js2-node' with the tag expression.
3775 template) ; `js2-template-node' with the template.
3776
3777 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3778 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3779
3780 (defun js2-visit-tagged-template (n callback)
3781 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3782 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3783
3784 (defun js2-print-tagged-template (n i)
3785 (insert (js2-make-pad i))
3786 (js2-print-ast (js2-tagged-template-node-tag n))
3787 (js2-print-ast (js2-tagged-template-node-template n)))
3788
3789 (cl-defstruct (js2-array-node
3790 (:include js2-node)
3791 (:constructor nil)
3792 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3793 (pos js2-ts-cursor)
3794 len elems)))
3795 "AST node for an array literal."
3796 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3797
3798 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3799 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3800
3801 (defun js2-visit-array-node (n v)
3802 (dolist (e (js2-array-node-elems n))
3803 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3804
3805 (defun js2-print-array-node (n i)
3806 (insert (js2-make-pad i) "[")
3807 (let ((elems (js2-array-node-elems n)))
3808 (js2-print-list elems)
3809 (when (and elems (null (car (last elems))))
3810 (insert ",")))
3811 (insert "]"))
3812
3813 (cl-defstruct (js2-class-node
3814 (:include js2-node)
3815 (:constructor nil)
3816 (:constructor make-js2-class-node (&key (type js2-CLASS)
3817 (pos js2-ts-cursor)
3818 (form 'CLASS_STATEMENT)
3819 (name "")
3820 extends len elems)))
3821 "AST node for an class expression.
3822 `elems' is a list of `js2-object-prop-node', and `extends' is an
3823 optional `js2-expr-node'"
3824 form ; CLASS_{STATEMENT|EXPRESSION}
3825 name ; class name (a `js2-node-name', or nil if anonymous)
3826 extends ; class heritage (a `js2-expr-node', or nil if none)
3827 elems)
3828
3829 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3830 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3831
3832 (defun js2-visit-class-node (n v)
3833 (js2-visit-ast (js2-class-node-name n) v)
3834 (js2-visit-ast (js2-class-node-extends n) v)
3835 (dolist (e (js2-class-node-elems n))
3836 (js2-visit-ast e v)))
3837
3838 (defun js2-print-class-node (n i)
3839 (let* ((pad (js2-make-pad i))
3840 (name (js2-class-node-name n))
3841 (extends (js2-class-node-extends n))
3842 (elems (js2-class-node-elems n)))
3843 (insert pad "class")
3844 (when name
3845 (insert " ")
3846 (js2-print-ast name 0))
3847 (when extends
3848 (insert " extends ")
3849 (js2-print-ast extends))
3850 (insert " {")
3851 (dolist (elem elems)
3852 (insert "\n")
3853 (if (js2-node-get-prop elem 'STATIC)
3854 (progn (insert (js2-make-pad (1+ i)) "static ")
3855 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3856 (js2-print-ast elem (1+ i))))
3857 (insert "\n" pad "}")))
3858
3859 (cl-defstruct (js2-object-node
3860 (:include js2-node)
3861 (:constructor nil)
3862 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3863 (pos js2-ts-cursor)
3864 len
3865 elems)))
3866 "AST node for an object literal expression.
3867 `elems' is a list of `js2-object-prop-node'."
3868 elems)
3869
3870 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3871 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3872
3873 (defun js2-visit-object-node (n v)
3874 (dolist (e (js2-object-node-elems n))
3875 (js2-visit-ast e v)))
3876
3877 (defun js2-print-object-node (n i)
3878 (insert (js2-make-pad i) "{")
3879 (js2-print-list (js2-object-node-elems n))
3880 (insert "}"))
3881
3882 (cl-defstruct (js2-object-prop-node
3883 (:include js2-infix-node)
3884 (:constructor nil)
3885 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3886 (pos js2-ts-cursor)
3887 len left
3888 right op-pos)))
3889 "AST node for an object literal prop:value entry.
3890 The `left' field is the property: a name node, string node,
3891 number node or expression node. The `right' field is a
3892 `js2-node' representing the initializer value. If the property
3893 is abbreviated, the node's `SHORTHAND' property is non-nil and
3894 both fields have the same value.")
3895
3896 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3897 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3898
3899 (defun js2-print-object-prop-node (n i)
3900 (let* ((left (js2-object-prop-node-left n))
3901 (right (js2-object-prop-node-right n))
3902 (computed (not (or (js2-string-node-p left)
3903 (js2-number-node-p left)
3904 (js2-name-node-p left)))))
3905 (insert (js2-make-pad i))
3906 (if computed
3907 (insert "["))
3908 (js2-print-ast left 0)
3909 (if computed
3910 (insert "]"))
3911 (if (not (js2-node-get-prop n 'SHORTHAND))
3912 (progn
3913 (insert ": ")
3914 (js2-print-ast right 0)))))
3915
3916 (cl-defstruct (js2-getter-setter-node
3917 (:include js2-infix-node)
3918 (:constructor nil)
3919 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3920 (pos js2-ts-cursor)
3921 len left right)))
3922 "AST node for a getter/setter property in an object literal.
3923 The `left' field is the `js2-name-node' naming the getter/setter prop.
3924 The `right' field is always an anonymous `js2-function-node' with a node
3925 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3926
3927 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3928 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3929
3930 (defun js2-print-getter-setter (n i)
3931 (let* ((pad (js2-make-pad i))
3932 (left (js2-getter-setter-node-left n))
3933 (right (js2-getter-setter-node-right n))
3934 (computed (not (or (js2-string-node-p left)
3935 (js2-number-node-p left)
3936 (js2-name-node-p left)))))
3937 (insert pad)
3938 (if (/= (js2-node-type n) js2-FUNCTION)
3939 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3940 (when (and (js2-function-node-p right)
3941 (eq 'STAR (js2-function-node-generator-type right)))
3942 (insert "*"))
3943 (when computed
3944 (insert "["))
3945 (js2-print-ast left 0)
3946 (when computed
3947 (insert "]"))
3948 (js2-print-ast right 0)))
3949
3950 (cl-defstruct (js2-prop-get-node
3951 (:include js2-infix-node)
3952 (:constructor nil)
3953 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3954 (pos js2-ts-cursor)
3955 len left right)))
3956 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3957
3958 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3959 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3960
3961 (defun js2-visit-prop-get-node (n v)
3962 (js2-visit-ast (js2-prop-get-node-left n) v)
3963 (js2-visit-ast (js2-prop-get-node-right n) v))
3964
3965 (defun js2-print-prop-get-node (n i)
3966 (insert (js2-make-pad i))
3967 (js2-print-ast (js2-prop-get-node-left n) 0)
3968 (insert ".")
3969 (js2-print-ast (js2-prop-get-node-right n) 0))
3970
3971 (cl-defstruct (js2-elem-get-node
3972 (:include js2-node)
3973 (:constructor nil)
3974 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3975 (pos js2-ts-cursor)
3976 len target element
3977 lb rb)))
3978 "AST node for an array index expression such as foo[bar]."
3979 target ; a `js2-node' - the expression preceding the "."
3980 element ; a `js2-node' - the expression in brackets
3981 lb ; position of left-bracket, nil if omitted
3982 rb) ; position of right-bracket, nil if omitted
3983
3984 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3985 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3986
3987 (defun js2-visit-elem-get-node (n v)
3988 (js2-visit-ast (js2-elem-get-node-target n) v)
3989 (js2-visit-ast (js2-elem-get-node-element n) v))
3990
3991 (defun js2-print-elem-get-node (n i)
3992 (insert (js2-make-pad i))
3993 (js2-print-ast (js2-elem-get-node-target n) 0)
3994 (insert "[")
3995 (js2-print-ast (js2-elem-get-node-element n) 0)
3996 (insert "]"))
3997
3998 (cl-defstruct (js2-call-node
3999 (:include js2-node)
4000 (:constructor nil)
4001 (:constructor make-js2-call-node (&key (type js2-CALL)
4002 (pos js2-ts-cursor)
4003 len target args
4004 lp rp)))
4005 "AST node for a JavaScript function call."
4006 target ; a `js2-node' evaluating to the function to call
4007 args ; a Lisp list of `js2-node' arguments
4008 lp ; position of open-paren, or nil if missing
4009 rp) ; position of close-paren, or nil if missing
4010
4011 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4012 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4013
4014 (defun js2-visit-call-node (n v)
4015 (js2-visit-ast (js2-call-node-target n) v)
4016 (dolist (arg (js2-call-node-args n))
4017 (js2-visit-ast arg v)))
4018
4019 (defun js2-print-call-node (n i)
4020 (insert (js2-make-pad i))
4021 (js2-print-ast (js2-call-node-target n) 0)
4022 (insert "(")
4023 (js2-print-list (js2-call-node-args n))
4024 (insert ")"))
4025
4026 (cl-defstruct (js2-yield-node
4027 (:include js2-node)
4028 (:constructor nil)
4029 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4030 (pos js2-ts-cursor)
4031 len value star-p)))
4032 "AST node for yield statement or expression."
4033 star-p ; whether it's yield*
4034 value) ; optional: value to be yielded
4035
4036 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4037 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4038
4039 (defun js2-visit-yield-node (n v)
4040 (js2-visit-ast (js2-yield-node-value n) v))
4041
4042 (defun js2-print-yield-node (n i)
4043 (insert (js2-make-pad i))
4044 (insert "yield")
4045 (when (js2-yield-node-star-p n)
4046 (insert "*"))
4047 (when (js2-yield-node-value n)
4048 (insert " ")
4049 (js2-print-ast (js2-yield-node-value n) 0)))
4050
4051 (cl-defstruct (js2-paren-node
4052 (:include js2-node)
4053 (:constructor nil)
4054 (:constructor make-js2-paren-node (&key (type js2-LP)
4055 (pos js2-ts-cursor)
4056 len expr)))
4057 "AST node for a parenthesized expression.
4058 In particular, used when the parens are syntactically optional,
4059 as opposed to required parens such as those enclosing an if-conditional."
4060 expr) ; `js2-node'
4061
4062 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4063 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4064
4065 (defun js2-visit-paren-node (n v)
4066 (js2-visit-ast (js2-paren-node-expr n) v))
4067
4068 (defun js2-print-paren-node (n i)
4069 (insert (js2-make-pad i))
4070 (insert "(")
4071 (js2-print-ast (js2-paren-node-expr n) 0)
4072 (insert ")"))
4073
4074 (cl-defstruct (js2-comp-node
4075 (:include js2-scope)
4076 (:constructor nil)
4077 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4078 (pos js2-ts-cursor)
4079 len result
4080 loops filters
4081 form)))
4082 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4083 result ; result expression (just after left-bracket)
4084 loops ; a Lisp list of `js2-comp-loop-node'
4085 filters ; a Lisp list of guard/filter expressions
4086 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4087 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4088 )
4089
4090 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4091 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4092
4093 (defun js2-visit-comp-node (n v)
4094 (js2-visit-ast (js2-comp-node-result n) v)
4095 (dolist (l (js2-comp-node-loops n))
4096 (js2-visit-ast l v))
4097 (dolist (f (js2-comp-node-filters n))
4098 (js2-visit-ast f v)))
4099
4100 (defun js2-print-comp-node (n i)
4101 (let ((pad (js2-make-pad i))
4102 (result (js2-comp-node-result n))
4103 (loops (js2-comp-node-loops n))
4104 (filters (js2-comp-node-filters n))
4105 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4106 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4107 (insert pad (if gen-p "(" "["))
4108 (when legacy-p
4109 (js2-print-ast result 0))
4110 (dolist (l loops)
4111 (when legacy-p
4112 (insert " "))
4113 (js2-print-ast l 0)
4114 (unless legacy-p
4115 (insert " ")))
4116 (dolist (f filters)
4117 (when legacy-p
4118 (insert " "))
4119 (insert "if (")
4120 (js2-print-ast f 0)
4121 (insert ")")
4122 (unless legacy-p
4123 (insert " ")))
4124 (unless legacy-p
4125 (js2-print-ast result 0))
4126 (insert (if gen-p ")" "]"))))
4127
4128 (cl-defstruct (js2-comp-loop-node
4129 (:include js2-for-in-node)
4130 (:constructor nil)
4131 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4132 (pos js2-ts-cursor)
4133 len iterator
4134 object in-pos
4135 foreach-p
4136 each-pos
4137 forof-p
4138 lp rp)))
4139 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4140
4141 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4142 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4143
4144 (defun js2-visit-comp-loop (n v)
4145 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4146 (js2-visit-ast (js2-comp-loop-node-object n) v))
4147
4148 (defun js2-print-comp-loop (n _i)
4149 (insert "for ")
4150 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4151 (insert "(")
4152 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4153 (insert (if (js2-comp-loop-node-forof-p n)
4154 " of " " in "))
4155 (js2-print-ast (js2-comp-loop-node-object n) 0)
4156 (insert ")"))
4157
4158 (cl-defstruct (js2-empty-expr-node
4159 (:include js2-node)
4160 (:constructor nil)
4161 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4162 (pos (js2-current-token-beg))
4163 len)))
4164 "AST node for an empty expression.")
4165
4166 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4167 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4168
4169 (cl-defstruct (js2-xml-node
4170 (:include js2-block-node)
4171 (:constructor nil)
4172 (:constructor make-js2-xml-node (&key (type js2-XML)
4173 (pos (js2-current-token-beg))
4174 len kids)))
4175 "AST node for initial parse of E4X literals.
4176 The kids field is a list of XML fragments, each a `js2-string-node' or
4177 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4178
4179 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4180 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4181
4182 (defun js2-print-xml-node (n i)
4183 (dolist (kid (js2-xml-node-kids n))
4184 (js2-print-ast kid i)))
4185
4186 (cl-defstruct (js2-xml-js-expr-node
4187 (:include js2-xml-node)
4188 (:constructor nil)
4189 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4190 (pos js2-ts-cursor)
4191 len expr)))
4192 "AST node for an embedded JavaScript {expression} in an E4X literal.
4193 The start and end fields correspond to the curly-braces."
4194 expr) ; a `js2-expr-node' of some sort
4195
4196 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4197 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4198
4199 (defun js2-visit-xml-js-expr (n v)
4200 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4201
4202 (defun js2-print-xml-js-expr (n i)
4203 (insert (js2-make-pad i))
4204 (insert "{")
4205 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4206 (insert "}"))
4207
4208 (cl-defstruct (js2-xml-dot-query-node
4209 (:include js2-infix-node)
4210 (:constructor nil)
4211 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4212 (pos js2-ts-cursor)
4213 op-pos len left
4214 right rp)))
4215 "AST node for an E4X foo.(bar) filter expression.
4216 Note that the left-paren is automatically the character immediately
4217 following the dot (.) in the operator. No whitespace is permitted
4218 between the dot and the lp by the scanner."
4219 rp)
4220
4221 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4222 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4223
4224 (defun js2-print-xml-dot-query (n i)
4225 (insert (js2-make-pad i))
4226 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4227 (insert ".(")
4228 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4229 (insert ")"))
4230
4231 (cl-defstruct (js2-xml-ref-node
4232 (:include js2-node)
4233 (:constructor nil)) ; abstract
4234 "Base type for E4X XML attribute-access or property-get expressions.
4235 Such expressions can take a variety of forms. The general syntax has
4236 three parts:
4237
4238 - (optional) an @ (specifying an attribute access)
4239 - (optional) a namespace (a `js2-name-node') and double-colon
4240 - (required) either a `js2-name-node' or a bracketed [expression]
4241
4242 The property-name expressions (examples: ns::name, @name) are
4243 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4244 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4245
4246 This node type (or more specifically, its subclasses) will sometimes
4247 be the right-hand child of a `js2-prop-get-node' or a
4248 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4249 The `js2-xml-ref-node' may also be a standalone primary expression with
4250 no explicit target, which is valid in certain expression contexts such as
4251
4252 company..employee.(@id < 100)
4253
4254 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4255 expression whose parent is a `js2-xml-dot-query-node'."
4256 namespace
4257 at-pos
4258 colon-pos)
4259
4260 (defsubst js2-xml-ref-node-attr-access-p (node)
4261 "Return non-nil if this expression began with an @-token."
4262 (and (numberp (js2-xml-ref-node-at-pos node))
4263 (cl-plusp (js2-xml-ref-node-at-pos node))))
4264
4265 (cl-defstruct (js2-xml-prop-ref-node
4266 (:include js2-xml-ref-node)
4267 (:constructor nil)
4268 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4269 (pos (js2-current-token-beg))
4270 len propname
4271 namespace at-pos
4272 colon-pos)))
4273 "AST node for an E4X XML [expr] property-ref expression.
4274 The JavaScript syntax is an optional @, an optional ns::, and a name.
4275
4276 [ '@' ] [ name '::' ] name
4277
4278 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4279 @ns::*, @*::attr, @*::*, and @*.
4280
4281 The node starts at the @ token, if present. Otherwise it starts at the
4282 namespace name. The node bounds extend through the closing right-bracket,
4283 or if it is missing due to a syntax error, through the end of the index
4284 expression."
4285 propname)
4286
4287 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4288 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4289
4290 (defun js2-visit-xml-prop-ref-node (n v)
4291 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4292 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4293
4294 (defun js2-print-xml-prop-ref-node (n i)
4295 (insert (js2-make-pad i))
4296 (if (js2-xml-ref-node-attr-access-p n)
4297 (insert "@"))
4298 (when (js2-xml-prop-ref-node-namespace n)
4299 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4300 (insert "::"))
4301 (if (js2-xml-prop-ref-node-propname n)
4302 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4303
4304 (cl-defstruct (js2-xml-elem-ref-node
4305 (:include js2-xml-ref-node)
4306 (:constructor nil)
4307 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4308 (pos (js2-current-token-beg))
4309 len expr lb rb
4310 namespace at-pos
4311 colon-pos)))
4312 "AST node for an E4X XML [expr] member-ref expression.
4313 Syntax:
4314
4315 [ '@' ] [ name '::' ] '[' expr ']'
4316
4317 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4318
4319 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4320 is not a legal E4X XML element-ref expression, since it's already used
4321 for standard JavaScript element-get array indexing. Hence, a
4322 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4323 non-nil namespace node, or both.
4324
4325 The node starts at the @ token, if present. Otherwise it starts
4326 at the namespace name. The node bounds extend through the closing
4327 right-bracket, or if it is missing due to a syntax error, through the
4328 end of the index expression."
4329 expr ; the bracketed index expression
4330 lb
4331 rb)
4332
4333 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4334 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4335
4336 (defun js2-visit-xml-elem-ref-node (n v)
4337 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4338 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4339
4340 (defun js2-print-xml-elem-ref-node (n i)
4341 (insert (js2-make-pad i))
4342 (if (js2-xml-ref-node-attr-access-p n)
4343 (insert "@"))
4344 (when (js2-xml-elem-ref-node-namespace n)
4345 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4346 (insert "::"))
4347 (insert "[")
4348 (if (js2-xml-elem-ref-node-expr n)
4349 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4350 (insert "]"))
4351
4352 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4353
4354 (cl-defstruct (js2-xml-start-tag-node
4355 (:include js2-xml-node)
4356 (:constructor nil)
4357 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4358 (pos js2-ts-cursor)
4359 len name attrs kids
4360 empty-p)))
4361 "AST node for an XML start-tag. Not currently used.
4362 The `kids' field is a Lisp list of child content nodes."
4363 name ; a `js2-xml-name-node'
4364 attrs ; a Lisp list of `js2-xml-attr-node'
4365 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4366
4367 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4368 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4369
4370 (defun js2-visit-xml-start-tag (n v)
4371 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4372 (dolist (attr (js2-xml-start-tag-node-attrs n))
4373 (js2-visit-ast attr v))
4374 (js2-visit-block n v))
4375
4376 (defun js2-print-xml-start-tag (n i)
4377 (insert (js2-make-pad i) "<")
4378 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4379 (when (js2-xml-start-tag-node-attrs n)
4380 (insert " ")
4381 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4382 (insert ">"))
4383
4384 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4385 ;; and add the end-tag to the kids list of the parent as well.
4386 (cl-defstruct (js2-xml-end-tag-node
4387 (:include js2-xml-node)
4388 (:constructor nil)
4389 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4390 (pos js2-ts-cursor)
4391 len name)))
4392 "AST node for an XML end-tag. Not currently used."
4393 name) ; a `js2-xml-name-node'
4394
4395 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4396 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4397
4398 (defun js2-visit-xml-end-tag (n v)
4399 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4400
4401 (defun js2-print-xml-end-tag (n i)
4402 (insert (js2-make-pad i))
4403 (insert "</")
4404 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4405 (insert ">"))
4406
4407 (cl-defstruct (js2-xml-name-node
4408 (:include js2-xml-node)
4409 (:constructor nil)
4410 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4411 (pos js2-ts-cursor)
4412 len namespace kids)))
4413 "AST node for an E4X XML name. Not currently used.
4414 Any XML name can be qualified with a namespace, hence the namespace field.
4415 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4416 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4417 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4418 namespace) ; a `js2-string-node'
4419
4420 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4421 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4422
4423 (defun js2-visit-xml-name-node (n v)
4424 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4425
4426 (defun js2-print-xml-name-node (n i)
4427 (insert (js2-make-pad i))
4428 (when (js2-xml-name-node-namespace n)
4429 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4430 (insert "::"))
4431 (dolist (kid (js2-xml-name-node-kids n))
4432 (js2-print-ast kid 0)))
4433
4434 (cl-defstruct (js2-xml-pi-node
4435 (:include js2-xml-node)
4436 (:constructor nil)
4437 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4438 (pos js2-ts-cursor)
4439 len name attrs)))
4440 "AST node for an E4X XML processing instruction. Not currently used."
4441 name ; a `js2-xml-name-node'
4442 attrs) ; a list of `js2-xml-attr-node'
4443
4444 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4445 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4446
4447 (defun js2-visit-xml-pi-node (n v)
4448 (js2-visit-ast (js2-xml-pi-node-name n) v)
4449 (dolist (attr (js2-xml-pi-node-attrs n))
4450 (js2-visit-ast attr v)))
4451
4452 (defun js2-print-xml-pi-node (n i)
4453 (insert (js2-make-pad i) "<?")
4454 (js2-print-ast (js2-xml-pi-node-name n))
4455 (when (js2-xml-pi-node-attrs n)
4456 (insert " ")
4457 (js2-print-list (js2-xml-pi-node-attrs n)))
4458 (insert "?>"))
4459
4460 (cl-defstruct (js2-xml-cdata-node
4461 (:include js2-xml-node)
4462 (:constructor nil)
4463 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4464 (pos js2-ts-cursor)
4465 len content)))
4466 "AST node for a CDATA escape section. Not currently used."
4467 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4468
4469 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4470 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4471
4472 (defun js2-visit-xml-cdata-node (n v)
4473 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4474
4475 (defun js2-print-xml-cdata-node (n i)
4476 (insert (js2-make-pad i))
4477 (js2-print-ast (js2-xml-cdata-node-content n)))
4478
4479 (cl-defstruct (js2-xml-attr-node
4480 (:include js2-xml-node)
4481 (:constructor nil)
4482 (:constructor make-js2-attr-node (&key (type js2-XML)
4483 (pos js2-ts-cursor)
4484 len name value
4485 eq-pos quote-type)))
4486 "AST node representing a foo='bar' XML attribute value. Not yet used."
4487 name ; a `js2-xml-name-node'
4488 value ; a `js2-xml-name-node'
4489 eq-pos ; buffer position of "=" sign
4490 quote-type) ; 'single or 'double
4491
4492 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4493 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4494
4495 (defun js2-visit-xml-attr-node (n v)
4496 (js2-visit-ast (js2-xml-attr-node-name n) v)
4497 (js2-visit-ast (js2-xml-attr-node-value n) v))
4498
4499 (defun js2-print-xml-attr-node (n i)
4500 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4501 "'"
4502 "\"")))
4503 (insert (js2-make-pad i))
4504 (js2-print-ast (js2-xml-attr-node-name n) 0)
4505 (insert "=" quote)
4506 (js2-print-ast (js2-xml-attr-node-value n) 0)
4507 (insert quote)))
4508
4509 (cl-defstruct (js2-xml-text-node
4510 (:include js2-xml-node)
4511 (:constructor nil)
4512 (:constructor make-js2-text-node (&key (type js2-XML)
4513 (pos js2-ts-cursor)
4514 len content)))
4515 "AST node for an E4X XML text node. Not currently used."
4516 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4517
4518 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4519 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4520
4521 (defun js2-visit-xml-text-node (n v)
4522 (js2-visit-ast (js2-xml-text-node-content n) v))
4523
4524 (defun js2-print-xml-text-node (n i)
4525 (insert (js2-make-pad i))
4526 (dolist (kid (js2-xml-text-node-content n))
4527 (js2-print-ast kid)))
4528
4529 (cl-defstruct (js2-xml-comment-node
4530 (:include js2-xml-node)
4531 (:constructor nil)
4532 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4533 (pos js2-ts-cursor)
4534 len)))
4535 "AST node for E4X XML comment. Not currently used.")
4536
4537 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4538 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4539
4540 (defun js2-print-xml-comment (n i)
4541 (insert (js2-make-pad i)
4542 (js2-node-string n)))
4543
4544 ;;; Node utilities
4545
4546 (defsubst js2-node-line (n)
4547 "Fetch the source line number at the start of node N.
4548 This is O(n) in the length of the source buffer; use prudently."
4549 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4550
4551 (defsubst js2-block-node-kid (n i)
4552 "Return child I of node N, or nil if there aren't that many."
4553 (nth i (js2-block-node-kids n)))
4554
4555 (defsubst js2-block-node-first (n)
4556 "Return first child of block node N, or nil if there is none."
4557 (cl-first (js2-block-node-kids n)))
4558
4559 (defun js2-node-root (n)
4560 "Return the root of the AST containing N.
4561 If N has no parent pointer, returns N."
4562 (let ((parent (js2-node-parent n)))
4563 (if parent
4564 (js2-node-root parent)
4565 n)))
4566
4567 (defsubst js2-node-short-name (n)
4568 "Return the short name of node N as a string, e.g. `js2-if-node'."
4569 (substring (symbol-name (aref n 0))
4570 (length "cl-struct-")))
4571
4572 (defun js2-node-child-list (node)
4573 "Return the child list for NODE, a Lisp list of nodes.
4574 Works for block nodes, array nodes, obj literals, funarg lists,
4575 var decls and try nodes (for catch clauses). Note that you should call
4576 `js2-block-node-kids' on the function body for the body statements.
4577 Returns nil for zero-length child lists or unsupported nodes."
4578 (cond
4579 ((js2-function-node-p node)
4580 (js2-function-node-params node))
4581 ((js2-block-node-p node)
4582 (js2-block-node-kids node))
4583 ((js2-try-node-p node)
4584 (js2-try-node-catch-clauses node))
4585 ((js2-array-node-p node)
4586 (js2-array-node-elems node))
4587 ((js2-object-node-p node)
4588 (js2-object-node-elems node))
4589 ((js2-call-node-p node)
4590 (js2-call-node-args node))
4591 ((js2-new-node-p node)
4592 (js2-new-node-args node))
4593 ((js2-var-decl-node-p node)
4594 (js2-var-decl-node-kids node))
4595 (t
4596 nil)))
4597
4598 (defun js2-node-set-child-list (node kids)
4599 "Set the child list for NODE to KIDS."
4600 (cond
4601 ((js2-function-node-p node)
4602 (setf (js2-function-node-params node) kids))
4603 ((js2-block-node-p node)
4604 (setf (js2-block-node-kids node) kids))
4605 ((js2-try-node-p node)
4606 (setf (js2-try-node-catch-clauses node) kids))
4607 ((js2-array-node-p node)
4608 (setf (js2-array-node-elems node) kids))
4609 ((js2-object-node-p node)
4610 (setf (js2-object-node-elems node) kids))
4611 ((js2-call-node-p node)
4612 (setf (js2-call-node-args node) kids))
4613 ((js2-new-node-p node)
4614 (setf (js2-new-node-args node) kids))
4615 ((js2-var-decl-node-p node)
4616 (setf (js2-var-decl-node-kids node) kids))
4617 (t
4618 (error "Unsupported node type: %s" (js2-node-short-name node))))
4619 kids)
4620
4621 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4622 (defconst js2-paren-expr-nodes
4623 '(cl-struct-js2-comp-loop-node
4624 cl-struct-js2-comp-node
4625 cl-struct-js2-call-node
4626 cl-struct-js2-catch-node
4627 cl-struct-js2-do-node
4628 cl-struct-js2-elem-get-node
4629 cl-struct-js2-for-in-node
4630 cl-struct-js2-for-node
4631 cl-struct-js2-function-node
4632 cl-struct-js2-if-node
4633 cl-struct-js2-let-node
4634 cl-struct-js2-new-node
4635 cl-struct-js2-paren-node
4636 cl-struct-js2-switch-node
4637 cl-struct-js2-while-node
4638 cl-struct-js2-with-node
4639 cl-struct-js2-xml-dot-query-node)
4640 "Node types that can have a parenthesized child expression.
4641 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4642
4643 (defsubst js2-paren-expr-node-p (node)
4644 "Return t for nodes that typically have a parenthesized child expression.
4645 Useful for computing the indentation anchors for arg-lists and conditions.
4646 Note that it may return a false positive, for instance when NODE is
4647 a `js2-new-node' and there are no arguments or parentheses."
4648 (memq (aref node 0) js2-paren-expr-nodes))
4649
4650 ;; Fake polymorphism... yech.
4651 (defun js2-node-lp (node)
4652 "Return relative left-paren position for NODE, if applicable.
4653 For `js2-elem-get-node' structs, returns left-bracket position.
4654 Note that the position may be nil in the case of a parse error."
4655 (cond
4656 ((js2-elem-get-node-p node)
4657 (js2-elem-get-node-lb node))
4658 ((js2-loop-node-p node)
4659 (js2-loop-node-lp node))
4660 ((js2-function-node-p node)
4661 (js2-function-node-lp node))
4662 ((js2-if-node-p node)
4663 (js2-if-node-lp node))
4664 ((js2-new-node-p node)
4665 (js2-new-node-lp node))
4666 ((js2-call-node-p node)
4667 (js2-call-node-lp node))
4668 ((js2-paren-node-p node)
4669 0)
4670 ((js2-switch-node-p node)
4671 (js2-switch-node-lp node))
4672 ((js2-catch-node-p node)
4673 (js2-catch-node-lp node))
4674 ((js2-let-node-p node)
4675 (js2-let-node-lp node))
4676 ((js2-comp-node-p node)
4677 0)
4678 ((js2-with-node-p node)
4679 (js2-with-node-lp node))
4680 ((js2-xml-dot-query-node-p node)
4681 (1+ (js2-infix-node-op-pos node)))
4682 (t
4683 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4684
4685 ;; Fake polymorphism... blech.
4686 (defun js2-node-rp (node)
4687 "Return relative right-paren position for NODE, if applicable.
4688 For `js2-elem-get-node' structs, returns right-bracket position.
4689 Note that the position may be nil in the case of a parse error."
4690 (cond
4691 ((js2-elem-get-node-p node)
4692 (js2-elem-get-node-rb node))
4693 ((js2-loop-node-p node)
4694 (js2-loop-node-rp node))
4695 ((js2-function-node-p node)
4696 (js2-function-node-rp node))
4697 ((js2-if-node-p node)
4698 (js2-if-node-rp node))
4699 ((js2-new-node-p node)
4700 (js2-new-node-rp node))
4701 ((js2-call-node-p node)
4702 (js2-call-node-rp node))
4703 ((js2-paren-node-p node)
4704 (1- (js2-node-len node)))
4705 ((js2-switch-node-p node)
4706 (js2-switch-node-rp node))
4707 ((js2-catch-node-p node)
4708 (js2-catch-node-rp node))
4709 ((js2-let-node-p node)
4710 (js2-let-node-rp node))
4711 ((js2-comp-node-p node)
4712 (1- (js2-node-len node)))
4713 ((js2-with-node-p node)
4714 (js2-with-node-rp node))
4715 ((js2-xml-dot-query-node-p node)
4716 (1+ (js2-xml-dot-query-node-rp node)))
4717 (t
4718 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4719
4720 (defsubst js2-node-first-child (node)
4721 "Return the first element of `js2-node-child-list' for NODE."
4722 (car (js2-node-child-list node)))
4723
4724 (defsubst js2-node-last-child (node)
4725 "Return the last element of `js2-node-last-child' for NODE."
4726 (car (last (js2-node-child-list node))))
4727
4728 (defun js2-node-prev-sibling (node)
4729 "Return the previous statement in parent.
4730 Works for parents supported by `js2-node-child-list'.
4731 Returns nil if NODE is not in the parent, or PARENT is
4732 not a supported node, or if NODE is the first child."
4733 (let* ((p (js2-node-parent node))
4734 (kids (js2-node-child-list p))
4735 (sib (car kids)))
4736 (while (and kids
4737 (not (eq node (cadr kids))))
4738 (setq kids (cdr kids)
4739 sib (car kids)))
4740 sib))
4741
4742 (defun js2-node-next-sibling (node)
4743 "Return the next statement in parent block.
4744 Returns nil if NODE is not in the block, or PARENT is not
4745 a block node, or if NODE is the last statement."
4746 (let* ((p (js2-node-parent node))
4747 (kids (js2-node-child-list p)))
4748 (while (and kids
4749 (not (eq node (car kids))))
4750 (setq kids (cdr kids)))
4751 (cadr kids)))
4752
4753 (defun js2-node-find-child-before (pos parent &optional after)
4754 "Find the last child that starts before POS in parent.
4755 If AFTER is non-nil, returns first child starting after POS.
4756 POS is an absolute buffer position. PARENT is any node
4757 supported by `js2-node-child-list'.
4758 Returns nil if no applicable child is found."
4759 (let ((kids (if (js2-function-node-p parent)
4760 (js2-block-node-kids (js2-function-node-body parent))
4761 (js2-node-child-list parent)))
4762 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4763 (js2-function-node-body parent)
4764 parent)))
4765 kid result fn
4766 (continue t))
4767 (setq fn (if after '>= '<))
4768 (while (and kids continue)
4769 (setq kid (car kids))
4770 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4771 (setq result kid
4772 continue (not after))
4773 (setq continue after))
4774 (setq kids (cdr kids)))
4775 result))
4776
4777 (defun js2-node-find-child-after (pos parent)
4778 "Find first child that starts after POS in parent.
4779 POS is an absolute buffer position. PARENT is any node
4780 supported by `js2-node-child-list'.
4781 Returns nil if no applicable child is found."
4782 (js2-node-find-child-before pos parent 'after))
4783
4784 (defun js2-node-replace-child (pos parent new-node)
4785 "Replace node at index POS in PARENT with NEW-NODE.
4786 Only works for parents supported by `js2-node-child-list'."
4787 (let ((kids (js2-node-child-list parent))
4788 (i 0))
4789 (while (< i pos)
4790 (setq kids (cdr kids)
4791 i (1+ i)))
4792 (setcar kids new-node)
4793 (js2-node-add-children parent new-node)))
4794
4795 (defun js2-node-buffer (n)
4796 "Return the buffer associated with AST N.
4797 Returns nil if the buffer is not set as a property on the root
4798 node, or if parent links were not recorded during parsing."
4799 (let ((root (js2-node-root n)))
4800 (and root
4801 (js2-ast-root-p root)
4802 (js2-ast-root-buffer root))))
4803
4804 (defun js2-block-node-push (n kid)
4805 "Push js2-node KID onto the end of js2-block-node N's child list.
4806 KID is always added to the -end- of the kids list.
4807 Function also calls `js2-node-add-children' to add the parent link."
4808 (let ((kids (js2-node-child-list n)))
4809 (if kids
4810 (setcdr kids (nconc (cdr kids) (list kid)))
4811 (js2-node-set-child-list n (list kid)))
4812 (js2-node-add-children n kid)))
4813
4814 (defun js2-node-string (node)
4815 (with-current-buffer (or (js2-node-buffer node)
4816 (error "No buffer available for node %s" node))
4817 (let ((pos (js2-node-abs-pos node)))
4818 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4819
4820 ;; Container for storing the node we're looking for in a traversal.
4821 (js2-deflocal js2-discovered-node nil)
4822
4823 ;; Keep track of absolute node position during traversals.
4824 (js2-deflocal js2-visitor-offset nil)
4825
4826 (js2-deflocal js2-node-search-point nil)
4827
4828 (when js2-mode-dev-mode-p
4829 (defun js2-find-node-at-point ()
4830 (interactive)
4831 (let ((node (js2-node-at-point)))
4832 (message "%s" (or node "No node found at point"))))
4833 (defun js2-node-name-at-point ()
4834 (interactive)
4835 (let ((node (js2-node-at-point)))
4836 (message "%s" (if node
4837 (js2-node-short-name node)
4838 "No node found at point.")))))
4839
4840 (defun js2-node-at-point (&optional pos skip-comments)
4841 "Return AST node at POS, a buffer position, defaulting to current point.
4842 The `js2-mode-ast' variable must be set to the current parse tree.
4843 Signals an error if the AST (`js2-mode-ast') is nil.
4844 Always returns a node - if it can't find one, it returns the root.
4845 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4846 (let ((ast js2-mode-ast)
4847 result)
4848 (unless ast
4849 (error "No JavaScript AST available"))
4850 ;; Look through comments first, since they may be inside nodes that
4851 ;; would otherwise report a match.
4852 (setq pos (or pos (point))
4853 result (if (> pos (js2-node-abs-end ast))
4854 ast
4855 (if (not skip-comments)
4856 (js2-comment-at-point pos))))
4857 (unless result
4858 (setq js2-discovered-node nil
4859 js2-visitor-offset 0
4860 js2-node-search-point pos)
4861 (unwind-protect
4862 (catch 'js2-visit-done
4863 (js2-visit-ast ast #'js2-node-at-point-visitor))
4864 (setq js2-visitor-offset nil
4865 js2-node-search-point nil))
4866 (setq result js2-discovered-node))
4867 ;; may have found a comment beyond end of last child node,
4868 ;; since visiting the ast-root looks at the comment-list last.
4869 (if (and skip-comments
4870 (js2-comment-node-p result))
4871 (setq result nil))
4872 (or result js2-mode-ast)))
4873
4874 (defun js2-node-at-point-visitor (node end-p)
4875 (let ((rel-pos (js2-node-pos node))
4876 abs-pos
4877 abs-end
4878 (point js2-node-search-point))
4879 (cond
4880 (end-p
4881 ;; this evaluates to a non-nil return value, even if it's zero
4882 (cl-decf js2-visitor-offset rel-pos))
4883 ;; we already looked for comments before visiting, and don't want them now
4884 ((js2-comment-node-p node)
4885 nil)
4886 (t
4887 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4888 ;; we only want to use the node if the point is before
4889 ;; the last character position in the node, so we decrement
4890 ;; the absolute end by 1.
4891 abs-end (+ abs-pos (js2-node-len node) -1))
4892 (cond
4893 ;; If this node starts after search-point, stop the search.
4894 ((> abs-pos point)
4895 (throw 'js2-visit-done nil))
4896 ;; If this node ends before the search-point, don't check kids.
4897 ((> point abs-end)
4898 nil)
4899 (t
4900 ;; Otherwise point is within this node, possibly in a child.
4901 (setq js2-discovered-node node)
4902 t)))))) ; keep processing kids to look for more specific match
4903
4904 (defsubst js2-block-comment-p (node)
4905 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4906 (and (js2-comment-node-p node)
4907 (memq (js2-comment-node-format node) '(jsdoc block))))
4908
4909 ;; TODO: put the comments in a vector and binary-search them instead
4910 (defun js2-comment-at-point (&optional pos)
4911 "Look through scanned comment nodes for one containing POS.
4912 POS is a buffer position that defaults to current point.
4913 Function returns nil if POS was not in any comment node."
4914 (let ((ast js2-mode-ast)
4915 (x (or pos (point)))
4916 beg end)
4917 (unless ast
4918 (error "No JavaScript AST available"))
4919 (catch 'done
4920 ;; Comments are stored in lexical order.
4921 (dolist (comment (js2-ast-root-comments ast) nil)
4922 (setq beg (js2-node-abs-pos comment)
4923 end (+ beg (js2-node-len comment)))
4924 (if (and (>= x beg)
4925 (<= x end))
4926 (throw 'done comment))))))
4927
4928 (defun js2-mode-find-parent-fn (node)
4929 "Find function enclosing NODE.
4930 Returns nil if NODE is not inside a function."
4931 (setq node (js2-node-parent node))
4932 (while (and node (not (js2-function-node-p node)))
4933 (setq node (js2-node-parent node)))
4934 (and (js2-function-node-p node) node))
4935
4936 (defun js2-mode-find-enclosing-fn (node)
4937 "Find function or root enclosing NODE."
4938 (if (js2-ast-root-p node)
4939 node
4940 (setq node (js2-node-parent node))
4941 (while (not (or (js2-ast-root-p node)
4942 (js2-function-node-p node)))
4943 (setq node (js2-node-parent node)))
4944 node))
4945
4946 (defun js2-mode-find-enclosing-node (beg end)
4947 "Find node fully enclosing BEG and END."
4948 (let ((node (js2-node-at-point beg))
4949 pos
4950 (continue t))
4951 (while continue
4952 (if (or (js2-ast-root-p node)
4953 (and
4954 (<= (setq pos (js2-node-abs-pos node)) beg)
4955 (>= (+ pos (js2-node-len node)) end)))
4956 (setq continue nil)
4957 (setq node (js2-node-parent node))))
4958 node))
4959
4960 (defun js2-node-parent-script-or-fn (node)
4961 "Find script or function immediately enclosing NODE.
4962 If NODE is the ast-root, returns nil."
4963 (if (js2-ast-root-p node)
4964 nil
4965 (setq node (js2-node-parent node))
4966 (while (and node (not (or (js2-function-node-p node)
4967 (js2-script-node-p node))))
4968 (setq node (js2-node-parent node)))
4969 node))
4970
4971 (defun js2-node-is-descendant (node ancestor)
4972 "Return t if NODE is a descendant of ANCESTOR."
4973 (while (and node
4974 (not (eq node ancestor)))
4975 (setq node (js2-node-parent node)))
4976 node)
4977
4978 ;;; visitor infrastructure
4979
4980 (defun js2-visit-none (_node _callback)
4981 "Visitor for AST node that have no node children."
4982 nil)
4983
4984 (defun js2-print-none (_node _indent)
4985 "Visitor for AST node with no printed representation.")
4986
4987 (defun js2-print-body (node indent)
4988 "Print a statement, or a block without braces."
4989 (if (js2-block-node-p node)
4990 (dolist (kid (js2-block-node-kids node))
4991 (js2-print-ast kid indent))
4992 (js2-print-ast node indent)))
4993
4994 (defun js2-print-list (args &optional delimiter)
4995 (cl-loop with len = (length args)
4996 for arg in args
4997 for count from 1
4998 do
4999 (when arg (js2-print-ast arg 0))
5000 (if (< count len)
5001 (insert (or delimiter ", ")))))
5002
5003 (defun js2-print-tree (ast)
5004 "Prints an AST to the current buffer.
5005 Makes `js2-ast-parent-nodes' available to the printer functions."
5006 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5007 (js2-print-ast ast)))
5008
5009 (defun js2-print-ast (node &optional indent)
5010 "Helper function for printing AST nodes.
5011 Requires `js2-ast-parent-nodes' to be non-nil.
5012 You should use `js2-print-tree' instead of this function."
5013 (let ((printer (get (aref node 0) 'js2-printer))
5014 (i (or indent 0)))
5015 ;; TODO: wedge comments in here somewhere
5016 (if printer
5017 (funcall printer node i))))
5018
5019 (defconst js2-side-effecting-tokens
5020 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5021 (dolist (tt (list js2-ASSIGN
5022 js2-ASSIGN_ADD
5023 js2-ASSIGN_BITAND
5024 js2-ASSIGN_BITOR
5025 js2-ASSIGN_BITXOR
5026 js2-ASSIGN_DIV
5027 js2-ASSIGN_LSH
5028 js2-ASSIGN_MOD
5029 js2-ASSIGN_MUL
5030 js2-ASSIGN_RSH
5031 js2-ASSIGN_SUB
5032 js2-ASSIGN_URSH
5033 js2-BLOCK
5034 js2-BREAK
5035 js2-CALL
5036 js2-CATCH
5037 js2-CATCH_SCOPE
5038 js2-CLASS
5039 js2-CONST
5040 js2-CONTINUE
5041 js2-DEBUGGER
5042 js2-DEC
5043 js2-DELPROP
5044 js2-DEL_REF
5045 js2-DO
5046 js2-ELSE
5047 js2-EMPTY
5048 js2-ENTERWITH
5049 js2-EXPORT
5050 js2-EXPR_RESULT
5051 js2-FINALLY
5052 js2-FOR
5053 js2-FUNCTION
5054 js2-GOTO
5055 js2-IF
5056 js2-IFEQ
5057 js2-IFNE
5058 js2-IMPORT
5059 js2-INC
5060 js2-JSR
5061 js2-LABEL
5062 js2-LEAVEWITH
5063 js2-LET
5064 js2-LETEXPR
5065 js2-LOCAL_BLOCK
5066 js2-LOOP
5067 js2-NEW
5068 js2-REF_CALL
5069 js2-RETHROW
5070 js2-RETURN
5071 js2-RETURN_RESULT
5072 js2-SEMI
5073 js2-SETELEM
5074 js2-SETELEM_OP
5075 js2-SETNAME
5076 js2-SETPROP
5077 js2-SETPROP_OP
5078 js2-SETVAR
5079 js2-SET_REF
5080 js2-SET_REF_OP
5081 js2-SWITCH
5082 js2-TARGET
5083 js2-THROW
5084 js2-TRY
5085 js2-VAR
5086 js2-WHILE
5087 js2-WITH
5088 js2-WITHEXPR
5089 js2-YIELD))
5090 (aset tokens tt t))
5091 (if js2-instanceof-has-side-effects
5092 (aset tokens js2-INSTANCEOF t))
5093 tokens))
5094
5095 (defun js2-node-has-side-effects (node)
5096 "Return t if NODE has side effects."
5097 (when node ; makes it easier to handle malformed expressions
5098 (let ((tt (js2-node-type node)))
5099 (cond
5100 ;; This doubtless needs some work, since EXPR_VOID is used
5101 ;; in several ways in Rhino and I may not have caught them all.
5102 ;; I'll wait for people to notice incorrect warnings.
5103 ((and (= tt js2-EXPR_VOID)
5104 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5105 (let ((expr (js2-expr-stmt-node-expr node)))
5106 (or (js2-node-has-side-effects expr)
5107 (when (js2-string-node-p expr)
5108 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5109 ((= tt js2-COMMA)
5110 (js2-node-has-side-effects (js2-infix-node-right node)))
5111 ((or (= tt js2-AND)
5112 (= tt js2-OR))
5113 (or (js2-node-has-side-effects (js2-infix-node-right node))
5114 (js2-node-has-side-effects (js2-infix-node-left node))))
5115 ((= tt js2-HOOK)
5116 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5117 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5118 ((js2-paren-node-p node)
5119 (js2-node-has-side-effects (js2-paren-node-expr node)))
5120 ((= tt js2-ERROR) ; avoid cascaded error messages
5121 nil)
5122 (t
5123 (aref js2-side-effecting-tokens tt))))))
5124
5125 (defconst js2-stmt-node-types
5126 (list js2-BLOCK
5127 js2-BREAK
5128 js2-CONTINUE
5129 js2-DEFAULT ; e4x "default xml namespace" statement
5130 js2-DO
5131 js2-EXPORT
5132 js2-EXPR_RESULT
5133 js2-EXPR_VOID
5134 js2-FOR
5135 js2-IF
5136 js2-IMPORT
5137 js2-RETURN
5138 js2-SWITCH
5139 js2-THROW
5140 js2-TRY
5141 js2-WHILE
5142 js2-WITH)
5143 "Node types that only appear in statement contexts.
5144 The list does not include nodes that always appear as the child
5145 of another specific statement type, such as switch-cases,
5146 catch and finally blocks, and else-clauses. The list also excludes
5147 nodes like yield, let and var, which may appear in either expression
5148 or statement context, and in the latter context always have a
5149 `js2-expr-stmt-node' parent. Finally, the list does not include
5150 functions or scripts, which are treated separately from statements
5151 by the JavaScript parser and runtime.")
5152
5153 (defun js2-stmt-node-p (node)
5154 "Heuristic for figuring out if NODE is a statement.
5155 Some node types can appear in either an expression context or a
5156 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5157 For these node types in a statement context, the parent will be a
5158 `js2-expr-stmt-node'.
5159 Functions aren't included in the check."
5160 (memq (js2-node-type node) js2-stmt-node-types))
5161
5162 (defun js2-mode-find-first-stmt (node)
5163 "Search upward starting from NODE looking for a statement.
5164 For purposes of this function, a `js2-function-node' counts."
5165 (while (not (or (js2-stmt-node-p node)
5166 (js2-function-node-p node)))
5167 (setq node (js2-node-parent node)))
5168 node)
5169
5170 (defun js2-node-parent-stmt (node)
5171 "Return the node's first ancestor that is a statement.
5172 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5173 appearing in a statement context will have a parent that is a
5174 `js2-expr-stmt-node' that will be returned by this function."
5175 (let ((parent (js2-node-parent node)))
5176 (if (or (null parent)
5177 (js2-stmt-node-p parent)
5178 (and (js2-function-node-p parent)
5179 (not (eq (js2-function-node-form parent)
5180 'FUNCTION_EXPRESSION))))
5181 parent
5182 (js2-node-parent-stmt parent))))
5183
5184 ;; In the Mozilla Rhino sources, Roshan James writes:
5185 ;; Does consistent-return analysis on the function body when strict mode is
5186 ;; enabled.
5187 ;;
5188 ;; function (x) { return (x+1) }
5189 ;;
5190 ;; is ok, but
5191 ;;
5192 ;; function (x) { if (x < 0) return (x+1); }
5193 ;;
5194 ;; is not because the function can potentially return a value when the
5195 ;; condition is satisfied and if not, the function does not explicitly
5196 ;; return a value.
5197 ;;
5198 ;; This extends to checking mismatches such as "return" and "return <value>"
5199 ;; used in the same function. Warnings are not emitted if inconsistent
5200 ;; returns exist in code that can be statically shown to be unreachable.
5201 ;; Ex.
5202 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5203 ;;
5204 ;; emits no warning. However if the loop had a break statement, then a
5205 ;; warning would be emitted.
5206 ;;
5207 ;; The consistency analysis looks at control structures such as loops, ifs,
5208 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5209 ;; warns the user about an inconsistent set of termination possibilities.
5210 ;;
5211 ;; These flags enumerate the possible ways a statement/function can
5212 ;; terminate. These flags are used by endCheck() and by the Parser to
5213 ;; detect inconsistent return usage.
5214 ;;
5215 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5216 ;; able to execute (example: throw, continue)
5217 ;;
5218 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5219 ;; next one. Statement such as return dont. A compound statement may have
5220 ;; some branch that drops off control to the next statement.
5221 ;;
5222 ;; END_RETURNS indicates that the statement can return with no value.
5223 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5224 ;;
5225 ;; A compound statement such as
5226 ;; if (condition) {
5227 ;; return value;
5228 ;; }
5229 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5230
5231 (defconst js2-END_UNREACHED 0)
5232 (defconst js2-END_DROPS_OFF 1)
5233 (defconst js2-END_RETURNS 2)
5234 (defconst js2-END_RETURNS_VALUE 4)
5235 (defconst js2-END_YIELDS 8)
5236
5237 (defun js2-has-consistent-return-usage (node)
5238 "Check that every return usage in a function body is consistent.
5239 Returns t if the function satisfies strict mode requirement."
5240 (let ((n (js2-end-check node)))
5241 ;; either it doesn't return a value in any branch...
5242 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5243 ;; or it returns a value (or is unreached) at every branch
5244 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5245 js2-END_RETURNS
5246 js2-END_YIELDS)))))
5247
5248 (defun js2-end-check-if (node)
5249 "Ensure that return usage in then/else blocks is consistent.
5250 If there is no else block, then the return statement can fall through.
5251 Returns logical OR of END_* flags"
5252 (let ((th (js2-if-node-then-part node))
5253 (el (js2-if-node-else-part node)))
5254 (if (null th)
5255 js2-END_UNREACHED
5256 (logior (js2-end-check th) (if el
5257 (js2-end-check el)
5258 js2-END_DROPS_OFF)))))
5259
5260 (defun js2-end-check-switch (node)
5261 "Consistency of return statements is checked between the case statements.
5262 If there is no default, then the switch can fall through. If there is a
5263 default, we check to see if all code paths in the default return or if
5264 there is a code path that can fall through.
5265 Returns logical OR of END_* flags."
5266 (let ((rv js2-END_UNREACHED)
5267 default-case)
5268 ;; examine the cases
5269 (catch 'break
5270 (dolist (c (js2-switch-node-cases node))
5271 (if (js2-case-node-expr c)
5272 (js2-set-flag rv (js2-end-check-block c))
5273 (setq default-case c)
5274 (throw 'break nil))))
5275 ;; we don't care how the cases drop into each other
5276 (js2-clear-flag rv js2-END_DROPS_OFF)
5277 ;; examine the default
5278 (js2-set-flag rv (if default-case
5279 (js2-end-check default-case)
5280 js2-END_DROPS_OFF))
5281 rv))
5282
5283 (defun js2-end-check-try (node)
5284 "If the block has a finally, return consistency is checked in the
5285 finally block. If all code paths in the finally return, then the
5286 returns in the try-catch blocks don't matter. If there is a code path
5287 that does not return or if there is no finally block, the returns
5288 of the try and catch blocks are checked for mismatch.
5289 Returns logical OR of END_* flags."
5290 (let ((finally (js2-try-node-finally-block node))
5291 rv)
5292 ;; check the finally if it exists
5293 (setq rv (if finally
5294 (js2-end-check (js2-finally-node-body finally))
5295 js2-END_DROPS_OFF))
5296 ;; If the finally block always returns, then none of the returns
5297 ;; in the try or catch blocks matter.
5298 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5299 (js2-clear-flag rv js2-END_DROPS_OFF)
5300 ;; examine the try block
5301 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5302 ;; check each catch block
5303 (dolist (cb (js2-try-node-catch-clauses node))
5304 (js2-set-flag rv (js2-end-check cb))))
5305 rv))
5306
5307 (defun js2-end-check-loop (node)
5308 "Return statement in the loop body must be consistent.
5309 The default assumption for any kind of a loop is that it will eventually
5310 terminate. The only exception is a loop with a constant true condition.
5311 Code that follows such a loop is examined only if one can determine
5312 statically that there is a break out of the loop.
5313
5314 for(... ; ... ; ...) {}
5315 for(... in ... ) {}
5316 while(...) { }
5317 do { } while(...)
5318
5319 Returns logical OR of END_* flags."
5320 (let ((rv (js2-end-check (js2-loop-node-body node)))
5321 (condition (cond
5322 ((js2-while-node-p node)
5323 (js2-while-node-condition node))
5324 ((js2-do-node-p node)
5325 (js2-do-node-condition node))
5326 ((js2-for-node-p node)
5327 (js2-for-node-condition node)))))
5328
5329 ;; check to see if the loop condition is always true
5330 (if (and condition
5331 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5332 (js2-clear-flag rv js2-END_DROPS_OFF))
5333
5334 ;; look for effect of breaks
5335 (js2-set-flag rv (js2-node-get-prop node
5336 'CONTROL_BLOCK_PROP
5337 js2-END_UNREACHED))
5338 rv))
5339
5340 (defun js2-end-check-block (node)
5341 "A general block of code is examined statement by statement.
5342 If any statement (even a compound one) returns in all branches, then
5343 subsequent statements are not examined.
5344 Returns logical OR of END_* flags."
5345 (let* ((rv js2-END_DROPS_OFF)
5346 (kids (js2-block-node-kids node))
5347 (n (car kids)))
5348 ;; Check each statement. If the statement can continue onto the next
5349 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5350 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5351 (js2-clear-flag rv js2-END_DROPS_OFF)
5352 (js2-set-flag rv (js2-end-check n))
5353 (setq kids (cdr kids)
5354 n (car kids)))
5355 rv))
5356
5357 (defun js2-end-check-label (node)
5358 "A labeled statement implies that there may be a break to the label.
5359 The function processes the labeled statement and then checks the
5360 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5361 particular label.
5362 Returns logical OR of END_* flags."
5363 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5364 (logior rv (js2-node-get-prop node
5365 'CONTROL_BLOCK_PROP
5366 js2-END_UNREACHED))))
5367
5368 (defun js2-end-check-break (node)
5369 "When a break is encountered annotate the statement being broken
5370 out of by setting its CONTROL_BLOCK_PROP property.
5371 Returns logical OR of END_* flags."
5372 (and (js2-break-node-target node)
5373 (js2-node-set-prop (js2-break-node-target node)
5374 'CONTROL_BLOCK_PROP
5375 js2-END_DROPS_OFF))
5376 js2-END_UNREACHED)
5377
5378 (defun js2-end-check (node)
5379 "Examine the body of a function, doing a basic reachability analysis.
5380 Returns a combination of flags END_* flags that indicate
5381 how the function execution can terminate. These constitute only the
5382 pessimistic set of termination conditions. It is possible that at
5383 runtime certain code paths will never be actually taken. Hence this
5384 analysis will flag errors in cases where there may not be errors.
5385 Returns logical OR of END_* flags"
5386 (let (kid)
5387 (cond
5388 ((js2-break-node-p node)
5389 (js2-end-check-break node))
5390 ((js2-expr-stmt-node-p node)
5391 (if (setq kid (js2-expr-stmt-node-expr node))
5392 (js2-end-check kid)
5393 js2-END_DROPS_OFF))
5394 ((or (js2-continue-node-p node)
5395 (js2-throw-node-p node))
5396 js2-END_UNREACHED)
5397 ((js2-return-node-p node)
5398 (if (setq kid (js2-return-node-retval node))
5399 js2-END_RETURNS_VALUE
5400 js2-END_RETURNS))
5401 ((js2-loop-node-p node)
5402 (js2-end-check-loop node))
5403 ((js2-switch-node-p node)
5404 (js2-end-check-switch node))
5405 ((js2-labeled-stmt-node-p node)
5406 (js2-end-check-label node))
5407 ((js2-if-node-p node)
5408 (js2-end-check-if node))
5409 ((js2-try-node-p node)
5410 (js2-end-check-try node))
5411 ((js2-block-node-p node)
5412 (if (null (js2-block-node-kids node))
5413 js2-END_DROPS_OFF
5414 (js2-end-check-block node)))
5415 ((js2-yield-node-p node)
5416 js2-END_YIELDS)
5417 (t
5418 js2-END_DROPS_OFF))))
5419
5420 (defun js2-always-defined-boolean-p (node)
5421 "Check if NODE always evaluates to true or false in boolean context.
5422 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5423 nor always false."
5424 (let ((tt (js2-node-type node))
5425 num)
5426 (cond
5427 ((or (= tt js2-FALSE) (= tt js2-NULL))
5428 'ALWAYS_FALSE)
5429 ((= tt js2-TRUE)
5430 'ALWAYS_TRUE)
5431 ((= tt js2-NUMBER)
5432 (setq num (js2-number-node-num-value node))
5433 (if (and (not (eq num 0.0e+NaN))
5434 (not (zerop num)))
5435 'ALWAYS_TRUE
5436 'ALWAYS_FALSE))
5437 (t
5438 nil))))
5439
5440 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5441 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5442
5443 (defvar js2-tokens nil
5444 "List of all defined token names.") ; initialized in `js2-token-names'
5445
5446 (defconst js2-token-names
5447 (let* ((names (make-vector js2-num-tokens -1))
5448 (case-fold-search nil) ; only match js2-UPPER_CASE
5449 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5450 (cl-loop for sym in syms
5451 for i from 0
5452 do
5453 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5454 (not (boundp sym)))
5455 (aset names (symbol-value sym) ; code, e.g. 152
5456 (downcase
5457 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5458 (push sym js2-tokens)))
5459 names)
5460 "Vector mapping int values to token string names, sans `js2-' prefix.")
5461
5462 (defun js2-tt-name (tok)
5463 "Return a string name for TOK, a token symbol or code.
5464 Signals an error if it's not a recognized token."
5465 (let ((code tok))
5466 (if (symbolp tok)
5467 (setq code (symbol-value tok)))
5468 (if (eq code -1)
5469 "ERROR"
5470 (if (and (numberp code)
5471 (not (cl-minusp code))
5472 (< code js2-num-tokens))
5473 (aref js2-token-names code)
5474 (error "Invalid token: %s" code)))))
5475
5476 (defsubst js2-tt-sym (tok)
5477 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5478 (intern (js2-tt-name tok)))
5479
5480 (defconst js2-token-codes
5481 (let ((table (make-hash-table :test 'eq :size 256)))
5482 (cl-loop for name across js2-token-names
5483 for sym = (intern (concat "js2-" (upcase name)))
5484 do
5485 (puthash sym (symbol-value sym) table))
5486 ;; clean up a few that are "wrong" in Rhino's token codes
5487 (puthash 'js2-DELETE js2-DELPROP table)
5488 table)
5489 "Hashtable mapping token type symbols to their bytecodes.")
5490
5491 (defsubst js2-tt-code (sym)
5492 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5493 (or (gethash sym js2-token-codes)
5494 (error "Invalid token symbol: %s " sym))) ; signal code bug
5495
5496 (defun js2-report-scan-error (msg &optional no-throw beg len)
5497 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5498 (js2-report-error msg nil
5499 (or beg (js2-current-token-beg))
5500 (or len (js2-current-token-len)))
5501 (unless no-throw
5502 (throw 'return js2-ERROR)))
5503
5504 (defun js2-set-string-from-buffer (token)
5505 "Set `string' and `end' slots for TOKEN, return the string."
5506 (setf (js2-token-end token) js2-ts-cursor
5507 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5508
5509 ;; TODO: could potentially avoid a lot of consing by allocating a
5510 ;; char buffer the way Rhino does.
5511 (defsubst js2-add-to-string (c)
5512 (push c js2-ts-string-buffer))
5513
5514 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5515 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5516 ;; any other character: when it's not part of the current token, we
5517 ;; unget it, allowing it to be read again by the following call.
5518 (defsubst js2-unget-char ()
5519 (cl-decf js2-ts-cursor))
5520
5521 ;; Rhino distinguishes \r and \n line endings. We don't need to
5522 ;; because we only scan from Emacs buffers, which always use \n.
5523 (defun js2-get-char ()
5524 "Read and return the next character from the input buffer.
5525 Increments `js2-ts-lineno' if the return value is a newline char.
5526 Updates `js2-ts-cursor' to the point after the returned char.
5527 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5528 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5529 (let (c)
5530 ;; check for end of buffer
5531 (if (>= js2-ts-cursor (point-max))
5532 (setq js2-ts-hit-eof t
5533 js2-ts-cursor (1+ js2-ts-cursor)
5534 c js2-EOF_CHAR) ; return value
5535 ;; otherwise read next char
5536 (setq c (char-before (cl-incf js2-ts-cursor)))
5537 ;; if we read a newline, update counters
5538 (if (= c ?\n)
5539 (setq js2-ts-line-start js2-ts-cursor
5540 js2-ts-lineno (1+ js2-ts-lineno)))
5541 ;; TODO: skip over format characters
5542 c)))
5543
5544 (defun js2-read-unicode-escape ()
5545 "Read a \\uNNNN sequence from the input.
5546 Assumes the ?\ and ?u have already been read.
5547 Returns the unicode character, or nil if it wasn't a valid character.
5548 Doesn't change the values of any scanner variables."
5549 ;; I really wish I knew a better way to do this, but I can't
5550 ;; find the Emacs function that takes a 16-bit int and converts
5551 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5552 ;; Have to first check that it's 4 hex characters or it may stop
5553 ;; the read early.
5554 (ignore-errors
5555 (let ((s (buffer-substring-no-properties js2-ts-cursor
5556 (+ 4 js2-ts-cursor))))
5557 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5558 (read (concat "?\\u" s))))))
5559
5560 (defun js2-match-char (test)
5561 "Consume and return next character if it matches TEST, a character.
5562 Returns nil and consumes nothing if TEST is not the next character."
5563 (let ((c (js2-get-char)))
5564 (if (eq c test)
5565 t
5566 (js2-unget-char)
5567 nil)))
5568
5569 (defun js2-peek-char ()
5570 (prog1
5571 (js2-get-char)
5572 (js2-unget-char)))
5573
5574 (defun js2-identifier-start-p (c)
5575 "Is C a valid start to an ES5 Identifier?
5576 See http://es5.github.io/#x7.6"
5577 (or
5578 (memq c '(?$ ?_))
5579 (memq (get-char-code-property c 'general-category)
5580 ;; Letters
5581 '(Lu Ll Lt Lm Lo Nl))))
5582
5583 (defun js2-identifier-part-p (c)
5584 "Is C a valid part of an ES5 Identifier?
5585 See http://es5.github.io/#x7.6"
5586 (or
5587 (memq c '(?$ ?_ ?\u200c ?\u200d))
5588 (memq (get-char-code-property c 'general-category)
5589 '(;; Letters
5590 Lu Ll Lt Lm Lo Nl
5591 ;; Combining Marks
5592 Mn Mc
5593 ;; Digits
5594 Nd
5595 ;; Connector Punctuation
5596 Pc))))
5597
5598 (defun js2-alpha-p (c)
5599 (cond ((and (<= ?A c) (<= c ?Z)) t)
5600 ((and (<= ?a c) (<= c ?z)) t)
5601 (t nil)))
5602
5603 (defsubst js2-digit-p (c)
5604 (and (<= ?0 c) (<= c ?9)))
5605
5606 (defun js2-js-space-p (c)
5607 (if (<= c 127)
5608 (memq c '(#x20 #x9 #xB #xC #xD))
5609 (or
5610 (eq c #xA0)
5611 ;; TODO: change this nil to check for Unicode space character
5612 nil)))
5613
5614 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5615
5616 (defun js2-skip-line ()
5617 "Skip to end of line."
5618 (while (not (memq (js2-get-char) js2-eol-chars)))
5619 (js2-unget-char)
5620 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5621
5622 (defun js2-init-scanner (&optional buf line)
5623 "Create token stream for BUF starting on LINE.
5624 BUF defaults to `current-buffer' and LINE defaults to 1.
5625
5626 A buffer can only have one scanner active at a time, which yields
5627 dramatically simpler code than using a defstruct. If you need to
5628 have simultaneous scanners in a buffer, copy the regions to scan
5629 into temp buffers."
5630 (with-current-buffer (or buf (current-buffer))
5631 (setq js2-ts-dirty-line nil
5632 js2-ts-hit-eof nil
5633 js2-ts-line-start 0
5634 js2-ts-lineno (or line 1)
5635 js2-ts-line-end-char -1
5636 js2-ts-cursor (point-min)
5637 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5638 js2-ti-tokens-cursor 0
5639 js2-ti-lookahead 0
5640 js2-ts-is-xml-attribute nil
5641 js2-ts-xml-is-tag-content nil
5642 js2-ts-xml-open-tags-count 0
5643 js2-ts-string-buffer nil)))
5644
5645 ;; This function uses the cached op, string and number fields in
5646 ;; TokenStream; if getToken has been called since the passed token
5647 ;; was scanned, the op or string printed may be incorrect.
5648 (defun js2-token-to-string (token)
5649 ;; Not sure where this function is used in Rhino. Not tested.
5650 (if (not js2-debug-print-trees)
5651 ""
5652 (let ((name (js2-tt-name token)))
5653 (cond
5654 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5655 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5656 (concat name " `" (js2-current-token-string) "'"))
5657 ((eq token js2-NUMBER)
5658 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5659 (t
5660 name)))))
5661
5662 (defconst js2-keywords
5663 '(break
5664 case catch class const continue
5665 debugger default delete do
5666 else extends export
5667 false finally for function
5668 if in instanceof import
5669 let
5670 new null
5671 return
5672 super switch
5673 this throw true try typeof
5674 var void
5675 while with
5676 yield))
5677
5678 ;; Token names aren't exactly the same as the keywords, unfortunately.
5679 ;; E.g. delete is js2-DELPROP.
5680 (defconst js2-kwd-tokens
5681 (let ((table (make-vector js2-num-tokens nil))
5682 (tokens
5683 (list js2-BREAK
5684 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5685 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5686 js2-ELSE js2-EXPORT
5687 js2-ELSE js2-EXTENDS js2-EXPORT
5688 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5689 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5690 js2-LET
5691 js2-NEW js2-NULL
5692 js2-RETURN
5693 js2-SUPER js2-SWITCH
5694 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5695 js2-VAR
5696 js2-WHILE js2-WITH
5697 js2-YIELD)))
5698 (dolist (i tokens)
5699 (aset table i 'font-lock-keyword-face))
5700 (aset table js2-STRING 'font-lock-string-face)
5701 (aset table js2-REGEXP 'font-lock-string-face)
5702 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5703 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5704 (aset table js2-COMMENT 'font-lock-comment-face)
5705 (aset table js2-THIS 'font-lock-builtin-face)
5706 (aset table js2-SUPER 'font-lock-builtin-face)
5707 (aset table js2-VOID 'font-lock-constant-face)
5708 (aset table js2-NULL 'font-lock-constant-face)
5709 (aset table js2-TRUE 'font-lock-constant-face)
5710 (aset table js2-FALSE 'font-lock-constant-face)
5711 (aset table js2-NOT 'font-lock-negation-char-face)
5712 table)
5713 "Vector whose values are non-nil for tokens that are keywords.
5714 The values are default faces to use for highlighting the keywords.")
5715
5716 ;; FIXME: Support strict mode-only future reserved words, after we know
5717 ;; which parts scopes are in strict mode, and which are not.
5718 (defconst js2-reserved-words '(class enum export extends import static super)
5719 "Future reserved keywords in ECMAScript 5.1.")
5720
5721 (defconst js2-keyword-names
5722 (let ((table (make-hash-table :test 'equal)))
5723 (cl-loop for k in js2-keywords
5724 do (puthash
5725 (symbol-name k) ; instanceof
5726 (intern (concat "js2-"
5727 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5728 table))
5729 table)
5730 "JavaScript keywords by name, mapped to their symbols.")
5731
5732 (defconst js2-reserved-word-names
5733 (let ((table (make-hash-table :test 'equal)))
5734 (cl-loop for k in js2-reserved-words
5735 do
5736 (puthash (symbol-name k) 'js2-RESERVED table))
5737 table)
5738 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5739
5740 (defun js2-collect-string (buf)
5741 "Convert BUF, a list of chars, to a string.
5742 Reverses BUF before converting."
5743 (if buf
5744 (apply #'string (nreverse buf))
5745 ""))
5746
5747 (defun js2-string-to-keyword (s)
5748 "Return token for S, a string, if S is a keyword or reserved word.
5749 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5750 (or (gethash s js2-keyword-names)
5751 (gethash s js2-reserved-word-names)))
5752
5753 (defsubst js2-ts-set-char-token-bounds (token)
5754 "Used when next token is one character."
5755 (setf (js2-token-beg token) (1- js2-ts-cursor)
5756 (js2-token-end token) js2-ts-cursor))
5757
5758 (defsubst js2-ts-return (token type)
5759 "Update the `end' and `type' slots of TOKEN,
5760 then throw `return' with value TYPE."
5761 (setf (js2-token-end token) js2-ts-cursor
5762 (js2-token-type token) type)
5763 (throw 'return type))
5764
5765 (defun js2-x-digit-to-int (c accumulator)
5766 "Build up a hex number.
5767 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5768 corresponding number. Otherwise return -1."
5769 (catch 'return
5770 (catch 'check
5771 ;; Use 0..9 < A..Z < a..z
5772 (cond
5773 ((<= c ?9)
5774 (cl-decf c ?0)
5775 (if (<= 0 c)
5776 (throw 'check nil)))
5777 ((<= c ?F)
5778 (when (<= ?A c)
5779 (cl-decf c (- ?A 10))
5780 (throw 'check nil)))
5781 ((<= c ?f)
5782 (when (<= ?a c)
5783 (cl-decf c (- ?a 10))
5784 (throw 'check nil))))
5785 (throw 'return -1))
5786 (logior c (lsh accumulator 4))))
5787
5788 (defun js2-get-token (&optional modifier)
5789 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5790 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5791 next saved token.
5792
5793 This function will not return a newline (js2-EOL) - instead, it
5794 gobbles newlines until it finds a non-newline token. Call
5795 `js2-peek-token-or-eol' when you care about newlines.
5796
5797 This function will also not return a js2-COMMENT. Instead, it
5798 records comments found in `js2-scanned-comments'. If the token
5799 returned by this function immediately follows a jsdoc comment,
5800 the token is flagged as such."
5801 (if (zerop js2-ti-lookahead)
5802 (js2-get-token-internal modifier)
5803 (cl-decf js2-ti-lookahead)
5804 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5805 (let ((tt (js2-current-token-type)))
5806 (cl-assert (not (= tt js2-EOL)))
5807 tt)))
5808
5809 (defun js2-unget-token ()
5810 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5811 (cl-incf js2-ti-lookahead)
5812 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5813
5814 (defun js2-get-token-internal (modifier)
5815 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5816 (tt (js2-token-type token))
5817 saw-eol
5818 face)
5819 ;; process comments
5820 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5821 (if (= tt js2-EOL)
5822 (setq saw-eol t)
5823 (setq saw-eol nil)
5824 (when js2-record-comments
5825 (js2-record-comment token)))
5826 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5827 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5828 tt (js2-token-type token)))
5829
5830 (when saw-eol
5831 (setf (js2-token-follows-eol-p token) t))
5832
5833 ;; perform lexical fontification as soon as token is scanned
5834 (when js2-parse-ide-mode
5835 (cond
5836 ((cl-minusp tt)
5837 (js2-record-face 'js2-error token))
5838 ((setq face (aref js2-kwd-tokens tt))
5839 (js2-record-face face token))
5840 ((and (= tt js2-NAME)
5841 (equal (js2-token-string token) "undefined"))
5842 (js2-record-face 'font-lock-constant-face token))))
5843 tt))
5844
5845 (defsubst js2-string-to-number (str base)
5846 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5847 (condition-case nil
5848 (string-to-number str base)
5849 (overflow-error -1)))
5850
5851 (defun js2-get-token-internal-1 (modifier)
5852 "Return next JavaScript token type, an int such as js2-RETURN.
5853 During operation, creates an instance of `js2-token' struct, sets
5854 its relevant fields and puts it into `js2-ti-tokens'."
5855 (let (identifier-start
5856 is-unicode-escape-start c
5857 contains-escape escape-val str result base
5858 look-for-slash continue tt
5859 (token (js2-new-token 0)))
5860 (setq
5861 tt
5862 (catch 'return
5863 (when (eq modifier 'TEMPLATE_TAIL)
5864 (setf (js2-token-beg token) (1- js2-ts-cursor))
5865 (throw 'return (js2-get-string-or-template-token ?` token)))
5866 (while t
5867 ;; Eat whitespace, possibly sensitive to newlines.
5868 (setq continue t)
5869 (while continue
5870 (setq c (js2-get-char))
5871 (cond
5872 ((eq c js2-EOF_CHAR)
5873 (js2-unget-char)
5874 (js2-ts-set-char-token-bounds token)
5875 (throw 'return js2-EOF))
5876 ((eq c ?\n)
5877 (js2-ts-set-char-token-bounds token)
5878 (setq js2-ts-dirty-line nil)
5879 (throw 'return js2-EOL))
5880 ((not (js2-js-space-p c))
5881 (if (/= c ?-) ; in case end of HTML comment
5882 (setq js2-ts-dirty-line t))
5883 (setq continue nil))))
5884 ;; Assume the token will be 1 char - fixed up below.
5885 (js2-ts-set-char-token-bounds token)
5886 (when (eq c ?@)
5887 (throw 'return js2-XMLATTR))
5888 ;; identifier/keyword/instanceof?
5889 ;; watch out for starting with a <backslash>
5890 (cond
5891 ((eq c ?\\)
5892 (setq c (js2-get-char))
5893 (if (eq c ?u)
5894 (setq identifier-start t
5895 is-unicode-escape-start t
5896 js2-ts-string-buffer nil)
5897 (setq identifier-start nil)
5898 (js2-unget-char)
5899 (setq c ?\\)))
5900 (t
5901 (when (setq identifier-start (js2-identifier-start-p c))
5902 (setq js2-ts-string-buffer nil)
5903 (js2-add-to-string c))))
5904 (when identifier-start
5905 (setq contains-escape is-unicode-escape-start)
5906 (catch 'break
5907 (while t
5908 (if is-unicode-escape-start
5909 ;; strictly speaking we should probably push-back
5910 ;; all the bad characters if the <backslash>uXXXX
5911 ;; sequence is malformed. But since there isn't a
5912 ;; correct context(is there?) for a bad Unicode
5913 ;; escape sequence in an identifier, we can report
5914 ;; an error here.
5915 (progn
5916 (setq escape-val 0)
5917 (dotimes (_ 4)
5918 (setq c (js2-get-char)
5919 escape-val (js2-x-digit-to-int c escape-val))
5920 ;; Next check takes care of c < 0 and bad escape
5921 (if (cl-minusp escape-val)
5922 (throw 'break nil)))
5923 (if (cl-minusp escape-val)
5924 (js2-report-scan-error "msg.invalid.escape" t))
5925 (js2-add-to-string escape-val)
5926 (setq is-unicode-escape-start nil))
5927 (setq c (js2-get-char))
5928 (cond
5929 ((eq c ?\\)
5930 (setq c (js2-get-char))
5931 (if (eq c ?u)
5932 (setq is-unicode-escape-start t
5933 contains-escape t)
5934 (js2-report-scan-error "msg.illegal.character" t)))
5935 (t
5936 (if (or (eq c js2-EOF_CHAR)
5937 (not (js2-identifier-part-p c)))
5938 (throw 'break nil))
5939 (js2-add-to-string c))))))
5940 (js2-unget-char)
5941 (setf str (js2-collect-string js2-ts-string-buffer)
5942 (js2-token-end token) js2-ts-cursor)
5943 ;; FIXME: Invalid in ES5 and ES6, see
5944 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5945 ;; Probably should just drop this conditional.
5946 (unless contains-escape
5947 ;; OPT we shouldn't have to make a string (object!) to
5948 ;; check if it's a keyword.
5949 ;; Return the corresponding token if it's a keyword
5950 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5951 (setq result (js2-string-to-keyword str)))
5952 (if (and (< js2-language-version 170)
5953 (memq result '(js2-LET js2-YIELD)))
5954 ;; LET and YIELD are tokens only in 1.7 and later
5955 (setq result 'js2-NAME))
5956 (when (eq result 'js2-RESERVED)
5957 (setf (js2-token-string token) str))
5958 (throw 'return (js2-tt-code result))))
5959 ;; If we want to intern these as Rhino does, just use (intern str)
5960 (setf (js2-token-string token) str)
5961 (throw 'return js2-NAME)) ; end identifier/kwd check
5962 ;; is it a number?
5963 (when (or (js2-digit-p c)
5964 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5965 (setq js2-ts-string-buffer nil
5966 base 10)
5967 (when (eq c ?0)
5968 (setq c (js2-get-char))
5969 (cond
5970 ((or (eq c ?x) (eq c ?X))
5971 (setq base 16)
5972 (setq c (js2-get-char)))
5973 ((and (or (eq c ?b) (eq c ?B))
5974 (>= js2-language-version 200))
5975 (setq base 2)
5976 (setq c (js2-get-char)))
5977 ((and (or (eq c ?o) (eq c ?O))
5978 (>= js2-language-version 200))
5979 (setq base 8)
5980 (setq c (js2-get-char)))
5981 ((js2-digit-p c)
5982 (setq base 'maybe-8))
5983 (t
5984 (js2-add-to-string ?0))))
5985 (cond
5986 ((eq base 16)
5987 (if (> 0 (js2-x-digit-to-int c 0))
5988 (js2-report-scan-error "msg.missing.hex.digits")
5989 (while (<= 0 (js2-x-digit-to-int c 0))
5990 (js2-add-to-string c)
5991 (setq c (js2-get-char)))))
5992 ((eq base 2)
5993 (if (not (memq c '(?0 ?1)))
5994 (js2-report-scan-error "msg.missing.binary.digits")
5995 (while (memq c '(?0 ?1))
5996 (js2-add-to-string c)
5997 (setq c (js2-get-char)))))
5998 ((eq base 8)
5999 (if (or (> ?0 c) (< ?7 c))
6000 (js2-report-scan-error "msg.missing.octal.digits")
6001 (while (and (<= ?0 c) (>= ?7 c))
6002 (js2-add-to-string c)
6003 (setq c (js2-get-char)))))
6004 (t
6005 (while (and (<= ?0 c) (<= c ?9))
6006 ;; We permit 08 and 09 as decimal numbers, which
6007 ;; makes our behavior a superset of the ECMA
6008 ;; numeric grammar. We might not always be so
6009 ;; permissive, so we warn about it.
6010 (when (and (eq base 'maybe-8) (>= c ?8))
6011 (js2-report-warning "msg.bad.octal.literal"
6012 (if (eq c ?8) "8" "9"))
6013 (setq base 10))
6014 (js2-add-to-string c)
6015 (setq c (js2-get-char)))
6016 (when (eq base 'maybe-8)
6017 (setq base 8))))
6018 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6019 (when (eq c ?.)
6020 (cl-loop do
6021 (js2-add-to-string c)
6022 (setq c (js2-get-char))
6023 while (js2-digit-p c)))
6024 (when (memq c '(?e ?E))
6025 (js2-add-to-string c)
6026 (setq c (js2-get-char))
6027 (when (memq c '(?+ ?-))
6028 (js2-add-to-string c)
6029 (setq c (js2-get-char)))
6030 (unless (js2-digit-p c)
6031 (js2-report-scan-error "msg.missing.exponent" t))
6032 (cl-loop do
6033 (js2-add-to-string c)
6034 (setq c (js2-get-char))
6035 while (js2-digit-p c))))
6036 (js2-unget-char)
6037 (let ((str (js2-set-string-from-buffer token)))
6038 (setf (js2-token-number token) (js2-string-to-number str base)
6039 (js2-token-number-base token) base))
6040 (throw 'return js2-NUMBER))
6041 ;; is it a string?
6042 (when (or (memq c '(?\" ?\'))
6043 (and (>= js2-language-version 200)
6044 (= c ?`)))
6045 (throw 'return
6046 (js2-get-string-or-template-token c token)))
6047 (js2-ts-return token
6048 (cl-case c
6049 (?\;
6050 (throw 'return js2-SEMI))
6051 (?\[
6052 (throw 'return js2-LB))
6053 (?\]
6054 (throw 'return js2-RB))
6055 (?{
6056 (throw 'return js2-LC))
6057 (?}
6058 (throw 'return js2-RC))
6059 (?\(
6060 (throw 'return js2-LP))
6061 (?\)
6062 (throw 'return js2-RP))
6063 (?,
6064 (throw 'return js2-COMMA))
6065 (??
6066 (throw 'return js2-HOOK))
6067 (?:
6068 (if (js2-match-char ?:)
6069 js2-COLONCOLON
6070 (throw 'return js2-COLON)))
6071 (?.
6072 (if (js2-match-char ?.)
6073 (if (js2-match-char ?.)
6074 js2-TRIPLEDOT js2-DOTDOT)
6075 (if (js2-match-char ?\()
6076 js2-DOTQUERY
6077 (throw 'return js2-DOT))))
6078 (?|
6079 (if (js2-match-char ?|)
6080 (throw 'return js2-OR)
6081 (if (js2-match-char ?=)
6082 js2-ASSIGN_BITOR
6083 (throw 'return js2-BITOR))))
6084 (?^
6085 (if (js2-match-char ?=)
6086 js2-ASSIGN_BITOR
6087 (throw 'return js2-BITXOR)))
6088 (?&
6089 (if (js2-match-char ?&)
6090 (throw 'return js2-AND)
6091 (if (js2-match-char ?=)
6092 js2-ASSIGN_BITAND
6093 (throw 'return js2-BITAND))))
6094 (?=
6095 (if (js2-match-char ?=)
6096 (if (js2-match-char ?=)
6097 js2-SHEQ
6098 (throw 'return js2-EQ))
6099 (if (js2-match-char ?>)
6100 (js2-ts-return token js2-ARROW)
6101 (throw 'return js2-ASSIGN))))
6102 (?!
6103 (if (js2-match-char ?=)
6104 (if (js2-match-char ?=)
6105 js2-SHNE
6106 js2-NE)
6107 (throw 'return js2-NOT)))
6108 (?<
6109 ;; NB:treat HTML begin-comment as comment-till-eol
6110 (when (js2-match-char ?!)
6111 (when (js2-match-char ?-)
6112 (when (js2-match-char ?-)
6113 (js2-skip-line)
6114 (setf (js2-token-comment-type (js2-current-token)) 'html)
6115 (throw 'return js2-COMMENT)))
6116 (js2-unget-char))
6117 (if (js2-match-char ?<)
6118 (if (js2-match-char ?=)
6119 js2-ASSIGN_LSH
6120 js2-LSH)
6121 (if (js2-match-char ?=)
6122 js2-LE
6123 (throw 'return js2-LT))))
6124 (?>
6125 (if (js2-match-char ?>)
6126 (if (js2-match-char ?>)
6127 (if (js2-match-char ?=)
6128 js2-ASSIGN_URSH
6129 js2-URSH)
6130 (if (js2-match-char ?=)
6131 js2-ASSIGN_RSH
6132 js2-RSH))
6133 (if (js2-match-char ?=)
6134 js2-GE
6135 (throw 'return js2-GT))))
6136 (?*
6137 (if (js2-match-char ?=)
6138 js2-ASSIGN_MUL
6139 (throw 'return js2-MUL)))
6140 (?/
6141 ;; is it a // comment?
6142 (when (js2-match-char ?/)
6143 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6144 (js2-skip-line)
6145 (setf (js2-token-comment-type token) 'line)
6146 ;; include newline so highlighting goes to end of
6147 ;; window, if there actually is a newline; if we
6148 ;; hit eof, then implicitly there isn't
6149 (unless js2-ts-hit-eof
6150 (cl-incf (js2-token-end token)))
6151 (throw 'return js2-COMMENT))
6152 ;; is it a /* comment?
6153 (when (js2-match-char ?*)
6154 (setf look-for-slash nil
6155 (js2-token-beg token) (- js2-ts-cursor 2)
6156 (js2-token-comment-type token)
6157 (if (js2-match-char ?*)
6158 (progn
6159 (setq look-for-slash t)
6160 'jsdoc)
6161 'block))
6162 (while t
6163 (setq c (js2-get-char))
6164 (cond
6165 ((eq c js2-EOF_CHAR)
6166 (setf (js2-token-end token) (1- js2-ts-cursor))
6167 (js2-report-error "msg.unterminated.comment")
6168 (throw 'return js2-COMMENT))
6169 ((eq c ?*)
6170 (setq look-for-slash t))
6171 ((eq c ?/)
6172 (if look-for-slash
6173 (js2-ts-return token js2-COMMENT)))
6174 (t
6175 (setf look-for-slash nil
6176 (js2-token-end token) js2-ts-cursor)))))
6177 (if (js2-match-char ?=)
6178 js2-ASSIGN_DIV
6179 (throw 'return js2-DIV)))
6180 (?#
6181 (when js2-skip-preprocessor-directives
6182 (js2-skip-line)
6183 (setf (js2-token-comment-type token) 'preprocessor
6184 (js2-token-end token) js2-ts-cursor)
6185 (throw 'return js2-COMMENT))
6186 (throw 'return js2-ERROR))
6187 (?%
6188 (if (js2-match-char ?=)
6189 js2-ASSIGN_MOD
6190 (throw 'return js2-MOD)))
6191 (?~
6192 (throw 'return js2-BITNOT))
6193 (?+
6194 (if (js2-match-char ?=)
6195 js2-ASSIGN_ADD
6196 (if (js2-match-char ?+)
6197 js2-INC
6198 (throw 'return js2-ADD))))
6199 (?-
6200 (cond
6201 ((js2-match-char ?=)
6202 (setq c js2-ASSIGN_SUB))
6203 ((js2-match-char ?-)
6204 (unless js2-ts-dirty-line
6205 ;; treat HTML end-comment after possible whitespace
6206 ;; after line start as comment-until-eol
6207 (when (js2-match-char ?>)
6208 (js2-skip-line)
6209 (setf (js2-token-comment-type (js2-current-token)) 'html)
6210 (throw 'return js2-COMMENT)))
6211 (setq c js2-DEC))
6212 (t
6213 (setq c js2-SUB)))
6214 (setq js2-ts-dirty-line t)
6215 c)
6216 (otherwise
6217 (js2-report-scan-error "msg.illegal.character")))))))
6218 (setf (js2-token-type token) tt)
6219 token))
6220
6221 (defun js2-get-string-or-template-token (quote-char token)
6222 ;; We attempt to accumulate a string the fast way, by
6223 ;; building it directly out of the reader. But if there
6224 ;; are any escaped characters in the string, we revert to
6225 ;; building it out of a string buffer.
6226 (let ((c (js2-get-char))
6227 js2-ts-string-buffer
6228 nc c1 val escape-val)
6229 (catch 'break
6230 (while (/= c quote-char)
6231 (catch 'continue
6232 (when (eq c js2-EOF_CHAR)
6233 (js2-unget-char)
6234 (js2-report-error "msg.unterminated.string.lit")
6235 (throw 'break nil))
6236 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6237 (js2-unget-char)
6238 (js2-report-error "msg.unterminated.string.lit")
6239 (throw 'break nil))
6240 (when (eq c ?\\)
6241 ;; We've hit an escaped character
6242 (setq c (js2-get-char))
6243 (cl-case c
6244 (?b (setq c ?\b))
6245 (?f (setq c ?\f))
6246 (?n (setq c ?\n))
6247 (?r (setq c ?\r))
6248 (?t (setq c ?\t))
6249 (?v (setq c ?\v))
6250 (?u
6251 (setq c1 (js2-read-unicode-escape))
6252 (if js2-parse-ide-mode
6253 (if c1
6254 (progn
6255 ;; just copy the string in IDE-mode
6256 (js2-add-to-string ?\\)
6257 (js2-add-to-string ?u)
6258 (dotimes (_ 3)
6259 (js2-add-to-string (js2-get-char)))
6260 (setq c (js2-get-char))) ; added at end of loop
6261 ;; flag it as an invalid escape
6262 (js2-report-warning "msg.invalid.escape"
6263 nil (- js2-ts-cursor 2) 6))
6264 ;; Get 4 hex digits; if the u escape is not
6265 ;; followed by 4 hex digits, use 'u' + the
6266 ;; literal character sequence that follows.
6267 (js2-add-to-string ?u)
6268 (setq escape-val 0)
6269 (dotimes (_ 4)
6270 (setq c (js2-get-char)
6271 escape-val (js2-x-digit-to-int c escape-val))
6272 (if (cl-minusp escape-val)
6273 (throw 'continue nil))
6274 (js2-add-to-string c))
6275 ;; prepare for replace of stored 'u' sequence by escape value
6276 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6277 c escape-val)))
6278 (?x
6279 ;; Get 2 hex digits, defaulting to 'x'+literal
6280 ;; sequence, as above.
6281 (setq c (js2-get-char)
6282 escape-val (js2-x-digit-to-int c 0))
6283 (if (cl-minusp escape-val)
6284 (progn
6285 (js2-add-to-string ?x)
6286 (throw 'continue nil))
6287 (setq c1 c
6288 c (js2-get-char)
6289 escape-val (js2-x-digit-to-int c escape-val))
6290 (if (cl-minusp escape-val)
6291 (progn
6292 (js2-add-to-string ?x)
6293 (js2-add-to-string c1)
6294 (throw 'continue nil))
6295 ;; got 2 hex digits
6296 (setq c escape-val))))
6297 (?\n
6298 ;; Remove line terminator after escape to follow
6299 ;; SpiderMonkey and C/C++
6300 (setq c (js2-get-char))
6301 (throw 'continue nil))
6302 (t
6303 (when (and (<= ?0 c) (< c ?8))
6304 (setq val (- c ?0)
6305 c (js2-get-char))
6306 (when (and (<= ?0 c) (< c ?8))
6307 (setq val (- (+ (* 8 val) c) ?0)
6308 c (js2-get-char))
6309 (when (and (<= ?0 c)
6310 (< c ?8)
6311 (< val #o37))
6312 ;; c is 3rd char of octal sequence only
6313 ;; if the resulting val <= 0377
6314 (setq val (- (+ (* 8 val) c) ?0)
6315 c (js2-get-char))))
6316 (js2-unget-char)
6317 (setq c val)))))
6318 (when (and (eq quote-char ?`) (eq c ?$))
6319 (when (eq (setq nc (js2-get-char)) ?\{)
6320 (throw 'break nil))
6321 (js2-unget-char))
6322 (js2-add-to-string c)
6323 (setq c (js2-get-char)))))
6324 (js2-set-string-from-buffer token)
6325 (if (not (eq quote-char ?`))
6326 js2-STRING
6327 (if (and (eq c ?$) (eq nc ?\{))
6328 js2-TEMPLATE_HEAD
6329 js2-NO_SUBS_TEMPLATE))))
6330
6331 (defun js2-read-regexp (start-tt)
6332 "Called by parser when it gets / or /= in literal context."
6333 (let (c err
6334 in-class ; inside a '[' .. ']' character-class
6335 flags
6336 (continue t)
6337 (token (js2-new-token 0)))
6338 (setq js2-ts-string-buffer nil)
6339 (if (eq start-tt js2-ASSIGN_DIV)
6340 ;; mis-scanned /=
6341 (js2-add-to-string ?=)
6342 (if (not (eq start-tt js2-DIV))
6343 (error "failed assertion")))
6344 (while (and (not err)
6345 (or (/= (setq c (js2-get-char)) ?/)
6346 in-class))
6347 (cond
6348 ((or (= c ?\n)
6349 (= c js2-EOF_CHAR))
6350 (setf (js2-token-end token) (1- js2-ts-cursor)
6351 err t
6352 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6353 (js2-report-error "msg.unterminated.re.lit"))
6354 (t (cond
6355 ((= c ?\\)
6356 (js2-add-to-string c)
6357 (setq c (js2-get-char)))
6358 ((= c ?\[)
6359 (setq in-class t))
6360 ((= c ?\])
6361 (setq in-class nil)))
6362 (js2-add-to-string c))))
6363 (unless err
6364 (while continue
6365 (cond
6366 ((js2-match-char ?g)
6367 (push ?g flags))
6368 ((js2-match-char ?i)
6369 (push ?i flags))
6370 ((js2-match-char ?m)
6371 (push ?m flags))
6372 ((and (js2-match-char ?u)
6373 (>= js2-language-version 200))
6374 (push ?u flags))
6375 ((and (js2-match-char ?y)
6376 (>= js2-language-version 200))
6377 (push ?y flags))
6378 (t
6379 (setq continue nil))))
6380 (if (js2-alpha-p (js2-peek-char))
6381 (js2-report-scan-error "msg.invalid.re.flag" t
6382 js2-ts-cursor 1))
6383 (js2-set-string-from-buffer token))
6384 (js2-collect-string flags)))
6385
6386 (defun js2-get-first-xml-token ()
6387 (setq js2-ts-xml-open-tags-count 0
6388 js2-ts-is-xml-attribute nil
6389 js2-ts-xml-is-tag-content nil)
6390 (js2-unget-char)
6391 (js2-get-next-xml-token))
6392
6393 (defun js2-xml-discard-string (token)
6394 "Throw away the string in progress and flag an XML parse error."
6395 (setf js2-ts-string-buffer nil
6396 (js2-token-string token) nil)
6397 (js2-report-scan-error "msg.XML.bad.form" t))
6398
6399 (defun js2-get-next-xml-token ()
6400 (setq js2-ts-string-buffer nil) ; for recording the XML
6401 (let ((token (js2-new-token 0))
6402 c result)
6403 (setq result
6404 (catch 'return
6405 (while t
6406 (setq c (js2-get-char))
6407 (cond
6408 ((= c js2-EOF_CHAR)
6409 (throw 'return js2-ERROR))
6410 (js2-ts-xml-is-tag-content
6411 (cl-case c
6412 (?>
6413 (js2-add-to-string c)
6414 (setq js2-ts-xml-is-tag-content nil
6415 js2-ts-is-xml-attribute nil))
6416 (?/
6417 (js2-add-to-string c)
6418 (when (eq ?> (js2-peek-char))
6419 (setq c (js2-get-char))
6420 (js2-add-to-string c)
6421 (setq js2-ts-xml-is-tag-content nil)
6422 (cl-decf js2-ts-xml-open-tags-count)))
6423 (?{
6424 (js2-unget-char)
6425 (js2-set-string-from-buffer token)
6426 (throw 'return js2-XML))
6427 ((?\' ?\")
6428 (js2-add-to-string c)
6429 (unless (js2-read-quoted-string c token)
6430 (throw 'return js2-ERROR)))
6431 (?=
6432 (js2-add-to-string c)
6433 (setq js2-ts-is-xml-attribute t))
6434 ((? ?\t ?\r ?\n)
6435 (js2-add-to-string c))
6436 (t
6437 (js2-add-to-string c)
6438 (setq js2-ts-is-xml-attribute nil)))
6439 (when (and (not js2-ts-xml-is-tag-content)
6440 (zerop js2-ts-xml-open-tags-count))
6441 (js2-set-string-from-buffer token)
6442 (throw 'return js2-XMLEND)))
6443 (t
6444 ;; else not tag content
6445 (cl-case c
6446 (?<
6447 (js2-add-to-string c)
6448 (setq c (js2-peek-char))
6449 (cl-case c
6450 (?!
6451 (setq c (js2-get-char)) ;; skip !
6452 (js2-add-to-string c)
6453 (setq c (js2-peek-char))
6454 (cl-case c
6455 (?-
6456 (setq c (js2-get-char)) ;; skip -
6457 (js2-add-to-string c)
6458 (if (eq c ?-)
6459 (progn
6460 (js2-add-to-string c)
6461 (unless (js2-read-xml-comment token)
6462 (throw 'return js2-ERROR)))
6463 (js2-xml-discard-string token)
6464 (throw 'return js2-ERROR)))
6465 (?\[
6466 (setq c (js2-get-char)) ;; skip [
6467 (js2-add-to-string c)
6468 (if (and (= (js2-get-char) ?C)
6469 (= (js2-get-char) ?D)
6470 (= (js2-get-char) ?A)
6471 (= (js2-get-char) ?T)
6472 (= (js2-get-char) ?A)
6473 (= (js2-get-char) ?\[))
6474 (progn
6475 (js2-add-to-string ?C)
6476 (js2-add-to-string ?D)
6477 (js2-add-to-string ?A)
6478 (js2-add-to-string ?T)
6479 (js2-add-to-string ?A)
6480 (js2-add-to-string ?\[)
6481 (unless (js2-read-cdata token)
6482 (throw 'return js2-ERROR)))
6483 (js2-xml-discard-string token)
6484 (throw 'return js2-ERROR)))
6485 (t
6486 (unless (js2-read-entity token)
6487 (throw 'return js2-ERROR))))
6488 ;; Allow bare CDATA section, e.g.:
6489 ;; let xml = <![CDATA[ foo bar baz ]]>;
6490 (when (zerop js2-ts-xml-open-tags-count)
6491 (throw 'return js2-XMLEND)))
6492 (??
6493 (setq c (js2-get-char)) ;; skip ?
6494 (js2-add-to-string c)
6495 (unless (js2-read-PI token)
6496 (throw 'return js2-ERROR)))
6497 (?/
6498 ;; end tag
6499 (setq c (js2-get-char)) ;; skip /
6500 (js2-add-to-string c)
6501 (when (zerop js2-ts-xml-open-tags-count)
6502 (js2-xml-discard-string token)
6503 (throw 'return js2-ERROR))
6504 (setq js2-ts-xml-is-tag-content t)
6505 (cl-decf js2-ts-xml-open-tags-count))
6506 (t
6507 ;; start tag
6508 (setq js2-ts-xml-is-tag-content t)
6509 (cl-incf js2-ts-xml-open-tags-count))))
6510 (?{
6511 (js2-unget-char)
6512 (js2-set-string-from-buffer token)
6513 (throw 'return js2-XML))
6514 (t
6515 (js2-add-to-string c))))))))
6516 (setf (js2-token-end token) js2-ts-cursor)
6517 (setf (js2-token-type token) result)
6518 result))
6519
6520 (defun js2-read-quoted-string (quote token)
6521 (let (c)
6522 (catch 'return
6523 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6524 (js2-add-to-string c)
6525 (if (eq c quote)
6526 (throw 'return t)))
6527 (js2-xml-discard-string token) ;; throw away string in progress
6528 nil)))
6529
6530 (defun js2-read-xml-comment (token)
6531 (let ((c (js2-get-char)))
6532 (catch 'return
6533 (while (/= c js2-EOF_CHAR)
6534 (catch 'continue
6535 (js2-add-to-string c)
6536 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6537 (setq c (js2-get-char))
6538 (js2-add-to-string c)
6539 (if (eq (js2-peek-char) ?>)
6540 (progn
6541 (setq c (js2-get-char)) ;; skip >
6542 (js2-add-to-string c)
6543 (throw 'return t))
6544 (throw 'continue nil)))
6545 (setq c (js2-get-char))))
6546 (js2-xml-discard-string token)
6547 nil)))
6548
6549 (defun js2-read-cdata (token)
6550 (let ((c (js2-get-char)))
6551 (catch 'return
6552 (while (/= c js2-EOF_CHAR)
6553 (catch 'continue
6554 (js2-add-to-string c)
6555 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6556 (setq c (js2-get-char))
6557 (js2-add-to-string c)
6558 (if (eq (js2-peek-char) ?>)
6559 (progn
6560 (setq c (js2-get-char)) ;; Skip >
6561 (js2-add-to-string c)
6562 (throw 'return t))
6563 (throw 'continue nil)))
6564 (setq c (js2-get-char))))
6565 (js2-xml-discard-string token)
6566 nil)))
6567
6568 (defun js2-read-entity (token)
6569 (let ((decl-tags 1)
6570 c)
6571 (catch 'return
6572 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6573 (js2-add-to-string c)
6574 (cl-case c
6575 (?<
6576 (cl-incf decl-tags))
6577 (?>
6578 (cl-decf decl-tags)
6579 (if (zerop decl-tags)
6580 (throw 'return t)))))
6581 (js2-xml-discard-string token)
6582 nil)))
6583
6584 (defun js2-read-PI (token)
6585 "Scan an XML processing instruction."
6586 (let (c)
6587 (catch 'return
6588 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6589 (js2-add-to-string c)
6590 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6591 (setq c (js2-get-char)) ;; Skip >
6592 (js2-add-to-string c)
6593 (throw 'return t)))
6594 (js2-xml-discard-string token)
6595 nil)))
6596
6597 ;;; Highlighting
6598
6599 (defun js2-set-face (beg end face &optional record)
6600 "Fontify a region. If RECORD is non-nil, record for later."
6601 (when (cl-plusp js2-highlight-level)
6602 (setq beg (min (point-max) beg)
6603 beg (max (point-min) beg)
6604 end (min (point-max) end)
6605 end (max (point-min) end))
6606 (if record
6607 (push (list beg end face) js2-mode-fontifications)
6608 (put-text-property beg end 'font-lock-face face))))
6609
6610 (defsubst js2-clear-face (beg end)
6611 (remove-text-properties beg end '(font-lock-face nil
6612 help-echo nil
6613 point-entered nil
6614 cursor-sensor-functions nil
6615 c-in-sws nil)))
6616
6617 (defconst js2-ecma-global-props
6618 (concat "^"
6619 (regexp-opt
6620 '("Infinity" "NaN" "undefined" "arguments") t)
6621 "$")
6622 "Value properties of the Ecma-262 Global Object.
6623 Shown at or above `js2-highlight-level' 2.")
6624
6625 ;; might want to add the name "arguments" to this list?
6626 (defconst js2-ecma-object-props
6627 (concat "^"
6628 (regexp-opt
6629 '("prototype" "__proto__" "__parent__") t)
6630 "$")
6631 "Value properties of the Ecma-262 Object constructor.
6632 Shown at or above `js2-highlight-level' 2.")
6633
6634 (defconst js2-ecma-global-funcs
6635 (concat
6636 "^"
6637 (regexp-opt
6638 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6639 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6640 "$")
6641 "Function properties of the Ecma-262 Global object.
6642 Shown at or above `js2-highlight-level' 2.")
6643
6644 (defconst js2-ecma-number-props
6645 (concat "^"
6646 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6647 "NEGATIVE_INFINITY"
6648 "POSITIVE_INFINITY") t)
6649 "$")
6650 "Properties of the Ecma-262 Number constructor.
6651 Shown at or above `js2-highlight-level' 2.")
6652
6653 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6654 "Properties of the Ecma-262 Date constructor.
6655 Shown at or above `js2-highlight-level' 2.")
6656
6657 (defconst js2-ecma-math-props
6658 (concat "^"
6659 (regexp-opt
6660 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6661 t)
6662 "$")
6663 "Properties of the Ecma-262 Math object.
6664 Shown at or above `js2-highlight-level' 2.")
6665
6666 (defconst js2-ecma-math-funcs
6667 (concat "^"
6668 (regexp-opt
6669 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6670 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6671 "$")
6672 "Function properties of the Ecma-262 Math object.
6673 Shown at or above `js2-highlight-level' 2.")
6674
6675 (defconst js2-ecma-function-props
6676 (concat
6677 "^"
6678 (regexp-opt
6679 '(;; properties of the Object prototype object
6680 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6681 "toLocaleString" "toString" "valueOf"
6682 ;; properties of the Function prototype object
6683 "apply" "call"
6684 ;; properties of the Array prototype object
6685 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6686 "splice" "unshift"
6687 ;; properties of the String prototype object
6688 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6689 "localeCompare" "match" "replace" "search" "split" "substring"
6690 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6691 "toUpperCase"
6692 ;; properties of the Number prototype object
6693 "toExponential" "toFixed" "toPrecision"
6694 ;; properties of the Date prototype object
6695 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6696 "getMinutes" "getMonth" "getSeconds" "getTime"
6697 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6698 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6699 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6700 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6701 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6702 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6703 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6704 "toTimeString" "toUTCString"
6705 ;; properties of the RegExp prototype object
6706 "exec" "test"
6707 ;; properties of the JSON prototype object
6708 "parse" "stringify"
6709 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6710 "toSource" "__defineGetter__" "__defineSetter__"
6711 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6712 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6713 t)
6714 "$")
6715 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6716 Shown at or above `js2-highlight-level' 3.")
6717
6718 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6719 (let ((target-name (and target
6720 (js2-name-node-p target)
6721 (js2-name-node-name target)))
6722 (prop-name (if prop (js2-name-node-name prop)))
6723 (level2 (>= js2-highlight-level 2))
6724 (level3 (>= js2-highlight-level 3)))
6725 (when level2
6726 (let ((face
6727 (if call-p
6728 (cond
6729 ((and target prop)
6730 (cond
6731 ((and level3 (string-match js2-ecma-function-props prop-name))
6732 'font-lock-builtin-face)
6733 ((and target-name prop)
6734 (cond
6735 ((string= target-name "Date")
6736 (if (string-match js2-ecma-date-props prop-name)
6737 'font-lock-builtin-face))
6738 ((string= target-name "Math")
6739 (if (string-match js2-ecma-math-funcs prop-name)
6740 'font-lock-builtin-face))))))
6741 (prop
6742 (if (string-match js2-ecma-global-funcs prop-name)
6743 'font-lock-builtin-face)))
6744 (cond
6745 ((and target prop)
6746 (cond
6747 ((string= target-name "Number")
6748 (if (string-match js2-ecma-number-props prop-name)
6749 'font-lock-constant-face))
6750 ((string= target-name "Math")
6751 (if (string-match js2-ecma-math-props prop-name)
6752 'font-lock-constant-face))))
6753 (prop
6754 (if (string-match js2-ecma-object-props prop-name)
6755 'font-lock-constant-face))))))
6756 (when face
6757 (let ((pos (+ (js2-node-pos parent) ; absolute
6758 (js2-node-pos prop)))) ; relative
6759 (js2-set-face pos
6760 (+ pos (js2-node-len prop))
6761 face 'record)))))))
6762
6763 (defun js2-parse-highlight-member-expr-node (node)
6764 "Perform syntax highlighting of EcmaScript built-in properties.
6765 The variable `js2-highlight-level' governs this highlighting."
6766 (let (face target prop name pos end parent call-p callee)
6767 (cond
6768 ;; case 1: simple name, e.g. foo
6769 ((js2-name-node-p node)
6770 (setq name (js2-name-node-name node))
6771 ;; possible for name to be nil in rare cases - saw it when
6772 ;; running js2-mode on an elisp buffer. Might as well try to
6773 ;; make it so js2-mode never barfs.
6774 (when name
6775 (setq face (if (string-match js2-ecma-global-props name)
6776 'font-lock-constant-face))
6777 (when face
6778 (setq pos (js2-node-pos node)
6779 end (+ pos (js2-node-len node)))
6780 (js2-set-face pos end face 'record))))
6781 ;; case 2: property access or function call
6782 ((or (js2-prop-get-node-p node)
6783 ;; highlight function call if expr is a prop-get node
6784 ;; or a plain name (i.e. unqualified function call)
6785 (and (setq call-p (js2-call-node-p node))
6786 (setq callee (js2-call-node-target node)) ; separate setq!
6787 (or (js2-prop-get-node-p callee)
6788 (js2-name-node-p callee))))
6789 (setq parent node
6790 node (if call-p callee node))
6791 (if (and call-p (js2-name-node-p callee))
6792 (setq prop callee)
6793 (setq target (js2-prop-get-node-left node)
6794 prop (js2-prop-get-node-right node)))
6795 (cond
6796 ((js2-name-node-p prop)
6797 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6798 (js2-parse-highlight-prop-get parent target prop call-p))
6799 ((js2-name-node-p target)
6800 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6801 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6802
6803 (defun js2-parse-highlight-member-expr-fn-name (expr)
6804 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6805 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6806 We currently only handle the case where the last component is a prop-get
6807 of a simple name. Called before EXPR has a parent node."
6808 (let (pos
6809 (name (and (js2-prop-get-node-p expr)
6810 (js2-prop-get-node-right expr))))
6811 (when (js2-name-node-p name)
6812 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6813 (js2-node-pos name)))
6814 (+ pos (js2-node-len name))
6815 'font-lock-function-name-face
6816 'record))))
6817
6818 ;; source: http://jsdoc.sourceforge.net/
6819 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6820 ;; allows type specifications, and needs work before entering the wild.
6821
6822 (defconst js2-jsdoc-param-tag-regexp
6823 (concat "^\\s-*\\*+\\s-*\\(@"
6824 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6825 "\\)"
6826 "\\s-*\\({[^}]+}\\)?" ; optional type
6827 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6828 "\\_>")
6829 "Matches jsdoc tags with optional type and optional param name.")
6830
6831 (defconst js2-jsdoc-typed-tag-regexp
6832 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6833 (regexp-opt
6834 '("enum"
6835 "extends"
6836 "field"
6837 "id"
6838 "implements"
6839 "lends"
6840 "mods"
6841 "requires"
6842 "return"
6843 "returns"
6844 "throw"
6845 "throws"))
6846 "\\)\\)\\s-*\\({[^}]+}\\)?")
6847 "Matches jsdoc tags with optional type.")
6848
6849 (defconst js2-jsdoc-arg-tag-regexp
6850 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6851 (regexp-opt
6852 '("alias"
6853 "augments"
6854 "borrows"
6855 "bug"
6856 "base"
6857 "config"
6858 "default"
6859 "define"
6860 "exception"
6861 "function"
6862 "member"
6863 "memberOf"
6864 "name"
6865 "namespace"
6866 "since"
6867 "suppress"
6868 "this"
6869 "throws"
6870 "type"
6871 "version"))
6872 "\\)\\)\\s-+\\([^ \t]+\\)")
6873 "Matches jsdoc tags with a single argument.")
6874
6875 (defconst js2-jsdoc-empty-tag-regexp
6876 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6877 (regexp-opt
6878 '("addon"
6879 "author"
6880 "class"
6881 "const"
6882 "constant"
6883 "constructor"
6884 "constructs"
6885 "deprecated"
6886 "desc"
6887 "description"
6888 "event"
6889 "example"
6890 "exec"
6891 "export"
6892 "fileoverview"
6893 "final"
6894 "function"
6895 "hidden"
6896 "ignore"
6897 "implicitCast"
6898 "inheritDoc"
6899 "inner"
6900 "interface"
6901 "license"
6902 "noalias"
6903 "noshadow"
6904 "notypecheck"
6905 "override"
6906 "owner"
6907 "preserve"
6908 "preserveTry"
6909 "private"
6910 "protected"
6911 "public"
6912 "static"
6913 "supported"
6914 ))
6915 "\\)\\)\\s-*")
6916 "Matches empty jsdoc tags.")
6917
6918 (defconst js2-jsdoc-link-tag-regexp
6919 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6920 "Matches a jsdoc link or code tag.")
6921
6922 (defconst js2-jsdoc-see-tag-regexp
6923 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6924 "Matches a jsdoc @see tag.")
6925
6926 (defconst js2-jsdoc-html-tag-regexp
6927 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6928 "Matches a simple (no attributes) html start- or end-tag.")
6929
6930 (defun js2-jsdoc-highlight-helper ()
6931 (js2-set-face (match-beginning 1)
6932 (match-end 1)
6933 'js2-jsdoc-tag)
6934 (if (match-beginning 2)
6935 (if (save-excursion
6936 (goto-char (match-beginning 2))
6937 (= (char-after) ?{))
6938 (js2-set-face (1+ (match-beginning 2))
6939 (1- (match-end 2))
6940 'js2-jsdoc-type)
6941 (js2-set-face (match-beginning 2)
6942 (match-end 2)
6943 'js2-jsdoc-value)))
6944 (if (match-beginning 3)
6945 (js2-set-face (match-beginning 3)
6946 (match-end 3)
6947 'js2-jsdoc-value)))
6948
6949 (defun js2-highlight-jsdoc (ast)
6950 "Highlight doc comment tags."
6951 (let ((comments (js2-ast-root-comments ast))
6952 beg end)
6953 (save-excursion
6954 (dolist (node comments)
6955 (when (eq (js2-comment-node-format node) 'jsdoc)
6956 (setq beg (js2-node-abs-pos node)
6957 end (+ beg (js2-node-len node)))
6958 (save-restriction
6959 (narrow-to-region beg end)
6960 (dolist (re (list js2-jsdoc-param-tag-regexp
6961 js2-jsdoc-typed-tag-regexp
6962 js2-jsdoc-arg-tag-regexp
6963 js2-jsdoc-link-tag-regexp
6964 js2-jsdoc-see-tag-regexp
6965 js2-jsdoc-empty-tag-regexp))
6966 (goto-char beg)
6967 (while (re-search-forward re nil t)
6968 (js2-jsdoc-highlight-helper)))
6969 ;; simple highlighting for html tags
6970 (goto-char beg)
6971 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6972 (js2-set-face (match-beginning 1)
6973 (match-end 1)
6974 'js2-jsdoc-html-tag-delimiter)
6975 (js2-set-face (match-beginning 2)
6976 (match-end 2)
6977 'js2-jsdoc-html-tag-name)
6978 (js2-set-face (match-beginning 3)
6979 (match-end 3)
6980 'js2-jsdoc-html-tag-delimiter))))))))
6981
6982 (defun js2-highlight-assign-targets (_node left right)
6983 "Highlight function properties and external variables."
6984 (let (leftpos name)
6985 ;; highlight vars and props assigned function values
6986 (when (or (js2-function-node-p right)
6987 (js2-class-node-p right))
6988 (cond
6989 ;; var foo = function() {...}
6990 ((js2-name-node-p left)
6991 (setq name left))
6992 ;; foo.bar.baz = function() {...}
6993 ((and (js2-prop-get-node-p left)
6994 (js2-name-node-p (js2-prop-get-node-right left)))
6995 (setq name (js2-prop-get-node-right left))))
6996 (when name
6997 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6998 (+ leftpos (js2-node-len name))
6999 'font-lock-function-name-face
7000 'record)))))
7001
7002 (defun js2-record-name-node (node)
7003 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7004 later. NODE must be a name node."
7005 (let ((leftpos (js2-node-abs-pos node)))
7006 (push (list node js2-current-scope
7007 leftpos
7008 (+ leftpos (js2-node-len node)))
7009 js2-recorded-identifiers)))
7010
7011 (defun js2-highlight-undeclared-vars ()
7012 "After entire parse is finished, look for undeclared variable references.
7013 We have to wait until entire buffer is parsed, since JavaScript permits var
7014 decls to occur after they're used.
7015
7016 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7017 it is considered declared."
7018 (let (name)
7019 (dolist (entry js2-recorded-identifiers)
7020 (cl-destructuring-bind (name-node scope pos end) entry
7021 (setq name (js2-name-node-name name-node))
7022 (unless (or (member name js2-global-externs)
7023 (member name js2-default-externs)
7024 (member name js2-additional-externs)
7025 (js2-get-defining-scope scope name pos))
7026 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7027 'js2-external-variable))))))
7028
7029 (defun js2--add-or-update-symbol (symbol inition used vars)
7030 "Add or update SYMBOL entry in VARS, an hash table.
7031 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7032 respectively meaning that SYMBOL is a mere declaration, an
7033 assignment or a function parameter; when USED is t, the symbol
7034 node is assumed to be an usage and thus added to the list stored
7035 in the cdr of the entry.
7036 "
7037 (let* ((nm (js2-name-node-name symbol))
7038 (es (js2-node-get-enclosing-scope symbol))
7039 (ds (js2-get-defining-scope es nm)))
7040 (when (and ds (not (equal nm "arguments")))
7041 (let* ((sym (js2-scope-get-symbol ds nm))
7042 (var (gethash sym vars))
7043 (err-var-p (js2-catch-node-p ds)))
7044 (unless inition
7045 (setq inition err-var-p))
7046 (if var
7047 (progn
7048 (when (and inition (not (equal (car var) ?P)))
7049 (setcar var inition))
7050 (when used
7051 (push symbol (cdr var))))
7052 ;; do not consider the declaration of catch parameter as an usage
7053 (when (and err-var-p used)
7054 (setq used nil))
7055 (puthash sym (cons inition (if used (list symbol))) vars))))))
7056
7057 (defun js2--classify-variables ()
7058 "Collect and classify variables declared or used within js2-mode-ast.
7059 Traverse the whole ast tree returning a summary of the variables
7060 usage as an hash-table, keyed by their corresponding symbol table
7061 entry.
7062 Each variable is described by a tuple where the car is a flag
7063 indicating whether the variable has been initialized and the cdr
7064 is a possibly empty list of name nodes where it is used. External
7065 symbols, i.e. those not present in the whole scopes hierarchy,
7066 are ignored."
7067 (let ((vars (make-hash-table :test #'eq :size 100)))
7068 (js2-visit-ast
7069 js2-mode-ast
7070 (lambda (node end-p)
7071 (when (null end-p)
7072 (cond
7073 ((js2-var-init-node-p node)
7074 ;; take note about possibly initialized declarations
7075 (let ((target (js2-var-init-node-target node))
7076 (initializer (js2-var-init-node-initializer node)))
7077 (when target
7078 (let* ((parent (js2-node-parent node))
7079 (grandparent (if parent (js2-node-parent parent)))
7080 (inited (not (null initializer))))
7081 (unless inited
7082 (setq inited
7083 (and grandparent
7084 (js2-for-in-node-p grandparent)
7085 (memq target
7086 (mapcar #'js2-var-init-node-target
7087 (js2-var-decl-node-kids
7088 (js2-for-in-node-iterator grandparent)))))))
7089 (js2--add-or-update-symbol target inited nil vars)))))
7090
7091 ((js2-assign-node-p node)
7092 ;; take note about assignments
7093 (let ((left (js2-assign-node-left node)))
7094 (when (js2-name-node-p left)
7095 (js2--add-or-update-symbol left t nil vars))))
7096
7097 ((js2-prop-get-node-p node)
7098 ;; handle x.y.z nodes, considering only x
7099 (let ((left (js2-prop-get-node-left node)))
7100 (when (js2-name-node-p left)
7101 (js2--add-or-update-symbol left nil t vars))))
7102
7103 ((js2-name-node-p node)
7104 ;; take note about used variables
7105 (let ((parent (js2-node-parent node)))
7106 (when parent
7107 (unless (or (and (js2-var-init-node-p parent) ; handled above
7108 (eq node (js2-var-init-node-target parent)))
7109 (and (js2-assign-node-p parent)
7110 (eq node (js2-assign-node-left parent)))
7111 (js2-prop-get-node-p parent))
7112 (let ((used t) inited)
7113 (cond
7114 ((and (js2-function-node-p parent)
7115 (js2-wrapper-function-p parent))
7116 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7117
7118 ((js2-for-in-node-p parent)
7119 (if (eq node (js2-for-in-node-iterator parent))
7120 (setq inited t used nil)))
7121
7122 ((js2-function-node-p parent)
7123 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7124 used nil)))
7125
7126 (unless used
7127 (let ((grandparent (js2-node-parent parent)))
7128 (when grandparent
7129 (setq used (js2-return-node-p grandparent)))))
7130
7131 (js2--add-or-update-symbol node inited used vars))))))))
7132 t))
7133 vars))
7134
7135 (defun js2--get-name-node (node)
7136 (cond
7137 ((js2-name-node-p node) node)
7138 ((js2-function-node-p node)
7139 (js2-function-node-name node))
7140 ((js2-class-node-p node)
7141 (js2-class-node-name node))
7142 ((js2-comp-loop-node-p node)
7143 (js2-comp-loop-node-iterator node))
7144 (t node)))
7145
7146 (defun js2--highlight-unused-variable (symbol info)
7147 (let ((name (js2-symbol-name symbol))
7148 (inited (car info))
7149 (refs (cdr info))
7150 pos len)
7151 (unless (and inited refs)
7152 (if refs
7153 (dolist (ref refs)
7154 (setq pos (js2-node-abs-pos ref))
7155 (setq len (js2-name-node-len ref))
7156 (js2-report-warning "msg.uninitialized.variable" name pos len
7157 'js2-warning))
7158 (when (or js2-warn-about-unused-function-arguments
7159 (not (eq inited ?P)))
7160 (let* ((symn (js2-symbol-ast-node symbol))
7161 (namen (js2--get-name-node symn)))
7162 (unless (js2-node-top-level-decl-p namen)
7163 (setq pos (js2-node-abs-pos namen))
7164 (setq len (js2-name-node-len namen))
7165 (js2-report-warning "msg.unused.variable" name pos len
7166 'js2-warning))))))))
7167
7168 (defun js2-highlight-unused-variables ()
7169 "Highlight unused variables."
7170 (let ((vars (js2--classify-variables)))
7171 (maphash #'js2--highlight-unused-variable vars)))
7172
7173 ;;;###autoload
7174 (define-minor-mode js2-highlight-unused-variables-mode
7175 "Toggle highlight of unused variables."
7176 :lighter ""
7177 (if js2-highlight-unused-variables-mode
7178 (add-hook 'js2-post-parse-callbacks
7179 #'js2-highlight-unused-variables nil t)
7180 (remove-hook 'js2-post-parse-callbacks
7181 #'js2-highlight-unused-variables t)))
7182
7183 (defun js2-set-default-externs ()
7184 "Set the value of `js2-default-externs' based on the various
7185 `js2-include-?-externs' variables."
7186 (setq js2-default-externs
7187 (append js2-ecma-262-externs
7188 (if js2-include-browser-externs js2-browser-externs)
7189 (if (and js2-include-browser-externs
7190 (>= js2-language-version 200)) js2-harmony-externs)
7191 (if js2-include-rhino-externs js2-rhino-externs)
7192 (if js2-include-node-externs js2-node-externs)
7193 (if (or js2-include-browser-externs js2-include-node-externs)
7194 js2-typed-array-externs))))
7195
7196 (defun js2-apply-jslint-globals ()
7197 (setq js2-additional-externs
7198 (nconc (js2-get-jslint-globals)
7199 js2-additional-externs)))
7200
7201 (defun js2-get-jslint-globals ()
7202 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7203 when (and (eq 'block (js2-comment-node-format node))
7204 (save-excursion
7205 (goto-char (js2-node-abs-pos node))
7206 (looking-at "/\\*global ")))
7207 append (js2-get-jslint-globals-in
7208 (match-end 0)
7209 (js2-node-abs-end node))))
7210
7211 (defun js2-get-jslint-globals-in (beg end)
7212 (let (res)
7213 (save-excursion
7214 (goto-char beg)
7215 (while (re-search-forward js2-mode-identifier-re end t)
7216 (let ((match (match-string 0)))
7217 (unless (member match '("true" "false"))
7218 (push match res)))))
7219 (nreverse res)))
7220
7221 ;;; IMenu support
7222
7223 ;; We currently only support imenu, but eventually should support speedbar and
7224 ;; possibly other browsing mechanisms.
7225
7226 ;; The basic strategy is to identify function assignment targets of the form
7227 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7228 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7229 ;; for imenu after parsing is finished.
7230
7231 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7232 ;; JavaScript, and the general problem is undecidable. However, several forms
7233 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7234 ;; include:
7235
7236 ;; function foo() -- function declaration
7237 ;; foo = function() -- function expression assigned to variable
7238 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7239 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7240 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7241 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7242 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7243 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7244 ;; function foo() {function bar() {...}} -- nested function
7245 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7246
7247 ;; This list boils down to a few forms that can be combined recursively.
7248 ;; Top-level named function declarations include both the left-hand (name)
7249 ;; and the right-hand (function value) expressions needed to produce an imenu
7250 ;; entry. The other "right-hand" forms we need to look for are:
7251 ;; - functions declared as props/getters/setters in object literals
7252 ;; - nested named function declarations
7253 ;; The "left-hand" expressions that functions can be assigned to include:
7254 ;; - local/global variables
7255 ;; - nested property-get expressions like a.b.c.d
7256 ;; - element gets like foo[10] or foo['bar'] where the index
7257 ;; expression can be trivially converted to a property name. They
7258 ;; effectively then become property gets.
7259
7260 ;; All the different definition types are canonicalized into the form
7261 ;; foo.bar.baz = position-of-function-keyword
7262
7263 ;; We need to build a trie-like structure for imenu. As an example,
7264 ;; consider the following JavaScript code:
7265
7266 ;; a = function() {...} // function at position 5
7267 ;; b = function() {...} // function at position 25
7268 ;; foo = function() {...} // function at position 100
7269 ;; foo.bar = function() {...} // function at position 200
7270 ;; foo.bar.baz = function() {...} // function at position 300
7271 ;; foo.bar.zab = function() {...} // function at position 400
7272
7273 ;; During parsing we accumulate an entry for each definition in
7274 ;; the variable `js2-imenu-recorder', like so:
7275
7276 ;; '((fn a 5)
7277 ;; (fn b 25)
7278 ;; (fn foo 100)
7279 ;; (fn foo bar 200)
7280 ;; (fn foo bar baz 300)
7281 ;; (fn foo bar zab 400))
7282
7283 ;; Where 'fn' is the respective function node.
7284 ;; After parsing these entries are merged into this alist-trie:
7285
7286 ;; '((a . 1)
7287 ;; (b . 2)
7288 ;; (foo (<definition> . 3)
7289 ;; (bar (<definition> . 6)
7290 ;; (baz . 100)
7291 ;; (zab . 200))))
7292
7293 ;; Note the wacky need for a <definition> name. The token can be anything
7294 ;; that isn't a valid JavaScript identifier, because you might make foo
7295 ;; a function and then start setting properties on it that are also functions.
7296
7297 (defun js2-prop-node-name (node)
7298 "Return the name of a node that may be a property-get/property-name.
7299 If NODE is not a valid name-node, string-node or integral number-node,
7300 returns nil. Otherwise returns the string name/value of the node."
7301 (cond
7302 ((js2-name-node-p node)
7303 (js2-name-node-name node))
7304 ((js2-string-node-p node)
7305 (js2-string-node-value node))
7306 ((and (js2-number-node-p node)
7307 (string-match "^[0-9]+$" (js2-number-node-value node)))
7308 (js2-number-node-value node))
7309 ((eq (js2-node-type node) js2-THIS)
7310 "this")
7311 ((eq (js2-node-type node) js2-SUPER)
7312 "super")))
7313
7314 (defun js2-node-qname-component (node)
7315 "Return the name of this node, if it contributes to a qname.
7316 Returns nil if the node doesn't contribute."
7317 (copy-sequence
7318 (or (js2-prop-node-name node)
7319 (if (and (js2-function-node-p node)
7320 (js2-function-node-name node))
7321 (js2-name-node-name (js2-function-node-name node))))))
7322
7323 (defun js2-record-imenu-entry (fn-node qname pos)
7324 "Add an entry to `js2-imenu-recorder'.
7325 FN-NODE should be the current item's function node.
7326
7327 Associate FN-NODE with its QNAME for later lookup.
7328 This is used in postprocessing the chain list. For each chain, we find
7329 the parent function, look up its qname, then prepend a copy of it to the chain."
7330 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7331 (unless js2-imenu-function-map
7332 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7333 (puthash fn-node qname js2-imenu-function-map))
7334
7335 (defun js2-record-imenu-functions (node &optional var)
7336 "Record function definitions for imenu.
7337 NODE is a function node or an object literal.
7338 VAR, if non-nil, is the expression that NODE is being assigned to.
7339 When passed arguments of wrong type, does nothing."
7340 (when js2-parse-ide-mode
7341 (let ((fun-p (js2-function-node-p node))
7342 qname fname-node)
7343 (cond
7344 ;; non-anonymous function declaration?
7345 ((and fun-p
7346 (not var)
7347 (setq fname-node (js2-function-node-name node)))
7348 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7349 ;; for remaining forms, compute left-side tree branch first
7350 ((and var (setq qname (js2-compute-nested-prop-get var)))
7351 (cond
7352 ;; foo.bar.baz = function
7353 (fun-p
7354 (js2-record-imenu-entry node qname (js2-node-pos node)))
7355 ;; foo.bar.baz = object-literal
7356 ;; look for nested functions: {a: {b: function() {...} }}
7357 ((js2-object-node-p node)
7358 ;; Node position here is still absolute, since the parser
7359 ;; passes the assignment target and value expressions
7360 ;; to us before they are added as children of the assignment node.
7361 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7362
7363 (defun js2-compute-nested-prop-get (node)
7364 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7365 component nodes as a list. Otherwise return nil. Element-gets are treated
7366 as property-gets if the index expression is a string, or a positive integer."
7367 (let (left right head)
7368 (cond
7369 ((or (js2-name-node-p node)
7370 (js2-this-or-super-node-p node))
7371 (list node))
7372 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7373 ((js2-prop-get-node-p node) ; foo.bar
7374 (setq left (js2-prop-get-node-left node)
7375 right (js2-prop-get-node-right node))
7376 (if (setq head (js2-compute-nested-prop-get left))
7377 (nconc head (list right))))
7378 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7379 (setq left (js2-elem-get-node-target node)
7380 right (js2-elem-get-node-element node))
7381 (if (or (js2-string-node-p right) ; ['bar']
7382 (and (js2-number-node-p right) ; [10]
7383 (string-match "^[0-9]+$"
7384 (js2-number-node-value right))))
7385 (if (setq head (js2-compute-nested-prop-get left))
7386 (nconc head (list right))))))))
7387
7388 (defun js2-record-object-literal (node qname pos)
7389 "Recursively process an object literal looking for functions.
7390 NODE is an object literal that is the right-hand child of an assignment
7391 expression. QNAME is a list of nodes representing the assignment target,
7392 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7393 POS is the absolute position of the node.
7394 We do a depth-first traversal of NODE. For any functions we find,
7395 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7396 (let (right)
7397 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7398 (let ((left (js2-infix-node-left e))
7399 ;; Element positions are relative to the parent position.
7400 (pos (+ pos (js2-node-pos e))))
7401 (cond
7402 ;; foo: function() {...}
7403 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7404 (when (js2-prop-node-name left)
7405 ;; As a policy decision, we record the position of the property,
7406 ;; not the position of the `function' keyword, since the property
7407 ;; is effectively the name of the function.
7408 (js2-record-imenu-entry right (append qname (list left)) pos)))
7409 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7410 ((js2-object-node-p right)
7411 (js2-record-object-literal right
7412 (append qname (list (js2-infix-node-left e)))
7413 (+ pos (js2-node-pos right)))))))))
7414
7415 (defun js2-node-top-level-decl-p (node)
7416 "Return t if NODE's name is defined in the top-level scope.
7417 Also returns t if NODE's name is not defined in any scope, since it implies
7418 that it's an external variable, which must also be in the top-level scope."
7419 (let* ((name (js2-prop-node-name node))
7420 (this-scope (js2-node-get-enclosing-scope node))
7421 defining-scope)
7422 (cond
7423 ((js2-this-or-super-node-p node)
7424 nil)
7425 ((null this-scope)
7426 t)
7427 ((setq defining-scope (js2-get-defining-scope this-scope name))
7428 (js2-ast-root-p defining-scope))
7429 (t t))))
7430
7431 (defun js2-wrapper-function-p (node)
7432 "Return t if NODE is a function expression that's immediately invoked.
7433 NODE must be `js2-function-node'."
7434 (let ((parent (js2-node-parent node)))
7435 (or
7436 ;; function(){...}();
7437 (and (js2-call-node-p parent)
7438 (eq node (js2-call-node-target parent)))
7439 (and (js2-paren-node-p parent)
7440 ;; (function(){...})();
7441 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7442 ;; (function(){...}).call(this);
7443 (and (js2-prop-get-node-p parent)
7444 (member (js2-name-node-name (js2-prop-get-node-right parent))
7445 '("call" "apply"))
7446 (js2-call-node-p (js2-node-parent parent))))))))
7447
7448 (defun js2-browse-postprocess-chains ()
7449 "Modify function-declaration name chains after parsing finishes.
7450 Some of the information is only available after the parse tree is complete.
7451 For instance, processing a nested scope requires a parent function node."
7452 (let (result fn parent-qname p elem)
7453 (dolist (entry js2-imenu-recorder)
7454 ;; function node goes first
7455 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7456 ;; Examine head's defining scope:
7457 ;; Pre-processed chain, or top-level/external, keep as-is.
7458 (if (or (stringp head) (js2-node-top-level-decl-p head))
7459 (push chain result)
7460 (when (js2-this-or-super-node-p head)
7461 (setq chain (cdr chain))) ; discard this-node
7462 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7463 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7464 (when (eq parent-qname 'not-found)
7465 ;; anonymous function expressions are not recorded
7466 ;; during the parse, so we need to handle this case here
7467 (setq parent-qname
7468 (if (js2-wrapper-function-p fn)
7469 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7470 (if (js2-ast-root-p grandparent)
7471 nil
7472 (gethash grandparent js2-imenu-function-map 'skip)))
7473 'skip))
7474 (puthash fn parent-qname js2-imenu-function-map))
7475 (if (eq parent-qname 'skip)
7476 ;; We don't show it, let's record that fact.
7477 (remhash current-fn js2-imenu-function-map)
7478 ;; Prepend parent fn qname to this chain.
7479 (let ((qname (append parent-qname chain)))
7480 (puthash current-fn (butlast qname) js2-imenu-function-map)
7481 (push qname result)))))))
7482 ;; Collect chains obtained by third-party code.
7483 (let (js2-imenu-recorder)
7484 (run-hooks 'js2-build-imenu-callbacks)
7485 (dolist (entry js2-imenu-recorder)
7486 (push (cdr entry) result)))
7487 ;; Finally replace each node in each chain with its name.
7488 (dolist (chain result)
7489 (setq p chain)
7490 (while p
7491 (if (js2-node-p (setq elem (car p)))
7492 (setcar p (js2-node-qname-component elem)))
7493 (setq p (cdr p))))
7494 result))
7495
7496 ;; Merge name chains into a trie-like tree structure of nested lists.
7497 ;; To simplify construction of the trie, we first build it out using the rule
7498 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7499 ;; [key, num-or-list]. The second element can be a number; if so, this key
7500 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7501 ;; associated with the key at this level.) Otherwise the second element is
7502 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7503 ;; a simple recursive formulation.
7504 ;;
7505 ;; js2-mode is building the data structure for imenu. The imenu documentation
7506 ;; claims that it's the structure above, but in practice it wants the children
7507 ;; at the same list level as the key for that level, which is how I've drawn
7508 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7509 ;; list wrapper around the children at each level.
7510 ;;
7511 ;; A completed nested imenu-alist entry looks like this:
7512 ;; '(("foo"
7513 ;; ("<definition>" . 7)
7514 ;; ("bar"
7515 ;; ("a" . 40)
7516 ;; ("b" . 60))))
7517 ;;
7518 ;; In particular, the documentation for `imenu--index-alist' says that
7519 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7520 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7521
7522 (defun js2-treeify (lst)
7523 "Convert (a b c d) to (a ((b ((c d)))))."
7524 (if (null (cddr lst)) ; list length <= 2
7525 lst
7526 (list (car lst) (list (js2-treeify (cdr lst))))))
7527
7528 (defun js2-build-alist-trie (chains trie)
7529 "Merge declaration name chains into a trie-like alist structure for imenu.
7530 CHAINS is the qname chain list produced during parsing. TRIE is a
7531 list of elements built up so far."
7532 (let (head tail pos branch kids)
7533 (dolist (chain chains)
7534 (setq head (car chain)
7535 tail (cdr chain)
7536 pos (if (numberp (car tail)) (car tail))
7537 branch (js2-find-if (lambda (n)
7538 (string= (car n) head))
7539 trie)
7540 kids (cl-second branch))
7541 (cond
7542 ;; case 1: this key isn't in the trie yet
7543 ((null branch)
7544 (if trie
7545 (setcdr (last trie) (list (js2-treeify chain)))
7546 (setq trie (list (js2-treeify chain)))))
7547 ;; case 2: key is present with a single number entry: replace w/ list
7548 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7549 ;; ("<definition>" 20)))
7550 ((numberp kids)
7551 (setcar (cdr branch)
7552 (list (list "<definition-1>" kids)
7553 (if pos
7554 (list "<definition-2>" pos)
7555 (js2-treeify tail)))))
7556 ;; case 3: key is there (with kids), and we're a number entry
7557 (pos
7558 (setcdr (last kids)
7559 (list
7560 (list (format "<definition-%d>"
7561 (1+ (cl-loop for kid in kids
7562 count (eq ?< (aref (car kid) 0)))))
7563 pos))))
7564 ;; case 4: key is there with kids, need to merge in our chain
7565 (t
7566 (js2-build-alist-trie (list tail) kids))))
7567 trie))
7568
7569 (defun js2-flatten-trie (trie)
7570 "Convert TRIE to imenu-format.
7571 Recurses through nodes, and for each one whose second element is a list,
7572 appends the list's flattened elements to the current element. Also
7573 changes the tails into conses. For instance, this pre-flattened trie
7574
7575 '(a ((b 20)
7576 (c ((d 30)
7577 (e 40)))))
7578
7579 becomes
7580
7581 '(a (b . 20)
7582 (c (d . 30)
7583 (e . 40)))
7584
7585 Note that the root of the trie has no key, just a list of chains.
7586 This is also true for the value of any key with multiple children,
7587 e.g. key 'c' in the example above."
7588 (cond
7589 ((listp (car trie))
7590 (mapcar #'js2-flatten-trie trie))
7591 (t
7592 (if (numberp (cl-second trie))
7593 (cons (car trie) (cl-second trie))
7594 ;; else pop list and append its kids
7595 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7596
7597 (defun js2-build-imenu-index ()
7598 "Turn `js2-imenu-recorder' into an imenu data structure."
7599 (when (eq js2-imenu-recorder 'empty)
7600 (setq js2-imenu-recorder nil))
7601 (let* ((chains (js2-browse-postprocess-chains))
7602 (result (js2-build-alist-trie chains nil)))
7603 (js2-flatten-trie result)))
7604
7605 (defun js2-test-print-chains (chains)
7606 "Print a list of qname chains.
7607 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7608 i.e. one or more nodes, and an integer position as the list tail."
7609 (mapconcat (lambda (chain)
7610 (concat "("
7611 (mapconcat (lambda (elem)
7612 (if (js2-node-p elem)
7613 (or (js2-node-qname-component elem)
7614 "nil")
7615 (number-to-string elem)))
7616 chain
7617 " ")
7618 ")"))
7619 chains
7620 "\n"))
7621
7622 ;;; Parser
7623
7624 (defconst js2-version "1.8.5"
7625 "Version of JavaScript supported.")
7626
7627 (defun js2-record-face (face &optional token)
7628 "Record a style run of FACE for TOKEN or the current token."
7629 (unless token (setq token (js2-current-token)))
7630 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7631
7632 (defsubst js2-node-end (n)
7633 "Computes the absolute end of node N.
7634 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7635 is only true until the node is added to its parent; i.e., while parsing."
7636 (+ (js2-node-pos n)
7637 (js2-node-len n)))
7638
7639 (defun js2-record-comment (token)
7640 "Record a comment in `js2-scanned-comments'."
7641 (let ((ct (js2-token-comment-type token))
7642 (beg (js2-token-beg token))
7643 (end (js2-token-end token)))
7644 (push (make-js2-comment-node :len (- end beg)
7645 :format ct)
7646 js2-scanned-comments)
7647 (when js2-parse-ide-mode
7648 (js2-record-face (if (eq ct 'jsdoc)
7649 'font-lock-doc-face
7650 'font-lock-comment-face)
7651 token)
7652 (when (memq ct '(html preprocessor))
7653 ;; Tell cc-engine the bounds of the comment.
7654 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7655
7656 (defun js2-peek-token ()
7657 "Return the next token type without consuming it.
7658 If `js2-ti-lookahead' is positive, return the type of next token
7659 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7660 (if (not (zerop js2-ti-lookahead))
7661 (js2-token-type
7662 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7663 (let ((tt (js2-get-token-internal nil)))
7664 (js2-unget-token)
7665 tt)))
7666
7667 (defalias 'js2-next-token 'js2-get-token)
7668
7669 (defun js2-match-token (match &optional dont-unget)
7670 "Get next token and return t if it matches MATCH, a bytecode.
7671 Returns nil and consumes nothing if MATCH is not the next token."
7672 (if (/= (js2-get-token) match)
7673 (ignore (unless dont-unget (js2-unget-token)))
7674 t))
7675
7676 (defun js2-match-contextual-kwd (name)
7677 "Consume and return t if next token is `js2-NAME', and its
7678 string is NAME. Returns nil and keeps current token otherwise."
7679 (if (or (/= (js2-get-token) js2-NAME)
7680 (not (string= (js2-current-token-string) name)))
7681 (progn
7682 (js2-unget-token)
7683 nil)
7684 (js2-record-face 'font-lock-keyword-face)
7685 t))
7686
7687 (defun js2-get-prop-name-token ()
7688 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7689
7690 (defun js2-match-prop-name ()
7691 "Consume token and return t if next token is a valid property name.
7692 If `js2-language-version' is >= 180, a keyword or reserved word
7693 is considered valid name as well."
7694 (if (eq js2-NAME (js2-get-prop-name-token))
7695 t
7696 (js2-unget-token)
7697 nil))
7698
7699 (defun js2-must-match-prop-name (msg-id &optional pos len)
7700 (if (js2-match-prop-name)
7701 t
7702 (js2-report-error msg-id nil pos len)
7703 nil))
7704
7705 (defun js2-peek-token-or-eol ()
7706 "Return js2-EOL if the next token immediately follows a newline.
7707 Else returns the next token. Used in situations where we don't
7708 consider certain token types valid if they are preceded by a newline.
7709 One example is the postfix ++ or -- operator, which has to be on the
7710 same line as its operand."
7711 (let ((tt (js2-get-token))
7712 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7713 (js2-unget-token)
7714 (if follows-eol
7715 js2-EOL
7716 tt)))
7717
7718 (defun js2-must-match (token msg-id &optional pos len)
7719 "Match next token to token code TOKEN, or record a syntax error.
7720 MSG-ID is the error message to report if the match fails.
7721 Returns t on match, nil if no match."
7722 (if (js2-match-token token t)
7723 t
7724 (js2-report-error msg-id nil pos len)
7725 (js2-unget-token)
7726 nil))
7727
7728 (defun js2-must-match-name (msg-id)
7729 (if (js2-match-token js2-NAME t)
7730 t
7731 (if (eq (js2-current-token-type) js2-RESERVED)
7732 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7733 (js2-report-error msg-id)
7734 (js2-unget-token))
7735 nil))
7736
7737 (defsubst js2-inside-function ()
7738 (cl-plusp js2-nesting-of-function))
7739
7740 (defun js2-set-requires-activation ()
7741 (if (js2-function-node-p js2-current-script-or-fn)
7742 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7743
7744 (defun js2-check-activation-name (name _token)
7745 (when (js2-inside-function)
7746 ;; skip language-version 1.2 check from Rhino
7747 (if (or (string= "arguments" name)
7748 (and js2-compiler-activation-names ; only used in codegen
7749 (gethash name js2-compiler-activation-names)))
7750 (js2-set-requires-activation))))
7751
7752 (defun js2-set-is-generator ()
7753 (let ((fn-node js2-current-script-or-fn))
7754 (when (and (js2-function-node-p fn-node)
7755 (not (js2-function-node-generator-type fn-node)))
7756 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7757
7758 (defun js2-must-have-xml ()
7759 (unless js2-compiler-xml-available
7760 (js2-report-error "msg.XML.not.available")))
7761
7762 (defun js2-push-scope (scope)
7763 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7764 (cl-assert (js2-scope-p scope))
7765 (cl-assert (null (js2-scope-parent-scope scope)))
7766 (cl-assert (not (eq js2-current-scope scope)))
7767 (setf (js2-scope-parent-scope scope) js2-current-scope
7768 js2-current-scope scope))
7769
7770 (defsubst js2-pop-scope ()
7771 (setq js2-current-scope
7772 (js2-scope-parent-scope js2-current-scope)))
7773
7774 (defun js2-enter-loop (loop-node)
7775 (push loop-node js2-loop-set)
7776 (push loop-node js2-loop-and-switch-set)
7777 (js2-push-scope loop-node)
7778 ;; Tell the current labeled statement (if any) its statement,
7779 ;; and set the jump target of the first label to the loop.
7780 ;; These are used in `js2-parse-continue' to verify that the
7781 ;; continue target is an actual labeled loop. (And for codegen.)
7782 (when js2-labeled-stmt
7783 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7784 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7785 js2-labeled-stmt))) loop-node)))
7786
7787 (defun js2-exit-loop ()
7788 (pop js2-loop-set)
7789 (pop js2-loop-and-switch-set)
7790 (js2-pop-scope))
7791
7792 (defsubst js2-enter-switch (switch-node)
7793 (push switch-node js2-loop-and-switch-set))
7794
7795 (defsubst js2-exit-switch ()
7796 (pop js2-loop-and-switch-set))
7797
7798 (defsubst js2-get-directive (node)
7799 "Return NODE's value if it is a directive, nil otherwise.
7800
7801 A directive is an otherwise-meaningless expression statement
7802 consisting of a string literal, such as \"use strict\"."
7803 (and (js2-expr-stmt-node-p node)
7804 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7805 (js2-string-node-value node)))
7806
7807 (defun js2-parse (&optional buf cb)
7808 "Tell the js2 parser to parse a region of JavaScript.
7809
7810 BUF is a buffer or buffer name containing the code to parse.
7811 Call `narrow-to-region' first to parse only part of the buffer.
7812
7813 The returned AST root node is given some additional properties:
7814 `node-count' - total number of nodes in the AST
7815 `buffer' - BUF. The buffer it refers to may change or be killed,
7816 so the value is not necessarily reliable.
7817
7818 An optional callback CB can be specified to report parsing
7819 progress. If `(functionp CB)' returns t, it will be called with
7820 the current line number once before parsing begins, then again
7821 each time the lexer reaches a new line number.
7822
7823 CB can also be a list of the form `(symbol cb ...)' to specify
7824 multiple callbacks with different criteria. Each symbol is a
7825 criterion keyword, and the following element is the callback to
7826 call
7827
7828 :line - called whenever the line number changes
7829 :token - called for each new token consumed
7830
7831 The list of criteria could be extended to include entering or
7832 leaving a statement, an expression, or a function definition."
7833 (if (and cb (not (functionp cb)))
7834 (error "criteria callbacks not yet implemented"))
7835 (let ((inhibit-point-motion-hooks t)
7836 (js2-compiler-xml-available (>= js2-language-version 160))
7837 ;; This is a recursive-descent parser, so give it a big stack.
7838 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7839 (max-specpdl-size (max max-specpdl-size 3000))
7840 (case-fold-search nil)
7841 ast)
7842 (with-current-buffer (or buf (current-buffer))
7843 (setq js2-scanned-comments nil
7844 js2-parsed-errors nil
7845 js2-parsed-warnings nil
7846 js2-imenu-recorder nil
7847 js2-imenu-function-map nil
7848 js2-label-set nil)
7849 (js2-init-scanner)
7850 (setq ast (js2-do-parse))
7851 (unless js2-ts-hit-eof
7852 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7853 (setf (js2-ast-root-errors ast) js2-parsed-errors
7854 (js2-ast-root-warnings ast) js2-parsed-warnings)
7855 ;; if we didn't find any declarations, put a dummy in this list so we
7856 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7857 (unless js2-imenu-recorder
7858 (setq js2-imenu-recorder 'empty))
7859 (run-hooks 'js2-parse-finished-hook)
7860 ast)))
7861
7862 ;; Corresponds to Rhino's Parser.parse() method.
7863 (defun js2-do-parse ()
7864 "Parse current buffer starting from current point.
7865 Scanner should be initialized."
7866 (let ((pos js2-ts-cursor)
7867 (end js2-ts-cursor) ; in case file is empty
7868 root n tt
7869 (in-directive-prologue t)
7870 (js2-in-use-strict-directive js2-in-use-strict-directive)
7871 directive)
7872 ;; initialize buffer-local parsing vars
7873 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7874 js2-current-script-or-fn root
7875 js2-current-scope root
7876 js2-nesting-of-function 0
7877 js2-labeled-stmt nil
7878 js2-recorded-identifiers nil ; for js2-highlight
7879 js2-in-use-strict-directive nil)
7880 (while (/= (setq tt (js2-get-token)) js2-EOF)
7881 (if (= tt js2-FUNCTION)
7882 (progn
7883 (setq n (if js2-called-by-compile-function
7884 (js2-parse-function-expr)
7885 (js2-parse-function-stmt))))
7886 ;; not a function - parse a statement
7887 (js2-unget-token)
7888 (setq n (js2-parse-statement))
7889 (when in-directive-prologue
7890 (setq directive (js2-get-directive n))
7891 (cond
7892 ((null directive)
7893 (setq in-directive-prologue nil))
7894 ((string= directive "use strict")
7895 (setq js2-in-use-strict-directive t)))))
7896 ;; add function or statement to script
7897 (setq end (js2-node-end n))
7898 (js2-block-node-push root n))
7899 ;; add comments to root in lexical order
7900 (when js2-scanned-comments
7901 ;; if we find a comment beyond end of normal kids, use its end
7902 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7903 (dolist (comment js2-scanned-comments)
7904 (push comment (js2-ast-root-comments root))
7905 (js2-node-add-children root comment)))
7906 (setf (js2-node-len root) (- end pos))
7907 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7908 ;; Give extensions a chance to muck with things before highlighting starts.
7909 (let ((js2-additional-externs js2-additional-externs))
7910 (save-excursion
7911 (run-hooks 'js2-post-parse-callbacks))
7912 (js2-highlight-undeclared-vars))
7913 root))
7914
7915 (defun js2-parse-function-closure-body (fn-node)
7916 "Parse a JavaScript 1.8 function closure body."
7917 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7918 (if js2-ts-hit-eof
7919 (js2-report-error "msg.no.brace.body" nil
7920 (js2-node-pos fn-node)
7921 (- js2-ts-cursor (js2-node-pos fn-node)))
7922 (js2-node-add-children fn-node
7923 (setf (js2-function-node-body fn-node)
7924 (js2-parse-expr t))))))
7925
7926 (defun js2-parse-function-body (fn-node)
7927 (js2-must-match js2-LC "msg.no.brace.body"
7928 (js2-node-pos fn-node)
7929 (- js2-ts-cursor (js2-node-pos fn-node)))
7930 (let ((pos (js2-current-token-beg)) ; LC position
7931 (pn (make-js2-block-node)) ; starts at LC position
7932 tt
7933 end
7934 not-in-directive-prologue
7935 node
7936 directive)
7937 (cl-incf js2-nesting-of-function)
7938 (unwind-protect
7939 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7940 (= tt js2-EOF)
7941 (= tt js2-RC)))
7942 (js2-block-node-push
7943 pn
7944 (if (/= tt js2-FUNCTION)
7945 (if not-in-directive-prologue
7946 (js2-parse-statement)
7947 (setq node (js2-parse-statement)
7948 directive (js2-get-directive node))
7949 (cond
7950 ((null directive)
7951 (setq not-in-directive-prologue t))
7952 ((string= directive "use strict")
7953 ;; Back up and reparse the function, because new rules apply
7954 ;; to the function name and parameters.
7955 (when (not js2-in-use-strict-directive)
7956 (setq js2-in-use-strict-directive t)
7957 (throw 'reparse t))))
7958 node)
7959 (js2-get-token)
7960 (js2-parse-function-stmt))))
7961 (cl-decf js2-nesting-of-function))
7962 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7963 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7964 (setq end (js2-current-token-end)))
7965 (setf (js2-node-pos pn) pos
7966 (js2-node-len pn) (- end pos))
7967 (setf (js2-function-node-body fn-node) pn)
7968 (js2-node-add-children fn-node pn)
7969 pn))
7970
7971 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7972 "Declare and fontify destructuring parameters inside NODE.
7973 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
7974
7975 Return a list of `js2-name-node' nodes representing the symbols
7976 declared; probably to check them for errors."
7977 (let (name-nodes)
7978 (cond
7979 ((js2-name-node-p node)
7980 (let (leftpos)
7981 (js2-define-symbol decl-type (js2-name-node-name node)
7982 node ignore-not-in-block)
7983 (when face
7984 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7985 (+ leftpos (js2-node-len node))
7986 face 'record))
7987 (list node)))
7988 ((js2-object-node-p node)
7989 (dolist (elem (js2-object-node-elems node))
7990 (when (js2-object-prop-node-p elem)
7991 (push (js2-define-destruct-symbols
7992 ;; In abbreviated destructuring {a, b}, right == left.
7993 (js2-object-prop-node-right elem)
7994 decl-type face ignore-not-in-block)
7995 name-nodes)))
7996 (apply #'append (nreverse name-nodes)))
7997 ((js2-array-node-p node)
7998 (dolist (elem (js2-array-node-elems node))
7999 (when elem
8000 (push (js2-define-destruct-symbols
8001 elem decl-type face ignore-not-in-block)
8002 name-nodes)))
8003 (apply #'append (nreverse name-nodes)))
8004 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8005 (js2-node-len node))
8006 nil))))
8007
8008 (defvar js2-illegal-strict-identifiers
8009 '("eval" "arguments")
8010 "Identifiers not allowed as variables in strict mode.")
8011
8012 (defun js2-check-strict-identifier (name-node)
8013 "Check that NAME-NODE makes a legal strict mode identifier."
8014 (when js2-in-use-strict-directive
8015 (let ((param-name (js2-name-node-name name-node)))
8016 (when (member param-name js2-illegal-strict-identifiers)
8017 (js2-report-error "msg.bad.id.strict" param-name
8018 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8019
8020 (defun js2-check-strict-function-params (preceding-params params)
8021 "Given PRECEDING-PARAMS in a function's parameter list, check
8022 for strict mode errors caused by PARAMS."
8023 (when js2-in-use-strict-directive
8024 (dolist (param params)
8025 (let ((param-name (js2-name-node-name param)))
8026 (js2-check-strict-identifier param)
8027 (when (cl-some (lambda (param)
8028 (string= (js2-name-node-name param) param-name))
8029 preceding-params)
8030 (js2-report-error "msg.dup.param.strict" param-name
8031 (js2-node-abs-pos param) (js2-node-len param)))))))
8032
8033 (defun js2-parse-function-params (function-type fn-node pos)
8034 "Parse the parameters of a function of FUNCTION-TYPE
8035 represented by FN-NODE at POS."
8036 (if (js2-match-token js2-RP)
8037 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8038 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8039 (eq (js2-current-token-type) js2-NAME)))
8040 params param
8041 param-name-nodes new-param-name-nodes
8042 rest-param-at)
8043 (when paren-free-arrow
8044 (js2-unget-token))
8045 (cl-loop for tt = (js2-peek-token)
8046 do
8047 (cond
8048 ;; destructuring param
8049 ((and (not paren-free-arrow)
8050 (or (= tt js2-LB) (= tt js2-LC)))
8051 (js2-get-token)
8052 (setq param (js2-parse-destruct-primary-expr)
8053 new-param-name-nodes (js2-define-destruct-symbols
8054 param js2-LP 'js2-function-param))
8055 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8056 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8057 (push param params))
8058 ;; variable name
8059 (t
8060 (when (and (>= js2-language-version 200)
8061 (not paren-free-arrow)
8062 (js2-match-token js2-TRIPLEDOT)
8063 (not rest-param-at))
8064 ;; to report errors if there are more parameters
8065 (setq rest-param-at (length params)))
8066 (js2-must-match-name "msg.no.parm")
8067 (js2-record-face 'js2-function-param)
8068 (setq param (js2-create-name-node))
8069 (js2-define-symbol js2-LP (js2-current-token-string) param)
8070 (js2-check-strict-function-params param-name-nodes (list param))
8071 (setq param-name-nodes (append param-name-nodes (list param)))
8072 ;; default parameter value
8073 (when (and (>= js2-language-version 200)
8074 (js2-match-token js2-ASSIGN))
8075 (cl-assert (not paren-free-arrow))
8076 (let* ((pos (js2-node-pos param))
8077 (tt (js2-current-token-type))
8078 (op-pos (- (js2-current-token-beg) pos))
8079 (left param)
8080 (right (js2-parse-assign-expr))
8081 (len (- (js2-node-end right) pos)))
8082 (setq param (make-js2-assign-node
8083 :type tt :pos pos :len len :op-pos op-pos
8084 :left left :right right))
8085 (js2-node-add-children param left right)))
8086 (push param params)))
8087 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8088 (js2-report-error "msg.param.after.rest" nil
8089 (js2-node-pos param) (js2-node-len param)))
8090 while
8091 (js2-match-token js2-COMMA))
8092 (when (and (not paren-free-arrow)
8093 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8094 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8095 (when rest-param-at
8096 (setf (js2-function-node-rest-p fn-node) t))
8097 (dolist (p params)
8098 (js2-node-add-children fn-node p)
8099 (push p (js2-function-node-params fn-node))))))
8100
8101 (defun js2-check-inconsistent-return-warning (fn-node name)
8102 "Possibly show inconsistent-return warning.
8103 Last token scanned is the close-curly for the function body."
8104 (when (and js2-mode-show-strict-warnings
8105 js2-strict-inconsistent-return-warning
8106 (not (js2-has-consistent-return-usage
8107 (js2-function-node-body fn-node))))
8108 ;; Have it extend from close-curly to bol or beginning of block.
8109 (let ((pos (save-excursion
8110 (goto-char (js2-current-token-end))
8111 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8112 (point-at-bol))))
8113 (end (js2-current-token-end)))
8114 (if (cl-plusp (js2-name-node-length name))
8115 (js2-add-strict-warning "msg.no.return.value"
8116 (js2-name-node-name name) pos end)
8117 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8118
8119 (defun js2-parse-function-stmt ()
8120 (let ((pos (js2-current-token-beg))
8121 (star-p (js2-match-token js2-MUL)))
8122 (js2-must-match-name "msg.unnamed.function.stmt")
8123 (let ((name (js2-create-name-node t))
8124 pn member-expr)
8125 (cond
8126 ((js2-match-token js2-LP)
8127 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8128 (js2-allow-member-expr-as-function-name
8129 (setq member-expr (js2-parse-member-expr-tail nil name))
8130 (js2-parse-highlight-member-expr-fn-name member-expr)
8131 (js2-must-match js2-LP "msg.no.paren.parms")
8132 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8133 (js2-function-node-member-expr pn) member-expr)
8134 pn)
8135 (t
8136 (js2-report-error "msg.no.paren.parms")
8137 (make-js2-error-node))))))
8138
8139 (defun js2-parse-function-expr ()
8140 (let ((pos (js2-current-token-beg))
8141 (star-p (js2-match-token js2-MUL))
8142 name)
8143 (when (js2-match-token js2-NAME)
8144 (setq name (js2-create-name-node t)))
8145 (js2-must-match js2-LP "msg.no.paren.parms")
8146 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8147
8148 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8149 (let (fn-node lp)
8150 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8151 (setq lp (js2-current-token-beg)))
8152 (setf fn-node (make-js2-function-node :pos pos
8153 :name name
8154 :form function-type
8155 :lp (if lp (- lp pos))
8156 :generator-type (and star-p 'STAR)))
8157 (when name
8158 (js2-set-face (js2-node-pos name) (js2-node-end name)
8159 'font-lock-function-name-face 'record)
8160 (when (and (eq function-type 'FUNCTION_STATEMENT)
8161 (cl-plusp (js2-name-node-length name)))
8162 ;; Function statements define a symbol in the enclosing scope
8163 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8164 (when js2-in-use-strict-directive
8165 (js2-check-strict-identifier name)))
8166 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8167 ;; 1. Nested functions are not affected by the dynamic scope flag
8168 ;; as dynamic scope is already a parent of their scope.
8169 ;; 2. Functions defined under the with statement also immune to
8170 ;; this setup, in which case dynamic scope is ignored in favor
8171 ;; of the with object.
8172 (setf (js2-function-node-ignore-dynamic fn-node) t))
8173 ;; dynamically bind all the per-function variables
8174 (let ((js2-current-script-or-fn fn-node)
8175 (js2-current-scope fn-node)
8176 (js2-nesting-of-with 0)
8177 (js2-end-flags 0)
8178 js2-label-set
8179 js2-loop-set
8180 js2-loop-and-switch-set)
8181 (js2-parse-function-params function-type fn-node pos)
8182 (when (eq function-type 'FUNCTION_ARROW)
8183 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8184 (if (and (>= js2-language-version 180)
8185 (/= (js2-peek-token) js2-LC))
8186 (js2-parse-function-closure-body fn-node)
8187 (js2-parse-function-body fn-node))
8188 (js2-check-inconsistent-return-warning fn-node name)
8189
8190 (when name
8191 (js2-node-add-children fn-node name)
8192 ;; Function expressions define a name only in the body of the
8193 ;; function, and only if not hidden by a parameter name
8194 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8195 (null (js2-scope-get-symbol js2-current-scope
8196 (js2-name-node-name name))))
8197 (js2-define-symbol js2-FUNCTION
8198 (js2-name-node-name name)
8199 fn-node))
8200 (when (eq function-type 'FUNCTION_STATEMENT)
8201 (js2-record-imenu-functions fn-node))))
8202
8203 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8204 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8205 ;; We wait until after parsing the function to set its parent scope,
8206 ;; since `js2-define-symbol' needs the defining-scope check to stop
8207 ;; at the function boundary when checking for redeclarations.
8208 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8209 fn-node))
8210
8211 (defun js2-parse-function (function-type pos star-p &optional name)
8212 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8213 beginning of the first token (function keyword, unless it's an
8214 arrow function), NAME is js2-name-node."
8215 (let ((continue t)
8216 ts-state
8217 fn-node
8218 ;; Preserve strict state outside this function.
8219 (js2-in-use-strict-directive js2-in-use-strict-directive))
8220 ;; Parse multiple times if a new strict mode directive is discovered in the
8221 ;; function body, as new rules will be retroactively applied to the legality
8222 ;; of function names and parameters.
8223 (while continue
8224 (setq ts-state (make-js2-ts-state))
8225 (setq continue (catch 'reparse
8226 (setq fn-node (js2-parse-function-internal
8227 function-type pos star-p name))
8228 ;; Don't continue.
8229 nil))
8230 (when continue
8231 (js2-ts-seek ts-state)))
8232 fn-node))
8233
8234 (defun js2-parse-statements (&optional parent)
8235 "Parse a statement list. Last token consumed must be js2-LC.
8236
8237 PARENT can be a `js2-block-node', in which case the statements are
8238 appended to PARENT. Otherwise a new `js2-block-node' is created
8239 and returned.
8240
8241 This function does not match the closing js2-RC: the caller
8242 matches the RC so it can provide a suitable error message if not
8243 matched. This means it's up to the caller to set the length of
8244 the node to include the closing RC. The node start pos is set to
8245 the absolute buffer start position, and the caller should fix it
8246 up to be relative to the parent node. All children of this block
8247 node are given relative start positions and correct lengths."
8248 (let ((pn (or parent (make-js2-block-node)))
8249 tt)
8250 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8251 (/= tt js2-RC))
8252 (js2-block-node-push pn (js2-parse-statement)))
8253 pn))
8254
8255 (defun js2-parse-statement ()
8256 (let (pn beg end)
8257 ;; coarse-grained user-interrupt check - needs work
8258 (and js2-parse-interruptable-p
8259 (zerop (% (cl-incf js2-parse-stmt-count)
8260 js2-statements-per-pause))
8261 (input-pending-p)
8262 (throw 'interrupted t))
8263 (setq pn (js2-statement-helper))
8264 ;; no-side-effects warning check
8265 (unless (js2-node-has-side-effects pn)
8266 (setq end (js2-node-end pn))
8267 (save-excursion
8268 (goto-char end)
8269 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8270 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8271 pn))
8272
8273 ;; These correspond to the switch cases in Parser.statementHelper
8274 (defconst js2-parsers
8275 (let ((parsers (make-vector js2-num-tokens
8276 #'js2-parse-expr-stmt)))
8277 (aset parsers js2-BREAK #'js2-parse-break)
8278 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8279 (aset parsers js2-CONST #'js2-parse-const-var)
8280 (aset parsers js2-CONTINUE #'js2-parse-continue)
8281 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8282 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8283 (aset parsers js2-DO #'js2-parse-do)
8284 (aset parsers js2-EXPORT #'js2-parse-export)
8285 (aset parsers js2-FOR #'js2-parse-for)
8286 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8287 (aset parsers js2-IF #'js2-parse-if)
8288 (aset parsers js2-IMPORT #'js2-parse-import)
8289 (aset parsers js2-LC #'js2-parse-block)
8290 (aset parsers js2-LET #'js2-parse-let-stmt)
8291 (aset parsers js2-NAME #'js2-parse-name-or-label)
8292 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8293 (aset parsers js2-SEMI #'js2-parse-semi)
8294 (aset parsers js2-SWITCH #'js2-parse-switch)
8295 (aset parsers js2-THROW #'js2-parse-throw)
8296 (aset parsers js2-TRY #'js2-parse-try)
8297 (aset parsers js2-VAR #'js2-parse-const-var)
8298 (aset parsers js2-WHILE #'js2-parse-while)
8299 (aset parsers js2-WITH #'js2-parse-with)
8300 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8301 parsers)
8302 "A vector mapping token types to parser functions.")
8303
8304 (defun js2-parse-warn-missing-semi (beg end)
8305 (and js2-mode-show-strict-warnings
8306 js2-strict-missing-semi-warning
8307 (js2-add-strict-warning
8308 "msg.missing.semi" nil
8309 ;; back up to beginning of statement or line
8310 (max beg (save-excursion
8311 (goto-char end)
8312 (point-at-bol)))
8313 end)))
8314
8315 (defconst js2-no-semi-insertion
8316 (list js2-IF
8317 js2-SWITCH
8318 js2-WHILE
8319 js2-DO
8320 js2-FOR
8321 js2-TRY
8322 js2-WITH
8323 js2-LC
8324 js2-ERROR
8325 js2-SEMI
8326 js2-CLASS
8327 js2-FUNCTION
8328 js2-EXPORT)
8329 "List of tokens that don't do automatic semicolon insertion.")
8330
8331 (defconst js2-autoinsert-semi-and-warn
8332 (list js2-ERROR js2-EOF js2-RC))
8333
8334 (defun js2-statement-helper ()
8335 (let* ((tt (js2-get-token))
8336 (first-tt tt)
8337 (parser (if (= tt js2-ERROR)
8338 #'js2-parse-semi
8339 (aref js2-parsers tt)))
8340 pn)
8341 ;; If the statement is set, then it's been told its label by now.
8342 (and js2-labeled-stmt
8343 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8344 (setq js2-labeled-stmt nil))
8345 (setq pn (funcall parser))
8346 ;; Don't do auto semi insertion for certain statement types.
8347 (unless (or (memq first-tt js2-no-semi-insertion)
8348 (js2-labeled-stmt-node-p pn))
8349 (js2-auto-insert-semicolon pn))
8350 pn))
8351
8352 (defun js2-auto-insert-semicolon (pn)
8353 (let* ((tt (js2-get-token))
8354 (pos (js2-node-pos pn)))
8355 (cond
8356 ((= tt js2-SEMI)
8357 ;; extend the node bounds to include the semicolon.
8358 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8359 ((memq tt js2-autoinsert-semi-and-warn)
8360 (js2-unget-token) ; Not ';', do not consume.
8361 ;; Autoinsert ;
8362 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8363 (t
8364 (if (not (js2-token-follows-eol-p (js2-current-token)))
8365 ;; Report error if no EOL or autoinsert ';' otherwise
8366 (js2-report-error "msg.no.semi.stmt")
8367 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8368 (js2-unget-token) ; Not ';', do not consume.
8369 ))))
8370
8371 (defun js2-parse-condition ()
8372 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8373 The parens are discarded and the expression node is returned.
8374 The `pos' field of the return value is set to an absolute position
8375 that must be fixed up by the caller.
8376 Return value is a list (EXPR LP RP), with absolute paren positions."
8377 (let (pn lp rp)
8378 (if (js2-must-match js2-LP "msg.no.paren.cond")
8379 (setq lp (js2-current-token-beg)))
8380 (setq pn (js2-parse-expr))
8381 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8382 (setq rp (js2-current-token-beg)))
8383 ;; Report strict warning on code like "if (a = 7) ..."
8384 (if (and js2-strict-cond-assign-warning
8385 (js2-assign-node-p pn))
8386 (js2-add-strict-warning "msg.equal.as.assign" nil
8387 (js2-node-pos pn)
8388 (+ (js2-node-pos pn)
8389 (js2-node-len pn))))
8390 (list pn lp rp)))
8391
8392 (defun js2-parse-if ()
8393 "Parser for if-statement. Last matched token must be js2-IF."
8394 (let ((pos (js2-current-token-beg))
8395 cond if-true if-false else-pos end pn)
8396 (setq cond (js2-parse-condition)
8397 if-true (js2-parse-statement)
8398 if-false (if (js2-match-token js2-ELSE)
8399 (progn
8400 (setq else-pos (- (js2-current-token-beg) pos))
8401 (js2-parse-statement)))
8402 end (js2-node-end (or if-false if-true))
8403 pn (make-js2-if-node :pos pos
8404 :len (- end pos)
8405 :condition (car cond)
8406 :then-part if-true
8407 :else-part if-false
8408 :else-pos else-pos
8409 :lp (js2-relpos (cl-second cond) pos)
8410 :rp (js2-relpos (cl-third cond) pos)))
8411 (js2-node-add-children pn (car cond) if-true if-false)
8412 pn))
8413
8414 (defun js2-parse-import ()
8415 "Parse import statement. The current token must be js2-IMPORT."
8416 (unless (js2-ast-root-p js2-current-scope)
8417 (js2-report-error "msg.mod.import.decl.at.top.level"))
8418 (let ((beg (js2-current-token-beg)))
8419 (cond ((js2-match-token js2-STRING)
8420 (make-js2-import-node
8421 :pos beg
8422 :len (- (js2-current-token-end) beg)
8423 :module-id (js2-current-token-string)))
8424 (t
8425 (let* ((import-clause (js2-parse-import-clause))
8426 (from-clause (and import-clause (js2-parse-from-clause)))
8427 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8428 (node (make-js2-import-node
8429 :pos beg
8430 :len (- (js2-current-token-end) beg)
8431 :import import-clause
8432 :from from-clause
8433 :module-id module-id)))
8434 (when import-clause
8435 (js2-node-add-children node import-clause))
8436 (when from-clause
8437 (js2-node-add-children node from-clause))
8438 node)))))
8439
8440 (defun js2-parse-import-clause ()
8441 "Parse the bindings in an import statement.
8442 This can take many forms:
8443
8444 ImportedDefaultBinding -> 'foo'
8445 NameSpaceImport -> '* as lib'
8446 NamedImports -> '{foo as bar, bang}'
8447 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8448 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8449
8450 Try to match namespace imports and named imports first because nothing can
8451 come after them. If it is an imported default binding, then it could have named
8452 imports or a namespace import that follows it.
8453 "
8454 (let* ((beg (js2-current-token-beg))
8455 (clause (make-js2-import-clause-node
8456 :pos beg))
8457 (children (list)))
8458 (cond
8459 ((js2-match-token js2-MUL)
8460 (let ((ns-import (js2-parse-namespace-import)))
8461 (when ns-import
8462 (let ((name-node (js2-namespace-import-node-name ns-import)))
8463 (js2-define-symbol
8464 js2-LET (js2-name-node-name name-node) name-node t)))
8465 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8466 (push ns-import children)))
8467 ((js2-match-token js2-LC)
8468 (let ((imports (js2-parse-export-bindings t)))
8469 (setf (js2-import-clause-node-named-imports clause) imports)
8470 (dolist (import imports)
8471 (push import children)
8472 (let ((name-node (js2-export-binding-node-local-name import)))
8473 (when name-node
8474 (js2-define-symbol
8475 js2-LET (js2-name-node-name name-node) name-node t))))))
8476 ((= (js2-peek-token) js2-NAME)
8477 (let ((binding (js2-maybe-parse-export-binding)))
8478 (let ((node-name (js2-export-binding-node-local-name binding)))
8479 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8480 (setf (js2-import-clause-node-default-binding clause) binding)
8481 (push binding children))
8482 (when (js2-match-token js2-COMMA)
8483 (cond
8484 ((js2-match-token js2-MUL)
8485 (let ((ns-import (js2-parse-namespace-import)))
8486 (let ((name-node (js2-namespace-import-node-name ns-import)))
8487 (js2-define-symbol
8488 js2-LET (js2-name-node-name name-node) name-node t))
8489 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8490 (push ns-import children)))
8491 ((js2-match-token js2-LC)
8492 (let ((imports (js2-parse-export-bindings t)))
8493 (setf (js2-import-clause-node-named-imports clause) imports)
8494 (dolist (import imports)
8495 (push import children)
8496 (let ((name-node (js2-export-binding-node-local-name import)))
8497 (when name-node
8498 (js2-define-symbol
8499 js2-LET (js2-name-node-name name-node) name-node t))))))
8500 (t (js2-report-error "msg.syntax")))))
8501 (t (js2-report-error "msg.mod.declaration.after.import")))
8502 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8503 (apply #'js2-node-add-children clause children)
8504 clause))
8505
8506 (defun js2-parse-namespace-import ()
8507 "Parse a namespace import expression such as '* as bar'.
8508 The current token must be js2-MUL."
8509 (let ((beg (js2-current-token-beg)))
8510 (when (js2-must-match js2-NAME "msg.syntax")
8511 (if (equal "as" (js2-current-token-string))
8512 (when (js2-must-match-prop-name "msg.syntax")
8513 (let ((node (make-js2-namespace-import-node
8514 :pos beg
8515 :len (- (js2-current-token-end) beg)
8516 :name (make-js2-name-node
8517 :pos (js2-current-token-beg)
8518 :len (js2-current-token-end)
8519 :name (js2-current-token-string)))))
8520 (js2-node-add-children node (js2-namespace-import-node-name node))
8521 node))
8522 (js2-unget-token)
8523 (js2-report-error "msg.syntax")))))
8524
8525
8526 (defun js2-parse-from-clause ()
8527 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8528 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8529 (let ((beg (js2-current-token-beg)))
8530 (if (equal "from" (js2-current-token-string))
8531 (cond
8532 ((js2-match-token js2-STRING)
8533 (make-js2-from-clause-node
8534 :pos beg
8535 :len (- (js2-current-token-end) beg)
8536 :module-id (js2-current-token-string)
8537 :metadata-p nil))
8538 ((js2-match-token js2-THIS)
8539 (when (js2-must-match-name "msg.mod.spec.after.from")
8540 (if (equal "module" (js2-current-token-string))
8541 (make-js2-from-clause-node
8542 :pos beg
8543 :len (- (js2-current-token-end) beg)
8544 :module-id "this"
8545 :metadata-p t)
8546 (js2-unget-token)
8547 (js2-unget-token)
8548 (js2-report-error "msg.mod.spec.after.from")
8549 nil)))
8550 (t (js2-report-error "msg.mod.spec.after.from") nil))
8551 (js2-unget-token)
8552 (js2-report-error "msg.mod.from.after.import.spec.set")
8553 nil))))
8554
8555 (defun js2-parse-export-bindings (&optional import-p)
8556 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8557 {foo as bar, baz as bang}. The current token must be
8558 js2-LC. Return a lisp list of js2-export-binding-node"
8559 (let ((bindings (list)))
8560 (while
8561 (let ((binding (js2-maybe-parse-export-binding)))
8562 (when binding
8563 (push binding bindings))
8564 (js2-match-token js2-COMMA)))
8565 (when (js2-must-match js2-RC (if import-p
8566 "msg.mod.rc.after.import.spec.list"
8567 "msg.mod.rc.after.export.spec.list"))
8568 (reverse bindings))))
8569
8570 (defun js2-maybe-parse-export-binding ()
8571 "Attempt to parse a binding expression found inside an import/export statement.
8572 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8573 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8574 js2-export-binding-node and consume all the tokens. If it does not match, it
8575 consumes no tokens."
8576 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8577 (beg (js2-current-token-beg))
8578 (extern-name-len (js2-current-token-len))
8579 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8580 (aref js2-kwd-tokens (js2-current-token-type)))))
8581 (if extern-name
8582 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8583 (if (and as (equal "as" (js2-current-token-string)))
8584 (let ((name
8585 (or
8586 (and (js2-match-token js2-DEFAULT) "default")
8587 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8588 (if name
8589 (let ((node (make-js2-export-binding-node
8590 :pos beg
8591 :len (- (js2-current-token-end) beg)
8592 :local-name (make-js2-name-node
8593 :name name
8594 :pos (js2-current-token-beg)
8595 :len (js2-current-token-len))
8596 :extern-name (make-js2-name-node
8597 :name extern-name
8598 :pos beg
8599 :len extern-name-len))))
8600 (js2-node-add-children
8601 node
8602 (js2-export-binding-node-local-name node)
8603 (js2-export-binding-node-extern-name node))
8604 node)
8605 (js2-unget-token)
8606 nil))
8607 (when as (js2-unget-token))
8608 (let* ((name-node (make-js2-name-node
8609 :name (js2-current-token-string)
8610 :pos (js2-current-token-beg)
8611 :len (js2-current-token-len)))
8612 (node (make-js2-export-binding-node
8613 :pos (js2-current-token-beg)
8614 :len (js2-current-token-len)
8615 :local-name name-node
8616 :extern-name name-node)))
8617 (when is-reserved-name
8618 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8619 (js2-node-add-children node name-node)
8620 node)))
8621 nil)))
8622
8623 (defun js2-parse-switch ()
8624 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8625 (let ((pos (js2-current-token-beg))
8626 tt pn discriminant has-default case-expr case-node
8627 case-pos cases stmt lp)
8628 (if (js2-must-match js2-LP "msg.no.paren.switch")
8629 (setq lp (js2-current-token-beg)))
8630 (setq discriminant (js2-parse-expr)
8631 pn (make-js2-switch-node :discriminant discriminant
8632 :pos pos
8633 :lp (js2-relpos lp pos)))
8634 (js2-node-add-children pn discriminant)
8635 (js2-enter-switch pn)
8636 (unwind-protect
8637 (progn
8638 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8639 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8640 (js2-must-match js2-LC "msg.no.brace.switch")
8641 (catch 'break
8642 (while t
8643 (setq tt (js2-next-token)
8644 case-pos (js2-current-token-beg))
8645 (cond
8646 ((= tt js2-RC)
8647 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8648 (throw 'break nil)) ; done
8649 ((= tt js2-CASE)
8650 (setq case-expr (js2-parse-expr))
8651 (js2-must-match js2-COLON "msg.no.colon.case"))
8652 ((= tt js2-DEFAULT)
8653 (if has-default
8654 (js2-report-error "msg.double.switch.default"))
8655 (setq has-default t
8656 case-expr nil)
8657 (js2-must-match js2-COLON "msg.no.colon.case"))
8658 (t
8659 (js2-report-error "msg.bad.switch")
8660 (throw 'break nil)))
8661 (setq case-node (make-js2-case-node :pos case-pos
8662 :len (- (js2-current-token-end) case-pos)
8663 :expr case-expr))
8664 (js2-node-add-children case-node case-expr)
8665 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8666 (/= tt js2-CASE)
8667 (/= tt js2-DEFAULT)
8668 (/= tt js2-EOF))
8669 (setf stmt (js2-parse-statement)
8670 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8671 (js2-block-node-push case-node stmt))
8672 (push case-node cases)))
8673 ;; add cases last, as pushing reverses the order to be correct
8674 (dolist (kid cases)
8675 (js2-node-add-children pn kid)
8676 (push kid (js2-switch-node-cases pn)))
8677 pn) ; return value
8678 (js2-exit-switch))))
8679
8680 (defun js2-parse-while ()
8681 "Parser for while-statement. Last matched token must be js2-WHILE."
8682 (let ((pos (js2-current-token-beg))
8683 (pn (make-js2-while-node))
8684 cond body)
8685 (js2-enter-loop pn)
8686 (unwind-protect
8687 (progn
8688 (setf cond (js2-parse-condition)
8689 (js2-while-node-condition pn) (car cond)
8690 body (js2-parse-statement)
8691 (js2-while-node-body pn) body
8692 (js2-node-len pn) (- (js2-node-end body) pos)
8693 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8694 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8695 (js2-node-add-children pn body (car cond)))
8696 (js2-exit-loop))
8697 pn))
8698
8699 (defun js2-parse-do ()
8700 "Parser for do-statement. Last matched token must be js2-DO."
8701 (let ((pos (js2-current-token-beg))
8702 (pn (make-js2-do-node))
8703 cond body end)
8704 (js2-enter-loop pn)
8705 (unwind-protect
8706 (progn
8707 (setq body (js2-parse-statement))
8708 (js2-must-match js2-WHILE "msg.no.while.do")
8709 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8710 cond (js2-parse-condition)
8711 (js2-do-node-condition pn) (car cond)
8712 (js2-do-node-body pn) body
8713 end js2-ts-cursor
8714 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8715 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8716 (js2-node-add-children pn (car cond) body))
8717 (js2-exit-loop))
8718 ;; Always auto-insert semicolon to follow SpiderMonkey:
8719 ;; It is required by ECMAScript but is ignored by the rest of
8720 ;; world; see bug 238945
8721 (if (js2-match-token js2-SEMI)
8722 (setq end js2-ts-cursor))
8723 (setf (js2-node-len pn) (- end pos))
8724 pn))
8725
8726 (defun js2-parse-export ()
8727 "Parse an export statement.
8728 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8729 expressions should only be either hoistable expressions (function or generator)
8730 or assignment expressions, but there is no checking to enforce that and so it
8731 will parse without error a small subset of
8732 invalid export statements."
8733 (unless (js2-ast-root-p js2-current-scope)
8734 (js2-report-error "msg.mod.export.decl.at.top.level"))
8735 (let ((beg (js2-current-token-beg))
8736 (children (list))
8737 exports-list from-clause declaration default)
8738 (cond
8739 ((js2-match-token js2-MUL)
8740 (setq from-clause (js2-parse-from-clause))
8741 (when from-clause
8742 (push from-clause children)))
8743 ((js2-match-token js2-LC)
8744 (setq exports-list (js2-parse-export-bindings))
8745 (when exports-list
8746 (dolist (export exports-list)
8747 (push export children)))
8748 (when (js2-match-token js2-NAME)
8749 (if (equal "from" (js2-current-token-string))
8750 (progn
8751 (js2-unget-token)
8752 (setq from-clause (js2-parse-from-clause)))
8753 (js2-unget-token))))
8754 ((js2-match-token js2-DEFAULT)
8755 (setq default (js2-parse-expr)))
8756 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8757 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8758 (t
8759 (setq declaration (js2-parse-expr))))
8760 (when from-clause
8761 (push from-clause children))
8762 (when declaration
8763 (push declaration children)
8764 (when (not (js2-function-node-p declaration))
8765 (js2-auto-insert-semicolon declaration)))
8766 (when default
8767 (push default children)
8768 (when (not (js2-function-node-p default))
8769 (js2-auto-insert-semicolon default)))
8770 (let ((node (make-js2-export-node
8771 :pos beg
8772 :len (- (js2-current-token-end) beg)
8773 :exports-list exports-list
8774 :from-clause from-clause
8775 :declaration declaration
8776 :default default)))
8777 (apply #'js2-node-add-children node children)
8778 node)))
8779
8780 (defun js2-parse-for ()
8781 "Parse a for, for-in or for each-in statement.
8782 Last matched token must be js2-FOR."
8783 (let ((for-pos (js2-current-token-beg))
8784 (tmp-scope (make-js2-scope))
8785 pn is-for-each is-for-in-or-of is-for-of
8786 in-pos each-pos tmp-pos
8787 init ; Node init is also foo in 'foo in object'.
8788 cond ; Node cond is also object in 'foo in object'.
8789 incr ; 3rd section of for-loop initializer.
8790 body tt lp rp)
8791 ;; See if this is a for each () instead of just a for ()
8792 (when (js2-match-token js2-NAME)
8793 (if (string= "each" (js2-current-token-string))
8794 (progn
8795 (setq is-for-each t
8796 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8797 (js2-record-face 'font-lock-keyword-face))
8798 (js2-report-error "msg.no.paren.for")))
8799 (if (js2-must-match js2-LP "msg.no.paren.for")
8800 (setq lp (- (js2-current-token-beg) for-pos)))
8801 (setq tt (js2-get-token))
8802 ;; Capture identifiers inside parens. We can't create the node
8803 ;; (and use it as the current scope) until we know its type.
8804 (js2-push-scope tmp-scope)
8805 (unwind-protect
8806 (progn
8807 ;; parse init clause
8808 (let ((js2-in-for-init t)) ; set as dynamic variable
8809 (cond
8810 ((= tt js2-SEMI)
8811 (js2-unget-token)
8812 (setq init (make-js2-empty-expr-node)))
8813 ((or (= tt js2-VAR) (= tt js2-LET))
8814 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8815 (t
8816 (js2-unget-token)
8817 (setq init (js2-parse-expr)))))
8818 (if (or (js2-match-token js2-IN)
8819 (and (>= js2-language-version 200)
8820 (js2-match-contextual-kwd "of")
8821 (setq is-for-of t)))
8822 (setq is-for-in-or-of t
8823 in-pos (- (js2-current-token-beg) for-pos)
8824 ;; scope of iteration target object is not the scope we've created above.
8825 ;; stash current scope temporary.
8826 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8827 (js2-parse-expr))) ; object over which we're iterating
8828 ;; else ordinary for loop - parse cond and incr
8829 (js2-must-match js2-SEMI "msg.no.semi.for")
8830 (setq cond (if (= (js2-peek-token) js2-SEMI)
8831 (make-js2-empty-expr-node) ; no loop condition
8832 (js2-parse-expr)))
8833 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8834 (setq tmp-pos (js2-current-token-end)
8835 incr (if (= (js2-peek-token) js2-RP)
8836 (make-js2-empty-expr-node :pos tmp-pos)
8837 (js2-parse-expr)))))
8838 (js2-pop-scope))
8839 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8840 (setq rp (- (js2-current-token-beg) for-pos)))
8841 (if (not is-for-in-or-of)
8842 (setq pn (make-js2-for-node :init init
8843 :condition cond
8844 :update incr
8845 :lp lp
8846 :rp rp))
8847 ;; cond could be null if 'in obj' got eaten by the init node.
8848 (if (js2-infix-node-p init)
8849 ;; it was (foo in bar) instead of (var foo in bar)
8850 (setq cond (js2-infix-node-right init)
8851 init (js2-infix-node-left init))
8852 (if (and (js2-var-decl-node-p init)
8853 (> (length (js2-var-decl-node-kids init)) 1))
8854 (js2-report-error "msg.mult.index")))
8855 (setq pn (make-js2-for-in-node :iterator init
8856 :object cond
8857 :in-pos in-pos
8858 :foreach-p is-for-each
8859 :each-pos each-pos
8860 :forof-p is-for-of
8861 :lp lp
8862 :rp rp)))
8863 ;; Transplant the declarations.
8864 (setf (js2-scope-symbol-table pn)
8865 (js2-scope-symbol-table tmp-scope))
8866 (unwind-protect
8867 (progn
8868 (js2-enter-loop pn)
8869 ;; We have to parse the body -after- creating the loop node,
8870 ;; so that the loop node appears in the js2-loop-set, allowing
8871 ;; break/continue statements to find the enclosing loop.
8872 (setf body (js2-parse-statement)
8873 (js2-loop-node-body pn) body
8874 (js2-node-pos pn) for-pos
8875 (js2-node-len pn) (- (js2-node-end body) for-pos))
8876 (js2-node-add-children pn init cond incr body))
8877 ;; finally
8878 (js2-exit-loop))
8879 pn))
8880
8881 (defun js2-parse-try ()
8882 "Parse a try statement. Last matched token must be js2-TRY."
8883 (let ((try-pos (js2-current-token-beg))
8884 try-end
8885 try-block
8886 catch-blocks
8887 finally-block
8888 saw-default-catch
8889 peek)
8890 (if (/= (js2-peek-token) js2-LC)
8891 (js2-report-error "msg.no.brace.try"))
8892 (setq try-block (js2-parse-statement)
8893 try-end (js2-node-end try-block)
8894 peek (js2-peek-token))
8895 (cond
8896 ((= peek js2-CATCH)
8897 (while (js2-match-token js2-CATCH)
8898 (let* ((catch-pos (js2-current-token-beg))
8899 (catch-node (make-js2-catch-node :pos catch-pos))
8900 param
8901 guard-kwd
8902 catch-cond
8903 lp rp)
8904 (if saw-default-catch
8905 (js2-report-error "msg.catch.unreachable"))
8906 (if (js2-must-match js2-LP "msg.no.paren.catch")
8907 (setq lp (- (js2-current-token-beg) catch-pos)))
8908 (js2-push-scope catch-node)
8909 (let ((tt (js2-peek-token)))
8910 (cond
8911 ;; Destructuring pattern:
8912 ;; catch ({ message, file }) { ... }
8913 ((or (= tt js2-LB) (= tt js2-LC))
8914 (js2-get-token)
8915 (setq param (js2-parse-destruct-primary-expr))
8916 (js2-define-destruct-symbols param js2-LET nil))
8917 ;; Simple name.
8918 (t
8919 (js2-must-match-name "msg.bad.catchcond")
8920 (setq param (js2-create-name-node))
8921 (js2-define-symbol js2-LET (js2-current-token-string) param)
8922 (js2-check-strict-identifier param))))
8923 ;; Catch condition.
8924 (if (js2-match-token js2-IF)
8925 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8926 catch-cond (js2-parse-expr))
8927 (setq saw-default-catch t))
8928 (if (js2-must-match js2-RP "msg.bad.catchcond")
8929 (setq rp (- (js2-current-token-beg) catch-pos)))
8930 (js2-must-match js2-LC "msg.no.brace.catchblock")
8931 (js2-parse-statements catch-node)
8932 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8933 (setq try-end (js2-current-token-end)))
8934 (js2-pop-scope)
8935 (setf (js2-node-len catch-node) (- try-end catch-pos)
8936 (js2-catch-node-param catch-node) param
8937 (js2-catch-node-guard-expr catch-node) catch-cond
8938 (js2-catch-node-guard-kwd catch-node) guard-kwd
8939 (js2-catch-node-lp catch-node) lp
8940 (js2-catch-node-rp catch-node) rp)
8941 (js2-node-add-children catch-node param catch-cond)
8942 (push catch-node catch-blocks))))
8943 ((/= peek js2-FINALLY)
8944 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8945 (js2-node-pos try-block)
8946 (- (setq try-end (js2-node-end try-block))
8947 (js2-node-pos try-block)))))
8948 (when (js2-match-token js2-FINALLY)
8949 (let ((finally-pos (js2-current-token-beg))
8950 (block (js2-parse-statement)))
8951 (setq try-end (js2-node-end block)
8952 finally-block (make-js2-finally-node :pos finally-pos
8953 :len (- try-end finally-pos)
8954 :body block))
8955 (js2-node-add-children finally-block block)))
8956 (let ((pn (make-js2-try-node :pos try-pos
8957 :len (- try-end try-pos)
8958 :try-block try-block
8959 :finally-block finally-block)))
8960 (js2-node-add-children pn try-block finally-block)
8961 ;; Push them onto the try-node, which reverses and corrects their order.
8962 (dolist (cb catch-blocks)
8963 (js2-node-add-children pn cb)
8964 (push cb (js2-try-node-catch-clauses pn)))
8965 pn)))
8966
8967 (defun js2-parse-throw ()
8968 "Parser for throw-statement. Last matched token must be js2-THROW."
8969 (let ((pos (js2-current-token-beg))
8970 expr pn)
8971 (if (= (js2-peek-token-or-eol) js2-EOL)
8972 ;; ECMAScript does not allow new lines before throw expression,
8973 ;; see bug 256617
8974 (js2-report-error "msg.bad.throw.eol"))
8975 (setq expr (js2-parse-expr)
8976 pn (make-js2-throw-node :pos pos
8977 :len (- (js2-node-end expr) pos)
8978 :expr expr))
8979 (js2-node-add-children pn expr)
8980 pn))
8981
8982 (defun js2-match-jump-label-name (label-name)
8983 "If break/continue specified a label, return that label's labeled stmt.
8984 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8985 does not match an existing label, reports an error and returns nil."
8986 (let ((bundle (cdr (assoc label-name js2-label-set))))
8987 (if (null bundle)
8988 (js2-report-error "msg.undef.label"))
8989 bundle))
8990
8991 (defun js2-parse-break ()
8992 "Parser for break-statement. Last matched token must be js2-BREAK."
8993 (let ((pos (js2-current-token-beg))
8994 (end (js2-current-token-end))
8995 break-target ; statement to break from
8996 break-label ; in "break foo", name-node representing the foo
8997 labels ; matching labeled statement to break to
8998 pn)
8999 (when (eq (js2-peek-token-or-eol) js2-NAME)
9000 (js2-get-token)
9001 (setq break-label (js2-create-name-node)
9002 end (js2-node-end break-label)
9003 ;; matchJumpLabelName only matches if there is one
9004 labels (js2-match-jump-label-name (js2-current-token-string))
9005 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9006 (unless (or break-target break-label)
9007 ;; no break target specified - try for innermost enclosing loop/switch
9008 (if (null js2-loop-and-switch-set)
9009 (unless break-label
9010 (js2-report-error "msg.bad.break" nil pos (length "break")))
9011 (setq break-target (car js2-loop-and-switch-set))))
9012 (setq pn (make-js2-break-node :pos pos
9013 :len (- end pos)
9014 :label break-label
9015 :target break-target))
9016 (js2-node-add-children pn break-label) ; but not break-target
9017 pn))
9018
9019 (defun js2-parse-continue ()
9020 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9021 (let ((pos (js2-current-token-beg))
9022 (end (js2-current-token-end))
9023 label ; optional user-specified label, a `js2-name-node'
9024 labels ; current matching labeled stmt, if any
9025 target ; the `js2-loop-node' target of this continue stmt
9026 pn)
9027 (when (= (js2-peek-token-or-eol) js2-NAME)
9028 (js2-get-token)
9029 (setq label (js2-create-name-node)
9030 end (js2-node-end label)
9031 ;; matchJumpLabelName only matches if there is one
9032 labels (js2-match-jump-label-name (js2-current-token-string))))
9033 (cond
9034 ((null labels) ; no current label to go to
9035 (if (null js2-loop-set) ; no loop to continue to
9036 (js2-report-error "msg.continue.outside" nil pos
9037 (length "continue"))
9038 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9039 (t
9040 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9041 (setq target (js2-labeled-stmt-node-stmt labels))
9042 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9043 (setq pn (make-js2-continue-node :pos pos
9044 :len (- end pos)
9045 :label label
9046 :target target))
9047 (js2-node-add-children pn label) ; but not target - it's not our child
9048 pn))
9049
9050 (defun js2-parse-with ()
9051 "Parser for with-statement. Last matched token must be js2-WITH."
9052 (when js2-in-use-strict-directive
9053 (js2-report-error "msg.no.with.strict"))
9054 (let ((pos (js2-current-token-beg))
9055 obj body pn lp rp)
9056 (if (js2-must-match js2-LP "msg.no.paren.with")
9057 (setq lp (js2-current-token-beg)))
9058 (setq obj (js2-parse-expr))
9059 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9060 (setq rp (js2-current-token-beg)))
9061 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9062 (setq body (js2-parse-statement)))
9063 (setq pn (make-js2-with-node :pos pos
9064 :len (- (js2-node-end body) pos)
9065 :object obj
9066 :body body
9067 :lp (js2-relpos lp pos)
9068 :rp (js2-relpos rp pos)))
9069 (js2-node-add-children pn obj body)
9070 pn))
9071
9072 (defun js2-parse-const-var ()
9073 "Parser for var- or const-statement.
9074 Last matched token must be js2-CONST or js2-VAR."
9075 (let ((tt (js2-current-token-type))
9076 (pos (js2-current-token-beg))
9077 expr pn)
9078 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9079 pn (make-js2-expr-stmt-node :pos pos
9080 :len (- (js2-node-end expr) pos)
9081 :expr expr))
9082 (js2-node-add-children pn expr)
9083 pn))
9084
9085 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9086 (let ((pn (make-js2-expr-stmt-node :pos pos
9087 :len (js2-node-len expr)
9088 :type (if (js2-inside-function)
9089 js2-EXPR_VOID
9090 js2-EXPR_RESULT)
9091 :expr expr)))
9092 (if add-child
9093 (js2-node-add-children pn expr))
9094 pn))
9095
9096 (defun js2-parse-let-stmt ()
9097 "Parser for let-statement. Last matched token must be js2-LET."
9098 (let ((pos (js2-current-token-beg))
9099 expr pn)
9100 (if (= (js2-peek-token) js2-LP)
9101 ;; let expression in statement context
9102 (setq expr (js2-parse-let pos 'statement)
9103 pn (js2-wrap-with-expr-stmt pos expr t))
9104 ;; else we're looking at a statement like let x=6, y=7;
9105 (setf expr (js2-parse-variables js2-LET pos)
9106 pn (js2-wrap-with-expr-stmt pos expr t)
9107 (js2-node-type pn) js2-EXPR_RESULT))
9108 pn))
9109
9110 (defun js2-parse-ret-yield ()
9111 (js2-parse-return-or-yield (js2-current-token-type) nil))
9112
9113 (defconst js2-parse-return-stmt-enders
9114 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9115
9116 (defsubst js2-now-all-set (before after mask)
9117 "Return whether or not the bits in the mask have changed to all set.
9118 BEFORE is bits before change, AFTER is bits after change, and MASK is
9119 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9120 but not BEFORE."
9121 (and (/= (logand before mask) mask)
9122 (= (logand after mask) mask)))
9123
9124 (defun js2-parse-return-or-yield (tt expr-context)
9125 (let* ((pos (js2-current-token-beg))
9126 (end (js2-current-token-end))
9127 (before js2-end-flags)
9128 (inside-function (js2-inside-function))
9129 (gen-type (and inside-function (js2-function-node-generator-type
9130 js2-current-script-or-fn)))
9131 e ret name yield-star-p)
9132 (unless inside-function
9133 (js2-report-error (if (eq tt js2-RETURN)
9134 "msg.bad.return"
9135 "msg.bad.yield")))
9136 (when (and inside-function
9137 (eq gen-type 'STAR)
9138 (js2-match-token js2-MUL))
9139 (setq yield-star-p t))
9140 ;; This is ugly, but we don't want to require a semicolon.
9141 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9142 (setq e (js2-parse-expr)
9143 end (js2-node-end e)))
9144 (cond
9145 ((eq tt js2-RETURN)
9146 (js2-set-flag js2-end-flags (if (null e)
9147 js2-end-returns
9148 js2-end-returns-value))
9149 (setq ret (make-js2-return-node :pos pos
9150 :len (- end pos)
9151 :retval e))
9152 (js2-node-add-children ret e)
9153 ;; See if we need a strict mode warning.
9154 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9155 ;; more thorough and accurate than this before/after flag check.
9156 ;; E.g. if there's a finally-block that always returns, we shouldn't
9157 ;; show a warning generated by inconsistent returns in the catch blocks.
9158 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9159 ;; so we know which returns/yields to highlight, and we should get rid of
9160 ;; all the checking in `js2-parse-return-or-yield'.
9161 (if (and js2-strict-inconsistent-return-warning
9162 (js2-now-all-set before js2-end-flags
9163 (logior js2-end-returns js2-end-returns-value)))
9164 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9165 ((eq gen-type 'COMPREHENSION)
9166 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9167 ;; like SpiderMonkey does.
9168 (js2-report-error "msg.syntax" nil pos 5))
9169 (t
9170 (setq ret (make-js2-yield-node :pos pos
9171 :len (- end pos)
9172 :value e
9173 :star-p yield-star-p))
9174 (js2-node-add-children ret e)
9175 (unless expr-context
9176 (setq e ret
9177 ret (js2-wrap-with-expr-stmt pos e t))
9178 (js2-set-requires-activation)
9179 (js2-set-is-generator))))
9180 ;; see if we are mixing yields and value returns.
9181 (when (and inside-function
9182 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9183 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9184 'LEGACY))
9185 (setq name (js2-function-name js2-current-script-or-fn))
9186 (if (zerop (length name))
9187 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9188 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9189 ret))
9190
9191 (defun js2-parse-debugger ()
9192 (make-js2-keyword-node :type js2-DEBUGGER))
9193
9194 (defun js2-parse-block ()
9195 "Parser for a curly-delimited statement block.
9196 Last token matched must be `js2-LC'."
9197 (let ((pos (js2-current-token-beg))
9198 (pn (make-js2-scope)))
9199 (js2-push-scope pn)
9200 (unwind-protect
9201 (progn
9202 (js2-parse-statements pn)
9203 (js2-must-match js2-RC "msg.no.brace.block")
9204 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9205 (js2-pop-scope))
9206 pn))
9207
9208 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9209 (defun js2-parse-semi ()
9210 "Parse a statement or handle an error.
9211 Current token type is `js2-SEMI' or `js2-ERROR'."
9212 (let ((tt (js2-current-token-type)) pos len)
9213 (if (eq tt js2-SEMI)
9214 (make-js2-empty-expr-node :len 1)
9215 (setq pos (js2-current-token-beg)
9216 len (- (js2-current-token-end) pos))
9217 (js2-report-error "msg.syntax" nil pos len)
9218 (make-js2-error-node :pos pos :len len))))
9219
9220 (defun js2-parse-default-xml-namespace ()
9221 "Parse a `default xml namespace = <expr>' e4x statement."
9222 (let ((pos (js2-current-token-beg))
9223 end len expr unary)
9224 (js2-must-have-xml)
9225 (js2-set-requires-activation)
9226 (setq len (- js2-ts-cursor pos))
9227 (unless (and (js2-match-token js2-NAME)
9228 (string= (js2-current-token-string) "xml"))
9229 (js2-report-error "msg.bad.namespace" nil pos len))
9230 (unless (and (js2-match-token js2-NAME)
9231 (string= (js2-current-token-string) "namespace"))
9232 (js2-report-error "msg.bad.namespace" nil pos len))
9233 (unless (js2-match-token js2-ASSIGN)
9234 (js2-report-error "msg.bad.namespace" nil pos len))
9235 (setq expr (js2-parse-expr)
9236 end (js2-node-end expr)
9237 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9238 :pos pos
9239 :len (- end pos)
9240 :operand expr))
9241 (js2-node-add-children unary expr)
9242 (make-js2-expr-stmt-node :pos pos
9243 :len (- end pos)
9244 :expr unary)))
9245
9246 (defun js2-record-label (label bundle)
9247 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9248 (js2-get-token)
9249 (let ((name (js2-label-node-name label))
9250 labeled-stmt
9251 dup)
9252 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9253 ;; flag both labels if possible when used in editing mode
9254 (if (and js2-parse-ide-mode
9255 (setq dup (js2-get-label-by-name labeled-stmt name)))
9256 (js2-report-error "msg.dup.label" nil
9257 (js2-node-abs-pos dup) (js2-node-len dup)))
9258 (js2-report-error "msg.dup.label" nil
9259 (js2-node-pos label) (js2-node-len label)))
9260 (js2-labeled-stmt-node-add-label bundle label)
9261 (js2-node-add-children bundle label)
9262 ;; Add one reference to the bundle per label in `js2-label-set'
9263 (push (cons name bundle) js2-label-set)))
9264
9265 (defun js2-parse-name-or-label ()
9266 "Parser for identifier or label. Last token matched must be js2-NAME.
9267 Called when we found a name in a statement context. If it's a label, we gather
9268 up any following labels and the next non-label statement into a
9269 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9270 expression and return it wrapped in a `js2-expr-stmt-node'."
9271 (let ((pos (js2-current-token-beg))
9272 expr stmt bundle
9273 (continue t))
9274 ;; set check for label and call down to `js2-parse-primary-expr'
9275 (setq expr (js2-maybe-parse-label))
9276 (if (null expr)
9277 ;; Parse the non-label expression and wrap with expression stmt.
9278 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9279 ;; else parsed a label
9280 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9281 (js2-record-label expr bundle)
9282 ;; look for more labels
9283 (while (and continue (= (js2-get-token) js2-NAME))
9284 (if (setq expr (js2-maybe-parse-label))
9285 (js2-record-label expr bundle)
9286 (setq expr (js2-parse-expr)
9287 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9288 continue nil)
9289 (js2-auto-insert-semicolon stmt)))
9290 ;; no more labels; now parse the labeled statement
9291 (unwind-protect
9292 (unless stmt
9293 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9294 (js2-unget-token)
9295 (setq stmt (js2-statement-helper))))
9296 ;; remove the labels for this statement from the global set
9297 (dolist (label (js2-labeled-stmt-node-labels bundle))
9298 (setq js2-label-set (remove label js2-label-set))))
9299 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9300 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9301 (js2-node-add-children bundle stmt)
9302 bundle)))
9303
9304 (defun js2-maybe-parse-label ()
9305 (cl-assert (= (js2-current-token-type) js2-NAME))
9306 (let (label-pos
9307 (next-tt (js2-get-token))
9308 (label-end (js2-current-token-end)))
9309 ;; Do not consume colon, it is used as unwind indicator
9310 ;; to return to statementHelper.
9311 (js2-unget-token)
9312 (if (= next-tt js2-COLON)
9313 (prog2
9314 (setq label-pos (js2-current-token-beg))
9315 (make-js2-label-node :pos label-pos
9316 :len (- label-end label-pos)
9317 :name (js2-current-token-string))
9318 (js2-set-face label-pos
9319 label-end
9320 'font-lock-variable-name-face 'record))
9321 ;; Backtrack from the name token, too.
9322 (js2-unget-token)
9323 nil)))
9324
9325 (defun js2-parse-expr-stmt ()
9326 "Default parser in statement context, if no recognized statement found."
9327 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9328 (progn
9329 (js2-unget-token)
9330 (js2-parse-expr)) t))
9331
9332 (defun js2-parse-variables (decl-type pos)
9333 "Parse a comma-separated list of variable declarations.
9334 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9335
9336 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9337 For 'var' or 'const', the keyword should be the token last scanned.
9338
9339 POS is the position where the node should start. It's sometimes the
9340 var/const/let keyword, and other times the beginning of the first token
9341 in the first variable declaration.
9342
9343 Returns the parsed `js2-var-decl-node' expression node."
9344 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9345 :pos pos))
9346 destructuring kid-pos tt init name end nbeg nend vi
9347 (continue t))
9348 ;; Example:
9349 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9350 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9351 ;; var {a, b} = baz;
9352 (while continue
9353 (setq destructuring nil
9354 name nil
9355 tt (js2-get-token)
9356 kid-pos (js2-current-token-beg)
9357 end (js2-current-token-end)
9358 init nil)
9359 (if (or (= tt js2-LB) (= tt js2-LC))
9360 ;; Destructuring assignment, e.g., var [a, b] = ...
9361 (setq destructuring (js2-parse-destruct-primary-expr)
9362 end (js2-node-end destructuring))
9363 ;; Simple variable name
9364 (js2-unget-token)
9365 (when (js2-must-match-name "msg.bad.var")
9366 (setq name (js2-create-name-node)
9367 nbeg (js2-current-token-beg)
9368 nend (js2-current-token-end)
9369 end nend)
9370 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9371 (js2-check-strict-identifier name)))
9372 (when (js2-match-token js2-ASSIGN)
9373 (setq init (js2-parse-assign-expr)
9374 end (js2-node-end init))
9375 (js2-record-imenu-functions init name))
9376 (when name
9377 (js2-set-face nbeg nend (if (js2-function-node-p init)
9378 'font-lock-function-name-face
9379 'font-lock-variable-name-face)
9380 'record))
9381 (setq vi (make-js2-var-init-node :pos kid-pos
9382 :len (- end kid-pos)
9383 :type decl-type))
9384 (if destructuring
9385 (progn
9386 (if (and (null init) (not js2-in-for-init))
9387 (js2-report-error "msg.destruct.assign.no.init"))
9388 (js2-define-destruct-symbols destructuring
9389 decl-type
9390 'font-lock-variable-name-face)
9391 (setf (js2-var-init-node-target vi) destructuring))
9392 (setf (js2-var-init-node-target vi) name))
9393 (setf (js2-var-init-node-initializer vi) init)
9394 (js2-node-add-children vi name destructuring init)
9395 (js2-block-node-push result vi)
9396 (unless (js2-match-token js2-COMMA)
9397 (setq continue nil)))
9398 (setf (js2-node-len result) (- end pos))
9399 result))
9400
9401 (defun js2-parse-let (pos &optional stmt-p)
9402 "Parse a let expression or statement.
9403 A let-expression is of the form `let (vars) expr'.
9404 A let-statement is of the form `let (vars) {statements}'.
9405 The third form of let is a variable declaration list, handled
9406 by `js2-parse-variables'."
9407 (let ((pn (make-js2-let-node :pos pos))
9408 beg vars body)
9409 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9410 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9411 (js2-push-scope pn)
9412 (unwind-protect
9413 (progn
9414 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9415 (if (js2-must-match js2-RP "msg.no.paren.let")
9416 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9417 (if (and stmt-p (js2-match-token js2-LC))
9418 ;; let statement
9419 (progn
9420 (setf beg (js2-current-token-beg) ; position stmt at LC
9421 body (js2-parse-statements))
9422 (js2-must-match js2-RC "msg.no.curly.let")
9423 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9424 (js2-node-len pn) (- (js2-current-token-end) pos)
9425 (js2-let-node-body pn) body
9426 (js2-node-type pn) js2-LET))
9427 ;; let expression
9428 (setf body (js2-parse-expr)
9429 (js2-node-len pn) (- (js2-node-end body) pos)
9430 (js2-let-node-body pn) body))
9431 (setf (js2-let-node-vars pn) vars)
9432 (js2-node-add-children pn vars body))
9433 (js2-pop-scope))
9434 pn))
9435
9436 (defun js2-define-new-symbol (decl-type name node &optional scope)
9437 (js2-scope-put-symbol (or scope js2-current-scope)
9438 name
9439 (make-js2-symbol decl-type name node)))
9440
9441 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9442 "Define a symbol in the current scope.
9443 If NODE is non-nil, it is the AST node associated with the symbol."
9444 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9445 (symbol (if defining-scope
9446 (js2-scope-get-symbol defining-scope name)))
9447 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9448 (pos (if node (js2-node-abs-pos node)))
9449 (len (if node (js2-node-len node))))
9450 (cond
9451 ((and symbol ; already defined
9452 (or (if js2-in-use-strict-directive
9453 ;; two const-bound vars in this block have same name
9454 (and (= sdt js2-CONST)
9455 (eq defining-scope js2-current-scope))
9456 (or (= sdt js2-CONST) ; old version is const
9457 (= decl-type js2-CONST))) ; new version is const
9458 ;; two let-bound vars in this block have same name
9459 (and (= sdt js2-LET)
9460 (eq defining-scope js2-current-scope))))
9461 (js2-report-error
9462 (cond
9463 ((= sdt js2-CONST) "msg.const.redecl")
9464 ((= sdt js2-LET) "msg.let.redecl")
9465 ((= sdt js2-VAR) "msg.var.redecl")
9466 ((= sdt js2-FUNCTION) "msg.function.redecl")
9467 (t "msg.parm.redecl"))
9468 name pos len))
9469 ((or (= decl-type js2-LET)
9470 ;; strict mode const is scoped to the current LexicalEnvironment
9471 (and js2-in-use-strict-directive
9472 (= decl-type js2-CONST)))
9473 (if (and (= decl-type js2-LET)
9474 (not ignore-not-in-block)
9475 (or (= (js2-node-type js2-current-scope) js2-IF)
9476 (js2-loop-node-p js2-current-scope)))
9477 (js2-report-error "msg.let.decl.not.in.block")
9478 (js2-define-new-symbol decl-type name node)))
9479 ((or (= decl-type js2-VAR)
9480 (= decl-type js2-FUNCTION)
9481 ;; sloppy mode const is scoped to the current VariableEnvironment
9482 (and (not js2-in-use-strict-directive)
9483 (= decl-type js2-CONST)))
9484 (if symbol
9485 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9486 (js2-add-strict-warning "msg.var.redecl" name)
9487 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9488 (js2-add-strict-warning "msg.var.hides.arg" name)))
9489 (js2-define-new-symbol decl-type name node
9490 js2-current-script-or-fn)))
9491 ((= decl-type js2-LP)
9492 (if symbol
9493 ;; must be duplicate parameter. Second parameter hides the
9494 ;; first, so go ahead and add the second pararameter
9495 (js2-report-warning "msg.dup.parms" name))
9496 (js2-define-new-symbol decl-type name node))
9497 (t (js2-code-bug)))))
9498
9499 (defun js2-parse-paren-expr-or-generator-comp ()
9500 (let ((px-pos (js2-current-token-beg)))
9501 (cond
9502 ((and (>= js2-language-version 200)
9503 (js2-match-token js2-FOR))
9504 (js2-parse-generator-comp px-pos))
9505 ((and (>= js2-language-version 200)
9506 (js2-match-token js2-RP))
9507 ;; Not valid expression syntax, but this is valid in an arrow
9508 ;; function with no params: () => body.
9509 (if (eq (js2-peek-token) js2-ARROW)
9510 ;; Return whatever, it will hopefully be rewinded and
9511 ;; reparsed when we reach the =>.
9512 (make-js2-keyword-node :type js2-NULL)
9513 (js2-report-error "msg.syntax")
9514 (make-js2-error-node)))
9515 (t
9516 (let* ((js2-in-for-init nil)
9517 (expr (js2-parse-expr))
9518 (pn (make-js2-paren-node :pos px-pos
9519 :expr expr)))
9520 (js2-node-add-children pn (js2-paren-node-expr pn))
9521 (js2-must-match js2-RP "msg.no.paren")
9522 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9523 pn)))))
9524
9525 (defun js2-parse-expr (&optional oneshot)
9526 (let* ((pn (js2-parse-assign-expr))
9527 (pos (js2-node-pos pn))
9528 left
9529 right
9530 op-pos)
9531 (while (and (not oneshot)
9532 (js2-match-token js2-COMMA))
9533 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9534 (if (= (js2-peek-token) js2-YIELD)
9535 (js2-report-error "msg.yield.parenthesized"))
9536 (setq right (js2-parse-assign-expr)
9537 left pn
9538 pn (make-js2-infix-node :type js2-COMMA
9539 :pos pos
9540 :len (- js2-ts-cursor pos)
9541 :op-pos op-pos
9542 :left left
9543 :right right))
9544 (js2-node-add-children pn left right))
9545 pn))
9546
9547 (defun js2-parse-assign-expr ()
9548 (let ((tt (js2-get-token))
9549 (pos (js2-current-token-beg))
9550 pn left right op-pos
9551 ts-state recorded-identifiers parsed-errors)
9552 (if (= tt js2-YIELD)
9553 (js2-parse-return-or-yield tt t)
9554 ;; Save the tokenizer state in case we find an arrow function
9555 ;; and have to rewind.
9556 (setq ts-state (make-js2-ts-state)
9557 recorded-identifiers js2-recorded-identifiers
9558 parsed-errors js2-parsed-errors)
9559 ;; not yield - parse assignment expression
9560 (setq pn (js2-parse-cond-expr)
9561 tt (js2-get-token))
9562 (cond
9563 ((and (<= js2-first-assign tt)
9564 (<= tt js2-last-assign))
9565 ;; tt express assignment (=, |=, ^=, ..., %=)
9566 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9567 left pn)
9568 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9569 ;; care about assignment to strict variable names.
9570 (when (js2-name-node-p left)
9571 (js2-check-strict-identifier left))
9572 (setq right (js2-parse-assign-expr)
9573 pn (make-js2-assign-node :type tt
9574 :pos pos
9575 :len (- (js2-node-end right) pos)
9576 :op-pos op-pos
9577 :left left
9578 :right right))
9579 (when js2-parse-ide-mode
9580 (js2-highlight-assign-targets pn left right)
9581 (js2-record-imenu-functions right left))
9582 ;; do this last so ide checks above can use absolute positions
9583 (js2-node-add-children pn left right))
9584 ((and (= tt js2-ARROW)
9585 (>= js2-language-version 200))
9586 (js2-ts-seek ts-state)
9587 (setq js2-recorded-identifiers recorded-identifiers
9588 js2-parsed-errors parsed-errors)
9589 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9590 (t
9591 (js2-unget-token)))
9592 pn)))
9593
9594 (defun js2-parse-cond-expr ()
9595 (let ((pos (js2-current-token-beg))
9596 (pn (js2-parse-or-expr))
9597 test-expr
9598 if-true
9599 if-false
9600 q-pos
9601 c-pos)
9602 (when (js2-match-token js2-HOOK)
9603 (setq q-pos (- (js2-current-token-beg) pos)
9604 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9605 (js2-must-match js2-COLON "msg.no.colon.cond")
9606 (setq c-pos (- (js2-current-token-beg) pos)
9607 if-false (js2-parse-assign-expr)
9608 test-expr pn
9609 pn (make-js2-cond-node :pos pos
9610 :len (- (js2-node-end if-false) pos)
9611 :test-expr test-expr
9612 :true-expr if-true
9613 :false-expr if-false
9614 :q-pos q-pos
9615 :c-pos c-pos))
9616 (js2-node-add-children pn test-expr if-true if-false))
9617 pn))
9618
9619 (defun js2-make-binary (type left parser)
9620 "Helper for constructing a binary-operator AST node.
9621 LEFT is the left-side-expression, already parsed, and the
9622 binary operator should have just been matched.
9623 PARSER is a function to call to parse the right operand,
9624 or a `js2-node' struct if it has already been parsed.
9625 FIXME: The latter option is unused?"
9626 (let* ((pos (js2-node-pos left))
9627 (op-pos (- (js2-current-token-beg) pos))
9628 (right (if (js2-node-p parser)
9629 parser
9630 (js2-get-token)
9631 (funcall parser)))
9632 (pn (make-js2-infix-node :type type
9633 :pos pos
9634 :len (- (js2-node-end right) pos)
9635 :op-pos op-pos
9636 :left left
9637 :right right)))
9638 (js2-node-add-children pn left right)
9639 pn))
9640
9641 (defun js2-parse-or-expr ()
9642 (let ((pn (js2-parse-and-expr)))
9643 (when (js2-match-token js2-OR)
9644 (setq pn (js2-make-binary js2-OR
9645 pn
9646 'js2-parse-or-expr)))
9647 pn))
9648
9649 (defun js2-parse-and-expr ()
9650 (let ((pn (js2-parse-bit-or-expr)))
9651 (when (js2-match-token js2-AND)
9652 (setq pn (js2-make-binary js2-AND
9653 pn
9654 'js2-parse-and-expr)))
9655 pn))
9656
9657 (defun js2-parse-bit-or-expr ()
9658 (let ((pn (js2-parse-bit-xor-expr)))
9659 (while (js2-match-token js2-BITOR)
9660 (setq pn (js2-make-binary js2-BITOR
9661 pn
9662 'js2-parse-bit-xor-expr)))
9663 pn))
9664
9665 (defun js2-parse-bit-xor-expr ()
9666 (let ((pn (js2-parse-bit-and-expr)))
9667 (while (js2-match-token js2-BITXOR)
9668 (setq pn (js2-make-binary js2-BITXOR
9669 pn
9670 'js2-parse-bit-and-expr)))
9671 pn))
9672
9673 (defun js2-parse-bit-and-expr ()
9674 (let ((pn (js2-parse-eq-expr)))
9675 (while (js2-match-token js2-BITAND)
9676 (setq pn (js2-make-binary js2-BITAND
9677 pn
9678 'js2-parse-eq-expr)))
9679 pn))
9680
9681 (defconst js2-parse-eq-ops
9682 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9683
9684 (defun js2-parse-eq-expr ()
9685 (let ((pn (js2-parse-rel-expr))
9686 tt)
9687 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9688 (setq pn (js2-make-binary tt
9689 pn
9690 'js2-parse-rel-expr)))
9691 (js2-unget-token)
9692 pn))
9693
9694 (defconst js2-parse-rel-ops
9695 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9696
9697 (defun js2-parse-rel-expr ()
9698 (let ((pn (js2-parse-shift-expr))
9699 (continue t)
9700 tt)
9701 (while continue
9702 (setq tt (js2-get-token))
9703 (cond
9704 ((and js2-in-for-init (= tt js2-IN))
9705 (js2-unget-token)
9706 (setq continue nil))
9707 ((memq tt js2-parse-rel-ops)
9708 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9709 (t
9710 (js2-unget-token)
9711 (setq continue nil))))
9712 pn))
9713
9714 (defconst js2-parse-shift-ops
9715 (list js2-LSH js2-URSH js2-RSH))
9716
9717 (defun js2-parse-shift-expr ()
9718 (let ((pn (js2-parse-add-expr))
9719 tt
9720 (continue t))
9721 (while continue
9722 (setq tt (js2-get-token))
9723 (if (memq tt js2-parse-shift-ops)
9724 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9725 (js2-unget-token)
9726 (setq continue nil)))
9727 pn))
9728
9729 (defun js2-parse-add-expr ()
9730 (let ((pn (js2-parse-mul-expr))
9731 tt
9732 (continue t))
9733 (while continue
9734 (setq tt (js2-get-token))
9735 (if (or (= tt js2-ADD) (= tt js2-SUB))
9736 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9737 (js2-unget-token)
9738 (setq continue nil)))
9739 pn))
9740
9741 (defconst js2-parse-mul-ops
9742 (list js2-MUL js2-DIV js2-MOD))
9743
9744 (defun js2-parse-mul-expr ()
9745 (let ((pn (js2-parse-unary-expr))
9746 tt
9747 (continue t))
9748 (while continue
9749 (setq tt (js2-get-token))
9750 (if (memq tt js2-parse-mul-ops)
9751 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9752 (js2-unget-token)
9753 (setq continue nil)))
9754 pn))
9755
9756 (defun js2-make-unary (type parser &rest args)
9757 "Make a unary node of type TYPE.
9758 PARSER is either a node (for postfix operators) or a function to call
9759 to parse the operand (for prefix operators)."
9760 (let* ((pos (js2-current-token-beg))
9761 (postfix (js2-node-p parser))
9762 (expr (if postfix
9763 parser
9764 (apply parser args)))
9765 end
9766 pn)
9767 (if postfix ; e.g. i++
9768 (setq pos (js2-node-pos expr)
9769 end (js2-current-token-end))
9770 (setq end (js2-node-end expr)))
9771 (setq pn (make-js2-unary-node :type type
9772 :pos pos
9773 :len (- end pos)
9774 :operand expr))
9775 (js2-node-add-children pn expr)
9776 pn))
9777
9778 (defconst js2-incrementable-node-types
9779 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9780 "Node types that can be the operand of a ++ or -- operator.")
9781
9782 (defun js2-check-bad-inc-dec (tt beg end unary)
9783 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9784 js2-incrementable-node-types)
9785 (js2-report-error (if (= tt js2-INC)
9786 "msg.bad.incr"
9787 "msg.bad.decr")
9788 nil beg (- end beg))))
9789
9790 (defun js2-parse-unary-expr ()
9791 (let ((tt (js2-current-token-type))
9792 pn expr beg end)
9793 (cond
9794 ((or (= tt js2-VOID)
9795 (= tt js2-NOT)
9796 (= tt js2-BITNOT)
9797 (= tt js2-TYPEOF))
9798 (js2-get-token)
9799 (js2-make-unary tt 'js2-parse-unary-expr))
9800 ((= tt js2-ADD)
9801 (js2-get-token)
9802 ;; Convert to special POS token in decompiler and parse tree
9803 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9804 ((= tt js2-SUB)
9805 (js2-get-token)
9806 ;; Convert to special NEG token in decompiler and parse tree
9807 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9808 ((or (= tt js2-INC)
9809 (= tt js2-DEC))
9810 (js2-get-token)
9811 (prog1
9812 (setq beg (js2-current-token-beg)
9813 end (js2-current-token-end)
9814 expr (js2-make-unary tt 'js2-parse-member-expr t))
9815 (js2-check-bad-inc-dec tt beg end expr)))
9816 ((= tt js2-DELPROP)
9817 (js2-get-token)
9818 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9819 ((= tt js2-ERROR)
9820 (js2-get-token)
9821 (make-js2-error-node)) ; try to continue
9822 ((and (= tt js2-LT)
9823 js2-compiler-xml-available)
9824 ;; XML stream encountered in expression.
9825 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9826 (t
9827 (setq pn (js2-parse-member-expr t)
9828 ;; Don't look across a newline boundary for a postfix incop.
9829 tt (js2-peek-token-or-eol))
9830 (when (or (= tt js2-INC) (= tt js2-DEC))
9831 (js2-get-token)
9832 (setf expr pn
9833 pn (js2-make-unary tt expr))
9834 (js2-node-set-prop pn 'postfix t)
9835 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9836 pn))))
9837
9838 (defun js2-parse-xml-initializer ()
9839 "Parse an E4X XML initializer.
9840 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9841 Then I'll postprocess the result, depending on whether we're in IDE
9842 mode or codegen mode, and generate the appropriate rewritten AST.
9843 IDE mode uses a rich AST that models the XML structure. Codegen mode
9844 just concatenates everything and makes a new XML or XMLList out of it."
9845 (let ((tt (js2-get-first-xml-token))
9846 pn-xml pn expr kids expr-pos
9847 (continue t)
9848 (first-token t))
9849 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9850 (js2-report-error "msg.syntax"))
9851 (setq pn-xml (make-js2-xml-node))
9852 (while continue
9853 (if first-token
9854 (setq first-token nil)
9855 (setq tt (js2-get-next-xml-token)))
9856 (cond
9857 ;; js2-XML means we found a {expr} in the XML stream.
9858 ;; The token string is the XML up to the left-curly.
9859 ((= tt js2-XML)
9860 (push (make-js2-string-node :pos (js2-current-token-beg)
9861 :len (- js2-ts-cursor (js2-current-token-beg)))
9862 kids)
9863 (js2-must-match js2-LC "msg.syntax")
9864 (setq expr-pos js2-ts-cursor
9865 expr (if (eq (js2-peek-token) js2-RC)
9866 (make-js2-empty-expr-node :pos expr-pos)
9867 (js2-parse-expr)))
9868 (js2-must-match js2-RC "msg.syntax")
9869 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9870 :len (js2-node-len expr)
9871 :expr expr))
9872 (js2-node-add-children pn expr)
9873 (push pn kids))
9874 ;; a js2-XMLEND token means we hit the final close-tag.
9875 ((= tt js2-XMLEND)
9876 (push (make-js2-string-node :pos (js2-current-token-beg)
9877 :len (- js2-ts-cursor (js2-current-token-beg)))
9878 kids)
9879 (dolist (kid (nreverse kids))
9880 (js2-block-node-push pn-xml kid))
9881 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9882 (js2-node-pos pn-xml))
9883 continue nil))
9884 (t
9885 (js2-report-error "msg.syntax")
9886 (setq continue nil))))
9887 pn-xml))
9888
9889
9890 (defun js2-parse-argument-list ()
9891 "Parse an argument list and return it as a Lisp list of nodes.
9892 Returns the list in reverse order. Consumes the right-paren token."
9893 (let (result)
9894 (unless (js2-match-token js2-RP)
9895 (cl-loop do
9896 (let ((tt (js2-get-token)))
9897 (if (= tt js2-YIELD)
9898 (js2-report-error "msg.yield.parenthesized"))
9899 (if (and (= tt js2-TRIPLEDOT)
9900 (>= js2-language-version 200))
9901 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9902 (js2-unget-token)
9903 (push (js2-parse-assign-expr) result)))
9904 while
9905 (js2-match-token js2-COMMA))
9906 (js2-must-match js2-RP "msg.no.paren.arg")
9907 result)))
9908
9909 (defun js2-parse-member-expr (&optional allow-call-syntax)
9910 (let ((tt (js2-current-token-type))
9911 pn pos target args beg end init)
9912 (if (/= tt js2-NEW)
9913 (setq pn (js2-parse-primary-expr))
9914 ;; parse a 'new' expression
9915 (js2-get-token)
9916 (setq pos (js2-current-token-beg)
9917 beg pos
9918 target (js2-parse-member-expr)
9919 end (js2-node-end target)
9920 pn (make-js2-new-node :pos pos
9921 :target target
9922 :len (- end pos)))
9923 (js2-highlight-function-call (js2-current-token))
9924 (js2-node-add-children pn target)
9925 (when (js2-match-token js2-LP)
9926 ;; Add the arguments to pn, if any are supplied.
9927 (setf beg pos ; start of "new" keyword
9928 pos (js2-current-token-beg)
9929 args (nreverse (js2-parse-argument-list))
9930 (js2-new-node-args pn) args
9931 end (js2-current-token-end)
9932 (js2-new-node-lp pn) (- pos beg)
9933 (js2-new-node-rp pn) (- end 1 beg))
9934 (apply #'js2-node-add-children pn args))
9935 (when (and js2-allow-rhino-new-expr-initializer
9936 (js2-match-token js2-LC))
9937 (setf init (js2-parse-object-literal)
9938 end (js2-node-end init)
9939 (js2-new-node-initializer pn) init)
9940 (js2-node-add-children pn init))
9941 (setf (js2-node-len pn) (- end beg))) ; end outer if
9942 (js2-parse-member-expr-tail allow-call-syntax pn)))
9943
9944 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9945 "Parse a chain of property/array accesses or function calls.
9946 Includes parsing for E4X operators like `..' and `.@'.
9947 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9948 Returns an expression tree that includes PN, the parent node."
9949 (let (tt
9950 (continue t))
9951 (while continue
9952 (setq tt (js2-get-token))
9953 (cond
9954 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9955 (setq pn (js2-parse-property-access tt pn)))
9956 ((= tt js2-DOTQUERY)
9957 (setq pn (js2-parse-dot-query pn)))
9958 ((= tt js2-LB)
9959 (setq pn (js2-parse-element-get pn)))
9960 ((= tt js2-LP)
9961 (js2-unget-token)
9962 (if allow-call-syntax
9963 (setq pn (js2-parse-function-call pn))
9964 (setq continue nil)))
9965 ((= tt js2-TEMPLATE_HEAD)
9966 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9967 ((= tt js2-NO_SUBS_TEMPLATE)
9968 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9969 (t
9970 (js2-unget-token)
9971 (setq continue nil))))
9972 (if (>= js2-highlight-level 2)
9973 (js2-parse-highlight-member-expr-node pn))
9974 pn))
9975
9976 (defun js2-parse-tagged-template (tag-node tpl-node)
9977 "Parse tagged template expression."
9978 (let* ((beg (js2-node-pos tag-node))
9979 (pn (make-js2-tagged-template-node :beg beg
9980 :len (- (js2-current-token-end) beg)
9981 :tag tag-node
9982 :template tpl-node)))
9983 (js2-node-add-children pn tag-node tpl-node)
9984 pn))
9985
9986 (defun js2-parse-dot-query (pn)
9987 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9988 Last token parsed must be `js2-DOTQUERY'."
9989 (let ((pos (js2-node-pos pn))
9990 op-pos expr end)
9991 (js2-must-have-xml)
9992 (js2-set-requires-activation)
9993 (setq op-pos (js2-current-token-beg)
9994 expr (js2-parse-expr)
9995 end (js2-node-end expr)
9996 pn (make-js2-xml-dot-query-node :left pn
9997 :pos pos
9998 :op-pos op-pos
9999 :right expr))
10000 (js2-node-add-children pn
10001 (js2-xml-dot-query-node-left pn)
10002 (js2-xml-dot-query-node-right pn))
10003 (if (js2-must-match js2-RP "msg.no.paren")
10004 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10005 end (js2-current-token-end)))
10006 (setf (js2-node-len pn) (- end pos))
10007 pn))
10008
10009 (defun js2-parse-element-get (pn)
10010 "Parse an element-get expression, e.g. foo[bar].
10011 Last token parsed must be `js2-RB'."
10012 (let ((lb (js2-current-token-beg))
10013 (pos (js2-node-pos pn))
10014 rb expr)
10015 (setq expr (js2-parse-expr))
10016 (if (js2-must-match js2-RB "msg.no.bracket.index")
10017 (setq rb (js2-current-token-beg)))
10018 (setq pn (make-js2-elem-get-node :target pn
10019 :pos pos
10020 :element expr
10021 :lb (js2-relpos lb pos)
10022 :rb (js2-relpos rb pos)
10023 :len (- (js2-current-token-end) pos)))
10024 (js2-node-add-children pn
10025 (js2-elem-get-node-target pn)
10026 (js2-elem-get-node-element pn))
10027 pn))
10028
10029 (defun js2-highlight-function-call (token)
10030 (when (eq (js2-token-type token) js2-NAME)
10031 (js2-record-face 'js2-function-call token)))
10032
10033 (defun js2-parse-function-call (pn)
10034 (js2-highlight-function-call (js2-current-token))
10035 (js2-get-token)
10036 (let (args
10037 (pos (js2-node-pos pn)))
10038 (setq pn (make-js2-call-node :pos pos
10039 :target pn
10040 :lp (- (js2-current-token-beg) pos)))
10041 (js2-node-add-children pn (js2-call-node-target pn))
10042 ;; Add the arguments to pn, if any are supplied.
10043 (setf args (nreverse (js2-parse-argument-list))
10044 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10045 (js2-call-node-args pn) args)
10046 (apply #'js2-node-add-children pn args)
10047 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10048 pn))
10049
10050 (defun js2-parse-property-access (tt pn)
10051 "Parse a property access, XML descendants access, or XML attr access."
10052 (let ((member-type-flags 0)
10053 (dot-pos (js2-current-token-beg))
10054 (dot-len (if (= tt js2-DOTDOT) 2 1))
10055 name
10056 ref ; right side of . or .. operator
10057 result)
10058 (when (= tt js2-DOTDOT)
10059 (js2-must-have-xml)
10060 (setq member-type-flags js2-descendants-flag))
10061 (if (not js2-compiler-xml-available)
10062 (progn
10063 (js2-must-match-prop-name "msg.no.name.after.dot")
10064 (setq name (js2-create-name-node t js2-GETPROP)
10065 result (make-js2-prop-get-node :left pn
10066 :pos (js2-current-token-beg)
10067 :right name
10068 :len (js2-current-token-len)))
10069 (js2-node-add-children result pn name)
10070 result)
10071 ;; otherwise look for XML operators
10072 (setf result (if (= tt js2-DOT)
10073 (make-js2-prop-get-node)
10074 (make-js2-infix-node :type js2-DOTDOT))
10075 (js2-node-pos result) (js2-node-pos pn)
10076 (js2-infix-node-op-pos result) dot-pos
10077 (js2-infix-node-left result) pn ; do this after setting position
10078 tt (js2-get-prop-name-token))
10079 (cond
10080 ;; handles: name, ns::name, ns::*, ns::[expr]
10081 ((= tt js2-NAME)
10082 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10083 ;; handles: *, *::name, *::*, *::[expr]
10084 ((= tt js2-MUL)
10085 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10086 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10087 ((= tt js2-XMLATTR)
10088 (setq result (js2-parse-attribute-access)))
10089 (t
10090 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10091 (if ref
10092 (setf (js2-node-len result) (- (js2-node-end ref)
10093 (js2-node-pos result))
10094 (js2-infix-node-right result) ref))
10095 (if (js2-infix-node-p result)
10096 (js2-node-add-children result
10097 (js2-infix-node-left result)
10098 (js2-infix-node-right result)))
10099 result)))
10100
10101 (defun js2-parse-attribute-access ()
10102 "Parse an E4X XML attribute expression.
10103 This includes expressions of the forms:
10104
10105 @attr @ns::attr @ns::*
10106 @* @*::attr @*::*
10107 @[expr] @*::[expr] @ns::[expr]
10108
10109 Called if we peeked an '@' token."
10110 (let ((tt (js2-get-prop-name-token))
10111 (at-pos (js2-current-token-beg)))
10112 (cond
10113 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10114 ((= tt js2-NAME)
10115 (js2-parse-property-name at-pos nil 0))
10116 ;; handles: @*, @*::name, @*::*, @*::[expr]
10117 ((= tt js2-MUL)
10118 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10119 ;; handles @[expr]
10120 ((= tt js2-LB)
10121 (js2-parse-xml-elem-ref at-pos))
10122 (t
10123 (js2-report-error "msg.no.name.after.xmlAttr")
10124 ;; Avoid cascaded errors that happen if we make an error node here.
10125 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10126
10127 (defun js2-parse-property-name (at-pos s member-type-flags)
10128 "Check if :: follows name in which case it becomes qualified name.
10129
10130 AT-POS is a natural number if we just read an '@' token, else nil.
10131 S is the name or string that was matched: an identifier, 'throw' or '*'.
10132 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10133
10134 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10135 operator, or the name is followed by ::. For a plain name, returns a
10136 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10137 (let ((pos (or at-pos (js2-current-token-beg)))
10138 colon-pos
10139 (name (js2-create-name-node t (js2-current-token-type) s))
10140 ns tt pn)
10141 (catch 'return
10142 (when (js2-match-token js2-COLONCOLON)
10143 (setq ns name
10144 colon-pos (js2-current-token-beg)
10145 tt (js2-get-prop-name-token))
10146 (cond
10147 ;; handles name::name
10148 ((= tt js2-NAME)
10149 (setq name (js2-create-name-node)))
10150 ;; handles name::*
10151 ((= tt js2-MUL)
10152 (setq name (js2-create-name-node nil nil "*")))
10153 ;; handles name::[expr]
10154 ((= tt js2-LB)
10155 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10156 (t
10157 (js2-report-error "msg.no.name.after.coloncolon"))))
10158 (if (and (null ns) (zerop member-type-flags))
10159 name
10160 (prog1
10161 (setq pn
10162 (make-js2-xml-prop-ref-node :pos pos
10163 :len (- (js2-node-end name) pos)
10164 :at-pos at-pos
10165 :colon-pos colon-pos
10166 :propname name))
10167 (js2-node-add-children pn name))))))
10168
10169 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10170 "Parse the [expr] portion of an xml element reference.
10171 For instance, @[expr], @*::[expr], or ns::[expr]."
10172 (let* ((lb (js2-current-token-beg))
10173 (pos (or at-pos lb))
10174 rb
10175 (expr (js2-parse-expr))
10176 (end (js2-node-end expr))
10177 pn)
10178 (if (js2-must-match js2-RB "msg.no.bracket.index")
10179 (setq rb (js2-current-token-beg)
10180 end (js2-current-token-end)))
10181 (prog1
10182 (setq pn
10183 (make-js2-xml-elem-ref-node :pos pos
10184 :len (- end pos)
10185 :namespace namespace
10186 :colon-pos colon-pos
10187 :at-pos at-pos
10188 :expr expr
10189 :lb (js2-relpos lb pos)
10190 :rb (js2-relpos rb pos)))
10191 (js2-node-add-children pn namespace expr))))
10192
10193 (defun js2-parse-destruct-primary-expr ()
10194 (let ((js2-is-in-destructuring t))
10195 (js2-parse-primary-expr)))
10196
10197 (defun js2-parse-primary-expr ()
10198 "Parse a literal (leaf) expression of some sort.
10199 Includes complex literals such as functions, object-literals,
10200 array-literals, array comprehensions and regular expressions."
10201 (let (tt node)
10202 (setq tt (js2-current-token-type))
10203 (cond
10204 ((= tt js2-CLASS)
10205 (js2-parse-class-expr))
10206 ((= tt js2-FUNCTION)
10207 (js2-parse-function-expr))
10208 ((= tt js2-LB)
10209 (js2-parse-array-comp-or-literal))
10210 ((= tt js2-LC)
10211 (js2-parse-object-literal))
10212 ((= tt js2-LET)
10213 (js2-parse-let (js2-current-token-beg)))
10214 ((= tt js2-LP)
10215 (js2-parse-paren-expr-or-generator-comp))
10216 ((= tt js2-XMLATTR)
10217 (js2-must-have-xml)
10218 (js2-parse-attribute-access))
10219 ((= tt js2-NAME)
10220 (js2-parse-name tt))
10221 ((= tt js2-NUMBER)
10222 (setq node (make-js2-number-node))
10223 (when (and js2-in-use-strict-directive
10224 (= (js2-number-node-num-base node) 8))
10225 (js2-report-error "msg.no.octal.strict"))
10226 node)
10227 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10228 (make-js2-string-node :type tt))
10229 ((= tt js2-TEMPLATE_HEAD)
10230 (js2-parse-template-literal))
10231 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10232 ;; Got / or /= which in this context means a regexp literal
10233 (let ((px-pos (js2-current-token-beg))
10234 (flags (js2-read-regexp tt))
10235 (end (js2-current-token-end)))
10236 (prog1
10237 (make-js2-regexp-node :pos px-pos
10238 :len (- end px-pos)
10239 :value (js2-current-token-string)
10240 :flags flags)
10241 (js2-set-face px-pos end 'font-lock-string-face 'record)
10242 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10243 ((or (= tt js2-NULL)
10244 (= tt js2-THIS)
10245 (= tt js2-SUPER)
10246 (= tt js2-FALSE)
10247 (= tt js2-TRUE))
10248 (make-js2-keyword-node :type tt))
10249 ((= tt js2-TRIPLEDOT)
10250 ;; Likewise, only valid in an arrow function with a rest param.
10251 (if (and (js2-match-token js2-NAME)
10252 (js2-match-token js2-RP)
10253 (eq (js2-peek-token) js2-ARROW))
10254 (progn
10255 (js2-unget-token) ; Put back the right paren.
10256 ;; See the previous case.
10257 (make-js2-keyword-node :type js2-NULL))
10258 (js2-report-error "msg.syntax")
10259 (make-js2-error-node)))
10260 ((= tt js2-RESERVED)
10261 (js2-report-error "msg.reserved.id")
10262 (make-js2-name-node))
10263 ((= tt js2-ERROR)
10264 ;; the scanner or one of its subroutines reported the error.
10265 (make-js2-error-node))
10266 ((= tt js2-EOF)
10267 (let* ((px-pos (point-at-bol))
10268 (len (- js2-ts-cursor px-pos)))
10269 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10270 (make-js2-error-node :pos (1- js2-ts-cursor)))
10271 (t
10272 (js2-report-error "msg.syntax")
10273 (make-js2-error-node)))))
10274
10275 (defun js2-parse-template-literal ()
10276 (let ((beg (js2-current-token-beg))
10277 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10278 (tt js2-TEMPLATE_HEAD))
10279 (while (eq tt js2-TEMPLATE_HEAD)
10280 (push (js2-parse-expr) kids)
10281 (js2-must-match js2-RC "msg.syntax")
10282 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10283 (push (make-js2-string-node :type tt) kids))
10284 (setq kids (nreverse kids))
10285 (let ((tpl (make-js2-template-node :beg beg
10286 :len (- (js2-current-token-end) beg)
10287 :kids kids)))
10288 (apply #'js2-node-add-children tpl kids)
10289 tpl)))
10290
10291 (defun js2-parse-name (_tt)
10292 (let ((name (js2-current-token-string))
10293 node)
10294 (setq node (if js2-compiler-xml-available
10295 (js2-parse-property-name nil name 0)
10296 (js2-create-name-node 'check-activation nil name)))
10297 (if js2-highlight-external-variables
10298 (js2-record-name-node node))
10299 node))
10300
10301 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10302 (js2-add-strict-warning
10303 msg nil
10304 ;; back up from comma to beginning of line or array/objlit
10305 (max (if elems
10306 (js2-node-pos (car elems))
10307 pos)
10308 (save-excursion
10309 (goto-char comma-pos)
10310 (back-to-indentation)
10311 (point)))
10312 comma-pos))
10313
10314 (defun js2-parse-array-comp-or-literal ()
10315 (let ((pos (js2-current-token-beg)))
10316 (if (and (>= js2-language-version 200)
10317 (js2-match-token js2-FOR))
10318 (js2-parse-array-comp pos)
10319 (js2-parse-array-literal pos))))
10320
10321 (defun js2-parse-array-literal (pos)
10322 (let ((after-lb-or-comma t)
10323 after-comma tt elems pn
10324 (continue t))
10325 (unless js2-is-in-destructuring
10326 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10327 (while continue
10328 (setq tt (js2-get-token))
10329 (cond
10330 ;; comma
10331 ((= tt js2-COMMA)
10332 (setq after-comma (js2-current-token-end))
10333 (if (not after-lb-or-comma)
10334 (setq after-lb-or-comma t)
10335 (push nil elems)))
10336 ;; end of array
10337 ((or (= tt js2-RB)
10338 (= tt js2-EOF)) ; prevent infinite loop
10339 (if (= tt js2-EOF)
10340 (js2-report-error "msg.no.bracket.arg" nil pos))
10341 (when (and after-comma (< js2-language-version 170))
10342 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10343 pos (remove nil elems) after-comma))
10344 (setq continue nil
10345 pn (make-js2-array-node :pos pos
10346 :len (- js2-ts-cursor pos)
10347 :elems (nreverse elems)))
10348 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10349 ;; destructuring binding
10350 (js2-is-in-destructuring
10351 (push (if (or (= tt js2-LC)
10352 (= tt js2-LB)
10353 (= tt js2-NAME))
10354 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10355 (js2-parse-destruct-primary-expr)
10356 ;; invalid pattern
10357 (js2-report-error "msg.bad.var")
10358 (make-js2-error-node))
10359 elems)
10360 (setq after-lb-or-comma nil
10361 after-comma nil))
10362 ;; array comp
10363 ((and (>= js2-language-version 170)
10364 (= tt js2-FOR) ; check for array comprehension
10365 (not after-lb-or-comma) ; "for" can't follow a comma
10366 elems ; must have at least 1 element
10367 (not (cdr elems))) ; but no 2nd element
10368 (js2-unget-token)
10369 (setf continue nil
10370 pn (js2-parse-legacy-array-comp (car elems) pos)))
10371 ;; another element
10372 (t
10373 (unless after-lb-or-comma
10374 (js2-report-error "msg.no.bracket.arg"))
10375 (if (and (= tt js2-TRIPLEDOT)
10376 (>= js2-language-version 200))
10377 ;; spread operator
10378 (push (js2-make-unary tt 'js2-parse-assign-expr)
10379 elems)
10380 (js2-unget-token)
10381 (push (js2-parse-assign-expr) elems))
10382 (setq after-lb-or-comma nil
10383 after-comma nil))))
10384 (unless js2-is-in-destructuring
10385 (js2-pop-scope))
10386 pn))
10387
10388 (defun js2-parse-legacy-array-comp (expr pos)
10389 "Parse a legacy array comprehension (JavaScript 1.7).
10390 EXPR is the first expression after the opening left-bracket.
10391 POS is the beginning of the LB token preceding EXPR.
10392 We should have just parsed the 'for' keyword before calling this function."
10393 (let ((current-scope js2-current-scope)
10394 loops first filter result)
10395 (unwind-protect
10396 (progn
10397 (while (js2-match-token js2-FOR)
10398 (let ((loop (make-js2-comp-loop-node)))
10399 (js2-push-scope loop)
10400 (push loop loops)
10401 (js2-parse-comp-loop loop)))
10402 ;; First loop takes expr scope's parent.
10403 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10404 (js2-scope-parent-scope current-scope))
10405 ;; Set expr scope's parent to the last loop.
10406 (setf (js2-scope-parent-scope current-scope) (car loops))
10407 (if (/= (js2-get-token) js2-IF)
10408 (js2-unget-token)
10409 (setq filter (js2-parse-condition))))
10410 (dotimes (_ (1- (length loops)))
10411 (js2-pop-scope)))
10412 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10413 (setq result (make-js2-comp-node :pos pos
10414 :len (- js2-ts-cursor pos)
10415 :result expr
10416 :loops (nreverse loops)
10417 :filters (and filter (list (car filter)))
10418 :form 'LEGACY_ARRAY))
10419 ;; Set comp loop's parent to the last loop.
10420 ;; TODO: Get rid of the bogus expr scope.
10421 (setf (js2-scope-parent-scope result) first)
10422 (apply #'js2-node-add-children result expr (car filter)
10423 (js2-comp-node-loops result))
10424 result))
10425
10426 (defun js2-parse-array-comp (pos)
10427 "Parse an ES6 array comprehension.
10428 POS is the beginning of the LB token.
10429 We should have just parsed the 'for' keyword before calling this function."
10430 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10431 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10432 pn))
10433
10434 (defun js2-parse-generator-comp (pos)
10435 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10436 (js2-current-script-or-fn
10437 (make-js2-function-node :generator-type 'COMPREHENSION))
10438 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10439 (js2-must-match js2-RP "msg.no.paren" pos)
10440 pn))
10441
10442 (defun js2-parse-comprehension (pos form)
10443 (let (loops filters expr result last)
10444 (unwind-protect
10445 (progn
10446 (js2-unget-token)
10447 (while (js2-match-token js2-FOR)
10448 (let ((loop (make-js2-comp-loop-node)))
10449 (js2-push-scope loop)
10450 (push loop loops)
10451 (js2-parse-comp-loop loop)))
10452 (while (js2-match-token js2-IF)
10453 (push (car (js2-parse-condition)) filters))
10454 (setq expr (js2-parse-assign-expr))
10455 (setq last (car loops)))
10456 (dolist (_ loops)
10457 (js2-pop-scope)))
10458 (setq result (make-js2-comp-node :pos pos
10459 :len (- js2-ts-cursor pos)
10460 :result expr
10461 :loops (nreverse loops)
10462 :filters (nreverse filters)
10463 :form form))
10464 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10465 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10466 (setf (js2-scope-parent-scope result) last)
10467 result))
10468
10469 (defun js2-parse-comp-loop (pn &optional only-of-p)
10470 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10471 The current token should be the initial FOR.
10472 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10473 (let ((pos (js2-comp-loop-node-pos pn))
10474 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10475 (when (and (not only-of-p) (js2-match-token js2-NAME))
10476 (if (string= (js2-current-token-string) "each")
10477 (progn
10478 (setq foreach-p t
10479 each-pos (- (js2-current-token-beg) pos)) ; relative
10480 (js2-record-face 'font-lock-keyword-face))
10481 (js2-report-error "msg.no.paren.for")))
10482 (if (js2-must-match js2-LP "msg.no.paren.for")
10483 (setq lp (- (js2-current-token-beg) pos)))
10484 (setq tt (js2-peek-token))
10485 (cond
10486 ((or (= tt js2-LB)
10487 (= tt js2-LC))
10488 (js2-get-token)
10489 (setq iter (js2-parse-destruct-primary-expr))
10490 (js2-define-destruct-symbols iter js2-LET
10491 'font-lock-variable-name-face t))
10492 ((js2-match-token js2-NAME)
10493 (setq iter (js2-create-name-node)))
10494 (t
10495 (js2-report-error "msg.bad.var")))
10496 ;; Define as a let since we want the scope of the variable to
10497 ;; be restricted to the array comprehension
10498 (if (js2-name-node-p iter)
10499 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10500 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10501 (and (>= js2-language-version 200)
10502 (js2-match-contextual-kwd "of")
10503 (setq forof-p t)))
10504 (setq in-pos (- (js2-current-token-beg) pos))
10505 (js2-report-error "msg.in.after.for.name"))
10506 (setq obj (js2-parse-expr))
10507 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10508 (setq rp (- (js2-current-token-beg) pos)))
10509 (setf (js2-node-pos pn) pos
10510 (js2-node-len pn) (- js2-ts-cursor pos)
10511 (js2-comp-loop-node-iterator pn) iter
10512 (js2-comp-loop-node-object pn) obj
10513 (js2-comp-loop-node-in-pos pn) in-pos
10514 (js2-comp-loop-node-each-pos pn) each-pos
10515 (js2-comp-loop-node-foreach-p pn) foreach-p
10516 (js2-comp-loop-node-forof-p pn) forof-p
10517 (js2-comp-loop-node-lp pn) lp
10518 (js2-comp-loop-node-rp pn) rp)
10519 (js2-node-add-children pn iter obj)
10520 pn))
10521
10522 (defun js2-parse-class-stmt ()
10523 (let ((pos (js2-current-token-beg))
10524 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10525 (name (js2-create-name-node t)))
10526 (js2-set-face (js2-node-pos name) (js2-node-end name)
10527 'font-lock-function-name-face 'record)
10528 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10529 (js2-define-symbol js2-FUNCTION
10530 (js2-name-node-name name)
10531 node)
10532 node)))
10533
10534 (defun js2-parse-class-expr ()
10535 (let ((pos (js2-current-token-beg))
10536 name)
10537 (when (js2-match-token js2-NAME)
10538 (setq name (js2-create-name-node t)))
10539 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10540
10541 (defun js2-parse-class (pos form name)
10542 ;; class X [extends ...] {
10543 (let (pn elems extends)
10544 (if (js2-match-token js2-EXTENDS)
10545 (if (= (js2-peek-token) js2-LC)
10546 (js2-report-error "msg.missing.extends")
10547 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10548 (setq extends (js2-parse-assign-expr))
10549 (if (not extends)
10550 (js2-report-error "msg.bad.extends"))))
10551 (js2-must-match js2-LC "msg.no.brace.class")
10552 (setq elems (js2-parse-object-literal-elems t)
10553 pn (make-js2-class-node :pos pos
10554 :len (- js2-ts-cursor pos)
10555 :form form
10556 :name name
10557 :extends extends
10558 :elems elems))
10559 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10560 pn))
10561
10562 (defun js2-parse-object-literal ()
10563 (let* ((pos (js2-current-token-beg))
10564 (elems (js2-parse-object-literal-elems))
10565 (result (make-js2-object-node :pos pos
10566 :len (- js2-ts-cursor pos)
10567 :elems elems)))
10568 (apply #'js2-node-add-children result (js2-object-node-elems result))
10569 result))
10570
10571 (defun js2-property-key-string (property-node)
10572 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10573 `js2-getter-setter-node') as a string, or nil if it can't be
10574 represented as a string (e.g., the key is computed by an
10575 expression)."
10576 (let ((key (js2-infix-node-left property-node)))
10577 (cond
10578 ((js2-name-node-p key)
10579 (js2-name-node-name key))
10580 ((js2-string-node-p key)
10581 (js2-string-node-value key))
10582 ((js2-number-node-p key)
10583 (js2-number-node-value key)))))
10584
10585 (defun js2-parse-object-literal-elems (&optional class-p)
10586 (let ((pos (js2-current-token-beg))
10587 (static nil)
10588 (continue t)
10589 tt elems elem
10590 elem-key-string previous-elem-key-string
10591 after-comma previous-token)
10592 (while continue
10593 (setq tt (js2-get-prop-name-token)
10594 static nil
10595 elem nil
10596 previous-token nil)
10597 ;; Handle 'static' keyword only if we're in a class
10598 (when (and class-p (= js2-NAME tt)
10599 (string= "static" (js2-current-token-string)))
10600 (js2-record-face 'font-lock-keyword-face)
10601 (setq static t
10602 tt (js2-get-prop-name-token)))
10603 ;; Handle generator * before the property name for in-line functions
10604 (when (and (>= js2-language-version 200)
10605 (= js2-MUL tt))
10606 (setq previous-token (js2-current-token)
10607 tt (js2-get-prop-name-token)))
10608 ;; Handle 'get' or 'set' keywords
10609 (let ((prop (js2-current-token-string)))
10610 (when (and (>= js2-language-version 200)
10611 (= js2-NAME tt)
10612 (or (string= prop "get")
10613 (string= prop "set"))
10614 (member (js2-peek-token)
10615 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10616 (setq previous-token (js2-current-token)
10617 tt (js2-get-prop-name-token))))
10618 (cond
10619 ;; Found a property (of any sort)
10620 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10621 (setq after-comma nil
10622 elem (js2-parse-named-prop tt pos previous-token))
10623 (if (and (null elem)
10624 (not js2-recover-from-parse-errors))
10625 (setq continue nil)))
10626 ;; Break out of loop, and handle trailing commas.
10627 ((or (= tt js2-RC)
10628 (= tt js2-EOF))
10629 (js2-unget-token)
10630 (setq continue nil)
10631 (if after-comma
10632 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10633 pos elems after-comma)))
10634 (t
10635 (js2-report-error "msg.bad.prop")
10636 (unless js2-recover-from-parse-errors
10637 (setq continue nil)))) ; end switch
10638 ;; Handle static for classes' codegen.
10639 (if static
10640 (if elem (js2-node-set-prop elem 'STATIC t)
10641 (js2-report-error "msg.unexpected.static")))
10642 ;; Handle commas, depending on class-p.
10643 (let ((tok (js2-get-prop-name-token)))
10644 (if (eq tok js2-COMMA)
10645 (if class-p
10646 (js2-report-error "msg.class.unexpected.comma")
10647 (setq after-comma (js2-current-token-end)))
10648 (js2-unget-token)
10649 (unless class-p (setq continue nil))))
10650 (when elem
10651 (when (and js2-in-use-strict-directive
10652 (setq elem-key-string (js2-property-key-string elem))
10653 (cl-some
10654 (lambda (previous-elem)
10655 (and (setq previous-elem-key-string
10656 (js2-property-key-string previous-elem))
10657 (string= previous-elem-key-string elem-key-string)))
10658 elems))
10659 (js2-report-error "msg.dup.obj.lit.prop.strict"
10660 elem-key-string
10661 (js2-node-abs-pos (js2-infix-node-left elem))
10662 (js2-node-len (js2-infix-node-left elem))))
10663 ;; Append any parsed element.
10664 (push elem elems))) ; end loop
10665 (js2-must-match js2-RC "msg.no.brace.prop")
10666 (nreverse elems)))
10667
10668 (defun js2-parse-named-prop (tt pos previous-token)
10669 "Parse a name, string, or getter/setter object property.
10670 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10671 (let ((key (cond
10672 ;; Literal string keys: {'foo': 'bar'}
10673 ((= tt js2-STRING)
10674 (make-js2-string-node))
10675 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10676 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10677 ((and (= tt js2-LB)
10678 (>= js2-language-version 200))
10679 (prog1 (js2-parse-expr)
10680 (js2-must-match js2-RB "msg.missing.computed.rb")))
10681 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10682 ((= tt js2-NUMBER)
10683 (make-js2-number-node))
10684 ;; Unquoted names: {foo: 12}
10685 ((= tt js2-NAME)
10686 (js2-create-name-node))
10687 ;; Anything else is an error
10688 (t (js2-report-error "msg.bad.prop"))))
10689 (prop (and previous-token (js2-token-string previous-token)))
10690 (property-type (when previous-token
10691 (if (= (js2-token-type previous-token) js2-MUL)
10692 "*"
10693 (js2-token-string previous-token)))))
10694 (when (or (string= prop "get")
10695 (string= prop "set"))
10696 (js2-set-face (js2-token-beg previous-token)
10697 (js2-token-end previous-token)
10698 'font-lock-keyword-face 'record)) ; get/set
10699 (cond
10700 ;; method definition: {f() {...}}
10701 ((and (= (js2-peek-token) js2-LP)
10702 (>= js2-language-version 200))
10703 (when (js2-name-node-p key) ; highlight function name properties
10704 (js2-record-face 'font-lock-function-name-face))
10705 (js2-parse-getter-setter-prop pos key property-type))
10706 ;; regular prop
10707 (t
10708 (let ((beg (js2-current-token-beg))
10709 (end (js2-current-token-end))
10710 (expr (js2-parse-plain-property key)))
10711 (when (and (= tt js2-NAME)
10712 (not js2-is-in-destructuring)
10713 js2-highlight-external-variables
10714 (js2-node-get-prop expr 'SHORTHAND))
10715 (js2-record-name-node key))
10716 (js2-set-face beg end
10717 (if (js2-function-node-p
10718 (js2-object-prop-node-right expr))
10719 'font-lock-function-name-face
10720 'font-lock-variable-name-face)
10721 'record)
10722 expr)))))
10723
10724 (defun js2-parse-plain-property (prop)
10725 "Parse a non-getter/setter property in an object literal.
10726 PROP is the node representing the property: a number, name,
10727 string or expression."
10728 (let* ((tt (js2-get-token))
10729 (pos (js2-node-pos prop))
10730 colon expr result)
10731 (cond
10732 ;; Abbreviated property, as in {foo, bar}
10733 ((and (>= js2-language-version 200)
10734 (or (= tt js2-COMMA)
10735 (= tt js2-RC))
10736 (not (js2-number-node-p prop)))
10737 (js2-unget-token)
10738 (setq result (make-js2-object-prop-node
10739 :pos pos
10740 :left prop
10741 :right prop
10742 :op-pos (js2-current-token-len)))
10743 (js2-node-add-children result prop)
10744 (js2-node-set-prop result 'SHORTHAND t)
10745 result)
10746 ;; Normal property
10747 (t
10748 (if (= tt js2-COLON)
10749 (setq colon (- (js2-current-token-beg) pos)
10750 expr (js2-parse-assign-expr))
10751 (js2-report-error "msg.no.colon.prop")
10752 (setq expr (make-js2-error-node)))
10753 (setq result (make-js2-object-prop-node
10754 :pos pos
10755 ;; don't include last consumed token in length
10756 :len (- (+ (js2-node-pos expr)
10757 (js2-node-len expr))
10758 pos)
10759 :left prop
10760 :right expr
10761 :op-pos colon))
10762 (js2-node-add-children result prop expr)
10763 result))))
10764
10765 (defun js2-parse-getter-setter-prop (pos prop type-string)
10766 "Parse getter or setter property in an object literal.
10767 JavaScript syntax is:
10768
10769 { get foo() {...}, set foo(x) {...} }
10770
10771 and expression closure style is also supported
10772
10773 { get foo() x, set foo(x) _x = x }
10774
10775 POS is the start position of the `get' or `set' keyword.
10776 PROP is the `js2-name-node' representing the property name.
10777 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10778 (let ((type (cond
10779 ((string= "get" type-string) js2-GET)
10780 ((string= "set" type-string) js2-SET)
10781 (t js2-FUNCTION)))
10782 result end
10783 (fn (js2-parse-function-expr)))
10784 ;; it has to be an anonymous function, as we already parsed the name
10785 (if (/= (js2-node-type fn) js2-FUNCTION)
10786 (js2-report-error "msg.bad.prop")
10787 (if (cl-plusp (length (js2-function-name fn)))
10788 (js2-report-error "msg.bad.prop")))
10789 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10790 (when (string= type-string "*")
10791 (setf (js2-function-node-generator-type fn) 'STAR))
10792 (setq end (js2-node-end fn)
10793 result (make-js2-getter-setter-node :type type
10794 :pos pos
10795 :len (- end pos)
10796 :left prop
10797 :right fn))
10798 (js2-node-add-children result prop fn)
10799 result))
10800
10801 (defun js2-create-name-node (&optional check-activation-p token string)
10802 "Create a name node using the current token and, optionally, STRING.
10803 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10804 (let* ((beg (js2-current-token-beg))
10805 (tt (js2-current-token-type))
10806 (s (or string
10807 (if (= js2-NAME tt)
10808 (js2-current-token-string)
10809 (js2-tt-name tt))))
10810 name)
10811 (setq name (make-js2-name-node :pos beg
10812 :name s
10813 :len (length s)))
10814 (if check-activation-p
10815 (js2-check-activation-name s (or token js2-NAME)))
10816 name))
10817
10818 ;;; Indentation support (bouncing)
10819
10820 ;; In recent-enough Emacs, we reuse the indentation code from
10821 ;; `js-mode'. To continue support for the older versions, some code
10822 ;; that was here previously was moved to `js2-old-indent.el'.
10823
10824 ;; Whichever indenter is used, it's often "wrong", however, and needs
10825 ;; to be overridden. The right long-term solution is probably to
10826 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
10827 ;; of coding. Even when a parse tree from `js2-parse' is present,
10828 ;; which is not true at the moment the user is typing, computing
10829 ;; indentation is still thousands of lines of code to handle every
10830 ;; possible syntactic edge case.
10831
10832 ;; In the meantime, the compromise solution is that we offer a "bounce
10833 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10834 ;; current line indent among various likely guess points. This approach
10835 ;; is far from perfect, but should at least make it slightly easier to
10836 ;; move the line towards its desired indentation when manually
10837 ;; overriding Karl's heuristic nesting guesser.
10838
10839 (defun js2-backward-sws ()
10840 "Move backward through whitespace and comments."
10841 (interactive)
10842 (while (forward-comment -1)))
10843
10844 (defun js2-forward-sws ()
10845 "Move forward through whitespace and comments."
10846 (interactive)
10847 (while (forward-comment 1)))
10848
10849 (defun js2-arglist-close ()
10850 "Return non-nil if we're on a line beginning with a close-paren/brace."
10851 (save-excursion
10852 (goto-char (point-at-bol))
10853 (js2-forward-sws)
10854 (looking-at "[])}]")))
10855
10856 (defun js2-indent-looks-like-label-p ()
10857 (goto-char (point-at-bol))
10858 (js2-forward-sws)
10859 (looking-at (concat js2-mode-identifier-re ":")))
10860
10861 (defun js2-indent-in-objlit-p (parse-status)
10862 "Return non-nil if this looks like an object-literal entry."
10863 (let ((start (nth 1 parse-status)))
10864 (and
10865 start
10866 (save-excursion
10867 (and (zerop (forward-line -1))
10868 (not (< (point) start)) ; crossed a {} boundary
10869 (js2-indent-looks-like-label-p)))
10870 (save-excursion
10871 (js2-indent-looks-like-label-p)))))
10872
10873 ;; If prev line looks like foobar({ then we're passing an object
10874 ;; literal to a function call, and people pretty much always want to
10875 ;; de-dent back to the previous line, so move the 'basic-offset'
10876 ;; position to the front.
10877 (defun js2-indent-objlit-arg-p (parse-status)
10878 (save-excursion
10879 (back-to-indentation)
10880 (js2-backward-sws)
10881 (and (eq (1- (point)) (nth 1 parse-status))
10882 (eq (char-before) ?{)
10883 (progn
10884 (forward-char -1)
10885 (skip-chars-backward " \t")
10886 (eq (char-before) ?\()))))
10887
10888 (defun js2-indent-case-block-p ()
10889 (save-excursion
10890 (back-to-indentation)
10891 (js2-backward-sws)
10892 (goto-char (point-at-bol))
10893 (skip-chars-forward " \t")
10894 (looking-at "case\\s-.+:")))
10895
10896 (defun js2-bounce-indent (normal-col parse-status &optional backward)
10897 "Cycle among alternate computed indentation positions.
10898 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10899 of the buffer to the current point. NORMAL-COL is the indentation
10900 column computed by the heuristic guesser based on current paren,
10901 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10902 in reverse."
10903 (let ((cur-indent (current-indentation))
10904 (old-buffer-undo-list buffer-undo-list)
10905 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10906 (current-line (save-excursion
10907 (forward-line 0) ; move to bol
10908 (1+ (count-lines (point-min) (point)))))
10909 positions pos main-pos anchor arglist-cont same-indent
10910 basic-offset computed-pos)
10911 ;; temporarily don't record undo info, if user requested this
10912 (when js2-mode-indent-inhibit-undo
10913 (setq buffer-undo-list t))
10914 (unwind-protect
10915 (progn
10916 ;; First likely point: indent from beginning of previous code line
10917 (push (setq basic-offset
10918 (+ (save-excursion
10919 (back-to-indentation)
10920 (js2-backward-sws)
10921 (back-to-indentation)
10922 (current-column))
10923 js2-basic-offset))
10924 positions)
10925
10926 ;; (First + epsilon) likely point: indent 2x from beginning of
10927 ;; previous code line. Google does it this way.
10928 (push (setq basic-offset
10929 (+ (save-excursion
10930 (back-to-indentation)
10931 (js2-backward-sws)
10932 (back-to-indentation)
10933 (current-column))
10934 (* 2 js2-basic-offset)))
10935 positions)
10936
10937 ;; Second likely point: indent from assign-expr RHS. This
10938 ;; is just a crude guess based on finding " = " on the previous
10939 ;; line containing actual code.
10940 (setq pos (save-excursion
10941 (forward-line -1)
10942 (goto-char (point-at-bol))
10943 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10944 (point-at-eol) t)
10945 (goto-char (match-end 1))
10946 (skip-chars-forward " \t\r\n")
10947 (current-column))))
10948 (when pos
10949 (cl-incf pos js2-basic-offset)
10950 (push pos positions))
10951
10952 ;; Third likely point: same indent as previous line of code.
10953 ;; Make it the first likely point if we're not on an
10954 ;; arglist-close line and previous line ends in a comma, or
10955 ;; both this line and prev line look like object-literal
10956 ;; elements.
10957 (setq pos (save-excursion
10958 (goto-char (point-at-bol))
10959 (js2-backward-sws)
10960 (back-to-indentation)
10961 (prog1
10962 (current-column)
10963 ;; while we're here, look for trailing comma
10964 (if (save-excursion
10965 (goto-char (point-at-eol))
10966 (js2-backward-sws)
10967 (eq (char-before) ?,))
10968 (setq arglist-cont (1- (point)))))))
10969 (when pos
10970 (if (and (or arglist-cont
10971 (js2-indent-in-objlit-p parse-status))
10972 (not (js2-arglist-close)))
10973 (setq same-indent pos))
10974 (push pos positions))
10975
10976 ;; Fourth likely point: first preceding code with less indentation.
10977 ;; than the immediately preceding code line.
10978 (setq pos (save-excursion
10979 (back-to-indentation)
10980 (js2-backward-sws)
10981 (back-to-indentation)
10982 (setq anchor (current-column))
10983 (while (and (zerop (forward-line -1))
10984 (>= (progn
10985 (back-to-indentation)
10986 (current-column))
10987 anchor)))
10988 (setq pos (current-column))))
10989 (push pos positions)
10990
10991 ;; nesting-heuristic position, main by default
10992 (push (setq main-pos normal-col) positions)
10993
10994 ;; delete duplicates and sort positions list
10995 (setq positions (sort (delete-dups positions) '<))
10996
10997 ;; comma-list continuation lines: prev line indent takes precedence
10998 (if same-indent
10999 (setq main-pos same-indent))
11000
11001 ;; common special cases where we want to indent in from previous line
11002 (if (or (js2-indent-case-block-p)
11003 (js2-indent-objlit-arg-p parse-status))
11004 (setq main-pos basic-offset))
11005
11006 ;; if bouncing backward, reverse positions list
11007 (if backward
11008 (setq positions (reverse positions)))
11009
11010 ;; record whether we're already sitting on one of the alternatives
11011 (setq pos (member cur-indent positions))
11012
11013 (cond
11014 ;; case 0: we're one one of the alternatives and this is the
11015 ;; first time they've pressed TAB on this line (best-guess).
11016 ((and js2-mode-indent-ignore-first-tab
11017 pos
11018 ;; first time pressing TAB on this line?
11019 (not (eq js2-mode-last-indented-line current-line)))
11020 ;; do nothing
11021 (setq computed-pos nil))
11022 ;; case 1: only one computed position => use it
11023 ((null (cdr positions))
11024 (setq computed-pos 0))
11025 ;; case 2: not on any of the computed spots => use main spot
11026 ((not pos)
11027 (setq computed-pos (js2-position main-pos positions)))
11028 ;; case 3: on last position: cycle to first position
11029 ((null (cdr pos))
11030 (setq computed-pos 0))
11031 ;; case 4: on intermediate position: cycle to next position
11032 (t
11033 (setq computed-pos (js2-position (cl-second pos) positions))))
11034
11035 ;; see if any hooks want to indent; otherwise we do it
11036 (cl-loop with result = nil
11037 for hook in js2-indent-hook
11038 while (null result)
11039 do
11040 (setq result (funcall hook positions computed-pos))
11041 finally do
11042 (unless (or result (null computed-pos))
11043 (indent-line-to (nth computed-pos positions)))))
11044
11045 ;; finally
11046 (if js2-mode-indent-inhibit-undo
11047 (setq buffer-undo-list old-buffer-undo-list))
11048 ;; see commentary for `js2-mode-last-indented-line'
11049 (setq js2-mode-last-indented-line current-line))))
11050
11051 (defun js2-1-line-comment-continuation-p ()
11052 "Return t if we're in a 1-line comment continuation.
11053 If so, we don't ever want to use bounce-indent."
11054 (save-excursion
11055 (and (progn
11056 (forward-line 0)
11057 (looking-at "\\s-*//"))
11058 (progn
11059 (forward-line -1)
11060 (forward-line 0)
11061 (when (looking-at "\\s-*$")
11062 (js2-backward-sws)
11063 (forward-line 0))
11064 (looking-at "\\s-*//")))))
11065
11066 (defun js2-indent-bounce (&optional backward)
11067 "Indent the current line, bouncing between several positions."
11068 (interactive)
11069 (let (parse-status offset indent-col
11070 ;; Don't whine about errors/warnings when we're indenting.
11071 ;; This has to be set before calling parse-partial-sexp below.
11072 (inhibit-point-motion-hooks t))
11073 (setq parse-status (save-excursion
11074 (syntax-ppss (point-at-bol)))
11075 offset (- (point) (save-excursion
11076 (back-to-indentation)
11077 (point))))
11078 ;; Don't touch multiline strings.
11079 (unless (nth 3 parse-status)
11080 (setq indent-col (js2-proper-indentation parse-status))
11081 (cond
11082 ;; It doesn't work well on first line of buffer.
11083 ((and (not (nth 4 parse-status))
11084 (not (js2-same-line (point-min)))
11085 (not (js2-1-line-comment-continuation-p)))
11086 (js2-bounce-indent indent-col parse-status backward))
11087 ;; just indent to the guesser's likely spot
11088 (t (indent-line-to indent-col)))
11089 (when (cl-plusp offset)
11090 (forward-char offset)))))
11091
11092 (defun js2-indent-bounce-backward ()
11093 "Indent the current line, bouncing between positions in reverse."
11094 (interactive)
11095 (js2-indent-bounce t))
11096
11097 (defun js2-indent-region (start end)
11098 "Indent the region, but don't use bounce indenting."
11099 (let ((js2-bounce-indent-p nil)
11100 (indent-region-function nil)
11101 (after-change-functions (remq 'js2-mode-edit
11102 after-change-functions)))
11103 (indent-region start end nil) ; nil for byte-compiler
11104 (js2-mode-edit start end (- end start))))
11105
11106 (defvar js2-minor-mode-map
11107 (let ((map (make-sparse-keymap)))
11108 (define-key map (kbd "C-c C-`") #'js2-next-error)
11109 (define-key map [mouse-1] #'js2-mode-show-node)
11110 map)
11111 "Keymap used when `js2-minor-mode' is active.")
11112
11113 ;;;###autoload
11114 (define-minor-mode js2-minor-mode
11115 "Minor mode for running js2 as a background linter.
11116 This allows you to use a different major mode for JavaScript editing,
11117 such as `js-mode', while retaining the asynchronous error/warning
11118 highlighting features of `js2-mode'."
11119 :group 'js2-mode
11120 :lighter " js-lint"
11121 (if (derived-mode-p 'js2-mode)
11122 (setq js2-minor-mode nil)
11123 (if js2-minor-mode
11124 (js2-minor-mode-enter)
11125 (js2-minor-mode-exit))))
11126
11127 (defun js2-minor-mode-enter ()
11128 "Initialization for `js2-minor-mode'."
11129 (set (make-local-variable 'max-lisp-eval-depth)
11130 (max max-lisp-eval-depth 3000))
11131 (setq next-error-function #'js2-next-error)
11132 (js2-set-default-externs)
11133 ;; Experiment: make reparse-delay longer for longer files.
11134 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11135 (setq js2-idle-timer-delay
11136 (* js2-idle-timer-delay
11137 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11138 (setq js2-mode-buffer-dirty-p t
11139 js2-mode-parsing nil)
11140 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11141 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11142 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11143 (when js2-include-jslint-globals
11144 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11145 (run-hooks 'js2-init-hook)
11146 (js2-reparse))
11147
11148 (defun js2-minor-mode-exit ()
11149 "Turn off `js2-minor-mode'."
11150 (setq next-error-function nil)
11151 (remove-hook 'after-change-functions #'js2-mode-edit t)
11152 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11153 (when js2-mode-node-overlay
11154 (delete-overlay js2-mode-node-overlay)
11155 (setq js2-mode-node-overlay nil))
11156 (js2-remove-overlays)
11157 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11158 (setq js2-mode-ast nil))
11159
11160 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11161 (make-variable-buffer-local 'js2-source-buffer)
11162
11163 (cl-defun js2-display-error-list ()
11164 "Display a navigable buffer listing parse errors/warnings."
11165 (interactive)
11166 (unless (js2-have-errors-p)
11167 (message "No errors")
11168 (cl-return-from js2-display-error-list))
11169 (cl-labels ((annotate-list
11170 (lst type)
11171 "Add diagnostic TYPE and line number to errs list"
11172 (mapcar (lambda (err)
11173 (list err type (line-number-at-pos (nth 1 err))))
11174 lst)))
11175 (let* ((srcbuf (current-buffer))
11176 (errbuf (get-buffer-create "*js-lint*"))
11177 (errors (annotate-list
11178 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11179 'js2-error)) ; must be a valid face name
11180 (warnings (annotate-list
11181 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11182 'js2-warning)) ; must be a valid face name
11183 (all-errs (sort (append errors warnings)
11184 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11185 (with-current-buffer errbuf
11186 (let ((inhibit-read-only t))
11187 (erase-buffer)
11188 (dolist (err all-errs)
11189 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11190 (insert-text-button
11191 (format "line %d: %s" line (js2-get-msg msg-key))
11192 'face type
11193 'follow-link "\C-m"
11194 'action 'js2-error-buffer-jump
11195 'js2-msg (js2-get-msg msg-key)
11196 'js2-pos beg)
11197 (insert "\n"))))
11198 (js2-error-buffer-mode)
11199 (setq js2-source-buffer srcbuf)
11200 (pop-to-buffer errbuf)
11201 (goto-char (point-min))
11202 (unless (eobp)
11203 (js2-error-buffer-view))))))
11204
11205 (defvar js2-error-buffer-mode-map
11206 (let ((map (make-sparse-keymap)))
11207 (define-key map "n" #'js2-error-buffer-next)
11208 (define-key map "p" #'js2-error-buffer-prev)
11209 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11210 (define-key map "o" #'js2-error-buffer-view)
11211 (define-key map "q" #'js2-error-buffer-quit)
11212 map)
11213 "Keymap used for js2 diagnostics buffers.")
11214
11215 (define-derived-mode js2-error-buffer-mode special-mode "JS Lint Diagnostics"
11216 "Major mode for js2 diagnostics buffers.
11217 Selecting an error will jump it to the corresponding source-buffer error.
11218 \\{js2-error-buffer-mode-map}"
11219 (setq truncate-lines t)
11220 (set-buffer-modified-p nil)
11221 (setq buffer-read-only t))
11222
11223 (defun js2-error-buffer-next ()
11224 "Move to next error and view it."
11225 (interactive)
11226 (when (zerop (forward-line 1))
11227 (js2-error-buffer-view)))
11228
11229 (defun js2-error-buffer-prev ()
11230 "Move to previous error and view it."
11231 (interactive)
11232 (when (zerop (forward-line -1))
11233 (js2-error-buffer-view)))
11234
11235 (defun js2-error-buffer-quit ()
11236 "Kill the current buffer."
11237 (interactive)
11238 (kill-buffer))
11239
11240 (defun js2-error-buffer-jump (&rest ignored)
11241 "Jump cursor to current error in source buffer."
11242 (interactive)
11243 (when (js2-error-buffer-view)
11244 (pop-to-buffer js2-source-buffer)))
11245
11246 (defun js2-error-buffer-view ()
11247 "Scroll source buffer to show error at current line."
11248 (interactive)
11249 (cond
11250 ((not (derived-mode-p 'js2-error-buffer-mode))
11251 (message "Not in a js2 errors buffer"))
11252 ((not (buffer-live-p js2-source-buffer))
11253 (message "Source buffer has been killed"))
11254 ((not (wholenump (get-text-property (point) 'js2-pos)))
11255 (message "There does not seem to be an error here"))
11256 (t
11257 (let ((pos (get-text-property (point) 'js2-pos))
11258 (msg (get-text-property (point) 'js2-msg)))
11259 (save-selected-window
11260 (pop-to-buffer js2-source-buffer)
11261 (goto-char pos)
11262 (message msg))))))
11263
11264 ;;;###autoload
11265 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11266 "Major mode for editing JavaScript code."
11267 (set (make-local-variable 'max-lisp-eval-depth)
11268 (max max-lisp-eval-depth 3000))
11269 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11270 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11271 (set (make-local-variable 'syntax-propertize-function) nil)
11272 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11273 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11274 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11275 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11276 ;; for characters inside regexp literals.
11277 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11278 ;; this is necessary to make `show-paren-function' work properly
11279 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11280 ;; needed for M-x rgrep, among other things
11281 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11282
11283 (setq font-lock-defaults '(nil t))
11284
11285 ;; Experiment: make reparse-delay longer for longer files.
11286 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11287 (setq js2-idle-timer-delay
11288 (* js2-idle-timer-delay
11289 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11290
11291 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11292 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11293 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11294 (setq next-error-function #'js2-next-error)
11295 (imenu-add-to-menubar (concat "IM-" mode-name))
11296 (add-to-invisibility-spec '(js2-outline . t))
11297 (set (make-local-variable 'line-move-ignore-invisible) t)
11298 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11299 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11300
11301 (setq js2-mode-functions-hidden nil
11302 js2-mode-comments-hidden nil
11303 js2-mode-buffer-dirty-p t
11304 js2-mode-parsing nil)
11305
11306 (js2-set-default-externs)
11307
11308 (when js2-include-jslint-globals
11309 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11310
11311 (run-hooks 'js2-init-hook)
11312
11313 (js2-reparse))
11314
11315 (defun js2-mode-exit ()
11316 "Exit `js2-mode' and clean up."
11317 (interactive)
11318 (when js2-mode-node-overlay
11319 (delete-overlay js2-mode-node-overlay)
11320 (setq js2-mode-node-overlay nil))
11321 (js2-remove-overlays)
11322 (setq js2-mode-ast nil)
11323 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11324 (remove-from-invisibility-spec '(js2-outline . t))
11325 (js2-mode-show-all)
11326 (with-silent-modifications
11327 (js2-clear-face (point-min) (point-max))))
11328
11329 (defun js2-mode-reset-timer ()
11330 "Cancel any existing parse timer and schedule a new one."
11331 (if js2-mode-parse-timer
11332 (cancel-timer js2-mode-parse-timer))
11333 (setq js2-mode-parsing nil)
11334 (let ((timer (timer-create)))
11335 (setq js2-mode-parse-timer timer)
11336 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11337 (timer-set-idle-time timer js2-idle-timer-delay)
11338 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11339 (timer-activate-when-idle timer nil)))
11340
11341 (defun js2-mode-idle-reparse (buffer)
11342 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11343 it to be reparsed when the buffer is selected."
11344 (cond ((eq buffer (current-buffer))
11345 (js2-reparse))
11346 ((buffer-live-p buffer)
11347 ;; reparse when the buffer is selected again
11348 (with-current-buffer buffer
11349 (add-hook 'window-configuration-change-hook
11350 #'js2-mode-idle-reparse-inner
11351 nil t)))))
11352
11353 (defun js2-mode-idle-reparse-inner ()
11354 (remove-hook 'window-configuration-change-hook
11355 #'js2-mode-idle-reparse-inner
11356 t)
11357 (js2-reparse))
11358
11359 (defun js2-mode-edit (_beg _end _len)
11360 "Schedule a new parse after buffer is edited.
11361 Buffer edit spans from BEG to END and is of length LEN."
11362 (setq js2-mode-buffer-dirty-p t)
11363 (js2-mode-hide-overlay)
11364 (js2-mode-reset-timer))
11365
11366 (defun js2-minor-mode-edit (_beg _end _len)
11367 "Callback for buffer edits in `js2-mode'.
11368 Schedules 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-reparse (&optional force)
11375 "Re-parse current buffer after user finishes some data entry.
11376 If we get any user input while parsing, including cursor motion,
11377 we discard the parse and reschedule it. If FORCE is nil, then the
11378 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11379 (let (time
11380 interrupted-p
11381 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11382 (unless js2-mode-parsing
11383 (setq js2-mode-parsing t)
11384 (unwind-protect
11385 (when (or js2-mode-buffer-dirty-p force)
11386 (js2-remove-overlays)
11387 (setq js2-mode-buffer-dirty-p nil
11388 js2-mode-fontifications nil
11389 js2-mode-deferred-properties nil)
11390 (if js2-mode-verbose-parse-p
11391 (message "parsing..."))
11392 (setq time
11393 (js2-time
11394 (setq interrupted-p
11395 (catch 'interrupted
11396 (js2-parse)
11397 (with-silent-modifications
11398 ;; if parsing is interrupted, comments and regex
11399 ;; literals stay ignored by `parse-partial-sexp'
11400 (remove-text-properties (point-min) (point-max)
11401 '(syntax-table))
11402 (js2-mode-apply-deferred-properties)
11403 (js2-mode-remove-suppressed-warnings)
11404 (js2-mode-show-warnings)
11405 (js2-mode-show-errors)
11406 (if (>= js2-highlight-level 1)
11407 (js2-highlight-jsdoc js2-mode-ast)))
11408 nil))))
11409 (if interrupted-p
11410 (progn
11411 ;; unfinished parse => try again
11412 (setq js2-mode-buffer-dirty-p t)
11413 (js2-mode-reset-timer))
11414 (if js2-mode-verbose-parse-p
11415 (message "Parse time: %s" time))))
11416 (setq js2-mode-parsing nil)
11417 (unless interrupted-p
11418 (setq js2-mode-parse-timer nil))))))
11419
11420 (defun js2-mode-show-node (event)
11421 "Debugging aid: highlight selected AST node on mouse click."
11422 (interactive "e")
11423 (mouse-set-point event)
11424 (setq deactivate-mark t)
11425 (when js2-mode-show-overlay
11426 (let ((node (js2-node-at-point))
11427 beg end)
11428 (if (null node)
11429 (message "No node found at location %s" (point))
11430 (setq beg (js2-node-abs-pos node)
11431 end (+ beg (js2-node-len node)))
11432 (if js2-mode-node-overlay
11433 (move-overlay js2-mode-node-overlay beg end)
11434 (setq js2-mode-node-overlay (make-overlay beg end))
11435 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11436 (with-silent-modifications
11437 (if (fboundp 'cursor-sensor-mode)
11438 (put-text-property beg end 'cursor-sensor-functions
11439 '(js2-mode-hide-overlay))
11440 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11441 (message "%s, parent: %s"
11442 (js2-node-short-name node)
11443 (if (js2-node-parent node)
11444 (js2-node-short-name (js2-node-parent node))
11445 "nil"))))))
11446
11447 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11448 "Remove the debugging overlay when point moves.
11449 ARG1, ARG2 and ARG3 have different values depending on whether this function
11450 was found on `point-left' or in `cursor-sensor-functions'."
11451 (when js2-mode-node-overlay
11452 (let ((beg (overlay-start js2-mode-node-overlay))
11453 (end (overlay-end js2-mode-node-overlay))
11454 (p2 (if (windowp arg1)
11455 ;; Called from cursor-sensor-functions.
11456 (window-point arg1)
11457 ;; Called from point-left.
11458 arg2)))
11459 ;; Sometimes we're called spuriously.
11460 (unless (and p2
11461 (>= p2 beg)
11462 (<= p2 end))
11463 (with-silent-modifications
11464 (remove-text-properties beg end
11465 '(point-left nil cursor-sensor-functions)))
11466 (delete-overlay js2-mode-node-overlay)
11467 (setq js2-mode-node-overlay nil)))))
11468
11469 (defun js2-mode-reset ()
11470 "Debugging helper: reset everything."
11471 (interactive)
11472 (js2-mode-exit)
11473 (js2-mode))
11474
11475 (defun js2-mode-show-warn-or-err (e face)
11476 "Highlight a warning or error E with FACE.
11477 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11478 The last element is optional. When present, use instead of FACE."
11479 (let* ((key (cl-first e))
11480 (beg (cl-second e))
11481 (end (+ beg (cl-third e)))
11482 ;; Don't inadvertently go out of bounds.
11483 (beg (max (point-min) (min beg (point-max))))
11484 (end (max (point-min) (min end (point-max))))
11485 (ovl (make-overlay beg end)))
11486 ;; FIXME: Why a mix of overlays and text-properties?
11487 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11488 (overlay-put ovl 'js2-error t)
11489 (put-text-property beg end 'help-echo (js2-get-msg key))
11490 (if (fboundp 'cursor-sensor-mode)
11491 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11492 (put-text-property beg end 'point-entered #'js2-echo-error))))
11493
11494 (defun js2-remove-overlays ()
11495 "Remove overlays from buffer that have a `js2-error' property."
11496 (let ((beg (point-min))
11497 (end (point-max)))
11498 (save-excursion
11499 (dolist (o (overlays-in beg end))
11500 (when (overlay-get o 'js2-error)
11501 (delete-overlay o))))))
11502
11503 (defun js2-mode-apply-deferred-properties ()
11504 "Apply fontifications and other text properties recorded during parsing."
11505 (when (cl-plusp js2-highlight-level)
11506 ;; We defer clearing faces as long as possible to eliminate flashing.
11507 (js2-clear-face (point-min) (point-max))
11508 ;; Have to reverse the recorded fontifications list so that errors
11509 ;; and warnings overwrite the normal fontifications.
11510 (dolist (f (nreverse js2-mode-fontifications))
11511 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11512 (setq js2-mode-fontifications nil))
11513 (dolist (p js2-mode-deferred-properties)
11514 (apply #'put-text-property p))
11515 (setq js2-mode-deferred-properties nil))
11516
11517 (defun js2-mode-show-errors ()
11518 "Highlight syntax errors."
11519 (when js2-mode-show-parse-errors
11520 (dolist (e (js2-ast-root-errors js2-mode-ast))
11521 (js2-mode-show-warn-or-err e 'js2-error))))
11522
11523 (defun js2-mode-remove-suppressed-warnings ()
11524 "Take suppressed warnings out of the AST warnings list.
11525 This ensures that the counts and `next-error' are correct."
11526 (setf (js2-ast-root-warnings js2-mode-ast)
11527 (js2-delete-if
11528 (lambda (e)
11529 (let ((key (caar e)))
11530 (or
11531 (and (not js2-strict-trailing-comma-warning)
11532 (string-match "trailing\\.comma" key))
11533 (and (not js2-strict-cond-assign-warning)
11534 (string= key "msg.equal.as.assign"))
11535 (and js2-missing-semi-one-line-override
11536 (string= key "msg.missing.semi")
11537 (let* ((beg (cl-second e))
11538 (node (js2-node-at-point beg))
11539 (fn (js2-mode-find-parent-fn node))
11540 (body (and fn (js2-function-node-body fn)))
11541 (lc (and body (js2-node-abs-pos body)))
11542 (rc (and lc (+ lc (js2-node-len body)))))
11543 (and fn
11544 (or (null body)
11545 (save-excursion
11546 (goto-char beg)
11547 (and (js2-same-line lc)
11548 (js2-same-line rc))))))))))
11549 (js2-ast-root-warnings js2-mode-ast))))
11550
11551 (defun js2-mode-show-warnings ()
11552 "Highlight strict-mode warnings."
11553 (when js2-mode-show-strict-warnings
11554 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11555 (js2-mode-show-warn-or-err e 'js2-warning))))
11556
11557 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11558 "Called by point-motion hooks.
11559 ARG1, ARG2 and ARG3 have different values depending on whether this function
11560 was found on `point-entered' or in `cursor-sensor-functions'."
11561 (let* ((new-point (if (windowp arg1)
11562 ;; Called from cursor-sensor-functions.
11563 (window-point arg1)
11564 ;; Called from point-left.
11565 arg2))
11566 (msg (get-text-property new-point 'help-echo)))
11567 (when (and (stringp msg)
11568 (not (active-minibuffer-window))
11569 (not (current-message)))
11570 (message msg))))
11571
11572 (defun js2-line-break (&optional _soft)
11573 "Break line at point and indent, continuing comment if within one.
11574 If inside a string, and `js2-concat-multiline-strings' is not
11575 nil, turn it into concatenation."
11576 (interactive)
11577 (let ((parse-status (syntax-ppss)))
11578 (cond
11579 ;; Check if we're inside a string.
11580 ((nth 3 parse-status)
11581 (if js2-concat-multiline-strings
11582 (js2-mode-split-string parse-status)
11583 (insert "\n")))
11584 ;; Check if inside a block comment.
11585 ((nth 4 parse-status)
11586 (js2-mode-extend-comment (nth 8 parse-status)))
11587 (t
11588 (newline-and-indent)))))
11589
11590 (defun js2-mode-split-string (parse-status)
11591 "Turn a newline in mid-string into a string concatenation.
11592 PARSE-STATUS is as documented in `parse-partial-sexp'."
11593 (let* ((quote-char (nth 3 parse-status))
11594 (at-eol (eq js2-concat-multiline-strings 'eol)))
11595 (insert quote-char)
11596 (insert (if at-eol " +\n" "\n"))
11597 (unless at-eol
11598 (insert "+ "))
11599 (js2-indent-line)
11600 (insert quote-char)
11601 (when (eolp)
11602 (insert quote-char)
11603 (backward-char 1))))
11604
11605 (defun js2-mode-extend-comment (start-pos)
11606 "Indent the line and, when inside a comment block, add comment prefix."
11607 (let (star single col first-line needs-close)
11608 (save-excursion
11609 (back-to-indentation)
11610 (when (< (point) start-pos)
11611 (goto-char start-pos))
11612 (cond
11613 ((looking-at "\\*[^/]")
11614 (setq star t
11615 col (current-column)))
11616 ((looking-at "/\\*")
11617 (setq star t
11618 first-line t
11619 col (1+ (current-column))))
11620 ((looking-at "//")
11621 (setq single t
11622 col (current-column)))))
11623 ;; Heuristic for whether we need to close the comment:
11624 ;; if we've got a parse error here, assume it's an unterminated
11625 ;; comment.
11626 (setq needs-close
11627 (or
11628 (get-char-property (1- (point)) 'js2-error)
11629 ;; The heuristic above doesn't work well when we're
11630 ;; creating a comment and there's another one downstream,
11631 ;; as our parser thinks this one ends at the end of the
11632 ;; next one. (You can have a /* inside a js block comment.)
11633 ;; So just close it if the next non-ws char isn't a *.
11634 (and first-line
11635 (eolp)
11636 (save-excursion
11637 (skip-chars-forward " \t\r\n")
11638 (not (eq (char-after) ?*))))))
11639 (delete-horizontal-space)
11640 (insert "\n")
11641 (cond
11642 (star
11643 (indent-to col)
11644 (insert "* ")
11645 (if (and first-line needs-close)
11646 (save-excursion
11647 (insert "\n")
11648 (indent-to col)
11649 (insert "*/"))))
11650 ((and single
11651 (save-excursion
11652 (and (zerop (forward-line 1))
11653 (looking-at "\\s-*//"))))
11654 (indent-to col)
11655 (insert "// ")))
11656 ;; Don't need to extend the comment after all.
11657 (js2-indent-line)))
11658
11659 (defun js2-beginning-of-line ()
11660 "Toggle point between bol and first non-whitespace char in line.
11661 Also moves past comment delimiters when inside comments."
11662 (interactive)
11663 (let (node)
11664 (cond
11665 ((bolp)
11666 (back-to-indentation))
11667 ((looking-at "//")
11668 (skip-chars-forward "/ \t"))
11669 ((and (eq (char-after) ?*)
11670 (setq node (js2-comment-at-point))
11671 (memq (js2-comment-node-format node) '(jsdoc block))
11672 (save-excursion
11673 (skip-chars-backward " \t")
11674 (bolp)))
11675 (skip-chars-forward "\* \t"))
11676 (t
11677 (goto-char (point-at-bol))))))
11678
11679 (defun js2-end-of-line ()
11680 "Toggle point between eol and last non-whitespace char in line."
11681 (interactive)
11682 (if (eolp)
11683 (skip-chars-backward " \t")
11684 (goto-char (point-at-eol))))
11685
11686 (defun js2-mode-wait-for-parse (callback)
11687 "Invoke CALLBACK when parsing is finished.
11688 If parsing is already finished, calls CALLBACK immediately."
11689 (if (not js2-mode-buffer-dirty-p)
11690 (funcall callback)
11691 (push callback js2-mode-pending-parse-callbacks)
11692 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11693
11694 (defun js2-mode-parse-finished ()
11695 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11696 ;; We can't let errors propagate up, since it prevents the
11697 ;; `js2-parse' method from completing normally and returning
11698 ;; the ast, which makes things mysteriously not work right.
11699 (unwind-protect
11700 (dolist (cb js2-mode-pending-parse-callbacks)
11701 (condition-case err
11702 (funcall cb)
11703 (error (message "%s" err))))
11704 (setq js2-mode-pending-parse-callbacks nil)))
11705
11706 (defun js2-mode-flag-region (from to flag)
11707 "Hide or show text from FROM to TO, according to FLAG.
11708 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11709 Returns the created overlay if FLAG is non-nil."
11710 (remove-overlays from to 'invisible 'js2-outline)
11711 (when flag
11712 (let ((o (make-overlay from to)))
11713 (overlay-put o 'invisible 'js2-outline)
11714 (overlay-put o 'isearch-open-invisible
11715 'js2-isearch-open-invisible)
11716 o)))
11717
11718 ;; Function to be set as an outline-isearch-open-invisible' property
11719 ;; to the overlay that makes the outline invisible (see
11720 ;; `js2-mode-flag-region').
11721 (defun js2-isearch-open-invisible (_overlay)
11722 ;; We rely on the fact that isearch places point on the matched text.
11723 (js2-mode-show-element))
11724
11725 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11726 "Return cons cell of bounds of folding overlay at POS.
11727 Returns nil if not found."
11728 (let ((overlays (overlays-at (or pos (point))))
11729 o)
11730 (while (and overlays
11731 (not o))
11732 (if (overlay-get (car overlays) 'invisible)
11733 (setq o (car overlays))
11734 (setq overlays (cdr overlays))))
11735 (if o
11736 (cons (overlay-start o) (overlay-end o)))))
11737
11738 (defun js2-mode-function-at-point (&optional pos)
11739 "Return the innermost function node enclosing current point.
11740 Returns nil if point is not in a function."
11741 (let ((node (js2-node-at-point pos)))
11742 (while (and node (not (js2-function-node-p node)))
11743 (setq node (js2-node-parent node)))
11744 (if (js2-function-node-p node)
11745 node)))
11746
11747 (defun js2-mode-toggle-element ()
11748 "Hide or show the foldable element at the point."
11749 (interactive)
11750 (let (comment fn pos)
11751 (save-excursion
11752 (cond
11753 ;; /* ... */ comment?
11754 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11755 (if (js2-mode-invisible-overlay-bounds
11756 (setq pos (+ 3 (js2-node-abs-pos comment))))
11757 (progn
11758 (goto-char pos)
11759 (js2-mode-show-element))
11760 (js2-mode-hide-element)))
11761 ;; //-comment?
11762 ((save-excursion
11763 (back-to-indentation)
11764 (looking-at js2-mode-//-comment-re))
11765 (js2-mode-toggle-//-comment))
11766 ;; function?
11767 ((setq fn (js2-mode-function-at-point))
11768 (setq pos (and (js2-function-node-body fn)
11769 (js2-node-abs-pos (js2-function-node-body fn))))
11770 (goto-char (1+ pos))
11771 (if (js2-mode-invisible-overlay-bounds)
11772 (js2-mode-show-element)
11773 (js2-mode-hide-element)))
11774 (t
11775 (message "Nothing at point to hide or show"))))))
11776
11777 (defun js2-mode-hide-element ()
11778 "Fold/hide contents of a block, showing ellipses.
11779 Show the hidden text with \\[js2-mode-show-element]."
11780 (interactive)
11781 (if js2-mode-buffer-dirty-p
11782 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11783 (let (node body beg end)
11784 (cond
11785 ((js2-mode-invisible-overlay-bounds)
11786 (message "already hidden"))
11787 (t
11788 (setq node (js2-node-at-point))
11789 (cond
11790 ((js2-block-comment-p node)
11791 (js2-mode-hide-comment node))
11792 (t
11793 (while (and node (not (js2-function-node-p node)))
11794 (setq node (js2-node-parent node)))
11795 (if (and node
11796 (setq body (js2-function-node-body node)))
11797 (progn
11798 (setq beg (js2-node-abs-pos body)
11799 end (+ beg (js2-node-len body)))
11800 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11801 (message "No collapsable element found at point"))))))))
11802
11803 (defun js2-mode-show-element ()
11804 "Show the hidden element at current point."
11805 (interactive)
11806 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11807 (if bounds
11808 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11809 (message "Nothing to un-hide"))))
11810
11811 (defun js2-mode-show-all ()
11812 "Show all of the text in the buffer."
11813 (interactive)
11814 (js2-mode-flag-region (point-min) (point-max) nil))
11815
11816 (defun js2-mode-toggle-hide-functions ()
11817 (interactive)
11818 (if js2-mode-functions-hidden
11819 (js2-mode-show-functions)
11820 (js2-mode-hide-functions)))
11821
11822 (defun js2-mode-hide-functions ()
11823 "Hides all non-nested function bodies in the buffer.
11824 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11825 to open an individual entry."
11826 (interactive)
11827 (if js2-mode-buffer-dirty-p
11828 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11829 (if (null js2-mode-ast)
11830 (message "Oops - parsing failed")
11831 (setq js2-mode-functions-hidden t)
11832 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11833
11834 (defun js2-mode-function-hider (n endp)
11835 (when (not endp)
11836 (let ((tt (js2-node-type n))
11837 body beg end)
11838 (cond
11839 ((and (= tt js2-FUNCTION)
11840 (setq body (js2-function-node-body n)))
11841 (setq beg (js2-node-abs-pos body)
11842 end (+ beg (js2-node-len body)))
11843 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11844 nil) ; don't process children of function
11845 (t
11846 t))))) ; keep processing other AST nodes
11847
11848 (defun js2-mode-show-functions ()
11849 "Un-hide any folded function bodies in the buffer."
11850 (interactive)
11851 (setq js2-mode-functions-hidden nil)
11852 (save-excursion
11853 (goto-char (point-min))
11854 (while (/= (goto-char (next-overlay-change (point)))
11855 (point-max))
11856 (dolist (o (overlays-at (point)))
11857 (when (and (overlay-get o 'invisible)
11858 (not (overlay-get o 'comment)))
11859 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11860
11861 (defun js2-mode-hide-comment (n)
11862 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11863 3 ; /**
11864 2)) ; /*
11865 (beg (+ (js2-node-abs-pos n) head))
11866 (end (- (+ beg (js2-node-len n)) head 2))
11867 (o (js2-mode-flag-region beg end 'hide)))
11868 (overlay-put o 'comment t)))
11869
11870 (defun js2-mode-toggle-hide-comments ()
11871 "Folds all block comments in the buffer.
11872 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11873 to open an individual entry."
11874 (interactive)
11875 (if js2-mode-comments-hidden
11876 (js2-mode-show-comments)
11877 (js2-mode-hide-comments)))
11878
11879 (defun js2-mode-hide-comments ()
11880 (interactive)
11881 (if js2-mode-buffer-dirty-p
11882 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11883 (if (null js2-mode-ast)
11884 (message "Oops - parsing failed")
11885 (setq js2-mode-comments-hidden t)
11886 (dolist (n (js2-ast-root-comments js2-mode-ast))
11887 (when (js2-block-comment-p n)
11888 (js2-mode-hide-comment n)))
11889 (js2-mode-hide-//-comments)))
11890
11891 (defun js2-mode-extend-//-comment (direction)
11892 "Find start or end of a block of similar //-comment lines.
11893 DIRECTION is -1 to look back, 1 to look forward.
11894 INDENT is the indentation level to match.
11895 Returns the end-of-line position of the furthest adjacent
11896 //-comment line with the same indentation as the current line.
11897 If there is no such matching line, returns current end of line."
11898 (let ((pos (point-at-eol))
11899 (indent (current-indentation)))
11900 (save-excursion
11901 (while (and (zerop (forward-line direction))
11902 (looking-at js2-mode-//-comment-re)
11903 (eq indent (length (match-string 1))))
11904 (setq pos (point-at-eol)))
11905 pos)))
11906
11907 (defun js2-mode-hide-//-comments ()
11908 "Fold adjacent 1-line comments, showing only snippet of first one."
11909 (let (beg end)
11910 (save-excursion
11911 (goto-char (point-min))
11912 (while (re-search-forward js2-mode-//-comment-re nil t)
11913 (setq beg (point)
11914 end (js2-mode-extend-//-comment 1))
11915 (unless (eq beg end)
11916 (overlay-put (js2-mode-flag-region beg end 'hide)
11917 'comment t))
11918 (goto-char end)
11919 (forward-char 1)))))
11920
11921 (defun js2-mode-toggle-//-comment ()
11922 "Fold or un-fold any multi-line //-comment at point.
11923 Caller should have determined that this line starts with a //-comment."
11924 (let* ((beg (point-at-eol))
11925 (end beg))
11926 (save-excursion
11927 (goto-char end)
11928 (if (js2-mode-invisible-overlay-bounds)
11929 (js2-mode-show-element)
11930 ;; else hide the comment
11931 (setq beg (js2-mode-extend-//-comment -1)
11932 end (js2-mode-extend-//-comment 1))
11933 (unless (eq beg end)
11934 (overlay-put (js2-mode-flag-region beg end 'hide)
11935 'comment t))))))
11936
11937 (defun js2-mode-show-comments ()
11938 "Un-hide any hidden comments, leaving other hidden elements alone."
11939 (interactive)
11940 (setq js2-mode-comments-hidden nil)
11941 (save-excursion
11942 (goto-char (point-min))
11943 (while (/= (goto-char (next-overlay-change (point)))
11944 (point-max))
11945 (dolist (o (overlays-at (point)))
11946 (when (overlay-get o 'comment)
11947 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11948
11949 (defun js2-mode-display-warnings-and-errors ()
11950 "Turn on display of warnings and errors."
11951 (interactive)
11952 (setq js2-mode-show-parse-errors t
11953 js2-mode-show-strict-warnings t)
11954 (js2-reparse 'force))
11955
11956 (defun js2-mode-hide-warnings-and-errors ()
11957 "Turn off display of warnings and errors."
11958 (interactive)
11959 (setq js2-mode-show-parse-errors nil
11960 js2-mode-show-strict-warnings nil)
11961 (js2-reparse 'force))
11962
11963 (defun js2-mode-toggle-warnings-and-errors ()
11964 "Toggle the display of warnings and errors.
11965 Some users don't like having warnings/errors reported while they type."
11966 (interactive)
11967 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11968 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11969 (if (called-interactively-p 'any)
11970 (message "warnings and errors %s"
11971 (if js2-mode-show-parse-errors
11972 "enabled"
11973 "disabled")))
11974 (js2-reparse 'force))
11975
11976 (defun js2-mode-customize ()
11977 (interactive)
11978 (customize-group 'js2-mode))
11979
11980 (defun js2-mode-forward-sexp (&optional arg)
11981 "Move forward across one statement or balanced expression.
11982 With ARG, do it that many times. Negative arg -N means
11983 move backward across N balanced expressions."
11984 (interactive "p")
11985 (setq arg (or arg 1))
11986 (save-restriction
11987 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11988 (js2-reparse)
11989 (let (forward-sexp-function
11990 node (start (point)) pos lp rp child)
11991 (cond
11992 ;; backward-sexp
11993 ;; could probably make this better for some cases:
11994 ;; - if in statement block (e.g. function body), go to parent
11995 ;; - infix exprs like (foo in bar) - maybe go to beginning
11996 ;; of infix expr if in the right-side expression?
11997 ((and arg (cl-minusp arg))
11998 (dotimes (_ (- arg))
11999 (js2-backward-sws)
12000 (forward-char -1) ; Enter the node we backed up to.
12001 (when (setq node (js2-node-at-point (point) t))
12002 (setq pos (js2-node-abs-pos node))
12003 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12004 (setq lp (car parens)
12005 rp (cdr parens)))
12006 (when (and lp (> start lp))
12007 (if (and rp (<= start rp))
12008 ;; Between parens, check if there's a child node we can jump.
12009 (when (setq child (js2-node-closest-child node (point) lp t))
12010 (setq pos (js2-node-abs-pos child)))
12011 ;; Before both parens.
12012 (setq pos lp)))
12013 (let ((state (parse-partial-sexp start pos)))
12014 (goto-char (if (not (zerop (car state)))
12015 ;; Stumble at the unbalanced paren if < 0, or
12016 ;; jump a bit further if > 0.
12017 (scan-sexps start -1)
12018 pos))))
12019 (unless pos (goto-char (point-min)))))
12020 (t
12021 ;; forward-sexp
12022 (dotimes (_ arg)
12023 (js2-forward-sws)
12024 (when (setq node (js2-node-at-point (point) t))
12025 (setq pos (js2-node-abs-pos node))
12026 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12027 (setq lp (car parens)
12028 rp (cdr parens)))
12029 (or
12030 (when (and rp (<= start rp))
12031 (if (> start lp)
12032 (when (setq child (js2-node-closest-child node (point) rp))
12033 (setq pos (js2-node-abs-end child)))
12034 (setq pos (1+ rp))))
12035 ;; No parens or child nodes, looks for the end of the current node.
12036 (cl-incf pos (js2-node-len
12037 (if (js2-expr-stmt-node-p (js2-node-parent node))
12038 ;; Stop after the semicolon.
12039 (js2-node-parent node)
12040 node))))
12041 (let ((state (save-excursion (parse-partial-sexp start pos))))
12042 (goto-char (if (not (zerop (car state)))
12043 (scan-sexps start 1)
12044 pos))))
12045 (unless pos (goto-char (point-max)))))))))
12046
12047 (defun js2-mode-forward-sexp-parens (node abs-pos)
12048 "Return a cons cell with positions of main parens in NODE."
12049 (cond
12050 ((or (js2-array-node-p node)
12051 (js2-object-node-p node)
12052 (js2-comp-node-p node)
12053 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12054 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12055 ((js2-paren-expr-node-p node)
12056 (let ((lp (js2-node-lp node))
12057 (rp (js2-node-rp node)))
12058 (cons (when lp (+ abs-pos lp))
12059 (when rp (+ abs-pos rp)))))))
12060
12061 (defun js2-node-closest-child (parent point limit &optional before)
12062 (let* ((parent-pos (js2-node-abs-pos parent))
12063 (rpoint (- point parent-pos))
12064 (rlimit (- limit parent-pos))
12065 (min (min rpoint rlimit))
12066 (max (max rpoint rlimit))
12067 found)
12068 (catch 'done
12069 (js2-visit-ast
12070 parent
12071 (lambda (node _end-p)
12072 (if (eq node parent)
12073 t
12074 (let ((pos (js2-node-pos node)) ;; Both relative values.
12075 (end (+ (js2-node-pos node) (js2-node-len node))))
12076 (when (and (>= pos min) (<= end max)
12077 (if before (< pos rpoint) (> end rpoint)))
12078 (setq found node))
12079 (when (> end rpoint)
12080 (throw 'done nil)))
12081 nil))))
12082 found))
12083
12084 (defun js2-errors ()
12085 "Return a list of errors found."
12086 (and js2-mode-ast
12087 (js2-ast-root-errors js2-mode-ast)))
12088
12089 (defun js2-warnings ()
12090 "Return a list of warnings found."
12091 (and js2-mode-ast
12092 (js2-ast-root-warnings js2-mode-ast)))
12093
12094 (defun js2-have-errors-p ()
12095 "Return non-nil if any parse errors or warnings were found."
12096 (or (js2-errors) (js2-warnings)))
12097
12098 (defun js2-errors-and-warnings ()
12099 "Return a copy of the concatenated errors and warnings lists.
12100 They are appended: first the errors, then the warnings.
12101 Entries are of the form (MSG BEG END)."
12102 (when js2-mode-ast
12103 (append (js2-ast-root-errors js2-mode-ast)
12104 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12105
12106 (defun js2-next-error (&optional arg reset)
12107 "Move to next parse error.
12108 Typically invoked via \\[next-error].
12109 ARG is the number of errors, forward or backward, to move.
12110 RESET means start over from the beginning."
12111 (interactive "p")
12112 (if (not (or (js2-errors) (js2-warnings)))
12113 (message "No errors")
12114 (when reset
12115 (goto-char (point-min)))
12116 (let* ((errs (js2-errors-and-warnings))
12117 (continue t)
12118 (start (point))
12119 (count (or arg 1))
12120 (backward (cl-minusp count))
12121 (sorter (if backward '> '<))
12122 (stopper (if backward '< '>))
12123 (count (abs count))
12124 all-errs err)
12125 ;; Sort by start position.
12126 (setq errs (sort errs (lambda (e1 e2)
12127 (funcall sorter (cl-second e1) (cl-second e2))))
12128 all-errs errs)
12129 ;; Find nth error with pos > start.
12130 (while (and errs continue)
12131 (when (funcall stopper (cl-cadar errs) start)
12132 (setq err (car errs))
12133 (if (zerop (cl-decf count))
12134 (setq continue nil)))
12135 (setq errs (cdr errs)))
12136 ;; Clear for `js2-echo-error'.
12137 (message nil)
12138 (if err
12139 (goto-char (cl-second err))
12140 ;; Wrap around to first error.
12141 (goto-char (cl-second (car all-errs)))
12142 ;; If we were already on it, echo msg again.
12143 (if (= (point) start)
12144 (js2-echo-error (point) (point)))))))
12145
12146 (defun js2-down-mouse-3 ()
12147 "Make right-click move the point to the click location.
12148 This makes right-click context menu operations a bit more intuitive.
12149 The point will not move if the region is active, however, to avoid
12150 destroying the region selection."
12151 (interactive)
12152 (when (and js2-move-point-on-right-click
12153 (not mark-active))
12154 (let ((e last-input-event))
12155 (ignore-errors
12156 (goto-char (cl-cadadr e))))))
12157
12158 (defun js2-mode-create-imenu-index ()
12159 "Return an alist for `imenu--index-alist'."
12160 ;; This is built up in `js2-parse-record-imenu' during parsing.
12161 (when js2-mode-ast
12162 ;; if we have an ast but no recorder, they're requesting a rescan
12163 (unless js2-imenu-recorder
12164 (js2-reparse 'force))
12165 (prog1
12166 (js2-build-imenu-index)
12167 (setq js2-imenu-recorder nil
12168 js2-imenu-function-map nil))))
12169
12170 (defun js2-mode-find-tag ()
12171 "Replacement for `find-tag-default'.
12172 `find-tag-default' returns a ridiculous answer inside comments."
12173 (let (beg end)
12174 (save-excursion
12175 (if (looking-at "\\_>")
12176 (setq beg (progn (forward-symbol -1) (point))
12177 end (progn (forward-symbol 1) (point)))
12178 (setq beg (progn (forward-symbol 1) (point))
12179 end (progn (forward-symbol -1) (point))))
12180 (replace-regexp-in-string
12181 "[\"']" ""
12182 (buffer-substring-no-properties beg end)))))
12183
12184 (defun js2-mode-forward-sibling ()
12185 "Move to the end of the sibling following point in parent.
12186 Returns non-nil if successful, or nil if there was no following sibling."
12187 (let* ((node (js2-node-at-point))
12188 (parent (js2-mode-find-enclosing-fn node))
12189 sib)
12190 (when (setq sib (js2-node-find-child-after (point) parent))
12191 (goto-char (+ (js2-node-abs-pos sib)
12192 (js2-node-len sib))))))
12193
12194 (defun js2-mode-backward-sibling ()
12195 "Move to the beginning of the sibling node preceding point in parent.
12196 Parent is defined as the enclosing script or function."
12197 (let* ((node (js2-node-at-point))
12198 (parent (js2-mode-find-enclosing-fn node))
12199 sib)
12200 (when (setq sib (js2-node-find-child-before (point) parent))
12201 (goto-char (js2-node-abs-pos sib)))))
12202
12203 (defun js2-beginning-of-defun (&optional arg)
12204 "Go to line on which current function starts, and return t on success.
12205 If we're not in a function or already at the beginning of one, go
12206 to beginning of previous script-level element.
12207 With ARG N, do that N times. If N is negative, move forward."
12208 (setq arg (or arg 1))
12209 (if (cl-plusp arg)
12210 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12211 (when (cond
12212 ((js2-function-node-p parent)
12213 (goto-char (js2-node-abs-pos parent)))
12214 (t
12215 (js2-mode-backward-sibling)))
12216 (if (> arg 1)
12217 (js2-beginning-of-defun (1- arg))
12218 t)))
12219 (when (js2-end-of-defun)
12220 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12221
12222 (defun js2-end-of-defun ()
12223 "Go to the char after the last position of the current function
12224 or script-level element."
12225 (let* ((node (js2-node-at-point))
12226 (parent (or (and (js2-function-node-p node) node)
12227 (js2-node-parent-script-or-fn node)))
12228 script)
12229 (unless (js2-function-node-p parent)
12230 ;; Use current script-level node, or, if none, the next one.
12231 (setq script (or parent node)
12232 parent (js2-node-find-child-before (point) script))
12233 (when (or (null parent)
12234 (>= (point) (+ (js2-node-abs-pos parent)
12235 (js2-node-len parent))))
12236 (setq parent (js2-node-find-child-after (point) script))))
12237 (when parent
12238 (goto-char (+ (js2-node-abs-pos parent)
12239 (js2-node-len parent))))))
12240
12241 (defun js2-mark-defun (&optional allow-extend)
12242 "Put mark at end of this function, point at beginning.
12243 The function marked is the one that contains point.
12244
12245 Interactively, if this command is repeated,
12246 or (in Transient Mark mode) if the mark is active,
12247 it marks the next defun after the ones already marked."
12248 (interactive "p")
12249 (let (extended)
12250 (when (and allow-extend
12251 (or (and (eq last-command this-command) (mark t))
12252 (and transient-mark-mode mark-active)))
12253 (let ((sib (save-excursion
12254 (goto-char (mark))
12255 (if (js2-mode-forward-sibling)
12256 (point)))))
12257 (if sib
12258 (progn
12259 (set-mark sib)
12260 (setq extended t))
12261 ;; no more siblings - try extending to enclosing node
12262 (goto-char (mark t)))))
12263 (when (not extended)
12264 (let ((node (js2-node-at-point (point) t)) ; skip comments
12265 ast fn stmt parent beg end)
12266 (when (js2-ast-root-p node)
12267 (setq ast node
12268 node (or (js2-node-find-child-after (point) node)
12269 (js2-node-find-child-before (point) node))))
12270 ;; only mark whole buffer if we can't find any children
12271 (if (null node)
12272 (setq node ast))
12273 (if (js2-function-node-p node)
12274 (setq parent node)
12275 (setq fn (js2-mode-find-enclosing-fn node)
12276 stmt (if (or (null fn)
12277 (js2-ast-root-p fn))
12278 (js2-mode-find-first-stmt node))
12279 parent (or stmt fn)))
12280 (setq beg (js2-node-abs-pos parent)
12281 end (+ beg (js2-node-len parent)))
12282 (push-mark beg)
12283 (goto-char end)
12284 (exchange-point-and-mark)))))
12285
12286 (defun js2-narrow-to-defun ()
12287 "Narrow to the function enclosing point."
12288 (interactive)
12289 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12290 (fn (if (js2-script-node-p node)
12291 node
12292 (js2-mode-find-enclosing-fn node)))
12293 (beg (js2-node-abs-pos fn)))
12294 (unless (js2-ast-root-p fn)
12295 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12296
12297 (defun js2-jump-to-definition (&optional arg)
12298 "Jump to the definition of an object's property, variable or function."
12299 (interactive "P")
12300 (ring-insert find-tag-marker-ring (point-marker))
12301 (let* ((node (js2-node-at-point))
12302 (parent (js2-node-parent node))
12303 (names (if (js2-prop-get-node-p parent)
12304 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12305 (cl-loop for n in temp
12306 with result = '()
12307 do (push n result)
12308 until (equal node n)
12309 finally return result)))))
12310 node-init)
12311 (unless (and (js2-name-node-p node)
12312 (not (js2-var-init-node-p parent))
12313 (not (js2-function-node-p parent)))
12314 (error "Node is not a supported jump node"))
12315 (push (or (and names (pop names))
12316 (unless (and (js2-object-prop-node-p parent)
12317 (eq node (js2-object-prop-node-left parent)))
12318 node)) names)
12319 (setq node-init (js2-search-scope node names))
12320
12321 ;; todo: display list of results in buffer
12322 ;; todo: group found references by buffer
12323 (unless node-init
12324 (switch-to-buffer
12325 (catch 'found
12326 (unless arg
12327 (mapc (lambda (b)
12328 (with-current-buffer b
12329 (when (derived-mode-p 'js2-mode)
12330 (setq node-init (js2-search-scope js2-mode-ast names))
12331 (if node-init
12332 (throw 'found b)))))
12333 (buffer-list)))
12334 nil)))
12335 (setq node-init (if (listp node-init) (car node-init) node-init))
12336 (unless node-init
12337 (pop-tag-mark)
12338 (error "No jump location found"))
12339 (goto-char (js2-node-abs-pos node-init))))
12340
12341 (defun js2-search-object (node name-node)
12342 "Check if object NODE contains element with NAME-NODE."
12343 (cl-assert (js2-object-node-p node))
12344 ;; Only support name-node and nodes for the time being
12345 (cl-loop for elem in (js2-object-node-elems node)
12346 for left = (js2-object-prop-node-left elem)
12347 if (or (and (js2-name-node-p left)
12348 (equal (js2-name-node-name name-node)
12349 (js2-name-node-name left)))
12350 (and (js2-string-node-p left)
12351 (string= (js2-name-node-name name-node)
12352 (js2-string-node-value left))))
12353 return elem))
12354
12355 (defun js2-search-object-for-prop (object prop-names)
12356 "Return node in OBJECT that matches PROP-NAMES or nil.
12357 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12358 i.e. ('name' 'value') = {name : { value: 3}}"
12359 (let (node
12360 (temp-object object)
12361 (temp t) ;temporay node
12362 (names prop-names))
12363 (while (and temp names (js2-object-node-p temp-object))
12364 (setq temp (js2-search-object temp-object (pop names)))
12365 (and (setq node temp)
12366 (setq temp-object (js2-object-prop-node-right temp))))
12367 (unless names node)))
12368
12369 (defun js2-search-scope (node names)
12370 "Searches NODE scope for jump location matching NAMES.
12371 NAMES is a list of property values to search for. For functions
12372 and variables NAMES will contain one element."
12373 (let (node-init
12374 (val (js2-name-node-name (car names))))
12375 (setq node-init (js2-get-symbol-declaration node val))
12376
12377 (when (> (length names) 1)
12378
12379 ;; Check var declarations
12380 (when (and node-init (string= val (js2-name-node-name node-init)))
12381 (let ((parent (js2-node-parent node-init))
12382 (temp-names names))
12383 (pop temp-names) ;; First element is var name
12384 (setq node-init (when (js2-var-init-node-p parent)
12385 (js2-search-object-for-prop
12386 (js2-var-init-node-initializer parent)
12387 temp-names)))))
12388
12389 ;; Check all assign nodes
12390 (js2-visit-ast
12391 js2-mode-ast
12392 (lambda (node endp)
12393 (unless endp
12394 (if (js2-assign-node-p node)
12395 (let ((left (js2-assign-node-left node))
12396 (right (js2-assign-node-right node))
12397 (temp-names names))
12398 (when (js2-prop-get-node-p left)
12399 (let* ((prop-list (js2-compute-nested-prop-get left))
12400 (found (cl-loop for prop in prop-list
12401 until (not (string= (js2-name-node-name
12402 (pop temp-names))
12403 (js2-name-node-name prop)))
12404 if (not temp-names) return prop))
12405 (found-node (or found
12406 (when (js2-object-node-p right)
12407 (js2-search-object-for-prop right
12408 temp-names)))))
12409 (if found-node (push found-node node-init))))))
12410 t))))
12411 node-init))
12412
12413 (defun js2-get-symbol-declaration (node name)
12414 "Find scope for NAME from NODE."
12415 (let ((scope (js2-get-defining-scope
12416 (or (js2-node-get-enclosing-scope node)
12417 node) name)))
12418 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12419
12420 (provide 'js2-mode)
12421
12422 ;;; js2-mode.el ends here