]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode/js2-mode.el
Merge commit '494c421bfa6f1b72b577267cb3841b0eff262250' from js2-mode
[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: 20150713
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require 'js)
91
92 (eval-and-compile
93 (if (version< emacs-version "25.0")
94 (require 'js2-old-indent)
95 (defvaralias 'js2-basic-offset 'js-indent-level nil)
96 (defalias 'js2-proper-indentation 'js--proper-indentation)
97 (defalias 'js2-indent-line 'js-indent-line)))
98
99 ;;; Externs (variables presumed to be defined by the host system)
100
101 (defvar js2-ecma-262-externs
102 (mapcar 'symbol-name
103 '(Array Boolean Date Error EvalError Function Infinity JSON
104 Math NaN Number Object RangeError ReferenceError RegExp
105 String SyntaxError TypeError URIError
106 decodeURI decodeURIComponent encodeURI
107 encodeURIComponent escape eval isFinite isNaN
108 parseFloat parseInt undefined unescape))
109 "Ecma-262 externs. Included in `js2-externs' by default.")
110
111 (defvar js2-browser-externs
112 (mapcar 'symbol-name
113 '(;; DOM level 1
114 Attr CDATASection CharacterData Comment DOMException
115 DOMImplementation Document DocumentFragment
116 DocumentType Element Entity EntityReference
117 ExceptionCode NamedNodeMap Node NodeList Notation
118 ProcessingInstruction Text
119
120 ;; DOM level 2
121 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
122 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
123 HTMLBodyElement HTMLButtonElement HTMLCollection
124 HTMLDListElement HTMLDirectoryElement HTMLDivElement
125 HTMLDocument HTMLElement HTMLFieldSetElement
126 HTMLFontElement HTMLFormElement HTMLFrameElement
127 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
128 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
129 HTMLImageElement HTMLInputElement HTMLIsIndexElement
130 HTMLLIElement HTMLLabelElement HTMLLegendElement
131 HTMLLinkElement HTMLMapElement HTMLMenuElement
132 HTMLMetaElement HTMLModElement HTMLOListElement
133 HTMLObjectElement HTMLOptGroupElement
134 HTMLOptionElement HTMLOptionsCollection
135 HTMLParagraphElement HTMLParamElement HTMLPreElement
136 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
137 HTMLStyleElement HTMLTableCaptionElement
138 HTMLTableCellElement HTMLTableColElement
139 HTMLTableElement HTMLTableRowElement
140 HTMLTableSectionElement HTMLTextAreaElement
141 HTMLTitleElement HTMLUListElement
142
143 ;; DOM level 3
144 DOMConfiguration DOMError DOMException
145 DOMImplementationList DOMImplementationSource
146 DOMLocator DOMStringList NameList TypeInfo
147 UserDataHandler
148
149 ;; Window
150 window alert confirm document java navigator prompt screen
151 self top requestAnimationFrame cancelAnimationFrame
152
153 ;; W3C CSS
154 CSSCharsetRule CSSFontFace CSSFontFaceRule
155 CSSImportRule CSSMediaRule CSSPageRule
156 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
157 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
158 CSSValue CSSValueList Counter DOMImplementationCSS
159 DocumentCSS DocumentStyle ElementCSSInlineStyle
160 LinkStyle MediaList RGBColor Rect StyleSheet
161 StyleSheetList ViewCSS
162
163 ;; W3C Event
164 EventListener EventTarget Event DocumentEvent UIEvent
165 MouseEvent MutationEvent KeyboardEvent
166
167 ;; W3C Range
168 DocumentRange Range RangeException
169
170 ;; W3C XML
171 XPathResult XMLHttpRequest
172
173 ;; console object. Provided by at least Chrome and Firefox.
174 console))
175 "Browser externs.
176 You can cause these to be included or excluded with the custom
177 variable `js2-include-browser-externs'.")
178
179 (defvar js2-rhino-externs
180 (mapcar 'symbol-name
181 '(Packages importClass importPackage com org java
182 ;; Global object (shell) externs.
183 defineClass deserialize doctest gc help load
184 loadClass print quit readFile readUrl runCommand seal
185 serialize spawn sync toint32 version))
186 "Mozilla Rhino externs.
187 Set `js2-include-rhino-externs' to t to include them.")
188
189 (defvar js2-node-externs
190 (mapcar 'symbol-name
191 '(__dirname __filename Buffer clearInterval clearTimeout require
192 console exports global module process setInterval setTimeout
193 querystring))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-idle-timer-delay 0.2
240 "Delay in secs before re-parsing after user makes changes.
241 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
242 :type 'number
243 :group 'js2-mode)
244 (make-variable-buffer-local 'js2-idle-timer-delay)
245
246 (defcustom js2-dynamic-idle-timer-adjust 0
247 "Positive to adjust `js2-idle-timer-delay' based on file size.
248 The idea is that for short files, parsing is faster so we can be
249 more responsive to user edits without interfering with editing.
250 The buffer length in characters (typically bytes) is divided by
251 this value and used to multiply `js2-idle-timer-delay' for the
252 buffer. For example, a 21k file and 10k adjust yields 21k/10k
253 == 2, so js2-idle-timer-delay is multiplied by 2.
254 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
255 `js2-idle-timer-delay' is not dependent on the file size."
256 :type 'number
257 :group 'js2-mode)
258
259 (defcustom js2-concat-multiline-strings t
260 "When non-nil, `js2-line-break' in mid-string will make it a
261 string concatenation. When `eol', the '+' will be inserted at the
262 end of the line, otherwise, at the beginning of the next line."
263 :type '(choice (const t) (const eol) (const nil))
264 :group 'js2-mode)
265
266 (defcustom js2-mode-show-parse-errors t
267 "True to highlight parse errors."
268 :type 'boolean
269 :group 'js2-mode)
270
271 (defcustom js2-mode-show-strict-warnings t
272 "Non-nil to emit Ecma strict-mode warnings.
273 Some of the warnings can be individually disabled by other flags,
274 even if this flag is non-nil."
275 :type 'boolean
276 :group 'js2-mode)
277
278 (defcustom js2-strict-trailing-comma-warning t
279 "Non-nil to warn about trailing commas in array literals.
280 Ecma-262-5.1 allows them, but older versions of IE raise an error."
281 :type 'boolean
282 :group 'js2-mode)
283
284 (defcustom js2-strict-missing-semi-warning t
285 "Non-nil to warn about semicolon auto-insertion after statement.
286 Technically this is legal per Ecma-262, but some style guides disallow
287 depending on it."
288 :type 'boolean
289 :group 'js2-mode)
290
291 (defcustom js2-missing-semi-one-line-override nil
292 "Non-nil to permit missing semicolons in one-line functions.
293 In one-liner functions such as `function identity(x) {return x}'
294 people often omit the semicolon for a cleaner look. If you are
295 such a person, you can suppress the missing-semicolon warning
296 by setting this variable to t."
297 :type 'boolean
298 :group 'js2-mode)
299
300 (defcustom js2-strict-inconsistent-return-warning t
301 "Non-nil to warn about mixing returns with value-returns.
302 It's perfectly legal to have a `return' and a `return foo' in the
303 same function, but it's often an indicator of a bug, and it also
304 interferes with type inference (in systems that support it.)"
305 :type 'boolean
306 :group 'js2-mode)
307
308 (defcustom js2-strict-cond-assign-warning t
309 "Non-nil to warn about expressions like if (a = b).
310 This often should have been '==' instead of '='. If the warning
311 is enabled, you can suppress it on a per-expression basis by
312 parenthesizing the expression, e.g. if ((a = b)) ..."
313 :type 'boolean
314 :group 'js2-mode)
315
316 (defcustom js2-strict-var-redeclaration-warning t
317 "Non-nil to warn about redeclaring variables in a script or function."
318 :type 'boolean
319 :group 'js2-mode)
320
321 (defcustom js2-strict-var-hides-function-arg-warning t
322 "Non-nil to warn about a var decl hiding a function argument."
323 :type 'boolean
324 :group 'js2-mode)
325
326 (defcustom js2-skip-preprocessor-directives nil
327 "Non-nil to treat lines beginning with # as comments.
328 Useful for viewing Mozilla JavaScript source code."
329 :type 'boolean
330 :group 'js2-mode)
331
332 (defcustom js2-language-version 200
333 "Configures what JavaScript language version to recognize.
334 Currently versions 150, 160, 170, 180 and 200 are supported,
335 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
336 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
337 yield, and Array comprehensions, and 1.8 adds function closures."
338 :type 'integer
339 :group 'js2-mode)
340
341 (defcustom js2-instanceof-has-side-effects nil
342 "If non-nil, treats the instanceof operator as having side effects.
343 This is useful for xulrunner apps."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-move-point-on-right-click t
348 "Non-nil to move insertion point when you right-click.
349 This makes right-click context menu behavior a bit more intuitive,
350 since menu operations generally apply to the point. The exception
351 is if there is a region selection, in which case the point does -not-
352 move, so cut/copy/paste can work properly.
353
354 Note that IntelliJ moves the point, and Eclipse leaves it alone,
355 so this behavior is customizable."
356 :group 'js2-mode
357 :type 'boolean)
358
359 (defcustom js2-allow-rhino-new-expr-initializer t
360 "Non-nil to support a Rhino's experimental syntactic construct.
361
362 Rhino supports the ability to follow a `new' expression with an object
363 literal, which is used to set additional properties on the new object
364 after calling its constructor. Syntax:
365
366 new <expr> [ ( arglist ) ] [initializer]
367
368 Hence, this expression:
369
370 new Object {a: 1, b: 2}
371
372 results in an Object with properties a=1 and b=2. This syntax is
373 apparently not configurable in Rhino - it's currently always enabled,
374 as of Rhino version 1.7R2."
375 :type 'boolean
376 :group 'js2-mode)
377
378 (defcustom js2-allow-member-expr-as-function-name nil
379 "Non-nil to support experimental Rhino syntax for function names.
380
381 Rhino supports an experimental syntax configured via the Rhino Context
382 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
383
384 function <member-expr> ( [ arg-list ] ) { <body> }
385
386 Where member-expr is a non-parenthesized 'member expression', which
387 is anything at the grammar level of a new-expression or lower, meaning
388 any expression that does not involve infix or unary operators.
389
390 When <member-expr> is not a simple identifier, then it is syntactic
391 sugar for assigning the anonymous function to the <member-expr>. Hence,
392 this code:
393
394 function a.b().c[2] (x, y) { ... }
395
396 is rewritten as:
397
398 a.b().c[2] = function(x, y) {...}
399
400 which doesn't seem particularly useful, but Rhino permits it."
401 :type 'boolean
402 :group 'js2-mode)
403
404 ;; scanner variables
405
406 (defmacro js2-deflocal (name value &optional comment)
407 "Define a buffer-local variable NAME with VALUE and COMMENT."
408 (declare (debug defvar) (doc-string 3))
409 `(progn
410 (defvar ,name ,value ,comment)
411 (make-variable-buffer-local ',name)))
412
413 (defvar js2-EOF_CHAR -1
414 "Represents end of stream. Distinct from js2-EOF token type.")
415
416 ;; I originally used symbols to represent tokens, but Rhino uses
417 ;; ints and then sets various flag bits in them, so ints it is.
418 ;; The upshot is that we need a `js2-' prefix in front of each name.
419 (defvar js2-ERROR -1)
420 (defvar js2-EOF 0)
421 (defvar js2-EOL 1)
422 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
423 (defvar js2-LEAVEWITH 3)
424 (defvar js2-RETURN 4)
425 (defvar js2-GOTO 5)
426 (defvar js2-IFEQ 6)
427 (defvar js2-IFNE 7)
428 (defvar js2-SETNAME 8)
429 (defvar js2-BITOR 9)
430 (defvar js2-BITXOR 10)
431 (defvar js2-BITAND 11)
432 (defvar js2-EQ 12)
433 (defvar js2-NE 13)
434 (defvar js2-LT 14)
435 (defvar js2-LE 15)
436 (defvar js2-GT 16)
437 (defvar js2-GE 17)
438 (defvar js2-LSH 18)
439 (defvar js2-RSH 19)
440 (defvar js2-URSH 20)
441 (defvar js2-ADD 21) ; infix plus
442 (defvar js2-SUB 22) ; infix minus
443 (defvar js2-MUL 23)
444 (defvar js2-DIV 24)
445 (defvar js2-MOD 25)
446 (defvar js2-NOT 26)
447 (defvar js2-BITNOT 27)
448 (defvar js2-POS 28) ; unary plus
449 (defvar js2-NEG 29) ; unary minus
450 (defvar js2-NEW 30)
451 (defvar js2-DELPROP 31)
452 (defvar js2-TYPEOF 32)
453 (defvar js2-GETPROP 33)
454 (defvar js2-GETPROPNOWARN 34)
455 (defvar js2-SETPROP 35)
456 (defvar js2-GETELEM 36)
457 (defvar js2-SETELEM 37)
458 (defvar js2-CALL 38)
459 (defvar js2-NAME 39) ; an identifier
460 (defvar js2-NUMBER 40)
461 (defvar js2-STRING 41)
462 (defvar js2-NULL 42)
463 (defvar js2-THIS 43)
464 (defvar js2-FALSE 44)
465 (defvar js2-TRUE 45)
466 (defvar js2-SHEQ 46) ; shallow equality (===)
467 (defvar js2-SHNE 47) ; shallow inequality (!==)
468 (defvar js2-REGEXP 48)
469 (defvar js2-BINDNAME 49)
470 (defvar js2-THROW 50)
471 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
472 (defvar js2-IN 52)
473 (defvar js2-INSTANCEOF 53)
474 (defvar js2-LOCAL_LOAD 54)
475 (defvar js2-GETVAR 55)
476 (defvar js2-SETVAR 56)
477 (defvar js2-CATCH_SCOPE 57)
478 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
479 (defvar js2-ENUM_INIT_VALUES 59)
480 (defvar js2-ENUM_INIT_ARRAY 60)
481 (defvar js2-ENUM_NEXT 61)
482 (defvar js2-ENUM_ID 62)
483 (defvar js2-THISFN 63)
484 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
485 (defvar js2-ARRAYLIT 65) ; array literal
486 (defvar js2-OBJECTLIT 66) ; object literal
487 (defvar js2-GET_REF 67) ; *reference
488 (defvar js2-SET_REF 68) ; *reference = something
489 (defvar js2-DEL_REF 69) ; delete reference
490 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
491 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
492 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
493
494 ;; XML support
495 (defvar js2-DEFAULTNAMESPACE 73)
496 (defvar js2-ESCXMLATTR 74)
497 (defvar js2-ESCXMLTEXT 75)
498 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
499 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
500 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
501 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
502
503 (defvar js2-first-bytecode js2-ENTERWITH)
504 (defvar js2-last-bytecode js2-REF_NS_NAME)
505
506 (defvar js2-TRY 80)
507 (defvar js2-SEMI 81) ; semicolon
508 (defvar js2-LB 82) ; left and right brackets
509 (defvar js2-RB 83)
510 (defvar js2-LC 84) ; left and right curly-braces
511 (defvar js2-RC 85)
512 (defvar js2-LP 86) ; left and right parens
513 (defvar js2-RP 87)
514 (defvar js2-COMMA 88) ; comma operator
515
516 (defvar js2-ASSIGN 89) ; simple assignment (=)
517 (defvar js2-ASSIGN_BITOR 90) ; |=
518 (defvar js2-ASSIGN_BITXOR 91) ; ^=
519 (defvar js2-ASSIGN_BITAND 92) ; &=
520 (defvar js2-ASSIGN_LSH 93) ; <<=
521 (defvar js2-ASSIGN_RSH 94) ; >>=
522 (defvar js2-ASSIGN_URSH 95) ; >>>=
523 (defvar js2-ASSIGN_ADD 96) ; +=
524 (defvar js2-ASSIGN_SUB 97) ; -=
525 (defvar js2-ASSIGN_MUL 98) ; *=
526 (defvar js2-ASSIGN_DIV 99) ; /=
527 (defvar js2-ASSIGN_MOD 100) ; %=
528
529 (defvar js2-first-assign js2-ASSIGN)
530 (defvar js2-last-assign js2-ASSIGN_MOD)
531
532 (defvar js2-HOOK 101) ; conditional (?:)
533 (defvar js2-COLON 102)
534 (defvar js2-OR 103) ; logical or (||)
535 (defvar js2-AND 104) ; logical and (&&)
536 (defvar js2-INC 105) ; increment/decrement (++ --)
537 (defvar js2-DEC 106)
538 (defvar js2-DOT 107) ; member operator (.)
539 (defvar js2-FUNCTION 108) ; function keyword
540 (defvar js2-EXPORT 109) ; export keyword
541 (defvar js2-IMPORT 110) ; import keyword
542 (defvar js2-IF 111) ; if keyword
543 (defvar js2-ELSE 112) ; else keyword
544 (defvar js2-SWITCH 113) ; switch keyword
545 (defvar js2-CASE 114) ; case keyword
546 (defvar js2-DEFAULT 115) ; default keyword
547 (defvar js2-WHILE 116) ; while keyword
548 (defvar js2-DO 117) ; do keyword
549 (defvar js2-FOR 118) ; for keyword
550 (defvar js2-BREAK 119) ; break keyword
551 (defvar js2-CONTINUE 120) ; continue keyword
552 (defvar js2-VAR 121) ; var keyword
553 (defvar js2-WITH 122) ; with keyword
554 (defvar js2-CATCH 123) ; catch keyword
555 (defvar js2-FINALLY 124) ; finally keyword
556 (defvar js2-VOID 125) ; void keyword
557 (defvar js2-RESERVED 126) ; reserved keywords
558
559 (defvar js2-EMPTY 127)
560
561 ;; Types used for the parse tree - never returned by scanner.
562
563 (defvar js2-BLOCK 128) ; statement block
564 (defvar js2-LABEL 129) ; label
565 (defvar js2-TARGET 130)
566 (defvar js2-LOOP 131)
567 (defvar js2-EXPR_VOID 132) ; expression statement in functions
568 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
569 (defvar js2-JSR 134)
570 (defvar js2-SCRIPT 135) ; top-level node for entire script
571 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
572 (defvar js2-USE_STACK 137)
573 (defvar js2-SETPROP_OP 138) ; x.y op= something
574 (defvar js2-SETELEM_OP 139) ; x[y] op= something
575 (defvar js2-LOCAL_BLOCK 140)
576 (defvar js2-SET_REF_OP 141) ; *reference op= something
577
578 ;; For XML support:
579 (defvar js2-DOTDOT 142) ; member operator (..)
580 (defvar js2-COLONCOLON 143) ; namespace::name
581 (defvar js2-XML 144) ; XML type
582 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
583 (defvar js2-XMLATTR 146) ; @
584 (defvar js2-XMLEND 147)
585
586 ;; Optimizer-only tokens
587 (defvar js2-TO_OBJECT 148)
588 (defvar js2-TO_DOUBLE 149)
589
590 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
591 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
592 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
593 (defvar js2-CONST 153)
594 (defvar js2-SETCONST 154)
595 (defvar js2-SETCONSTVAR 155)
596 (defvar js2-ARRAYCOMP 156)
597 (defvar js2-LETEXPR 157)
598 (defvar js2-WITHEXPR 158)
599 (defvar js2-DEBUGGER 159)
600
601 (defvar js2-COMMENT 160)
602 (defvar js2-TRIPLEDOT 161) ; for rest parameter
603 (defvar js2-ARROW 162) ; function arrow (=>)
604 (defvar js2-CLASS 163)
605 (defvar js2-EXTENDS 164)
606 (defvar js2-SUPER 165)
607 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
608 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
609 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
610
611 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
612
613 (defconst js2-debug-print-trees nil)
614
615 ;; Rhino accepts any string or stream as input. Emacs character
616 ;; processing works best in buffers, so we'll assume the input is a
617 ;; buffer. JavaScript strings can be copied into temp buffers before
618 ;; scanning them.
619
620 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
621 ;; They're the Emacs equivalent of instance variables, more or less.
622
623 (js2-deflocal js2-ts-dirty-line nil
624 "Token stream buffer-local variable.
625 Indicates stuff other than whitespace since start of line.")
626
627 (js2-deflocal js2-ts-hit-eof nil
628 "Token stream buffer-local variable.")
629
630 ;; FIXME: Unused.
631 (js2-deflocal js2-ts-line-start 0
632 "Token stream buffer-local variable.")
633
634 (js2-deflocal js2-ts-lineno 1
635 "Token stream buffer-local variable.")
636
637 ;; FIXME: Unused.
638 (js2-deflocal js2-ts-line-end-char -1
639 "Token stream buffer-local variable.")
640
641 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
642 "Token stream buffer-local variable.
643 Current scan position.")
644
645 ;; FIXME: Unused.
646 (js2-deflocal js2-ts-is-xml-attribute nil
647 "Token stream buffer-local variable.")
648
649 (js2-deflocal js2-ts-xml-is-tag-content nil
650 "Token stream buffer-local variable.")
651
652 (js2-deflocal js2-ts-xml-open-tags-count 0
653 "Token stream buffer-local variable.")
654
655 (js2-deflocal js2-ts-string-buffer nil
656 "Token stream buffer-local variable.
657 List of chars built up while scanning various tokens.")
658
659 (cl-defstruct (js2-token
660 (:constructor nil)
661 (:constructor make-js2-token (beg)))
662 "Value returned from the token stream."
663 (type js2-EOF)
664 (beg 1)
665 (end -1)
666 (string "")
667 number
668 number-base
669 regexp-flags
670 comment-type
671 follows-eol-p)
672
673 ;; Have to call `js2-init-scanner' to initialize the values.
674 (js2-deflocal js2-ti-tokens nil)
675 (js2-deflocal js2-ti-tokens-cursor nil)
676 (js2-deflocal js2-ti-lookahead nil)
677
678 (cl-defstruct (js2-ts-state
679 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
680 (cursor js2-ts-cursor)
681 (tokens (copy-sequence js2-ti-tokens))
682 (tokens-cursor js2-ti-tokens-cursor)
683 (lookahead js2-ti-lookahead))))
684 lineno
685 cursor
686 tokens
687 tokens-cursor
688 lookahead)
689
690 ;;; Parser variables
691
692 (js2-deflocal js2-parsed-errors nil
693 "List of errors produced during scanning/parsing.")
694
695 (js2-deflocal js2-parsed-warnings nil
696 "List of warnings produced during scanning/parsing.")
697
698 (js2-deflocal js2-recover-from-parse-errors t
699 "Non-nil to continue parsing after a syntax error.
700
701 In recovery mode, the AST will be built in full, and any error
702 nodes will be flagged with appropriate error information. If
703 this flag is nil, a syntax error will result in an error being
704 signaled.
705
706 The variable is automatically buffer-local, because different
707 modes that use the parser will need different settings.")
708
709 (js2-deflocal js2-parse-hook nil
710 "List of callbacks for receiving parsing progress.")
711
712 (defvar js2-parse-finished-hook nil
713 "List of callbacks to notify when parsing finishes.
714 Not called if parsing was interrupted.")
715
716 (js2-deflocal js2-is-eval-code nil
717 "True if we're evaluating code in a string.
718 If non-nil, the tokenizer will record the token text, and the AST nodes
719 will record their source text. Off by default for IDE modes, since the
720 text is available in the buffer.")
721
722 (defvar js2-parse-ide-mode t
723 "Non-nil if the parser is being used for `js2-mode'.
724 If non-nil, the parser will set text properties for fontification
725 and the syntax table. The value should be nil when using the
726 parser as a frontend to an interpreter or byte compiler.")
727
728 ;;; Parser instance variables (buffer-local vars for js2-parse)
729
730 (defconst js2-ti-after-eol (lsh 1 16)
731 "Flag: first token of the source line.")
732
733 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
734
735 (js2-deflocal js2-compiler-generate-debug-info t)
736 (js2-deflocal js2-compiler-use-dynamic-scope nil)
737 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
738 (js2-deflocal js2-compiler-xml-available t)
739 (js2-deflocal js2-compiler-optimization-level 0)
740 (js2-deflocal js2-compiler-generating-source t)
741 (js2-deflocal js2-compiler-strict-mode nil)
742 (js2-deflocal js2-compiler-report-warning-as-error nil)
743 (js2-deflocal js2-compiler-generate-observer-count nil)
744 (js2-deflocal js2-compiler-activation-names nil)
745
746 ;; SKIP: sourceURI
747
748 ;; There's a compileFunction method in Context.java - may need it.
749 (js2-deflocal js2-called-by-compile-function nil
750 "True if `js2-parse' was called by `js2-compile-function'.
751 Will only be used when we finish implementing the interpreter.")
752
753 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
754
755 ;; SKIP: node factory - we're going to just call functions directly,
756 ;; and eventually go to a unified AST format.
757
758 (js2-deflocal js2-nesting-of-function 0)
759
760 (js2-deflocal js2-recorded-identifiers nil
761 "Tracks identifiers found during parsing.")
762
763 (js2-deflocal js2-is-in-destructuring nil
764 "True while parsing destructuring expression.")
765
766 (js2-deflocal js2-in-use-strict-directive nil
767 "True while inside a script or function under strict mode.")
768
769 (defcustom js2-global-externs nil
770 "A list of any extern names you'd like to consider always declared.
771 This list is global and is used by all `js2-mode' files.
772 You can create buffer-local externs list using `js2-additional-externs'.
773
774 There is also a buffer-local variable `js2-default-externs',
775 which is initialized by default to include the Ecma-262 externs
776 and the standard browser externs. The three lists are all
777 checked during highlighting."
778 :type 'list
779 :group 'js2-mode)
780
781 (js2-deflocal js2-default-externs nil
782 "Default external declarations.
783
784 These are currently only used for highlighting undeclared variables,
785 which only worries about top-level (unqualified) references.
786 As js2-mode's processing improves, we will flesh out this list.
787
788 The initial value is set to `js2-ecma-262-externs', unless some
789 of the `js2-include-?-externs' variables are set to t, in which
790 case the browser, Rhino and/or Node.js externs are also included.
791
792 See `js2-additional-externs' for more information.")
793
794 (defcustom js2-include-browser-externs t
795 "Non-nil to include browser externs in the master externs list.
796 If you work on JavaScript files that are not intended for browsers,
797 such as Mozilla Rhino server-side JavaScript, set this to nil.
798 See `js2-additional-externs' for more information about externs."
799 :type 'boolean
800 :group 'js2-mode)
801
802 (defcustom js2-include-rhino-externs nil
803 "Non-nil to include Mozilla Rhino externs in the master externs list.
804 See `js2-additional-externs' for more information about externs."
805 :type 'boolean
806 :group 'js2-mode)
807
808 (defcustom js2-include-node-externs nil
809 "Non-nil to include Node.js externs in the master externs list.
810 See `js2-additional-externs' for more information about externs."
811 :type 'boolean
812 :group 'js2-mode)
813
814 (js2-deflocal js2-additional-externs nil
815 "A buffer-local list of additional external declarations.
816 It is used to decide whether variables are considered undeclared
817 for purposes of highlighting.
818
819 Each entry is a Lisp string. The string should be the fully qualified
820 name of an external entity. All externs should be added to this list,
821 so that as js2-mode's processing improves it can take advantage of them.
822
823 You may want to declare your externs in three ways.
824 First, you can add externs that are valid for all your JavaScript files.
825 You should probably do this by adding them to `js2-global-externs', which
826 is a global list used for all js2-mode files.
827
828 Next, you can add a function to `js2-init-hook' that adds additional
829 externs appropriate for the specific file, perhaps based on its path.
830 These should go in `js2-additional-externs', which is buffer-local.
831
832 Third, you can use JSLint's global declaration, as long as
833 `js2-include-jslint-globals' is non-nil, which see.
834
835 Finally, you can add a function to `js2-post-parse-callbacks',
836 which is called after parsing completes, and `js2-mode-ast' is bound to
837 the root of the parse tree. At this stage you can set up an AST
838 node visitor using `js2-visit-ast' and examine the parse tree
839 for specific import patterns that may imply the existence of
840 other externs, possibly tied to your build system. These should also
841 be added to `js2-additional-externs'.
842
843 Your post-parse callback may of course also use the simpler and
844 faster (but perhaps less robust) approach of simply scanning the
845 buffer text for your imports, using regular expressions.")
846
847 ;; SKIP: decompiler
848 ;; SKIP: encoded-source
849
850 ;;; The following variables are per-function and should be saved/restored
851 ;;; during function parsing...
852
853 (js2-deflocal js2-current-script-or-fn nil)
854 (js2-deflocal js2-current-scope nil)
855 (js2-deflocal js2-nesting-of-with 0)
856 (js2-deflocal js2-label-set nil
857 "An alist mapping label names to nodes.")
858
859 (js2-deflocal js2-loop-set nil)
860 (js2-deflocal js2-loop-and-switch-set nil)
861 (js2-deflocal js2-has-return-value nil)
862 (js2-deflocal js2-end-flags 0)
863
864 ;;; ...end of per function variables
865
866 ;; These flags enumerate the possible ways a statement/function can
867 ;; terminate. These flags are used by endCheck() and by the Parser to
868 ;; detect inconsistent return usage.
869 ;;
870 ;; END_UNREACHED is reserved for code paths that are assumed to always be
871 ;; able to execute (example: throw, continue)
872 ;;
873 ;; END_DROPS_OFF indicates if the statement can transfer control to the
874 ;; next one. Statement such as return dont. A compound statement may have
875 ;; some branch that drops off control to the next statement.
876 ;;
877 ;; END_RETURNS indicates that the statement can return (without arguments)
878 ;; END_RETURNS_VALUE indicates that the statement can return a value.
879 ;;
880 ;; A compound statement such as
881 ;; if (condition) {
882 ;; return value;
883 ;; }
884 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
885
886 (defconst js2-end-unreached #x0)
887 (defconst js2-end-drops-off #x1)
888 (defconst js2-end-returns #x2)
889 (defconst js2-end-returns-value #x4)
890
891 ;; Rhino awkwardly passes a statementLabel parameter to the
892 ;; statementHelper() function, the main statement parser, which
893 ;; is then used by quite a few of the sub-parsers. We just make
894 ;; it a buffer-local variable and make sure it's cleaned up properly.
895 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
896
897 ;; Similarly, Rhino passes an inForInit boolean through about half
898 ;; the expression parsers. We use a dynamically-scoped variable,
899 ;; which makes it easier to funcall the parsers individually without
900 ;; worrying about whether they take the parameter or not.
901 (js2-deflocal js2-in-for-init nil)
902 (js2-deflocal js2-temp-name-counter 0)
903 (js2-deflocal js2-parse-stmt-count 0)
904
905 (defsubst js2-get-next-temp-name ()
906 (format "$%d" (cl-incf js2-temp-name-counter)))
907
908 (defvar js2-parse-interruptable-p t
909 "Set this to nil to force parse to continue until finished.
910 This will mostly be useful for interpreters.")
911
912 (defvar js2-statements-per-pause 50
913 "Pause after this many statements to check for user input.
914 If user input is pending, stop the parse and discard the tree.
915 This makes for a smoother user experience for large files.
916 You may have to wait a second or two before the highlighting
917 and error-reporting appear, but you can always type ahead if
918 you wish. This appears to be more or less how Eclipse, IntelliJ
919 and other editors work.")
920
921 (js2-deflocal js2-record-comments t
922 "Instructs the scanner to record comments in `js2-scanned-comments'.")
923
924 (js2-deflocal js2-scanned-comments nil
925 "List of all comments from the current parse.")
926
927 (defcustom js2-mode-indent-inhibit-undo nil
928 "Non-nil to disable collection of Undo information when indenting lines.
929 Some users have requested this behavior. It's nil by default because
930 other Emacs modes don't work this way."
931 :type 'boolean
932 :group 'js2-mode)
933
934 (defcustom js2-mode-indent-ignore-first-tab nil
935 "If non-nil, ignore first TAB keypress if we look indented properly.
936 It's fairly common for users to navigate to an already-indented line
937 and press TAB for reassurance that it's been indented. For this class
938 of users, we want the first TAB press on a line to be ignored if the
939 line is already indented to one of the precomputed alternatives.
940
941 This behavior is only partly implemented. If you TAB-indent a line,
942 navigate to another line, and then navigate back, it fails to clear
943 the last-indented variable, so it thinks you've already hit TAB once,
944 and performs the indent. A full solution would involve getting on the
945 point-motion hooks for the entire buffer. If we come across another
946 use cases that requires watching point motion, I'll consider doing it.
947
948 If you set this variable to nil, then the TAB key will always change
949 the indentation of the current line, if more than one alternative
950 indentation spot exists."
951 :type 'boolean
952 :group 'js2-mode)
953
954 (defvar js2-indent-hook nil
955 "A hook for user-defined indentation rules.
956
957 Functions on this hook should expect two arguments: (LIST INDEX)
958 The LIST argument is the list of computed indentation points for
959 the current line. INDEX is the list index of the indentation point
960 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
961 indent function is not going to change the current line indentation.
962
963 If a hook function on this list returns a non-nil value, then
964 `js2-bounce-indent' assumes the hook function has performed its own
965 indentation, and will do nothing. If all hook functions on the list
966 return nil, then `js2-bounce-indent' will use its computed indentation
967 and reindent the line.
968
969 When hook functions on this hook list are called, the variable
970 `js2-mode-ast' may or may not be set, depending on whether the
971 parse tree is available. If the variable is nil, you can pass a
972 callback to `js2-mode-wait-for-parse', and your callback will be
973 called after the new parse tree is built. This can take some time
974 in large files.")
975
976 (defface js2-warning
977 `((((class color) (background light))
978 (:underline "orange"))
979 (((class color) (background dark))
980 (:underline "orange"))
981 (t (:underline t)))
982 "Face for JavaScript warnings."
983 :group 'js2-mode)
984
985 (defface js2-error
986 `((((class color) (background light))
987 (:foreground "red"))
988 (((class color) (background dark))
989 (:foreground "red"))
990 (t (:foreground "red")))
991 "Face for JavaScript errors."
992 :group 'js2-mode)
993
994 (defface js2-jsdoc-tag
995 '((t :foreground "SlateGray"))
996 "Face used to highlight @whatever tags in jsdoc comments."
997 :group 'js2-mode)
998
999 (defface js2-jsdoc-type
1000 '((t :foreground "SteelBlue"))
1001 "Face used to highlight {FooBar} types in jsdoc comments."
1002 :group 'js2-mode)
1003
1004 (defface js2-jsdoc-value
1005 '((t :foreground "PeachPuff3"))
1006 "Face used to highlight tag values in jsdoc comments."
1007 :group 'js2-mode)
1008
1009 (defface js2-function-param
1010 '((t :foreground "SeaGreen"))
1011 "Face used to highlight function parameters in javascript."
1012 :group 'js2-mode)
1013
1014 (defface js2-function-call
1015 '((t :inherit default))
1016 "Face used to highlight function name in calls."
1017 :group 'js2-mode)
1018
1019 (defface js2-instance-member
1020 '((t :foreground "DarkOrchid"))
1021 "Face used to highlight instance variables in javascript.
1022 Not currently used."
1023 :group 'js2-mode)
1024
1025 (defface js2-private-member
1026 '((t :foreground "PeachPuff3"))
1027 "Face used to highlight calls to private methods in javascript.
1028 Not currently used."
1029 :group 'js2-mode)
1030
1031 (defface js2-private-function-call
1032 '((t :foreground "goldenrod"))
1033 "Face used to highlight calls to private functions in javascript.
1034 Not currently used."
1035 :group 'js2-mode)
1036
1037 (defface js2-jsdoc-html-tag-name
1038 '((((class color) (min-colors 88) (background light))
1039 (:foreground "rosybrown"))
1040 (((class color) (min-colors 8) (background dark))
1041 (:foreground "yellow"))
1042 (((class color) (min-colors 8) (background light))
1043 (:foreground "magenta")))
1044 "Face used to highlight jsdoc html tag names"
1045 :group 'js2-mode)
1046
1047 (defface js2-jsdoc-html-tag-delimiter
1048 '((((class color) (min-colors 88) (background light))
1049 (:foreground "dark khaki"))
1050 (((class color) (min-colors 8) (background dark))
1051 (:foreground "green"))
1052 (((class color) (min-colors 8) (background light))
1053 (:foreground "green")))
1054 "Face used to highlight brackets in jsdoc html tags."
1055 :group 'js2-mode)
1056
1057 (defface js2-external-variable
1058 '((t :foreground "orange"))
1059 "Face used to highlight undeclared variable identifiers.")
1060
1061 (defcustom js2-init-hook nil
1062 "List of functions to be called after `js2-mode' or
1063 `js2-minor-mode' has initialized all variables, before parsing
1064 the buffer for the first time."
1065 :type 'hook
1066 :group 'js2-mode
1067 :version "20130608")
1068
1069 (defcustom js2-post-parse-callbacks nil
1070 "List of callback functions invoked after parsing finishes.
1071 Currently, the main use for this function is to add synthetic
1072 declarations to `js2-recorded-identifiers', which see."
1073 :type 'hook
1074 :group 'js2-mode)
1075
1076 (defcustom js2-build-imenu-callbacks nil
1077 "List of functions called during Imenu index generation.
1078 It's a good place to add additional entries to it, using
1079 `js2-record-imenu-entry'."
1080 :type 'hook
1081 :group 'js2-mode)
1082
1083 (defcustom js2-highlight-external-variables t
1084 "Non-nil to highlight undeclared variable identifiers.
1085 An undeclared variable is any variable not declared with var or let
1086 in the current scope or any lexically enclosing scope. If you use
1087 such a variable, then you are either expecting it to originate from
1088 another file, or you've got a potential bug."
1089 :type 'boolean
1090 :group 'js2-mode)
1091
1092 (defcustom js2-warn-about-unused-function-arguments nil
1093 "Non-nil to treat function arguments like declared-but-unused variables."
1094 :type 'booleanp
1095 :group 'js2-mode)
1096
1097 (defcustom js2-include-jslint-globals t
1098 "Non-nil to include the identifiers from JSLint global
1099 declaration (see http://www.jslint.com/lint.html#global) in the
1100 buffer-local externs list. See `js2-additional-externs' for more
1101 information."
1102 :type 'boolean
1103 :group 'js2-mode)
1104
1105 (defvar js2-mode-map
1106 (let ((map (make-sparse-keymap)))
1107 (define-key map [mouse-1] #'js2-mode-show-node)
1108 (define-key map (kbd "M-j") #'js2-line-break)
1109 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1110 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1111 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1112 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1113 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1114 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1115 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1116 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1117
1118 (define-key map [menu-bar javascript]
1119 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1120
1121 (define-key map [menu-bar javascript customize-js2-mode]
1122 '(menu-item "Customize js2-mode" js2-mode-customize
1123 :help "Customize the behavior of this mode"))
1124
1125 (define-key map [menu-bar javascript js2-force-refresh]
1126 '(menu-item "Force buffer refresh" js2-mode-reset
1127 :help "Re-parse the buffer from scratch"))
1128
1129 (define-key map [menu-bar javascript separator-2]
1130 '("--"))
1131
1132 (define-key map [menu-bar javascript next-error]
1133 '(menu-item "Next warning or error" next-error
1134 :enabled (and js2-mode-ast
1135 (or (js2-ast-root-errors js2-mode-ast)
1136 (js2-ast-root-warnings js2-mode-ast)))
1137 :help "Move to next warning or error"))
1138
1139 (define-key map [menu-bar javascript display-errors]
1140 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1141 :visible (not js2-mode-show-parse-errors)
1142 :help "Turn on display of warnings and errors"))
1143
1144 (define-key map [menu-bar javascript hide-errors]
1145 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1146 :visible js2-mode-show-parse-errors
1147 :help "Turn off display of warnings and errors"))
1148
1149 (define-key map [menu-bar javascript separator-1]
1150 '("--"))
1151
1152 (define-key map [menu-bar javascript js2-toggle-function]
1153 '(menu-item "Show/collapse element" js2-mode-toggle-element
1154 :help "Hide or show function body or comment"))
1155
1156 (define-key map [menu-bar javascript show-comments]
1157 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1158 :visible js2-mode-comments-hidden
1159 :help "Expand all hidden block comments"))
1160
1161 (define-key map [menu-bar javascript hide-comments]
1162 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1163 :visible (not js2-mode-comments-hidden)
1164 :help "Show block comments as /*...*/"))
1165
1166 (define-key map [menu-bar javascript show-all-functions]
1167 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1168 :visible js2-mode-functions-hidden
1169 :help "Expand all hidden function bodies"))
1170
1171 (define-key map [menu-bar javascript hide-all-functions]
1172 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1173 :visible (not js2-mode-functions-hidden)
1174 :help "Show {...} for all top-level function bodies"))
1175
1176 map)
1177 "Keymap used in `js2-mode' buffers.")
1178
1179 (defcustom js2-bounce-indent-p nil
1180 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1181 They will augment the default indent-line behavior with cycling
1182 among several computed alternatives. See the function
1183 `js2-bounce-indent' for details. The above commands will be
1184 bound to TAB and backtab."
1185 :type 'boolean
1186 :group 'js2-mode
1187 :set (lambda (sym value)
1188 (set-default sym value)
1189 (let ((map js2-mode-map))
1190 (if (not value)
1191 (progn
1192 (define-key map "\t" nil)
1193 (define-key map (kbd "<backtab>") nil))
1194 (define-key map "\t" #'js2-indent-bounce)
1195 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1196
1197 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1198
1199 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1200 "Matches a //-comment line. Must be first non-whitespace on line.
1201 First match-group is the leading whitespace.")
1202
1203 (defvar js2-mode-hook nil)
1204
1205 (js2-deflocal js2-mode-ast nil "Private variable.")
1206 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1207 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1208 (js2-deflocal js2-mode-parsing nil "Private variable.")
1209 (js2-deflocal js2-mode-node-overlay nil)
1210
1211 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1212 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1213
1214 (js2-deflocal js2-mode-fontifications nil "Private variable")
1215 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1216 (js2-deflocal js2-imenu-recorder nil "Private variable")
1217 (js2-deflocal js2-imenu-function-map nil "Private variable")
1218
1219 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1220 "Non-nil to emit status messages during parsing.")
1221
1222 (defvar js2-mode-functions-hidden nil "Private variable.")
1223 (defvar js2-mode-comments-hidden nil "Private variable.")
1224
1225 (defvar js2-mode-syntax-table
1226 (let ((table (make-syntax-table)))
1227 (c-populate-syntax-table table)
1228 (modify-syntax-entry ?` "\"" table)
1229 table)
1230 "Syntax table used in `js2-mode' buffers.")
1231
1232 (defvar js2-mode-abbrev-table nil
1233 "Abbrev table in use in `js2-mode' buffers.")
1234 (define-abbrev-table 'js2-mode-abbrev-table ())
1235
1236 (defvar js2-mode-pending-parse-callbacks nil
1237 "List of functions waiting to be notified that parse is finished.")
1238
1239 (defvar js2-mode-last-indented-line -1)
1240
1241 ;;; Localizable error and warning messages
1242
1243 ;; Messages are copied from Rhino's Messages.properties.
1244 ;; Many of the Java-specific messages have been elided.
1245 ;; Add any js2-specific ones at the end, so we can keep
1246 ;; this file synced with changes to Rhino's.
1247
1248 (defvar js2-message-table
1249 (make-hash-table :test 'equal :size 250)
1250 "Contains localized messages for `js2-mode'.")
1251
1252 ;; TODO(stevey): construct this table at compile-time.
1253 (defmacro js2-msg (key &rest strings)
1254 `(puthash ,key (concat ,@strings)
1255 js2-message-table))
1256
1257 (defun js2-get-msg (msg-key)
1258 "Look up a localized message.
1259 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1260 the correct number of ARGS must be provided."
1261 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1262 (args (if (listp msg-key) (cdr msg-key)))
1263 (msg (gethash key js2-message-table)))
1264 (if msg
1265 (apply #'format msg args)
1266 key))) ; default to showing the key
1267
1268 (js2-msg "msg.dup.parms"
1269 "Duplicate parameter name '%s'.")
1270
1271 (js2-msg "msg.too.big.jump"
1272 "Program too complex: jump offset too big.")
1273
1274 (js2-msg "msg.too.big.index"
1275 "Program too complex: internal index exceeds 64K limit.")
1276
1277 (js2-msg "msg.while.compiling.fn"
1278 "Encountered code generation error while compiling function '%s': %s")
1279
1280 (js2-msg "msg.while.compiling.script"
1281 "Encountered code generation error while compiling script: %s")
1282
1283 ;; Context
1284 (js2-msg "msg.ctor.not.found"
1285 "Constructor for '%s' not found.")
1286
1287 (js2-msg "msg.not.ctor"
1288 "'%s' is not a constructor.")
1289
1290 ;; FunctionObject
1291 (js2-msg "msg.varargs.ctor"
1292 "Method or constructor '%s' must be static "
1293 "with the signature (Context cx, Object[] args, "
1294 "Function ctorObj, boolean inNewExpr) "
1295 "to define a variable arguments constructor.")
1296
1297 (js2-msg "msg.varargs.fun"
1298 "Method '%s' must be static with the signature "
1299 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1300 "to define a variable arguments function.")
1301
1302 (js2-msg "msg.incompat.call"
1303 "Method '%s' called on incompatible object.")
1304
1305 (js2-msg "msg.bad.parms"
1306 "Unsupported parameter type '%s' in method '%s'.")
1307
1308 (js2-msg "msg.bad.method.return"
1309 "Unsupported return type '%s' in method '%s'.")
1310
1311 (js2-msg "msg.bad.ctor.return"
1312 "Construction of objects of type '%s' is not supported.")
1313
1314 (js2-msg "msg.no.overload"
1315 "Method '%s' occurs multiple times in class '%s'.")
1316
1317 (js2-msg "msg.method.not.found"
1318 "Method '%s' not found in '%s'.")
1319
1320 ;; IRFactory
1321
1322 (js2-msg "msg.bad.for.in.lhs"
1323 "Invalid left-hand side of for..in loop.")
1324
1325 (js2-msg "msg.mult.index"
1326 "Only one variable allowed in for..in loop.")
1327
1328 (js2-msg "msg.bad.for.in.destruct"
1329 "Left hand side of for..in loop must be an array of "
1330 "length 2 to accept key/value pair.")
1331
1332 (js2-msg "msg.cant.convert"
1333 "Can't convert to type '%s'.")
1334
1335 (js2-msg "msg.bad.assign.left"
1336 "Invalid assignment left-hand side.")
1337
1338 (js2-msg "msg.bad.decr"
1339 "Invalid decrement operand.")
1340
1341 (js2-msg "msg.bad.incr"
1342 "Invalid increment operand.")
1343
1344 (js2-msg "msg.bad.yield"
1345 "yield must be in a function.")
1346
1347 (js2-msg "msg.yield.parenthesized"
1348 "yield expression must be parenthesized.")
1349
1350 ;; NativeGlobal
1351 (js2-msg "msg.cant.call.indirect"
1352 "Function '%s' must be called directly, and not by way of a "
1353 "function of another name.")
1354
1355 (js2-msg "msg.eval.nonstring"
1356 "Calling eval() with anything other than a primitive "
1357 "string value will simply return the value. "
1358 "Is this what you intended?")
1359
1360 (js2-msg "msg.eval.nonstring.strict"
1361 "Calling eval() with anything other than a primitive "
1362 "string value is not allowed in strict mode.")
1363
1364 (js2-msg "msg.bad.destruct.op"
1365 "Invalid destructuring assignment operator")
1366
1367 ;; NativeCall
1368 (js2-msg "msg.only.from.new"
1369 "'%s' may only be invoked from a `new' expression.")
1370
1371 (js2-msg "msg.deprec.ctor"
1372 "The '%s' constructor is deprecated.")
1373
1374 ;; NativeFunction
1375 (js2-msg "msg.no.function.ref.found"
1376 "no source found to decompile function reference %s")
1377
1378 (js2-msg "msg.arg.isnt.array"
1379 "second argument to Function.prototype.apply must be an array")
1380
1381 ;; NativeGlobal
1382 (js2-msg "msg.bad.esc.mask"
1383 "invalid string escape mask")
1384
1385 ;; NativeRegExp
1386 (js2-msg "msg.bad.quant"
1387 "Invalid quantifier %s")
1388
1389 (js2-msg "msg.overlarge.backref"
1390 "Overly large back reference %s")
1391
1392 (js2-msg "msg.overlarge.min"
1393 "Overly large minimum %s")
1394
1395 (js2-msg "msg.overlarge.max"
1396 "Overly large maximum %s")
1397
1398 (js2-msg "msg.zero.quant"
1399 "Zero quantifier %s")
1400
1401 (js2-msg "msg.max.lt.min"
1402 "Maximum %s less than minimum")
1403
1404 (js2-msg "msg.unterm.quant"
1405 "Unterminated quantifier %s")
1406
1407 (js2-msg "msg.unterm.paren"
1408 "Unterminated parenthetical %s")
1409
1410 (js2-msg "msg.unterm.class"
1411 "Unterminated character class %s")
1412
1413 (js2-msg "msg.bad.range"
1414 "Invalid range in character class.")
1415
1416 (js2-msg "msg.trail.backslash"
1417 "Trailing \\ in regular expression.")
1418
1419 (js2-msg "msg.re.unmatched.right.paren"
1420 "unmatched ) in regular expression.")
1421
1422 (js2-msg "msg.no.regexp"
1423 "Regular expressions are not available.")
1424
1425 (js2-msg "msg.bad.backref"
1426 "back-reference exceeds number of capturing parentheses.")
1427
1428 (js2-msg "msg.bad.regexp.compile"
1429 "Only one argument may be specified if the first "
1430 "argument to RegExp.prototype.compile is a RegExp object.")
1431
1432 ;; Parser
1433 (js2-msg "msg.got.syntax.errors"
1434 "Compilation produced %s syntax errors.")
1435
1436 (js2-msg "msg.var.redecl"
1437 "TypeError: redeclaration of var %s.")
1438
1439 (js2-msg "msg.const.redecl"
1440 "TypeError: redeclaration of const %s.")
1441
1442 (js2-msg "msg.let.redecl"
1443 "TypeError: redeclaration of variable %s.")
1444
1445 (js2-msg "msg.parm.redecl"
1446 "TypeError: redeclaration of formal parameter %s.")
1447
1448 (js2-msg "msg.fn.redecl"
1449 "TypeError: redeclaration of function %s.")
1450
1451 (js2-msg "msg.let.decl.not.in.block"
1452 "SyntaxError: let declaration not directly within block")
1453
1454 (js2-msg "msg.mod.import.decl.at.top.level"
1455 "SyntaxError: import declarations may only appear at the top level")
1456
1457 (js2-msg "msg.mod.as.after.reserved.word"
1458 "SyntaxError: missing keyword 'as' after reserved word %s")
1459
1460 (js2-msg "msg.mod.rc.after.import.spec.list"
1461 "SyntaxError: missing '}' after module specifier list")
1462
1463 (js2-msg "msg.mod.from.after.import.spec.set"
1464 "SyntaxError: missing keyword 'from' after import specifier set")
1465
1466 (js2-msg "msg.mod.declaration.after.import"
1467 "SyntaxError: missing declaration after 'import' keyword")
1468
1469 (js2-msg "msg.mod.spec.after.from"
1470 "SyntaxError: missing module specifier after 'from' keyword")
1471
1472 (js2-msg "msg.mod.export.decl.at.top.level"
1473 "SyntaxError: export declarations may only appear at top level")
1474
1475 (js2-msg "msg.mod.rc.after.export.spec.list"
1476 "SyntaxError: missing '}' after export specifier list")
1477
1478 ;; NodeTransformer
1479 (js2-msg "msg.dup.label"
1480 "duplicated label")
1481
1482 (js2-msg "msg.undef.label"
1483 "undefined label")
1484
1485 (js2-msg "msg.bad.break"
1486 "unlabelled break must be inside loop or switch")
1487
1488 (js2-msg "msg.continue.outside"
1489 "continue must be inside loop")
1490
1491 (js2-msg "msg.continue.nonloop"
1492 "continue can only use labels of iteration statements")
1493
1494 (js2-msg "msg.bad.throw.eol"
1495 "Line terminator is not allowed between the throw "
1496 "keyword and throw expression.")
1497
1498 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1499 "function statement requires a name")
1500
1501 (js2-msg "msg.no.paren.parms"
1502 "missing ( before function parameters.")
1503
1504 (js2-msg "msg.no.parm"
1505 "missing formal parameter")
1506
1507 (js2-msg "msg.no.paren.after.parms"
1508 "missing ) after formal parameters")
1509
1510 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1511 "parameter without default follows parameter with default")
1512
1513 (js2-msg "msg.param.after.rest" ; added by js2-mode
1514 "parameter after rest parameter")
1515
1516 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1517 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1518
1519 (js2-msg "msg.no.brace.body"
1520 "missing '{' before function body")
1521
1522 (js2-msg "msg.no.brace.after.body"
1523 "missing } after function body")
1524
1525 (js2-msg "msg.no.paren.cond"
1526 "missing ( before condition")
1527
1528 (js2-msg "msg.no.paren.after.cond"
1529 "missing ) after condition")
1530
1531 (js2-msg "msg.no.semi.stmt"
1532 "missing ; before statement")
1533
1534 (js2-msg "msg.missing.semi"
1535 "missing ; after statement")
1536
1537 (js2-msg "msg.no.name.after.dot"
1538 "missing name after . operator")
1539
1540 (js2-msg "msg.no.name.after.coloncolon"
1541 "missing name after :: operator")
1542
1543 (js2-msg "msg.no.name.after.dotdot"
1544 "missing name after .. operator")
1545
1546 (js2-msg "msg.no.name.after.xmlAttr"
1547 "missing name after .@")
1548
1549 (js2-msg "msg.no.bracket.index"
1550 "missing ] in index expression")
1551
1552 (js2-msg "msg.no.paren.switch"
1553 "missing ( before switch expression")
1554
1555 (js2-msg "msg.no.paren.after.switch"
1556 "missing ) after switch expression")
1557
1558 (js2-msg "msg.no.brace.switch"
1559 "missing '{' before switch body")
1560
1561 (js2-msg "msg.bad.switch"
1562 "invalid switch statement")
1563
1564 (js2-msg "msg.no.colon.case"
1565 "missing : after case expression")
1566
1567 (js2-msg "msg.double.switch.default"
1568 "double default label in the switch statement")
1569
1570 (js2-msg "msg.no.while.do"
1571 "missing while after do-loop body")
1572
1573 (js2-msg "msg.no.paren.for"
1574 "missing ( after for")
1575
1576 (js2-msg "msg.no.semi.for"
1577 "missing ; after for-loop initializer")
1578
1579 (js2-msg "msg.no.semi.for.cond"
1580 "missing ; after for-loop condition")
1581
1582 (js2-msg "msg.in.after.for.name"
1583 "missing in or of after for")
1584
1585 (js2-msg "msg.no.paren.for.ctrl"
1586 "missing ) after for-loop control")
1587
1588 (js2-msg "msg.no.paren.with"
1589 "missing ( before with-statement object")
1590
1591 (js2-msg "msg.no.paren.after.with"
1592 "missing ) after with-statement object")
1593
1594 (js2-msg "msg.no.with.strict"
1595 "with statements not allowed in strict mode")
1596
1597 (js2-msg "msg.no.paren.after.let"
1598 "missing ( after let")
1599
1600 (js2-msg "msg.no.paren.let"
1601 "missing ) after variable list")
1602
1603 (js2-msg "msg.no.curly.let"
1604 "missing } after let statement")
1605
1606 (js2-msg "msg.bad.return"
1607 "invalid return")
1608
1609 (js2-msg "msg.no.brace.block"
1610 "missing } in compound statement")
1611
1612 (js2-msg "msg.bad.label"
1613 "invalid label")
1614
1615 (js2-msg "msg.bad.var"
1616 "missing variable name")
1617
1618 (js2-msg "msg.bad.var.init"
1619 "invalid variable initialization")
1620
1621 (js2-msg "msg.no.colon.cond"
1622 "missing : in conditional expression")
1623
1624 (js2-msg "msg.no.paren.arg"
1625 "missing ) after argument list")
1626
1627 (js2-msg "msg.no.bracket.arg"
1628 "missing ] after element list")
1629
1630 (js2-msg "msg.bad.prop"
1631 "invalid property id")
1632
1633 (js2-msg "msg.no.colon.prop"
1634 "missing : after property id")
1635
1636 (js2-msg "msg.no.brace.prop"
1637 "missing } after property list")
1638
1639 (js2-msg "msg.no.paren"
1640 "missing ) in parenthetical")
1641
1642 (js2-msg "msg.reserved.id"
1643 "'%s' is a reserved identifier")
1644
1645 (js2-msg "msg.no.paren.catch"
1646 "missing ( before catch-block condition")
1647
1648 (js2-msg "msg.bad.catchcond"
1649 "invalid catch block condition")
1650
1651 (js2-msg "msg.catch.unreachable"
1652 "any catch clauses following an unqualified catch are unreachable")
1653
1654 (js2-msg "msg.no.brace.try"
1655 "missing '{' before try block")
1656
1657 (js2-msg "msg.no.brace.catchblock"
1658 "missing '{' before catch-block body")
1659
1660 (js2-msg "msg.try.no.catchfinally"
1661 "'try' without 'catch' or 'finally'")
1662
1663 (js2-msg "msg.no.return.value"
1664 "function %s does not always return a value")
1665
1666 (js2-msg "msg.anon.no.return.value"
1667 "anonymous function does not always return a value")
1668
1669 (js2-msg "msg.return.inconsistent"
1670 "return statement is inconsistent with previous usage")
1671
1672 (js2-msg "msg.generator.returns"
1673 "TypeError: legacy generator function '%s' returns a value")
1674
1675 (js2-msg "msg.anon.generator.returns"
1676 "TypeError: anonymous legacy generator function returns a value")
1677
1678 (js2-msg "msg.syntax"
1679 "syntax error")
1680
1681 (js2-msg "msg.unexpected.eof"
1682 "Unexpected end of file")
1683
1684 (js2-msg "msg.XML.bad.form"
1685 "illegally formed XML syntax")
1686
1687 (js2-msg "msg.XML.not.available"
1688 "XML runtime not available")
1689
1690 (js2-msg "msg.too.deep.parser.recursion"
1691 "Too deep recursion while parsing")
1692
1693 (js2-msg "msg.no.side.effects"
1694 "Code has no side effects")
1695
1696 (js2-msg "msg.extra.trailing.comma"
1697 "Trailing comma is not supported in some browsers")
1698
1699 (js2-msg "msg.array.trailing.comma"
1700 "Trailing comma yields different behavior across browsers")
1701
1702 (js2-msg "msg.equal.as.assign"
1703 (concat "Test for equality (==) mistyped as assignment (=)?"
1704 " (parenthesize to suppress warning)"))
1705
1706 (js2-msg "msg.var.hides.arg"
1707 "Variable %s hides argument")
1708
1709 (js2-msg "msg.destruct.assign.no.init"
1710 "Missing = in destructuring declaration")
1711
1712 (js2-msg "msg.no.octal.strict"
1713 "Octal numbers prohibited in strict mode.")
1714
1715 (js2-msg "msg.dup.obj.lit.prop.strict"
1716 "Property '%s' already defined in this object literal.")
1717
1718 (js2-msg "msg.dup.param.strict"
1719 "Parameter '%s' already declared in this function.")
1720
1721 (js2-msg "msg.bad.id.strict"
1722 "'%s' is not a valid identifier for this use in strict mode.")
1723
1724 ;; ScriptRuntime
1725 (js2-msg "msg.no.properties"
1726 "%s has no properties.")
1727
1728 (js2-msg "msg.invalid.iterator"
1729 "Invalid iterator value")
1730
1731 (js2-msg "msg.iterator.primitive"
1732 "__iterator__ returned a primitive value")
1733
1734 (js2-msg "msg.assn.create.strict"
1735 "Assignment to undeclared variable %s")
1736
1737 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1738 "Undeclared variable or function '%s'")
1739
1740 (js2-msg "msg.unused.variable" ; added by js2-mode
1741 "Unused variable or function '%s'")
1742
1743 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1744 "Variable '%s' referenced but never initialized")
1745
1746 (js2-msg "msg.ref.undefined.prop"
1747 "Reference to undefined property '%s'")
1748
1749 (js2-msg "msg.prop.not.found"
1750 "Property %s not found.")
1751
1752 (js2-msg "msg.invalid.type"
1753 "Invalid JavaScript value of type %s")
1754
1755 (js2-msg "msg.primitive.expected"
1756 "Primitive type expected (had %s instead)")
1757
1758 (js2-msg "msg.namespace.expected"
1759 "Namespace object expected to left of :: (found %s instead)")
1760
1761 (js2-msg "msg.null.to.object"
1762 "Cannot convert null to an object.")
1763
1764 (js2-msg "msg.undef.to.object"
1765 "Cannot convert undefined to an object.")
1766
1767 (js2-msg "msg.cyclic.value"
1768 "Cyclic %s value not allowed.")
1769
1770 (js2-msg "msg.is.not.defined"
1771 "'%s' is not defined.")
1772
1773 (js2-msg "msg.undef.prop.read"
1774 "Cannot read property '%s' from %s")
1775
1776 (js2-msg "msg.undef.prop.write"
1777 "Cannot set property '%s' of %s to '%s'")
1778
1779 (js2-msg "msg.undef.prop.delete"
1780 "Cannot delete property '%s' of %s")
1781
1782 (js2-msg "msg.undef.method.call"
1783 "Cannot call method '%s' of %s")
1784
1785 (js2-msg "msg.undef.with"
1786 "Cannot apply 'with' to %s")
1787
1788 (js2-msg "msg.isnt.function"
1789 "%s is not a function, it is %s.")
1790
1791 (js2-msg "msg.isnt.function.in"
1792 "Cannot call property %s in object %s. "
1793 "It is not a function, it is '%s'.")
1794
1795 (js2-msg "msg.function.not.found"
1796 "Cannot find function %s.")
1797
1798 (js2-msg "msg.function.not.found.in"
1799 "Cannot find function %s in object %s.")
1800
1801 (js2-msg "msg.isnt.xml.object"
1802 "%s is not an xml object.")
1803
1804 (js2-msg "msg.no.ref.to.get"
1805 "%s is not a reference to read reference value.")
1806
1807 (js2-msg "msg.no.ref.to.set"
1808 "%s is not a reference to set reference value to %s.")
1809
1810 (js2-msg "msg.no.ref.from.function"
1811 "Function %s can not be used as the left-hand "
1812 "side of assignment or as an operand of ++ or -- operator.")
1813
1814 (js2-msg "msg.bad.default.value"
1815 "Object's getDefaultValue() method returned an object.")
1816
1817 (js2-msg "msg.instanceof.not.object"
1818 "Can't use instanceof on a non-object.")
1819
1820 (js2-msg "msg.instanceof.bad.prototype"
1821 "'prototype' property of %s is not an object.")
1822
1823 (js2-msg "msg.bad.radix"
1824 "illegal radix %s.")
1825
1826 ;; ScriptableObject
1827 (js2-msg "msg.default.value"
1828 "Cannot find default value for object.")
1829
1830 (js2-msg "msg.zero.arg.ctor"
1831 "Cannot load class '%s' which has no zero-parameter constructor.")
1832
1833 (js2-msg "msg.ctor.multiple.parms"
1834 "Can't define constructor or class %s since more than "
1835 "one constructor has multiple parameters.")
1836
1837 (js2-msg "msg.extend.scriptable"
1838 "%s must extend ScriptableObject in order to define property %s.")
1839
1840 (js2-msg "msg.bad.getter.parms"
1841 "In order to define a property, getter %s must have zero "
1842 "parameters or a single ScriptableObject parameter.")
1843
1844 (js2-msg "msg.obj.getter.parms"
1845 "Expected static or delegated getter %s to take "
1846 "a ScriptableObject parameter.")
1847
1848 (js2-msg "msg.getter.static"
1849 "Getter and setter must both be static or neither be static.")
1850
1851 (js2-msg "msg.setter.return"
1852 "Setter must have void return type: %s")
1853
1854 (js2-msg "msg.setter2.parms"
1855 "Two-parameter setter must take a ScriptableObject as "
1856 "its first parameter.")
1857
1858 (js2-msg "msg.setter1.parms"
1859 "Expected single parameter setter for %s")
1860
1861 (js2-msg "msg.setter2.expected"
1862 "Expected static or delegated setter %s to take two parameters.")
1863
1864 (js2-msg "msg.setter.parms"
1865 "Expected either one or two parameters for setter.")
1866
1867 (js2-msg "msg.setter.bad.type"
1868 "Unsupported parameter type '%s' in setter '%s'.")
1869
1870 (js2-msg "msg.add.sealed"
1871 "Cannot add a property to a sealed object: %s.")
1872
1873 (js2-msg "msg.remove.sealed"
1874 "Cannot remove a property from a sealed object: %s.")
1875
1876 (js2-msg "msg.modify.sealed"
1877 "Cannot modify a property of a sealed object: %s.")
1878
1879 (js2-msg "msg.modify.readonly"
1880 "Cannot modify readonly property: %s.")
1881
1882 ;; TokenStream
1883 (js2-msg "msg.missing.exponent"
1884 "missing exponent")
1885
1886 (js2-msg "msg.caught.nfe"
1887 "number format error")
1888
1889 (js2-msg "msg.unterminated.string.lit"
1890 "unterminated string literal")
1891
1892 (js2-msg "msg.unterminated.comment"
1893 "unterminated comment")
1894
1895 (js2-msg "msg.unterminated.re.lit"
1896 "unterminated regular expression literal")
1897
1898 (js2-msg "msg.invalid.re.flag"
1899 "invalid flag after regular expression")
1900
1901 (js2-msg "msg.no.re.input.for"
1902 "no input for %s")
1903
1904 (js2-msg "msg.illegal.character"
1905 "illegal character")
1906
1907 (js2-msg "msg.invalid.escape"
1908 "invalid Unicode escape sequence")
1909
1910 (js2-msg "msg.bad.namespace"
1911 "not a valid default namespace statement. "
1912 "Syntax is: default xml namespace = EXPRESSION;")
1913
1914 ;; TokensStream warnings
1915 (js2-msg "msg.bad.octal.literal"
1916 "illegal octal literal digit %s; "
1917 "interpreting it as a decimal digit")
1918
1919 (js2-msg "msg.missing.hex.digits"
1920 "missing hexadecimal digits after '0x'")
1921
1922 (js2-msg "msg.missing.binary.digits"
1923 "missing binary digits after '0b'")
1924
1925 (js2-msg "msg.missing.octal.digits"
1926 "missing octal digits after '0o'")
1927
1928 (js2-msg "msg.script.is.not.constructor"
1929 "Script objects are not constructors.")
1930
1931 ;; Arrays
1932 (js2-msg "msg.arraylength.bad"
1933 "Inappropriate array length.")
1934
1935 ;; Arrays
1936 (js2-msg "msg.arraylength.too.big"
1937 "Array length %s exceeds supported capacity limit.")
1938
1939 ;; URI
1940 (js2-msg "msg.bad.uri"
1941 "Malformed URI sequence.")
1942
1943 ;; Number
1944 (js2-msg "msg.bad.precision"
1945 "Precision %s out of range.")
1946
1947 ;; NativeGenerator
1948 (js2-msg "msg.send.newborn"
1949 "Attempt to send value to newborn generator")
1950
1951 (js2-msg "msg.already.exec.gen"
1952 "Already executing generator")
1953
1954 (js2-msg "msg.StopIteration.invalid"
1955 "StopIteration may not be changed to an arbitrary object.")
1956
1957 ;; Interpreter
1958 (js2-msg "msg.yield.closing"
1959 "Yield from closing generator")
1960
1961 ;; Classes
1962 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1963 "class statement requires a name")
1964
1965 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1966 "unexpected ',' between class properties")
1967
1968 (js2-msg "msg.unexpected.static" ; added by js2-mode
1969 "unexpected 'static'")
1970
1971 (js2-msg "msg.missing.extends" ; added by js2-mode
1972 "name is required after extends")
1973
1974 (js2-msg "msg.no.brace.class" ; added by js2-mode
1975 "missing '{' before class body")
1976
1977 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1978 "missing ']' after computed property expression")
1979
1980 ;;; Tokens Buffer
1981
1982 (defconst js2-ti-max-lookahead 2)
1983 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1984
1985 (defun js2-new-token (offset)
1986 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1987 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1988 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1989 token))
1990
1991 (defsubst js2-current-token ()
1992 (aref js2-ti-tokens js2-ti-tokens-cursor))
1993
1994 (defsubst js2-current-token-string ()
1995 (js2-token-string (js2-current-token)))
1996
1997 (defsubst js2-current-token-type ()
1998 (js2-token-type (js2-current-token)))
1999
2000 (defsubst js2-current-token-beg ()
2001 (js2-token-beg (js2-current-token)))
2002
2003 (defsubst js2-current-token-end ()
2004 (js2-token-end (js2-current-token)))
2005
2006 (defun js2-current-token-len ()
2007 (let ((token (js2-current-token)))
2008 (- (js2-token-end token)
2009 (js2-token-beg token))))
2010
2011 (defun js2-ts-seek (state)
2012 (setq js2-ts-lineno (js2-ts-state-lineno state)
2013 js2-ts-cursor (js2-ts-state-cursor state)
2014 js2-ti-tokens (js2-ts-state-tokens state)
2015 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2016 js2-ti-lookahead (js2-ts-state-lookahead state)))
2017
2018 ;;; Utilities
2019
2020 (defun js2-delete-if (predicate list)
2021 "Remove all items satisfying PREDICATE in LIST."
2022 (cl-loop for item in list
2023 if (not (funcall predicate item))
2024 collect item))
2025
2026 (defun js2-position (element list)
2027 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2028 Returns nil if element is not found in the list."
2029 (let ((count 0)
2030 found)
2031 (while (and list (not found))
2032 (if (eq element (car list))
2033 (setq found t)
2034 (setq count (1+ count)
2035 list (cdr list))))
2036 (if found count)))
2037
2038 (defun js2-find-if (predicate list)
2039 "Find first item satisfying PREDICATE in LIST."
2040 (let (result)
2041 (while (and list (not result))
2042 (if (funcall predicate (car list))
2043 (setq result (car list)))
2044 (setq list (cdr list)))
2045 result))
2046
2047 (defmacro js2-time (form)
2048 "Evaluate FORM, discard result, and return elapsed time in sec."
2049 (declare (debug t))
2050 (let ((beg (make-symbol "--js2-time-beg--")))
2051 `(let ((,beg (current-time)))
2052 ,form
2053 (/ (truncate (* (- (float-time (current-time))
2054 (float-time ,beg))
2055 10000))
2056 10000.0))))
2057
2058 (defsubst js2-same-line (pos)
2059 "Return t if POS is on the same line as current point."
2060 (and (>= pos (point-at-bol))
2061 (<= pos (point-at-eol))))
2062
2063 (defun js2-code-bug ()
2064 "Signal an error when we encounter an unexpected code path."
2065 (error "failed assertion"))
2066
2067 (defsubst js2-record-text-property (beg end prop value)
2068 "Record a text property to set when parsing finishes."
2069 (push (list beg end prop value) js2-mode-deferred-properties))
2070
2071 ;; I'd like to associate errors with nodes, but for now the
2072 ;; easiest thing to do is get the context info from the last token.
2073 (defun js2-record-parse-error (msg &optional arg pos len)
2074 (push (list (list msg arg)
2075 (or pos (js2-current-token-beg))
2076 (or len (js2-current-token-len)))
2077 js2-parsed-errors))
2078
2079 (defun js2-report-error (msg &optional msg-arg pos len)
2080 "Signal a syntax error or record a parse error."
2081 (if js2-recover-from-parse-errors
2082 (js2-record-parse-error msg msg-arg pos len)
2083 (signal 'js2-syntax-error
2084 (list msg
2085 js2-ts-lineno
2086 (save-excursion
2087 (goto-char js2-ts-cursor)
2088 (current-column))
2089 js2-ts-hit-eof))))
2090
2091 (defun js2-report-warning (msg &optional msg-arg pos len face)
2092 (if js2-compiler-report-warning-as-error
2093 (js2-report-error msg msg-arg pos len)
2094 (push (list (list msg msg-arg)
2095 (or pos (js2-current-token-beg))
2096 (or len (js2-current-token-len))
2097 face)
2098 js2-parsed-warnings)))
2099
2100 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2101 (if js2-compiler-strict-mode
2102 (js2-report-warning msg-id msg-arg beg
2103 (and beg end (- end beg)))))
2104
2105 (put 'js2-syntax-error 'error-conditions
2106 '(error syntax-error js2-syntax-error))
2107 (put 'js2-syntax-error 'error-message "Syntax error")
2108
2109 (put 'js2-parse-error 'error-conditions
2110 '(error parse-error js2-parse-error))
2111 (put 'js2-parse-error 'error-message "Parse error")
2112
2113 (defmacro js2-clear-flag (flags flag)
2114 `(setq ,flags (logand ,flags (lognot ,flag))))
2115
2116 (defmacro js2-set-flag (flags flag)
2117 "Logical-or FLAG into FLAGS."
2118 `(setq ,flags (logior ,flags ,flag)))
2119
2120 (defsubst js2-flag-set-p (flags flag)
2121 (/= 0 (logand flags flag)))
2122
2123 (defsubst js2-flag-not-set-p (flags flag)
2124 (zerop (logand flags flag)))
2125
2126 ;;; AST struct and function definitions
2127
2128 ;; flags for ast node property 'member-type (used for e4x operators)
2129 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2130 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2131 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2132
2133 (defsubst js2-relpos (pos anchor)
2134 "Convert POS to be relative to ANCHOR.
2135 If POS is nil, returns nil."
2136 (and pos (- pos anchor)))
2137
2138 (defun js2-make-pad (indent)
2139 (if (zerop indent)
2140 ""
2141 (make-string (* indent js2-basic-offset) ? )))
2142
2143 (defun js2-visit-ast (node callback)
2144 "Visit every node in ast NODE with visitor CALLBACK.
2145
2146 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2147 called twice: once to visit the node, and again after all the node's
2148 children have been processed. The END-P argument is nil on the first
2149 call and non-nil on the second call. The return value of the callback
2150 affects the traversal: if non-nil, the children of NODE are processed.
2151 If the callback returns nil, or if the node has no children, then the
2152 callback is called immediately with a non-nil END-P argument.
2153
2154 The node traversal is approximately lexical-order, although there
2155 are currently no guarantees around this."
2156 (when node
2157 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2158 ;; visit the node
2159 (when (funcall callback node nil)
2160 ;; visit the kids
2161 (cond
2162 ((eq vfunc 'js2-visit-none)
2163 nil) ; don't even bother calling it
2164 ;; Each AST node type has to define a `js2-visitor' function
2165 ;; that takes a node and a callback, and calls `js2-visit-ast'
2166 ;; on each child of the node.
2167 (vfunc
2168 (funcall vfunc node callback))
2169 (t
2170 (error "%s does not define a visitor-traversal function"
2171 (aref node 0)))))
2172 ;; call the end-visit
2173 (funcall callback node t))))
2174
2175 (cl-defstruct (js2-node
2176 (:constructor nil)) ; abstract
2177 "Base AST node type."
2178 (type -1) ; token type
2179 (pos -1) ; start position of this AST node in parsed input
2180 (len 1) ; num characters spanned by the node
2181 props ; optional node property list (an alist)
2182 parent) ; link to parent node; null for root
2183
2184 (defsubst js2-node-get-prop (node prop &optional default)
2185 (or (cadr (assoc prop (js2-node-props node))) default))
2186
2187 (defsubst js2-node-set-prop (node prop value)
2188 (setf (js2-node-props node)
2189 (cons (list prop value) (js2-node-props node))))
2190
2191 (defun js2-fixup-starts (n nodes)
2192 "Adjust the start positions of NODES to be relative to N.
2193 Any node in the list may be nil, for convenience."
2194 (dolist (node nodes)
2195 (when node
2196 (setf (js2-node-pos node) (- (js2-node-pos node)
2197 (js2-node-pos n))))))
2198
2199 (defun js2-node-add-children (parent &rest nodes)
2200 "Set parent node of NODES to PARENT, and return PARENT.
2201 Does nothing if we're not recording parent links.
2202 If any given node in NODES is nil, doesn't record that link."
2203 (js2-fixup-starts parent nodes)
2204 (dolist (node nodes)
2205 (and node
2206 (setf (js2-node-parent node) parent))))
2207
2208 ;; Non-recursive since it's called a frightening number of times.
2209 (defun js2-node-abs-pos (n)
2210 (let ((pos (js2-node-pos n)))
2211 (while (setq n (js2-node-parent n))
2212 (setq pos (+ pos (js2-node-pos n))))
2213 pos))
2214
2215 (defsubst js2-node-abs-end (n)
2216 "Return absolute buffer position of end of N."
2217 (+ (js2-node-abs-pos n) (js2-node-len n)))
2218
2219 ;; It's important to make sure block nodes have a Lisp list for the
2220 ;; child nodes, to limit printing recursion depth in an AST that
2221 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2222 ;; a sufficiently large vector tree.
2223
2224 (cl-defstruct (js2-block-node
2225 (:include js2-node)
2226 (:constructor nil)
2227 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2228 (pos (js2-current-token-beg))
2229 len
2230 props
2231 kids)))
2232 "A block of statements."
2233 kids) ; a Lisp list of the child statement nodes
2234
2235 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2236 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2237
2238 (defun js2-visit-block (ast callback)
2239 "Visit the `js2-block-node' children of AST."
2240 (dolist (kid (js2-block-node-kids ast))
2241 (js2-visit-ast kid callback)))
2242
2243 (defun js2-print-block (n i)
2244 (let ((pad (js2-make-pad i)))
2245 (insert pad "{\n")
2246 (dolist (kid (js2-block-node-kids n))
2247 (js2-print-ast kid (1+ i)))
2248 (insert pad "}")))
2249
2250 (cl-defstruct (js2-scope
2251 (:include js2-block-node)
2252 (:constructor nil)
2253 (:constructor make-js2-scope (&key (type js2-BLOCK)
2254 (pos (js2-current-token-beg))
2255 len
2256 kids)))
2257 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2258 ;; I don't have one of those handy, so I'll use an alist for now.
2259 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2260 ;; and is much lighter-weight to construct (both CPU and mem).
2261 ;; The keys are interned strings (symbols) for faster lookup.
2262 ;; Should switch to hybrid alist/hashtable eventually.
2263 symbol-table ; an alist of (symbol . js2-symbol)
2264 parent-scope ; a `js2-scope'
2265 top) ; top-level `js2-scope' (script/function)
2266
2267 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2268 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2269
2270 (defun js2-node-get-enclosing-scope (node)
2271 "Return the innermost `js2-scope' node surrounding NODE.
2272 Returns nil if there is no enclosing scope node."
2273 (while (and (setq node (js2-node-parent node))
2274 (not (js2-scope-p node))))
2275 node)
2276
2277 (defun js2-get-defining-scope (scope name &optional point)
2278 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2279 Returns `js2-scope' in which NAME is defined, or nil if not found.
2280
2281 If POINT is non-nil, and if the found declaration type is
2282 `js2-LET', also check that the declaration node is before POINT."
2283 (let ((sym (if (symbolp name)
2284 name
2285 (intern name)))
2286 result
2287 (continue t))
2288 (while (and scope continue)
2289 (if (or
2290 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2291 (and entry
2292 (or (not point)
2293 (not (eq js2-LET (js2-symbol-decl-type entry)))
2294 (>= point
2295 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2296 (and (eq sym 'arguments)
2297 (js2-function-node-p scope)))
2298 (setq continue nil
2299 result scope)
2300 (setq scope (js2-scope-parent-scope scope))))
2301 result))
2302
2303 (defun js2-scope-get-symbol (scope name)
2304 "Return symbol table entry for NAME in SCOPE.
2305 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2306 (and (js2-scope-symbol-table scope)
2307 (cdr (assq (if (symbolp name)
2308 name
2309 (intern name))
2310 (js2-scope-symbol-table scope)))))
2311
2312 (defun js2-scope-put-symbol (scope name symbol)
2313 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2314 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2315 (let* ((table (js2-scope-symbol-table scope))
2316 (sym (if (symbolp name) name (intern name)))
2317 (entry (assq sym table)))
2318 (if entry
2319 (setcdr entry symbol)
2320 (push (cons sym symbol)
2321 (js2-scope-symbol-table scope)))))
2322
2323 (cl-defstruct (js2-symbol
2324 (:constructor nil)
2325 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2326 "A symbol table entry."
2327 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2328 ;; js2-LET, or js2-CONST
2329 decl-type
2330 name ; string
2331 ast-node) ; a `js2-node'
2332
2333 (cl-defstruct (js2-error-node
2334 (:include js2-node)
2335 (:constructor nil) ; silence emacs21 byte-compiler
2336 (:constructor make-js2-error-node (&key (type js2-ERROR)
2337 (pos (js2-current-token-beg))
2338 len)))
2339 "AST node representing a parse error.")
2340
2341 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2342 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2343
2344 (cl-defstruct (js2-script-node
2345 (:include js2-scope)
2346 (:constructor nil)
2347 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2348 (pos (js2-current-token-beg))
2349 len
2350 ;; FIXME: What are those?
2351 var-decls
2352 fun-decls)))
2353 functions ; Lisp list of nested functions
2354 regexps ; Lisp list of (string . flags)
2355 symbols ; alist (every symbol gets unique index)
2356 (param-count 0)
2357 var-names ; vector of string names
2358 consts ; bool-vector matching var-decls
2359 (temp-number 0)) ; for generating temp variables
2360
2361 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2362 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2363
2364 (defun js2-print-script (node indent)
2365 (dolist (kid (js2-block-node-kids node))
2366 (js2-print-ast kid indent)))
2367
2368 (cl-defstruct (js2-ast-root
2369 (:include js2-script-node)
2370 (:constructor nil)
2371 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2372 (pos (js2-current-token-beg))
2373 len
2374 buffer)))
2375 "The root node of a js2 AST."
2376 buffer ; the source buffer from which the code was parsed
2377 comments ; a Lisp list of comments, ordered by start position
2378 errors ; a Lisp list of errors found during parsing
2379 warnings ; a Lisp list of warnings found during parsing
2380 node-count) ; number of nodes in the tree, including the root
2381
2382 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2383 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2384
2385 (defun js2-visit-ast-root (ast callback)
2386 (dolist (kid (js2-ast-root-kids ast))
2387 (js2-visit-ast kid callback))
2388 (dolist (comment (js2-ast-root-comments ast))
2389 (js2-visit-ast comment callback)))
2390
2391 (cl-defstruct (js2-comment-node
2392 (:include js2-node)
2393 (:constructor nil)
2394 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2395 (pos (js2-current-token-beg))
2396 len
2397 format)))
2398 format) ; 'line, 'block, 'jsdoc or 'html
2399
2400 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2401 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2402
2403 (defun js2-print-comment (n i)
2404 ;; We really ought to link end-of-line comments to their nodes.
2405 ;; Or maybe we could add a new comment type, 'endline.
2406 (insert (js2-make-pad i)
2407 (js2-node-string n)))
2408
2409 (cl-defstruct (js2-expr-stmt-node
2410 (:include js2-node)
2411 (:constructor nil)
2412 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2413 (pos js2-ts-cursor)
2414 len
2415 expr)))
2416 "An expression statement."
2417 expr)
2418
2419 (defsubst js2-expr-stmt-node-set-has-result (node)
2420 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2421 (setf (js2-node-type node) js2-EXPR_RESULT))
2422
2423 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2424 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2425
2426 (defun js2-visit-expr-stmt-node (n v)
2427 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2428
2429 (defun js2-print-expr-stmt-node (n indent)
2430 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2431 (insert ";\n"))
2432
2433 (cl-defstruct (js2-loop-node
2434 (:include js2-scope)
2435 (:constructor nil))
2436 "Abstract supertype of loop nodes."
2437 body ; a `js2-block-node'
2438 lp ; position of left-paren, nil if omitted
2439 rp) ; position of right-paren, nil if omitted
2440
2441 (cl-defstruct (js2-do-node
2442 (:include js2-loop-node)
2443 (:constructor nil)
2444 (:constructor make-js2-do-node (&key (type js2-DO)
2445 (pos (js2-current-token-beg))
2446 len
2447 body
2448 condition
2449 while-pos
2450 lp
2451 rp)))
2452 "AST node for do-loop."
2453 condition ; while (expression)
2454 while-pos) ; buffer position of 'while' keyword
2455
2456 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2457 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2458
2459 (defun js2-visit-do-node (n v)
2460 (js2-visit-ast (js2-do-node-body n) v)
2461 (js2-visit-ast (js2-do-node-condition n) v))
2462
2463 (defun js2-print-do-node (n i)
2464 (let ((pad (js2-make-pad i)))
2465 (insert pad "do {\n")
2466 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2467 (js2-print-ast kid (1+ i)))
2468 (insert pad "} while (")
2469 (js2-print-ast (js2-do-node-condition n) 0)
2470 (insert ");\n")))
2471
2472 (cl-defstruct (js2-export-node
2473 (:include js2-node)
2474 (:constructor nil)
2475 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2476 (pos (js2-current-token-beg))
2477 len
2478 exports-list
2479 from-clause
2480 declaration
2481 default)))
2482 "AST node for an export statement. There are many things that can be exported,
2483 so many of its properties will be nil.
2484 "
2485 exports-list ; lisp list of js2-export-binding-node to export
2486 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2487 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2488 default) ; js2-function-node or js2-assign-node
2489
2490 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2491 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2492
2493 (defun js2-visit-export-node (n v)
2494 (let ((exports-list (js2-export-node-exports-list n))
2495 (from (js2-export-node-from-clause n))
2496 (declaration (js2-export-node-declaration n))
2497 (default (js2-export-node-default n)))
2498 (when exports-list
2499 (dolist (export exports-list)
2500 (js2-visit-ast export v)))
2501 (when from
2502 (js2-visit-ast from v))
2503 (when declaration
2504 (js2-visit-ast declaration v))
2505 (when default
2506 (js2-visit-ast default v))))
2507
2508 (defun js2-print-export-node (n i)
2509 (let ((pad (js2-make-pad i))
2510 (exports-list (js2-export-node-exports-list n))
2511 (from (js2-export-node-from-clause n))
2512 (declaration (js2-export-node-declaration n))
2513 (default (js2-export-node-default n)))
2514 (insert pad "export ")
2515 (cond
2516 (default
2517 (insert "default ")
2518 (js2-print-ast default i))
2519 (declaration
2520 (js2-print-ast declaration i))
2521 ((and exports-list from)
2522 (js2-print-named-imports exports-list)
2523 (insert " ")
2524 (js2-print-from-clause from))
2525 (from
2526 (insert "* ")
2527 (js2-print-from-clause from))
2528 (exports-list
2529 (js2-print-named-imports exports-list)))
2530 (insert ";\n")))
2531
2532 (cl-defstruct (js2-while-node
2533 (:include js2-loop-node)
2534 (:constructor nil)
2535 (:constructor make-js2-while-node (&key (type js2-WHILE)
2536 (pos (js2-current-token-beg))
2537 len body
2538 condition lp
2539 rp)))
2540 "AST node for while-loop."
2541 condition) ; while-condition
2542
2543 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2544 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2545
2546 (defun js2-visit-while-node (n v)
2547 (js2-visit-ast (js2-while-node-condition n) v)
2548 (js2-visit-ast (js2-while-node-body n) v))
2549
2550 (defun js2-print-while-node (n i)
2551 (let ((pad (js2-make-pad i)))
2552 (insert pad "while (")
2553 (js2-print-ast (js2-while-node-condition n) 0)
2554 (insert ") {\n")
2555 (js2-print-body (js2-while-node-body n) (1+ i))
2556 (insert pad "}\n")))
2557
2558 (cl-defstruct (js2-for-node
2559 (:include js2-loop-node)
2560 (:constructor nil)
2561 (:constructor make-js2-for-node (&key (type js2-FOR)
2562 (pos js2-ts-cursor)
2563 len body init
2564 condition
2565 update lp rp)))
2566 "AST node for a C-style for-loop."
2567 init ; initialization expression
2568 condition ; loop condition
2569 update) ; update clause
2570
2571 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2572 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2573
2574 (defun js2-visit-for-node (n v)
2575 (js2-visit-ast (js2-for-node-init n) v)
2576 (js2-visit-ast (js2-for-node-condition n) v)
2577 (js2-visit-ast (js2-for-node-update n) v)
2578 (js2-visit-ast (js2-for-node-body n) v))
2579
2580 (defun js2-print-for-node (n i)
2581 (let ((pad (js2-make-pad i)))
2582 (insert pad "for (")
2583 (js2-print-ast (js2-for-node-init n) 0)
2584 (insert "; ")
2585 (js2-print-ast (js2-for-node-condition n) 0)
2586 (insert "; ")
2587 (js2-print-ast (js2-for-node-update n) 0)
2588 (insert ") {\n")
2589 (js2-print-body (js2-for-node-body n) (1+ i))
2590 (insert pad "}\n")))
2591
2592 (cl-defstruct (js2-for-in-node
2593 (:include js2-loop-node)
2594 (:constructor nil)
2595 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2596 (pos js2-ts-cursor)
2597 len body
2598 iterator
2599 object
2600 in-pos
2601 each-pos
2602 foreach-p forof-p
2603 lp rp)))
2604 "AST node for a for..in loop."
2605 iterator ; [var] foo in ...
2606 object ; object over which we're iterating
2607 in-pos ; buffer position of 'in' keyword
2608 each-pos ; buffer position of 'each' keyword, if foreach-p
2609 foreach-p ; t if it's a for-each loop
2610 forof-p) ; t if it's a for-of loop
2611
2612 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2613 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2614
2615 (defun js2-visit-for-in-node (n v)
2616 (js2-visit-ast (js2-for-in-node-iterator n) v)
2617 (js2-visit-ast (js2-for-in-node-object n) v)
2618 (js2-visit-ast (js2-for-in-node-body n) v))
2619
2620 (defun js2-print-for-in-node (n i)
2621 (let ((pad (js2-make-pad i))
2622 (foreach (js2-for-in-node-foreach-p n))
2623 (forof (js2-for-in-node-forof-p n)))
2624 (insert pad "for ")
2625 (if foreach
2626 (insert "each "))
2627 (insert "(")
2628 (js2-print-ast (js2-for-in-node-iterator n) 0)
2629 (insert (if forof " of " " in "))
2630 (js2-print-ast (js2-for-in-node-object n) 0)
2631 (insert ") {\n")
2632 (js2-print-body (js2-for-in-node-body n) (1+ i))
2633 (insert pad "}\n")))
2634
2635 (cl-defstruct (js2-return-node
2636 (:include js2-node)
2637 (:constructor nil)
2638 (:constructor make-js2-return-node (&key (type js2-RETURN)
2639 (pos js2-ts-cursor)
2640 len
2641 retval)))
2642 "AST node for a return statement."
2643 retval) ; expression to return, or 'undefined
2644
2645 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2646 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2647
2648 (defun js2-visit-return-node (n v)
2649 (js2-visit-ast (js2-return-node-retval n) v))
2650
2651 (defun js2-print-return-node (n i)
2652 (insert (js2-make-pad i) "return")
2653 (when (js2-return-node-retval n)
2654 (insert " ")
2655 (js2-print-ast (js2-return-node-retval n) 0))
2656 (insert ";\n"))
2657
2658 (cl-defstruct (js2-if-node
2659 (:include js2-node)
2660 (:constructor nil)
2661 (:constructor make-js2-if-node (&key (type js2-IF)
2662 (pos js2-ts-cursor)
2663 len condition
2664 then-part
2665 else-pos
2666 else-part lp
2667 rp)))
2668 "AST node for an if-statement."
2669 condition ; expression
2670 then-part ; statement or block
2671 else-pos ; optional buffer position of 'else' keyword
2672 else-part ; optional statement or block
2673 lp ; position of left-paren, nil if omitted
2674 rp) ; position of right-paren, nil if omitted
2675
2676 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2677 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2678
2679 (defun js2-visit-if-node (n v)
2680 (js2-visit-ast (js2-if-node-condition n) v)
2681 (js2-visit-ast (js2-if-node-then-part n) v)
2682 (js2-visit-ast (js2-if-node-else-part n) v))
2683
2684 (defun js2-print-if-node (n i)
2685 (let ((pad (js2-make-pad i))
2686 (then-part (js2-if-node-then-part n))
2687 (else-part (js2-if-node-else-part n)))
2688 (insert pad "if (")
2689 (js2-print-ast (js2-if-node-condition n) 0)
2690 (insert ") {\n")
2691 (js2-print-body then-part (1+ i))
2692 (insert pad "}")
2693 (cond
2694 ((not else-part)
2695 (insert "\n"))
2696 ((js2-if-node-p else-part)
2697 (insert " else ")
2698 (js2-print-body else-part i))
2699 (t
2700 (insert " else {\n")
2701 (js2-print-body else-part (1+ i))
2702 (insert pad "}\n")))))
2703
2704 (cl-defstruct (js2-export-binding-node
2705 (:include js2-node)
2706 (:constructor nil)
2707 (:constructor make-js2-export-binding-node (&key (type -1)
2708 pos
2709 len
2710 local-name
2711 extern-name)))
2712 "AST node for an external symbol binding.
2713 It contains a local-name node which is the name of the value in the
2714 current scope, and extern-name which is the name of the value in the
2715 imported or exported scope. By default these are the same, but if the
2716 name is aliased as in {foo as bar}, it would have an extern-name node
2717 containing 'foo' and a local-name node containing 'bar'."
2718 local-name ; js2-name-node with the variable name in this scope
2719 extern-name) ; js2-name-node with the value name in the exporting module
2720
2721 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2722 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2723
2724 (defun js2-visit-extern-binding (n v)
2725 "Visit an extern binding node. First visit the local-name, and, if
2726 different, visit the extern-name."
2727 (let ((local-name (js2-export-binding-node-local-name n))
2728 (extern-name (js2-export-binding-node-extern-name n)))
2729 (when local-name
2730 (js2-visit-ast local-name v))
2731 (when (not (equal local-name extern-name))
2732 (js2-visit-ast extern-name v))))
2733
2734 (defun js2-print-extern-binding (n _i)
2735 "Print a representation of a single extern binding. E.g. 'foo' or
2736 'foo as bar'."
2737 (let ((local-name (js2-export-binding-node-local-name n))
2738 (extern-name (js2-export-binding-node-extern-name n)))
2739 (insert (js2-name-node-name extern-name))
2740 (when (not (equal local-name extern-name))
2741 (insert " as ")
2742 (insert (js2-name-node-name local-name)))))
2743
2744
2745 (cl-defstruct (js2-import-node
2746 (:include js2-node)
2747 (:constructor nil)
2748 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2749 (pos (js2-current-token-beg))
2750 len
2751 import
2752 from
2753 module-id)))
2754 "AST node for an import statement. It follows the form
2755
2756 import ModuleSpecifier;
2757 import ImportClause FromClause;"
2758 import ; js2-import-clause-node specifying which names are to imported.
2759 from ; js2-from-clause-node indicating the module from which to import.
2760 module-id) ; module-id of the import. E.g. 'src/mylib'.
2761
2762 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2763 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2764
2765 (defun js2-visit-import (n v)
2766 (let ((import-clause (js2-import-node-import n))
2767 (from-clause (js2-import-node-from n)))
2768 (when import-clause
2769 (js2-visit-ast import-clause v))
2770 (when from-clause
2771 (js2-visit-ast from-clause v))))
2772
2773 (defun js2-print-import (n i)
2774 "Prints a representation of the import node"
2775 (let ((pad (js2-make-pad i))
2776 (import-clause (js2-import-node-import n))
2777 (from-clause (js2-import-node-from n))
2778 (module-id (js2-import-node-module-id n)))
2779 (insert pad "import ")
2780 (if import-clause
2781 (progn
2782 (js2-print-import-clause import-clause)
2783 (insert " ")
2784 (js2-print-from-clause from-clause))
2785 (insert "'")
2786 (insert module-id)
2787 (insert "'"))
2788 (insert ";\n")))
2789
2790 (cl-defstruct (js2-import-clause-node
2791 (:include js2-node)
2792 (:constructor nil)
2793 (:constructor make-js2-import-clause-node (&key (type -1)
2794 pos
2795 len
2796 namespace-import
2797 named-imports
2798 default-binding)))
2799 "AST node corresponding to the import clause of an import statement. This is
2800 the portion of the import that bindings names from the external context to the
2801 local context."
2802 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2803 named-imports ; lisp list of js2-export-binding-node for all named imports.
2804 default-binding) ; js2-export-binding-node for the default import binding
2805
2806 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2807 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2808
2809 (defun js2-visit-import-clause (n v)
2810 (let ((ns-import (js2-import-clause-node-namespace-import n))
2811 (named-imports (js2-import-clause-node-named-imports n))
2812 (default (js2-import-clause-node-default-binding n)))
2813 (when ns-import
2814 (js2-visit-ast ns-import v))
2815 (when named-imports
2816 (dolist (import named-imports)
2817 (js2-visit-ast import v)))
2818 (when default
2819 (js2-visit-ast default v))))
2820
2821 (defun js2-print-import-clause (n)
2822 (let ((ns-import (js2-import-clause-node-namespace-import n))
2823 (named-imports (js2-import-clause-node-named-imports n))
2824 (default (js2-import-clause-node-default-binding n)))
2825 (cond
2826 ((and default ns-import)
2827 (js2-print-ast default)
2828 (insert ", ")
2829 (js2-print-namespace-import ns-import))
2830 ((and default named-imports)
2831 (js2-print-ast default)
2832 (insert ", ")
2833 (js2-print-named-imports named-imports))
2834 (default
2835 (js2-print-ast default))
2836 (ns-import
2837 (js2-print-namespace-import ns-import))
2838 (named-imports
2839 (js2-print-named-imports named-imports)))))
2840
2841 (defun js2-print-namespace-import (node)
2842 (insert "* as ")
2843 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2844
2845 (defun js2-print-named-imports (imports)
2846 (insert "{")
2847 (let ((len (length imports))
2848 (n 0))
2849 (while (< n len)
2850 (js2-print-extern-binding (nth n imports) 0)
2851 (unless (= n (- len 1))
2852 (insert ", "))
2853 (setq n (+ n 1))))
2854 (insert "}"))
2855
2856 (cl-defstruct (js2-namespace-import-node
2857 (:include js2-node)
2858 (:constructor nil)
2859 (:constructor make-js2-namespace-import-node (&key (type -1)
2860 pos
2861 len
2862 name)))
2863 "AST node for a complete namespace import.
2864 E.g. the '* as lib' expression in:
2865
2866 import * as lib from 'src/lib'
2867
2868 It contains a single name node referring to the bound name."
2869 name) ; js2-name-node of the bound name.
2870
2871 (defun js2-visit-namespace-import (n v)
2872 (js2-visit-ast (js2-namespace-import-node-name n) v))
2873
2874 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2875 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2876
2877 (cl-defstruct (js2-from-clause-node
2878 (:include js2-node)
2879 (:constructor nil)
2880 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2881 pos
2882 len
2883 module-id
2884 metadata-p)))
2885 "AST node for the from clause in an import or export statement.
2886 E.g. from 'my/module'. It can refere to either an external module, or to the
2887 modules metadata itself."
2888 module-id ; string containing the module specifier.
2889 metadata-p) ; true if this clause refers to the module's metadata
2890
2891 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2892 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2893
2894 (defun js2-print-from-clause (n)
2895 (insert "from ")
2896 (if (js2-from-clause-node-metadata-p n)
2897 (insert "this module")
2898 (insert "'")
2899 (insert (js2-from-clause-node-module-id n))
2900 (insert "'")))
2901
2902 (cl-defstruct (js2-try-node
2903 (:include js2-node)
2904 (:constructor nil)
2905 (:constructor make-js2-try-node (&key (type js2-TRY)
2906 (pos js2-ts-cursor)
2907 len
2908 try-block
2909 catch-clauses
2910 finally-block)))
2911 "AST node for a try-statement."
2912 try-block
2913 catch-clauses ; a Lisp list of `js2-catch-node'
2914 finally-block) ; a `js2-finally-node'
2915
2916 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2917 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2918
2919 (defun js2-visit-try-node (n v)
2920 (js2-visit-ast (js2-try-node-try-block n) v)
2921 (dolist (clause (js2-try-node-catch-clauses n))
2922 (js2-visit-ast clause v))
2923 (js2-visit-ast (js2-try-node-finally-block n) v))
2924
2925 (defun js2-print-try-node (n i)
2926 (let ((pad (js2-make-pad i))
2927 (catches (js2-try-node-catch-clauses n))
2928 (finally (js2-try-node-finally-block n)))
2929 (insert pad "try {\n")
2930 (js2-print-body (js2-try-node-try-block n) (1+ i))
2931 (insert pad "}")
2932 (when catches
2933 (dolist (catch catches)
2934 (js2-print-ast catch i)))
2935 (if finally
2936 (js2-print-ast finally i)
2937 (insert "\n"))))
2938
2939 (cl-defstruct (js2-catch-node
2940 (:include js2-scope)
2941 (:constructor nil)
2942 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2943 (pos js2-ts-cursor)
2944 len
2945 param
2946 guard-kwd
2947 guard-expr
2948 lp rp)))
2949 "AST node for a catch clause."
2950 param ; destructuring form or simple name node
2951 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2952 guard-expr ; catch condition, a `js2-node'
2953 lp ; buffer position of left-paren, nil if omitted
2954 rp) ; buffer position of right-paren, nil if omitted
2955
2956 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2957 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2958
2959 (defun js2-visit-catch-node (n v)
2960 (js2-visit-ast (js2-catch-node-param n) v)
2961 (when (js2-catch-node-guard-kwd n)
2962 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2963 (js2-visit-block n v))
2964
2965 (defun js2-print-catch-node (n i)
2966 (let ((pad (js2-make-pad i))
2967 (guard-kwd (js2-catch-node-guard-kwd n))
2968 (guard-expr (js2-catch-node-guard-expr n)))
2969 (insert " catch (")
2970 (js2-print-ast (js2-catch-node-param n) 0)
2971 (when guard-kwd
2972 (insert " if ")
2973 (js2-print-ast guard-expr 0))
2974 (insert ") {\n")
2975 (js2-print-body n (1+ i))
2976 (insert pad "}")))
2977
2978 (cl-defstruct (js2-finally-node
2979 (:include js2-node)
2980 (:constructor nil)
2981 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2982 (pos js2-ts-cursor)
2983 len body)))
2984 "AST node for a finally clause."
2985 body) ; a `js2-node', often but not always a block node
2986
2987 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2988 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2989
2990 (defun js2-visit-finally-node (n v)
2991 (js2-visit-ast (js2-finally-node-body n) v))
2992
2993 (defun js2-print-finally-node (n i)
2994 (let ((pad (js2-make-pad i)))
2995 (insert " finally {\n")
2996 (js2-print-body (js2-finally-node-body n) (1+ i))
2997 (insert pad "}\n")))
2998
2999 (cl-defstruct (js2-switch-node
3000 (:include js2-node)
3001 (:constructor nil)
3002 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3003 (pos js2-ts-cursor)
3004 len
3005 discriminant
3006 cases lp
3007 rp)))
3008 "AST node for a switch statement."
3009 discriminant ; a `js2-node' (switch expression)
3010 cases ; a Lisp list of `js2-case-node'
3011 lp ; position of open-paren for discriminant, nil if omitted
3012 rp) ; position of close-paren for discriminant, nil if omitted
3013
3014 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3015 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3016
3017 (defun js2-visit-switch-node (n v)
3018 (js2-visit-ast (js2-switch-node-discriminant n) v)
3019 (dolist (c (js2-switch-node-cases n))
3020 (js2-visit-ast c v)))
3021
3022 (defun js2-print-switch-node (n i)
3023 (let ((pad (js2-make-pad i))
3024 (cases (js2-switch-node-cases n)))
3025 (insert pad "switch (")
3026 (js2-print-ast (js2-switch-node-discriminant n) 0)
3027 (insert ") {\n")
3028 (dolist (case cases)
3029 (js2-print-ast case i))
3030 (insert pad "}\n")))
3031
3032 (cl-defstruct (js2-case-node
3033 (:include js2-block-node)
3034 (:constructor nil)
3035 (:constructor make-js2-case-node (&key (type js2-CASE)
3036 (pos js2-ts-cursor)
3037 len kids expr)))
3038 "AST node for a case clause of a switch statement."
3039 expr) ; the case expression (nil for default)
3040
3041 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3042 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3043
3044 (defun js2-visit-case-node (n v)
3045 (js2-visit-ast (js2-case-node-expr n) v)
3046 (js2-visit-block n v))
3047
3048 (defun js2-print-case-node (n i)
3049 (let ((pad (js2-make-pad i))
3050 (expr (js2-case-node-expr n)))
3051 (insert pad)
3052 (if (null expr)
3053 (insert "default:\n")
3054 (insert "case ")
3055 (js2-print-ast expr 0)
3056 (insert ":\n"))
3057 (dolist (kid (js2-case-node-kids n))
3058 (js2-print-ast kid (1+ i)))))
3059
3060 (cl-defstruct (js2-throw-node
3061 (:include js2-node)
3062 (:constructor nil)
3063 (:constructor make-js2-throw-node (&key (type js2-THROW)
3064 (pos js2-ts-cursor)
3065 len expr)))
3066 "AST node for a throw statement."
3067 expr) ; the expression to throw
3068
3069 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3070 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3071
3072 (defun js2-visit-throw-node (n v)
3073 (js2-visit-ast (js2-throw-node-expr n) v))
3074
3075 (defun js2-print-throw-node (n i)
3076 (insert (js2-make-pad i) "throw ")
3077 (js2-print-ast (js2-throw-node-expr n) 0)
3078 (insert ";\n"))
3079
3080 (cl-defstruct (js2-with-node
3081 (:include js2-node)
3082 (:constructor nil)
3083 (:constructor make-js2-with-node (&key (type js2-WITH)
3084 (pos js2-ts-cursor)
3085 len object
3086 body lp rp)))
3087 "AST node for a with-statement."
3088 object
3089 body
3090 lp ; buffer position of left-paren around object, nil if omitted
3091 rp) ; buffer position of right-paren around object, nil if omitted
3092
3093 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3094 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3095
3096 (defun js2-visit-with-node (n v)
3097 (js2-visit-ast (js2-with-node-object n) v)
3098 (js2-visit-ast (js2-with-node-body n) v))
3099
3100 (defun js2-print-with-node (n i)
3101 (let ((pad (js2-make-pad i)))
3102 (insert pad "with (")
3103 (js2-print-ast (js2-with-node-object n) 0)
3104 (insert ") {\n")
3105 (js2-print-body (js2-with-node-body n) (1+ i))
3106 (insert pad "}\n")))
3107
3108 (cl-defstruct (js2-label-node
3109 (:include js2-node)
3110 (:constructor nil)
3111 (:constructor make-js2-label-node (&key (type js2-LABEL)
3112 (pos js2-ts-cursor)
3113 len name)))
3114 "AST node for a statement label or case label."
3115 name ; a string
3116 loop) ; for validating and code-generating continue-to-label
3117
3118 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3119 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3120
3121 (defun js2-print-label (n i)
3122 (insert (js2-make-pad i)
3123 (js2-label-node-name n)
3124 ":\n"))
3125
3126 (cl-defstruct (js2-labeled-stmt-node
3127 (:include js2-node)
3128 (:constructor nil)
3129 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3130 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3131 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3132 (pos js2-ts-cursor)
3133 len labels stmt)))
3134 "AST node for a statement with one or more labels.
3135 Multiple labels for a statement are collapsed into the labels field."
3136 labels ; Lisp list of `js2-label-node'
3137 stmt) ; the statement these labels are for
3138
3139 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3140 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3141
3142 (defun js2-get-label-by-name (lbl-stmt name)
3143 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3144 Returns nil if no such label is in the list."
3145 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3146 result)
3147 (while (and label-list (not result))
3148 (if (string= (js2-label-node-name (car label-list)) name)
3149 (setq result (car label-list))
3150 (setq label-list (cdr label-list))))
3151 result))
3152
3153 (defun js2-visit-labeled-stmt (n v)
3154 (dolist (label (js2-labeled-stmt-node-labels n))
3155 (js2-visit-ast label v))
3156 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3157
3158 (defun js2-print-labeled-stmt (n i)
3159 (dolist (label (js2-labeled-stmt-node-labels n))
3160 (js2-print-ast label i))
3161 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3162
3163 (defun js2-labeled-stmt-node-contains (node label)
3164 "Return t if NODE contains LABEL in its label set.
3165 NODE is a `js2-labels-node'. LABEL is an identifier."
3166 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3167 if (string= label (js2-label-node-name nl))
3168 return t
3169 finally return nil))
3170
3171 (defsubst js2-labeled-stmt-node-add-label (node label)
3172 "Add a `js2-label-node' to the label set for this statement."
3173 (setf (js2-labeled-stmt-node-labels node)
3174 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3175
3176 (cl-defstruct (js2-jump-node
3177 (:include js2-node)
3178 (:constructor nil))
3179 "Abstract supertype of break and continue nodes."
3180 label ; `js2-name-node' for location of label identifier, if present
3181 target) ; target js2-labels-node or loop/switch statement
3182
3183 (defun js2-visit-jump-node (n v)
3184 ;; We don't visit the target, since it's a back-link.
3185 (js2-visit-ast (js2-jump-node-label n) v))
3186
3187 (cl-defstruct (js2-break-node
3188 (:include js2-jump-node)
3189 (:constructor nil)
3190 (:constructor make-js2-break-node (&key (type js2-BREAK)
3191 (pos js2-ts-cursor)
3192 len label target)))
3193 "AST node for a break statement.
3194 The label field is a `js2-name-node', possibly nil, for the named label
3195 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3196 is the target of the break - a label node or enclosing loop/switch statement.")
3197
3198 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3199 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3200
3201 (defun js2-print-break-node (n i)
3202 (insert (js2-make-pad i) "break")
3203 (when (js2-break-node-label n)
3204 (insert " ")
3205 (js2-print-ast (js2-break-node-label n) 0))
3206 (insert ";\n"))
3207
3208 (cl-defstruct (js2-continue-node
3209 (:include js2-jump-node)
3210 (:constructor nil)
3211 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3212 (pos js2-ts-cursor)
3213 len label target)))
3214 "AST node for a continue statement.
3215 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3216 It is nil if continue specifies no label. The target field is the jump target:
3217 a `js2-label-node' or the innermost enclosing loop.")
3218
3219 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3220 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3221
3222 (defun js2-print-continue-node (n i)
3223 (insert (js2-make-pad i) "continue")
3224 (when (js2-continue-node-label n)
3225 (insert " ")
3226 (js2-print-ast (js2-continue-node-label n) 0))
3227 (insert ";\n"))
3228
3229 (cl-defstruct (js2-function-node
3230 (:include js2-script-node)
3231 (:constructor nil)
3232 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3233 (pos js2-ts-cursor)
3234 len
3235 (ftype 'FUNCTION)
3236 (form 'FUNCTION_STATEMENT)
3237 (name "")
3238 params rest-p
3239 body
3240 generator-type
3241 lp rp)))
3242 "AST node for a function declaration.
3243 The `params' field is a Lisp list of nodes. Each node is either a simple
3244 `js2-name-node', or if it's a destructuring-assignment parameter, a
3245 `js2-array-node' or `js2-object-node'."
3246 ftype ; FUNCTION, GETTER or SETTER
3247 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3248 name ; function name (a `js2-name-node', or nil if anonymous)
3249 params ; a Lisp list of destructuring forms or simple name nodes
3250 rest-p ; if t, the last parameter is rest parameter
3251 body ; a `js2-block-node' or expression node (1.8 only)
3252 lp ; position of arg-list open-paren, or nil if omitted
3253 rp ; position of arg-list close-paren, or nil if omitted
3254 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3255 needs-activation ; t if we need an activation object for this frame
3256 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3257 member-expr) ; nonstandard Ecma extension from Rhino
3258
3259 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3260 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3261
3262 (defun js2-visit-function-node (n v)
3263 (js2-visit-ast (js2-function-node-name n) v)
3264 (dolist (p (js2-function-node-params n))
3265 (js2-visit-ast p v))
3266 (js2-visit-ast (js2-function-node-body n) v))
3267
3268 (defun js2-print-function-node (n i)
3269 (let* ((pad (js2-make-pad i))
3270 (getter (js2-node-get-prop n 'GETTER_SETTER))
3271 (name (or (js2-function-node-name n)
3272 (js2-function-node-member-expr n)))
3273 (params (js2-function-node-params n))
3274 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3275 (rest-p (js2-function-node-rest-p n))
3276 (body (js2-function-node-body n))
3277 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3278 (unless (or getter arrow)
3279 (insert pad "function")
3280 (when (eq (js2-function-node-generator-type n) 'STAR)
3281 (insert "*")))
3282 (when name
3283 (insert " ")
3284 (js2-print-ast name 0))
3285 (insert "(")
3286 (cl-loop with len = (length params)
3287 for param in params
3288 for count from 1
3289 do
3290 (when (and rest-p (= count len))
3291 (insert "..."))
3292 (js2-print-ast param 0)
3293 (when (< count len)
3294 (insert ", ")))
3295 (insert ") ")
3296 (when arrow
3297 (insert "=> "))
3298 (insert "{")
3299 ;; TODO: fix this to be smarter about indenting, etc.
3300 (unless expr
3301 (insert "\n"))
3302 (if (js2-block-node-p body)
3303 (js2-print-body body (1+ i))
3304 (js2-print-ast body 0))
3305 (insert pad "}")
3306 (unless expr
3307 (insert "\n"))))
3308
3309 (defun js2-function-name (node)
3310 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3311 (and (js2-function-node-name node)
3312 (js2-name-node-name (js2-function-node-name node))))
3313
3314 ;; Having this be an expression node makes it more flexible.
3315 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3316 ;; that work better if you assume it's an expression. Whenever we have
3317 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3318 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3319 (cl-defstruct (js2-var-decl-node
3320 (:include js2-node)
3321 (:constructor nil)
3322 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3323 (pos (js2-current-token-beg))
3324 len kids
3325 decl-type)))
3326 "AST node for a variable declaration list (VAR, CONST or LET).
3327 The node bounds differ depending on the declaration type. For VAR or
3328 CONST declarations, the bounds include the var/const keyword. For LET
3329 declarations, the node begins at the position of the first child."
3330 kids ; a Lisp list of `js2-var-init-node' structs.
3331 decl-type) ; js2-VAR, js2-CONST or js2-LET
3332
3333 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3334 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3335
3336 (defun js2-visit-var-decl (n v)
3337 (dolist (kid (js2-var-decl-node-kids n))
3338 (js2-visit-ast kid v)))
3339
3340 (defun js2-print-var-decl (n i)
3341 (let ((pad (js2-make-pad i))
3342 (tt (js2-var-decl-node-decl-type n)))
3343 (insert pad)
3344 (insert (cond
3345 ((= tt js2-VAR) "var ")
3346 ((= tt js2-LET) "let ")
3347 ((= tt js2-CONST) "const ")
3348 (t
3349 (error "malformed var-decl node"))))
3350 (cl-loop with kids = (js2-var-decl-node-kids n)
3351 with len = (length kids)
3352 for kid in kids
3353 for count from 1
3354 do
3355 (js2-print-ast kid 0)
3356 (if (< count len)
3357 (insert ", ")))))
3358
3359 (cl-defstruct (js2-var-init-node
3360 (:include js2-node)
3361 (:constructor nil)
3362 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3363 (pos js2-ts-cursor)
3364 len target
3365 initializer)))
3366 "AST node for a variable declaration.
3367 The type field will be js2-CONST for a const decl."
3368 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3369 initializer) ; initializer expression, a `js2-node'
3370
3371 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3372 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3373
3374 (defun js2-visit-var-init-node (n v)
3375 (js2-visit-ast (js2-var-init-node-target n) v)
3376 (js2-visit-ast (js2-var-init-node-initializer n) v))
3377
3378 (defun js2-print-var-init-node (n i)
3379 (let ((pad (js2-make-pad i))
3380 (name (js2-var-init-node-target n))
3381 (init (js2-var-init-node-initializer n)))
3382 (insert pad)
3383 (js2-print-ast name 0)
3384 (when init
3385 (insert " = ")
3386 (js2-print-ast init 0))))
3387
3388 (cl-defstruct (js2-cond-node
3389 (:include js2-node)
3390 (:constructor nil)
3391 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3392 (pos js2-ts-cursor)
3393 len
3394 test-expr
3395 true-expr
3396 false-expr
3397 q-pos c-pos)))
3398 "AST node for the ternary operator"
3399 test-expr
3400 true-expr
3401 false-expr
3402 q-pos ; buffer position of ?
3403 c-pos) ; buffer position of :
3404
3405 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3406 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3407
3408 (defun js2-visit-cond-node (n v)
3409 (js2-visit-ast (js2-cond-node-test-expr n) v)
3410 (js2-visit-ast (js2-cond-node-true-expr n) v)
3411 (js2-visit-ast (js2-cond-node-false-expr n) v))
3412
3413 (defun js2-print-cond-node (n i)
3414 (let ((pad (js2-make-pad i)))
3415 (insert pad)
3416 (js2-print-ast (js2-cond-node-test-expr n) 0)
3417 (insert " ? ")
3418 (js2-print-ast (js2-cond-node-true-expr n) 0)
3419 (insert " : ")
3420 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3421
3422 (cl-defstruct (js2-infix-node
3423 (:include js2-node)
3424 (:constructor nil)
3425 (:constructor make-js2-infix-node (&key type
3426 (pos js2-ts-cursor)
3427 len op-pos
3428 left right)))
3429 "Represents infix expressions.
3430 Includes assignment ops like `|=', and the comma operator.
3431 The type field inherited from `js2-node' holds the operator."
3432 op-pos ; buffer position where operator begins
3433 left ; any `js2-node'
3434 right) ; any `js2-node'
3435
3436 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3437 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3438
3439 (defun js2-visit-infix-node (n v)
3440 (js2-visit-ast (js2-infix-node-left n) v)
3441 (js2-visit-ast (js2-infix-node-right n) v))
3442
3443 (defconst js2-operator-tokens
3444 (let ((table (make-hash-table :test 'eq))
3445 (tokens
3446 (list (cons js2-IN "in")
3447 (cons js2-TYPEOF "typeof")
3448 (cons js2-INSTANCEOF "instanceof")
3449 (cons js2-DELPROP "delete")
3450 (cons js2-COMMA ",")
3451 (cons js2-COLON ":")
3452 (cons js2-OR "||")
3453 (cons js2-AND "&&")
3454 (cons js2-INC "++")
3455 (cons js2-DEC "--")
3456 (cons js2-BITOR "|")
3457 (cons js2-BITXOR "^")
3458 (cons js2-BITAND "&")
3459 (cons js2-EQ "==")
3460 (cons js2-NE "!=")
3461 (cons js2-LT "<")
3462 (cons js2-LE "<=")
3463 (cons js2-GT ">")
3464 (cons js2-GE ">=")
3465 (cons js2-LSH "<<")
3466 (cons js2-RSH ">>")
3467 (cons js2-URSH ">>>")
3468 (cons js2-ADD "+") ; infix plus
3469 (cons js2-SUB "-") ; infix minus
3470 (cons js2-MUL "*")
3471 (cons js2-DIV "/")
3472 (cons js2-MOD "%")
3473 (cons js2-NOT "!")
3474 (cons js2-BITNOT "~")
3475 (cons js2-POS "+") ; unary plus
3476 (cons js2-NEG "-") ; unary minus
3477 (cons js2-TRIPLEDOT "...")
3478 (cons js2-SHEQ "===") ; shallow equality
3479 (cons js2-SHNE "!==") ; shallow inequality
3480 (cons js2-ASSIGN "=")
3481 (cons js2-ASSIGN_BITOR "|=")
3482 (cons js2-ASSIGN_BITXOR "^=")
3483 (cons js2-ASSIGN_BITAND "&=")
3484 (cons js2-ASSIGN_LSH "<<=")
3485 (cons js2-ASSIGN_RSH ">>=")
3486 (cons js2-ASSIGN_URSH ">>>=")
3487 (cons js2-ASSIGN_ADD "+=")
3488 (cons js2-ASSIGN_SUB "-=")
3489 (cons js2-ASSIGN_MUL "*=")
3490 (cons js2-ASSIGN_DIV "/=")
3491 (cons js2-ASSIGN_MOD "%="))))
3492 (cl-loop for (k . v) in tokens do
3493 (puthash k v table))
3494 table))
3495
3496 (defun js2-print-infix-node (n i)
3497 (let* ((tt (js2-node-type n))
3498 (op (gethash tt js2-operator-tokens)))
3499 (unless op
3500 (error "unrecognized infix operator %s" (js2-node-type n)))
3501 (insert (js2-make-pad i))
3502 (js2-print-ast (js2-infix-node-left n) 0)
3503 (unless (= tt js2-COMMA)
3504 (insert " "))
3505 (insert op)
3506 (insert " ")
3507 (js2-print-ast (js2-infix-node-right n) 0)))
3508
3509 (cl-defstruct (js2-assign-node
3510 (:include js2-infix-node)
3511 (:constructor nil)
3512 (:constructor make-js2-assign-node (&key type
3513 (pos js2-ts-cursor)
3514 len op-pos
3515 left right)))
3516 "Represents any assignment.
3517 The type field holds the actual assignment operator.")
3518
3519 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3520 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3521
3522 (cl-defstruct (js2-unary-node
3523 (:include js2-node)
3524 (:constructor nil)
3525 (:constructor make-js2-unary-node (&key type ; required
3526 (pos js2-ts-cursor)
3527 len operand)))
3528 "AST node type for unary operator nodes.
3529 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3530 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3531 property is added if the operator follows the operand."
3532 operand) ; a `js2-node' expression
3533
3534 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3535 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3536
3537 (defun js2-visit-unary-node (n v)
3538 (js2-visit-ast (js2-unary-node-operand n) v))
3539
3540 (defun js2-print-unary-node (n i)
3541 (let* ((tt (js2-node-type n))
3542 (op (gethash tt js2-operator-tokens))
3543 (postfix (js2-node-get-prop n 'postfix)))
3544 (unless op
3545 (error "unrecognized unary operator %s" tt))
3546 (insert (js2-make-pad i))
3547 (unless postfix
3548 (insert op))
3549 (if (or (= tt js2-TYPEOF)
3550 (= tt js2-DELPROP))
3551 (insert " "))
3552 (js2-print-ast (js2-unary-node-operand n) 0)
3553 (when postfix
3554 (insert op))))
3555
3556 (cl-defstruct (js2-let-node
3557 (:include js2-scope)
3558 (:constructor nil)
3559 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3560 (pos (js2-current-token-beg))
3561 len vars body
3562 lp rp)))
3563 "AST node for a let expression or a let statement.
3564 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3565 vars ; a `js2-var-decl-node'
3566 body ; a `js2-node' representing the expression or body block
3567 lp
3568 rp)
3569
3570 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3571 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3572
3573 (defun js2-visit-let-node (n v)
3574 (js2-visit-ast (js2-let-node-vars n) v)
3575 (js2-visit-ast (js2-let-node-body n) v))
3576
3577 (defun js2-print-let-node (n i)
3578 (insert (js2-make-pad i) "let (")
3579 (let ((p (point)))
3580 (js2-print-ast (js2-let-node-vars n) 0)
3581 (delete-region p (+ p 4)))
3582 (insert ") ")
3583 (js2-print-ast (js2-let-node-body n) i))
3584
3585 (cl-defstruct (js2-keyword-node
3586 (:include js2-node)
3587 (:constructor nil)
3588 (:constructor make-js2-keyword-node (&key type
3589 (pos (js2-current-token-beg))
3590 (len (- js2-ts-cursor pos)))))
3591 "AST node representing a literal keyword such as `null'.
3592 Used for `null', `this', `true', `false' and `debugger'.
3593 The node type is set to js2-NULL, js2-THIS, etc.")
3594
3595 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3596 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3597
3598 (defun js2-print-keyword-node (n i)
3599 (insert (js2-make-pad i)
3600 (let ((tt (js2-node-type n)))
3601 (cond
3602 ((= tt js2-THIS) "this")
3603 ((= tt js2-SUPER) "super")
3604 ((= tt js2-NULL) "null")
3605 ((= tt js2-TRUE) "true")
3606 ((= tt js2-FALSE) "false")
3607 ((= tt js2-DEBUGGER) "debugger")
3608 (t (error "Invalid keyword literal type: %d" tt))))))
3609
3610 (defsubst js2-this-or-super-node-p (node)
3611 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3612 (let ((type (js2-node-type node)))
3613 (or (eq type js2-THIS) (eq type js2-SUPER))))
3614
3615 (cl-defstruct (js2-new-node
3616 (:include js2-node)
3617 (:constructor nil)
3618 (:constructor make-js2-new-node (&key (type js2-NEW)
3619 (pos (js2-current-token-beg))
3620 len target
3621 args initializer
3622 lp rp)))
3623 "AST node for new-expression such as new Foo()."
3624 target ; an identifier or reference
3625 args ; a Lisp list of argument nodes
3626 lp ; position of left-paren, nil if omitted
3627 rp ; position of right-paren, nil if omitted
3628 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3629
3630 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3631 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3632
3633 (defun js2-visit-new-node (n v)
3634 (js2-visit-ast (js2-new-node-target n) v)
3635 (dolist (arg (js2-new-node-args n))
3636 (js2-visit-ast arg v))
3637 (js2-visit-ast (js2-new-node-initializer n) v))
3638
3639 (defun js2-print-new-node (n i)
3640 (insert (js2-make-pad i) "new ")
3641 (js2-print-ast (js2-new-node-target n))
3642 (insert "(")
3643 (js2-print-list (js2-new-node-args n))
3644 (insert ")")
3645 (when (js2-new-node-initializer n)
3646 (insert " ")
3647 (js2-print-ast (js2-new-node-initializer n))))
3648
3649 (cl-defstruct (js2-name-node
3650 (:include js2-node)
3651 (:constructor nil)
3652 (:constructor make-js2-name-node (&key (type js2-NAME)
3653 (pos (js2-current-token-beg))
3654 (len (- js2-ts-cursor
3655 (js2-current-token-beg)))
3656 (name (js2-current-token-string)))))
3657 "AST node for a JavaScript identifier"
3658 name ; a string
3659 scope) ; a `js2-scope' (optional, used for codegen)
3660
3661 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3662 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3663
3664 (defun js2-print-name-node (n i)
3665 (insert (js2-make-pad i)
3666 (js2-name-node-name n)))
3667
3668 (defsubst js2-name-node-length (node)
3669 "Return identifier length of NODE, a `js2-name-node'.
3670 Returns 0 if NODE is nil or its identifier field is nil."
3671 (if node
3672 (length (js2-name-node-name node))
3673 0))
3674
3675 (cl-defstruct (js2-number-node
3676 (:include js2-node)
3677 (:constructor nil)
3678 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3679 (pos (js2-current-token-beg))
3680 (len (- js2-ts-cursor
3681 (js2-current-token-beg)))
3682 (value (js2-current-token-string))
3683 (num-value (js2-token-number
3684 (js2-current-token)))
3685 (num-base (js2-token-number-base
3686 (js2-current-token))))))
3687 "AST node for a number literal."
3688 value ; the original string, e.g. "6.02e23"
3689 num-value ; the parsed number value
3690 num-base) ; the number's base
3691
3692 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3693 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3694
3695 (defun js2-print-number-node (n i)
3696 (insert (js2-make-pad i)
3697 (number-to-string (js2-number-node-num-value n))))
3698
3699 (cl-defstruct (js2-regexp-node
3700 (:include js2-node)
3701 (:constructor nil)
3702 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3703 (pos (js2-current-token-beg))
3704 (len (- js2-ts-cursor
3705 (js2-current-token-beg)))
3706 value flags)))
3707 "AST node for a regular expression literal."
3708 value ; the regexp string, without // delimiters
3709 flags) ; a string of flags, e.g. `mi'.
3710
3711 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3712 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3713
3714 (defun js2-print-regexp (n i)
3715 (insert (js2-make-pad i)
3716 "/"
3717 (js2-regexp-node-value n)
3718 "/")
3719 (if (js2-regexp-node-flags n)
3720 (insert (js2-regexp-node-flags n))))
3721
3722 (cl-defstruct (js2-string-node
3723 (:include js2-node)
3724 (:constructor nil)
3725 (:constructor make-js2-string-node (&key (type js2-STRING)
3726 (pos (js2-current-token-beg))
3727 (len (- js2-ts-cursor
3728 (js2-current-token-beg)))
3729 (value (js2-current-token-string)))))
3730 "String literal.
3731 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3732 You can tell the quote type by looking at the first character."
3733 value) ; the characters of the string, including the quotes
3734
3735 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3736 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3737
3738 (defun js2-print-string-node (n i)
3739 (insert (js2-make-pad i)
3740 (js2-node-string n)))
3741
3742 (cl-defstruct (js2-template-node
3743 (:include js2-node)
3744 (:constructor nil)
3745 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3746 beg len kids)))
3747 "Template literal."
3748 kids) ; `js2-string-node' is used for string segments, other nodes
3749 ; for substitutions inside.
3750
3751 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3752 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3753
3754 (defun js2-visit-template (n callback)
3755 (dolist (kid (js2-template-node-kids n))
3756 (js2-visit-ast kid callback)))
3757
3758 (defun js2-print-template (n i)
3759 (insert (js2-make-pad i))
3760 (dolist (kid (js2-template-node-kids n))
3761 (if (js2-string-node-p kid)
3762 (insert (js2-node-string kid))
3763 (js2-print-ast kid))))
3764
3765 (cl-defstruct (js2-tagged-template-node
3766 (:include js2-node)
3767 (:constructor nil)
3768 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3769 beg len tag template)))
3770 "Tagged template literal."
3771 tag ; `js2-node' with the tag expression.
3772 template) ; `js2-template-node' with the template.
3773
3774 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3775 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3776
3777 (defun js2-visit-tagged-template (n callback)
3778 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3779 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3780
3781 (defun js2-print-tagged-template (n i)
3782 (insert (js2-make-pad i))
3783 (js2-print-ast (js2-tagged-template-node-tag n))
3784 (js2-print-ast (js2-tagged-template-node-template n)))
3785
3786 (cl-defstruct (js2-array-node
3787 (:include js2-node)
3788 (:constructor nil)
3789 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3790 (pos js2-ts-cursor)
3791 len elems)))
3792 "AST node for an array literal."
3793 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3794
3795 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3796 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3797
3798 (defun js2-visit-array-node (n v)
3799 (dolist (e (js2-array-node-elems n))
3800 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3801
3802 (defun js2-print-array-node (n i)
3803 (insert (js2-make-pad i) "[")
3804 (let ((elems (js2-array-node-elems n)))
3805 (js2-print-list elems)
3806 (when (and elems (null (car (last elems))))
3807 (insert ",")))
3808 (insert "]"))
3809
3810 (cl-defstruct (js2-class-node
3811 (:include js2-node)
3812 (:constructor nil)
3813 (:constructor make-js2-class-node (&key (type js2-CLASS)
3814 (pos js2-ts-cursor)
3815 (form 'CLASS_STATEMENT)
3816 (name "")
3817 extends len elems)))
3818 "AST node for an class expression.
3819 `elems' is a list of `js2-object-prop-node', and `extends' is an
3820 optional `js2-expr-node'"
3821 form ; CLASS_{STATEMENT|EXPRESSION}
3822 name ; class name (a `js2-node-name', or nil if anonymous)
3823 extends ; class heritage (a `js2-expr-node', or nil if none)
3824 elems)
3825
3826 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3827 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3828
3829 (defun js2-visit-class-node (n v)
3830 (js2-visit-ast (js2-class-node-name n) v)
3831 (js2-visit-ast (js2-class-node-extends n) v)
3832 (dolist (e (js2-class-node-elems n))
3833 (js2-visit-ast e v)))
3834
3835 (defun js2-print-class-node (n i)
3836 (let* ((pad (js2-make-pad i))
3837 (name (js2-class-node-name n))
3838 (extends (js2-class-node-extends n))
3839 (elems (js2-class-node-elems n)))
3840 (insert pad "class")
3841 (when name
3842 (insert " ")
3843 (js2-print-ast name 0))
3844 (when extends
3845 (insert " extends ")
3846 (js2-print-ast extends))
3847 (insert " {")
3848 (dolist (elem elems)
3849 (insert "\n")
3850 (if (js2-node-get-prop elem 'STATIC)
3851 (progn (insert (js2-make-pad (1+ i)) "static ")
3852 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3853 (js2-print-ast elem (1+ i))))
3854 (insert "\n" pad "}")))
3855
3856 (cl-defstruct (js2-object-node
3857 (:include js2-node)
3858 (:constructor nil)
3859 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3860 (pos js2-ts-cursor)
3861 len
3862 elems)))
3863 "AST node for an object literal expression.
3864 `elems' is a list of `js2-object-prop-node'."
3865 elems)
3866
3867 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3868 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3869
3870 (defun js2-visit-object-node (n v)
3871 (dolist (e (js2-object-node-elems n))
3872 (js2-visit-ast e v)))
3873
3874 (defun js2-print-object-node (n i)
3875 (insert (js2-make-pad i) "{")
3876 (js2-print-list (js2-object-node-elems n))
3877 (insert "}"))
3878
3879 (cl-defstruct (js2-object-prop-node
3880 (:include js2-infix-node)
3881 (:constructor nil)
3882 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3883 (pos js2-ts-cursor)
3884 len left
3885 right op-pos)))
3886 "AST node for an object literal prop:value entry.
3887 The `left' field is the property: a name node, string node,
3888 number node or expression node. The `right' field is a
3889 `js2-node' representing the initializer value. If the property
3890 is abbreviated, the node's `SHORTHAND' property is non-nil and
3891 both fields have the same value.")
3892
3893 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3894 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3895
3896 (defun js2-print-object-prop-node (n i)
3897 (let* ((left (js2-object-prop-node-left n))
3898 (right (js2-object-prop-node-right n))
3899 (computed (not (or (js2-string-node-p left)
3900 (js2-number-node-p left)
3901 (js2-name-node-p left)))))
3902 (insert (js2-make-pad i))
3903 (if computed
3904 (insert "["))
3905 (js2-print-ast left 0)
3906 (if computed
3907 (insert "]"))
3908 (if (not (js2-node-get-prop n 'SHORTHAND))
3909 (progn
3910 (insert ": ")
3911 (js2-print-ast right 0)))))
3912
3913 (cl-defstruct (js2-getter-setter-node
3914 (:include js2-infix-node)
3915 (:constructor nil)
3916 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3917 (pos js2-ts-cursor)
3918 len left right)))
3919 "AST node for a getter/setter property in an object literal.
3920 The `left' field is the `js2-name-node' naming the getter/setter prop.
3921 The `right' field is always an anonymous `js2-function-node' with a node
3922 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3923
3924 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3925 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3926
3927 (defun js2-print-getter-setter (n i)
3928 (let* ((pad (js2-make-pad i))
3929 (left (js2-getter-setter-node-left n))
3930 (right (js2-getter-setter-node-right n))
3931 (computed (not (or (js2-string-node-p left)
3932 (js2-number-node-p left)
3933 (js2-name-node-p left)))))
3934 (insert pad)
3935 (if (/= (js2-node-type n) js2-FUNCTION)
3936 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3937 (when (and (js2-function-node-p right)
3938 (eq 'STAR (js2-function-node-generator-type right)))
3939 (insert "*"))
3940 (when computed
3941 (insert "["))
3942 (js2-print-ast left 0)
3943 (when computed
3944 (insert "]"))
3945 (js2-print-ast right 0)))
3946
3947 (cl-defstruct (js2-prop-get-node
3948 (:include js2-infix-node)
3949 (:constructor nil)
3950 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3951 (pos js2-ts-cursor)
3952 len left right)))
3953 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3954
3955 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3956 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3957
3958 (defun js2-visit-prop-get-node (n v)
3959 (js2-visit-ast (js2-prop-get-node-left n) v)
3960 (js2-visit-ast (js2-prop-get-node-right n) v))
3961
3962 (defun js2-print-prop-get-node (n i)
3963 (insert (js2-make-pad i))
3964 (js2-print-ast (js2-prop-get-node-left n) 0)
3965 (insert ".")
3966 (js2-print-ast (js2-prop-get-node-right n) 0))
3967
3968 (cl-defstruct (js2-elem-get-node
3969 (:include js2-node)
3970 (:constructor nil)
3971 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3972 (pos js2-ts-cursor)
3973 len target element
3974 lb rb)))
3975 "AST node for an array index expression such as foo[bar]."
3976 target ; a `js2-node' - the expression preceding the "."
3977 element ; a `js2-node' - the expression in brackets
3978 lb ; position of left-bracket, nil if omitted
3979 rb) ; position of right-bracket, nil if omitted
3980
3981 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3982 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3983
3984 (defun js2-visit-elem-get-node (n v)
3985 (js2-visit-ast (js2-elem-get-node-target n) v)
3986 (js2-visit-ast (js2-elem-get-node-element n) v))
3987
3988 (defun js2-print-elem-get-node (n i)
3989 (insert (js2-make-pad i))
3990 (js2-print-ast (js2-elem-get-node-target n) 0)
3991 (insert "[")
3992 (js2-print-ast (js2-elem-get-node-element n) 0)
3993 (insert "]"))
3994
3995 (cl-defstruct (js2-call-node
3996 (:include js2-node)
3997 (:constructor nil)
3998 (:constructor make-js2-call-node (&key (type js2-CALL)
3999 (pos js2-ts-cursor)
4000 len target args
4001 lp rp)))
4002 "AST node for a JavaScript function call."
4003 target ; a `js2-node' evaluating to the function to call
4004 args ; a Lisp list of `js2-node' arguments
4005 lp ; position of open-paren, or nil if missing
4006 rp) ; position of close-paren, or nil if missing
4007
4008 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4009 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4010
4011 (defun js2-visit-call-node (n v)
4012 (js2-visit-ast (js2-call-node-target n) v)
4013 (dolist (arg (js2-call-node-args n))
4014 (js2-visit-ast arg v)))
4015
4016 (defun js2-print-call-node (n i)
4017 (insert (js2-make-pad i))
4018 (js2-print-ast (js2-call-node-target n) 0)
4019 (insert "(")
4020 (js2-print-list (js2-call-node-args n))
4021 (insert ")"))
4022
4023 (cl-defstruct (js2-yield-node
4024 (:include js2-node)
4025 (:constructor nil)
4026 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4027 (pos js2-ts-cursor)
4028 len value star-p)))
4029 "AST node for yield statement or expression."
4030 star-p ; whether it's yield*
4031 value) ; optional: value to be yielded
4032
4033 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4034 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4035
4036 (defun js2-visit-yield-node (n v)
4037 (js2-visit-ast (js2-yield-node-value n) v))
4038
4039 (defun js2-print-yield-node (n i)
4040 (insert (js2-make-pad i))
4041 (insert "yield")
4042 (when (js2-yield-node-star-p n)
4043 (insert "*"))
4044 (when (js2-yield-node-value n)
4045 (insert " ")
4046 (js2-print-ast (js2-yield-node-value n) 0)))
4047
4048 (cl-defstruct (js2-paren-node
4049 (:include js2-node)
4050 (:constructor nil)
4051 (:constructor make-js2-paren-node (&key (type js2-LP)
4052 (pos js2-ts-cursor)
4053 len expr)))
4054 "AST node for a parenthesized expression.
4055 In particular, used when the parens are syntactically optional,
4056 as opposed to required parens such as those enclosing an if-conditional."
4057 expr) ; `js2-node'
4058
4059 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4060 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4061
4062 (defun js2-visit-paren-node (n v)
4063 (js2-visit-ast (js2-paren-node-expr n) v))
4064
4065 (defun js2-print-paren-node (n i)
4066 (insert (js2-make-pad i))
4067 (insert "(")
4068 (js2-print-ast (js2-paren-node-expr n) 0)
4069 (insert ")"))
4070
4071 (cl-defstruct (js2-comp-node
4072 (:include js2-scope)
4073 (:constructor nil)
4074 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4075 (pos js2-ts-cursor)
4076 len result
4077 loops filters
4078 form)))
4079 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4080 result ; result expression (just after left-bracket)
4081 loops ; a Lisp list of `js2-comp-loop-node'
4082 filters ; a Lisp list of guard/filter expressions
4083 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4084 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4085 )
4086
4087 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4088 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4089
4090 (defun js2-visit-comp-node (n v)
4091 (js2-visit-ast (js2-comp-node-result n) v)
4092 (dolist (l (js2-comp-node-loops n))
4093 (js2-visit-ast l v))
4094 (dolist (f (js2-comp-node-filters n))
4095 (js2-visit-ast f v)))
4096
4097 (defun js2-print-comp-node (n i)
4098 (let ((pad (js2-make-pad i))
4099 (result (js2-comp-node-result n))
4100 (loops (js2-comp-node-loops n))
4101 (filters (js2-comp-node-filters n))
4102 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4103 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4104 (insert pad (if gen-p "(" "["))
4105 (when legacy-p
4106 (js2-print-ast result 0))
4107 (dolist (l loops)
4108 (when legacy-p
4109 (insert " "))
4110 (js2-print-ast l 0)
4111 (unless legacy-p
4112 (insert " ")))
4113 (dolist (f filters)
4114 (when legacy-p
4115 (insert " "))
4116 (insert "if (")
4117 (js2-print-ast f 0)
4118 (insert ")")
4119 (unless legacy-p
4120 (insert " ")))
4121 (unless legacy-p
4122 (js2-print-ast result 0))
4123 (insert (if gen-p ")" "]"))))
4124
4125 (cl-defstruct (js2-comp-loop-node
4126 (:include js2-for-in-node)
4127 (:constructor nil)
4128 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4129 (pos js2-ts-cursor)
4130 len iterator
4131 object in-pos
4132 foreach-p
4133 each-pos
4134 forof-p
4135 lp rp)))
4136 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4137
4138 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4139 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4140
4141 (defun js2-visit-comp-loop (n v)
4142 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4143 (js2-visit-ast (js2-comp-loop-node-object n) v))
4144
4145 (defun js2-print-comp-loop (n _i)
4146 (insert "for ")
4147 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4148 (insert "(")
4149 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4150 (insert (if (js2-comp-loop-node-forof-p n)
4151 " of " " in "))
4152 (js2-print-ast (js2-comp-loop-node-object n) 0)
4153 (insert ")"))
4154
4155 (cl-defstruct (js2-empty-expr-node
4156 (:include js2-node)
4157 (:constructor nil)
4158 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4159 (pos (js2-current-token-beg))
4160 len)))
4161 "AST node for an empty expression.")
4162
4163 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4164 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4165
4166 (cl-defstruct (js2-xml-node
4167 (:include js2-block-node)
4168 (:constructor nil)
4169 (:constructor make-js2-xml-node (&key (type js2-XML)
4170 (pos (js2-current-token-beg))
4171 len kids)))
4172 "AST node for initial parse of E4X literals.
4173 The kids field is a list of XML fragments, each a `js2-string-node' or
4174 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4175
4176 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4177 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4178
4179 (defun js2-print-xml-node (n i)
4180 (dolist (kid (js2-xml-node-kids n))
4181 (js2-print-ast kid i)))
4182
4183 (cl-defstruct (js2-xml-js-expr-node
4184 (:include js2-xml-node)
4185 (:constructor nil)
4186 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4187 (pos js2-ts-cursor)
4188 len expr)))
4189 "AST node for an embedded JavaScript {expression} in an E4X literal.
4190 The start and end fields correspond to the curly-braces."
4191 expr) ; a `js2-expr-node' of some sort
4192
4193 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4194 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4195
4196 (defun js2-visit-xml-js-expr (n v)
4197 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4198
4199 (defun js2-print-xml-js-expr (n i)
4200 (insert (js2-make-pad i))
4201 (insert "{")
4202 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4203 (insert "}"))
4204
4205 (cl-defstruct (js2-xml-dot-query-node
4206 (:include js2-infix-node)
4207 (:constructor nil)
4208 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4209 (pos js2-ts-cursor)
4210 op-pos len left
4211 right rp)))
4212 "AST node for an E4X foo.(bar) filter expression.
4213 Note that the left-paren is automatically the character immediately
4214 following the dot (.) in the operator. No whitespace is permitted
4215 between the dot and the lp by the scanner."
4216 rp)
4217
4218 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4219 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4220
4221 (defun js2-print-xml-dot-query (n i)
4222 (insert (js2-make-pad i))
4223 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4224 (insert ".(")
4225 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4226 (insert ")"))
4227
4228 (cl-defstruct (js2-xml-ref-node
4229 (:include js2-node)
4230 (:constructor nil)) ; abstract
4231 "Base type for E4X XML attribute-access or property-get expressions.
4232 Such expressions can take a variety of forms. The general syntax has
4233 three parts:
4234
4235 - (optional) an @ (specifying an attribute access)
4236 - (optional) a namespace (a `js2-name-node') and double-colon
4237 - (required) either a `js2-name-node' or a bracketed [expression]
4238
4239 The property-name expressions (examples: ns::name, @name) are
4240 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4241 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4242
4243 This node type (or more specifically, its subclasses) will sometimes
4244 be the right-hand child of a `js2-prop-get-node' or a
4245 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4246 The `js2-xml-ref-node' may also be a standalone primary expression with
4247 no explicit target, which is valid in certain expression contexts such as
4248
4249 company..employee.(@id < 100)
4250
4251 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4252 expression whose parent is a `js2-xml-dot-query-node'."
4253 namespace
4254 at-pos
4255 colon-pos)
4256
4257 (defsubst js2-xml-ref-node-attr-access-p (node)
4258 "Return non-nil if this expression began with an @-token."
4259 (and (numberp (js2-xml-ref-node-at-pos node))
4260 (cl-plusp (js2-xml-ref-node-at-pos node))))
4261
4262 (cl-defstruct (js2-xml-prop-ref-node
4263 (:include js2-xml-ref-node)
4264 (:constructor nil)
4265 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4266 (pos (js2-current-token-beg))
4267 len propname
4268 namespace at-pos
4269 colon-pos)))
4270 "AST node for an E4X XML [expr] property-ref expression.
4271 The JavaScript syntax is an optional @, an optional ns::, and a name.
4272
4273 [ '@' ] [ name '::' ] name
4274
4275 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4276 @ns::*, @*::attr, @*::*, and @*.
4277
4278 The node starts at the @ token, if present. Otherwise it starts at the
4279 namespace name. The node bounds extend through the closing right-bracket,
4280 or if it is missing due to a syntax error, through the end of the index
4281 expression."
4282 propname)
4283
4284 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4285 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4286
4287 (defun js2-visit-xml-prop-ref-node (n v)
4288 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4289 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4290
4291 (defun js2-print-xml-prop-ref-node (n i)
4292 (insert (js2-make-pad i))
4293 (if (js2-xml-ref-node-attr-access-p n)
4294 (insert "@"))
4295 (when (js2-xml-prop-ref-node-namespace n)
4296 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4297 (insert "::"))
4298 (if (js2-xml-prop-ref-node-propname n)
4299 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4300
4301 (cl-defstruct (js2-xml-elem-ref-node
4302 (:include js2-xml-ref-node)
4303 (:constructor nil)
4304 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4305 (pos (js2-current-token-beg))
4306 len expr lb rb
4307 namespace at-pos
4308 colon-pos)))
4309 "AST node for an E4X XML [expr] member-ref expression.
4310 Syntax:
4311
4312 [ '@' ] [ name '::' ] '[' expr ']'
4313
4314 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4315
4316 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4317 is not a legal E4X XML element-ref expression, since it's already used
4318 for standard JavaScript element-get array indexing. Hence, a
4319 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4320 non-nil namespace node, or both.
4321
4322 The node starts at the @ token, if present. Otherwise it starts
4323 at the namespace name. The node bounds extend through the closing
4324 right-bracket, or if it is missing due to a syntax error, through the
4325 end of the index expression."
4326 expr ; the bracketed index expression
4327 lb
4328 rb)
4329
4330 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4331 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4332
4333 (defun js2-visit-xml-elem-ref-node (n v)
4334 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4335 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4336
4337 (defun js2-print-xml-elem-ref-node (n i)
4338 (insert (js2-make-pad i))
4339 (if (js2-xml-ref-node-attr-access-p n)
4340 (insert "@"))
4341 (when (js2-xml-elem-ref-node-namespace n)
4342 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4343 (insert "::"))
4344 (insert "[")
4345 (if (js2-xml-elem-ref-node-expr n)
4346 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4347 (insert "]"))
4348
4349 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4350
4351 (cl-defstruct (js2-xml-start-tag-node
4352 (:include js2-xml-node)
4353 (:constructor nil)
4354 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4355 (pos js2-ts-cursor)
4356 len name attrs kids
4357 empty-p)))
4358 "AST node for an XML start-tag. Not currently used.
4359 The `kids' field is a Lisp list of child content nodes."
4360 name ; a `js2-xml-name-node'
4361 attrs ; a Lisp list of `js2-xml-attr-node'
4362 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4363
4364 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4365 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4366
4367 (defun js2-visit-xml-start-tag (n v)
4368 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4369 (dolist (attr (js2-xml-start-tag-node-attrs n))
4370 (js2-visit-ast attr v))
4371 (js2-visit-block n v))
4372
4373 (defun js2-print-xml-start-tag (n i)
4374 (insert (js2-make-pad i) "<")
4375 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4376 (when (js2-xml-start-tag-node-attrs n)
4377 (insert " ")
4378 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4379 (insert ">"))
4380
4381 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4382 ;; and add the end-tag to the kids list of the parent as well.
4383 (cl-defstruct (js2-xml-end-tag-node
4384 (:include js2-xml-node)
4385 (:constructor nil)
4386 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4387 (pos js2-ts-cursor)
4388 len name)))
4389 "AST node for an XML end-tag. Not currently used."
4390 name) ; a `js2-xml-name-node'
4391
4392 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4393 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4394
4395 (defun js2-visit-xml-end-tag (n v)
4396 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4397
4398 (defun js2-print-xml-end-tag (n i)
4399 (insert (js2-make-pad i))
4400 (insert "</")
4401 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4402 (insert ">"))
4403
4404 (cl-defstruct (js2-xml-name-node
4405 (:include js2-xml-node)
4406 (:constructor nil)
4407 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4408 (pos js2-ts-cursor)
4409 len namespace kids)))
4410 "AST node for an E4X XML name. Not currently used.
4411 Any XML name can be qualified with a namespace, hence the namespace field.
4412 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4413 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4414 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4415 namespace) ; a `js2-string-node'
4416
4417 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4418 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4419
4420 (defun js2-visit-xml-name-node (n v)
4421 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4422
4423 (defun js2-print-xml-name-node (n i)
4424 (insert (js2-make-pad i))
4425 (when (js2-xml-name-node-namespace n)
4426 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4427 (insert "::"))
4428 (dolist (kid (js2-xml-name-node-kids n))
4429 (js2-print-ast kid 0)))
4430
4431 (cl-defstruct (js2-xml-pi-node
4432 (:include js2-xml-node)
4433 (:constructor nil)
4434 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4435 (pos js2-ts-cursor)
4436 len name attrs)))
4437 "AST node for an E4X XML processing instruction. Not currently used."
4438 name ; a `js2-xml-name-node'
4439 attrs) ; a list of `js2-xml-attr-node'
4440
4441 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4442 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4443
4444 (defun js2-visit-xml-pi-node (n v)
4445 (js2-visit-ast (js2-xml-pi-node-name n) v)
4446 (dolist (attr (js2-xml-pi-node-attrs n))
4447 (js2-visit-ast attr v)))
4448
4449 (defun js2-print-xml-pi-node (n i)
4450 (insert (js2-make-pad i) "<?")
4451 (js2-print-ast (js2-xml-pi-node-name n))
4452 (when (js2-xml-pi-node-attrs n)
4453 (insert " ")
4454 (js2-print-list (js2-xml-pi-node-attrs n)))
4455 (insert "?>"))
4456
4457 (cl-defstruct (js2-xml-cdata-node
4458 (:include js2-xml-node)
4459 (:constructor nil)
4460 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4461 (pos js2-ts-cursor)
4462 len content)))
4463 "AST node for a CDATA escape section. Not currently used."
4464 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4465
4466 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4467 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4468
4469 (defun js2-visit-xml-cdata-node (n v)
4470 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4471
4472 (defun js2-print-xml-cdata-node (n i)
4473 (insert (js2-make-pad i))
4474 (js2-print-ast (js2-xml-cdata-node-content n)))
4475
4476 (cl-defstruct (js2-xml-attr-node
4477 (:include js2-xml-node)
4478 (:constructor nil)
4479 (:constructor make-js2-attr-node (&key (type js2-XML)
4480 (pos js2-ts-cursor)
4481 len name value
4482 eq-pos quote-type)))
4483 "AST node representing a foo='bar' XML attribute value. Not yet used."
4484 name ; a `js2-xml-name-node'
4485 value ; a `js2-xml-name-node'
4486 eq-pos ; buffer position of "=" sign
4487 quote-type) ; 'single or 'double
4488
4489 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4490 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4491
4492 (defun js2-visit-xml-attr-node (n v)
4493 (js2-visit-ast (js2-xml-attr-node-name n) v)
4494 (js2-visit-ast (js2-xml-attr-node-value n) v))
4495
4496 (defun js2-print-xml-attr-node (n i)
4497 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4498 "'"
4499 "\"")))
4500 (insert (js2-make-pad i))
4501 (js2-print-ast (js2-xml-attr-node-name n) 0)
4502 (insert "=" quote)
4503 (js2-print-ast (js2-xml-attr-node-value n) 0)
4504 (insert quote)))
4505
4506 (cl-defstruct (js2-xml-text-node
4507 (:include js2-xml-node)
4508 (:constructor nil)
4509 (:constructor make-js2-text-node (&key (type js2-XML)
4510 (pos js2-ts-cursor)
4511 len content)))
4512 "AST node for an E4X XML text node. Not currently used."
4513 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4514
4515 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4516 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4517
4518 (defun js2-visit-xml-text-node (n v)
4519 (js2-visit-ast (js2-xml-text-node-content n) v))
4520
4521 (defun js2-print-xml-text-node (n i)
4522 (insert (js2-make-pad i))
4523 (dolist (kid (js2-xml-text-node-content n))
4524 (js2-print-ast kid)))
4525
4526 (cl-defstruct (js2-xml-comment-node
4527 (:include js2-xml-node)
4528 (:constructor nil)
4529 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4530 (pos js2-ts-cursor)
4531 len)))
4532 "AST node for E4X XML comment. Not currently used.")
4533
4534 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4535 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4536
4537 (defun js2-print-xml-comment (n i)
4538 (insert (js2-make-pad i)
4539 (js2-node-string n)))
4540
4541 ;;; Node utilities
4542
4543 (defsubst js2-node-line (n)
4544 "Fetch the source line number at the start of node N.
4545 This is O(n) in the length of the source buffer; use prudently."
4546 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4547
4548 (defsubst js2-block-node-kid (n i)
4549 "Return child I of node N, or nil if there aren't that many."
4550 (nth i (js2-block-node-kids n)))
4551
4552 (defsubst js2-block-node-first (n)
4553 "Return first child of block node N, or nil if there is none."
4554 (cl-first (js2-block-node-kids n)))
4555
4556 (defun js2-node-root (n)
4557 "Return the root of the AST containing N.
4558 If N has no parent pointer, returns N."
4559 (let ((parent (js2-node-parent n)))
4560 (if parent
4561 (js2-node-root parent)
4562 n)))
4563
4564 (defsubst js2-node-short-name (n)
4565 "Return the short name of node N as a string, e.g. `js2-if-node'."
4566 (substring (symbol-name (aref n 0))
4567 (length "cl-struct-")))
4568
4569 (defun js2-node-child-list (node)
4570 "Return the child list for NODE, a Lisp list of nodes.
4571 Works for block nodes, array nodes, obj literals, funarg lists,
4572 var decls and try nodes (for catch clauses). Note that you should call
4573 `js2-block-node-kids' on the function body for the body statements.
4574 Returns nil for zero-length child lists or unsupported nodes."
4575 (cond
4576 ((js2-function-node-p node)
4577 (js2-function-node-params node))
4578 ((js2-block-node-p node)
4579 (js2-block-node-kids node))
4580 ((js2-try-node-p node)
4581 (js2-try-node-catch-clauses node))
4582 ((js2-array-node-p node)
4583 (js2-array-node-elems node))
4584 ((js2-object-node-p node)
4585 (js2-object-node-elems node))
4586 ((js2-call-node-p node)
4587 (js2-call-node-args node))
4588 ((js2-new-node-p node)
4589 (js2-new-node-args node))
4590 ((js2-var-decl-node-p node)
4591 (js2-var-decl-node-kids node))
4592 (t
4593 nil)))
4594
4595 (defun js2-node-set-child-list (node kids)
4596 "Set the child list for NODE to KIDS."
4597 (cond
4598 ((js2-function-node-p node)
4599 (setf (js2-function-node-params node) kids))
4600 ((js2-block-node-p node)
4601 (setf (js2-block-node-kids node) kids))
4602 ((js2-try-node-p node)
4603 (setf (js2-try-node-catch-clauses node) kids))
4604 ((js2-array-node-p node)
4605 (setf (js2-array-node-elems node) kids))
4606 ((js2-object-node-p node)
4607 (setf (js2-object-node-elems node) kids))
4608 ((js2-call-node-p node)
4609 (setf (js2-call-node-args node) kids))
4610 ((js2-new-node-p node)
4611 (setf (js2-new-node-args node) kids))
4612 ((js2-var-decl-node-p node)
4613 (setf (js2-var-decl-node-kids node) kids))
4614 (t
4615 (error "Unsupported node type: %s" (js2-node-short-name node))))
4616 kids)
4617
4618 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4619 (defconst js2-paren-expr-nodes
4620 '(cl-struct-js2-comp-loop-node
4621 cl-struct-js2-comp-node
4622 cl-struct-js2-call-node
4623 cl-struct-js2-catch-node
4624 cl-struct-js2-do-node
4625 cl-struct-js2-elem-get-node
4626 cl-struct-js2-for-in-node
4627 cl-struct-js2-for-node
4628 cl-struct-js2-function-node
4629 cl-struct-js2-if-node
4630 cl-struct-js2-let-node
4631 cl-struct-js2-new-node
4632 cl-struct-js2-paren-node
4633 cl-struct-js2-switch-node
4634 cl-struct-js2-while-node
4635 cl-struct-js2-with-node
4636 cl-struct-js2-xml-dot-query-node)
4637 "Node types that can have a parenthesized child expression.
4638 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4639
4640 (defsubst js2-paren-expr-node-p (node)
4641 "Return t for nodes that typically have a parenthesized child expression.
4642 Useful for computing the indentation anchors for arg-lists and conditions.
4643 Note that it may return a false positive, for instance when NODE is
4644 a `js2-new-node' and there are no arguments or parentheses."
4645 (memq (aref node 0) js2-paren-expr-nodes))
4646
4647 ;; Fake polymorphism... yech.
4648 (defun js2-node-lp (node)
4649 "Return relative left-paren position for NODE, if applicable.
4650 For `js2-elem-get-node' structs, returns left-bracket position.
4651 Note that the position may be nil in the case of a parse error."
4652 (cond
4653 ((js2-elem-get-node-p node)
4654 (js2-elem-get-node-lb node))
4655 ((js2-loop-node-p node)
4656 (js2-loop-node-lp node))
4657 ((js2-function-node-p node)
4658 (js2-function-node-lp node))
4659 ((js2-if-node-p node)
4660 (js2-if-node-lp node))
4661 ((js2-new-node-p node)
4662 (js2-new-node-lp node))
4663 ((js2-call-node-p node)
4664 (js2-call-node-lp node))
4665 ((js2-paren-node-p node)
4666 0)
4667 ((js2-switch-node-p node)
4668 (js2-switch-node-lp node))
4669 ((js2-catch-node-p node)
4670 (js2-catch-node-lp node))
4671 ((js2-let-node-p node)
4672 (js2-let-node-lp node))
4673 ((js2-comp-node-p node)
4674 0)
4675 ((js2-with-node-p node)
4676 (js2-with-node-lp node))
4677 ((js2-xml-dot-query-node-p node)
4678 (1+ (js2-infix-node-op-pos node)))
4679 (t
4680 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4681
4682 ;; Fake polymorphism... blech.
4683 (defun js2-node-rp (node)
4684 "Return relative right-paren position for NODE, if applicable.
4685 For `js2-elem-get-node' structs, returns right-bracket position.
4686 Note that the position may be nil in the case of a parse error."
4687 (cond
4688 ((js2-elem-get-node-p node)
4689 (js2-elem-get-node-rb node))
4690 ((js2-loop-node-p node)
4691 (js2-loop-node-rp node))
4692 ((js2-function-node-p node)
4693 (js2-function-node-rp node))
4694 ((js2-if-node-p node)
4695 (js2-if-node-rp node))
4696 ((js2-new-node-p node)
4697 (js2-new-node-rp node))
4698 ((js2-call-node-p node)
4699 (js2-call-node-rp node))
4700 ((js2-paren-node-p node)
4701 (1- (js2-node-len node)))
4702 ((js2-switch-node-p node)
4703 (js2-switch-node-rp node))
4704 ((js2-catch-node-p node)
4705 (js2-catch-node-rp node))
4706 ((js2-let-node-p node)
4707 (js2-let-node-rp node))
4708 ((js2-comp-node-p node)
4709 (1- (js2-node-len node)))
4710 ((js2-with-node-p node)
4711 (js2-with-node-rp node))
4712 ((js2-xml-dot-query-node-p node)
4713 (1+ (js2-xml-dot-query-node-rp node)))
4714 (t
4715 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4716
4717 (defsubst js2-node-first-child (node)
4718 "Return the first element of `js2-node-child-list' for NODE."
4719 (car (js2-node-child-list node)))
4720
4721 (defsubst js2-node-last-child (node)
4722 "Return the last element of `js2-node-last-child' for NODE."
4723 (car (last (js2-node-child-list node))))
4724
4725 (defun js2-node-prev-sibling (node)
4726 "Return the previous statement in parent.
4727 Works for parents supported by `js2-node-child-list'.
4728 Returns nil if NODE is not in the parent, or PARENT is
4729 not a supported node, or if NODE is the first child."
4730 (let* ((p (js2-node-parent node))
4731 (kids (js2-node-child-list p))
4732 (sib (car kids)))
4733 (while (and kids
4734 (not (eq node (cadr kids))))
4735 (setq kids (cdr kids)
4736 sib (car kids)))
4737 sib))
4738
4739 (defun js2-node-next-sibling (node)
4740 "Return the next statement in parent block.
4741 Returns nil if NODE is not in the block, or PARENT is not
4742 a block node, or if NODE is the last statement."
4743 (let* ((p (js2-node-parent node))
4744 (kids (js2-node-child-list p)))
4745 (while (and kids
4746 (not (eq node (car kids))))
4747 (setq kids (cdr kids)))
4748 (cadr kids)))
4749
4750 (defun js2-node-find-child-before (pos parent &optional after)
4751 "Find the last child that starts before POS in parent.
4752 If AFTER is non-nil, returns first child starting after POS.
4753 POS is an absolute buffer position. PARENT is any node
4754 supported by `js2-node-child-list'.
4755 Returns nil if no applicable child is found."
4756 (let ((kids (if (js2-function-node-p parent)
4757 (js2-block-node-kids (js2-function-node-body parent))
4758 (js2-node-child-list parent)))
4759 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4760 (js2-function-node-body parent)
4761 parent)))
4762 kid result fn
4763 (continue t))
4764 (setq fn (if after '>= '<))
4765 (while (and kids continue)
4766 (setq kid (car kids))
4767 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4768 (setq result kid
4769 continue (not after))
4770 (setq continue after))
4771 (setq kids (cdr kids)))
4772 result))
4773
4774 (defun js2-node-find-child-after (pos parent)
4775 "Find first child that starts after POS in parent.
4776 POS is an absolute buffer position. PARENT is any node
4777 supported by `js2-node-child-list'.
4778 Returns nil if no applicable child is found."
4779 (js2-node-find-child-before pos parent 'after))
4780
4781 (defun js2-node-replace-child (pos parent new-node)
4782 "Replace node at index POS in PARENT with NEW-NODE.
4783 Only works for parents supported by `js2-node-child-list'."
4784 (let ((kids (js2-node-child-list parent))
4785 (i 0))
4786 (while (< i pos)
4787 (setq kids (cdr kids)
4788 i (1+ i)))
4789 (setcar kids new-node)
4790 (js2-node-add-children parent new-node)))
4791
4792 (defun js2-node-buffer (n)
4793 "Return the buffer associated with AST N.
4794 Returns nil if the buffer is not set as a property on the root
4795 node, or if parent links were not recorded during parsing."
4796 (let ((root (js2-node-root n)))
4797 (and root
4798 (js2-ast-root-p root)
4799 (js2-ast-root-buffer root))))
4800
4801 (defun js2-block-node-push (n kid)
4802 "Push js2-node KID onto the end of js2-block-node N's child list.
4803 KID is always added to the -end- of the kids list.
4804 Function also calls `js2-node-add-children' to add the parent link."
4805 (let ((kids (js2-node-child-list n)))
4806 (if kids
4807 (setcdr kids (nconc (cdr kids) (list kid)))
4808 (js2-node-set-child-list n (list kid)))
4809 (js2-node-add-children n kid)))
4810
4811 (defun js2-node-string (node)
4812 (with-current-buffer (or (js2-node-buffer node)
4813 (error "No buffer available for node %s" node))
4814 (let ((pos (js2-node-abs-pos node)))
4815 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4816
4817 ;; Container for storing the node we're looking for in a traversal.
4818 (js2-deflocal js2-discovered-node nil)
4819
4820 ;; Keep track of absolute node position during traversals.
4821 (js2-deflocal js2-visitor-offset nil)
4822
4823 (js2-deflocal js2-node-search-point nil)
4824
4825 (when js2-mode-dev-mode-p
4826 (defun js2-find-node-at-point ()
4827 (interactive)
4828 (let ((node (js2-node-at-point)))
4829 (message "%s" (or node "No node found at point"))))
4830 (defun js2-node-name-at-point ()
4831 (interactive)
4832 (let ((node (js2-node-at-point)))
4833 (message "%s" (if node
4834 (js2-node-short-name node)
4835 "No node found at point.")))))
4836
4837 (defun js2-node-at-point (&optional pos skip-comments)
4838 "Return AST node at POS, a buffer position, defaulting to current point.
4839 The `js2-mode-ast' variable must be set to the current parse tree.
4840 Signals an error if the AST (`js2-mode-ast') is nil.
4841 Always returns a node - if it can't find one, it returns the root.
4842 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4843 (let ((ast js2-mode-ast)
4844 result)
4845 (unless ast
4846 (error "No JavaScript AST available"))
4847 ;; Look through comments first, since they may be inside nodes that
4848 ;; would otherwise report a match.
4849 (setq pos (or pos (point))
4850 result (if (> pos (js2-node-abs-end ast))
4851 ast
4852 (if (not skip-comments)
4853 (js2-comment-at-point pos))))
4854 (unless result
4855 (setq js2-discovered-node nil
4856 js2-visitor-offset 0
4857 js2-node-search-point pos)
4858 (unwind-protect
4859 (catch 'js2-visit-done
4860 (js2-visit-ast ast #'js2-node-at-point-visitor))
4861 (setq js2-visitor-offset nil
4862 js2-node-search-point nil))
4863 (setq result js2-discovered-node))
4864 ;; may have found a comment beyond end of last child node,
4865 ;; since visiting the ast-root looks at the comment-list last.
4866 (if (and skip-comments
4867 (js2-comment-node-p result))
4868 (setq result nil))
4869 (or result js2-mode-ast)))
4870
4871 (defun js2-node-at-point-visitor (node end-p)
4872 (let ((rel-pos (js2-node-pos node))
4873 abs-pos
4874 abs-end
4875 (point js2-node-search-point))
4876 (cond
4877 (end-p
4878 ;; this evaluates to a non-nil return value, even if it's zero
4879 (cl-decf js2-visitor-offset rel-pos))
4880 ;; we already looked for comments before visiting, and don't want them now
4881 ((js2-comment-node-p node)
4882 nil)
4883 (t
4884 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4885 ;; we only want to use the node if the point is before
4886 ;; the last character position in the node, so we decrement
4887 ;; the absolute end by 1.
4888 abs-end (+ abs-pos (js2-node-len node) -1))
4889 (cond
4890 ;; If this node starts after search-point, stop the search.
4891 ((> abs-pos point)
4892 (throw 'js2-visit-done nil))
4893 ;; If this node ends before the search-point, don't check kids.
4894 ((> point abs-end)
4895 nil)
4896 (t
4897 ;; Otherwise point is within this node, possibly in a child.
4898 (setq js2-discovered-node node)
4899 t)))))) ; keep processing kids to look for more specific match
4900
4901 (defsubst js2-block-comment-p (node)
4902 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4903 (and (js2-comment-node-p node)
4904 (memq (js2-comment-node-format node) '(jsdoc block))))
4905
4906 ;; TODO: put the comments in a vector and binary-search them instead
4907 (defun js2-comment-at-point (&optional pos)
4908 "Look through scanned comment nodes for one containing POS.
4909 POS is a buffer position that defaults to current point.
4910 Function returns nil if POS was not in any comment node."
4911 (let ((ast js2-mode-ast)
4912 (x (or pos (point)))
4913 beg end)
4914 (unless ast
4915 (error "No JavaScript AST available"))
4916 (catch 'done
4917 ;; Comments are stored in lexical order.
4918 (dolist (comment (js2-ast-root-comments ast) nil)
4919 (setq beg (js2-node-abs-pos comment)
4920 end (+ beg (js2-node-len comment)))
4921 (if (and (>= x beg)
4922 (<= x end))
4923 (throw 'done comment))))))
4924
4925 (defun js2-mode-find-parent-fn (node)
4926 "Find function enclosing NODE.
4927 Returns nil if NODE is not inside a function."
4928 (setq node (js2-node-parent node))
4929 (while (and node (not (js2-function-node-p node)))
4930 (setq node (js2-node-parent node)))
4931 (and (js2-function-node-p node) node))
4932
4933 (defun js2-mode-find-enclosing-fn (node)
4934 "Find function or root enclosing NODE."
4935 (if (js2-ast-root-p node)
4936 node
4937 (setq node (js2-node-parent node))
4938 (while (not (or (js2-ast-root-p node)
4939 (js2-function-node-p node)))
4940 (setq node (js2-node-parent node)))
4941 node))
4942
4943 (defun js2-mode-find-enclosing-node (beg end)
4944 "Find node fully enclosing BEG and END."
4945 (let ((node (js2-node-at-point beg))
4946 pos
4947 (continue t))
4948 (while continue
4949 (if (or (js2-ast-root-p node)
4950 (and
4951 (<= (setq pos (js2-node-abs-pos node)) beg)
4952 (>= (+ pos (js2-node-len node)) end)))
4953 (setq continue nil)
4954 (setq node (js2-node-parent node))))
4955 node))
4956
4957 (defun js2-node-parent-script-or-fn (node)
4958 "Find script or function immediately enclosing NODE.
4959 If NODE is the ast-root, returns nil."
4960 (if (js2-ast-root-p node)
4961 nil
4962 (setq node (js2-node-parent node))
4963 (while (and node (not (or (js2-function-node-p node)
4964 (js2-script-node-p node))))
4965 (setq node (js2-node-parent node)))
4966 node))
4967
4968 (defun js2-node-is-descendant (node ancestor)
4969 "Return t if NODE is a descendant of ANCESTOR."
4970 (while (and node
4971 (not (eq node ancestor)))
4972 (setq node (js2-node-parent node)))
4973 node)
4974
4975 ;;; visitor infrastructure
4976
4977 (defun js2-visit-none (_node _callback)
4978 "Visitor for AST node that have no node children."
4979 nil)
4980
4981 (defun js2-print-none (_node _indent)
4982 "Visitor for AST node with no printed representation.")
4983
4984 (defun js2-print-body (node indent)
4985 "Print a statement, or a block without braces."
4986 (if (js2-block-node-p node)
4987 (dolist (kid (js2-block-node-kids node))
4988 (js2-print-ast kid indent))
4989 (js2-print-ast node indent)))
4990
4991 (defun js2-print-list (args &optional delimiter)
4992 (cl-loop with len = (length args)
4993 for arg in args
4994 for count from 1
4995 do
4996 (when arg (js2-print-ast arg 0))
4997 (if (< count len)
4998 (insert (or delimiter ", ")))))
4999
5000 (defun js2-print-tree (ast)
5001 "Prints an AST to the current buffer.
5002 Makes `js2-ast-parent-nodes' available to the printer functions."
5003 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5004 (js2-print-ast ast)))
5005
5006 (defun js2-print-ast (node &optional indent)
5007 "Helper function for printing AST nodes.
5008 Requires `js2-ast-parent-nodes' to be non-nil.
5009 You should use `js2-print-tree' instead of this function."
5010 (let ((printer (get (aref node 0) 'js2-printer))
5011 (i (or indent 0)))
5012 ;; TODO: wedge comments in here somewhere
5013 (if printer
5014 (funcall printer node i))))
5015
5016 (defconst js2-side-effecting-tokens
5017 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5018 (dolist (tt (list js2-ASSIGN
5019 js2-ASSIGN_ADD
5020 js2-ASSIGN_BITAND
5021 js2-ASSIGN_BITOR
5022 js2-ASSIGN_BITXOR
5023 js2-ASSIGN_DIV
5024 js2-ASSIGN_LSH
5025 js2-ASSIGN_MOD
5026 js2-ASSIGN_MUL
5027 js2-ASSIGN_RSH
5028 js2-ASSIGN_SUB
5029 js2-ASSIGN_URSH
5030 js2-BLOCK
5031 js2-BREAK
5032 js2-CALL
5033 js2-CATCH
5034 js2-CATCH_SCOPE
5035 js2-CLASS
5036 js2-CONST
5037 js2-CONTINUE
5038 js2-DEBUGGER
5039 js2-DEC
5040 js2-DELPROP
5041 js2-DEL_REF
5042 js2-DO
5043 js2-ELSE
5044 js2-EMPTY
5045 js2-ENTERWITH
5046 js2-EXPORT
5047 js2-EXPR_RESULT
5048 js2-FINALLY
5049 js2-FOR
5050 js2-FUNCTION
5051 js2-GOTO
5052 js2-IF
5053 js2-IFEQ
5054 js2-IFNE
5055 js2-IMPORT
5056 js2-INC
5057 js2-JSR
5058 js2-LABEL
5059 js2-LEAVEWITH
5060 js2-LET
5061 js2-LETEXPR
5062 js2-LOCAL_BLOCK
5063 js2-LOOP
5064 js2-NEW
5065 js2-REF_CALL
5066 js2-RETHROW
5067 js2-RETURN
5068 js2-RETURN_RESULT
5069 js2-SEMI
5070 js2-SETELEM
5071 js2-SETELEM_OP
5072 js2-SETNAME
5073 js2-SETPROP
5074 js2-SETPROP_OP
5075 js2-SETVAR
5076 js2-SET_REF
5077 js2-SET_REF_OP
5078 js2-SWITCH
5079 js2-TARGET
5080 js2-THROW
5081 js2-TRY
5082 js2-VAR
5083 js2-WHILE
5084 js2-WITH
5085 js2-WITHEXPR
5086 js2-YIELD))
5087 (aset tokens tt t))
5088 (if js2-instanceof-has-side-effects
5089 (aset tokens js2-INSTANCEOF t))
5090 tokens))
5091
5092 (defun js2-node-has-side-effects (node)
5093 "Return t if NODE has side effects."
5094 (when node ; makes it easier to handle malformed expressions
5095 (let ((tt (js2-node-type node)))
5096 (cond
5097 ;; This doubtless needs some work, since EXPR_VOID is used
5098 ;; in several ways in Rhino and I may not have caught them all.
5099 ;; I'll wait for people to notice incorrect warnings.
5100 ((and (= tt js2-EXPR_VOID)
5101 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5102 (let ((expr (js2-expr-stmt-node-expr node)))
5103 (or (js2-node-has-side-effects expr)
5104 (when (js2-string-node-p expr)
5105 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5106 ((= tt js2-COMMA)
5107 (js2-node-has-side-effects (js2-infix-node-right node)))
5108 ((or (= tt js2-AND)
5109 (= tt js2-OR))
5110 (or (js2-node-has-side-effects (js2-infix-node-right node))
5111 (js2-node-has-side-effects (js2-infix-node-left node))))
5112 ((= tt js2-HOOK)
5113 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5114 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5115 ((js2-paren-node-p node)
5116 (js2-node-has-side-effects (js2-paren-node-expr node)))
5117 ((= tt js2-ERROR) ; avoid cascaded error messages
5118 nil)
5119 (t
5120 (aref js2-side-effecting-tokens tt))))))
5121
5122 (defconst js2-stmt-node-types
5123 (list js2-BLOCK
5124 js2-BREAK
5125 js2-CONTINUE
5126 js2-DEFAULT ; e4x "default xml namespace" statement
5127 js2-DO
5128 js2-EXPORT
5129 js2-EXPR_RESULT
5130 js2-EXPR_VOID
5131 js2-FOR
5132 js2-IF
5133 js2-IMPORT
5134 js2-RETURN
5135 js2-SWITCH
5136 js2-THROW
5137 js2-TRY
5138 js2-WHILE
5139 js2-WITH)
5140 "Node types that only appear in statement contexts.
5141 The list does not include nodes that always appear as the child
5142 of another specific statement type, such as switch-cases,
5143 catch and finally blocks, and else-clauses. The list also excludes
5144 nodes like yield, let and var, which may appear in either expression
5145 or statement context, and in the latter context always have a
5146 `js2-expr-stmt-node' parent. Finally, the list does not include
5147 functions or scripts, which are treated separately from statements
5148 by the JavaScript parser and runtime.")
5149
5150 (defun js2-stmt-node-p (node)
5151 "Heuristic for figuring out if NODE is a statement.
5152 Some node types can appear in either an expression context or a
5153 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5154 For these node types in a statement context, the parent will be a
5155 `js2-expr-stmt-node'.
5156 Functions aren't included in the check."
5157 (memq (js2-node-type node) js2-stmt-node-types))
5158
5159 (defun js2-mode-find-first-stmt (node)
5160 "Search upward starting from NODE looking for a statement.
5161 For purposes of this function, a `js2-function-node' counts."
5162 (while (not (or (js2-stmt-node-p node)
5163 (js2-function-node-p node)))
5164 (setq node (js2-node-parent node)))
5165 node)
5166
5167 (defun js2-node-parent-stmt (node)
5168 "Return the node's first ancestor that is a statement.
5169 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5170 appearing in a statement context will have a parent that is a
5171 `js2-expr-stmt-node' that will be returned by this function."
5172 (let ((parent (js2-node-parent node)))
5173 (if (or (null parent)
5174 (js2-stmt-node-p parent)
5175 (and (js2-function-node-p parent)
5176 (not (eq (js2-function-node-form parent)
5177 'FUNCTION_EXPRESSION))))
5178 parent
5179 (js2-node-parent-stmt parent))))
5180
5181 ;; In the Mozilla Rhino sources, Roshan James writes:
5182 ;; Does consistent-return analysis on the function body when strict mode is
5183 ;; enabled.
5184 ;;
5185 ;; function (x) { return (x+1) }
5186 ;;
5187 ;; is ok, but
5188 ;;
5189 ;; function (x) { if (x < 0) return (x+1); }
5190 ;;
5191 ;; is not because the function can potentially return a value when the
5192 ;; condition is satisfied and if not, the function does not explicitly
5193 ;; return a value.
5194 ;;
5195 ;; This extends to checking mismatches such as "return" and "return <value>"
5196 ;; used in the same function. Warnings are not emitted if inconsistent
5197 ;; returns exist in code that can be statically shown to be unreachable.
5198 ;; Ex.
5199 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5200 ;;
5201 ;; emits no warning. However if the loop had a break statement, then a
5202 ;; warning would be emitted.
5203 ;;
5204 ;; The consistency analysis looks at control structures such as loops, ifs,
5205 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5206 ;; warns the user about an inconsistent set of termination possibilities.
5207 ;;
5208 ;; These flags enumerate the possible ways a statement/function can
5209 ;; terminate. These flags are used by endCheck() and by the Parser to
5210 ;; detect inconsistent return usage.
5211 ;;
5212 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5213 ;; able to execute (example: throw, continue)
5214 ;;
5215 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5216 ;; next one. Statement such as return dont. A compound statement may have
5217 ;; some branch that drops off control to the next statement.
5218 ;;
5219 ;; END_RETURNS indicates that the statement can return with no value.
5220 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5221 ;;
5222 ;; A compound statement such as
5223 ;; if (condition) {
5224 ;; return value;
5225 ;; }
5226 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5227
5228 (defconst js2-END_UNREACHED 0)
5229 (defconst js2-END_DROPS_OFF 1)
5230 (defconst js2-END_RETURNS 2)
5231 (defconst js2-END_RETURNS_VALUE 4)
5232 (defconst js2-END_YIELDS 8)
5233
5234 (defun js2-has-consistent-return-usage (node)
5235 "Check that every return usage in a function body is consistent.
5236 Returns t if the function satisfies strict mode requirement."
5237 (let ((n (js2-end-check node)))
5238 ;; either it doesn't return a value in any branch...
5239 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5240 ;; or it returns a value (or is unreached) at every branch
5241 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5242 js2-END_RETURNS
5243 js2-END_YIELDS)))))
5244
5245 (defun js2-end-check-if (node)
5246 "Ensure that return usage in then/else blocks is consistent.
5247 If there is no else block, then the return statement can fall through.
5248 Returns logical OR of END_* flags"
5249 (let ((th (js2-if-node-then-part node))
5250 (el (js2-if-node-else-part node)))
5251 (if (null th)
5252 js2-END_UNREACHED
5253 (logior (js2-end-check th) (if el
5254 (js2-end-check el)
5255 js2-END_DROPS_OFF)))))
5256
5257 (defun js2-end-check-switch (node)
5258 "Consistency of return statements is checked between the case statements.
5259 If there is no default, then the switch can fall through. If there is a
5260 default, we check to see if all code paths in the default return or if
5261 there is a code path that can fall through.
5262 Returns logical OR of END_* flags."
5263 (let ((rv js2-END_UNREACHED)
5264 default-case)
5265 ;; examine the cases
5266 (catch 'break
5267 (dolist (c (js2-switch-node-cases node))
5268 (if (js2-case-node-expr c)
5269 (js2-set-flag rv (js2-end-check-block c))
5270 (setq default-case c)
5271 (throw 'break nil))))
5272 ;; we don't care how the cases drop into each other
5273 (js2-clear-flag rv js2-END_DROPS_OFF)
5274 ;; examine the default
5275 (js2-set-flag rv (if default-case
5276 (js2-end-check default-case)
5277 js2-END_DROPS_OFF))
5278 rv))
5279
5280 (defun js2-end-check-try (node)
5281 "If the block has a finally, return consistency is checked in the
5282 finally block. If all code paths in the finally return, then the
5283 returns in the try-catch blocks don't matter. If there is a code path
5284 that does not return or if there is no finally block, the returns
5285 of the try and catch blocks are checked for mismatch.
5286 Returns logical OR of END_* flags."
5287 (let ((finally (js2-try-node-finally-block node))
5288 rv)
5289 ;; check the finally if it exists
5290 (setq rv (if finally
5291 (js2-end-check (js2-finally-node-body finally))
5292 js2-END_DROPS_OFF))
5293 ;; If the finally block always returns, then none of the returns
5294 ;; in the try or catch blocks matter.
5295 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5296 (js2-clear-flag rv js2-END_DROPS_OFF)
5297 ;; examine the try block
5298 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5299 ;; check each catch block
5300 (dolist (cb (js2-try-node-catch-clauses node))
5301 (js2-set-flag rv (js2-end-check cb))))
5302 rv))
5303
5304 (defun js2-end-check-loop (node)
5305 "Return statement in the loop body must be consistent.
5306 The default assumption for any kind of a loop is that it will eventually
5307 terminate. The only exception is a loop with a constant true condition.
5308 Code that follows such a loop is examined only if one can determine
5309 statically that there is a break out of the loop.
5310
5311 for(... ; ... ; ...) {}
5312 for(... in ... ) {}
5313 while(...) { }
5314 do { } while(...)
5315
5316 Returns logical OR of END_* flags."
5317 (let ((rv (js2-end-check (js2-loop-node-body node)))
5318 (condition (cond
5319 ((js2-while-node-p node)
5320 (js2-while-node-condition node))
5321 ((js2-do-node-p node)
5322 (js2-do-node-condition node))
5323 ((js2-for-node-p node)
5324 (js2-for-node-condition node)))))
5325
5326 ;; check to see if the loop condition is always true
5327 (if (and condition
5328 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5329 (js2-clear-flag rv js2-END_DROPS_OFF))
5330
5331 ;; look for effect of breaks
5332 (js2-set-flag rv (js2-node-get-prop node
5333 'CONTROL_BLOCK_PROP
5334 js2-END_UNREACHED))
5335 rv))
5336
5337 (defun js2-end-check-block (node)
5338 "A general block of code is examined statement by statement.
5339 If any statement (even a compound one) returns in all branches, then
5340 subsequent statements are not examined.
5341 Returns logical OR of END_* flags."
5342 (let* ((rv js2-END_DROPS_OFF)
5343 (kids (js2-block-node-kids node))
5344 (n (car kids)))
5345 ;; Check each statement. If the statement can continue onto the next
5346 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5347 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5348 (js2-clear-flag rv js2-END_DROPS_OFF)
5349 (js2-set-flag rv (js2-end-check n))
5350 (setq kids (cdr kids)
5351 n (car kids)))
5352 rv))
5353
5354 (defun js2-end-check-label (node)
5355 "A labeled statement implies that there may be a break to the label.
5356 The function processes the labeled statement and then checks the
5357 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5358 particular label.
5359 Returns logical OR of END_* flags."
5360 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5361 (logior rv (js2-node-get-prop node
5362 'CONTROL_BLOCK_PROP
5363 js2-END_UNREACHED))))
5364
5365 (defun js2-end-check-break (node)
5366 "When a break is encountered annotate the statement being broken
5367 out of by setting its CONTROL_BLOCK_PROP property.
5368 Returns logical OR of END_* flags."
5369 (and (js2-break-node-target node)
5370 (js2-node-set-prop (js2-break-node-target node)
5371 'CONTROL_BLOCK_PROP
5372 js2-END_DROPS_OFF))
5373 js2-END_UNREACHED)
5374
5375 (defun js2-end-check (node)
5376 "Examine the body of a function, doing a basic reachability analysis.
5377 Returns a combination of flags END_* flags that indicate
5378 how the function execution can terminate. These constitute only the
5379 pessimistic set of termination conditions. It is possible that at
5380 runtime certain code paths will never be actually taken. Hence this
5381 analysis will flag errors in cases where there may not be errors.
5382 Returns logical OR of END_* flags"
5383 (let (kid)
5384 (cond
5385 ((js2-break-node-p node)
5386 (js2-end-check-break node))
5387 ((js2-expr-stmt-node-p node)
5388 (if (setq kid (js2-expr-stmt-node-expr node))
5389 (js2-end-check kid)
5390 js2-END_DROPS_OFF))
5391 ((or (js2-continue-node-p node)
5392 (js2-throw-node-p node))
5393 js2-END_UNREACHED)
5394 ((js2-return-node-p node)
5395 (if (setq kid (js2-return-node-retval node))
5396 js2-END_RETURNS_VALUE
5397 js2-END_RETURNS))
5398 ((js2-loop-node-p node)
5399 (js2-end-check-loop node))
5400 ((js2-switch-node-p node)
5401 (js2-end-check-switch node))
5402 ((js2-labeled-stmt-node-p node)
5403 (js2-end-check-label node))
5404 ((js2-if-node-p node)
5405 (js2-end-check-if node))
5406 ((js2-try-node-p node)
5407 (js2-end-check-try node))
5408 ((js2-block-node-p node)
5409 (if (null (js2-block-node-kids node))
5410 js2-END_DROPS_OFF
5411 (js2-end-check-block node)))
5412 ((js2-yield-node-p node)
5413 js2-END_YIELDS)
5414 (t
5415 js2-END_DROPS_OFF))))
5416
5417 (defun js2-always-defined-boolean-p (node)
5418 "Check if NODE always evaluates to true or false in boolean context.
5419 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5420 nor always false."
5421 (let ((tt (js2-node-type node))
5422 num)
5423 (cond
5424 ((or (= tt js2-FALSE) (= tt js2-NULL))
5425 'ALWAYS_FALSE)
5426 ((= tt js2-TRUE)
5427 'ALWAYS_TRUE)
5428 ((= tt js2-NUMBER)
5429 (setq num (js2-number-node-num-value node))
5430 (if (and (not (eq num 0.0e+NaN))
5431 (not (zerop num)))
5432 'ALWAYS_TRUE
5433 'ALWAYS_FALSE))
5434 (t
5435 nil))))
5436
5437 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5438 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5439
5440 (defvar js2-tokens nil
5441 "List of all defined token names.") ; initialized in `js2-token-names'
5442
5443 (defconst js2-token-names
5444 (let* ((names (make-vector js2-num-tokens -1))
5445 (case-fold-search nil) ; only match js2-UPPER_CASE
5446 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5447 (cl-loop for sym in syms
5448 for i from 0
5449 do
5450 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5451 (not (boundp sym)))
5452 (aset names (symbol-value sym) ; code, e.g. 152
5453 (downcase
5454 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5455 (push sym js2-tokens)))
5456 names)
5457 "Vector mapping int values to token string names, sans `js2-' prefix.")
5458
5459 (defun js2-tt-name (tok)
5460 "Return a string name for TOK, a token symbol or code.
5461 Signals an error if it's not a recognized token."
5462 (let ((code tok))
5463 (if (symbolp tok)
5464 (setq code (symbol-value tok)))
5465 (if (eq code -1)
5466 "ERROR"
5467 (if (and (numberp code)
5468 (not (cl-minusp code))
5469 (< code js2-num-tokens))
5470 (aref js2-token-names code)
5471 (error "Invalid token: %s" code)))))
5472
5473 (defsubst js2-tt-sym (tok)
5474 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5475 (intern (js2-tt-name tok)))
5476
5477 (defconst js2-token-codes
5478 (let ((table (make-hash-table :test 'eq :size 256)))
5479 (cl-loop for name across js2-token-names
5480 for sym = (intern (concat "js2-" (upcase name)))
5481 do
5482 (puthash sym (symbol-value sym) table))
5483 ;; clean up a few that are "wrong" in Rhino's token codes
5484 (puthash 'js2-DELETE js2-DELPROP table)
5485 table)
5486 "Hashtable mapping token type symbols to their bytecodes.")
5487
5488 (defsubst js2-tt-code (sym)
5489 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5490 (or (gethash sym js2-token-codes)
5491 (error "Invalid token symbol: %s " sym))) ; signal code bug
5492
5493 (defun js2-report-scan-error (msg &optional no-throw beg len)
5494 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5495 (js2-report-error msg nil
5496 (or beg (js2-current-token-beg))
5497 (or len (js2-current-token-len)))
5498 (unless no-throw
5499 (throw 'return js2-ERROR)))
5500
5501 (defun js2-set-string-from-buffer (token)
5502 "Set `string' and `end' slots for TOKEN, return the string."
5503 (setf (js2-token-end token) js2-ts-cursor
5504 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5505
5506 ;; TODO: could potentially avoid a lot of consing by allocating a
5507 ;; char buffer the way Rhino does.
5508 (defsubst js2-add-to-string (c)
5509 (push c js2-ts-string-buffer))
5510
5511 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5512 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5513 ;; any other character: when it's not part of the current token, we
5514 ;; unget it, allowing it to be read again by the following call.
5515 (defsubst js2-unget-char ()
5516 (cl-decf js2-ts-cursor))
5517
5518 ;; Rhino distinguishes \r and \n line endings. We don't need to
5519 ;; because we only scan from Emacs buffers, which always use \n.
5520 (defun js2-get-char ()
5521 "Read and return the next character from the input buffer.
5522 Increments `js2-ts-lineno' if the return value is a newline char.
5523 Updates `js2-ts-cursor' to the point after the returned char.
5524 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5525 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5526 (let (c)
5527 ;; check for end of buffer
5528 (if (>= js2-ts-cursor (point-max))
5529 (setq js2-ts-hit-eof t
5530 js2-ts-cursor (1+ js2-ts-cursor)
5531 c js2-EOF_CHAR) ; return value
5532 ;; otherwise read next char
5533 (setq c (char-before (cl-incf js2-ts-cursor)))
5534 ;; if we read a newline, update counters
5535 (if (= c ?\n)
5536 (setq js2-ts-line-start js2-ts-cursor
5537 js2-ts-lineno (1+ js2-ts-lineno)))
5538 ;; TODO: skip over format characters
5539 c)))
5540
5541 (defun js2-read-unicode-escape ()
5542 "Read a \\uNNNN sequence from the input.
5543 Assumes the ?\ and ?u have already been read.
5544 Returns the unicode character, or nil if it wasn't a valid character.
5545 Doesn't change the values of any scanner variables."
5546 ;; I really wish I knew a better way to do this, but I can't
5547 ;; find the Emacs function that takes a 16-bit int and converts
5548 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5549 ;; Have to first check that it's 4 hex characters or it may stop
5550 ;; the read early.
5551 (ignore-errors
5552 (let ((s (buffer-substring-no-properties js2-ts-cursor
5553 (+ 4 js2-ts-cursor))))
5554 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5555 (read (concat "?\\u" s))))))
5556
5557 (defun js2-match-char (test)
5558 "Consume and return next character if it matches TEST, a character.
5559 Returns nil and consumes nothing if TEST is not the next character."
5560 (let ((c (js2-get-char)))
5561 (if (eq c test)
5562 t
5563 (js2-unget-char)
5564 nil)))
5565
5566 (defun js2-peek-char ()
5567 (prog1
5568 (js2-get-char)
5569 (js2-unget-char)))
5570
5571 (defun js2-identifier-start-p (c)
5572 "Is C a valid start to an ES5 Identifier?
5573 See http://es5.github.io/#x7.6"
5574 (or
5575 (memq c '(?$ ?_))
5576 (memq (get-char-code-property c 'general-category)
5577 ;; Letters
5578 '(Lu Ll Lt Lm Lo Nl))))
5579
5580 (defun js2-identifier-part-p (c)
5581 "Is C a valid part of an ES5 Identifier?
5582 See http://es5.github.io/#x7.6"
5583 (or
5584 (memq c '(?$ ?_ ?\u200c ?\u200d))
5585 (memq (get-char-code-property c 'general-category)
5586 '(;; Letters
5587 Lu Ll Lt Lm Lo Nl
5588 ;; Combining Marks
5589 Mn Mc
5590 ;; Digits
5591 Nd
5592 ;; Connector Punctuation
5593 Pc))))
5594
5595 (defun js2-alpha-p (c)
5596 (cond ((and (<= ?A c) (<= c ?Z)) t)
5597 ((and (<= ?a c) (<= c ?z)) t)
5598 (t nil)))
5599
5600 (defsubst js2-digit-p (c)
5601 (and (<= ?0 c) (<= c ?9)))
5602
5603 (defun js2-js-space-p (c)
5604 (if (<= c 127)
5605 (memq c '(#x20 #x9 #xB #xC #xD))
5606 (or
5607 (eq c #xA0)
5608 ;; TODO: change this nil to check for Unicode space character
5609 nil)))
5610
5611 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5612
5613 (defun js2-skip-line ()
5614 "Skip to end of line."
5615 (while (not (memq (js2-get-char) js2-eol-chars)))
5616 (js2-unget-char)
5617 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5618
5619 (defun js2-init-scanner (&optional buf line)
5620 "Create token stream for BUF starting on LINE.
5621 BUF defaults to `current-buffer' and LINE defaults to 1.
5622
5623 A buffer can only have one scanner active at a time, which yields
5624 dramatically simpler code than using a defstruct. If you need to
5625 have simultaneous scanners in a buffer, copy the regions to scan
5626 into temp buffers."
5627 (with-current-buffer (or buf (current-buffer))
5628 (setq js2-ts-dirty-line nil
5629 js2-ts-hit-eof nil
5630 js2-ts-line-start 0
5631 js2-ts-lineno (or line 1)
5632 js2-ts-line-end-char -1
5633 js2-ts-cursor (point-min)
5634 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5635 js2-ti-tokens-cursor 0
5636 js2-ti-lookahead 0
5637 js2-ts-is-xml-attribute nil
5638 js2-ts-xml-is-tag-content nil
5639 js2-ts-xml-open-tags-count 0
5640 js2-ts-string-buffer nil)))
5641
5642 ;; This function uses the cached op, string and number fields in
5643 ;; TokenStream; if getToken has been called since the passed token
5644 ;; was scanned, the op or string printed may be incorrect.
5645 (defun js2-token-to-string (token)
5646 ;; Not sure where this function is used in Rhino. Not tested.
5647 (if (not js2-debug-print-trees)
5648 ""
5649 (let ((name (js2-tt-name token)))
5650 (cond
5651 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5652 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5653 (concat name " `" (js2-current-token-string) "'"))
5654 ((eq token js2-NUMBER)
5655 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5656 (t
5657 name)))))
5658
5659 (defconst js2-keywords
5660 '(break
5661 case catch class const continue
5662 debugger default delete do
5663 else extends export
5664 false finally for function
5665 if in instanceof import
5666 let
5667 new null
5668 return
5669 super switch
5670 this throw true try typeof
5671 var void
5672 while with
5673 yield))
5674
5675 ;; Token names aren't exactly the same as the keywords, unfortunately.
5676 ;; E.g. delete is js2-DELPROP.
5677 (defconst js2-kwd-tokens
5678 (let ((table (make-vector js2-num-tokens nil))
5679 (tokens
5680 (list js2-BREAK
5681 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5682 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5683 js2-ELSE js2-EXPORT
5684 js2-ELSE js2-EXTENDS js2-EXPORT
5685 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5686 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5687 js2-LET
5688 js2-NEW js2-NULL
5689 js2-RETURN
5690 js2-SUPER js2-SWITCH
5691 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5692 js2-VAR
5693 js2-WHILE js2-WITH
5694 js2-YIELD)))
5695 (dolist (i tokens)
5696 (aset table i 'font-lock-keyword-face))
5697 (aset table js2-STRING 'font-lock-string-face)
5698 (aset table js2-REGEXP 'font-lock-string-face)
5699 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5700 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5701 (aset table js2-COMMENT 'font-lock-comment-face)
5702 (aset table js2-THIS 'font-lock-builtin-face)
5703 (aset table js2-SUPER 'font-lock-builtin-face)
5704 (aset table js2-VOID 'font-lock-constant-face)
5705 (aset table js2-NULL 'font-lock-constant-face)
5706 (aset table js2-TRUE 'font-lock-constant-face)
5707 (aset table js2-FALSE 'font-lock-constant-face)
5708 (aset table js2-NOT 'font-lock-negation-char-face)
5709 table)
5710 "Vector whose values are non-nil for tokens that are keywords.
5711 The values are default faces to use for highlighting the keywords.")
5712
5713 ;; FIXME: Support strict mode-only future reserved words, after we know
5714 ;; which parts scopes are in strict mode, and which are not.
5715 (defconst js2-reserved-words '(class enum export extends import static super)
5716 "Future reserved keywords in ECMAScript 5.1.")
5717
5718 (defconst js2-keyword-names
5719 (let ((table (make-hash-table :test 'equal)))
5720 (cl-loop for k in js2-keywords
5721 do (puthash
5722 (symbol-name k) ; instanceof
5723 (intern (concat "js2-"
5724 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5725 table))
5726 table)
5727 "JavaScript keywords by name, mapped to their symbols.")
5728
5729 (defconst js2-reserved-word-names
5730 (let ((table (make-hash-table :test 'equal)))
5731 (cl-loop for k in js2-reserved-words
5732 do
5733 (puthash (symbol-name k) 'js2-RESERVED table))
5734 table)
5735 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5736
5737 (defun js2-collect-string (buf)
5738 "Convert BUF, a list of chars, to a string.
5739 Reverses BUF before converting."
5740 (if buf
5741 (apply #'string (nreverse buf))
5742 ""))
5743
5744 (defun js2-string-to-keyword (s)
5745 "Return token for S, a string, if S is a keyword or reserved word.
5746 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5747 (or (gethash s js2-keyword-names)
5748 (gethash s js2-reserved-word-names)))
5749
5750 (defsubst js2-ts-set-char-token-bounds (token)
5751 "Used when next token is one character."
5752 (setf (js2-token-beg token) (1- js2-ts-cursor)
5753 (js2-token-end token) js2-ts-cursor))
5754
5755 (defsubst js2-ts-return (token type)
5756 "Update the `end' and `type' slots of TOKEN,
5757 then throw `return' with value TYPE."
5758 (setf (js2-token-end token) js2-ts-cursor
5759 (js2-token-type token) type)
5760 (throw 'return type))
5761
5762 (defun js2-x-digit-to-int (c accumulator)
5763 "Build up a hex number.
5764 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5765 corresponding number. Otherwise return -1."
5766 (catch 'return
5767 (catch 'check
5768 ;; Use 0..9 < A..Z < a..z
5769 (cond
5770 ((<= c ?9)
5771 (cl-decf c ?0)
5772 (if (<= 0 c)
5773 (throw 'check nil)))
5774 ((<= c ?F)
5775 (when (<= ?A c)
5776 (cl-decf c (- ?A 10))
5777 (throw 'check nil)))
5778 ((<= c ?f)
5779 (when (<= ?a c)
5780 (cl-decf c (- ?a 10))
5781 (throw 'check nil))))
5782 (throw 'return -1))
5783 (logior c (lsh accumulator 4))))
5784
5785 (defun js2-get-token (&optional modifier)
5786 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5787 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5788 next saved token.
5789
5790 This function will not return a newline (js2-EOL) - instead, it
5791 gobbles newlines until it finds a non-newline token. Call
5792 `js2-peek-token-or-eol' when you care about newlines.
5793
5794 This function will also not return a js2-COMMENT. Instead, it
5795 records comments found in `js2-scanned-comments'. If the token
5796 returned by this function immediately follows a jsdoc comment,
5797 the token is flagged as such."
5798 (if (zerop js2-ti-lookahead)
5799 (js2-get-token-internal modifier)
5800 (cl-decf js2-ti-lookahead)
5801 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5802 (let ((tt (js2-current-token-type)))
5803 (cl-assert (not (= tt js2-EOL)))
5804 tt)))
5805
5806 (defun js2-unget-token ()
5807 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5808 (cl-incf js2-ti-lookahead)
5809 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5810
5811 (defun js2-get-token-internal (modifier)
5812 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5813 (tt (js2-token-type token))
5814 saw-eol
5815 face)
5816 ;; process comments
5817 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5818 (if (= tt js2-EOL)
5819 (setq saw-eol t)
5820 (setq saw-eol nil)
5821 (when js2-record-comments
5822 (js2-record-comment token)))
5823 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5824 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5825 tt (js2-token-type token)))
5826
5827 (when saw-eol
5828 (setf (js2-token-follows-eol-p token) t))
5829
5830 ;; perform lexical fontification as soon as token is scanned
5831 (when js2-parse-ide-mode
5832 (cond
5833 ((cl-minusp tt)
5834 (js2-record-face 'js2-error token))
5835 ((setq face (aref js2-kwd-tokens tt))
5836 (js2-record-face face token))
5837 ((and (= tt js2-NAME)
5838 (equal (js2-token-string token) "undefined"))
5839 (js2-record-face 'font-lock-constant-face token))))
5840 tt))
5841
5842 (defsubst js2-string-to-number (str base)
5843 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5844 (condition-case nil
5845 (string-to-number str base)
5846 (overflow-error -1)))
5847
5848 (defun js2-get-token-internal-1 (modifier)
5849 "Return next JavaScript token type, an int such as js2-RETURN.
5850 During operation, creates an instance of `js2-token' struct, sets
5851 its relevant fields and puts it into `js2-ti-tokens'."
5852 (let (identifier-start
5853 is-unicode-escape-start c
5854 contains-escape escape-val str result base
5855 look-for-slash continue tt
5856 (token (js2-new-token 0)))
5857 (setq
5858 tt
5859 (catch 'return
5860 (when (eq modifier 'TEMPLATE_TAIL)
5861 (setf (js2-token-beg token) (1- js2-ts-cursor))
5862 (throw 'return (js2-get-string-or-template-token ?` token)))
5863 (while t
5864 ;; Eat whitespace, possibly sensitive to newlines.
5865 (setq continue t)
5866 (while continue
5867 (setq c (js2-get-char))
5868 (cond
5869 ((eq c js2-EOF_CHAR)
5870 (js2-unget-char)
5871 (js2-ts-set-char-token-bounds token)
5872 (throw 'return js2-EOF))
5873 ((eq c ?\n)
5874 (js2-ts-set-char-token-bounds token)
5875 (setq js2-ts-dirty-line nil)
5876 (throw 'return js2-EOL))
5877 ((not (js2-js-space-p c))
5878 (if (/= c ?-) ; in case end of HTML comment
5879 (setq js2-ts-dirty-line t))
5880 (setq continue nil))))
5881 ;; Assume the token will be 1 char - fixed up below.
5882 (js2-ts-set-char-token-bounds token)
5883 (when (eq c ?@)
5884 (throw 'return js2-XMLATTR))
5885 ;; identifier/keyword/instanceof?
5886 ;; watch out for starting with a <backslash>
5887 (cond
5888 ((eq c ?\\)
5889 (setq c (js2-get-char))
5890 (if (eq c ?u)
5891 (setq identifier-start t
5892 is-unicode-escape-start t
5893 js2-ts-string-buffer nil)
5894 (setq identifier-start nil)
5895 (js2-unget-char)
5896 (setq c ?\\)))
5897 (t
5898 (when (setq identifier-start (js2-identifier-start-p c))
5899 (setq js2-ts-string-buffer nil)
5900 (js2-add-to-string c))))
5901 (when identifier-start
5902 (setq contains-escape is-unicode-escape-start)
5903 (catch 'break
5904 (while t
5905 (if is-unicode-escape-start
5906 ;; strictly speaking we should probably push-back
5907 ;; all the bad characters if the <backslash>uXXXX
5908 ;; sequence is malformed. But since there isn't a
5909 ;; correct context(is there?) for a bad Unicode
5910 ;; escape sequence in an identifier, we can report
5911 ;; an error here.
5912 (progn
5913 (setq escape-val 0)
5914 (dotimes (_ 4)
5915 (setq c (js2-get-char)
5916 escape-val (js2-x-digit-to-int c escape-val))
5917 ;; Next check takes care of c < 0 and bad escape
5918 (if (cl-minusp escape-val)
5919 (throw 'break nil)))
5920 (if (cl-minusp escape-val)
5921 (js2-report-scan-error "msg.invalid.escape" t))
5922 (js2-add-to-string escape-val)
5923 (setq is-unicode-escape-start nil))
5924 (setq c (js2-get-char))
5925 (cond
5926 ((eq c ?\\)
5927 (setq c (js2-get-char))
5928 (if (eq c ?u)
5929 (setq is-unicode-escape-start t
5930 contains-escape t)
5931 (js2-report-scan-error "msg.illegal.character" t)))
5932 (t
5933 (if (or (eq c js2-EOF_CHAR)
5934 (not (js2-identifier-part-p c)))
5935 (throw 'break nil))
5936 (js2-add-to-string c))))))
5937 (js2-unget-char)
5938 (setf str (js2-collect-string js2-ts-string-buffer)
5939 (js2-token-end token) js2-ts-cursor)
5940 ;; FIXME: Invalid in ES5 and ES6, see
5941 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5942 ;; Probably should just drop this conditional.
5943 (unless contains-escape
5944 ;; OPT we shouldn't have to make a string (object!) to
5945 ;; check if it's a keyword.
5946 ;; Return the corresponding token if it's a keyword
5947 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5948 (setq result (js2-string-to-keyword str)))
5949 (if (and (< js2-language-version 170)
5950 (memq result '(js2-LET js2-YIELD)))
5951 ;; LET and YIELD are tokens only in 1.7 and later
5952 (setq result 'js2-NAME))
5953 (when (eq result 'js2-RESERVED)
5954 (setf (js2-token-string token) str))
5955 (throw 'return (js2-tt-code result))))
5956 ;; If we want to intern these as Rhino does, just use (intern str)
5957 (setf (js2-token-string token) str)
5958 (throw 'return js2-NAME)) ; end identifier/kwd check
5959 ;; is it a number?
5960 (when (or (js2-digit-p c)
5961 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5962 (setq js2-ts-string-buffer nil
5963 base 10)
5964 (when (eq c ?0)
5965 (setq c (js2-get-char))
5966 (cond
5967 ((or (eq c ?x) (eq c ?X))
5968 (setq base 16)
5969 (setq c (js2-get-char)))
5970 ((and (or (eq c ?b) (eq c ?B))
5971 (>= js2-language-version 200))
5972 (setq base 2)
5973 (setq c (js2-get-char)))
5974 ((and (or (eq c ?o) (eq c ?O))
5975 (>= js2-language-version 200))
5976 (setq base 8)
5977 (setq c (js2-get-char)))
5978 ((js2-digit-p c)
5979 (setq base 'maybe-8))
5980 (t
5981 (js2-add-to-string ?0))))
5982 (cond
5983 ((eq base 16)
5984 (if (> 0 (js2-x-digit-to-int c 0))
5985 (js2-report-scan-error "msg.missing.hex.digits")
5986 (while (<= 0 (js2-x-digit-to-int c 0))
5987 (js2-add-to-string c)
5988 (setq c (js2-get-char)))))
5989 ((eq base 2)
5990 (if (not (memq c '(?0 ?1)))
5991 (js2-report-scan-error "msg.missing.binary.digits")
5992 (while (memq c '(?0 ?1))
5993 (js2-add-to-string c)
5994 (setq c (js2-get-char)))))
5995 ((eq base 8)
5996 (if (or (> ?0 c) (< ?7 c))
5997 (js2-report-scan-error "msg.missing.octal.digits")
5998 (while (and (<= ?0 c) (>= ?7 c))
5999 (js2-add-to-string c)
6000 (setq c (js2-get-char)))))
6001 (t
6002 (while (and (<= ?0 c) (<= c ?9))
6003 ;; We permit 08 and 09 as decimal numbers, which
6004 ;; makes our behavior a superset of the ECMA
6005 ;; numeric grammar. We might not always be so
6006 ;; permissive, so we warn about it.
6007 (when (and (eq base 'maybe-8) (>= c ?8))
6008 (js2-report-warning "msg.bad.octal.literal"
6009 (if (eq c ?8) "8" "9"))
6010 (setq base 10))
6011 (js2-add-to-string c)
6012 (setq c (js2-get-char)))
6013 (when (eq base 'maybe-8)
6014 (setq base 8))))
6015 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6016 (when (eq c ?.)
6017 (cl-loop do
6018 (js2-add-to-string c)
6019 (setq c (js2-get-char))
6020 while (js2-digit-p c)))
6021 (when (memq c '(?e ?E))
6022 (js2-add-to-string c)
6023 (setq c (js2-get-char))
6024 (when (memq c '(?+ ?-))
6025 (js2-add-to-string c)
6026 (setq c (js2-get-char)))
6027 (unless (js2-digit-p c)
6028 (js2-report-scan-error "msg.missing.exponent" t))
6029 (cl-loop do
6030 (js2-add-to-string c)
6031 (setq c (js2-get-char))
6032 while (js2-digit-p c))))
6033 (js2-unget-char)
6034 (let ((str (js2-set-string-from-buffer token)))
6035 (setf (js2-token-number token) (js2-string-to-number str base)
6036 (js2-token-number-base token) base))
6037 (throw 'return js2-NUMBER))
6038 ;; is it a string?
6039 (when (or (memq c '(?\" ?\'))
6040 (and (>= js2-language-version 200)
6041 (= c ?`)))
6042 (throw 'return
6043 (js2-get-string-or-template-token c token)))
6044 (js2-ts-return token
6045 (cl-case c
6046 (?\;
6047 (throw 'return js2-SEMI))
6048 (?\[
6049 (throw 'return js2-LB))
6050 (?\]
6051 (throw 'return js2-RB))
6052 (?{
6053 (throw 'return js2-LC))
6054 (?}
6055 (throw 'return js2-RC))
6056 (?\(
6057 (throw 'return js2-LP))
6058 (?\)
6059 (throw 'return js2-RP))
6060 (?,
6061 (throw 'return js2-COMMA))
6062 (??
6063 (throw 'return js2-HOOK))
6064 (?:
6065 (if (js2-match-char ?:)
6066 js2-COLONCOLON
6067 (throw 'return js2-COLON)))
6068 (?.
6069 (if (js2-match-char ?.)
6070 (if (js2-match-char ?.)
6071 js2-TRIPLEDOT js2-DOTDOT)
6072 (if (js2-match-char ?\()
6073 js2-DOTQUERY
6074 (throw 'return js2-DOT))))
6075 (?|
6076 (if (js2-match-char ?|)
6077 (throw 'return js2-OR)
6078 (if (js2-match-char ?=)
6079 js2-ASSIGN_BITOR
6080 (throw 'return js2-BITOR))))
6081 (?^
6082 (if (js2-match-char ?=)
6083 js2-ASSIGN_BITOR
6084 (throw 'return js2-BITXOR)))
6085 (?&
6086 (if (js2-match-char ?&)
6087 (throw 'return js2-AND)
6088 (if (js2-match-char ?=)
6089 js2-ASSIGN_BITAND
6090 (throw 'return js2-BITAND))))
6091 (?=
6092 (if (js2-match-char ?=)
6093 (if (js2-match-char ?=)
6094 js2-SHEQ
6095 (throw 'return js2-EQ))
6096 (if (js2-match-char ?>)
6097 (js2-ts-return token js2-ARROW)
6098 (throw 'return js2-ASSIGN))))
6099 (?!
6100 (if (js2-match-char ?=)
6101 (if (js2-match-char ?=)
6102 js2-SHNE
6103 js2-NE)
6104 (throw 'return js2-NOT)))
6105 (?<
6106 ;; NB:treat HTML begin-comment as comment-till-eol
6107 (when (js2-match-char ?!)
6108 (when (js2-match-char ?-)
6109 (when (js2-match-char ?-)
6110 (js2-skip-line)
6111 (setf (js2-token-comment-type (js2-current-token)) 'html)
6112 (throw 'return js2-COMMENT)))
6113 (js2-unget-char))
6114 (if (js2-match-char ?<)
6115 (if (js2-match-char ?=)
6116 js2-ASSIGN_LSH
6117 js2-LSH)
6118 (if (js2-match-char ?=)
6119 js2-LE
6120 (throw 'return js2-LT))))
6121 (?>
6122 (if (js2-match-char ?>)
6123 (if (js2-match-char ?>)
6124 (if (js2-match-char ?=)
6125 js2-ASSIGN_URSH
6126 js2-URSH)
6127 (if (js2-match-char ?=)
6128 js2-ASSIGN_RSH
6129 js2-RSH))
6130 (if (js2-match-char ?=)
6131 js2-GE
6132 (throw 'return js2-GT))))
6133 (?*
6134 (if (js2-match-char ?=)
6135 js2-ASSIGN_MUL
6136 (throw 'return js2-MUL)))
6137 (?/
6138 ;; is it a // comment?
6139 (when (js2-match-char ?/)
6140 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6141 (js2-skip-line)
6142 (setf (js2-token-comment-type token) 'line)
6143 ;; include newline so highlighting goes to end of
6144 ;; window, if there actually is a newline; if we
6145 ;; hit eof, then implicitly there isn't
6146 (unless js2-ts-hit-eof
6147 (cl-incf (js2-token-end token)))
6148 (throw 'return js2-COMMENT))
6149 ;; is it a /* comment?
6150 (when (js2-match-char ?*)
6151 (setf look-for-slash nil
6152 (js2-token-beg token) (- js2-ts-cursor 2)
6153 (js2-token-comment-type token)
6154 (if (js2-match-char ?*)
6155 (progn
6156 (setq look-for-slash t)
6157 'jsdoc)
6158 'block))
6159 (while t
6160 (setq c (js2-get-char))
6161 (cond
6162 ((eq c js2-EOF_CHAR)
6163 (setf (js2-token-end token) (1- js2-ts-cursor))
6164 (js2-report-error "msg.unterminated.comment")
6165 (throw 'return js2-COMMENT))
6166 ((eq c ?*)
6167 (setq look-for-slash t))
6168 ((eq c ?/)
6169 (if look-for-slash
6170 (js2-ts-return token js2-COMMENT)))
6171 (t
6172 (setf look-for-slash nil
6173 (js2-token-end token) js2-ts-cursor)))))
6174 (if (js2-match-char ?=)
6175 js2-ASSIGN_DIV
6176 (throw 'return js2-DIV)))
6177 (?#
6178 (when js2-skip-preprocessor-directives
6179 (js2-skip-line)
6180 (setf (js2-token-comment-type token) 'preprocessor
6181 (js2-token-end token) js2-ts-cursor)
6182 (throw 'return js2-COMMENT))
6183 (throw 'return js2-ERROR))
6184 (?%
6185 (if (js2-match-char ?=)
6186 js2-ASSIGN_MOD
6187 (throw 'return js2-MOD)))
6188 (?~
6189 (throw 'return js2-BITNOT))
6190 (?+
6191 (if (js2-match-char ?=)
6192 js2-ASSIGN_ADD
6193 (if (js2-match-char ?+)
6194 js2-INC
6195 (throw 'return js2-ADD))))
6196 (?-
6197 (cond
6198 ((js2-match-char ?=)
6199 (setq c js2-ASSIGN_SUB))
6200 ((js2-match-char ?-)
6201 (unless js2-ts-dirty-line
6202 ;; treat HTML end-comment after possible whitespace
6203 ;; after line start as comment-until-eol
6204 (when (js2-match-char ?>)
6205 (js2-skip-line)
6206 (setf (js2-token-comment-type (js2-current-token)) 'html)
6207 (throw 'return js2-COMMENT)))
6208 (setq c js2-DEC))
6209 (t
6210 (setq c js2-SUB)))
6211 (setq js2-ts-dirty-line t)
6212 c)
6213 (otherwise
6214 (js2-report-scan-error "msg.illegal.character")))))))
6215 (setf (js2-token-type token) tt)
6216 token))
6217
6218 (defun js2-get-string-or-template-token (quote-char token)
6219 ;; We attempt to accumulate a string the fast way, by
6220 ;; building it directly out of the reader. But if there
6221 ;; are any escaped characters in the string, we revert to
6222 ;; building it out of a string buffer.
6223 (let ((c (js2-get-char))
6224 js2-ts-string-buffer
6225 nc c1 val escape-val)
6226 (catch 'break
6227 (while (/= c quote-char)
6228 (catch 'continue
6229 (when (eq c js2-EOF_CHAR)
6230 (js2-unget-char)
6231 (js2-report-error "msg.unterminated.string.lit")
6232 (throw 'break nil))
6233 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6234 (js2-unget-char)
6235 (js2-report-error "msg.unterminated.string.lit")
6236 (throw 'break nil))
6237 (when (eq c ?\\)
6238 ;; We've hit an escaped character
6239 (setq c (js2-get-char))
6240 (cl-case c
6241 (?b (setq c ?\b))
6242 (?f (setq c ?\f))
6243 (?n (setq c ?\n))
6244 (?r (setq c ?\r))
6245 (?t (setq c ?\t))
6246 (?v (setq c ?\v))
6247 (?u
6248 (setq c1 (js2-read-unicode-escape))
6249 (if js2-parse-ide-mode
6250 (if c1
6251 (progn
6252 ;; just copy the string in IDE-mode
6253 (js2-add-to-string ?\\)
6254 (js2-add-to-string ?u)
6255 (dotimes (_ 3)
6256 (js2-add-to-string (js2-get-char)))
6257 (setq c (js2-get-char))) ; added at end of loop
6258 ;; flag it as an invalid escape
6259 (js2-report-warning "msg.invalid.escape"
6260 nil (- js2-ts-cursor 2) 6))
6261 ;; Get 4 hex digits; if the u escape is not
6262 ;; followed by 4 hex digits, use 'u' + the
6263 ;; literal character sequence that follows.
6264 (js2-add-to-string ?u)
6265 (setq escape-val 0)
6266 (dotimes (_ 4)
6267 (setq c (js2-get-char)
6268 escape-val (js2-x-digit-to-int c escape-val))
6269 (if (cl-minusp escape-val)
6270 (throw 'continue nil))
6271 (js2-add-to-string c))
6272 ;; prepare for replace of stored 'u' sequence by escape value
6273 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6274 c escape-val)))
6275 (?x
6276 ;; Get 2 hex digits, defaulting to 'x'+literal
6277 ;; sequence, as above.
6278 (setq c (js2-get-char)
6279 escape-val (js2-x-digit-to-int c 0))
6280 (if (cl-minusp escape-val)
6281 (progn
6282 (js2-add-to-string ?x)
6283 (throw 'continue nil))
6284 (setq c1 c
6285 c (js2-get-char)
6286 escape-val (js2-x-digit-to-int c escape-val))
6287 (if (cl-minusp escape-val)
6288 (progn
6289 (js2-add-to-string ?x)
6290 (js2-add-to-string c1)
6291 (throw 'continue nil))
6292 ;; got 2 hex digits
6293 (setq c escape-val))))
6294 (?\n
6295 ;; Remove line terminator after escape to follow
6296 ;; SpiderMonkey and C/C++
6297 (setq c (js2-get-char))
6298 (throw 'continue nil))
6299 (t
6300 (when (and (<= ?0 c) (< c ?8))
6301 (setq val (- c ?0)
6302 c (js2-get-char))
6303 (when (and (<= ?0 c) (< c ?8))
6304 (setq val (- (+ (* 8 val) c) ?0)
6305 c (js2-get-char))
6306 (when (and (<= ?0 c)
6307 (< c ?8)
6308 (< val #o37))
6309 ;; c is 3rd char of octal sequence only
6310 ;; if the resulting val <= 0377
6311 (setq val (- (+ (* 8 val) c) ?0)
6312 c (js2-get-char))))
6313 (js2-unget-char)
6314 (setq c val)))))
6315 (when (and (eq quote-char ?`) (eq c ?$))
6316 (when (eq (setq nc (js2-get-char)) ?\{)
6317 (throw 'break nil))
6318 (js2-unget-char))
6319 (js2-add-to-string c)
6320 (setq c (js2-get-char)))))
6321 (js2-set-string-from-buffer token)
6322 (if (not (eq quote-char ?`))
6323 js2-STRING
6324 (if (and (eq c ?$) (eq nc ?\{))
6325 js2-TEMPLATE_HEAD
6326 js2-NO_SUBS_TEMPLATE))))
6327
6328 (defun js2-read-regexp (start-tt)
6329 "Called by parser when it gets / or /= in literal context."
6330 (let (c err
6331 in-class ; inside a '[' .. ']' character-class
6332 flags
6333 (continue t)
6334 (token (js2-new-token 0)))
6335 (setq js2-ts-string-buffer nil)
6336 (if (eq start-tt js2-ASSIGN_DIV)
6337 ;; mis-scanned /=
6338 (js2-add-to-string ?=)
6339 (if (not (eq start-tt js2-DIV))
6340 (error "failed assertion")))
6341 (while (and (not err)
6342 (or (/= (setq c (js2-get-char)) ?/)
6343 in-class))
6344 (cond
6345 ((or (= c ?\n)
6346 (= c js2-EOF_CHAR))
6347 (setf (js2-token-end token) (1- js2-ts-cursor)
6348 err t
6349 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6350 (js2-report-error "msg.unterminated.re.lit"))
6351 (t (cond
6352 ((= c ?\\)
6353 (js2-add-to-string c)
6354 (setq c (js2-get-char)))
6355 ((= c ?\[)
6356 (setq in-class t))
6357 ((= c ?\])
6358 (setq in-class nil)))
6359 (js2-add-to-string c))))
6360 (unless err
6361 (while continue
6362 (cond
6363 ((js2-match-char ?g)
6364 (push ?g flags))
6365 ((js2-match-char ?i)
6366 (push ?i flags))
6367 ((js2-match-char ?m)
6368 (push ?m flags))
6369 ((and (js2-match-char ?u)
6370 (>= js2-language-version 200))
6371 (push ?u flags))
6372 ((and (js2-match-char ?y)
6373 (>= js2-language-version 200))
6374 (push ?y flags))
6375 (t
6376 (setq continue nil))))
6377 (if (js2-alpha-p (js2-peek-char))
6378 (js2-report-scan-error "msg.invalid.re.flag" t
6379 js2-ts-cursor 1))
6380 (js2-set-string-from-buffer token))
6381 (js2-collect-string flags)))
6382
6383 (defun js2-get-first-xml-token ()
6384 (setq js2-ts-xml-open-tags-count 0
6385 js2-ts-is-xml-attribute nil
6386 js2-ts-xml-is-tag-content nil)
6387 (js2-unget-char)
6388 (js2-get-next-xml-token))
6389
6390 (defun js2-xml-discard-string (token)
6391 "Throw away the string in progress and flag an XML parse error."
6392 (setf js2-ts-string-buffer nil
6393 (js2-token-string token) nil)
6394 (js2-report-scan-error "msg.XML.bad.form" t))
6395
6396 (defun js2-get-next-xml-token ()
6397 (setq js2-ts-string-buffer nil) ; for recording the XML
6398 (let ((token (js2-new-token 0))
6399 c result)
6400 (setq result
6401 (catch 'return
6402 (while t
6403 (setq c (js2-get-char))
6404 (cond
6405 ((= c js2-EOF_CHAR)
6406 (throw 'return js2-ERROR))
6407 (js2-ts-xml-is-tag-content
6408 (cl-case c
6409 (?>
6410 (js2-add-to-string c)
6411 (setq js2-ts-xml-is-tag-content nil
6412 js2-ts-is-xml-attribute nil))
6413 (?/
6414 (js2-add-to-string c)
6415 (when (eq ?> (js2-peek-char))
6416 (setq c (js2-get-char))
6417 (js2-add-to-string c)
6418 (setq js2-ts-xml-is-tag-content nil)
6419 (cl-decf js2-ts-xml-open-tags-count)))
6420 (?{
6421 (js2-unget-char)
6422 (js2-set-string-from-buffer token)
6423 (throw 'return js2-XML))
6424 ((?\' ?\")
6425 (js2-add-to-string c)
6426 (unless (js2-read-quoted-string c token)
6427 (throw 'return js2-ERROR)))
6428 (?=
6429 (js2-add-to-string c)
6430 (setq js2-ts-is-xml-attribute t))
6431 ((? ?\t ?\r ?\n)
6432 (js2-add-to-string c))
6433 (t
6434 (js2-add-to-string c)
6435 (setq js2-ts-is-xml-attribute nil)))
6436 (when (and (not js2-ts-xml-is-tag-content)
6437 (zerop js2-ts-xml-open-tags-count))
6438 (js2-set-string-from-buffer token)
6439 (throw 'return js2-XMLEND)))
6440 (t
6441 ;; else not tag content
6442 (cl-case c
6443 (?<
6444 (js2-add-to-string c)
6445 (setq c (js2-peek-char))
6446 (cl-case c
6447 (?!
6448 (setq c (js2-get-char)) ;; skip !
6449 (js2-add-to-string c)
6450 (setq c (js2-peek-char))
6451 (cl-case c
6452 (?-
6453 (setq c (js2-get-char)) ;; skip -
6454 (js2-add-to-string c)
6455 (if (eq c ?-)
6456 (progn
6457 (js2-add-to-string c)
6458 (unless (js2-read-xml-comment token)
6459 (throw 'return js2-ERROR)))
6460 (js2-xml-discard-string token)
6461 (throw 'return js2-ERROR)))
6462 (?\[
6463 (setq c (js2-get-char)) ;; skip [
6464 (js2-add-to-string c)
6465 (if (and (= (js2-get-char) ?C)
6466 (= (js2-get-char) ?D)
6467 (= (js2-get-char) ?A)
6468 (= (js2-get-char) ?T)
6469 (= (js2-get-char) ?A)
6470 (= (js2-get-char) ?\[))
6471 (progn
6472 (js2-add-to-string ?C)
6473 (js2-add-to-string ?D)
6474 (js2-add-to-string ?A)
6475 (js2-add-to-string ?T)
6476 (js2-add-to-string ?A)
6477 (js2-add-to-string ?\[)
6478 (unless (js2-read-cdata token)
6479 (throw 'return js2-ERROR)))
6480 (js2-xml-discard-string token)
6481 (throw 'return js2-ERROR)))
6482 (t
6483 (unless (js2-read-entity token)
6484 (throw 'return js2-ERROR))))
6485 ;; Allow bare CDATA section, e.g.:
6486 ;; let xml = <![CDATA[ foo bar baz ]]>;
6487 (when (zerop js2-ts-xml-open-tags-count)
6488 (throw 'return js2-XMLEND)))
6489 (??
6490 (setq c (js2-get-char)) ;; skip ?
6491 (js2-add-to-string c)
6492 (unless (js2-read-PI token)
6493 (throw 'return js2-ERROR)))
6494 (?/
6495 ;; end tag
6496 (setq c (js2-get-char)) ;; skip /
6497 (js2-add-to-string c)
6498 (when (zerop js2-ts-xml-open-tags-count)
6499 (js2-xml-discard-string token)
6500 (throw 'return js2-ERROR))
6501 (setq js2-ts-xml-is-tag-content t)
6502 (cl-decf js2-ts-xml-open-tags-count))
6503 (t
6504 ;; start tag
6505 (setq js2-ts-xml-is-tag-content t)
6506 (cl-incf js2-ts-xml-open-tags-count))))
6507 (?{
6508 (js2-unget-char)
6509 (js2-set-string-from-buffer token)
6510 (throw 'return js2-XML))
6511 (t
6512 (js2-add-to-string c))))))))
6513 (setf (js2-token-end token) js2-ts-cursor)
6514 (setf (js2-token-type token) result)
6515 result))
6516
6517 (defun js2-read-quoted-string (quote token)
6518 (let (c)
6519 (catch 'return
6520 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6521 (js2-add-to-string c)
6522 (if (eq c quote)
6523 (throw 'return t)))
6524 (js2-xml-discard-string token) ;; throw away string in progress
6525 nil)))
6526
6527 (defun js2-read-xml-comment (token)
6528 (let ((c (js2-get-char)))
6529 (catch 'return
6530 (while (/= c js2-EOF_CHAR)
6531 (catch 'continue
6532 (js2-add-to-string c)
6533 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6534 (setq c (js2-get-char))
6535 (js2-add-to-string c)
6536 (if (eq (js2-peek-char) ?>)
6537 (progn
6538 (setq c (js2-get-char)) ;; skip >
6539 (js2-add-to-string c)
6540 (throw 'return t))
6541 (throw 'continue nil)))
6542 (setq c (js2-get-char))))
6543 (js2-xml-discard-string token)
6544 nil)))
6545
6546 (defun js2-read-cdata (token)
6547 (let ((c (js2-get-char)))
6548 (catch 'return
6549 (while (/= c js2-EOF_CHAR)
6550 (catch 'continue
6551 (js2-add-to-string c)
6552 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6553 (setq c (js2-get-char))
6554 (js2-add-to-string c)
6555 (if (eq (js2-peek-char) ?>)
6556 (progn
6557 (setq c (js2-get-char)) ;; Skip >
6558 (js2-add-to-string c)
6559 (throw 'return t))
6560 (throw 'continue nil)))
6561 (setq c (js2-get-char))))
6562 (js2-xml-discard-string token)
6563 nil)))
6564
6565 (defun js2-read-entity (token)
6566 (let ((decl-tags 1)
6567 c)
6568 (catch 'return
6569 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6570 (js2-add-to-string c)
6571 (cl-case c
6572 (?<
6573 (cl-incf decl-tags))
6574 (?>
6575 (cl-decf decl-tags)
6576 (if (zerop decl-tags)
6577 (throw 'return t)))))
6578 (js2-xml-discard-string token)
6579 nil)))
6580
6581 (defun js2-read-PI (token)
6582 "Scan an XML processing instruction."
6583 (let (c)
6584 (catch 'return
6585 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6586 (js2-add-to-string c)
6587 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6588 (setq c (js2-get-char)) ;; Skip >
6589 (js2-add-to-string c)
6590 (throw 'return t)))
6591 (js2-xml-discard-string token)
6592 nil)))
6593
6594 ;;; Highlighting
6595
6596 (defun js2-set-face (beg end face &optional record)
6597 "Fontify a region. If RECORD is non-nil, record for later."
6598 (when (cl-plusp js2-highlight-level)
6599 (setq beg (min (point-max) beg)
6600 beg (max (point-min) beg)
6601 end (min (point-max) end)
6602 end (max (point-min) end))
6603 (if record
6604 (push (list beg end face) js2-mode-fontifications)
6605 (put-text-property beg end 'font-lock-face face))))
6606
6607 (defsubst js2-clear-face (beg end)
6608 (remove-text-properties beg end '(font-lock-face nil
6609 help-echo nil
6610 point-entered nil
6611 cursor-sensor-functions nil
6612 c-in-sws nil)))
6613
6614 (defconst js2-ecma-global-props
6615 (concat "^"
6616 (regexp-opt
6617 '("Infinity" "NaN" "undefined" "arguments") t)
6618 "$")
6619 "Value properties of the Ecma-262 Global Object.
6620 Shown at or above `js2-highlight-level' 2.")
6621
6622 ;; might want to add the name "arguments" to this list?
6623 (defconst js2-ecma-object-props
6624 (concat "^"
6625 (regexp-opt
6626 '("prototype" "__proto__" "__parent__") t)
6627 "$")
6628 "Value properties of the Ecma-262 Object constructor.
6629 Shown at or above `js2-highlight-level' 2.")
6630
6631 (defconst js2-ecma-global-funcs
6632 (concat
6633 "^"
6634 (regexp-opt
6635 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6636 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6637 "$")
6638 "Function properties of the Ecma-262 Global object.
6639 Shown at or above `js2-highlight-level' 2.")
6640
6641 (defconst js2-ecma-number-props
6642 (concat "^"
6643 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6644 "NEGATIVE_INFINITY"
6645 "POSITIVE_INFINITY") t)
6646 "$")
6647 "Properties of the Ecma-262 Number constructor.
6648 Shown at or above `js2-highlight-level' 2.")
6649
6650 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6651 "Properties of the Ecma-262 Date constructor.
6652 Shown at or above `js2-highlight-level' 2.")
6653
6654 (defconst js2-ecma-math-props
6655 (concat "^"
6656 (regexp-opt
6657 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6658 t)
6659 "$")
6660 "Properties of the Ecma-262 Math object.
6661 Shown at or above `js2-highlight-level' 2.")
6662
6663 (defconst js2-ecma-math-funcs
6664 (concat "^"
6665 (regexp-opt
6666 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6667 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6668 "$")
6669 "Function properties of the Ecma-262 Math object.
6670 Shown at or above `js2-highlight-level' 2.")
6671
6672 (defconst js2-ecma-function-props
6673 (concat
6674 "^"
6675 (regexp-opt
6676 '(;; properties of the Object prototype object
6677 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6678 "toLocaleString" "toString" "valueOf"
6679 ;; properties of the Function prototype object
6680 "apply" "call"
6681 ;; properties of the Array prototype object
6682 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6683 "splice" "unshift"
6684 ;; properties of the String prototype object
6685 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6686 "localeCompare" "match" "replace" "search" "split" "substring"
6687 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6688 "toUpperCase"
6689 ;; properties of the Number prototype object
6690 "toExponential" "toFixed" "toPrecision"
6691 ;; properties of the Date prototype object
6692 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6693 "getMinutes" "getMonth" "getSeconds" "getTime"
6694 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6695 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6696 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6697 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6698 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6699 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6700 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6701 "toTimeString" "toUTCString"
6702 ;; properties of the RegExp prototype object
6703 "exec" "test"
6704 ;; properties of the JSON prototype object
6705 "parse" "stringify"
6706 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6707 "toSource" "__defineGetter__" "__defineSetter__"
6708 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6709 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6710 t)
6711 "$")
6712 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6713 Shown at or above `js2-highlight-level' 3.")
6714
6715 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6716 (let ((target-name (and target
6717 (js2-name-node-p target)
6718 (js2-name-node-name target)))
6719 (prop-name (if prop (js2-name-node-name prop)))
6720 (level2 (>= js2-highlight-level 2))
6721 (level3 (>= js2-highlight-level 3)))
6722 (when level2
6723 (let ((face
6724 (if call-p
6725 (cond
6726 ((and target prop)
6727 (cond
6728 ((and level3 (string-match js2-ecma-function-props prop-name))
6729 'font-lock-builtin-face)
6730 ((and target-name prop)
6731 (cond
6732 ((string= target-name "Date")
6733 (if (string-match js2-ecma-date-props prop-name)
6734 'font-lock-builtin-face))
6735 ((string= target-name "Math")
6736 (if (string-match js2-ecma-math-funcs prop-name)
6737 'font-lock-builtin-face))))))
6738 (prop
6739 (if (string-match js2-ecma-global-funcs prop-name)
6740 'font-lock-builtin-face)))
6741 (cond
6742 ((and target prop)
6743 (cond
6744 ((string= target-name "Number")
6745 (if (string-match js2-ecma-number-props prop-name)
6746 'font-lock-constant-face))
6747 ((string= target-name "Math")
6748 (if (string-match js2-ecma-math-props prop-name)
6749 'font-lock-constant-face))))
6750 (prop
6751 (if (string-match js2-ecma-object-props prop-name)
6752 'font-lock-constant-face))))))
6753 (when face
6754 (let ((pos (+ (js2-node-pos parent) ; absolute
6755 (js2-node-pos prop)))) ; relative
6756 (js2-set-face pos
6757 (+ pos (js2-node-len prop))
6758 face 'record)))))))
6759
6760 (defun js2-parse-highlight-member-expr-node (node)
6761 "Perform syntax highlighting of EcmaScript built-in properties.
6762 The variable `js2-highlight-level' governs this highlighting."
6763 (let (face target prop name pos end parent call-p callee)
6764 (cond
6765 ;; case 1: simple name, e.g. foo
6766 ((js2-name-node-p node)
6767 (setq name (js2-name-node-name node))
6768 ;; possible for name to be nil in rare cases - saw it when
6769 ;; running js2-mode on an elisp buffer. Might as well try to
6770 ;; make it so js2-mode never barfs.
6771 (when name
6772 (setq face (if (string-match js2-ecma-global-props name)
6773 'font-lock-constant-face))
6774 (when face
6775 (setq pos (js2-node-pos node)
6776 end (+ pos (js2-node-len node)))
6777 (js2-set-face pos end face 'record))))
6778 ;; case 2: property access or function call
6779 ((or (js2-prop-get-node-p node)
6780 ;; highlight function call if expr is a prop-get node
6781 ;; or a plain name (i.e. unqualified function call)
6782 (and (setq call-p (js2-call-node-p node))
6783 (setq callee (js2-call-node-target node)) ; separate setq!
6784 (or (js2-prop-get-node-p callee)
6785 (js2-name-node-p callee))))
6786 (setq parent node
6787 node (if call-p callee node))
6788 (if (and call-p (js2-name-node-p callee))
6789 (setq prop callee)
6790 (setq target (js2-prop-get-node-left node)
6791 prop (js2-prop-get-node-right node)))
6792 (cond
6793 ((js2-name-node-p prop)
6794 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6795 (js2-parse-highlight-prop-get parent target prop call-p))
6796 ((js2-name-node-p target)
6797 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6798 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6799
6800 (defun js2-parse-highlight-member-expr-fn-name (expr)
6801 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6802 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6803 We currently only handle the case where the last component is a prop-get
6804 of a simple name. Called before EXPR has a parent node."
6805 (let (pos
6806 (name (and (js2-prop-get-node-p expr)
6807 (js2-prop-get-node-right expr))))
6808 (when (js2-name-node-p name)
6809 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6810 (js2-node-pos name)))
6811 (+ pos (js2-node-len name))
6812 'font-lock-function-name-face
6813 'record))))
6814
6815 ;; source: http://jsdoc.sourceforge.net/
6816 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6817 ;; allows type specifications, and needs work before entering the wild.
6818
6819 (defconst js2-jsdoc-param-tag-regexp
6820 (concat "^\\s-*\\*+\\s-*\\(@"
6821 "\\(?:param\\|argument\\)"
6822 "\\)"
6823 "\\s-*\\({[^}]+}\\)?" ; optional type
6824 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6825 "\\_>")
6826 "Matches jsdoc tags with optional type and optional param name.")
6827
6828 (defconst js2-jsdoc-typed-tag-regexp
6829 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6830 (regexp-opt
6831 '("enum"
6832 "extends"
6833 "field"
6834 "id"
6835 "implements"
6836 "lends"
6837 "mods"
6838 "requires"
6839 "return"
6840 "returns"
6841 "throw"
6842 "throws"))
6843 "\\)\\)\\s-*\\({[^}]+}\\)?")
6844 "Matches jsdoc tags with optional type.")
6845
6846 (defconst js2-jsdoc-arg-tag-regexp
6847 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6848 (regexp-opt
6849 '("alias"
6850 "augments"
6851 "borrows"
6852 "bug"
6853 "base"
6854 "config"
6855 "default"
6856 "define"
6857 "exception"
6858 "function"
6859 "member"
6860 "memberOf"
6861 "name"
6862 "namespace"
6863 "property"
6864 "since"
6865 "suppress"
6866 "this"
6867 "throws"
6868 "type"
6869 "version"))
6870 "\\)\\)\\s-+\\([^ \t]+\\)")
6871 "Matches jsdoc tags with a single argument.")
6872
6873 (defconst js2-jsdoc-empty-tag-regexp
6874 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6875 (regexp-opt
6876 '("addon"
6877 "author"
6878 "class"
6879 "const"
6880 "constant"
6881 "constructor"
6882 "constructs"
6883 "deprecated"
6884 "desc"
6885 "description"
6886 "event"
6887 "example"
6888 "exec"
6889 "export"
6890 "fileoverview"
6891 "final"
6892 "function"
6893 "hidden"
6894 "ignore"
6895 "implicitCast"
6896 "inheritDoc"
6897 "inner"
6898 "interface"
6899 "license"
6900 "noalias"
6901 "noshadow"
6902 "notypecheck"
6903 "override"
6904 "owner"
6905 "preserve"
6906 "preserveTry"
6907 "private"
6908 "protected"
6909 "public"
6910 "static"
6911 "supported"
6912 ))
6913 "\\)\\)\\s-*")
6914 "Matches empty jsdoc tags.")
6915
6916 (defconst js2-jsdoc-link-tag-regexp
6917 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6918 "Matches a jsdoc link or code tag.")
6919
6920 (defconst js2-jsdoc-see-tag-regexp
6921 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6922 "Matches a jsdoc @see tag.")
6923
6924 (defconst js2-jsdoc-html-tag-regexp
6925 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6926 "Matches a simple (no attributes) html start- or end-tag.")
6927
6928 (defun js2-jsdoc-highlight-helper ()
6929 (js2-set-face (match-beginning 1)
6930 (match-end 1)
6931 'js2-jsdoc-tag)
6932 (if (match-beginning 2)
6933 (if (save-excursion
6934 (goto-char (match-beginning 2))
6935 (= (char-after) ?{))
6936 (js2-set-face (1+ (match-beginning 2))
6937 (1- (match-end 2))
6938 'js2-jsdoc-type)
6939 (js2-set-face (match-beginning 2)
6940 (match-end 2)
6941 'js2-jsdoc-value)))
6942 (if (match-beginning 3)
6943 (js2-set-face (match-beginning 3)
6944 (match-end 3)
6945 'js2-jsdoc-value)))
6946
6947 (defun js2-highlight-jsdoc (ast)
6948 "Highlight doc comment tags."
6949 (let ((comments (js2-ast-root-comments ast))
6950 beg end)
6951 (save-excursion
6952 (dolist (node comments)
6953 (when (eq (js2-comment-node-format node) 'jsdoc)
6954 (setq beg (js2-node-abs-pos node)
6955 end (+ beg (js2-node-len node)))
6956 (save-restriction
6957 (narrow-to-region beg end)
6958 (dolist (re (list js2-jsdoc-param-tag-regexp
6959 js2-jsdoc-typed-tag-regexp
6960 js2-jsdoc-arg-tag-regexp
6961 js2-jsdoc-link-tag-regexp
6962 js2-jsdoc-see-tag-regexp
6963 js2-jsdoc-empty-tag-regexp))
6964 (goto-char beg)
6965 (while (re-search-forward re nil t)
6966 (js2-jsdoc-highlight-helper)))
6967 ;; simple highlighting for html tags
6968 (goto-char beg)
6969 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6970 (js2-set-face (match-beginning 1)
6971 (match-end 1)
6972 'js2-jsdoc-html-tag-delimiter)
6973 (js2-set-face (match-beginning 2)
6974 (match-end 2)
6975 'js2-jsdoc-html-tag-name)
6976 (js2-set-face (match-beginning 3)
6977 (match-end 3)
6978 'js2-jsdoc-html-tag-delimiter))))))))
6979
6980 (defun js2-highlight-assign-targets (_node left right)
6981 "Highlight function properties and external variables."
6982 (let (leftpos name)
6983 ;; highlight vars and props assigned function values
6984 (when (or (js2-function-node-p right)
6985 (js2-class-node-p right))
6986 (cond
6987 ;; var foo = function() {...}
6988 ((js2-name-node-p left)
6989 (setq name left))
6990 ;; foo.bar.baz = function() {...}
6991 ((and (js2-prop-get-node-p left)
6992 (js2-name-node-p (js2-prop-get-node-right left)))
6993 (setq name (js2-prop-get-node-right left))))
6994 (when name
6995 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6996 (+ leftpos (js2-node-len name))
6997 'font-lock-function-name-face
6998 'record)))))
6999
7000 (defun js2-record-name-node (node)
7001 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7002 later. NODE must be a name node."
7003 (let ((leftpos (js2-node-abs-pos node)))
7004 (push (list node js2-current-scope
7005 leftpos
7006 (+ leftpos (js2-node-len node)))
7007 js2-recorded-identifiers)))
7008
7009 (defun js2-highlight-undeclared-vars ()
7010 "After entire parse is finished, look for undeclared variable references.
7011 We have to wait until entire buffer is parsed, since JavaScript permits var
7012 decls to occur after they're used.
7013
7014 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7015 it is considered declared."
7016 (let (name)
7017 (dolist (entry js2-recorded-identifiers)
7018 (cl-destructuring-bind (name-node scope pos end) entry
7019 (setq name (js2-name-node-name name-node))
7020 (unless (or (member name js2-global-externs)
7021 (member name js2-default-externs)
7022 (member name js2-additional-externs)
7023 (js2-get-defining-scope scope name pos))
7024 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7025 'js2-external-variable))))))
7026
7027 (defun js2--add-or-update-symbol (symbol inition used vars)
7028 "Add or update SYMBOL entry in VARS, an hash table.
7029 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7030 respectively meaning that SYMBOL is a mere declaration, an
7031 assignment or a function parameter; when USED is t, the symbol
7032 node is assumed to be an usage and thus added to the list stored
7033 in the cdr of the entry.
7034 "
7035 (let* ((nm (js2-name-node-name symbol))
7036 (es (js2-node-get-enclosing-scope symbol))
7037 (ds (js2-get-defining-scope es nm)))
7038 (when (and ds (not (equal nm "arguments")))
7039 (let* ((sym (js2-scope-get-symbol ds nm))
7040 (var (gethash sym vars))
7041 (err-var-p (js2-catch-node-p ds)))
7042 (unless inition
7043 (setq inition err-var-p))
7044 (if var
7045 (progn
7046 (when (and inition (not (equal (car var) ?P)))
7047 (setcar var inition))
7048 (when used
7049 (push symbol (cdr var))))
7050 ;; do not consider the declaration of catch parameter as an usage
7051 (when (and err-var-p used)
7052 (setq used nil))
7053 (puthash sym (cons inition (if used (list symbol))) vars))))))
7054
7055 (defun js2--classify-variables ()
7056 "Collect and classify variables declared or used within js2-mode-ast.
7057 Traverse the whole ast tree returning a summary of the variables
7058 usage as an hash-table, keyed by their corresponding symbol table
7059 entry.
7060 Each variable is described by a tuple where the car is a flag
7061 indicating whether the variable has been initialized and the cdr
7062 is a possibly empty list of name nodes where it is used. External
7063 symbols, i.e. those not present in the whole scopes hierarchy,
7064 are ignored."
7065 (let ((vars (make-hash-table :test #'eq :size 100)))
7066 (js2-visit-ast
7067 js2-mode-ast
7068 (lambda (node end-p)
7069 (when (null end-p)
7070 (cond
7071 ((js2-var-init-node-p node)
7072 ;; take note about possibly initialized declarations
7073 (let ((target (js2-var-init-node-target node))
7074 (initializer (js2-var-init-node-initializer node)))
7075 (when target
7076 (let* ((parent (js2-node-parent node))
7077 (grandparent (if parent (js2-node-parent parent)))
7078 (inited (not (null initializer))))
7079 (unless inited
7080 (setq inited
7081 (and grandparent
7082 (js2-for-in-node-p grandparent)
7083 (memq target
7084 (mapcar #'js2-var-init-node-target
7085 (js2-var-decl-node-kids
7086 (js2-for-in-node-iterator grandparent)))))))
7087 (js2--add-or-update-symbol target inited nil vars)))))
7088
7089 ((js2-assign-node-p node)
7090 ;; take note about assignments
7091 (let ((left (js2-assign-node-left node)))
7092 (when (js2-name-node-p left)
7093 (js2--add-or-update-symbol left t nil vars))))
7094
7095 ((js2-prop-get-node-p node)
7096 ;; handle x.y.z nodes, considering only x
7097 (let ((left (js2-prop-get-node-left node)))
7098 (when (js2-name-node-p left)
7099 (js2--add-or-update-symbol left nil t vars))))
7100
7101 ((js2-name-node-p node)
7102 ;; take note about used variables
7103 (let ((parent (js2-node-parent node)))
7104 (when parent
7105 (unless (or (and (js2-var-init-node-p parent) ; handled above
7106 (eq node (js2-var-init-node-target parent)))
7107 (and (js2-assign-node-p parent)
7108 (eq node (js2-assign-node-left parent)))
7109 (js2-prop-get-node-p parent))
7110 (let ((used t) inited)
7111 (cond
7112 ((and (js2-function-node-p parent)
7113 (js2-wrapper-function-p parent))
7114 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7115
7116 ((js2-for-in-node-p parent)
7117 (if (eq node (js2-for-in-node-iterator parent))
7118 (setq inited t used nil)))
7119
7120 ((js2-function-node-p parent)
7121 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7122 used nil)))
7123
7124 (unless used
7125 (let ((grandparent (js2-node-parent parent)))
7126 (when grandparent
7127 (setq used (js2-return-node-p grandparent)))))
7128
7129 (js2--add-or-update-symbol node inited used vars))))))))
7130 t))
7131 vars))
7132
7133 (defun js2--get-name-node (node)
7134 (cond
7135 ((js2-name-node-p node) node)
7136 ((js2-function-node-p node)
7137 (js2-function-node-name node))
7138 ((js2-class-node-p node)
7139 (js2-class-node-name node))
7140 ((js2-comp-loop-node-p node)
7141 (js2-comp-loop-node-iterator node))
7142 (t node)))
7143
7144 (defun js2--highlight-unused-variable (symbol info)
7145 (let ((name (js2-symbol-name symbol))
7146 (inited (car info))
7147 (refs (cdr info))
7148 pos len)
7149 (unless (and inited refs)
7150 (if refs
7151 (dolist (ref refs)
7152 (setq pos (js2-node-abs-pos ref))
7153 (setq len (js2-name-node-len ref))
7154 (js2-report-warning "msg.uninitialized.variable" name pos len
7155 'js2-warning))
7156 (when (or js2-warn-about-unused-function-arguments
7157 (not (eq inited ?P)))
7158 (let* ((symn (js2-symbol-ast-node symbol))
7159 (namen (js2--get-name-node symn)))
7160 (unless (js2-node-top-level-decl-p namen)
7161 (setq pos (js2-node-abs-pos namen))
7162 (setq len (js2-name-node-len namen))
7163 (js2-report-warning "msg.unused.variable" name pos len
7164 'js2-warning))))))))
7165
7166 (defun js2-highlight-unused-variables ()
7167 "Highlight unused variables."
7168 (let ((vars (js2--classify-variables)))
7169 (maphash #'js2--highlight-unused-variable vars)))
7170
7171 ;;;###autoload
7172 (define-minor-mode js2-highlight-unused-variables-mode
7173 "Toggle highlight of unused variables."
7174 :lighter ""
7175 (if js2-highlight-unused-variables-mode
7176 (add-hook 'js2-post-parse-callbacks
7177 #'js2-highlight-unused-variables nil t)
7178 (remove-hook 'js2-post-parse-callbacks
7179 #'js2-highlight-unused-variables t)))
7180
7181 (defun js2-set-default-externs ()
7182 "Set the value of `js2-default-externs' based on the various
7183 `js2-include-?-externs' variables."
7184 (setq js2-default-externs
7185 (append js2-ecma-262-externs
7186 (if js2-include-browser-externs js2-browser-externs)
7187 (if (and js2-include-browser-externs
7188 (>= js2-language-version 200)) js2-harmony-externs)
7189 (if js2-include-rhino-externs js2-rhino-externs)
7190 (if js2-include-node-externs js2-node-externs)
7191 (if (or js2-include-browser-externs js2-include-node-externs)
7192 js2-typed-array-externs))))
7193
7194 (defun js2-apply-jslint-globals ()
7195 (setq js2-additional-externs
7196 (nconc (js2-get-jslint-globals)
7197 js2-additional-externs)))
7198
7199 (defun js2-get-jslint-globals ()
7200 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7201 when (and (eq 'block (js2-comment-node-format node))
7202 (save-excursion
7203 (goto-char (js2-node-abs-pos node))
7204 (looking-at "/\\*global ")))
7205 append (js2-get-jslint-globals-in
7206 (match-end 0)
7207 (js2-node-abs-end node))))
7208
7209 (defun js2-get-jslint-globals-in (beg end)
7210 (let (res)
7211 (save-excursion
7212 (goto-char beg)
7213 (while (re-search-forward js2-mode-identifier-re end t)
7214 (let ((match (match-string 0)))
7215 (unless (member match '("true" "false"))
7216 (push match res)))))
7217 (nreverse res)))
7218
7219 ;;; IMenu support
7220
7221 ;; We currently only support imenu, but eventually should support speedbar and
7222 ;; possibly other browsing mechanisms.
7223
7224 ;; The basic strategy is to identify function assignment targets of the form
7225 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7226 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7227 ;; for imenu after parsing is finished.
7228
7229 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7230 ;; JavaScript, and the general problem is undecidable. However, several forms
7231 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7232 ;; include:
7233
7234 ;; function foo() -- function declaration
7235 ;; foo = function() -- function expression assigned to variable
7236 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7237 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7238 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7239 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7240 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7241 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7242 ;; function foo() {function bar() {...}} -- nested function
7243 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7244
7245 ;; This list boils down to a few forms that can be combined recursively.
7246 ;; Top-level named function declarations include both the left-hand (name)
7247 ;; and the right-hand (function value) expressions needed to produce an imenu
7248 ;; entry. The other "right-hand" forms we need to look for are:
7249 ;; - functions declared as props/getters/setters in object literals
7250 ;; - nested named function declarations
7251 ;; The "left-hand" expressions that functions can be assigned to include:
7252 ;; - local/global variables
7253 ;; - nested property-get expressions like a.b.c.d
7254 ;; - element gets like foo[10] or foo['bar'] where the index
7255 ;; expression can be trivially converted to a property name. They
7256 ;; effectively then become property gets.
7257
7258 ;; All the different definition types are canonicalized into the form
7259 ;; foo.bar.baz = position-of-function-keyword
7260
7261 ;; We need to build a trie-like structure for imenu. As an example,
7262 ;; consider the following JavaScript code:
7263
7264 ;; a = function() {...} // function at position 5
7265 ;; b = function() {...} // function at position 25
7266 ;; foo = function() {...} // function at position 100
7267 ;; foo.bar = function() {...} // function at position 200
7268 ;; foo.bar.baz = function() {...} // function at position 300
7269 ;; foo.bar.zab = function() {...} // function at position 400
7270
7271 ;; During parsing we accumulate an entry for each definition in
7272 ;; the variable `js2-imenu-recorder', like so:
7273
7274 ;; '((fn a 5)
7275 ;; (fn b 25)
7276 ;; (fn foo 100)
7277 ;; (fn foo bar 200)
7278 ;; (fn foo bar baz 300)
7279 ;; (fn foo bar zab 400))
7280
7281 ;; Where 'fn' is the respective function node.
7282 ;; After parsing these entries are merged into this alist-trie:
7283
7284 ;; '((a . 1)
7285 ;; (b . 2)
7286 ;; (foo (<definition> . 3)
7287 ;; (bar (<definition> . 6)
7288 ;; (baz . 100)
7289 ;; (zab . 200))))
7290
7291 ;; Note the wacky need for a <definition> name. The token can be anything
7292 ;; that isn't a valid JavaScript identifier, because you might make foo
7293 ;; a function and then start setting properties on it that are also functions.
7294
7295 (defun js2-prop-node-name (node)
7296 "Return the name of a node that may be a property-get/property-name.
7297 If NODE is not a valid name-node, string-node or integral number-node,
7298 returns nil. Otherwise returns the string name/value of the node."
7299 (cond
7300 ((js2-name-node-p node)
7301 (js2-name-node-name node))
7302 ((js2-string-node-p node)
7303 (js2-string-node-value node))
7304 ((and (js2-number-node-p node)
7305 (string-match "^[0-9]+$" (js2-number-node-value node)))
7306 (js2-number-node-value node))
7307 ((eq (js2-node-type node) js2-THIS)
7308 "this")
7309 ((eq (js2-node-type node) js2-SUPER)
7310 "super")))
7311
7312 (defun js2-node-qname-component (node)
7313 "Return the name of this node, if it contributes to a qname.
7314 Returns nil if the node doesn't contribute."
7315 (copy-sequence
7316 (or (js2-prop-node-name node)
7317 (if (and (js2-function-node-p node)
7318 (js2-function-node-name node))
7319 (js2-name-node-name (js2-function-node-name node))))))
7320
7321 (defun js2-record-imenu-entry (fn-node qname pos)
7322 "Add an entry to `js2-imenu-recorder'.
7323 FN-NODE should be the current item's function node.
7324
7325 Associate FN-NODE with its QNAME for later lookup.
7326 This is used in postprocessing the chain list. For each chain, we find
7327 the parent function, look up its qname, then prepend a copy of it to the chain."
7328 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7329 (unless js2-imenu-function-map
7330 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7331 (puthash fn-node qname js2-imenu-function-map))
7332
7333 (defun js2-record-imenu-functions (node &optional var)
7334 "Record function definitions for imenu.
7335 NODE is a function node or an object literal.
7336 VAR, if non-nil, is the expression that NODE is being assigned to.
7337 When passed arguments of wrong type, does nothing."
7338 (when js2-parse-ide-mode
7339 (let ((fun-p (js2-function-node-p node))
7340 qname fname-node)
7341 (cond
7342 ;; non-anonymous function declaration?
7343 ((and fun-p
7344 (not var)
7345 (setq fname-node (js2-function-node-name node)))
7346 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7347 ;; for remaining forms, compute left-side tree branch first
7348 ((and var (setq qname (js2-compute-nested-prop-get var)))
7349 (cond
7350 ;; foo.bar.baz = function
7351 (fun-p
7352 (js2-record-imenu-entry node qname (js2-node-pos node)))
7353 ;; foo.bar.baz = object-literal
7354 ;; look for nested functions: {a: {b: function() {...} }}
7355 ((js2-object-node-p node)
7356 ;; Node position here is still absolute, since the parser
7357 ;; passes the assignment target and value expressions
7358 ;; to us before they are added as children of the assignment node.
7359 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7360
7361 (defun js2-compute-nested-prop-get (node)
7362 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7363 component nodes as a list. Otherwise return nil. Element-gets are treated
7364 as property-gets if the index expression is a string, or a positive integer."
7365 (let (left right head)
7366 (cond
7367 ((or (js2-name-node-p node)
7368 (js2-this-or-super-node-p node))
7369 (list node))
7370 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7371 ((js2-prop-get-node-p node) ; foo.bar
7372 (setq left (js2-prop-get-node-left node)
7373 right (js2-prop-get-node-right node))
7374 (if (setq head (js2-compute-nested-prop-get left))
7375 (nconc head (list right))))
7376 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7377 (setq left (js2-elem-get-node-target node)
7378 right (js2-elem-get-node-element node))
7379 (if (or (js2-string-node-p right) ; ['bar']
7380 (and (js2-number-node-p right) ; [10]
7381 (string-match "^[0-9]+$"
7382 (js2-number-node-value right))))
7383 (if (setq head (js2-compute-nested-prop-get left))
7384 (nconc head (list right))))))))
7385
7386 (defun js2-record-object-literal (node qname pos)
7387 "Recursively process an object literal looking for functions.
7388 NODE is an object literal that is the right-hand child of an assignment
7389 expression. QNAME is a list of nodes representing the assignment target,
7390 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7391 POS is the absolute position of the node.
7392 We do a depth-first traversal of NODE. For any functions we find,
7393 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7394 (let (right)
7395 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7396 (let ((left (js2-infix-node-left e))
7397 ;; Element positions are relative to the parent position.
7398 (pos (+ pos (js2-node-pos e))))
7399 (cond
7400 ;; foo: function() {...}
7401 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7402 (when (js2-prop-node-name left)
7403 ;; As a policy decision, we record the position of the property,
7404 ;; not the position of the `function' keyword, since the property
7405 ;; is effectively the name of the function.
7406 (js2-record-imenu-entry right (append qname (list left)) pos)))
7407 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7408 ((js2-object-node-p right)
7409 (js2-record-object-literal right
7410 (append qname (list (js2-infix-node-left e)))
7411 (+ pos (js2-node-pos right)))))))))
7412
7413 (defun js2-node-top-level-decl-p (node)
7414 "Return t if NODE's name is defined in the top-level scope.
7415 Also returns t if NODE's name is not defined in any scope, since it implies
7416 that it's an external variable, which must also be in the top-level scope."
7417 (let* ((name (js2-prop-node-name node))
7418 (this-scope (js2-node-get-enclosing-scope node))
7419 defining-scope)
7420 (cond
7421 ((js2-this-or-super-node-p node)
7422 nil)
7423 ((null this-scope)
7424 t)
7425 ((setq defining-scope (js2-get-defining-scope this-scope name))
7426 (js2-ast-root-p defining-scope))
7427 (t t))))
7428
7429 (defun js2-wrapper-function-p (node)
7430 "Return t if NODE is a function expression that's immediately invoked.
7431 NODE must be `js2-function-node'."
7432 (let ((parent (js2-node-parent node)))
7433 (or
7434 ;; function(){...}();
7435 (and (js2-call-node-p parent)
7436 (eq node (js2-call-node-target parent)))
7437 (and (js2-paren-node-p parent)
7438 ;; (function(){...})();
7439 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7440 ;; (function(){...}).call(this);
7441 (and (js2-prop-get-node-p parent)
7442 (member (js2-name-node-name (js2-prop-get-node-right parent))
7443 '("call" "apply"))
7444 (js2-call-node-p (js2-node-parent parent))))))))
7445
7446 (defun js2-browse-postprocess-chains ()
7447 "Modify function-declaration name chains after parsing finishes.
7448 Some of the information is only available after the parse tree is complete.
7449 For instance, processing a nested scope requires a parent function node."
7450 (let (result fn parent-qname p elem)
7451 (dolist (entry js2-imenu-recorder)
7452 ;; function node goes first
7453 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7454 ;; Examine head's defining scope:
7455 ;; Pre-processed chain, or top-level/external, keep as-is.
7456 (if (or (stringp head) (js2-node-top-level-decl-p head))
7457 (push chain result)
7458 (when (js2-this-or-super-node-p head)
7459 (setq chain (cdr chain))) ; discard this-node
7460 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7461 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7462 (when (eq parent-qname 'not-found)
7463 ;; anonymous function expressions are not recorded
7464 ;; during the parse, so we need to handle this case here
7465 (setq parent-qname
7466 (if (js2-wrapper-function-p fn)
7467 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7468 (if (js2-ast-root-p grandparent)
7469 nil
7470 (gethash grandparent js2-imenu-function-map 'skip)))
7471 'skip))
7472 (puthash fn parent-qname js2-imenu-function-map))
7473 (if (eq parent-qname 'skip)
7474 ;; We don't show it, let's record that fact.
7475 (remhash current-fn js2-imenu-function-map)
7476 ;; Prepend parent fn qname to this chain.
7477 (let ((qname (append parent-qname chain)))
7478 (puthash current-fn (butlast qname) js2-imenu-function-map)
7479 (push qname result)))))))
7480 ;; Collect chains obtained by third-party code.
7481 (let (js2-imenu-recorder)
7482 (run-hooks 'js2-build-imenu-callbacks)
7483 (dolist (entry js2-imenu-recorder)
7484 (push (cdr entry) result)))
7485 ;; Finally replace each node in each chain with its name.
7486 (dolist (chain result)
7487 (setq p chain)
7488 (while p
7489 (if (js2-node-p (setq elem (car p)))
7490 (setcar p (js2-node-qname-component elem)))
7491 (setq p (cdr p))))
7492 result))
7493
7494 ;; Merge name chains into a trie-like tree structure of nested lists.
7495 ;; To simplify construction of the trie, we first build it out using the rule
7496 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7497 ;; [key, num-or-list]. The second element can be a number; if so, this key
7498 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7499 ;; associated with the key at this level.) Otherwise the second element is
7500 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7501 ;; a simple recursive formulation.
7502 ;;
7503 ;; js2-mode is building the data structure for imenu. The imenu documentation
7504 ;; claims that it's the structure above, but in practice it wants the children
7505 ;; at the same list level as the key for that level, which is how I've drawn
7506 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7507 ;; list wrapper around the children at each level.
7508 ;;
7509 ;; A completed nested imenu-alist entry looks like this:
7510 ;; '(("foo"
7511 ;; ("<definition>" . 7)
7512 ;; ("bar"
7513 ;; ("a" . 40)
7514 ;; ("b" . 60))))
7515 ;;
7516 ;; In particular, the documentation for `imenu--index-alist' says that
7517 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7518 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7519
7520 (defun js2-treeify (lst)
7521 "Convert (a b c d) to (a ((b ((c d)))))."
7522 (if (null (cddr lst)) ; list length <= 2
7523 lst
7524 (list (car lst) (list (js2-treeify (cdr lst))))))
7525
7526 (defun js2-build-alist-trie (chains trie)
7527 "Merge declaration name chains into a trie-like alist structure for imenu.
7528 CHAINS is the qname chain list produced during parsing. TRIE is a
7529 list of elements built up so far."
7530 (let (head tail pos branch kids)
7531 (dolist (chain chains)
7532 (setq head (car chain)
7533 tail (cdr chain)
7534 pos (if (numberp (car tail)) (car tail))
7535 branch (js2-find-if (lambda (n)
7536 (string= (car n) head))
7537 trie)
7538 kids (cl-second branch))
7539 (cond
7540 ;; case 1: this key isn't in the trie yet
7541 ((null branch)
7542 (if trie
7543 (setcdr (last trie) (list (js2-treeify chain)))
7544 (setq trie (list (js2-treeify chain)))))
7545 ;; case 2: key is present with a single number entry: replace w/ list
7546 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7547 ;; ("<definition>" 20)))
7548 ((numberp kids)
7549 (setcar (cdr branch)
7550 (list (list "<definition-1>" kids)
7551 (if pos
7552 (list "<definition-2>" pos)
7553 (js2-treeify tail)))))
7554 ;; case 3: key is there (with kids), and we're a number entry
7555 (pos
7556 (setcdr (last kids)
7557 (list
7558 (list (format "<definition-%d>"
7559 (1+ (cl-loop for kid in kids
7560 count (eq ?< (aref (car kid) 0)))))
7561 pos))))
7562 ;; case 4: key is there with kids, need to merge in our chain
7563 (t
7564 (js2-build-alist-trie (list tail) kids))))
7565 trie))
7566
7567 (defun js2-flatten-trie (trie)
7568 "Convert TRIE to imenu-format.
7569 Recurses through nodes, and for each one whose second element is a list,
7570 appends the list's flattened elements to the current element. Also
7571 changes the tails into conses. For instance, this pre-flattened trie
7572
7573 '(a ((b 20)
7574 (c ((d 30)
7575 (e 40)))))
7576
7577 becomes
7578
7579 '(a (b . 20)
7580 (c (d . 30)
7581 (e . 40)))
7582
7583 Note that the root of the trie has no key, just a list of chains.
7584 This is also true for the value of any key with multiple children,
7585 e.g. key 'c' in the example above."
7586 (cond
7587 ((listp (car trie))
7588 (mapcar #'js2-flatten-trie trie))
7589 (t
7590 (if (numberp (cl-second trie))
7591 (cons (car trie) (cl-second trie))
7592 ;; else pop list and append its kids
7593 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7594
7595 (defun js2-build-imenu-index ()
7596 "Turn `js2-imenu-recorder' into an imenu data structure."
7597 (when (eq js2-imenu-recorder 'empty)
7598 (setq js2-imenu-recorder nil))
7599 (let* ((chains (js2-browse-postprocess-chains))
7600 (result (js2-build-alist-trie chains nil)))
7601 (js2-flatten-trie result)))
7602
7603 (defun js2-test-print-chains (chains)
7604 "Print a list of qname chains.
7605 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7606 i.e. one or more nodes, and an integer position as the list tail."
7607 (mapconcat (lambda (chain)
7608 (concat "("
7609 (mapconcat (lambda (elem)
7610 (if (js2-node-p elem)
7611 (or (js2-node-qname-component elem)
7612 "nil")
7613 (number-to-string elem)))
7614 chain
7615 " ")
7616 ")"))
7617 chains
7618 "\n"))
7619
7620 ;;; Parser
7621
7622 (defconst js2-version "1.8.5"
7623 "Version of JavaScript supported.")
7624
7625 (defun js2-record-face (face &optional token)
7626 "Record a style run of FACE for TOKEN or the current token."
7627 (unless token (setq token (js2-current-token)))
7628 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7629
7630 (defsubst js2-node-end (n)
7631 "Computes the absolute end of node N.
7632 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7633 is only true until the node is added to its parent; i.e., while parsing."
7634 (+ (js2-node-pos n)
7635 (js2-node-len n)))
7636
7637 (defun js2-record-comment (token)
7638 "Record a comment in `js2-scanned-comments'."
7639 (let ((ct (js2-token-comment-type token))
7640 (beg (js2-token-beg token))
7641 (end (js2-token-end token)))
7642 (push (make-js2-comment-node :len (- end beg)
7643 :format ct)
7644 js2-scanned-comments)
7645 (when js2-parse-ide-mode
7646 (js2-record-face (if (eq ct 'jsdoc)
7647 'font-lock-doc-face
7648 'font-lock-comment-face)
7649 token)
7650 (when (memq ct '(html preprocessor))
7651 ;; Tell cc-engine the bounds of the comment.
7652 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7653
7654 (defun js2-peek-token ()
7655 "Return the next token type without consuming it.
7656 If `js2-ti-lookahead' is positive, return the type of next token
7657 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7658 (if (not (zerop js2-ti-lookahead))
7659 (js2-token-type
7660 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7661 (let ((tt (js2-get-token-internal nil)))
7662 (js2-unget-token)
7663 tt)))
7664
7665 (defalias 'js2-next-token 'js2-get-token)
7666
7667 (defun js2-match-token (match &optional dont-unget)
7668 "Get next token and return t if it matches MATCH, a bytecode.
7669 Returns nil and consumes nothing if MATCH is not the next token."
7670 (if (/= (js2-get-token) match)
7671 (ignore (unless dont-unget (js2-unget-token)))
7672 t))
7673
7674 (defun js2-match-contextual-kwd (name)
7675 "Consume and return t if next token is `js2-NAME', and its
7676 string is NAME. Returns nil and keeps current token otherwise."
7677 (if (or (/= (js2-get-token) js2-NAME)
7678 (not (string= (js2-current-token-string) name)))
7679 (progn
7680 (js2-unget-token)
7681 nil)
7682 (js2-record-face 'font-lock-keyword-face)
7683 t))
7684
7685 (defun js2-get-prop-name-token ()
7686 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7687
7688 (defun js2-match-prop-name ()
7689 "Consume token and return t if next token is a valid property name.
7690 If `js2-language-version' is >= 180, a keyword or reserved word
7691 is considered valid name as well."
7692 (if (eq js2-NAME (js2-get-prop-name-token))
7693 t
7694 (js2-unget-token)
7695 nil))
7696
7697 (defun js2-must-match-prop-name (msg-id &optional pos len)
7698 (if (js2-match-prop-name)
7699 t
7700 (js2-report-error msg-id nil pos len)
7701 nil))
7702
7703 (defun js2-peek-token-or-eol ()
7704 "Return js2-EOL if the next token immediately follows a newline.
7705 Else returns the next token. Used in situations where we don't
7706 consider certain token types valid if they are preceded by a newline.
7707 One example is the postfix ++ or -- operator, which has to be on the
7708 same line as its operand."
7709 (let ((tt (js2-get-token))
7710 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7711 (js2-unget-token)
7712 (if follows-eol
7713 js2-EOL
7714 tt)))
7715
7716 (defun js2-must-match (token msg-id &optional pos len)
7717 "Match next token to token code TOKEN, or record a syntax error.
7718 MSG-ID is the error message to report if the match fails.
7719 Returns t on match, nil if no match."
7720 (if (js2-match-token token t)
7721 t
7722 (js2-report-error msg-id nil pos len)
7723 (js2-unget-token)
7724 nil))
7725
7726 (defun js2-must-match-name (msg-id)
7727 (if (js2-match-token js2-NAME t)
7728 t
7729 (if (eq (js2-current-token-type) js2-RESERVED)
7730 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7731 (js2-report-error msg-id)
7732 (js2-unget-token))
7733 nil))
7734
7735 (defsubst js2-inside-function ()
7736 (cl-plusp js2-nesting-of-function))
7737
7738 (defun js2-set-requires-activation ()
7739 (if (js2-function-node-p js2-current-script-or-fn)
7740 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7741
7742 (defun js2-check-activation-name (name _token)
7743 (when (js2-inside-function)
7744 ;; skip language-version 1.2 check from Rhino
7745 (if (or (string= "arguments" name)
7746 (and js2-compiler-activation-names ; only used in codegen
7747 (gethash name js2-compiler-activation-names)))
7748 (js2-set-requires-activation))))
7749
7750 (defun js2-set-is-generator ()
7751 (let ((fn-node js2-current-script-or-fn))
7752 (when (and (js2-function-node-p fn-node)
7753 (not (js2-function-node-generator-type fn-node)))
7754 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7755
7756 (defun js2-must-have-xml ()
7757 (unless js2-compiler-xml-available
7758 (js2-report-error "msg.XML.not.available")))
7759
7760 (defun js2-push-scope (scope)
7761 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7762 (cl-assert (js2-scope-p scope))
7763 (cl-assert (null (js2-scope-parent-scope scope)))
7764 (cl-assert (not (eq js2-current-scope scope)))
7765 (setf (js2-scope-parent-scope scope) js2-current-scope
7766 js2-current-scope scope))
7767
7768 (defsubst js2-pop-scope ()
7769 (setq js2-current-scope
7770 (js2-scope-parent-scope js2-current-scope)))
7771
7772 (defun js2-enter-loop (loop-node)
7773 (push loop-node js2-loop-set)
7774 (push loop-node js2-loop-and-switch-set)
7775 (js2-push-scope loop-node)
7776 ;; Tell the current labeled statement (if any) its statement,
7777 ;; and set the jump target of the first label to the loop.
7778 ;; These are used in `js2-parse-continue' to verify that the
7779 ;; continue target is an actual labeled loop. (And for codegen.)
7780 (when js2-labeled-stmt
7781 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7782 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7783 js2-labeled-stmt))) loop-node)))
7784
7785 (defun js2-exit-loop ()
7786 (pop js2-loop-set)
7787 (pop js2-loop-and-switch-set)
7788 (js2-pop-scope))
7789
7790 (defsubst js2-enter-switch (switch-node)
7791 (push switch-node js2-loop-and-switch-set))
7792
7793 (defsubst js2-exit-switch ()
7794 (pop js2-loop-and-switch-set))
7795
7796 (defsubst js2-get-directive (node)
7797 "Return NODE's value if it is a directive, nil otherwise.
7798
7799 A directive is an otherwise-meaningless expression statement
7800 consisting of a string literal, such as \"use strict\"."
7801 (and (js2-expr-stmt-node-p node)
7802 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7803 (js2-string-node-value node)))
7804
7805 (defun js2-parse (&optional buf cb)
7806 "Tell the js2 parser to parse a region of JavaScript.
7807
7808 BUF is a buffer or buffer name containing the code to parse.
7809 Call `narrow-to-region' first to parse only part of the buffer.
7810
7811 The returned AST root node is given some additional properties:
7812 `node-count' - total number of nodes in the AST
7813 `buffer' - BUF. The buffer it refers to may change or be killed,
7814 so the value is not necessarily reliable.
7815
7816 An optional callback CB can be specified to report parsing
7817 progress. If `(functionp CB)' returns t, it will be called with
7818 the current line number once before parsing begins, then again
7819 each time the lexer reaches a new line number.
7820
7821 CB can also be a list of the form `(symbol cb ...)' to specify
7822 multiple callbacks with different criteria. Each symbol is a
7823 criterion keyword, and the following element is the callback to
7824 call
7825
7826 :line - called whenever the line number changes
7827 :token - called for each new token consumed
7828
7829 The list of criteria could be extended to include entering or
7830 leaving a statement, an expression, or a function definition."
7831 (if (and cb (not (functionp cb)))
7832 (error "criteria callbacks not yet implemented"))
7833 (let ((inhibit-point-motion-hooks t)
7834 (js2-compiler-xml-available (>= js2-language-version 160))
7835 ;; This is a recursive-descent parser, so give it a big stack.
7836 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7837 (max-specpdl-size (max max-specpdl-size 3000))
7838 (case-fold-search nil)
7839 ast)
7840 (with-current-buffer (or buf (current-buffer))
7841 (setq js2-scanned-comments nil
7842 js2-parsed-errors nil
7843 js2-parsed-warnings nil
7844 js2-imenu-recorder nil
7845 js2-imenu-function-map nil
7846 js2-label-set nil)
7847 (js2-init-scanner)
7848 (setq ast (js2-do-parse))
7849 (unless js2-ts-hit-eof
7850 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7851 (setf (js2-ast-root-errors ast) js2-parsed-errors
7852 (js2-ast-root-warnings ast) js2-parsed-warnings)
7853 ;; if we didn't find any declarations, put a dummy in this list so we
7854 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7855 (unless js2-imenu-recorder
7856 (setq js2-imenu-recorder 'empty))
7857 (run-hooks 'js2-parse-finished-hook)
7858 ast)))
7859
7860 ;; Corresponds to Rhino's Parser.parse() method.
7861 (defun js2-do-parse ()
7862 "Parse current buffer starting from current point.
7863 Scanner should be initialized."
7864 (let ((pos js2-ts-cursor)
7865 (end js2-ts-cursor) ; in case file is empty
7866 root n tt
7867 (in-directive-prologue t)
7868 (js2-in-use-strict-directive js2-in-use-strict-directive)
7869 directive)
7870 ;; initialize buffer-local parsing vars
7871 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7872 js2-current-script-or-fn root
7873 js2-current-scope root
7874 js2-nesting-of-function 0
7875 js2-labeled-stmt nil
7876 js2-recorded-identifiers nil ; for js2-highlight
7877 js2-in-use-strict-directive nil)
7878 (while (/= (setq tt (js2-get-token)) js2-EOF)
7879 (if (= tt js2-FUNCTION)
7880 (progn
7881 (setq n (if js2-called-by-compile-function
7882 (js2-parse-function-expr)
7883 (js2-parse-function-stmt))))
7884 ;; not a function - parse a statement
7885 (js2-unget-token)
7886 (setq n (js2-parse-statement))
7887 (when in-directive-prologue
7888 (setq directive (js2-get-directive n))
7889 (cond
7890 ((null directive)
7891 (setq in-directive-prologue nil))
7892 ((string= directive "use strict")
7893 (setq js2-in-use-strict-directive t)))))
7894 ;; add function or statement to script
7895 (setq end (js2-node-end n))
7896 (js2-block-node-push root n))
7897 ;; add comments to root in lexical order
7898 (when js2-scanned-comments
7899 ;; if we find a comment beyond end of normal kids, use its end
7900 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7901 (dolist (comment js2-scanned-comments)
7902 (push comment (js2-ast-root-comments root))
7903 (js2-node-add-children root comment)))
7904 (setf (js2-node-len root) (- end pos))
7905 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7906 ;; Give extensions a chance to muck with things before highlighting starts.
7907 (let ((js2-additional-externs js2-additional-externs))
7908 (save-excursion
7909 (run-hooks 'js2-post-parse-callbacks))
7910 (js2-highlight-undeclared-vars))
7911 root))
7912
7913 (defun js2-parse-function-closure-body (fn-node)
7914 "Parse a JavaScript 1.8 function closure body."
7915 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7916 (if js2-ts-hit-eof
7917 (js2-report-error "msg.no.brace.body" nil
7918 (js2-node-pos fn-node)
7919 (- js2-ts-cursor (js2-node-pos fn-node)))
7920 (js2-node-add-children fn-node
7921 (setf (js2-function-node-body fn-node)
7922 (js2-parse-expr t))))))
7923
7924 (defun js2-parse-function-body (fn-node)
7925 (js2-must-match js2-LC "msg.no.brace.body"
7926 (js2-node-pos fn-node)
7927 (- js2-ts-cursor (js2-node-pos fn-node)))
7928 (let ((pos (js2-current-token-beg)) ; LC position
7929 (pn (make-js2-block-node)) ; starts at LC position
7930 tt
7931 end
7932 not-in-directive-prologue
7933 node
7934 directive)
7935 (cl-incf js2-nesting-of-function)
7936 (unwind-protect
7937 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7938 (= tt js2-EOF)
7939 (= tt js2-RC)))
7940 (js2-block-node-push
7941 pn
7942 (if (/= tt js2-FUNCTION)
7943 (if not-in-directive-prologue
7944 (js2-parse-statement)
7945 (setq node (js2-parse-statement)
7946 directive (js2-get-directive node))
7947 (cond
7948 ((null directive)
7949 (setq not-in-directive-prologue t))
7950 ((string= directive "use strict")
7951 ;; Back up and reparse the function, because new rules apply
7952 ;; to the function name and parameters.
7953 (when (not js2-in-use-strict-directive)
7954 (setq js2-in-use-strict-directive t)
7955 (throw 'reparse t))))
7956 node)
7957 (js2-get-token)
7958 (js2-parse-function-stmt))))
7959 (cl-decf js2-nesting-of-function))
7960 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7961 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7962 (setq end (js2-current-token-end)))
7963 (setf (js2-node-pos pn) pos
7964 (js2-node-len pn) (- end pos))
7965 (setf (js2-function-node-body fn-node) pn)
7966 (js2-node-add-children fn-node pn)
7967 pn))
7968
7969 (defun js2-define-destruct-symbols-internal
7970 (node decl-type face &optional ignore-not-in-block name-nodes)
7971 "Internal version of `js2-define-destruct-symbols'. The only
7972 difference is that NAME-NODES is passed down recursively."
7973 (cond
7974 ((js2-name-node-p node)
7975 (let (leftpos)
7976 (js2-define-symbol decl-type (js2-name-node-name node)
7977 node ignore-not-in-block)
7978 (when face
7979 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7980 (+ leftpos (js2-node-len node))
7981 face 'record))
7982 (setq name-nodes (append name-nodes (list node)))))
7983 ((js2-object-node-p node)
7984 (dolist (elem (js2-object-node-elems node))
7985 (setq name-nodes
7986 (append name-nodes
7987 (js2-define-destruct-symbols-internal
7988 ;; In abbreviated destructuring {a, b}, right == left.
7989 (js2-object-prop-node-right elem)
7990 decl-type face ignore-not-in-block name-nodes)))))
7991 ((js2-array-node-p node)
7992 (dolist (elem (js2-array-node-elems node))
7993 (when elem
7994 (setq name-nodes
7995 (append name-nodes
7996 (js2-define-destruct-symbols-internal
7997 elem decl-type face ignore-not-in-block name-nodes))))))
7998 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7999 (js2-node-len node))))
8000 name-nodes)
8001
8002 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8003 "Declare and fontify destructuring parameters inside NODE.
8004 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8005
8006 Return a list of `js2-name-node' nodes representing the symbols
8007 declared; probably to check them for errors."
8008 (js2-define-destruct-symbols-internal node decl-type face ignore-not-in-block))
8009
8010 (defvar js2-illegal-strict-identifiers
8011 '("eval" "arguments")
8012 "Identifiers not allowed as variables in strict mode.")
8013
8014 (defun js2-check-strict-identifier (name-node)
8015 "Check that NAME-NODE makes a legal strict mode identifier."
8016 (when js2-in-use-strict-directive
8017 (let ((param-name (js2-name-node-name name-node)))
8018 (when (member param-name js2-illegal-strict-identifiers)
8019 (js2-report-error "msg.bad.id.strict" param-name
8020 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8021
8022 (defun js2-check-strict-function-params (preceding-params params)
8023 "Given PRECEDING-PARAMS in a function's parameter list, check
8024 for strict mode errors caused by PARAMS."
8025 (when js2-in-use-strict-directive
8026 (dolist (param params)
8027 (let ((param-name (js2-name-node-name param)))
8028 (js2-check-strict-identifier param)
8029 (when (cl-some (lambda (param)
8030 (string= (js2-name-node-name param) param-name))
8031 preceding-params)
8032 (js2-report-error "msg.dup.param.strict" param-name
8033 (js2-node-abs-pos param) (js2-node-len param)))))))
8034
8035 (defun js2-parse-function-params (function-type fn-node pos)
8036 "Parse the parameters of a function of FUNCTION-TYPE
8037 represented by FN-NODE at POS."
8038 (if (js2-match-token js2-RP)
8039 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8040 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8041 (eq (js2-current-token-type) js2-NAME)))
8042 params param
8043 param-name-nodes new-param-name-nodes
8044 default-found rest-param-at)
8045 (when paren-free-arrow
8046 (js2-unget-token))
8047 (cl-loop for tt = (js2-peek-token)
8048 do
8049 (cond
8050 ;; destructuring param
8051 ((and (not paren-free-arrow)
8052 (or (= tt js2-LB) (= tt js2-LC)))
8053 (js2-get-token)
8054 (when default-found
8055 (js2-report-error "msg.no.default.after.default.param"))
8056 (setq param (js2-parse-destruct-primary-expr)
8057 new-param-name-nodes (js2-define-destruct-symbols
8058 param js2-LP 'js2-function-param))
8059 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8060 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8061 (push param params))
8062 ;; variable name
8063 (t
8064 (when (and (>= js2-language-version 200)
8065 (not paren-free-arrow)
8066 (js2-match-token js2-TRIPLEDOT)
8067 (not rest-param-at))
8068 ;; to report errors if there are more parameters
8069 (setq rest-param-at (length params)))
8070 (js2-must-match-name "msg.no.parm")
8071 (js2-record-face 'js2-function-param)
8072 (setq param (js2-create-name-node))
8073 (js2-define-symbol js2-LP (js2-current-token-string) param)
8074 (js2-check-strict-function-params param-name-nodes (list param))
8075 (setq param-name-nodes (append param-name-nodes (list param)))
8076 ;; default parameter value
8077 (when (or (and default-found
8078 (not rest-param-at)
8079 (js2-must-match js2-ASSIGN
8080 "msg.no.default.after.default.param"
8081 (js2-node-pos param)
8082 (js2-node-len param)))
8083 (and (>= js2-language-version 200)
8084 (js2-match-token js2-ASSIGN)))
8085 (cl-assert (not paren-free-arrow))
8086 (let* ((pos (js2-node-pos param))
8087 (tt (js2-current-token-type))
8088 (op-pos (- (js2-current-token-beg) pos))
8089 (left param)
8090 (right (js2-parse-assign-expr))
8091 (len (- (js2-node-end right) pos)))
8092 (setq param (make-js2-assign-node
8093 :type tt :pos pos :len len :op-pos op-pos
8094 :left left :right right)
8095 default-found t)
8096 (js2-node-add-children param left right)))
8097 (push param params)))
8098 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8099 (js2-report-error "msg.param.after.rest" nil
8100 (js2-node-pos param) (js2-node-len param)))
8101 while
8102 (js2-match-token js2-COMMA))
8103 (when (and (not paren-free-arrow)
8104 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8105 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8106 (when rest-param-at
8107 (setf (js2-function-node-rest-p fn-node) t))
8108 (dolist (p params)
8109 (js2-node-add-children fn-node p)
8110 (push p (js2-function-node-params fn-node))))))
8111
8112 (defun js2-check-inconsistent-return-warning (fn-node name)
8113 "Possibly show inconsistent-return warning.
8114 Last token scanned is the close-curly for the function body."
8115 (when (and js2-mode-show-strict-warnings
8116 js2-strict-inconsistent-return-warning
8117 (not (js2-has-consistent-return-usage
8118 (js2-function-node-body fn-node))))
8119 ;; Have it extend from close-curly to bol or beginning of block.
8120 (let ((pos (save-excursion
8121 (goto-char (js2-current-token-end))
8122 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8123 (point-at-bol))))
8124 (end (js2-current-token-end)))
8125 (if (cl-plusp (js2-name-node-length name))
8126 (js2-add-strict-warning "msg.no.return.value"
8127 (js2-name-node-name name) pos end)
8128 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8129
8130 (defun js2-parse-function-stmt ()
8131 (let ((pos (js2-current-token-beg))
8132 (star-p (js2-match-token js2-MUL)))
8133 (js2-must-match-name "msg.unnamed.function.stmt")
8134 (let ((name (js2-create-name-node t))
8135 pn member-expr)
8136 (cond
8137 ((js2-match-token js2-LP)
8138 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8139 (js2-allow-member-expr-as-function-name
8140 (setq member-expr (js2-parse-member-expr-tail nil name))
8141 (js2-parse-highlight-member-expr-fn-name member-expr)
8142 (js2-must-match js2-LP "msg.no.paren.parms")
8143 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8144 (js2-function-node-member-expr pn) member-expr)
8145 pn)
8146 (t
8147 (js2-report-error "msg.no.paren.parms")
8148 (make-js2-error-node))))))
8149
8150 (defun js2-parse-function-expr ()
8151 (let ((pos (js2-current-token-beg))
8152 (star-p (js2-match-token js2-MUL))
8153 name)
8154 (when (js2-match-token js2-NAME)
8155 (setq name (js2-create-name-node t)))
8156 (js2-must-match js2-LP "msg.no.paren.parms")
8157 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8158
8159 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8160 (let (fn-node lp)
8161 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8162 (setq lp (js2-current-token-beg)))
8163 (setf fn-node (make-js2-function-node :pos pos
8164 :name name
8165 :form function-type
8166 :lp (if lp (- lp pos))
8167 :generator-type (and star-p 'STAR)))
8168 (when name
8169 (js2-set-face (js2-node-pos name) (js2-node-end name)
8170 'font-lock-function-name-face 'record)
8171 (when (and (eq function-type 'FUNCTION_STATEMENT)
8172 (cl-plusp (js2-name-node-length name)))
8173 ;; Function statements define a symbol in the enclosing scope
8174 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8175 (when js2-in-use-strict-directive
8176 (js2-check-strict-identifier name)))
8177 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8178 ;; 1. Nested functions are not affected by the dynamic scope flag
8179 ;; as dynamic scope is already a parent of their scope.
8180 ;; 2. Functions defined under the with statement also immune to
8181 ;; this setup, in which case dynamic scope is ignored in favor
8182 ;; of the with object.
8183 (setf (js2-function-node-ignore-dynamic fn-node) t))
8184 ;; dynamically bind all the per-function variables
8185 (let ((js2-current-script-or-fn fn-node)
8186 (js2-current-scope fn-node)
8187 (js2-nesting-of-with 0)
8188 (js2-end-flags 0)
8189 js2-label-set
8190 js2-loop-set
8191 js2-loop-and-switch-set)
8192 (js2-parse-function-params function-type fn-node pos)
8193 (when (eq function-type 'FUNCTION_ARROW)
8194 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8195 (if (and (>= js2-language-version 180)
8196 (/= (js2-peek-token) js2-LC))
8197 (js2-parse-function-closure-body fn-node)
8198 (js2-parse-function-body fn-node))
8199 (js2-check-inconsistent-return-warning fn-node name)
8200
8201 (when name
8202 (js2-node-add-children fn-node name)
8203 ;; Function expressions define a name only in the body of the
8204 ;; function, and only if not hidden by a parameter name
8205 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8206 (null (js2-scope-get-symbol js2-current-scope
8207 (js2-name-node-name name))))
8208 (js2-define-symbol js2-FUNCTION
8209 (js2-name-node-name name)
8210 fn-node))
8211 (when (eq function-type 'FUNCTION_STATEMENT)
8212 (js2-record-imenu-functions fn-node))))
8213
8214 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8215 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8216 ;; We wait until after parsing the function to set its parent scope,
8217 ;; since `js2-define-symbol' needs the defining-scope check to stop
8218 ;; at the function boundary when checking for redeclarations.
8219 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8220 fn-node))
8221
8222 (defun js2-parse-function (function-type pos star-p &optional name)
8223 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8224 beginning of the first token (function keyword, unless it's an
8225 arrow function), NAME is js2-name-node."
8226 (let ((continue t)
8227 ts-state
8228 fn-node
8229 ;; Preserve strict state outside this function.
8230 (js2-in-use-strict-directive js2-in-use-strict-directive))
8231 ;; Parse multiple times if a new strict mode directive is discovered in the
8232 ;; function body, as new rules will be retroactively applied to the legality
8233 ;; of function names and parameters.
8234 (while continue
8235 (setq ts-state (make-js2-ts-state))
8236 (setq continue (catch 'reparse
8237 (setq fn-node (js2-parse-function-internal
8238 function-type pos star-p name))
8239 ;; Don't continue.
8240 nil))
8241 (when continue
8242 (js2-ts-seek ts-state)))
8243 fn-node))
8244
8245 (defun js2-parse-statements (&optional parent)
8246 "Parse a statement list. Last token consumed must be js2-LC.
8247
8248 PARENT can be a `js2-block-node', in which case the statements are
8249 appended to PARENT. Otherwise a new `js2-block-node' is created
8250 and returned.
8251
8252 This function does not match the closing js2-RC: the caller
8253 matches the RC so it can provide a suitable error message if not
8254 matched. This means it's up to the caller to set the length of
8255 the node to include the closing RC. The node start pos is set to
8256 the absolute buffer start position, and the caller should fix it
8257 up to be relative to the parent node. All children of this block
8258 node are given relative start positions and correct lengths."
8259 (let ((pn (or parent (make-js2-block-node)))
8260 tt)
8261 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8262 (/= tt js2-RC))
8263 (js2-block-node-push pn (js2-parse-statement)))
8264 pn))
8265
8266 (defun js2-parse-statement ()
8267 (let (pn beg end)
8268 ;; coarse-grained user-interrupt check - needs work
8269 (and js2-parse-interruptable-p
8270 (zerop (% (cl-incf js2-parse-stmt-count)
8271 js2-statements-per-pause))
8272 (input-pending-p)
8273 (throw 'interrupted t))
8274 (setq pn (js2-statement-helper))
8275 ;; no-side-effects warning check
8276 (unless (js2-node-has-side-effects pn)
8277 (setq end (js2-node-end pn))
8278 (save-excursion
8279 (goto-char end)
8280 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8281 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8282 pn))
8283
8284 ;; These correspond to the switch cases in Parser.statementHelper
8285 (defconst js2-parsers
8286 (let ((parsers (make-vector js2-num-tokens
8287 #'js2-parse-expr-stmt)))
8288 (aset parsers js2-BREAK #'js2-parse-break)
8289 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8290 (aset parsers js2-CONST #'js2-parse-const-var)
8291 (aset parsers js2-CONTINUE #'js2-parse-continue)
8292 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8293 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8294 (aset parsers js2-DO #'js2-parse-do)
8295 (aset parsers js2-EXPORT #'js2-parse-export)
8296 (aset parsers js2-FOR #'js2-parse-for)
8297 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8298 (aset parsers js2-IF #'js2-parse-if)
8299 (aset parsers js2-IMPORT #'js2-parse-import)
8300 (aset parsers js2-LC #'js2-parse-block)
8301 (aset parsers js2-LET #'js2-parse-let-stmt)
8302 (aset parsers js2-NAME #'js2-parse-name-or-label)
8303 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8304 (aset parsers js2-SEMI #'js2-parse-semi)
8305 (aset parsers js2-SWITCH #'js2-parse-switch)
8306 (aset parsers js2-THROW #'js2-parse-throw)
8307 (aset parsers js2-TRY #'js2-parse-try)
8308 (aset parsers js2-VAR #'js2-parse-const-var)
8309 (aset parsers js2-WHILE #'js2-parse-while)
8310 (aset parsers js2-WITH #'js2-parse-with)
8311 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8312 parsers)
8313 "A vector mapping token types to parser functions.")
8314
8315 (defun js2-parse-warn-missing-semi (beg end)
8316 (and js2-mode-show-strict-warnings
8317 js2-strict-missing-semi-warning
8318 (js2-add-strict-warning
8319 "msg.missing.semi" nil
8320 ;; back up to beginning of statement or line
8321 (max beg (save-excursion
8322 (goto-char end)
8323 (point-at-bol)))
8324 end)))
8325
8326 (defconst js2-no-semi-insertion
8327 (list js2-IF
8328 js2-SWITCH
8329 js2-WHILE
8330 js2-DO
8331 js2-FOR
8332 js2-TRY
8333 js2-WITH
8334 js2-LC
8335 js2-ERROR
8336 js2-SEMI
8337 js2-CLASS
8338 js2-FUNCTION
8339 js2-EXPORT)
8340 "List of tokens that don't do automatic semicolon insertion.")
8341
8342 (defconst js2-autoinsert-semi-and-warn
8343 (list js2-ERROR js2-EOF js2-RC))
8344
8345 (defun js2-statement-helper ()
8346 (let* ((tt (js2-get-token))
8347 (first-tt tt)
8348 (parser (if (= tt js2-ERROR)
8349 #'js2-parse-semi
8350 (aref js2-parsers tt)))
8351 pn)
8352 ;; If the statement is set, then it's been told its label by now.
8353 (and js2-labeled-stmt
8354 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8355 (setq js2-labeled-stmt nil))
8356 (setq pn (funcall parser))
8357 ;; Don't do auto semi insertion for certain statement types.
8358 (unless (or (memq first-tt js2-no-semi-insertion)
8359 (js2-labeled-stmt-node-p pn))
8360 (js2-auto-insert-semicolon pn))
8361 pn))
8362
8363 (defun js2-auto-insert-semicolon (pn)
8364 (let* ((tt (js2-get-token))
8365 (pos (js2-node-pos pn)))
8366 (cond
8367 ((= tt js2-SEMI)
8368 ;; extend the node bounds to include the semicolon.
8369 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8370 ((memq tt js2-autoinsert-semi-and-warn)
8371 (js2-unget-token) ; Not ';', do not consume.
8372 ;; Autoinsert ;
8373 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8374 (t
8375 (if (not (js2-token-follows-eol-p (js2-current-token)))
8376 ;; Report error if no EOL or autoinsert ';' otherwise
8377 (js2-report-error "msg.no.semi.stmt")
8378 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8379 (js2-unget-token) ; Not ';', do not consume.
8380 ))))
8381
8382 (defun js2-parse-condition ()
8383 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8384 The parens are discarded and the expression node is returned.
8385 The `pos' field of the return value is set to an absolute position
8386 that must be fixed up by the caller.
8387 Return value is a list (EXPR LP RP), with absolute paren positions."
8388 (let (pn lp rp)
8389 (if (js2-must-match js2-LP "msg.no.paren.cond")
8390 (setq lp (js2-current-token-beg)))
8391 (setq pn (js2-parse-expr))
8392 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8393 (setq rp (js2-current-token-beg)))
8394 ;; Report strict warning on code like "if (a = 7) ..."
8395 (if (and js2-strict-cond-assign-warning
8396 (js2-assign-node-p pn))
8397 (js2-add-strict-warning "msg.equal.as.assign" nil
8398 (js2-node-pos pn)
8399 (+ (js2-node-pos pn)
8400 (js2-node-len pn))))
8401 (list pn lp rp)))
8402
8403 (defun js2-parse-if ()
8404 "Parser for if-statement. Last matched token must be js2-IF."
8405 (let ((pos (js2-current-token-beg))
8406 cond if-true if-false else-pos end pn)
8407 (setq cond (js2-parse-condition)
8408 if-true (js2-parse-statement)
8409 if-false (if (js2-match-token js2-ELSE)
8410 (progn
8411 (setq else-pos (- (js2-current-token-beg) pos))
8412 (js2-parse-statement)))
8413 end (js2-node-end (or if-false if-true))
8414 pn (make-js2-if-node :pos pos
8415 :len (- end pos)
8416 :condition (car cond)
8417 :then-part if-true
8418 :else-part if-false
8419 :else-pos else-pos
8420 :lp (js2-relpos (cl-second cond) pos)
8421 :rp (js2-relpos (cl-third cond) pos)))
8422 (js2-node-add-children pn (car cond) if-true if-false)
8423 pn))
8424
8425 (defun js2-parse-import ()
8426 "Parse import statement. The current token must be js2-IMPORT."
8427 (unless (js2-ast-root-p js2-current-scope)
8428 (js2-report-error "msg.mod.import.decl.at.top.level"))
8429 (let ((beg (js2-current-token-beg)))
8430 (cond ((js2-match-token js2-STRING)
8431 (make-js2-import-node
8432 :pos beg
8433 :len (- (js2-current-token-end) beg)
8434 :module-id (js2-current-token-string)))
8435 (t
8436 (let* ((import-clause (js2-parse-import-clause))
8437 (from-clause (and import-clause (js2-parse-from-clause)))
8438 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8439 (node (make-js2-import-node
8440 :pos beg
8441 :len (- (js2-current-token-end) beg)
8442 :import import-clause
8443 :from from-clause
8444 :module-id module-id)))
8445 (when import-clause
8446 (js2-node-add-children node import-clause))
8447 (when from-clause
8448 (js2-node-add-children node from-clause))
8449 node)))))
8450
8451 (defun js2-parse-import-clause ()
8452 "Parse the bindings in an import statement.
8453 This can take many forms:
8454
8455 ImportedDefaultBinding -> 'foo'
8456 NameSpaceImport -> '* as lib'
8457 NamedImports -> '{foo as bar, bang}'
8458 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8459 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8460
8461 Try to match namespace imports and named imports first because nothing can
8462 come after them. If it is an imported default binding, then it could have named
8463 imports or a namespace import that follows it.
8464 "
8465 (let* ((beg (js2-current-token-beg))
8466 (clause (make-js2-import-clause-node
8467 :pos beg))
8468 (children (list)))
8469 (cond
8470 ((js2-match-token js2-MUL)
8471 (let ((ns-import (js2-parse-namespace-import)))
8472 (when ns-import
8473 (let ((name-node (js2-namespace-import-node-name ns-import)))
8474 (js2-define-symbol
8475 js2-LET (js2-name-node-name name-node) name-node t)))
8476 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8477 (push ns-import children)))
8478 ((js2-match-token js2-LC)
8479 (let ((imports (js2-parse-export-bindings t)))
8480 (setf (js2-import-clause-node-named-imports clause) imports)
8481 (dolist (import imports)
8482 (push import children)
8483 (let ((name-node (js2-export-binding-node-local-name import)))
8484 (when name-node
8485 (js2-define-symbol
8486 js2-LET (js2-name-node-name name-node) name-node t))))))
8487 ((= (js2-peek-token) js2-NAME)
8488 (let ((binding (js2-maybe-parse-export-binding)))
8489 (let ((node-name (js2-export-binding-node-local-name binding)))
8490 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8491 (setf (js2-import-clause-node-default-binding clause) binding)
8492 (push binding children))
8493 (when (js2-match-token js2-COMMA)
8494 (cond
8495 ((js2-match-token js2-MUL)
8496 (let ((ns-import (js2-parse-namespace-import)))
8497 (let ((name-node (js2-namespace-import-node-name ns-import)))
8498 (js2-define-symbol
8499 js2-LET (js2-name-node-name name-node) name-node t))
8500 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8501 (push ns-import children)))
8502 ((js2-match-token js2-LC)
8503 (let ((imports (js2-parse-export-bindings t)))
8504 (setf (js2-import-clause-node-named-imports clause) imports)
8505 (dolist (import imports)
8506 (push import children)
8507 (let ((name-node (js2-export-binding-node-local-name import)))
8508 (when name-node
8509 (js2-define-symbol
8510 js2-LET (js2-name-node-name name-node) name-node t))))))
8511 (t (js2-report-error "msg.syntax")))))
8512 (t (js2-report-error "msg.mod.declaration.after.import")))
8513 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8514 (apply #'js2-node-add-children clause children)
8515 clause))
8516
8517 (defun js2-parse-namespace-import ()
8518 "Parse a namespace import expression such as '* as bar'.
8519 The current token must be js2-MUL."
8520 (let ((beg (js2-current-token-beg)))
8521 (when (js2-must-match js2-NAME "msg.syntax")
8522 (if (equal "as" (js2-current-token-string))
8523 (when (js2-must-match-prop-name "msg.syntax")
8524 (let ((node (make-js2-namespace-import-node
8525 :pos beg
8526 :len (- (js2-current-token-end) beg)
8527 :name (make-js2-name-node
8528 :pos (js2-current-token-beg)
8529 :len (js2-current-token-end)
8530 :name (js2-current-token-string)))))
8531 (js2-node-add-children node (js2-namespace-import-node-name node))
8532 node))
8533 (js2-unget-token)
8534 (js2-report-error "msg.syntax")))))
8535
8536
8537 (defun js2-parse-from-clause ()
8538 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8539 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8540 (let ((beg (js2-current-token-beg)))
8541 (if (equal "from" (js2-current-token-string))
8542 (cond
8543 ((js2-match-token js2-STRING)
8544 (make-js2-from-clause-node
8545 :pos beg
8546 :len (- (js2-current-token-end) beg)
8547 :module-id (js2-current-token-string)
8548 :metadata-p nil))
8549 ((js2-match-token js2-THIS)
8550 (when (js2-must-match-name "msg.mod.spec.after.from")
8551 (if (equal "module" (js2-current-token-string))
8552 (make-js2-from-clause-node
8553 :pos beg
8554 :len (- (js2-current-token-end) beg)
8555 :module-id "this"
8556 :metadata-p t)
8557 (js2-unget-token)
8558 (js2-unget-token)
8559 (js2-report-error "msg.mod.spec.after.from")
8560 nil)))
8561 (t (js2-report-error "msg.mod.spec.after.from") nil))
8562 (js2-unget-token)
8563 (js2-report-error "msg.mod.from.after.import.spec.set")
8564 nil))))
8565
8566 (defun js2-parse-export-bindings (&optional import-p)
8567 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8568 {foo as bar, baz as bang}. The current token must be
8569 js2-LC. Return a lisp list of js2-export-binding-node"
8570 (let ((bindings (list)))
8571 (while
8572 (let ((binding (js2-maybe-parse-export-binding)))
8573 (when binding
8574 (push binding bindings))
8575 (js2-match-token js2-COMMA)))
8576 (when (js2-must-match js2-RC (if import-p
8577 "msg.mod.rc.after.import.spec.list"
8578 "msg.mod.rc.after.export.spec.list"))
8579 (reverse bindings))))
8580
8581 (defun js2-maybe-parse-export-binding ()
8582 "Attempt to parse a binding expression found inside an import/export statement.
8583 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8584 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8585 js2-export-binding-node and consume all the tokens. If it does not match, it
8586 consumes no tokens."
8587 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8588 (beg (js2-current-token-beg))
8589 (extern-name-len (js2-current-token-len))
8590 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8591 (aref js2-kwd-tokens (js2-current-token-type)))))
8592 (if extern-name
8593 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8594 (if (and as (equal "as" (js2-current-token-string)))
8595 (let ((name
8596 (or
8597 (and (js2-match-token js2-DEFAULT) "default")
8598 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8599 (if name
8600 (let ((node (make-js2-export-binding-node
8601 :pos beg
8602 :len (- (js2-current-token-end) beg)
8603 :local-name (make-js2-name-node
8604 :name name
8605 :pos (js2-current-token-beg)
8606 :len (js2-current-token-len))
8607 :extern-name (make-js2-name-node
8608 :name extern-name
8609 :pos beg
8610 :len extern-name-len))))
8611 (js2-node-add-children
8612 node
8613 (js2-export-binding-node-local-name node)
8614 (js2-export-binding-node-extern-name node))
8615 node)
8616 (js2-unget-token)
8617 nil))
8618 (when as (js2-unget-token))
8619 (let* ((name-node (make-js2-name-node
8620 :name (js2-current-token-string)
8621 :pos (js2-current-token-beg)
8622 :len (js2-current-token-len)))
8623 (node (make-js2-export-binding-node
8624 :pos (js2-current-token-beg)
8625 :len (js2-current-token-len)
8626 :local-name name-node
8627 :extern-name name-node)))
8628 (when is-reserved-name
8629 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8630 (js2-node-add-children node name-node)
8631 node)))
8632 nil)))
8633
8634 (defun js2-parse-switch ()
8635 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8636 (let ((pos (js2-current-token-beg))
8637 tt pn discriminant has-default case-expr case-node
8638 case-pos cases stmt lp)
8639 (if (js2-must-match js2-LP "msg.no.paren.switch")
8640 (setq lp (js2-current-token-beg)))
8641 (setq discriminant (js2-parse-expr)
8642 pn (make-js2-switch-node :discriminant discriminant
8643 :pos pos
8644 :lp (js2-relpos lp pos)))
8645 (js2-node-add-children pn discriminant)
8646 (js2-enter-switch pn)
8647 (unwind-protect
8648 (progn
8649 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8650 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8651 (js2-must-match js2-LC "msg.no.brace.switch")
8652 (catch 'break
8653 (while t
8654 (setq tt (js2-next-token)
8655 case-pos (js2-current-token-beg))
8656 (cond
8657 ((= tt js2-RC)
8658 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8659 (throw 'break nil)) ; done
8660 ((= tt js2-CASE)
8661 (setq case-expr (js2-parse-expr))
8662 (js2-must-match js2-COLON "msg.no.colon.case"))
8663 ((= tt js2-DEFAULT)
8664 (if has-default
8665 (js2-report-error "msg.double.switch.default"))
8666 (setq has-default t
8667 case-expr nil)
8668 (js2-must-match js2-COLON "msg.no.colon.case"))
8669 (t
8670 (js2-report-error "msg.bad.switch")
8671 (throw 'break nil)))
8672 (setq case-node (make-js2-case-node :pos case-pos
8673 :len (- (js2-current-token-end) case-pos)
8674 :expr case-expr))
8675 (js2-node-add-children case-node case-expr)
8676 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8677 (/= tt js2-CASE)
8678 (/= tt js2-DEFAULT)
8679 (/= tt js2-EOF))
8680 (setf stmt (js2-parse-statement)
8681 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8682 (js2-block-node-push case-node stmt))
8683 (push case-node cases)))
8684 ;; add cases last, as pushing reverses the order to be correct
8685 (dolist (kid cases)
8686 (js2-node-add-children pn kid)
8687 (push kid (js2-switch-node-cases pn)))
8688 pn) ; return value
8689 (js2-exit-switch))))
8690
8691 (defun js2-parse-while ()
8692 "Parser for while-statement. Last matched token must be js2-WHILE."
8693 (let ((pos (js2-current-token-beg))
8694 (pn (make-js2-while-node))
8695 cond body)
8696 (js2-enter-loop pn)
8697 (unwind-protect
8698 (progn
8699 (setf cond (js2-parse-condition)
8700 (js2-while-node-condition pn) (car cond)
8701 body (js2-parse-statement)
8702 (js2-while-node-body pn) body
8703 (js2-node-len pn) (- (js2-node-end body) pos)
8704 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8705 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8706 (js2-node-add-children pn body (car cond)))
8707 (js2-exit-loop))
8708 pn))
8709
8710 (defun js2-parse-do ()
8711 "Parser for do-statement. Last matched token must be js2-DO."
8712 (let ((pos (js2-current-token-beg))
8713 (pn (make-js2-do-node))
8714 cond body end)
8715 (js2-enter-loop pn)
8716 (unwind-protect
8717 (progn
8718 (setq body (js2-parse-statement))
8719 (js2-must-match js2-WHILE "msg.no.while.do")
8720 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8721 cond (js2-parse-condition)
8722 (js2-do-node-condition pn) (car cond)
8723 (js2-do-node-body pn) body
8724 end js2-ts-cursor
8725 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8726 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8727 (js2-node-add-children pn (car cond) body))
8728 (js2-exit-loop))
8729 ;; Always auto-insert semicolon to follow SpiderMonkey:
8730 ;; It is required by ECMAScript but is ignored by the rest of
8731 ;; world; see bug 238945
8732 (if (js2-match-token js2-SEMI)
8733 (setq end js2-ts-cursor))
8734 (setf (js2-node-len pn) (- end pos))
8735 pn))
8736
8737 (defun js2-parse-export ()
8738 "Parse an export statement.
8739 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8740 expressions should only be either hoistable expressions (function or generator)
8741 or assignment expressions, but there is no checking to enforce that and so it
8742 will parse without error a small subset of
8743 invalid export statements."
8744 (unless (js2-ast-root-p js2-current-scope)
8745 (js2-report-error "msg.mod.export.decl.at.top.level"))
8746 (let ((beg (js2-current-token-beg))
8747 (children (list))
8748 exports-list from-clause declaration default)
8749 (cond
8750 ((js2-match-token js2-MUL)
8751 (setq from-clause (js2-parse-from-clause))
8752 (when from-clause
8753 (push from-clause children)))
8754 ((js2-match-token js2-LC)
8755 (setq exports-list (js2-parse-export-bindings))
8756 (when exports-list
8757 (dolist (export exports-list)
8758 (push export children)))
8759 (when (js2-match-token js2-NAME)
8760 (if (equal "from" (js2-current-token-string))
8761 (progn
8762 (js2-unget-token)
8763 (setq from-clause (js2-parse-from-clause)))
8764 (js2-unget-token))))
8765 ((js2-match-token js2-DEFAULT)
8766 (setq default (js2-parse-expr)))
8767 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8768 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8769 (t
8770 (setq declaration (js2-parse-expr))))
8771 (when from-clause
8772 (push from-clause children))
8773 (when declaration
8774 (push declaration children)
8775 (when (not (js2-function-node-p declaration))
8776 (js2-auto-insert-semicolon declaration)))
8777 (when default
8778 (push default children)
8779 (when (not (js2-function-node-p default))
8780 (js2-auto-insert-semicolon default)))
8781 (let ((node (make-js2-export-node
8782 :pos beg
8783 :len (- (js2-current-token-end) beg)
8784 :exports-list exports-list
8785 :from-clause from-clause
8786 :declaration declaration
8787 :default default)))
8788 (apply #'js2-node-add-children node children)
8789 node)))
8790
8791 (defun js2-parse-for ()
8792 "Parse a for, for-in or for each-in statement.
8793 Last matched token must be js2-FOR."
8794 (let ((for-pos (js2-current-token-beg))
8795 (tmp-scope (make-js2-scope))
8796 pn is-for-each is-for-in-or-of is-for-of
8797 in-pos each-pos tmp-pos
8798 init ; Node init is also foo in 'foo in object'.
8799 cond ; Node cond is also object in 'foo in object'.
8800 incr ; 3rd section of for-loop initializer.
8801 body tt lp rp)
8802 ;; See if this is a for each () instead of just a for ()
8803 (when (js2-match-token js2-NAME)
8804 (if (string= "each" (js2-current-token-string))
8805 (progn
8806 (setq is-for-each t
8807 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8808 (js2-record-face 'font-lock-keyword-face))
8809 (js2-report-error "msg.no.paren.for")))
8810 (if (js2-must-match js2-LP "msg.no.paren.for")
8811 (setq lp (- (js2-current-token-beg) for-pos)))
8812 (setq tt (js2-get-token))
8813 ;; Capture identifiers inside parens. We can't create the node
8814 ;; (and use it as the current scope) until we know its type.
8815 (js2-push-scope tmp-scope)
8816 (unwind-protect
8817 (progn
8818 ;; parse init clause
8819 (let ((js2-in-for-init t)) ; set as dynamic variable
8820 (cond
8821 ((= tt js2-SEMI)
8822 (js2-unget-token)
8823 (setq init (make-js2-empty-expr-node)))
8824 ((or (= tt js2-VAR) (= tt js2-LET))
8825 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8826 (t
8827 (js2-unget-token)
8828 (setq init (js2-parse-expr)))))
8829 (if (or (js2-match-token js2-IN)
8830 (and (>= js2-language-version 200)
8831 (js2-match-contextual-kwd "of")
8832 (setq is-for-of t)))
8833 (setq is-for-in-or-of t
8834 in-pos (- (js2-current-token-beg) for-pos)
8835 ;; scope of iteration target object is not the scope we've created above.
8836 ;; stash current scope temporary.
8837 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8838 (js2-parse-expr))) ; object over which we're iterating
8839 ;; else ordinary for loop - parse cond and incr
8840 (js2-must-match js2-SEMI "msg.no.semi.for")
8841 (setq cond (if (= (js2-peek-token) js2-SEMI)
8842 (make-js2-empty-expr-node) ; no loop condition
8843 (js2-parse-expr)))
8844 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8845 (setq tmp-pos (js2-current-token-end)
8846 incr (if (= (js2-peek-token) js2-RP)
8847 (make-js2-empty-expr-node :pos tmp-pos)
8848 (js2-parse-expr)))))
8849 (js2-pop-scope))
8850 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8851 (setq rp (- (js2-current-token-beg) for-pos)))
8852 (if (not is-for-in-or-of)
8853 (setq pn (make-js2-for-node :init init
8854 :condition cond
8855 :update incr
8856 :lp lp
8857 :rp rp))
8858 ;; cond could be null if 'in obj' got eaten by the init node.
8859 (if (js2-infix-node-p init)
8860 ;; it was (foo in bar) instead of (var foo in bar)
8861 (setq cond (js2-infix-node-right init)
8862 init (js2-infix-node-left init))
8863 (if (and (js2-var-decl-node-p init)
8864 (> (length (js2-var-decl-node-kids init)) 1))
8865 (js2-report-error "msg.mult.index")))
8866 (setq pn (make-js2-for-in-node :iterator init
8867 :object cond
8868 :in-pos in-pos
8869 :foreach-p is-for-each
8870 :each-pos each-pos
8871 :forof-p is-for-of
8872 :lp lp
8873 :rp rp)))
8874 ;; Transplant the declarations.
8875 (setf (js2-scope-symbol-table pn)
8876 (js2-scope-symbol-table tmp-scope))
8877 (unwind-protect
8878 (progn
8879 (js2-enter-loop pn)
8880 ;; We have to parse the body -after- creating the loop node,
8881 ;; so that the loop node appears in the js2-loop-set, allowing
8882 ;; break/continue statements to find the enclosing loop.
8883 (setf body (js2-parse-statement)
8884 (js2-loop-node-body pn) body
8885 (js2-node-pos pn) for-pos
8886 (js2-node-len pn) (- (js2-node-end body) for-pos))
8887 (js2-node-add-children pn init cond incr body))
8888 ;; finally
8889 (js2-exit-loop))
8890 pn))
8891
8892 (defun js2-parse-try ()
8893 "Parse a try statement. Last matched token must be js2-TRY."
8894 (let ((try-pos (js2-current-token-beg))
8895 try-end
8896 try-block
8897 catch-blocks
8898 finally-block
8899 saw-default-catch
8900 peek)
8901 (if (/= (js2-peek-token) js2-LC)
8902 (js2-report-error "msg.no.brace.try"))
8903 (setq try-block (js2-parse-statement)
8904 try-end (js2-node-end try-block)
8905 peek (js2-peek-token))
8906 (cond
8907 ((= peek js2-CATCH)
8908 (while (js2-match-token js2-CATCH)
8909 (let* ((catch-pos (js2-current-token-beg))
8910 (catch-node (make-js2-catch-node :pos catch-pos))
8911 param
8912 guard-kwd
8913 catch-cond
8914 lp rp)
8915 (if saw-default-catch
8916 (js2-report-error "msg.catch.unreachable"))
8917 (if (js2-must-match js2-LP "msg.no.paren.catch")
8918 (setq lp (- (js2-current-token-beg) catch-pos)))
8919 (js2-push-scope catch-node)
8920 (let ((tt (js2-peek-token)))
8921 (cond
8922 ;; Destructuring pattern:
8923 ;; catch ({ message, file }) { ... }
8924 ((or (= tt js2-LB) (= tt js2-LC))
8925 (js2-get-token)
8926 (setq param (js2-parse-destruct-primary-expr))
8927 (js2-define-destruct-symbols param js2-LET nil))
8928 ;; Simple name.
8929 (t
8930 (js2-must-match-name "msg.bad.catchcond")
8931 (setq param (js2-create-name-node))
8932 (js2-define-symbol js2-LET (js2-current-token-string) param)
8933 (js2-check-strict-identifier param))))
8934 ;; Catch condition.
8935 (if (js2-match-token js2-IF)
8936 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8937 catch-cond (js2-parse-expr))
8938 (setq saw-default-catch t))
8939 (if (js2-must-match js2-RP "msg.bad.catchcond")
8940 (setq rp (- (js2-current-token-beg) catch-pos)))
8941 (js2-must-match js2-LC "msg.no.brace.catchblock")
8942 (js2-parse-statements catch-node)
8943 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8944 (setq try-end (js2-current-token-end)))
8945 (js2-pop-scope)
8946 (setf (js2-node-len catch-node) (- try-end catch-pos)
8947 (js2-catch-node-param catch-node) param
8948 (js2-catch-node-guard-expr catch-node) catch-cond
8949 (js2-catch-node-guard-kwd catch-node) guard-kwd
8950 (js2-catch-node-lp catch-node) lp
8951 (js2-catch-node-rp catch-node) rp)
8952 (js2-node-add-children catch-node param catch-cond)
8953 (push catch-node catch-blocks))))
8954 ((/= peek js2-FINALLY)
8955 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8956 (js2-node-pos try-block)
8957 (- (setq try-end (js2-node-end try-block))
8958 (js2-node-pos try-block)))))
8959 (when (js2-match-token js2-FINALLY)
8960 (let ((finally-pos (js2-current-token-beg))
8961 (block (js2-parse-statement)))
8962 (setq try-end (js2-node-end block)
8963 finally-block (make-js2-finally-node :pos finally-pos
8964 :len (- try-end finally-pos)
8965 :body block))
8966 (js2-node-add-children finally-block block)))
8967 (let ((pn (make-js2-try-node :pos try-pos
8968 :len (- try-end try-pos)
8969 :try-block try-block
8970 :finally-block finally-block)))
8971 (js2-node-add-children pn try-block finally-block)
8972 ;; Push them onto the try-node, which reverses and corrects their order.
8973 (dolist (cb catch-blocks)
8974 (js2-node-add-children pn cb)
8975 (push cb (js2-try-node-catch-clauses pn)))
8976 pn)))
8977
8978 (defun js2-parse-throw ()
8979 "Parser for throw-statement. Last matched token must be js2-THROW."
8980 (let ((pos (js2-current-token-beg))
8981 expr pn)
8982 (if (= (js2-peek-token-or-eol) js2-EOL)
8983 ;; ECMAScript does not allow new lines before throw expression,
8984 ;; see bug 256617
8985 (js2-report-error "msg.bad.throw.eol"))
8986 (setq expr (js2-parse-expr)
8987 pn (make-js2-throw-node :pos pos
8988 :len (- (js2-node-end expr) pos)
8989 :expr expr))
8990 (js2-node-add-children pn expr)
8991 pn))
8992
8993 (defun js2-match-jump-label-name (label-name)
8994 "If break/continue specified a label, return that label's labeled stmt.
8995 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8996 does not match an existing label, reports an error and returns nil."
8997 (let ((bundle (cdr (assoc label-name js2-label-set))))
8998 (if (null bundle)
8999 (js2-report-error "msg.undef.label"))
9000 bundle))
9001
9002 (defun js2-parse-break ()
9003 "Parser for break-statement. Last matched token must be js2-BREAK."
9004 (let ((pos (js2-current-token-beg))
9005 (end (js2-current-token-end))
9006 break-target ; statement to break from
9007 break-label ; in "break foo", name-node representing the foo
9008 labels ; matching labeled statement to break to
9009 pn)
9010 (when (eq (js2-peek-token-or-eol) js2-NAME)
9011 (js2-get-token)
9012 (setq break-label (js2-create-name-node)
9013 end (js2-node-end break-label)
9014 ;; matchJumpLabelName only matches if there is one
9015 labels (js2-match-jump-label-name (js2-current-token-string))
9016 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9017 (unless (or break-target break-label)
9018 ;; no break target specified - try for innermost enclosing loop/switch
9019 (if (null js2-loop-and-switch-set)
9020 (unless break-label
9021 (js2-report-error "msg.bad.break" nil pos (length "break")))
9022 (setq break-target (car js2-loop-and-switch-set))))
9023 (setq pn (make-js2-break-node :pos pos
9024 :len (- end pos)
9025 :label break-label
9026 :target break-target))
9027 (js2-node-add-children pn break-label) ; but not break-target
9028 pn))
9029
9030 (defun js2-parse-continue ()
9031 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9032 (let ((pos (js2-current-token-beg))
9033 (end (js2-current-token-end))
9034 label ; optional user-specified label, a `js2-name-node'
9035 labels ; current matching labeled stmt, if any
9036 target ; the `js2-loop-node' target of this continue stmt
9037 pn)
9038 (when (= (js2-peek-token-or-eol) js2-NAME)
9039 (js2-get-token)
9040 (setq label (js2-create-name-node)
9041 end (js2-node-end label)
9042 ;; matchJumpLabelName only matches if there is one
9043 labels (js2-match-jump-label-name (js2-current-token-string))))
9044 (cond
9045 ((null labels) ; no current label to go to
9046 (if (null js2-loop-set) ; no loop to continue to
9047 (js2-report-error "msg.continue.outside" nil pos
9048 (length "continue"))
9049 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9050 (t
9051 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9052 (setq target (js2-labeled-stmt-node-stmt labels))
9053 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9054 (setq pn (make-js2-continue-node :pos pos
9055 :len (- end pos)
9056 :label label
9057 :target target))
9058 (js2-node-add-children pn label) ; but not target - it's not our child
9059 pn))
9060
9061 (defun js2-parse-with ()
9062 "Parser for with-statement. Last matched token must be js2-WITH."
9063 (when js2-in-use-strict-directive
9064 (js2-report-error "msg.no.with.strict"))
9065 (let ((pos (js2-current-token-beg))
9066 obj body pn lp rp)
9067 (if (js2-must-match js2-LP "msg.no.paren.with")
9068 (setq lp (js2-current-token-beg)))
9069 (setq obj (js2-parse-expr))
9070 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9071 (setq rp (js2-current-token-beg)))
9072 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9073 (setq body (js2-parse-statement)))
9074 (setq pn (make-js2-with-node :pos pos
9075 :len (- (js2-node-end body) pos)
9076 :object obj
9077 :body body
9078 :lp (js2-relpos lp pos)
9079 :rp (js2-relpos rp pos)))
9080 (js2-node-add-children pn obj body)
9081 pn))
9082
9083 (defun js2-parse-const-var ()
9084 "Parser for var- or const-statement.
9085 Last matched token must be js2-CONST or js2-VAR."
9086 (let ((tt (js2-current-token-type))
9087 (pos (js2-current-token-beg))
9088 expr pn)
9089 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9090 pn (make-js2-expr-stmt-node :pos pos
9091 :len (- (js2-node-end expr) pos)
9092 :expr expr))
9093 (js2-node-add-children pn expr)
9094 pn))
9095
9096 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9097 (let ((pn (make-js2-expr-stmt-node :pos pos
9098 :len (js2-node-len expr)
9099 :type (if (js2-inside-function)
9100 js2-EXPR_VOID
9101 js2-EXPR_RESULT)
9102 :expr expr)))
9103 (if add-child
9104 (js2-node-add-children pn expr))
9105 pn))
9106
9107 (defun js2-parse-let-stmt ()
9108 "Parser for let-statement. Last matched token must be js2-LET."
9109 (let ((pos (js2-current-token-beg))
9110 expr pn)
9111 (if (= (js2-peek-token) js2-LP)
9112 ;; let expression in statement context
9113 (setq expr (js2-parse-let pos 'statement)
9114 pn (js2-wrap-with-expr-stmt pos expr t))
9115 ;; else we're looking at a statement like let x=6, y=7;
9116 (setf expr (js2-parse-variables js2-LET pos)
9117 pn (js2-wrap-with-expr-stmt pos expr t)
9118 (js2-node-type pn) js2-EXPR_RESULT))
9119 pn))
9120
9121 (defun js2-parse-ret-yield ()
9122 (js2-parse-return-or-yield (js2-current-token-type) nil))
9123
9124 (defconst js2-parse-return-stmt-enders
9125 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9126
9127 (defsubst js2-now-all-set (before after mask)
9128 "Return whether or not the bits in the mask have changed to all set.
9129 BEFORE is bits before change, AFTER is bits after change, and MASK is
9130 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9131 but not BEFORE."
9132 (and (/= (logand before mask) mask)
9133 (= (logand after mask) mask)))
9134
9135 (defun js2-parse-return-or-yield (tt expr-context)
9136 (let* ((pos (js2-current-token-beg))
9137 (end (js2-current-token-end))
9138 (before js2-end-flags)
9139 (inside-function (js2-inside-function))
9140 (gen-type (and inside-function (js2-function-node-generator-type
9141 js2-current-script-or-fn)))
9142 e ret name yield-star-p)
9143 (unless inside-function
9144 (js2-report-error (if (eq tt js2-RETURN)
9145 "msg.bad.return"
9146 "msg.bad.yield")))
9147 (when (and inside-function
9148 (eq gen-type 'STAR)
9149 (js2-match-token js2-MUL))
9150 (setq yield-star-p t))
9151 ;; This is ugly, but we don't want to require a semicolon.
9152 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9153 (setq e (js2-parse-expr)
9154 end (js2-node-end e)))
9155 (cond
9156 ((eq tt js2-RETURN)
9157 (js2-set-flag js2-end-flags (if (null e)
9158 js2-end-returns
9159 js2-end-returns-value))
9160 (setq ret (make-js2-return-node :pos pos
9161 :len (- end pos)
9162 :retval e))
9163 (js2-node-add-children ret e)
9164 ;; See if we need a strict mode warning.
9165 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9166 ;; more thorough and accurate than this before/after flag check.
9167 ;; E.g. if there's a finally-block that always returns, we shouldn't
9168 ;; show a warning generated by inconsistent returns in the catch blocks.
9169 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9170 ;; so we know which returns/yields to highlight, and we should get rid of
9171 ;; all the checking in `js2-parse-return-or-yield'.
9172 (if (and js2-strict-inconsistent-return-warning
9173 (js2-now-all-set before js2-end-flags
9174 (logior js2-end-returns js2-end-returns-value)))
9175 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9176 ((eq gen-type 'COMPREHENSION)
9177 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9178 ;; like SpiderMonkey does.
9179 (js2-report-error "msg.syntax" nil pos 5))
9180 (t
9181 (setq ret (make-js2-yield-node :pos pos
9182 :len (- end pos)
9183 :value e
9184 :star-p yield-star-p))
9185 (js2-node-add-children ret e)
9186 (unless expr-context
9187 (setq e ret
9188 ret (js2-wrap-with-expr-stmt pos e t))
9189 (js2-set-requires-activation)
9190 (js2-set-is-generator))))
9191 ;; see if we are mixing yields and value returns.
9192 (when (and inside-function
9193 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9194 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9195 'LEGACY))
9196 (setq name (js2-function-name js2-current-script-or-fn))
9197 (if (zerop (length name))
9198 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9199 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9200 ret))
9201
9202 (defun js2-parse-debugger ()
9203 (make-js2-keyword-node :type js2-DEBUGGER))
9204
9205 (defun js2-parse-block ()
9206 "Parser for a curly-delimited statement block.
9207 Last token matched must be `js2-LC'."
9208 (let ((pos (js2-current-token-beg))
9209 (pn (make-js2-scope)))
9210 (js2-push-scope pn)
9211 (unwind-protect
9212 (progn
9213 (js2-parse-statements pn)
9214 (js2-must-match js2-RC "msg.no.brace.block")
9215 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9216 (js2-pop-scope))
9217 pn))
9218
9219 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9220 (defun js2-parse-semi ()
9221 "Parse a statement or handle an error.
9222 Current token type is `js2-SEMI' or `js2-ERROR'."
9223 (let ((tt (js2-current-token-type)) pos len)
9224 (if (eq tt js2-SEMI)
9225 (make-js2-empty-expr-node :len 1)
9226 (setq pos (js2-current-token-beg)
9227 len (- (js2-current-token-end) pos))
9228 (js2-report-error "msg.syntax" nil pos len)
9229 (make-js2-error-node :pos pos :len len))))
9230
9231 (defun js2-parse-default-xml-namespace ()
9232 "Parse a `default xml namespace = <expr>' e4x statement."
9233 (let ((pos (js2-current-token-beg))
9234 end len expr unary)
9235 (js2-must-have-xml)
9236 (js2-set-requires-activation)
9237 (setq len (- js2-ts-cursor pos))
9238 (unless (and (js2-match-token js2-NAME)
9239 (string= (js2-current-token-string) "xml"))
9240 (js2-report-error "msg.bad.namespace" nil pos len))
9241 (unless (and (js2-match-token js2-NAME)
9242 (string= (js2-current-token-string) "namespace"))
9243 (js2-report-error "msg.bad.namespace" nil pos len))
9244 (unless (js2-match-token js2-ASSIGN)
9245 (js2-report-error "msg.bad.namespace" nil pos len))
9246 (setq expr (js2-parse-expr)
9247 end (js2-node-end expr)
9248 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9249 :pos pos
9250 :len (- end pos)
9251 :operand expr))
9252 (js2-node-add-children unary expr)
9253 (make-js2-expr-stmt-node :pos pos
9254 :len (- end pos)
9255 :expr unary)))
9256
9257 (defun js2-record-label (label bundle)
9258 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9259 (js2-get-token)
9260 (let ((name (js2-label-node-name label))
9261 labeled-stmt
9262 dup)
9263 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9264 ;; flag both labels if possible when used in editing mode
9265 (if (and js2-parse-ide-mode
9266 (setq dup (js2-get-label-by-name labeled-stmt name)))
9267 (js2-report-error "msg.dup.label" nil
9268 (js2-node-abs-pos dup) (js2-node-len dup)))
9269 (js2-report-error "msg.dup.label" nil
9270 (js2-node-pos label) (js2-node-len label)))
9271 (js2-labeled-stmt-node-add-label bundle label)
9272 (js2-node-add-children bundle label)
9273 ;; Add one reference to the bundle per label in `js2-label-set'
9274 (push (cons name bundle) js2-label-set)))
9275
9276 (defun js2-parse-name-or-label ()
9277 "Parser for identifier or label. Last token matched must be js2-NAME.
9278 Called when we found a name in a statement context. If it's a label, we gather
9279 up any following labels and the next non-label statement into a
9280 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9281 expression and return it wrapped in a `js2-expr-stmt-node'."
9282 (let ((pos (js2-current-token-beg))
9283 expr stmt bundle
9284 (continue t))
9285 ;; set check for label and call down to `js2-parse-primary-expr'
9286 (setq expr (js2-maybe-parse-label))
9287 (if (null expr)
9288 ;; Parse the non-label expression and wrap with expression stmt.
9289 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9290 ;; else parsed a label
9291 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9292 (js2-record-label expr bundle)
9293 ;; look for more labels
9294 (while (and continue (= (js2-get-token) js2-NAME))
9295 (if (setq expr (js2-maybe-parse-label))
9296 (js2-record-label expr bundle)
9297 (setq expr (js2-parse-expr)
9298 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9299 continue nil)
9300 (js2-auto-insert-semicolon stmt)))
9301 ;; no more labels; now parse the labeled statement
9302 (unwind-protect
9303 (unless stmt
9304 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9305 (js2-unget-token)
9306 (setq stmt (js2-statement-helper))))
9307 ;; remove the labels for this statement from the global set
9308 (dolist (label (js2-labeled-stmt-node-labels bundle))
9309 (setq js2-label-set (remove label js2-label-set))))
9310 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9311 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9312 (js2-node-add-children bundle stmt)
9313 bundle)))
9314
9315 (defun js2-maybe-parse-label ()
9316 (cl-assert (= (js2-current-token-type) js2-NAME))
9317 (let (label-pos
9318 (next-tt (js2-get-token))
9319 (label-end (js2-current-token-end)))
9320 ;; Do not consume colon, it is used as unwind indicator
9321 ;; to return to statementHelper.
9322 (js2-unget-token)
9323 (if (= next-tt js2-COLON)
9324 (prog2
9325 (setq label-pos (js2-current-token-beg))
9326 (make-js2-label-node :pos label-pos
9327 :len (- label-end label-pos)
9328 :name (js2-current-token-string))
9329 (js2-set-face label-pos
9330 label-end
9331 'font-lock-variable-name-face 'record))
9332 ;; Backtrack from the name token, too.
9333 (js2-unget-token)
9334 nil)))
9335
9336 (defun js2-parse-expr-stmt ()
9337 "Default parser in statement context, if no recognized statement found."
9338 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9339 (progn
9340 (js2-unget-token)
9341 (js2-parse-expr)) t))
9342
9343 (defun js2-parse-variables (decl-type pos)
9344 "Parse a comma-separated list of variable declarations.
9345 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9346
9347 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9348 For 'var' or 'const', the keyword should be the token last scanned.
9349
9350 POS is the position where the node should start. It's sometimes the
9351 var/const/let keyword, and other times the beginning of the first token
9352 in the first variable declaration.
9353
9354 Returns the parsed `js2-var-decl-node' expression node."
9355 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9356 :pos pos))
9357 destructuring kid-pos tt init name end nbeg nend vi
9358 (continue t))
9359 ;; Example:
9360 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9361 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9362 ;; var {a, b} = baz;
9363 (while continue
9364 (setq destructuring nil
9365 name nil
9366 tt (js2-get-token)
9367 kid-pos (js2-current-token-beg)
9368 end (js2-current-token-end)
9369 init nil)
9370 (if (or (= tt js2-LB) (= tt js2-LC))
9371 ;; Destructuring assignment, e.g., var [a, b] = ...
9372 (setq destructuring (js2-parse-destruct-primary-expr)
9373 end (js2-node-end destructuring))
9374 ;; Simple variable name
9375 (js2-unget-token)
9376 (when (js2-must-match-name "msg.bad.var")
9377 (setq name (js2-create-name-node)
9378 nbeg (js2-current-token-beg)
9379 nend (js2-current-token-end)
9380 end nend)
9381 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9382 (js2-check-strict-identifier name)))
9383 (when (js2-match-token js2-ASSIGN)
9384 (setq init (js2-parse-assign-expr)
9385 end (js2-node-end init))
9386 (js2-record-imenu-functions init name))
9387 (when name
9388 (js2-set-face nbeg nend (if (js2-function-node-p init)
9389 'font-lock-function-name-face
9390 'font-lock-variable-name-face)
9391 'record))
9392 (setq vi (make-js2-var-init-node :pos kid-pos
9393 :len (- end kid-pos)
9394 :type decl-type))
9395 (if destructuring
9396 (progn
9397 (if (and (null init) (not js2-in-for-init))
9398 (js2-report-error "msg.destruct.assign.no.init"))
9399 (js2-define-destruct-symbols destructuring
9400 decl-type
9401 'font-lock-variable-name-face)
9402 (setf (js2-var-init-node-target vi) destructuring))
9403 (setf (js2-var-init-node-target vi) name))
9404 (setf (js2-var-init-node-initializer vi) init)
9405 (js2-node-add-children vi name destructuring init)
9406 (js2-block-node-push result vi)
9407 (unless (js2-match-token js2-COMMA)
9408 (setq continue nil)))
9409 (setf (js2-node-len result) (- end pos))
9410 result))
9411
9412 (defun js2-parse-let (pos &optional stmt-p)
9413 "Parse a let expression or statement.
9414 A let-expression is of the form `let (vars) expr'.
9415 A let-statement is of the form `let (vars) {statements}'.
9416 The third form of let is a variable declaration list, handled
9417 by `js2-parse-variables'."
9418 (let ((pn (make-js2-let-node :pos pos))
9419 beg vars body)
9420 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9421 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9422 (js2-push-scope pn)
9423 (unwind-protect
9424 (progn
9425 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9426 (if (js2-must-match js2-RP "msg.no.paren.let")
9427 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9428 (if (and stmt-p (js2-match-token js2-LC))
9429 ;; let statement
9430 (progn
9431 (setf beg (js2-current-token-beg) ; position stmt at LC
9432 body (js2-parse-statements))
9433 (js2-must-match js2-RC "msg.no.curly.let")
9434 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9435 (js2-node-len pn) (- (js2-current-token-end) pos)
9436 (js2-let-node-body pn) body
9437 (js2-node-type pn) js2-LET))
9438 ;; let expression
9439 (setf body (js2-parse-expr)
9440 (js2-node-len pn) (- (js2-node-end body) pos)
9441 (js2-let-node-body pn) body))
9442 (setf (js2-let-node-vars pn) vars)
9443 (js2-node-add-children pn vars body))
9444 (js2-pop-scope))
9445 pn))
9446
9447 (defun js2-define-new-symbol (decl-type name node &optional scope)
9448 (js2-scope-put-symbol (or scope js2-current-scope)
9449 name
9450 (make-js2-symbol decl-type name node)))
9451
9452 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9453 "Define a symbol in the current scope.
9454 If NODE is non-nil, it is the AST node associated with the symbol."
9455 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9456 (symbol (if defining-scope
9457 (js2-scope-get-symbol defining-scope name)))
9458 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9459 (pos (if node (js2-node-abs-pos node)))
9460 (len (if node (js2-node-len node))))
9461 (cond
9462 ((and symbol ; already defined
9463 (or (if js2-in-use-strict-directive
9464 ;; two const-bound vars in this block have same name
9465 (and (= sdt js2-CONST)
9466 (eq defining-scope js2-current-scope))
9467 (or (= sdt js2-CONST) ; old version is const
9468 (= decl-type js2-CONST))) ; new version is const
9469 ;; two let-bound vars in this block have same name
9470 (and (= sdt js2-LET)
9471 (eq defining-scope js2-current-scope))))
9472 (js2-report-error
9473 (cond
9474 ((= sdt js2-CONST) "msg.const.redecl")
9475 ((= sdt js2-LET) "msg.let.redecl")
9476 ((= sdt js2-VAR) "msg.var.redecl")
9477 ((= sdt js2-FUNCTION) "msg.function.redecl")
9478 (t "msg.parm.redecl"))
9479 name pos len))
9480 ((or (= decl-type js2-LET)
9481 ;; strict mode const is scoped to the current LexicalEnvironment
9482 (and js2-in-use-strict-directive
9483 (= decl-type js2-CONST)))
9484 (if (and (= decl-type js2-LET)
9485 (not ignore-not-in-block)
9486 (or (= (js2-node-type js2-current-scope) js2-IF)
9487 (js2-loop-node-p js2-current-scope)))
9488 (js2-report-error "msg.let.decl.not.in.block")
9489 (js2-define-new-symbol decl-type name node)))
9490 ((or (= decl-type js2-VAR)
9491 (= decl-type js2-FUNCTION)
9492 ;; sloppy mode const is scoped to the current VariableEnvironment
9493 (and (not js2-in-use-strict-directive)
9494 (= decl-type js2-CONST)))
9495 (if symbol
9496 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9497 (js2-add-strict-warning "msg.var.redecl" name)
9498 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9499 (js2-add-strict-warning "msg.var.hides.arg" name)))
9500 (js2-define-new-symbol decl-type name node
9501 js2-current-script-or-fn)))
9502 ((= decl-type js2-LP)
9503 (if symbol
9504 ;; must be duplicate parameter. Second parameter hides the
9505 ;; first, so go ahead and add the second pararameter
9506 (js2-report-warning "msg.dup.parms" name))
9507 (js2-define-new-symbol decl-type name node))
9508 (t (js2-code-bug)))))
9509
9510 (defun js2-parse-paren-expr-or-generator-comp ()
9511 (let ((px-pos (js2-current-token-beg)))
9512 (cond
9513 ((and (>= js2-language-version 200)
9514 (js2-match-token js2-FOR))
9515 (js2-parse-generator-comp px-pos))
9516 ((and (>= js2-language-version 200)
9517 (js2-match-token js2-RP))
9518 ;; Not valid expression syntax, but this is valid in an arrow
9519 ;; function with no params: () => body.
9520 (if (eq (js2-peek-token) js2-ARROW)
9521 ;; Return whatever, it will hopefully be rewinded and
9522 ;; reparsed when we reach the =>.
9523 (make-js2-keyword-node :type js2-NULL)
9524 (js2-report-error "msg.syntax")
9525 (make-js2-error-node)))
9526 (t
9527 (let* ((js2-in-for-init nil)
9528 (expr (js2-parse-expr))
9529 (pn (make-js2-paren-node :pos px-pos
9530 :expr expr)))
9531 (js2-node-add-children pn (js2-paren-node-expr pn))
9532 (js2-must-match js2-RP "msg.no.paren")
9533 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9534 pn)))))
9535
9536 (defun js2-parse-expr (&optional oneshot)
9537 (let* ((pn (js2-parse-assign-expr))
9538 (pos (js2-node-pos pn))
9539 left
9540 right
9541 op-pos)
9542 (while (and (not oneshot)
9543 (js2-match-token js2-COMMA))
9544 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9545 (if (= (js2-peek-token) js2-YIELD)
9546 (js2-report-error "msg.yield.parenthesized"))
9547 (setq right (js2-parse-assign-expr)
9548 left pn
9549 pn (make-js2-infix-node :type js2-COMMA
9550 :pos pos
9551 :len (- js2-ts-cursor pos)
9552 :op-pos op-pos
9553 :left left
9554 :right right))
9555 (js2-node-add-children pn left right))
9556 pn))
9557
9558 (defun js2-parse-assign-expr ()
9559 (let ((tt (js2-get-token))
9560 (pos (js2-current-token-beg))
9561 pn left right op-pos
9562 ts-state recorded-identifiers parsed-errors)
9563 (if (= tt js2-YIELD)
9564 (js2-parse-return-or-yield tt t)
9565 ;; Save the tokenizer state in case we find an arrow function
9566 ;; and have to rewind.
9567 (setq ts-state (make-js2-ts-state)
9568 recorded-identifiers js2-recorded-identifiers
9569 parsed-errors js2-parsed-errors)
9570 ;; not yield - parse assignment expression
9571 (setq pn (js2-parse-cond-expr)
9572 tt (js2-get-token))
9573 (cond
9574 ((and (<= js2-first-assign tt)
9575 (<= tt js2-last-assign))
9576 ;; tt express assignment (=, |=, ^=, ..., %=)
9577 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9578 left pn)
9579 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9580 ;; care about assignment to strict variable names.
9581 (when (js2-name-node-p left)
9582 (js2-check-strict-identifier left))
9583 (setq right (js2-parse-assign-expr)
9584 pn (make-js2-assign-node :type tt
9585 :pos pos
9586 :len (- (js2-node-end right) pos)
9587 :op-pos op-pos
9588 :left left
9589 :right right))
9590 (when js2-parse-ide-mode
9591 (js2-highlight-assign-targets pn left right)
9592 (js2-record-imenu-functions right left))
9593 ;; do this last so ide checks above can use absolute positions
9594 (js2-node-add-children pn left right))
9595 ((and (= tt js2-ARROW)
9596 (>= js2-language-version 200))
9597 (js2-ts-seek ts-state)
9598 (setq js2-recorded-identifiers recorded-identifiers
9599 js2-parsed-errors parsed-errors)
9600 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9601 (t
9602 (js2-unget-token)))
9603 pn)))
9604
9605 (defun js2-parse-cond-expr ()
9606 (let ((pos (js2-current-token-beg))
9607 (pn (js2-parse-or-expr))
9608 test-expr
9609 if-true
9610 if-false
9611 q-pos
9612 c-pos)
9613 (when (js2-match-token js2-HOOK)
9614 (setq q-pos (- (js2-current-token-beg) pos)
9615 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9616 (js2-must-match js2-COLON "msg.no.colon.cond")
9617 (setq c-pos (- (js2-current-token-beg) pos)
9618 if-false (js2-parse-assign-expr)
9619 test-expr pn
9620 pn (make-js2-cond-node :pos pos
9621 :len (- (js2-node-end if-false) pos)
9622 :test-expr test-expr
9623 :true-expr if-true
9624 :false-expr if-false
9625 :q-pos q-pos
9626 :c-pos c-pos))
9627 (js2-node-add-children pn test-expr if-true if-false))
9628 pn))
9629
9630 (defun js2-make-binary (type left parser)
9631 "Helper for constructing a binary-operator AST node.
9632 LEFT is the left-side-expression, already parsed, and the
9633 binary operator should have just been matched.
9634 PARSER is a function to call to parse the right operand,
9635 or a `js2-node' struct if it has already been parsed.
9636 FIXME: The latter option is unused?"
9637 (let* ((pos (js2-node-pos left))
9638 (op-pos (- (js2-current-token-beg) pos))
9639 (right (if (js2-node-p parser)
9640 parser
9641 (js2-get-token)
9642 (funcall parser)))
9643 (pn (make-js2-infix-node :type type
9644 :pos pos
9645 :len (- (js2-node-end right) pos)
9646 :op-pos op-pos
9647 :left left
9648 :right right)))
9649 (js2-node-add-children pn left right)
9650 pn))
9651
9652 (defun js2-parse-or-expr ()
9653 (let ((pn (js2-parse-and-expr)))
9654 (when (js2-match-token js2-OR)
9655 (setq pn (js2-make-binary js2-OR
9656 pn
9657 'js2-parse-or-expr)))
9658 pn))
9659
9660 (defun js2-parse-and-expr ()
9661 (let ((pn (js2-parse-bit-or-expr)))
9662 (when (js2-match-token js2-AND)
9663 (setq pn (js2-make-binary js2-AND
9664 pn
9665 'js2-parse-and-expr)))
9666 pn))
9667
9668 (defun js2-parse-bit-or-expr ()
9669 (let ((pn (js2-parse-bit-xor-expr)))
9670 (while (js2-match-token js2-BITOR)
9671 (setq pn (js2-make-binary js2-BITOR
9672 pn
9673 'js2-parse-bit-xor-expr)))
9674 pn))
9675
9676 (defun js2-parse-bit-xor-expr ()
9677 (let ((pn (js2-parse-bit-and-expr)))
9678 (while (js2-match-token js2-BITXOR)
9679 (setq pn (js2-make-binary js2-BITXOR
9680 pn
9681 'js2-parse-bit-and-expr)))
9682 pn))
9683
9684 (defun js2-parse-bit-and-expr ()
9685 (let ((pn (js2-parse-eq-expr)))
9686 (while (js2-match-token js2-BITAND)
9687 (setq pn (js2-make-binary js2-BITAND
9688 pn
9689 'js2-parse-eq-expr)))
9690 pn))
9691
9692 (defconst js2-parse-eq-ops
9693 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9694
9695 (defun js2-parse-eq-expr ()
9696 (let ((pn (js2-parse-rel-expr))
9697 tt)
9698 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9699 (setq pn (js2-make-binary tt
9700 pn
9701 'js2-parse-rel-expr)))
9702 (js2-unget-token)
9703 pn))
9704
9705 (defconst js2-parse-rel-ops
9706 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9707
9708 (defun js2-parse-rel-expr ()
9709 (let ((pn (js2-parse-shift-expr))
9710 (continue t)
9711 tt)
9712 (while continue
9713 (setq tt (js2-get-token))
9714 (cond
9715 ((and js2-in-for-init (= tt js2-IN))
9716 (js2-unget-token)
9717 (setq continue nil))
9718 ((memq tt js2-parse-rel-ops)
9719 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9720 (t
9721 (js2-unget-token)
9722 (setq continue nil))))
9723 pn))
9724
9725 (defconst js2-parse-shift-ops
9726 (list js2-LSH js2-URSH js2-RSH))
9727
9728 (defun js2-parse-shift-expr ()
9729 (let ((pn (js2-parse-add-expr))
9730 tt
9731 (continue t))
9732 (while continue
9733 (setq tt (js2-get-token))
9734 (if (memq tt js2-parse-shift-ops)
9735 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9736 (js2-unget-token)
9737 (setq continue nil)))
9738 pn))
9739
9740 (defun js2-parse-add-expr ()
9741 (let ((pn (js2-parse-mul-expr))
9742 tt
9743 (continue t))
9744 (while continue
9745 (setq tt (js2-get-token))
9746 (if (or (= tt js2-ADD) (= tt js2-SUB))
9747 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9748 (js2-unget-token)
9749 (setq continue nil)))
9750 pn))
9751
9752 (defconst js2-parse-mul-ops
9753 (list js2-MUL js2-DIV js2-MOD))
9754
9755 (defun js2-parse-mul-expr ()
9756 (let ((pn (js2-parse-unary-expr))
9757 tt
9758 (continue t))
9759 (while continue
9760 (setq tt (js2-get-token))
9761 (if (memq tt js2-parse-mul-ops)
9762 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9763 (js2-unget-token)
9764 (setq continue nil)))
9765 pn))
9766
9767 (defun js2-make-unary (type parser &rest args)
9768 "Make a unary node of type TYPE.
9769 PARSER is either a node (for postfix operators) or a function to call
9770 to parse the operand (for prefix operators)."
9771 (let* ((pos (js2-current-token-beg))
9772 (postfix (js2-node-p parser))
9773 (expr (if postfix
9774 parser
9775 (apply parser args)))
9776 end
9777 pn)
9778 (if postfix ; e.g. i++
9779 (setq pos (js2-node-pos expr)
9780 end (js2-current-token-end))
9781 (setq end (js2-node-end expr)))
9782 (setq pn (make-js2-unary-node :type type
9783 :pos pos
9784 :len (- end pos)
9785 :operand expr))
9786 (js2-node-add-children pn expr)
9787 pn))
9788
9789 (defconst js2-incrementable-node-types
9790 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9791 "Node types that can be the operand of a ++ or -- operator.")
9792
9793 (defun js2-check-bad-inc-dec (tt beg end unary)
9794 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9795 js2-incrementable-node-types)
9796 (js2-report-error (if (= tt js2-INC)
9797 "msg.bad.incr"
9798 "msg.bad.decr")
9799 nil beg (- end beg))))
9800
9801 (defun js2-parse-unary-expr ()
9802 (let ((tt (js2-current-token-type))
9803 pn expr beg end)
9804 (cond
9805 ((or (= tt js2-VOID)
9806 (= tt js2-NOT)
9807 (= tt js2-BITNOT)
9808 (= tt js2-TYPEOF))
9809 (js2-get-token)
9810 (js2-make-unary tt 'js2-parse-unary-expr))
9811 ((= tt js2-ADD)
9812 (js2-get-token)
9813 ;; Convert to special POS token in decompiler and parse tree
9814 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9815 ((= tt js2-SUB)
9816 (js2-get-token)
9817 ;; Convert to special NEG token in decompiler and parse tree
9818 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9819 ((or (= tt js2-INC)
9820 (= tt js2-DEC))
9821 (js2-get-token)
9822 (prog1
9823 (setq beg (js2-current-token-beg)
9824 end (js2-current-token-end)
9825 expr (js2-make-unary tt 'js2-parse-member-expr t))
9826 (js2-check-bad-inc-dec tt beg end expr)))
9827 ((= tt js2-DELPROP)
9828 (js2-get-token)
9829 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9830 ((= tt js2-ERROR)
9831 (js2-get-token)
9832 (make-js2-error-node)) ; try to continue
9833 ((and (= tt js2-LT)
9834 js2-compiler-xml-available)
9835 ;; XML stream encountered in expression.
9836 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9837 (t
9838 (setq pn (js2-parse-member-expr t)
9839 ;; Don't look across a newline boundary for a postfix incop.
9840 tt (js2-peek-token-or-eol))
9841 (when (or (= tt js2-INC) (= tt js2-DEC))
9842 (js2-get-token)
9843 (setf expr pn
9844 pn (js2-make-unary tt expr))
9845 (js2-node-set-prop pn 'postfix t)
9846 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9847 pn))))
9848
9849 (defun js2-parse-xml-initializer ()
9850 "Parse an E4X XML initializer.
9851 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9852 Then I'll postprocess the result, depending on whether we're in IDE
9853 mode or codegen mode, and generate the appropriate rewritten AST.
9854 IDE mode uses a rich AST that models the XML structure. Codegen mode
9855 just concatenates everything and makes a new XML or XMLList out of it."
9856 (let ((tt (js2-get-first-xml-token))
9857 pn-xml pn expr kids expr-pos
9858 (continue t)
9859 (first-token t))
9860 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9861 (js2-report-error "msg.syntax"))
9862 (setq pn-xml (make-js2-xml-node))
9863 (while continue
9864 (if first-token
9865 (setq first-token nil)
9866 (setq tt (js2-get-next-xml-token)))
9867 (cond
9868 ;; js2-XML means we found a {expr} in the XML stream.
9869 ;; The token string is the XML up to the left-curly.
9870 ((= tt js2-XML)
9871 (push (make-js2-string-node :pos (js2-current-token-beg)
9872 :len (- js2-ts-cursor (js2-current-token-beg)))
9873 kids)
9874 (js2-must-match js2-LC "msg.syntax")
9875 (setq expr-pos js2-ts-cursor
9876 expr (if (eq (js2-peek-token) js2-RC)
9877 (make-js2-empty-expr-node :pos expr-pos)
9878 (js2-parse-expr)))
9879 (js2-must-match js2-RC "msg.syntax")
9880 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9881 :len (js2-node-len expr)
9882 :expr expr))
9883 (js2-node-add-children pn expr)
9884 (push pn kids))
9885 ;; a js2-XMLEND token means we hit the final close-tag.
9886 ((= tt js2-XMLEND)
9887 (push (make-js2-string-node :pos (js2-current-token-beg)
9888 :len (- js2-ts-cursor (js2-current-token-beg)))
9889 kids)
9890 (dolist (kid (nreverse kids))
9891 (js2-block-node-push pn-xml kid))
9892 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9893 (js2-node-pos pn-xml))
9894 continue nil))
9895 (t
9896 (js2-report-error "msg.syntax")
9897 (setq continue nil))))
9898 pn-xml))
9899
9900
9901 (defun js2-parse-argument-list ()
9902 "Parse an argument list and return it as a Lisp list of nodes.
9903 Returns the list in reverse order. Consumes the right-paren token."
9904 (let (result)
9905 (unless (js2-match-token js2-RP)
9906 (cl-loop do
9907 (let ((tt (js2-get-token)))
9908 (if (= tt js2-YIELD)
9909 (js2-report-error "msg.yield.parenthesized"))
9910 (if (and (= tt js2-TRIPLEDOT)
9911 (>= js2-language-version 200))
9912 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9913 (js2-unget-token)
9914 (push (js2-parse-assign-expr) result)))
9915 while
9916 (js2-match-token js2-COMMA))
9917 (js2-must-match js2-RP "msg.no.paren.arg")
9918 result)))
9919
9920 (defun js2-parse-member-expr (&optional allow-call-syntax)
9921 (let ((tt (js2-current-token-type))
9922 pn pos target args beg end init)
9923 (if (/= tt js2-NEW)
9924 (setq pn (js2-parse-primary-expr))
9925 ;; parse a 'new' expression
9926 (js2-get-token)
9927 (setq pos (js2-current-token-beg)
9928 beg pos
9929 target (js2-parse-member-expr)
9930 end (js2-node-end target)
9931 pn (make-js2-new-node :pos pos
9932 :target target
9933 :len (- end pos)))
9934 (js2-highlight-function-call (js2-current-token))
9935 (js2-node-add-children pn target)
9936 (when (js2-match-token js2-LP)
9937 ;; Add the arguments to pn, if any are supplied.
9938 (setf beg pos ; start of "new" keyword
9939 pos (js2-current-token-beg)
9940 args (nreverse (js2-parse-argument-list))
9941 (js2-new-node-args pn) args
9942 end (js2-current-token-end)
9943 (js2-new-node-lp pn) (- pos beg)
9944 (js2-new-node-rp pn) (- end 1 beg))
9945 (apply #'js2-node-add-children pn args))
9946 (when (and js2-allow-rhino-new-expr-initializer
9947 (js2-match-token js2-LC))
9948 (setf init (js2-parse-object-literal)
9949 end (js2-node-end init)
9950 (js2-new-node-initializer pn) init)
9951 (js2-node-add-children pn init))
9952 (setf (js2-node-len pn) (- end beg))) ; end outer if
9953 (js2-parse-member-expr-tail allow-call-syntax pn)))
9954
9955 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9956 "Parse a chain of property/array accesses or function calls.
9957 Includes parsing for E4X operators like `..' and `.@'.
9958 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9959 Returns an expression tree that includes PN, the parent node."
9960 (let (tt
9961 (continue t))
9962 (while continue
9963 (setq tt (js2-get-token))
9964 (cond
9965 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9966 (setq pn (js2-parse-property-access tt pn)))
9967 ((= tt js2-DOTQUERY)
9968 (setq pn (js2-parse-dot-query pn)))
9969 ((= tt js2-LB)
9970 (setq pn (js2-parse-element-get pn)))
9971 ((= tt js2-LP)
9972 (js2-unget-token)
9973 (if allow-call-syntax
9974 (setq pn (js2-parse-function-call pn))
9975 (setq continue nil)))
9976 ((= tt js2-TEMPLATE_HEAD)
9977 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9978 ((= tt js2-NO_SUBS_TEMPLATE)
9979 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9980 (t
9981 (js2-unget-token)
9982 (setq continue nil))))
9983 (if (>= js2-highlight-level 2)
9984 (js2-parse-highlight-member-expr-node pn))
9985 pn))
9986
9987 (defun js2-parse-tagged-template (tag-node tpl-node)
9988 "Parse tagged template expression."
9989 (let* ((beg (js2-node-pos tag-node))
9990 (pn (make-js2-tagged-template-node :beg beg
9991 :len (- (js2-current-token-end) beg)
9992 :tag tag-node
9993 :template tpl-node)))
9994 (js2-node-add-children pn tag-node tpl-node)
9995 pn))
9996
9997 (defun js2-parse-dot-query (pn)
9998 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9999 Last token parsed must be `js2-DOTQUERY'."
10000 (let ((pos (js2-node-pos pn))
10001 op-pos expr end)
10002 (js2-must-have-xml)
10003 (js2-set-requires-activation)
10004 (setq op-pos (js2-current-token-beg)
10005 expr (js2-parse-expr)
10006 end (js2-node-end expr)
10007 pn (make-js2-xml-dot-query-node :left pn
10008 :pos pos
10009 :op-pos op-pos
10010 :right expr))
10011 (js2-node-add-children pn
10012 (js2-xml-dot-query-node-left pn)
10013 (js2-xml-dot-query-node-right pn))
10014 (if (js2-must-match js2-RP "msg.no.paren")
10015 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10016 end (js2-current-token-end)))
10017 (setf (js2-node-len pn) (- end pos))
10018 pn))
10019
10020 (defun js2-parse-element-get (pn)
10021 "Parse an element-get expression, e.g. foo[bar].
10022 Last token parsed must be `js2-RB'."
10023 (let ((lb (js2-current-token-beg))
10024 (pos (js2-node-pos pn))
10025 rb expr)
10026 (setq expr (js2-parse-expr))
10027 (if (js2-must-match js2-RB "msg.no.bracket.index")
10028 (setq rb (js2-current-token-beg)))
10029 (setq pn (make-js2-elem-get-node :target pn
10030 :pos pos
10031 :element expr
10032 :lb (js2-relpos lb pos)
10033 :rb (js2-relpos rb pos)
10034 :len (- (js2-current-token-end) pos)))
10035 (js2-node-add-children pn
10036 (js2-elem-get-node-target pn)
10037 (js2-elem-get-node-element pn))
10038 pn))
10039
10040 (defun js2-highlight-function-call (token)
10041 (when (eq (js2-token-type token) js2-NAME)
10042 (js2-record-face 'js2-function-call token)))
10043
10044 (defun js2-parse-function-call (pn)
10045 (js2-highlight-function-call (js2-current-token))
10046 (js2-get-token)
10047 (let (args
10048 (pos (js2-node-pos pn)))
10049 (setq pn (make-js2-call-node :pos pos
10050 :target pn
10051 :lp (- (js2-current-token-beg) pos)))
10052 (js2-node-add-children pn (js2-call-node-target pn))
10053 ;; Add the arguments to pn, if any are supplied.
10054 (setf args (nreverse (js2-parse-argument-list))
10055 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10056 (js2-call-node-args pn) args)
10057 (apply #'js2-node-add-children pn args)
10058 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10059 pn))
10060
10061 (defun js2-parse-property-access (tt pn)
10062 "Parse a property access, XML descendants access, or XML attr access."
10063 (let ((member-type-flags 0)
10064 (dot-pos (js2-current-token-beg))
10065 (dot-len (if (= tt js2-DOTDOT) 2 1))
10066 name
10067 ref ; right side of . or .. operator
10068 result)
10069 (when (= tt js2-DOTDOT)
10070 (js2-must-have-xml)
10071 (setq member-type-flags js2-descendants-flag))
10072 (if (not js2-compiler-xml-available)
10073 (progn
10074 (js2-must-match-prop-name "msg.no.name.after.dot")
10075 (setq name (js2-create-name-node t js2-GETPROP)
10076 result (make-js2-prop-get-node :left pn
10077 :pos (js2-current-token-beg)
10078 :right name
10079 :len (js2-current-token-len)))
10080 (js2-node-add-children result pn name)
10081 result)
10082 ;; otherwise look for XML operators
10083 (setf result (if (= tt js2-DOT)
10084 (make-js2-prop-get-node)
10085 (make-js2-infix-node :type js2-DOTDOT))
10086 (js2-node-pos result) (js2-node-pos pn)
10087 (js2-infix-node-op-pos result) dot-pos
10088 (js2-infix-node-left result) pn ; do this after setting position
10089 tt (js2-get-prop-name-token))
10090 (cond
10091 ;; handles: name, ns::name, ns::*, ns::[expr]
10092 ((= tt js2-NAME)
10093 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10094 ;; handles: *, *::name, *::*, *::[expr]
10095 ((= tt js2-MUL)
10096 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10097 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10098 ((= tt js2-XMLATTR)
10099 (setq result (js2-parse-attribute-access)))
10100 (t
10101 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10102 (if ref
10103 (setf (js2-node-len result) (- (js2-node-end ref)
10104 (js2-node-pos result))
10105 (js2-infix-node-right result) ref))
10106 (if (js2-infix-node-p result)
10107 (js2-node-add-children result
10108 (js2-infix-node-left result)
10109 (js2-infix-node-right result)))
10110 result)))
10111
10112 (defun js2-parse-attribute-access ()
10113 "Parse an E4X XML attribute expression.
10114 This includes expressions of the forms:
10115
10116 @attr @ns::attr @ns::*
10117 @* @*::attr @*::*
10118 @[expr] @*::[expr] @ns::[expr]
10119
10120 Called if we peeked an '@' token."
10121 (let ((tt (js2-get-prop-name-token))
10122 (at-pos (js2-current-token-beg)))
10123 (cond
10124 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10125 ((= tt js2-NAME)
10126 (js2-parse-property-name at-pos nil 0))
10127 ;; handles: @*, @*::name, @*::*, @*::[expr]
10128 ((= tt js2-MUL)
10129 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10130 ;; handles @[expr]
10131 ((= tt js2-LB)
10132 (js2-parse-xml-elem-ref at-pos))
10133 (t
10134 (js2-report-error "msg.no.name.after.xmlAttr")
10135 ;; Avoid cascaded errors that happen if we make an error node here.
10136 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10137
10138 (defun js2-parse-property-name (at-pos s member-type-flags)
10139 "Check if :: follows name in which case it becomes qualified name.
10140
10141 AT-POS is a natural number if we just read an '@' token, else nil.
10142 S is the name or string that was matched: an identifier, 'throw' or '*'.
10143 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10144
10145 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10146 operator, or the name is followed by ::. For a plain name, returns a
10147 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10148 (let ((pos (or at-pos (js2-current-token-beg)))
10149 colon-pos
10150 (name (js2-create-name-node t (js2-current-token-type) s))
10151 ns tt pn)
10152 (catch 'return
10153 (when (js2-match-token js2-COLONCOLON)
10154 (setq ns name
10155 colon-pos (js2-current-token-beg)
10156 tt (js2-get-prop-name-token))
10157 (cond
10158 ;; handles name::name
10159 ((= tt js2-NAME)
10160 (setq name (js2-create-name-node)))
10161 ;; handles name::*
10162 ((= tt js2-MUL)
10163 (setq name (js2-create-name-node nil nil "*")))
10164 ;; handles name::[expr]
10165 ((= tt js2-LB)
10166 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10167 (t
10168 (js2-report-error "msg.no.name.after.coloncolon"))))
10169 (if (and (null ns) (zerop member-type-flags))
10170 name
10171 (prog1
10172 (setq pn
10173 (make-js2-xml-prop-ref-node :pos pos
10174 :len (- (js2-node-end name) pos)
10175 :at-pos at-pos
10176 :colon-pos colon-pos
10177 :propname name))
10178 (js2-node-add-children pn name))))))
10179
10180 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10181 "Parse the [expr] portion of an xml element reference.
10182 For instance, @[expr], @*::[expr], or ns::[expr]."
10183 (let* ((lb (js2-current-token-beg))
10184 (pos (or at-pos lb))
10185 rb
10186 (expr (js2-parse-expr))
10187 (end (js2-node-end expr))
10188 pn)
10189 (if (js2-must-match js2-RB "msg.no.bracket.index")
10190 (setq rb (js2-current-token-beg)
10191 end (js2-current-token-end)))
10192 (prog1
10193 (setq pn
10194 (make-js2-xml-elem-ref-node :pos pos
10195 :len (- end pos)
10196 :namespace namespace
10197 :colon-pos colon-pos
10198 :at-pos at-pos
10199 :expr expr
10200 :lb (js2-relpos lb pos)
10201 :rb (js2-relpos rb pos)))
10202 (js2-node-add-children pn namespace expr))))
10203
10204 (defun js2-parse-destruct-primary-expr ()
10205 (let ((js2-is-in-destructuring t))
10206 (js2-parse-primary-expr)))
10207
10208 (defun js2-parse-primary-expr ()
10209 "Parse a literal (leaf) expression of some sort.
10210 Includes complex literals such as functions, object-literals,
10211 array-literals, array comprehensions and regular expressions."
10212 (let (tt node)
10213 (setq tt (js2-current-token-type))
10214 (cond
10215 ((= tt js2-CLASS)
10216 (js2-parse-class-expr))
10217 ((= tt js2-FUNCTION)
10218 (js2-parse-function-expr))
10219 ((= tt js2-LB)
10220 (js2-parse-array-comp-or-literal))
10221 ((= tt js2-LC)
10222 (js2-parse-object-literal))
10223 ((= tt js2-LET)
10224 (js2-parse-let (js2-current-token-beg)))
10225 ((= tt js2-LP)
10226 (js2-parse-paren-expr-or-generator-comp))
10227 ((= tt js2-XMLATTR)
10228 (js2-must-have-xml)
10229 (js2-parse-attribute-access))
10230 ((= tt js2-NAME)
10231 (js2-parse-name tt))
10232 ((= tt js2-NUMBER)
10233 (setq node (make-js2-number-node))
10234 (when (and js2-in-use-strict-directive
10235 (= (js2-number-node-num-base node) 8))
10236 (js2-report-error "msg.no.octal.strict"))
10237 node)
10238 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10239 (make-js2-string-node :type tt))
10240 ((= tt js2-TEMPLATE_HEAD)
10241 (js2-parse-template-literal))
10242 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10243 ;; Got / or /= which in this context means a regexp literal
10244 (let ((px-pos (js2-current-token-beg))
10245 (flags (js2-read-regexp tt))
10246 (end (js2-current-token-end)))
10247 (prog1
10248 (make-js2-regexp-node :pos px-pos
10249 :len (- end px-pos)
10250 :value (js2-current-token-string)
10251 :flags flags)
10252 (js2-set-face px-pos end 'font-lock-string-face 'record)
10253 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10254 ((or (= tt js2-NULL)
10255 (= tt js2-THIS)
10256 (= tt js2-SUPER)
10257 (= tt js2-FALSE)
10258 (= tt js2-TRUE))
10259 (make-js2-keyword-node :type tt))
10260 ((= tt js2-TRIPLEDOT)
10261 ;; Likewise, only valid in an arrow function with a rest param.
10262 (if (and (js2-match-token js2-NAME)
10263 (js2-match-token js2-RP)
10264 (eq (js2-peek-token) js2-ARROW))
10265 (progn
10266 (js2-unget-token) ; Put back the right paren.
10267 ;; See the previous case.
10268 (make-js2-keyword-node :type js2-NULL))
10269 (js2-report-error "msg.syntax")
10270 (make-js2-error-node)))
10271 ((= tt js2-RESERVED)
10272 (js2-report-error "msg.reserved.id")
10273 (make-js2-name-node))
10274 ((= tt js2-ERROR)
10275 ;; the scanner or one of its subroutines reported the error.
10276 (make-js2-error-node))
10277 ((= tt js2-EOF)
10278 (let* ((px-pos (point-at-bol))
10279 (len (- js2-ts-cursor px-pos)))
10280 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10281 (make-js2-error-node :pos (1- js2-ts-cursor)))
10282 (t
10283 (js2-report-error "msg.syntax")
10284 (make-js2-error-node)))))
10285
10286 (defun js2-parse-template-literal ()
10287 (let ((beg (js2-current-token-beg))
10288 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10289 (tt js2-TEMPLATE_HEAD))
10290 (while (eq tt js2-TEMPLATE_HEAD)
10291 (push (js2-parse-expr) kids)
10292 (js2-must-match js2-RC "msg.syntax")
10293 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10294 (push (make-js2-string-node :type tt) kids))
10295 (setq kids (nreverse kids))
10296 (let ((tpl (make-js2-template-node :beg beg
10297 :len (- (js2-current-token-end) beg)
10298 :kids kids)))
10299 (apply #'js2-node-add-children tpl kids)
10300 tpl)))
10301
10302 (defun js2-parse-name (_tt)
10303 (let ((name (js2-current-token-string))
10304 node)
10305 (setq node (if js2-compiler-xml-available
10306 (js2-parse-property-name nil name 0)
10307 (js2-create-name-node 'check-activation nil name)))
10308 (if js2-highlight-external-variables
10309 (js2-record-name-node node))
10310 node))
10311
10312 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10313 (js2-add-strict-warning
10314 msg nil
10315 ;; back up from comma to beginning of line or array/objlit
10316 (max (if elems
10317 (js2-node-pos (car elems))
10318 pos)
10319 (save-excursion
10320 (goto-char comma-pos)
10321 (back-to-indentation)
10322 (point)))
10323 comma-pos))
10324
10325 (defun js2-parse-array-comp-or-literal ()
10326 (let ((pos (js2-current-token-beg)))
10327 (if (and (>= js2-language-version 200)
10328 (js2-match-token js2-FOR))
10329 (js2-parse-array-comp pos)
10330 (js2-parse-array-literal pos))))
10331
10332 (defun js2-parse-array-literal (pos)
10333 (let ((after-lb-or-comma t)
10334 after-comma tt elems pn
10335 (continue t))
10336 (unless js2-is-in-destructuring
10337 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10338 (while continue
10339 (setq tt (js2-get-token))
10340 (cond
10341 ;; comma
10342 ((= tt js2-COMMA)
10343 (setq after-comma (js2-current-token-end))
10344 (if (not after-lb-or-comma)
10345 (setq after-lb-or-comma t)
10346 (push nil elems)))
10347 ;; end of array
10348 ((or (= tt js2-RB)
10349 (= tt js2-EOF)) ; prevent infinite loop
10350 (if (= tt js2-EOF)
10351 (js2-report-error "msg.no.bracket.arg" nil pos))
10352 (when (and after-comma (< js2-language-version 170))
10353 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10354 pos (remove nil elems) after-comma))
10355 (setq continue nil
10356 pn (make-js2-array-node :pos pos
10357 :len (- js2-ts-cursor pos)
10358 :elems (nreverse elems)))
10359 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10360 ;; destructuring binding
10361 (js2-is-in-destructuring
10362 (push (if (or (= tt js2-LC)
10363 (= tt js2-LB)
10364 (= tt js2-NAME))
10365 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10366 (js2-parse-destruct-primary-expr)
10367 ;; invalid pattern
10368 (js2-report-error "msg.bad.var")
10369 (make-js2-error-node))
10370 elems)
10371 (setq after-lb-or-comma nil
10372 after-comma nil))
10373 ;; array comp
10374 ((and (>= js2-language-version 170)
10375 (= tt js2-FOR) ; check for array comprehension
10376 (not after-lb-or-comma) ; "for" can't follow a comma
10377 elems ; must have at least 1 element
10378 (not (cdr elems))) ; but no 2nd element
10379 (js2-unget-token)
10380 (setf continue nil
10381 pn (js2-parse-legacy-array-comp (car elems) pos)))
10382 ;; another element
10383 (t
10384 (unless after-lb-or-comma
10385 (js2-report-error "msg.no.bracket.arg"))
10386 (if (and (= tt js2-TRIPLEDOT)
10387 (>= js2-language-version 200))
10388 ;; spread operator
10389 (push (js2-make-unary tt 'js2-parse-assign-expr)
10390 elems)
10391 (js2-unget-token)
10392 (push (js2-parse-assign-expr) elems))
10393 (setq after-lb-or-comma nil
10394 after-comma nil))))
10395 (unless js2-is-in-destructuring
10396 (js2-pop-scope))
10397 pn))
10398
10399 (defun js2-parse-legacy-array-comp (expr pos)
10400 "Parse a legacy array comprehension (JavaScript 1.7).
10401 EXPR is the first expression after the opening left-bracket.
10402 POS is the beginning of the LB token preceding EXPR.
10403 We should have just parsed the 'for' keyword before calling this function."
10404 (let ((current-scope js2-current-scope)
10405 loops filter result)
10406 (unwind-protect
10407 (progn
10408 (while (js2-match-token js2-FOR)
10409 (let ((loop (make-js2-comp-loop-node)))
10410 (js2-push-scope loop)
10411 (push loop loops)
10412 (js2-parse-comp-loop loop)))
10413 ;; First loop takes expr scope's parent.
10414 (setf (js2-scope-parent-scope (car (last loops)))
10415 (js2-scope-parent-scope current-scope))
10416 ;; Set expr scope's parent to the last loop.
10417 (setf (js2-scope-parent-scope current-scope) (car loops))
10418 (if (/= (js2-get-token) js2-IF)
10419 (js2-unget-token)
10420 (setq filter (js2-parse-condition))))
10421 (dotimes (_ (1- (length loops)))
10422 (js2-pop-scope)))
10423 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10424 (setq result (make-js2-comp-node :pos pos
10425 :len (- js2-ts-cursor pos)
10426 :result expr
10427 :loops (nreverse loops)
10428 :filters (and filter (list (car filter)))
10429 :form 'LEGACY_ARRAY))
10430 ;; Set comp loop's parent to the last loop.
10431 ;; TODO: Get rid of the bogus expr scope.
10432 (setf (js2-scope-parent-scope result) first)
10433 (apply #'js2-node-add-children result expr (car filter)
10434 (js2-comp-node-loops result))
10435 result))
10436
10437 (defun js2-parse-array-comp (pos)
10438 "Parse an ES6 array comprehension.
10439 POS is the beginning of the LB token.
10440 We should have just parsed the 'for' keyword before calling this function."
10441 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10442 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10443 pn))
10444
10445 (defun js2-parse-generator-comp (pos)
10446 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10447 (js2-current-script-or-fn
10448 (make-js2-function-node :generator-type 'COMPREHENSION))
10449 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10450 (js2-must-match js2-RP "msg.no.paren" pos)
10451 pn))
10452
10453 (defun js2-parse-comprehension (pos form)
10454 (let (loops filters expr result last)
10455 (unwind-protect
10456 (progn
10457 (js2-unget-token)
10458 (while (js2-match-token js2-FOR)
10459 (let ((loop (make-js2-comp-loop-node)))
10460 (js2-push-scope loop)
10461 (push loop loops)
10462 (js2-parse-comp-loop loop)))
10463 (while (js2-match-token js2-IF)
10464 (push (car (js2-parse-condition)) filters))
10465 (setq expr (js2-parse-assign-expr))
10466 (setq last (car loops)))
10467 (dolist (_ loops)
10468 (js2-pop-scope)))
10469 (setq result (make-js2-comp-node :pos pos
10470 :len (- js2-ts-cursor pos)
10471 :result expr
10472 :loops (nreverse loops)
10473 :filters (nreverse filters)
10474 :form form))
10475 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10476 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10477 (setf (js2-scope-parent-scope result) last)
10478 result))
10479
10480 (defun js2-parse-comp-loop (pn &optional only-of-p)
10481 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10482 The current token should be the initial FOR.
10483 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10484 (let ((pos (js2-comp-loop-node-pos pn))
10485 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10486 (when (and (not only-of-p) (js2-match-token js2-NAME))
10487 (if (string= (js2-current-token-string) "each")
10488 (progn
10489 (setq foreach-p t
10490 each-pos (- (js2-current-token-beg) pos)) ; relative
10491 (js2-record-face 'font-lock-keyword-face))
10492 (js2-report-error "msg.no.paren.for")))
10493 (if (js2-must-match js2-LP "msg.no.paren.for")
10494 (setq lp (- (js2-current-token-beg) pos)))
10495 (setq tt (js2-peek-token))
10496 (cond
10497 ((or (= tt js2-LB)
10498 (= tt js2-LC))
10499 (js2-get-token)
10500 (setq iter (js2-parse-destruct-primary-expr))
10501 (js2-define-destruct-symbols iter js2-LET
10502 'font-lock-variable-name-face t))
10503 ((js2-match-token js2-NAME)
10504 (setq iter (js2-create-name-node)))
10505 (t
10506 (js2-report-error "msg.bad.var")))
10507 ;; Define as a let since we want the scope of the variable to
10508 ;; be restricted to the array comprehension
10509 (if (js2-name-node-p iter)
10510 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10511 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10512 (and (>= js2-language-version 200)
10513 (js2-match-contextual-kwd "of")
10514 (setq forof-p t)))
10515 (setq in-pos (- (js2-current-token-beg) pos))
10516 (js2-report-error "msg.in.after.for.name"))
10517 (setq obj (js2-parse-expr))
10518 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10519 (setq rp (- (js2-current-token-beg) pos)))
10520 (setf (js2-node-pos pn) pos
10521 (js2-node-len pn) (- js2-ts-cursor pos)
10522 (js2-comp-loop-node-iterator pn) iter
10523 (js2-comp-loop-node-object pn) obj
10524 (js2-comp-loop-node-in-pos pn) in-pos
10525 (js2-comp-loop-node-each-pos pn) each-pos
10526 (js2-comp-loop-node-foreach-p pn) foreach-p
10527 (js2-comp-loop-node-forof-p pn) forof-p
10528 (js2-comp-loop-node-lp pn) lp
10529 (js2-comp-loop-node-rp pn) rp)
10530 (js2-node-add-children pn iter obj)
10531 pn))
10532
10533 (defun js2-parse-class-stmt ()
10534 (let ((pos (js2-current-token-beg))
10535 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10536 (name (js2-create-name-node t)))
10537 (js2-set-face (js2-node-pos name) (js2-node-end name)
10538 'font-lock-function-name-face 'record)
10539 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10540 (js2-define-symbol js2-FUNCTION
10541 (js2-name-node-name name)
10542 node)
10543 node)))
10544
10545 (defun js2-parse-class-expr ()
10546 (let ((pos (js2-current-token-beg))
10547 name)
10548 (when (js2-match-token js2-NAME)
10549 (setq name (js2-create-name-node t)))
10550 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10551
10552 (defun js2-parse-class (pos form name)
10553 ;; class X [extends ...] {
10554 (let (pn elems extends)
10555 (if (js2-match-token js2-EXTENDS)
10556 (if (= (js2-peek-token) js2-LC)
10557 (js2-report-error "msg.missing.extends")
10558 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10559 (setq extends (js2-parse-assign-expr))
10560 (if (not extends)
10561 (js2-report-error "msg.bad.extends"))))
10562 (js2-must-match js2-LC "msg.no.brace.class")
10563 (setq elems (js2-parse-object-literal-elems t)
10564 pn (make-js2-class-node :pos pos
10565 :len (- js2-ts-cursor pos)
10566 :form form
10567 :name name
10568 :extends extends
10569 :elems elems))
10570 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10571 pn))
10572
10573 (defun js2-parse-object-literal ()
10574 (let* ((pos (js2-current-token-beg))
10575 (elems (js2-parse-object-literal-elems))
10576 (result (make-js2-object-node :pos pos
10577 :len (- js2-ts-cursor pos)
10578 :elems elems)))
10579 (apply #'js2-node-add-children result (js2-object-node-elems result))
10580 result))
10581
10582 (defun js2-property-key-string (property-node)
10583 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10584 `js2-getter-setter-node') as a string, or nil if it can't be
10585 represented as a string (e.g., the key is computed by an
10586 expression)."
10587 (let ((key (js2-infix-node-left property-node)))
10588 (cond
10589 ((js2-name-node-p key)
10590 (js2-name-node-name key))
10591 ((js2-string-node-p key)
10592 (js2-string-node-value key))
10593 ((js2-number-node-p key)
10594 (js2-number-node-value key)))))
10595
10596 (defun js2-parse-object-literal-elems (&optional class-p)
10597 (let ((pos (js2-current-token-beg))
10598 (static nil)
10599 (continue t)
10600 tt elems elem
10601 elem-key-string previous-elem-key-string
10602 after-comma previous-token)
10603 (while continue
10604 (setq tt (js2-get-prop-name-token)
10605 static nil
10606 elem nil
10607 previous-token nil)
10608 ;; Handle 'static' keyword only if we're in a class
10609 (when (and class-p (= js2-NAME tt)
10610 (string= "static" (js2-current-token-string)))
10611 (js2-record-face 'font-lock-keyword-face)
10612 (setq static t
10613 tt (js2-get-prop-name-token)))
10614 ;; Handle generator * before the property name for in-line functions
10615 (when (and (>= js2-language-version 200)
10616 (= js2-MUL tt))
10617 (setq previous-token (js2-current-token)
10618 tt (js2-get-prop-name-token)))
10619 ;; Handle 'get' or 'set' keywords
10620 (let ((prop (js2-current-token-string)))
10621 (when (and (>= js2-language-version 200)
10622 (= js2-NAME tt)
10623 (or (string= prop "get")
10624 (string= prop "set"))
10625 (member (js2-peek-token)
10626 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10627 (setq previous-token (js2-current-token)
10628 tt (js2-get-prop-name-token))))
10629 (cond
10630 ;; Found a property (of any sort)
10631 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10632 (setq after-comma nil
10633 elem (js2-parse-named-prop tt pos previous-token))
10634 (if (and (null elem)
10635 (not js2-recover-from-parse-errors))
10636 (setq continue nil)))
10637 ;; Break out of loop, and handle trailing commas.
10638 ((or (= tt js2-RC)
10639 (= tt js2-EOF))
10640 (js2-unget-token)
10641 (setq continue nil)
10642 (if after-comma
10643 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10644 pos elems after-comma)))
10645 (t
10646 (js2-report-error "msg.bad.prop")
10647 (unless js2-recover-from-parse-errors
10648 (setq continue nil)))) ; end switch
10649 ;; Handle static for classes' codegen.
10650 (if static
10651 (if elem (js2-node-set-prop elem 'STATIC t)
10652 (js2-report-error "msg.unexpected.static")))
10653 ;; Handle commas, depending on class-p.
10654 (let ((tok (js2-get-prop-name-token)))
10655 (if (eq tok js2-COMMA)
10656 (if class-p
10657 (js2-report-error "msg.class.unexpected.comma")
10658 (setq after-comma (js2-current-token-end)))
10659 (js2-unget-token)
10660 (unless class-p (setq continue nil))))
10661 (when elem
10662 (when (and js2-in-use-strict-directive
10663 (setq elem-key-string (js2-property-key-string elem))
10664 (cl-some
10665 (lambda (previous-elem)
10666 (and (setq previous-elem-key-string
10667 (js2-property-key-string previous-elem))
10668 (string= previous-elem-key-string elem-key-string)))
10669 elems))
10670 (js2-report-error "msg.dup.obj.lit.prop.strict"
10671 elem-key-string
10672 (js2-node-abs-pos (js2-infix-node-left elem))
10673 (js2-node-len (js2-infix-node-left elem))))
10674 ;; Append any parsed element.
10675 (push elem elems))) ; end loop
10676 (js2-must-match js2-RC "msg.no.brace.prop")
10677 (nreverse elems)))
10678
10679 (defun js2-parse-named-prop (tt pos previous-token)
10680 "Parse a name, string, or getter/setter object property.
10681 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10682 (let ((key (cond
10683 ;; Literal string keys: {'foo': 'bar'}
10684 ((= tt js2-STRING)
10685 (make-js2-string-node))
10686 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10687 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10688 ((and (= tt js2-LB)
10689 (>= js2-language-version 200))
10690 (prog1 (js2-parse-expr)
10691 (js2-must-match js2-RB "msg.missing.computed.rb")))
10692 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10693 ((= tt js2-NUMBER)
10694 (make-js2-number-node))
10695 ;; Unquoted names: {foo: 12}
10696 ((= tt js2-NAME)
10697 (js2-create-name-node))
10698 ;; Anything else is an error
10699 (t (js2-report-error "msg.bad.prop"))))
10700 (prop (and previous-token (js2-token-string previous-token)))
10701 (property-type (when previous-token
10702 (if (= (js2-token-type previous-token) js2-MUL)
10703 "*"
10704 (js2-token-string previous-token)))))
10705 (when (or (string= prop "get")
10706 (string= prop "set"))
10707 (js2-set-face (js2-token-beg previous-token)
10708 (js2-token-end previous-token)
10709 'font-lock-keyword-face 'record)) ; get/set
10710 (cond
10711 ;; method definition: {f() {...}}
10712 ((and (= (js2-peek-token) js2-LP)
10713 (>= js2-language-version 200))
10714 (when (js2-name-node-p key) ; highlight function name properties
10715 (js2-record-face 'font-lock-function-name-face))
10716 (js2-parse-getter-setter-prop pos key property-type))
10717 ;; regular prop
10718 (t
10719 (let ((beg (js2-current-token-beg))
10720 (end (js2-current-token-end))
10721 (expr (js2-parse-plain-property key)))
10722 (when (and (= tt js2-NAME)
10723 (not js2-is-in-destructuring)
10724 js2-highlight-external-variables
10725 (js2-node-get-prop expr 'SHORTHAND))
10726 (js2-record-name-node key))
10727 (js2-set-face beg end
10728 (if (js2-function-node-p
10729 (js2-object-prop-node-right expr))
10730 'font-lock-function-name-face
10731 'font-lock-variable-name-face)
10732 'record)
10733 expr)))))
10734
10735 (defun js2-parse-plain-property (prop)
10736 "Parse a non-getter/setter property in an object literal.
10737 PROP is the node representing the property: a number, name,
10738 string or expression."
10739 (let* ((tt (js2-get-token))
10740 (pos (js2-node-pos prop))
10741 colon expr result)
10742 (cond
10743 ;; Abbreviated property, as in {foo, bar}
10744 ((and (>= js2-language-version 200)
10745 (or (= tt js2-COMMA)
10746 (= tt js2-RC))
10747 (not (js2-number-node-p prop)))
10748 (js2-unget-token)
10749 (setq result (make-js2-object-prop-node
10750 :pos pos
10751 :left prop
10752 :right prop
10753 :op-pos (js2-current-token-len)))
10754 (js2-node-add-children result prop)
10755 (js2-node-set-prop result 'SHORTHAND t)
10756 result)
10757 ;; Normal property
10758 (t
10759 (if (= tt js2-COLON)
10760 (setq colon (- (js2-current-token-beg) pos)
10761 expr (js2-parse-assign-expr))
10762 (js2-report-error "msg.no.colon.prop")
10763 (setq expr (make-js2-error-node)))
10764 (setq result (make-js2-object-prop-node
10765 :pos pos
10766 ;; don't include last consumed token in length
10767 :len (- (+ (js2-node-pos expr)
10768 (js2-node-len expr))
10769 pos)
10770 :left prop
10771 :right expr
10772 :op-pos colon))
10773 (js2-node-add-children result prop expr)
10774 result))))
10775
10776 (defun js2-parse-getter-setter-prop (pos prop type-string)
10777 "Parse getter or setter property in an object literal.
10778 JavaScript syntax is:
10779
10780 { get foo() {...}, set foo(x) {...} }
10781
10782 and expression closure style is also supported
10783
10784 { get foo() x, set foo(x) _x = x }
10785
10786 POS is the start position of the `get' or `set' keyword.
10787 PROP is the `js2-name-node' representing the property name.
10788 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10789 (let ((type (cond
10790 ((string= "get" type-string) js2-GET)
10791 ((string= "set" type-string) js2-SET)
10792 (t js2-FUNCTION)))
10793 result end
10794 (fn (js2-parse-function-expr)))
10795 ;; it has to be an anonymous function, as we already parsed the name
10796 (if (/= (js2-node-type fn) js2-FUNCTION)
10797 (js2-report-error "msg.bad.prop")
10798 (if (cl-plusp (length (js2-function-name fn)))
10799 (js2-report-error "msg.bad.prop")))
10800 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10801 (when (string= type-string "*")
10802 (setf (js2-function-node-generator-type fn) 'STAR))
10803 (setq end (js2-node-end fn)
10804 result (make-js2-getter-setter-node :type type
10805 :pos pos
10806 :len (- end pos)
10807 :left prop
10808 :right fn))
10809 (js2-node-add-children result prop fn)
10810 result))
10811
10812 (defun js2-create-name-node (&optional check-activation-p token string)
10813 "Create a name node using the current token and, optionally, STRING.
10814 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10815 (let* ((beg (js2-current-token-beg))
10816 (tt (js2-current-token-type))
10817 (s (or string
10818 (if (= js2-NAME tt)
10819 (js2-current-token-string)
10820 (js2-tt-name tt))))
10821 name)
10822 (setq name (make-js2-name-node :pos beg
10823 :name s
10824 :len (length s)))
10825 (if check-activation-p
10826 (js2-check-activation-name s (or token js2-NAME)))
10827 name))
10828
10829 ;;; Indentation support (bouncing)
10830
10831 ;; In recent-enough Emacs, we reuse the indentation code from
10832 ;; `js-mode'. To continue support for the older versions, some code
10833 ;; that was here previously was moved to `js2-old-indent.el'.
10834
10835 ;; Whichever indenter is used, it's often "wrong", however, and needs
10836 ;; to be overridden. The right long-term solution is probably to
10837 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
10838 ;; of coding. Even when a parse tree from `js2-parse' is present,
10839 ;; which is not true at the moment the user is typing, computing
10840 ;; indentation is still thousands of lines of code to handle every
10841 ;; possible syntactic edge case.
10842
10843 ;; In the meantime, the compromise solution is that we offer a "bounce
10844 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10845 ;; current line indent among various likely guess points. This approach
10846 ;; is far from perfect, but should at least make it slightly easier to
10847 ;; move the line towards its desired indentation when manually
10848 ;; overriding Karl's heuristic nesting guesser.
10849
10850 (defun js2-backward-sws ()
10851 "Move backward through whitespace and comments."
10852 (interactive)
10853 (while (forward-comment -1)))
10854
10855 (defun js2-forward-sws ()
10856 "Move forward through whitespace and comments."
10857 (interactive)
10858 (while (forward-comment 1)))
10859
10860 (defun js2-arglist-close ()
10861 "Return non-nil if we're on a line beginning with a close-paren/brace."
10862 (save-excursion
10863 (goto-char (point-at-bol))
10864 (js2-forward-sws)
10865 (looking-at "[])}]")))
10866
10867 (defun js2-indent-looks-like-label-p ()
10868 (goto-char (point-at-bol))
10869 (js2-forward-sws)
10870 (looking-at (concat js2-mode-identifier-re ":")))
10871
10872 (defun js2-indent-in-objlit-p (parse-status)
10873 "Return non-nil if this looks like an object-literal entry."
10874 (let ((start (nth 1 parse-status)))
10875 (and
10876 start
10877 (save-excursion
10878 (and (zerop (forward-line -1))
10879 (not (< (point) start)) ; crossed a {} boundary
10880 (js2-indent-looks-like-label-p)))
10881 (save-excursion
10882 (js2-indent-looks-like-label-p)))))
10883
10884 ;; If prev line looks like foobar({ then we're passing an object
10885 ;; literal to a function call, and people pretty much always want to
10886 ;; de-dent back to the previous line, so move the 'basic-offset'
10887 ;; position to the front.
10888 (defun js2-indent-objlit-arg-p (parse-status)
10889 (save-excursion
10890 (back-to-indentation)
10891 (js2-backward-sws)
10892 (and (eq (1- (point)) (nth 1 parse-status))
10893 (eq (char-before) ?{)
10894 (progn
10895 (forward-char -1)
10896 (skip-chars-backward " \t")
10897 (eq (char-before) ?\()))))
10898
10899 (defun js2-indent-case-block-p ()
10900 (save-excursion
10901 (back-to-indentation)
10902 (js2-backward-sws)
10903 (goto-char (point-at-bol))
10904 (skip-chars-forward " \t")
10905 (looking-at "case\\s-.+:")))
10906
10907 (defun js2-bounce-indent (normal-col parse-status &optional backward)
10908 "Cycle among alternate computed indentation positions.
10909 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10910 of the buffer to the current point. NORMAL-COL is the indentation
10911 column computed by the heuristic guesser based on current paren,
10912 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10913 in reverse."
10914 (let ((cur-indent (current-indentation))
10915 (old-buffer-undo-list buffer-undo-list)
10916 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10917 (current-line (save-excursion
10918 (forward-line 0) ; move to bol
10919 (1+ (count-lines (point-min) (point)))))
10920 positions pos main-pos anchor arglist-cont same-indent
10921 basic-offset computed-pos)
10922 ;; temporarily don't record undo info, if user requested this
10923 (when js2-mode-indent-inhibit-undo
10924 (setq buffer-undo-list t))
10925 (unwind-protect
10926 (progn
10927 ;; First likely point: indent from beginning of previous code line
10928 (push (setq basic-offset
10929 (+ (save-excursion
10930 (back-to-indentation)
10931 (js2-backward-sws)
10932 (back-to-indentation)
10933 (current-column))
10934 js2-basic-offset))
10935 positions)
10936
10937 ;; (First + epsilon) likely point: indent 2x from beginning of
10938 ;; previous code line. Google does it this way.
10939 (push (setq basic-offset
10940 (+ (save-excursion
10941 (back-to-indentation)
10942 (js2-backward-sws)
10943 (back-to-indentation)
10944 (current-column))
10945 (* 2 js2-basic-offset)))
10946 positions)
10947
10948 ;; Second likely point: indent from assign-expr RHS. This
10949 ;; is just a crude guess based on finding " = " on the previous
10950 ;; line containing actual code.
10951 (setq pos (save-excursion
10952 (forward-line -1)
10953 (goto-char (point-at-bol))
10954 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10955 (point-at-eol) t)
10956 (goto-char (match-end 1))
10957 (skip-chars-forward " \t\r\n")
10958 (current-column))))
10959 (when pos
10960 (cl-incf pos js2-basic-offset)
10961 (push pos positions))
10962
10963 ;; Third likely point: same indent as previous line of code.
10964 ;; Make it the first likely point if we're not on an
10965 ;; arglist-close line and previous line ends in a comma, or
10966 ;; both this line and prev line look like object-literal
10967 ;; elements.
10968 (setq pos (save-excursion
10969 (goto-char (point-at-bol))
10970 (js2-backward-sws)
10971 (back-to-indentation)
10972 (prog1
10973 (current-column)
10974 ;; while we're here, look for trailing comma
10975 (if (save-excursion
10976 (goto-char (point-at-eol))
10977 (js2-backward-sws)
10978 (eq (char-before) ?,))
10979 (setq arglist-cont (1- (point)))))))
10980 (when pos
10981 (if (and (or arglist-cont
10982 (js2-indent-in-objlit-p parse-status))
10983 (not (js2-arglist-close)))
10984 (setq same-indent pos))
10985 (push pos positions))
10986
10987 ;; Fourth likely point: first preceding code with less indentation.
10988 ;; than the immediately preceding code line.
10989 (setq pos (save-excursion
10990 (back-to-indentation)
10991 (js2-backward-sws)
10992 (back-to-indentation)
10993 (setq anchor (current-column))
10994 (while (and (zerop (forward-line -1))
10995 (>= (progn
10996 (back-to-indentation)
10997 (current-column))
10998 anchor)))
10999 (setq pos (current-column))))
11000 (push pos positions)
11001
11002 ;; nesting-heuristic position, main by default
11003 (push (setq main-pos normal-col) positions)
11004
11005 ;; delete duplicates and sort positions list
11006 (setq positions (sort (delete-dups positions) '<))
11007
11008 ;; comma-list continuation lines: prev line indent takes precedence
11009 (if same-indent
11010 (setq main-pos same-indent))
11011
11012 ;; common special cases where we want to indent in from previous line
11013 (if (or (js2-indent-case-block-p)
11014 (js2-indent-objlit-arg-p parse-status))
11015 (setq main-pos basic-offset))
11016
11017 ;; if bouncing backward, reverse positions list
11018 (if backward
11019 (setq positions (reverse positions)))
11020
11021 ;; record whether we're already sitting on one of the alternatives
11022 (setq pos (member cur-indent positions))
11023
11024 (cond
11025 ;; case 0: we're one one of the alternatives and this is the
11026 ;; first time they've pressed TAB on this line (best-guess).
11027 ((and js2-mode-indent-ignore-first-tab
11028 pos
11029 ;; first time pressing TAB on this line?
11030 (not (eq js2-mode-last-indented-line current-line)))
11031 ;; do nothing
11032 (setq computed-pos nil))
11033 ;; case 1: only one computed position => use it
11034 ((null (cdr positions))
11035 (setq computed-pos 0))
11036 ;; case 2: not on any of the computed spots => use main spot
11037 ((not pos)
11038 (setq computed-pos (js2-position main-pos positions)))
11039 ;; case 3: on last position: cycle to first position
11040 ((null (cdr pos))
11041 (setq computed-pos 0))
11042 ;; case 4: on intermediate position: cycle to next position
11043 (t
11044 (setq computed-pos (js2-position (cl-second pos) positions))))
11045
11046 ;; see if any hooks want to indent; otherwise we do it
11047 (cl-loop with result = nil
11048 for hook in js2-indent-hook
11049 while (null result)
11050 do
11051 (setq result (funcall hook positions computed-pos))
11052 finally do
11053 (unless (or result (null computed-pos))
11054 (indent-line-to (nth computed-pos positions)))))
11055
11056 ;; finally
11057 (if js2-mode-indent-inhibit-undo
11058 (setq buffer-undo-list old-buffer-undo-list))
11059 ;; see commentary for `js2-mode-last-indented-line'
11060 (setq js2-mode-last-indented-line current-line))))
11061
11062 (defun js2-1-line-comment-continuation-p ()
11063 "Return t if we're in a 1-line comment continuation.
11064 If so, we don't ever want to use bounce-indent."
11065 (save-excursion
11066 (and (progn
11067 (forward-line 0)
11068 (looking-at "\\s-*//"))
11069 (progn
11070 (forward-line -1)
11071 (forward-line 0)
11072 (when (looking-at "\\s-*$")
11073 (js2-backward-sws)
11074 (forward-line 0))
11075 (looking-at "\\s-*//")))))
11076
11077 (defun js2-indent-bounce (&optional backward)
11078 "Indent the current line, bouncing between several positions."
11079 (interactive)
11080 (let (parse-status offset indent-col
11081 ;; Don't whine about errors/warnings when we're indenting.
11082 ;; This has to be set before calling parse-partial-sexp below.
11083 (inhibit-point-motion-hooks t))
11084 (setq parse-status (save-excursion
11085 (syntax-ppss (point-at-bol)))
11086 offset (- (point) (save-excursion
11087 (back-to-indentation)
11088 (point))))
11089 ;; Don't touch multiline strings.
11090 (unless (nth 3 parse-status)
11091 (setq indent-col (js2-proper-indentation parse-status))
11092 (cond
11093 ;; It doesn't work well on first line of buffer.
11094 ((and (not (nth 4 parse-status))
11095 (not (js2-same-line (point-min)))
11096 (not (js2-1-line-comment-continuation-p)))
11097 (js2-bounce-indent indent-col parse-status backward))
11098 ;; just indent to the guesser's likely spot
11099 (t (indent-line-to indent-col)))
11100 (when (cl-plusp offset)
11101 (forward-char offset)))))
11102
11103 (defun js2-indent-bounce-backward ()
11104 "Indent the current line, bouncing between positions in reverse."
11105 (interactive)
11106 (js2-indent-bounce t))
11107
11108 (defun js2-indent-region (start end)
11109 "Indent the region, but don't use bounce indenting."
11110 (let ((js2-bounce-indent-p nil)
11111 (indent-region-function nil)
11112 (after-change-functions (remq 'js2-mode-edit
11113 after-change-functions)))
11114 (indent-region start end nil) ; nil for byte-compiler
11115 (js2-mode-edit start end (- end start))))
11116
11117 (defvar js2-minor-mode-map
11118 (let ((map (make-sparse-keymap)))
11119 (define-key map (kbd "C-c C-`") #'js2-next-error)
11120 (define-key map [mouse-1] #'js2-mode-show-node)
11121 map)
11122 "Keymap used when `js2-minor-mode' is active.")
11123
11124 ;;;###autoload
11125 (define-minor-mode js2-minor-mode
11126 "Minor mode for running js2 as a background linter.
11127 This allows you to use a different major mode for JavaScript editing,
11128 such as `js-mode', while retaining the asynchronous error/warning
11129 highlighting features of `js2-mode'."
11130 :group 'js2-mode
11131 :lighter " js-lint"
11132 (if js2-minor-mode
11133 (js2-minor-mode-enter)
11134 (js2-minor-mode-exit)))
11135
11136 (defun js2-minor-mode-enter ()
11137 "Initialization for `js2-minor-mode'."
11138 (set (make-local-variable 'max-lisp-eval-depth)
11139 (max max-lisp-eval-depth 3000))
11140 (setq next-error-function #'js2-next-error)
11141 (js2-set-default-externs)
11142 ;; Experiment: make reparse-delay longer for longer files.
11143 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11144 (setq js2-idle-timer-delay
11145 (* js2-idle-timer-delay
11146 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11147 (setq js2-mode-buffer-dirty-p t
11148 js2-mode-parsing nil)
11149 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11150 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11151 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11152 (when js2-include-jslint-globals
11153 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11154 (run-hooks 'js2-init-hook)
11155 (js2-reparse))
11156
11157 (defun js2-minor-mode-exit ()
11158 "Turn off `js2-minor-mode'."
11159 (setq next-error-function nil)
11160 (remove-hook 'after-change-functions #'js2-mode-edit t)
11161 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11162 (when js2-mode-node-overlay
11163 (delete-overlay js2-mode-node-overlay)
11164 (setq js2-mode-node-overlay nil))
11165 (js2-remove-overlays)
11166 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11167 (setq js2-mode-ast nil))
11168
11169 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11170 (make-variable-buffer-local 'js2-source-buffer)
11171
11172 (cl-defun js2-display-error-list ()
11173 "Display a navigable buffer listing parse errors/warnings."
11174 (interactive)
11175 (unless (js2-have-errors-p)
11176 (message "No errors")
11177 (cl-return-from js2-display-error-list))
11178 (cl-labels ((annotate-list
11179 (lst type)
11180 "Add diagnostic TYPE and line number to errs list"
11181 (mapcar (lambda (err)
11182 (list err type (line-number-at-pos (nth 1 err))))
11183 lst)))
11184 (let* ((srcbuf (current-buffer))
11185 (errbuf (get-buffer-create "*js-lint*"))
11186 (errors (annotate-list
11187 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11188 'js2-error)) ; must be a valid face name
11189 (warnings (annotate-list
11190 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11191 'js2-warning)) ; must be a valid face name
11192 (all-errs (sort (append errors warnings)
11193 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11194 (with-current-buffer errbuf
11195 (let ((inhibit-read-only t))
11196 (erase-buffer)
11197 (dolist (err all-errs)
11198 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11199 (insert-text-button
11200 (format "line %d: %s" line (js2-get-msg msg-key))
11201 'face type
11202 'follow-link "\C-m"
11203 'action 'js2-error-buffer-jump
11204 'js2-msg (js2-get-msg msg-key)
11205 'js2-pos beg)
11206 (insert "\n"))))
11207 (js2-error-buffer-mode)
11208 (setq js2-source-buffer srcbuf)
11209 (pop-to-buffer errbuf)
11210 (goto-char (point-min))
11211 (unless (eobp)
11212 (js2-error-buffer-view))))))
11213
11214 (defvar js2-error-buffer-mode-map
11215 (let ((map (make-sparse-keymap)))
11216 (define-key map "n" #'js2-error-buffer-next)
11217 (define-key map "p" #'js2-error-buffer-prev)
11218 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11219 (define-key map "o" #'js2-error-buffer-view)
11220 (define-key map "q" #'js2-error-buffer-quit)
11221 map)
11222 "Keymap used for js2 diagnostics buffers.")
11223
11224 (defun js2-error-buffer-mode ()
11225 "Major mode for js2 diagnostics buffers.
11226 Selecting an error will jump it to the corresponding source-buffer error.
11227 \\{js2-error-buffer-mode-map}"
11228 (interactive)
11229 (setq major-mode 'js2-error-buffer-mode
11230 mode-name "JS Lint Diagnostics")
11231 (use-local-map js2-error-buffer-mode-map)
11232 (setq truncate-lines t)
11233 (set-buffer-modified-p nil)
11234 (setq buffer-read-only t)
11235 (run-hooks 'js2-error-buffer-mode-hook))
11236
11237 (defun js2-error-buffer-next ()
11238 "Move to next error and view it."
11239 (interactive)
11240 (when (zerop (forward-line 1))
11241 (js2-error-buffer-view)))
11242
11243 (defun js2-error-buffer-prev ()
11244 "Move to previous error and view it."
11245 (interactive)
11246 (when (zerop (forward-line -1))
11247 (js2-error-buffer-view)))
11248
11249 (defun js2-error-buffer-quit ()
11250 "Kill the current buffer."
11251 (interactive)
11252 (kill-buffer))
11253
11254 (defun js2-error-buffer-jump (&rest ignored)
11255 "Jump cursor to current error in source buffer."
11256 (interactive)
11257 (when (js2-error-buffer-view)
11258 (pop-to-buffer js2-source-buffer)))
11259
11260 (defun js2-error-buffer-view ()
11261 "Scroll source buffer to show error at current line."
11262 (interactive)
11263 (cond
11264 ((not (eq major-mode 'js2-error-buffer-mode))
11265 (message "Not in a js2 errors buffer"))
11266 ((not (buffer-live-p js2-source-buffer))
11267 (message "Source buffer has been killed"))
11268 ((not (wholenump (get-text-property (point) 'js2-pos)))
11269 (message "There does not seem to be an error here"))
11270 (t
11271 (let ((pos (get-text-property (point) 'js2-pos))
11272 (msg (get-text-property (point) 'js2-msg)))
11273 (save-selected-window
11274 (pop-to-buffer js2-source-buffer)
11275 (goto-char pos)
11276 (message msg))))))
11277
11278 ;;;###autoload
11279 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11280 "Major mode for editing JavaScript code."
11281 ;; Used by comment-region; don't change it.
11282 (set (make-local-variable 'max-lisp-eval-depth)
11283 (max max-lisp-eval-depth 3000))
11284 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11285 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11286 (set (make-local-variable 'syntax-propertize-function) nil)
11287 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11288 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11289 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11290 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11291 ;; for characters inside regexp literals.
11292 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11293 ;; this is necessary to make `show-paren-function' work properly
11294 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11295 ;; needed for M-x rgrep, among other things
11296 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11297
11298 (setq font-lock-defaults '(nil t))
11299
11300 ;; Experiment: make reparse-delay longer for longer files.
11301 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11302 (setq js2-idle-timer-delay
11303 (* js2-idle-timer-delay
11304 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11305
11306 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11307 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11308 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11309 (setq next-error-function #'js2-next-error)
11310 (imenu-add-to-menubar (concat "IM-" mode-name))
11311 (add-to-invisibility-spec '(js2-outline . t))
11312 (set (make-local-variable 'line-move-ignore-invisible) t)
11313 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11314 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11315
11316 (setq js2-mode-functions-hidden nil
11317 js2-mode-comments-hidden nil
11318 js2-mode-buffer-dirty-p t
11319 js2-mode-parsing nil)
11320
11321 (js2-set-default-externs)
11322
11323 (when js2-include-jslint-globals
11324 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11325
11326 (run-hooks 'js2-init-hook)
11327
11328 (js2-reparse))
11329
11330 (defun js2-mode-exit ()
11331 "Exit `js2-mode' and clean up."
11332 (interactive)
11333 (when js2-mode-node-overlay
11334 (delete-overlay js2-mode-node-overlay)
11335 (setq js2-mode-node-overlay nil))
11336 (js2-remove-overlays)
11337 (setq js2-mode-ast nil)
11338 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11339 (remove-from-invisibility-spec '(js2-outline . t))
11340 (js2-mode-show-all)
11341 (with-silent-modifications
11342 (js2-clear-face (point-min) (point-max))))
11343
11344 (defun js2-mode-reset-timer ()
11345 "Cancel any existing parse timer and schedule a new one."
11346 (if js2-mode-parse-timer
11347 (cancel-timer js2-mode-parse-timer))
11348 (setq js2-mode-parsing nil)
11349 (let ((timer (timer-create)))
11350 (setq js2-mode-parse-timer timer)
11351 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11352 (timer-set-idle-time timer js2-idle-timer-delay)
11353 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11354 (timer-activate-when-idle timer nil)))
11355
11356 (defun js2-mode-idle-reparse (buffer)
11357 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11358 it to be reparsed when the buffer is selected."
11359 (cond ((eq buffer (current-buffer))
11360 (js2-reparse))
11361 ((buffer-live-p buffer)
11362 ;; reparse when the buffer is selected again
11363 (with-current-buffer buffer
11364 (add-hook 'window-configuration-change-hook
11365 #'js2-mode-idle-reparse-inner
11366 nil t)))))
11367
11368 (defun js2-mode-idle-reparse-inner ()
11369 (remove-hook 'window-configuration-change-hook
11370 #'js2-mode-idle-reparse-inner
11371 t)
11372 (js2-reparse))
11373
11374 (defun js2-mode-edit (_beg _end _len)
11375 "Schedule a new parse after buffer is edited.
11376 Buffer edit spans from BEG to END and is of length LEN."
11377 (setq js2-mode-buffer-dirty-p t)
11378 (js2-mode-hide-overlay)
11379 (js2-mode-reset-timer))
11380
11381 (defun js2-minor-mode-edit (_beg _end _len)
11382 "Callback for buffer edits in `js2-mode'.
11383 Schedules a new parse after buffer is edited.
11384 Buffer edit spans from BEG to END and is of length LEN."
11385 (setq js2-mode-buffer-dirty-p t)
11386 (js2-mode-hide-overlay)
11387 (js2-mode-reset-timer))
11388
11389 (defun js2-reparse (&optional force)
11390 "Re-parse current buffer after user finishes some data entry.
11391 If we get any user input while parsing, including cursor motion,
11392 we discard the parse and reschedule it. If FORCE is nil, then the
11393 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11394 (let (time
11395 interrupted-p
11396 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11397 (unless js2-mode-parsing
11398 (setq js2-mode-parsing t)
11399 (unwind-protect
11400 (when (or js2-mode-buffer-dirty-p force)
11401 (js2-remove-overlays)
11402 (setq js2-mode-buffer-dirty-p nil
11403 js2-mode-fontifications nil
11404 js2-mode-deferred-properties nil)
11405 (if js2-mode-verbose-parse-p
11406 (message "parsing..."))
11407 (setq time
11408 (js2-time
11409 (setq interrupted-p
11410 (catch 'interrupted
11411 (js2-parse)
11412 (with-silent-modifications
11413 ;; if parsing is interrupted, comments and regex
11414 ;; literals stay ignored by `parse-partial-sexp'
11415 (remove-text-properties (point-min) (point-max)
11416 '(syntax-table))
11417 (js2-mode-apply-deferred-properties)
11418 (js2-mode-remove-suppressed-warnings)
11419 (js2-mode-show-warnings)
11420 (js2-mode-show-errors)
11421 (if (>= js2-highlight-level 1)
11422 (js2-highlight-jsdoc js2-mode-ast)))
11423 nil))))
11424 (if interrupted-p
11425 (progn
11426 ;; unfinished parse => try again
11427 (setq js2-mode-buffer-dirty-p t)
11428 (js2-mode-reset-timer))
11429 (if js2-mode-verbose-parse-p
11430 (message "Parse time: %s" time))))
11431 (setq js2-mode-parsing nil)
11432 (unless interrupted-p
11433 (setq js2-mode-parse-timer nil))))))
11434
11435 (defun js2-mode-show-node (event)
11436 "Debugging aid: highlight selected AST node on mouse click."
11437 (interactive "e")
11438 (mouse-set-point event)
11439 (setq deactivate-mark t)
11440 (when js2-mode-show-overlay
11441 (let ((node (js2-node-at-point))
11442 beg end)
11443 (if (null node)
11444 (message "No node found at location %s" (point))
11445 (setq beg (js2-node-abs-pos node)
11446 end (+ beg (js2-node-len node)))
11447 (if js2-mode-node-overlay
11448 (move-overlay js2-mode-node-overlay beg end)
11449 (setq js2-mode-node-overlay (make-overlay beg end))
11450 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11451 (with-silent-modifications
11452 (if (fboundp 'cursor-sensor-mode)
11453 (put-text-property beg end 'cursor-sensor-functions
11454 '(js2-mode-hide-overlay))
11455 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11456 (message "%s, parent: %s"
11457 (js2-node-short-name node)
11458 (if (js2-node-parent node)
11459 (js2-node-short-name (js2-node-parent node))
11460 "nil"))))))
11461
11462 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11463 "Remove the debugging overlay when point moves.
11464 ARG1, ARG2 and ARG3 have different values depending on whether this function
11465 was found on `point-left' or in `cursor-sensor-functions'."
11466 (when js2-mode-node-overlay
11467 (let ((beg (overlay-start js2-mode-node-overlay))
11468 (end (overlay-end js2-mode-node-overlay))
11469 (p2 (if (windowp arg1)
11470 ;; Called from cursor-sensor-functions.
11471 (window-point arg1)
11472 ;; Called from point-left.
11473 arg2)))
11474 ;; Sometimes we're called spuriously.
11475 (unless (and p2
11476 (>= p2 beg)
11477 (<= p2 end))
11478 (with-silent-modifications
11479 (remove-text-properties beg end
11480 '(point-left nil cursor-sensor-functions)))
11481 (delete-overlay js2-mode-node-overlay)
11482 (setq js2-mode-node-overlay nil)))))
11483
11484 (defun js2-mode-reset ()
11485 "Debugging helper: reset everything."
11486 (interactive)
11487 (js2-mode-exit)
11488 (js2-mode))
11489
11490 (defun js2-mode-show-warn-or-err (e face)
11491 "Highlight a warning or error E with FACE.
11492 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11493 The last element is optional. When present, use instead of FACE."
11494 (let* ((key (cl-first e))
11495 (beg (cl-second e))
11496 (end (+ beg (cl-third e)))
11497 ;; Don't inadvertently go out of bounds.
11498 (beg (max (point-min) (min beg (point-max))))
11499 (end (max (point-min) (min end (point-max))))
11500 (ovl (make-overlay beg end)))
11501 ;; FIXME: Why a mix of overlays and text-properties?
11502 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11503 (overlay-put ovl 'js2-error t)
11504 (put-text-property beg end 'help-echo (js2-get-msg key))
11505 (if (fboundp 'cursor-sensor-mode)
11506 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11507 (put-text-property beg end 'point-entered #'js2-echo-error))))
11508
11509 (defun js2-remove-overlays ()
11510 "Remove overlays from buffer that have a `js2-error' property."
11511 (let ((beg (point-min))
11512 (end (point-max)))
11513 (save-excursion
11514 (dolist (o (overlays-in beg end))
11515 (when (overlay-get o 'js2-error)
11516 (delete-overlay o))))))
11517
11518 (defun js2-mode-apply-deferred-properties ()
11519 "Apply fontifications and other text properties recorded during parsing."
11520 (when (cl-plusp js2-highlight-level)
11521 ;; We defer clearing faces as long as possible to eliminate flashing.
11522 (js2-clear-face (point-min) (point-max))
11523 ;; Have to reverse the recorded fontifications list so that errors
11524 ;; and warnings overwrite the normal fontifications.
11525 (dolist (f (nreverse js2-mode-fontifications))
11526 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11527 (setq js2-mode-fontifications nil))
11528 (dolist (p js2-mode-deferred-properties)
11529 (apply #'put-text-property p))
11530 (setq js2-mode-deferred-properties nil))
11531
11532 (defun js2-mode-show-errors ()
11533 "Highlight syntax errors."
11534 (when js2-mode-show-parse-errors
11535 (dolist (e (js2-ast-root-errors js2-mode-ast))
11536 (js2-mode-show-warn-or-err e 'js2-error))))
11537
11538 (defun js2-mode-remove-suppressed-warnings ()
11539 "Take suppressed warnings out of the AST warnings list.
11540 This ensures that the counts and `next-error' are correct."
11541 (setf (js2-ast-root-warnings js2-mode-ast)
11542 (js2-delete-if
11543 (lambda (e)
11544 (let ((key (caar e)))
11545 (or
11546 (and (not js2-strict-trailing-comma-warning)
11547 (string-match "trailing\\.comma" key))
11548 (and (not js2-strict-cond-assign-warning)
11549 (string= key "msg.equal.as.assign"))
11550 (and js2-missing-semi-one-line-override
11551 (string= key "msg.missing.semi")
11552 (let* ((beg (cl-second e))
11553 (node (js2-node-at-point beg))
11554 (fn (js2-mode-find-parent-fn node))
11555 (body (and fn (js2-function-node-body fn)))
11556 (lc (and body (js2-node-abs-pos body)))
11557 (rc (and lc (+ lc (js2-node-len body)))))
11558 (and fn
11559 (or (null body)
11560 (save-excursion
11561 (goto-char beg)
11562 (and (js2-same-line lc)
11563 (js2-same-line rc))))))))))
11564 (js2-ast-root-warnings js2-mode-ast))))
11565
11566 (defun js2-mode-show-warnings ()
11567 "Highlight strict-mode warnings."
11568 (when js2-mode-show-strict-warnings
11569 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11570 (js2-mode-show-warn-or-err e 'js2-warning))))
11571
11572 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11573 "Called by point-motion hooks.
11574 ARG1, ARG2 and ARG3 have different values depending on whether this function
11575 was found on `point-entered' or in `cursor-sensor-functions'."
11576 (let* ((new-point (if (windowp arg1)
11577 ;; Called from cursor-sensor-functions.
11578 (window-point arg1)
11579 ;; Called from point-left.
11580 arg2))
11581 (msg (get-text-property new-point 'help-echo)))
11582 (when (and (stringp msg)
11583 (not (active-minibuffer-window))
11584 (not (current-message)))
11585 (message msg))))
11586
11587 (defun js2-line-break (&optional _soft)
11588 "Break line at point and indent, continuing comment if within one.
11589 If inside a string, and `js2-concat-multiline-strings' is not
11590 nil, turn it into concatenation."
11591 (interactive)
11592 (let ((parse-status (syntax-ppss)))
11593 (cond
11594 ;; Check if we're inside a string.
11595 ((nth 3 parse-status)
11596 (if js2-concat-multiline-strings
11597 (js2-mode-split-string parse-status)
11598 (insert "\n")))
11599 ;; Check if inside a block comment.
11600 ((nth 4 parse-status)
11601 (js2-mode-extend-comment (nth 8 parse-status)))
11602 (t
11603 (newline-and-indent)))))
11604
11605 (defun js2-mode-split-string (parse-status)
11606 "Turn a newline in mid-string into a string concatenation.
11607 PARSE-STATUS is as documented in `parse-partial-sexp'."
11608 (let* ((quote-char (nth 3 parse-status))
11609 (at-eol (eq js2-concat-multiline-strings 'eol)))
11610 (insert quote-char)
11611 (insert (if at-eol " +\n" "\n"))
11612 (unless at-eol
11613 (insert "+ "))
11614 (js2-indent-line)
11615 (insert quote-char)
11616 (when (eolp)
11617 (insert quote-char)
11618 (backward-char 1))))
11619
11620 (defun js2-mode-extend-comment (start-pos)
11621 "Indent the line and, when inside a comment block, add comment prefix."
11622 (let (star single col first-line needs-close)
11623 (save-excursion
11624 (back-to-indentation)
11625 (when (< (point) start-pos)
11626 (goto-char start-pos))
11627 (cond
11628 ((looking-at "\\*[^/]")
11629 (setq star t
11630 col (current-column)))
11631 ((looking-at "/\\*")
11632 (setq star t
11633 first-line t
11634 col (1+ (current-column))))
11635 ((looking-at "//")
11636 (setq single t
11637 col (current-column)))))
11638 ;; Heuristic for whether we need to close the comment:
11639 ;; if we've got a parse error here, assume it's an unterminated
11640 ;; comment.
11641 (setq needs-close
11642 (or
11643 (get-char-property (1- (point)) 'js2-error)
11644 ;; The heuristic above doesn't work well when we're
11645 ;; creating a comment and there's another one downstream,
11646 ;; as our parser thinks this one ends at the end of the
11647 ;; next one. (You can have a /* inside a js block comment.)
11648 ;; So just close it if the next non-ws char isn't a *.
11649 (and first-line
11650 (eolp)
11651 (save-excursion
11652 (skip-chars-forward " \t\r\n")
11653 (not (eq (char-after) ?*))))))
11654 (delete-horizontal-space)
11655 (insert "\n")
11656 (cond
11657 (star
11658 (indent-to col)
11659 (insert "* ")
11660 (if (and first-line needs-close)
11661 (save-excursion
11662 (insert "\n")
11663 (indent-to col)
11664 (insert "*/"))))
11665 ((and single
11666 (save-excursion
11667 (and (zerop (forward-line 1))
11668 (looking-at "\\s-*//"))))
11669 (indent-to col)
11670 (insert "// ")))
11671 ;; Don't need to extend the comment after all.
11672 (js2-indent-line)))
11673
11674 (defun js2-beginning-of-line ()
11675 "Toggle point between bol and first non-whitespace char in line.
11676 Also moves past comment delimiters when inside comments."
11677 (interactive)
11678 (let (node)
11679 (cond
11680 ((bolp)
11681 (back-to-indentation))
11682 ((looking-at "//")
11683 (skip-chars-forward "/ \t"))
11684 ((and (eq (char-after) ?*)
11685 (setq node (js2-comment-at-point))
11686 (memq (js2-comment-node-format node) '(jsdoc block))
11687 (save-excursion
11688 (skip-chars-backward " \t")
11689 (bolp)))
11690 (skip-chars-forward "\* \t"))
11691 (t
11692 (goto-char (point-at-bol))))))
11693
11694 (defun js2-end-of-line ()
11695 "Toggle point between eol and last non-whitespace char in line."
11696 (interactive)
11697 (if (eolp)
11698 (skip-chars-backward " \t")
11699 (goto-char (point-at-eol))))
11700
11701 (defun js2-mode-wait-for-parse (callback)
11702 "Invoke CALLBACK when parsing is finished.
11703 If parsing is already finished, calls CALLBACK immediately."
11704 (if (not js2-mode-buffer-dirty-p)
11705 (funcall callback)
11706 (push callback js2-mode-pending-parse-callbacks)
11707 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11708
11709 (defun js2-mode-parse-finished ()
11710 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11711 ;; We can't let errors propagate up, since it prevents the
11712 ;; `js2-parse' method from completing normally and returning
11713 ;; the ast, which makes things mysteriously not work right.
11714 (unwind-protect
11715 (dolist (cb js2-mode-pending-parse-callbacks)
11716 (condition-case err
11717 (funcall cb)
11718 (error (message "%s" err))))
11719 (setq js2-mode-pending-parse-callbacks nil)))
11720
11721 (defun js2-mode-flag-region (from to flag)
11722 "Hide or show text from FROM to TO, according to FLAG.
11723 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11724 Returns the created overlay if FLAG is non-nil."
11725 (remove-overlays from to 'invisible 'js2-outline)
11726 (when flag
11727 (let ((o (make-overlay from to)))
11728 (overlay-put o 'invisible 'js2-outline)
11729 (overlay-put o 'isearch-open-invisible
11730 'js2-isearch-open-invisible)
11731 o)))
11732
11733 ;; Function to be set as an outline-isearch-open-invisible' property
11734 ;; to the overlay that makes the outline invisible (see
11735 ;; `js2-mode-flag-region').
11736 (defun js2-isearch-open-invisible (_overlay)
11737 ;; We rely on the fact that isearch places point on the matched text.
11738 (js2-mode-show-element))
11739
11740 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11741 "Return cons cell of bounds of folding overlay at POS.
11742 Returns nil if not found."
11743 (let ((overlays (overlays-at (or pos (point))))
11744 o)
11745 (while (and overlays
11746 (not o))
11747 (if (overlay-get (car overlays) 'invisible)
11748 (setq o (car overlays))
11749 (setq overlays (cdr overlays))))
11750 (if o
11751 (cons (overlay-start o) (overlay-end o)))))
11752
11753 (defun js2-mode-function-at-point (&optional pos)
11754 "Return the innermost function node enclosing current point.
11755 Returns nil if point is not in a function."
11756 (let ((node (js2-node-at-point pos)))
11757 (while (and node (not (js2-function-node-p node)))
11758 (setq node (js2-node-parent node)))
11759 (if (js2-function-node-p node)
11760 node)))
11761
11762 (defun js2-mode-toggle-element ()
11763 "Hide or show the foldable element at the point."
11764 (interactive)
11765 (let (comment fn pos)
11766 (save-excursion
11767 (cond
11768 ;; /* ... */ comment?
11769 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11770 (if (js2-mode-invisible-overlay-bounds
11771 (setq pos (+ 3 (js2-node-abs-pos comment))))
11772 (progn
11773 (goto-char pos)
11774 (js2-mode-show-element))
11775 (js2-mode-hide-element)))
11776 ;; //-comment?
11777 ((save-excursion
11778 (back-to-indentation)
11779 (looking-at js2-mode-//-comment-re))
11780 (js2-mode-toggle-//-comment))
11781 ;; function?
11782 ((setq fn (js2-mode-function-at-point))
11783 (setq pos (and (js2-function-node-body fn)
11784 (js2-node-abs-pos (js2-function-node-body fn))))
11785 (goto-char (1+ pos))
11786 (if (js2-mode-invisible-overlay-bounds)
11787 (js2-mode-show-element)
11788 (js2-mode-hide-element)))
11789 (t
11790 (message "Nothing at point to hide or show"))))))
11791
11792 (defun js2-mode-hide-element ()
11793 "Fold/hide contents of a block, showing ellipses.
11794 Show the hidden text with \\[js2-mode-show-element]."
11795 (interactive)
11796 (if js2-mode-buffer-dirty-p
11797 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11798 (let (node body beg end)
11799 (cond
11800 ((js2-mode-invisible-overlay-bounds)
11801 (message "already hidden"))
11802 (t
11803 (setq node (js2-node-at-point))
11804 (cond
11805 ((js2-block-comment-p node)
11806 (js2-mode-hide-comment node))
11807 (t
11808 (while (and node (not (js2-function-node-p node)))
11809 (setq node (js2-node-parent node)))
11810 (if (and node
11811 (setq body (js2-function-node-body node)))
11812 (progn
11813 (setq beg (js2-node-abs-pos body)
11814 end (+ beg (js2-node-len body)))
11815 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11816 (message "No collapsable element found at point"))))))))
11817
11818 (defun js2-mode-show-element ()
11819 "Show the hidden element at current point."
11820 (interactive)
11821 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11822 (if bounds
11823 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11824 (message "Nothing to un-hide"))))
11825
11826 (defun js2-mode-show-all ()
11827 "Show all of the text in the buffer."
11828 (interactive)
11829 (js2-mode-flag-region (point-min) (point-max) nil))
11830
11831 (defun js2-mode-toggle-hide-functions ()
11832 (interactive)
11833 (if js2-mode-functions-hidden
11834 (js2-mode-show-functions)
11835 (js2-mode-hide-functions)))
11836
11837 (defun js2-mode-hide-functions ()
11838 "Hides all non-nested function bodies in the buffer.
11839 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11840 to open an individual entry."
11841 (interactive)
11842 (if js2-mode-buffer-dirty-p
11843 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11844 (if (null js2-mode-ast)
11845 (message "Oops - parsing failed")
11846 (setq js2-mode-functions-hidden t)
11847 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11848
11849 (defun js2-mode-function-hider (n endp)
11850 (when (not endp)
11851 (let ((tt (js2-node-type n))
11852 body beg end)
11853 (cond
11854 ((and (= tt js2-FUNCTION)
11855 (setq body (js2-function-node-body n)))
11856 (setq beg (js2-node-abs-pos body)
11857 end (+ beg (js2-node-len body)))
11858 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11859 nil) ; don't process children of function
11860 (t
11861 t))))) ; keep processing other AST nodes
11862
11863 (defun js2-mode-show-functions ()
11864 "Un-hide any folded function bodies in the buffer."
11865 (interactive)
11866 (setq js2-mode-functions-hidden nil)
11867 (save-excursion
11868 (goto-char (point-min))
11869 (while (/= (goto-char (next-overlay-change (point)))
11870 (point-max))
11871 (dolist (o (overlays-at (point)))
11872 (when (and (overlay-get o 'invisible)
11873 (not (overlay-get o 'comment)))
11874 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11875
11876 (defun js2-mode-hide-comment (n)
11877 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11878 3 ; /**
11879 2)) ; /*
11880 (beg (+ (js2-node-abs-pos n) head))
11881 (end (- (+ beg (js2-node-len n)) head 2))
11882 (o (js2-mode-flag-region beg end 'hide)))
11883 (overlay-put o 'comment t)))
11884
11885 (defun js2-mode-toggle-hide-comments ()
11886 "Folds all block comments in the buffer.
11887 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11888 to open an individual entry."
11889 (interactive)
11890 (if js2-mode-comments-hidden
11891 (js2-mode-show-comments)
11892 (js2-mode-hide-comments)))
11893
11894 (defun js2-mode-hide-comments ()
11895 (interactive)
11896 (if js2-mode-buffer-dirty-p
11897 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11898 (if (null js2-mode-ast)
11899 (message "Oops - parsing failed")
11900 (setq js2-mode-comments-hidden t)
11901 (dolist (n (js2-ast-root-comments js2-mode-ast))
11902 (when (js2-block-comment-p n)
11903 (js2-mode-hide-comment n)))
11904 (js2-mode-hide-//-comments)))
11905
11906 (defun js2-mode-extend-//-comment (direction)
11907 "Find start or end of a block of similar //-comment lines.
11908 DIRECTION is -1 to look back, 1 to look forward.
11909 INDENT is the indentation level to match.
11910 Returns the end-of-line position of the furthest adjacent
11911 //-comment line with the same indentation as the current line.
11912 If there is no such matching line, returns current end of line."
11913 (let ((pos (point-at-eol))
11914 (indent (current-indentation)))
11915 (save-excursion
11916 (while (and (zerop (forward-line direction))
11917 (looking-at js2-mode-//-comment-re)
11918 (eq indent (length (match-string 1))))
11919 (setq pos (point-at-eol)))
11920 pos)))
11921
11922 (defun js2-mode-hide-//-comments ()
11923 "Fold adjacent 1-line comments, showing only snippet of first one."
11924 (let (beg end)
11925 (save-excursion
11926 (goto-char (point-min))
11927 (while (re-search-forward js2-mode-//-comment-re nil t)
11928 (setq beg (point)
11929 end (js2-mode-extend-//-comment 1))
11930 (unless (eq beg end)
11931 (overlay-put (js2-mode-flag-region beg end 'hide)
11932 'comment t))
11933 (goto-char end)
11934 (forward-char 1)))))
11935
11936 (defun js2-mode-toggle-//-comment ()
11937 "Fold or un-fold any multi-line //-comment at point.
11938 Caller should have determined that this line starts with a //-comment."
11939 (let* ((beg (point-at-eol))
11940 (end beg))
11941 (save-excursion
11942 (goto-char end)
11943 (if (js2-mode-invisible-overlay-bounds)
11944 (js2-mode-show-element)
11945 ;; else hide the comment
11946 (setq beg (js2-mode-extend-//-comment -1)
11947 end (js2-mode-extend-//-comment 1))
11948 (unless (eq beg end)
11949 (overlay-put (js2-mode-flag-region beg end 'hide)
11950 'comment t))))))
11951
11952 (defun js2-mode-show-comments ()
11953 "Un-hide any hidden comments, leaving other hidden elements alone."
11954 (interactive)
11955 (setq js2-mode-comments-hidden nil)
11956 (save-excursion
11957 (goto-char (point-min))
11958 (while (/= (goto-char (next-overlay-change (point)))
11959 (point-max))
11960 (dolist (o (overlays-at (point)))
11961 (when (overlay-get o 'comment)
11962 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11963
11964 (defun js2-mode-display-warnings-and-errors ()
11965 "Turn on display of warnings and errors."
11966 (interactive)
11967 (setq js2-mode-show-parse-errors t
11968 js2-mode-show-strict-warnings t)
11969 (js2-reparse 'force))
11970
11971 (defun js2-mode-hide-warnings-and-errors ()
11972 "Turn off display of warnings and errors."
11973 (interactive)
11974 (setq js2-mode-show-parse-errors nil
11975 js2-mode-show-strict-warnings nil)
11976 (js2-reparse 'force))
11977
11978 (defun js2-mode-toggle-warnings-and-errors ()
11979 "Toggle the display of warnings and errors.
11980 Some users don't like having warnings/errors reported while they type."
11981 (interactive)
11982 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11983 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11984 (if (called-interactively-p 'any)
11985 (message "warnings and errors %s"
11986 (if js2-mode-show-parse-errors
11987 "enabled"
11988 "disabled")))
11989 (js2-reparse 'force))
11990
11991 (defun js2-mode-customize ()
11992 (interactive)
11993 (customize-group 'js2-mode))
11994
11995 (defun js2-mode-forward-sexp (&optional arg)
11996 "Move forward across one statement or balanced expression.
11997 With ARG, do it that many times. Negative arg -N means
11998 move backward across N balanced expressions."
11999 (interactive "p")
12000 (setq arg (or arg 1))
12001 (save-restriction
12002 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12003 (js2-reparse)
12004 (let (forward-sexp-function
12005 node (start (point)) pos lp rp child)
12006 (cond
12007 ;; backward-sexp
12008 ;; could probably make this better for some cases:
12009 ;; - if in statement block (e.g. function body), go to parent
12010 ;; - infix exprs like (foo in bar) - maybe go to beginning
12011 ;; of infix expr if in the right-side expression?
12012 ((and arg (cl-minusp arg))
12013 (dotimes (_ (- arg))
12014 (js2-backward-sws)
12015 (forward-char -1) ; Enter the node we backed up to.
12016 (when (setq node (js2-node-at-point (point) t))
12017 (setq pos (js2-node-abs-pos node))
12018 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12019 (setq lp (car parens)
12020 rp (cdr parens)))
12021 (when (and lp (> start lp))
12022 (if (and rp (<= start rp))
12023 ;; Between parens, check if there's a child node we can jump.
12024 (when (setq child (js2-node-closest-child node (point) lp t))
12025 (setq pos (js2-node-abs-pos child)))
12026 ;; Before both parens.
12027 (setq pos lp)))
12028 (let ((state (parse-partial-sexp start pos)))
12029 (goto-char (if (not (zerop (car state)))
12030 ;; Stumble at the unbalanced paren if < 0, or
12031 ;; jump a bit further if > 0.
12032 (scan-sexps start -1)
12033 pos))))
12034 (unless pos (goto-char (point-min)))))
12035 (t
12036 ;; forward-sexp
12037 (dotimes (_ arg)
12038 (js2-forward-sws)
12039 (when (setq node (js2-node-at-point (point) t))
12040 (setq pos (js2-node-abs-pos node))
12041 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12042 (setq lp (car parens)
12043 rp (cdr parens)))
12044 (or
12045 (when (and rp (<= start rp))
12046 (if (> start lp)
12047 (when (setq child (js2-node-closest-child node (point) rp))
12048 (setq pos (js2-node-abs-end child)))
12049 (setq pos (1+ rp))))
12050 ;; No parens or child nodes, looks for the end of the current node.
12051 (cl-incf pos (js2-node-len
12052 (if (js2-expr-stmt-node-p (js2-node-parent node))
12053 ;; Stop after the semicolon.
12054 (js2-node-parent node)
12055 node))))
12056 (let ((state (save-excursion (parse-partial-sexp start pos))))
12057 (goto-char (if (not (zerop (car state)))
12058 (scan-sexps start 1)
12059 pos))))
12060 (unless pos (goto-char (point-max)))))))))
12061
12062 (defun js2-mode-forward-sexp-parens (node abs-pos)
12063 "Return a cons cell with positions of main parens in NODE."
12064 (cond
12065 ((or (js2-array-node-p node)
12066 (js2-object-node-p node)
12067 (js2-comp-node-p node)
12068 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12069 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12070 ((js2-paren-expr-node-p node)
12071 (let ((lp (js2-node-lp node))
12072 (rp (js2-node-rp node)))
12073 (cons (when lp (+ abs-pos lp))
12074 (when rp (+ abs-pos rp)))))))
12075
12076 (defun js2-node-closest-child (parent point limit &optional before)
12077 (let* ((parent-pos (js2-node-abs-pos parent))
12078 (rpoint (- point parent-pos))
12079 (rlimit (- limit parent-pos))
12080 (min (min rpoint rlimit))
12081 (max (max rpoint rlimit))
12082 found)
12083 (catch 'done
12084 (js2-visit-ast
12085 parent
12086 (lambda (node _end-p)
12087 (if (eq node parent)
12088 t
12089 (let ((pos (js2-node-pos node)) ;; Both relative values.
12090 (end (+ (js2-node-pos node) (js2-node-len node))))
12091 (when (and (>= pos min) (<= end max)
12092 (if before (< pos rpoint) (> end rpoint)))
12093 (setq found node))
12094 (when (> end rpoint)
12095 (throw 'done nil)))
12096 nil))))
12097 found))
12098
12099 (defun js2-errors ()
12100 "Return a list of errors found."
12101 (and js2-mode-ast
12102 (js2-ast-root-errors js2-mode-ast)))
12103
12104 (defun js2-warnings ()
12105 "Return a list of warnings found."
12106 (and js2-mode-ast
12107 (js2-ast-root-warnings js2-mode-ast)))
12108
12109 (defun js2-have-errors-p ()
12110 "Return non-nil if any parse errors or warnings were found."
12111 (or (js2-errors) (js2-warnings)))
12112
12113 (defun js2-errors-and-warnings ()
12114 "Return a copy of the concatenated errors and warnings lists.
12115 They are appended: first the errors, then the warnings.
12116 Entries are of the form (MSG BEG END)."
12117 (when js2-mode-ast
12118 (append (js2-ast-root-errors js2-mode-ast)
12119 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12120
12121 (defun js2-next-error (&optional arg reset)
12122 "Move to next parse error.
12123 Typically invoked via \\[next-error].
12124 ARG is the number of errors, forward or backward, to move.
12125 RESET means start over from the beginning."
12126 (interactive "p")
12127 (if (not (or (js2-errors) (js2-warnings)))
12128 (message "No errors")
12129 (when reset
12130 (goto-char (point-min)))
12131 (let* ((errs (js2-errors-and-warnings))
12132 (continue t)
12133 (start (point))
12134 (count (or arg 1))
12135 (backward (cl-minusp count))
12136 (sorter (if backward '> '<))
12137 (stopper (if backward '< '>))
12138 (count (abs count))
12139 all-errs err)
12140 ;; Sort by start position.
12141 (setq errs (sort errs (lambda (e1 e2)
12142 (funcall sorter (cl-second e1) (cl-second e2))))
12143 all-errs errs)
12144 ;; Find nth error with pos > start.
12145 (while (and errs continue)
12146 (when (funcall stopper (cl-cadar errs) start)
12147 (setq err (car errs))
12148 (if (zerop (cl-decf count))
12149 (setq continue nil)))
12150 (setq errs (cdr errs)))
12151 ;; Clear for `js2-echo-error'.
12152 (message nil)
12153 (if err
12154 (goto-char (cl-second err))
12155 ;; Wrap around to first error.
12156 (goto-char (cl-second (car all-errs)))
12157 ;; If we were already on it, echo msg again.
12158 (if (= (point) start)
12159 (js2-echo-error (point) (point)))))))
12160
12161 (defun js2-down-mouse-3 ()
12162 "Make right-click move the point to the click location.
12163 This makes right-click context menu operations a bit more intuitive.
12164 The point will not move if the region is active, however, to avoid
12165 destroying the region selection."
12166 (interactive)
12167 (when (and js2-move-point-on-right-click
12168 (not mark-active))
12169 (let ((e last-input-event))
12170 (ignore-errors
12171 (goto-char (cl-cadadr e))))))
12172
12173 (defun js2-mode-create-imenu-index ()
12174 "Return an alist for `imenu--index-alist'."
12175 ;; This is built up in `js2-parse-record-imenu' during parsing.
12176 (when js2-mode-ast
12177 ;; if we have an ast but no recorder, they're requesting a rescan
12178 (unless js2-imenu-recorder
12179 (js2-reparse 'force))
12180 (prog1
12181 (js2-build-imenu-index)
12182 (setq js2-imenu-recorder nil
12183 js2-imenu-function-map nil))))
12184
12185 (defun js2-mode-find-tag ()
12186 "Replacement for `find-tag-default'.
12187 `find-tag-default' returns a ridiculous answer inside comments."
12188 (let (beg end)
12189 (save-excursion
12190 (if (looking-at "\\_>")
12191 (setq beg (progn (forward-symbol -1) (point))
12192 end (progn (forward-symbol 1) (point)))
12193 (setq beg (progn (forward-symbol 1) (point))
12194 end (progn (forward-symbol -1) (point))))
12195 (replace-regexp-in-string
12196 "[\"']" ""
12197 (buffer-substring-no-properties beg end)))))
12198
12199 (defun js2-mode-forward-sibling ()
12200 "Move to the end of the sibling following point in parent.
12201 Returns non-nil if successful, or nil if there was no following sibling."
12202 (let* ((node (js2-node-at-point))
12203 (parent (js2-mode-find-enclosing-fn node))
12204 sib)
12205 (when (setq sib (js2-node-find-child-after (point) parent))
12206 (goto-char (+ (js2-node-abs-pos sib)
12207 (js2-node-len sib))))))
12208
12209 (defun js2-mode-backward-sibling ()
12210 "Move to the beginning of the sibling node preceding point in parent.
12211 Parent is defined as the enclosing script or function."
12212 (let* ((node (js2-node-at-point))
12213 (parent (js2-mode-find-enclosing-fn node))
12214 sib)
12215 (when (setq sib (js2-node-find-child-before (point) parent))
12216 (goto-char (js2-node-abs-pos sib)))))
12217
12218 (defun js2-beginning-of-defun (&optional arg)
12219 "Go to line on which current function starts, and return t on success.
12220 If we're not in a function or already at the beginning of one, go
12221 to beginning of previous script-level element.
12222 With ARG N, do that N times. If N is negative, move forward."
12223 (setq arg (or arg 1))
12224 (if (cl-plusp arg)
12225 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12226 (when (cond
12227 ((js2-function-node-p parent)
12228 (goto-char (js2-node-abs-pos parent)))
12229 (t
12230 (js2-mode-backward-sibling)))
12231 (if (> arg 1)
12232 (js2-beginning-of-defun (1- arg))
12233 t)))
12234 (when (js2-end-of-defun)
12235 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12236
12237 (defun js2-end-of-defun ()
12238 "Go to the char after the last position of the current function
12239 or script-level element."
12240 (let* ((node (js2-node-at-point))
12241 (parent (or (and (js2-function-node-p node) node)
12242 (js2-node-parent-script-or-fn node)))
12243 script)
12244 (unless (js2-function-node-p parent)
12245 ;; Use current script-level node, or, if none, the next one.
12246 (setq script (or parent node)
12247 parent (js2-node-find-child-before (point) script))
12248 (when (or (null parent)
12249 (>= (point) (+ (js2-node-abs-pos parent)
12250 (js2-node-len parent))))
12251 (setq parent (js2-node-find-child-after (point) script))))
12252 (when parent
12253 (goto-char (+ (js2-node-abs-pos parent)
12254 (js2-node-len parent))))))
12255
12256 (defun js2-mark-defun (&optional allow-extend)
12257 "Put mark at end of this function, point at beginning.
12258 The function marked is the one that contains point.
12259
12260 Interactively, if this command is repeated,
12261 or (in Transient Mark mode) if the mark is active,
12262 it marks the next defun after the ones already marked."
12263 (interactive "p")
12264 (let (extended)
12265 (when (and allow-extend
12266 (or (and (eq last-command this-command) (mark t))
12267 (and transient-mark-mode mark-active)))
12268 (let ((sib (save-excursion
12269 (goto-char (mark))
12270 (if (js2-mode-forward-sibling)
12271 (point)))))
12272 (if sib
12273 (progn
12274 (set-mark sib)
12275 (setq extended t))
12276 ;; no more siblings - try extending to enclosing node
12277 (goto-char (mark t)))))
12278 (when (not extended)
12279 (let ((node (js2-node-at-point (point) t)) ; skip comments
12280 ast fn stmt parent beg end)
12281 (when (js2-ast-root-p node)
12282 (setq ast node
12283 node (or (js2-node-find-child-after (point) node)
12284 (js2-node-find-child-before (point) node))))
12285 ;; only mark whole buffer if we can't find any children
12286 (if (null node)
12287 (setq node ast))
12288 (if (js2-function-node-p node)
12289 (setq parent node)
12290 (setq fn (js2-mode-find-enclosing-fn node)
12291 stmt (if (or (null fn)
12292 (js2-ast-root-p fn))
12293 (js2-mode-find-first-stmt node))
12294 parent (or stmt fn)))
12295 (setq beg (js2-node-abs-pos parent)
12296 end (+ beg (js2-node-len parent)))
12297 (push-mark beg)
12298 (goto-char end)
12299 (exchange-point-and-mark)))))
12300
12301 (defun js2-narrow-to-defun ()
12302 "Narrow to the function enclosing point."
12303 (interactive)
12304 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12305 (fn (if (js2-script-node-p node)
12306 node
12307 (js2-mode-find-enclosing-fn node)))
12308 (beg (js2-node-abs-pos fn)))
12309 (unless (js2-ast-root-p fn)
12310 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12311
12312 (provide 'js2-mode)
12313
12314 ;;; js2-mode.el ends here